lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
bsd-3-clause
977751c41656e8d25ebe5237fc9e96779140b5fc
0
svn2github/semanticvectors,tuxdna/semanticvectors-googlecode,svn2github/semanticvectors,tuxdna/semanticvectors-googlecode,svn2github/semanticvectors,tuxdna/semanticvectors-googlecode,tuxdna/semanticvectors-googlecode,svn2github/semanticvectors
/** Copyright (c) 2008, University of Pittsburgh 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 University of Pittsburgh nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 pitt.search.semanticvectors; import java.util.Arrays; import java.util.Enumeration; import java.util.Random; import java.io.File; import java.io.IOException; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.Term; import org.apache.lucene.index.TermEnum; import org.apache.lucene.index.TermPositionVector; import org.apache.lucene.store.FSDirectory; /** * Implementation of vector store that creates term by term * cooccurence vectors by iterating through all the documents in a * Lucene index. This class implements a sliding context window * approach, as used by Burgess and Lund (HAL) and Schutze amongst * others Uses a sparse representation for the basic document vectors, * which saves considerable space for collections with many individual * documents. * * @author Trevor Cohen, Dominic Widdows. */ public class TermTermVectorsFromLucene implements VectorStore { private boolean retraining = false; private VectorStoreRAM termVectors; private VectorStore indexVectors; private IndexReader indexReader; private int seedLength; private String[] fieldsToIndex; private int minFreq; private int windowSize; private float[][] localindexvectors; private short[][] localsparseindexvectors; private LuceneUtils lUtils; private int nonAlphabet; private int dimension; private String positionalmethod; static final short NONEXISTENT = -1; /** * @return The object's indexReader. */ public IndexReader getIndexReader(){ return this.indexReader; } /** * @return The object's basicTermVectors. */ public VectorStore getBasicTermVectors(){ return this.termVectors; } public String[] getFieldsToIndex(){ return this.fieldsToIndex; } // Basic VectorStore interface methods implemented through termVectors. public float[] getVector(Object term) { return termVectors.getVector(term); } public Enumeration getAllVectors() { return termVectors.getAllVectors(); } public int getNumVectors() { return termVectors.getNumVectors(); } /** * This constructor uses all the values passed as arguments and in addition * the parameters dimension and positionalmethod from Flags. * @param indexDir Directory containing Lucene index. * @param seedLength Number of +1 or -1 entries in basic * vectors. Should be even to give same number of each. * @param minFreq The minimum term frequency for a term to be indexed. * @param nonAlphabet * @param windowSize The size of the sliding context window. * @param basicTermVectors * @param fieldsToIndex These fields will be indexed. * @throws IOException * @throws RuntimeException * @deprecated use the constructor that explicitly specifies all needed * values from Flags. */ public TermTermVectorsFromLucene(String indexDir, int seedLength, int minFreq, int nonAlphabet, int windowSize, VectorStore basicTermVectors, String[] fieldsToIndex) throws IOException, RuntimeException { this.dimension = Flags.dimension; this.positionalmethod = Flags.positionalmethod; doConstructor(indexDir,seedLength,minFreq,nonAlphabet, windowSize,basicTermVectors,fieldsToIndex); } /** * This constructor uses only the values passed, no parameters from Flag. * @param indexDir Directory containing Lucene index. * @dimension number of dimensions to use for the vectors * @param dimension * @param seedLength Number of +1 or -1 entries in basic * vectors. Should be even to give same number of each. * @param minFreq The minimum term frequency for a term to be indexed. * @param nonAlphabet * @param windowSize The size of the sliding context window. * @param positionalmethod * @param basicTermVectors * @param fieldsToIndex These fields will be indexed. * @throws IOException * @throws RuntimeException */ public TermTermVectorsFromLucene(String indexDir, int dimension, int seedLength, int minFreq, int nonAlphabet, int windowSize, String positionalmethod, VectorStore basicTermVectors, String[] fieldsToIndex) throws IOException, RuntimeException { this.dimension = dimension; this.positionalmethod = positionalmethod; doConstructor(indexDir,seedLength,minFreq,nonAlphabet, windowSize,basicTermVectors,fieldsToIndex); } private void doConstructor(String indexDir, int seedLength, int minFreq, int nonAlphabet, int windowSize, VectorStore basicTermVectors, String[] fieldsToIndex) throws IOException, RuntimeException { this.minFreq = minFreq; this.nonAlphabet = nonAlphabet; this.fieldsToIndex = fieldsToIndex; this.seedLength = seedLength; this.windowSize = windowSize; // Check that the Lucene index contains Term Positions. LuceneUtils.CompressIndex(indexDir); this.indexReader = IndexReader.open(FSDirectory.open(new File(indexDir))); java.util.Collection fields_with_positions = indexReader.getFieldNames(IndexReader.FieldOption.TERMVECTOR_WITH_POSITION); if (fields_with_positions.isEmpty()) { System.err.println("Term-term indexing requires a Lucene index containing TermPositionVectors"); System.err.println("Try rebuilding Lucene index using pitt.search.lucene.IndexFilePositions"); throw new IOException("Lucene indexes not built correctly."); } lUtils = new LuceneUtils(indexDir); // If basicTermVectors was passed in, set state accordingly. if (basicTermVectors != null) { retraining = true; this.indexVectors = basicTermVectors; System.out.println("Reusing basic term vectors; number of terms: " + basicTermVectors.getNumVectors()); } else { this.indexVectors = new VectorStoreSparseRAM(); } Random random = new Random(); this.termVectors = new VectorStoreRAM(); // Iterate through an enumeration of terms and allocate termVector memory. // If not retraining, create random elemental vectors as well. System.err.println("Creating basic term vectors ..."); TermEnum terms = this.indexReader.terms(); int tc = 0; while(terms.next()){ Term term = terms.term(); // Skip terms that don't pass the filter. if (!lUtils.termFilter(terms.term(), fieldsToIndex)) { continue; } tc++; float[] termVector = new float[dimension]; // Place each term vector in the vector store. this.termVectors.putVector(term.text(), termVector); // Do the same for random index vectors unless retraining with trained term vectors if (!retraining) { short[] indexVector = VectorUtils.generateRandomVector(seedLength, random); ((VectorStoreSparseRAM) this.indexVectors).putVector(term.text(), indexVector); } } System.err.println("There are " + tc + " terms (and " + indexReader.numDocs() + " docs)"); // Iterate through documents. int numdocs = this.indexReader.numDocs(); for (int dc = 0; dc < numdocs; ++dc) { /* output progress counter */ if ((dc % 10000 == 0) || (dc < 10000 && dc % 1000 == 0)) { System.err.print(dc + " ... "); } try { for (String field: fieldsToIndex) { TermPositionVector vex = (TermPositionVector) indexReader.getTermFreqVector(dc, field); if (vex != null) processTermPositionVector(vex); } } catch (Exception e) { System.err.println("\nFailed to process document "+indexReader.document(dc).get("path")+"\n"); } } System.err.println("\nCreated " + termVectors.getNumVectors() + " term vectors ..."); System.err.println("\nNormalizing term vectors"); Enumeration e = termVectors.getAllVectors(); while (e.hasMoreElements()) { ObjectVector temp = (ObjectVector) e.nextElement(); float[] next = temp.getVector(); next = VectorUtils.getNormalizedVector(next); temp.setVector(next); } // If building a permutation index, these need to be written out to be reused. if ((positionalmethod.equals("permutation") || (positionalmethod.equals("permutation_plus_basic") ))&& !retraining) { String randFile = "randomvectors.bin"; System.err.println("\nWriting random vectors to "+randFile); System.err.println("\nNormalizing random vectors"); Enumeration f = indexVectors.getAllVectors(); while (f.hasMoreElements()) { ObjectVector temp = (ObjectVector) f.nextElement(); float[] next = temp.getVector(); next = VectorUtils.getNormalizedVector(next); temp.setVector(next); } new VectorStoreWriter().WriteVectors(randFile, this.indexVectors); } } /** For each term, add term index vector * for any term occurring within a window of size windowSize such * that for example if windowSize = 5 with the window over the * phrase "your life is your life" the index vectors for terms * "your" and "life" would each be added to the term vector for * "is" twice. * * TermPositionVectors contain arrays of (1) terms as text (2) * term frequencies and (3) term positions within a * document. The index of a particular term within this array * will be referred to as the 'local index' in comments. */ private void processTermPositionVector(TermPositionVector vex) throws java.lang.ArrayIndexOutOfBoundsException { int[] freqs = vex.getTermFrequencies(); // Find number of positions in document (across all terms). int numwords = freqs.length; int numpositions = 0; for (short tcn = 0; tcn < numwords; ++tcn) { int[] posns = vex.getTermPositions(tcn); for (int pc = 0; pc < posns.length; ++pc) { numpositions = Math.max(numpositions, posns[pc]); } } numpositions += 1; //convert from zero-based index to count // Create local random index and term vectors for relevant terms. if (retraining) localindexvectors = new float[numwords][dimension]; else localsparseindexvectors = new short[numwords][seedLength]; float[][] localtermvectors = new float[numwords][dimension]; // Create index with one space for each position. short[] positions = new short[numpositions]; Arrays.fill(positions, NONEXISTENT); String[] docterms = vex.getTerms(); for (short tcn = 0; tcn < numwords; ++tcn) { // Insert local term indices in position vector. int[] posns = vex.getTermPositions(tcn); // Get all positions of term in document for (int pc = 0; pc < posns.length; ++pc) { // Set position of index vector to local // (document-specific) index of term in this position. int position = posns[pc]; positions[position] = tcn; } // Only terms that have passed the term filter are included in the VectorStores. if (this.indexVectors.getVector(docterms[tcn]) != null) { // Retrieve relevant random index vectors. if (retraining) localindexvectors[tcn] = indexVectors.getVector(docterms[tcn]); else localsparseindexvectors[tcn] = ((VectorStoreSparseRAM) indexVectors).getSparseVector(docterms[tcn]); // Retrieve the float[] arrays of relevant term vectors. localtermvectors[tcn] = termVectors.getVector(docterms[tcn]); } } /** Iterate through positions adding index vectors of terms * occurring within window to term vector for focus term **/ int w2 = windowSize / 2; for (int p = 0; p < positions.length; ++p) { int focusposn = p; int focusterm = positions[focusposn]; if (focusterm == NONEXISTENT) continue; int windowstart = Math.max(0, p - w2); int windowend = Math.min(focusposn + w2, positions.length - 1); /* add random vector (in condensed (signed index + 1) * representation) to term vector by adding -1 or +1 to the * location (index - 1) according to the sign of the index. * (The -1 and +1 are necessary because there is no signed * version of 0, so we'd have no way of telling that the * zeroth position in the array should be plus or minus 1.) * See also generateRandomVector method below. */ for (int w = windowstart; w <= windowend; w++) { if (w == focusposn) continue; int coterm = positions[w]; if (coterm == NONEXISTENT) continue; // calculate permutation required for either Sahlgren (2008) implementation // encoding word order, or encoding direction as in Burgess and Lund's HAL float[] localindex= new float[0]; short[] localsparseindex = new short[0]; if (retraining) localindex = localindexvectors[coterm].clone(); else localsparseindex = localsparseindexvectors[coterm].clone(); //combine 'content' and 'order' information - first add the unpermuted vector if (positionalmethod.equals("permutation_plus_basic")) { // docterms[coterm] contains the term in position[w] in this document. if (this.indexVectors.getVector(docterms[coterm]) != null && localtermvectors[focusterm] != null) { if (retraining) VectorUtils.addVectors(localtermvectors[focusterm],localindex,1); else VectorUtils.addVectors(localtermvectors[focusterm],localsparseindex,1); } } if (positionalmethod.equals("permutation") || positionalmethod.equals("permutation_plus_basic")) { int permutation = w - focusposn; if (retraining) localindex = VectorUtils.permuteVector(localindex , permutation); else localsparseindex = VectorUtils.permuteVector(localsparseindex, permutation); } else if (positionalmethod.equals("directional")) { if (retraining) localindex = VectorUtils.permuteVector(localindex, new Float(Math.signum(w-focusposn)).intValue()); else localsparseindex = VectorUtils.permuteVector(localsparseindex, new Float(Math.signum(w-focusposn)).intValue()); } // docterms[coterm] contains the term in position[w] in this document. if (this.indexVectors.getVector(docterms[coterm]) != null && localtermvectors[focusterm] != null) { if (retraining) VectorUtils.addVectors(localtermvectors[focusterm],localindex,1); else VectorUtils.addVectors(localtermvectors[focusterm],localsparseindex,1); } } } } }
src/pitt/search/semanticvectors/TermTermVectorsFromLucene.java
/** Copyright (c) 2008, University of Pittsburgh 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 University of Pittsburgh nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 pitt.search.semanticvectors; import java.util.Arrays; import java.util.Hashtable; import java.util.Enumeration; import java.util.Random; import java.io.File; import java.io.IOException; import java.lang.RuntimeException; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.index.TermDocs; import org.apache.lucene.index.TermEnum; import org.apache.lucene.index.TermPositionVector; import org.apache.lucene.store.FSDirectory; /** * Implementation of vector store that creates term by term * cooccurence vectors by iterating through all the documents in a * Lucene index. This class implements a sliding context window * approach, as used by Burgess and Lund (HAL) and Schutze amongst * others Uses a sparse representation for the basic document vectors, * which saves considerable space for collections with many individual * documents. * * @author Trevor Cohen, Dominic Widdows. */ public class TermTermVectorsFromLucene implements VectorStore { private boolean retraining = false; private VectorStoreRAM termVectors; private VectorStore indexVectors; private IndexReader indexReader; private int seedLength; private String[] fieldsToIndex; private int minFreq; private int windowSize; private float[][] localindexvectors; private short[][] localsparseindexvectors; private LuceneUtils lUtils; private int nonAlphabet; static final short NONEXISTENT = -1; /** * @return The object's indexReader. */ public IndexReader getIndexReader(){ return this.indexReader; } /** * @return The object's basicTermVectors. */ public VectorStore getBasicTermVectors(){ return this.termVectors; } public String[] getFieldsToIndex(){ return this.fieldsToIndex; } // Basic VectorStore interface methods implemented through termVectors. public float[] getVector(Object term) { return termVectors.getVector(term); } public Enumeration getAllVectors() { return termVectors.getAllVectors(); } public int getNumVectors() { return termVectors.getNumVectors(); } /** * @param indexDir Directory containing Lucene index. * @param seedLength Number of +1 or -1 entries in basic * vectors. Should be even to give same number of each. * @param minFreq The minimum term frequency for a term to be indexed. * @param windowSize The size of the sliding context window. * @param fieldsToIndex These fields will be indexed. */ public TermTermVectorsFromLucene(String indexDir, int seedLength, int minFreq, int nonAlphabet, int windowSize, VectorStore basicTermVectors, String[] fieldsToIndex) throws IOException, RuntimeException { this.minFreq = minFreq; this.nonAlphabet = nonAlphabet; this.fieldsToIndex = fieldsToIndex; this.seedLength = seedLength; this.windowSize = windowSize; // Check that the Lucene index contains Term Positions. LuceneUtils.CompressIndex(indexDir); this.indexReader = IndexReader.open(FSDirectory.open(new File(indexDir))); java.util.Collection fields_with_positions = indexReader.getFieldNames(IndexReader.FieldOption.TERMVECTOR_WITH_POSITION); if (fields_with_positions.isEmpty()) { System.err.println("Term-term indexing requires a Lucene index containing TermPositionVectors"); System.err.println("Try rebuilding Lucene index using pitt.search.lucene.IndexFilePositions"); throw new IOException("Lucene indexes not built correctly."); } lUtils = new LuceneUtils(indexDir); // If basicTermVectors was passed in, set state accordingly. if (basicTermVectors != null) { retraining = true; this.indexVectors = basicTermVectors; System.out.println("Reusing basic term vectors; number of terms: " + basicTermVectors.getNumVectors()); } else { this.indexVectors = new VectorStoreSparseRAM(); } Random random = new Random(); this.termVectors = new VectorStoreRAM(); // Iterate through an enumeration of terms and allocate termVector memory. // If not retraining, create random elemental vectors as well. System.err.println("Creating basic term vectors ..."); TermEnum terms = this.indexReader.terms(); int tc = 0; while(terms.next()){ Term term = terms.term(); // Skip terms that don't pass the filter. if (!lUtils.termFilter(terms.term(), fieldsToIndex)) { continue; } tc++; float[] termVector = new float[Flags.dimension]; // Place each term vector in the vector store. this.termVectors.putVector(term.text(), termVector); // Do the same for random index vectors unless retraining with trained term vectors if (!retraining) { short[] indexVector = VectorUtils.generateRandomVector(seedLength, random); ((VectorStoreSparseRAM) this.indexVectors).putVector(term.text(), indexVector); } } System.err.println("There are " + tc + " terms (and " + indexReader.numDocs() + " docs)"); // Iterate through documents. int numdocs = this.indexReader.numDocs(); for (int dc = 0; dc < numdocs; ++dc) { /* output progress counter */ if ((dc % 10000 == 0) || (dc < 10000 && dc % 1000 == 0)) { System.err.print(dc + " ... "); } try { for (String field: fieldsToIndex) { TermPositionVector vex = (TermPositionVector) indexReader.getTermFreqVector(dc, field); if (vex != null) processTermPositionVector(vex); } } catch (Exception e) { System.err.println("\nFailed to process document "+indexReader.document(dc).get("path")+"\n"); } } System.err.println("\nCreated " + termVectors.getNumVectors() + " term vectors ..."); System.err.println("\nNormalizing term vectors"); Enumeration e = termVectors.getAllVectors(); while (e.hasMoreElements()) { ObjectVector temp = (ObjectVector) e.nextElement(); float[] next = temp.getVector(); next = VectorUtils.getNormalizedVector(next); temp.setVector(next); } // If building a permutation index, these need to be written out to be reused. if ((Flags.positionalmethod.equals("permutation") || (Flags.positionalmethod.equals("permutation_plus_basic") ))&& !retraining) { String randFile = "randomvectors.bin"; System.err.println("\nWriting random vectors to "+randFile); System.err.println("\nNormalizing random vectors"); Enumeration f = indexVectors.getAllVectors(); while (f.hasMoreElements()) { ObjectVector temp = (ObjectVector) f.nextElement(); float[] next = temp.getVector(); next = VectorUtils.getNormalizedVector(next); temp.setVector(next); } new VectorStoreWriter().WriteVectors(randFile, this.indexVectors); } } /** For each term, add term index vector * for any term occurring within a window of size windowSize such * that for example if windowSize = 5 with the window over the * phrase "your life is your life" the index vectors for terms * "your" and "life" would each be added to the term vector for * "is" twice. * * TermPositionVectors contain arrays of (1) terms as text (2) * term frequencies and (3) term positions within a * document. The index of a particular term within this array * will be referred to as the 'local index' in comments. */ private void processTermPositionVector(TermPositionVector vex) throws java.lang.ArrayIndexOutOfBoundsException { int[] freqs = vex.getTermFrequencies(); // Find number of positions in document (across all terms). int numwords = freqs.length; int numpositions = 0; for (short tcn = 0; tcn < numwords; ++tcn) { int[] posns = vex.getTermPositions(tcn); for (int pc = 0; pc < posns.length; ++pc) { numpositions = Math.max(numpositions, posns[pc]); } } numpositions += 1; //convert from zero-based index to count // Create local random index and term vectors for relevant terms. if (retraining) localindexvectors = new float[numwords][Flags.dimension]; else localsparseindexvectors = new short[numwords][seedLength]; float[][] localtermvectors = new float[numwords][Flags.dimension]; // Create index with one space for each position. short[] positions = new short[numpositions]; Arrays.fill(positions, NONEXISTENT); String[] docterms = vex.getTerms(); for (short tcn = 0; tcn < numwords; ++tcn) { // Insert local term indices in position vector. int[] posns = vex.getTermPositions(tcn); // Get all positions of term in document for (int pc = 0; pc < posns.length; ++pc) { // Set position of index vector to local // (document-specific) index of term in this position. int position = posns[pc]; positions[position] = tcn; } // Only terms that have passed the term filter are included in the VectorStores. if (this.indexVectors.getVector(docterms[tcn]) != null) { // Retrieve relevant random index vectors. if (retraining) localindexvectors[tcn] = indexVectors.getVector(docterms[tcn]); else localsparseindexvectors[tcn] = ((VectorStoreSparseRAM) indexVectors).getSparseVector(docterms[tcn]); // Retrieve the float[] arrays of relevant term vectors. localtermvectors[tcn] = termVectors.getVector(docterms[tcn]); } } /** Iterate through positions adding index vectors of terms * occurring within window to term vector for focus term **/ int w2 = windowSize / 2; for (int p = 0; p < positions.length; ++p) { int focusposn = p; int focusterm = positions[focusposn]; if (focusterm == NONEXISTENT) continue; int windowstart = Math.max(0, p - w2); int windowend = Math.min(focusposn + w2, positions.length - 1); /* add random vector (in condensed (signed index + 1) * representation) to term vector by adding -1 or +1 to the * location (index - 1) according to the sign of the index. * (The -1 and +1 are necessary because there is no signed * version of 0, so we'd have no way of telling that the * zeroth position in the array should be plus or minus 1.) * See also generateRandomVector method below. */ for (int w = windowstart; w <= windowend; w++) { if (w == focusposn) continue; int coterm = positions[w]; if (coterm == NONEXISTENT) continue; // calculate permutation required for either Sahlgren (2008) implementation // encoding word order, or encoding direction as in Burgess and Lund's HAL float[] localindex= new float[0]; short[] localsparseindex = new short[0]; if (retraining) localindex = localindexvectors[coterm].clone(); else localsparseindex = localsparseindexvectors[coterm].clone(); //combine 'content' and 'order' information - first add the unpermuted vector if (Flags.positionalmethod.equals("permutation_plus_basic")) { // docterms[coterm] contains the term in position[w] in this document. if (this.indexVectors.getVector(docterms[coterm]) != null && localtermvectors[focusterm] != null) { if (retraining) VectorUtils.addVectors(localtermvectors[focusterm],localindex,1); else VectorUtils.addVectors(localtermvectors[focusterm],localsparseindex,1); } } if (Flags.positionalmethod.equals("permutation") || Flags.positionalmethod.equals("permutation_plus_basic")) { int permutation = w - focusposn; if (retraining) localindex = VectorUtils.permuteVector(localindex , permutation); else localsparseindex = VectorUtils.permuteVector(localsparseindex, permutation); } else if (Flags.positionalmethod.equals("directional")) { if (retraining) localindex = VectorUtils.permuteVector(localindex, new Float(Math.signum(w-focusposn)).intValue()); else localsparseindex = VectorUtils.permuteVector(localsparseindex, new Float(Math.signum(w-focusposn)).intValue()); } // docterms[coterm] contains the term in position[w] in this document. if (this.indexVectors.getVector(docterms[coterm]) != null && localtermvectors[focusterm] != null) { if (retraining) VectorUtils.addVectors(localtermvectors[focusterm],localindex,1); else VectorUtils.addVectors(localtermvectors[focusterm],localsparseindex,1); } } } } }
Add a constructor that takes the additional parameters dimension and positionalmethod, making the constructor completely independent from Flags. git-svn-id: 08ea2b8556b98ff0c759f891b20f299445ddff2f@390 483481f0-a63c-0410-a8a8-396719eec1a4
src/pitt/search/semanticvectors/TermTermVectorsFromLucene.java
Add a constructor that takes the additional parameters dimension and positionalmethod, making the constructor completely independent from Flags.
<ide><path>rc/pitt/search/semanticvectors/TermTermVectorsFromLucene.java <ide> package pitt.search.semanticvectors; <ide> <ide> import java.util.Arrays; <del>import java.util.Hashtable; <ide> import java.util.Enumeration; <ide> import java.util.Random; <ide> import java.io.File; <ide> import java.io.IOException; <del>import java.lang.RuntimeException; <del> <del>import org.apache.lucene.analysis.standard.StandardAnalyzer; <add> <ide> import org.apache.lucene.index.IndexReader; <del>import org.apache.lucene.index.IndexWriter; <ide> import org.apache.lucene.index.Term; <del>import org.apache.lucene.index.TermDocs; <ide> import org.apache.lucene.index.TermEnum; <ide> import org.apache.lucene.index.TermPositionVector; <ide> import org.apache.lucene.store.FSDirectory; <ide> private short[][] localsparseindexvectors; <ide> private LuceneUtils lUtils; <ide> private int nonAlphabet; <add> <add> private int dimension; <add> private String positionalmethod; <ide> <ide> static final short NONEXISTENT = -1; <ide> <ide> } <ide> <ide> /** <add> * This constructor uses all the values passed as arguments and in addition <add> * the parameters dimension and positionalmethod from Flags. <ide> * @param indexDir Directory containing Lucene index. <ide> * @param seedLength Number of +1 or -1 entries in basic <ide> * vectors. Should be even to give same number of each. <ide> * @param minFreq The minimum term frequency for a term to be indexed. <add> * @param nonAlphabet <ide> * @param windowSize The size of the sliding context window. <add> * @param basicTermVectors <ide> * @param fieldsToIndex These fields will be indexed. <add> * @throws IOException <add> * @throws RuntimeException <add> * @deprecated use the constructor that explicitly specifies all needed <add> * values from Flags. <ide> */ <ide> public TermTermVectorsFromLucene(String indexDir, <ide> int seedLength, <ide> VectorStore basicTermVectors, <ide> String[] fieldsToIndex) <ide> throws IOException, RuntimeException { <add> this.dimension = Flags.dimension; <add> this.positionalmethod = Flags.positionalmethod; <add> doConstructor(indexDir,seedLength,minFreq,nonAlphabet, <add> windowSize,basicTermVectors,fieldsToIndex); <add> } <add> /** <add> * This constructor uses only the values passed, no parameters from Flag. <add> * @param indexDir Directory containing Lucene index. <add> * @dimension number of dimensions to use for the vectors <add> * @param dimension <add> * @param seedLength Number of +1 or -1 entries in basic <add> * vectors. Should be even to give same number of each. <add> * @param minFreq The minimum term frequency for a term to be indexed. <add> * @param nonAlphabet <add> * @param windowSize The size of the sliding context window. <add> * @param positionalmethod <add> * @param basicTermVectors <add> * @param fieldsToIndex These fields will be indexed. <add> * @throws IOException <add> * @throws RuntimeException <add> */ <add> public TermTermVectorsFromLucene(String indexDir, <add> int dimension, <add> int seedLength, <add> int minFreq, <add> int nonAlphabet, <add> int windowSize, <add> String positionalmethod, <add> VectorStore basicTermVectors, <add> String[] fieldsToIndex) <add> throws IOException, RuntimeException { <add> this.dimension = dimension; <add> this.positionalmethod = positionalmethod; <add> doConstructor(indexDir,seedLength,minFreq,nonAlphabet, <add> windowSize,basicTermVectors,fieldsToIndex); <add> } <add> private void doConstructor(String indexDir, <add> int seedLength, <add> int minFreq, <add> int nonAlphabet, <add> int windowSize, <add> VectorStore basicTermVectors, <add> String[] fieldsToIndex) <add> throws IOException, RuntimeException { <add> <ide> this.minFreq = minFreq; <ide> this.nonAlphabet = nonAlphabet; <ide> this.fieldsToIndex = fieldsToIndex; <ide> continue; <ide> } <ide> tc++; <del> float[] termVector = new float[Flags.dimension]; <add> float[] termVector = new float[dimension]; <ide> // Place each term vector in the vector store. <ide> this.termVectors.putVector(term.text(), termVector); <ide> // Do the same for random index vectors unless retraining with trained term vectors <ide> } <ide> <ide> // If building a permutation index, these need to be written out to be reused. <del> if ((Flags.positionalmethod.equals("permutation") || (Flags.positionalmethod.equals("permutation_plus_basic") ))&& !retraining) { <add> if ((positionalmethod.equals("permutation") || (positionalmethod.equals("permutation_plus_basic") ))&& !retraining) { <ide> String randFile = "randomvectors.bin"; <ide> System.err.println("\nWriting random vectors to "+randFile); <ide> System.err.println("\nNormalizing random vectors"); <ide> <ide> // Create local random index and term vectors for relevant terms. <ide> if (retraining) <del> localindexvectors = new float[numwords][Flags.dimension]; <add> localindexvectors = new float[numwords][dimension]; <ide> else <ide> localsparseindexvectors = new short[numwords][seedLength]; <ide> <del> float[][] localtermvectors = new float[numwords][Flags.dimension]; <add> float[][] localtermvectors = new float[numwords][dimension]; <ide> <ide> // Create index with one space for each position. <ide> short[] positions = new short[numpositions]; <ide> else localsparseindex = localsparseindexvectors[coterm].clone(); <ide> <ide> //combine 'content' and 'order' information - first add the unpermuted vector <del> if (Flags.positionalmethod.equals("permutation_plus_basic")) <add> if (positionalmethod.equals("permutation_plus_basic")) <ide> { <ide> // docterms[coterm] contains the term in position[w] in this document. <ide> if (this.indexVectors.getVector(docterms[coterm]) != null && localtermvectors[focusterm] != null) { <ide> VectorUtils.addVectors(localtermvectors[focusterm],localsparseindex,1); <ide> } <ide> } <del> <del> if (Flags.positionalmethod.equals("permutation") || Flags.positionalmethod.equals("permutation_plus_basic")) { <add> <add> if (positionalmethod.equals("permutation") || positionalmethod.equals("permutation_plus_basic")) { <ide> int permutation = w - focusposn; <ide> if (retraining) <ide> localindex = VectorUtils.permuteVector(localindex , permutation); <ide> else localsparseindex = VectorUtils.permuteVector(localsparseindex, permutation); <del> } else if (Flags.positionalmethod.equals("directional")) { <add> } else if (positionalmethod.equals("directional")) { <ide> if (retraining) <ide> localindex = VectorUtils.permuteVector(localindex, new Float(Math.signum(w-focusposn)).intValue()); <ide> else localsparseindex = VectorUtils.permuteVector(localsparseindex, new Float(Math.signum(w-focusposn)).intValue());
Java
apache-2.0
831201224a63bd8152bb9e8703cefe2d2aefe486
0
openanalytics/shinyproxy,openanalytics/shinyproxy,openanalytics/shinyproxy,openanalytics/shinyproxy
/** * ShinyProxy * * Copyright (C) 2016-2017 Open Analytics * * =========================================================================== * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License as published by * The Apache Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Apache License for more details. * * You should have received a copy of the Apache License * along with this program. If not, see <http://www.apache.org/licenses/> */ package eu.openanalytics.services; import java.io.FileInputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Properties; import java.util.Random; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.function.IntPredicate; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import org.apache.commons.codec.binary.Hex; import org.apache.log4j.Logger; import org.springframework.context.annotation.Bean; import org.springframework.core.env.Environment; import org.springframework.stereotype.Service; import org.springframework.web.util.WebUtils; import com.spotify.docker.client.DefaultDockerClient; import com.spotify.docker.client.DockerCertificates; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.DockerClient.LogsParam; import com.spotify.docker.client.DockerClient.RemoveContainerParam; import com.spotify.docker.client.LogStream; import com.spotify.docker.client.exceptions.DockerCertificateException; import com.spotify.docker.client.exceptions.DockerException; import com.spotify.docker.client.messages.ContainerConfig; import com.spotify.docker.client.messages.ContainerCreation; import com.spotify.docker.client.messages.ContainerInfo; import com.spotify.docker.client.messages.HostConfig; import com.spotify.docker.client.messages.HostConfig.Builder; import com.spotify.docker.client.messages.PortBinding; import com.spotify.docker.client.messages.mount.Mount; import com.spotify.docker.client.messages.swarm.ContainerSpec; import com.spotify.docker.client.messages.swarm.DnsConfig; import com.spotify.docker.client.messages.swarm.EndpointSpec; import com.spotify.docker.client.messages.swarm.NetworkAttachmentConfig; import com.spotify.docker.client.messages.swarm.Node; import com.spotify.docker.client.messages.swarm.PortConfig; import com.spotify.docker.client.messages.swarm.ServiceSpec; import com.spotify.docker.client.messages.swarm.Task; import com.spotify.docker.client.messages.swarm.TaskSpec; import eu.openanalytics.ShinyProxyException; import eu.openanalytics.services.AppService.ShinyApp; import eu.openanalytics.services.EventService.EventType; import io.undertow.server.HttpServerExchange; import io.undertow.server.handlers.Cookie; import io.undertow.servlet.handlers.ServletRequestContext; @Service public class DockerService { private Logger log = Logger.getLogger(DockerService.class); private Random rng = new Random(); private List<Proxy> launchingProxies = Collections.synchronizedList(new ArrayList<>()); private List<Proxy> activeProxies = Collections.synchronizedList(new ArrayList<>()); private List<MappingListener> mappingListeners = Collections.synchronizedList(new ArrayList<>()); private Set<Integer> occupiedPorts = Collections.synchronizedSet(new HashSet<>()); private ExecutorService containerKiller = Executors.newSingleThreadExecutor(); private boolean swarmMode = false; @Inject Environment environment; @Inject AppService appService; @Inject UserService userService; @Inject EventService eventService; @Inject LogService logService; @Inject DockerClient dockerClient; public static class Proxy { public String name; public String protocol; public String host; public int port; public String containerId; public String serviceId; public String userName; public String appName; public Set<String> sessionIds = new HashSet<>(); public long startupTimestamp; public Long lastHeartbeatTimestamp; public String uptime() { long uptimeSec = (System.currentTimeMillis() - startupTimestamp)/1000; return String.format("%d:%02d:%02d", uptimeSec/3600, (uptimeSec%3600)/60, uptimeSec%60); } public Proxy copyInto(Proxy target) { target.name = this.name; target.protocol = this.protocol; target.host = this.host; target.port = this.port; target.containerId = this.containerId; target.serviceId = this.serviceId; target.userName = this.userName; target.appName = this.appName; target.sessionIds = this.sessionIds; target.startupTimestamp = this.startupTimestamp; return target; } } @PostConstruct public void init() { try { swarmMode = (dockerClient.inspectSwarm().id() != null); } catch (DockerException | InterruptedException e) {} log.info(String.format("Swarm mode is %s", (swarmMode ? "enabled" : "disabled"))); Thread heartbeatThread = new Thread(new AppCleaner(), "HeartbeatThread"); heartbeatThread.setDaemon(true); heartbeatThread.start(); } @PreDestroy public void shutdown() { containerKiller.shutdown(); List<Proxy> proxiesToRelease = new ArrayList<>(); synchronized (activeProxies) { proxiesToRelease.addAll(activeProxies); } for (Proxy proxy: proxiesToRelease) releaseProxy(proxy, false); } @Bean public DockerClient getDockerClient() { try { DefaultDockerClient.Builder builder = DefaultDockerClient.fromEnv(); String confCertPath = environment.getProperty("shiny.proxy.docker.cert-path"); if (confCertPath != null) { builder.dockerCertificates(DockerCertificates.builder().dockerCertPath(Paths.get(confCertPath)).build().orNull()); } String confUrl = environment.getProperty("shiny.proxy.docker.url"); if (confUrl != null) { builder.uri(confUrl); } return builder.build(); } catch (DockerCertificateException e) { throw new ShinyProxyException("Failed to initialize docker client", e); } } public List<Proxy> listProxies() { synchronized (activeProxies) { return activeProxies.stream().map(p -> p.copyInto(new Proxy())).collect(Collectors.toList()); } } public String getMapping(HttpServletRequest request, String userName, String appName, boolean startNew) { waitForLaunchingProxy(userName, appName); Proxy proxy = findProxy(userName, appName); if (proxy == null && startNew) { // The user has no proxy yet. proxy = startProxy(userName, appName); } if (proxy == null) { return null; } else { proxy.sessionIds.add(getCurrentSessionId(request)); return proxy.name; } } public boolean sessionOwnsProxy(HttpServerExchange exchange) { String sessionId = getCurrentSessionId(exchange); if (sessionId == null) return false; String proxyName = exchange.getRelativePath(); synchronized (activeProxies) { for (Proxy p: activeProxies) { if (p.sessionIds.contains(sessionId) && proxyName.startsWith("/" + p.name)) { return true; } } } synchronized (launchingProxies) { for (Proxy p: launchingProxies) { if (p.sessionIds.contains(sessionId) && proxyName.startsWith("/" + p.name)) { return true; } } } return false; } public List<Proxy> releaseProxies(String userName) { List<Proxy> proxiesToRelease = new ArrayList<>(); synchronized (activeProxies) { for (Proxy proxy: activeProxies) { if (userName.equals(proxy.userName)) proxiesToRelease.add(proxy); } } for (Proxy proxy: proxiesToRelease) { releaseProxy(proxy, true); } return proxiesToRelease; } public void releaseProxy(String userName, String appName) { Proxy proxy = findProxy(userName, appName); if (proxy != null) { releaseProxy(proxy, true); } } private String getCurrentSessionId(HttpServerExchange exchange) { if (exchange == null && ServletRequestContext.current() != null) { exchange = ServletRequestContext.current().getExchange(); } if (exchange == null) return null; Cookie sessionCookie = exchange.getRequestCookies().get("JSESSIONID"); if (sessionCookie == null) return null; return sessionCookie.getValue(); } private String getCurrentSessionId(HttpServletRequest request) { if (request == null) { return getCurrentSessionId((HttpServerExchange) null); } javax.servlet.http.Cookie sessionCookie = WebUtils.getCookie(request, "JSESSIONID"); if (sessionCookie == null) return null; return sessionCookie.getValue(); } private void releaseProxy(Proxy proxy, boolean async) { activeProxies.remove(proxy); Runnable releaser = () -> { try { if (swarmMode) { dockerClient.removeService(proxy.serviceId); } else { ShinyApp app = appService.getApp(proxy.appName); if (app != null && app.getDockerNetworkConnections() != null) { for (String networkConnection: app.getDockerNetworkConnections()) { dockerClient.disconnectFromNetwork(proxy.containerId, networkConnection); } } dockerClient.removeContainer(proxy.containerId, RemoveContainerParam.forceKill()); } releasePort(proxy.port); log.info(String.format("Proxy released [user: %s] [app: %s] [port: %d]", proxy.userName, proxy.appName, proxy.port)); eventService.post(EventType.AppStop.toString(), proxy.userName, proxy.appName); } catch (Exception e){ log.error("Failed to release proxy " + proxy.name, e); } }; if (async) containerKiller.submit(releaser); else releaser.run(); synchronized (mappingListeners) { for (MappingListener listener: mappingListeners) { listener.mappingRemoved(proxy.name); } } } private Proxy startProxy(String userName, String appName) { ShinyApp app = appService.getApp(appName); if (app == null) { throw new ShinyProxyException("Cannot start container: unknown application: " + appName); } if (findProxy(userName, appName) != null) { throw new ShinyProxyException("Cannot start container: user " + userName + " already has a running proxy"); } boolean internalNetworking = "true".equals(environment.getProperty("shiny.proxy.docker.internal-networking")); boolean generateName = swarmMode || "true".equals(environment.getProperty("shiny.proxy.docker.generate-name", String.valueOf(internalNetworking))); Proxy proxy = new Proxy(); proxy.userName = userName; proxy.appName = appName; if (internalNetworking) { proxy.port = app.getPort(); } else { proxy.port = getFreePort(); } launchingProxies.add(proxy); try { URL hostURL = null; String containerProtocolDefault = "http"; if (!internalNetworking) { hostURL = new URL(environment.getProperty("shiny.proxy.docker.url")); containerProtocolDefault = hostURL.getProtocol(); } proxy.protocol = environment.getProperty("shiny.proxy.docker.container-protocol", containerProtocolDefault); if (generateName) { byte[] nameBytes = new byte[20]; rng.nextBytes(nameBytes); proxy.name = Hex.encodeHexString(nameBytes); } if (swarmMode) { Mount[] mounts = getBindVolumes(app).stream() .map(b -> b.split(":")) .map(fromTo -> Mount.builder().source(fromTo[0]).target(fromTo[1]).type("bind").build()) .toArray(i -> new Mount[i]); ContainerSpec containerSpec = ContainerSpec.builder() .image(app.getDockerImage()) .command(app.getDockerCmd()) .env(buildEnv(userName, app)) .dnsConfig(DnsConfig.builder().nameServers(app.getDockerDns()).build()) .mounts(mounts) .build(); NetworkAttachmentConfig[] networks = Arrays .stream(Optional.ofNullable(app.getDockerNetworkConnections()).orElse(new String[0])) .map(n -> NetworkAttachmentConfig.builder().target(n).build()) .toArray(i -> new NetworkAttachmentConfig[i]); ServiceSpec.Builder serviceSpecBuilder = ServiceSpec.builder() .networks(networks) .name(proxy.name) .taskTemplate(TaskSpec.builder() .containerSpec(containerSpec) .build()); if (!internalNetworking) { serviceSpecBuilder.endpointSpec(EndpointSpec.builder() .ports(PortConfig.builder().publishedPort(proxy.port).targetPort(app.getPort()).build()) .build()); } proxy.serviceId = dockerClient.createService(serviceSpecBuilder.build()).id(); boolean containerFound = retry(i -> { try { Task serviceTask = dockerClient .listTasks(Task.Criteria.builder().serviceName(proxy.name).build()) .stream().findAny().orElseThrow(() -> new IllegalStateException("Swarm service has no tasks")); proxy.containerId = serviceTask.status().containerStatus().containerId(); proxy.host = serviceTask.nodeId(); } catch (Exception e) { throw new RuntimeException("Failed to inspect swarm service tasks"); } return (proxy.containerId != null); }, 10, 2000); if (!containerFound) throw new IllegalStateException("Swarm container did not start in time"); if (internalNetworking) { proxy.host = proxy.name; } else { Node node = dockerClient.listNodes().stream() .filter(n -> n.id().equals(proxy.host)).findAny() .orElseThrow(() -> new IllegalStateException(String.format("Swarm node not found [id: %s]", proxy.host))); proxy.host = node.description().hostname(); } log.info(String.format("Container running in swarm [service: %s] [node: %s]", proxy.name, proxy.host)); } else { Builder hostConfigBuilder = HostConfig.builder(); Optional.ofNullable(memoryToBytes(app.getDockerMemory())).ifPresent(l -> hostConfigBuilder.memory(l)); Optional.ofNullable(app.getDockerNetwork()).ifPresent(n -> hostConfigBuilder.networkMode(app.getDockerNetwork())); List<PortBinding> portBindings; if (internalNetworking) { portBindings = Collections.emptyList(); } else { portBindings = Collections.singletonList(PortBinding.of("0.0.0.0", proxy.port)); } hostConfigBuilder .portBindings(Collections.singletonMap(app.getPort().toString(), portBindings)) .dns(app.getDockerDns()) .binds(getBindVolumes(app)); ContainerConfig containerConfig = ContainerConfig.builder() .hostConfig(hostConfigBuilder.build()) .image(app.getDockerImage()) .exposedPorts(app.getPort().toString()) .cmd(app.getDockerCmd()) .env(buildEnv(userName, app)) .build(); ContainerCreation container = dockerClient.createContainer(containerConfig); if (app.getDockerNetworkConnections() != null) { for (String networkConnection: app.getDockerNetworkConnections()) { dockerClient.connectToNetwork(container.id(), networkConnection); } } if (proxy.name != null) { dockerClient.renameContainer(container.id(), proxy.name); } dockerClient.startContainer(container.id()); ContainerInfo info = dockerClient.inspectContainer(container.id()); if (proxy.name == null) { proxy.name = info.name().substring(1); } if (internalNetworking) { proxy.host = proxy.name; } else { proxy.host = hostURL.getHost(); } proxy.containerId = container.id(); } proxy.startupTimestamp = System.currentTimeMillis(); } catch (Exception e) { releasePort(proxy.port); launchingProxies.remove(proxy); throw new ShinyProxyException("Failed to start container: " + e.getMessage(), e); } if (!testProxy(proxy)) { releaseProxy(proxy, true); launchingProxies.remove(proxy); throw new ShinyProxyException("Container did not respond in time"); } try { URI target = new URI(String.format("%s://%s:%d", proxy.protocol, proxy.host, proxy.port)); synchronized (mappingListeners) { for (MappingListener listener: mappingListeners) { listener.mappingAdded(proxy.name, target); } } } catch (URISyntaxException ignore) {} if (logService.isContainerLoggingEnabled()) { try { LogStream logStream = dockerClient.logs(proxy.containerId, LogsParam.follow(), LogsParam.stdout(), LogsParam.stderr()); logService.attachLogWriter(proxy, logStream); } catch (DockerException e) { log.error("Failed to attach to container log " + proxy.containerId, e); } catch (InterruptedException e) { log.error("Interrupted while attaching to container log " + proxy.containerId, e); } } activeProxies.add(proxy); launchingProxies.remove(proxy); log.info(String.format("Proxy activated [user: %s] [app: %s] [port: %d]", userName, appName, proxy.port)); eventService.post(EventType.AppStart.toString(), userName, appName); return proxy; } private Proxy findProxy(String userName, String appName) { synchronized (activeProxies) { for (Proxy proxy: activeProxies) { if (userName.equals(proxy.userName) && appName.equals(proxy.appName)) return proxy; } } return null; } private void waitForLaunchingProxy(String userName, String appName) { int totalWaitMs = Integer.parseInt(environment.getProperty("shiny.proxy.container-wait-time", "20000")); int waitMs = Math.min(2000, totalWaitMs); int maxTries = totalWaitMs / waitMs; boolean mayProceed = retry(i -> { synchronized (launchingProxies) { for (Proxy proxy: launchingProxies) { if (userName.equals(proxy.userName) && appName.equals(proxy.appName)) { return false; } } } return true; }, maxTries, waitMs); if (!mayProceed) throw new ShinyProxyException("Cannot proceed: waiting for proxy to launch"); } private boolean testProxy(Proxy proxy) { int totalWaitMs = Integer.parseInt(environment.getProperty("shiny.proxy.container-wait-time", "20000")); int waitMs = Math.min(2000, totalWaitMs); int maxTries = totalWaitMs / waitMs; int timeoutMs = Integer.parseInt(environment.getProperty("shiny.proxy.container-wait-timeout", "5000")); return retry(i -> { String urlString = String.format("%s://%s:%d", proxy.protocol, proxy.host, proxy.port); try { URL testURL = new URL(urlString); HttpURLConnection connection = ((HttpURLConnection) testURL.openConnection()); connection.setConnectTimeout(timeoutMs); int responseCode = connection.getResponseCode(); if (responseCode == 200) return true; } catch (Exception e) { if (i > 1) log.warn(String.format("Container unresponsive, trying again (%d/%d): %s", i, maxTries, urlString)); } return false; }, maxTries, waitMs); } private List<String> buildEnv(String userName, ShinyApp app) throws IOException { List<String> env = new ArrayList<>(); env.add(String.format("SHINYPROXY_USERNAME=%s", userName)); String[] groups = userService.getGroups(userService.getCurrentAuth()); env.add(String.format("SHINYPROXY_USERGROUPS=%s", Arrays.stream(groups).collect(Collectors.joining(",")))); String envFile = app.getDockerEnvFile(); if (envFile != null && Files.isRegularFile(Paths.get(envFile))) { Properties envProps = new Properties(); envProps.load(new FileInputStream(envFile)); for (Object key: envProps.keySet()) { env.add(String.format("%s=%s", key, envProps.get(key))); } } for (Map.Entry<String, String> entry : app.getDockerEnv().entrySet()) { env.add(String.format("%s=%s", entry.getKey(), entry.getValue())); } return env; } private List<String> getBindVolumes(ShinyApp app) { List<String> volumes = new ArrayList<>(); if (app.getDockerVolumes() != null) { for (String vol: app.getDockerVolumes()) { volumes.add(vol); } } return volumes; } private int getFreePort() { int startPort = Integer.valueOf(environment.getProperty("shiny.proxy.docker.port-range-start")); int maxPort = Integer.valueOf(environment.getProperty("shiny.proxy.docker.port-range-max", "-1")); int nextPort = startPort; while (occupiedPorts.contains(nextPort)) nextPort++; if (maxPort > 0 && nextPort > maxPort) { throw new ShinyProxyException("Cannot start container: all allocated ports are currently in use." + " Please try again later or contact an administrator."); } occupiedPorts.add(nextPort); return nextPort; } private void releasePort(int port) { occupiedPorts.remove(port); } private boolean retry(IntPredicate job, int tries, int waitTime) { boolean retVal = false; for (int currentTry = 1; currentTry <= tries; currentTry++) { if (job.test(currentTry)) { retVal = true; break; } try { Thread.sleep(waitTime); } catch (InterruptedException ignore) {} } return retVal; } private Long memoryToBytes(String memory) { if (memory == null || memory.isEmpty()) return null; Matcher matcher = Pattern.compile("(\\d+)([bkmg]?)").matcher(memory.toLowerCase()); if (!matcher.matches()) throw new IllegalArgumentException("Invalid memory argument: " + memory); long mem = Long.parseLong(matcher.group(1)); String unit = matcher.group(2); switch (unit) { case "k": mem *= 1024; break; case "m": mem *= 1024*1024; break; case "g": mem *= 1024*1024*1024; break; default: } return mem; } public void addMappingListener(MappingListener listener) { mappingListeners.add(listener); } public void removeMappingListener(MappingListener listener) { mappingListeners.remove(listener); } public static interface MappingListener { public void mappingAdded(String mapping, URI target); public void mappingRemoved(String mapping); } public void heartbeatReceived(String user, String app) { Proxy proxy = findProxy(user, app); if (proxy != null) { proxy.lastHeartbeatTimestamp = System.currentTimeMillis(); } } private class AppCleaner implements Runnable { @Override public void run() { long cleanupInterval = 2 * Long.parseLong(environment.getProperty("shiny.proxy.heartbeat-rate", "10000")); long heartbeatTimeout = Long.parseLong(environment.getProperty("shiny.proxy.heartbeat-timeout", "60000")); while (true) { try { List<Proxy> proxiesToRemove = new ArrayList<>(); long currentTimestamp = System.currentTimeMillis(); synchronized (activeProxies) { for (Proxy proxy: activeProxies) { Long lastHeartbeat = proxy.lastHeartbeatTimestamp; if (lastHeartbeat == null) lastHeartbeat = proxy.startupTimestamp; long proxySilence = currentTimestamp - lastHeartbeat; if (proxySilence > heartbeatTimeout) { log.info(String.format("Releasing inactive proxy [user: %s] [app: %s] [silence: %dms]", proxy.userName, proxy.appName, proxySilence)); proxiesToRemove.add(proxy); } } } for (Proxy proxy: proxiesToRemove) { releaseProxy(proxy, true); } } catch (Throwable t) { log.error("Error in HeartbeatThread", t); } try { Thread.sleep(cleanupInterval); } catch (InterruptedException e) {} } } } }
src/main/java/eu/openanalytics/services/DockerService.java
/** * ShinyProxy * * Copyright (C) 2016-2017 Open Analytics * * =========================================================================== * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License as published by * The Apache Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Apache License for more details. * * You should have received a copy of the Apache License * along with this program. If not, see <http://www.apache.org/licenses/> */ package eu.openanalytics.services; import java.io.FileInputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Properties; import java.util.Random; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.function.IntPredicate; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import org.apache.commons.codec.binary.Hex; import org.apache.log4j.Logger; import org.springframework.context.annotation.Bean; import org.springframework.core.env.Environment; import org.springframework.stereotype.Service; import org.springframework.web.util.WebUtils; import com.spotify.docker.client.DefaultDockerClient; import com.spotify.docker.client.DockerCertificates; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.DockerClient.LogsParam; import com.spotify.docker.client.DockerClient.RemoveContainerParam; import com.spotify.docker.client.LogStream; import com.spotify.docker.client.exceptions.DockerCertificateException; import com.spotify.docker.client.exceptions.DockerException; import com.spotify.docker.client.messages.ContainerConfig; import com.spotify.docker.client.messages.ContainerCreation; import com.spotify.docker.client.messages.ContainerInfo; import com.spotify.docker.client.messages.HostConfig; import com.spotify.docker.client.messages.HostConfig.Builder; import com.spotify.docker.client.messages.PortBinding; import com.spotify.docker.client.messages.mount.Mount; import com.spotify.docker.client.messages.swarm.ContainerSpec; import com.spotify.docker.client.messages.swarm.DnsConfig; import com.spotify.docker.client.messages.swarm.EndpointSpec; import com.spotify.docker.client.messages.swarm.NetworkAttachmentConfig; import com.spotify.docker.client.messages.swarm.Node; import com.spotify.docker.client.messages.swarm.PortConfig; import com.spotify.docker.client.messages.swarm.ServiceSpec; import com.spotify.docker.client.messages.swarm.Task; import com.spotify.docker.client.messages.swarm.TaskSpec; import eu.openanalytics.ShinyProxyException; import eu.openanalytics.services.AppService.ShinyApp; import eu.openanalytics.services.EventService.EventType; import io.undertow.server.HttpServerExchange; import io.undertow.server.handlers.Cookie; import io.undertow.servlet.handlers.ServletRequestContext; @Service public class DockerService { private Logger log = Logger.getLogger(DockerService.class); private Random rng = new Random(); private List<Proxy> launchingProxies = Collections.synchronizedList(new ArrayList<>()); private List<Proxy> activeProxies = Collections.synchronizedList(new ArrayList<>()); private List<MappingListener> mappingListeners = Collections.synchronizedList(new ArrayList<>()); private Set<Integer> occupiedPorts = Collections.synchronizedSet(new HashSet<>()); private ExecutorService containerKiller = Executors.newSingleThreadExecutor(); private boolean swarmMode = false; @Inject Environment environment; @Inject AppService appService; @Inject UserService userService; @Inject EventService eventService; @Inject LogService logService; @Inject DockerClient dockerClient; public static class Proxy { public String name; public String protocol; public String host; public int port; public String containerId; public String serviceId; public String userName; public String appName; public Set<String> sessionIds = new HashSet<>(); public long startupTimestamp; public Long lastHeartbeatTimestamp; public String uptime() { long uptimeSec = (System.currentTimeMillis() - startupTimestamp)/1000; return String.format("%d:%02d:%02d", uptimeSec/3600, (uptimeSec%3600)/60, uptimeSec%60); } public Proxy copyInto(Proxy target) { target.name = this.name; target.protocol = this.protocol; target.host = this.host; target.port = this.port; target.containerId = this.containerId; target.serviceId = this.serviceId; target.userName = this.userName; target.appName = this.appName; target.sessionIds = this.sessionIds; target.startupTimestamp = this.startupTimestamp; return target; } } @PostConstruct public void init() { try { swarmMode = (dockerClient.inspectSwarm().id() != null); } catch (DockerException | InterruptedException e) {} log.info(String.format("Swarm mode is %s", (swarmMode ? "enabled" : "disabled"))); Thread heartbeatThread = new Thread(new AppCleaner(), "HeartbeatThread"); heartbeatThread.setDaemon(true); heartbeatThread.start(); } @PreDestroy public void shutdown() { containerKiller.shutdown(); List<Proxy> proxiesToRelease = new ArrayList<>(); synchronized (activeProxies) { proxiesToRelease.addAll(activeProxies); } for (Proxy proxy: proxiesToRelease) releaseProxy(proxy, false); } @Bean public DockerClient getDockerClient() { try { DefaultDockerClient.Builder builder = DefaultDockerClient.fromEnv(); String confCertPath = environment.getProperty("shiny.proxy.docker.cert-path"); if (confCertPath != null) { builder.dockerCertificates(DockerCertificates.builder().dockerCertPath(Paths.get(confCertPath)).build().orNull()); } String confUrl = environment.getProperty("shiny.proxy.docker.url"); if (confUrl != null) { builder.uri(confUrl); } return builder.build(); } catch (DockerCertificateException e) { throw new ShinyProxyException("Failed to initialize docker client", e); } } public List<Proxy> listProxies() { synchronized (activeProxies) { return activeProxies.stream().map(p -> p.copyInto(new Proxy())).collect(Collectors.toList()); } } public String getMapping(HttpServletRequest request, String userName, String appName, boolean startNew) { waitForLaunchingProxy(userName, appName); Proxy proxy = findProxy(userName, appName); if (proxy == null && startNew) { // The user has no proxy yet. proxy = startProxy(userName, appName); } if (proxy == null) { return null; } else { proxy.sessionIds.add(getCurrentSessionId(request)); return proxy.name; } } public boolean sessionOwnsProxy(HttpServerExchange exchange) { String sessionId = getCurrentSessionId(exchange); if (sessionId == null) return false; String proxyName = exchange.getRelativePath(); synchronized (activeProxies) { for (Proxy p: activeProxies) { if (p.sessionIds.contains(sessionId) && proxyName.startsWith("/" + p.name)) { return true; } } } synchronized (launchingProxies) { for (Proxy p: launchingProxies) { if (p.sessionIds.contains(sessionId) && proxyName.startsWith("/" + p.name)) { return true; } } } return false; } public List<Proxy> releaseProxies(String userName) { List<Proxy> proxiesToRelease = new ArrayList<>(); synchronized (activeProxies) { for (Proxy proxy: activeProxies) { if (userName.equals(proxy.userName)) proxiesToRelease.add(proxy); } } for (Proxy proxy: proxiesToRelease) { releaseProxy(proxy, true); } return proxiesToRelease; } public void releaseProxy(String userName, String appName) { Proxy proxy = findProxy(userName, appName); if (proxy != null) { releaseProxy(proxy, true); } } private String getCurrentSessionId(HttpServerExchange exchange) { if (exchange == null && ServletRequestContext.current() != null) { exchange = ServletRequestContext.current().getExchange(); } if (exchange == null) return null; Cookie sessionCookie = exchange.getRequestCookies().get("JSESSIONID"); if (sessionCookie == null) return null; return sessionCookie.getValue(); } private String getCurrentSessionId(HttpServletRequest request) { if (request == null) { return getCurrentSessionId((HttpServerExchange) null); } javax.servlet.http.Cookie sessionCookie = WebUtils.getCookie(request, "JSESSIONID"); if (sessionCookie == null) return null; return sessionCookie.getValue(); } private void releaseProxy(Proxy proxy, boolean async) { activeProxies.remove(proxy); Runnable releaser = () -> { try { if (swarmMode) { dockerClient.removeService(proxy.serviceId); } else { ShinyApp app = appService.getApp(proxy.appName); if (app != null && app.getDockerNetworkConnections() != null) { for (String networkConnection: app.getDockerNetworkConnections()) { dockerClient.disconnectFromNetwork(proxy.containerId, networkConnection); } } dockerClient.removeContainer(proxy.containerId, RemoveContainerParam.forceKill()); } releasePort(proxy.port); log.info(String.format("Proxy released [user: %s] [app: %s] [port: %d]", proxy.userName, proxy.appName, proxy.port)); eventService.post(EventType.AppStop.toString(), proxy.userName, proxy.appName); } catch (Exception e){ log.error("Failed to release proxy " + proxy.name, e); } }; if (async) containerKiller.submit(releaser); else releaser.run(); synchronized (mappingListeners) { for (MappingListener listener: mappingListeners) { listener.mappingRemoved(proxy.name); } } } private Proxy startProxy(String userName, String appName) { ShinyApp app = appService.getApp(appName); if (app == null) { throw new ShinyProxyException("Cannot start container: unknown application: " + appName); } if (findProxy(userName, appName) != null) { throw new ShinyProxyException("Cannot start container: user " + userName + " already has a running proxy"); } boolean nameNetworking = "true".equals(environment.getProperty("shiny.proxy.docker.name-networking")); boolean generateName = swarmMode || "true".equals(environment.getProperty("shiny.proxy.docker.generate-name", String.valueOf(nameNetworking))); Proxy proxy = new Proxy(); proxy.userName = userName; proxy.appName = appName; if (nameNetworking) { proxy.port = app.getPort(); } else { proxy.port = getFreePort(); } launchingProxies.add(proxy); try { URL hostURL = null; String containerProtocolDefault = "http"; if (!nameNetworking) { hostURL = new URL(environment.getProperty("shiny.proxy.docker.url")); containerProtocolDefault = hostURL.getProtocol(); } proxy.protocol = environment.getProperty("shiny.proxy.docker.container-protocol", containerProtocolDefault); if (generateName) { byte[] nameBytes = new byte[20]; rng.nextBytes(nameBytes); proxy.name = Hex.encodeHexString(nameBytes); } if (swarmMode) { Mount[] mounts = getBindVolumes(app).stream() .map(b -> b.split(":")) .map(fromTo -> Mount.builder().source(fromTo[0]).target(fromTo[1]).type("bind").build()) .toArray(i -> new Mount[i]); ContainerSpec containerSpec = ContainerSpec.builder() .image(app.getDockerImage()) .command(app.getDockerCmd()) .env(buildEnv(userName, app)) .dnsConfig(DnsConfig.builder().nameServers(app.getDockerDns()).build()) .mounts(mounts) .build(); NetworkAttachmentConfig[] networks = Arrays .stream(Optional.ofNullable(app.getDockerNetworkConnections()).orElse(new String[0])) .map(n -> NetworkAttachmentConfig.builder().target(n).build()) .toArray(i -> new NetworkAttachmentConfig[i]); ServiceSpec.Builder serviceSpecBuilder = ServiceSpec.builder() .networks(networks) .name(proxy.name) .taskTemplate(TaskSpec.builder() .containerSpec(containerSpec) .build()); if (!nameNetworking) { serviceSpecBuilder.endpointSpec(EndpointSpec.builder() .ports(PortConfig.builder().publishedPort(proxy.port).targetPort(app.getPort()).build()) .build()); } proxy.serviceId = dockerClient.createService(serviceSpecBuilder.build()).id(); boolean containerFound = retry(i -> { try { Task serviceTask = dockerClient .listTasks(Task.Criteria.builder().serviceName(proxy.name).build()) .stream().findAny().orElseThrow(() -> new IllegalStateException("Swarm service has no tasks")); proxy.containerId = serviceTask.status().containerStatus().containerId(); proxy.host = serviceTask.nodeId(); } catch (Exception e) { throw new RuntimeException("Failed to inspect swarm service tasks"); } return (proxy.containerId != null); }, 10, 2000); if (!containerFound) throw new IllegalStateException("Swarm container did not start in time"); if (!nameNetworking) { Node node = dockerClient.listNodes().stream() .filter(n -> n.id().equals(proxy.host)).findAny() .orElseThrow(() -> new IllegalStateException(String.format("Swarm node not found [id: %s]", proxy.host))); proxy.host = node.description().hostname(); } log.info(String.format("Container running in swarm [service: %s] [node: %s]", proxy.name, proxy.host)); } else { Builder hostConfigBuilder = HostConfig.builder(); Optional.ofNullable(memoryToBytes(app.getDockerMemory())).ifPresent(l -> hostConfigBuilder.memory(l)); Optional.ofNullable(app.getDockerNetwork()).ifPresent(n -> hostConfigBuilder.networkMode(app.getDockerNetwork())); List<PortBinding> portBindings; if (nameNetworking) { portBindings = Collections.emptyList(); } else { portBindings = Collections.singletonList(PortBinding.of("0.0.0.0", proxy.port)); } hostConfigBuilder .portBindings(Collections.singletonMap(app.getPort().toString(), portBindings)) .dns(app.getDockerDns()) .binds(getBindVolumes(app)); ContainerConfig containerConfig = ContainerConfig.builder() .hostConfig(hostConfigBuilder.build()) .image(app.getDockerImage()) .exposedPorts(app.getPort().toString()) .cmd(app.getDockerCmd()) .env(buildEnv(userName, app)) .build(); ContainerCreation container = dockerClient.createContainer(containerConfig); if (app.getDockerNetworkConnections() != null) { for (String networkConnection: app.getDockerNetworkConnections()) { dockerClient.connectToNetwork(container.id(), networkConnection); } } if (proxy.name != null) { dockerClient.renameContainer(container.id(), proxy.name); } dockerClient.startContainer(container.id()); ContainerInfo info = dockerClient.inspectContainer(container.id()); if (proxy.name == null) { proxy.name = info.name().substring(1); } if (!nameNetworking) { proxy.host = hostURL.getHost(); } proxy.containerId = container.id(); } if (nameNetworking) { proxy.host = proxy.name; } proxy.startupTimestamp = System.currentTimeMillis(); } catch (Exception e) { releasePort(proxy.port); launchingProxies.remove(proxy); throw new ShinyProxyException("Failed to start container: " + e.getMessage(), e); } if (!testProxy(proxy)) { releaseProxy(proxy, true); launchingProxies.remove(proxy); throw new ShinyProxyException("Container did not respond in time"); } try { URI target = new URI(String.format("%s://%s:%d", proxy.protocol, proxy.host, proxy.port)); synchronized (mappingListeners) { for (MappingListener listener: mappingListeners) { listener.mappingAdded(proxy.name, target); } } } catch (URISyntaxException ignore) {} if (logService.isContainerLoggingEnabled()) { try { LogStream logStream = dockerClient.logs(proxy.containerId, LogsParam.follow(), LogsParam.stdout(), LogsParam.stderr()); logService.attachLogWriter(proxy, logStream); } catch (DockerException e) { log.error("Failed to attach to container log " + proxy.containerId, e); } catch (InterruptedException e) { log.error("Interrupted while attaching to container log " + proxy.containerId, e); } } activeProxies.add(proxy); launchingProxies.remove(proxy); log.info(String.format("Proxy activated [user: %s] [app: %s] [port: %d]", userName, appName, proxy.port)); eventService.post(EventType.AppStart.toString(), userName, appName); return proxy; } private Proxy findProxy(String userName, String appName) { synchronized (activeProxies) { for (Proxy proxy: activeProxies) { if (userName.equals(proxy.userName) && appName.equals(proxy.appName)) return proxy; } } return null; } private void waitForLaunchingProxy(String userName, String appName) { int totalWaitMs = Integer.parseInt(environment.getProperty("shiny.proxy.container-wait-time", "20000")); int waitMs = Math.min(2000, totalWaitMs); int maxTries = totalWaitMs / waitMs; boolean mayProceed = retry(i -> { synchronized (launchingProxies) { for (Proxy proxy: launchingProxies) { if (userName.equals(proxy.userName) && appName.equals(proxy.appName)) { return false; } } } return true; }, maxTries, waitMs); if (!mayProceed) throw new ShinyProxyException("Cannot proceed: waiting for proxy to launch"); } private boolean testProxy(Proxy proxy) { int totalWaitMs = Integer.parseInt(environment.getProperty("shiny.proxy.container-wait-time", "20000")); int waitMs = Math.min(2000, totalWaitMs); int maxTries = totalWaitMs / waitMs; int timeoutMs = Integer.parseInt(environment.getProperty("shiny.proxy.container-wait-timeout", "5000")); return retry(i -> { String urlString = String.format("%s://%s:%d", proxy.protocol, proxy.host, proxy.port); try { URL testURL = new URL(urlString); HttpURLConnection connection = ((HttpURLConnection) testURL.openConnection()); connection.setConnectTimeout(timeoutMs); int responseCode = connection.getResponseCode(); if (responseCode == 200) return true; } catch (Exception e) { if (i > 1) log.warn(String.format("Container unresponsive, trying again (%d/%d): %s", i, maxTries, urlString)); } return false; }, maxTries, waitMs); } private List<String> buildEnv(String userName, ShinyApp app) throws IOException { List<String> env = new ArrayList<>(); env.add(String.format("SHINYPROXY_USERNAME=%s", userName)); String[] groups = userService.getGroups(userService.getCurrentAuth()); env.add(String.format("SHINYPROXY_USERGROUPS=%s", Arrays.stream(groups).collect(Collectors.joining(",")))); String envFile = app.getDockerEnvFile(); if (envFile != null && Files.isRegularFile(Paths.get(envFile))) { Properties envProps = new Properties(); envProps.load(new FileInputStream(envFile)); for (Object key: envProps.keySet()) { env.add(String.format("%s=%s", key, envProps.get(key))); } } for (Map.Entry<String, String> entry : app.getDockerEnv().entrySet()) { env.add(String.format("%s=%s", entry.getKey(), entry.getValue())); } return env; } private List<String> getBindVolumes(ShinyApp app) { List<String> volumes = new ArrayList<>(); if (app.getDockerVolumes() != null) { for (String vol: app.getDockerVolumes()) { volumes.add(vol); } } return volumes; } private int getFreePort() { int startPort = Integer.valueOf(environment.getProperty("shiny.proxy.docker.port-range-start")); int maxPort = Integer.valueOf(environment.getProperty("shiny.proxy.docker.port-range-max", "-1")); int nextPort = startPort; while (occupiedPorts.contains(nextPort)) nextPort++; if (maxPort > 0 && nextPort > maxPort) { throw new ShinyProxyException("Cannot start container: all allocated ports are currently in use." + " Please try again later or contact an administrator."); } occupiedPorts.add(nextPort); return nextPort; } private void releasePort(int port) { occupiedPorts.remove(port); } private boolean retry(IntPredicate job, int tries, int waitTime) { boolean retVal = false; for (int currentTry = 1; currentTry <= tries; currentTry++) { if (job.test(currentTry)) { retVal = true; break; } try { Thread.sleep(waitTime); } catch (InterruptedException ignore) {} } return retVal; } private Long memoryToBytes(String memory) { if (memory == null || memory.isEmpty()) return null; Matcher matcher = Pattern.compile("(\\d+)([bkmg]?)").matcher(memory.toLowerCase()); if (!matcher.matches()) throw new IllegalArgumentException("Invalid memory argument: " + memory); long mem = Long.parseLong(matcher.group(1)); String unit = matcher.group(2); switch (unit) { case "k": mem *= 1024; break; case "m": mem *= 1024*1024; break; case "g": mem *= 1024*1024*1024; break; default: } return mem; } public void addMappingListener(MappingListener listener) { mappingListeners.add(listener); } public void removeMappingListener(MappingListener listener) { mappingListeners.remove(listener); } public static interface MappingListener { public void mappingAdded(String mapping, URI target); public void mappingRemoved(String mapping); } public void heartbeatReceived(String user, String app) { Proxy proxy = findProxy(user, app); if (proxy != null) { proxy.lastHeartbeatTimestamp = System.currentTimeMillis(); } } private class AppCleaner implements Runnable { @Override public void run() { long cleanupInterval = 2 * Long.parseLong(environment.getProperty("shiny.proxy.heartbeat-rate", "10000")); long heartbeatTimeout = Long.parseLong(environment.getProperty("shiny.proxy.heartbeat-timeout", "60000")); while (true) { try { List<Proxy> proxiesToRemove = new ArrayList<>(); long currentTimestamp = System.currentTimeMillis(); synchronized (activeProxies) { for (Proxy proxy: activeProxies) { Long lastHeartbeat = proxy.lastHeartbeatTimestamp; if (lastHeartbeat == null) lastHeartbeat = proxy.startupTimestamp; long proxySilence = currentTimestamp - lastHeartbeat; if (proxySilence > heartbeatTimeout) { log.info(String.format("Releasing inactive proxy [user: %s] [app: %s] [silence: %dms]", proxy.userName, proxy.appName, proxySilence)); proxiesToRemove.add(proxy); } } } for (Proxy proxy: proxiesToRemove) { releaseProxy(proxy, true); } } catch (Throwable t) { log.error("Error in HeartbeatThread", t); } try { Thread.sleep(cleanupInterval); } catch (InterruptedException e) {} } } } }
Rename name-networking to internal-networking I'm planning to add support for Kubernetes, and I don't think I'll be using the name based DNS system for that. I think it's better to describe this option as internal networking, which describes the what instead of the how.
src/main/java/eu/openanalytics/services/DockerService.java
Rename name-networking to internal-networking
<ide><path>rc/main/java/eu/openanalytics/services/DockerService.java <ide> throw new ShinyProxyException("Cannot start container: user " + userName + " already has a running proxy"); <ide> } <ide> <del> boolean nameNetworking = "true".equals(environment.getProperty("shiny.proxy.docker.name-networking")); <del> boolean generateName = swarmMode || "true".equals(environment.getProperty("shiny.proxy.docker.generate-name", String.valueOf(nameNetworking))); <add> boolean internalNetworking = "true".equals(environment.getProperty("shiny.proxy.docker.internal-networking")); <add> boolean generateName = swarmMode || "true".equals(environment.getProperty("shiny.proxy.docker.generate-name", String.valueOf(internalNetworking))); <ide> <ide> Proxy proxy = new Proxy(); <ide> proxy.userName = userName; <ide> proxy.appName = appName; <del> if (nameNetworking) { <add> if (internalNetworking) { <ide> proxy.port = app.getPort(); <ide> } else { <ide> proxy.port = getFreePort(); <ide> try { <ide> URL hostURL = null; <ide> String containerProtocolDefault = "http"; <del> if (!nameNetworking) { <add> if (!internalNetworking) { <ide> hostURL = new URL(environment.getProperty("shiny.proxy.docker.url")); <ide> containerProtocolDefault = hostURL.getProtocol(); <ide> } <ide> .taskTemplate(TaskSpec.builder() <ide> .containerSpec(containerSpec) <ide> .build()); <del> if (!nameNetworking) { <add> if (!internalNetworking) { <ide> serviceSpecBuilder.endpointSpec(EndpointSpec.builder() <ide> .ports(PortConfig.builder().publishedPort(proxy.port).targetPort(app.getPort()).build()) <ide> .build()); <ide> }, 10, 2000); <ide> if (!containerFound) throw new IllegalStateException("Swarm container did not start in time"); <ide> <del> if (!nameNetworking) { <add> if (internalNetworking) { <add> proxy.host = proxy.name; <add> } else { <ide> Node node = dockerClient.listNodes().stream() <ide> .filter(n -> n.id().equals(proxy.host)).findAny() <ide> .orElseThrow(() -> new IllegalStateException(String.format("Swarm node not found [id: %s]", proxy.host))); <ide> Optional.ofNullable(app.getDockerNetwork()).ifPresent(n -> hostConfigBuilder.networkMode(app.getDockerNetwork())); <ide> <ide> List<PortBinding> portBindings; <del> if (nameNetworking) { <add> if (internalNetworking) { <ide> portBindings = Collections.emptyList(); <ide> } else { <ide> portBindings = Collections.singletonList(PortBinding.of("0.0.0.0", proxy.port)); <ide> if (proxy.name == null) { <ide> proxy.name = info.name().substring(1); <ide> } <del> if (!nameNetworking) { <add> if (internalNetworking) { <add> proxy.host = proxy.name; <add> } else { <ide> proxy.host = hostURL.getHost(); <ide> } <ide> proxy.containerId = container.id(); <del> } <del> if (nameNetworking) { <del> proxy.host = proxy.name; <ide> } <ide> <ide> proxy.startupTimestamp = System.currentTimeMillis();
Java
mit
9345678127487d1a166bb0527f013d19976466f8
0
conveyal/datatools-manager,conveyal/datatools-manager,conveyal/datatools-manager,conveyal/datatools-manager
package com.conveyal.datatools.manager.models; import com.conveyal.datatools.editor.datastore.FeedTx; import com.conveyal.datatools.editor.datastore.GlobalTx; import com.conveyal.datatools.editor.datastore.VersionedDataStore; import com.conveyal.datatools.manager.DataManager; import com.conveyal.datatools.manager.auth.Auth0UserProfile; import com.conveyal.datatools.manager.jobs.NotifyUsersForSubscriptionJob; import com.conveyal.datatools.manager.persistence.DataStore; import com.conveyal.datatools.manager.utils.HashUtils; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonView; import com.google.common.eventbus.EventBus; import org.mapdb.Fun; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import spark.HaltException; import java.io.File; import java.io.IOException; import java.io.InvalidClassException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import java.util.stream.Collectors; import static spark.Spark.halt; /** * Created by demory on 3/22/16. */ @JsonIgnoreProperties(ignoreUnknown = true) public class FeedSource extends Model implements Cloneable { private static final long serialVersionUID = 1L; public static final Logger LOG = LoggerFactory.getLogger(FeedSource.class); private static DataStore<FeedSource> sourceStore = new DataStore<FeedSource>("feedsources"); /** * The collection of which this feed is a part */ //@JsonView(JsonViews.DataDump.class) public String projectId; public String[] regions = {"1"}; /** * Get the Project of which this feed is a part */ @JsonIgnore public Project getProject () { return Project.get(projectId); } @JsonIgnore public List<Region> getRegionList () { return Region.getAll().stream().filter(r -> Arrays.asList(regions).contains(r.id)).collect(Collectors.toList()); } public void setProject(Project proj) { this.projectId = proj.id; this.save(); proj.save(); } /** The name of this feed source, e.g. MTA New York City Subway */ public String name; /** Is this feed public, i.e. should it be listed on the * public feeds page for download? */ public boolean isPublic; /** Is this feed deployable? */ public boolean deployable; /** * How do we receive this feed? */ public FeedRetrievalMethod retrievalMethod; /** * When was this feed last fetched? */ public Date lastFetched; /** * When was this feed last updated? */ public transient Date lastUpdated; /** * From whence is this feed fetched? */ public URL url; /** * What is the GTFS Editor snapshot for this feed? * * This is the String-formatted snapshot ID, which is the base64-encoded ID and the version number. */ public String snapshotVersion; public String publishedVersionId; /** * Create a new feed. */ public FeedSource (String name) { super(); this.name = name; this.retrievalMethod = FeedRetrievalMethod.MANUALLY_UPLOADED; } /** * No-arg constructor to yield an uninitialized feed source, for dump/restore. * Should not be used in general code. */ public FeedSource () { this(null); } /** * Fetch the latest version of the feed. */ public FeedVersion fetch (EventBus eventBus, String fetchUser) { Map<String, Object> statusMap = new HashMap<>(); statusMap.put("message", "Downloading file"); statusMap.put("percentComplete", 20.0); statusMap.put("error", false); eventBus.post(statusMap); FeedVersion latest = getLatest(); // We create a new FeedVersion now, so that the fetched date is (milliseconds) before // fetch occurs. That way, in the highly unlikely event that a feed is updated while we're // fetching it, we will not miss a new feed. FeedVersion version = new FeedVersion(this); // build the URL from which to fetch URL url = this.url; LOG.info("Fetching from {}", url.toString()); // make the request, using the proper HTTP caching headers to prevent refetch, if applicable HttpURLConnection conn; try { conn = (HttpURLConnection) url.openConnection(); } catch (IOException e) { String message = String.format("Unable to open connection to %s; not fetching feed %s", url, this.name); LOG.error(message); statusMap.put("message", message); statusMap.put("percentComplete", 0.0); statusMap.put("error", true); eventBus.post(statusMap); halt(400, message); return null; } catch (ClassCastException e) { String message = String.format("Unable to open connection to %s; not fetching %s feed", url, this.name); LOG.error(message); statusMap.put("message", message); statusMap.put("percentComplete", 0.0); statusMap.put("error", true); eventBus.post(statusMap); halt(400, message); return null; } catch (NullPointerException e) { String message = String.format("Unable to open connection to %s; not fetching %s feed", url, this.name); LOG.error(message); statusMap.put("message", message); statusMap.put("percentComplete", 0.0); statusMap.put("error", true); eventBus.post(statusMap); halt(400, message); return null; } conn.setDefaultUseCaches(true); // lastFetched is set to null when the URL changes and when latest feed version is deleted if (latest != null && this.lastFetched != null) conn.setIfModifiedSince(Math.min(latest.updated.getTime(), this.lastFetched.getTime())); File newGtfsFile; try { conn.connect(); if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { String message = String.format("Feed %s has not been modified", this.name); LOG.info(message); statusMap.put("message", message); statusMap.put("percentComplete", 100.0); statusMap.put("error", true); eventBus.post(statusMap); halt(304, message); return null; } // TODO: redirects else if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { String message = String.format("Saving %s feed.", this.name); LOG.info(message); statusMap.put("message", message); statusMap.put("percentComplete", 75.0); statusMap.put("error", false); eventBus.post(statusMap); newGtfsFile = version.newGtfsFile(conn.getInputStream()); } else { String message = String.format("HTTP status %s retrieving %s feed", conn.getResponseMessage(), this.name); LOG.error(message); statusMap.put("message", message); statusMap.put("percentComplete", 100.0); statusMap.put("error", true); eventBus.post(statusMap); halt(400, message); return null; } } catch (IOException e) { String message = String.format("Unable to connect to %s; not fetching %s feed", url, this.name); LOG.error(message); statusMap.put("message", message); statusMap.put("percentComplete", 100.0); statusMap.put("error", true); eventBus.post(statusMap); e.printStackTrace(); halt(400, message); return null; } catch (HaltException e) { LOG.warn("Halt thrown", e); throw e; } // note that anything other than a new feed fetched successfully will have already returned from the function // version.hash(); version.hash = HashUtils.hashFile(newGtfsFile); if (latest != null && version.hash.equals(latest.hash)) { String message = String.format("Feed %s was fetched but has not changed; server operators should add If-Modified-Since support to avoid wasting bandwidth", this.name); LOG.warn(message); newGtfsFile.delete(); version.delete(); statusMap.put("message", message); statusMap.put("percentComplete", 100.0); statusMap.put("error", true); eventBus.post(statusMap); halt(304); return null; } else { version.userId = this.userId; this.lastFetched = version.updated; this.save(); NotifyUsersForSubscriptionJob notifyFeedJob = new NotifyUsersForSubscriptionJob("feed-updated", this.id, "New feed version created for " + this.name); Thread notifyThread = new Thread(notifyFeedJob); notifyThread.start(); String message = String.format("Fetch complete for %s", this.name); LOG.info(message); statusMap.put("message", message); statusMap.put("percentComplete", 100.0); statusMap.put("error", false); eventBus.post(statusMap); version.setUserById(fetchUser); version.fileTimestamp = conn.getLastModified(); return version; } } public int compareTo(FeedSource o) { return this.name.compareTo(o.name); } public String toString () { return "<FeedSource " + this.name + " (" + this.id + ")>"; } public void save () { save(true); } public void setName(String name){ this.name = name; this.save(); } public void save (boolean commit) { if (commit) sourceStore.save(this.id, this); else sourceStore.saveWithoutCommit(this.id, this); } /** * Get the latest version of this feed * @return the latest version of this feed */ @JsonIgnore public FeedVersion getLatest () { FeedVersion v = FeedVersion.versionStore.findFloor("version", new Fun.Tuple2(this.id, Fun.HI)); // the ID doesn't necessarily match, because it will fall back to the previous source in the store if there are no versions for this source if (v == null || !v.feedSourceId.equals(this.id)) return null; return v; } @JsonInclude(JsonInclude.Include.NON_NULL) @JsonView(JsonViews.UserInterface.class) public String getLatestVersionId () { FeedVersion latest = getLatest(); return latest != null ? latest.id : null; } /** * We can't pass the entire latest feed version back, because it contains references back to this feedsource, * so Jackson doesn't work. So instead we specifically expose the validation results and the latest update. * @return */ // TODO: use summarized feed source here. requires serious refactoring on client side. @JsonInclude(JsonInclude.Include.NON_NULL) @JsonView(JsonViews.UserInterface.class) public Date getLastUpdated() { FeedVersion latest = getLatest(); return latest != null ? latest.updated : null; } @JsonInclude(JsonInclude.Include.NON_NULL) @JsonView(JsonViews.UserInterface.class) public FeedValidationResultSummary getLatestValidation () { FeedVersion latest = getLatest(); FeedValidationResult result = latest != null ? latest.validationResult : null; return result != null ?new FeedValidationResultSummary(result) : null; } @JsonInclude(JsonInclude.Include.NON_NULL) @JsonView(JsonViews.UserInterface.class) public boolean getEditedSinceSnapshot() { // FeedTx tx; // try { // tx = VersionedDataStore.getFeedTx(id); // } catch (Exception e) { // // } // return tx.editedSinceSnapshot.get(); return false; } @JsonInclude(JsonInclude.Include.NON_NULL) @JsonView(JsonViews.UserInterface.class) public Map<String, Map<String, String>> getExternalProperties() { Map<String, Map<String, String>> resourceTable = new HashMap<>(); for(String resourceType : DataManager.feedResources.keySet()) { Map<String, String> propTable = new HashMap<>(); ExternalFeedSourceProperty.getAll().stream() .filter(prop -> prop.getFeedSourceId().equals(this.id)) .forEach(prop -> propTable.put(prop.name, prop.value)); resourceTable.put(resourceType, propTable); } return resourceTable; } public static FeedSource get(String id) { return sourceStore.getById(id); } public static Collection<FeedSource> getAll() { return sourceStore.getAll(); } /** * Get all of the feed versions for this source * @return collection of feed versions */ @JsonIgnore public Collection<FeedVersion> getFeedVersions() { // TODO Indices return FeedVersion.getAll().stream() .filter(v -> this.id.equals(v.feedSourceId)) .collect(Collectors.toCollection(ArrayList::new)); } @JsonView(JsonViews.UserInterface.class) public int getFeedVersionCount() { return getFeedVersions().size(); } @JsonView(JsonViews.UserInterface.class) public int getNoteCount() { return this.noteIds != null ? this.noteIds.size() : 0; } /** * Represents ways feeds can be retrieved */ public enum FeedRetrievalMethod { FETCHED_AUTOMATICALLY, // automatically retrieved over HTTP on some regular basis MANUALLY_UPLOADED, // manually uploaded by someone, perhaps the agency, or perhaps an internal user PRODUCED_IN_HOUSE // produced in-house in a GTFS Editor instance } public static void commit() { sourceStore.commit(); } /** * Delete this feed source and everything that it contains. */ public void delete() { getFeedVersions().forEach(FeedVersion::delete); // Delete editor feed mapdb // TODO: does the mapdb folder need to be deleted separately? GlobalTx gtx = VersionedDataStore.getGlobalTx(); if (!gtx.feeds.containsKey(id)) { gtx.rollback(); } else { gtx.feeds.remove(id); gtx.commit(); } ExternalFeedSourceProperty.getAll().stream() .filter(prop -> prop.getFeedSourceId().equals(this.id)) .forEach(ExternalFeedSourceProperty::delete); // TODO: add delete for osm extract and r5 network (maybe that goes with version) sourceStore.delete(this.id); } /*@JsonIgnore public AgencyBranding getAgencyBranding(String agencyId) { if(branding != null) { for (AgencyBranding agencyBranding : branding) { if (agencyBranding.agencyId.equals(agencyId)) return agencyBranding; } } return null; } @JsonIgnore public void addAgencyBranding(AgencyBranding agencyBranding) { if(branding == null) { branding = new ArrayList<>(); } branding.add(agencyBranding); }*/ public FeedSource clone () throws CloneNotSupportedException { return (FeedSource) super.clone(); } }
src/main/java/com/conveyal/datatools/manager/models/FeedSource.java
package com.conveyal.datatools.manager.models; import com.conveyal.datatools.editor.datastore.FeedTx; import com.conveyal.datatools.editor.datastore.GlobalTx; import com.conveyal.datatools.editor.datastore.VersionedDataStore; import com.conveyal.datatools.manager.DataManager; import com.conveyal.datatools.manager.auth.Auth0UserProfile; import com.conveyal.datatools.manager.jobs.NotifyUsersForSubscriptionJob; import com.conveyal.datatools.manager.persistence.DataStore; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonView; import com.google.common.eventbus.EventBus; import org.mapdb.Fun; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import spark.HaltException; import java.io.File; import java.io.IOException; import java.io.InvalidClassException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import java.util.stream.Collectors; import static spark.Spark.halt; /** * Created by demory on 3/22/16. */ @JsonIgnoreProperties(ignoreUnknown = true) public class FeedSource extends Model implements Cloneable { private static final long serialVersionUID = 1L; public static final Logger LOG = LoggerFactory.getLogger(FeedSource.class); private static DataStore<FeedSource> sourceStore = new DataStore<FeedSource>("feedsources"); /** * The collection of which this feed is a part */ //@JsonView(JsonViews.DataDump.class) public String projectId; public String[] regions = {"1"}; /** * Get the Project of which this feed is a part */ @JsonIgnore public Project getProject () { return Project.get(projectId); } @JsonIgnore public List<Region> getRegionList () { return Region.getAll().stream().filter(r -> Arrays.asList(regions).contains(r.id)).collect(Collectors.toList()); } public void setProject(Project proj) { this.projectId = proj.id; this.save(); proj.save(); } /** The name of this feed source, e.g. MTA New York City Subway */ public String name; /** Is this feed public, i.e. should it be listed on the * public feeds page for download? */ public boolean isPublic; /** Is this feed deployable? */ public boolean deployable; /** * How do we receive this feed? */ public FeedRetrievalMethod retrievalMethod; /** * When was this feed last fetched? */ public Date lastFetched; /** * When was this feed last updated? */ public transient Date lastUpdated; /** * From whence is this feed fetched? */ public URL url; /** * What is the GTFS Editor snapshot for this feed? * * This is the String-formatted snapshot ID, which is the base64-encoded ID and the version number. */ public String snapshotVersion; public String publishedVersionId; /** * Create a new feed. */ public FeedSource (String name) { super(); this.name = name; this.retrievalMethod = FeedRetrievalMethod.MANUALLY_UPLOADED; } /** * No-arg constructor to yield an uninitialized feed source, for dump/restore. * Should not be used in general code. */ public FeedSource () { this(null); } /** * Fetch the latest version of the feed. */ public FeedVersion fetch (EventBus eventBus, String fetchUser) { Map<String, Object> statusMap = new HashMap<>(); statusMap.put("message", "Downloading file"); statusMap.put("percentComplete", 20.0); statusMap.put("error", false); eventBus.post(statusMap); FeedVersion latest = getLatest(); // We create a new FeedVersion now, so that the fetched date is (milliseconds) before // fetch occurs. That way, in the highly unlikely event that a feed is updated while we're // fetching it, we will not miss a new feed. FeedVersion version = new FeedVersion(this); // build the URL from which to fetch URL url = this.url; LOG.info("Fetching from {}", url.toString()); // make the request, using the proper HTTP caching headers to prevent refetch, if applicable HttpURLConnection conn; try { conn = (HttpURLConnection) url.openConnection(); } catch (IOException e) { String message = String.format("Unable to open connection to %s; not fetching feed %s", url, this.name); LOG.error(message); statusMap.put("message", message); statusMap.put("percentComplete", 0.0); statusMap.put("error", true); eventBus.post(statusMap); halt(400, message); return null; } catch (ClassCastException e) { String message = String.format("Unable to open connection to %s; not fetching %s feed", url, this.name); LOG.error(message); statusMap.put("message", message); statusMap.put("percentComplete", 0.0); statusMap.put("error", true); eventBus.post(statusMap); halt(400, message); return null; } catch (NullPointerException e) { String message = String.format("Unable to open connection to %s; not fetching %s feed", url, this.name); LOG.error(message); statusMap.put("message", message); statusMap.put("percentComplete", 0.0); statusMap.put("error", true); eventBus.post(statusMap); halt(400, message); return null; } conn.setDefaultUseCaches(true); // lastFetched is set to null when the URL changes and when latest feed version is deleted if (latest != null && this.lastFetched != null) conn.setIfModifiedSince(Math.min(latest.updated.getTime(), this.lastFetched.getTime())); try { conn.connect(); if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { String message = String.format("Feed %s has not been modified", this.name); LOG.info(message); statusMap.put("message", message); statusMap.put("percentComplete", 100.0); statusMap.put("error", true); eventBus.post(statusMap); halt(304, message); return null; } // TODO: redirects else if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { String message = String.format("Saving %s feed.", this.name); LOG.info(message); statusMap.put("message", message); statusMap.put("percentComplete", 75.0); statusMap.put("error", false); eventBus.post(statusMap); version.newGtfsFile(conn.getInputStream()); } else { String message = String.format("HTTP status %s retrieving %s feed", conn.getResponseMessage(), this.name); LOG.error(message); statusMap.put("message", message); statusMap.put("percentComplete", 100.0); statusMap.put("error", true); eventBus.post(statusMap); halt(400, message); return null; } } catch (IOException e) { String message = String.format("Unable to connect to %s; not fetching %s feed", url, this.name); LOG.error(message); statusMap.put("message", message); statusMap.put("percentComplete", 100.0); statusMap.put("error", true); eventBus.post(statusMap); e.printStackTrace(); halt(400, message); return null; } catch (HaltException e) { LOG.warn("Halt thrown", e); throw e; } // note that anything other than a new feed fetched successfully will have already returned from the function version.hash(); if (latest != null && version.hash.equals(latest.hash)) { String message = String.format("Feed %s was fetched but has not changed; server operators should add If-Modified-Since support to avoid wasting bandwidth", this.name); LOG.warn(message); version.getGtfsFile().delete(); version.delete(); statusMap.put("message", message); statusMap.put("percentComplete", 100.0); statusMap.put("error", true); eventBus.post(statusMap); halt(304); return null; } else { version.userId = this.userId; this.lastFetched = version.updated; this.save(); NotifyUsersForSubscriptionJob notifyFeedJob = new NotifyUsersForSubscriptionJob("feed-updated", this.id, "New feed version created for " + this.name); Thread notifyThread = new Thread(notifyFeedJob); notifyThread.start(); String message = String.format("Fetch complete for %s", this.name); LOG.info(message); statusMap.put("message", message); statusMap.put("percentComplete", 100.0); statusMap.put("error", false); eventBus.post(statusMap); version.setUserById(fetchUser); version.fileTimestamp = conn.getLastModified(); return version; } } public int compareTo(FeedSource o) { return this.name.compareTo(o.name); } public String toString () { return "<FeedSource " + this.name + " (" + this.id + ")>"; } public void save () { save(true); } public void setName(String name){ this.name = name; this.save(); } public void save (boolean commit) { if (commit) sourceStore.save(this.id, this); else sourceStore.saveWithoutCommit(this.id, this); } /** * Get the latest version of this feed * @return the latest version of this feed */ @JsonIgnore public FeedVersion getLatest () { FeedVersion v = FeedVersion.versionStore.findFloor("version", new Fun.Tuple2(this.id, Fun.HI)); // the ID doesn't necessarily match, because it will fall back to the previous source in the store if there are no versions for this source if (v == null || !v.feedSourceId.equals(this.id)) return null; return v; } @JsonInclude(JsonInclude.Include.NON_NULL) @JsonView(JsonViews.UserInterface.class) public String getLatestVersionId () { FeedVersion latest = getLatest(); return latest != null ? latest.id : null; } /** * We can't pass the entire latest feed version back, because it contains references back to this feedsource, * so Jackson doesn't work. So instead we specifically expose the validation results and the latest update. * @return */ // TODO: use summarized feed source here. requires serious refactoring on client side. @JsonInclude(JsonInclude.Include.NON_NULL) @JsonView(JsonViews.UserInterface.class) public Date getLastUpdated() { FeedVersion latest = getLatest(); return latest != null ? latest.updated : null; } @JsonInclude(JsonInclude.Include.NON_NULL) @JsonView(JsonViews.UserInterface.class) public FeedValidationResultSummary getLatestValidation () { FeedVersion latest = getLatest(); FeedValidationResult result = latest != null ? latest.validationResult : null; return result != null ?new FeedValidationResultSummary(result) : null; } @JsonInclude(JsonInclude.Include.NON_NULL) @JsonView(JsonViews.UserInterface.class) public boolean getEditedSinceSnapshot() { // FeedTx tx; // try { // tx = VersionedDataStore.getFeedTx(id); // } catch (Exception e) { // // } // return tx.editedSinceSnapshot.get(); return false; } @JsonInclude(JsonInclude.Include.NON_NULL) @JsonView(JsonViews.UserInterface.class) public Map<String, Map<String, String>> getExternalProperties() { Map<String, Map<String, String>> resourceTable = new HashMap<>(); for(String resourceType : DataManager.feedResources.keySet()) { Map<String, String> propTable = new HashMap<>(); ExternalFeedSourceProperty.getAll().stream() .filter(prop -> prop.getFeedSourceId().equals(this.id)) .forEach(prop -> propTable.put(prop.name, prop.value)); resourceTable.put(resourceType, propTable); } return resourceTable; } public static FeedSource get(String id) { return sourceStore.getById(id); } public static Collection<FeedSource> getAll() { return sourceStore.getAll(); } /** * Get all of the feed versions for this source * @return collection of feed versions */ @JsonIgnore public Collection<FeedVersion> getFeedVersions() { // TODO Indices return FeedVersion.getAll().stream() .filter(v -> this.id.equals(v.feedSourceId)) .collect(Collectors.toCollection(ArrayList::new)); } @JsonView(JsonViews.UserInterface.class) public int getFeedVersionCount() { return getFeedVersions().size(); } @JsonView(JsonViews.UserInterface.class) public int getNoteCount() { return this.noteIds != null ? this.noteIds.size() : 0; } /** * Represents ways feeds can be retrieved */ public enum FeedRetrievalMethod { FETCHED_AUTOMATICALLY, // automatically retrieved over HTTP on some regular basis MANUALLY_UPLOADED, // manually uploaded by someone, perhaps the agency, or perhaps an internal user PRODUCED_IN_HOUSE // produced in-house in a GTFS Editor instance } public static void commit() { sourceStore.commit(); } /** * Delete this feed source and everything that it contains. */ public void delete() { getFeedVersions().forEach(FeedVersion::delete); // Delete editor feed mapdb // TODO: does the mapdb folder need to be deleted separately? GlobalTx gtx = VersionedDataStore.getGlobalTx(); if (!gtx.feeds.containsKey(id)) { gtx.rollback(); } else { gtx.feeds.remove(id); gtx.commit(); } ExternalFeedSourceProperty.getAll().stream() .filter(prop -> prop.getFeedSourceId().equals(this.id)) .forEach(ExternalFeedSourceProperty::delete); // TODO: add delete for osm extract and r5 network (maybe that goes with version) sourceStore.delete(this.id); } /*@JsonIgnore public AgencyBranding getAgencyBranding(String agencyId) { if(branding != null) { for (AgencyBranding agencyBranding : branding) { if (agencyBranding.agencyId.equals(agencyId)) return agencyBranding; } } return null; } @JsonIgnore public void addAgencyBranding(AgencyBranding agencyBranding) { if(branding == null) { branding = new ArrayList<>(); } branding.add(agencyBranding); }*/ public FeedSource clone () throws CloneNotSupportedException { return (FeedSource) super.clone(); } }
compute hash on and delete newGtfsFile in FeedSource.fetch
src/main/java/com/conveyal/datatools/manager/models/FeedSource.java
compute hash on and delete newGtfsFile in FeedSource.fetch
<ide><path>rc/main/java/com/conveyal/datatools/manager/models/FeedSource.java <ide> import com.conveyal.datatools.manager.auth.Auth0UserProfile; <ide> import com.conveyal.datatools.manager.jobs.NotifyUsersForSubscriptionJob; <ide> import com.conveyal.datatools.manager.persistence.DataStore; <add>import com.conveyal.datatools.manager.utils.HashUtils; <ide> import com.fasterxml.jackson.annotation.JsonIgnore; <ide> import com.fasterxml.jackson.annotation.JsonIgnoreProperties; <ide> import com.fasterxml.jackson.annotation.JsonInclude; <ide> // lastFetched is set to null when the URL changes and when latest feed version is deleted <ide> if (latest != null && this.lastFetched != null) <ide> conn.setIfModifiedSince(Math.min(latest.updated.getTime(), this.lastFetched.getTime())); <add> <add> File newGtfsFile; <ide> <ide> try { <ide> conn.connect(); <ide> statusMap.put("percentComplete", 75.0); <ide> statusMap.put("error", false); <ide> eventBus.post(statusMap); <del> version.newGtfsFile(conn.getInputStream()); <add> newGtfsFile = version.newGtfsFile(conn.getInputStream()); <ide> } <ide> <ide> else { <ide> } <ide> <ide> // note that anything other than a new feed fetched successfully will have already returned from the function <del> version.hash(); <add>// version.hash(); <add> version.hash = HashUtils.hashFile(newGtfsFile); <ide> <ide> <ide> if (latest != null && version.hash.equals(latest.hash)) { <ide> String message = String.format("Feed %s was fetched but has not changed; server operators should add If-Modified-Since support to avoid wasting bandwidth", this.name); <ide> LOG.warn(message); <del> version.getGtfsFile().delete(); <add> newGtfsFile.delete(); <ide> version.delete(); <ide> statusMap.put("message", message); <ide> statusMap.put("percentComplete", 100.0);
Java
apache-2.0
e67e58f6182319a923cd43461340bfc76149a31a
0
zimingd/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,zimingd/Synapse-Repository-Services
package org.sagebionetworks.table.cluster; import static org.sagebionetworks.repo.model.table.TableConstants.ROW_ID; import static org.sagebionetworks.repo.model.table.TableConstants.ROW_VERSION; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.sql.DataSource; import org.sagebionetworks.repo.model.dao.table.RowAndHeaderHandler; import org.sagebionetworks.repo.model.table.ColumnModel; import org.sagebionetworks.repo.model.table.ColumnType; import org.sagebionetworks.repo.model.table.Row; import org.sagebionetworks.repo.model.table.RowSet; import org.sagebionetworks.repo.model.table.SelectColumn; import org.sagebionetworks.repo.model.table.TableConstants; import org.sagebionetworks.table.cluster.SQLUtils.TableType; import org.sagebionetworks.table.cluster.utils.TableModelUtils; import org.sagebionetworks.util.ValidateArgument; import org.springframework.dao.InvalidDataAccessResourceUsageException; import org.springframework.jdbc.BadSqlGrammarException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowCallbackHandler; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.SingleColumnRowMapper; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import com.google.common.base.Function; import com.google.common.collect.Lists; public class TableIndexDAOImpl implements TableIndexDAO { private static final String SQL_SHOW_COLUMNS = "SHOW COLUMNS FROM "; private static final String FIELD = "Field"; private static final String TYPE = "Type"; private static final Pattern VARCHAR = Pattern.compile("varchar\\((\\d+)\\)"); private final DataSourceTransactionManager transactionManager; private final TransactionTemplate writeTransactionTemplate; private final TransactionTemplate readTransactionTemplate; private final JdbcTemplate template; /** * The IoC constructor. * * @param template * @param transactionManager */ public TableIndexDAOImpl(DataSource dataSource) { super(); this.transactionManager = new DataSourceTransactionManager(dataSource); // This will manage transactions for calls that need it. this.writeTransactionTemplate = createTransactionTemplate(this.transactionManager, false); this.readTransactionTemplate = createTransactionTemplate(this.transactionManager, true); this.template = new JdbcTemplate(dataSource); } private static TransactionTemplate createTransactionTemplate(DataSourceTransactionManager transactionManager, boolean readOnly) { // This will define how transaction are run for this instance. DefaultTransactionDefinition transactionDef; transactionDef = new DefaultTransactionDefinition(); transactionDef.setIsolationLevel(Connection.TRANSACTION_READ_COMMITTED); transactionDef.setReadOnly(readOnly); transactionDef.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); transactionDef.setName("TableIndexDAOImpl"); return new TransactionTemplate(transactionManager, transactionDef); } @Override public boolean createOrUpdateTable(List<ColumnModel> newSchema, String tableId) { // First determine if we have any columns for this table yet List<ColumnDefinition> oldColumnDefs = getCurrentTableColumns(tableId); List<String> oldColumns = oldColumnDefs == null ? null : Lists.transform(oldColumnDefs, new Function<ColumnDefinition, String>() { @Override public String apply(ColumnDefinition input) { return input.name; } }); // Build the SQL to create or update the table String dml = SQLUtils.creatOrAlterTableSQL(oldColumns, newSchema, tableId); // If there is nothing to apply then do nothing if (dml == null) return false; // Execute the DML try { template.update(dml); } catch (BadSqlGrammarException e) { if (e.getCause() != null && e.getCause().getMessage() != null && e.getCause().getMessage().startsWith("Row size too large")) { throw new InvalidDataAccessResourceUsageException( "Too much data per column. The maximum size for a row is about 65000 bytes", e.getCause()); } else { throw e; } } return true; } @Override public void addIndexes(String tableId) { List<ColumnDefinition> columns = getCurrentTableColumns(tableId); // do one by one and ignore any errors for adding a duplicate index List<String> indexes = Lists.newArrayList(); for (ColumnDefinition column : columns) { if (TableConstants.isReservedColumnName(column.name)) { continue; } SQLUtils.appendColumnIndexDefinition(column.name, column.maxSize, indexes); } for (String index : indexes) { try { template.update("alter table " + SQLUtils.getTableNameForId(tableId, TableType.INDEX) + " add " + index); } catch (BadSqlGrammarException e) { if (e.getCause() != null && e.getCause().getMessage() != null) { String message = e.getCause().getMessage(); if (message.startsWith("Duplicate key name") || message.startsWith("Too many keys")) { continue; } } throw e; } } } @Override public void removeIndexes(String tableId) { List<ColumnDefinition> columns = getCurrentTableColumns(tableId); // do one by one and ignore any errors for removing non-existant indexes for (ColumnDefinition column : columns) { if (TableConstants.isReservedColumnName(column.name)) { continue; } try { template.update("alter table " + SQLUtils.getTableNameForId(tableId, TableType.INDEX) + " drop index " + SQLUtils.getColumnIndexName(column.name)); } catch (BadSqlGrammarException e) { if (e.getCause() == null || e.getCause().getMessage() == null || !e.getCause().getMessage().contains("check that column/key exists")) { throw e; } } } } @Override public void addIndex(String tableId, ColumnModel columnModel) { // do one by one and ignore any errors for adding a duplicate index String column = SQLUtils.getColumnNameForId(columnModel.getId()); if (TableConstants.isReservedColumnName(column)) { return; } List<String> indexes = Lists.newArrayList(); SQLUtils.appendColumnIndexDefinition(column, columnModel.getMaximumSize(), indexes); for (String index : indexes) { try { template.update("alter table " + SQLUtils.getTableNameForId(tableId, TableType.INDEX) + " add " + index); } catch (BadSqlGrammarException e) { if (e.getCause() == null || e.getCause().getMessage() == null || !e.getCause().getMessage().startsWith("Duplicate key name")) { throw e; } } } } @Override public boolean deleteTable(String tableId) { String dropTableDML = SQLUtils.dropTableSQL(tableId, SQLUtils.TableType.INDEX); try { template.update(dropTableDML); return true; } catch (BadSqlGrammarException e) { // This is thrown when the table does not exist return false; } } @Override public List<ColumnDefinition> getCurrentTableColumns(String tableId) { String tableName = SQLUtils.getTableNameForId(tableId, SQLUtils.TableType.INDEX); // Bind variables do not seem to work here try { return template.query(SQL_SHOW_COLUMNS + tableName, new RowMapper<ColumnDefinition>() { @Override public ColumnDefinition mapRow(ResultSet rs, int rowNum) throws SQLException { ColumnDefinition columnDefinition = new ColumnDefinition(); columnDefinition.name = rs.getString(FIELD); columnDefinition.maxSize = null; String type = rs.getString(TYPE); Matcher m = VARCHAR.matcher(type); if (m.matches()) { columnDefinition.columnType = ColumnType.STRING; columnDefinition.maxSize = Long.parseLong(m.group(1)); } return columnDefinition; } }); } catch (BadSqlGrammarException e) { // Spring throws this when the table does not return null; } } @Override public void createOrUpdateOrDeleteRows(final RowSet rowset, final List<ColumnModel> schema) { if (rowset == null) throw new IllegalArgumentException("Rowset cannot be null"); if (schema == null) throw new IllegalArgumentException("Current schema cannot be null"); // Execute this within a transaction this.writeTransactionTemplate.execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { // Within a transaction // Build the SQL String createOrUpdateSql = SQLUtils.buildCreateOrUpdateRowSQL(schema, rowset.getTableId()); String deleteSql = SQLUtils.buildDeleteSQL(schema, rowset.getTableId()); SqlParameterSource[] batchUpdateOrCreateBinding = SQLUtils .bindParametersForCreateOrUpdate(rowset, schema); SqlParameterSource batchDeleteBinding = SQLUtils .bindParameterForDelete(rowset, schema); // We need a named template for this case. NamedParameterJdbcTemplate namedTemplate = new NamedParameterJdbcTemplate(template); if (batchUpdateOrCreateBinding.length > 0) { namedTemplate.batchUpdate(createOrUpdateSql, batchUpdateOrCreateBinding); } if (batchDeleteBinding != null) { namedTemplate.update(deleteSql, batchDeleteBinding); } return null; } }); } @Override public Long getRowCountForTable(String tableId) { String sql = SQLUtils.getCountSQL(tableId); try { return template.queryForObject(sql,new SingleColumnRowMapper<Long>()); } catch (BadSqlGrammarException e) { // Spring throws this when the table does not return null; } } @Override public Long getMaxCurrentCompleteVersionForTable(String tableId) { String sql = SQLUtils.getStatusMaxVersionSQL(tableId); try { return template.queryForObject(sql, new SingleColumnRowMapper<Long>()); } catch (BadSqlGrammarException e) { // Spring throws this when the table does not exist return -1L; } } @Override public void setMaxCurrentCompleteVersionForTable(String tableId, Long version) { String createStatusTableSql = SQLUtils.createTableSQL(tableId, SQLUtils.TableType.STATUS); template.update(createStatusTableSql); String createOrUpdateStatusSql = SQLUtils.buildCreateOrUpdateStatusSQL(tableId); template.update(createOrUpdateStatusSql, version); } @Override public void deleteStatusTable(String tableId) { String dropStatusTableDML = SQLUtils.dropTableSQL(tableId, SQLUtils.TableType.STATUS); try { template.update(dropStatusTableDML); } catch (BadSqlGrammarException e) { // This is thrown when the table does not exist } } @Override public JdbcTemplate getConnection() { return template; } @Override public RowSet query(final SqlQuery query) { if (query == null) throw new IllegalArgumentException("SqlQuery cannot be null"); final List<Row> rows = new LinkedList<Row>(); final RowSet rowSet = new RowSet(); rowSet.setRows(rows); rowSet.setHeaders(query.getSelectColumnModels().getSelectColumns()); // Stream over the results and save the results in a a list queryAsStream(query, new RowAndHeaderHandler() { @Override public void writeHeader() { // no-op } @Override public void nextRow(Row row) { rows.add(row); } @Override public void setEtag(String etag) { rowSet.setEtag(etag); } }); rowSet.setTableId(query.getTableId()); return rowSet; } @Override public boolean queryAsStream(final SqlQuery query, final RowAndHeaderHandler handler) { ValidateArgument.required(query, "Query"); // We use spring to create create the prepared statement NamedParameterJdbcTemplate namedTemplate = new NamedParameterJdbcTemplate(this.template); handler.writeHeader(); namedTemplate.query(query.getOutputSQL(), new MapSqlParameterSource(query.getParameters()), new RowCallbackHandler() { @Override public void processRow(ResultSet rs) throws SQLException { ResultSetMetaData metadata = rs.getMetaData(); Row row = new Row(); List<String> values = new LinkedList<String>(); row.setValues(values); // ROW_ID and ROW_VERSION are always appended to the list of columns int selectModelIndex = 0; int columnCount = metadata.getColumnCount(); List<SelectColumn> selectColumns = query.getSelectColumnModels().getSelectColumns(); // result sets use 1-base indexing for (int i = 1; i <= columnCount; i++) { String name = metadata.getColumnName(i); if (ROW_ID.equals(name)) { row.setRowId(rs.getLong(i)); } else if (ROW_VERSION.equals(name)) { row.setVersionNumber(rs.getLong(i)); } else { SelectColumn selectColumn = selectColumns.get(selectModelIndex++); String value = rs.getString(i); value = TableModelUtils.translateRowValueFromQuery(value, selectColumn); values.add(value); } } if (selectModelIndex != selectColumns.size()) { throw new IllegalStateException("The number of columns returned (" + selectModelIndex + ") is not the same as the number expected (" + selectColumns.size() + ")"); } handler.nextRow(row); } }); return true; } @Override public <T> T executeInReadTransaction(TransactionCallback<T> callable) { return readTransactionTemplate.execute(callable); } }
lib/lib-table-cluster/src/main/java/org/sagebionetworks/table/cluster/TableIndexDAOImpl.java
package org.sagebionetworks.table.cluster; import static org.sagebionetworks.repo.model.table.TableConstants.ROW_ID; import static org.sagebionetworks.repo.model.table.TableConstants.ROW_VERSION; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.sql.DataSource; import org.sagebionetworks.repo.model.dao.table.RowAndHeaderHandler; import org.sagebionetworks.repo.model.table.ColumnModel; import org.sagebionetworks.repo.model.table.ColumnType; import org.sagebionetworks.repo.model.table.Row; import org.sagebionetworks.repo.model.table.RowSet; import org.sagebionetworks.repo.model.table.SelectColumn; import org.sagebionetworks.repo.model.table.TableConstants; import org.sagebionetworks.table.cluster.SQLUtils.TableType; import org.sagebionetworks.table.cluster.utils.TableModelUtils; import org.sagebionetworks.util.ValidateArgument; import org.springframework.dao.InvalidDataAccessResourceUsageException; import org.springframework.jdbc.BadSqlGrammarException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowCallbackHandler; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.SingleColumnRowMapper; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import com.google.common.base.Function; import com.google.common.collect.Lists; public class TableIndexDAOImpl implements TableIndexDAO { private static final String SQL_SHOW_COLUMNS = "SHOW COLUMNS FROM "; private static final String FIELD = "Field"; private static final String TYPE = "Type"; private static final Pattern VARCHAR = Pattern.compile("varchar\\((\\d+)\\)"); private final DataSourceTransactionManager transactionManager; private final TransactionTemplate writeTransactionTemplate; private final TransactionTemplate readTransactionTemplate; private final JdbcTemplate template; /** * The IoC constructor. * * @param template * @param transactionManager */ public TableIndexDAOImpl(DataSource dataSource) { super(); this.transactionManager = new DataSourceTransactionManager(dataSource); // This will manage transactions for calls that need it. this.writeTransactionTemplate = createTransactionTemplate(this.transactionManager, false); this.readTransactionTemplate = createTransactionTemplate(this.transactionManager, true); this.template = new JdbcTemplate(dataSource); } private static TransactionTemplate createTransactionTemplate(DataSourceTransactionManager transactionManager, boolean readOnly) { // This will define how transaction are run for this instance. DefaultTransactionDefinition transactionDef; transactionDef = new DefaultTransactionDefinition(); transactionDef.setIsolationLevel(Connection.TRANSACTION_READ_COMMITTED); transactionDef.setReadOnly(readOnly); transactionDef.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); transactionDef.setName("TableIndexDAOImpl"); return new TransactionTemplate(transactionManager, transactionDef); } @Override public boolean createOrUpdateTable(List<ColumnModel> newSchema, String tableId) { // First determine if we have any columns for this table yet List<ColumnDefinition> oldColumnDefs = getCurrentTableColumns(tableId); List<String> oldColumns = oldColumnDefs == null ? null : Lists.transform(oldColumnDefs, new Function<ColumnDefinition, String>() { @Override public String apply(ColumnDefinition input) { return input.name; } }); // Build the SQL to create or update the table String dml = SQLUtils.creatOrAlterTableSQL(oldColumns, newSchema, tableId); // If there is nothing to apply then do nothing if (dml == null) return false; // Execute the DML try { template.update(dml); } catch (BadSqlGrammarException e) { if (e.getCause() != null && e.getCause().getMessage() != null && e.getCause().getMessage().startsWith("Row size too large")) { throw new InvalidDataAccessResourceUsageException( "Too much data per column. The maximum size for a row is about 65000 bytes", e.getCause()); } else { throw e; } } return true; } @Override public void addIndexes(String tableId) { List<ColumnDefinition> columns = getCurrentTableColumns(tableId); // do one by one and ignore any errors for adding a duplicate index List<String> indexes = Lists.newArrayList(); for (ColumnDefinition column : columns) { if (TableConstants.isReservedColumnName(column.name)) { continue; } SQLUtils.appendColumnIndexDefinition(column.name, column.maxSize, indexes); } for (String index : indexes) { try { template.update("alter table " + SQLUtils.getTableNameForId(tableId, TableType.INDEX) + " add " + index); } catch (BadSqlGrammarException e) { if (e.getCause() == null || e.getCause().getMessage() == null || !e.getCause().getMessage().startsWith("Duplicate key name")) { throw e; } } } } @Override public void removeIndexes(String tableId) { List<ColumnDefinition> columns = getCurrentTableColumns(tableId); // do one by one and ignore any errors for removing non-existant indexes for (ColumnDefinition column : columns) { if (TableConstants.isReservedColumnName(column.name)) { continue; } try { template.update("alter table " + SQLUtils.getTableNameForId(tableId, TableType.INDEX) + " drop index " + SQLUtils.getColumnIndexName(column.name)); } catch (BadSqlGrammarException e) { if (e.getCause() == null || e.getCause().getMessage() == null || !e.getCause().getMessage().contains("check that column/key exists")) { throw e; } } } } @Override public void addIndex(String tableId, ColumnModel columnModel) { // do one by one and ignore any errors for adding a duplicate index String column = SQLUtils.getColumnNameForId(columnModel.getId()); if (TableConstants.isReservedColumnName(column)) { return; } List<String> indexes = Lists.newArrayList(); SQLUtils.appendColumnIndexDefinition(column, columnModel.getMaximumSize(), indexes); for (String index : indexes) { try { template.update("alter table " + SQLUtils.getTableNameForId(tableId, TableType.INDEX) + " add " + index); } catch (BadSqlGrammarException e) { if (e.getCause() == null || e.getCause().getMessage() == null || !e.getCause().getMessage().startsWith("Duplicate key name")) { throw e; } } } } @Override public boolean deleteTable(String tableId) { String dropTableDML = SQLUtils.dropTableSQL(tableId, SQLUtils.TableType.INDEX); try { template.update(dropTableDML); return true; } catch (BadSqlGrammarException e) { // This is thrown when the table does not exist return false; } } @Override public List<ColumnDefinition> getCurrentTableColumns(String tableId) { String tableName = SQLUtils.getTableNameForId(tableId, SQLUtils.TableType.INDEX); // Bind variables do not seem to work here try { return template.query(SQL_SHOW_COLUMNS + tableName, new RowMapper<ColumnDefinition>() { @Override public ColumnDefinition mapRow(ResultSet rs, int rowNum) throws SQLException { ColumnDefinition columnDefinition = new ColumnDefinition(); columnDefinition.name = rs.getString(FIELD); columnDefinition.maxSize = null; String type = rs.getString(TYPE); Matcher m = VARCHAR.matcher(type); if (m.matches()) { columnDefinition.columnType = ColumnType.STRING; columnDefinition.maxSize = Long.parseLong(m.group(1)); } return columnDefinition; } }); } catch (BadSqlGrammarException e) { // Spring throws this when the table does not return null; } } @Override public void createOrUpdateOrDeleteRows(final RowSet rowset, final List<ColumnModel> schema) { if (rowset == null) throw new IllegalArgumentException("Rowset cannot be null"); if (schema == null) throw new IllegalArgumentException("Current schema cannot be null"); // Execute this within a transaction this.writeTransactionTemplate.execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { // Within a transaction // Build the SQL String createOrUpdateSql = SQLUtils.buildCreateOrUpdateRowSQL(schema, rowset.getTableId()); String deleteSql = SQLUtils.buildDeleteSQL(schema, rowset.getTableId()); SqlParameterSource[] batchUpdateOrCreateBinding = SQLUtils .bindParametersForCreateOrUpdate(rowset, schema); SqlParameterSource batchDeleteBinding = SQLUtils .bindParameterForDelete(rowset, schema); // We need a named template for this case. NamedParameterJdbcTemplate namedTemplate = new NamedParameterJdbcTemplate(template); if (batchUpdateOrCreateBinding.length > 0) { namedTemplate.batchUpdate(createOrUpdateSql, batchUpdateOrCreateBinding); } if (batchDeleteBinding != null) { namedTemplate.update(deleteSql, batchDeleteBinding); } return null; } }); } @Override public Long getRowCountForTable(String tableId) { String sql = SQLUtils.getCountSQL(tableId); try { return template.queryForObject(sql,new SingleColumnRowMapper<Long>()); } catch (BadSqlGrammarException e) { // Spring throws this when the table does not return null; } } @Override public Long getMaxCurrentCompleteVersionForTable(String tableId) { String sql = SQLUtils.getStatusMaxVersionSQL(tableId); try { return template.queryForObject(sql, new SingleColumnRowMapper<Long>()); } catch (BadSqlGrammarException e) { // Spring throws this when the table does not exist return -1L; } } @Override public void setMaxCurrentCompleteVersionForTable(String tableId, Long version) { String createStatusTableSql = SQLUtils.createTableSQL(tableId, SQLUtils.TableType.STATUS); template.update(createStatusTableSql); String createOrUpdateStatusSql = SQLUtils.buildCreateOrUpdateStatusSQL(tableId); template.update(createOrUpdateStatusSql, version); } @Override public void deleteStatusTable(String tableId) { String dropStatusTableDML = SQLUtils.dropTableSQL(tableId, SQLUtils.TableType.STATUS); try { template.update(dropStatusTableDML); } catch (BadSqlGrammarException e) { // This is thrown when the table does not exist } } @Override public JdbcTemplate getConnection() { return template; } @Override public RowSet query(final SqlQuery query) { if (query == null) throw new IllegalArgumentException("SqlQuery cannot be null"); final List<Row> rows = new LinkedList<Row>(); final RowSet rowSet = new RowSet(); rowSet.setRows(rows); rowSet.setHeaders(query.getSelectColumnModels().getSelectColumns()); // Stream over the results and save the results in a a list queryAsStream(query, new RowAndHeaderHandler() { @Override public void writeHeader() { // no-op } @Override public void nextRow(Row row) { rows.add(row); } @Override public void setEtag(String etag) { rowSet.setEtag(etag); } }); rowSet.setTableId(query.getTableId()); return rowSet; } @Override public boolean queryAsStream(final SqlQuery query, final RowAndHeaderHandler handler) { ValidateArgument.required(query, "Query"); // We use spring to create create the prepared statement NamedParameterJdbcTemplate namedTemplate = new NamedParameterJdbcTemplate(this.template); handler.writeHeader(); namedTemplate.query(query.getOutputSQL(), new MapSqlParameterSource(query.getParameters()), new RowCallbackHandler() { @Override public void processRow(ResultSet rs) throws SQLException { ResultSetMetaData metadata = rs.getMetaData(); Row row = new Row(); List<String> values = new LinkedList<String>(); row.setValues(values); // ROW_ID and ROW_VERSION are always appended to the list of columns int selectModelIndex = 0; int columnCount = metadata.getColumnCount(); List<SelectColumn> selectColumns = query.getSelectColumnModels().getSelectColumns(); // result sets use 1-base indexing for (int i = 1; i <= columnCount; i++) { String name = metadata.getColumnName(i); if (ROW_ID.equals(name)) { row.setRowId(rs.getLong(i)); } else if (ROW_VERSION.equals(name)) { row.setVersionNumber(rs.getLong(i)); } else { SelectColumn selectColumn = selectColumns.get(selectModelIndex++); String value = rs.getString(i); value = TableModelUtils.translateRowValueFromQuery(value, selectColumn); values.add(value); } } if (selectModelIndex != selectColumns.size()) { throw new IllegalStateException("The number of columns returned (" + selectModelIndex + ") is not the same as the number expected (" + selectColumns.size() + ")"); } handler.nextRow(row); } }); return true; } @Override public <T> T executeInReadTransaction(TransactionCallback<T> callable) { return readTransactionTemplate.execute(callable); } }
handle more than 64 columns for admin api
lib/lib-table-cluster/src/main/java/org/sagebionetworks/table/cluster/TableIndexDAOImpl.java
handle more than 64 columns for admin api
<ide><path>ib/lib-table-cluster/src/main/java/org/sagebionetworks/table/cluster/TableIndexDAOImpl.java <ide> } <ide> for (String index : indexes) { <ide> try { <del> template.update("alter table " + SQLUtils.getTableNameForId(tableId, TableType.INDEX) + " add " <del> + index); <add> template.update("alter table " + SQLUtils.getTableNameForId(tableId, TableType.INDEX) + " add " + index); <ide> } catch (BadSqlGrammarException e) { <del> if (e.getCause() == null || e.getCause().getMessage() == null || !e.getCause().getMessage().startsWith("Duplicate key name")) { <del> throw e; <del> } <add> if (e.getCause() != null && e.getCause().getMessage() != null) { <add> String message = e.getCause().getMessage(); <add> if (message.startsWith("Duplicate key name") || message.startsWith("Too many keys")) { <add> continue; <add> } <add> } <add> throw e; <ide> } <ide> } <ide> }
JavaScript
mit
57819540edf7fac7f80975c1910865692479cf2e
0
jordanco/drafter-frontend,jordanco/drafter-frontend,jordanco/drafter-frontend
import React, { Component } from 'react'; import { connect } from 'react-redux'; //import EmailReply from '../../components/email/reply'; import { sendEmail, changeEmailContent } from '../../actions/email/reply'; class EmailReply extends Component { onEmailChange(event) { this.props.onEmailChange(event.target.value); } onEmailSend(event){ this.props.onSendClick(this.props.emailMsg.text, this.props.emails.activeEmail); } // componentDidMount(){ // this.props.emailMsg.showLoader = false; // } // componentDidUpdate(){ // console.log("This update called props: ", this.props); // } render() { return ( <div className="editor"> <div className="typebox"> <div className={ this.props.emailMsg.showLoader? '' : 'hidden-elements' }> <div>Loading...</div> </div> <div className="w-form"> <form data-name="Email Form" id="email-form" name="email-form"> <textarea className="textatea w-input" onChange={ this.onEmailChange.bind(this) } value={ this.props.emailMsg.text } data-ix="show-suggestions" id="field" maxlength="5000" name="field" placeholder="Type response here" ></textarea> </form> <div className={ this.props.emailMsg.showSuccessMsg? '' : 'w-form-done' }> <div>Thank you! Your submission has been received!</div> </div> <div className={ this.props.emailMsg.showErrorMsg? '' : 'w-form-fail' }> <div>Oops! Something went wrong while submitting the form</div> </div> </div> </div> <div className="editor-buttons"> <div className="connect-button offset hidden-elements"><img className="li-connect-image" src="https://d3e54v103j8qbb.cloudfront.net/img/image-placeholder.svg"/> <div>Templates</div> </div> <div className="connect-button offset-2 hidden-elements"><img className="li-connect-image" src="https://d3e54v103j8qbb.cloudfront.net/img/image-placeholder.svg"/> <div>Open in Gmail</div> </div> <div className="connect-button hidden-elements"><img className="li-connect-image" src="https://d3e54v103j8qbb.cloudfront.net/img/image-placeholder.svg"/> <div>Other</div> </div> <div className="connect-button hidden-elements"><img className="li-connect-image" src="https://d3e54v103j8qbb.cloudfront.net/img/image-placeholder.svg"/> <div>Snooze</div> </div> <div className="connect-button" onClick={ this.onEmailSend.bind(this) }> <img className="li-connect-image" src="https://d3e54v103j8qbb.cloudfront.net/img/image-placeholder.svg"/> <div>Send</div> </div> </div> </div> ); } } const mapStateToProps = (state) => { console.log("Map state to props: ", state); return { emailMsg: state.emailMsg, emails: state.emails, currentMsgs: [] } } const mapDispatchToProps = (dispatch) => { return { onTemplatesClick: () => {}, onOpenGmailClick: () => {}, onOtherClick: () => {}, onSnoozeClick: () => {}, onSendClick: (text, activeEmail) => { dispatch(sendEmail(text, activeEmail)) }, onEmailChange: (text) => { dispatch(changeEmailContent(text)) } } } export default connect( mapStateToProps, mapDispatchToProps )(EmailReply)
src/app/containers/email/functionalities.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; //import EmailReply from '../../components/email/reply'; import { sendEmail, changeEmailContent } from '../../actions/email/reply'; class EmailReply extends Component { onEmailChange(event) { this.props.onEmailChange(event.target.value); } onEmailSend(event){ this.props.onSendClick(this.props.emailMsg.text, this.props.emails.activeEmail); } // componentDidMount(){ // this.props.emailMsg.showLoader = false; // } componentDidUpdate(){ console.log("This update called props: ", this.props); } render() { return ( <div className="editor"> <div className="typebox"> <div className={ this.props.emailMsg.showLoader? '' : 'hidden-elements' }> <div>Loading...</div> </div> <div className="w-form"> <form data-name="Email Form" id="email-form" name="email-form"> <textarea className="textatea w-input" onChange={ this.onEmailChange.bind(this) } value={ this.props.emailMsg.text } data-ix="show-suggestions" id="field" maxlength="5000" name="field" placeholder="Type response here" ></textarea> </form> <div className={ this.props.emailMsg.showSuccessMsg? '' : 'w-form-done' }> <div>Thank you! Your submission has been received!</div> </div> <div className={ this.props.emailMsg.showErrorMsg? '' : 'w-form-fail' }> <div>Oops! Something went wrong while submitting the form</div> </div> </div> </div> <div className="editor-buttons"> <div className="connect-button offset hidden-elements"><img className="li-connect-image" src="https://d3e54v103j8qbb.cloudfront.net/img/image-placeholder.svg"/> <div>Templates</div> </div> <div className="connect-button offset-2 hidden-elements"><img className="li-connect-image" src="https://d3e54v103j8qbb.cloudfront.net/img/image-placeholder.svg"/> <div>Open in Gmail</div> </div> <div className="connect-button hidden-elements"><img className="li-connect-image" src="https://d3e54v103j8qbb.cloudfront.net/img/image-placeholder.svg"/> <div>Other</div> </div> <div className="connect-button hidden-elements"><img className="li-connect-image" src="https://d3e54v103j8qbb.cloudfront.net/img/image-placeholder.svg"/> <div>Snooze</div> </div> <div className="connect-button" onClick={ this.onEmailSend.bind(this) }> <img className="li-connect-image" src="https://d3e54v103j8qbb.cloudfront.net/img/image-placeholder.svg"/> <div>Send</div> </div> </div> </div> ); } } const mapStateToProps = (state) => { return { emailMsg: state.emailMsg, emails: state.emails, currentMsgs: [] } } const mapDispatchToProps = (dispatch) => { return { onTemplatesClick: () => {}, onOpenGmailClick: () => {}, onOtherClick: () => {}, onSnoozeClick: () => {}, onSendClick: (text, activeEmail) => { dispatch(sendEmail(text, activeEmail)) }, onEmailChange: (text) => { dispatch(changeEmailContent(text)) } } } export default connect( mapStateToProps, mapDispatchToProps )(EmailReply)
send im
src/app/containers/email/functionalities.js
send im
<ide><path>rc/app/containers/email/functionalities.js <ide> // this.props.emailMsg.showLoader = false; <ide> // } <ide> <del> componentDidUpdate(){ <del> console.log("This update called props: ", this.props); <del> } <add> // componentDidUpdate(){ <add> // console.log("This update called props: ", this.props); <add> // } <ide> <ide> render() { <ide> return ( <ide> <ide> <ide> const mapStateToProps = (state) => { <add> console.log("Map state to props: ", state); <ide> return { <ide> emailMsg: state.emailMsg, <ide> emails: state.emails,
Java
apache-2.0
78c56fcdd73a73b3b6b1d0476e83721549b526d9
0
caskdata/cdap,caskdata/cdap,caskdata/cdap,caskdata/cdap,caskdata/cdap,caskdata/cdap
/* * Copyright © 2015-2016 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package co.cask.cdap.internal.app.services; import co.cask.cdap.api.ProgramSpecification; import co.cask.cdap.api.app.ApplicationSpecification; import co.cask.cdap.api.flow.FlowSpecification; import co.cask.cdap.app.program.Program; import co.cask.cdap.app.program.Programs; import co.cask.cdap.app.runtime.ProgramController; import co.cask.cdap.app.runtime.ProgramRuntimeService; import co.cask.cdap.app.runtime.ProgramRuntimeService.RuntimeInfo; import co.cask.cdap.app.store.Store; import co.cask.cdap.common.ApplicationNotFoundException; import co.cask.cdap.common.BadRequestException; import co.cask.cdap.common.ConflictException; import co.cask.cdap.common.NotFoundException; import co.cask.cdap.common.ProgramNotFoundException; import co.cask.cdap.common.app.RunIds; import co.cask.cdap.common.conf.CConfiguration; import co.cask.cdap.common.conf.Constants; import co.cask.cdap.common.io.CaseInsensitiveEnumTypeAdapterFactory; import co.cask.cdap.common.namespace.NamespacedLocationFactory; import co.cask.cdap.config.PreferencesStore; import co.cask.cdap.internal.app.ApplicationSpecificationAdapter; import co.cask.cdap.internal.app.runtime.AbstractListener; import co.cask.cdap.internal.app.runtime.BasicArguments; import co.cask.cdap.internal.app.runtime.ProgramOptionConstants; import co.cask.cdap.internal.app.runtime.SimpleProgramOptions; import co.cask.cdap.internal.app.store.RunRecordMeta; import co.cask.cdap.proto.NamespaceMeta; import co.cask.cdap.proto.ProgramRunStatus; import co.cask.cdap.proto.ProgramStatus; import co.cask.cdap.proto.ProgramType; import co.cask.cdap.proto.RunRecord; import co.cask.cdap.proto.id.Ids; import co.cask.cdap.proto.id.NamespaceId; import co.cask.cdap.proto.id.ProgramId; import co.cask.cdap.proto.id.ProgramRunId; import co.cask.cdap.proto.security.Action; import co.cask.cdap.security.authorization.AuthorizerInstantiatorService; import co.cask.cdap.security.spi.authentication.SecurityRequestContext; import co.cask.cdap.security.spi.authorization.UnauthorizedException; import co.cask.cdap.store.NamespaceStore; import com.google.common.base.Predicate; import com.google.common.base.Throwables; import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import com.google.common.util.concurrent.AbstractIdleService; import com.google.common.util.concurrent.ListenableFuture; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.inject.Inject; import org.apache.twill.api.RunId; import org.apache.twill.common.Threads; import org.apache.twill.filesystem.Location; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Collection; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; /** * Service that manages lifecycle of Programs. */ public class ProgramLifecycleService extends AbstractIdleService { private static final Logger LOG = LoggerFactory.getLogger(ProgramLifecycleService.class); private static final Gson GSON = ApplicationSpecificationAdapter .addTypeAdapters(new GsonBuilder()) .registerTypeAdapterFactory(new CaseInsensitiveEnumTypeAdapterFactory()) .create(); private final ScheduledExecutorService scheduledExecutorService; private final Store store; private final ProgramRuntimeService runtimeService; private final CConfiguration cConf; private final NamespaceStore nsStore; private final PropertiesResolver propertiesResolver; private final NamespacedLocationFactory namespacedLocationFactory; private final String appFabricDir; private final PreferencesStore preferencesStore; private final AuthorizerInstantiatorService authorizerInstantiatorService; @Inject ProgramLifecycleService(Store store, NamespaceStore nsStore, ProgramRuntimeService runtimeService, CConfiguration cConf, PropertiesResolver propertiesResolver, NamespacedLocationFactory namespacedLocationFactory, PreferencesStore preferencesStore, AuthorizerInstantiatorService authorizerInstantiatorService) { this.store = store; this.nsStore = nsStore; this.runtimeService = runtimeService; this.propertiesResolver = propertiesResolver; this.namespacedLocationFactory = namespacedLocationFactory; this.appFabricDir = cConf.get(Constants.AppFabric.OUTPUT_DIR); this.scheduledExecutorService = Executors.newScheduledThreadPool(1); this.cConf = cConf; this.preferencesStore = preferencesStore; this.authorizerInstantiatorService = authorizerInstantiatorService; } @Override protected void startUp() throws Exception { LOG.info("Starting ProgramLifecycleService"); long interval = cConf.getLong(Constants.AppFabric.PROGRAM_RUNID_CORRECTOR_INTERVAL_SECONDS); if (interval <= 0) { LOG.debug("Invalid run id corrector interval {}. Setting it to 180 seconds.", interval); interval = 180L; } scheduledExecutorService.scheduleWithFixedDelay(new RunRecordsCorrectorRunnable(this), 2L, interval, TimeUnit.SECONDS); } @Override protected void shutDown() throws Exception { LOG.info("Shutting down ProgramLifecycleService"); scheduledExecutorService.shutdown(); try { if (!scheduledExecutorService.awaitTermination(5, TimeUnit.SECONDS)) { scheduledExecutorService.shutdownNow(); } } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } /** * Returns the program status. * @param programId the id of the program for which the status call is made * @return the status of the program * @throws NotFoundException if the application to which this program belongs was not found */ public ProgramStatus getProgramStatus(ProgramId programId) throws NotFoundException { // check that app exists ApplicationSpecification appSpec = store.getApplication(programId.toId().getApplication()); if (appSpec == null) { throw new NotFoundException(Ids.namespace(programId.getNamespace()).app(programId.getApplication()).toId()); } ProgramRuntimeService.RuntimeInfo runtimeInfo = findRuntimeInfo(programId); if (runtimeInfo == null) { if (programId.getType() != ProgramType.WEBAPP) { //Runtime info not found. Check to see if the program exists. ProgramSpecification spec = getProgramSpecification(programId); if (spec == null) { // program doesn't exist throw new NotFoundException(programId); } if ((programId.getType() == ProgramType.MAPREDUCE || programId.getType() == ProgramType.SPARK) && !store.getRuns(programId.toId(), ProgramRunStatus.RUNNING, 0, Long.MAX_VALUE, 1).isEmpty()) { // MapReduce program exists and running as a part of Workflow return ProgramStatus.RUNNING; } return ProgramStatus.STOPPED; } // TODO: Fetching webapp status is a hack. This will be fixed when webapp spec is added. try { Location webappLoc = Programs.programLocation(namespacedLocationFactory, appFabricDir, programId.toId()); if (webappLoc != null && webappLoc.exists()) { // webapp exists and not running. so return stopped. return ProgramStatus.STOPPED; } // the webappLoc does not exists throw new NotFoundException(programId); } catch (IOException ioe) { throw new NotFoundException(programId.toId(), ioe); } } return runtimeInfo.getController().getState().getProgramStatus(); } /** * Returns the {@link ProgramSpecification} for the specified {@link ProgramId program}. * * @param programId the {@link ProgramId program} for which the {@link ProgramSpecification} is requested * @return the {@link ProgramSpecification} for the specified {@link ProgramId program} */ @Nullable public ProgramSpecification getProgramSpecification(ProgramId programId) { ApplicationSpecification appSpec; appSpec = store.getApplication(Ids.namespace(programId.getNamespace()).app(programId.getApplication()).toId()); if (appSpec == null) { return null; } String programName = programId.getProgram(); ProgramType type = programId.getType(); ProgramSpecification programSpec; if (type == ProgramType.FLOW && appSpec.getFlows().containsKey(programName)) { programSpec = appSpec.getFlows().get(programName); } else if (type == ProgramType.MAPREDUCE && appSpec.getMapReduce().containsKey(programName)) { programSpec = appSpec.getMapReduce().get(programName); } else if (type == ProgramType.SPARK && appSpec.getSpark().containsKey(programName)) { programSpec = appSpec.getSpark().get(programName); } else if (type == ProgramType.WORKFLOW && appSpec.getWorkflows().containsKey(programName)) { programSpec = appSpec.getWorkflows().get(programName); } else if (type == ProgramType.SERVICE && appSpec.getServices().containsKey(programName)) { programSpec = appSpec.getServices().get(programName); } else if (type == ProgramType.WORKER && appSpec.getWorkers().containsKey(programName)) { programSpec = appSpec.getWorkers().get(programName); } else { programSpec = null; } return programSpec; } /** * Starts a Program with the specified argument overrides. * * @param programId the {@link ProgramId} to start/stop * @param overrides the arguments to override in the program's configured user arguments before starting * @param debug {@code true} if the program is to be started in debug mode, {@code false} otherwise * @throws ConflictException if the specified program is already running, and if concurrent runs are not allowed * @throws NotFoundException if the specified program or the app it belongs to is not found in the specified namespace * @throws IOException if there is an error starting the program * @throws UnauthorizedException if the logged in user is not authorized to start the program. To start a program, * a user requires {@link Action#EXECUTE} on the program * @throws Exception if there were other exceptions checking if the current user is authorized to start the program */ public synchronized void start(ProgramId programId, Map<String, String> overrides, boolean debug) throws Exception { Map<String, String> sysArgs = propertiesResolver.getSystemProperties(programId.toId()); Map<String, String> userArgs = propertiesResolver.getUserProperties(programId.toId()); if (overrides != null) { userArgs.putAll(overrides); } if (isRunning(programId) && !isConcurrentRunsAllowed(programId.getType())) { throw new ConflictException(String.format("Program %s is already running", programId)); } ProgramRuntimeService.RuntimeInfo runtimeInfo = start(programId, sysArgs, userArgs, debug); if (runtimeInfo == null) { throw new IOException(String.format("Failed to start program %s", programId)); } } /** * Start a Program. * * @param programId the {@link ProgramId program} to start * @param systemArgs system arguments * @param userArgs user arguments * @param debug enable debug mode * @return {@link ProgramRuntimeService.RuntimeInfo} * @throws IOException if there is an error starting the program * @throws ProgramNotFoundException if program is not found * @throws UnauthorizedException if the logged in user is not authorized to start the program. To start a program, * a user requires {@link Action#EXECUTE} on the program * @throws Exception if there were other exceptions checking if the current user is authorized to start the program */ public ProgramRuntimeService.RuntimeInfo start(final ProgramId programId, final Map<String, String> systemArgs, final Map<String, String> userArgs, boolean debug) throws Exception { authorizerInstantiatorService.get().enforce(programId, SecurityRequestContext.toPrincipal(), Action.EXECUTE); Program program = store.loadProgram(programId.toId()); BasicArguments systemArguments = new BasicArguments(systemArgs); BasicArguments userArguments = new BasicArguments(userArgs); ProgramRuntimeService.RuntimeInfo runtimeInfo = runtimeService.run(program, new SimpleProgramOptions( programId.getProgram(), systemArguments, userArguments, debug)); final ProgramController controller = runtimeInfo.getController(); final String runId = controller.getRunId().getId(); final String twillRunId = runtimeInfo.getTwillRunId() == null ? null : runtimeInfo.getTwillRunId().getId(); if (programId.getType() != ProgramType.MAPREDUCE && programId.getType() != ProgramType.SPARK) { // MapReduce state recording is done by the MapReduceProgramRunner // TODO [JIRA: CDAP-2013] Same needs to be done for other programs as well controller.addListener(new AbstractListener() { @Override public void init(ProgramController.State state, @Nullable Throwable cause) { // Get start time from RunId long startTimeInSeconds = RunIds.getTime(controller.getRunId(), TimeUnit.SECONDS); if (startTimeInSeconds == -1) { // If RunId is not time-based, use current time as start time startTimeInSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()); } store.setStart(programId.toId(), runId, startTimeInSeconds, twillRunId, userArgs, systemArgs); if (state == ProgramController.State.COMPLETED) { completed(); } if (state == ProgramController.State.ERROR) { error(controller.getFailureCause()); } } @Override public void completed() { LOG.debug("Program {} completed successfully.", programId); store.setStop(programId.toId(), runId, TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()), ProgramController.State.COMPLETED.getRunStatus()); } @Override public void killed() { LOG.debug("Program {} killed.", programId.getNamespaceId()); store.setStop(programId.toId(), runId, TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()), ProgramController.State.KILLED.getRunStatus()); } @Override public void suspended() { LOG.debug("Suspending Program {} {}.", programId, runId); store.setSuspend(programId.toId(), runId); } @Override public void resuming() { LOG.debug("Resuming Program {} {}.", programId, runId); store.setResume(programId.toId(), runId); } @Override public void error(Throwable cause) { LOG.info("Program stopped with error {}, {}", programId, runId, cause); store.setStop(programId.toId(), runId, TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()), ProgramController.State.ERROR.getRunStatus(), cause); } }, Threads.SAME_THREAD_EXECUTOR); } return runtimeInfo; } /** * Stops the specified program. The first run of the program as found by {@link ProgramRuntimeService} is stopped. * * @param programId the {@link ProgramId program} to stop * @throws NotFoundException if the app, program or run was not found * @throws BadRequestException if an attempt is made to stop a program that is either not running or * was started by a workflow * @throws InterruptedException if there was a problem while waiting for the stop call to complete * @throws ExecutionException if there was a problem while waiting for the stop call to complete */ public synchronized void stop(ProgramId programId) throws Exception { stop(programId, null); } /** * Stops the specified run of the specified program. * * @param programId the {@link ProgramId program} to stop * @param runId the runId of the program run to stop. If null, the first run of the program as returned by * {@link ProgramRuntimeService} is stopped. * @throws NotFoundException if the app, program or run was not found * @throws BadRequestException if an attempt is made to stop a program that is either not running or * was started by a workflow * @throws InterruptedException if there was a problem while waiting for the stop call to complete * @throws ExecutionException if there was a problem while waiting for the stop call to complete */ public void stop(ProgramId programId, @Nullable String runId) throws Exception { issueStop(programId, runId).get(); } /** * Issues a command to stop the specified {@link RunId} of the specified {@link ProgramId} and returns a * {@link ListenableFuture} with the {@link ProgramController} for it. * Clients can wait for completion of the {@link ListenableFuture}. * * @param programId the {@link ProgramId program} to issue a stop for * @param runId the runId of the program run to stop. If null, the first run of the program as returned by * {@link ProgramRuntimeService} is stopped. * @return a {@link ListenableFuture} with a {@link ProgramController} that clients can wait on for stop to complete. * @throws NotFoundException if the app, program or run was not found * @throws BadRequestException if an attempt is made to stop a program that is either not running or * was started by a workflow * @throws UnauthorizedException if the user issuing the command is not authorized to stop the program. To stop a * program, a user requires {@link Action#EXECUTE} permission on the program. */ public ListenableFuture<ProgramController> issueStop(ProgramId programId, @Nullable String runId) throws Exception { authorizerInstantiatorService.get().enforce(programId, SecurityRequestContext.toPrincipal(), Action.EXECUTE); ProgramRuntimeService.RuntimeInfo runtimeInfo = findRuntimeInfo(programId, runId); if (runtimeInfo == null) { if (!store.applicationExists(programId.toId().getApplication())) { throw new ApplicationNotFoundException(programId.toId().getApplication()); } else if (!store.programExists(programId.toId())) { throw new ProgramNotFoundException(programId.toId()); } else if (runId != null) { ProgramRunId programRunId = programId.run(runId); // Check if the program is running and is started by the Workflow RunRecordMeta runRecord = store.getRun(programId.toId(), runId); if (runRecord != null && runRecord.getProperties().containsKey("workflowrunid") && runRecord.getStatus().equals(ProgramRunStatus.RUNNING)) { String workflowRunId = runRecord.getProperties().get("workflowrunid"); throw new BadRequestException(String.format("Cannot stop the program '%s' started by the Workflow " + "run '%s'. Please stop the Workflow.", programRunId, workflowRunId)); } throw new NotFoundException(programRunId); } throw new BadRequestException(String.format("Program '%s' is not running.", programId)); } return runtimeInfo.getController().stop(); } /** * Save runtime arguments for all future runs of this program. The runtime arguments are saved in the * {@link PreferencesStore}. * * @param programId the {@link ProgramId program} for which runtime arguments are to be saved * @param runtimeArgs the runtime arguments to save * @throws NotFoundException if the specified program was not found * @throws UnauthorizedException if the current user does not have sufficient privileges to save runtime arguments for * the specified program. To save runtime arguments for a program, a user requires * {@link Action#ADMIN} privileges on the program. */ public void saveRuntimeArgs(ProgramId programId, Map<String, String> runtimeArgs) throws Exception { authorizerInstantiatorService.get().enforce(programId, SecurityRequestContext.toPrincipal(), Action.ADMIN); if (!store.programExists(programId.toId())) { throw new NotFoundException(programId.toId()); } preferencesStore.setProperties(programId.getNamespace(), programId.getApplication(), programId.getType().getCategoryName(), programId.getProgram(), runtimeArgs); } private boolean isRunning(ProgramId programId) throws BadRequestException, NotFoundException { return ProgramStatus.STOPPED != getProgramStatus(programId); } private boolean isConcurrentRunsAllowed(ProgramType type) { // Concurrent runs are only allowed for the Workflow and MapReduce return EnumSet.of(ProgramType.WORKFLOW, ProgramType.MAPREDUCE).contains(type); } @Nullable private ProgramRuntimeService.RuntimeInfo findRuntimeInfo(ProgramId programId, @Nullable String runId) throws BadRequestException { Map<RunId, ProgramRuntimeService.RuntimeInfo> runtimeInfos = runtimeService.list(programId.getType()); if (runId != null) { RunId run; try { run = RunIds.fromString(runId); } catch (IllegalArgumentException e) { throw new BadRequestException("Error parsing run-id.", e); } return runtimeInfos.get(run); } return findRuntimeInfo(programId); } @Nullable private ProgramRuntimeService.RuntimeInfo findRuntimeInfo(ProgramId programId) { Map<RunId, ProgramRuntimeService.RuntimeInfo> runtimeInfos = runtimeService.list(programId.getType()); for (ProgramRuntimeService.RuntimeInfo info : runtimeInfos.values()) { if (programId.equals(info.getProgramId().toEntityId())) { return info; } } return null; } /** * @see #setInstances(ProgramId, int, String) */ public void setInstances(ProgramId programId, int instances) throws Exception { setInstances(programId, instances, null); } /** * Set instances for the given program. Only supported program types for this action are {@link ProgramType#FLOW}, * {@link ProgramType#SERVICE} and {@link ProgramType#WORKER}. * * @param programId the {@link ProgramId} of the program for which instances are to be updated * @param instances the number of instances to be updated. * @param component the flowlet name. Only used when the program is a {@link ProgramType#FLOW flow}. * @throws InterruptedException if there is an error while asynchronously updating instances * @throws ExecutionException if there is an error while asynchronously updating instances * @throws BadRequestException if the number of instances specified is less than 0 * @throws UnauthorizedException if the user does not have privileges to set instances for the specified program. * To set instances for a program, a user needs {@link Action#ADMIN} on the program. */ public void setInstances(ProgramId programId, int instances, @Nullable String component) throws Exception { authorizerInstantiatorService.get().enforce(programId, SecurityRequestContext.toPrincipal(), Action.ADMIN); if (instances < 1) { throw new BadRequestException(String.format("Instance count should be greater than 0. Got %s.", instances)); } switch (programId.getType()) { case SERVICE: setServiceInstances(programId, instances); break; case WORKER: setWorkerInstances(programId, instances); break; case FLOW: setFlowletInstances(programId, component, instances); break; default: throw new BadRequestException(String.format("Setting instances for program type %s is not supported", programId.getType().getPrettyName())); } } private void setWorkerInstances(ProgramId programId, int instances) throws ExecutionException, InterruptedException { int oldInstances = store.getWorkerInstances(programId.toId()); if (oldInstances != instances) { store.setWorkerInstances(programId.toId(), instances); ProgramRuntimeService.RuntimeInfo runtimeInfo = findRuntimeInfo(programId); if (runtimeInfo != null) { runtimeInfo.getController().command(ProgramOptionConstants.INSTANCES, ImmutableMap.of("runnable", programId.getProgram(), "newInstances", String.valueOf(instances), "oldInstances", String.valueOf(oldInstances))).get(); } } } private void setFlowletInstances(ProgramId programId, String flowletId, int instances) throws ExecutionException, InterruptedException { int oldInstances = store.getFlowletInstances(programId.toId(), flowletId); if (oldInstances != instances) { FlowSpecification flowSpec = store.setFlowletInstances(programId.toId(), flowletId, instances); ProgramRuntimeService.RuntimeInfo runtimeInfo = findRuntimeInfo(programId); if (runtimeInfo != null) { runtimeInfo.getController() .command(ProgramOptionConstants.INSTANCES, ImmutableMap.of("flowlet", flowletId, "newInstances", String.valueOf(instances), "oldFlowSpec", GSON.toJson(flowSpec, FlowSpecification.class))).get(); } } } private void setServiceInstances(ProgramId programId, int instances) throws ExecutionException, InterruptedException { int oldInstances = store.getServiceInstances(programId.toId()); if (oldInstances != instances) { store.setServiceInstances(programId.toId(), instances); ProgramRuntimeService.RuntimeInfo runtimeInfo = findRuntimeInfo(programId); if (runtimeInfo != null) { runtimeInfo.getController().command(ProgramOptionConstants.INSTANCES, ImmutableMap.of("runnable", programId.getProgram(), "newInstances", String.valueOf(instances), "oldInstances", String.valueOf(oldInstances))).get(); } } } /** * Fix all the possible inconsistent states for RunRecords that shows it is in RUNNING state but actually not * via check to {@link ProgramRuntimeService}. */ private void validateAndCorrectRunningRunRecords() { Set<String> processedInvalidRunRecordIds = Sets.newHashSet(); // Lets update the running programs run records for (ProgramType programType : ProgramType.values()) { validateAndCorrectRunningRunRecords(programType, processedInvalidRunRecordIds); } if (!processedInvalidRunRecordIds.isEmpty()) { LOG.info("Corrected {} of run records with RUNNING status but no actual program running.", processedInvalidRunRecordIds.size()); } } /** * Fix all the possible inconsistent states for RunRecords that shows it is in RUNNING state but actually not * via check to {@link ProgramRuntimeService} for a type of CDAP program. * * @param programType The type of program the run records need to validate and update. * @param processedInvalidRunRecordIds the {@link Set} of processed invalid run record ids. */ void validateAndCorrectRunningRunRecords(final ProgramType programType, Set<String> processedInvalidRunRecordIds) { final Map<RunId, RuntimeInfo> runIdToRuntimeInfo = runtimeService.list(programType); LOG.trace("Start getting run records not actually running ..."); List<RunRecordMeta> notActuallyRunning = store.getRuns(ProgramRunStatus.RUNNING, new Predicate<RunRecordMeta>() { @Override public boolean apply(RunRecordMeta input) { String runId = input.getPid(); // Check if it is not actually running. return !runIdToRuntimeInfo.containsKey(RunIds.fromString(runId)); } }); LOG.trace("End getting {} run records not actually running.", notActuallyRunning.size()); final Map<String, ProgramId> runIdToProgramId = new HashMap<>(); LOG.trace("Start getting invalid run records ..."); Collection<RunRecordMeta> invalidRunRecords = Collections2.filter(notActuallyRunning, new Predicate<RunRecordMeta>() { @Override public boolean apply(RunRecordMeta input) { String runId = input.getPid(); // check for program Id for the run record, if null then it is invalid program type. ProgramId targetProgramId = retrieveProgramIdForRunRecord(programType, runId); // Check if run id is for the right program type if (targetProgramId != null) { runIdToProgramId.put(runId, targetProgramId); return true; } else { return false; } } }); LOG.trace("End getting invalid run records."); if (!invalidRunRecords.isEmpty()) { LOG.warn("Found {} RunRecords with RUNNING status but the program is not actually running for program type {}", invalidRunRecords.size(), programType.getPrettyName()); } else { LOG.trace("No RunRecords found with RUNNING status but the program is not actually running for program type {}", programType.getPrettyName()); } // Now lets correct the invalid RunRecords for (RunRecordMeta invalidRunRecordMeta : invalidRunRecords) { boolean shouldCorrect = shouldCorrectForWorkflowChildren(invalidRunRecordMeta, processedInvalidRunRecordIds); if (!shouldCorrect) { LOG.trace("Will not correct invalid run record {} since it's parent workflow still running.", invalidRunRecordMeta); continue; } String runId = invalidRunRecordMeta.getPid(); ProgramId targetProgramId = runIdToProgramId.get(runId); LOG.warn("Fixing RunRecord {} in program {} of type {} with RUNNING status but the program is not running", runId, targetProgramId, programType.getPrettyName()); store.compareAndSetStatus(targetProgramId.toId(), runId, ProgramController.State.ALIVE.getRunStatus(), ProgramController.State.ERROR.getRunStatus()); processedInvalidRunRecordIds.add(runId); } } /** * Helper method to check if the run record is a child program of a Workflow * * @param runRecordMeta The target {@link RunRecordMeta} to check * @param processedInvalidRunRecordIds the {@link Set} of processed invalid run record ids. * @return {@code true} of we should check and {@code false} otherwise */ private boolean shouldCorrectForWorkflowChildren(RunRecordMeta runRecordMeta, Set<String> processedInvalidRunRecordIds) { // check if it is part of workflow because it may not have actual runtime info if (runRecordMeta.getProperties() != null && runRecordMeta.getProperties().get("workflowrunid") != null) { // Get the parent Workflow info String workflowRunId = runRecordMeta.getProperties().get("workflowrunid"); if (!processedInvalidRunRecordIds.contains(workflowRunId)) { // If the parent workflow has not been processed, then check if it still valid ProgramId workflowProgramId = retrieveProgramIdForRunRecord(ProgramType.WORKFLOW, workflowRunId); if (workflowProgramId != null) { // lets see if the parent workflow run records state is still running RunRecordMeta wfRunRecord = store.getRun(workflowProgramId.toId(), workflowRunId); RuntimeInfo wfRuntimeInfo = runtimeService.lookup(workflowProgramId.toId(), RunIds.fromString(workflowRunId)); // Check of the parent workflow run record exists and it is running and runtime info said it is still there // then do not update it if (wfRunRecord != null && wfRunRecord.getStatus() == ProgramRunStatus.RUNNING && wfRuntimeInfo != null) { return false; } } } } return true; } /** * Helper method to get {@link ProgramId} for a RunRecord for type of program * * @param programType Type of program to search * @param runId The target id of the {@link RunRecord} to find * @return the program id of the run record or {@code null} if does not exist. */ @Nullable private ProgramId retrieveProgramIdForRunRecord(ProgramType programType, String runId) { // Get list of namespaces (borrow logic from AbstractAppFabricHttpHandler#listPrograms) List<NamespaceMeta> namespaceMetas = nsStore.list(); // For each, get all programs under it ProgramId targetProgramId = null; for (NamespaceMeta nm : namespaceMetas) { NamespaceId namespace = Ids.namespace(nm.getName()); Collection<ApplicationSpecification> appSpecs = store.getAllApplications(namespace.toId()); // For each application get the programs checked against run records for (ApplicationSpecification appSpec : appSpecs) { switch (programType) { case FLOW: for (String programName : appSpec.getFlows().keySet()) { ProgramId programId = validateProgramForRunRecord(nm.getName(), appSpec.getName(), programType, programName, runId); if (programId != null) { targetProgramId = programId; break; } } break; case MAPREDUCE: for (String programName : appSpec.getMapReduce().keySet()) { ProgramId programId = validateProgramForRunRecord(nm.getName(), appSpec.getName(), programType, programName, runId); if (programId != null) { targetProgramId = programId; break; } } break; case SPARK: for (String programName : appSpec.getSpark().keySet()) { ProgramId programId = validateProgramForRunRecord(nm.getName(), appSpec.getName(), programType, programName, runId); if (programId != null) { targetProgramId = programId; break; } } break; case SERVICE: for (String programName : appSpec.getServices().keySet()) { ProgramId programId = validateProgramForRunRecord(nm.getName(), appSpec.getName(), programType, programName, runId); if (programId != null) { targetProgramId = programId; break; } } break; case WORKER: for (String programName : appSpec.getWorkers().keySet()) { ProgramId programId = validateProgramForRunRecord(nm.getName(), appSpec.getName(), programType, programName, runId); if (programId != null) { targetProgramId = programId; break; } } break; case WORKFLOW: for (String programName : appSpec.getWorkflows().keySet()) { ProgramId programId = validateProgramForRunRecord(nm.getName(), appSpec.getName(), programType, programName, runId); if (programId != null) { targetProgramId = programId; break; } } break; case CUSTOM_ACTION: case WEBAPP: // no-op break; default: LOG.debug("Unknown program type: " + programType.name()); break; } if (targetProgramId != null) { break; } } if (targetProgramId != null) { break; } } return targetProgramId; } /** * Helper method to get program id for a run record if it exists in the store. * * @return instance of {@link ProgramId} if exist for the runId or null if does not */ @Nullable private ProgramId validateProgramForRunRecord(String namespaceName, String appName, ProgramType programType, String programName, String runId) { ProgramId programId = Ids.namespace(namespaceName).app(appName).program(programType, programName); RunRecordMeta runRecord = store.getRun(programId.toId(), runId); if (runRecord == null) { return null; } return programId; } /** * Helper class to run in separate thread to validate the invalid running run records */ private static class RunRecordsCorrectorRunnable implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(RunRecordsCorrectorRunnable.class); private final ProgramLifecycleService programLifecycleService; public RunRecordsCorrectorRunnable(ProgramLifecycleService programLifecycleService) { this.programLifecycleService = programLifecycleService; } @Override public void run() { try { RunRecordsCorrectorRunnable.LOG.debug("Start correcting invalid run records ..."); // Lets update the running programs run records programLifecycleService.validateAndCorrectRunningRunRecords(); RunRecordsCorrectorRunnable.LOG.debug("End correcting invalid run records."); } catch (Throwable t) { // Ignore any exception thrown since this behaves like daemon thread. //noinspection ThrowableResultOfMethodCallIgnored LOG.warn("Unable to complete correcting run records: {}", Throwables.getRootCause(t).getMessage()); LOG.debug("Exception thrown when running run id cleaner.", t); } } } }
cdap-app-fabric/src/main/java/co/cask/cdap/internal/app/services/ProgramLifecycleService.java
/* * Copyright © 2015-2016 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package co.cask.cdap.internal.app.services; import co.cask.cdap.api.ProgramSpecification; import co.cask.cdap.api.app.ApplicationSpecification; import co.cask.cdap.api.flow.FlowSpecification; import co.cask.cdap.app.program.Program; import co.cask.cdap.app.program.Programs; import co.cask.cdap.app.runtime.ProgramController; import co.cask.cdap.app.runtime.ProgramRuntimeService; import co.cask.cdap.app.runtime.ProgramRuntimeService.RuntimeInfo; import co.cask.cdap.app.store.Store; import co.cask.cdap.common.ApplicationNotFoundException; import co.cask.cdap.common.BadRequestException; import co.cask.cdap.common.ConflictException; import co.cask.cdap.common.NotFoundException; import co.cask.cdap.common.ProgramNotFoundException; import co.cask.cdap.common.app.RunIds; import co.cask.cdap.common.conf.CConfiguration; import co.cask.cdap.common.conf.Constants; import co.cask.cdap.common.io.CaseInsensitiveEnumTypeAdapterFactory; import co.cask.cdap.common.namespace.NamespacedLocationFactory; import co.cask.cdap.config.PreferencesStore; import co.cask.cdap.internal.app.ApplicationSpecificationAdapter; import co.cask.cdap.internal.app.runtime.AbstractListener; import co.cask.cdap.internal.app.runtime.BasicArguments; import co.cask.cdap.internal.app.runtime.ProgramOptionConstants; import co.cask.cdap.internal.app.runtime.SimpleProgramOptions; import co.cask.cdap.internal.app.store.RunRecordMeta; import co.cask.cdap.proto.NamespaceMeta; import co.cask.cdap.proto.ProgramRunStatus; import co.cask.cdap.proto.ProgramStatus; import co.cask.cdap.proto.ProgramType; import co.cask.cdap.proto.RunRecord; import co.cask.cdap.proto.id.Ids; import co.cask.cdap.proto.id.NamespaceId; import co.cask.cdap.proto.id.ProgramId; import co.cask.cdap.proto.id.ProgramRunId; import co.cask.cdap.proto.security.Action; import co.cask.cdap.security.authorization.AuthorizerInstantiatorService; import co.cask.cdap.security.spi.authentication.SecurityRequestContext; import co.cask.cdap.security.spi.authorization.UnauthorizedException; import co.cask.cdap.store.NamespaceStore; import com.google.common.base.Predicate; import com.google.common.base.Throwables; import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import com.google.common.util.concurrent.AbstractIdleService; import com.google.common.util.concurrent.ListenableFuture; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.inject.Inject; import org.apache.twill.api.RunId; import org.apache.twill.common.Threads; import org.apache.twill.filesystem.Location; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Collection; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; /** * Service that manages lifecycle of Programs. */ public class ProgramLifecycleService extends AbstractIdleService { private static final Logger LOG = LoggerFactory.getLogger(ProgramLifecycleService.class); private static final Gson GSON = ApplicationSpecificationAdapter .addTypeAdapters(new GsonBuilder()) .registerTypeAdapterFactory(new CaseInsensitiveEnumTypeAdapterFactory()) .create(); private final ScheduledExecutorService scheduledExecutorService; private final Store store; private final ProgramRuntimeService runtimeService; private final CConfiguration cConf; private final NamespaceStore nsStore; private final PropertiesResolver propertiesResolver; private final NamespacedLocationFactory namespacedLocationFactory; private final String appFabricDir; private final PreferencesStore preferencesStore; private final AuthorizerInstantiatorService authorizerInstantiatorService; @Inject ProgramLifecycleService(Store store, NamespaceStore nsStore, ProgramRuntimeService runtimeService, CConfiguration cConf, PropertiesResolver propertiesResolver, NamespacedLocationFactory namespacedLocationFactory, PreferencesStore preferencesStore, AuthorizerInstantiatorService authorizerInstantiatorService) { this.store = store; this.nsStore = nsStore; this.runtimeService = runtimeService; this.propertiesResolver = propertiesResolver; this.namespacedLocationFactory = namespacedLocationFactory; this.appFabricDir = cConf.get(Constants.AppFabric.OUTPUT_DIR); this.scheduledExecutorService = Executors.newScheduledThreadPool(1); this.cConf = cConf; this.preferencesStore = preferencesStore; this.authorizerInstantiatorService = authorizerInstantiatorService; } @Override protected void startUp() throws Exception { LOG.info("Starting ProgramLifecycleService"); long interval = cConf.getLong(Constants.AppFabric.PROGRAM_RUNID_CORRECTOR_INTERVAL_SECONDS); if (interval <= 0) { LOG.debug("Invalid run id corrector interval {}. Setting it to 180 seconds.", interval); interval = 180L; } scheduledExecutorService.scheduleWithFixedDelay(new RunRecordsCorrectorRunnable(this), 2L, interval, TimeUnit.SECONDS); } @Override protected void shutDown() throws Exception { LOG.info("Shutting down ProgramLifecycleService"); scheduledExecutorService.shutdown(); try { if (!scheduledExecutorService.awaitTermination(5, TimeUnit.SECONDS)) { scheduledExecutorService.shutdownNow(); } } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } /** * Returns the program status. * @param programId the id of the program for which the status call is made * @return the status of the program * @throws NotFoundException if the application to which this program belongs was not found */ public ProgramStatus getProgramStatus(ProgramId programId) throws NotFoundException { // check that app exists ApplicationSpecification appSpec = store.getApplication(programId.toId().getApplication()); if (appSpec == null) { throw new NotFoundException(Ids.namespace(programId.getNamespace()).app(programId.getApplication()).toId()); } ProgramRuntimeService.RuntimeInfo runtimeInfo = findRuntimeInfo(programId); if (runtimeInfo == null) { if (programId.getType() != ProgramType.WEBAPP) { //Runtime info not found. Check to see if the program exists. ProgramSpecification spec = getProgramSpecification(programId); if (spec == null) { // program doesn't exist throw new NotFoundException(programId); } if ((programId.getType() == ProgramType.MAPREDUCE || programId.getType() == ProgramType.SPARK) && !store.getRuns(programId.toId(), ProgramRunStatus.RUNNING, 0, Long.MAX_VALUE, 1).isEmpty()) { // MapReduce program exists and running as a part of Workflow return ProgramStatus.RUNNING; } return ProgramStatus.STOPPED; } // TODO: Fetching webapp status is a hack. This will be fixed when webapp spec is added. try { Location webappLoc = Programs.programLocation(namespacedLocationFactory, appFabricDir, programId.toId()); if (webappLoc != null && webappLoc.exists()) { // webapp exists and not running. so return stopped. return ProgramStatus.STOPPED; } // the webappLoc does not exists throw new NotFoundException(programId); } catch (IOException ioe) { throw new NotFoundException(programId.toId(), ioe); } } return runtimeInfo.getController().getState().getProgramStatus(); } /** * Returns the {@link ProgramSpecification} for the specified {@link ProgramId program}. * * @param programId the {@link ProgramId program} for which the {@link ProgramSpecification} is requested * @return the {@link ProgramSpecification} for the specified {@link ProgramId program} */ @Nullable public ProgramSpecification getProgramSpecification(ProgramId programId) { ApplicationSpecification appSpec; appSpec = store.getApplication(Ids.namespace(programId.getNamespace()).app(programId.getApplication()).toId()); if (appSpec == null) { return null; } String programName = programId.getProgram(); ProgramType type = programId.getType(); ProgramSpecification programSpec; if (type == ProgramType.FLOW && appSpec.getFlows().containsKey(programName)) { programSpec = appSpec.getFlows().get(programName); } else if (type == ProgramType.MAPREDUCE && appSpec.getMapReduce().containsKey(programName)) { programSpec = appSpec.getMapReduce().get(programName); } else if (type == ProgramType.SPARK && appSpec.getSpark().containsKey(programName)) { programSpec = appSpec.getSpark().get(programName); } else if (type == ProgramType.WORKFLOW && appSpec.getWorkflows().containsKey(programName)) { programSpec = appSpec.getWorkflows().get(programName); } else if (type == ProgramType.SERVICE && appSpec.getServices().containsKey(programName)) { programSpec = appSpec.getServices().get(programName); } else if (type == ProgramType.WORKER && appSpec.getWorkers().containsKey(programName)) { programSpec = appSpec.getWorkers().get(programName); } else { programSpec = null; } return programSpec; } /** * Starts a Program with the specified argument overrides. * * @param programId the {@link ProgramId} to start/stop * @param overrides the arguments to override in the program's configured user arguments before starting * @param debug {@code true} if the program is to be started in debug mode, {@code false} otherwise * @throws ConflictException if the specified program is already running, and if concurrent runs are not allowed * @throws NotFoundException if the specified program or the app it belongs to is not found in the specified namespace * @throws IOException if there is an error starting the program * @throws UnauthorizedException if the logged in user is not authorized to start the program. To start a program, * a user requires {@link Action#EXECUTE} on the program * @throws Exception if there were other exceptions checking if the current user is authorized to start the program */ public synchronized void start(ProgramId programId, Map<String, String> overrides, boolean debug) throws Exception { Map<String, String> sysArgs = propertiesResolver.getSystemProperties(programId.toId()); Map<String, String> userArgs = propertiesResolver.getUserProperties(programId.toId()); if (overrides != null) { userArgs.putAll(overrides); } if (isRunning(programId) && !isConcurrentRunsAllowed(programId.getType())) { throw new ConflictException(String.format("Program %s is already running", programId)); } ProgramRuntimeService.RuntimeInfo runtimeInfo = start(programId, sysArgs, userArgs, debug); if (runtimeInfo == null) { throw new IOException(String.format("Failed to start program %s", programId)); } } /** * Start a Program. * * @param programId the {@link ProgramId program} to start * @param systemArgs system arguments * @param userArgs user arguments * @param debug enable debug mode * @return {@link ProgramRuntimeService.RuntimeInfo} * @throws IOException if there is an error starting the program * @throws ProgramNotFoundException if program is not found * @throws UnauthorizedException if the logged in user is not authorized to start the program. To start a program, * a user requires {@link Action#EXECUTE} on the program * @throws Exception if there were other exceptions checking if the current user is authorized to start the program */ public ProgramRuntimeService.RuntimeInfo start(final ProgramId programId, final Map<String, String> systemArgs, final Map<String, String> userArgs, boolean debug) throws Exception { authorizerInstantiatorService.get().enforce(programId, SecurityRequestContext.toPrincipal(), Action.EXECUTE); Program program = store.loadProgram(programId.toId()); BasicArguments systemArguments = new BasicArguments(systemArgs); BasicArguments userArguments = new BasicArguments(userArgs); ProgramRuntimeService.RuntimeInfo runtimeInfo = runtimeService.run(program, new SimpleProgramOptions( programId.getProgram(), systemArguments, userArguments, debug)); final ProgramController controller = runtimeInfo.getController(); final String runId = controller.getRunId().getId(); final String twillRunId = runtimeInfo.getTwillRunId() == null ? null : runtimeInfo.getTwillRunId().getId(); if (programId.getType() != ProgramType.MAPREDUCE && programId.getType() != ProgramType.SPARK) { // MapReduce state recording is done by the MapReduceProgramRunner // TODO [JIRA: CDAP-2013] Same needs to be done for other programs as well controller.addListener(new AbstractListener() { @Override public void init(ProgramController.State state, @Nullable Throwable cause) { // Get start time from RunId long startTimeInSeconds = RunIds.getTime(controller.getRunId(), TimeUnit.SECONDS); if (startTimeInSeconds == -1) { // If RunId is not time-based, use current time as start time startTimeInSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()); } store.setStart(programId.toId(), runId, startTimeInSeconds, twillRunId, userArgs, systemArgs); if (state == ProgramController.State.COMPLETED) { completed(); } if (state == ProgramController.State.ERROR) { error(controller.getFailureCause()); } } @Override public void completed() { LOG.debug("Program {} completed successfully.", programId); store.setStop(programId.toId(), runId, TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()), ProgramController.State.COMPLETED.getRunStatus()); } @Override public void killed() { LOG.debug("Program {} killed.", programId.getNamespaceId()); store.setStop(programId.toId(), runId, TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()), ProgramController.State.KILLED.getRunStatus()); } @Override public void suspended() { LOG.debug("Suspending Program {} {}.", programId, runId); store.setSuspend(programId.toId(), runId); } @Override public void resuming() { LOG.debug("Resuming Program {} {}.", programId, runId); store.setResume(programId.toId(), runId); } @Override public void error(Throwable cause) { LOG.info("Program stopped with error {}, {}", programId, runId, cause); store.setStop(programId.toId(), runId, TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()), ProgramController.State.ERROR.getRunStatus(), cause); } }, Threads.SAME_THREAD_EXECUTOR); } return runtimeInfo; } /** * Stops the specified program. The first run of the program as found by {@link ProgramRuntimeService} is stopped. * * @param programId the {@link ProgramId program} to stop * @throws NotFoundException if the app, program or run was not found * @throws BadRequestException if an attempt is made to stop a program that is either not running or * was started by a workflow * @throws InterruptedException if there was a problem while waiting for the stop call to complete * @throws ExecutionException if there was a problem while waiting for the stop call to complete */ public synchronized void stop(ProgramId programId) throws Exception { stop(programId, null); } /** * Stops the specified run of the specified program. * * @param programId the {@link ProgramId program} to stop * @param runId the runId of the program run to stop. If null, the first run of the program as returned by * {@link ProgramRuntimeService} is stopped. * @throws NotFoundException if the app, program or run was not found * @throws BadRequestException if an attempt is made to stop a program that is either not running or * was started by a workflow * @throws InterruptedException if there was a problem while waiting for the stop call to complete * @throws ExecutionException if there was a problem while waiting for the stop call to complete */ public void stop(ProgramId programId, @Nullable String runId) throws Exception { issueStop(programId, runId).get(); } /** * Issues a command to stop the specified {@link RunId} of the specified {@link ProgramId} and returns a * {@link ListenableFuture} with the {@link ProgramController} for it. * Clients can wait for completion of the {@link ListenableFuture}. * * @param programId the {@link ProgramId program} to issue a stop for * @param runId the runId of the program run to stop. If null, the first run of the program as returned by * {@link ProgramRuntimeService} is stopped. * @return a {@link ListenableFuture} with a {@link ProgramController} that clients can wait on for stop to complete. * @throws NotFoundException if the app, program or run was not found * @throws BadRequestException if an attempt is made to stop a program that is either not running or * was started by a workflow * @throws UnauthorizedException if the user issuing the command is not authorized to stop the program. To stop a * program, a user requires {@link Action#EXECUTE} permission on the program. */ public ListenableFuture<ProgramController> issueStop(ProgramId programId, @Nullable String runId) throws Exception { authorizerInstantiatorService.get().enforce(programId, SecurityRequestContext.toPrincipal(), Action.EXECUTE); ProgramRuntimeService.RuntimeInfo runtimeInfo = findRuntimeInfo(programId, runId); if (runtimeInfo == null) { if (!store.applicationExists(programId.toId().getApplication())) { throw new ApplicationNotFoundException(programId.toId().getApplication()); } else if (!store.programExists(programId.toId())) { throw new ProgramNotFoundException(programId.toId()); } else if (runId != null) { ProgramRunId programRunId = programId.run(runId); // Check if the program is running and is started by the Workflow RunRecordMeta runRecord = store.getRun(programId.toId(), runId); if (runRecord != null && runRecord.getProperties().containsKey("workflowrunid") && runRecord.getStatus().equals(ProgramRunStatus.RUNNING)) { String workflowRunId = runRecord.getProperties().get("workflowrunid"); throw new BadRequestException(String.format("Cannot stop the program '%s' started by the Workflow " + "run '%s'. Please stop the Workflow.", programRunId, workflowRunId)); } throw new NotFoundException(programRunId); } throw new BadRequestException(String.format("Program '%s' is not running.", programId)); } return runtimeInfo.getController().stop(); } /** * Save runtime arguments for all future runs of this program. The runtime arguments are saved in the * {@link PreferencesStore}. * * @param programId the {@link ProgramId program} for which runtime arguments are to be saved * @param runtimeArgs the runtime arguments to save * @throws NotFoundException if the specified program was not found * @throws UnauthorizedException if the current user does not have sufficient privileges to save runtime arguments for * the specified program. To save runtime arguments for a program, a user requires * {@link Action#ADMIN} privileges on the program. */ public void saveRuntimeArgs(ProgramId programId, Map<String, String> runtimeArgs) throws Exception { authorizerInstantiatorService.get().enforce(programId, SecurityRequestContext.toPrincipal(), Action.ADMIN); if (!store.programExists(programId.toId())) { throw new NotFoundException(programId.toId()); } preferencesStore.setProperties(programId.getNamespace(), programId.getApplication(), programId.getType().getCategoryName(), programId.getProgram(), runtimeArgs); } private boolean isRunning(ProgramId programId) throws BadRequestException, NotFoundException { return ProgramStatus.STOPPED != getProgramStatus(programId); } private boolean isConcurrentRunsAllowed(ProgramType type) { // Concurrent runs are only allowed for the Workflow and MapReduce return EnumSet.of(ProgramType.WORKFLOW, ProgramType.MAPREDUCE).contains(type); } @Nullable private ProgramRuntimeService.RuntimeInfo findRuntimeInfo(ProgramId programId, @Nullable String runId) throws BadRequestException { Map<RunId, ProgramRuntimeService.RuntimeInfo> runtimeInfos = runtimeService.list(programId.getType()); if (runId != null) { RunId run; try { run = RunIds.fromString(runId); } catch (IllegalArgumentException e) { throw new BadRequestException("Error parsing run-id.", e); } return runtimeInfos.get(run); } return findRuntimeInfo(programId); } @Nullable private ProgramRuntimeService.RuntimeInfo findRuntimeInfo(ProgramId programId) { Map<RunId, ProgramRuntimeService.RuntimeInfo> runtimeInfos = runtimeService.list(programId.getType()); for (ProgramRuntimeService.RuntimeInfo info : runtimeInfos.values()) { if (programId.equals(info.getProgramId().toEntityId())) { return info; } } return null; } /** * @see #setInstances(ProgramId, int, String) */ public void setInstances(ProgramId programId, int instances) throws Exception { setInstances(programId, instances, null); } /** * Set instances for the given program. Only supported program types for this action are {@link ProgramType#FLOW}, * {@link ProgramType#SERVICE} and {@link ProgramType#WORKER}. * * @param programId the {@link ProgramId} of the program for which instances are to be updated * @param instances the number of instances to be updated. * @param component the flowlet name. Only used when the program is a {@link ProgramType#FLOW flow}. * @throws InterruptedException if there is an error while asynchronously updating instances * @throws ExecutionException if there is an error while asynchronously updating instances * @throws BadRequestException if the number of instances specified is less than 0 * @throws UnauthorizedException if the user does not have privileges to set instances for the specified program. * To set instances for a program, a user needs {@link Action#ADMIN} on the program. */ public void setInstances(ProgramId programId, int instances, @Nullable String component) throws Exception { authorizerInstantiatorService.get().enforce(programId, SecurityRequestContext.toPrincipal(), Action.ADMIN); if (instances < 1) { throw new BadRequestException(String.format("Instance count should be greater than 0. Got %s.", instances)); } switch (programId.getType()) { case SERVICE: setServiceInstances(programId, instances); break; case WORKER: setWorkerInstances(programId, instances); break; case FLOW: setFlowletInstances(programId, component, instances); break; default: throw new BadRequestException(String.format("Setting instances for program type %s is not supported", programId.getType().getPrettyName())); } } private void setWorkerInstances(ProgramId programId, int instances) throws ExecutionException, InterruptedException { int oldInstances = store.getWorkerInstances(programId.toId()); if (oldInstances != instances) { store.setWorkerInstances(programId.toId(), instances); ProgramRuntimeService.RuntimeInfo runtimeInfo = findRuntimeInfo(programId); if (runtimeInfo != null) { runtimeInfo.getController().command(ProgramOptionConstants.INSTANCES, ImmutableMap.of("runnable", programId.getProgram(), "newInstances", String.valueOf(instances), "oldInstances", String.valueOf(oldInstances))).get(); } } } private void setFlowletInstances(ProgramId programId, String flowletId, int instances) throws ExecutionException, InterruptedException { int oldInstances = store.getFlowletInstances(programId.toId(), flowletId); if (oldInstances != instances) { FlowSpecification flowSpec = store.setFlowletInstances(programId.toId(), flowletId, instances); ProgramRuntimeService.RuntimeInfo runtimeInfo = findRuntimeInfo(programId); if (runtimeInfo != null) { runtimeInfo.getController() .command(ProgramOptionConstants.INSTANCES, ImmutableMap.of("flowlet", flowletId, "newInstances", String.valueOf(instances), "oldFlowSpec", GSON.toJson(flowSpec, FlowSpecification.class))).get(); } } } private void setServiceInstances(ProgramId programId, int instances) throws ExecutionException, InterruptedException { int oldInstances = store.getServiceInstances(programId.toId()); if (oldInstances != instances) { store.setServiceInstances(programId.toId(), instances); ProgramRuntimeService.RuntimeInfo runtimeInfo = findRuntimeInfo(programId); if (runtimeInfo != null) { runtimeInfo.getController().command(ProgramOptionConstants.INSTANCES, ImmutableMap.of("runnable", programId.getProgram(), "newInstances", String.valueOf(instances), "oldInstances", String.valueOf(oldInstances))).get(); } } } /** * Fix all the possible inconsistent states for RunRecords that shows it is in RUNNING state but actually not * via check to {@link ProgramRuntimeService}. */ private void validateAndCorrectRunningRunRecords() { Set<String> processedInvalidRunRecordIds = Sets.newHashSet(); // Lets update the running programs run records for (ProgramType programType : ProgramType.values()) { validateAndCorrectRunningRunRecords(programType, processedInvalidRunRecordIds); } if (!processedInvalidRunRecordIds.isEmpty()) { LOG.info("Corrected {} of run records with RUNNING status but no actual program running.", processedInvalidRunRecordIds.size()); } } /** * Fix all the possible inconsistent states for RunRecords that shows it is in RUNNING state but actually not * via check to {@link ProgramRuntimeService} for a type of CDAP program. * * @param programType The type of program the run records need to validate and update. * @param processedInvalidRunRecordIds the {@link Set} of processed invalid run record ids. */ void validateAndCorrectRunningRunRecords(final ProgramType programType, Set<String> processedInvalidRunRecordIds) { final Map<RunId, RuntimeInfo> runIdToRuntimeInfo = runtimeService.list(programType); LOG.trace("Start getting run records not actually running ..."); List<RunRecordMeta> notActuallyRunning = store.getRuns(ProgramRunStatus.RUNNING, new Predicate<RunRecordMeta>() { @Override public boolean apply(RunRecordMeta input) { String runId = input.getPid(); // Check if it is not actually running. return !runIdToRuntimeInfo.containsKey(RunIds.fromString(runId)); } }); LOG.trace("End getting {} run records not actually running.", notActuallyRunning.size()); final Map<String, ProgramId> runIdToProgramId = new HashMap<>(); LOG.trace("Start getting invalid run records ..."); Collection<RunRecordMeta> invalidRunRecords = Collections2.filter(notActuallyRunning, new Predicate<RunRecordMeta>() { @Override public boolean apply(RunRecordMeta input) { String runId = input.getPid(); // check for program Id for the run record, if null then it is invalid program type. ProgramId targetProgramId = retrieveProgramIdForRunRecord(programType, runId); // Check if run id is for the right program type if (targetProgramId != null) { runIdToProgramId.put(runId, targetProgramId); return true; } else { return false; } } }); LOG.trace("End getting invalid run records."); if (!invalidRunRecords.isEmpty()) { LOG.warn("Found {} RunRecords with RUNNING status but the program is not actually running for program type {}", invalidRunRecords.size(), programType.getPrettyName()); } else { LOG.trace("No RunRecords found with RUNNING status but the program is not actually running for program type {}", programType.getPrettyName()); } // Now lets correct the invalid RunRecords for (RunRecordMeta invalidRunRecordMeta : invalidRunRecords) { boolean shouldCorrect = shouldCorrectForWorkflowChildren(invalidRunRecordMeta, processedInvalidRunRecordIds); if (!shouldCorrect) { LOG.trace("Will not correct invalid run record {} since it's parent workflow still running.", invalidRunRecordMeta); continue; } String runId = invalidRunRecordMeta.getPid(); ProgramId targetProgramId = runIdToProgramId.get(runId); LOG.warn("Fixing RunRecord {} in program {} of type {} with RUNNING status but the program is not running", runId, targetProgramId, programType.getPrettyName()); store.compareAndSetStatus(targetProgramId.toId(), runId, ProgramController.State.ALIVE.getRunStatus(), ProgramController.State.ERROR.getRunStatus()); processedInvalidRunRecordIds.add(runId); } } /** * Helper method to check if the run record is a child program of a Workflow * * @param runRecordMeta The target {@link RunRecordMeta} to check * @param processedInvalidRunRecordIds the {@link Set} of processed invalid run record ids. * @return {@code true} of we should check and {@code false} otherwise */ private boolean shouldCorrectForWorkflowChildren(RunRecordMeta runRecordMeta, Set<String> processedInvalidRunRecordIds) { // check if it is part of workflow because it may not have actual runtime info if (runRecordMeta.getProperties() != null && runRecordMeta.getProperties().get("workflowrunid") != null) { // Get the parent Workflow info String workflowRunId = runRecordMeta.getProperties().get("workflowrunid"); if (!processedInvalidRunRecordIds.contains(workflowRunId)) { // If the parent workflow has not been processed, then check if it still valid ProgramId workflowProgramId = retrieveProgramIdForRunRecord(ProgramType.WORKFLOW, workflowRunId); if (workflowProgramId != null) { // lets see if the parent workflow run records state is still running RunRecordMeta wfRunRecord = store.getRun(workflowProgramId.toId(), workflowRunId); RuntimeInfo wfRuntimeInfo = runtimeService.lookup(workflowProgramId.toId(), RunIds.fromString(workflowRunId)); // Check of the parent workflow run record exists and it is running and runtime info said it is still there // then do not update it if (wfRunRecord != null && wfRunRecord.getStatus() == ProgramRunStatus.RUNNING && wfRuntimeInfo != null) { return false; } } } } return true; } /** * Helper method to get {@link ProgramId} for a RunRecord for type of program * * @param programType Type of program to search * @param runId The target id of the {@link RunRecord} to find * @return the program id of the run record or {@code null} if does not exist. */ @Nullable private ProgramId retrieveProgramIdForRunRecord(ProgramType programType, String runId) { // Get list of namespaces (borrow logic from AbstractAppFabricHttpHandler#listPrograms) List<NamespaceMeta> namespaceMetas = nsStore.list(); // For each, get all programs under it ProgramId targetProgramId = null; for (NamespaceMeta nm : namespaceMetas) { NamespaceId namespace = Ids.namespace(nm.getName()); Collection<ApplicationSpecification> appSpecs = store.getAllApplications(namespace.toId()); // For each application get the programs checked against run records for (ApplicationSpecification appSpec : appSpecs) { switch (programType) { case FLOW: for (String programName : appSpec.getFlows().keySet()) { ProgramId programId = validateProgramForRunRecord(nm.getName(), appSpec.getName(), programType, programName, runId); if (programId != null) { targetProgramId = programId; break; } } break; case MAPREDUCE: for (String programName : appSpec.getMapReduce().keySet()) { ProgramId programId = validateProgramForRunRecord(nm.getName(), appSpec.getName(), programType, programName, runId); if (programId != null) { targetProgramId = programId; break; } } break; case SPARK: for (String programName : appSpec.getSpark().keySet()) { ProgramId programId = validateProgramForRunRecord(nm.getName(), appSpec.getName(), programType, programName, runId); if (programId != null) { targetProgramId = programId; break; } } break; case SERVICE: for (String programName : appSpec.getServices().keySet()) { ProgramId programId = validateProgramForRunRecord(nm.getName(), appSpec.getName(), programType, programName, runId); if (programId != null) { targetProgramId = programId; break; } } break; case WORKER: for (String programName : appSpec.getWorkers().keySet()) { ProgramId programId = validateProgramForRunRecord(nm.getName(), appSpec.getName(), programType, programName, runId); if (programId != null) { targetProgramId = programId; break; } } break; case WORKFLOW: for (String programName : appSpec.getWorkflows().keySet()) { ProgramId programId = validateProgramForRunRecord(nm.getName(), appSpec.getName(), programType, programName, runId); if (programId != null) { targetProgramId = programId; break; } } break; default: LOG.debug("Unknown program type: " + programType.name()); break; } if (targetProgramId != null) { break; } } if (targetProgramId != null) { break; } } return targetProgramId; } /** * Helper method to get program id for a run record if it exists in the store. * * @return instance of {@link ProgramId} if exist for the runId or null if does not */ @Nullable private ProgramId validateProgramForRunRecord(String namespaceName, String appName, ProgramType programType, String programName, String runId) { ProgramId programId = Ids.namespace(namespaceName).app(appName).program(programType, programName); RunRecordMeta runRecord = store.getRun(programId.toId(), runId); if (runRecord == null) { return null; } return programId; } /** * Helper class to run in separate thread to validate the invalid running run records */ private static class RunRecordsCorrectorRunnable implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(RunRecordsCorrectorRunnable.class); private final ProgramLifecycleService programLifecycleService; public RunRecordsCorrectorRunnable(ProgramLifecycleService programLifecycleService) { this.programLifecycleService = programLifecycleService; } @Override public void run() { try { RunRecordsCorrectorRunnable.LOG.debug("Start correcting invalid run records ..."); // Lets update the running programs run records programLifecycleService.validateAndCorrectRunningRunRecords(); RunRecordsCorrectorRunnable.LOG.debug("End correcting invalid run records."); } catch (Throwable t) { // Ignore any exception thrown since this behaves like daemon thread. //noinspection ThrowableResultOfMethodCallIgnored LOG.warn("Unable to complete correcting run records: {}", Throwables.getRootCause(t).getMessage()); LOG.debug("Exception thrown when running run id cleaner.", t); } } } }
CDAP-5574 dont log unnknown program type for custom action and webapp
cdap-app-fabric/src/main/java/co/cask/cdap/internal/app/services/ProgramLifecycleService.java
CDAP-5574 dont log unnknown program type for custom action and webapp
<ide><path>dap-app-fabric/src/main/java/co/cask/cdap/internal/app/services/ProgramLifecycleService.java <ide> } <ide> } <ide> break; <add> case CUSTOM_ACTION: <add> case WEBAPP: <add> // no-op <add> break; <ide> default: <ide> LOG.debug("Unknown program type: " + programType.name()); <ide> break;
Java
apache-2.0
a5d6a9b78988f67e2adca7a90a56397c8b459418
0
kaaholst/android-squeezer
/* * Copyright (c) 2011 Kurt Aaholst <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.org.ngo.squeezer.model; import android.content.Context; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.net.Uri; import android.os.Parcel; import android.text.TextUtils; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.StringRes; import androidx.appcompat.content.res.AppCompatResources; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import uk.org.ngo.squeezer.R; import uk.org.ngo.squeezer.Squeezer; import uk.org.ngo.squeezer.Util; public class JiveItem extends Item { private static final String TAG = "JiveItem"; public static final JiveItem HOME = new JiveItem("home", null, R.string.HOME, 1, Window.WindowStyle.HOME_MENU); public static final JiveItem CURRENT_PLAYLIST = new JiveItem("status", null, R.string.menu_item_playlist, 1, Window.WindowStyle.PLAY_LIST); public static final JiveItem EXTRAS = new JiveItem("extras", "home", R.string.EXTRAS, 50, Window.WindowStyle.HOME_MENU); public static final JiveItem SETTINGS = new JiveItem("settings", "home", R.string.SETTINGS, 1005, Window.WindowStyle.HOME_MENU); public static final JiveItem ADVANCED_SETTINGS = new JiveItem("advancedSettings", "settings", R.string.ADVANCED_SETTINGS, 105, Window.WindowStyle.TEXT_ONLY); public static final JiveItem ARCHIVE = new JiveItem("archiveNode", "home", R.string.ARCHIVE_NODE, 2000, Window.WindowStyle.HOME_MENU); /** * Information that will be requested about songs. * <p> * a:artist artist name<br/> * C:compilation (1 if true, missing otherwise)<br/> * j:coverart (1 if available, missing otherwise)<br/> * J:artwork_track_id (if available, missing otherwise)<br/> * K:artwork_url URL to remote artwork<br/> * l:album album name<br/> * t:tracknum, if known<br/> * u:url Song file url<br/> * x:remote 1, if this is a remote track<br/> */ private static final String SONG_TAGS = "aCjJKltux"; public static final Creator<JiveItem> CREATOR = new Creator<JiveItem>() { @Override public JiveItem[] newArray(int size) { return new JiveItem[size]; } @Override public JiveItem createFromParcel(Parcel source) { return new JiveItem(source); } }; private JiveItem(String id, String node, @StringRes int text, int weight, Window.WindowStyle windowStyle) { this(record(id, node, text, weight)); window = new Window(); window.windowStyle = windowStyle; } private static Map<String, Object> record(String id, String node, @StringRes int text, int weight) { Map<String, Object> record = new HashMap<>(); record.put("id", id); record.put("node", node); record.put("name", Squeezer.getContext().getString(text)); record.put("weight", weight); return record; } private String id; @NonNull private String name; public String text2; @NonNull private final Uri icon; private String node; private String originalNode; private int weight; private String type; public Action.NextWindow nextWindow; public Input input; public String inputValue; public Window window; public boolean doAction; public Action goAction; public Action playAction; public Action addAction; public Action insertAction; public Action moreAction; public List<JiveItem> subItems; public boolean showBigArtwork; public int selectedIndex; public String[] choiceStrings; public Boolean checkbox; public Map<Boolean, Action> checkboxActions; public Boolean radio; public Slider slider; private SlimCommand downloadCommand; public JiveItem() { name = ""; icon = Uri.EMPTY; } public void setId(String id) { this.id = id; } public String getId() { return id; } @NonNull public String getName() { return name; } public void setName(@NonNull String name) { this.name = name; } /** The URL to use to download the icon. */ @NonNull public Uri getIcon() { if (icon.equals(Uri.EMPTY) && window != null) { return window.icon; } return icon; } /** * @return Whether the song has downloadable artwork associated with it. */ public boolean hasIconUri() { return !getIcon().equals(Uri.EMPTY); } /** * @return Whether the song has an icon associated with it. */ public boolean hasIcon() { return !(!hasIconUri() && getItemIcon() == null && getSlimIcon() == null); } /** * @return Icon resource for this item if it is embedded in the Squeezer app, or an empty icon. */ public Drawable getIconDrawable(Context context) { return getIconDrawable(context, R.drawable.icon_pending_artwork); } /** * @return Icon resource for this item if it is embedded in the Squeezer app, or the supplied default icon. */ public Drawable getIconDrawable(Context context, @DrawableRes int defaultIcon) { @DrawableRes Integer foreground = getItemIcon(); if (foreground != null) { Drawable background = AppCompatResources.getDrawable(context, R.drawable.icon_background); Drawable icon = AppCompatResources.getDrawable(context, foreground); return new LayerDrawable(new Drawable[]{background, icon}); } Integer slimIcon = getSlimIcon(); return AppCompatResources.getDrawable(context, slimIcon != null ? slimIcon : defaultIcon); } @DrawableRes private Integer getSlimIcon() { return slimIcons.get(id); } private static final Map<String, Integer> slimIcons = initializeSlimIcons(); private static Map<String, Integer> initializeSlimIcons() { Map<String, Integer> result = new HashMap<>(); result.put("myMusic", R.drawable.icon_mymusic); result.put("myMusicArtists", R.drawable.icon_ml_artists); result.put("myMusicGenres", R.drawable.icon_ml_genres); result.put("myMusicYears", R.drawable.icon_ml_years); result.put("myMusicNewMusic", R.drawable.icon_ml_new_music); result.put("extras", R.drawable.icon_settings_adv); result.put("settings", R.drawable.icon_settings); result.put("settingsAlarm", R.drawable.icon_alarm); result.put("appletCustomizeHome", R.drawable.icon_settings_home); result.put("settingsPlayerNameChange", R.drawable.icon_settings_name); result.put("advancedSettings", R.drawable.icon_settings_adv); // result.put("archive", R.drawable.icon_settings); // TODO: Icon for Archive return result; } @DrawableRes private Integer getItemIcon() { return itemIcons.get(id); } private static final Map<String, Integer> itemIcons = initializeItemIcons(); private static Map<String, Integer> initializeItemIcons() { Map<String, Integer> result = new HashMap<>(); result.put("radio", R.drawable.internet_radio); result.put("radios", R.drawable.internet_radio); result.put("favorites", R.drawable.favorites); result.put("globalSearch", R.drawable.search); result.put("homeSearchRecent", R.drawable.search); result.put("playerpower", R.drawable.power); result.put("myMusicSearch", R.drawable.search); result.put("myMusicSearchArtists", R.drawable.search); result.put("myMusicSearchAlbums", R.drawable.search); result.put("myMusicSearchSongs", R.drawable.search); result.put("myMusicSearchPlaylists", R.drawable.search); result.put("myMusicSearchRecent", R.drawable.search); result.put("myMusicAlbums", R.drawable.ml_albums); result.put("myMusicMusicFolder", R.drawable.ml_folder); result.put("myMusicPlaylists", R.drawable.ml_playlist); result.put("randomplay", R.drawable.ml_random); result.put("settingsShuffle", R.drawable.shuffle); result.put("settingsRepeat", R.drawable.settings_repeat); result.put("settingsAudio", R.drawable.settings_audio); result.put("settingsFixedVolume", R.drawable.settings_audio); result.put("settingsXfade", R.drawable.settings_audio); result.put("settingsReplayGain", R.drawable.settings_audio); result.put("settingsSleep", R.drawable.settings_sleep); result.put("settingsSync", R.drawable.settings_sync); return result; } public String getNode() { return node; } public int getWeight() { return weight; } public String getType() { return type; } public boolean isSelectable() { return (goAction != null || nextWindow != null || hasSubItems()|| node != null || checkbox != null); } public boolean hasContextMenu() { return (playAction != null || addAction != null || insertAction != null || moreAction != null || checkbox != null || radio != null); } public JiveItem(Map<String, Object> record) { setId(getString(record, record.containsKey("cmd") ? "cmd" : "id")); splitItemText(getStringOrEmpty(record, record.containsKey("name") ? "name" : "text")); icon = getImageUrl(record, record.containsKey("icon-id") ? "icon-id" : "icon"); node = originalNode = getString(record, "node"); weight = getInt(record, "weight"); type = getString(record, "type"); Map<String, Object> baseRecord = getRecord(record, "base"); Map<String, Object> baseActions = (baseRecord != null ? getRecord(baseRecord, "actions") : null); Map<String, Object> baseWindow = (baseRecord != null ? getRecord(baseRecord, "window") : null); Map<String, Object> actionsRecord = getRecord(record, "actions"); nextWindow = Action.NextWindow.fromString(getString(record, "nextWindow")); input = extractInput(getRecord(record, "input")); window = extractWindow(getRecord(record, "window"), baseWindow); // do takes precedence over go goAction = extractAction("do", baseActions, actionsRecord, record, baseRecord); doAction = (goAction != null); if (goAction == null) { // check if item instructs us to use a different action String goActionName = record.containsKey("goAction") ? getString(record, "goAction") : "go"; goAction = extractAction(goActionName, baseActions, actionsRecord, record, baseRecord); } playAction = extractAction("play", baseActions, actionsRecord, record, baseRecord); addAction = extractAction("add", baseActions, actionsRecord, record, baseRecord); insertAction = extractAction("add-hold", baseActions, actionsRecord, record, baseRecord); moreAction = extractAction("more", baseActions, actionsRecord, record, baseRecord); if (moreAction != null) { moreAction.action.params.put("xmlBrowseInterimCM", 1); } downloadCommand = extractDownloadAction(record); subItems = extractSubItems((Object[]) record.get("item_loop")); showBigArtwork = record.containsKey("showBigArtwork"); selectedIndex = getInt(record, "selectedIndex"); choiceStrings = Util.getStringArray(record, "choiceStrings"); if (goAction != null && goAction.action != null && goAction.action.cmd.size() == 0) { doAction = true; } if (record.containsKey("checkbox")) { checkbox = (getInt(record, "checkbox") != 0); checkboxActions = new HashMap<>(); checkboxActions.put(true, extractAction("on", baseActions, actionsRecord, record, baseRecord)); checkboxActions.put(false, extractAction("off", baseActions, actionsRecord, record, baseRecord)); } if (record.containsKey("radio")) { radio = (getInt(record, "radio") != 0); } if (record.containsKey("slider")) { slider = new Slider(); slider.min = getInt(record, "min"); slider.max = getInt(record, "max"); slider.adjust = getInt(record, "adjust"); slider.initial = getInt(record, "initial"); slider.sliderIcons = getString(record, "sliderIcons"); slider.help = getString(record, "help"); } } public JiveItem(Parcel source) { setId(source.readString()); name = source.readString(); text2 = source.readString(); icon = Uri.parse(source.readString()); node = source.readString(); weight = source.readInt(); type = source.readString(); nextWindow = Action.NextWindow.fromString(source.readString()); input = Input.readFromParcel(source); window = source.readParcelable(getClass().getClassLoader()); goAction = source.readParcelable(getClass().getClassLoader()); playAction = source.readParcelable(getClass().getClassLoader()); addAction = source.readParcelable(getClass().getClassLoader()); insertAction = source.readParcelable(getClass().getClassLoader()); moreAction = source.readParcelable(getClass().getClassLoader()); subItems = source.createTypedArrayList(JiveItem.CREATOR); doAction = (source.readByte() != 0); showBigArtwork = (source.readByte() != 0); selectedIndex = source.readInt(); choiceStrings = source.createStringArray(); checkbox = (Boolean) source.readValue(getClass().getClassLoader()); if (checkbox != null) { checkboxActions = new HashMap<>(); checkboxActions.put(true, (Action) source.readParcelable(getClass().getClassLoader())); checkboxActions.put(false, (Action) source.readParcelable(getClass().getClassLoader())); } radio = (Boolean) source.readValue(getClass().getClassLoader()); slider = source.readParcelable(getClass().getClassLoader()); downloadCommand = source.readParcelable(getClass().getClassLoader()); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(getId()); dest.writeString(name); dest.writeString(text2); dest.writeString(icon.toString()); dest.writeString(node); dest.writeInt(weight); dest.writeString(type); dest.writeString(nextWindow == null ? null : nextWindow.toString()); Input.writeToParcel(dest, input); dest.writeParcelable(window, flags); dest.writeParcelable(goAction, flags); dest.writeParcelable(playAction, flags); dest.writeParcelable(addAction, flags); dest.writeParcelable(insertAction, flags); dest.writeParcelable(moreAction, flags); dest.writeTypedList(subItems); dest.writeByte((byte) (doAction ? 1 : 0)); dest.writeByte((byte) (showBigArtwork ? 1 : 0)); dest.writeInt(selectedIndex); dest.writeStringArray(choiceStrings); dest.writeValue(checkbox); if (checkbox != null) { dest.writeParcelable(checkboxActions.get(true), flags); dest.writeParcelable(checkboxActions.get(false), flags); } dest.writeValue(radio); dest.writeParcelable(slider, flags); dest.writeParcelable(downloadCommand, flags); } public boolean hasInput() { return hasInputField() || hasChoices(); } public boolean hasInputField() { return (input != null); } public boolean hasChoices() { return (choiceStrings.length > 0); } public boolean hasSlider() { return (slider != null); } public boolean isInputReady() { return !TextUtils.isEmpty(inputValue); } public boolean hasSubItems() { return (subItems != null); } public boolean canDownload() { return downloadCommand != null; } public SlimCommand downloadCommand() { return downloadCommand; } @Override public int describeContents() { return 0; } @Override public int hashCode() { return (getId() != null ? getId().hashCode() : 0); } private String toStringOpen() { return getClass().getSimpleName() + " { id: " + getId() + ", name: " + getName() + ", node: " + node + ", weight: " + getWeight() + ", go: " + goAction + ", play: " + playAction + ", add: " + addAction + ", insert: " + insertAction + ", more: " + moreAction + ", window: " + window + ", originalNode: " + originalNode; } @NonNull @Override public String toString() { return toStringOpen() + " }"; } private void splitItemText(String text) { // This happens enough for regular expressions to be ineffective int nameEnd = text.indexOf('\n'); if (nameEnd > 0) { name = text.substring(0, nameEnd); text2 = text.substring(nameEnd+1); } else { name = text; text2 = ""; } } public static Window extractWindow(Map<String, Object> itemWindow, Map<String, Object> baseWindow) { if (itemWindow == null && baseWindow == null) return null; Map<String, Object> params = new HashMap<>(); if (baseWindow != null) params.putAll(baseWindow); if (itemWindow != null) params.putAll(itemWindow); Window window = new Window(); window.windowId = getString(params, "windowId"); window.text = getString(params, "text"); window.textarea = getStringOrEmpty(params, "textarea").replaceAll("\\\\n", "\n"); window.textareaToken = getString(params, "textAreaToken"); window.help = getString(params, "help"); window.icon = getImageUrl(params, params.containsKey("icon-id") ? "icon-id" : "icon"); window.titleStyle = getString(params, "titleStyle"); String menuStyle = getString(params, "menuStyle"); String windowStyle = getString(params, "windowStyle"); window.windowStyle = Window.WindowStyle.get(windowStyle); if (window.windowStyle == null) { window.windowStyle = menu2window.get(menuStyle); if (window.windowStyle == null) { window.windowStyle = Window.WindowStyle.TEXT_ONLY; } } return window; } /** * legacy map of menuStyles to windowStyles * <p> * make an educated guess at window style when one is not sent but a menu style is */ private static final Map<String, Window.WindowStyle> menu2window = initializeMenu2Window(); private static Map<String, Window.WindowStyle> initializeMenu2Window() { Map<String, Window.WindowStyle> result = new HashMap<>(); result.put("album", Window.WindowStyle.ICON_LIST); result.put("playlist", Window.WindowStyle.PLAY_LIST); return result; } private Input extractInput(Map<String, Object> record) { if (record == null) return null; Input input = new Input(); input.len = getInt(record, "len"); input.softbutton1 = getString(record, "softbutton1"); input.softbutton2 = getString(record, "softbutton2"); input.inputStyle = getString(record, "_inputStyle"); input.title = getString(record, "title"); input.initialText = getString(record, "initialText"); input.allowedChars = getString(record, "allowedChars"); Map<String, Object> helpRecord = getRecord(record, "help"); if (helpRecord != null) { input.help = new HelpText(); input.help.text = getString(helpRecord, "text"); input.help.token = getString(helpRecord, "token"); } return input; } private Action extractAction(String actionName, Map<String, Object> baseActions, Map<String, Object> itemActions, Map<String, Object> record, Map<String, Object> baseRecord) { Map<String, Object> actionRecord = null; Map<String, Object> itemParams = null; Object itemAction = (itemActions != null ? itemActions.get(actionName) : null); if (itemAction instanceof Map) { actionRecord = (Map<String, Object>) itemAction; } if (actionRecord == null && baseActions != null) { Map<String, Object> baseAction = getRecord(baseActions, actionName); if (baseAction != null) { String itemsParams = (String) baseAction.get("itemsParams"); if (itemsParams != null) { itemParams = getRecord(record, itemsParams); if (itemParams != null) { actionRecord = baseAction; } } } } if (actionRecord == null) return null; Action actionHolder = new Action(); if (actionRecord.containsKey("choices")) { Object[] choices = (Object[]) actionRecord.get("choices"); actionHolder.choices = new Action.JsonAction[choices.length]; for (int i = 0; i < choices.length; i++) { actionRecord = (Map<String, Object>) choices[i]; actionHolder.choices[i]= extractJsonAction(baseRecord, actionRecord, itemParams); } } else { actionHolder.action = extractJsonAction(baseRecord, actionRecord, itemParams); } return actionHolder; } private Action.JsonAction extractJsonAction(Map<String, Object> baseRecord, Map<String, Object> actionRecord, Map<String, Object> itemParams) { Action.JsonAction action = new Action.JsonAction(); action.nextWindow = Action.NextWindow.fromString(getString(actionRecord, "nextWindow")); if (action.nextWindow == null) action.nextWindow = nextWindow; if (action.nextWindow == null && baseRecord != null) action.nextWindow = Action.NextWindow.fromString(getString(baseRecord, "nextWindow")); action.cmd(Util.getStringArray(actionRecord, "cmd")); Map<String, Object> params = getRecord(actionRecord, "params"); if (params != null) { action.params(params); } if (itemParams != null) { action.params(itemParams); } action.param("useContextMenu", "1"); Map<String, Object> windowRecord = getRecord(actionRecord, "window"); if (windowRecord != null) { action.window = new Action.ActionWindow(getInt(windowRecord, "isContextMenu") != 0); } // LMS may send isContextMenu in the itemParams, but this is ignored by squeezeplay, so we must do the same. action.isContextMenu = (params != null && params.containsKey("isContextMenu")) || (action.window != null && action.window.isContextMenu); return action; } private List<JiveItem> extractSubItems(Object[] item_loop) { if (item_loop != null) { List<JiveItem> items = new ArrayList<>(); for (Object item_d : item_loop) { Map<String, Object> record = (Map<String, Object>) item_d; items.add(new JiveItem(record)); } return items; } return null; } private SlimCommand extractDownloadAction(Map<String, Object> record) { if ("local".equals(getString(record, "trackType")) && (goAction != null || moreAction != null)) { Action action = (moreAction != null ? moreAction : goAction); String trackId = getStringOrEmpty(action.action.params, "track_id"); return new SlimCommand() .cmd("titles") .param("tags", SONG_TAGS) .param("track_id", trackId); } else if (playAction != null && Collections.singletonList("playlistcontrol").equals(playAction.action.cmd) && "load".equals(playAction.action.params.get("cmd"))) { if (playAction.action.params.containsKey("folder_id")) { return new SlimCommand() .cmd("musicfolder") .param("tags", "cu") .param("recursive", "1") .param("folder_id", playAction.action.params.get("folder_id")); } else if (playAction.action.params.containsKey("playlist_id")) { return new SlimCommand() .cmd("playlists", "tracks") .param("tags", SONG_TAGS) .param("playlist_id", playAction.action.params.get("playlist_id")); } else { return new SlimCommand() .cmd("titles") .param("tags", SONG_TAGS) .params(getTitlesParams(playAction.action)); } } return null; } public static SlimCommand downloadCommand(String id) { return new SlimCommand() .cmd("titles") .param("tags", SONG_TAGS) .param("track_id", id); } /** * Get parameters which can be used in a titles command from the supplied action */ private Map<String,Object> getTitlesParams(SlimCommand action) { Map<String, Object> map = new HashMap<>(); for (Map.Entry<String, Object> e : action.params.entrySet()) { if (title_parameters.contains(e.getKey()) && e.getValue() != null) { map.put(e.getKey(), e.getValue()); } } return map; } private static final Set<String> title_parameters = new HashSet<>(Arrays.asList("track_id", "album_id", "artist_id", "genre_id", "year")); public void setNode(String node) { this.node = node; } public String getOriginalNode() { return this.originalNode; } }
Squeezer/src/main/java/uk/org/ngo/squeezer/model/JiveItem.java
/* * Copyright (c) 2011 Kurt Aaholst <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.org.ngo.squeezer.model; import android.content.Context; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.net.Uri; import android.os.Parcel; import android.text.TextUtils; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.StringRes; import androidx.appcompat.content.res.AppCompatResources; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import uk.org.ngo.squeezer.R; import uk.org.ngo.squeezer.Squeezer; import uk.org.ngo.squeezer.Util; public class JiveItem extends Item { private static final String TAG = "JiveItem"; public static final JiveItem HOME = new JiveItem("home", null, R.string.HOME, 1, Window.WindowStyle.HOME_MENU); public static final JiveItem CURRENT_PLAYLIST = new JiveItem("status", null, R.string.menu_item_playlist, 1, Window.WindowStyle.PLAY_LIST); public static final JiveItem EXTRAS = new JiveItem("extras", "home", R.string.EXTRAS, 50, Window.WindowStyle.HOME_MENU); public static final JiveItem SETTINGS = new JiveItem("settings", "home", R.string.SETTINGS, 1005, Window.WindowStyle.HOME_MENU); public static final JiveItem ADVANCED_SETTINGS = new JiveItem("advancedSettings", "settings", R.string.ADVANCED_SETTINGS, 105, Window.WindowStyle.TEXT_ONLY); public static final JiveItem ARCHIVE = new JiveItem("archiveNode", "home", R.string.ARCHIVE_NODE, 1, Window.WindowStyle.HOME_MENU); public static final JiveItem CUSTOM = new JiveItem("customNode", "home", R.string.CUSTOM_NODE, 1010, Window.WindowStyle.HOME_MENU); /** * Information that will be requested about songs. * <p> * a:artist artist name<br/> * C:compilation (1 if true, missing otherwise)<br/> * j:coverart (1 if available, missing otherwise)<br/> * J:artwork_track_id (if available, missing otherwise)<br/> * K:artwork_url URL to remote artwork<br/> * l:album album name<br/> * t:tracknum, if known<br/> * u:url Song file url<br/> * x:remote 1, if this is a remote track<br/> */ private static final String SONG_TAGS = "aCjJKltux"; public static final Creator<JiveItem> CREATOR = new Creator<JiveItem>() { @Override public JiveItem[] newArray(int size) { return new JiveItem[size]; } @Override public JiveItem createFromParcel(Parcel source) { return new JiveItem(source); } }; private JiveItem(String id, String node, @StringRes int text, int weight, Window.WindowStyle windowStyle) { this(record(id, node, text, weight)); window = new Window(); window.windowStyle = windowStyle; } private static Map<String, Object> record(String id, String node, @StringRes int text, int weight) { Map<String, Object> record = new HashMap<>(); record.put("id", id); record.put("node", node); record.put("name", Squeezer.getContext().getString(text)); record.put("weight", weight); return record; } private String id; @NonNull private String name; public String text2; @NonNull private final Uri icon; private String node; private String originalNode; private int weight; private String type; public Action.NextWindow nextWindow; public Input input; public String inputValue; public Window window; public boolean doAction; public Action goAction; public Action playAction; public Action addAction; public Action insertAction; public Action moreAction; public List<JiveItem> subItems; public boolean showBigArtwork; public int selectedIndex; public String[] choiceStrings; public Boolean checkbox; public Map<Boolean, Action> checkboxActions; public Boolean radio; public Slider slider; private SlimCommand downloadCommand; public JiveItem() { name = ""; icon = Uri.EMPTY; } public void setId(String id) { this.id = id; } public String getId() { return id; } @NonNull public String getName() { return name; } public void setName(@NonNull String name) { this.name = name; } /** The URL to use to download the icon. */ @NonNull public Uri getIcon() { if (icon.equals(Uri.EMPTY) && window != null) { return window.icon; } return icon; } /** * @return Whether the song has downloadable artwork associated with it. */ public boolean hasIconUri() { return !getIcon().equals(Uri.EMPTY); } /** * @return Whether the song has an icon associated with it. */ public boolean hasIcon() { return !(!hasIconUri() && getItemIcon() == null && getSlimIcon() == null); } /** * @return Icon resource for this item if it is embedded in the Squeezer app, or an empty icon. */ public Drawable getIconDrawable(Context context) { return getIconDrawable(context, R.drawable.icon_pending_artwork); } /** * @return Icon resource for this item if it is embedded in the Squeezer app, or the supplied default icon. */ public Drawable getIconDrawable(Context context, @DrawableRes int defaultIcon) { @DrawableRes Integer foreground = getItemIcon(); if (foreground != null) { Drawable background = AppCompatResources.getDrawable(context, R.drawable.icon_background); Drawable icon = AppCompatResources.getDrawable(context, foreground); return new LayerDrawable(new Drawable[]{background, icon}); } Integer slimIcon = getSlimIcon(); return AppCompatResources.getDrawable(context, slimIcon != null ? slimIcon : defaultIcon); } @DrawableRes private Integer getSlimIcon() { return slimIcons.get(id); } private static final Map<String, Integer> slimIcons = initializeSlimIcons(); private static Map<String, Integer> initializeSlimIcons() { Map<String, Integer> result = new HashMap<>(); result.put("myMusic", R.drawable.icon_mymusic); result.put("myMusicArtists", R.drawable.icon_ml_artists); result.put("myMusicGenres", R.drawable.icon_ml_genres); result.put("myMusicYears", R.drawable.icon_ml_years); result.put("myMusicNewMusic", R.drawable.icon_ml_new_music); result.put("extras", R.drawable.icon_settings_adv); result.put("settings", R.drawable.icon_settings); result.put("settingsAlarm", R.drawable.icon_alarm); result.put("appletCustomizeHome", R.drawable.icon_settings_home); result.put("settingsPlayerNameChange", R.drawable.icon_settings_name); result.put("advancedSettings", R.drawable.icon_settings_adv); // result.put("archive", R.drawable.icon_settings); // TODO: Icon for Archive return result; } @DrawableRes private Integer getItemIcon() { return itemIcons.get(id); } private static final Map<String, Integer> itemIcons = initializeItemIcons(); private static Map<String, Integer> initializeItemIcons() { Map<String, Integer> result = new HashMap<>(); result.put("radio", R.drawable.internet_radio); result.put("radios", R.drawable.internet_radio); result.put("favorites", R.drawable.favorites); result.put("globalSearch", R.drawable.search); result.put("homeSearchRecent", R.drawable.search); result.put("playerpower", R.drawable.power); result.put("myMusicSearch", R.drawable.search); result.put("myMusicSearchArtists", R.drawable.search); result.put("myMusicSearchAlbums", R.drawable.search); result.put("myMusicSearchSongs", R.drawable.search); result.put("myMusicSearchPlaylists", R.drawable.search); result.put("myMusicSearchRecent", R.drawable.search); result.put("myMusicAlbums", R.drawable.ml_albums); result.put("myMusicMusicFolder", R.drawable.ml_folder); result.put("myMusicPlaylists", R.drawable.ml_playlist); result.put("randomplay", R.drawable.ml_random); result.put("settingsShuffle", R.drawable.shuffle); result.put("settingsRepeat", R.drawable.settings_repeat); result.put("settingsAudio", R.drawable.settings_audio); result.put("settingsFixedVolume", R.drawable.settings_audio); result.put("settingsXfade", R.drawable.settings_audio); result.put("settingsReplayGain", R.drawable.settings_audio); result.put("settingsSleep", R.drawable.settings_sleep); result.put("settingsSync", R.drawable.settings_sync); return result; } public String getNode() { return node; } public int getWeight() { return weight; } public String getType() { return type; } public boolean isSelectable() { return (goAction != null || nextWindow != null || hasSubItems()|| node != null || checkbox != null); } public boolean hasContextMenu() { return (playAction != null || addAction != null || insertAction != null || moreAction != null || checkbox != null || radio != null); } public JiveItem(Map<String, Object> record) { setId(getString(record, record.containsKey("cmd") ? "cmd" : "id")); splitItemText(getStringOrEmpty(record, record.containsKey("name") ? "name" : "text")); icon = getImageUrl(record, record.containsKey("icon-id") ? "icon-id" : "icon"); node = originalNode = getString(record, "node"); weight = getInt(record, "weight"); type = getString(record, "type"); Map<String, Object> baseRecord = getRecord(record, "base"); Map<String, Object> baseActions = (baseRecord != null ? getRecord(baseRecord, "actions") : null); Map<String, Object> baseWindow = (baseRecord != null ? getRecord(baseRecord, "window") : null); Map<String, Object> actionsRecord = getRecord(record, "actions"); nextWindow = Action.NextWindow.fromString(getString(record, "nextWindow")); input = extractInput(getRecord(record, "input")); window = extractWindow(getRecord(record, "window"), baseWindow); // do takes precedence over go goAction = extractAction("do", baseActions, actionsRecord, record, baseRecord); doAction = (goAction != null); if (goAction == null) { // check if item instructs us to use a different action String goActionName = record.containsKey("goAction") ? getString(record, "goAction") : "go"; goAction = extractAction(goActionName, baseActions, actionsRecord, record, baseRecord); } playAction = extractAction("play", baseActions, actionsRecord, record, baseRecord); addAction = extractAction("add", baseActions, actionsRecord, record, baseRecord); insertAction = extractAction("add-hold", baseActions, actionsRecord, record, baseRecord); moreAction = extractAction("more", baseActions, actionsRecord, record, baseRecord); if (moreAction != null) { moreAction.action.params.put("xmlBrowseInterimCM", 1); } downloadCommand = extractDownloadAction(record); subItems = extractSubItems((Object[]) record.get("item_loop")); showBigArtwork = record.containsKey("showBigArtwork"); selectedIndex = getInt(record, "selectedIndex"); choiceStrings = Util.getStringArray(record, "choiceStrings"); if (goAction != null && goAction.action != null && goAction.action.cmd.size() == 0) { doAction = true; } if (record.containsKey("checkbox")) { checkbox = (getInt(record, "checkbox") != 0); checkboxActions = new HashMap<>(); checkboxActions.put(true, extractAction("on", baseActions, actionsRecord, record, baseRecord)); checkboxActions.put(false, extractAction("off", baseActions, actionsRecord, record, baseRecord)); } if (record.containsKey("radio")) { radio = (getInt(record, "radio") != 0); } if (record.containsKey("slider")) { slider = new Slider(); slider.min = getInt(record, "min"); slider.max = getInt(record, "max"); slider.adjust = getInt(record, "adjust"); slider.initial = getInt(record, "initial"); slider.sliderIcons = getString(record, "sliderIcons"); slider.help = getString(record, "help"); } } public JiveItem(Parcel source) { setId(source.readString()); name = source.readString(); text2 = source.readString(); icon = Uri.parse(source.readString()); node = source.readString(); weight = source.readInt(); type = source.readString(); nextWindow = Action.NextWindow.fromString(source.readString()); input = Input.readFromParcel(source); window = source.readParcelable(getClass().getClassLoader()); goAction = source.readParcelable(getClass().getClassLoader()); playAction = source.readParcelable(getClass().getClassLoader()); addAction = source.readParcelable(getClass().getClassLoader()); insertAction = source.readParcelable(getClass().getClassLoader()); moreAction = source.readParcelable(getClass().getClassLoader()); subItems = source.createTypedArrayList(JiveItem.CREATOR); doAction = (source.readByte() != 0); showBigArtwork = (source.readByte() != 0); selectedIndex = source.readInt(); choiceStrings = source.createStringArray(); checkbox = (Boolean) source.readValue(getClass().getClassLoader()); if (checkbox != null) { checkboxActions = new HashMap<>(); checkboxActions.put(true, (Action) source.readParcelable(getClass().getClassLoader())); checkboxActions.put(false, (Action) source.readParcelable(getClass().getClassLoader())); } radio = (Boolean) source.readValue(getClass().getClassLoader()); slider = source.readParcelable(getClass().getClassLoader()); downloadCommand = source.readParcelable(getClass().getClassLoader()); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(getId()); dest.writeString(name); dest.writeString(text2); dest.writeString(icon.toString()); dest.writeString(node); dest.writeInt(weight); dest.writeString(type); dest.writeString(nextWindow == null ? null : nextWindow.toString()); Input.writeToParcel(dest, input); dest.writeParcelable(window, flags); dest.writeParcelable(goAction, flags); dest.writeParcelable(playAction, flags); dest.writeParcelable(addAction, flags); dest.writeParcelable(insertAction, flags); dest.writeParcelable(moreAction, flags); dest.writeTypedList(subItems); dest.writeByte((byte) (doAction ? 1 : 0)); dest.writeByte((byte) (showBigArtwork ? 1 : 0)); dest.writeInt(selectedIndex); dest.writeStringArray(choiceStrings); dest.writeValue(checkbox); if (checkbox != null) { dest.writeParcelable(checkboxActions.get(true), flags); dest.writeParcelable(checkboxActions.get(false), flags); } dest.writeValue(radio); dest.writeParcelable(slider, flags); dest.writeParcelable(downloadCommand, flags); } public boolean hasInput() { return hasInputField() || hasChoices(); } public boolean hasInputField() { return (input != null); } public boolean hasChoices() { return (choiceStrings.length > 0); } public boolean hasSlider() { return (slider != null); } public boolean isInputReady() { return !TextUtils.isEmpty(inputValue); } public boolean hasSubItems() { return (subItems != null); } public boolean canDownload() { return downloadCommand != null; } public SlimCommand downloadCommand() { return downloadCommand; } @Override public int describeContents() { return 0; } @Override public int hashCode() { return (getId() != null ? getId().hashCode() : 0); } private String toStringOpen() { return getClass().getSimpleName() + " { id: " + getId() + ", name: " + getName() + ", node: " + node + ", weight: " + getWeight() + ", go: " + goAction + ", play: " + playAction + ", add: " + addAction + ", insert: " + insertAction + ", more: " + moreAction + ", window: " + window + ", originalNode: " + originalNode; } @NonNull @Override public String toString() { return toStringOpen() + " }"; } private void splitItemText(String text) { // This happens enough for regular expressions to be ineffective int nameEnd = text.indexOf('\n'); if (nameEnd > 0) { name = text.substring(0, nameEnd); text2 = text.substring(nameEnd+1); } else { name = text; text2 = ""; } } public static Window extractWindow(Map<String, Object> itemWindow, Map<String, Object> baseWindow) { if (itemWindow == null && baseWindow == null) return null; Map<String, Object> params = new HashMap<>(); if (baseWindow != null) params.putAll(baseWindow); if (itemWindow != null) params.putAll(itemWindow); Window window = new Window(); window.windowId = getString(params, "windowId"); window.text = getString(params, "text"); window.textarea = getStringOrEmpty(params, "textarea").replaceAll("\\\\n", "\n"); window.textareaToken = getString(params, "textAreaToken"); window.help = getString(params, "help"); window.icon = getImageUrl(params, params.containsKey("icon-id") ? "icon-id" : "icon"); window.titleStyle = getString(params, "titleStyle"); String menuStyle = getString(params, "menuStyle"); String windowStyle = getString(params, "windowStyle"); window.windowStyle = Window.WindowStyle.get(windowStyle); if (window.windowStyle == null) { window.windowStyle = menu2window.get(menuStyle); if (window.windowStyle == null) { window.windowStyle = Window.WindowStyle.TEXT_ONLY; } } return window; } /** * legacy map of menuStyles to windowStyles * <p> * make an educated guess at window style when one is not sent but a menu style is */ private static final Map<String, Window.WindowStyle> menu2window = initializeMenu2Window(); private static Map<String, Window.WindowStyle> initializeMenu2Window() { Map<String, Window.WindowStyle> result = new HashMap<>(); result.put("album", Window.WindowStyle.ICON_LIST); result.put("playlist", Window.WindowStyle.PLAY_LIST); return result; } private Input extractInput(Map<String, Object> record) { if (record == null) return null; Input input = new Input(); input.len = getInt(record, "len"); input.softbutton1 = getString(record, "softbutton1"); input.softbutton2 = getString(record, "softbutton2"); input.inputStyle = getString(record, "_inputStyle"); input.title = getString(record, "title"); input.initialText = getString(record, "initialText"); input.allowedChars = getString(record, "allowedChars"); Map<String, Object> helpRecord = getRecord(record, "help"); if (helpRecord != null) { input.help = new HelpText(); input.help.text = getString(helpRecord, "text"); input.help.token = getString(helpRecord, "token"); } return input; } private Action extractAction(String actionName, Map<String, Object> baseActions, Map<String, Object> itemActions, Map<String, Object> record, Map<String, Object> baseRecord) { Map<String, Object> actionRecord = null; Map<String, Object> itemParams = null; Object itemAction = (itemActions != null ? itemActions.get(actionName) : null); if (itemAction instanceof Map) { actionRecord = (Map<String, Object>) itemAction; } if (actionRecord == null && baseActions != null) { Map<String, Object> baseAction = getRecord(baseActions, actionName); if (baseAction != null) { String itemsParams = (String) baseAction.get("itemsParams"); if (itemsParams != null) { itemParams = getRecord(record, itemsParams); if (itemParams != null) { actionRecord = baseAction; } } } } if (actionRecord == null) return null; Action actionHolder = new Action(); if (actionRecord.containsKey("choices")) { Object[] choices = (Object[]) actionRecord.get("choices"); actionHolder.choices = new Action.JsonAction[choices.length]; for (int i = 0; i < choices.length; i++) { actionRecord = (Map<String, Object>) choices[i]; actionHolder.choices[i]= extractJsonAction(baseRecord, actionRecord, itemParams); } } else { actionHolder.action = extractJsonAction(baseRecord, actionRecord, itemParams); } return actionHolder; } private Action.JsonAction extractJsonAction(Map<String, Object> baseRecord, Map<String, Object> actionRecord, Map<String, Object> itemParams) { Action.JsonAction action = new Action.JsonAction(); action.nextWindow = Action.NextWindow.fromString(getString(actionRecord, "nextWindow")); if (action.nextWindow == null) action.nextWindow = nextWindow; if (action.nextWindow == null && baseRecord != null) action.nextWindow = Action.NextWindow.fromString(getString(baseRecord, "nextWindow")); action.cmd(Util.getStringArray(actionRecord, "cmd")); Map<String, Object> params = getRecord(actionRecord, "params"); if (params != null) { action.params(params); } if (itemParams != null) { action.params(itemParams); } action.param("useContextMenu", "1"); Map<String, Object> windowRecord = getRecord(actionRecord, "window"); if (windowRecord != null) { action.window = new Action.ActionWindow(getInt(windowRecord, "isContextMenu") != 0); } // LMS may send isContextMenu in the itemParams, but this is ignored by squeezeplay, so we must do the same. action.isContextMenu = (params != null && params.containsKey("isContextMenu")) || (action.window != null && action.window.isContextMenu); return action; } private List<JiveItem> extractSubItems(Object[] item_loop) { if (item_loop != null) { List<JiveItem> items = new ArrayList<>(); for (Object item_d : item_loop) { Map<String, Object> record = (Map<String, Object>) item_d; items.add(new JiveItem(record)); } return items; } return null; } private SlimCommand extractDownloadAction(Map<String, Object> record) { if ("local".equals(getString(record, "trackType")) && (goAction != null || moreAction != null)) { Action action = (moreAction != null ? moreAction : goAction); String trackId = getStringOrEmpty(action.action.params, "track_id"); return new SlimCommand() .cmd("titles") .param("tags", SONG_TAGS) .param("track_id", trackId); } else if (playAction != null && Collections.singletonList("playlistcontrol").equals(playAction.action.cmd) && "load".equals(playAction.action.params.get("cmd"))) { if (playAction.action.params.containsKey("folder_id")) { return new SlimCommand() .cmd("musicfolder") .param("tags", "cu") .param("recursive", "1") .param("folder_id", playAction.action.params.get("folder_id")); } else if (playAction.action.params.containsKey("playlist_id")) { return new SlimCommand() .cmd("playlists", "tracks") .param("tags", SONG_TAGS) .param("playlist_id", playAction.action.params.get("playlist_id")); } else { return new SlimCommand() .cmd("titles") .param("tags", SONG_TAGS) .params(getTitlesParams(playAction.action)); } } return null; } public static SlimCommand downloadCommand(String id) { return new SlimCommand() .cmd("titles") .param("tags", SONG_TAGS) .param("track_id", id); } /** * Get parameters which can be used in a titles command from the supplied action */ private Map<String,Object> getTitlesParams(SlimCommand action) { Map<String, Object> map = new HashMap<>(); for (Map.Entry<String, Object> e : action.params.entrySet()) { if (title_parameters.contains(e.getKey()) && e.getValue() != null) { map.put(e.getKey(), e.getValue()); } } return map; } private static final Set<String> title_parameters = new HashSet<>(Arrays.asList("track_id", "album_id", "artist_id", "genre_id", "year")); public void setNode(String node) { this.node = node; } public String getOriginalNode() { return this.originalNode; } }
Removed custom node & reset archive weight
Squeezer/src/main/java/uk/org/ngo/squeezer/model/JiveItem.java
Removed custom node & reset archive weight
<ide><path>queezer/src/main/java/uk/org/ngo/squeezer/model/JiveItem.java <ide> public static final JiveItem EXTRAS = new JiveItem("extras", "home", R.string.EXTRAS, 50, Window.WindowStyle.HOME_MENU); <ide> public static final JiveItem SETTINGS = new JiveItem("settings", "home", R.string.SETTINGS, 1005, Window.WindowStyle.HOME_MENU); <ide> public static final JiveItem ADVANCED_SETTINGS = new JiveItem("advancedSettings", "settings", R.string.ADVANCED_SETTINGS, 105, Window.WindowStyle.TEXT_ONLY); <del> public static final JiveItem ARCHIVE = new JiveItem("archiveNode", "home", R.string.ARCHIVE_NODE, 1, Window.WindowStyle.HOME_MENU); <del> public static final JiveItem CUSTOM = new JiveItem("customNode", "home", R.string.CUSTOM_NODE, 1010, Window.WindowStyle.HOME_MENU); <add> public static final JiveItem ARCHIVE = new JiveItem("archiveNode", "home", R.string.ARCHIVE_NODE, 2000, Window.WindowStyle.HOME_MENU); <ide> <ide> /** <ide> * Information that will be requested about songs.
JavaScript
mit
4baf5749775c742de13485c1a0d8bd35ab321f0f
0
Jokero/transformer-chain
var validateValue = require('./validateValue'); /** * @param {*} value * @param {Object} config * @param {String[]} path * @param {Object} originalObject * * @returns {Promise} */ module.exports = function validateProperty(value, config, path, originalObject) { var promise; var validators = config.validators; if (config.properties instanceof Object) { validators = Object.assign({ type: 'object' }, validators); } else if (config.items instanceof Object) { validators = Object.assign({ type: 'array' }, validators); } if (validators instanceof Object) { promise = validateValue(value, validators, path, originalObject); } else { promise = Promise.resolve(); } return promise.then(function() { var validateObject = require('./validateObject'); if (config.properties instanceof Object) { return validateObject(value, config.properties, path, originalObject); } else if (value instanceof Array && config.items instanceof Object) { var arrayConfig = {}; value.forEach(function(item, index) { arrayConfig[index] = config.items; }); return validateObject(value, arrayConfig, path, originalObject); } }); };
lib/plugins/validate/validateProperty.js
var validateValue = require('./validateValue'); /** * @param {*} value * @param {Object} config * @param {String[]} path * @param {Object} originalObject * * @returns {Promise} */ module.exports = function validateProperty(value, config, path, originalObject) { var promise; var validators = config.validators; if (config.properties instanceof Object) { validators = Object.assign({}, config.validators); validators.type = 'object'; } else if (config.items instanceof Object) { validators = Object.assign({}, config.validators); validators.type = 'array'; } if (validators instanceof Object) { promise = validateValue(value, validators, path, originalObject); } else { promise = Promise.resolve(); } return promise.then(function() { var validateObject = require('./validateObject'); if (config.properties instanceof Object) { return validateObject(value, config.properties, path, originalObject); } else if (value instanceof Array && config.items instanceof Object) { var arrayConfig = {}; value.forEach(function(item, index) { arrayConfig[index] = config.items; }); return validateObject(value, arrayConfig, path, originalObject); } }); };
more compact
lib/plugins/validate/validateProperty.js
more compact
<ide><path>ib/plugins/validate/validateProperty.js <ide> var validators = config.validators; <ide> <ide> if (config.properties instanceof Object) { <del> validators = Object.assign({}, config.validators); <del> validators.type = 'object'; <add> validators = Object.assign({ type: 'object' }, validators); <ide> } else if (config.items instanceof Object) { <del> validators = Object.assign({}, config.validators); <del> validators.type = 'array'; <add> validators = Object.assign({ type: 'array' }, validators); <ide> } <ide> <ide> if (validators instanceof Object) {
Java
apache-2.0
6bfd682d15dd0eac77d7119a0f8dbe30bc0691bc
0
gpndata/cattle,yasker/cattle,stresler/cattle,kaos/cattle,stresler/cattle,yasker/cattle,rancherio/cattle,dx9/cattle,cjellick/cattle,sonchang/cattle,cjellick/cattle,imikushin/cattle,vincent99/cattle,cloudnautique/cloud-cattle,ubiquityhosting/rancher_cattle,rancherio/cattle,stresler/cattle,willseward/cattle,ubiquityhosting/rancher_cattle,vincent99/cattle,cloudnautique/cloud-cattle,prachidamle/cattle,sonchang/cattle,jimengliu/cattle,prachidamle/cattle,cloudnautique/cattle,rancherio/cattle,alena1108/cattle,jimengliu/cattle,sonchang/cattle,vincent99/cattle,OnePaaS/cattle,hibooboo2/cattle,yasker/cattle,imikushin/cattle,gpndata/cattle,cloudnautique/cattle,alena1108/cattle,wlan0/cattle,gpndata/cattle,willseward/cattle,kaos/cattle,jimengliu/cattle,ubiquityhosting/rancher_cattle,Cerfoglg/cattle,cloudnautique/cattle,imikushin/cattle,prachidamle/cattle,cloudnautique/cloud-cattle,sonchang/cattle,Cerfoglg/cattle,OnePaaS/cattle,Cerfoglg/cattle,dx9/cattle,dx9/cattle,cjellick/cattle,hibooboo2/cattle,hibooboo2/cattle,kaos/cattle,gpndata/cattle,cloudnautique/cloud-cattle,imikushin/cattle,rancher/cattle,OnePaaS/cattle,rancher/cattle,dx9/cattle,alena1108/cattle,willseward/cattle,OnePaaS/cattle,cloudnautique/cattle,rancher/cattle,willseward/cattle,cjellick/cattle,prachidamle/cattle,wlan0/cattle,wlan0/cattle,ubiquityhosting/rancher_cattle
package io.cattle.platform.async.retry.impl; import io.cattle.platform.async.retry.CancelRetryException; import io.cattle.platform.async.retry.Retry; import io.cattle.platform.async.retry.RetryTimeoutService; import io.cattle.platform.async.utils.TimeoutException; import io.cattle.platform.util.concurrent.DelayedObject; import java.util.concurrent.DelayQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import javax.inject.Inject; import org.apache.cloudstack.managed.context.NoExceptionRunnable; import com.google.common.util.concurrent.SettableFuture; public class RetryTimeoutServiceImpl implements RetryTimeoutService { DelayQueue<DelayedObject<Retry>> retryQueue = new DelayQueue<DelayedObject<Retry>>(); ExecutorService executorService; @Override public Object timeout(Future<?> future, long timeout) { return submit(new Retry(0, timeout, future, null)); } @Override public Object submit(Retry retry) { return queue(retry); } public void retry() { DelayedObject<Retry> delayed = retryQueue.poll(); while ( delayed != null ) { final Retry retry = delayed.getObject(); executorService.execute(new Runnable() { @Override public void run() { retry.increment(); if ( retry.getRetryCount() >= retry.getRetries() ) { Future<?> future = retry.getFuture(); if ( future instanceof SettableFuture ) { ((SettableFuture<?>)future).setException(new TimeoutException()); } else { future.cancel(true); } } else { queue(retry); final Runnable run = retry.getRunnable(); if ( run != null ) { new NoExceptionRunnable() { @Override protected void doRun() throws Exception { try { run.run(); } catch ( CancelRetryException e) { completed(retry); } } }.run(); } } } }); delayed = retryQueue.poll(); } } protected DelayedObject<Retry> queue(Retry retry) { DelayedObject<Retry> delayed = new DelayedObject<Retry>(System.currentTimeMillis() + retry.getTimeoutMillis(), retry); retryQueue.add(delayed); return delayed; } @Override public void completed(Object obj) { retryQueue.remove(obj); } public ExecutorService getExecutorService() { return executorService; } @Inject public void setExecutorService(ExecutorService executorService) { this.executorService = executorService; } }
code/framework/async/src/main/java/io/cattle/platform/async/retry/impl/RetryTimeoutServiceImpl.java
package io.cattle.platform.async.retry.impl; import io.cattle.platform.async.retry.CancelRetryException; import io.cattle.platform.async.retry.Retry; import io.cattle.platform.async.retry.RetryTimeoutService; import io.cattle.platform.util.concurrent.DelayedObject; import java.util.concurrent.DelayQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeoutException; import javax.inject.Inject; import org.apache.cloudstack.managed.context.NoExceptionRunnable; import com.google.common.util.concurrent.SettableFuture; public class RetryTimeoutServiceImpl implements RetryTimeoutService { DelayQueue<DelayedObject<Retry>> retryQueue = new DelayQueue<DelayedObject<Retry>>(); ExecutorService executorService; @Override public Object timeout(Future<?> future, long timeout) { return submit(new Retry(0, timeout, future, null)); } @Override public Object submit(Retry retry) { return queue(retry); } public void retry() { DelayedObject<Retry> delayed = retryQueue.poll(); while ( delayed != null ) { final Retry retry = delayed.getObject(); executorService.execute(new Runnable() { @Override public void run() { retry.increment(); if ( retry.getRetryCount() >= retry.getRetries() ) { Future<?> future = retry.getFuture(); if ( future instanceof SettableFuture ) { ((SettableFuture<?>)future).setException(new TimeoutException()); } else { future.cancel(true); } } else { queue(retry); final Runnable run = retry.getRunnable(); if ( run != null ) { new NoExceptionRunnable() { @Override protected void doRun() throws Exception { try { run.run(); } catch ( CancelRetryException e) { completed(retry); } } }.run(); } } } }); delayed = retryQueue.poll(); } } protected DelayedObject<Retry> queue(Retry retry) { DelayedObject<Retry> delayed = new DelayedObject<Retry>(System.currentTimeMillis() + retry.getTimeoutMillis(), retry); retryQueue.add(delayed); return delayed; } @Override public void completed(Object obj) { retryQueue.remove(obj); } public ExecutorService getExecutorService() { return executorService; } @Inject public void setExecutorService(ExecutorService executorService) { this.executorService = executorService; } }
[async] wrong exception being thrown
code/framework/async/src/main/java/io/cattle/platform/async/retry/impl/RetryTimeoutServiceImpl.java
[async] wrong exception being thrown
<ide><path>ode/framework/async/src/main/java/io/cattle/platform/async/retry/impl/RetryTimeoutServiceImpl.java <ide> import io.cattle.platform.async.retry.CancelRetryException; <ide> import io.cattle.platform.async.retry.Retry; <ide> import io.cattle.platform.async.retry.RetryTimeoutService; <add>import io.cattle.platform.async.utils.TimeoutException; <ide> import io.cattle.platform.util.concurrent.DelayedObject; <ide> <ide> import java.util.concurrent.DelayQueue; <ide> import java.util.concurrent.ExecutorService; <ide> import java.util.concurrent.Future; <del>import java.util.concurrent.TimeoutException; <ide> <ide> import javax.inject.Inject; <ide>
JavaScript
isc
ba87a49c1d4903e49496d866f283c057ef153974
0
dmmn/dlib,damienmortini/dlib
import WebSocket from "../utils/WebSocket.js"; import Keyboard from "../input/Keyboard.js"; import GUIInput from "./GUIInput.js"; let staticGUI; // STYLES let style = document.createElement("style"); document.head.appendChild(style); style.sheet.insertRule(` dlib-gui { display: block; position: absolute; resize: horizontal; top: 0; left: 0; width: 250px; padding: 5px; color: white; font-family: monospace; max-height: 100%; box-sizing: border-box; overflow: auto; } `, 0); style.sheet.insertRule(` dlib-gui dlib-guiinput { margin: 5px 0; } `, 0); style.sheet.insertRule(` dlib-gui details details { margin: 10px; } `, 0); style.sheet.insertRule(` dlib-gui details summary { cursor: pointer; } `, 0); style.sheet.insertRule(` dlib-gui details summary:focus { outline: none; } `, 0); // UTILS function componentToHex(c) { let hex = c.toString(16); return hex.length == 1 ? "0" + hex : hex; } function rgbToHex(r, g, b) { return "#" + componentToHex(r * 255) + componentToHex(g * 255) + componentToHex(b * 255); } function hexToRgb(hex) { var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16) / 255, g: parseInt(result[2], 16) / 255, b: parseInt(result[3], 16) / 255 } : null; } function colorFromHex(color, hex) { if (typeof color === "string") { return hex; } let colorValue = hexToRgb(hex); if (color.r !== undefined) { Object.assign(color, colorValue); } else if (color.x !== undefined) { [color.x, color.y, color.z] = [colorValue.r, colorValue.g, colorValue.b]; } else { [color[0], color[1], color[2]] = [colorValue.r, colorValue.g, colorValue.b]; } return color; } function colorToHex(color) { if (typeof color === "string") { return color; } return rgbToHex( color.r !== undefined ? color.r : color.x !== undefined ? color.x : color[0], color.g !== undefined ? color.g : color.y !== undefined ? color.y : color[1], color.b !== undefined ? color.b : color.z !== undefined ? color.z : color[2] ); } function normalizeString(string) { return `${string.toLowerCase().replace(/[^\w-]/g, "")}`; } function urlHashRegExpFromKey(key) { return new RegExp(`([#&]gui/${key}=)([^=&#?]*)`, "g"); } // GUI const GUI_REG_EXP = /([#&]gui=)((%7B|{).*(%7D|}))([&?]*)/; let DATA = {}; (function() { let matches = GUI_REG_EXP.exec(window.location.hash); if (matches) { let string = matches[2]; string = string.replace(/”|%E2%80%9D/g, "%22"); window.location.hash = window.location.hash.replace(GUI_REG_EXP, `$1${string}$5`); DATA = JSON.parse(decodeURI(string)); } })(); export default class GUI extends HTMLElement { static _addStatic() { if (staticGUI) { return; } staticGUI = document.createElement("dlib-gui"); document.body.appendChild(staticGUI); } static add(...params) { GUI._addStatic(); return staticGUI.add(...params); } static get element() { return staticGUI; } static get data() { return DATA; } static set visible(value) { GUI._addStatic(); staticGUI.visible = value; } static get visible() { return staticGUI.visible; } static set open(value) { GUI._addStatic(); staticGUI.open = value; } static get groups() { return staticGUI.groups; } static get open() { return staticGUI.open; } static get update() { return staticGUI.update; } static set serverUrl(value) { GUI._addStatic(); staticGUI.serverUrl = value; } constructor({serverUrl} = {}) { super(); this.serverUrl = serverUrl; this.groups = new Map(); this._inputs = new Map(); this._uids = new Set(); this._container = document.createElement("details"); this._container.innerHTML = "<summary>GUI</summary>"; this.open = true; } set serverUrl(value) { this._serverUrl = value; if(this._webSocket) { this._webSocket.removeEventListener("message", this._onWebSocketMessage); this._webSocket.close(); this._webSocket = null; } if(!this._serverUrl) { return; } this._webSocket = new WebSocket(this._serverUrl); this._onWebSocketMessage = (e) => { let data = JSON.parse(e.data); let input = this._inputs.get(data.uid); if(input._client) { if(input.type === "button") { input.value(); } else { input.value = data.value; } } } this._webSocket.addEventListener("message", this._onWebSocketMessage); } get serverUrl() { return this._serverUrl; } set visible(value) { this.style.display = value ? "" : "none"; } get visible() { return this.style.visibility === "visible"; } update() { for (let input of this._inputs.values()) { input.update(); } } set open(value) { this._container.open = value; } get open() { return this._container.open; } add(object, key, {type, label = key, id = label, group = "", reload = false, remote = false, client = remote, onChange = () => { }, options, max, min, step} = {}) { if(object[key] === null || object[key] === undefined) { console.error(`GUI: ${id} must be defined.`); return; } let idKey = normalizeString(id); let groupKey = normalizeString(group); let uid = groupKey ? `${groupKey}/${idKey}` : idKey; if(this._uids.has(uid)) { console.error(`GUI: An input with id ${id} already exist in the group ${group}`); return; } this._uids.add(uid); if(remote && !this.serverUrl) { this._serverUrl = `wss://${location.hostname}:80`; } type = type || (options ? "select" : ""); if (!type) { switch (typeof object[key]) { case "boolean": type = "checkbox"; break; case "string": type = "text"; break; case "function": type = "button"; break; default: type = typeof object[key]; } } if (!this._container.parentNode) { this.appendChild(this._container); } let container = this._container; if(group) { container = this.groups.get(group); if(!container) { container = document.createElement("details"); container.innerHTML = `<summary>${group}</summary>`; this.groups.set(group, container); this._container.appendChild(container); } } let input = document.createElement("dlib-guiinput"); input.object = type === "color" ? { value: "#000000" } : object; input.key = type === "color" ? "value" : key; input.label = label; input.value = (type === "color" ? colorToHex(object[key]) : object[key]); input._client = client; if (min) { input.min = min; } if (max) { input.max = max; } if (step) { input.step = step; } if (options) { input.options = options; } input.type = type; container.appendChild(input); const SAVED_VALUE = groupKey && DATA[groupKey] ? DATA[groupKey][idKey] : DATA[idKey]; if(SAVED_VALUE !== undefined) { input.value = SAVED_VALUE; if (type === "color") { object[key] = colorFromHex(object[key], SAVED_VALUE); } } const onValueChange = (value) => { let containerData = groupKey ? DATA[groupKey] : DATA; if (!containerData) { containerData = DATA[groupKey] = {}; } containerData[idKey] = input.value; if (GUI_REG_EXP.test(window.location.hash)) { window.location.hash = window.location.hash.replace(GUI_REG_EXP, `$1${encodeURI(JSON.stringify(DATA))}$5`); } else { let prefix = window.location.hash ? "&" : "#"; window.location.hash += `${prefix}gui=${encodeURI(JSON.stringify(DATA))}`; } if(remote && this._webSocket) { this._webSocket.send(JSON.stringify({uid, value})); } if (reload) { if (Keyboard.hasKeyDown(Keyboard.SHIFT)) { Keyboard.addEventListener("keyup", function reloadLocation() { Keyboard.removeEventListener("keyup", reloadLocation); window.location.reload(); }); } else { window.location.reload(); } } onChange(value); } // TODO: Clean here if (type === "button") { input.addEventListener("click", onValueChange); } else { let animationFrameId = -1; const onValueChangeTmp = () => { cancelAnimationFrame(animationFrameId); animationFrameId = requestAnimationFrame(() => { if (type === "color") { onValueChange(colorFromHex(object[key], input.value)); } else { onValueChange(input.value); } }); } if (type !== "text") { input.addEventListener("input", onValueChangeTmp); } input.addEventListener("change", onValueChangeTmp); } onChange(object[key]); this._inputs.set(uid, input); return input; } } window.customElements.define("dlib-gui", GUI);
gui/GUI.js
import WebSocket from "../utils/WebSocket.js"; import Keyboard from "../input/Keyboard.js"; import GUIInput from "./GUIInput.js"; let staticGUI; // STYLES let style = document.createElement("style"); document.head.appendChild(style); style.sheet.insertRule(` dlib-gui { display: block; position: absolute; resize: horizontal; top: 0; left: 0; width: 250px; padding: 5px; color: white; font-family: monospace; max-height: 100%; box-sizing: border-box; overflow: auto; } `, 0); style.sheet.insertRule(` dlib-gui dlib-guiinput { margin: 5px 0; } `, 0); style.sheet.insertRule(` dlib-gui details details { margin: 10px; } `, 0); style.sheet.insertRule(` dlib-gui details summary { cursor: pointer; } `, 0); style.sheet.insertRule(` dlib-gui details summary:focus { outline: none; } `, 0); // UTILS function componentToHex(c) { let hex = c.toString(16); return hex.length == 1 ? "0" + hex : hex; } function rgbToHex(r, g, b) { return "#" + componentToHex(r * 255) + componentToHex(g * 255) + componentToHex(b * 255); } function hexToRgb(hex) { var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16) / 255, g: parseInt(result[2], 16) / 255, b: parseInt(result[3], 16) / 255 } : null; } function colorFromHex(color, hex) { if (typeof color === "string") { return hex; } let colorValue = hexToRgb(hex); if (color.r !== undefined) { Object.assign(color, colorValue); } else if (color.x !== undefined) { [color.x, color.y, color.z] = [colorValue.r, colorValue.g, colorValue.b]; } else { [color[0], color[1], color[2]] = [colorValue.r, colorValue.g, colorValue.b]; } return color; } function colorToHex(color) { if (typeof color === "string") { return color; } return rgbToHex( color.r !== undefined ? color.r : color.x !== undefined ? color.x : color[0], color.g !== undefined ? color.g : color.y !== undefined ? color.y : color[1], color.b !== undefined ? color.b : color.z !== undefined ? color.z : color[2] ); } function normalizeString(string) { return `${string.toLowerCase().replace(/[^\w-]/g, "")}`; } function urlHashRegExpFromKey(key) { return new RegExp(`([#&]gui/${key}=)([^=&#?]*)`, "g"); } // GUI const GUI_REG_EXP = /([#&]gui=)((%7B|{).*(%7D|}))([&?]*)/; let DATA = {}; (function() { let matches = GUI_REG_EXP.exec(window.location.hash); if (matches) { let string = matches[2]; string = string.replace(/”|%E2%80%9D/g, "%22"); window.location.hash = window.location.hash.replace(GUI_REG_EXP, `$1${string}$5`); DATA = JSON.parse(decodeURI(string)); } })(); export default class GUI extends HTMLElement { static _addStatic() { if (staticGUI) { return; } staticGUI = document.createElement("dlib-gui"); document.body.appendChild(staticGUI); } static add(...params) { GUI._addStatic(); return staticGUI.add(...params); } static get element() { return staticGUI; } static get data() { return DATA; } static set visible(value) { GUI._addStatic(); staticGUI.visible = value; } static get visible() { return staticGUI.visible; } static set open(value) { GUI._addStatic(); staticGUI.open = value; } static get groups() { return staticGUI.groups; } static get open() { return staticGUI.open; } static set serverUrl(value) { GUI._addStatic(); staticGUI.serverUrl = value; } constructor({serverUrl} = {}) { super(); this.serverUrl = serverUrl; this.groups = new Map(); this._inputs = new Map(); this._uids = new Set(); this._container = document.createElement("details"); this._container.innerHTML = "<summary>GUI</summary>"; this.open = true; } set serverUrl(value) { this._serverUrl = value; if(this._webSocket) { this._webSocket.removeEventListener("message", this._onWebSocketMessage); this._webSocket.close(); this._webSocket = null; } if(!this._serverUrl) { return; } this._webSocket = new WebSocket(this._serverUrl); this._onWebSocketMessage = (e) => { let data = JSON.parse(e.data); let input = this._inputs.get(data.uid); if(input._client) { if(input.type === "button") { input.value(); } else { input.value = data.value; } } } this._webSocket.addEventListener("message", this._onWebSocketMessage); } get serverUrl() { return this._serverUrl; } set visible(value) { this.style.display = value ? "" : "none"; } get visible() { return this.style.visibility === "visible"; } update() { for (let input of this._inputs.values()) { input.update(); } } set open(value) { this._container.open = value; } get open() { return this._container.open; } add(object, key, {type, label = key, id = label, group = "", reload = false, remote = false, client = remote, onChange = () => { }, options, max, min, step} = {}) { if(object[key] === null || object[key] === undefined) { console.error(`GUI: ${id} must be defined.`); return; } let idKey = normalizeString(id); let groupKey = normalizeString(group); let uid = groupKey ? `${groupKey}/${idKey}` : idKey; if(this._uids.has(uid)) { console.error(`GUI: An input with id ${id} already exist in the group ${group}`); return; } this._uids.add(uid); if(remote && !this.serverUrl) { this._serverUrl = `wss://${location.hostname}:80`; } type = type || (options ? "select" : ""); if (!type) { switch (typeof object[key]) { case "boolean": type = "checkbox"; break; case "string": type = "text"; break; case "function": type = "button"; break; default: type = typeof object[key]; } } if (!this._container.parentNode) { this.appendChild(this._container); } let container = this._container; if(group) { container = this.groups.get(group); if(!container) { container = document.createElement("details"); container.innerHTML = `<summary>${group}</summary>`; this.groups.set(group, container); this._container.appendChild(container); } } let input = document.createElement("dlib-guiinput"); input.object = type === "color" ? { value: "#000000" } : object; input.key = type === "color" ? "value" : key; input.label = label; input.value = (type === "color" ? colorToHex(object[key]) : object[key]); input._client = client; if (min) { input.min = min; } if (max) { input.max = max; } if (step) { input.step = step; } if (options) { input.options = options; } input.type = type; container.appendChild(input); const SAVED_VALUE = groupKey && DATA[groupKey] ? DATA[groupKey][idKey] : DATA[idKey]; if(SAVED_VALUE !== undefined) { input.value = SAVED_VALUE; if (type === "color") { object[key] = colorFromHex(object[key], SAVED_VALUE); } } const onValueChange = (value) => { let containerData = groupKey ? DATA[groupKey] : DATA; if (!containerData) { containerData = DATA[groupKey] = {}; } containerData[idKey] = input.value; if (GUI_REG_EXP.test(window.location.hash)) { window.location.hash = window.location.hash.replace(GUI_REG_EXP, `$1${encodeURI(JSON.stringify(DATA))}$5`); } else { let prefix = window.location.hash ? "&" : "#"; window.location.hash += `${prefix}gui=${encodeURI(JSON.stringify(DATA))}`; } if(remote && this._webSocket) { this._webSocket.send(JSON.stringify({uid, value})); } if (reload) { if (Keyboard.hasKeyDown(Keyboard.SHIFT)) { Keyboard.addEventListener("keyup", function reloadLocation() { Keyboard.removeEventListener("keyup", reloadLocation); window.location.reload(); }); } else { window.location.reload(); } } onChange(value); } // TODO: Clean here if (type === "button") { input.addEventListener("click", onValueChange); } else { let animationFrameId = -1; const onValueChangeTmp = () => { cancelAnimationFrame(animationFrameId); animationFrameId = requestAnimationFrame(() => { if (type === "color") { onValueChange(colorFromHex(object[key], input.value)); } else { onValueChange(input.value); } }); } if (type !== "text") { input.addEventListener("input", onValueChangeTmp); } input.addEventListener("change", onValueChangeTmp); } onChange(object[key]); this._inputs.set(uid, input); return input; } } window.customElements.define("dlib-gui", GUI);
add static update method to GUI
gui/GUI.js
add static update method to GUI
<ide><path>ui/GUI.js <ide> return staticGUI.open; <ide> } <ide> <add> static get update() { <add> return staticGUI.update; <add> } <add> <ide> static set serverUrl(value) { <ide> GUI._addStatic(); <ide> staticGUI.serverUrl = value;
Java
mpl-2.0
d38e186479299481ed28167662d8bfd6a79d78aa
0
trevorbernard/jeromq,zeromq/jeromq,zeromq/jeromq,c-rack/jeromq,fredoboulo/jeromq,fredoboulo/jeromq,trevorbernard/jeromq
/* Copyright (c) 2009-2011 250bpm s.r.o. Copyright (c) 2007-2009 iMatix Corporation Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file This file is part of 0MQ. 0MQ is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 0MQ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package zmq; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; public class StreamEngine implements IEngine, IPollEvents, IMsgSink { // Size of the greeting message: // Preamble (10 bytes) + version (1 byte) + socket type (1 byte). private static final int GREETING_SIZE = 12; // True iff we are registered with an I/O poller. private boolean io_enabled; //final private IOObject io_object; private SocketChannel handle; private ByteBuffer inbuf; private int insize; private DecoderBase decoder; private Transfer outbuf; private int outsize; private EncoderBase encoder; // When true, we are still trying to determine whether // the peer is using versioned protocol, and if so, which // version. When false, normal message flow has started. private boolean handshaking; // The receive buffer holding the greeting message // that we are receiving from the peer. private final ByteBuffer greeting; // The send buffer holding the greeting message // that we are sending to the peer. private final ByteBuffer greeting_output_buffer; // The session this engine is attached to. private SessionBase session; // Detached transient session. //private SessionBase leftover_session; private Options options; // String representation of endpoint private String endpoint; private boolean plugged; private boolean terminating; // Socket private SocketBase socket; private IOObject io_object; public StreamEngine (SocketChannel fd_, final Options options_, final String endpoint_) { handle = fd_; inbuf = null; insize = 0; io_enabled = false; outbuf = null; outsize = 0; handshaking = true; session = null; options = options_; plugged = false; terminating = false; endpoint = endpoint_; socket = null; greeting = ByteBuffer.allocate (GREETING_SIZE); greeting_output_buffer = ByteBuffer.allocate (GREETING_SIZE); encoder = null; decoder = null; // Put the socket into non-blocking mode. try { Utils.unblock_socket (handle); // Set the socket buffer limits for the underlying socket. if (options.sndbuf != 0) { handle.socket().setSendBufferSize((int)options.sndbuf); } if (options.rcvbuf != 0) { handle.socket().setReceiveBufferSize((int)options.rcvbuf); } } catch (IOException e) { throw new ZError.IOException(e); } } private DecoderBase new_decoder (int size, long max, SessionBase session, int version) { if (options.decoder == null) { if (version == V1Protocol.VERSION) return new V1Decoder (size, max, session); return new Decoder (size, max); } try { Constructor<? extends DecoderBase> dcon; if (version == 0) { dcon = options.decoder.getConstructor (int.class, long.class); return dcon.newInstance (size, max); } else { dcon = options.decoder.getConstructor (int.class, long.class, IMsgSink.class, int.class); return dcon.newInstance (size, max, session, version); } } catch (SecurityException e) { throw new ZError.InstantiationException (e); } catch (NoSuchMethodException e) { throw new ZError.InstantiationException (e); } catch (InvocationTargetException e) { throw new ZError.InstantiationException (e); } catch (IllegalAccessException e) { throw new ZError.InstantiationException (e); } catch (InstantiationException e) { throw new ZError.InstantiationException (e); } } private EncoderBase new_encoder (int size, SessionBase session, int version) { if (options.encoder == null) { if (version == V1Protocol.VERSION) return new V1Encoder (size, session); return new Encoder (size); } try { Constructor<? extends EncoderBase> econ; if (version == 0) { econ = options.encoder.getConstructor (int.class); return econ.newInstance (size); } else { econ = options.encoder.getConstructor (int.class, IMsgSource.class, int.class); return econ.newInstance (size, session, version); } } catch (SecurityException e) { throw new ZError.InstantiationException (e); } catch (NoSuchMethodException e) { throw new ZError.InstantiationException (e); } catch (InvocationTargetException e) { throw new ZError.InstantiationException (e); } catch (IllegalAccessException e) { throw new ZError.InstantiationException (e); } catch (InstantiationException e) { throw new ZError.InstantiationException (e); } } public void destroy () { assert (!plugged); if (handle != null) { try { handle.close(); } catch (IOException e) { } handle = null; } } public void plug (IOThread io_thread_, SessionBase session_) { assert (!plugged); plugged = true; // Connect to session object. assert (session == null); assert (session_ != null); session = session_; socket = session.get_soket (); io_object = new IOObject(null); io_object.set_handler(this); // Connect to I/O threads poller object. io_object.plug (io_thread_); io_object.add_fd (handle); io_enabled = true; // Send the 'length' and 'flags' fields of the identity message. // The 'length' field is encoded in the long format. greeting_output_buffer.put ((byte) 0xff); greeting_output_buffer.putLong (options.identity_size + 1); greeting_output_buffer.put ((byte) 0x7f); io_object.set_pollin (handle); // When there's a raw custom encoder, we don't send 10 bytes frame boolean custom = false; try { custom = options.encoder != null && options.encoder.getDeclaredField ("RAW_ENCODER") != null; } catch (SecurityException e) { } catch (NoSuchFieldException e) { } if (!custom) { outsize = greeting_output_buffer.position (); outbuf = new Transfer.ByteBufferTransfer ((ByteBuffer) greeting_output_buffer.flip ()); io_object.set_pollout (handle); } // Flush all the data that may have been already received downstream. in_event (); } private void unplug () { assert (plugged); plugged = false; // Cancel all fd subscriptions. if (io_enabled) { io_object.rm_fd (handle); io_enabled = false; } // Disconnect from I/O threads poller object. io_object.unplug (); // Disconnect from session object. if (encoder != null) encoder.set_msg_source (null); if (decoder != null) decoder.set_msg_sink (null); session = null; } @Override public void terminate () { if (!terminating && encoder != null && encoder.has_data ()) { terminating = true; return; } unplug (); destroy (); } @Override public void in_event () { // If still handshaking, receive and process the greeting message. if (handshaking) if (!handshake ()) return; assert (decoder != null); boolean disconnection = false; // If there's no data to process in the buffer... if (insize == 0) { // Retrieve the buffer and read as much data as possible. // Note that buffer can be arbitrarily large. However, we assume // the underlying TCP layer has fixed buffer size and thus the // number of bytes read will be always limited. inbuf = decoder.get_buffer (); insize = read (inbuf); inbuf.flip(); // Check whether the peer has closed the connection. if (insize == -1) { insize = 0; disconnection = true; } } // Push the data to the decoder. int processed = decoder.process_buffer (inbuf, insize); if (processed == -1) { disconnection = true; } else { // Stop polling for input if we got stuck. if (processed < insize) io_object.reset_pollin (handle); // Adjust the buffer. insize -= processed; } // Flush all messages the decoder may have produced. session.flush (); // An input error has occurred. If the last decoded message // has already been accepted, we terminate the engine immediately. // Otherwise, we stop waiting for socket events and postpone // the termination until after the message is accepted. if (disconnection) { if (decoder.stalled ()) { io_object.rm_fd (handle); io_enabled = false; } else error (); } } @Override public void out_event () { // If write buffer is empty, try to read new data from the encoder. if (outsize == 0) { // Even when we stop polling as soon as there is no // data to send, the poller may invoke out_event one // more time due to 'speculative write' optimisation. if (encoder == null) { assert (handshaking); return; } outbuf = encoder.get_data (null); outsize = outbuf.remaining(); // If there is no data to send, stop polling for output. if (outbuf.remaining() == 0) { io_object.reset_pollout (handle); // when we use custom encoder, we might want to close if (encoder.is_error()) { error(); } return; } } // If there are any data to write in write buffer, write as much as // possible to the socket. Note that amount of data to write can be // arbitratily large. However, we assume that underlying TCP layer has // limited transmission buffer and thus the actual number of bytes // written should be reasonably modest. int nbytes = write (outbuf); // IO error has occurred. We stop waiting for output events. // The engine is not terminated until we detect input error; // this is necessary to prevent losing incomming messages. if (nbytes == -1) { io_object.reset_pollout (handle); if (terminating) terminate (); return; } outsize -= nbytes; // If we are still handshaking and there are no data // to send, stop polling for output. if (handshaking) if (outsize == 0) io_object.reset_pollout (handle); // when we use custom encoder, we might want to close after sending a response if (outsize == 0) { if (encoder != null && encoder.is_error ()) { error(); return; } if (terminating) terminate (); } } @Override public void connect_event() { throw new UnsupportedOperationException(); } @Override public void accept_event() { throw new UnsupportedOperationException(); } @Override public void timer_event(int id_) { throw new UnsupportedOperationException(); } @Override public void activate_out() { io_object.set_pollout (handle); // Speculative write: The assumption is that at the moment new message // was sent by the user the socket is probably available for writing. // Thus we try to write the data to socket avoiding polling for POLLOUT. // Consequently, the latency should be better in request/reply scenarios. out_event (); } @Override public void activate_in () { if (!io_enabled) { // There was an input error but the engine could not // be terminated (due to the stalled decoder). // Flush the pending message and terminate the engine now. decoder.process_buffer (inbuf, 0); assert (!decoder.stalled ()); session.flush (); error (); return; } io_object.set_pollin (handle); // Speculative read. io_object.in_event (); } private boolean handshake () { assert (handshaking); // Receive the greeting. while (greeting.position () < GREETING_SIZE) { final int n = read (greeting); if (n == -1) { error (); return false; } if (n == 0) return false; // We have received at least one byte from the peer. // If the first byte is not 0xff, we know that the // peer is using unversioned protocol. if ((greeting.get (0) & 0xff) != 0xff) break; if (greeting.position () < 10) continue; // Inspect the right-most bit of the 10th byte (which coincides // with the 'flags' field if a regular message was sent). // Zero indicates this is a header of identity message // (i.e. the peer is using the unversioned protocol). if ((greeting.get (9) & 0x01) == 0) break; // The peer is using versioned protocol. // Send the rest of the greeting, if necessary. if (greeting_output_buffer.limit () < GREETING_SIZE) { if (outsize == 0) io_object.set_pollout (handle); int pos = greeting_output_buffer.position (); greeting_output_buffer.position (10).limit (GREETING_SIZE); greeting_output_buffer.put ((byte) 1); // Protocol version greeting_output_buffer.put ((byte) options.type); // Socket type greeting_output_buffer.position (pos); outsize += 2; } } // Position of the version field in the greeting. final int version_pos = 10; // Is the peer using the unversioned protocol? // If so, we send and receive rests of identity // messages. if ((greeting.get (0) & 0xff) != 0xff || (greeting.get (9) & 0x01) == 0) { encoder = new_encoder (Config.OUT_BATCH_SIZE.getValue (), null, 0); encoder.set_msg_source (session); decoder = new_decoder (Config.IN_BATCH_SIZE.getValue (), options.maxmsgsize, null, 0); decoder.set_msg_sink (session); // We have already sent the message header. // Since there is no way to tell the encoder to // skip the message header, we simply throw that // header data away. final int header_size = options.identity_size + 1 >= 255 ? 10 : 2; ByteBuffer tmp = ByteBuffer.allocate (header_size); encoder.get_data (tmp); assert (tmp.remaining () == header_size); // Make sure the decoder sees the data we have already received. inbuf = greeting; greeting.flip (); insize = greeting.remaining (); // To allow for interoperability with peers that do not forward // their subscriptions, we inject a phony subsription // message into the incomming message stream. To put this // message right after the identity message, we temporarily // divert the message stream from session to ourselves. if (options.type == ZMQ.ZMQ_PUB || options.type == ZMQ.ZMQ_XPUB) decoder.set_msg_sink (this); } else if (greeting.get (version_pos) == 0) { // ZMTP/1.0 framing. encoder = new_encoder (Config.OUT_BATCH_SIZE.getValue (), null, 0); encoder.set_msg_source (session); decoder = new_decoder (Config.IN_BATCH_SIZE.getValue (), options.maxmsgsize, null, 0); decoder.set_msg_sink (session); } else { // v1 framing protocol. encoder = new_encoder (Config.OUT_BATCH_SIZE.getValue (), session, V1Protocol.VERSION); decoder = new_decoder (Config.IN_BATCH_SIZE.getValue (), options.maxmsgsize, session, V1Protocol.VERSION); } // Start polling for output if necessary. if (outsize == 0) io_object.set_pollout (handle); // Handshaking was successful. // Switch into the normal message flow. handshaking = false; return true; } @Override public int push_msg (Msg msg_) { assert (options.type == ZMQ.ZMQ_PUB || options.type == ZMQ.ZMQ_XPUB); // The first message is identity. // Let the session process it. int rc = session.push_msg (msg_); assert (rc == 0); // Inject the subscription message so that the ZMQ 2.x peer // receives our messages. msg_ = new Msg (1); msg_.put ((byte) 1); rc = session.push_msg (msg_); session.flush (); // Once we have injected the subscription message, we can // Divert the message flow back to the session. assert (decoder != null); decoder.set_msg_sink (session); return rc; } private void error () { assert (session != null); socket.event_disconnected (endpoint, handle); session.detach (); unplug (); destroy (); } private int write (Transfer buf) { int nbytes = 0 ; try { nbytes = buf.transferTo(handle); } catch (IOException e) { return -1; } return nbytes; } private int read (ByteBuffer buf) { int nbytes = 0 ; try { nbytes = handle.read (buf); } catch (IOException e) { return -1; } return nbytes; } }
src/main/java/zmq/StreamEngine.java
/* Copyright (c) 2009-2011 250bpm s.r.o. Copyright (c) 2007-2009 iMatix Corporation Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file This file is part of 0MQ. 0MQ is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 0MQ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package zmq; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; public class StreamEngine implements IEngine, IPollEvents, IMsgSink { // Size of the greeting message: // Preamble (10 bytes) + version (1 byte) + socket type (1 byte). private static final int GREETING_SIZE = 12; // True iff we are registered with an I/O poller. private boolean io_enabled; //final private IOObject io_object; private SocketChannel handle; private ByteBuffer inbuf; private int insize; private DecoderBase decoder; private Transfer outbuf; private int outsize; private EncoderBase encoder; // When true, we are still trying to determine whether // the peer is using versioned protocol, and if so, which // version. When false, normal message flow has started. private boolean handshaking; // The receive buffer holding the greeting message // that we are receiving from the peer. private final ByteBuffer greeting; // The send buffer holding the greeting message // that we are sending to the peer. private final ByteBuffer greeting_output_buffer; // The session this engine is attached to. private SessionBase session; // Detached transient session. //private SessionBase leftover_session; private Options options; // String representation of endpoint private String endpoint; private boolean plugged; private boolean terminating; // Socket private SocketBase socket; private IOObject io_object; public StreamEngine (SocketChannel fd_, final Options options_, final String endpoint_) { handle = fd_; inbuf = null; insize = 0; io_enabled = false; outbuf = null; outsize = 0; handshaking = true; session = null; options = options_; plugged = false; terminating = false; endpoint = endpoint_; socket = null; greeting = ByteBuffer.allocate (GREETING_SIZE); greeting_output_buffer = ByteBuffer.allocate (GREETING_SIZE); encoder = null; decoder = null; // Put the socket into non-blocking mode. try { Utils.unblock_socket (handle); // Set the socket buffer limits for the underlying socket. if (options.sndbuf != 0) { handle.socket().setSendBufferSize((int)options.sndbuf); } if (options.rcvbuf != 0) { handle.socket().setReceiveBufferSize((int)options.rcvbuf); } } catch (IOException e) { throw new ZError.IOException(e); } } private DecoderBase new_decoder (int size, long max, SessionBase session, int version) { if (options.decoder == null) { if (version == V1Protocol.VERSION) return new V1Decoder (size, max, session); return new Decoder (size, max); } try { Constructor<? extends DecoderBase> dcon; if (version == 0) { dcon = options.decoder.getConstructor (int.class, long.class); return dcon.newInstance (size, max); } else { dcon = options.decoder.getConstructor (int.class, long.class, IMsgSink.class, int.class); return dcon.newInstance (size, max, session, version); } } catch (SecurityException e) { throw new ZError.InstantiationException (e); } catch (NoSuchMethodException e) { throw new ZError.InstantiationException (e); } catch (InvocationTargetException e) { throw new ZError.InstantiationException (e); } catch (IllegalAccessException e) { throw new ZError.InstantiationException (e); } catch (InstantiationException e) { throw new ZError.InstantiationException (e); } } private EncoderBase new_encoder (int size, SessionBase session, int version) { if (options.encoder == null) { if (version == V1Protocol.VERSION) return new V1Encoder (size, session); return new Encoder (size); } try { Constructor<? extends EncoderBase> econ; if (version == 0) { econ = options.encoder.getConstructor (int.class); return econ.newInstance (size); } else { econ = options.encoder.getConstructor (int.class, IMsgSource.class, int.class); return econ.newInstance (size, session, version); } } catch (SecurityException e) { throw new ZError.InstantiationException (e); } catch (NoSuchMethodException e) { throw new ZError.InstantiationException (e); } catch (InvocationTargetException e) { throw new ZError.InstantiationException (e); } catch (IllegalAccessException e) { throw new ZError.InstantiationException (e); } catch (InstantiationException e) { throw new ZError.InstantiationException (e); } } public void destroy () { assert (!plugged); if (handle != null) { try { handle.close(); } catch (IOException e) { } handle = null; } } public void plug (IOThread io_thread_, SessionBase session_) { assert (!plugged); plugged = true; // Connect to session object. assert (session == null); assert (session_ != null); session = session_; socket = session.get_soket (); io_object = new IOObject(null); io_object.set_handler(this); // Connect to I/O threads poller object. io_object.plug (io_thread_); io_object.add_fd (handle); io_enabled = true; // Send the 'length' and 'flags' fields of the identity message. // The 'length' field is encoded in the long format. greeting_output_buffer.put ((byte) 0xff); greeting_output_buffer.putLong (options.identity_size + 1); greeting_output_buffer.put ((byte) 0x7f); io_object.set_pollin (handle); // When there's a raw custom encoder, we don't send 10 bytes frame boolean custom = false; try { custom = options.encoder != null && options.encoder.getDeclaredField ("RAW_ENCODER") != null; } catch (SecurityException e) { } catch (NoSuchFieldException e) { } if (!custom) { outsize = greeting_output_buffer.position (); outbuf = new Transfer.ByteBufferTransfer ((ByteBuffer) greeting_output_buffer.flip ()); io_object.set_pollout (handle); } // Flush all the data that may have been already received downstream. in_event (); } private void unplug () { assert (plugged); plugged = false; // Cancel all fd subscriptions. if (io_enabled) { io_object.rm_fd (handle); io_enabled = false; } // Disconnect from I/O threads poller object. io_object.unplug (); // Disconnect from session object. if (encoder != null) encoder.set_msg_source (null); if (decoder != null) decoder.set_msg_sink (null); session = null; } @Override public void terminate () { if (!terminating && encoder != null && encoder.has_data ()) { terminating = true; return; } unplug (); destroy (); } @Override public void in_event () { // If still handshaking, receive and process the greeting message. if (handshaking) if (!handshake ()) return; assert (decoder != null); boolean disconnection = false; // If there's no data to process in the buffer... if (insize == 0) { // Retrieve the buffer and read as much data as possible. // Note that buffer can be arbitrarily large. However, we assume // the underlying TCP layer has fixed buffer size and thus the // number of bytes read will be always limited. inbuf = decoder.get_buffer (); insize = read (inbuf); inbuf.flip(); // Check whether the peer has closed the connection. if (insize == -1) { insize = 0; disconnection = true; } } // Push the data to the decoder. int processed = decoder.process_buffer (inbuf, insize); if (processed == -1) { disconnection = true; } else { // Stop polling for input if we got stuck. if (processed < insize) io_object.reset_pollin (handle); // Adjust the buffer. insize -= processed; } // Flush all messages the decoder may have produced. session.flush (); // An input error has occurred. If the last decoded message // has already been accepted, we terminate the engine immediately. // Otherwise, we stop waiting for socket events and postpone // the termination until after the message is accepted. if (disconnection) { if (decoder.stalled ()) { io_object.rm_fd (handle); io_enabled = false; } else error (); } } @Override public void out_event () { // If write buffer is empty, try to read new data from the encoder. if (outsize == 0) { // Even when we stop polling as soon as there is no // data to send, the poller may invoke out_event one // more time due to 'speculative write' optimisation. if (encoder == null) { assert (handshaking); return; } outbuf = encoder.get_data (null); outsize = outbuf.remaining(); // If there is no data to send, stop polling for output. if (outbuf.remaining() == 0) { io_object.reset_pollout (handle); // when we use custom encoder, we might want to close if (encoder.is_error()) { error(); } return; } } // If there are any data to write in write buffer, write as much as // possible to the socket. Note that amount of data to write can be // arbitratily large. However, we assume that underlying TCP layer has // limited transmission buffer and thus the actual number of bytes // written should be reasonably modest. int nbytes = write (outbuf); // IO error has occurred. We stop waiting for output events. // The engine is not terminated until we detect input error; // this is necessary to prevent losing incomming messages. if (nbytes == -1) { io_object.reset_pollout (handle); if (terminating) terminate (); return; } outsize -= nbytes; // If we are still handshaking and there are no data // to send, stop polling for output. if (handshaking) if (outsize == 0) io_object.reset_pollout (handle); // when we use custom encoder, we might want to close after sending a response if (outsize == 0) { if (encoder != null && encoder.is_error ()) { error(); return; } if (terminating) terminate (); } } @Override public void connect_event() { throw new UnsupportedOperationException(); } @Override public void accept_event() { throw new UnsupportedOperationException(); } @Override public void timer_event(int id_) { throw new UnsupportedOperationException(); } @Override public void activate_out() { io_object.set_pollout (handle); // Speculative write: The assumption is that at the moment new message // was sent by the user the socket is probably available for writing. // Thus we try to write the data to socket avoiding polling for POLLOUT. // Consequently, the latency should be better in request/reply scenarios. out_event (); } @Override public void activate_in () { if (!io_enabled) { // There was an input error but the engine could not // be terminated (due to the stalled decoder). // Flush the pending message and terminate the engine now. decoder.process_buffer (inbuf, 0); assert (!decoder.stalled ()); session.flush (); error (); return; } io_object.set_pollin (handle); // Speculative read. io_object.in_event (); } private boolean handshake () { assert (handshaking); // Receive the greeting. while (greeting.position () < GREETING_SIZE) { final int n = read (greeting); if (n == -1) { error (); return false; } if (n == 0) return false; // We have received at least one byte from the peer. // If the first byte is not 0xff, we know that the // peer is using unversioned protocol. if (greeting.array () [0] != -1) break; if (greeting.position () < 10) continue; // Inspect the right-most bit of the 10th byte (which coincides // with the 'flags' field if a regular message was sent). // Zero indicates this is a header of identity message // (i.e. the peer is using the unversioned protocol). if ((greeting.array () [9] & 0x01) == 0) break; // The peer is using versioned protocol. // Send the rest of the greeting, if necessary. if (greeting_output_buffer.limit () < GREETING_SIZE) { if (outsize == 0) io_object.set_pollout (handle); int pos = greeting_output_buffer.position (); greeting_output_buffer.position (10).limit (GREETING_SIZE); greeting_output_buffer.put ((byte) 1); // Protocol version greeting_output_buffer.put ((byte) options.type); // Socket type greeting_output_buffer.position (pos); outsize += 2; } } // Position of the version field in the greeting. final int version_pos = 10; // Is the peer using the unversioned protocol? // If so, we send and receive rests of identity // messages. if (greeting.array () [0] != -1 || (greeting.array () [9] & 0x01) == 0) { encoder = new_encoder (Config.OUT_BATCH_SIZE.getValue (), null, 0); encoder.set_msg_source (session); decoder = new_decoder (Config.IN_BATCH_SIZE.getValue (), options.maxmsgsize, null, 0); decoder.set_msg_sink (session); // We have already sent the message header. // Since there is no way to tell the encoder to // skip the message header, we simply throw that // header data away. final int header_size = options.identity_size + 1 >= 255 ? 10 : 2; ByteBuffer tmp = ByteBuffer.allocate (header_size); encoder.get_data (tmp); assert (tmp.remaining () == header_size); // Make sure the decoder sees the data we have already received. inbuf = greeting; greeting.flip (); insize = greeting.remaining (); // To allow for interoperability with peers that do not forward // their subscriptions, we inject a phony subsription // message into the incomming message stream. To put this // message right after the identity message, we temporarily // divert the message stream from session to ourselves. if (options.type == ZMQ.ZMQ_PUB || options.type == ZMQ.ZMQ_XPUB) decoder.set_msg_sink (this); } else if (greeting.array () [version_pos] == 0) { // ZMTP/1.0 framing. encoder = new_encoder (Config.OUT_BATCH_SIZE.getValue (), null, 0); encoder.set_msg_source (session); decoder = new_decoder (Config.IN_BATCH_SIZE.getValue (), options.maxmsgsize, null, 0); decoder.set_msg_sink (session); } else { // v1 framing protocol. encoder = new_encoder (Config.OUT_BATCH_SIZE.getValue (), session, V1Protocol.VERSION); decoder = new_decoder (Config.IN_BATCH_SIZE.getValue (), options.maxmsgsize, session, V1Protocol.VERSION); } // Start polling for output if necessary. if (outsize == 0) io_object.set_pollout (handle); // Handshaking was successful. // Switch into the normal message flow. handshaking = false; return true; } @Override public int push_msg (Msg msg_) { assert (options.type == ZMQ.ZMQ_PUB || options.type == ZMQ.ZMQ_XPUB); // The first message is identity. // Let the session process it. int rc = session.push_msg (msg_); assert (rc == 0); // Inject the subscription message so that the ZMQ 2.x peer // receives our messages. msg_ = new Msg (1); msg_.put ((byte) 1); rc = session.push_msg (msg_); session.flush (); // Once we have injected the subscription message, we can // Divert the message flow back to the session. assert (decoder != null); decoder.set_msg_sink (session); return rc; } private void error () { assert (session != null); socket.event_disconnected (endpoint, handle); session.detach (); unplug (); destroy (); } private int write (Transfer buf) { int nbytes = 0 ; try { nbytes = buf.transferTo(handle); } catch (IOException e) { return -1; } return nbytes; } private int read (ByteBuffer buf) { int nbytes = 0 ; try { nbytes = handle.read (buf); } catch (IOException e) { return -1; } return nbytes; } }
Fix issue #122 - handshake now uses ByteBuffer accessor methods directly
src/main/java/zmq/StreamEngine.java
Fix issue #122 - handshake now uses ByteBuffer accessor methods directly
<ide><path>rc/main/java/zmq/StreamEngine.java <ide> // We have received at least one byte from the peer. <ide> // If the first byte is not 0xff, we know that the <ide> // peer is using unversioned protocol. <del> if (greeting.array () [0] != -1) <add> if ((greeting.get (0) & 0xff) != 0xff) <ide> break; <ide> <ide> if (greeting.position () < 10) <ide> // with the 'flags' field if a regular message was sent). <ide> // Zero indicates this is a header of identity message <ide> // (i.e. the peer is using the unversioned protocol). <del> if ((greeting.array () [9] & 0x01) == 0) <add> if ((greeting.get (9) & 0x01) == 0) <ide> break; <ide> <ide> // The peer is using versioned protocol. <ide> // Is the peer using the unversioned protocol? <ide> // If so, we send and receive rests of identity <ide> // messages. <del> if (greeting.array () [0] != -1 || (greeting.array () [9] & 0x01) == 0) { <add> if ((greeting.get (0) & 0xff) != 0xff || (greeting.get (9) & 0x01) == 0) { <ide> encoder = new_encoder (Config.OUT_BATCH_SIZE.getValue (), null, 0); <ide> encoder.set_msg_source (session); <ide> <ide> decoder.set_msg_sink (this); <ide> } <ide> else <del> if (greeting.array () [version_pos] == 0) { <add> if (greeting.get (version_pos) == 0) { <ide> // ZMTP/1.0 framing. <ide> encoder = new_encoder (Config.OUT_BATCH_SIZE.getValue (), null, 0); <ide> encoder.set_msg_source (session);
Java
mit
error: pathspec 'src/main/java/org/concurrent/sync/UsingLatches.java' did not match any file(s) known to git
2ecfe68d8a810aee05d37d4f49a1405475b8ad0f
1
zoopaper/java-concurrent,zoopaper/concurrent-programming
package org.concurrent.sync; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * Latches are used to delay the progress of threads until it reach a terminal * state * * Most common implementation is CountDownLatch. * * In CountDownLatch, each event adds 1. When ready, countDown() is called, * decrementing by counter by 1. await() method releases when counter is 0. * * Single use synchronizer. */ public class UsingLatches { public static void main(String[] args) { ExecutorService executor = Executors.newCachedThreadPool(); CountDownLatch latch = new CountDownLatch(3); Runnable r = () -> { try { Thread.sleep(1000); System.out.println("Service in " + Thread.currentThread().getName() + " initialized."); latch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } }; executor.execute(r); executor.execute(r); executor.execute(r); try { latch.await(2, TimeUnit.SECONDS); System.out.println("All services up and running!"); } catch (InterruptedException e) { e.printStackTrace(); } executor.shutdown(); } }
src/main/java/org/concurrent/sync/UsingLatches.java
UsingLatches
src/main/java/org/concurrent/sync/UsingLatches.java
UsingLatches
<ide><path>rc/main/java/org/concurrent/sync/UsingLatches.java <add>package org.concurrent.sync; <add> <add>import java.util.concurrent.CountDownLatch; <add>import java.util.concurrent.ExecutorService; <add>import java.util.concurrent.Executors; <add>import java.util.concurrent.TimeUnit; <add> <add>/** <add> * Latches are used to delay the progress of threads until it reach a terminal <add> * state <add> * <add> * Most common implementation is CountDownLatch. <add> * <add> * In CountDownLatch, each event adds 1. When ready, countDown() is called, <add> * decrementing by counter by 1. await() method releases when counter is 0. <add> * <add> * Single use synchronizer. <add> */ <add>public class UsingLatches { <add> <add> public static void main(String[] args) { <add> ExecutorService executor = Executors.newCachedThreadPool(); <add> CountDownLatch latch = new CountDownLatch(3); <add> Runnable r = () -> { <add> try { <add> Thread.sleep(1000); <add> System.out.println("Service in " + Thread.currentThread().getName() + " initialized."); <add> latch.countDown(); <add> } catch (InterruptedException e) { <add> e.printStackTrace(); <add> } <add> }; <add> executor.execute(r); <add> executor.execute(r); <add> executor.execute(r); <add> try { <add> latch.await(2, TimeUnit.SECONDS); <add> System.out.println("All services up and running!"); <add> } catch (InterruptedException e) { <add> e.printStackTrace(); <add> } <add> executor.shutdown(); <add> } <add> <add>}
Java
apache-2.0
887007265dc622483bde29279a8a1ebd2ddb80af
0
MCGallaspy/selenium,MCGallaspy/selenium,jabbrwcky/selenium,SeleniumHQ/selenium,SeleniumHQ/selenium,lukeis/selenium,jerome-jacob/selenium,dbo/selenium,mojwang/selenium,MCGallaspy/selenium,sag-enorman/selenium,sag-enorman/selenium,uchida/selenium,dbo/selenium,clavery/selenium,stupidnetizen/selenium,knorrium/selenium,rplevka/selenium,Sravyaksr/selenium,jerome-jacob/selenium,krosenvold/selenium,joshuaduffy/selenium,krosenvold/selenium,gorlemik/selenium,carlosroh/selenium,minhthuanit/selenium,customcommander/selenium,twalpole/selenium,rovner/selenium,asashour/selenium,o-schneider/selenium,lmtierney/selenium,dandv/selenium,joshmgrant/selenium,alexec/selenium,clavery/selenium,Tom-Trumper/selenium,valfirst/selenium,titusfortner/selenium,yukaReal/selenium,tkurnosova/selenium,krmahadevan/selenium,tkurnosova/selenium,carsonmcdonald/selenium,lilredindy/selenium,p0deje/selenium,MCGallaspy/selenium,blackboarddd/selenium,5hawnknight/selenium,quoideneuf/selenium,gorlemik/selenium,AutomatedTester/selenium,amar-sharma/selenium,dcjohnson1989/selenium,vveliev/selenium,rovner/selenium,rplevka/selenium,markodolancic/selenium,doungni/selenium,rrussell39/selenium,gurayinan/selenium,bmannix/selenium,skurochkin/selenium,DrMarcII/selenium,alb-i986/selenium,chrisblock/selenium,twalpole/selenium,jsakamoto/selenium,actmd/selenium,rplevka/selenium,customcommander/selenium,xsyntrex/selenium,rplevka/selenium,GorK-ChO/selenium,asashour/selenium,dibagga/selenium,mestihudson/selenium,tbeadle/selenium,gurayinan/selenium,dbo/selenium,slongwang/selenium,mach6/selenium,DrMarcII/selenium,jerome-jacob/selenium,yukaReal/selenium,clavery/selenium,Sravyaksr/selenium,mestihudson/selenium,dandv/selenium,Sravyaksr/selenium,krosenvold/selenium,slongwang/selenium,mach6/selenium,oddui/selenium,AutomatedTester/selenium,AutomatedTester/selenium,TikhomirovSergey/selenium,sri85/selenium,zenefits/selenium,p0deje/selenium,AutomatedTester/selenium,markodolancic/selenium,blackboarddd/selenium,davehunt/selenium,lmtierney/selenium,rrussell39/selenium,bayandin/selenium,jabbrwcky/selenium,minhthuanit/selenium,dandv/selenium,gabrielsimas/selenium,asashour/selenium,sag-enorman/selenium,vveliev/selenium,gregerrag/selenium,joshmgrant/selenium,joshbruning/selenium,joshuaduffy/selenium,Herst/selenium,joshmgrant/selenium,doungni/selenium,uchida/selenium,gabrielsimas/selenium,dimacus/selenium,carlosroh/selenium,stupidnetizen/selenium,lilredindy/selenium,stupidnetizen/selenium,mestihudson/selenium,TheBlackTuxCorp/selenium,Dude-X/selenium,lrowe/selenium,TikhomirovSergey/selenium,joshmgrant/selenium,p0deje/selenium,markodolancic/selenium,DrMarcII/selenium,amar-sharma/selenium,Sravyaksr/selenium,knorrium/selenium,customcommander/selenium,Jarob22/selenium,quoideneuf/selenium,krmahadevan/selenium,jsakamoto/selenium,HtmlUnit/selenium,gorlemik/selenium,sri85/selenium,Herst/selenium,gotcha/selenium,quoideneuf/selenium,anshumanchatterji/selenium,joshbruning/selenium,oddui/selenium,juangj/selenium,zenefits/selenium,uchida/selenium,houchj/selenium,s2oBCN/selenium,meksh/selenium,Appdynamics/selenium,carsonmcdonald/selenium,tkurnosova/selenium,HtmlUnit/selenium,asolntsev/selenium,lukeis/selenium,amikey/selenium,SouWilliams/selenium,bayandin/selenium,thanhpete/selenium,petruc/selenium,lukeis/selenium,juangj/selenium,rplevka/selenium,houchj/selenium,Sravyaksr/selenium,alb-i986/selenium,rrussell39/selenium,skurochkin/selenium,minhthuanit/selenium,Ardesco/selenium,asashour/selenium,tkurnosova/selenium,krmahadevan/selenium,TikhomirovSergey/selenium,s2oBCN/selenium,eric-stanley/selenium,mach6/selenium,valfirst/selenium,dbo/selenium,lmtierney/selenium,anshumanchatterji/selenium,dimacus/selenium,TikhomirovSergey/selenium,krmahadevan/selenium,dandv/selenium,mojwang/selenium,carsonmcdonald/selenium,i17c/selenium,krosenvold/selenium,MeetMe/selenium,mojwang/selenium,MeetMe/selenium,TikhomirovSergey/selenium,HtmlUnit/selenium,joshbruning/selenium,houchj/selenium,bartolkaruza/selenium,slongwang/selenium,Herst/selenium,rovner/selenium,gotcha/selenium,alb-i986/selenium,xsyntrex/selenium,mojwang/selenium,o-schneider/selenium,uchida/selenium,SouWilliams/selenium,HtmlUnit/selenium,asolntsev/selenium,BlackSmith/selenium,jerome-jacob/selenium,stupidnetizen/selenium,rovner/selenium,bayandin/selenium,JosephCastro/selenium,sankha93/selenium,gorlemik/selenium,stupidnetizen/selenium,mestihudson/selenium,yukaReal/selenium,TheBlackTuxCorp/selenium,sag-enorman/selenium,Dude-X/selenium,joshbruning/selenium,bartolkaruza/selenium,doungni/selenium,houchj/selenium,wambat/selenium,anshumanchatterji/selenium,jsakamoto/selenium,5hawnknight/selenium,lilredindy/selenium,asolntsev/selenium,chrisblock/selenium,gurayinan/selenium,krmahadevan/selenium,gabrielsimas/selenium,vveliev/selenium,quoideneuf/selenium,gregerrag/selenium,customcommander/selenium,doungni/selenium,actmd/selenium,bartolkaruza/selenium,Sravyaksr/selenium,dandv/selenium,xmhubj/selenium,tarlabs/selenium,dibagga/selenium,dandv/selenium,knorrium/selenium,SeleniumHQ/selenium,clavery/selenium,valfirst/selenium,tkurnosova/selenium,dandv/selenium,gotcha/selenium,HtmlUnit/selenium,joshmgrant/selenium,jabbrwcky/selenium,SouWilliams/selenium,tarlabs/selenium,wambat/selenium,dimacus/selenium,SeleniumHQ/selenium,Herst/selenium,quoideneuf/selenium,mestihudson/selenium,chrisblock/selenium,mojwang/selenium,bmannix/selenium,krosenvold/selenium,skurochkin/selenium,o-schneider/selenium,mach6/selenium,sankha93/selenium,skurochkin/selenium,dkentw/selenium,markodolancic/selenium,petruc/selenium,asolntsev/selenium,o-schneider/selenium,5hawnknight/selenium,zenefits/selenium,dcjohnson1989/selenium,Ardesco/selenium,vveliev/selenium,davehunt/selenium,markodolancic/selenium,AutomatedTester/selenium,lmtierney/selenium,mach6/selenium,thanhpete/selenium,bayandin/selenium,TikhomirovSergey/selenium,bmannix/selenium,JosephCastro/selenium,bmannix/selenium,rrussell39/selenium,gabrielsimas/selenium,minhthuanit/selenium,dibagga/selenium,slongwang/selenium,arunsingh/selenium,Appdynamics/selenium,dkentw/selenium,Jarob22/selenium,amar-sharma/selenium,joshuaduffy/selenium,dbo/selenium,dibagga/selenium,carlosroh/selenium,o-schneider/selenium,bartolkaruza/selenium,HtmlUnit/selenium,juangj/selenium,gabrielsimas/selenium,lmtierney/selenium,gurayinan/selenium,vveliev/selenium,customcommander/selenium,TikhomirovSergey/selenium,twalpole/selenium,thanhpete/selenium,s2oBCN/selenium,rplevka/selenium,lrowe/selenium,dandv/selenium,clavery/selenium,krosenvold/selenium,tbeadle/selenium,Sravyaksr/selenium,knorrium/selenium,s2oBCN/selenium,dibagga/selenium,tarlabs/selenium,Ardesco/selenium,HtmlUnit/selenium,dimacus/selenium,bartolkaruza/selenium,jsakamoto/selenium,tkurnosova/selenium,valfirst/selenium,alexec/selenium,jabbrwcky/selenium,s2oBCN/selenium,knorrium/selenium,dcjohnson1989/selenium,minhthuanit/selenium,oddui/selenium,joshuaduffy/selenium,tbeadle/selenium,alexec/selenium,clavery/selenium,dibagga/selenium,actmd/selenium,titusfortner/selenium,dkentw/selenium,sag-enorman/selenium,rovner/selenium,blackboarddd/selenium,Ardesco/selenium,mach6/selenium,meksh/selenium,JosephCastro/selenium,asashour/selenium,carlosroh/selenium,gotcha/selenium,bmannix/selenium,amikey/selenium,lmtierney/selenium,dimacus/selenium,sri85/selenium,petruc/selenium,p0deje/selenium,titusfortner/selenium,titusfortner/selenium,davehunt/selenium,mach6/selenium,actmd/selenium,thanhpete/selenium,arunsingh/selenium,tbeadle/selenium,eric-stanley/selenium,bayandin/selenium,i17c/selenium,GorK-ChO/selenium,DrMarcII/selenium,doungni/selenium,MeetMe/selenium,tbeadle/selenium,rplevka/selenium,rovner/selenium,xsyntrex/selenium,zenefits/selenium,s2oBCN/selenium,Tom-Trumper/selenium,juangj/selenium,bayandin/selenium,lrowe/selenium,lukeis/selenium,anshumanchatterji/selenium,o-schneider/selenium,blackboarddd/selenium,oddui/selenium,actmd/selenium,TheBlackTuxCorp/selenium,valfirst/selenium,petruc/selenium,thanhpete/selenium,anshumanchatterji/selenium,gorlemik/selenium,chrisblock/selenium,dibagga/selenium,lukeis/selenium,carsonmcdonald/selenium,amikey/selenium,o-schneider/selenium,SouWilliams/selenium,bmannix/selenium,Appdynamics/selenium,5hawnknight/selenium,sri85/selenium,asolntsev/selenium,markodolancic/selenium,asashour/selenium,lilredindy/selenium,lilredindy/selenium,wambat/selenium,twalpole/selenium,doungni/selenium,xmhubj/selenium,p0deje/selenium,customcommander/selenium,MCGallaspy/selenium,thanhpete/selenium,rovner/selenium,Jarob22/selenium,TheBlackTuxCorp/selenium,bartolkaruza/selenium,petruc/selenium,tbeadle/selenium,clavery/selenium,davehunt/selenium,joshmgrant/selenium,titusfortner/selenium,slongwang/selenium,GorK-ChO/selenium,GorK-ChO/selenium,xsyntrex/selenium,alb-i986/selenium,skurochkin/selenium,Tom-Trumper/selenium,dibagga/selenium,skurochkin/selenium,Dude-X/selenium,gabrielsimas/selenium,AutomatedTester/selenium,lrowe/selenium,SeleniumHQ/selenium,titusfortner/selenium,customcommander/selenium,GorK-ChO/selenium,stupidnetizen/selenium,5hawnknight/selenium,GorK-ChO/selenium,jabbrwcky/selenium,s2oBCN/selenium,blackboarddd/selenium,wambat/selenium,lukeis/selenium,alexec/selenium,juangj/selenium,joshuaduffy/selenium,xsyntrex/selenium,MeetMe/selenium,yukaReal/selenium,joshbruning/selenium,anshumanchatterji/selenium,minhthuanit/selenium,dcjohnson1989/selenium,wambat/selenium,p0deje/selenium,gotcha/selenium,MCGallaspy/selenium,sri85/selenium,alexec/selenium,gregerrag/selenium,gorlemik/selenium,houchj/selenium,TheBlackTuxCorp/selenium,jsakamoto/selenium,lrowe/selenium,Ardesco/selenium,yukaReal/selenium,kalyanjvn1/selenium,joshmgrant/selenium,zenefits/selenium,rrussell39/selenium,sri85/selenium,doungni/selenium,DrMarcII/selenium,minhthuanit/selenium,tbeadle/selenium,juangj/selenium,dbo/selenium,houchj/selenium,MeetMe/selenium,SeleniumHQ/selenium,gurayinan/selenium,MCGallaspy/selenium,krosenvold/selenium,davehunt/selenium,o-schneider/selenium,slongwang/selenium,Ardesco/selenium,meksh/selenium,bayandin/selenium,Sravyaksr/selenium,Ardesco/selenium,tarlabs/selenium,juangj/selenium,twalpole/selenium,mojwang/selenium,quoideneuf/selenium,xmhubj/selenium,Dude-X/selenium,arunsingh/selenium,xsyntrex/selenium,petruc/selenium,titusfortner/selenium,lukeis/selenium,yukaReal/selenium,mach6/selenium,twalpole/selenium,zenefits/selenium,yukaReal/selenium,dkentw/selenium,alexec/selenium,rplevka/selenium,thanhpete/selenium,meksh/selenium,vveliev/selenium,i17c/selenium,Appdynamics/selenium,dkentw/selenium,meksh/selenium,dandv/selenium,stupidnetizen/selenium,markodolancic/selenium,BlackSmith/selenium,meksh/selenium,tkurnosova/selenium,uchida/selenium,jabbrwcky/selenium,HtmlUnit/selenium,BlackSmith/selenium,xmhubj/selenium,slongwang/selenium,sag-enorman/selenium,SouWilliams/selenium,carlosroh/selenium,asashour/selenium,alb-i986/selenium,Ardesco/selenium,p0deje/selenium,houchj/selenium,jsakamoto/selenium,rplevka/selenium,AutomatedTester/selenium,rrussell39/selenium,arunsingh/selenium,Tom-Trumper/selenium,kalyanjvn1/selenium,houchj/selenium,alexec/selenium,petruc/selenium,jabbrwcky/selenium,jerome-jacob/selenium,jerome-jacob/selenium,sankha93/selenium,JosephCastro/selenium,JosephCastro/selenium,dbo/selenium,dcjohnson1989/selenium,kalyanjvn1/selenium,dimacus/selenium,actmd/selenium,TheBlackTuxCorp/selenium,lilredindy/selenium,krmahadevan/selenium,blackboarddd/selenium,DrMarcII/selenium,jerome-jacob/selenium,Appdynamics/selenium,uchida/selenium,Ardesco/selenium,thanhpete/selenium,asashour/selenium,anshumanchatterji/selenium,kalyanjvn1/selenium,tkurnosova/selenium,amikey/selenium,kalyanjvn1/selenium,HtmlUnit/selenium,customcommander/selenium,stupidnetizen/selenium,chrisblock/selenium,houchj/selenium,valfirst/selenium,krmahadevan/selenium,rovner/selenium,sag-enorman/selenium,carsonmcdonald/selenium,actmd/selenium,amar-sharma/selenium,Herst/selenium,gurayinan/selenium,vveliev/selenium,joshmgrant/selenium,eric-stanley/selenium,knorrium/selenium,MeetMe/selenium,DrMarcII/selenium,TheBlackTuxCorp/selenium,joshbruning/selenium,lrowe/selenium,sankha93/selenium,alb-i986/selenium,dibagga/selenium,amikey/selenium,i17c/selenium,eric-stanley/selenium,amar-sharma/selenium,arunsingh/selenium,zenefits/selenium,titusfortner/selenium,lukeis/selenium,TheBlackTuxCorp/selenium,oddui/selenium,gabrielsimas/selenium,lmtierney/selenium,eric-stanley/selenium,SouWilliams/selenium,joshuaduffy/selenium,tkurnosova/selenium,skurochkin/selenium,HtmlUnit/selenium,sag-enorman/selenium,Appdynamics/selenium,bartolkaruza/selenium,Appdynamics/selenium,quoideneuf/selenium,chrisblock/selenium,slongwang/selenium,GorK-ChO/selenium,tarlabs/selenium,zenefits/selenium,joshuaduffy/selenium,xsyntrex/selenium,davehunt/selenium,meksh/selenium,lmtierney/selenium,blackboarddd/selenium,carlosroh/selenium,mestihudson/selenium,rovner/selenium,slongwang/selenium,gregerrag/selenium,kalyanjvn1/selenium,eric-stanley/selenium,dkentw/selenium,Tom-Trumper/selenium,lilredindy/selenium,davehunt/selenium,mach6/selenium,MeetMe/selenium,Herst/selenium,valfirst/selenium,uchida/selenium,xmhubj/selenium,jerome-jacob/selenium,juangj/selenium,i17c/selenium,JosephCastro/selenium,davehunt/selenium,jsakamoto/selenium,mestihudson/selenium,DrMarcII/selenium,Jarob22/selenium,dcjohnson1989/selenium,kalyanjvn1/selenium,tarlabs/selenium,lilredindy/selenium,tbeadle/selenium,BlackSmith/selenium,krmahadevan/selenium,alexec/selenium,xmhubj/selenium,gabrielsimas/selenium,Jarob22/selenium,dkentw/selenium,Sravyaksr/selenium,dbo/selenium,AutomatedTester/selenium,SouWilliams/selenium,JosephCastro/selenium,mestihudson/selenium,eric-stanley/selenium,arunsingh/selenium,eric-stanley/selenium,tarlabs/selenium,bartolkaruza/selenium,clavery/selenium,Appdynamics/selenium,alb-i986/selenium,SeleniumHQ/selenium,SeleniumHQ/selenium,Herst/selenium,carsonmcdonald/selenium,davehunt/selenium,oddui/selenium,TheBlackTuxCorp/selenium,bartolkaruza/selenium,meksh/selenium,jabbrwcky/selenium,knorrium/selenium,jsakamoto/selenium,lrowe/selenium,markodolancic/selenium,chrisblock/selenium,Herst/selenium,Dude-X/selenium,anshumanchatterji/selenium,doungni/selenium,jabbrwcky/selenium,sankha93/selenium,twalpole/selenium,gorlemik/selenium,dimacus/selenium,lmtierney/selenium,i17c/selenium,lrowe/selenium,kalyanjvn1/selenium,xsyntrex/selenium,oddui/selenium,dkentw/selenium,Tom-Trumper/selenium,gregerrag/selenium,jerome-jacob/selenium,petruc/selenium,mojwang/selenium,twalpole/selenium,bayandin/selenium,knorrium/selenium,bmannix/selenium,petruc/selenium,jsakamoto/selenium,MeetMe/selenium,GorK-ChO/selenium,gotcha/selenium,dcjohnson1989/selenium,dcjohnson1989/selenium,sankha93/selenium,carlosroh/selenium,tarlabs/selenium,twalpole/selenium,joshuaduffy/selenium,zenefits/selenium,wambat/selenium,alb-i986/selenium,i17c/selenium,tbeadle/selenium,skurochkin/selenium,asolntsev/selenium,sankha93/selenium,wambat/selenium,tarlabs/selenium,BlackSmith/selenium,5hawnknight/selenium,bmannix/selenium,Dude-X/selenium,asolntsev/selenium,amar-sharma/selenium,gorlemik/selenium,gurayinan/selenium,quoideneuf/selenium,p0deje/selenium,carlosroh/selenium,asolntsev/selenium,carsonmcdonald/selenium,sri85/selenium,krmahadevan/selenium,amikey/selenium,DrMarcII/selenium,BlackSmith/selenium,Jarob22/selenium,5hawnknight/selenium,Jarob22/selenium,oddui/selenium,sankha93/selenium,clavery/selenium,quoideneuf/selenium,Appdynamics/selenium,lilredindy/selenium,valfirst/selenium,bayandin/selenium,titusfortner/selenium,mestihudson/selenium,meksh/selenium,amar-sharma/selenium,Tom-Trumper/selenium,mojwang/selenium,valfirst/selenium,amar-sharma/selenium,doungni/selenium,knorrium/selenium,customcommander/selenium,s2oBCN/selenium,5hawnknight/selenium,yukaReal/selenium,s2oBCN/selenium,anshumanchatterji/selenium,JosephCastro/selenium,bmannix/selenium,BlackSmith/selenium,vveliev/selenium,vveliev/selenium,amikey/selenium,joshbruning/selenium,chrisblock/selenium,amikey/selenium,p0deje/selenium,alexec/selenium,titusfortner/selenium,juangj/selenium,eric-stanley/selenium,gurayinan/selenium,uchida/selenium,wambat/selenium,uchida/selenium,gotcha/selenium,xmhubj/selenium,amikey/selenium,minhthuanit/selenium,wambat/selenium,JosephCastro/selenium,chrisblock/selenium,gotcha/selenium,lukeis/selenium,skurochkin/selenium,valfirst/selenium,arunsingh/selenium,Jarob22/selenium,valfirst/selenium,5hawnknight/selenium,Dude-X/selenium,TikhomirovSergey/selenium,minhthuanit/selenium,BlackSmith/selenium,krosenvold/selenium,Jarob22/selenium,rrussell39/selenium,rrussell39/selenium,titusfortner/selenium,dbo/selenium,Dude-X/selenium,gurayinan/selenium,carlosroh/selenium,dimacus/selenium,blackboarddd/selenium,asolntsev/selenium,sri85/selenium,amar-sharma/selenium,joshbruning/selenium,sri85/selenium,dcjohnson1989/selenium,joshmgrant/selenium,Tom-Trumper/selenium,joshmgrant/selenium,asashour/selenium,thanhpete/selenium,actmd/selenium,rrussell39/selenium,joshmgrant/selenium,SeleniumHQ/selenium,lrowe/selenium,gregerrag/selenium,TikhomirovSergey/selenium,yukaReal/selenium,SeleniumHQ/selenium,Dude-X/selenium,carsonmcdonald/selenium,krosenvold/selenium,xmhubj/selenium,i17c/selenium,sankha93/selenium,kalyanjvn1/selenium,SouWilliams/selenium,MeetMe/selenium,SouWilliams/selenium,o-schneider/selenium,BlackSmith/selenium,gotcha/selenium,sag-enorman/selenium,MCGallaspy/selenium,stupidnetizen/selenium,gorlemik/selenium,gregerrag/selenium,blackboarddd/selenium,Tom-Trumper/selenium,joshbruning/selenium,gabrielsimas/selenium,gregerrag/selenium,joshuaduffy/selenium,MCGallaspy/selenium,SeleniumHQ/selenium,xmhubj/selenium,carsonmcdonald/selenium,xsyntrex/selenium,arunsingh/selenium,dimacus/selenium,alb-i986/selenium,i17c/selenium,arunsingh/selenium,markodolancic/selenium,GorK-ChO/selenium,mojwang/selenium,AutomatedTester/selenium,Herst/selenium,dkentw/selenium,oddui/selenium,gregerrag/selenium,actmd/selenium
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium.htmlunit; import com.google.common.base.Strings; import com.google.common.base.Throwables; import com.gargoylesoftware.htmlunit.ScriptResult; import com.gargoylesoftware.htmlunit.html.DomElement; import com.gargoylesoftware.htmlunit.html.DomNode; import com.gargoylesoftware.htmlunit.html.DomText; import com.gargoylesoftware.htmlunit.html.HtmlButton; import com.gargoylesoftware.htmlunit.html.HtmlElement; import com.gargoylesoftware.htmlunit.html.HtmlForm; import com.gargoylesoftware.htmlunit.html.HtmlImageInput; import com.gargoylesoftware.htmlunit.html.HtmlInput; import com.gargoylesoftware.htmlunit.html.HtmlLabel; import com.gargoylesoftware.htmlunit.html.HtmlOption; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.html.HtmlPreformattedText; import com.gargoylesoftware.htmlunit.html.HtmlScript; import com.gargoylesoftware.htmlunit.html.HtmlSelect; import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput; import com.gargoylesoftware.htmlunit.html.HtmlTextArea; import com.gargoylesoftware.htmlunit.javascript.host.Event; import net.sourceforge.htmlunit.corejs.javascript.Undefined; import org.openqa.selenium.By; import org.openqa.selenium.Dimension; import org.openqa.selenium.ElementNotVisibleException; import org.openqa.selenium.InvalidElementStateException; import org.openqa.selenium.InvalidSelectorException; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.Point; import org.openqa.selenium.StaleElementReferenceException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.internal.Coordinates; import org.openqa.selenium.internal.FindsByCssSelector; import org.openqa.selenium.internal.FindsById; import org.openqa.selenium.internal.FindsByLinkText; import org.openqa.selenium.internal.FindsByTagName; import org.openqa.selenium.internal.FindsByXPath; import org.openqa.selenium.internal.Locatable; import org.openqa.selenium.internal.WrapsDriver; import org.openqa.selenium.internal.WrapsElement; import org.w3c.dom.Attr; import org.w3c.dom.NamedNodeMap; import java.io.IOException; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Callable; public class HtmlUnitWebElement implements WrapsDriver, FindsById, FindsByLinkText, FindsByXPath, FindsByTagName, FindsByCssSelector, Locatable, WebElement { protected final HtmlUnitDriver parent; protected final HtmlElement element; private static final char nbspChar = 160; private static final String[] blockLevelsTagNames = {"p", "h1", "h2", "h3", "h4", "h5", "h6", "dl", "div", "noscript", "blockquote", "form", "hr", "table", "fieldset", "address", "ul", "ol", "pre", "br"}; private static final String[] booleanAttributes = { "async", "autofocus", "autoplay", "checked", "compact", "complete", "controls", "declare", "defaultchecked", "defaultselected", "defer", "disabled", "draggable", "ended", "formnovalidate", "hidden", "indeterminate", "iscontenteditable", "ismap", "itemscope", "loop", "multiple", "muted", "nohref", "noresize", "noshade", "novalidate", "nowrap", "open", "paused", "pubdate", "readonly", "required", "reversed", "scoped", "seamless", "seeking", "selected", "spellcheck", "truespeed", "willvalidate" }; private String toString; public HtmlUnitWebElement(HtmlUnitDriver parent, HtmlElement element) { this.parent = parent; this.element = element; } @Override public void click() { try { verifyCanInteractWithElement(); } catch (InvalidElementStateException e) { Throwables.propagateIfInstanceOf(e, ElementNotVisibleException.class); // Swallow disabled element case // Clicking disabled elements should still be passed through, // we just don't expect any state change // TODO: The javadoc for this method implies we shouldn't throw for // element not visible either } if (element instanceof HtmlButton) { String type = element.getAttribute("type"); if (type == DomElement.ATTRIBUTE_NOT_DEFINED || type == DomElement.ATTRIBUTE_VALUE_EMPTY) { element.setAttribute("type", "submit"); } } HtmlUnitMouse mouse = (HtmlUnitMouse) parent.getMouse(); mouse.click(getCoordinates()); if (element instanceof HtmlLabel) { HtmlElement referencedElement = ((HtmlLabel)element).getReferencedElement(); if (referencedElement != null) { new HtmlUnitWebElement(parent, referencedElement).click(); } } } @Override public void submit() { try { if (element instanceof HtmlForm) { submitForm((HtmlForm) element); return; } else if ((element instanceof HtmlSubmitInput) || (element instanceof HtmlImageInput)) { element.click(); return; } else if (element instanceof HtmlInput) { HtmlForm form = element.getEnclosingForm(); if (form == null) { throw new NoSuchElementException("Unable to find the containing form"); } submitForm(form); return; } WebElement form = findParentForm(); if (form == null) { throw new NoSuchElementException("Unable to find the containing form"); } form.submit(); } catch (IOException e) { throw new WebDriverException(e); } } private void submitForm(HtmlForm form) { assertElementNotStale(); List<String> names = new ArrayList<String>(); names.add("input"); names.add("button"); List<? extends HtmlElement> allElements = form.getHtmlElementsByTagNames(names); HtmlElement submit = null; for (HtmlElement element : allElements) { if (!isSubmitElement(element)) { continue; } if (isBefore(submit)) { submit = element; } } if (submit == null) { if (parent.isJavascriptEnabled()) { ScriptResult eventResult = form.fireEvent("submit"); if (!ScriptResult.isFalse(eventResult)) { parent.executeScript("arguments[0].submit()", form); } return; } throw new WebDriverException("Cannot locate element used to submit form"); } try { submit.click(); } catch (IOException e) { throw new WebDriverException(e); } } private boolean isSubmitElement(HtmlElement element) { HtmlElement candidate = null; if (element instanceof HtmlSubmitInput && !((HtmlSubmitInput) element).isDisabled()) { candidate = element; } else if (element instanceof HtmlImageInput && !((HtmlImageInput) element).isDisabled()) { candidate = element; } else if (element instanceof HtmlButton) { HtmlButton button = (HtmlButton) element; if ("submit".equalsIgnoreCase(button.getTypeAttribute()) && !button.isDisabled()) { candidate = element; } } return candidate != null; } private boolean isBefore(HtmlElement submit) { return submit == null; } @Override public void clear() { assertElementNotStale(); if (element instanceof HtmlInput) { HtmlInput htmlInput = (HtmlInput) element; if (htmlInput.isReadOnly()) { throw new InvalidElementStateException("You may only edit editable elements"); } if (htmlInput.isDisabled()) { throw new InvalidElementStateException("You may only interact with enabled elements"); } htmlInput.setValueAttribute(""); } else if (element instanceof HtmlTextArea) { HtmlTextArea htmlTextArea = (HtmlTextArea) element; if (htmlTextArea.isReadOnly()) { throw new InvalidElementStateException("You may only edit editable elements"); } if (htmlTextArea.isDisabled()) { throw new InvalidElementStateException("You may only interact with enabled elements"); } htmlTextArea.setText(""); } else if (element.getAttribute("contenteditable") != HtmlElement.ATTRIBUTE_NOT_DEFINED) { element.setTextContent(""); } } private void verifyCanInteractWithElement() { assertElementNotStale(); Boolean displayed = parent.implicitlyWaitFor(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return isDisplayed(); } }); if (displayed == null || !displayed.booleanValue()) { throw new ElementNotVisibleException("You may only interact with visible elements"); } if (!isEnabled()) { throw new InvalidElementStateException("You may only interact with enabled elements"); } } private void switchFocusToThisIfNeeded() { HtmlUnitWebElement oldActiveElement = ((HtmlUnitWebElement) parent.switchTo().activeElement()); boolean jsEnabled = parent.isJavascriptEnabled(); boolean oldActiveEqualsCurrent = oldActiveElement.equals(this); try { boolean isBody = oldActiveElement.getTagName().toLowerCase().equals("body"); if (jsEnabled && !oldActiveEqualsCurrent && !isBody) { oldActiveElement.element.blur(); } } catch (StaleElementReferenceException ex) { // old element has gone, do nothing } element.focus(); } /** * @deprecated Visibility will soon be reduced. */ public void sendKeyDownEvent(CharSequence modifierKey) { sendSingleKeyEvent(modifierKey, Event.TYPE_KEY_DOWN); } /** * @deprecated Visibility will soon be reduced. */ public void sendKeyUpEvent(CharSequence modifierKey) { sendSingleKeyEvent(modifierKey, Event.TYPE_KEY_UP); } private void sendSingleKeyEvent(CharSequence modifierKey, String eventDescription) { verifyCanInteractWithElement(); switchFocusToThisIfNeeded(); HtmlUnitKeyboard keyboard = (HtmlUnitKeyboard) parent.getKeyboard(); keyboard.performSingleKeyAction(getElement(), modifierKey, eventDescription); } @Override public void sendKeys(CharSequence... value) { verifyCanInteractWithElement(); InputKeysContainer keysContainer = new InputKeysContainer(isInputElement(), value); switchFocusToThisIfNeeded(); HtmlUnitKeyboard keyboard = (HtmlUnitKeyboard) parent.getKeyboard(); keyboard.sendKeys(element, getAttribute("value"), keysContainer); if (isInputElement() && keysContainer.wasSubmitKeyFound()) { submit(); } } private boolean isInputElement() { return element instanceof HtmlInput; } @Override public String getTagName() { assertElementNotStale(); return element.getNodeName(); } @Override public String getAttribute(String name) { assertElementNotStale(); final String lowerName = name.toLowerCase(); String value = element.getAttribute(name); if (element instanceof HtmlInput && ("selected".equals(lowerName) || "checked".equals(lowerName))) { return trueOrNull(((HtmlInput) element).isChecked()); } if ("href".equals(lowerName) || "src".equals(lowerName)) { if (!element.hasAttribute(name)) { return null; } String link = element.getAttribute(name).trim(); HtmlPage page = (HtmlPage) element.getPage(); try { return page.getFullyQualifiedUrl(link).toString(); } catch (MalformedURLException e) { return null; } } if ("disabled".equals(lowerName)) { return trueOrNull(! isEnabled()); } if ("multiple".equals(lowerName) && element instanceof HtmlSelect) { String multipleAttribute = ((HtmlSelect) element).getMultipleAttribute(); if ("".equals(multipleAttribute)) { return trueOrNull(element.hasAttribute("multiple")); } return "true"; } for (String booleanAttribute : booleanAttributes) { if (booleanAttribute.equals(lowerName)) { return trueOrNull(element.hasAttribute(lowerName)); } } if ("index".equals(lowerName) && element instanceof HtmlOption) { HtmlSelect select = ((HtmlOption) element).getEnclosingSelect(); List<HtmlOption> allOptions = select.getOptions(); for (int i = 0; i < allOptions.size(); i++) { HtmlOption option = select.getOption(i); if (element.equals(option)) { return String.valueOf(i); } } return null; } if ("readonly".equalsIgnoreCase(lowerName)) { if (element instanceof HtmlInput) { return trueOrNull(((HtmlInput) element).isReadOnly()); } if (element instanceof HtmlTextArea) { return trueOrNull("".equals(((HtmlTextArea) element).getReadOnlyAttribute())); } return null; } if ("value".equals(lowerName)) { if (element instanceof HtmlTextArea) { return ((HtmlTextArea) element).getText(); } // According to // http://www.w3.org/TR/1999/REC-html401-19991224/interact/forms.html#adef-value-OPTION // if the value attribute doesn't exist, getting the "value" attribute defers to the // option's content. if (element instanceof HtmlOption && !element.hasAttribute("value")) { return element.getTextContent(); } return value == null ? "" : value; } if (!"".equals(value)) { return value; } if (element.hasAttribute(name)) { return ""; } final Object slotVal = element.getScriptObject().get(name); if (slotVal instanceof String) { String strVal = (String) slotVal; if (!Strings.isNullOrEmpty(strVal)) { return strVal; } } return null; } private String trueOrNull(boolean condition) { return condition ? "true" : null; } @Override public boolean isSelected() { assertElementNotStale(); if (element instanceof HtmlInput) { return ((HtmlInput) element).isChecked(); } else if (element instanceof HtmlOption) { return ((HtmlOption) element).isSelected(); } throw new UnsupportedOperationException( "Unable to determine if element is selected. Tag name is: " + element.getTagName()); } @Override public boolean isEnabled() { assertElementNotStale(); return !element.hasAttribute("disabled"); } @Override public boolean isDisplayed() { assertElementNotStale(); return element.isDisplayed(); } @Override public Point getLocation() { assertElementNotStale(); try { return new Point(readAndRound("left"), readAndRound("top")); } catch (Exception e) { throw new WebDriverException("Cannot determine size of element", e); } } @Override public Dimension getSize() { assertElementNotStale(); try { final int width = readAndRound("width"); final int height = readAndRound("height"); return new Dimension(width, height); } catch (Exception e) { throw new WebDriverException("Cannot determine size of element", e); } } private int readAndRound(final String property) { final String cssValue = getCssValue(property).replaceAll("[^0-9\\.]", ""); if (cssValue.length() == 0) { return 5; // wrong... but better than nothing } return Math.round(Float.parseFloat(cssValue)); } // This isn't very pretty. Sorry. @Override public String getText() { assertElementNotStale(); StringBuffer toReturn = new StringBuffer(); StringBuffer textSoFar = new StringBuffer(); boolean isPreformatted = element instanceof HtmlPreformattedText; getTextFromNode(element, toReturn, textSoFar, isPreformatted); String text = toReturn.toString() + collapseWhitespace(textSoFar); if (!isPreformatted) { text = text.trim(); } else { if (text.endsWith("\n")) { text = text.substring(0, text.length()-1); } } return text.replace(nbspChar, ' '); } protected HtmlUnitDriver getParent() { return parent; } protected HtmlElement getElement() { return element; } private void getTextFromNode(DomNode node, StringBuffer toReturn, StringBuffer textSoFar, boolean isPreformatted) { if (node instanceof HtmlScript) { return; } if (isPreformatted) { getPreformattedText(node, toReturn); } else { for (DomNode child : node.getChildren()) { // Do we need to collapse the text so far? if (child instanceof HtmlPreformattedText) { if (child.isDisplayed()) { String textToAdd = collapseWhitespace(textSoFar); if (! " ".equals(textToAdd)) { toReturn.append(textToAdd); } textSoFar.delete(0, textSoFar.length()); } getTextFromNode(child, toReturn, textSoFar, true); continue; } // Or is this just plain text? if (child instanceof DomText) { if (child.isDisplayed()) { String textToAdd = ((DomText) child).getData(); textSoFar.append(textToAdd); } continue; } // Treat as another child node. getTextFromNode(child, toReturn, textSoFar, false); } } if (isBlockLevel(node)) { toReturn.append(collapseWhitespace(textSoFar).trim()).append("\n"); textSoFar.delete(0, textSoFar.length()); } } private boolean isBlockLevel(DomNode node) { // From the HTML spec (http://www.w3.org/TR/html401/sgml/dtd.html#block) // <!ENTITY % block // "P | %heading; | %list; | %preformatted; | DL | DIV | NOSCRIPT | BLOCKQUOTE | FORM | HR | TABLE | FIELDSET | ADDRESS"> // <!ENTITY % heading "H1|H2|H3|H4|H5|H6"> // <!ENTITY % list "UL | OL"> // <!ENTITY % preformatted "PRE"> if (!(node instanceof HtmlElement)) { return false; } String tagName = ((HtmlElement) node).getTagName().toLowerCase(); for (String blockLevelsTagName : blockLevelsTagNames) { if (blockLevelsTagName.equals(tagName)) { return true; } } return false; } private String collapseWhitespace(StringBuffer textSoFar) { String textToAdd = textSoFar.toString(); return textToAdd.replaceAll("\\p{javaWhitespace}+", " ").replaceAll("\r", ""); } private void getPreformattedText(DomNode node, StringBuffer toReturn) { if (node.isDisplayed()) { toReturn.append(node.getTextContent()); } } public List<WebElement> getElementsByTagName(String tagName) { assertElementNotStale(); List<?> allChildren = element.getByXPath(".//" + tagName); List<WebElement> elements = new ArrayList<WebElement>(); for (Object o : allChildren) { if (!(o instanceof HtmlElement)) { continue; } HtmlElement child = (HtmlElement) o; elements.add(getParent().newHtmlUnitWebElement(child)); } return elements; } @Override public WebElement findElement(By by) { assertElementNotStale(); return parent.findElement(by, this); } @Override public List<WebElement> findElements(By by) { assertElementNotStale(); return parent.findElements(by, this); } @Override public WebElement findElementById(String id) { assertElementNotStale(); return findElementByXPath(".//*[@id = '" + id + "']"); } @Override public List<WebElement> findElementsById(String id) { assertElementNotStale(); return findElementsByXPath(".//*[@id = '" + id + "']"); } @Override public List<WebElement> findElementsByCssSelector(String using) { List<WebElement> allElements = parent.findElementsByCssSelector(using); return findChildNodes(allElements); } @Override public WebElement findElementByCssSelector(String using) { List<WebElement> allElements = parent.findElementsByCssSelector(using); allElements = findChildNodes(allElements); if (allElements.isEmpty()) { throw new NoSuchElementException("Cannot find child element using css: " + using); } return allElements.get(0); } private List<WebElement> findChildNodes(List<WebElement> allElements) { List<WebElement> toReturn = new LinkedList<WebElement>(); for (WebElement current : allElements) { HtmlElement candidate = ((HtmlUnitWebElement) current).element; if (element.isAncestorOf(candidate) && element != candidate) { toReturn.add(current); } } return toReturn; } @Override public WebElement findElementByXPath(String xpathExpr) { assertElementNotStale(); Object node; try { node = element.getFirstByXPath(xpathExpr); } catch (Exception ex) { // The xpath expression cannot be evaluated, so the expression is invalid throw new InvalidSelectorException( String.format(HtmlUnitDriver.INVALIDXPATHERROR, xpathExpr), ex); } if (node == null) { throw new NoSuchElementException("Unable to find an element with xpath " + xpathExpr); } if (node instanceof HtmlElement) { return getParent().newHtmlUnitWebElement((HtmlElement) node); } // The xpath selector selected something different than a WebElement. The selector is therefore // invalid throw new InvalidSelectorException( String.format(HtmlUnitDriver.INVALIDSELECTIONERROR, xpathExpr, node.getClass().toString())); } @Override public List<WebElement> findElementsByXPath(String xpathExpr) { assertElementNotStale(); List<WebElement> webElements = new ArrayList<WebElement>(); List<?> htmlElements; try { htmlElements = element.getByXPath(xpathExpr); } catch (Exception ex) { // The xpath expression cannot be evaluated, so the expression is invalid throw new InvalidSelectorException( String.format(HtmlUnitDriver.INVALIDXPATHERROR, xpathExpr), ex); } for (Object e : htmlElements) { if (e instanceof HtmlElement) { webElements.add(getParent().newHtmlUnitWebElement((HtmlElement) e)); } else { // The xpath selector selected something different than a WebElement. The selector is // therefore invalid throw new InvalidSelectorException( String.format(HtmlUnitDriver.INVALIDSELECTIONERROR, xpathExpr, e.getClass().toString())); } } return webElements; } @Override public WebElement findElementByLinkText(String linkText) { assertElementNotStale(); List<WebElement> elements = findElementsByLinkText(linkText); if (elements.isEmpty()) { throw new NoSuchElementException("Unable to find element with linkText " + linkText); } return elements.get(0); } @Override public List<WebElement> findElementsByLinkText(String linkText) { assertElementNotStale(); String expectedText = linkText.trim(); List<? extends HtmlElement> htmlElements = element.getHtmlElementsByTagName("a"); List<WebElement> webElements = new ArrayList<WebElement>(); for (HtmlElement e : htmlElements) { if (expectedText.equals(e.getTextContent().trim()) && e.getAttribute("href") != null) { webElements.add(getParent().newHtmlUnitWebElement(e)); } } return webElements; } @Override public WebElement findElementByPartialLinkText(String linkText) { assertElementNotStale(); List<WebElement> elements = findElementsByPartialLinkText(linkText); if (elements.isEmpty()) { throw new NoSuchElementException( "Unable to find element with linkText " + linkText); } return elements.size() > 0 ? elements.get(0) : null; } @Override public List<WebElement> findElementsByPartialLinkText(String linkText) { assertElementNotStale(); List<? extends HtmlElement> htmlElements = element.getHtmlElementsByTagName("a"); List<WebElement> webElements = new ArrayList<WebElement>(); for (HtmlElement e : htmlElements) { if (e.getTextContent().contains(linkText) && e.getAttribute("href") != null) { webElements.add(getParent().newHtmlUnitWebElement(e)); } } return webElements; } @Override public WebElement findElementByTagName(String name) { assertElementNotStale(); List<WebElement> elements = findElementsByTagName(name); if (elements.isEmpty()) { throw new NoSuchElementException("Cannot find element with tag name: " + name); } return elements.get(0); } @Override public List<WebElement> findElementsByTagName(String name) { assertElementNotStale(); List<HtmlElement> elements = element.getHtmlElementsByTagName(name); List<WebElement> toReturn = new ArrayList<WebElement>(elements.size()); for (HtmlElement element : elements) { toReturn.add(parent.newHtmlUnitWebElement(element)); } return toReturn; } private WebElement findParentForm() { DomNode current = element; while (!(current == null || current instanceof HtmlForm)) { current = current.getParentNode(); } return getParent().newHtmlUnitWebElement((HtmlForm) current); } @Override public String toString() { if (toString == null) { StringBuilder sb = new StringBuilder(); sb.append('<').append(element.getTagName()); NamedNodeMap attributes = element.getAttributes(); int n = attributes.getLength(); for (int i = 0; i < n; ++i) { Attr a = (Attr) attributes.item(i); sb.append(' ').append(a.getName()).append("=\"") .append(a.getValue().replace("\"", "&quot;")).append("\""); } if (element.hasChildNodes()) { sb.append('>'); } else { sb.append(" />"); } toString = sb.toString(); } return toString; } protected void assertElementNotStale() { parent.assertElementNotStale(element); } @Override public String getCssValue(String propertyName) { assertElementNotStale(); return getEffectiveStyle(element, propertyName); } private String getEffectiveStyle(HtmlElement htmlElement, String propertyName) { HtmlElement current = htmlElement; String value = "inherit"; while ("inherit".equals(value)) { // Hat-tip to the Selenium team Object result = parent .executeScript( "if (window.getComputedStyle) { " + " return window.getComputedStyle(arguments[0], null).getPropertyValue(arguments[1]); " + "} " + "if (arguments[0].currentStyle) { " + " return arguments[0].currentStyle[arguments[1]]; " + "} " + "if (window.document.defaultView && window.document.defaultView.getComputedStyle) { " + " return window.document.defaultView.getComputedStyle(arguments[0], null)[arguments[1]]; " + "} ", current, propertyName ); if (!(result instanceof Undefined)) { value = String.valueOf(result); } current = (HtmlElement) current.getParentNode(); } return value; } @Override public boolean equals(Object obj) { if (!(obj instanceof WebElement)) { return false; } WebElement other = (WebElement) obj; if (other instanceof WrapsElement) { other = ((WrapsElement) obj).getWrappedElement(); } return other instanceof HtmlUnitWebElement && element.equals(((HtmlUnitWebElement) other).element); } @Override public int hashCode() { return element.hashCode(); } /* * (non-Javadoc) * * @see org.openqa.selenium.internal.WrapsDriver#getContainingDriver() */ @Override public WebDriver getWrappedDriver() { return parent; } @Override public Coordinates getCoordinates() { return new Coordinates() { @Override public Point onScreen() { throw new UnsupportedOperationException("Not displayed, no screen location."); } @Override public Point inViewPort() { return getLocation(); } @Override public Point onPage() { return getLocation(); } @Override public Object getAuxiliary() { return getElement(); } }; } }
java/client/src/org/openqa/selenium/htmlunit/HtmlUnitWebElement.java
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium.htmlunit; import com.google.common.base.Strings; import com.google.common.base.Throwables; import com.gargoylesoftware.htmlunit.ScriptResult; import com.gargoylesoftware.htmlunit.html.DomElement; import com.gargoylesoftware.htmlunit.html.DomNode; import com.gargoylesoftware.htmlunit.html.DomText; import com.gargoylesoftware.htmlunit.html.HtmlButton; import com.gargoylesoftware.htmlunit.html.HtmlElement; import com.gargoylesoftware.htmlunit.html.HtmlForm; import com.gargoylesoftware.htmlunit.html.HtmlImageInput; import com.gargoylesoftware.htmlunit.html.HtmlInput; import com.gargoylesoftware.htmlunit.html.HtmlLabel; import com.gargoylesoftware.htmlunit.html.HtmlOption; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.html.HtmlPreformattedText; import com.gargoylesoftware.htmlunit.html.HtmlScript; import com.gargoylesoftware.htmlunit.html.HtmlSelect; import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput; import com.gargoylesoftware.htmlunit.html.HtmlTextArea; import com.gargoylesoftware.htmlunit.javascript.host.Event; import net.sourceforge.htmlunit.corejs.javascript.Undefined; import org.openqa.selenium.By; import org.openqa.selenium.Dimension; import org.openqa.selenium.ElementNotVisibleException; import org.openqa.selenium.InvalidElementStateException; import org.openqa.selenium.InvalidSelectorException; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.Point; import org.openqa.selenium.StaleElementReferenceException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.internal.Coordinates; import org.openqa.selenium.internal.FindsByCssSelector; import org.openqa.selenium.internal.FindsById; import org.openqa.selenium.internal.FindsByLinkText; import org.openqa.selenium.internal.FindsByTagName; import org.openqa.selenium.internal.FindsByXPath; import org.openqa.selenium.internal.Locatable; import org.openqa.selenium.internal.WrapsDriver; import org.openqa.selenium.internal.WrapsElement; import org.w3c.dom.Attr; import org.w3c.dom.NamedNodeMap; import java.io.IOException; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Callable; public class HtmlUnitWebElement implements WrapsDriver, FindsById, FindsByLinkText, FindsByXPath, FindsByTagName, FindsByCssSelector, Locatable, WebElement { protected final HtmlUnitDriver parent; protected final HtmlElement element; private static final char nbspChar = 160; private static final String[] blockLevelsTagNames = {"p", "h1", "h2", "h3", "h4", "h5", "h6", "dl", "div", "noscript", "blockquote", "form", "hr", "table", "fieldset", "address", "ul", "ol", "pre", "br"}; private static final String[] booleanAttributes = { "async", "autofocus", "autoplay", "checked", "compact", "complete", "controls", "declare", "defaultchecked", "defaultselected", "defer", "disabled", "draggable", "ended", "formnovalidate", "hidden", "indeterminate", "iscontenteditable", "ismap", "itemscope", "loop", "multiple", "muted", "nohref", "noresize", "noshade", "novalidate", "nowrap", "open", "paused", "pubdate", "readonly", "required", "reversed", "scoped", "seamless", "seeking", "selected", "spellcheck", "truespeed", "willvalidate" }; private String toString; public HtmlUnitWebElement(HtmlUnitDriver parent, HtmlElement element) { this.parent = parent; this.element = element; } @Override public void click() { try { verifyCanInteractWithElement(); } catch (InvalidElementStateException e) { Throwables.propagateIfInstanceOf(e, ElementNotVisibleException.class); // Swallow disabled element case // Clicking disabled elements should still be passed through, // we just don't expect any state change // TODO: The javadoc for this method implies we shouldn't throw for // element not visible either } if (element instanceof HtmlButton) { String type = element.getAttribute("type"); if (type == DomElement.ATTRIBUTE_NOT_DEFINED || type == DomElement.ATTRIBUTE_VALUE_EMPTY) { element.setAttribute("type", "submit"); } } HtmlUnitMouse mouse = (HtmlUnitMouse) parent.getMouse(); mouse.click(getCoordinates()); if (element instanceof HtmlLabel) { HtmlElement referencedElement = ((HtmlLabel)element).getReferencedElement(); if (referencedElement != null) { new HtmlUnitWebElement(parent, referencedElement).click(); } } } @Override public void submit() { try { if (element instanceof HtmlForm) { submitForm((HtmlForm) element); return; } else if ((element instanceof HtmlSubmitInput) || (element instanceof HtmlImageInput)) { element.click(); return; } else if (element instanceof HtmlInput) { HtmlForm form = element.getEnclosingForm(); if (form == null) { throw new NoSuchElementException("Unable to find the containing form"); } submitForm(form); return; } WebElement form = findParentForm(); if (form == null) { throw new NoSuchElementException("Unable to find the containing form"); } form.submit(); } catch (IOException e) { throw new WebDriverException(e); } } private void submitForm(HtmlForm form) { assertElementNotStale(); List<String> names = new ArrayList<String>(); names.add("input"); names.add("button"); List<? extends HtmlElement> allElements = form.getHtmlElementsByTagNames(names); HtmlElement submit = null; for (HtmlElement element : allElements) { if (!isSubmitElement(element)) { continue; } if (isBefore(submit)) { submit = element; } } if (submit == null) { if (parent.isJavascriptEnabled()) { ScriptResult eventResult = form.fireEvent("submit"); if (!ScriptResult.isFalse(eventResult)) { parent.executeScript("arguments[0].submit()", form); } return; } throw new WebDriverException("Cannot locate element used to submit form"); } try { submit.click(); } catch (IOException e) { throw new WebDriverException(e); } } private boolean isSubmitElement(HtmlElement element) { HtmlElement candidate = null; if (element instanceof HtmlSubmitInput && !((HtmlSubmitInput) element).isDisabled()) { candidate = element; } else if (element instanceof HtmlImageInput && !((HtmlImageInput) element).isDisabled()) { candidate = element; } else if (element instanceof HtmlButton) { HtmlButton button = (HtmlButton) element; if ("submit".equalsIgnoreCase(button.getTypeAttribute()) && !button.isDisabled()) { candidate = element; } } return candidate != null; } private boolean isBefore(HtmlElement submit) { return submit == null; } @Override public void clear() { assertElementNotStale(); if (element instanceof HtmlInput) { HtmlInput htmlInput = (HtmlInput) element; if (htmlInput.isReadOnly()) { throw new InvalidElementStateException("You may only edit editable elements"); } if (htmlInput.isDisabled()) { throw new InvalidElementStateException("You may only interact with enabled elements"); } htmlInput.setValueAttribute(""); } else if (element instanceof HtmlTextArea) { HtmlTextArea htmlTextArea = (HtmlTextArea) element; if (htmlTextArea.isReadOnly()) { throw new InvalidElementStateException("You may only edit editable elements"); } if (htmlTextArea.isDisabled()) { throw new InvalidElementStateException("You may only interact with enabled elements"); } htmlTextArea.setText(""); } else if (element.getAttribute("contenteditable") != HtmlElement.ATTRIBUTE_NOT_DEFINED) { element.setTextContent(""); } } private void verifyCanInteractWithElement() { assertElementNotStale(); Boolean displayed = parent.implicitlyWaitFor(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return isDisplayed(); } }); if (displayed == null || !displayed.booleanValue()) { throw new ElementNotVisibleException("You may only interact with visible elements"); } if (!isEnabled()) { throw new InvalidElementStateException("You may only interact with enabled elements"); } } private void switchFocusToThisIfNeeded() { HtmlUnitWebElement oldActiveElement = ((HtmlUnitWebElement) parent.switchTo().activeElement()); boolean jsEnabled = parent.isJavascriptEnabled(); boolean oldActiveEqualsCurrent = oldActiveElement.equals(this); try { boolean isBody = oldActiveElement.getTagName().toLowerCase().equals("body"); if (jsEnabled && !oldActiveEqualsCurrent && !isBody) { oldActiveElement.element.blur(); } } catch (StaleElementReferenceException ex) { // old element has gone, do nothing } element.focus(); } /** * @deprecated Visibility will soon be reduced. */ public void sendKeyDownEvent(CharSequence modifierKey) { sendSingleKeyEvent(modifierKey, Event.TYPE_KEY_DOWN); } /** * @deprecated Visibility will soon be reduced. */ public void sendKeyUpEvent(CharSequence modifierKey) { sendSingleKeyEvent(modifierKey, Event.TYPE_KEY_UP); } private void sendSingleKeyEvent(CharSequence modifierKey, String eventDescription) { verifyCanInteractWithElement(); switchFocusToThisIfNeeded(); HtmlUnitKeyboard keyboard = (HtmlUnitKeyboard) parent.getKeyboard(); keyboard.performSingleKeyAction(getElement(), modifierKey, eventDescription); } @Override public void sendKeys(CharSequence... value) { verifyCanInteractWithElement(); InputKeysContainer keysContainer = new InputKeysContainer(isInputElement(), value); switchFocusToThisIfNeeded(); HtmlUnitKeyboard keyboard = (HtmlUnitKeyboard) parent.getKeyboard(); keyboard.sendKeys(element, getAttribute("value"), keysContainer); if (isInputElement() && keysContainer.wasSubmitKeyFound()) { submit(); } } private boolean isInputElement() { return element instanceof HtmlInput; } @Override public String getTagName() { assertElementNotStale(); return element.getNodeName(); } @Override public String getAttribute(String name) { assertElementNotStale(); final String lowerName = name.toLowerCase(); String value = element.getAttribute(name); if (element instanceof HtmlInput && ("selected".equals(lowerName) || "checked".equals(lowerName))) { return trueOrNull(((HtmlInput) element).isChecked()); } if ("href".equals(lowerName) || "src".equals(lowerName)) { if (!element.hasAttribute(name)) { return null; } String link = element.getAttribute(name).trim(); HtmlPage page = (HtmlPage) element.getPage(); try { return page.getFullyQualifiedUrl(link).toString(); } catch (MalformedURLException e) { return null; } } if ("disabled".equals(lowerName)) { return trueOrNull(! isEnabled()); } if ("multiple".equals(lowerName) && element instanceof HtmlSelect) { String multipleAttribute = ((HtmlSelect) element).getMultipleAttribute(); if ("".equals(multipleAttribute)) { return trueOrNull(element.hasAttribute("multiple")); } return "true"; } for (String booleanAttribute : booleanAttributes) { if (booleanAttribute.equals(lowerName)) { return trueOrNull(element.hasAttribute(lowerName)); } } if ("index".equals(lowerName) && element instanceof HtmlOption) { HtmlSelect select = ((HtmlOption) element).getEnclosingSelect(); List<HtmlOption> allOptions = select.getOptions(); for (int i = 0; i < allOptions.size(); i++) { HtmlOption option = select.getOption(i); if (element.equals(option)) { return String.valueOf(i); } } return null; } if ("readonly".equalsIgnoreCase(lowerName)) { if (element instanceof HtmlInput) { return trueOrNull(((HtmlInput) element).isReadOnly()); } if (element instanceof HtmlTextArea) { return trueOrNull("".equals(((HtmlTextArea) element).getReadOnlyAttribute())); } return null; } if ("value".equals(lowerName)) { if (element instanceof HtmlTextArea) { return ((HtmlTextArea) element).getText(); } // According to // http://www.w3.org/TR/1999/REC-html401-19991224/interact/forms.html#adef-value-OPTION // if the value attribute doesn't exist, getting the "value" attribute defers to the // option's content. if (element instanceof HtmlOption && !element.hasAttribute("value")) { return element.getTextContent(); } return value == null ? "" : value; } if (!"".equals(value)) { return value; } if (element.hasAttribute(name)) { return ""; } final Object slotVal = element.getScriptObject().get(name); if (slotVal instanceof String) { String strVal = (String) slotVal; if (!Strings.isNullOrEmpty(strVal)) { return strVal; } } return null; } private String trueOrNull(boolean condition) { return condition ? "true" : null; } @Override public boolean isSelected() { assertElementNotStale(); if (element instanceof HtmlInput) { return ((HtmlInput) element).isChecked(); } else if (element instanceof HtmlOption) { return ((HtmlOption) element).isSelected(); } throw new UnsupportedOperationException( "Unable to determine if element is selected. Tag name is: " + element.getTagName()); } @Override public boolean isEnabled() { assertElementNotStale(); return !element.hasAttribute("disabled"); } @Override public boolean isDisplayed() { assertElementNotStale(); if (!parent.isJavascriptEnabled()) { return true; } return element.isDisplayed(); } @Override public Point getLocation() { assertElementNotStale(); try { return new Point(readAndRound("left"), readAndRound("top")); } catch (Exception e) { throw new WebDriverException("Cannot determine size of element", e); } } @Override public Dimension getSize() { assertElementNotStale(); try { final int width = readAndRound("width"); final int height = readAndRound("height"); return new Dimension(width, height); } catch (Exception e) { throw new WebDriverException("Cannot determine size of element", e); } } private int readAndRound(final String property) { final String cssValue = getCssValue(property).replaceAll("[^0-9\\.]", ""); if (cssValue.length() == 0) { return 5; // wrong... but better than nothing } return Math.round(Float.parseFloat(cssValue)); } // This isn't very pretty. Sorry. @Override public String getText() { assertElementNotStale(); StringBuffer toReturn = new StringBuffer(); StringBuffer textSoFar = new StringBuffer(); boolean isPreformatted = element instanceof HtmlPreformattedText; getTextFromNode(element, toReturn, textSoFar, isPreformatted); String text = toReturn.toString() + collapseWhitespace(textSoFar); if (!isPreformatted) { text = text.trim(); } else { if (text.endsWith("\n")) { text = text.substring(0, text.length()-1); } } return text.replace(nbspChar, ' '); } protected HtmlUnitDriver getParent() { return parent; } protected HtmlElement getElement() { return element; } private void getTextFromNode(DomNode node, StringBuffer toReturn, StringBuffer textSoFar, boolean isPreformatted) { if (node instanceof HtmlScript) { return; } if (isPreformatted) { getPreformattedText(node, toReturn); } else { for (DomNode child : node.getChildren()) { // Do we need to collapse the text so far? if (child instanceof HtmlPreformattedText) { if (child.isDisplayed()) { String textToAdd = collapseWhitespace(textSoFar); if (! " ".equals(textToAdd)) { toReturn.append(textToAdd); } textSoFar.delete(0, textSoFar.length()); } getTextFromNode(child, toReturn, textSoFar, true); continue; } // Or is this just plain text? if (child instanceof DomText) { if (child.isDisplayed()) { String textToAdd = ((DomText) child).getData(); textSoFar.append(textToAdd); } continue; } // Treat as another child node. getTextFromNode(child, toReturn, textSoFar, false); } } if (isBlockLevel(node)) { toReturn.append(collapseWhitespace(textSoFar).trim()).append("\n"); textSoFar.delete(0, textSoFar.length()); } } private boolean isBlockLevel(DomNode node) { // From the HTML spec (http://www.w3.org/TR/html401/sgml/dtd.html#block) // <!ENTITY % block // "P | %heading; | %list; | %preformatted; | DL | DIV | NOSCRIPT | BLOCKQUOTE | FORM | HR | TABLE | FIELDSET | ADDRESS"> // <!ENTITY % heading "H1|H2|H3|H4|H5|H6"> // <!ENTITY % list "UL | OL"> // <!ENTITY % preformatted "PRE"> if (!(node instanceof HtmlElement)) { return false; } String tagName = ((HtmlElement) node).getTagName().toLowerCase(); for (String blockLevelsTagName : blockLevelsTagNames) { if (blockLevelsTagName.equals(tagName)) { return true; } } return false; } private String collapseWhitespace(StringBuffer textSoFar) { String textToAdd = textSoFar.toString(); return textToAdd.replaceAll("\\p{javaWhitespace}+", " ").replaceAll("\r", ""); } private void getPreformattedText(DomNode node, StringBuffer toReturn) { if (node.isDisplayed()) { toReturn.append(node.getTextContent()); } } public List<WebElement> getElementsByTagName(String tagName) { assertElementNotStale(); List<?> allChildren = element.getByXPath(".//" + tagName); List<WebElement> elements = new ArrayList<WebElement>(); for (Object o : allChildren) { if (!(o instanceof HtmlElement)) { continue; } HtmlElement child = (HtmlElement) o; elements.add(getParent().newHtmlUnitWebElement(child)); } return elements; } @Override public WebElement findElement(By by) { assertElementNotStale(); return parent.findElement(by, this); } @Override public List<WebElement> findElements(By by) { assertElementNotStale(); return parent.findElements(by, this); } @Override public WebElement findElementById(String id) { assertElementNotStale(); return findElementByXPath(".//*[@id = '" + id + "']"); } @Override public List<WebElement> findElementsById(String id) { assertElementNotStale(); return findElementsByXPath(".//*[@id = '" + id + "']"); } @Override public List<WebElement> findElementsByCssSelector(String using) { List<WebElement> allElements = parent.findElementsByCssSelector(using); return findChildNodes(allElements); } @Override public WebElement findElementByCssSelector(String using) { List<WebElement> allElements = parent.findElementsByCssSelector(using); allElements = findChildNodes(allElements); if (allElements.isEmpty()) { throw new NoSuchElementException("Cannot find child element using css: " + using); } return allElements.get(0); } private List<WebElement> findChildNodes(List<WebElement> allElements) { List<WebElement> toReturn = new LinkedList<WebElement>(); for (WebElement current : allElements) { HtmlElement candidate = ((HtmlUnitWebElement) current).element; if (element.isAncestorOf(candidate) && element != candidate) { toReturn.add(current); } } return toReturn; } @Override public WebElement findElementByXPath(String xpathExpr) { assertElementNotStale(); Object node; try { node = element.getFirstByXPath(xpathExpr); } catch (Exception ex) { // The xpath expression cannot be evaluated, so the expression is invalid throw new InvalidSelectorException( String.format(HtmlUnitDriver.INVALIDXPATHERROR, xpathExpr), ex); } if (node == null) { throw new NoSuchElementException("Unable to find an element with xpath " + xpathExpr); } if (node instanceof HtmlElement) { return getParent().newHtmlUnitWebElement((HtmlElement) node); } // The xpath selector selected something different than a WebElement. The selector is therefore // invalid throw new InvalidSelectorException( String.format(HtmlUnitDriver.INVALIDSELECTIONERROR, xpathExpr, node.getClass().toString())); } @Override public List<WebElement> findElementsByXPath(String xpathExpr) { assertElementNotStale(); List<WebElement> webElements = new ArrayList<WebElement>(); List<?> htmlElements; try { htmlElements = element.getByXPath(xpathExpr); } catch (Exception ex) { // The xpath expression cannot be evaluated, so the expression is invalid throw new InvalidSelectorException( String.format(HtmlUnitDriver.INVALIDXPATHERROR, xpathExpr), ex); } for (Object e : htmlElements) { if (e instanceof HtmlElement) { webElements.add(getParent().newHtmlUnitWebElement((HtmlElement) e)); } else { // The xpath selector selected something different than a WebElement. The selector is // therefore invalid throw new InvalidSelectorException( String.format(HtmlUnitDriver.INVALIDSELECTIONERROR, xpathExpr, e.getClass().toString())); } } return webElements; } @Override public WebElement findElementByLinkText(String linkText) { assertElementNotStale(); List<WebElement> elements = findElementsByLinkText(linkText); if (elements.isEmpty()) { throw new NoSuchElementException("Unable to find element with linkText " + linkText); } return elements.get(0); } @Override public List<WebElement> findElementsByLinkText(String linkText) { assertElementNotStale(); String expectedText = linkText.trim(); List<? extends HtmlElement> htmlElements = element.getHtmlElementsByTagName("a"); List<WebElement> webElements = new ArrayList<WebElement>(); for (HtmlElement e : htmlElements) { if (expectedText.equals(e.getTextContent().trim()) && e.getAttribute("href") != null) { webElements.add(getParent().newHtmlUnitWebElement(e)); } } return webElements; } @Override public WebElement findElementByPartialLinkText(String linkText) { assertElementNotStale(); List<WebElement> elements = findElementsByPartialLinkText(linkText); if (elements.isEmpty()) { throw new NoSuchElementException( "Unable to find element with linkText " + linkText); } return elements.size() > 0 ? elements.get(0) : null; } @Override public List<WebElement> findElementsByPartialLinkText(String linkText) { assertElementNotStale(); List<? extends HtmlElement> htmlElements = element.getHtmlElementsByTagName("a"); List<WebElement> webElements = new ArrayList<WebElement>(); for (HtmlElement e : htmlElements) { if (e.getTextContent().contains(linkText) && e.getAttribute("href") != null) { webElements.add(getParent().newHtmlUnitWebElement(e)); } } return webElements; } @Override public WebElement findElementByTagName(String name) { assertElementNotStale(); List<WebElement> elements = findElementsByTagName(name); if (elements.isEmpty()) { throw new NoSuchElementException("Cannot find element with tag name: " + name); } return elements.get(0); } @Override public List<WebElement> findElementsByTagName(String name) { assertElementNotStale(); List<HtmlElement> elements = element.getHtmlElementsByTagName(name); List<WebElement> toReturn = new ArrayList<WebElement>(elements.size()); for (HtmlElement element : elements) { toReturn.add(parent.newHtmlUnitWebElement(element)); } return toReturn; } private WebElement findParentForm() { DomNode current = element; while (!(current == null || current instanceof HtmlForm)) { current = current.getParentNode(); } return getParent().newHtmlUnitWebElement((HtmlForm) current); } @Override public String toString() { if (toString == null) { StringBuilder sb = new StringBuilder(); sb.append('<').append(element.getTagName()); NamedNodeMap attributes = element.getAttributes(); int n = attributes.getLength(); for (int i = 0; i < n; ++i) { Attr a = (Attr) attributes.item(i); sb.append(' ').append(a.getName()).append("=\"") .append(a.getValue().replace("\"", "&quot;")).append("\""); } if (element.hasChildNodes()) { sb.append('>'); } else { sb.append(" />"); } toString = sb.toString(); } return toString; } protected void assertElementNotStale() { parent.assertElementNotStale(element); } @Override public String getCssValue(String propertyName) { assertElementNotStale(); return getEffectiveStyle(element, propertyName); } private String getEffectiveStyle(HtmlElement htmlElement, String propertyName) { HtmlElement current = htmlElement; String value = "inherit"; while ("inherit".equals(value)) { // Hat-tip to the Selenium team Object result = parent .executeScript( "if (window.getComputedStyle) { " + " return window.getComputedStyle(arguments[0], null).getPropertyValue(arguments[1]); " + "} " + "if (arguments[0].currentStyle) { " + " return arguments[0].currentStyle[arguments[1]]; " + "} " + "if (window.document.defaultView && window.document.defaultView.getComputedStyle) { " + " return window.document.defaultView.getComputedStyle(arguments[0], null)[arguments[1]]; " + "} ", current, propertyName ); if (!(result instanceof Undefined)) { value = String.valueOf(result); } current = (HtmlElement) current.getParentNode(); } return value; } @Override public boolean equals(Object obj) { if (!(obj instanceof WebElement)) { return false; } WebElement other = (WebElement) obj; if (other instanceof WrapsElement) { other = ((WrapsElement) obj).getWrappedElement(); } return other instanceof HtmlUnitWebElement && element.equals(((HtmlUnitWebElement) other).element); } @Override public int hashCode() { return element.hashCode(); } /* * (non-Javadoc) * * @see org.openqa.selenium.internal.WrapsDriver#getContainingDriver() */ @Override public WebDriver getWrappedDriver() { return parent; } @Override public Coordinates getCoordinates() { return new Coordinates() { @Override public Point onScreen() { throw new UnsupportedOperationException("Not displayed, no screen location."); } @Override public Point inViewPort() { return getLocation(); } @Override public Point onPage() { return getLocation(); } @Override public Object getAuxiliary() { return getElement(); } }; } }
HtmlUnit: Determining visibility does not require javascript in general Signed-off-by: Alexei Barantsev <[email protected]>
java/client/src/org/openqa/selenium/htmlunit/HtmlUnitWebElement.java
HtmlUnit: Determining visibility does not require javascript in general
<ide><path>ava/client/src/org/openqa/selenium/htmlunit/HtmlUnitWebElement.java <ide> public boolean isDisplayed() { <ide> assertElementNotStale(); <ide> <del> if (!parent.isJavascriptEnabled()) { <del> return true; <del> } <del> <ide> return element.isDisplayed(); <ide> } <ide>
Java
apache-2.0
10e4a48b5d83e7a426f47376a26e39b5dad059f5
0
merlimat/pulsar,merlimat/pulsar,yahoo/pulsar,massakam/pulsar,yahoo/pulsar,massakam/pulsar,merlimat/pulsar,merlimat/pulsar,massakam/pulsar,massakam/pulsar,yahoo/pulsar,yahoo/pulsar,massakam/pulsar,merlimat/pulsar,yahoo/pulsar,yahoo/pulsar,merlimat/pulsar,massakam/pulsar
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pulsar.broker.service.nonpersistent; import java.util.List; import org.apache.bookkeeper.mledger.Entry; import org.apache.bookkeeper.mledger.impl.PositionImpl; import org.apache.pulsar.broker.service.Consumer; import org.apache.pulsar.broker.service.Dispatcher; import org.apache.pulsar.common.stats.Rate; public interface NonPersistentDispatcher extends Dispatcher { void sendMessages(List<Entry> entries); Rate getMessageDropRate(); boolean hasPermits(); @Override default void redeliverUnacknowledgedMessages(Consumer consumer, long consumerEpoch) { // No-op } @Override default void redeliverUnacknowledgedMessages(Consumer consumer, List<PositionImpl> positions) { // No-op } @Override default void addUnAckedMessages(int unAckMessages) { // No-op } }
pulsar-broker/src/main/java/org/apache/pulsar/broker/service/nonpersistent/NonPersistentDispatcher.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pulsar.broker.service.nonpersistent; import java.util.List; import java.util.concurrent.CompletableFuture; import org.apache.bookkeeper.mledger.Entry; import org.apache.bookkeeper.mledger.impl.PositionImpl; import org.apache.pulsar.broker.service.BrokerServiceException; import org.apache.pulsar.broker.service.Consumer; import org.apache.pulsar.broker.service.Dispatcher; import org.apache.pulsar.common.api.proto.CommandSubscribe.SubType; import org.apache.pulsar.common.stats.Rate; public interface NonPersistentDispatcher extends Dispatcher { void addConsumer(Consumer consumer) throws BrokerServiceException; void removeConsumer(Consumer consumer) throws BrokerServiceException; boolean isConsumerConnected(); List<Consumer> getConsumers(); boolean canUnsubscribe(Consumer consumer); CompletableFuture<Void> close(); CompletableFuture<Void> disconnectAllConsumers(boolean isResetCursor); void reset(); SubType getType(); void sendMessages(List<Entry> entries); Rate getMessageDropRate(); boolean hasPermits(); @Override default void redeliverUnacknowledgedMessages(Consumer consumer, long consumerEpoch) { // No-op } @Override default void redeliverUnacknowledgedMessages(Consumer consumer, List<PositionImpl> positions) { // No-op } @Override default void addUnAckedMessages(int unAckMessages) { // No-op } }
[cleanup] [broker] Delete duplicate method definitions (#15613)
pulsar-broker/src/main/java/org/apache/pulsar/broker/service/nonpersistent/NonPersistentDispatcher.java
[cleanup] [broker] Delete duplicate method definitions (#15613)
<ide><path>ulsar-broker/src/main/java/org/apache/pulsar/broker/service/nonpersistent/NonPersistentDispatcher.java <ide> package org.apache.pulsar.broker.service.nonpersistent; <ide> <ide> import java.util.List; <del>import java.util.concurrent.CompletableFuture; <ide> import org.apache.bookkeeper.mledger.Entry; <ide> import org.apache.bookkeeper.mledger.impl.PositionImpl; <del>import org.apache.pulsar.broker.service.BrokerServiceException; <ide> import org.apache.pulsar.broker.service.Consumer; <ide> import org.apache.pulsar.broker.service.Dispatcher; <del>import org.apache.pulsar.common.api.proto.CommandSubscribe.SubType; <ide> import org.apache.pulsar.common.stats.Rate; <ide> <ide> <ide> public interface NonPersistentDispatcher extends Dispatcher { <del> <del> void addConsumer(Consumer consumer) throws BrokerServiceException; <del> <del> void removeConsumer(Consumer consumer) throws BrokerServiceException; <del> <del> boolean isConsumerConnected(); <del> <del> List<Consumer> getConsumers(); <del> <del> boolean canUnsubscribe(Consumer consumer); <del> <del> CompletableFuture<Void> close(); <del> <del> CompletableFuture<Void> disconnectAllConsumers(boolean isResetCursor); <del> <del> void reset(); <del> <del> SubType getType(); <ide> <ide> void sendMessages(List<Entry> entries); <ide>
Java
apache-2.0
631d79274b514d8f65722d31a77d4ccd164e1a92
0
Sage-Bionetworks/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,xschildw/Synapse-Repository-Services
package org.sagebionetworks.repo.web; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import org.sagebionetworks.repo.model.ServiceConstants; import org.sagebionetworks.repo.model.ServiceConstants.AttachmentType; import org.sagebionetworks.repo.model.Annotations; import org.sagebionetworks.repo.model.Entity; import org.sagebionetworks.repo.model.EntityType; import org.sagebionetworks.repo.model.Locationable; import org.sagebionetworks.repo.model.PrefixConst; import org.sagebionetworks.repo.model.Versionable; /** * UrlHelpers is responsible for the formatting of all URLs exposed by the * service. * * The various controllers should not be formatting URLs. They should instead * call methods in this helper. Its important to keep URL formulation logic in * one place to ensure consistency across the space of URLs that this service * supports. * * @author deflaux */ public class UrlHelpers { private static final Logger log = Logger.getLogger(UrlHelpers.class.getName()); public static final String ACCESS = "/access"; /** * Used for batch requests */ public static final String ALL = "/all"; public static final String BATCH = "/batch"; public static final String PERMISSIONS = "/permissions"; public static final String ACCESS_TYPE_PARAM = "accessType"; public static final String BUNDLE = "/bundle"; public static final String GENERATED_BY = "/generatedBy"; /** * URL prefix for all objects that are referenced by their ID. * */ public static final String ID_PATH_VARIABLE = "id"; public static final String ID = "/{"+ID_PATH_VARIABLE+"}"; public static final String IDS_PATH_VARIABLE = "ids"; /** * URL prefix for all objects that are referenced by their ID. * */ public static final String PROFILE_ID = "/{profileId}"; public static final String PARENT_TYPE = "/{parentType}"; public static final String PARENT_ID = "/{parentId}"; public static final String VERSION_NUMBER = "/{versionNumber}"; public static final String PARENT_TYPE_ID = PARENT_TYPE+PARENT_ID; // public static final String TOKEN_ID = "{tokenId}/{filename}.{mimeType}"; public static final String TYPE = "/type"; public static final String TYPE_HEADER = "/header"; /** * The URL prefix for all object's Access Control List (ACL). */ public static final String ACL = "/acl"; public static final String BENEFACTOR = "/benefactor"; /** * The request parameter to enforce ACL inheritance of child nodes. */ public static final String RECURSIVE = "recursive"; /** * URL suffix for entity annotations * */ public static final String ANNOTATIONS = "/annotations"; /** * URL suffix for locationable entity S3Token * */ public static final String S3TOKEN = "/s3Token"; /** * Used to get the path of a entity. */ public static final String PATH = "/path"; /** * URL suffix for entity schemas */ public static final String SCHEMA = "/schema"; public static final String REGISTRY = "/registry"; /** * The Effective schema is the flattened schema of an entity. */ public static final String EFFECTIVE_SCHEMA = "/effectiveSchema"; public static final String REST_RESOURCES = "/REST/resources"; public static final String VERSION = "/version"; public static final String PROMOTE_VERSION = "/promoteVersion"; public static final String REFERENCED_BY = "/referencedby"; public static final String ATTACHMENT_S3_TOKEN = "/s3AttachmentToken"; public static final String ATTACHMENT_URL = "/attachmentUrl"; public static final String MIGRATION_OBJECT_ID_PARAM = "id"; /** * parameter used by migration services to describe the type of migration * to be performed */ public static final String MIGRATION_TYPE_PARAM = "migrationType"; /** * All of the base URLs for Synapse objects */ public static final String ENTITY = PrefixConst.ENTITY; public static final String USER_PROFILE = PrefixConst.USER_PROFILE; public static final String HEALTHCHECK = PrefixConst.HEALTHCHECK; public static final String VERSIONINFO = PrefixConst.VERSIONINFO; public static final String ACTIVITY = PrefixConst.ACTIVITY; /** * All of the base URLs for Synapse object batch requests */ public static final String ENTITY_TYPE = ENTITY+TYPE; public static final String ENTITY_TYPE_HEADER = ENTITY+TYPE_HEADER; /** * All of the base URLs for Synapse objects with ID. */ public static final String ENTITY_ID = ENTITY+ID; public static final String USER_PROFILE_ID = USER_PROFILE+PROFILE_ID; public static final String ENTITY_BUNDLE = ENTITY+BUNDLE; public static final String ENTITY_ID_BUNDLE = ENTITY_ID+BUNDLE; public static final String ENTITY_ID_ACL = ENTITY_ID+ACL; public static final String ENTITY_ID_ID_BENEFACTOR = ENTITY_ID+BENEFACTOR; public static final String FILE= "/file"; public static final String ENTITY_FILE = ENTITY_ID+FILE; public static final String ENTITY_VERSION_FILE = ENTITY_ID+VERSION+VERSION_NUMBER+FILE; /** * Activity URLs */ public static final String ACTIVITY_ID = ACTIVITY+ID; /** * Used to get an entity attachment token */ public static final String ENTITY_S3_ATTACHMENT_TOKEN = ENTITY_ID+ATTACHMENT_S3_TOKEN; /** * The url used to get an attachment URL. */ public static final String ENTITY_ATTACHMENT_URL = ENTITY_ID+ATTACHMENT_URL; /** * The url used to get a user profile attachment URL. */ public static final String USER_PROFILE_ATTACHMENT_URL = USER_PROFILE_ID+ATTACHMENT_URL; /** * The base URL for Synapse objects's type (a.k.a. EntityHeader) */ public static final String ENTITY_ID_TYPE = ENTITY_ID+TYPE; /** * All of the base URLs for Synapse objects's Annotations. */ public static final String ENTITY_ANNOTATIONS = ENTITY_ID+ANNOTATIONS; /** * All of the base URLs for locationable entity s3Tokens */ public static final String ENTITY_S3TOKEN = ENTITY_ID+S3TOKEN; /** * Used to get a user profile attachment token */ public static final String USER_PROFILE_S3_ATTACHMENT_TOKEN = USER_PROFILE_ID+ATTACHMENT_S3_TOKEN; /** * All of the base URLs for Synapse objects's paths. */ public static final String ENTITY_PATH = ENTITY_ID+PATH; /** * All of the base URLs for Synapse object's versions. */ public static final String ENTITY_PROMOTE_VERSION = ENTITY_ID+PROMOTE_VERSION+VERSION_NUMBER; public static final String ENTITY_VERSION = ENTITY_ID+VERSION; public static final String ENTITY_VERSION_NUMBER = ENTITY_VERSION+VERSION_NUMBER; /** * Get the annotations of a specific version of an entity */ public static final String ENTITY_VERSION_ANNOTATIONS = ENTITY_VERSION_NUMBER+ANNOTATIONS; /** * Get the bundle for a specific version of an entity */ public static final String ENTITY_VERSION_NUMBER_BUNDLE = ENTITY_VERSION_NUMBER+BUNDLE; /** * Get the generating activity for the current version of an entity */ public static final String ENTITY_GENERATED_BY = ENTITY_ID+GENERATED_BY; /** * Get the generating activity for a specific version of an entity */ public static final String ENTITY_VERSION_GENERATED_BY = ENTITY_VERSION_NUMBER+GENERATED_BY; /** * Gets the root node. */ public static final String ENTITY_ROOT = ENTITY + "/root"; /** * Gets the ancestors for the specified node. */ public static final String ENTITY_ANCESTORS = ENTITY_ID + "/ancestors"; /** * Gets the descendants for the specified node. */ public static final String ENTITY_DESCENDANTS = ENTITY_ID + "/descendants"; /** * Gets the descendants of a particular generation for the specified node. */ public static final String GENERATION = "generation"; /** * Gets the descendants of a particular generation for the specified node. */ public static final String ENTITY_DESCENDANTS_GENERATION = ENTITY_ID + "/descendants/{" + GENERATION + "}"; /** * Gets the parent for the specified node. */ public static final String ENTITY_PARENT = ENTITY_ID + "/parent"; /** * Gets the children for the specified node. */ public static final String ENTITY_CHILDREN = ENTITY_ID + "/children"; /** * For trash can APIs. */ public static final String TRASHCAN = "/trashcan"; /** * Moves an entity to the trash can. */ public static final String TRASHCAN_TRASH = TRASHCAN + "/trash" + ID; /** * Restores an entity from the trash can back to a parent entity. */ public static final String TRASHCAN_RESTORE = TRASHCAN + "/restore" + ID + PARENT_ID; /** * Views the current trash can. */ public static final String TRASHCAN_VIEW = TRASHCAN + "/view"; /** * URL path for query controller * */ public static final String QUERY = "/query"; /** * URL prefix for Users in the system * */ public static final String USER = "/user"; /** * URL prefix for User Group model objects * */ public static final String USERGROUP = "/userGroup"; public static final String ACCESS_REQUIREMENT = "/accessRequirement"; public static final String ACCESS_REQUIREMENT_WITH_ENTITY_ID = ENTITY_ID+ACCESS_REQUIREMENT; public static final String ACCESS_REQUIREMENT_WITH_REQUIREMENT_ID = ACCESS_REQUIREMENT+"/{requirementId}"; public static final String ACCESS_REQUIREMENT_UNFULFILLED_WITH_ID = ENTITY_ID+"/accessRequirementUnfulfilled"; public static final String ACCESS_APPROVAL = "/accessApproval"; public static final String ACCESS_APPROVAL_WITH_ENTITY_ID = ENTITY_ID+ACCESS_APPROVAL; public static final String ACCESS_APPROVAL_WITH_APPROVAL_ID = ACCESS_APPROVAL+"/{approvalId}"; /** * URL prefix for Users in a UserGroup * */ public static final String RESOURCES = "/resources"; /** * URL prefix for User mirroring service * */ public static final String USER_MIRROR = "/userMirror"; /** * All administration URLs must start with this URL or calls will be * blocked when Synapse enters READ_ONLY or DOWN modes for maintenance. */ public static final String ADMIN = "/admin"; /** * These are the new more RESTful backup/restore URLS. */ public static final String DAEMON = ADMIN+"/daemon"; public static final String BACKUP = "/backup"; public static final String RESTORE = "/restore"; public static final String DAEMON_ID = "/{daemonId}"; public static final String ENTITY_BACKUP_DAMEON = DAEMON+BACKUP; public static final String ENTITY_RESTORE_DAMEON = DAEMON+RESTORE; public static final String ENTITY_DAEMON_ID = DAEMON+DAEMON_ID; public static final String CONCEPT = "/concept"; public static final String CONCEPT_ID = CONCEPT+ID; public static final String CHILDERN_TRANSITIVE = "/childrenTransitive"; public static final String CONCEPT_ID_CHILDERN_TRANSITIVE = CONCEPT_ID+CHILDERN_TRANSITIVE; /** * Storage usage summary for the current user. */ public static final String STORAGE_SUMMARY = "/storageSummary"; /** * Itemized storage usage for the current user. */ public static final String STORAGE_DETAILS = "/storageDetails"; /** * The user whose storage usage is queried. */ public static final String STORAGE_USER_ID = "userId"; /** * Storage usage summary for the specified user. */ public static final String STORAGE_SUMMARY_USER_ID = STORAGE_SUMMARY + "/{" + STORAGE_USER_ID + "}"; /** * Itemized storage usage for the specified user. */ public static final String STORAGE_DETAILS_USER_ID = STORAGE_DETAILS + "/{" + STORAGE_USER_ID + "}"; /** * Itemized storage usage for the specified NODE. */ public static final String STORAGE_DETAILS_ENTITY_ID = STORAGE_DETAILS + ENTITY_ID; /** * Storage usage summary for administrators. */ public static final String ADMIN_STORAGE_SUMMARY = ADMIN + STORAGE_SUMMARY; /** * Storage usage summaries, aggregated by users, for administrators. */ public static final String ADMIN_STORAGE_SUMMARY_PER_USER = ADMIN_STORAGE_SUMMARY + "/perUser"; /** * Storage usage summaries, aggregated by entities, for administrators. */ public static final String ADMIN_STORAGE_SUMMARY_PER_ENTITY = ADMIN_STORAGE_SUMMARY + "/perEntity"; /** * Public access for Synapse user and group info */ public static final String USER_GROUP_HEADERS = "/userGroupHeaders"; /** * Public batch request access for Synapse user and group info */ public static final String USER_GROUP_HEADERS_BATCH = USER_GROUP_HEADERS + BATCH; /** * The name of the query parameter for a prefix filter. */ public static final String PREFIX_FILTER = "prefix"; /** * The other header key used to request JSONP */ public static final String REQUEST_CALLBACK_JSONP = "callback"; /** * The stack status of synapse */ public static final String STACK_STATUS = ADMIN+"/synapse/status"; /** * Mapping of dependent property classes to their URL suffixes */ private static final Map<Class, String> PROPERTY2URLSUFFIX; /** * The parameter for a resource name. */ public static final String RESOURCE_ID = "resourceId"; public static final String GET_ALL_BACKUP_OBJECTS = "/backupObjects"; public static final String GET_ALL_BACKUP_OBJECTS_COUNTS = "/backupObjectsCounts"; /** * Used by AdministrationController service to say whether object dependencies should be calculated * when listing objects to back up. */ public static final String INCLUDE_DEPENDENCIES_PARAM = "includeDependencies"; // Competition URLs public static final String COMPETITION = "/competition"; public static final String COMPETITION_ID_PATH_VAR = "{compId}"; public static final String COMPETITION_WITH_ID = COMPETITION + "/"+COMPETITION_ID_PATH_VAR; public static final String COMPETITION_WITH_NAME = COMPETITION + "/name/{name}"; public static final String COMPETITION_COUNT = COMPETITION + "/count"; public static final String PARTICIPANT = COMPETITION_WITH_ID + "/participant"; public static final String PARTICIPANT_WITH_ID = PARTICIPANT + "/{partId}"; public static final String PARTICIPANT_COUNT = PARTICIPANT + "/count"; public static final String STATUS = "status"; public static final String SUBMISSION = COMPETITION + "/submission"; public static final String SUBMISSION_WITH_ID = SUBMISSION + "/{subId}"; public static final String SUBMISSION_STATUS = SUBMISSION_WITH_ID + "/status"; public static final String SUBMISSION_WITH_COMP_ID = COMPETITION_WITH_ID + "/submission"; public static final String SUBMISSION_WITH_COMP_ID_BUNDLE = SUBMISSION_WITH_COMP_ID + BUNDLE; public static final String SUBMISSION_WITH_COMP_ID_ADMIN = SUBMISSION_WITH_COMP_ID + ALL; public static final String SUBMISSION_WITH_COMP_ID_ADMIN_BUNDLE = SUBMISSION_WITH_COMP_ID + BUNDLE + ALL; public static final String SUBMISSION_COUNT = SUBMISSION_WITH_COMP_ID + "/count"; // Wiki URL public static final String WIKI = "/wiki"; public static final String WIKI_HEADER_TREE = "/wikiheadertree"; public static final String ATTACHMENT = "/attachment"; public static final String ATTACHMENT_PREVIEW = "/attachmentpreview"; public static final String ATTACHMENT_HANDLES = "/attachmenthandles"; public static final String WIKI_WITH_ID = WIKI + "/{wikiId}"; // Entity public static final String ENTITY_OWNER_ID = ENTITY+"/{ownerId}"; public static final String ENTITY_WIKI = ENTITY_OWNER_ID + WIKI; public static final String ENTITY_WIKI_TREE = ENTITY_OWNER_ID + WIKI_HEADER_TREE; public static final String ENTITY_WIKI_ID = ENTITY_OWNER_ID + WIKI_WITH_ID; public static final String ENTITY_WIKI_ID_ATTCHMENT_HANDLE = ENTITY_OWNER_ID + WIKI_WITH_ID+ATTACHMENT_HANDLES; public static final String ENTITY_WIKI_ID_ATTCHMENT_FILE = ENTITY_OWNER_ID + WIKI_WITH_ID+ATTACHMENT; public static final String ENTITY_WIKI_ID_ATTCHMENT_FILE_PREVIEW = ENTITY_OWNER_ID + WIKI_WITH_ID+ATTACHMENT_PREVIEW; // competition public static final String COMPETITION_OWNER_ID = COMPETITION+"/{ownerId}"; public static final String COMPETITION_WIKI = COMPETITION_OWNER_ID+ WIKI; public static final String COMPETITION_WIKI_TREE = COMPETITION_OWNER_ID + WIKI_HEADER_TREE; public static final String COMPETITION_WIKI_ID =COMPETITION_OWNER_ID + WIKI_WITH_ID; public static final String COMPETITION_WIKI_ID_ATTCHMENT_HANDLE =COMPETITION_OWNER_ID + WIKI_WITH_ID+ATTACHMENT_HANDLES; public static final String COMPETITION_WIKI_ID_ATTCHMENT_FILE =COMPETITION_OWNER_ID + WIKI_WITH_ID+ATTACHMENT; public static final String COMPETITION_WIKI_ID_ATTCHMENT_FILE_PREVIEW =COMPETITION_OWNER_ID + WIKI_WITH_ID+ATTACHMENT_PREVIEW; /** * This is a memoized cache for our URL regular expressions */ private static Map<Class, Pattern> MODEL2REGEX = new HashMap<Class, Pattern>(); static { Map<Class, String> property2urlsuffix = new HashMap<Class, String>(); property2urlsuffix.put(Annotations.class, ANNOTATIONS); PROPERTY2URLSUFFIX = Collections.unmodifiableMap(property2urlsuffix); } /** * Determine the controller URL prefix for a given model class * * @param theModelClass * @return the URL for the model class */ // @SuppressWarnings("unchecked") // public static String getUrlForModel(Class theModelClass) { // EntityType type = EntityType.getNodeTypeForClass(theModelClass); // return type.getUrlPrefix(); // } /** * Helper function to create a relative URL for an entity's annotations * <p> * * This includes not only the entity id but also the controller and servlet * portions of the path * * @param request * @return the uri for this entity's annotations */ public static String makeEntityAnnotationsUri(String entityId) { return ENTITY + "/" + entityId + ANNOTATIONS; } /** * Helper function to create a relative URL for an entity's ACL * <p> * * This includes not only the entity id but also the controller and servlet * portions of the path * * @param request * @return the uri for this entity's annotations */ public static String makeEntityACLUri(String entityId) { return ENTITY + "/" + entityId + ACL; } /** * Helper function to create a relative URL for an entity's dependent * property * <p> * * This includes not only the entity id but also the controller and servlet * portions of the path * * @param request * @return the uri for this entity's annotations */ public static String makeEntityPropertyUri(HttpServletRequest request) { return request.getRequestURI(); } /** * Helper function to create a relative URL for an entity's annotations * <p> * * This includes not only the entity id but also the controller and servlet * portions of the path * * @param entity * @param propertyClass * @param request * @return the uri for this entity's annotations */ @SuppressWarnings("unchecked") public static String makeEntityPropertyUri(Entity entity, Class propertyClass, HttpServletRequest request) { String urlPrefix = getUrlPrefixFromRequest(request); String uri = null; try { uri = urlPrefix + UrlHelpers.ENTITY + "/" + URLEncoder.encode(entity.getId(), "UTF-8") + PROPERTY2URLSUFFIX.get(propertyClass); } catch (UnsupportedEncodingException e) { log.log(Level.SEVERE, "Something is really messed up if we don't support UTF-8", e); } return uri; } /** * Helper function to translate ids found in URLs to ids used by the system * <p> * * Specifically we currently use the serialized system id url-encoded for * use in URLs * * @param id * @return URL-decoded entity id */ public static String getEntityIdFromUriId(String id) { String entityId = null; try { entityId = URLDecoder.decode(id, "UTF-8"); } catch (UnsupportedEncodingException e) { log.log(Level.SEVERE, "Something is really messed up if we don't support UTF-8", e); } return entityId; } /** * Get the URL prefix from a request. * @param request * @return Servlet context and path url prefix */ public static String getUrlPrefixFromRequest(HttpServletRequest request){ if(request == null) throw new IllegalArgumentException("Request cannot be null"); if(request.getServletPath() == null) throw new IllegalArgumentException("Servlet path cannot be null"); String urlPrefix = (null != request.getContextPath()) ? request.getContextPath() + request.getServletPath() : request.getServletPath(); return urlPrefix; } /** * Set the URI for any entity. * @param entityId * @param entityClass * @param urlPrefix * @return the entity uri */ public static String createEntityUri(String entityId, Class<? extends Entity> entityClass, String urlPrefix){ if(entityId == null) throw new IllegalArgumentException("Entity id cannot be null"); if(entityClass == null) throw new IllegalArgumentException("Entity class cannot be null"); if(urlPrefix == null) throw new IllegalArgumentException("Url prefix cannot be null"); StringBuilder builder = new StringBuilder(); builder.append(urlPrefix); builder.append(UrlHelpers.ENTITY); builder.append("/"); builder.append(entityId); return builder.toString(); } /** * Set the base uri for any entity. * @param entity * @param request */ public static void setBaseUriForEntity(Entity entity, HttpServletRequest request){ if(entity == null) throw new IllegalArgumentException("Entity cannot be null"); if(request == null) throw new IllegalArgumentException("Request cannot be null"); // First get the prefix String prefix = UrlHelpers.getUrlPrefixFromRequest(request); // Now build the uri. String uri = UrlHelpers.createEntityUri(entity.getId(), entity.getClass(), prefix); entity.setUri(uri); } /** * Set the all of the Entity URLs (annotations, ACL) * @param entity */ public static void setAllEntityUrls(Entity entity){ if(entity == null) throw new IllegalArgumentException("Entity cannot be null"); if(entity.getUri() == null) throw new IllegalArgumentException("Entity.uri cannot be null null"); // Add the annotations entity.setAnnotations(entity.getUri()+ANNOTATIONS); // Add the acl entity.setAccessControlList(entity.getUri()+ACL); if(entity instanceof Locationable) { Locationable able = (Locationable) entity; able.setS3Token(entity.getUri() + UrlHelpers.S3TOKEN); } } /** * Set the URL of a versionable entity. * @param entity */ public static void setVersionableUrl(Versionable entity){ if(entity == null) throw new IllegalArgumentException("Entity cannot be null"); if(entity.getUri() == null) throw new IllegalArgumentException("Entity.uri cannot be null null"); if(entity.getVersionNumber() == null) throw new IllegalArgumentException("Entity version number cannot be null"); // This URL wil list all version for this entity. entity.setVersions(entity.getUri()+VERSION); // This URL will reference this specific version of the entity. entity.setVersionUrl(entity.getUri()+VERSION+"/"+entity.getVersionNumber()); } /** * * @param entity * @param request */ public static void setAllUrlsForEntity(Entity entity, HttpServletRequest request){ // First set the base url setBaseUriForEntity(entity, request); // Set the Entity types setAllEntityUrls(entity); // Set the specialty types // Versions if(entity instanceof Versionable){ setVersionableUrl((Versionable)entity); } // Set the entity type entity.setEntityType(entity.getClass().getName()); } /** * Helper method to validate all urs. * @param object */ public static void validateAllUrls(Entity object) { if(object == null) throw new IllegalArgumentException("Entity cannot be null"); if(object.getUri() == null) throw new IllegalArgumentException("Entity.uri cannot be null"); EntityType type = EntityType.getNodeTypeForClass(object.getClass()); String expectedBaseSuffix = UrlHelpers.ENTITY +"/"+object.getId(); if(!object.getUri().endsWith(expectedBaseSuffix)){ throw new IllegalArgumentException("Expected base uri suffix: "+expectedBaseSuffix+" but was: "+object.getUri()); } String expected = object.getUri()+UrlHelpers.ANNOTATIONS; if(!expected.equals(object.getAnnotations())){ throw new IllegalArgumentException("Expected annotations: "+expected+" but was: "+object.getAnnotations()); } expected = object.getUri()+UrlHelpers.ACL; if(!expected.equals(object.getAccessControlList())){ throw new IllegalArgumentException("Expected annotations: "+expected+" but was: "+object.getAccessControlList()); } // Versionable if(object instanceof Versionable){ Versionable able = (Versionable) object; expected = object.getUri()+UrlHelpers.VERSION; if(!expected.equals(able.getVersions())){ throw new IllegalArgumentException("Expected versions: "+expected+" but was: "+able.getVersions()); } expected = object.getUri()+UrlHelpers.VERSION+"/"+able.getVersionNumber(); if(!expected.equals(able.getVersionUrl())){ throw new IllegalArgumentException("Expected versionUrl: "+expected+" but was: "+able.getVersionUrl()); } } // Locationable if(object instanceof Locationable) { Locationable able = (Locationable) object; expected = object.getUri() + UrlHelpers.S3TOKEN; if(!expected.equals(able.getS3Token())) { throw new IllegalArgumentException("Expected s3Token: " + expected + " but was " + able.getS3Token()); } } } /** * Create an ACL redirect URL. * @param request - The initial request. * @param type - The type of the redirect entity. * @param id - The ID of the redirect entity * @return */ public static String createACLRedirectURL(HttpServletRequest request, String id){ if(request == null) throw new IllegalArgumentException("Request cannot be null"); if(id == null) throw new IllegalArgumentException("ID cannot be null"); StringBuilder redirectURL = new StringBuilder(); redirectURL.append(UrlHelpers.getUrlPrefixFromRequest(request)); redirectURL.append(UrlHelpers.ENTITY); redirectURL.append("/"); redirectURL.append(id); redirectURL.append(UrlHelpers.ACL); return redirectURL.toString(); } public static String getAttachmentTypeURL(ServiceConstants.AttachmentType type) { if (type == AttachmentType.ENTITY) return UrlHelpers.ENTITY; else if (type == AttachmentType.USER_PROFILE) return UrlHelpers.USER_PROFILE; else throw new IllegalArgumentException("Unrecognized attachment type: " + type); } }
services/repository/src/main/java/org/sagebionetworks/repo/web/UrlHelpers.java
package org.sagebionetworks.repo.web; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import org.sagebionetworks.repo.model.ServiceConstants; import org.sagebionetworks.repo.model.ServiceConstants.AttachmentType; import org.sagebionetworks.repo.model.Annotations; import org.sagebionetworks.repo.model.Entity; import org.sagebionetworks.repo.model.EntityType; import org.sagebionetworks.repo.model.Locationable; import org.sagebionetworks.repo.model.PrefixConst; import org.sagebionetworks.repo.model.Versionable; /** * UrlHelpers is responsible for the formatting of all URLs exposed by the * service. * * The various controllers should not be formatting URLs. They should instead * call methods in this helper. Its important to keep URL formulation logic in * one place to ensure consistency across the space of URLs that this service * supports. * * @author deflaux */ public class UrlHelpers { private static final Logger log = Logger.getLogger(UrlHelpers.class.getName()); public static final String ACCESS = "/access"; /** * Used for batch requests */ public static final String ALL = "/all"; public static final String BATCH = "/batch"; public static final String PERMISSIONS = "/permissions"; public static final String ACCESS_TYPE_PARAM = "accessType"; public static final String BUNDLE = "/bundle"; public static final String GENERATED_BY = "/generatedBy"; /** * URL prefix for all objects that are referenced by their ID. * */ public static final String ID_PATH_VARIABLE = "id"; public static final String ID = "/{"+ID_PATH_VARIABLE+"}"; public static final String IDS_PATH_VARIABLE = "ids"; /** * URL prefix for all objects that are referenced by their ID. * */ public static final String PROFILE_ID = "/{profileId}"; public static final String PARENT_TYPE = "/{parentType}"; public static final String PARENT_ID = "/{parentId}"; public static final String VERSION_NUMBER = "/{versionNumber}"; public static final String PARENT_TYPE_ID = PARENT_TYPE+PARENT_ID; // public static final String TOKEN_ID = "{tokenId}/{filename}.{mimeType}"; public static final String TYPE = "/type"; public static final String TYPE_HEADER = "/header"; /** * The URL prefix for all object's Access Control List (ACL). */ public static final String ACL = "/acl"; public static final String BENEFACTOR = "/benefactor"; /** * The request parameter to enforce ACL inheritance of child nodes. */ public static final String RECURSIVE = "recursive"; /** * URL suffix for entity annotations * */ public static final String ANNOTATIONS = "/annotations"; /** * URL suffix for locationable entity S3Token * */ public static final String S3TOKEN = "/s3Token"; /** * Used to get the path of a entity. */ public static final String PATH = "/path"; /** * URL suffix for entity schemas */ public static final String SCHEMA = "/schema"; public static final String REGISTRY = "/registry"; /** * The Effective schema is the flattened schema of an entity. */ public static final String EFFECTIVE_SCHEMA = "/effectiveSchema"; public static final String REST_RESOURCES = "/REST/resources"; public static final String VERSION = "/version"; public static final String PROMOTE_VERSION = "/promoteVersion"; public static final String REFERENCED_BY = "/referencedby"; public static final String ATTACHMENT_S3_TOKEN = "/s3AttachmentToken"; public static final String ATTACHMENT_URL = "/attachmentUrl"; public static final String MIGRATION_OBJECT_ID_PARAM = "id"; /** * parameter used by migration services to describe the type of migration * to be performed */ public static final String MIGRATION_TYPE_PARAM = "migrationType"; /** * All of the base URLs for Synapse objects */ public static final String ENTITY = PrefixConst.ENTITY; public static final String USER_PROFILE = PrefixConst.USER_PROFILE; public static final String HEALTHCHECK = PrefixConst.HEALTHCHECK; public static final String VERSIONINFO = PrefixConst.VERSIONINFO; public static final String ACTIVITY = PrefixConst.ACTIVITY; /** * All of the base URLs for Synapse object batch requests */ public static final String ENTITY_TYPE = ENTITY+TYPE; public static final String ENTITY_TYPE_HEADER = ENTITY+TYPE_HEADER; /** * All of the base URLs for Synapse objects with ID. */ public static final String ENTITY_ID = ENTITY+ID; public static final String USER_PROFILE_ID = USER_PROFILE+PROFILE_ID; public static final String ENTITY_BUNDLE = ENTITY+BUNDLE; public static final String ENTITY_ID_BUNDLE = ENTITY_ID+BUNDLE; public static final String ENTITY_ID_ACL = ENTITY_ID+ACL; public static final String ENTITY_ID_ID_BENEFACTOR = ENTITY_ID+BENEFACTOR; public static final String FILE= "/file"; public static final String ENTITY_FILE = ENTITY_ID+FILE; public static final String ENTITY_VERSION_FILE = ENTITY_ID+VERSION+VERSION_NUMBER+FILE; /** * Activity URLs */ public static final String ACTIVITY_ID = ACTIVITY+ID; /** * Used to get an entity attachment token */ public static final String ENTITY_S3_ATTACHMENT_TOKEN = ENTITY_ID+ATTACHMENT_S3_TOKEN; /** * The url used to get an attachment URL. */ public static final String ENTITY_ATTACHMENT_URL = ENTITY_ID+ATTACHMENT_URL; /** * The url used to get a user profile attachment URL. */ public static final String USER_PROFILE_ATTACHMENT_URL = USER_PROFILE_ID+ATTACHMENT_URL; /** * The base URL for Synapse objects's type (a.k.a. EntityHeader) */ public static final String ENTITY_ID_TYPE = ENTITY_ID+TYPE; /** * All of the base URLs for Synapse objects's Annotations. */ public static final String ENTITY_ANNOTATIONS = ENTITY_ID+ANNOTATIONS; /** * All of the base URLs for locationable entity s3Tokens */ public static final String ENTITY_S3TOKEN = ENTITY_ID+S3TOKEN; /** * Used to get a user profile attachment token */ public static final String USER_PROFILE_S3_ATTACHMENT_TOKEN = USER_PROFILE_ID+ATTACHMENT_S3_TOKEN; /** * All of the base URLs for Synapse objects's paths. */ public static final String ENTITY_PATH = ENTITY_ID+PATH; /** * All of the base URLs for Synapse object's versions. */ public static final String ENTITY_PROMOTE_VERSION = ENTITY_ID+PROMOTE_VERSION+VERSION_NUMBER; public static final String ENTITY_VERSION = ENTITY_ID+VERSION; public static final String ENTITY_VERSION_NUMBER = ENTITY_VERSION+VERSION_NUMBER; /** * Get the annotations of a specific version of an entity */ public static final String ENTITY_VERSION_ANNOTATIONS = ENTITY_VERSION_NUMBER+ANNOTATIONS; /** * Get the bundle for a specific version of an entity */ public static final String ENTITY_VERSION_NUMBER_BUNDLE = ENTITY_VERSION_NUMBER+BUNDLE; /** * Get the generating activity for the current version of an entity */ public static final String ENTITY_GENERATED_BY = ENTITY_ID+GENERATED_BY; /** * Get the generating activity for a specific version of an entity */ public static final String ENTITY_VERSION_GENERATED_BY = ENTITY_VERSION_NUMBER+GENERATED_BY; /** * Gets the root node. */ public static final String ENTITY_ROOT = ENTITY + "/root"; /** * Gets the ancestors for the specified node. */ public static final String ENTITY_ANCESTORS = ENTITY_ID + "/ancestors"; /** * Gets the descendants for the specified node. */ public static final String ENTITY_DESCENDANTS = ENTITY_ID + "/descendants"; /** * Gets the descendants of a particular generation for the specified node. */ public static final String GENERATION = "generation"; /** * Gets the descendants of a particular generation for the specified node. */ public static final String ENTITY_DESCENDANTS_GENERATION = ENTITY_ID + "/descendants/{" + GENERATION + "}"; /** * Gets the parent for the specified node. */ public static final String ENTITY_PARENT = ENTITY_ID + "/parent"; /** * Gets the children for the specified node. */ public static final String ENTITY_CHILDREN = ENTITY_ID + "/children"; /** * For trash can APIs. */ public static final String TRASHCAN = "/trash"; /** * Moves an entity to the trash can. */ public static final String TRASHCAN_TRASH = TRASHCAN + "/trash" + ID; /** * Restores an entity from the trash can back to a parent entity. */ public static final String TRASHCAN_RESTORE = TRASHCAN + "/restore" + ID + PARENT_ID; /** * Views the current trash can. */ public static final String TRASHCAN_VIEW = TRASHCAN + "/view"; /** * URL path for query controller * */ public static final String QUERY = "/query"; /** * URL prefix for Users in the system * */ public static final String USER = "/user"; /** * URL prefix for User Group model objects * */ public static final String USERGROUP = "/userGroup"; public static final String ACCESS_REQUIREMENT = "/accessRequirement"; public static final String ACCESS_REQUIREMENT_WITH_ENTITY_ID = ENTITY_ID+ACCESS_REQUIREMENT; public static final String ACCESS_REQUIREMENT_WITH_REQUIREMENT_ID = ACCESS_REQUIREMENT+"/{requirementId}"; public static final String ACCESS_REQUIREMENT_UNFULFILLED_WITH_ID = ENTITY_ID+"/accessRequirementUnfulfilled"; public static final String ACCESS_APPROVAL = "/accessApproval"; public static final String ACCESS_APPROVAL_WITH_ENTITY_ID = ENTITY_ID+ACCESS_APPROVAL; public static final String ACCESS_APPROVAL_WITH_APPROVAL_ID = ACCESS_APPROVAL+"/{approvalId}"; /** * URL prefix for Users in a UserGroup * */ public static final String RESOURCES = "/resources"; /** * URL prefix for User mirroring service * */ public static final String USER_MIRROR = "/userMirror"; /** * All administration URLs must start with this URL or calls will be * blocked when Synapse enters READ_ONLY or DOWN modes for maintenance. */ public static final String ADMIN = "/admin"; /** * These are the new more RESTful backup/restore URLS. */ public static final String DAEMON = ADMIN+"/daemon"; public static final String BACKUP = "/backup"; public static final String RESTORE = "/restore"; public static final String DAEMON_ID = "/{daemonId}"; public static final String ENTITY_BACKUP_DAMEON = DAEMON+BACKUP; public static final String ENTITY_RESTORE_DAMEON = DAEMON+RESTORE; public static final String ENTITY_DAEMON_ID = DAEMON+DAEMON_ID; public static final String CONCEPT = "/concept"; public static final String CONCEPT_ID = CONCEPT+ID; public static final String CHILDERN_TRANSITIVE = "/childrenTransitive"; public static final String CONCEPT_ID_CHILDERN_TRANSITIVE = CONCEPT_ID+CHILDERN_TRANSITIVE; /** * Storage usage summary for the current user. */ public static final String STORAGE_SUMMARY = "/storageSummary"; /** * Itemized storage usage for the current user. */ public static final String STORAGE_DETAILS = "/storageDetails"; /** * The user whose storage usage is queried. */ public static final String STORAGE_USER_ID = "userId"; /** * Storage usage summary for the specified user. */ public static final String STORAGE_SUMMARY_USER_ID = STORAGE_SUMMARY + "/{" + STORAGE_USER_ID + "}"; /** * Itemized storage usage for the specified user. */ public static final String STORAGE_DETAILS_USER_ID = STORAGE_DETAILS + "/{" + STORAGE_USER_ID + "}"; /** * Itemized storage usage for the specified NODE. */ public static final String STORAGE_DETAILS_ENTITY_ID = STORAGE_DETAILS + ENTITY_ID; /** * Storage usage summary for administrators. */ public static final String ADMIN_STORAGE_SUMMARY = ADMIN + STORAGE_SUMMARY; /** * Storage usage summaries, aggregated by users, for administrators. */ public static final String ADMIN_STORAGE_SUMMARY_PER_USER = ADMIN_STORAGE_SUMMARY + "/perUser"; /** * Storage usage summaries, aggregated by entities, for administrators. */ public static final String ADMIN_STORAGE_SUMMARY_PER_ENTITY = ADMIN_STORAGE_SUMMARY + "/perEntity"; /** * Public access for Synapse user and group info */ public static final String USER_GROUP_HEADERS = "/userGroupHeaders"; /** * Public batch request access for Synapse user and group info */ public static final String USER_GROUP_HEADERS_BATCH = USER_GROUP_HEADERS + BATCH; /** * The name of the query parameter for a prefix filter. */ public static final String PREFIX_FILTER = "prefix"; /** * The other header key used to request JSONP */ public static final String REQUEST_CALLBACK_JSONP = "callback"; /** * The stack status of synapse */ public static final String STACK_STATUS = ADMIN+"/synapse/status"; /** * Mapping of dependent property classes to their URL suffixes */ private static final Map<Class, String> PROPERTY2URLSUFFIX; /** * The parameter for a resource name. */ public static final String RESOURCE_ID = "resourceId"; public static final String GET_ALL_BACKUP_OBJECTS = "/backupObjects"; public static final String GET_ALL_BACKUP_OBJECTS_COUNTS = "/backupObjectsCounts"; /** * Used by AdministrationController service to say whether object dependencies should be calculated * when listing objects to back up. */ public static final String INCLUDE_DEPENDENCIES_PARAM = "includeDependencies"; // Competition URLs public static final String COMPETITION = "/competition"; public static final String COMPETITION_ID_PATH_VAR = "{compId}"; public static final String COMPETITION_WITH_ID = COMPETITION + "/"+COMPETITION_ID_PATH_VAR; public static final String COMPETITION_WITH_NAME = COMPETITION + "/name/{name}"; public static final String COMPETITION_COUNT = COMPETITION + "/count"; public static final String PARTICIPANT = COMPETITION_WITH_ID + "/participant"; public static final String PARTICIPANT_WITH_ID = PARTICIPANT + "/{partId}"; public static final String PARTICIPANT_COUNT = PARTICIPANT + "/count"; public static final String STATUS = "status"; public static final String SUBMISSION = COMPETITION + "/submission"; public static final String SUBMISSION_WITH_ID = SUBMISSION + "/{subId}"; public static final String SUBMISSION_STATUS = SUBMISSION_WITH_ID + "/status"; public static final String SUBMISSION_WITH_COMP_ID = COMPETITION_WITH_ID + "/submission"; public static final String SUBMISSION_WITH_COMP_ID_BUNDLE = SUBMISSION_WITH_COMP_ID + BUNDLE; public static final String SUBMISSION_WITH_COMP_ID_ADMIN = SUBMISSION_WITH_COMP_ID + ALL; public static final String SUBMISSION_WITH_COMP_ID_ADMIN_BUNDLE = SUBMISSION_WITH_COMP_ID + BUNDLE + ALL; public static final String SUBMISSION_COUNT = SUBMISSION_WITH_COMP_ID + "/count"; // Wiki URL public static final String WIKI = "/wiki"; public static final String WIKI_HEADER_TREE = "/wikiheadertree"; public static final String ATTACHMENT = "/attachment"; public static final String ATTACHMENT_PREVIEW = "/attachmentpreview"; public static final String ATTACHMENT_HANDLES = "/attachmenthandles"; public static final String WIKI_WITH_ID = WIKI + "/{wikiId}"; // Entity public static final String ENTITY_OWNER_ID = ENTITY+"/{ownerId}"; public static final String ENTITY_WIKI = ENTITY_OWNER_ID + WIKI; public static final String ENTITY_WIKI_TREE = ENTITY_OWNER_ID + WIKI_HEADER_TREE; public static final String ENTITY_WIKI_ID = ENTITY_OWNER_ID + WIKI_WITH_ID; public static final String ENTITY_WIKI_ID_ATTCHMENT_HANDLE = ENTITY_OWNER_ID + WIKI_WITH_ID+ATTACHMENT_HANDLES; public static final String ENTITY_WIKI_ID_ATTCHMENT_FILE = ENTITY_OWNER_ID + WIKI_WITH_ID+ATTACHMENT; public static final String ENTITY_WIKI_ID_ATTCHMENT_FILE_PREVIEW = ENTITY_OWNER_ID + WIKI_WITH_ID+ATTACHMENT_PREVIEW; // competition public static final String COMPETITION_OWNER_ID = COMPETITION+"/{ownerId}"; public static final String COMPETITION_WIKI = COMPETITION_OWNER_ID+ WIKI; public static final String COMPETITION_WIKI_TREE = COMPETITION_OWNER_ID + WIKI_HEADER_TREE; public static final String COMPETITION_WIKI_ID =COMPETITION_OWNER_ID + WIKI_WITH_ID; public static final String COMPETITION_WIKI_ID_ATTCHMENT_HANDLE =COMPETITION_OWNER_ID + WIKI_WITH_ID+ATTACHMENT_HANDLES; public static final String COMPETITION_WIKI_ID_ATTCHMENT_FILE =COMPETITION_OWNER_ID + WIKI_WITH_ID+ATTACHMENT; public static final String COMPETITION_WIKI_ID_ATTCHMENT_FILE_PREVIEW =COMPETITION_OWNER_ID + WIKI_WITH_ID+ATTACHMENT_PREVIEW; /** * This is a memoized cache for our URL regular expressions */ private static Map<Class, Pattern> MODEL2REGEX = new HashMap<Class, Pattern>(); static { Map<Class, String> property2urlsuffix = new HashMap<Class, String>(); property2urlsuffix.put(Annotations.class, ANNOTATIONS); PROPERTY2URLSUFFIX = Collections.unmodifiableMap(property2urlsuffix); } /** * Determine the controller URL prefix for a given model class * * @param theModelClass * @return the URL for the model class */ // @SuppressWarnings("unchecked") // public static String getUrlForModel(Class theModelClass) { // EntityType type = EntityType.getNodeTypeForClass(theModelClass); // return type.getUrlPrefix(); // } /** * Helper function to create a relative URL for an entity's annotations * <p> * * This includes not only the entity id but also the controller and servlet * portions of the path * * @param request * @return the uri for this entity's annotations */ public static String makeEntityAnnotationsUri(String entityId) { return ENTITY + "/" + entityId + ANNOTATIONS; } /** * Helper function to create a relative URL for an entity's ACL * <p> * * This includes not only the entity id but also the controller and servlet * portions of the path * * @param request * @return the uri for this entity's annotations */ public static String makeEntityACLUri(String entityId) { return ENTITY + "/" + entityId + ACL; } /** * Helper function to create a relative URL for an entity's dependent * property * <p> * * This includes not only the entity id but also the controller and servlet * portions of the path * * @param request * @return the uri for this entity's annotations */ public static String makeEntityPropertyUri(HttpServletRequest request) { return request.getRequestURI(); } /** * Helper function to create a relative URL for an entity's annotations * <p> * * This includes not only the entity id but also the controller and servlet * portions of the path * * @param entity * @param propertyClass * @param request * @return the uri for this entity's annotations */ @SuppressWarnings("unchecked") public static String makeEntityPropertyUri(Entity entity, Class propertyClass, HttpServletRequest request) { String urlPrefix = getUrlPrefixFromRequest(request); String uri = null; try { uri = urlPrefix + UrlHelpers.ENTITY + "/" + URLEncoder.encode(entity.getId(), "UTF-8") + PROPERTY2URLSUFFIX.get(propertyClass); } catch (UnsupportedEncodingException e) { log.log(Level.SEVERE, "Something is really messed up if we don't support UTF-8", e); } return uri; } /** * Helper function to translate ids found in URLs to ids used by the system * <p> * * Specifically we currently use the serialized system id url-encoded for * use in URLs * * @param id * @return URL-decoded entity id */ public static String getEntityIdFromUriId(String id) { String entityId = null; try { entityId = URLDecoder.decode(id, "UTF-8"); } catch (UnsupportedEncodingException e) { log.log(Level.SEVERE, "Something is really messed up if we don't support UTF-8", e); } return entityId; } /** * Get the URL prefix from a request. * @param request * @return Servlet context and path url prefix */ public static String getUrlPrefixFromRequest(HttpServletRequest request){ if(request == null) throw new IllegalArgumentException("Request cannot be null"); if(request.getServletPath() == null) throw new IllegalArgumentException("Servlet path cannot be null"); String urlPrefix = (null != request.getContextPath()) ? request.getContextPath() + request.getServletPath() : request.getServletPath(); return urlPrefix; } /** * Set the URI for any entity. * @param entityId * @param entityClass * @param urlPrefix * @return the entity uri */ public static String createEntityUri(String entityId, Class<? extends Entity> entityClass, String urlPrefix){ if(entityId == null) throw new IllegalArgumentException("Entity id cannot be null"); if(entityClass == null) throw new IllegalArgumentException("Entity class cannot be null"); if(urlPrefix == null) throw new IllegalArgumentException("Url prefix cannot be null"); StringBuilder builder = new StringBuilder(); builder.append(urlPrefix); builder.append(UrlHelpers.ENTITY); builder.append("/"); builder.append(entityId); return builder.toString(); } /** * Set the base uri for any entity. * @param entity * @param request */ public static void setBaseUriForEntity(Entity entity, HttpServletRequest request){ if(entity == null) throw new IllegalArgumentException("Entity cannot be null"); if(request == null) throw new IllegalArgumentException("Request cannot be null"); // First get the prefix String prefix = UrlHelpers.getUrlPrefixFromRequest(request); // Now build the uri. String uri = UrlHelpers.createEntityUri(entity.getId(), entity.getClass(), prefix); entity.setUri(uri); } /** * Set the all of the Entity URLs (annotations, ACL) * @param entity */ public static void setAllEntityUrls(Entity entity){ if(entity == null) throw new IllegalArgumentException("Entity cannot be null"); if(entity.getUri() == null) throw new IllegalArgumentException("Entity.uri cannot be null null"); // Add the annotations entity.setAnnotations(entity.getUri()+ANNOTATIONS); // Add the acl entity.setAccessControlList(entity.getUri()+ACL); if(entity instanceof Locationable) { Locationable able = (Locationable) entity; able.setS3Token(entity.getUri() + UrlHelpers.S3TOKEN); } } /** * Set the URL of a versionable entity. * @param entity */ public static void setVersionableUrl(Versionable entity){ if(entity == null) throw new IllegalArgumentException("Entity cannot be null"); if(entity.getUri() == null) throw new IllegalArgumentException("Entity.uri cannot be null null"); if(entity.getVersionNumber() == null) throw new IllegalArgumentException("Entity version number cannot be null"); // This URL wil list all version for this entity. entity.setVersions(entity.getUri()+VERSION); // This URL will reference this specific version of the entity. entity.setVersionUrl(entity.getUri()+VERSION+"/"+entity.getVersionNumber()); } /** * * @param entity * @param request */ public static void setAllUrlsForEntity(Entity entity, HttpServletRequest request){ // First set the base url setBaseUriForEntity(entity, request); // Set the Entity types setAllEntityUrls(entity); // Set the specialty types // Versions if(entity instanceof Versionable){ setVersionableUrl((Versionable)entity); } // Set the entity type entity.setEntityType(entity.getClass().getName()); } /** * Helper method to validate all urs. * @param object */ public static void validateAllUrls(Entity object) { if(object == null) throw new IllegalArgumentException("Entity cannot be null"); if(object.getUri() == null) throw new IllegalArgumentException("Entity.uri cannot be null"); EntityType type = EntityType.getNodeTypeForClass(object.getClass()); String expectedBaseSuffix = UrlHelpers.ENTITY +"/"+object.getId(); if(!object.getUri().endsWith(expectedBaseSuffix)){ throw new IllegalArgumentException("Expected base uri suffix: "+expectedBaseSuffix+" but was: "+object.getUri()); } String expected = object.getUri()+UrlHelpers.ANNOTATIONS; if(!expected.equals(object.getAnnotations())){ throw new IllegalArgumentException("Expected annotations: "+expected+" but was: "+object.getAnnotations()); } expected = object.getUri()+UrlHelpers.ACL; if(!expected.equals(object.getAccessControlList())){ throw new IllegalArgumentException("Expected annotations: "+expected+" but was: "+object.getAccessControlList()); } // Versionable if(object instanceof Versionable){ Versionable able = (Versionable) object; expected = object.getUri()+UrlHelpers.VERSION; if(!expected.equals(able.getVersions())){ throw new IllegalArgumentException("Expected versions: "+expected+" but was: "+able.getVersions()); } expected = object.getUri()+UrlHelpers.VERSION+"/"+able.getVersionNumber(); if(!expected.equals(able.getVersionUrl())){ throw new IllegalArgumentException("Expected versionUrl: "+expected+" but was: "+able.getVersionUrl()); } } // Locationable if(object instanceof Locationable) { Locationable able = (Locationable) object; expected = object.getUri() + UrlHelpers.S3TOKEN; if(!expected.equals(able.getS3Token())) { throw new IllegalArgumentException("Expected s3Token: " + expected + " but was " + able.getS3Token()); } } } /** * Create an ACL redirect URL. * @param request - The initial request. * @param type - The type of the redirect entity. * @param id - The ID of the redirect entity * @return */ public static String createACLRedirectURL(HttpServletRequest request, String id){ if(request == null) throw new IllegalArgumentException("Request cannot be null"); if(id == null) throw new IllegalArgumentException("ID cannot be null"); StringBuilder redirectURL = new StringBuilder(); redirectURL.append(UrlHelpers.getUrlPrefixFromRequest(request)); redirectURL.append(UrlHelpers.ENTITY); redirectURL.append("/"); redirectURL.append(id); redirectURL.append(UrlHelpers.ACL); return redirectURL.toString(); } public static String getAttachmentTypeURL(ServiceConstants.AttachmentType type) { if (type == AttachmentType.ENTITY) return UrlHelpers.ENTITY; else if (type == AttachmentType.USER_PROFILE) return UrlHelpers.USER_PROFILE; else throw new IllegalArgumentException("Unrecognized attachment type: " + type); } }
Better URL names
services/repository/src/main/java/org/sagebionetworks/repo/web/UrlHelpers.java
Better URL names
<ide><path>ervices/repository/src/main/java/org/sagebionetworks/repo/web/UrlHelpers.java <ide> /** <ide> * For trash can APIs. <ide> */ <del> public static final String TRASHCAN = "/trash"; <add> public static final String TRASHCAN = "/trashcan"; <ide> <ide> /** <ide> * Moves an entity to the trash can.
Java
mit
bc0429a3f85a5bcd903d3c705e29e608625ec4c7
0
nilsschmidt1337/ldparteditor,nilsschmidt1337/ldparteditor
/* MIT - License Copyright (c) 2012 - this year, Nils Schmidt 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. */ package org.nschmidt.ldparteditor.shells.editor3d; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.math.BigDecimal; import java.net.URL; import java.net.URLConnection; import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.swt.SWT; import org.eclipse.swt.SWTException; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.opengl.GLCanvas; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.wb.swt.SWTResourceManager; import org.lwjgl.LWJGLException; import org.lwjgl.opengl.GLContext; import org.lwjgl.util.vector.Matrix4f; import org.lwjgl.util.vector.Vector3f; import org.lwjgl.util.vector.Vector4f; import org.nschmidt.ldparteditor.composites.Composite3D; import org.nschmidt.ldparteditor.composites.CompositeContainer; import org.nschmidt.ldparteditor.composites.CompositeScale; import org.nschmidt.ldparteditor.composites.ToolItem; import org.nschmidt.ldparteditor.composites.compositetab.CompositeTab; import org.nschmidt.ldparteditor.composites.primitive.CompositePrimitive; import org.nschmidt.ldparteditor.data.DatFile; import org.nschmidt.ldparteditor.data.DatType; import org.nschmidt.ldparteditor.data.GColour; import org.nschmidt.ldparteditor.data.GData; import org.nschmidt.ldparteditor.data.GData1; import org.nschmidt.ldparteditor.data.GDataPNG; import org.nschmidt.ldparteditor.data.GraphicalDataTools; import org.nschmidt.ldparteditor.data.LibraryManager; import org.nschmidt.ldparteditor.data.Matrix; import org.nschmidt.ldparteditor.data.Primitive; import org.nschmidt.ldparteditor.data.ReferenceParser; import org.nschmidt.ldparteditor.data.RingsAndCones; import org.nschmidt.ldparteditor.data.Vertex; import org.nschmidt.ldparteditor.data.VertexManager; import org.nschmidt.ldparteditor.dialogs.colour.ColourDialog; import org.nschmidt.ldparteditor.dialogs.copy.CopyDialog; import org.nschmidt.ldparteditor.dialogs.edger2.EdgerDialog; import org.nschmidt.ldparteditor.dialogs.intersector.IntersectorDialog; import org.nschmidt.ldparteditor.dialogs.isecalc.IsecalcDialog; import org.nschmidt.ldparteditor.dialogs.keys.KeyTableDialog; import org.nschmidt.ldparteditor.dialogs.lines2pattern.Lines2PatternDialog; import org.nschmidt.ldparteditor.dialogs.logupload.LogUploadDialog; import org.nschmidt.ldparteditor.dialogs.newproject.NewProjectDialog; import org.nschmidt.ldparteditor.dialogs.pathtruder.PathTruderDialog; import org.nschmidt.ldparteditor.dialogs.rectifier.RectifierDialog; import org.nschmidt.ldparteditor.dialogs.ringsandcones.RingsAndConesDialog; import org.nschmidt.ldparteditor.dialogs.rotate.RotateDialog; import org.nschmidt.ldparteditor.dialogs.round.RoundDialog; import org.nschmidt.ldparteditor.dialogs.scale.ScaleDialog; import org.nschmidt.ldparteditor.dialogs.selectvertex.VertexDialog; import org.nschmidt.ldparteditor.dialogs.setcoordinates.CoordinatesDialog; import org.nschmidt.ldparteditor.dialogs.slicerpro.SlicerProDialog; import org.nschmidt.ldparteditor.dialogs.symsplitter.SymSplitterDialog; import org.nschmidt.ldparteditor.dialogs.tjunction.TJunctionDialog; import org.nschmidt.ldparteditor.dialogs.translate.TranslateDialog; import org.nschmidt.ldparteditor.dialogs.txt2dat.Txt2DatDialog; import org.nschmidt.ldparteditor.dialogs.unificator.UnificatorDialog; import org.nschmidt.ldparteditor.dialogs.value.ValueDialog; import org.nschmidt.ldparteditor.dialogs.value.ValueDialogInt; import org.nschmidt.ldparteditor.enums.GLPrimitives; import org.nschmidt.ldparteditor.enums.ManipulatorScope; import org.nschmidt.ldparteditor.enums.MergeTo; import org.nschmidt.ldparteditor.enums.MouseButton; import org.nschmidt.ldparteditor.enums.MyLanguage; import org.nschmidt.ldparteditor.enums.ObjectMode; import org.nschmidt.ldparteditor.enums.OpenInWhat; import org.nschmidt.ldparteditor.enums.Perspective; import org.nschmidt.ldparteditor.enums.Threshold; import org.nschmidt.ldparteditor.enums.TransformationMode; import org.nschmidt.ldparteditor.enums.View; import org.nschmidt.ldparteditor.enums.WorkingMode; import org.nschmidt.ldparteditor.helpers.Manipulator; import org.nschmidt.ldparteditor.helpers.ShellHelper; import org.nschmidt.ldparteditor.helpers.Sphere; import org.nschmidt.ldparteditor.helpers.Version; import org.nschmidt.ldparteditor.helpers.WidgetSelectionHelper; import org.nschmidt.ldparteditor.helpers.composite3d.Edger2Settings; import org.nschmidt.ldparteditor.helpers.composite3d.IntersectorSettings; import org.nschmidt.ldparteditor.helpers.composite3d.IsecalcSettings; import org.nschmidt.ldparteditor.helpers.composite3d.PathTruderSettings; import org.nschmidt.ldparteditor.helpers.composite3d.RectifierSettings; import org.nschmidt.ldparteditor.helpers.composite3d.RingsAndConesSettings; import org.nschmidt.ldparteditor.helpers.composite3d.SelectorSettings; import org.nschmidt.ldparteditor.helpers.composite3d.SlicerProSettings; import org.nschmidt.ldparteditor.helpers.composite3d.SymSplitterSettings; import org.nschmidt.ldparteditor.helpers.composite3d.TJunctionSettings; import org.nschmidt.ldparteditor.helpers.composite3d.TreeData; import org.nschmidt.ldparteditor.helpers.composite3d.Txt2DatSettings; import org.nschmidt.ldparteditor.helpers.composite3d.UnificatorSettings; import org.nschmidt.ldparteditor.helpers.composite3d.ViewIdleManager; import org.nschmidt.ldparteditor.helpers.compositetext.ProjectActions; import org.nschmidt.ldparteditor.helpers.compositetext.SubfileCompiler; import org.nschmidt.ldparteditor.helpers.math.MathHelper; import org.nschmidt.ldparteditor.helpers.math.Vector3d; import org.nschmidt.ldparteditor.i18n.I18n; import org.nschmidt.ldparteditor.logger.NLogger; import org.nschmidt.ldparteditor.main.LDPartEditor; import org.nschmidt.ldparteditor.opengl.OpenGLRenderer; import org.nschmidt.ldparteditor.project.Project; import org.nschmidt.ldparteditor.resources.ResourceManager; import org.nschmidt.ldparteditor.shells.editormeta.EditorMetaWindow; import org.nschmidt.ldparteditor.shells.editortext.EditorTextWindow; import org.nschmidt.ldparteditor.shells.searchnreplace.SearchWindow; import org.nschmidt.ldparteditor.text.LDParsingException; import org.nschmidt.ldparteditor.text.References; import org.nschmidt.ldparteditor.text.StringHelper; import org.nschmidt.ldparteditor.text.TextTriangulator; import org.nschmidt.ldparteditor.text.UTF8BufferedReader; import org.nschmidt.ldparteditor.widgets.BigDecimalSpinner; import org.nschmidt.ldparteditor.widgets.TreeItem; import org.nschmidt.ldparteditor.widgets.ValueChangeAdapter; import org.nschmidt.ldparteditor.workbench.Composite3DState; import org.nschmidt.ldparteditor.workbench.Editor3DWindowState; import org.nschmidt.ldparteditor.workbench.WorkbenchManager; /** * The 3D editor window * <p> * Note: This class should be instantiated once, it defines all listeners and * part of the business logic. * * @author nils * */ public class Editor3DWindow extends Editor3DDesign { /** The window state of this window */ private Editor3DWindowState editor3DWindowState; /** The reference to this window */ private static Editor3DWindow window; /** The window state of this window */ private SearchWindow searchWindow; public static final ArrayList<GLCanvas> canvasList = new ArrayList<GLCanvas>(); public static final ArrayList<OpenGLRenderer> renders = new ArrayList<OpenGLRenderer>(); final private static AtomicBoolean alive = new AtomicBoolean(true); private boolean addingSomething = false; private boolean addingVertices = false; private boolean addingLines = false; private boolean addingTriangles = false; private boolean addingQuads = false; private boolean addingCondlines = false; private boolean addingSubfiles = false; private boolean movingAdjacentData = false; private boolean noTransparentSelection = false; private boolean bfcToggle = false; private ObjectMode workingType = ObjectMode.VERTICES; private WorkingMode workingAction = WorkingMode.SELECT; private GColour lastUsedColour = new GColour(16, .5f, .5f, .5f, 1f); private ManipulatorScope transformationMode = ManipulatorScope.LOCAL; private int snapSize = 1; private Txt2DatSettings ts = new Txt2DatSettings(); private Edger2Settings es = new Edger2Settings(); private RectifierSettings rs = new RectifierSettings(); private IsecalcSettings is = new IsecalcSettings(); private SlicerProSettings ss = new SlicerProSettings(); private IntersectorSettings ins = new IntersectorSettings(); private PathTruderSettings ps = new PathTruderSettings(); private SymSplitterSettings sims = new SymSplitterSettings(); private UnificatorSettings us = new UnificatorSettings(); private RingsAndConesSettings ris = new RingsAndConesSettings(); private SelectorSettings sels = new SelectorSettings(); private TJunctionSettings tjs = new TJunctionSettings(); private boolean updatingPngPictureTab; private int pngPictureUpdateCounter = 0; private final EditorMetaWindow metaWindow = new EditorMetaWindow(); private boolean updatingSelectionTab = true; private ArrayList<String> recentItems = new ArrayList<String>(); /** * Create the application window. */ public Editor3DWindow() { super(); final int[] i = new int[1]; final int[] j = new int[1]; final GLCanvas[] first1 = ViewIdleManager.firstCanvas; final OpenGLRenderer[] first2 = ViewIdleManager.firstRender; final int[] intervall = new int[] { 10 }; Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { if (ViewIdleManager.pause[0].get()) { ViewIdleManager.pause[0].set(false); intervall[0] = 500; } else { final int cs = canvasList.size(); if (i[0] < cs && cs > 0) { GLCanvas canvas; if (!canvasList.get(i[0]).equals(first1[0])) { canvas = first1[0]; if (canvas != null && !canvas.isDisposed()) { first2[0].drawScene(); first1[0] = null; first2[0] = null; } } canvas = canvasList.get(i[0]); if (!canvas.isDisposed()) { boolean stdMode = ViewIdleManager.renderLDrawStandard[0].get(); // FIXME Needs workaround since SWT upgrade to 4.5! if (renders.get(i[0]).getC3D().getRenderMode() != 5 || cs == 1 || stdMode) { renders.get(i[0]).drawScene(); if (stdMode) { j[0]++; } } } else { canvasList.remove(i[0]); renders.remove(i[0]); } i[0]++; } else { i[0] = 0; if (j[0] > cs) { j[0] = 0; ViewIdleManager.renderLDrawStandard[0].set(false); } } } Display.getCurrent().timerExec(intervall[0], this); intervall[0] = 10; } }); } /** * Run a fresh instance of this window */ public void run() { window = this; // Load recent files recentItems = WorkbenchManager.getUserSettingState().getRecentItems(); if (recentItems == null) recentItems = new ArrayList<String>(); // Load the window state data editor3DWindowState = WorkbenchManager.getEditor3DWindowState(); WorkbenchManager.setEditor3DWindow(this); // Closing this window causes the whole application to quit this.setBlockOnOpen(true); // Creating the window to get the shell this.create(); final Shell sh = this.getShell(); sh.setText(Version.getApplicationName()); sh.setImage(ResourceManager.getImage("imgDuke2.png")); //$NON-NLS-1$ sh.setMinimumSize(640, 480); sh.setBounds(this.editor3DWindowState.getWindowState().getSizeAndPosition()); if (this.editor3DWindowState.getWindowState().isCentered()) { ShellHelper.centerShellOnPrimaryScreen(sh); } // Maximize has to be called asynchronously sh.getDisplay().asyncExec(new Runnable() { @Override public void run() { sh.setMaximized(editor3DWindowState.getWindowState().isMaximized()); } }); // Set the snapping Manipulator.setSnap( WorkbenchManager.getUserSettingState().getMedium_move_snap(), WorkbenchManager.getUserSettingState().getMedium_rotate_snap(), WorkbenchManager.getUserSettingState().getMedium_scale_snap() ); // MARK All final listeners will be configured here.. NLogger.writeVersion(); btn_Sync[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { resetSearch(); int[][] stats = new int[15][3]; stats[0] = LibraryManager.syncProjectElements(treeItem_Project[0]); stats[5] = LibraryManager.syncUnofficialParts(treeItem_UnofficialParts[0]); stats[6] = LibraryManager.syncUnofficialSubparts(treeItem_UnofficialSubparts[0]); stats[7] = LibraryManager.syncUnofficialPrimitives(treeItem_UnofficialPrimitives[0]); stats[8] = LibraryManager.syncUnofficialHiResPrimitives(treeItem_UnofficialPrimitives48[0]); stats[9] = LibraryManager.syncUnofficialLowResPrimitives(treeItem_UnofficialPrimitives8[0]); stats[10] = LibraryManager.syncOfficialParts(treeItem_OfficialParts[0]); stats[11] = LibraryManager.syncOfficialSubparts(treeItem_OfficialSubparts[0]); stats[12] = LibraryManager.syncOfficialPrimitives(treeItem_OfficialPrimitives[0]); stats[13] = LibraryManager.syncOfficialHiResPrimitives(treeItem_OfficialPrimitives48[0]); stats[14] = LibraryManager.syncOfficialLowResPrimitives(treeItem_OfficialPrimitives8[0]); int additions = 0; int deletions = 0; int conflicts = 0; for (int[] is : stats) { additions += is[0]; deletions += is[1]; conflicts += is[2]; } txt_Search[0].setText(" "); //$NON-NLS-1$ txt_Search[0].setText(""); //$NON-NLS-1$ Set<DatFile> dfs = new HashSet<DatFile>(); for (OpenGLRenderer renderer : renders) { dfs.add(renderer.getC3D().getLockableDatFileReference()); } for (EditorTextWindow w : Project.getOpenTextWindows()) { for (CTabItem t : w.getTabFolder().getItems()) { DatFile txtDat = ((CompositeTab) t).getState().getFileNameObj(); if (txtDat != null) { dfs.add(txtDat); } } } for (DatFile df : dfs) { SubfileCompiler.compile(df, false, false); } for (EditorTextWindow w : Project.getOpenTextWindows()) { for (CTabItem t : w.getTabFolder().getItems()) { DatFile txtDat = ((CompositeTab) t).getState().getFileNameObj(); if (txtDat != null) { ((CompositeTab) t).parseForErrorAndHints(); ((CompositeTab) t).getTextComposite().redraw(); ((CompositeTab) t).getState().getTab().setText(((CompositeTab) t).getState().getFilenameWithStar()); } } } updateTree_unsavedEntries(); try { new ProgressMonitorDialog(Editor3DWindow.getWindow().getShell()).run(true, false, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask(I18n.E3D_LoadingPrimitives, IProgressMonitor.UNKNOWN); Thread.sleep(1500); } }); } catch (InvocationTargetException consumed) { } catch (InterruptedException consumed) { } cmp_Primitives[0].load(false); MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK); messageBox.setText(I18n.DIALOG_SyncTitle); Object[] messageArguments = {additions, deletions, conflicts}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.DIALOG_Sync); messageBox.setMessage(formatter.format(messageArguments)); messageBox.open(); } }); btn_LastOpen[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Menu lastOpenedMenu = new Menu(treeParts[0].getTree()); btn_LastOpen[0].setMenu(lastOpenedMenu); final int size = recentItems.size() - 1; for (int i = size; i > -1; i--) { final String path = recentItems.get(i); File f = new File(path); if (f.exists() && f.canRead()) { if (f.isFile()) { MenuItem mntmItem = new MenuItem(lastOpenedMenu, I18n.I18N_NON_BIDIRECT()); mntmItem.setEnabled(true); mntmItem.setText(path); mntmItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { File f = new File(path); if (f.exists() && f.isFile() && f.canRead()) openDatFile(getShell(), OpenInWhat.EDITOR_TEXT_AND_3D, path); } }); } else if (f.isDirectory()) { MenuItem mntmItem = new MenuItem(lastOpenedMenu, I18n.I18N_NON_BIDIRECT()); mntmItem.setEnabled(true); Object[] messageArguments = {path}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.E3D_LastProject); mntmItem.setText(formatter.format(messageArguments)); mntmItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { File f = new File(path); if (f.exists() && f.isDirectory() && f.canRead() && ProjectActions.openProject(path)) { Project.create(false); treeItem_Project[0].setData(Project.getProjectPath()); resetSearch(); LibraryManager.readProjectPartsParent(treeItem_ProjectParts[0]); LibraryManager.readProjectParts(treeItem_ProjectParts[0]); LibraryManager.readProjectSubparts(treeItem_ProjectSubparts[0]); LibraryManager.readProjectPrimitives(treeItem_ProjectPrimitives[0]); LibraryManager.readProjectHiResPrimitives(treeItem_ProjectPrimitives48[0]); LibraryManager.readProjectLowResPrimitives(treeItem_ProjectPrimitives8[0]); treeItem_OfficialParts[0].setData(null); txt_Search[0].setText(" "); //$NON-NLS-1$ txt_Search[0].setText(""); //$NON-NLS-1$ updateTree_unsavedEntries(); } } }); } } } java.awt.Point b = java.awt.MouseInfo.getPointerInfo().getLocation(); final int x = (int) b.getX(); final int y = (int) b.getY(); lastOpenedMenu.setLocation(x, y); lastOpenedMenu.setVisible(true); } }); btn_New[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ProjectActions.createNewProject(Editor3DWindow.getWindow(), false); addRecentFile(Project.getProjectPath()); } }); btn_Open[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (ProjectActions.openProject(null)) { addRecentFile(Project.getProjectPath()); Project.create(false); treeItem_Project[0].setData(Project.getProjectPath()); resetSearch(); LibraryManager.readProjectPartsParent(treeItem_ProjectParts[0]); LibraryManager.readProjectParts(treeItem_ProjectParts[0]); LibraryManager.readProjectSubparts(treeItem_ProjectSubparts[0]); LibraryManager.readProjectPrimitives(treeItem_ProjectPrimitives[0]); LibraryManager.readProjectHiResPrimitives(treeItem_ProjectPrimitives48[0]); LibraryManager.readProjectLowResPrimitives(treeItem_ProjectPrimitives8[0]); treeItem_OfficialParts[0].setData(null); txt_Search[0].setText(" "); //$NON-NLS-1$ txt_Search[0].setText(""); //$NON-NLS-1$ updateTree_unsavedEntries(); } } }); btn_Save[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (treeParts[0].getSelectionCount() == 1) { if (treeParts[0].getSelection()[0].getData() instanceof DatFile) { DatFile df = (DatFile) treeParts[0].getSelection()[0].getData(); if (!df.isReadOnly() && Project.getUnsavedFiles().contains(df)) { if (df.save()) { Editor3DWindow.getWindow().addRecentFile(df); Editor3DWindow.getWindow().updateTree_unsavedEntries(); } else { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK); messageBoxError.setText(I18n.DIALOG_Error); messageBoxError.setMessage(I18n.DIALOG_CantSaveFile); messageBoxError.open(); Editor3DWindow.getWindow().updateTree_unsavedEntries(); } } } else if (treeParts[0].getSelection()[0].getData() instanceof ArrayList<?>) { NLogger.debug(getClass(), "Saving all files from this group"); //$NON-NLS-1$ { @SuppressWarnings("unchecked") ArrayList<DatFile> dfs = (ArrayList<DatFile>) treeParts[0].getSelection()[0].getData(); for (DatFile df : dfs) { if (!df.isReadOnly() && Project.getUnsavedFiles().contains(df)) { if (df.save()) { Editor3DWindow.getWindow().addRecentFile(df); Project.removeUnsavedFile(df); Editor3DWindow.getWindow().updateTree_unsavedEntries(); } else { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK); messageBoxError.setText(I18n.DIALOG_Error); messageBoxError.setMessage(I18n.DIALOG_CantSaveFile); messageBoxError.open(); Editor3DWindow.getWindow().updateTree_unsavedEntries(); } } } } } else if (treeParts[0].getSelection()[0].getData() instanceof String) { if (treeParts[0].getSelection()[0].equals(treeItem_Project[0])) { NLogger.debug(getClass(), "Save the project..."); //$NON-NLS-1$ if (Project.isDefaultProject()) { ProjectActions.createNewProject(Editor3DWindow.getWindow(), true); } iterateOverItems(treeItem_ProjectParts[0]); iterateOverItems(treeItem_ProjectSubparts[0]); iterateOverItems(treeItem_ProjectPrimitives[0]); iterateOverItems(treeItem_ProjectPrimitives48[0]); iterateOverItems(treeItem_ProjectPrimitives8[0]); } else if (treeParts[0].getSelection()[0].equals(treeItem_Unofficial[0])) { iterateOverItems(treeItem_UnofficialParts[0]); iterateOverItems(treeItem_UnofficialSubparts[0]); iterateOverItems(treeItem_UnofficialPrimitives[0]); iterateOverItems(treeItem_UnofficialPrimitives48[0]); iterateOverItems(treeItem_UnofficialPrimitives8[0]); } NLogger.debug(getClass(), "Saving all files from this group to {0}", treeParts[0].getSelection()[0].getData()); //$NON-NLS-1$ } } else { NLogger.debug(getClass(), "Save the project..."); //$NON-NLS-1$ if (Project.isDefaultProject()) { ProjectActions.createNewProject(Editor3DWindow.getWindow(), true); } } } private void iterateOverItems(TreeItem ti) { { @SuppressWarnings("unchecked") ArrayList<DatFile> dfs = (ArrayList<DatFile>) ti.getData(); for (DatFile df : dfs) { if (!df.isReadOnly() && Project.getUnsavedFiles().contains(df)) { if (df.save()) { Editor3DWindow.getWindow().addRecentFile(df); Project.removeUnsavedFile(df); Editor3DWindow.getWindow().updateTree_unsavedEntries(); } else { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK); messageBoxError.setText(I18n.DIALOG_Error); messageBoxError.setMessage(I18n.DIALOG_CantSaveFile); messageBoxError.open(); Editor3DWindow.getWindow().updateTree_unsavedEntries(); } } } } } }); btn_SaveAll[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { HashSet<DatFile> dfs = new HashSet<DatFile>(Project.getUnsavedFiles()); for (DatFile df : dfs) { if (!df.isReadOnly()) { if (df.save()) { Editor3DWindow.getWindow().addRecentFile(df); Project.removeUnsavedFile(df); } else { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK); messageBoxError.setText(I18n.DIALOG_Error); messageBoxError.setMessage(I18n.DIALOG_CantSaveFile); messageBoxError.open(); } } } if (Project.isDefaultProject()) { ProjectActions.createNewProject(getWindow(), true); } Editor3DWindow.getWindow().updateTree_unsavedEntries(); } }); btn_NewDat[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { DatFile dat = createNewDatFile(getShell(), OpenInWhat.EDITOR_TEXT_AND_3D); if (dat != null) { addRecentFile(dat); } } }); btn_OpenDat[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { DatFile dat = openDatFile(getShell(), OpenInWhat.EDITOR_TEXT_AND_3D, null); if (dat != null) { addRecentFile(dat); } } }); btn_Undo[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().undo(null); } } }); btn_Redo[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().redo(null); } } }); if (NLogger.DEBUG) { btn_AddHistory[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().addHistory(); } } }); } btn_Select[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { clickBtnTest(btn_Select[0]); workingAction = WorkingMode.SELECT; } }); btn_Move[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { clickBtnTest(btn_Move[0]); workingAction = WorkingMode.MOVE; } }); btn_Rotate[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { clickBtnTest(btn_Rotate[0]); workingAction = WorkingMode.ROTATE; } }); btn_Scale[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { clickBtnTest(btn_Scale[0]); workingAction = WorkingMode.SCALE; } }); btn_Combined[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { clickBtnTest(btn_Combined[0]); workingAction = WorkingMode.COMBINED; } }); btn_Local[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { clickBtnTest(btn_Local[0]); transformationMode = ManipulatorScope.LOCAL; } }); btn_Global[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { clickBtnTest(btn_Global[0]); transformationMode = ManipulatorScope.GLOBAL; } }); btn_Vertices[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { clickBtnTest(btn_Vertices[0]); setWorkingType(ObjectMode.VERTICES); } }); btn_TrisNQuads[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { clickBtnTest(btn_TrisNQuads[0]); setWorkingType(ObjectMode.FACES); } }); btn_Lines[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { clickBtnTest(btn_Lines[0]); setWorkingType(ObjectMode.LINES); } }); btn_Subfiles[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { clickBtnTest(btn_Subfiles[0]); setWorkingType(ObjectMode.SUBFILES); } } }); btn_AddComment[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (!metaWindow.isOpened()) { metaWindow.run(); } else { metaWindow.open(); } } }); btn_AddVertex[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { resetAddState(); clickSingleBtn(btn_AddVertex[0]); setAddingVertices(btn_AddVertex[0].getSelection()); setAddingSomething(isAddingVertices()); } }); btn_AddPrimitive[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { resetAddState(); setAddingSubfiles(btn_AddPrimitive[0].getSelection()); setAddingSomething(isAddingSubfiles()); clickSingleBtn(btn_AddPrimitive[0]); } }); btn_AddLine[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { resetAddState(); setAddingLines(btn_AddLine[0].getSelection()); setAddingSomething(isAddingLines()); clickSingleBtn(btn_AddLine[0]); } }); btn_AddTriangle[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { resetAddState(); setAddingTriangles(btn_AddTriangle[0].getSelection()); setAddingSomething(isAddingTriangles()); clickSingleBtn(btn_AddTriangle[0]); } }); btn_AddQuad[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { resetAddState(); setAddingQuads(btn_AddQuad[0].getSelection()); setAddingSomething(isAddingQuads()); clickSingleBtn(btn_AddQuad[0]); } }); btn_AddCondline[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { resetAddState(); setAddingCondlines(btn_AddCondline[0].getSelection()); setAddingSomething(isAddingCondlines()); clickSingleBtn(btn_AddCondline[0]); } }); btn_MoveAdjacentData[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { clickSingleBtn(btn_MoveAdjacentData[0]); setMovingAdjacentData(btn_MoveAdjacentData[0].getSelection()); } }); btn_CompileSubfile[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Project.getFileToEdit().getVertexManager().addSnapshot(); SubfileCompiler.compile(Project.getFileToEdit(), false, false); } } }); btn_lineSize1[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { setLineSize(GLPrimitives.SPHERE1, GLPrimitives.SPHERE_INV1, 25f, .025f, .375f, btn_lineSize1[0]); } }); btn_lineSize2[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { setLineSize(GLPrimitives.SPHERE2, GLPrimitives.SPHERE_INV2, 50f, .050f, .75f, btn_lineSize2[0]); } }); btn_lineSize3[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { setLineSize(GLPrimitives.SPHERE3, GLPrimitives.SPHERE_INV3, 100f, .100f, 1.5f, btn_lineSize3[0]); } }); btn_lineSize4[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { setLineSize(GLPrimitives.SPHERE4, GLPrimitives.SPHERE_INV4, 200f, .200f, 3f, btn_lineSize4[0]); } }); btn_BFCswap[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager().windingChangeSelection(); } } }); btn_RoundSelection[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { if ((e.stateMask & SWT.CTRL) == SWT.CTRL) { if (new RoundDialog(getShell()).open() == IDialogConstants.CANCEL_ID) return; } Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager() .roundSelection(WorkbenchManager.getUserSettingState().getCoordsPrecision(), WorkbenchManager.getUserSettingState().getTransMatrixPrecision(), isMovingAdjacentData(), true); } } }); btn_Pipette[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { VertexManager vm = Project.getFileToEdit().getVertexManager(); vm.addSnapshot(); final GColour gColour2 = vm.getRandomSelectedColour(lastUsedColour); setLastUsedColour(gColour2); btn_LastUsedColour[0].removeListener(SWT.Paint, btn_LastUsedColour[0].getListeners(SWT.Paint)[0]); btn_LastUsedColour[0].removeListener(SWT.Selection, btn_LastUsedColour[0].getListeners(SWT.Selection)[0]); final Color col = SWTResourceManager.getColor((int) (gColour2.getR() * 255f), (int) (gColour2.getG() * 255f), (int) (gColour2.getB() * 255f)); final Point size = btn_LastUsedColour[0].computeSize(SWT.DEFAULT, SWT.DEFAULT); final int x = size.x / 4; final int y = size.y / 4; final int w = size.x / 2; final int h = size.y / 2; int num = gColour2.getColourNumber(); btn_LastUsedColour[0].addPaintListener(new PaintListener() { @Override public void paintControl(PaintEvent e) { e.gc.setBackground(col); e.gc.fillRectangle(x, y, w, h); if (gColour2.getA() == 1f) { e.gc.drawImage(ResourceManager.getImage("icon16_transparent.png"), 0, 0, 16, 16, x, y, w, h); //$NON-NLS-1$ } else { e.gc.drawImage(ResourceManager.getImage("icon16_halftrans.png"), 0, 0, 16, 16, x, y, w, h); //$NON-NLS-1$ } } }); btn_LastUsedColour[0].addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { int num = gColour2.getColourNumber(); if (!View.hasLDConfigColour(num)) { num = -1; } Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager().colourChangeSelection(num, gColour2.getR(), gColour2.getG(), gColour2.getB(), gColour2.getA()); } } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); if (num != -1) { Object[] messageArguments = {num, View.getLDConfigColourName(num)}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.EDITORTEXT_Colour1); btn_LastUsedColour[0].setToolTipText(formatter.format(messageArguments)); } else { StringBuilder colourBuilder = new StringBuilder(); colourBuilder.append("0x2"); //$NON-NLS-1$ colourBuilder.append(MathHelper.toHex((int) (255f * gColour2.getR())).toUpperCase()); colourBuilder.append(MathHelper.toHex((int) (255f * gColour2.getG())).toUpperCase()); colourBuilder.append(MathHelper.toHex((int) (255f * gColour2.getB())).toUpperCase()); Object[] messageArguments = {colourBuilder.toString()}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.EDITORTEXT_Colour2); btn_LastUsedColour[0].setToolTipText(formatter.format(messageArguments)); } btn_LastUsedColour[0].redraw(); } } }); btn_Palette[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { final GColour[] gColour2 = new GColour[1]; new ColourDialog(getShell(), gColour2).open(); if (gColour2[0] != null) { setLastUsedColour(gColour2[0]); int num = gColour2[0].getColourNumber(); if (!View.hasLDConfigColour(num)) { num = -1; } Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager().colourChangeSelection(num, gColour2[0].getR(), gColour2[0].getG(), gColour2[0].getB(), gColour2[0].getA()); btn_LastUsedColour[0].removeListener(SWT.Paint, btn_LastUsedColour[0].getListeners(SWT.Paint)[0]); btn_LastUsedColour[0].removeListener(SWT.Selection, btn_LastUsedColour[0].getListeners(SWT.Selection)[0]); final Color col = SWTResourceManager.getColor((int) (gColour2[0].getR() * 255f), (int) (gColour2[0].getG() * 255f), (int) (gColour2[0].getB() * 255f)); final Point size = btn_LastUsedColour[0].computeSize(SWT.DEFAULT, SWT.DEFAULT); final int x = size.x / 4; final int y = size.y / 4; final int w = size.x / 2; final int h = size.y / 2; btn_LastUsedColour[0].addPaintListener(new PaintListener() { @Override public void paintControl(PaintEvent e) { e.gc.setBackground(col); e.gc.fillRectangle(x, y, w, h); if (gColour2[0].getA() == 1f) { e.gc.drawImage(ResourceManager.getImage("icon16_transparent.png"), 0, 0, 16, 16, x, y, w, h); //$NON-NLS-1$ } else { e.gc.drawImage(ResourceManager.getImage("icon16_halftrans.png"), 0, 0, 16, 16, x, y, w, h); //$NON-NLS-1$ } } }); btn_LastUsedColour[0].addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { int num = gColour2[0].getColourNumber(); if (!View.hasLDConfigColour(num)) { num = -1; } Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager().colourChangeSelection(num, gColour2[0].getR(), gColour2[0].getG(), gColour2[0].getB(), gColour2[0].getA()); } } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); if (num != -1) { Object[] messageArguments = {num, View.getLDConfigColourName(num)}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.EDITORTEXT_Colour1); btn_LastUsedColour[0].setToolTipText(formatter.format(messageArguments)); } else { StringBuilder colourBuilder = new StringBuilder(); colourBuilder.append("0x2"); //$NON-NLS-1$ colourBuilder.append(MathHelper.toHex((int) (255f * gColour2[0].getR())).toUpperCase()); colourBuilder.append(MathHelper.toHex((int) (255f * gColour2[0].getG())).toUpperCase()); colourBuilder.append(MathHelper.toHex((int) (255f * gColour2[0].getB())).toUpperCase()); Object[] messageArguments = {colourBuilder.toString()}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.EDITORTEXT_Colour2); btn_LastUsedColour[0].setToolTipText(formatter.format(messageArguments)); } btn_LastUsedColour[0].redraw(); } } } }); btn_Coarse[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { BigDecimal m = WorkbenchManager.getUserSettingState().getCoarse_move_snap(); BigDecimal r = WorkbenchManager.getUserSettingState().getCoarse_rotate_snap(); BigDecimal s = WorkbenchManager.getUserSettingState().getCoarse_scale_snap(); snapSize = 2; spn_Move[0].setValue(m); spn_Rotate[0].setValue(r); spn_Scale[0].setValue(s); Manipulator.setSnap(m, r, s); } }); btn_Medium[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { BigDecimal m = WorkbenchManager.getUserSettingState().getMedium_move_snap(); BigDecimal r = WorkbenchManager.getUserSettingState().getMedium_rotate_snap(); BigDecimal s = WorkbenchManager.getUserSettingState().getMedium_scale_snap(); snapSize = 1; spn_Move[0].setValue(m); spn_Rotate[0].setValue(r); spn_Scale[0].setValue(s); Manipulator.setSnap(m, r, s); } }); btn_Fine[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { BigDecimal m = WorkbenchManager.getUserSettingState().getFine_move_snap(); BigDecimal r = WorkbenchManager.getUserSettingState().getFine_rotate_snap(); BigDecimal s = WorkbenchManager.getUserSettingState().getFine_scale_snap(); snapSize = 0; spn_Move[0].setValue(m); spn_Rotate[0].setValue(r); spn_Scale[0].setValue(s); Manipulator.setSnap(m, r, s); } }); btn_Coarse[0].addListener(SWT.MouseDown, new Listener() { @Override public void handleEvent(Event event) { if (event.button == MouseButton.RIGHT) { try { if (btn_Coarse[0].getMenu() != null) { btn_Coarse[0].getMenu().dispose(); } } catch (Exception ex) {} Menu gridMenu = new Menu(btn_Coarse[0]); btn_Coarse[0].setMenu(gridMenu); mnu_coarseMenu[0] = gridMenu; MenuItem mntmGridCoarseDefault = new MenuItem(gridMenu, I18n.I18N_NON_BIDIRECT()); mntm_gridCoarseDefault[0] = mntmGridCoarseDefault; mntmGridCoarseDefault.setEnabled(true); mntmGridCoarseDefault.setText(I18n.E3D_GridCoarseDefault); mntm_gridCoarseDefault[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { WorkbenchManager.getUserSettingState().setCoarse_move_snap(new BigDecimal("1")); //$NON-NLS-1$ WorkbenchManager.getUserSettingState().setCoarse_rotate_snap(new BigDecimal("90")); //$NON-NLS-1$ WorkbenchManager.getUserSettingState().setCoarse_scale_snap(new BigDecimal("2")); //$NON-NLS-1$ BigDecimal m = WorkbenchManager.getUserSettingState().getCoarse_move_snap(); BigDecimal r = WorkbenchManager.getUserSettingState().getCoarse_rotate_snap(); BigDecimal s = WorkbenchManager.getUserSettingState().getCoarse_scale_snap(); snapSize = 2; spn_Move[0].setValue(m); spn_Rotate[0].setValue(r); spn_Scale[0].setValue(s); Manipulator.setSnap(m, r, s); } }); java.awt.Point b = java.awt.MouseInfo.getPointerInfo().getLocation(); final int x = (int) b.getX(); final int y = (int) b.getY(); Menu menu = mnu_coarseMenu[0]; menu.setLocation(x, y); menu.setVisible(true); } } }); btn_Medium[0].addListener(SWT.MouseDown, new Listener() { @Override public void handleEvent(Event event) { if (event.button == MouseButton.RIGHT) { try { if (btn_Medium[0].getMenu() != null) { btn_Medium[0].getMenu().dispose(); } } catch (Exception ex) {} Menu gridMenu = new Menu(btn_Medium[0]); btn_Medium[0].setMenu(gridMenu); mnu_mediumMenu[0] = gridMenu; MenuItem mntmGridMediumDefault = new MenuItem(gridMenu, I18n.I18N_NON_BIDIRECT()); mntm_gridMediumDefault[0] = mntmGridMediumDefault; mntmGridMediumDefault.setEnabled(true); mntmGridMediumDefault.setText(I18n.E3D_GridMediumDefault); mntm_gridMediumDefault[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { WorkbenchManager.getUserSettingState().setMedium_move_snap(new BigDecimal("0.01")); //$NON-NLS-1$ WorkbenchManager.getUserSettingState().setMedium_rotate_snap(new BigDecimal("11.25")); //$NON-NLS-1$ WorkbenchManager.getUserSettingState().setMedium_scale_snap(new BigDecimal("1.1")); //$NON-NLS-1$ BigDecimal m = WorkbenchManager.getUserSettingState().getMedium_move_snap(); BigDecimal r = WorkbenchManager.getUserSettingState().getMedium_rotate_snap(); BigDecimal s = WorkbenchManager.getUserSettingState().getMedium_scale_snap(); snapSize = 1; spn_Move[0].setValue(m); spn_Rotate[0].setValue(r); spn_Scale[0].setValue(s); Manipulator.setSnap(m, r, s); } }); java.awt.Point b = java.awt.MouseInfo.getPointerInfo().getLocation(); final int x = (int) b.getX(); final int y = (int) b.getY(); Menu menu = mnu_mediumMenu[0]; menu.setLocation(x, y); menu.setVisible(true); } } }); btn_Fine[0].addListener(SWT.MouseDown, new Listener() { @Override public void handleEvent(Event event) { if (event.button == MouseButton.RIGHT) { try { if (btn_Fine[0].getMenu() != null) { btn_Fine[0].getMenu().dispose(); } } catch (Exception ex) {} Menu gridMenu = new Menu(btn_Fine[0]); btn_Fine[0].setMenu(gridMenu); mnu_fineMenu[0] = gridMenu; MenuItem mntmGridFineDefault = new MenuItem(gridMenu, I18n.I18N_NON_BIDIRECT()); mntm_gridFineDefault[0] = mntmGridFineDefault; mntmGridFineDefault.setEnabled(true); mntmGridFineDefault.setText(I18n.E3D_GridFineDefault); mntm_gridFineDefault[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { WorkbenchManager.getUserSettingState().setFine_move_snap(new BigDecimal("0.0001")); //$NON-NLS-1$ WorkbenchManager.getUserSettingState().setFine_rotate_snap(BigDecimal.ONE); WorkbenchManager.getUserSettingState().setFine_scale_snap(new BigDecimal("1.001")); //$NON-NLS-1$ BigDecimal m = WorkbenchManager.getUserSettingState().getFine_move_snap(); BigDecimal r = WorkbenchManager.getUserSettingState().getFine_rotate_snap(); BigDecimal s = WorkbenchManager.getUserSettingState().getFine_scale_snap(); snapSize = 0; spn_Move[0].setValue(m); spn_Rotate[0].setValue(r); spn_Scale[0].setValue(s); Manipulator.setSnap(m, r, s); } }); java.awt.Point b = java.awt.MouseInfo.getPointerInfo().getLocation(); final int x = (int) b.getX(); final int y = (int) b.getY(); Menu menu = mnu_fineMenu[0]; menu.setLocation(x, y); menu.setVisible(true); } } }); btn_SplitQuad[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null && !Project.getFileToEdit().isReadOnly()) { Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager().splitQuads(true); } } }); btn_CondlineToLine[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null && !Project.getFileToEdit().isReadOnly()) { Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager().condlineToLine(); } } }); btn_LineToCondline[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null && !Project.getFileToEdit().isReadOnly()) { Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager().lineToCondline(); } } }); btn_MoveOnLine[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null && !Project.getFileToEdit().isReadOnly()) { Project.getFileToEdit().getVertexManager().addSnapshot(); Set<Vertex> verts = Project.getFileToEdit().getVertexManager().getSelectedVertices(); CoordinatesDialog.setStart(null); CoordinatesDialog.setEnd(null); if (verts.size() == 2) { Iterator<Vertex> it = verts.iterator(); CoordinatesDialog.setStart(new Vector3d(it.next())); CoordinatesDialog.setEnd(new Vector3d(it.next())); } } } }); spn_Move[0].addValueChangeListener(new ValueChangeAdapter() { @Override public void valueChanged(BigDecimalSpinner spn) { BigDecimal m, r, s; m = spn.getValue(); switch (snapSize) { case 0: WorkbenchManager.getUserSettingState().setFine_move_snap(m); r = WorkbenchManager.getUserSettingState().getFine_rotate_snap(); s = WorkbenchManager.getUserSettingState().getFine_scale_snap(); break; case 2: WorkbenchManager.getUserSettingState().setCoarse_move_snap(m); r = WorkbenchManager.getUserSettingState().getCoarse_rotate_snap(); s = WorkbenchManager.getUserSettingState().getCoarse_scale_snap(); break; default: WorkbenchManager.getUserSettingState().setMedium_move_snap(m); r = WorkbenchManager.getUserSettingState().getMedium_rotate_snap(); s = WorkbenchManager.getUserSettingState().getMedium_scale_snap(); break; } Manipulator.setSnap(m, r, s); } }); spn_Rotate[0].addValueChangeListener(new ValueChangeAdapter() { @Override public void valueChanged(BigDecimalSpinner spn) { BigDecimal m, r, s; r = spn.getValue(); switch (snapSize) { case 0: m = WorkbenchManager.getUserSettingState().getFine_move_snap(); WorkbenchManager.getUserSettingState().setFine_rotate_snap(r); s = WorkbenchManager.getUserSettingState().getFine_scale_snap(); break; case 2: m = WorkbenchManager.getUserSettingState().getCoarse_move_snap(); WorkbenchManager.getUserSettingState().setCoarse_rotate_snap(r); s = WorkbenchManager.getUserSettingState().getCoarse_scale_snap(); break; default: m = WorkbenchManager.getUserSettingState().getMedium_move_snap(); WorkbenchManager.getUserSettingState().setMedium_rotate_snap(r); s = WorkbenchManager.getUserSettingState().getMedium_scale_snap(); break; } Manipulator.setSnap(m, r, s); } }); spn_Scale[0].addValueChangeListener(new ValueChangeAdapter() { @Override public void valueChanged(BigDecimalSpinner spn) { BigDecimal m, r, s; s = spn.getValue(); switch (snapSize) { case 0: m = WorkbenchManager.getUserSettingState().getFine_move_snap(); r = WorkbenchManager.getUserSettingState().getFine_rotate_snap(); WorkbenchManager.getUserSettingState().setFine_scale_snap(s); break; case 2: m = WorkbenchManager.getUserSettingState().getCoarse_move_snap(); r = WorkbenchManager.getUserSettingState().getCoarse_rotate_snap(); WorkbenchManager.getUserSettingState().setCoarse_scale_snap(s); break; default: m = WorkbenchManager.getUserSettingState().getMedium_move_snap(); r = WorkbenchManager.getUserSettingState().getMedium_rotate_snap(); WorkbenchManager.getUserSettingState().setMedium_scale_snap(s); break; } Manipulator.setSnap(m, r, s); } }); btn_PreviousSelection[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { updatingSelectionTab = true; NLogger.debug(getClass(), "Previous Selection..."); //$NON-NLS-1$ final DatFile df = Project.getFileToEdit(); if (df != null && !df.isReadOnly()) { final VertexManager vm = df.getVertexManager(); vm.addSnapshot(); final int count = vm.getSelectedData().size(); if (count > 0) { boolean breakIt = false; boolean firstRun = true; while (true) { int index = vm.getSelectedItemIndex(); index--; if (index < 0) { index = count - 1; if (!firstRun) breakIt = true; } if (index > count - 1) index = count - 1; firstRun = false; vm.setSelectedItemIndex(index); final GData gdata = (GData) vm.getSelectedData().toArray()[index]; if (vm.isNotInSubfileAndLinetype1to5(gdata)) { vm.setSelectedLine(gdata); disableSelectionTab(); updatingSelectionTab = true; switch (gdata.type()) { case 1: case 5: case 4: spn_SelectionX4[0].setEnabled(true); spn_SelectionY4[0].setEnabled(true); spn_SelectionZ4[0].setEnabled(true); case 3: spn_SelectionX3[0].setEnabled(true); spn_SelectionY3[0].setEnabled(true); spn_SelectionZ3[0].setEnabled(true); case 2: spn_SelectionX1[0].setEnabled(true); spn_SelectionY1[0].setEnabled(true); spn_SelectionZ1[0].setEnabled(true); spn_SelectionX2[0].setEnabled(true); spn_SelectionY2[0].setEnabled(true); spn_SelectionZ2[0].setEnabled(true); txt_Line[0].setText(gdata.toString()); breakIt = true; btn_MoveAdjacentData2[0].setEnabled(true); switch (gdata.type()) { case 5: BigDecimal[] g5 = GraphicalDataTools.getPreciseCoordinates(gdata); spn_SelectionX1[0].setValue(g5[0]); spn_SelectionY1[0].setValue(g5[1]); spn_SelectionZ1[0].setValue(g5[2]); spn_SelectionX2[0].setValue(g5[3]); spn_SelectionY2[0].setValue(g5[4]); spn_SelectionZ2[0].setValue(g5[5]); spn_SelectionX3[0].setValue(g5[6]); spn_SelectionY3[0].setValue(g5[7]); spn_SelectionZ3[0].setValue(g5[8]); spn_SelectionX4[0].setValue(g5[9]); spn_SelectionY4[0].setValue(g5[10]); spn_SelectionZ4[0].setValue(g5[11]); break; case 4: BigDecimal[] g4 = GraphicalDataTools.getPreciseCoordinates(gdata); spn_SelectionX1[0].setValue(g4[0]); spn_SelectionY1[0].setValue(g4[1]); spn_SelectionZ1[0].setValue(g4[2]); spn_SelectionX2[0].setValue(g4[3]); spn_SelectionY2[0].setValue(g4[4]); spn_SelectionZ2[0].setValue(g4[5]); spn_SelectionX3[0].setValue(g4[6]); spn_SelectionY3[0].setValue(g4[7]); spn_SelectionZ3[0].setValue(g4[8]); spn_SelectionX4[0].setValue(g4[9]); spn_SelectionY4[0].setValue(g4[10]); spn_SelectionZ4[0].setValue(g4[11]); break; case 3: BigDecimal[] g3 = GraphicalDataTools.getPreciseCoordinates(gdata); spn_SelectionX1[0].setValue(g3[0]); spn_SelectionY1[0].setValue(g3[1]); spn_SelectionZ1[0].setValue(g3[2]); spn_SelectionX2[0].setValue(g3[3]); spn_SelectionY2[0].setValue(g3[4]); spn_SelectionZ2[0].setValue(g3[5]); spn_SelectionX3[0].setValue(g3[6]); spn_SelectionY3[0].setValue(g3[7]); spn_SelectionZ3[0].setValue(g3[8]); break; case 2: BigDecimal[] g2 = GraphicalDataTools.getPreciseCoordinates(gdata); spn_SelectionX1[0].setValue(g2[0]); spn_SelectionY1[0].setValue(g2[1]); spn_SelectionZ1[0].setValue(g2[2]); spn_SelectionX2[0].setValue(g2[3]); spn_SelectionY2[0].setValue(g2[4]); spn_SelectionZ2[0].setValue(g2[5]); break; case 1: vm.getSelectedVertices().clear(); btn_MoveAdjacentData2[0].setEnabled(false); GData1 g1 = (GData1) gdata; spn_SelectionX1[0].setValue(g1.getAccurateProductMatrix().M30); spn_SelectionY1[0].setValue(g1.getAccurateProductMatrix().M31); spn_SelectionZ1[0].setValue(g1.getAccurateProductMatrix().M32); spn_SelectionX2[0].setValue(g1.getAccurateProductMatrix().M00); spn_SelectionY2[0].setValue(g1.getAccurateProductMatrix().M01); spn_SelectionZ2[0].setValue(g1.getAccurateProductMatrix().M02); spn_SelectionX3[0].setValue(g1.getAccurateProductMatrix().M10); spn_SelectionY3[0].setValue(g1.getAccurateProductMatrix().M11); spn_SelectionZ3[0].setValue(g1.getAccurateProductMatrix().M12); spn_SelectionX4[0].setValue(g1.getAccurateProductMatrix().M20); spn_SelectionY4[0].setValue(g1.getAccurateProductMatrix().M21); spn_SelectionZ4[0].setValue(g1.getAccurateProductMatrix().M22); break; default: disableSelectionTab(); updatingSelectionTab = true; break; } lbl_SelectionX1[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX1 : "") + " {" + spn_SelectionX1[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionY1[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY1 : "") + " {" + spn_SelectionY1[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionZ1[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ1 : "") + " {" + spn_SelectionZ1[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionX2[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX2 : "") + " {" + spn_SelectionX2[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionY2[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY2 : "") + " {" + spn_SelectionY2[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionZ2[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ2 : "") + " {" + spn_SelectionZ2[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionX3[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX3 : "") + " {" + spn_SelectionX3[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionY3[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY3 : "") + " {" + spn_SelectionY3[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionZ3[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ3 : "") + " {" + spn_SelectionZ3[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionX4[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX4 : "") + " {" + spn_SelectionX4[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionY4[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY4 : "") + " {" + spn_SelectionY4[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionZ4[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ4 : "") + " {" + spn_SelectionZ4[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionX1[0].getParent().layout(); updatingSelectionTab = false; break; default: disableSelectionTab(); break; } } else { disableSelectionTab(); } if (breakIt) break; } } else { disableSelectionTab(); } } else { disableSelectionTab(); } updatingSelectionTab = false; } }); btn_NextSelection[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { updatingSelectionTab = true; NLogger.debug(getClass(), "Next Selection..."); //$NON-NLS-1$ final DatFile df = Project.getFileToEdit(); if (df != null && !df.isReadOnly()) { final VertexManager vm = df.getVertexManager(); vm.addSnapshot(); final int count = vm.getSelectedData().size(); if (count > 0) { boolean breakIt = false; boolean firstRun = true; while (true) { int index = vm.getSelectedItemIndex(); index++; if (index >= count) { index = 0; if (!firstRun) breakIt = true; } firstRun = false; vm.setSelectedItemIndex(index); final GData gdata = (GData) vm.getSelectedData().toArray()[index]; if (vm.isNotInSubfileAndLinetype1to5(gdata)) { vm.setSelectedLine(gdata); disableSelectionTab(); updatingSelectionTab = true; switch (gdata.type()) { case 1: case 5: case 4: spn_SelectionX4[0].setEnabled(true); spn_SelectionY4[0].setEnabled(true); spn_SelectionZ4[0].setEnabled(true); case 3: spn_SelectionX3[0].setEnabled(true); spn_SelectionY3[0].setEnabled(true); spn_SelectionZ3[0].setEnabled(true); case 2: spn_SelectionX1[0].setEnabled(true); spn_SelectionY1[0].setEnabled(true); spn_SelectionZ1[0].setEnabled(true); spn_SelectionX2[0].setEnabled(true); spn_SelectionY2[0].setEnabled(true); spn_SelectionZ2[0].setEnabled(true); txt_Line[0].setText(gdata.toString()); breakIt = true; btn_MoveAdjacentData2[0].setEnabled(true); switch (gdata.type()) { case 5: BigDecimal[] g5 = GraphicalDataTools.getPreciseCoordinates(gdata); spn_SelectionX1[0].setValue(g5[0]); spn_SelectionY1[0].setValue(g5[1]); spn_SelectionZ1[0].setValue(g5[2]); spn_SelectionX2[0].setValue(g5[3]); spn_SelectionY2[0].setValue(g5[4]); spn_SelectionZ2[0].setValue(g5[5]); spn_SelectionX3[0].setValue(g5[6]); spn_SelectionY3[0].setValue(g5[7]); spn_SelectionZ3[0].setValue(g5[8]); spn_SelectionX4[0].setValue(g5[9]); spn_SelectionY4[0].setValue(g5[10]); spn_SelectionZ4[0].setValue(g5[11]); break; case 4: BigDecimal[] g4 = GraphicalDataTools.getPreciseCoordinates(gdata); spn_SelectionX1[0].setValue(g4[0]); spn_SelectionY1[0].setValue(g4[1]); spn_SelectionZ1[0].setValue(g4[2]); spn_SelectionX2[0].setValue(g4[3]); spn_SelectionY2[0].setValue(g4[4]); spn_SelectionZ2[0].setValue(g4[5]); spn_SelectionX3[0].setValue(g4[6]); spn_SelectionY3[0].setValue(g4[7]); spn_SelectionZ3[0].setValue(g4[8]); spn_SelectionX4[0].setValue(g4[9]); spn_SelectionY4[0].setValue(g4[10]); spn_SelectionZ4[0].setValue(g4[11]); break; case 3: BigDecimal[] g3 = GraphicalDataTools.getPreciseCoordinates(gdata); spn_SelectionX1[0].setValue(g3[0]); spn_SelectionY1[0].setValue(g3[1]); spn_SelectionZ1[0].setValue(g3[2]); spn_SelectionX2[0].setValue(g3[3]); spn_SelectionY2[0].setValue(g3[4]); spn_SelectionZ2[0].setValue(g3[5]); spn_SelectionX3[0].setValue(g3[6]); spn_SelectionY3[0].setValue(g3[7]); spn_SelectionZ3[0].setValue(g3[8]); break; case 2: BigDecimal[] g2 = GraphicalDataTools.getPreciseCoordinates(gdata); spn_SelectionX1[0].setValue(g2[0]); spn_SelectionY1[0].setValue(g2[1]); spn_SelectionZ1[0].setValue(g2[2]); spn_SelectionX2[0].setValue(g2[3]); spn_SelectionY2[0].setValue(g2[4]); spn_SelectionZ2[0].setValue(g2[5]); break; case 1: vm.getSelectedVertices().clear(); btn_MoveAdjacentData2[0].setEnabled(false); GData1 g1 = (GData1) gdata; spn_SelectionX1[0].setValue(g1.getAccurateProductMatrix().M30); spn_SelectionY1[0].setValue(g1.getAccurateProductMatrix().M31); spn_SelectionZ1[0].setValue(g1.getAccurateProductMatrix().M32); spn_SelectionX2[0].setValue(g1.getAccurateProductMatrix().M00); spn_SelectionY2[0].setValue(g1.getAccurateProductMatrix().M01); spn_SelectionZ2[0].setValue(g1.getAccurateProductMatrix().M02); spn_SelectionX3[0].setValue(g1.getAccurateProductMatrix().M10); spn_SelectionY3[0].setValue(g1.getAccurateProductMatrix().M11); spn_SelectionZ3[0].setValue(g1.getAccurateProductMatrix().M12); spn_SelectionX4[0].setValue(g1.getAccurateProductMatrix().M20); spn_SelectionY4[0].setValue(g1.getAccurateProductMatrix().M21); spn_SelectionZ4[0].setValue(g1.getAccurateProductMatrix().M22); break; default: disableSelectionTab(); updatingSelectionTab = true; break; } lbl_SelectionX1[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX1 : "X :") + " {" + spn_SelectionX1[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionY1[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY1 : "Y :") + " {" + spn_SelectionY1[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionZ1[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ1 : "Z :") + " {" + spn_SelectionZ1[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionX2[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX2 : "M00:") + " {" + spn_SelectionX2[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionY2[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY2 : "M01:") + " {" + spn_SelectionY2[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionZ2[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ2 : "M02:") + " {" + spn_SelectionZ2[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionX3[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX3 : "M10:") + " {" + spn_SelectionX3[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionY3[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY3 : "M11:") + " {" + spn_SelectionY3[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionZ3[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ3 : "M12:") + " {" + spn_SelectionZ3[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionX4[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX4 : "M20:") + " {" + spn_SelectionX4[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionY4[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY4 : "M21:") + " {" + spn_SelectionY4[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionZ4[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ4 : "M22:") + " {" + spn_SelectionZ4[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionX1[0].getParent().layout(); break; default: disableSelectionTab(); break; } } else { disableSelectionTab(); } if (breakIt) break; } } else { disableSelectionTab(); } } else { disableSelectionTab(); } updatingSelectionTab = false; } }); final ValueChangeAdapter va = new ValueChangeAdapter() { @Override public void valueChanged(BigDecimalSpinner spn) { if (updatingSelectionTab || Project.getFileToEdit() == null) return; Project.getFileToEdit().getVertexManager().addSnapshot(); final GData newLine = Project.getFileToEdit().getVertexManager().updateSelectedLine( spn_SelectionX1[0].getValue(), spn_SelectionY1[0].getValue(), spn_SelectionZ1[0].getValue(), spn_SelectionX2[0].getValue(), spn_SelectionY2[0].getValue(), spn_SelectionZ2[0].getValue(), spn_SelectionX3[0].getValue(), spn_SelectionY3[0].getValue(), spn_SelectionZ3[0].getValue(), spn_SelectionX4[0].getValue(), spn_SelectionY4[0].getValue(), spn_SelectionZ4[0].getValue(), btn_MoveAdjacentData2[0].getSelection() ); if (newLine == null) { disableSelectionTab(); } else { txt_Line[0].setText(newLine.toString()); } } }; spn_SelectionX1[0].addValueChangeListener(va); spn_SelectionY1[0].addValueChangeListener(va); spn_SelectionZ1[0].addValueChangeListener(va); spn_SelectionX2[0].addValueChangeListener(va); spn_SelectionY2[0].addValueChangeListener(va); spn_SelectionZ2[0].addValueChangeListener(va); spn_SelectionX3[0].addValueChangeListener(va); spn_SelectionY3[0].addValueChangeListener(va); spn_SelectionZ3[0].addValueChangeListener(va); spn_SelectionX4[0].addValueChangeListener(va); spn_SelectionY4[0].addValueChangeListener(va); spn_SelectionZ4[0].addValueChangeListener(va); // treeParts[0].addSelectionListener(new SelectionAdapter() { // @Override // public void widgetSelected(final SelectionEvent e) { // // } // }); treeParts[0].addListener(SWT.MouseDown, new Listener() { @Override public void handleEvent(Event event) { if (event.button == MouseButton.RIGHT) { NLogger.debug(getClass(), "Showing context menu."); //$NON-NLS-1$ try { if (treeParts[0].getTree().getMenu() != null) { treeParts[0].getTree().getMenu().dispose(); } } catch (Exception ex) {} Menu treeMenu = new Menu(treeParts[0].getTree()); treeParts[0].getTree().setMenu(treeMenu); mnu_treeMenu[0] = treeMenu; MenuItem mntmOpenIn3DEditor = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT()); mntm_OpenIn3DEditor[0] = mntmOpenIn3DEditor; mntmOpenIn3DEditor.setEnabled(true); mntmOpenIn3DEditor.setText(I18n.E3D_OpenIn3DEditor); MenuItem mntmOpenInTextEditor = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT()); mntm_OpenInTextEditor[0] = mntmOpenInTextEditor; mntmOpenInTextEditor.setEnabled(true); mntmOpenInTextEditor.setText(I18n.E3D_OpenInTextEditor); @SuppressWarnings("unused") MenuItem mntm_Separator = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT() | SWT.SEPARATOR); MenuItem mntmRename = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT()); mntm_Rename[0] = mntmRename; mntmRename.setEnabled(true); mntmRename.setText(I18n.E3D_RenameMove); MenuItem mntmRevert = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT()); mntm_Revert[0] = mntmRevert; mntmRevert.setEnabled(true); mntmRevert.setText(I18n.E3D_RevertAllChanges); MenuItem mntmDelete = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT()); mntm_Delete[0] = mntmDelete; mntmDelete.setEnabled(true); mntmDelete.setText(I18n.E3D_Delete); @SuppressWarnings("unused") MenuItem mntm_Separator2 = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT() | SWT.SEPARATOR); MenuItem mntmCopyToUnofficial = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT()); mntm_CopyToUnofficial[0] = mntmCopyToUnofficial; mntmCopyToUnofficial.setEnabled(true); mntmCopyToUnofficial.setText(I18n.E3D_CopyToUnofficialLibrary); mntm_OpenInTextEditor[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].getData() instanceof DatFile) { DatFile df = (DatFile) treeParts[0].getSelection()[0].getData(); for (EditorTextWindow w : Project.getOpenTextWindows()) { for (CTabItem t : w.getTabFolder().getItems()) { if (df.equals(((CompositeTab) t).getState().getFileNameObj())) { w.getTabFolder().setSelection(t); ((CompositeTab) t).getControl().getShell().forceActive(); w.open(); df.getVertexManager().setUpdated(true); return; } } } // Project.getParsedFiles().add(df); IS NECESSARY HERE Project.getParsedFiles().add(df); new EditorTextWindow().run(df); df.getVertexManager().addSnapshot(); } else { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK); messageBoxError.setText(I18n.DIALOG_UnavailableTitle); messageBoxError.setMessage(I18n.DIALOG_Unavailable); messageBoxError.open(); } cleanupClosedData(); } }); mntm_OpenIn3DEditor[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].getData() instanceof DatFile) { if (renders.isEmpty()) { if ("%EMPTY%".equals(Editor3DWindow.getSashForm().getChildren()[1].getData())) { //$NON-NLS-1$ int[] mainSashWeights = Editor3DWindow.getSashForm().getWeights(); Editor3DWindow.getSashForm().getChildren()[1].dispose(); CompositeContainer cmp_Container = new CompositeContainer(Editor3DWindow.getSashForm(), false); cmp_Container.moveBelow(Editor3DWindow.getSashForm().getChildren()[0]); DatFile df = (DatFile) treeParts[0].getSelection()[0].getData(); df.parseForData(true); Project.setFileToEdit(df); cmp_Container.getComposite3D().setLockableDatFileReference(df); df.getVertexManager().addSnapshot(); Editor3DWindow.getSashForm().getParent().layout(); Editor3DWindow.getSashForm().setWeights(mainSashWeights); } } else { boolean canUpdate = false; for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (!c3d.isDatFileLockedOnDisplay()) { canUpdate = true; break; } } if (canUpdate) { DatFile df = (DatFile) treeParts[0].getSelection()[0].getData(); final VertexManager vm = df.getVertexManager(); if (vm.isModified()) { df.setText(df.getText()); } df.parseForData(true); Project.setFileToEdit(df); for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (!c3d.isDatFileLockedOnDisplay()) { c3d.setLockableDatFileReference(df); c3d.getModifier().zoomToFit(); } } df.getVertexManager().addSnapshot(); } } } else { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK); messageBoxError.setText(I18n.DIALOG_UnavailableTitle); messageBoxError.setMessage(I18n.DIALOG_Unavailable); messageBoxError.open(); } cleanupClosedData(); } }); mntm_Revert[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].getData() instanceof DatFile) { DatFile df = (DatFile) treeParts[0].getSelection()[0].getData(); if (df.isReadOnly() || !Project.getUnsavedFiles().contains(df) || df.isVirtual() && df.getText().trim().isEmpty()) return; df.getVertexManager().addSnapshot(); MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.NO); messageBox.setText(I18n.DIALOG_RevertTitle); Object[] messageArguments = {df.getShortName(), df.getLastSavedOpened()}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.DIALOG_Revert); messageBox.setMessage(formatter.format(messageArguments)); int result = messageBox.open(); if (result == SWT.NO) { return; } boolean canUpdate = false; for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(df)) { canUpdate = true; break; } } EditorTextWindow tmpW = null; CTabItem tmpT = null; for (EditorTextWindow w : Project.getOpenTextWindows()) { for (CTabItem t : w.getTabFolder().getItems()) { if (df.equals(((CompositeTab) t).getState().getFileNameObj())) { canUpdate = true; tmpW = w; tmpT = t; break; } } } df.setText(df.getOriginalText()); df.setOldName(df.getNewName()); if (!df.isVirtual()) { Project.removeUnsavedFile(df); updateTree_unsavedEntries(); } if (canUpdate) { df.parseForData(true); df.getVertexManager().setModified(true, true); if (tmpW != null) { tmpW.getTabFolder().setSelection(tmpT); ((CompositeTab) tmpT).getControl().getShell().forceActive(); tmpW.open(); ((CompositeTab) tmpT).getTextComposite().forceFocus(); } } } else { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK); messageBoxError.setText(I18n.DIALOG_UnavailableTitle); messageBoxError.setMessage(I18n.DIALOG_Unavailable); messageBoxError.open(); } } }); mntm_Delete[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].getData() instanceof DatFile) { DatFile df = (DatFile) treeParts[0].getSelection()[0].getData(); if (df.isReadOnly()) { if (treeParts[0].getSelection()[0].getParentItem().getParentItem() == treeItem_Project[0]) { updateTree_removeEntry(df); cleanupClosedData(); } return; } updateTree_removeEntry(df); if (df.getOldName().startsWith(Project.getProjectPath()) && df.getNewName().startsWith(Project.getProjectPath())) { try { File f = new File(df.getOldName()); if (f.exists()) { File bakFile = new File(df.getOldName() + ".bak"); //$NON-NLS-1$ if (bakFile.exists()) { bakFile.delete(); } f.renameTo(bakFile); } } catch (Exception ex) {} } cleanupClosedData(); } else { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK); messageBoxError.setText(I18n.DIALOG_UnavailableTitle); messageBoxError.setMessage(I18n.DIALOG_Unavailable); messageBoxError.open(); } } }); mntm_Rename[0].addSelectionListener(new SelectionAdapter() { @SuppressWarnings("unchecked") @Override public void widgetSelected(SelectionEvent e) { if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].getData() instanceof DatFile) { DatFile df = (DatFile) treeParts[0].getSelection()[0].getData(); if (df.isReadOnly()) return; df.getVertexManager().addSnapshot(); FileDialog dlg = new FileDialog(Editor3DWindow.getWindow().getShell(), SWT.SAVE); File tmp = new File(df.getNewName()); dlg.setFilterPath(tmp.getAbsolutePath().substring(0, tmp.getAbsolutePath().length() - tmp.getName().length())); dlg.setFileName(tmp.getName()); dlg.setFilterExtensions(new String[]{"*.dat"}); //$NON-NLS-1$ dlg.setOverwrite(true); // Change the title bar text dlg.setText(I18n.DIALOG_RenameOrMove); // Calling open() will open and run the dialog. // It will return the selected file, or // null if user cancels String newPath = dlg.open(); if (newPath != null) { while (isFileNameAllocated(newPath, df, false)) { MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.RETRY | SWT.CANCEL); messageBox.setText(I18n.DIALOG_AlreadyAllocatedNameTitle); messageBox.setMessage(I18n.DIALOG_AlreadyAllocatedName); int result = messageBox.open(); if (result == SWT.CANCEL) { return; } newPath = dlg.open(); if (newPath == null) return; } if (df.isProjectFile() && !newPath.startsWith(Project.getProjectPath())) { MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_WARNING | SWT.YES | SWT.NO); messageBox.setText(I18n.DIALOG_NoProjectLocationTitle); Object[] messageArguments = {new File(newPath).getName()}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.DIALOG_NoProjectLocation); messageBox.setMessage(formatter.format(messageArguments)); int result = messageBox.open(); if (result == SWT.NO) { return; } } df.setNewName(newPath); if (!df.getOldName().equals(df.getNewName())) { if (!Project.getUnsavedFiles().contains(df)) { df.parseForData(true); df.getVertexManager().setModified(true, true); Project.getUnsavedFiles().add(df); } } else { if (df.getText().equals(df.getOriginalText()) && df.getOldName().equals(df.getNewName())) { Project.removeUnsavedFile(df); } } df.setProjectFile(df.getNewName().startsWith(Project.getProjectPath())); HashSet<EditorTextWindow> windows = new HashSet<EditorTextWindow>(Project.getOpenTextWindows()); for (EditorTextWindow win : windows) { win.updateTabWithDatfile(df); } updateTree_renamedEntries(); updateTree_unsavedEntries(); } } else if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].equals(treeItem_Project[0])) { if (Project.isDefaultProject()) { ProjectActions.createNewProject(Editor3DWindow.getWindow(), true); } else { int result = new NewProjectDialog(true).open(); if (result == IDialogConstants.OK_ID && !Project.getTempProjectPath().equals(Project.getProjectPath())) { try { while (new File(Project.getTempProjectPath()).isDirectory()) { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.YES | SWT.CANCEL | SWT.NO); messageBoxError.setText(I18n.PROJECT_ProjectOverwriteTitle); messageBoxError.setMessage(I18n.PROJECT_ProjectOverwrite); int result2 = messageBoxError.open(); if (result2 == SWT.CANCEL) { return; } else if (result2 == SWT.YES) { break; } else { result = new NewProjectDialog(true).open(); if (result == IDialogConstants.CANCEL_ID) { return; } } } Project.copyFolder(new File(Project.getProjectPath()), new File(Project.getTempProjectPath())); Project.deleteFolder(new File(Project.getProjectPath())); // Linked project parts need a new path, because they were copied to a new directory String defaultPrefix = new File(Project.getProjectPath()).getAbsolutePath() + File.separator; String projectPrefix = new File(Project.getTempProjectPath()).getAbsolutePath() + File.separator; Editor3DWindow.getWindow().getProjectParts().getParentItem().setData(Project.getTempProjectPath()); HashSet<DatFile> projectFiles = new HashSet<DatFile>(); projectFiles.addAll((ArrayList<DatFile>) Editor3DWindow.getWindow().getProjectParts().getData()); projectFiles.addAll((ArrayList<DatFile>) Editor3DWindow.getWindow().getProjectSubparts().getData()); projectFiles.addAll((ArrayList<DatFile>) Editor3DWindow.getWindow().getProjectPrimitives().getData()); projectFiles.addAll((ArrayList<DatFile>) Editor3DWindow.getWindow().getProjectPrimitives48().getData()); for (DatFile df : projectFiles) { df.getVertexManager().addSnapshot(); boolean isUnsaved = Project.getUnsavedFiles().contains(df); boolean isParsed = Project.getParsedFiles().contains(df); Project.getParsedFiles().remove(df); Project.getUnsavedFiles().remove(df); String newName = df.getNewName(); String oldName = df.getOldName(); df.updateLastModified(); if (!newName.startsWith(projectPrefix) && newName.startsWith(defaultPrefix)) { df.setNewName(projectPrefix + newName.substring(defaultPrefix.length())); } if (!oldName.startsWith(projectPrefix) && oldName.startsWith(defaultPrefix)) { df.setOldName(projectPrefix + oldName.substring(defaultPrefix.length())); } df.setProjectFile(df.getNewName().startsWith(Project.getProjectPath())); if (isUnsaved) Project.addUnsavedFile(df); if (isParsed) Project.getParsedFiles().add(df); } Project.setProjectName(Project.getTempProjectName()); Project.setProjectPath(Project.getTempProjectPath()); Editor3DWindow.getWindow().getProjectParts().getParentItem().setText(Project.getProjectName()); updateTree_unsavedEntries(); Project.updateEditor(); Editor3DWindow.getWindow().getShell().update(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } } else { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK); messageBoxError.setText(I18n.DIALOG_UnavailableTitle); messageBoxError.setMessage(I18n.DIALOG_Unavailable); messageBoxError.open(); } } }); mntm_CopyToUnofficial[0] .addSelectionListener(new SelectionAdapter() { @SuppressWarnings("unchecked") @Override public void widgetSelected(SelectionEvent e) { if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].getData() instanceof DatFile) { DatFile df = (DatFile) treeParts[0].getSelection()[0].getData(); TreeItem p = treeParts[0].getSelection()[0].getParentItem(); String targetPath_u; String targetPath_l; String targetPathDir_u; String targetPathDir_l; TreeItem targetTreeItem; boolean projectIsFileOrigin = false; if (treeItem_ProjectParts[0].equals(p)) { targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "PARTS"; //$NON-NLS-1$ targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "parts"; //$NON-NLS-1$ targetTreeItem = treeItem_UnofficialParts[0]; projectIsFileOrigin = true; } else if (treeItem_ProjectPrimitives[0].equals(p)) { targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P"; //$NON-NLS-1$ targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p"; //$NON-NLS-1$ targetTreeItem = treeItem_UnofficialPrimitives[0]; projectIsFileOrigin = true; } else if (treeItem_ProjectPrimitives48[0].equals(p)) { targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator + "48"; //$NON-NLS-1$ //$NON-NLS-2$ targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator + "48"; //$NON-NLS-1$ //$NON-NLS-2$ targetTreeItem = treeItem_UnofficialPrimitives48[0]; projectIsFileOrigin = true; } else if (treeItem_ProjectPrimitives8[0].equals(p)) { targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator + "8"; //$NON-NLS-1$ //$NON-NLS-2$ targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator + "8"; //$NON-NLS-1$ //$NON-NLS-2$ targetTreeItem = treeItem_UnofficialPrimitives8[0]; projectIsFileOrigin = true; } else if (treeItem_ProjectSubparts[0].equals(p)) { targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "PARTS"+ File.separator + "S"; //$NON-NLS-1$ //$NON-NLS-2$ targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "parts"+ File.separator + "s"; //$NON-NLS-1$ //$NON-NLS-2$ targetTreeItem = treeItem_UnofficialSubparts[0]; projectIsFileOrigin = true; } else if (treeItem_OfficialParts[0].equals(p)) { targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "PARTS"; //$NON-NLS-1$ targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "parts"; //$NON-NLS-1$ targetTreeItem = treeItem_UnofficialParts[0]; } else if (treeItem_OfficialPrimitives[0].equals(p)) { targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P"; //$NON-NLS-1$ targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p"; //$NON-NLS-1$ targetTreeItem = treeItem_UnofficialPrimitives[0]; } else if (treeItem_OfficialPrimitives48[0].equals(p)) { targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator + "48"; //$NON-NLS-1$ //$NON-NLS-2$ targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator + "48"; //$NON-NLS-1$ //$NON-NLS-2$ targetTreeItem = treeItem_UnofficialPrimitives48[0]; } else if (treeItem_OfficialPrimitives8[0].equals(p)) { targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator + "8"; //$NON-NLS-1$ //$NON-NLS-2$ targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator + "8"; //$NON-NLS-1$ //$NON-NLS-2$ targetTreeItem = treeItem_UnofficialPrimitives8[0]; } else if (treeItem_OfficialSubparts[0].equals(p)) { targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "PARTS"+ File.separator + "S"; //$NON-NLS-1$ //$NON-NLS-2$ targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "parts"+ File.separator + "s"; //$NON-NLS-1$ //$NON-NLS-2$ targetTreeItem = treeItem_UnofficialSubparts[0]; } else { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK); messageBoxError.setText(I18n.DIALOG_UnavailableTitle); messageBoxError.setMessage(I18n.DIALOG_Unavailable); messageBoxError.open(); return; } targetPathDir_l = targetPath_l; targetPathDir_u = targetPath_u; final String newName = new File(df.getNewName()).getName(); targetPath_u = targetPath_u + File.separator + newName; targetPath_l = targetPath_l + File.separator + newName; DatFile fileToOverwrite_u = new DatFile(targetPath_u); DatFile fileToOverwrite_l = new DatFile(targetPath_l); DatFile targetFile = null; TreeItem[] folders = new TreeItem[5]; folders[0] = treeItem_UnofficialParts[0]; folders[1] = treeItem_UnofficialPrimitives[0]; folders[2] = treeItem_UnofficialPrimitives48[0]; folders[3] = treeItem_UnofficialPrimitives8[0]; folders[4] = treeItem_UnofficialSubparts[0]; for (TreeItem folder : folders) { ArrayList<DatFile> cachedReferences =(ArrayList<DatFile>) folder.getData(); for (DatFile d : cachedReferences) { if (fileToOverwrite_u.equals(d) || fileToOverwrite_l.equals(d)) { targetFile = d; break; } } } if (new File(targetPath_u).exists() || new File(targetPath_l).exists() || targetFile != null) { MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_WARNING | SWT.OK | SWT.CANCEL); messageBox.setText(I18n.DIALOG_ReplaceTitle); Object[] messageArguments = {newName}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.DIALOG_Replace); messageBox.setMessage(formatter.format(messageArguments)); int result = messageBox.open(); if (result == SWT.CANCEL) { return; } } ArrayList<ArrayList<DatFile>> refResult = null; if (new File(targetPathDir_l).exists() || new File(targetPathDir_u).exists()) { if (targetFile == null) { int result = new CopyDialog(getShell(), new File(df.getNewName()).getName()).open(); switch (result) { case IDialogConstants.OK_ID: // Copy File Only break; case IDialogConstants.NO_ID: // Copy File and required and related if (projectIsFileOrigin) { refResult = ReferenceParser.checkForReferences(df, References.REQUIRED_AND_RELATED, treeItem_Project[0], treeItem_Unofficial[0], treeItem_Official[0]); } else { refResult = ReferenceParser.checkForReferences(df, References.REQUIRED_AND_RELATED, treeItem_Official[0], treeItem_Unofficial[0], treeItem_Project[0]); } break; case IDialogConstants.YES_ID: // Copy File and required if (projectIsFileOrigin) { refResult = ReferenceParser.checkForReferences(df, References.REQUIRED, treeItem_Project[0], treeItem_Unofficial[0], treeItem_Official[0]); } else { refResult = ReferenceParser.checkForReferences(df, References.REQUIRED, treeItem_Official[0], treeItem_Unofficial[0], treeItem_Project[0]); } break; default: return; } DatFile newDatFile = new DatFile(new File(targetPathDir_l).exists() ? targetPath_l : targetPath_u); // Text exchange includes description exchange newDatFile.setText(df.getText()); newDatFile.saveForced(); newDatFile.setType(df.getType()); ((ArrayList<DatFile>) targetTreeItem.getData()).add(newDatFile); TreeItem ti = new TreeItem(targetTreeItem, SWT.NONE); ti.setText(new File(df.getNewName()).getName()); ti.setData(newDatFile); } else if (targetFile.equals(df)) { // This can only happen if the user opens the unofficial parts folder as a project MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK); messageBox.setText(I18n.DIALOG_AlreadyAllocatedNameTitle); messageBox.setMessage(I18n.DIALOG_AlreadyAllocatedName); messageBox.open(); return; } else { int result = new CopyDialog(getShell(), new File(df.getNewName()).getName()).open(); switch (result) { case IDialogConstants.OK_ID: // Copy File Only break; case IDialogConstants.NO_ID: // Copy File and required and related if (projectIsFileOrigin) { refResult = ReferenceParser.checkForReferences(df, References.REQUIRED_AND_RELATED, treeItem_Project[0], treeItem_Unofficial[0], treeItem_Official[0]); } else { refResult = ReferenceParser.checkForReferences(df, References.REQUIRED_AND_RELATED, treeItem_Official[0], treeItem_Unofficial[0], treeItem_Project[0]); } break; case IDialogConstants.YES_ID: // Copy File and required if (projectIsFileOrigin) { refResult = ReferenceParser.checkForReferences(df, References.REQUIRED, treeItem_Project[0], treeItem_Unofficial[0], treeItem_Official[0]); } else { refResult = ReferenceParser.checkForReferences(df, References.REQUIRED, treeItem_Official[0], treeItem_Unofficial[0], treeItem_Project[0]); } break; default: return; } targetFile.disposeData(); updateTree_removeEntry(targetFile); DatFile newDatFile = new DatFile(new File(targetPathDir_l).exists() ? targetPath_l : targetPath_u); newDatFile.setText(df.getText()); newDatFile.saveForced(); ((ArrayList<DatFile>) targetTreeItem.getData()).add(newDatFile); TreeItem ti = new TreeItem(targetTreeItem, SWT.NONE); ti.setText(new File(df.getNewName()).getName()); ti.setData(newDatFile); } if (refResult != null) { // Remove old data for(int i = 0; i < 5; i++) { ArrayList<DatFile> toRemove = refResult.get(i); for (DatFile datToRemove : toRemove) { datToRemove.disposeData(); updateTree_removeEntry(datToRemove); } } // Create new data TreeItem[] targetTrees = new TreeItem[]{treeItem_UnofficialParts[0], treeItem_UnofficialSubparts[0], treeItem_UnofficialPrimitives[0], treeItem_UnofficialPrimitives48[0], treeItem_UnofficialPrimitives8[0]}; for(int i = 5; i < 10; i++) { ArrayList<DatFile> toCreate = refResult.get(i); for (DatFile datToCreate : toCreate) { DatFile newDatFile = new DatFile(datToCreate.getOldName()); String source = datToCreate.getTextDirect(); newDatFile.setText(source); newDatFile.setOriginalText(source); newDatFile.saveForced(); newDatFile.setType(datToCreate.getType()); ((ArrayList<DatFile>) targetTrees[i - 5].getData()).add(newDatFile); TreeItem ti = new TreeItem(targetTrees[i - 5], SWT.NONE); ti.setText(new File(datToCreate.getOldName()).getName()); ti.setData(newDatFile); } } } updateTree_unsavedEntries(); } } else { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK); messageBoxError.setText(I18n.DIALOG_UnavailableTitle); messageBoxError.setMessage(I18n.DIALOG_Unavailable); messageBoxError.open(); } } }); java.awt.Point b = java.awt.MouseInfo.getPointerInfo().getLocation(); final int x = (int) b.getX(); final int y = (int) b.getY(); Menu menu = mnu_treeMenu[0]; menu.setLocation(x, y); menu.setVisible(true); } } }); treeParts[0].addListener(SWT.MouseDoubleClick, new Listener() { @Override public void handleEvent(Event event) { if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null) { treeParts[0].getSelection()[0].setVisible(!treeParts[0].getSelection()[0].isVisible()); TreeItem sel = treeParts[0].getSelection()[0]; sh.getDisplay().asyncExec(new Runnable() { @Override public void run() { treeParts[0].build(); } }); treeParts[0].redraw(); treeParts[0].update(); treeParts[0].getTree().select(treeParts[0].getMapInv().get(sel)); } } }); txt_Search[0].addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { search(txt_Search[0].getText()); } }); btn_ResetSearch[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { txt_Search[0].setText(""); //$NON-NLS-1$ } }); txt_primitiveSearch[0].addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { getCompositePrimitive().collapseAll(); ArrayList<Primitive> prims = getCompositePrimitive().getPrimitives(); final String crit = txt_primitiveSearch[0].getText(); if (crit.trim().isEmpty()) { getCompositePrimitive().setSearchResults(new ArrayList<Primitive>()); Matrix4f.setIdentity(getCompositePrimitive().getTranslation()); getCompositePrimitive().getOpenGL().drawScene(-1, -1); return; } String criteria = ".*" + crit + ".*"; //$NON-NLS-1$ //$NON-NLS-2$ try { "DUMMY".matches(criteria); //$NON-NLS-1$ } catch (PatternSyntaxException pe) { getCompositePrimitive().setSearchResults(new ArrayList<Primitive>()); Matrix4f.setIdentity(getCompositePrimitive().getTranslation()); getCompositePrimitive().getOpenGL().drawScene(-1, -1); return; } final Pattern pattern = Pattern.compile(criteria); ArrayList<Primitive> results = new ArrayList<Primitive>(); for (Primitive p : prims) { p.search(pattern, results); } if (results.isEmpty()) { results.add(null); } getCompositePrimitive().setSearchResults(results); Matrix4f.setIdentity(getCompositePrimitive().getTranslation()); getCompositePrimitive().getOpenGL().drawScene(-1, -1); } }); btn_resetPrimitiveSearch[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { txt_primitiveSearch[0].setText(""); //$NON-NLS-1$ } }); btn_Hide[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager().hideSelection(); } } }); btn_ShowAll[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager().showAll(); } } }); btn_NoTransparentSelection[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { setNoTransparentSelection(btn_NoTransparentSelection[0].getSelection()); } }); btn_BFCToggle[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { setBfcToggle(btn_BFCToggle[0].getSelection()); } }); btn_Delete[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager().delete(Editor3DWindow.getWindow().isMovingAdjacentData(), true); } } }); btn_Copy[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager().copy(); } } }); btn_Cut[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager().copy(); Project.getFileToEdit().getVertexManager().delete(false, true); } } }); btn_Paste[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager().paste(); setMovingAdjacentData(false); } } }); btn_Manipulator_0_toOrigin[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { c3d.getManipulator().reset(); } } } } }); btn_Manipulator_XIII_toWorld[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { Vector4f t = new Vector4f(c3d.getManipulator().getPosition()); BigDecimal[] T = c3d.getManipulator().getAccuratePosition(); c3d.getManipulator().reset(); c3d.getManipulator().getPosition().set(t); c3d.getManipulator().setAccuratePosition(T[0], T[1], T[2]); ; } } } } }); btn_Manipulator_X_XReverse[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { Vector4f.sub(new Vector4f(0f, 0f, 0f, 2f), c3d.getManipulator().getXaxis(), c3d.getManipulator().getXaxis()); BigDecimal[] a = c3d.getManipulator().getAccurateXaxis(); c3d.getManipulator().setAccurateXaxis(a[0].negate(), a[1].negate(), a[2].negate()); } } } }); btn_Manipulator_XI_YReverse[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { Vector4f.sub(new Vector4f(0f, 0f, 0f, 2f), c3d.getManipulator().getYaxis(), c3d.getManipulator().getYaxis()); BigDecimal[] a = c3d.getManipulator().getAccurateYaxis(); c3d.getManipulator().setAccurateYaxis(a[0].negate(), a[1].negate(), a[2].negate()); } } } }); btn_Manipulator_XII_ZReverse[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { Vector4f.sub(new Vector4f(0f, 0f, 0f, 2f), c3d.getManipulator().getZaxis(), c3d.getManipulator().getZaxis()); BigDecimal[] a = c3d.getManipulator().getAccurateZaxis(); c3d.getManipulator().setAccurateZaxis(a[0].negate(), a[1].negate(), a[2].negate()); } } } }); btn_Manipulator_SwitchXY[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { Vector4f temp = new Vector4f(c3d.getManipulator().getXaxis()); c3d.getManipulator().getXaxis().set(c3d.getManipulator().getYaxis()); c3d.getManipulator().getYaxis().set(temp); BigDecimal[] a = c3d.getManipulator().getAccurateXaxis().clone(); BigDecimal[] b = c3d.getManipulator().getAccurateYaxis().clone(); c3d.getManipulator().setAccurateXaxis(b[0], b[1], b[2]); c3d.getManipulator().setAccurateYaxis(a[0], a[1], a[2]); } } } }); btn_Manipulator_SwitchXZ[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { Vector4f temp = new Vector4f(c3d.getManipulator().getXaxis()); c3d.getManipulator().getXaxis().set(c3d.getManipulator().getZaxis()); c3d.getManipulator().getZaxis().set(temp); BigDecimal[] a = c3d.getManipulator().getAccurateXaxis().clone(); BigDecimal[] b = c3d.getManipulator().getAccurateZaxis().clone(); c3d.getManipulator().setAccurateXaxis(b[0], b[1], b[2]); c3d.getManipulator().setAccurateZaxis(a[0], a[1], a[2]); } } } }); btn_Manipulator_SwitchYZ[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { Vector4f temp = new Vector4f(c3d.getManipulator().getZaxis()); c3d.getManipulator().getZaxis().set(c3d.getManipulator().getYaxis()); c3d.getManipulator().getYaxis().set(temp); BigDecimal[] a = c3d.getManipulator().getAccurateYaxis().clone(); BigDecimal[] b = c3d.getManipulator().getAccurateZaxis().clone(); c3d.getManipulator().setAccurateYaxis(b[0], b[1], b[2]); c3d.getManipulator().setAccurateZaxis(a[0], a[1], a[2]); } } } }); btn_Manipulator_1_cameraToPos[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); Vector4f pos = c3d.getManipulator().getPosition(); Vector4f a1 = c3d.getManipulator().getXaxis(); Vector4f a2 = c3d.getManipulator().getYaxis(); Vector4f a3 = c3d.getManipulator().getZaxis(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { c3d.setClassicPerspective(false); WidgetSelectionHelper.unselectAllChildButtons(c3d.getViewAnglesMenu()); Matrix4f rot = new Matrix4f(); Matrix4f.setIdentity(rot); rot.m00 = a1.x; rot.m10 = a1.y; rot.m20 = a1.z; rot.m01 = a2.x; rot.m11 = a2.y; rot.m21 = a2.z; rot.m02 = a3.x; rot.m12 = a3.y; rot.m22 = a3.z; c3d.getRotation().load(rot); Matrix4f trans = new Matrix4f(); Matrix4f.setIdentity(trans); trans.translate(new Vector3f(-pos.x, -pos.y, -pos.z)); c3d.getTranslation().load(trans); c3d.getPerspectiveCalculator().calculateOriginData(); } } } }); btn_Manipulator_2_toAverage[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Vector4f avg = Project.getFileToEdit().getVertexManager().getSelectionCenter(); for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { c3d.getManipulator().getPosition().set(avg.x, avg.y, avg.z, 1f); c3d.getManipulator().setAccuratePosition(new BigDecimal(avg.x / 1000f), new BigDecimal(avg.y / 1000f), new BigDecimal(avg.z / 1000f)); } } } } }); btn_Manipulator_3_toSubfile[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Set<GData1> subfiles = Project.getFileToEdit().getVertexManager().getSelectedSubfiles(); if (!subfiles.isEmpty()) { GData1 subfile = null; for (GData1 g1 : subfiles) { subfile = g1; break; } Matrix4f m = subfile.getProductMatrix(); Matrix M = subfile.getAccurateProductMatrix(); for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { c3d.getManipulator().getPosition().set(m.m30, m.m31, m.m32, 1f); c3d.getManipulator().setAccuratePosition(M.M30, M.M31, M.M32); Vector3f x = new Vector3f(m.m00, m.m01, m.m02); x.normalise(); Vector3f y = new Vector3f(m.m10, m.m11, m.m12); y.normalise(); Vector3f z = new Vector3f(m.m20, m.m21, m.m22); z.normalise(); c3d.getManipulator().getXaxis().set(x.x, x.y, x.z, 1f); c3d.getManipulator().getYaxis().set(y.x, y.y, y.z, 1f); c3d.getManipulator().getZaxis().set(z.x, z.y, z.z, 1f); c3d.getManipulator().setAccurateXaxis(new BigDecimal(c3d.getManipulator().getXaxis().x), new BigDecimal(c3d.getManipulator().getXaxis().y), new BigDecimal(c3d.getManipulator().getXaxis().z)); c3d.getManipulator().setAccurateYaxis(new BigDecimal(c3d.getManipulator().getYaxis().x), new BigDecimal(c3d.getManipulator().getYaxis().y), new BigDecimal(c3d.getManipulator().getYaxis().z)); c3d.getManipulator().setAccurateZaxis(new BigDecimal(c3d.getManipulator().getZaxis().x), new BigDecimal(c3d.getManipulator().getZaxis().y), new BigDecimal(c3d.getManipulator().getZaxis().z)); } } } } } }); btn_Manipulator_32_subfileTo[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { VertexManager vm = Project.getFileToEdit().getVertexManager(); Set<GData1> subfiles = vm.getSelectedSubfiles(); if (!subfiles.isEmpty()) { GData1 subfile = null; for (GData1 g1 : subfiles) { if (vm.getLineLinkedToVertices().containsKey(g1)) { subfile = g1; break; } } if (subfile == null) { return; } for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { vm.addSnapshot(); Manipulator ma = c3d.getManipulator(); vm.transformSubfile(subfile, ma.getAccurateMatrix(), true, true); break; } } } } } }); btn_Manipulator_4_toVertex[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { float minDist = Float.MAX_VALUE; Vector4f next = new Vector4f(c3d.getManipulator().getPosition()); Vector4f min = new Vector4f(c3d.getManipulator().getPosition()); VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); Set<Vertex> vertices; if (vm.getSelectedVertices().isEmpty()) { vertices = vm.getVertices(); } else { vertices = vm.getSelectedVertices(); } Vertex minVertex = new Vertex(0f, 0f, 0f); for (Vertex vertex : vertices) { Vector4f sub = Vector4f.sub(next, vertex.toVector4f(), null); float d2 = sub.lengthSquared(); if (d2 < minDist) { minVertex = vertex; minDist = d2; min = vertex.toVector4f(); } } c3d.getManipulator().getPosition().set(min.x, min.y, min.z, 1f); c3d.getManipulator().setAccuratePosition(minVertex.X, minVertex.Y, minVertex.Z); } } } }); btn_Manipulator_5_toEdge[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { Vector4f min = new Vector4f(c3d.getManipulator().getPosition()); VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); min = vm.getMinimalDistanceVertexToLines(new Vertex(c3d.getManipulator().getPosition())).toVector4f(); c3d.getManipulator().getPosition().set(min.x, min.y, min.z, 1f); c3d.getManipulator().setAccuratePosition(new BigDecimal(min.x / 1000f), new BigDecimal(min.y / 1000f), new BigDecimal(min.z / 1000f)); } } } }); btn_Manipulator_6_toSurface[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { Vector4f min = new Vector4f(c3d.getManipulator().getPosition()); VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); min = vm.getMinimalDistanceVertexToSurfaces(new Vertex(c3d.getManipulator().getPosition())).toVector4f(); c3d.getManipulator().getPosition().set(min.x, min.y, min.z, 1f); c3d.getManipulator().setAccuratePosition(new BigDecimal(min.x / 1000f), new BigDecimal(min.y / 1000f), new BigDecimal(min.z / 1000f)); } } } }); btn_Manipulator_7_toVertexNormal[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { float minDist = Float.MAX_VALUE; Vector4f next = new Vector4f(c3d.getManipulator().getPosition()); Vertex min = null; VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); Set<Vertex> vertices; if (vm.getSelectedVertices().isEmpty()) { vertices = vm.getVertices(); } else { vertices = vm.getSelectedVertices(); } for (Vertex vertex : vertices) { Vector4f sub = Vector4f.sub(next, vertex.toVector4f(), null); float d2 = sub.lengthSquared(); if (d2 < minDist) { minDist = d2; min = vertex; } } vm = c3d.getLockableDatFileReference().getVertexManager(); Vector4f n = vm.getVertexNormal(min); float tx = 1f; float ty = 0f; float tz = 0f; if (n.x <= 0f) { tx = -1; } if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) { tz = tx; tx = 0f; ty = 0f; } else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, 0f, 0f), null).length()) > .00001f) { // ty = 0f; // tz = 0f; } else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) { ty = tx; tx = 0f; tz = 0f; } else { return; } Vector3f cross = (Vector3f) Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, ty, tz), null).normalise(); c3d.getManipulator().getZaxis().set(n.x, n.y, n.z, 1f); c3d.getManipulator().getXaxis().set(cross.x, cross.y, cross.z, 1f); Vector4f zaxis = c3d.getManipulator().getZaxis(); Vector4f xaxis = c3d.getManipulator().getXaxis(); cross = Vector3f.cross(new Vector3f(xaxis.x, xaxis.y, xaxis.z), new Vector3f(zaxis.x, zaxis.y, zaxis.z), null); c3d.getManipulator().getYaxis().set(cross.x, cross.y, cross.z, 1f); c3d.getManipulator().setAccurateXaxis(new BigDecimal(c3d.getManipulator().getXaxis().x), new BigDecimal(c3d.getManipulator().getXaxis().y), new BigDecimal(c3d.getManipulator().getXaxis().z)); c3d.getManipulator().setAccurateYaxis(new BigDecimal(c3d.getManipulator().getYaxis().x), new BigDecimal(c3d.getManipulator().getYaxis().y), new BigDecimal(c3d.getManipulator().getYaxis().z)); c3d.getManipulator().setAccurateZaxis(new BigDecimal(c3d.getManipulator().getZaxis().x), new BigDecimal(c3d.getManipulator().getZaxis().y), new BigDecimal(c3d.getManipulator().getZaxis().z)); } } } }); btn_Manipulator_8_toEdgeNormal[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); Vector4f n = vm.getMinimalDistanceEdgeNormal(new Vertex(c3d.getManipulator().getPosition())); float tx = 1f; float ty = 0f; float tz = 0f; if (n.x <= 0f) { tx = -1; } if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) { tz = tx; tx = 0f; ty = 0f; } else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, 0f, 0f), null).length()) > .00001f) { // ty = 0f; // tz = 0f; } else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) { ty = tx; tx = 0f; tz = 0f; } else { return; } Vector3f cross = (Vector3f) Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, ty, tz), null).normalise(); c3d.getManipulator().getZaxis().set(n.x, n.y, n.z, 1f); c3d.getManipulator().getXaxis().set(cross.x, cross.y, cross.z, 1f); Vector4f zaxis = c3d.getManipulator().getZaxis(); Vector4f xaxis = c3d.getManipulator().getXaxis(); cross = Vector3f.cross(new Vector3f(xaxis.x, xaxis.y, xaxis.z), new Vector3f(zaxis.x, zaxis.y, zaxis.z), null); c3d.getManipulator().getYaxis().set(cross.x, cross.y, cross.z, 1f); c3d.getManipulator().setAccurateXaxis(new BigDecimal(c3d.getManipulator().getXaxis().x), new BigDecimal(c3d.getManipulator().getXaxis().y), new BigDecimal(c3d.getManipulator().getXaxis().z)); c3d.getManipulator().setAccurateYaxis(new BigDecimal(c3d.getManipulator().getYaxis().x), new BigDecimal(c3d.getManipulator().getYaxis().y), new BigDecimal(c3d.getManipulator().getYaxis().z)); c3d.getManipulator().setAccurateZaxis(new BigDecimal(c3d.getManipulator().getZaxis().x), new BigDecimal(c3d.getManipulator().getZaxis().y), new BigDecimal(c3d.getManipulator().getZaxis().z)); } } } }); btn_Manipulator_9_toSurfaceNormal[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); Vector4f n = vm.getMinimalDistanceSurfaceNormal(new Vertex(c3d.getManipulator().getPosition())); float tx = 1f; float ty = 0f; float tz = 0f; if (n.x <= 0f) { tx = -1; } if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) { tz = tx; tx = 0f; ty = 0f; } else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, 0f, 0f), null).length()) > .00001f) { // ty = 0f; // tz = 0f; } else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) { ty = tx; tx = 0f; tz = 0f; } else { return; } Vector3f cross = (Vector3f) Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, ty, tz), null).normalise(); c3d.getManipulator().getZaxis().set(n.x, n.y, n.z, 1f); c3d.getManipulator().getXaxis().set(cross.x, cross.y, cross.z, 1f); Vector4f zaxis = c3d.getManipulator().getZaxis(); Vector4f xaxis = c3d.getManipulator().getXaxis(); cross = Vector3f.cross(new Vector3f(xaxis.x, xaxis.y, xaxis.z), new Vector3f(zaxis.x, zaxis.y, zaxis.z), null); c3d.getManipulator().getYaxis().set(cross.x, cross.y, cross.z, 1f); c3d.getManipulator().setAccurateXaxis(new BigDecimal(c3d.getManipulator().getXaxis().x), new BigDecimal(c3d.getManipulator().getXaxis().y), new BigDecimal(c3d.getManipulator().getXaxis().z)); c3d.getManipulator().setAccurateYaxis(new BigDecimal(c3d.getManipulator().getYaxis().x), new BigDecimal(c3d.getManipulator().getYaxis().y), new BigDecimal(c3d.getManipulator().getYaxis().z)); c3d.getManipulator().setAccurateZaxis(new BigDecimal(c3d.getManipulator().getZaxis().x), new BigDecimal(c3d.getManipulator().getZaxis().y), new BigDecimal(c3d.getManipulator().getZaxis().z)); } } } }); btn_Manipulator_XIV_adjustRotationCenter[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.adjustRotationCenter(c3d, null); } } } }); mntm_SelectAll[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); loadSelectorSettings(); vm.selectAll(sels, true); vm.syncWithTextEditors(true); return; } } } }); mntm_SelectAllVisible[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); loadSelectorSettings(); vm.selectAll(sels, false); vm.syncWithTextEditors(true); return; } } } }); mntm_SelectAllWithColours[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); loadSelectorSettings(); vm.selectAllWithSameColours(sels, true); vm.syncWithTextEditors(true); return; } } } }); mntm_SelectAllVisibleWithColours[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); loadSelectorSettings(); vm.selectAllWithSameColours(sels, false); vm.syncWithTextEditors(true); return; } } } }); mntm_SelectNone[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); vm.clearSelection(); vm.syncWithTextEditors(true); return; } } } }); mntm_SelectInverse[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); loadSelectorSettings(); vm.selectInverse(sels); vm.syncWithTextEditors(true); return; } } } }); mntm_WithSameColour[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { mntm_SelectEverything[0].setEnabled( mntm_WithHiddenData[0].getSelection() || mntm_WithSameColour[0].getSelection() || mntm_WithSameOrientation[0].getSelection() || mntm_ExceptSubfiles[0].getSelection() ); showSelectMenu(); } }); } }); mntm_WithSameOrientation[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { mntm_SelectEverything[0].setEnabled( mntm_WithHiddenData[0].getSelection() || mntm_WithSameColour[0].getSelection() || mntm_WithSameOrientation[0].getSelection() || mntm_ExceptSubfiles[0].getSelection() ); if (mntm_WithSameOrientation[0].getSelection()) { new ValueDialog(getShell(), I18n.E3D_AngleDiff, I18n.E3D_ThreshInDeg) { @Override public void initializeSpinner() { this.spn_Value[0].setMinimum(new BigDecimal("-90")); //$NON-NLS-1$ this.spn_Value[0].setMaximum(new BigDecimal("180")); //$NON-NLS-1$ this.spn_Value[0].setValue(sels.getAngle()); } @Override public void applyValue() { sels.setAngle(this.spn_Value[0].getValue()); } }.open(); } showSelectMenu(); } }); } }); mntm_WithAccuracy[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { mntm_SelectEverything[0].setEnabled( mntm_WithHiddenData[0].getSelection() || mntm_WithSameColour[0].getSelection() || mntm_WithSameOrientation[0].getSelection() || mntm_ExceptSubfiles[0].getSelection() ); if (mntm_WithAccuracy[0].getSelection()) { new ValueDialog(getShell(), I18n.E3D_SetAccuracy, I18n.E3D_ThreshInLdu) { @Override public void initializeSpinner() { this.spn_Value[0].setMinimum(new BigDecimal("0")); //$NON-NLS-1$ this.spn_Value[0].setMaximum(new BigDecimal("1000")); //$NON-NLS-1$ this.spn_Value[0].setValue(sels.getEqualDistance()); } @Override public void applyValue() { sels.setEqualDistance(this.spn_Value[0].getValue()); } }.open(); } showSelectMenu(); } }); } }); mntm_WithHiddenData[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { mntm_SelectEverything[0].setEnabled( mntm_WithHiddenData[0].getSelection() || mntm_WithSameColour[0].getSelection() || mntm_WithSameOrientation[0].getSelection() || mntm_ExceptSubfiles[0].getSelection() ); showSelectMenu(); } }); } }); mntm_WithWholeSubfiles[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { showSelectMenu(); } }); } }); mntm_ExceptSubfiles[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { mntm_SelectEverything[0].setEnabled( mntm_WithHiddenData[0].getSelection() || mntm_WithSameColour[0].getSelection() || mntm_WithSameOrientation[0].getSelection() || mntm_ExceptSubfiles[0].getSelection() ); mntm_WithWholeSubfiles[0].setEnabled(!mntm_ExceptSubfiles[0].getSelection()); showSelectMenu(); } }); } }); mntm_StopAtEdges[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { showSelectMenu(); } }); } }); mntm_STriangles[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { showSelectMenu(); } }); } }); mntm_SQuads[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { showSelectMenu(); } }); } }); mntm_SCLines[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { showSelectMenu(); } }); } }); mntm_SVertices[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { showSelectMenu(); } }); } }); mntm_SLines[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { showSelectMenu(); } }); } }); mntm_SelectEverything[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); sels.setScope(SelectorSettings.EVERYTHING); loadSelectorSettings(); vm.selector(sels); vm.syncWithTextEditors(true); return; } } } }); mntm_SelectConnected[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); sels.setScope(SelectorSettings.CONNECTED); loadSelectorSettings(); vm.selector(sels); vm.syncWithTextEditors(true); return; } } } }); mntm_SelectTouching[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); sels.setScope(SelectorSettings.TOUCHING); loadSelectorSettings(); vm.selector(sels); vm.syncWithTextEditors(true); return; } } } }); mntm_SelectIsolatedVertices[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); vm.selectIsolatedVertices(); vm.syncWithTextEditors(true); } } } }); } }); mntm_Split[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); vm.split(2); } } } }); } }); mntm_SplitNTimes[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { final int[] frac = new int[]{2}; if (new ValueDialogInt(getShell(), I18n.E3D_SplitEdges, I18n.E3D_NumberOfFractions) { @Override public void initializeSpinner() { this.spn_Value[0].setMinimum(2); this.spn_Value[0].setMaximum(1000); this.spn_Value[0].setValue(2); } @Override public void applyValue() { frac[0] = this.spn_Value[0].getValue(); } }.open() == OK) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); vm.split(frac[0]); } } } } }); } }); mntm_MergeToAverage[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); vm.merge(MergeTo.AVERAGE, true); return; } } } }); mntm_MergeToLastSelected[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); vm.merge(MergeTo.LAST_SELECTED, true); return; } } } }); mntm_MergeToNearestVertex[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); vm.merge(MergeTo.NEAREST_VERTEX, true); return; } } } }); mntm_MergeToNearestEdge[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); vm.merge(MergeTo.NEAREST_EDGE, true); return; } } } }); mntm_MergeToNearestFace[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); vm.merge(MergeTo.NEAREST_FACE, true); return; } } } }); mntm_SelectSingleVertex[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { final VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); final Set<Vertex> sv = vm.getSelectedVertices(); if (new VertexDialog(getShell()).open() == IDialogConstants.OK_ID) { Vertex v = VertexDialog.getVertex(); if (vm.getVertices().contains(v)) { sv.add(v); vm.syncWithTextEditors(true); } } return; } } } }); mntm_setXYZ[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { Vertex v = null; final VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); final Set<Vertex> sv = vm.getSelectedVertices(); if (VertexManager.getClipboard().size() == 1) { GData vertex = VertexManager.getClipboard().get(0); if (vertex.type() == 0) { String line = vertex.toString(); line = line.replaceAll("\\s+", " ").trim(); //$NON-NLS-1$ //$NON-NLS-2$ String[] data_segments = line.split("\\s+"); //$NON-NLS-1$ if (line.startsWith("0 !LPE")) { //$NON-NLS-1$ if (line.startsWith("VERTEX ", 7)) { //$NON-NLS-1$ Vector3d start = new Vector3d(); boolean numberError = false; if (data_segments.length == 6) { try { start.setX(new BigDecimal(data_segments[3], Threshold.mc)); } catch (NumberFormatException nfe) { numberError = true; } try { start.setY(new BigDecimal(data_segments[4], Threshold.mc)); } catch (NumberFormatException nfe) { numberError = true; } try { start.setZ(new BigDecimal(data_segments[5], Threshold.mc)); } catch (NumberFormatException nfe) { numberError = true; } } else { numberError = true; } if (!numberError) { v = new Vertex(start); } } } } } else if (sv.size() == 1) { v = sv.iterator().next(); } if (new CoordinatesDialog(getShell(), v).open() == IDialogConstants.OK_ID) { vm.addSnapshot(); int coordCount = 0; coordCount += CoordinatesDialog.isX() ? 1 : 0; coordCount += CoordinatesDialog.isY() ? 1 : 0; coordCount += CoordinatesDialog.isZ() ? 1 : 0; if (coordCount == 1 && CoordinatesDialog.getStart() != null) { Vector3d delta = Vector3d.sub(CoordinatesDialog.getEnd(), CoordinatesDialog.getStart()); boolean doMoveOnLine = false; BigDecimal s = BigDecimal.ZERO; Vector3d v1 = CoordinatesDialog.getStart(); Vertex v2 = CoordinatesDialog.getVertex(); if (CoordinatesDialog.isX() && delta.X.compareTo(BigDecimal.ZERO) != 0) { doMoveOnLine = true; s = v2.X.subtract(CoordinatesDialog.getStart().X).divide(delta.X, Threshold.mc); } else if (CoordinatesDialog.isY() && delta.Y.compareTo(BigDecimal.ZERO) != 0) { doMoveOnLine = true; s = v2.Y.subtract(CoordinatesDialog.getStart().Y).divide(delta.Y, Threshold.mc); } else if (CoordinatesDialog.isZ() && delta.Z.compareTo(BigDecimal.ZERO) != 0) { doMoveOnLine = true; s = v2.Z.subtract(CoordinatesDialog.getStart().Z).divide(delta.Z, Threshold.mc); } if (doMoveOnLine) { CoordinatesDialog.setVertex(new Vertex(v1.X.add(delta.X.multiply(s)), v1.Y.add(delta.Y.multiply(s)), v1.Z.add(delta.Z.multiply(s)))); CoordinatesDialog.setX(true); CoordinatesDialog.setY(true); CoordinatesDialog.setZ(true); } } vm.setXyzOrTranslateOrTransform(CoordinatesDialog.getVertex(), null, TransformationMode.SET, CoordinatesDialog.isX(), CoordinatesDialog.isY(), CoordinatesDialog.isZ(), true, true); CoordinatesDialog.setStart(null); CoordinatesDialog.setEnd(null); } return; } } } }); mntm_Translate[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { if (new TranslateDialog(getShell(), null).open() == IDialogConstants.OK_ID) { c3d.getLockableDatFileReference().getVertexManager().addSnapshot(); c3d.getLockableDatFileReference().getVertexManager().setXyzOrTranslateOrTransform(TranslateDialog.getOffset(), null, TransformationMode.TRANSLATE, TranslateDialog.isX(), TranslateDialog.isY(), TranslateDialog.isZ(), isMovingAdjacentData(), true); } return; } } } }); mntm_Rotate[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { TreeSet<Vertex> clipboard = new TreeSet<Vertex>(); if (VertexManager.getClipboard().size() == 1) { GData vertex = VertexManager.getClipboard().get(0); if (vertex.type() == 0) { String line = vertex.toString(); line = line.replaceAll("\\s+", " ").trim(); //$NON-NLS-1$ //$NON-NLS-2$ String[] data_segments = line.split("\\s+"); //$NON-NLS-1$ if (line.startsWith("0 !LPE")) { //$NON-NLS-1$ if (line.startsWith("VERTEX ", 7)) { //$NON-NLS-1$ Vector3d start = new Vector3d(); boolean numberError = false; if (data_segments.length == 6) { try { start.setX(new BigDecimal(data_segments[3], Threshold.mc)); } catch (NumberFormatException nfe) { numberError = true; } try { start.setY(new BigDecimal(data_segments[4], Threshold.mc)); } catch (NumberFormatException nfe) { numberError = true; } try { start.setZ(new BigDecimal(data_segments[5], Threshold.mc)); } catch (NumberFormatException nfe) { numberError = true; } } else { numberError = true; } if (!numberError) { clipboard.add(new Vertex(start)); } } } } } if (new RotateDialog(getShell(), null, clipboard).open() == IDialogConstants.OK_ID) { c3d.getLockableDatFileReference().getVertexManager().addSnapshot(); c3d.getLockableDatFileReference().getVertexManager().setXyzOrTranslateOrTransform(RotateDialog.getAngles(), RotateDialog.getPivot(), TransformationMode.ROTATE, RotateDialog.isX(), RotateDialog.isY(), TranslateDialog.isZ(), isMovingAdjacentData(), true); } return; } } } }); mntm_Scale[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { TreeSet<Vertex> clipboard = new TreeSet<Vertex>(); if (VertexManager.getClipboard().size() == 1) { GData vertex = VertexManager.getClipboard().get(0); if (vertex.type() == 0) { String line = vertex.toString(); line = line.replaceAll("\\s+", " ").trim(); //$NON-NLS-1$ //$NON-NLS-2$ String[] data_segments = line.split("\\s+"); //$NON-NLS-1$ if (line.startsWith("0 !LPE")) { //$NON-NLS-1$ if (line.startsWith("VERTEX ", 7)) { //$NON-NLS-1$ Vector3d start = new Vector3d(); boolean numberError = false; if (data_segments.length == 6) { try { start.setX(new BigDecimal(data_segments[3], Threshold.mc)); } catch (NumberFormatException nfe) { numberError = true; } try { start.setY(new BigDecimal(data_segments[4], Threshold.mc)); } catch (NumberFormatException nfe) { numberError = true; } try { start.setZ(new BigDecimal(data_segments[5], Threshold.mc)); } catch (NumberFormatException nfe) { numberError = true; } } else { numberError = true; } if (!numberError) { clipboard.add(new Vertex(start)); } } } } } if (new ScaleDialog(getShell(), null, clipboard).open() == IDialogConstants.OK_ID) { c3d.getLockableDatFileReference().getVertexManager().addSnapshot(); c3d.getLockableDatFileReference().getVertexManager().setXyzOrTranslateOrTransform(ScaleDialog.getScaleFactors(), ScaleDialog.getPivot(), TransformationMode.SCALE, ScaleDialog.isX(), ScaleDialog.isY(), ScaleDialog.isZ(), isMovingAdjacentData(), true); } return; } } } }); mntm_Edger2[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); if (new EdgerDialog(getShell(), es).open() == IDialogConstants.OK_ID) { vm.addSnapshot(); vm.addEdges(es); } return; } } } }); mntm_Rectifier[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); if (new RectifierDialog(getShell(), rs).open() == IDialogConstants.OK_ID) { vm.addSnapshot(); vm.rectify(rs, true, true); } return; } } } }); mntm_Isecalc[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); if (new IsecalcDialog(getShell(), is).open() == IDialogConstants.OK_ID) { vm.addSnapshot(); vm.isecalc(is); } return; } } } }); mntm_SlicerPro[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); if (new SlicerProDialog(getShell(), ss).open() == IDialogConstants.OK_ID) { vm.addSnapshot(); vm.slicerpro(ss); } return; } } } }); mntm_Intersector[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); if (new IntersectorDialog(getShell(), ins).open() == IDialogConstants.OK_ID) { vm.addSnapshot(); vm.intersector(ins, true); } return; } } } }); mntm_Lines2Pattern[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); if (new Lines2PatternDialog(getShell()).open() == IDialogConstants.OK_ID) { vm.addSnapshot(); vm.lines2pattern(); } return; } } } }); mntm_PathTruder[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); if (new PathTruderDialog(getShell(), ps).open() == IDialogConstants.OK_ID) { vm.addSnapshot(); vm.pathTruder(ps); } return; } } } }); mntm_SymSplitter[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); if (new SymSplitterDialog(getShell(), sims).open() == IDialogConstants.OK_ID) { vm.addSnapshot(); vm.symSplitter(sims); } return; } } } }); mntm_Unificator[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); if (new UnificatorDialog(getShell(), us).open() == IDialogConstants.OK_ID) { vm.addSnapshot(); vm.unificator(us); } return; } } } }); mntm_RingsAndCones[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { if (new RingsAndConesDialog(getShell(), ris).open() == IDialogConstants.OK_ID) { c3d.getLockableDatFileReference().getVertexManager().addSnapshot(); RingsAndCones.solve(Editor3DWindow.getWindow().getShell(), c3d.getLockableDatFileReference(), cmp_Primitives[0].getPrimitives(), ris, true); } return; } } } }); mntm_TJunctionFinder[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); DatFile df = c3d.getLockableDatFileReference(); if (df.equals(Project.getFileToEdit()) && !df.isReadOnly()) { if (new TJunctionDialog(getShell(), tjs).open() == IDialogConstants.OK_ID) { VertexManager vm = df.getVertexManager(); vm.addSnapshot(); vm.fixTjunctions(tjs.getMode() == 0); } return; } } } }); mntm_MeshReducer[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); DatFile df = c3d.getLockableDatFileReference(); if (df.equals(Project.getFileToEdit()) && !df.isReadOnly()) { VertexManager vm = df.getVertexManager(); vm.addSnapshot(); vm.meshReduce(); return; } } } }); mntm_Txt2Dat[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { DatFile df = c3d.getLockableDatFileReference(); if (df.isReadOnly()) return; VertexManager vm = df.getVertexManager(); vm.addSnapshot(); if (new Txt2DatDialog(getShell(), ts).open() == IDialogConstants.OK_ID && !ts.getText().trim().isEmpty()) { java.awt.Font myFont; if (ts.getFontData() == null) { myFont = new java.awt.Font(org.nschmidt.ldparteditor.enums.Font.MONOSPACE.getFontData()[0].getName(), java.awt.Font.PLAIN, 32); } else { FontData fd = ts.getFontData(); int style = 0; final int c2 = SWT.BOLD | SWT.ITALIC; switch (fd.getStyle()) { case c2: style = java.awt.Font.BOLD | java.awt.Font.ITALIC; break; case SWT.BOLD: style = java.awt.Font.BOLD; break; case SWT.ITALIC: style = java.awt.Font.ITALIC; break; case SWT.NORMAL: style = java.awt.Font.PLAIN; break; } myFont = new java.awt.Font(fd.getName(), style, fd.getHeight()); } GData anchorData = df.getDrawChainTail(); int lineNumber = df.getDrawPerLine_NOCLONE().getKey(anchorData); Set<GData> triangleSet = TextTriangulator.triangulateText(myFont, ts.getText().trim(), ts.getFlatness().doubleValue(), ts.getInterpolateFlatness().doubleValue(), View.DUMMY_REFERENCE, df, ts.getFontHeight().intValue(), ts.getDeltaAngle().doubleValue()); for (GData gda3 : triangleSet) { lineNumber++; df.getDrawPerLine_NOCLONE().put(lineNumber, gda3); GData gdata = gda3; anchorData.setNext(gda3); anchorData = gdata; } anchorData.setNext(null); df.setDrawChainTail(anchorData); vm.setModified(true, true); return; } } } } }); // MARK Options mntm_ResetSettingsOnRestart[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_WARNING | SWT.OK | SWT.CANCEL); messageBox.setText(I18n.DIALOG_Warning); messageBox.setMessage(I18n.E3D_DeleteConfig); int result = messageBox.open(); if (result == SWT.CANCEL) { return; } WorkbenchManager.getUserSettingState().setResetOnStart(true); } }); mntm_CustomiseKeys[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { KeyTableDialog dialog = new KeyTableDialog(getShell()); if (dialog.open() == IDialogConstants.OK_ID) { } } }); mntm_SelectAnotherLDConfig[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { FileDialog fd = new FileDialog(sh, SWT.OPEN); fd.setText(I18n.E3D_OpenLDConfig); fd.setFilterPath(WorkbenchManager.getUserSettingState().getLdrawFolderPath()); String[] filterExt = { "*.ldr", "LDConfig.ldr", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ fd.setFilterExtensions(filterExt); String[] filterNames = { I18n.E3D_LDrawConfigurationFile1, I18n.E3D_LDrawConfigurationFile2, I18n.E3D_AllFiles }; fd.setFilterNames(filterNames); String selected = fd.open(); System.out.println(selected); if (selected != null && View.loadLDConfig(selected)) { GData.CACHE_warningsAndErrors.clear(); WorkbenchManager.getUserSettingState().setLdConfigPath(selected); Set<DatFile> dfs = new HashSet<DatFile>(); for (OpenGLRenderer renderer : renders) { dfs.add(renderer.getC3D().getLockableDatFileReference()); } for (DatFile df : dfs) { df.getVertexManager().addSnapshot(); SubfileCompiler.compile(df, false, false); } } } }); mntm_UploadLogs[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { String source = ""; //$NON-NLS-1$ { UTF8BufferedReader b1 = null, b2 = null; StringBuilder code = new StringBuilder(); File l1 = new File("error_log.txt");//$NON-NLS-1$ File l2 = new File("error_log2.txt");//$NON-NLS-1$ if (l1.exists() || l2.exists()) { try { if (l1.exists()) { b1 = new UTF8BufferedReader("error_log.txt"); //$NON-NLS-1$ String line; while ((line = b1.readLine()) != null) { code.append(line); code.append(StringHelper.getLineDelimiter()); } } if (l2.exists()) { b2 = new UTF8BufferedReader("error_log2.txt"); //$NON-NLS-1$ String line; while ((line = b2.readLine()) != null) { code.append(line); code.append(StringHelper.getLineDelimiter()); } } source = code.toString(); } catch (Exception e1) { if (b1 != null) { try { b1.close(); } catch (Exception consumend) {} } if (b2 != null) { try { b2.close(); } catch (Exception consumend) {} } MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK); messageBox.setText(I18n.DIALOG_Error); messageBox.setMessage(I18n.E3D_LogUploadUnexpectedException); messageBox.open(); return; } finally { if (b1 != null) { try { b1.close(); } catch (Exception consumend) {} } if (b2 != null) { try { b2.close(); } catch (Exception consumend) {} } } } else { MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK); messageBox.setText(I18n.DIALOG_Info); messageBox.setMessage(I18n.E3D_LogUploadNoLogFiles); messageBox.open(); return; } } LogUploadDialog dialog = new LogUploadDialog(getShell(), source); if (dialog.open() == IDialogConstants.OK_ID) { UTF8BufferedReader b1 = null, b2 = null; if (mntm_UploadLogs[0].getData() == null) { mntm_UploadLogs[0].setData(0); } else { int uploadCount = (int) mntm_UploadLogs[0].getData(); uploadCount++; if (uploadCount > 16) { MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK); messageBox.setText(I18n.DIALOG_Warning); messageBox.setMessage(I18n.E3D_LogUploadLimit); messageBox.open(); return; } mntm_UploadLogs[0].setData(uploadCount); } try { Thread.sleep(2000); String url = "http://pastebin.com/api/api_post.php"; //$NON-NLS-1$ String charset = StandardCharsets.UTF_8.name(); // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name() String title = "[LDPartEditor " + I18n.VERSION_Version + "]"; //$NON-NLS-1$ //$NON-NLS-2$ String devKey = "79cf77977cd2d798dd02f07d93b01ddb"; //$NON-NLS-1$ StringBuilder code = new StringBuilder(); File l1 = new File("error_log.txt");//$NON-NLS-1$ File l2 = new File("error_log2.txt");//$NON-NLS-1$ if (l1.exists() || l2.exists()) { if (l1.exists()) { b1 = new UTF8BufferedReader("error_log.txt"); //$NON-NLS-1$ String line; while ((line = b1.readLine()) != null) { code.append(line); code.append(StringHelper.getLineDelimiter()); } } if (l2.exists()) { b2 = new UTF8BufferedReader("error_log2.txt"); //$NON-NLS-1$ String line; while ((line = b2.readLine()) != null) { code.append(line); code.append(StringHelper.getLineDelimiter()); } } String query = String.format("api_option=paste&api_user_key=%s&api_paste_private=%s&api_paste_name=%s&api_dev_key=%s&api_paste_code=%s", //$NON-NLS-1$ URLEncoder.encode("4cc892c8052bd17d805a1a2907ee8014", charset), //$NON-NLS-1$ URLEncoder.encode("0", charset),//$NON-NLS-1$ URLEncoder.encode(title, charset), URLEncoder.encode(devKey, charset), URLEncoder.encode(code.toString(), charset) ); URLConnection connection = new URL(url).openConnection(); connection.setDoOutput(true); // Triggers POST. connection.setRequestProperty("Accept-Charset", charset); //$NON-NLS-1$ connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset); //$NON-NLS-1$ //$NON-NLS-2$ try (OutputStream output = connection.getOutputStream()) { output.write(query.getBytes(charset)); } BufferedReader response =new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); //$NON-NLS-1$ MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK); messageBox.setText(I18n.DIALOG_Info); Object[] messageArguments = {response.readLine()}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.E3D_LogUploadSuccess); messageBox.setMessage(formatter.format(messageArguments)); messageBox.open(); } else { MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK); messageBox.setText(I18n.DIALOG_Info); messageBox.setMessage(I18n.E3D_LogUploadNoLogFiles); messageBox.open(); } } catch (Exception e1) { MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK); messageBox.setText(I18n.DIALOG_Info); messageBox.setMessage(I18n.E3D_LogUploadUnexpectedException); messageBox.open(); } finally { if (b1 != null) { try { b1.close(); } catch (Exception consumend) {} } if (b2 != null) { try { b2.close(); } catch (Exception consumend) {} } } } } }); mntm_SyncWithTextEditor[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { WorkbenchManager.getUserSettingState().getSyncWithTextEditor().set(mntm_SyncWithTextEditor[0].getSelection()); mntm_SyncLpeInline[0].setEnabled(mntm_SyncWithTextEditor[0].getSelection()); } }); mntm_SyncLpeInline[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { WorkbenchManager.getUserSettingState().getSyncWithLpeInline().set(mntm_SyncLpeInline[0].getSelection()); } }); // MARK Merge, split... mntm_Flip[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); vm.flipSelection(); return; } } } }); mntm_SubdivideCatmullClark[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); vm.subdivideCatmullClark(); return; } } } }); mntm_SubdivideLoop[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); vm.subdivideLoop(); return; } } } }); // MARK Background PNG btn_PngFocus[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Composite3D c3d = null; for (OpenGLRenderer renderer : renders) { c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { c3d = c3d.getLockableDatFileReference().getLastSelectedComposite(); if (c3d == null) { c3d = renderer.getC3D(); } break; } } if (c3d == null) return; c3d.setClassicPerspective(false); WidgetSelectionHelper.unselectAllChildButtons(c3d.getViewAnglesMenu()); VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); GDataPNG png = vm.getSelectedBgPicture(); if (png == null) { if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) { vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$ vm.setModified(true, true); } vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0)); png = vm.getSelectedBgPicture(); updateBgPictureTab(); } Matrix4f tMatrix = new Matrix4f(); tMatrix.setIdentity(); tMatrix = tMatrix.scale(new Vector3f(png.scale.x, png.scale.y, png.scale.z)); Matrix4f dMatrix = new Matrix4f(); dMatrix.setIdentity(); Matrix4f.rotate((float) (png.angleB.doubleValue() / 180.0 * Math.PI), new Vector3f(1f, 0f, 0f), dMatrix, dMatrix); Matrix4f.rotate((float) (png.angleA.doubleValue() / 180.0 * Math.PI), new Vector3f(0f, 1f, 0f), dMatrix, dMatrix); Matrix4f.mul(dMatrix, tMatrix, tMatrix); Vector4f vx = Matrix4f.transform(dMatrix, new Vector4f(png.offset.x, 0f, 0f, 1f), null); Vector4f vy = Matrix4f.transform(dMatrix, new Vector4f(0f, png.offset.y, 0f, 1f), null); Vector4f vz = Matrix4f.transform(dMatrix, new Vector4f(0f, 0f, png.offset.z, 1f), null); Matrix4f transMatrix = new Matrix4f(); transMatrix.setIdentity(); transMatrix.m30 = -vx.x; transMatrix.m31 = -vx.y; transMatrix.m32 = -vx.z; transMatrix.m30 -= vy.x; transMatrix.m31 -= vy.y; transMatrix.m32 -= vy.z; transMatrix.m30 -= vz.x; transMatrix.m31 -= vz.y; transMatrix.m32 -= vz.z; Matrix4f rotMatrixD = new Matrix4f(); rotMatrixD.setIdentity(); Matrix4f.rotate((float) (png.angleB.doubleValue() / 180.0 * Math.PI), new Vector3f(1f, 0f, 0f), rotMatrixD, rotMatrixD); Matrix4f.rotate((float) (png.angleA.doubleValue() / 180.0 * Math.PI), new Vector3f(0f, 1f, 0f), rotMatrixD, rotMatrixD); rotMatrixD = rotMatrixD.scale(new Vector3f(-1f, 1f, -1f)); rotMatrixD.invert(); c3d.getRotation().load(rotMatrixD); c3d.getTranslation().load(transMatrix); c3d.getPerspectiveCalculator().calculateOriginData(); vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex())); return; } }); btn_PngImage[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); GDataPNG png = vm.getSelectedBgPicture(); if (updatingPngPictureTab) return; if (png == null) { if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeAllTextures(); } vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$ vm.setModified(true, true); } vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0)); png = vm.getSelectedBgPicture(); updateBgPictureTab(); } FileDialog fd = new FileDialog(getShell(), SWT.SAVE); fd.setText(I18n.E3D_OpenPngImage); try { File f = new File(png.texturePath); fd.setFilterPath(f.getParent()); fd.setFileName(f.getName()); } catch (Exception ex) { } String[] filterExt = { "*.png", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$ fd.setFilterExtensions(filterExt); String[] filterNames = { I18n.E3D_PortableNetworkGraphics, I18n.E3D_AllFiles}; fd.setFilterNames(filterNames); String texturePath = fd.open(); if (texturePath != null) { String newText = png.getString(png.offset, png.angleA, png.angleB, png.angleC, png.scale, texturePath); GDataPNG newPngPicture = new GDataPNG(newText, png.offset, png.angleA, png.angleB, png.angleC, png.scale, texturePath); replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference()); pngPictureUpdateCounter++; if (pngPictureUpdateCounter > 3) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeOldTextures(); } pngPictureUpdateCounter = 0; } vm.setModified(true, true); vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex())); } return; } } } }); btn_PngNext[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); DatFile df = c3d.getLockableDatFileReference(); if (df.equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) { VertexManager vm = df.getVertexManager(); GDataPNG sp = vm.getSelectedBgPicture(); boolean noBgPictures = df.hasNoBackgroundPictures(); vm.setSelectedBgPictureIndex(vm.getSelectedBgPictureIndex() + 1); boolean indexOutOfBounds = vm.getSelectedBgPictureIndex() >= df.getBackgroundPictureCount(); boolean noRealData = df.getDrawPerLine_NOCLONE().getKey(sp) == null; if (noBgPictures) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeAllTextures(); } vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$ vm.setModified(true, true); vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0)); } else { if (indexOutOfBounds) vm.setSelectedBgPictureIndex(0); if (noRealData) { vm.setSelectedBgPictureIndex(0); vm.setSelectedBgPicture(df.getBackgroundPicture(0)); } else { vm.setSelectedBgPicture(df.getBackgroundPicture(vm.getSelectedBgPictureIndex())); } } updateBgPictureTab(); } } } }); btn_PngPrevious[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); DatFile df = c3d.getLockableDatFileReference(); if (df.equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) { VertexManager vm = df.getVertexManager(); GDataPNG sp = vm.getSelectedBgPicture(); boolean noBgPictures = df.hasNoBackgroundPictures(); vm.setSelectedBgPictureIndex(vm.getSelectedBgPictureIndex() - 1); boolean indexOutOfBounds = vm.getSelectedBgPictureIndex() < 0; boolean noRealData = df.getDrawPerLine_NOCLONE().getKey(sp) == null; if (noBgPictures) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeAllTextures(); } vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$ vm.setModified(true, true); vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0)); } else { if (indexOutOfBounds) vm.setSelectedBgPictureIndex(df.getBackgroundPictureCount() - 1); if (noRealData) { vm.setSelectedBgPictureIndex(0); vm.setSelectedBgPicture(df.getBackgroundPicture(0)); } else { vm.setSelectedBgPicture(df.getBackgroundPicture(vm.getSelectedBgPictureIndex())); } } updateBgPictureTab(); } } } }); spn_PngA1[0].addValueChangeListener(new ValueChangeAdapter() { @Override public void valueChanged(BigDecimalSpinner spn) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); GDataPNG png = vm.getSelectedBgPicture(); if (updatingPngPictureTab) return; if (png == null) { if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeAllTextures(); } vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$ vm.setModified(true, true); } vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0)); png = vm.getSelectedBgPicture(); updateBgPictureTab(); } String newText = png.getString(png.offset, spn.getValue(), png.angleB, png.angleC, png.scale, png.texturePath); GDataPNG newPngPicture = new GDataPNG(newText, png.offset, spn.getValue(), png.angleB, png.angleC, png.scale, png.texturePath); replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference()); pngPictureUpdateCounter++; if (pngPictureUpdateCounter > 3) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeOldTextures(); } pngPictureUpdateCounter = 0; } vm.setModified(true, true); vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex())); return; } } } }); spn_PngA2[0].addValueChangeListener(new ValueChangeAdapter() { @Override public void valueChanged(BigDecimalSpinner spn) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); GDataPNG png = vm.getSelectedBgPicture(); if (updatingPngPictureTab) return; if (png == null) { if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeAllTextures(); } vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$ vm.setModified(true, true); } vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0)); png = vm.getSelectedBgPicture(); updateBgPictureTab(); } String newText = png.getString(png.offset, png.angleA, spn.getValue(), png.angleC, png.scale, png.texturePath); GDataPNG newPngPicture = new GDataPNG(newText, png.offset, png.angleA, spn.getValue(), png.angleC, png.scale, png.texturePath); replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference()); pngPictureUpdateCounter++; if (pngPictureUpdateCounter > 3) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeOldTextures(); } pngPictureUpdateCounter = 0; } vm.setModified(true, true); vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex())); return; } } } }); spn_PngA3[0].addValueChangeListener(new ValueChangeAdapter() { @Override public void valueChanged(BigDecimalSpinner spn) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); GDataPNG png = vm.getSelectedBgPicture(); if (updatingPngPictureTab) return; if (png == null) { if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeAllTextures(); } vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$ vm.setModified(true, true); } vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0)); png = vm.getSelectedBgPicture(); updateBgPictureTab(); } String newText = png.getString(png.offset, png.angleA, png.angleB, spn.getValue(), png.scale, png.texturePath); GDataPNG newPngPicture = new GDataPNG(newText, png.offset, png.angleA, png.angleB, spn.getValue(), png.scale, png.texturePath); replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference()); pngPictureUpdateCounter++; if (pngPictureUpdateCounter > 3) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeOldTextures(); } pngPictureUpdateCounter = 0; } vm.setModified(true, true); vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex())); return; } } } }); spn_PngSX[0].addValueChangeListener(new ValueChangeAdapter() { @Override public void valueChanged(BigDecimalSpinner spn) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); GDataPNG png = vm.getSelectedBgPicture(); if (updatingPngPictureTab) return; if (png == null) { if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeAllTextures(); } vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$ vm.setModified(true, true); } vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0)); png = vm.getSelectedBgPicture(); updateBgPictureTab(); } Vertex newScale = new Vertex(spn.getValue(), png.scale.Y, png.scale.Z); String newText = png.getString(png.offset, png.angleA, png.angleB, png.angleC, newScale, png.texturePath); GDataPNG newPngPicture = new GDataPNG(newText, png.offset, png.angleA, png.angleB, png.angleC, newScale, png.texturePath); replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference()); pngPictureUpdateCounter++; if (pngPictureUpdateCounter > 3) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeOldTextures(); } pngPictureUpdateCounter = 0; } vm.setModified(true, true); vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex())); return; } } } }); spn_PngSY[0].addValueChangeListener(new ValueChangeAdapter() { @Override public void valueChanged(BigDecimalSpinner spn) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); GDataPNG png = vm.getSelectedBgPicture(); if (updatingPngPictureTab) return; if (png == null) { if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeAllTextures(); } vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$ vm.setModified(true, true); } vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0)); png = vm.getSelectedBgPicture(); updateBgPictureTab(); } Vertex newScale = new Vertex(png.scale.X, spn.getValue(), png.scale.Z); String newText = png.getString(png.offset, png.angleA, png.angleB, png.angleC, newScale, png.texturePath); GDataPNG newPngPicture = new GDataPNG(newText, png.offset, png.angleA, png.angleB, png.angleC, newScale, png.texturePath); replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference()); vm.setModified(true, true); vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex())); return; } } } }); spn_PngX[0].addValueChangeListener(new ValueChangeAdapter() { @Override public void valueChanged(BigDecimalSpinner spn) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); GDataPNG png = vm.getSelectedBgPicture(); if (updatingPngPictureTab) return; if (png == null) { if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeAllTextures(); } vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$ vm.setModified(true, true); } vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0)); png = vm.getSelectedBgPicture(); updateBgPictureTab(); } Vertex newOffset = new Vertex(spn.getValue(), png.offset.Y, png.offset.Z); String newText = png.getString(newOffset, png.angleA, png.angleB, png.angleC, png.scale, png.texturePath); GDataPNG newPngPicture = new GDataPNG(newText, newOffset, png.angleA, png.angleB, png.angleC, png.scale, png.texturePath); replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference()); pngPictureUpdateCounter++; if (pngPictureUpdateCounter > 3) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeOldTextures(); } pngPictureUpdateCounter = 0; } vm.setModified(true, true); vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex())); return; } } } }); spn_PngY[0].addValueChangeListener(new ValueChangeAdapter() { @Override public void valueChanged(BigDecimalSpinner spn) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); GDataPNG png = vm.getSelectedBgPicture(); if (updatingPngPictureTab) return; if (png == null) { if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeAllTextures(); } vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$ vm.setModified(true, true); } vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0)); png = vm.getSelectedBgPicture(); updateBgPictureTab(); } Vertex newOffset = new Vertex(png.offset.X, spn.getValue(), png.offset.Z); String newText = png.getString(newOffset, png.angleA, png.angleB, png.angleC, png.scale, png.texturePath); GDataPNG newPngPicture = new GDataPNG(newText, newOffset, png.angleA, png.angleB, png.angleC, png.scale, png.texturePath); replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference()); pngPictureUpdateCounter++; if (pngPictureUpdateCounter > 3) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeOldTextures(); } pngPictureUpdateCounter = 0; } vm.setModified(true, true); vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex())); return; } } } }); spn_PngZ[0].addValueChangeListener(new ValueChangeAdapter() { @Override public void valueChanged(BigDecimalSpinner spn) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); GDataPNG png = vm.getSelectedBgPicture(); if (updatingPngPictureTab) return; if (png == null) { if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeAllTextures(); } vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$ vm.setModified(true, true); } vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0)); png = vm.getSelectedBgPicture(); updateBgPictureTab(); } Vertex newOffset = new Vertex(png.offset.X, png.offset.Y, spn.getValue()); String newText = png.getString(newOffset, png.angleA, png.angleB, png.angleC, png.scale, png.texturePath); GDataPNG newPngPicture = new GDataPNG(newText, newOffset, png.angleA, png.angleB, png.angleC, png.scale, png.texturePath); replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference()); pngPictureUpdateCounter++; if (pngPictureUpdateCounter > 3) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeOldTextures(); } pngPictureUpdateCounter = 0; } vm.setModified(true, true); vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex())); return; } } } }); mntm_IconSize1[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { WorkbenchManager.getUserSettingState().setIconSize(0); } }); mntm_IconSize2[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { WorkbenchManager.getUserSettingState().setIconSize(1); } }); mntm_IconSize3[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { WorkbenchManager.getUserSettingState().setIconSize(2); } }); mntm_IconSize4[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { WorkbenchManager.getUserSettingState().setIconSize(3); } }); mntm_IconSize5[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { WorkbenchManager.getUserSettingState().setIconSize(4); } }); mntm_IconSize6[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { WorkbenchManager.getUserSettingState().setIconSize(5); } }); Project.createDefault(); treeItem_Project[0].setData(Project.getProjectPath()); treeItem_Official[0].setData(WorkbenchManager.getUserSettingState().getLdrawFolderPath()); treeItem_Unofficial[0].setData(WorkbenchManager.getUserSettingState().getUnofficialFolderPath()); try { new ProgressMonitorDialog(Editor3DWindow.getWindow().getShell()).run(true, false, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask(I18n.E3D_LoadingLibrary, IProgressMonitor.UNKNOWN); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { LibraryManager.readUnofficialParts(treeItem_UnofficialParts[0]); LibraryManager.readUnofficialSubparts(treeItem_UnofficialSubparts[0]); LibraryManager.readUnofficialPrimitives(treeItem_UnofficialPrimitives[0]); LibraryManager.readUnofficialHiResPrimitives(treeItem_UnofficialPrimitives48[0]); LibraryManager.readUnofficialLowResPrimitives(treeItem_UnofficialPrimitives8[0]); LibraryManager.readOfficialParts(treeItem_OfficialParts[0]); LibraryManager.readOfficialSubparts(treeItem_OfficialSubparts[0]); LibraryManager.readOfficialPrimitives(treeItem_OfficialPrimitives[0]); LibraryManager.readOfficialHiResPrimitives(treeItem_OfficialPrimitives48[0]); LibraryManager.readOfficialLowResPrimitives(treeItem_OfficialPrimitives8[0]); } }); Thread.sleep(1500); } }); } catch (InvocationTargetException consumed) { } catch (InterruptedException consumed) { } txt_Search[0].setText(" "); //$NON-NLS-1$ txt_Search[0].setText(""); //$NON-NLS-1$ Project.getFileToEdit().setLastSelectedComposite(Editor3DWindow.renders.get(0).getC3D()); new EditorTextWindow().run(Project.getFileToEdit()); updateBgPictureTab(); Project.getFileToEdit().addHistory(); this.open(); // Dispose all resources (never delete this!) ResourceManager.dispose(); SWTResourceManager.dispose(); // Dispose the display (never delete this, too!) Display.getCurrent().dispose(); } protected void addRecentFile(String projectPath) { final int index = recentItems.indexOf(projectPath); if (index > -1) { recentItems.remove(index); } else if (recentItems.size() > 20) { recentItems.remove(0); } recentItems.add(projectPath); } public void addRecentFile(DatFile dat) { addRecentFile(dat.getNewName()); } private void replaceBgPicture(GDataPNG selectedBgPicture, GDataPNG newBgPicture, DatFile linkedDatFile) { if (linkedDatFile.getDrawPerLine_NOCLONE().getKey(selectedBgPicture) == null) return; GData before = selectedBgPicture.getBefore(); GData next = selectedBgPicture.getNext(); int index = linkedDatFile.getDrawPerLine_NOCLONE().getKey(selectedBgPicture); selectedBgPicture.setGoingToBeReplaced(true); linkedDatFile.getVertexManager().remove(selectedBgPicture); linkedDatFile.getDrawPerLine_NOCLONE().put(index, newBgPicture); before.setNext(newBgPicture); newBgPicture.setNext(next); linkedDatFile.getVertexManager().setSelectedBgPicture(newBgPicture); updateBgPictureTab(); return; } private void resetAddState() { setAddingSubfiles(false); setAddingVertices(false); setAddingLines(false); setAddingTriangles(false); setAddingQuads(false); setAddingCondlines(false); for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); DatFile df = c3d.getLockableDatFileReference(); df.setObjVertex1(null); df.setObjVertex2(null); df.setObjVertex3(null); df.setObjVertex4(null); df.setNearestObjVertex1(null); df.setNearestObjVertex2(null); } } public void setAddState(int type) { if (isAddingSomething()) { resetAddState(); btn_AddVertex[0].setSelection(false); btn_AddLine[0].setSelection(false); btn_AddTriangle[0].setSelection(false); btn_AddQuad[0].setSelection(false); btn_AddCondline[0].setSelection(false); btn_AddPrimitive[0].setSelection(false); setAddingSomething(false); } switch (type) { case 0: btn_AddComment[0].notifyListeners(SWT.Selection, new Event()); break; case 1: setAddingVertices(!isAddingVertices()); btn_AddVertex[0].setSelection(isAddingVertices()); setAddingSomething(isAddingVertices()); clickSingleBtn(btn_AddVertex[0]); break; case 2: setAddingLines(!isAddingLines()); btn_AddLine[0].setSelection(isAddingLines()); setAddingSomething(isAddingLines()); clickSingleBtn(btn_AddLine[0]); break; case 3: setAddingTriangles(!isAddingTriangles()); btn_AddTriangle[0].setSelection(isAddingTriangles()); setAddingSomething(isAddingTriangles()); clickSingleBtn(btn_AddTriangle[0]); break; case 4: setAddingQuads(!isAddingQuads()); btn_AddQuad[0].setSelection(isAddingQuads()); setAddingSomething(isAddingQuads()); clickSingleBtn(btn_AddQuad[0]); break; case 5: setAddingCondlines(!isAddingCondlines()); btn_AddCondline[0].setSelection(isAddingCondlines()); setAddingSomething(isAddingCondlines()); clickSingleBtn(btn_AddCondline[0]); break; } } public void setObjMode(int type) { switch (type) { case 0: btn_Vertices[0].setSelection(true); setWorkingType(ObjectMode.VERTICES); clickSingleBtn(btn_Vertices[0]); break; case 1: btn_TrisNQuads[0].setSelection(true); setWorkingType(ObjectMode.FACES); clickSingleBtn(btn_TrisNQuads[0]); break; case 2: btn_Lines[0].setSelection(true); setWorkingType(ObjectMode.LINES); clickSingleBtn(btn_Lines[0]); break; case 3: btn_Subfiles[0].setSelection(true); setWorkingType(ObjectMode.SUBFILES); clickSingleBtn(btn_Subfiles[0]); break; } } /** * The Shell-Close-Event */ @Override protected void handleShellCloseEvent() { boolean unsavedProjectFiles = false; Set<DatFile> unsavedFiles = new HashSet<DatFile>(Project.getUnsavedFiles()); for (DatFile df : unsavedFiles) { if (!df.getText().equals(df.getOriginalText()) || df.isVirtual() && !df.getText().trim().isEmpty()) { MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.CANCEL | SWT.NO); messageBox.setText(I18n.DIALOG_UnsavedChangesTitle); Object[] messageArguments = {df.getShortName()}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.DIALOG_UnsavedChanges); messageBox.setMessage(formatter.format(messageArguments)); int result = messageBox.open(); if (result == SWT.NO) { // Remove file from tree updateTree_removeEntry(df); } else if (result == SWT.YES) { if (df.save()) { Editor3DWindow.getWindow().addRecentFile(df); } else { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK); messageBoxError.setText(I18n.DIALOG_Error); messageBoxError.setMessage(I18n.DIALOG_CantSaveFile); messageBoxError.open(); cleanupClosedData(); updateTree_unsavedEntries(); return; } } else { cleanupClosedData(); updateTree_unsavedEntries(); return; } } } Set<EditorTextWindow> ow = new HashSet<EditorTextWindow>(Project.getOpenTextWindows()); for (EditorTextWindow w : ow) { w.getShell().close(); } { ArrayList<TreeItem> ta = getProjectParts().getItems(); for (TreeItem ti : ta) { unsavedProjectFiles = unsavedProjectFiles || !((DatFile) ti.getData()).getText().trim().equals("") || !Project.getUnsavedFiles().contains(ti.getData()); //$NON-NLS-1$ } } { ArrayList<TreeItem> ta = getProjectSubparts().getItems(); for (TreeItem ti : ta) { unsavedProjectFiles = unsavedProjectFiles || !((DatFile) ti.getData()).getText().trim().equals("") || !Project.getUnsavedFiles().contains(ti.getData()); ; //$NON-NLS-1$ } } { ArrayList<TreeItem> ta = getProjectPrimitives().getItems(); for (TreeItem ti : ta) { unsavedProjectFiles = unsavedProjectFiles || !((DatFile) ti.getData()).getText().trim().equals("") || !Project.getUnsavedFiles().contains(ti.getData()); ; //$NON-NLS-1$ } } { ArrayList<TreeItem> ta = getProjectPrimitives48().getItems(); for (TreeItem ti : ta) { unsavedProjectFiles = unsavedProjectFiles || !((DatFile) ti.getData()).getText().trim().equals("") || !Project.getUnsavedFiles().contains(ti.getData()); ; //$NON-NLS-1$ } } { ArrayList<TreeItem> ta = getProjectPrimitives8().getItems(); for (TreeItem ti : ta) { unsavedProjectFiles = unsavedProjectFiles || !((DatFile) ti.getData()).getText().trim().equals("") || !Project.getUnsavedFiles().contains(ti.getData()); ; //$NON-NLS-1$ } } if (unsavedProjectFiles && Project.isDefaultProject()) { // Save new project here, if the project contains at least one non-empty file boolean cancelIt = false; boolean secondRun = false; while (true) { int result = IDialogConstants.CANCEL_ID; if (secondRun) result = new NewProjectDialog(true).open(); if (result == IDialogConstants.OK_ID) { while (new File(Project.getTempProjectPath()).isDirectory()) { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.YES | SWT.CANCEL | SWT.NO); messageBoxError.setText(I18n.PROJECT_ProjectOverwriteTitle); messageBoxError.setMessage(I18n.PROJECT_ProjectOverwrite); int result2 = messageBoxError.open(); if (result2 == SWT.NO) { result = new NewProjectDialog(true).open(); } else if (result2 == SWT.YES) { break; } else { cancelIt = true; break; } } if (!cancelIt) { Project.setProjectName(Project.getTempProjectName()); Project.setProjectPath(Project.getTempProjectPath()); NLogger.debug(getClass(), "Saving new project..."); //$NON-NLS-1$ if (!Project.save()) { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK); messageBoxError.setText(I18n.DIALOG_Error); messageBoxError.setMessage(I18n.DIALOG_CantSaveProject); } } break; } else { secondRun = true; MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.CANCEL | SWT.NO); messageBox.setText(I18n.DIALOG_UnsavedChangesTitle); Object[] messageArguments = {I18n.DIALOG_TheNewProject}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.DIALOG_UnsavedChanges); messageBox.setMessage(formatter.format(messageArguments)); int result2 = messageBox.open(); if (result2 == SWT.CANCEL) { cancelIt = true; break; } else if (result2 == SWT.NO) { break; } } } if (cancelIt) { cleanupClosedData(); updateTree_unsavedEntries(); return; } } // NEVER DELETE THIS! final int s = renders.size(); for (int i = 0; i < s; i++) { try { GLCanvas canvas = canvasList.get(i); OpenGLRenderer renderer = renders.get(i); if (!canvas.isCurrent()) { canvas.setCurrent(); try { GLContext.useContext(canvas); } catch (LWJGLException e) { NLogger.error(Editor3DWindow.class, e); } } renderer.dispose(); } catch (SWTException swtEx) { NLogger.error(Editor3DWindow.class, swtEx); } } // All "history threads" needs to know that the main window was closed alive.set(false); final Editor3DWindowState winState = WorkbenchManager.getEditor3DWindowState(); // Traverse the sash forms to store the 3D configuration final ArrayList<Composite3DState> c3dStates = new ArrayList<Composite3DState>(); Control c = Editor3DDesign.getSashForm().getChildren()[1]; if (c != null) { if (c instanceof SashForm|| c instanceof CompositeContainer) { // c instanceof CompositeContainer: Simple case, since its only one 3D view open -> No recursion! saveComposite3DStates(c, c3dStates, "", "|"); //$NON-NLS-1$ //$NON-NLS-2$ } else { // There is no 3D window open at the moment } } else { // There is no 3D window open at the moment } winState.setThreeDwindowConfig(c3dStates); winState.setLeftSashWeights(((SashForm) Editor3DDesign.getSashForm().getChildren()[0]).getWeights()); winState.setLeftSashWidth(Editor3DDesign.getSashForm().getWeights()); winState.setPrimitiveZoom(cmp_Primitives[0].getZoom()); winState.setPrimitiveZoomExponent(cmp_Primitives[0].getZoom_exponent()); winState.setPrimitiveViewport(cmp_Primitives[0].getViewport2()); WorkbenchManager.getUserSettingState().setRecentItems(getRecentItems()); // Save the workbench WorkbenchManager.saveWorkbench(); setReturnCode(CANCEL); close(); } private void saveComposite3DStates(Control c, ArrayList<Composite3DState> c3dStates, String parentPath, String path) { Composite3DState st = new Composite3DState(); st.setParentPath(parentPath); st.setPath(path); if (c instanceof CompositeContainer) { NLogger.debug(getClass(), "{0}C", path); //$NON-NLS-1$ final Composite3D c3d = ((CompositeContainer) c).getComposite3D(); st.setSash(false); st.setScales(c3d.getParent() instanceof CompositeScale); st.setVertical(false); st.setWeights(null); st.setPerspective(c3d.isClassicPerspective() ? c3d.getPerspectiveIndex() : Perspective.TWO_THIRDS); st.setRenderMode(c3d.getRenderMode()); st.setShowLabel(c3d.isShowingLabels()); st.setShowAxis(c3d.isShowingAxis()); st.setShowGrid(c3d.isGridShown()); st.setShowOrigin(c3d.isOriginShown()); st.setLights(c3d.isLightOn()); st.setMeshlines(c3d.isMeshLines()); st.setSubfileMeshlines(c3d.isSubMeshLines()); st.setVertices(c3d.isShowingVertices()); st.setHiddenVertices(c3d.isShowingHiddenVertices()); st.setStudLogo(c3d.isShowingLogo()); st.setLineMode(c3d.getLineMode()); st.setAlwaysBlackLines(c3d.isBlackEdges()); st.setAnaglyph3d(c3d.isAnaglyph3d()); st.setGridScale(c3d.getGrid_scale()); } else if (c instanceof SashForm) { NLogger.debug(getClass(), path); SashForm s = (SashForm) c; st.setSash(true); st.setVertical((s.getStyle() & SWT.VERTICAL) != 0); st.setWeights(s.getWeights()); Control c1 = s.getChildren()[0]; Control c2 = s.getChildren()[1]; saveComposite3DStates(c1, c3dStates, path, path + "s1|"); //$NON-NLS-1$ saveComposite3DStates(c2, c3dStates, path, path + "s2|"); //$NON-NLS-1$ } else { return; } c3dStates.add(st); } /** * @return The serializable window state of the Editor3DWindow */ public Editor3DWindowState getEditor3DWindowState() { return this.editor3DWindowState; } /** * @param editor3DWindowState * The serializable window state of the Editor3DWindow */ public void setEditor3DWindowState(Editor3DWindowState editor3DWindowState) { this.editor3DWindowState = editor3DWindowState; } /** * @return The current Editor3DWindow instance */ public static Editor3DWindow getWindow() { return Editor3DWindow.window; } /** * Updates the tree for new unsaved entries */ public void updateTree_unsavedEntries() { ArrayList<TreeItem> categories = new ArrayList<TreeItem>(); categories.add(this.treeItem_ProjectParts[0]); categories.add(this.treeItem_ProjectSubparts[0]); categories.add(this.treeItem_ProjectPrimitives[0]); categories.add(this.treeItem_ProjectPrimitives48[0]); categories.add(this.treeItem_ProjectPrimitives8[0]); categories.add(this.treeItem_UnofficialParts[0]); categories.add(this.treeItem_UnofficialSubparts[0]); categories.add(this.treeItem_UnofficialPrimitives[0]); categories.add(this.treeItem_UnofficialPrimitives48[0]); categories.add(this.treeItem_UnofficialPrimitives8[0]); int counter = 0; for (TreeItem item : categories) { counter++; ArrayList<TreeItem> datFileTreeItems = item.getItems(); for (TreeItem df : datFileTreeItems) { DatFile d = (DatFile) df.getData(); StringBuilder nameSb = new StringBuilder(new File(d.getNewName()).getName()); final String d2 = d.getDescription(); if (counter < 6 && (!d.getNewName().startsWith(Project.getProjectPath()) || !d.getNewName().replace(Project.getProjectPath() + File.separator, "").contains(File.separator))) { //$NON-NLS-1$ nameSb.insert(0, "(!) "); //$NON-NLS-1$ } // MARK For Debug Only! // DatType t = d.getType(); // if (t == DatType.PART) { // nameSb.append(" PART"); //$NON-NLS-1$ // } else if (t == DatType.SUBPART) { // nameSb.append(" SUBPART"); //$NON-NLS-1$ // } else if (t == DatType.PRIMITIVE) { // nameSb.append(" PRIMITIVE"); //$NON-NLS-1$ // } else if (t == DatType.PRIMITIVE48) { // nameSb.append(" PRIMITIVE48"); //$NON-NLS-1$ // } else if (t == DatType.PRIMITIVE8) { // nameSb.append(" PRIMITIVE8"); //$NON-NLS-1$ // } if (d2 != null) nameSb.append(d2); if (Project.getUnsavedFiles().contains(d)) { df.setText("* " + nameSb.toString()); //$NON-NLS-1$ } else { df.setText(nameSb.toString()); } } } this.treeItem_Unsaved[0].removeAll(); Set<DatFile> unsaved = Project.getUnsavedFiles(); for (DatFile df : unsaved) { TreeItem ti = new TreeItem(this.treeItem_Unsaved[0], SWT.NONE); StringBuilder nameSb = new StringBuilder(new File(df.getNewName()).getName()); final String d = df.getDescription(); if (d != null) nameSb.append(d); ti.setText(nameSb.toString()); ti.setData(df); } this.treeParts[0].build(); this.treeParts[0].redraw(); } /** * Updates the tree for renamed entries */ @SuppressWarnings("unchecked") public void updateTree_renamedEntries() { HashMap<String, TreeItem> categories = new HashMap<String, TreeItem>(); HashMap<String, DatType> types = new HashMap<String, DatType>(); ArrayList<String> validPrefixes = new ArrayList<String>(); { String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "PARTS" + File.separator + "S" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$ validPrefixes.add(s); categories.put(s, this.treeItem_UnofficialSubparts[0]); types.put(s, DatType.SUBPART); } { String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "parts" + File.separator + "s" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$ validPrefixes.add(s); categories.put(s, this.treeItem_UnofficialSubparts[0]); types.put(s, DatType.SUBPART); } { String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "PARTS" + File.separator; //$NON-NLS-1$ validPrefixes.add(s); categories.put(s, this.treeItem_UnofficialParts[0]); types.put(s, DatType.PART); } { String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "parts" + File.separator; //$NON-NLS-1$ validPrefixes.add(s); categories.put(s,this.treeItem_UnofficialParts[0]); types.put(s, DatType.PART); } { String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator + "48" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$ validPrefixes.add(s); categories.put(s, this.treeItem_UnofficialPrimitives48[0]); types.put(s, DatType.PRIMITIVE48); } { String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator + "48" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$ validPrefixes.add(s); categories.put(s, this.treeItem_UnofficialPrimitives48[0]); types.put(s, DatType.PRIMITIVE48); } { String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator + "8" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$ validPrefixes.add(s); categories.put(s, this.treeItem_UnofficialPrimitives8[0]); types.put(s, DatType.PRIMITIVE8); } { String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator + "8" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$ validPrefixes.add(s); categories.put(s, this.treeItem_UnofficialPrimitives8[0]); types.put(s, DatType.PRIMITIVE8); } { String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator; //$NON-NLS-1$ validPrefixes.add(s); categories.put(s, this.treeItem_UnofficialPrimitives[0]); types.put(s, DatType.PRIMITIVE); } { String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator; //$NON-NLS-1$ validPrefixes.add(s); categories.put(s, this.treeItem_UnofficialPrimitives[0]); types.put(s, DatType.PRIMITIVE); } { String s = Project.getProjectPath() + File.separator + "PARTS" + File.separator + "S" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$ validPrefixes.add(s); categories.put(s, this.treeItem_ProjectSubparts[0]); types.put(s, DatType.SUBPART); } { String s = Project.getProjectPath() + File.separator + "parts" + File.separator + "s" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$ validPrefixes.add(s); categories.put(s, this.treeItem_ProjectSubparts[0]); types.put(s, DatType.SUBPART); } { String s = Project.getProjectPath() + File.separator + "PARTS" + File.separator; //$NON-NLS-1$ validPrefixes.add(s); categories.put(s, this.treeItem_ProjectParts[0]); types.put(s, DatType.PART); } { String s = Project.getProjectPath() + File.separator + "parts" + File.separator; //$NON-NLS-1$ validPrefixes.add(s); categories.put(s, this.treeItem_ProjectParts[0]); types.put(s, DatType.PART); } { String s = Project.getProjectPath() + File.separator + "P" + File.separator + "48" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$ validPrefixes.add(s); categories.put(s, this.treeItem_ProjectPrimitives48[0]); types.put(s, DatType.PRIMITIVE48); } { String s = Project.getProjectPath() + File.separator + "p" + File.separator + "48" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$ validPrefixes.add(s); categories.put(s, this.treeItem_ProjectPrimitives48[0]); types.put(s, DatType.PRIMITIVE48); } { String s = Project.getProjectPath() + File.separator + "P" + File.separator + "8" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$ validPrefixes.add(s); categories.put(s, this.treeItem_ProjectPrimitives8[0]); types.put(s, DatType.PRIMITIVE8); } { String s = Project.getProjectPath() + File.separator + "p" + File.separator + "8" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$ validPrefixes.add(s); categories.put(s, this.treeItem_ProjectPrimitives8[0]); types.put(s, DatType.PRIMITIVE8); } { String s = Project.getProjectPath() + File.separator + "P" + File.separator; //$NON-NLS-1$ validPrefixes.add(s); categories.put(s, this.treeItem_ProjectPrimitives[0]); types.put(s, DatType.PRIMITIVE); } { String s = Project.getProjectPath() + File.separator + "p" + File.separator; //$NON-NLS-1$ validPrefixes.add(s); categories.put(s, this.treeItem_ProjectPrimitives[0]); types.put(s, DatType.PRIMITIVE); } Collections.sort(validPrefixes, new Comp()); for (String prefix : validPrefixes) { TreeItem item = categories.get(prefix); ArrayList<DatFile> dats = (ArrayList<DatFile>) item.getData(); ArrayList<TreeItem> datFileTreeItems = item.getItems(); Set<TreeItem> itemsToRemove = new HashSet<TreeItem>(); for (TreeItem df : datFileTreeItems) { DatFile d = (DatFile) df.getData(); String newName = d.getNewName(); String validPrefix = null; for (String p2 : validPrefixes) { if (newName.startsWith(p2)) { validPrefix = p2; break; } } if (validPrefix != null) { TreeItem item2 = categories.get(validPrefix); if (!item2.equals(item)) { itemsToRemove.add(df); dats.remove(d); ((ArrayList<DatFile>) item2.getData()).add(d); TreeItem nt = new TreeItem(item2, SWT.NONE); nt.setText(df.getText()); d.setType(types.get(validPrefix)); nt.setData(d); } } } datFileTreeItems.removeAll(itemsToRemove); } this.treeParts[0].build(); this.treeParts[0].redraw(); } private class Comp implements Comparator<String> { @Override public int compare(String o1, String o2) { if (o1.length() < o2.length()) { return 1; } else if (o1.length() > o2.length()) { return -1; } else { return 0; } } } /** * Removes an item from the tree,<br><br> * If it is open in a {@linkplain Composite3D}, this composite will be linked with a dummy file * If it is open in a {@linkplain CompositeTab}, this composite will be closed * */ public void updateTree_removeEntry(DatFile e) { ArrayList<TreeItem> categories = new ArrayList<TreeItem>(); categories.add(this.treeItem_ProjectParts[0]); categories.add(this.treeItem_ProjectSubparts[0]); categories.add(this.treeItem_ProjectPrimitives[0]); categories.add(this.treeItem_ProjectPrimitives8[0]); categories.add(this.treeItem_ProjectPrimitives48[0]); categories.add(this.treeItem_UnofficialParts[0]); categories.add(this.treeItem_UnofficialSubparts[0]); categories.add(this.treeItem_UnofficialPrimitives[0]); categories.add(this.treeItem_UnofficialPrimitives8[0]); categories.add(this.treeItem_UnofficialPrimitives48[0]); int counter = 0; for (TreeItem item : categories) { counter++; ArrayList<TreeItem> datFileTreeItems = new ArrayList<TreeItem>(item.getItems()); for (TreeItem df : datFileTreeItems) { DatFile d = (DatFile) df.getData(); if (e.equals(d)) { item.getItems().remove(df); } else { StringBuilder nameSb = new StringBuilder(new File(d.getNewName()).getName()); final String d2 = d.getDescription(); if (counter < 6 && (!d.getNewName().startsWith(Project.getProjectPath()) || !d.getNewName().replace(Project.getProjectPath() + File.separator, "").contains(File.separator))) { //$NON-NLS-1$ nameSb.insert(0, "(!) "); //$NON-NLS-1$ } if (d2 != null) nameSb.append(d2); if (Project.getUnsavedFiles().contains(d)) { df.setText("* " + nameSb.toString()); //$NON-NLS-1$ } else { df.setText(nameSb.toString()); } } } } this.treeItem_Unsaved[0].removeAll(); Project.removeUnsavedFile(e); for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(e)) { c3d.unlinkData(); } } HashSet<EditorTextWindow> windows = new HashSet<EditorTextWindow>(Project.getOpenTextWindows()); for (EditorTextWindow win : windows) { win.closeTabWithDatfile(e); } Set<DatFile> unsaved = Project.getUnsavedFiles(); for (DatFile df : unsaved) { TreeItem ti = new TreeItem(this.treeItem_Unsaved[0], SWT.NONE); StringBuilder nameSb = new StringBuilder(new File(df.getNewName()).getName()); final String d = df.getDescription(); if (d != null) nameSb.append(d); ti.setText(nameSb.toString()); ti.setData(df); } TreeItem[] folders = new TreeItem[10]; folders[0] = treeItem_ProjectParts[0]; folders[1] = treeItem_ProjectPrimitives[0]; folders[2] = treeItem_ProjectPrimitives8[0]; folders[3] = treeItem_ProjectPrimitives48[0]; folders[4] = treeItem_ProjectSubparts[0]; folders[5] = treeItem_UnofficialParts[0]; folders[6] = treeItem_UnofficialPrimitives[0]; folders[7] = treeItem_UnofficialPrimitives8[0]; folders[8] = treeItem_UnofficialPrimitives48[0]; folders[9] = treeItem_UnofficialSubparts[0]; for (TreeItem folder : folders) { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences =(ArrayList<DatFile>) folder.getData(); cachedReferences.remove(e); } this.treeParts[0].build(); this.treeParts[0].redraw(); } // Helper functions private void clickBtnTest(Button btn) { WidgetSelectionHelper.unselectAllChildButtons((ToolItem) btn.getParent()); btn.setSelection(true); } private void clickSingleBtn(Button btn) { boolean state = btn.getSelection(); WidgetSelectionHelper.unselectAllChildButtons((ToolItem) btn.getParent()); btn.setSelection(state); } public boolean isAddingSomething() { return addingSomething; } public void setAddingSomething(boolean addingSomething) { this.addingSomething = addingSomething; for (OpenGLRenderer renderer : renders) { renderer.getC3D().getLockableDatFileReference().getVertexManager().clearSelection(); } } public boolean isAddingVertices() { return addingVertices; } public void setAddingVertices(boolean addingVertices) { this.addingVertices = addingVertices; } public boolean isAddingLines() { return addingLines; } public void setAddingLines(boolean addingLines) { this.addingLines = addingLines; } public boolean isAddingTriangles() { return addingTriangles; } public void setAddingTriangles(boolean addingTriangles) { this.addingTriangles = addingTriangles; } public boolean isAddingQuads() { return addingQuads; } public void setAddingQuads(boolean addingQuads) { this.addingQuads = addingQuads; } public boolean isAddingCondlines() { return addingCondlines; } public void setAddingCondlines(boolean addingCondlines) { this.addingCondlines = addingCondlines; } public boolean isAddingSubfiles() { return addingSubfiles; } public void setAddingSubfiles(boolean addingSubfiles) { this.addingSubfiles = addingSubfiles; } public void disableAddAction() { addingSomething = false; addingVertices = false; addingLines = false; addingTriangles = false; addingQuads = false; addingCondlines = false; addingSubfiles = false; btn_AddVertex[0].setSelection(false); btn_AddLine[0].setSelection(false); btn_AddTriangle[0].setSelection(false); btn_AddQuad[0].setSelection(false); btn_AddCondline[0].setSelection(false); btn_AddPrimitive[0].setSelection(false); } public TreeItem getProjectParts() { return treeItem_ProjectParts[0]; } public TreeItem getProjectPrimitives() { return treeItem_ProjectPrimitives[0]; } public TreeItem getProjectPrimitives48() { return treeItem_ProjectPrimitives48[0]; } public TreeItem getProjectPrimitives8() { return treeItem_ProjectPrimitives8[0]; } public TreeItem getProjectSubparts() { return treeItem_ProjectSubparts[0]; } public TreeItem getUnofficialParts() { return treeItem_UnofficialParts[0]; } public TreeItem getUnofficialPrimitives() { return treeItem_UnofficialPrimitives[0]; } public TreeItem getUnofficialPrimitives48() { return treeItem_UnofficialPrimitives48[0]; } public TreeItem getUnofficialPrimitives8() { return treeItem_UnofficialPrimitives8[0]; } public TreeItem getUnofficialSubparts() { return treeItem_UnofficialSubparts[0]; } public TreeItem getOfficialParts() { return treeItem_OfficialParts[0]; } public TreeItem getOfficialPrimitives() { return treeItem_OfficialPrimitives[0]; } public TreeItem getOfficialPrimitives48() { return treeItem_OfficialPrimitives48[0]; } public TreeItem getOfficialPrimitives8() { return treeItem_OfficialPrimitives8[0]; } public TreeItem getOfficialSubparts() { return treeItem_OfficialSubparts[0]; } public TreeItem getUnsaved() { return treeItem_Unsaved[0]; } public ObjectMode getWorkingType() { return workingType; } public void setWorkingType(ObjectMode workingMode) { this.workingType = workingMode; } public boolean isMovingAdjacentData() { return movingAdjacentData; } public void setMovingAdjacentData(boolean movingAdjacentData) { btn_MoveAdjacentData[0].setSelection(movingAdjacentData); this.movingAdjacentData = movingAdjacentData; } public WorkingMode getWorkingAction() { return workingAction; } public void setWorkingAction(WorkingMode workingAction) { this.workingAction = workingAction; switch (workingAction) { case COMBINED: clickBtnTest(btn_Combined[0]); workingAction = WorkingMode.COMBINED; break; case MOVE: clickBtnTest(btn_Move[0]); workingAction = WorkingMode.MOVE; break; case ROTATE: clickBtnTest(btn_Rotate[0]); workingAction = WorkingMode.ROTATE; break; case SCALE: clickBtnTest(btn_Scale[0]); workingAction = WorkingMode.SCALE; break; case SELECT: clickBtnTest(btn_Select[0]); workingAction = WorkingMode.SELECT; break; default: break; } } public ManipulatorScope getTransformationMode() { return transformationMode; } public boolean hasNoTransparentSelection() { return noTransparentSelection; } public void setNoTransparentSelection(boolean noTransparentSelection) { this.noTransparentSelection = noTransparentSelection; } public boolean hasBfcToggle() { return bfcToggle; } public void setBfcToggle(boolean bfcToggle) { this.bfcToggle = bfcToggle; } public GColour getLastUsedColour() { return lastUsedColour; } public void setLastUsedColour(GColour lastUsedColour) { this.lastUsedColour = lastUsedColour; } public void setLastUsedColour2(GColour lastUsedColour) { final int imgSize; switch (Editor3DWindow.getIconsize()) { case 0: imgSize = 16; break; case 1: imgSize = 24; break; case 2: imgSize = 32; break; case 3: imgSize = 48; break; case 4: imgSize = 64; break; case 5: imgSize = 72; break; default: imgSize = 16; break; } final GColour[] gColour2 = new GColour[] { lastUsedColour }; int num = gColour2[0].getColourNumber(); if (View.hasLDConfigColour(num)) { gColour2[0] = View.getLDConfigColour(num); } else { num = -1; } Editor3DWindow.getWindow().setLastUsedColour(gColour2[0]); btn_LastUsedColour[0].removeListener(SWT.Paint, btn_LastUsedColour[0].getListeners(SWT.Paint)[0]); btn_LastUsedColour[0].removeListener(SWT.Selection, btn_LastUsedColour[0].getListeners(SWT.Selection)[0]); final Color col = SWTResourceManager.getColor((int) (gColour2[0].getR() * 255f), (int) (gColour2[0].getG() * 255f), (int) (gColour2[0].getB() * 255f)); final Point size = btn_LastUsedColour[0].computeSize(SWT.DEFAULT, SWT.DEFAULT); final int x = size.x / 4; final int y = size.y / 4; final int w = size.x / 2; final int h = size.y / 2; btn_LastUsedColour[0].addPaintListener(new PaintListener() { @Override public void paintControl(PaintEvent e) { e.gc.setBackground(col); e.gc.fillRectangle(x, y, w, h); if (gColour2[0].getA() == 1f) { e.gc.drawImage(ResourceManager.getImage("icon16_transparent.png"), 0, 0, imgSize, imgSize, x, y, w, h); //$NON-NLS-1$ } else { e.gc.drawImage(ResourceManager.getImage("icon16_halftrans.png"), 0, 0, imgSize, imgSize, x, y, w, h); //$NON-NLS-1$ } } }); btn_LastUsedColour[0].addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Editor3DWindow.getWindow().setLastUsedColour(gColour2[0]); int num = gColour2[0].getColourNumber(); if (!View.hasLDConfigColour(num)) { num = -1; } Project.getFileToEdit().getVertexManager().colourChangeSelection(num, gColour2[0].getR(), gColour2[0].getG(), gColour2[0].getB(), gColour2[0].getA()); } } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); if (num != -1) { Object[] messageArguments = {num, View.getLDConfigColourName(num)}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.EDITORTEXT_Colour1); btn_LastUsedColour[0].setToolTipText(formatter.format(messageArguments)); } else { StringBuilder colourBuilder = new StringBuilder(); colourBuilder.append("0x2"); //$NON-NLS-1$ colourBuilder.append(MathHelper.toHex((int) (255f * gColour2[0].getR())).toUpperCase()); colourBuilder.append(MathHelper.toHex((int) (255f * gColour2[0].getG())).toUpperCase()); colourBuilder.append(MathHelper.toHex((int) (255f * gColour2[0].getB())).toUpperCase()); Object[] messageArguments = {colourBuilder.toString()}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.EDITORTEXT_Colour2); btn_LastUsedColour[0].setToolTipText(formatter.format(messageArguments)); } btn_LastUsedColour[0].redraw(); } public void cleanupClosedData() { Set<DatFile> openFiles = new HashSet<DatFile>(Project.getUnsavedFiles()); for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); openFiles.add(c3d.getLockableDatFileReference()); } for (EditorTextWindow w : Project.getOpenTextWindows()) { for (CTabItem t : w.getTabFolder().getItems()) { openFiles.add(((CompositeTab) t).getState().getFileNameObj()); } } Set<DatFile> deadFiles = new HashSet<DatFile>(Project.getParsedFiles()); deadFiles.removeAll(openFiles); if (!deadFiles.isEmpty()) { GData.CACHE_viewByProjection.clear(); GData.parsedLines.clear(); GData.CACHE_parsedFilesSource.clear(); } for (DatFile datFile : deadFiles) { datFile.disposeData(); } if (!deadFiles.isEmpty()) { // TODO Debug only System.gc(); } } public String getSearchCriteria() { return txt_Search[0].getText(); } public void resetSearch() { search(""); //$NON-NLS-1$ } public void search(final String word) { this.getShell().getDisplay().asyncExec(new Runnable() { @SuppressWarnings("unchecked") @Override public void run() { String criteria = ".*" + word + ".*"; //$NON-NLS-1$ //$NON-NLS-2$ TreeItem[] folders = new TreeItem[15]; folders[0] = treeItem_OfficialParts[0]; folders[1] = treeItem_OfficialPrimitives[0]; folders[2] = treeItem_OfficialPrimitives8[0]; folders[3] = treeItem_OfficialPrimitives48[0]; folders[4] = treeItem_OfficialSubparts[0]; folders[5] = treeItem_UnofficialParts[0]; folders[6] = treeItem_UnofficialPrimitives[0]; folders[7] = treeItem_UnofficialPrimitives8[0]; folders[8] = treeItem_UnofficialPrimitives48[0]; folders[9] = treeItem_UnofficialSubparts[0]; folders[10] = treeItem_ProjectParts[0]; folders[11] = treeItem_ProjectPrimitives[0]; folders[12] = treeItem_ProjectPrimitives8[0]; folders[13] = treeItem_ProjectPrimitives48[0]; folders[14] = treeItem_ProjectSubparts[0]; if (folders[0].getData() == null) { for (TreeItem folder : folders) { folder.setData(new ArrayList<DatFile>()); for (TreeItem part : folder.getItems()) { ((ArrayList<DatFile>) folder.getData()).add((DatFile) part.getData()); } } } try { "42".matches(criteria); //$NON-NLS-1$ } catch (Exception ex) { criteria = ".*"; //$NON-NLS-1$ } final Pattern pattern = Pattern.compile(criteria); for (int i = 0; i < 15; i++) { TreeItem folder = folders[i]; folder.removeAll(); for (DatFile part : (ArrayList<DatFile>) folder.getData()) { StringBuilder nameSb = new StringBuilder(new File(part.getNewName()).getName()); if (i > 9 && (!part.getNewName().startsWith(Project.getProjectPath()) || !part.getNewName().replace(Project.getProjectPath() + File.separator, "").contains(File.separator))) { //$NON-NLS-1$ nameSb.insert(0, "(!) "); //$NON-NLS-1$ } final String d = part.getDescription(); if (d != null) nameSb.append(d); String name = nameSb.toString(); TreeItem finding = new TreeItem(folder, SWT.NONE); // Save the path finding.setData(part); // Set the filename if (Project.getUnsavedFiles().contains(part) || !part.getOldName().equals(part.getNewName())) { // Insert asterisk if the file was // modified finding.setText("* " + name); //$NON-NLS-1$ } else { finding.setText(name); } finding.setShown(!(d != null && d.startsWith(" - ~Moved to")) && pattern.matcher(name).matches()); //$NON-NLS-1$ } } folders[0].getParent().build(); folders[0].getParent().redraw(); folders[0].getParent().update(); } }); } public void closeAllComposite3D() { ArrayList<OpenGLRenderer> renders2 = new ArrayList<OpenGLRenderer>(renders); for (OpenGLRenderer renderer : renders2) { Composite3D c3d = renderer.getC3D(); c3d.getModifier().closeView(); } } public TreeData getDatFileTreeData(DatFile df) { TreeData result = new TreeData(); ArrayList<TreeItem> categories = new ArrayList<TreeItem>(); categories.add(this.treeItem_ProjectParts[0]); categories.add(this.treeItem_ProjectSubparts[0]); categories.add(this.treeItem_ProjectPrimitives[0]); categories.add(this.treeItem_ProjectPrimitives48[0]); categories.add(this.treeItem_ProjectPrimitives8[0]); categories.add(this.treeItem_UnofficialParts[0]); categories.add(this.treeItem_UnofficialSubparts[0]); categories.add(this.treeItem_UnofficialPrimitives[0]); categories.add(this.treeItem_UnofficialPrimitives48[0]); categories.add(this.treeItem_UnofficialPrimitives8[0]); categories.add(this.treeItem_OfficialParts[0]); categories.add(this.treeItem_OfficialSubparts[0]); categories.add(this.treeItem_OfficialPrimitives[0]); categories.add(this.treeItem_OfficialPrimitives48[0]); categories.add(this.treeItem_OfficialPrimitives8[0]); categories.add(this.treeItem_Unsaved[0]); for (TreeItem item : categories) { ArrayList<TreeItem> datFileTreeItems = item.getItems(); for (TreeItem ti : datFileTreeItems) { DatFile d = (DatFile) ti.getData(); if (df.equals(d)) { result.setLocation(ti); } else if (d.getShortName().equals(df.getShortName())) { result.getLocationsWithSameShortFilenames().add(ti); } } } return result; } /** * Updates the background picture tab */ public void updateBgPictureTab() { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); GDataPNG png = vm.getSelectedBgPicture(); if (png == null) { updatingPngPictureTab = true; txt_PngPath[0].setText("---"); //$NON-NLS-1$ txt_PngPath[0].setToolTipText("---"); //$NON-NLS-1$ spn_PngX[0].setValue(BigDecimal.ZERO); spn_PngY[0].setValue(BigDecimal.ZERO); spn_PngZ[0].setValue(BigDecimal.ZERO); spn_PngA1[0].setValue(BigDecimal.ZERO); spn_PngA2[0].setValue(BigDecimal.ZERO); spn_PngA3[0].setValue(BigDecimal.ZERO); spn_PngSX[0].setValue(BigDecimal.ONE); spn_PngSY[0].setValue(BigDecimal.ONE); txt_PngPath[0].setEnabled(false); btn_PngFocus[0].setEnabled(false); btn_PngImage[0].setEnabled(false); spn_PngX[0].setEnabled(false); spn_PngY[0].setEnabled(false); spn_PngZ[0].setEnabled(false); spn_PngA1[0].setEnabled(false); spn_PngA2[0].setEnabled(false); spn_PngA3[0].setEnabled(false); spn_PngSX[0].setEnabled(false); spn_PngSY[0].setEnabled(false); spn_PngA1[0].getParent().update(); updatingPngPictureTab = false; return; } updatingPngPictureTab = true; txt_PngPath[0].setEnabled(true); btn_PngFocus[0].setEnabled(true); btn_PngImage[0].setEnabled(true); spn_PngX[0].setEnabled(true); spn_PngY[0].setEnabled(true); spn_PngZ[0].setEnabled(true); spn_PngA1[0].setEnabled(true); spn_PngA2[0].setEnabled(true); spn_PngA3[0].setEnabled(true); spn_PngSX[0].setEnabled(true); spn_PngSY[0].setEnabled(true); txt_PngPath[0].setText(png.texturePath); txt_PngPath[0].setToolTipText(png.texturePath); spn_PngX[0].setValue(png.offset.X); spn_PngY[0].setValue(png.offset.Y); spn_PngZ[0].setValue(png.offset.Z); spn_PngA1[0].setValue(png.angleA); spn_PngA2[0].setValue(png.angleB); spn_PngA3[0].setValue(png.angleC); spn_PngSX[0].setValue(png.scale.X); spn_PngSY[0].setValue(png.scale.Y); spn_PngA1[0].getParent().update(); updatingPngPictureTab = false; return; } } } public void unselectAddSubfile() { resetAddState(); btn_AddPrimitive[0].setSelection(false); setAddingSubfiles(false); setAddingSomething(false); } public DatFile createNewDatFile(Shell sh, OpenInWhat where) { FileDialog fd = new FileDialog(sh, SWT.SAVE); fd.setText(I18n.E3D_CreateNewDat); if ("project".equals(Project.getProjectPath())) { //$NON-NLS-1$ try { String path = LDPartEditor.class.getProtectionDomain().getCodeSource().getLocation().getPath(); String decodedPath = URLDecoder.decode(path, "UTF-8"); //$NON-NLS-1$ decodedPath = decodedPath.substring(0, decodedPath.length() - 4); fd.setFilterPath(decodedPath + "project"); //$NON-NLS-1$ } catch (Exception consumed) { fd.setFilterPath(Project.getProjectPath()); } } else { fd.setFilterPath(Project.getProjectPath()); } String[] filterExt = { "*.dat", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$ fd.setFilterExtensions(filterExt); String[] filterNames = { I18n.E3D_LDrawSourceFile, I18n.E3D_AllFiles }; fd.setFilterNames(filterNames); while (true) { String selected = fd.open(); System.out.println(selected); if (selected != null) { // Check if its already created DatFile df = new DatFile(selected); if (isFileNameAllocated(selected, df, true)) { MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.RETRY | SWT.CANCEL); messageBox.setText(I18n.DIALOG_AlreadyAllocatedNameTitle); messageBox.setMessage(I18n.DIALOG_AlreadyAllocatedName); int result = messageBox.open(); if (result == SWT.CANCEL) { break; } } else { TreeItem ti = new TreeItem(this.treeItem_ProjectParts[0], SWT.NONE); StringBuilder nameSb = new StringBuilder(new File(df.getNewName()).getName()); nameSb.append(I18n.E3D_NewFile); ti.setText(nameSb.toString()); ti.setData(df); @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectParts[0].getData(); cachedReferences.add(df); Project.addUnsavedFile(df); updateTree_renamedEntries(); updateTree_unsavedEntries(); openDatFile(df, where, null); return df; } } else { break; } } return null; } public DatFile openDatFile(Shell sh, OpenInWhat where, String filePath) { FileDialog fd = new FileDialog(sh, SWT.OPEN); fd.setText(I18n.E3D_OpenDatFile); if ("project".equals(Project.getProjectPath())) { //$NON-NLS-1$ try { String path = LDPartEditor.class.getProtectionDomain().getCodeSource().getLocation().getPath(); String decodedPath = URLDecoder.decode(path, "UTF-8"); //$NON-NLS-1$ decodedPath = decodedPath.substring(0, decodedPath.length() - 4); fd.setFilterPath(decodedPath + "project"); //$NON-NLS-1$ } catch (Exception consumed) { fd.setFilterPath(Project.getProjectPath()); } } else { fd.setFilterPath(Project.getProjectPath()); } String[] filterExt = { "*.dat", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$ fd.setFilterExtensions(filterExt); String[] filterNames = {I18n.E3D_LDrawSourceFile, I18n.E3D_AllFiles}; fd.setFilterNames(filterNames); String selected = filePath == null ? fd.open() : filePath; System.out.println(selected); if (selected != null) { // Check if its already created DatType type = DatType.PART; DatFile df = new DatFile(selected); DatFile original = isFileNameAllocated2(selected, df); if (original == null) { // Type Check and Description Parsing!! StringBuilder titleSb = new StringBuilder(); UTF8BufferedReader reader = null; File f = new File(selected); try { reader = new UTF8BufferedReader(f.getAbsolutePath()); String title = reader.readLine(); if (title != null) { title = title.trim(); if (title.length() > 0) { titleSb.append(" -"); //$NON-NLS-1$ titleSb.append(title.substring(1)); } } while (true) { String typ = reader.readLine(); if (typ != null) { typ = typ.trim(); if (!typ.startsWith("0")) { //$NON-NLS-1$ break; } else { int i1 = typ.indexOf("!LDRAW_ORG"); //$NON-NLS-1$ if (i1 > -1) { int i2; i2 = typ.indexOf("Subpart"); //$NON-NLS-1$ if (i2 > -1 && i1 < i2) { type = DatType.SUBPART; break; } i2 = typ.indexOf("Part"); //$NON-NLS-1$ if (i2 > -1 && i1 < i2) { type = DatType.PART; break; } i2 = typ.indexOf("48_Primitive"); //$NON-NLS-1$ if (i2 > -1 && i1 < i2) { type = DatType.PRIMITIVE48; break; } i2 = typ.indexOf("8_Primitive"); //$NON-NLS-1$ if (i2 > -1 && i1 < i2) { type = DatType.PRIMITIVE8; break; } i2 = typ.indexOf("Primitive"); //$NON-NLS-1$ if (i2 > -1 && i1 < i2) { type = DatType.PRIMITIVE; break; } } } } else { break; } } } catch (LDParsingException e) { } catch (FileNotFoundException e) { } catch (UnsupportedEncodingException e) { } finally { try { if (reader != null) reader.close(); } catch (LDParsingException e1) { } } df = new DatFile(selected, titleSb.toString(), false, type); df.setProjectFile(df.getNewName().startsWith(Project.getProjectPath())); } else { df.setProjectFile(df.getNewName().startsWith(Project.getProjectPath())); if (original.isProjectFile()) { openDatFile(df, where, null); return df; } { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectParts[0].getData(); if (cachedReferences.contains(df)) { openDatFile(df, where, null); return df; } } { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectSubparts[0].getData(); if (cachedReferences.contains(df)) { openDatFile(df, where, null); return df; } } { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectPrimitives[0].getData(); if (cachedReferences.contains(df)) { openDatFile(df, where, null); return df; } } { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectPrimitives48[0].getData(); if (cachedReferences.contains(df)) { openDatFile(df, where, null); return df; } } { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectPrimitives8[0].getData(); if (cachedReferences.contains(df)) { openDatFile(df, where, null); return df; } } type = original.getType(); df = original; } TreeItem ti; switch (type) { case PART: { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectParts[0].getData(); cachedReferences.add(df); } ti = new TreeItem(this.treeItem_ProjectParts[0], SWT.NONE); break; case SUBPART: { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectSubparts[0].getData(); cachedReferences.add(df); } ti = new TreeItem(this.treeItem_ProjectSubparts[0], SWT.NONE); break; case PRIMITIVE: { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectPrimitives[0].getData(); cachedReferences.add(df); } ti = new TreeItem(this.treeItem_ProjectPrimitives[0], SWT.NONE); break; case PRIMITIVE48: { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectPrimitives48[0].getData(); cachedReferences.add(df); } ti = new TreeItem(this.treeItem_ProjectPrimitives48[0], SWT.NONE); break; case PRIMITIVE8: { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectPrimitives8[0].getData(); cachedReferences.add(df); } ti = new TreeItem(this.treeItem_ProjectPrimitives8[0], SWT.NONE); break; default: { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectParts[0].getData(); cachedReferences.add(df); } ti = new TreeItem(this.treeItem_ProjectParts[0], SWT.NONE); break; } StringBuilder nameSb = new StringBuilder(new File(df.getNewName()).getName()); nameSb.append(I18n.E3D_NewFile); ti.setText(nameSb.toString()); ti.setData(df); updateTree_unsavedEntries(); openDatFile(df, where, null); return df; } return null; } public boolean openDatFile(DatFile df, OpenInWhat where, EditorTextWindow tWin) { if (where == OpenInWhat.EDITOR_3D || where == OpenInWhat.EDITOR_TEXT_AND_3D) { if (renders.isEmpty()) { if ("%EMPTY%".equals(Editor3DWindow.getSashForm().getChildren()[1].getData())) { //$NON-NLS-1$ int[] mainSashWeights = Editor3DWindow.getSashForm().getWeights(); Editor3DWindow.getSashForm().getChildren()[1].dispose(); CompositeContainer cmp_Container = new CompositeContainer(Editor3DWindow.getSashForm(), false); cmp_Container.moveBelow(Editor3DWindow.getSashForm().getChildren()[0]); df.parseForData(true); Project.setFileToEdit(df); cmp_Container.getComposite3D().setLockableDatFileReference(df); cmp_Container.getComposite3D().getModifier().zoomToFit(); Editor3DWindow.getSashForm().getParent().layout(); Editor3DWindow.getSashForm().setWeights(mainSashWeights); } } else { boolean canUpdate = false; for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (!c3d.isDatFileLockedOnDisplay()) { canUpdate = true; break; } } if (canUpdate) { final VertexManager vm = df.getVertexManager(); if (vm.isModified()) { df.setText(df.getText()); } df.parseForData(true); Project.setFileToEdit(df); for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (!c3d.isDatFileLockedOnDisplay()) { c3d.setLockableDatFileReference(df); c3d.getModifier().zoomToFit(); } } } } } if (where == OpenInWhat.EDITOR_TEXT || where == OpenInWhat.EDITOR_TEXT_AND_3D) { for (EditorTextWindow w : Project.getOpenTextWindows()) { for (CTabItem t : w.getTabFolder().getItems()) { if (df.equals(((CompositeTab) t).getState().getFileNameObj())) { w.getTabFolder().setSelection(t); ((CompositeTab) t).getControl().getShell().forceActive(); w.open(); return w == tWin; } } } if (tWin == null) { // Project.getParsedFiles().add(df); IS NECESSARY HERE Project.getParsedFiles().add(df); new EditorTextWindow().run(df); } } return false; } public void disableSelectionTab() { if (Thread.currentThread() == Display.getDefault().getThread()) { updatingSelectionTab = true; txt_Line[0].setText(""); //$NON-NLS-1$ spn_SelectionX1[0].setEnabled(false); spn_SelectionY1[0].setEnabled(false); spn_SelectionZ1[0].setEnabled(false); spn_SelectionX2[0].setEnabled(false); spn_SelectionY2[0].setEnabled(false); spn_SelectionZ2[0].setEnabled(false); spn_SelectionX3[0].setEnabled(false); spn_SelectionY3[0].setEnabled(false); spn_SelectionZ3[0].setEnabled(false); spn_SelectionX4[0].setEnabled(false); spn_SelectionY4[0].setEnabled(false); spn_SelectionZ4[0].setEnabled(false); spn_SelectionX1[0].setValue(BigDecimal.ZERO); spn_SelectionY1[0].setValue(BigDecimal.ZERO); spn_SelectionZ1[0].setValue(BigDecimal.ZERO); spn_SelectionX2[0].setValue(BigDecimal.ZERO); spn_SelectionY2[0].setValue(BigDecimal.ZERO); spn_SelectionZ2[0].setValue(BigDecimal.ZERO); spn_SelectionX3[0].setValue(BigDecimal.ZERO); spn_SelectionY3[0].setValue(BigDecimal.ZERO); spn_SelectionZ3[0].setValue(BigDecimal.ZERO); spn_SelectionX4[0].setValue(BigDecimal.ZERO); spn_SelectionY4[0].setValue(BigDecimal.ZERO); spn_SelectionZ4[0].setValue(BigDecimal.ZERO); lbl_SelectionX1[0].setText(I18n.E3D_PositionX1); lbl_SelectionY1[0].setText(I18n.E3D_PositionY1); lbl_SelectionZ1[0].setText(I18n.E3D_PositionZ1); lbl_SelectionX2[0].setText(I18n.E3D_PositionX2); lbl_SelectionY2[0].setText(I18n.E3D_PositionY2); lbl_SelectionZ2[0].setText(I18n.E3D_PositionZ2); lbl_SelectionX3[0].setText(I18n.E3D_PositionX3); lbl_SelectionY3[0].setText(I18n.E3D_PositionY3); lbl_SelectionZ3[0].setText(I18n.E3D_PositionZ3); lbl_SelectionX4[0].setText(I18n.E3D_PositionX4); lbl_SelectionY4[0].setText(I18n.E3D_PositionY4); lbl_SelectionZ4[0].setText(I18n.E3D_PositionZ4); updatingSelectionTab = false; } else { NLogger.error(getClass(), new SWTException(SWT.ERROR_THREAD_INVALID_ACCESS, "A wrong thread tries to access the GUI!")); //$NON-NLS-1$ Display.getDefault().asyncExec(new Runnable() { @Override public void run() { try { updatingSelectionTab = true; txt_Line[0].setText(""); //$NON-NLS-1$ spn_SelectionX1[0].setEnabled(false); spn_SelectionY1[0].setEnabled(false); spn_SelectionZ1[0].setEnabled(false); spn_SelectionX2[0].setEnabled(false); spn_SelectionY2[0].setEnabled(false); spn_SelectionZ2[0].setEnabled(false); spn_SelectionX3[0].setEnabled(false); spn_SelectionY3[0].setEnabled(false); spn_SelectionZ3[0].setEnabled(false); spn_SelectionX4[0].setEnabled(false); spn_SelectionY4[0].setEnabled(false); spn_SelectionZ4[0].setEnabled(false); spn_SelectionX1[0].setValue(BigDecimal.ZERO); spn_SelectionY1[0].setValue(BigDecimal.ZERO); spn_SelectionZ1[0].setValue(BigDecimal.ZERO); spn_SelectionX2[0].setValue(BigDecimal.ZERO); spn_SelectionY2[0].setValue(BigDecimal.ZERO); spn_SelectionZ2[0].setValue(BigDecimal.ZERO); spn_SelectionX3[0].setValue(BigDecimal.ZERO); spn_SelectionY3[0].setValue(BigDecimal.ZERO); spn_SelectionZ3[0].setValue(BigDecimal.ZERO); spn_SelectionX4[0].setValue(BigDecimal.ZERO); spn_SelectionY4[0].setValue(BigDecimal.ZERO); spn_SelectionZ4[0].setValue(BigDecimal.ZERO); lbl_SelectionX1[0].setText(I18n.E3D_PositionX1); lbl_SelectionY1[0].setText(I18n.E3D_PositionY1); lbl_SelectionZ1[0].setText(I18n.E3D_PositionZ1); lbl_SelectionX2[0].setText(I18n.E3D_PositionX2); lbl_SelectionY2[0].setText(I18n.E3D_PositionY2); lbl_SelectionZ2[0].setText(I18n.E3D_PositionZ2); lbl_SelectionX3[0].setText(I18n.E3D_PositionX3); lbl_SelectionY3[0].setText(I18n.E3D_PositionY3); lbl_SelectionZ3[0].setText(I18n.E3D_PositionZ3); lbl_SelectionX4[0].setText(I18n.E3D_PositionX4); lbl_SelectionY4[0].setText(I18n.E3D_PositionY4); lbl_SelectionZ4[0].setText(I18n.E3D_PositionZ4); updatingSelectionTab = false; } catch (Exception ex) { NLogger.error(getClass(), ex); } } }); } } public static ArrayList<OpenGLRenderer> getRenders() { return renders; } public SearchWindow getSearchWindow() { return searchWindow; } public void setSearchWindow(SearchWindow searchWindow) { this.searchWindow = searchWindow; } public SelectorSettings loadSelectorSettings() { sels.setColour(mntm_WithSameColour[0].getSelection()); sels.setEdgeStop(mntm_StopAtEdges[0].getSelection()); sels.setHidden(mntm_WithHiddenData[0].getSelection()); sels.setNoSubfiles(mntm_ExceptSubfiles[0].getSelection()); sels.setOrientation(mntm_WithSameOrientation[0].getSelection()); sels.setDistance(mntm_WithAccuracy[0].getSelection()); sels.setWholeSubfiles(mntm_WithWholeSubfiles[0].getSelection()); sels.setVertices(mntm_SVertices[0].getSelection()); sels.setLines(mntm_SLines[0].getSelection()); sels.setTriangles(mntm_STriangles[0].getSelection()); sels.setQuads(mntm_SQuads[0].getSelection()); sels.setCondlines(mntm_SCLines[0].getSelection()); return sels; } public boolean isFileNameAllocated(String dir, DatFile df, boolean createNew) { TreeItem[] folders = new TreeItem[15]; folders[0] = treeItem_OfficialParts[0]; folders[1] = treeItem_OfficialPrimitives[0]; folders[2] = treeItem_OfficialPrimitives8[0]; folders[3] = treeItem_OfficialPrimitives48[0]; folders[4] = treeItem_OfficialSubparts[0]; folders[5] = treeItem_UnofficialParts[0]; folders[6] = treeItem_UnofficialPrimitives[0]; folders[7] = treeItem_UnofficialPrimitives8[0]; folders[8] = treeItem_UnofficialPrimitives48[0]; folders[9] = treeItem_UnofficialSubparts[0]; folders[10] = treeItem_ProjectParts[0]; folders[11] = treeItem_ProjectPrimitives[0]; folders[12] = treeItem_ProjectPrimitives8[0]; folders[13] = treeItem_ProjectPrimitives48[0]; folders[14] = treeItem_ProjectSubparts[0]; for (TreeItem folder : folders) { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences =(ArrayList<DatFile>) folder.getData(); for (DatFile d : cachedReferences) { if (createNew || !df.equals(d)) { if (dir.equals(d.getOldName()) || dir.equals(d.getNewName())) { return true; } } } } return false; } private DatFile isFileNameAllocated2(String dir, DatFile df) { TreeItem[] folders = new TreeItem[15]; folders[0] = treeItem_OfficialParts[0]; folders[1] = treeItem_OfficialPrimitives[0]; folders[2] = treeItem_OfficialPrimitives8[0]; folders[3] = treeItem_OfficialPrimitives48[0]; folders[4] = treeItem_OfficialSubparts[0]; folders[5] = treeItem_UnofficialParts[0]; folders[6] = treeItem_UnofficialPrimitives[0]; folders[7] = treeItem_UnofficialPrimitives8[0]; folders[8] = treeItem_UnofficialPrimitives48[0]; folders[9] = treeItem_UnofficialSubparts[0]; folders[10] = treeItem_ProjectParts[0]; folders[11] = treeItem_ProjectPrimitives[0]; folders[12] = treeItem_ProjectPrimitives8[0]; folders[13] = treeItem_ProjectPrimitives48[0]; folders[14] = treeItem_ProjectSubparts[0]; for (TreeItem folder : folders) { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences =(ArrayList<DatFile>) folder.getData(); for (DatFile d : cachedReferences) { if (dir.equals(d.getOldName()) || dir.equals(d.getNewName())) { return d; } } } return null; } public void updatePrimitiveLabel(Primitive p) { if (lbl_selectedPrimitiveItem[0] == null) return; if (p == null) { lbl_selectedPrimitiveItem[0].setText(I18n.E3D_NoPrimitiveSelected); } else { lbl_selectedPrimitiveItem[0].setText(p.toString()); } lbl_selectedPrimitiveItem[0].getParent().layout(); } public CompositePrimitive getCompositePrimitive() { return cmp_Primitives[0]; } public static AtomicBoolean getAlive() { return alive; } public MenuItem getMntmWithSameColour() { return mntm_WithSameColour[0]; } public ArrayList<String> getRecentItems() { return recentItems; } private void setLineSize(Sphere sp, Sphere sp_inv, float line_width1000, float line_width, float line_width_gl, Button btn) { GLPrimitives.SPHERE = sp; GLPrimitives.SPHERE_INV = sp_inv; View.lineWidth1000[0] = line_width1000; View.lineWidth[0] = line_width; View.lineWidthGL[0] = line_width_gl; Set<DatFile> dfs = new HashSet<DatFile>(); for (OpenGLRenderer renderer : renders) { dfs.add(renderer.getC3D().getLockableDatFileReference()); } for (DatFile df : dfs) { df.getVertexManager().addSnapshot(); SubfileCompiler.compile(df, false, false); } clickSingleBtn(btn); } }
src/org/nschmidt/ldparteditor/shells/editor3d/Editor3DWindow.java
/* MIT - License Copyright (c) 2012 - this year, Nils Schmidt 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. */ package org.nschmidt.ldparteditor.shells.editor3d; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.math.BigDecimal; import java.net.URL; import java.net.URLConnection; import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.swt.SWT; import org.eclipse.swt.SWTException; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.opengl.GLCanvas; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.wb.swt.SWTResourceManager; import org.lwjgl.LWJGLException; import org.lwjgl.opengl.GLContext; import org.lwjgl.util.vector.Matrix4f; import org.lwjgl.util.vector.Vector3f; import org.lwjgl.util.vector.Vector4f; import org.nschmidt.ldparteditor.composites.Composite3D; import org.nschmidt.ldparteditor.composites.CompositeContainer; import org.nschmidt.ldparteditor.composites.CompositeScale; import org.nschmidt.ldparteditor.composites.ToolItem; import org.nschmidt.ldparteditor.composites.compositetab.CompositeTab; import org.nschmidt.ldparteditor.composites.primitive.CompositePrimitive; import org.nschmidt.ldparteditor.data.DatFile; import org.nschmidt.ldparteditor.data.DatType; import org.nschmidt.ldparteditor.data.GColour; import org.nschmidt.ldparteditor.data.GData; import org.nschmidt.ldparteditor.data.GData1; import org.nschmidt.ldparteditor.data.GDataPNG; import org.nschmidt.ldparteditor.data.GraphicalDataTools; import org.nschmidt.ldparteditor.data.LibraryManager; import org.nschmidt.ldparteditor.data.Matrix; import org.nschmidt.ldparteditor.data.Primitive; import org.nschmidt.ldparteditor.data.ReferenceParser; import org.nschmidt.ldparteditor.data.RingsAndCones; import org.nschmidt.ldparteditor.data.Vertex; import org.nschmidt.ldparteditor.data.VertexManager; import org.nschmidt.ldparteditor.dialogs.colour.ColourDialog; import org.nschmidt.ldparteditor.dialogs.copy.CopyDialog; import org.nschmidt.ldparteditor.dialogs.edger2.EdgerDialog; import org.nschmidt.ldparteditor.dialogs.intersector.IntersectorDialog; import org.nschmidt.ldparteditor.dialogs.isecalc.IsecalcDialog; import org.nschmidt.ldparteditor.dialogs.keys.KeyTableDialog; import org.nschmidt.ldparteditor.dialogs.lines2pattern.Lines2PatternDialog; import org.nschmidt.ldparteditor.dialogs.logupload.LogUploadDialog; import org.nschmidt.ldparteditor.dialogs.newproject.NewProjectDialog; import org.nschmidt.ldparteditor.dialogs.pathtruder.PathTruderDialog; import org.nschmidt.ldparteditor.dialogs.rectifier.RectifierDialog; import org.nschmidt.ldparteditor.dialogs.ringsandcones.RingsAndConesDialog; import org.nschmidt.ldparteditor.dialogs.rotate.RotateDialog; import org.nschmidt.ldparteditor.dialogs.round.RoundDialog; import org.nschmidt.ldparteditor.dialogs.scale.ScaleDialog; import org.nschmidt.ldparteditor.dialogs.selectvertex.VertexDialog; import org.nschmidt.ldparteditor.dialogs.setcoordinates.CoordinatesDialog; import org.nschmidt.ldparteditor.dialogs.slicerpro.SlicerProDialog; import org.nschmidt.ldparteditor.dialogs.symsplitter.SymSplitterDialog; import org.nschmidt.ldparteditor.dialogs.tjunction.TJunctionDialog; import org.nschmidt.ldparteditor.dialogs.translate.TranslateDialog; import org.nschmidt.ldparteditor.dialogs.txt2dat.Txt2DatDialog; import org.nschmidt.ldparteditor.dialogs.unificator.UnificatorDialog; import org.nschmidt.ldparteditor.dialogs.value.ValueDialog; import org.nschmidt.ldparteditor.dialogs.value.ValueDialogInt; import org.nschmidt.ldparteditor.enums.GLPrimitives; import org.nschmidt.ldparteditor.enums.ManipulatorScope; import org.nschmidt.ldparteditor.enums.MergeTo; import org.nschmidt.ldparteditor.enums.MouseButton; import org.nschmidt.ldparteditor.enums.MyLanguage; import org.nschmidt.ldparteditor.enums.ObjectMode; import org.nschmidt.ldparteditor.enums.OpenInWhat; import org.nschmidt.ldparteditor.enums.Perspective; import org.nschmidt.ldparteditor.enums.Threshold; import org.nschmidt.ldparteditor.enums.TransformationMode; import org.nschmidt.ldparteditor.enums.View; import org.nschmidt.ldparteditor.enums.WorkingMode; import org.nschmidt.ldparteditor.helpers.Manipulator; import org.nschmidt.ldparteditor.helpers.ShellHelper; import org.nschmidt.ldparteditor.helpers.Sphere; import org.nschmidt.ldparteditor.helpers.Version; import org.nschmidt.ldparteditor.helpers.WidgetSelectionHelper; import org.nschmidt.ldparteditor.helpers.composite3d.Edger2Settings; import org.nschmidt.ldparteditor.helpers.composite3d.IntersectorSettings; import org.nschmidt.ldparteditor.helpers.composite3d.IsecalcSettings; import org.nschmidt.ldparteditor.helpers.composite3d.PathTruderSettings; import org.nschmidt.ldparteditor.helpers.composite3d.RectifierSettings; import org.nschmidt.ldparteditor.helpers.composite3d.RingsAndConesSettings; import org.nschmidt.ldparteditor.helpers.composite3d.SelectorSettings; import org.nschmidt.ldparteditor.helpers.composite3d.SlicerProSettings; import org.nschmidt.ldparteditor.helpers.composite3d.SymSplitterSettings; import org.nschmidt.ldparteditor.helpers.composite3d.TJunctionSettings; import org.nschmidt.ldparteditor.helpers.composite3d.TreeData; import org.nschmidt.ldparteditor.helpers.composite3d.Txt2DatSettings; import org.nschmidt.ldparteditor.helpers.composite3d.UnificatorSettings; import org.nschmidt.ldparteditor.helpers.composite3d.ViewIdleManager; import org.nschmidt.ldparteditor.helpers.compositetext.ProjectActions; import org.nschmidt.ldparteditor.helpers.compositetext.SubfileCompiler; import org.nschmidt.ldparteditor.helpers.math.MathHelper; import org.nschmidt.ldparteditor.helpers.math.Vector3d; import org.nschmidt.ldparteditor.i18n.I18n; import org.nschmidt.ldparteditor.logger.NLogger; import org.nschmidt.ldparteditor.main.LDPartEditor; import org.nschmidt.ldparteditor.opengl.OpenGLRenderer; import org.nschmidt.ldparteditor.project.Project; import org.nschmidt.ldparteditor.resources.ResourceManager; import org.nschmidt.ldparteditor.shells.editormeta.EditorMetaWindow; import org.nschmidt.ldparteditor.shells.editortext.EditorTextWindow; import org.nschmidt.ldparteditor.shells.searchnreplace.SearchWindow; import org.nschmidt.ldparteditor.text.LDParsingException; import org.nschmidt.ldparteditor.text.References; import org.nschmidt.ldparteditor.text.StringHelper; import org.nschmidt.ldparteditor.text.TextTriangulator; import org.nschmidt.ldparteditor.text.UTF8BufferedReader; import org.nschmidt.ldparteditor.widgets.BigDecimalSpinner; import org.nschmidt.ldparteditor.widgets.TreeItem; import org.nschmidt.ldparteditor.widgets.ValueChangeAdapter; import org.nschmidt.ldparteditor.workbench.Composite3DState; import org.nschmidt.ldparteditor.workbench.Editor3DWindowState; import org.nschmidt.ldparteditor.workbench.WorkbenchManager; /** * The 3D editor window * <p> * Note: This class should be instantiated once, it defines all listeners and * part of the business logic. * * @author nils * */ public class Editor3DWindow extends Editor3DDesign { /** The window state of this window */ private Editor3DWindowState editor3DWindowState; /** The reference to this window */ private static Editor3DWindow window; /** The window state of this window */ private SearchWindow searchWindow; public static final ArrayList<GLCanvas> canvasList = new ArrayList<GLCanvas>(); public static final ArrayList<OpenGLRenderer> renders = new ArrayList<OpenGLRenderer>(); final private static AtomicBoolean alive = new AtomicBoolean(true); private boolean addingSomething = false; private boolean addingVertices = false; private boolean addingLines = false; private boolean addingTriangles = false; private boolean addingQuads = false; private boolean addingCondlines = false; private boolean addingSubfiles = false; private boolean movingAdjacentData = false; private boolean noTransparentSelection = false; private boolean bfcToggle = false; private ObjectMode workingType = ObjectMode.VERTICES; private WorkingMode workingAction = WorkingMode.SELECT; private GColour lastUsedColour = new GColour(16, .5f, .5f, .5f, 1f); private ManipulatorScope transformationMode = ManipulatorScope.LOCAL; private int snapSize = 1; private Txt2DatSettings ts = new Txt2DatSettings(); private Edger2Settings es = new Edger2Settings(); private RectifierSettings rs = new RectifierSettings(); private IsecalcSettings is = new IsecalcSettings(); private SlicerProSettings ss = new SlicerProSettings(); private IntersectorSettings ins = new IntersectorSettings(); private PathTruderSettings ps = new PathTruderSettings(); private SymSplitterSettings sims = new SymSplitterSettings(); private UnificatorSettings us = new UnificatorSettings(); private RingsAndConesSettings ris = new RingsAndConesSettings(); private SelectorSettings sels = new SelectorSettings(); private TJunctionSettings tjs = new TJunctionSettings(); private boolean updatingPngPictureTab; private int pngPictureUpdateCounter = 0; private final EditorMetaWindow metaWindow = new EditorMetaWindow(); private boolean updatingSelectionTab = true; private ArrayList<String> recentItems = new ArrayList<String>(); /** * Create the application window. */ public Editor3DWindow() { super(); final int[] i = new int[1]; final int[] j = new int[1]; final GLCanvas[] first1 = ViewIdleManager.firstCanvas; final OpenGLRenderer[] first2 = ViewIdleManager.firstRender; final int[] intervall = new int[] { 10 }; Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { if (ViewIdleManager.pause[0].get()) { ViewIdleManager.pause[0].set(false); intervall[0] = 500; } else { final int cs = canvasList.size(); if (i[0] < cs && cs > 0) { GLCanvas canvas; if (!canvasList.get(i[0]).equals(first1[0])) { canvas = first1[0]; if (canvas != null && !canvas.isDisposed()) { first2[0].drawScene(); first1[0] = null; first2[0] = null; } } canvas = canvasList.get(i[0]); if (!canvas.isDisposed()) { boolean stdMode = ViewIdleManager.renderLDrawStandard[0].get(); // FIXME Needs workaround since SWT upgrade to 4.5! if (renders.get(i[0]).getC3D().getRenderMode() != 5 || cs == 1 || stdMode) { renders.get(i[0]).drawScene(); if (stdMode) { j[0]++; } } } else { canvasList.remove(i[0]); renders.remove(i[0]); } i[0]++; } else { i[0] = 0; if (j[0] > cs) { j[0] = 0; ViewIdleManager.renderLDrawStandard[0].set(false); } } } Display.getCurrent().timerExec(intervall[0], this); intervall[0] = 10; } }); } /** * Run a fresh instance of this window */ public void run() { window = this; // Load recent files recentItems = WorkbenchManager.getUserSettingState().getRecentItems(); if (recentItems == null) recentItems = new ArrayList<String>(); // Load the window state data editor3DWindowState = WorkbenchManager.getEditor3DWindowState(); WorkbenchManager.setEditor3DWindow(this); // Closing this window causes the whole application to quit this.setBlockOnOpen(true); // Creating the window to get the shell this.create(); final Shell sh = this.getShell(); sh.setText(Version.getApplicationName()); sh.setImage(ResourceManager.getImage("imgDuke2.png")); //$NON-NLS-1$ sh.setMinimumSize(640, 480); sh.setBounds(this.editor3DWindowState.getWindowState().getSizeAndPosition()); if (this.editor3DWindowState.getWindowState().isCentered()) { ShellHelper.centerShellOnPrimaryScreen(sh); } // Maximize has to be called asynchronously sh.getDisplay().asyncExec(new Runnable() { @Override public void run() { sh.setMaximized(editor3DWindowState.getWindowState().isMaximized()); } }); // Set the snapping Manipulator.setSnap( WorkbenchManager.getUserSettingState().getMedium_move_snap(), WorkbenchManager.getUserSettingState().getMedium_rotate_snap(), WorkbenchManager.getUserSettingState().getMedium_scale_snap() ); // MARK All final listeners will be configured here.. NLogger.writeVersion(); btn_Sync[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { resetSearch(); int[][] stats = new int[15][3]; stats[0] = LibraryManager.syncProjectElements(treeItem_Project[0]); stats[5] = LibraryManager.syncUnofficialParts(treeItem_UnofficialParts[0]); stats[6] = LibraryManager.syncUnofficialSubparts(treeItem_UnofficialSubparts[0]); stats[7] = LibraryManager.syncUnofficialPrimitives(treeItem_UnofficialPrimitives[0]); stats[8] = LibraryManager.syncUnofficialHiResPrimitives(treeItem_UnofficialPrimitives48[0]); stats[9] = LibraryManager.syncUnofficialLowResPrimitives(treeItem_UnofficialPrimitives8[0]); stats[10] = LibraryManager.syncOfficialParts(treeItem_OfficialParts[0]); stats[11] = LibraryManager.syncOfficialSubparts(treeItem_OfficialSubparts[0]); stats[12] = LibraryManager.syncOfficialPrimitives(treeItem_OfficialPrimitives[0]); stats[13] = LibraryManager.syncOfficialHiResPrimitives(treeItem_OfficialPrimitives48[0]); stats[14] = LibraryManager.syncOfficialLowResPrimitives(treeItem_OfficialPrimitives8[0]); int additions = 0; int deletions = 0; int conflicts = 0; for (int[] is : stats) { additions += is[0]; deletions += is[1]; conflicts += is[2]; } txt_Search[0].setText(" "); //$NON-NLS-1$ txt_Search[0].setText(""); //$NON-NLS-1$ Set<DatFile> dfs = new HashSet<DatFile>(); for (OpenGLRenderer renderer : renders) { dfs.add(renderer.getC3D().getLockableDatFileReference()); } for (EditorTextWindow w : Project.getOpenTextWindows()) { for (CTabItem t : w.getTabFolder().getItems()) { DatFile txtDat = ((CompositeTab) t).getState().getFileNameObj(); if (txtDat != null) { dfs.add(txtDat); } } } for (DatFile df : dfs) { SubfileCompiler.compile(df, false, false); } for (EditorTextWindow w : Project.getOpenTextWindows()) { for (CTabItem t : w.getTabFolder().getItems()) { DatFile txtDat = ((CompositeTab) t).getState().getFileNameObj(); if (txtDat != null) { ((CompositeTab) t).parseForErrorAndHints(); ((CompositeTab) t).getTextComposite().redraw(); ((CompositeTab) t).getState().getTab().setText(((CompositeTab) t).getState().getFilenameWithStar()); } } } updateTree_unsavedEntries(); try { new ProgressMonitorDialog(Editor3DWindow.getWindow().getShell()).run(true, false, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask(I18n.E3D_LoadingPrimitives, IProgressMonitor.UNKNOWN); Thread.sleep(1500); } }); } catch (InvocationTargetException consumed) { } catch (InterruptedException consumed) { } cmp_Primitives[0].load(false); MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK); messageBox.setText(I18n.DIALOG_SyncTitle); Object[] messageArguments = {additions, deletions, conflicts}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.DIALOG_Sync); messageBox.setMessage(formatter.format(messageArguments)); messageBox.open(); } }); btn_LastOpen[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Menu lastOpenedMenu = new Menu(treeParts[0].getTree()); btn_LastOpen[0].setMenu(lastOpenedMenu); final int size = recentItems.size() - 1; for (int i = size; i > -1; i--) { final String path = recentItems.get(i); File f = new File(path); if (f.exists() && f.canRead()) { if (f.isFile()) { MenuItem mntmItem = new MenuItem(lastOpenedMenu, I18n.I18N_NON_BIDIRECT()); mntmItem.setEnabled(true); mntmItem.setText(path); mntmItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { File f = new File(path); if (f.exists() && f.isFile() && f.canRead()) openDatFile(getShell(), OpenInWhat.EDITOR_TEXT_AND_3D, path); } }); } else if (f.isDirectory()) { MenuItem mntmItem = new MenuItem(lastOpenedMenu, I18n.I18N_NON_BIDIRECT()); mntmItem.setEnabled(true); Object[] messageArguments = {path}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.E3D_LastProject); mntmItem.setText(formatter.format(messageArguments)); mntmItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { File f = new File(path); if (f.exists() && f.isDirectory() && f.canRead() && ProjectActions.openProject(path)) { Project.create(false); treeItem_Project[0].setData(Project.getProjectPath()); resetSearch(); LibraryManager.readProjectPartsParent(treeItem_ProjectParts[0]); LibraryManager.readProjectParts(treeItem_ProjectParts[0]); LibraryManager.readProjectSubparts(treeItem_ProjectSubparts[0]); LibraryManager.readProjectPrimitives(treeItem_ProjectPrimitives[0]); LibraryManager.readProjectHiResPrimitives(treeItem_ProjectPrimitives48[0]); LibraryManager.readProjectLowResPrimitives(treeItem_ProjectPrimitives8[0]); treeItem_OfficialParts[0].setData(null); txt_Search[0].setText(" "); //$NON-NLS-1$ txt_Search[0].setText(""); //$NON-NLS-1$ updateTree_unsavedEntries(); } } }); } } } java.awt.Point b = java.awt.MouseInfo.getPointerInfo().getLocation(); final int x = (int) b.getX(); final int y = (int) b.getY(); lastOpenedMenu.setLocation(x, y); lastOpenedMenu.setVisible(true); } }); btn_New[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ProjectActions.createNewProject(Editor3DWindow.getWindow(), false); addRecentFile(Project.getProjectPath()); } }); btn_Open[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (ProjectActions.openProject(null)) { addRecentFile(Project.getProjectPath()); Project.create(false); treeItem_Project[0].setData(Project.getProjectPath()); resetSearch(); LibraryManager.readProjectPartsParent(treeItem_ProjectParts[0]); LibraryManager.readProjectParts(treeItem_ProjectParts[0]); LibraryManager.readProjectSubparts(treeItem_ProjectSubparts[0]); LibraryManager.readProjectPrimitives(treeItem_ProjectPrimitives[0]); LibraryManager.readProjectHiResPrimitives(treeItem_ProjectPrimitives48[0]); LibraryManager.readProjectLowResPrimitives(treeItem_ProjectPrimitives8[0]); treeItem_OfficialParts[0].setData(null); txt_Search[0].setText(" "); //$NON-NLS-1$ txt_Search[0].setText(""); //$NON-NLS-1$ updateTree_unsavedEntries(); } } }); btn_Save[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (treeParts[0].getSelectionCount() == 1) { if (treeParts[0].getSelection()[0].getData() instanceof DatFile) { DatFile df = (DatFile) treeParts[0].getSelection()[0].getData(); if (!df.isReadOnly() && Project.getUnsavedFiles().contains(df)) { if (df.save()) { Editor3DWindow.getWindow().addRecentFile(df); Editor3DWindow.getWindow().updateTree_unsavedEntries(); } else { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK); messageBoxError.setText(I18n.DIALOG_Error); messageBoxError.setMessage(I18n.DIALOG_CantSaveFile); messageBoxError.open(); Editor3DWindow.getWindow().updateTree_unsavedEntries(); } } } else if (treeParts[0].getSelection()[0].getData() instanceof ArrayList<?>) { NLogger.debug(getClass(), "Saving all files from this group"); //$NON-NLS-1$ { @SuppressWarnings("unchecked") ArrayList<DatFile> dfs = (ArrayList<DatFile>) treeParts[0].getSelection()[0].getData(); for (DatFile df : dfs) { if (!df.isReadOnly() && Project.getUnsavedFiles().contains(df)) { if (df.save()) { Editor3DWindow.getWindow().addRecentFile(df); Project.removeUnsavedFile(df); Editor3DWindow.getWindow().updateTree_unsavedEntries(); } else { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK); messageBoxError.setText(I18n.DIALOG_Error); messageBoxError.setMessage(I18n.DIALOG_CantSaveFile); messageBoxError.open(); Editor3DWindow.getWindow().updateTree_unsavedEntries(); } } } } } else if (treeParts[0].getSelection()[0].getData() instanceof String) { if (treeParts[0].getSelection()[0].equals(treeItem_Project[0])) { NLogger.debug(getClass(), "Save the project..."); //$NON-NLS-1$ if (Project.isDefaultProject()) { ProjectActions.createNewProject(Editor3DWindow.getWindow(), true); } iterateOverItems(treeItem_ProjectParts[0]); iterateOverItems(treeItem_ProjectSubparts[0]); iterateOverItems(treeItem_ProjectPrimitives[0]); iterateOverItems(treeItem_ProjectPrimitives48[0]); iterateOverItems(treeItem_ProjectPrimitives8[0]); } else if (treeParts[0].getSelection()[0].equals(treeItem_Unofficial[0])) { iterateOverItems(treeItem_UnofficialParts[0]); iterateOverItems(treeItem_UnofficialSubparts[0]); iterateOverItems(treeItem_UnofficialPrimitives[0]); iterateOverItems(treeItem_UnofficialPrimitives48[0]); iterateOverItems(treeItem_UnofficialPrimitives8[0]); } NLogger.debug(getClass(), "Saving all files from this group to {0}", treeParts[0].getSelection()[0].getData()); //$NON-NLS-1$ } } else { NLogger.debug(getClass(), "Save the project..."); //$NON-NLS-1$ if (Project.isDefaultProject()) { ProjectActions.createNewProject(Editor3DWindow.getWindow(), true); } } } private void iterateOverItems(TreeItem ti) { { @SuppressWarnings("unchecked") ArrayList<DatFile> dfs = (ArrayList<DatFile>) ti.getData(); for (DatFile df : dfs) { if (!df.isReadOnly() && Project.getUnsavedFiles().contains(df)) { if (df.save()) { Editor3DWindow.getWindow().addRecentFile(df); Project.removeUnsavedFile(df); Editor3DWindow.getWindow().updateTree_unsavedEntries(); } else { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK); messageBoxError.setText(I18n.DIALOG_Error); messageBoxError.setMessage(I18n.DIALOG_CantSaveFile); messageBoxError.open(); Editor3DWindow.getWindow().updateTree_unsavedEntries(); } } } } } }); btn_SaveAll[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { HashSet<DatFile> dfs = new HashSet<DatFile>(Project.getUnsavedFiles()); for (DatFile df : dfs) { if (!df.isReadOnly()) { if (df.save()) { Editor3DWindow.getWindow().addRecentFile(df); Project.removeUnsavedFile(df); } else { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK); messageBoxError.setText(I18n.DIALOG_Error); messageBoxError.setMessage(I18n.DIALOG_CantSaveFile); messageBoxError.open(); } } } if (Project.isDefaultProject()) { ProjectActions.createNewProject(getWindow(), true); } Editor3DWindow.getWindow().updateTree_unsavedEntries(); } }); btn_NewDat[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { DatFile dat = createNewDatFile(getShell(), OpenInWhat.EDITOR_TEXT_AND_3D); if (dat != null) { addRecentFile(dat); } } }); btn_OpenDat[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { DatFile dat = openDatFile(getShell(), OpenInWhat.EDITOR_TEXT_AND_3D, null); if (dat != null) { addRecentFile(dat); } } }); btn_Undo[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().undo(null); } } }); btn_Redo[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().redo(null); } } }); if (NLogger.DEBUG) { btn_AddHistory[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().addHistory(); } } }); } btn_Select[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { clickBtnTest(btn_Select[0]); workingAction = WorkingMode.SELECT; } }); btn_Move[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { clickBtnTest(btn_Move[0]); workingAction = WorkingMode.MOVE; } }); btn_Rotate[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { clickBtnTest(btn_Rotate[0]); workingAction = WorkingMode.ROTATE; } }); btn_Scale[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { clickBtnTest(btn_Scale[0]); workingAction = WorkingMode.SCALE; } }); btn_Combined[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { clickBtnTest(btn_Combined[0]); workingAction = WorkingMode.COMBINED; } }); btn_Local[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { clickBtnTest(btn_Local[0]); transformationMode = ManipulatorScope.LOCAL; } }); btn_Global[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { clickBtnTest(btn_Global[0]); transformationMode = ManipulatorScope.GLOBAL; } }); btn_Vertices[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { clickBtnTest(btn_Vertices[0]); setWorkingType(ObjectMode.VERTICES); } }); btn_TrisNQuads[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { clickBtnTest(btn_TrisNQuads[0]); setWorkingType(ObjectMode.FACES); } }); btn_Lines[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { clickBtnTest(btn_Lines[0]); setWorkingType(ObjectMode.LINES); } }); btn_Subfiles[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { clickBtnTest(btn_Subfiles[0]); setWorkingType(ObjectMode.SUBFILES); } } }); btn_AddComment[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (!metaWindow.isOpened()) { metaWindow.run(); } else { metaWindow.open(); } } }); btn_AddVertex[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { resetAddState(); clickSingleBtn(btn_AddVertex[0]); setAddingVertices(btn_AddVertex[0].getSelection()); setAddingSomething(isAddingVertices()); } }); btn_AddPrimitive[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { resetAddState(); setAddingSubfiles(btn_AddPrimitive[0].getSelection()); setAddingSomething(isAddingSubfiles()); clickSingleBtn(btn_AddPrimitive[0]); } }); btn_AddLine[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { resetAddState(); setAddingLines(btn_AddLine[0].getSelection()); setAddingSomething(isAddingLines()); clickSingleBtn(btn_AddLine[0]); } }); btn_AddTriangle[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { resetAddState(); setAddingTriangles(btn_AddTriangle[0].getSelection()); setAddingSomething(isAddingTriangles()); clickSingleBtn(btn_AddTriangle[0]); } }); btn_AddQuad[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { resetAddState(); setAddingQuads(btn_AddQuad[0].getSelection()); setAddingSomething(isAddingQuads()); clickSingleBtn(btn_AddQuad[0]); } }); btn_AddCondline[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { resetAddState(); setAddingCondlines(btn_AddCondline[0].getSelection()); setAddingSomething(isAddingCondlines()); clickSingleBtn(btn_AddCondline[0]); } }); btn_MoveAdjacentData[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { clickSingleBtn(btn_MoveAdjacentData[0]); setMovingAdjacentData(btn_MoveAdjacentData[0].getSelection()); } }); btn_CompileSubfile[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Project.getFileToEdit().getVertexManager().addSnapshot(); SubfileCompiler.compile(Project.getFileToEdit(), false, false); } } }); btn_lineSize1[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { setLineSize(GLPrimitives.SPHERE1, GLPrimitives.SPHERE_INV1, 25f, .025f, .375f, btn_lineSize1[0]); } }); btn_lineSize2[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { setLineSize(GLPrimitives.SPHERE2, GLPrimitives.SPHERE_INV2, 50f, .050f, .75f, btn_lineSize2[0]); } }); btn_lineSize3[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { setLineSize(GLPrimitives.SPHERE3, GLPrimitives.SPHERE_INV3, 100f, .100f, 1.5f, btn_lineSize3[0]); } }); btn_lineSize4[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { setLineSize(GLPrimitives.SPHERE4, GLPrimitives.SPHERE_INV4, 200f, .200f, 3f, btn_lineSize4[0]); } }); btn_BFCswap[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager().windingChangeSelection(); } } }); btn_RoundSelection[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { if ((e.stateMask & SWT.CTRL) == SWT.CTRL) { if (new RoundDialog(getShell()).open() == IDialogConstants.CANCEL_ID) return; } Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager() .roundSelection(WorkbenchManager.getUserSettingState().getCoordsPrecision(), WorkbenchManager.getUserSettingState().getTransMatrixPrecision(), isMovingAdjacentData(), true); } } }); btn_Pipette[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { VertexManager vm = Project.getFileToEdit().getVertexManager(); vm.addSnapshot(); final GColour gColour2 = vm.getRandomSelectedColour(lastUsedColour); setLastUsedColour(gColour2); btn_LastUsedColour[0].removeListener(SWT.Paint, btn_LastUsedColour[0].getListeners(SWT.Paint)[0]); btn_LastUsedColour[0].removeListener(SWT.Selection, btn_LastUsedColour[0].getListeners(SWT.Selection)[0]); final Color col = SWTResourceManager.getColor((int) (gColour2.getR() * 255f), (int) (gColour2.getG() * 255f), (int) (gColour2.getB() * 255f)); final Point size = btn_LastUsedColour[0].computeSize(SWT.DEFAULT, SWT.DEFAULT); final int x = size.x / 4; final int y = size.y / 4; final int w = size.x / 2; final int h = size.y / 2; int num = gColour2.getColourNumber(); btn_LastUsedColour[0].addPaintListener(new PaintListener() { @Override public void paintControl(PaintEvent e) { e.gc.setBackground(col); e.gc.fillRectangle(x, y, w, h); if (gColour2.getA() == 1f) { e.gc.drawImage(ResourceManager.getImage("icon16_transparent.png"), 0, 0, 16, 16, x, y, w, h); //$NON-NLS-1$ } else { e.gc.drawImage(ResourceManager.getImage("icon16_halftrans.png"), 0, 0, 16, 16, x, y, w, h); //$NON-NLS-1$ } } }); btn_LastUsedColour[0].addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { int num = gColour2.getColourNumber(); if (!View.hasLDConfigColour(num)) { num = -1; } Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager().colourChangeSelection(num, gColour2.getR(), gColour2.getG(), gColour2.getB(), gColour2.getA()); } } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); if (num != -1) { Object[] messageArguments = {num, View.getLDConfigColourName(num)}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.EDITORTEXT_Colour1); btn_LastUsedColour[0].setToolTipText(formatter.format(messageArguments)); } else { StringBuilder colourBuilder = new StringBuilder(); colourBuilder.append("0x2"); //$NON-NLS-1$ colourBuilder.append(MathHelper.toHex((int) (255f * gColour2.getR())).toUpperCase()); colourBuilder.append(MathHelper.toHex((int) (255f * gColour2.getG())).toUpperCase()); colourBuilder.append(MathHelper.toHex((int) (255f * gColour2.getB())).toUpperCase()); Object[] messageArguments = {colourBuilder.toString()}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.EDITORTEXT_Colour2); btn_LastUsedColour[0].setToolTipText(formatter.format(messageArguments)); } btn_LastUsedColour[0].redraw(); } } }); btn_Palette[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { final GColour[] gColour2 = new GColour[1]; new ColourDialog(getShell(), gColour2).open(); if (gColour2[0] != null) { setLastUsedColour(gColour2[0]); int num = gColour2[0].getColourNumber(); if (!View.hasLDConfigColour(num)) { num = -1; } Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager().colourChangeSelection(num, gColour2[0].getR(), gColour2[0].getG(), gColour2[0].getB(), gColour2[0].getA()); btn_LastUsedColour[0].removeListener(SWT.Paint, btn_LastUsedColour[0].getListeners(SWT.Paint)[0]); btn_LastUsedColour[0].removeListener(SWT.Selection, btn_LastUsedColour[0].getListeners(SWT.Selection)[0]); final Color col = SWTResourceManager.getColor((int) (gColour2[0].getR() * 255f), (int) (gColour2[0].getG() * 255f), (int) (gColour2[0].getB() * 255f)); final Point size = btn_LastUsedColour[0].computeSize(SWT.DEFAULT, SWT.DEFAULT); final int x = size.x / 4; final int y = size.y / 4; final int w = size.x / 2; final int h = size.y / 2; btn_LastUsedColour[0].addPaintListener(new PaintListener() { @Override public void paintControl(PaintEvent e) { e.gc.setBackground(col); e.gc.fillRectangle(x, y, w, h); if (gColour2[0].getA() == 1f) { e.gc.drawImage(ResourceManager.getImage("icon16_transparent.png"), 0, 0, 16, 16, x, y, w, h); //$NON-NLS-1$ } else { e.gc.drawImage(ResourceManager.getImage("icon16_halftrans.png"), 0, 0, 16, 16, x, y, w, h); //$NON-NLS-1$ } } }); btn_LastUsedColour[0].addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { int num = gColour2[0].getColourNumber(); if (!View.hasLDConfigColour(num)) { num = -1; } Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager().colourChangeSelection(num, gColour2[0].getR(), gColour2[0].getG(), gColour2[0].getB(), gColour2[0].getA()); } } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); if (num != -1) { Object[] messageArguments = {num, View.getLDConfigColourName(num)}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.EDITORTEXT_Colour1); btn_LastUsedColour[0].setToolTipText(formatter.format(messageArguments)); } else { StringBuilder colourBuilder = new StringBuilder(); colourBuilder.append("0x2"); //$NON-NLS-1$ colourBuilder.append(MathHelper.toHex((int) (255f * gColour2[0].getR())).toUpperCase()); colourBuilder.append(MathHelper.toHex((int) (255f * gColour2[0].getG())).toUpperCase()); colourBuilder.append(MathHelper.toHex((int) (255f * gColour2[0].getB())).toUpperCase()); Object[] messageArguments = {colourBuilder.toString()}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.EDITORTEXT_Colour2); btn_LastUsedColour[0].setToolTipText(formatter.format(messageArguments)); } btn_LastUsedColour[0].redraw(); } } } }); btn_Coarse[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { BigDecimal m = WorkbenchManager.getUserSettingState().getCoarse_move_snap(); BigDecimal r = WorkbenchManager.getUserSettingState().getCoarse_rotate_snap(); BigDecimal s = WorkbenchManager.getUserSettingState().getCoarse_scale_snap(); snapSize = 2; spn_Move[0].setValue(m); spn_Rotate[0].setValue(r); spn_Scale[0].setValue(s); Manipulator.setSnap(m, r, s); } }); btn_Medium[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { BigDecimal m = WorkbenchManager.getUserSettingState().getMedium_move_snap(); BigDecimal r = WorkbenchManager.getUserSettingState().getMedium_rotate_snap(); BigDecimal s = WorkbenchManager.getUserSettingState().getMedium_scale_snap(); snapSize = 1; spn_Move[0].setValue(m); spn_Rotate[0].setValue(r); spn_Scale[0].setValue(s); Manipulator.setSnap(m, r, s); } }); btn_Fine[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { BigDecimal m = WorkbenchManager.getUserSettingState().getFine_move_snap(); BigDecimal r = WorkbenchManager.getUserSettingState().getFine_rotate_snap(); BigDecimal s = WorkbenchManager.getUserSettingState().getFine_scale_snap(); snapSize = 0; spn_Move[0].setValue(m); spn_Rotate[0].setValue(r); spn_Scale[0].setValue(s); Manipulator.setSnap(m, r, s); } }); btn_Coarse[0].addListener(SWT.MouseDown, new Listener() { @Override public void handleEvent(Event event) { if (event.button == MouseButton.RIGHT) { try { if (btn_Coarse[0].getMenu() != null) { btn_Coarse[0].getMenu().dispose(); } } catch (Exception ex) {} Menu gridMenu = new Menu(btn_Coarse[0]); btn_Coarse[0].setMenu(gridMenu); mnu_coarseMenu[0] = gridMenu; MenuItem mntmGridCoarseDefault = new MenuItem(gridMenu, I18n.I18N_NON_BIDIRECT()); mntm_gridCoarseDefault[0] = mntmGridCoarseDefault; mntmGridCoarseDefault.setEnabled(true); mntmGridCoarseDefault.setText(I18n.E3D_GridCoarseDefault); mntm_gridCoarseDefault[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { WorkbenchManager.getUserSettingState().setCoarse_move_snap(new BigDecimal("1")); //$NON-NLS-1$ WorkbenchManager.getUserSettingState().setCoarse_rotate_snap(new BigDecimal("90")); //$NON-NLS-1$ WorkbenchManager.getUserSettingState().setCoarse_scale_snap(new BigDecimal("2")); //$NON-NLS-1$ BigDecimal m = WorkbenchManager.getUserSettingState().getCoarse_move_snap(); BigDecimal r = WorkbenchManager.getUserSettingState().getCoarse_rotate_snap(); BigDecimal s = WorkbenchManager.getUserSettingState().getCoarse_scale_snap(); snapSize = 2; spn_Move[0].setValue(m); spn_Rotate[0].setValue(r); spn_Scale[0].setValue(s); Manipulator.setSnap(m, r, s); } }); java.awt.Point b = java.awt.MouseInfo.getPointerInfo().getLocation(); final int x = (int) b.getX(); final int y = (int) b.getY(); Menu menu = mnu_coarseMenu[0]; menu.setLocation(x, y); menu.setVisible(true); } } }); btn_Medium[0].addListener(SWT.MouseDown, new Listener() { @Override public void handleEvent(Event event) { if (event.button == MouseButton.RIGHT) { try { if (btn_Medium[0].getMenu() != null) { btn_Medium[0].getMenu().dispose(); } } catch (Exception ex) {} Menu gridMenu = new Menu(btn_Medium[0]); btn_Medium[0].setMenu(gridMenu); mnu_mediumMenu[0] = gridMenu; MenuItem mntmGridMediumDefault = new MenuItem(gridMenu, I18n.I18N_NON_BIDIRECT()); mntm_gridMediumDefault[0] = mntmGridMediumDefault; mntmGridMediumDefault.setEnabled(true); mntmGridMediumDefault.setText(I18n.E3D_GridMediumDefault); mntm_gridMediumDefault[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { WorkbenchManager.getUserSettingState().setMedium_move_snap(new BigDecimal("0.01")); //$NON-NLS-1$ WorkbenchManager.getUserSettingState().setMedium_rotate_snap(new BigDecimal("11.25")); //$NON-NLS-1$ WorkbenchManager.getUserSettingState().setMedium_scale_snap(new BigDecimal("1.1")); //$NON-NLS-1$ BigDecimal m = WorkbenchManager.getUserSettingState().getMedium_move_snap(); BigDecimal r = WorkbenchManager.getUserSettingState().getMedium_rotate_snap(); BigDecimal s = WorkbenchManager.getUserSettingState().getMedium_scale_snap(); snapSize = 1; spn_Move[0].setValue(m); spn_Rotate[0].setValue(r); spn_Scale[0].setValue(s); Manipulator.setSnap(m, r, s); } }); java.awt.Point b = java.awt.MouseInfo.getPointerInfo().getLocation(); final int x = (int) b.getX(); final int y = (int) b.getY(); Menu menu = mnu_mediumMenu[0]; menu.setLocation(x, y); menu.setVisible(true); } } }); btn_Fine[0].addListener(SWT.MouseDown, new Listener() { @Override public void handleEvent(Event event) { if (event.button == MouseButton.RIGHT) { try { if (btn_Fine[0].getMenu() != null) { btn_Fine[0].getMenu().dispose(); } } catch (Exception ex) {} Menu gridMenu = new Menu(btn_Fine[0]); btn_Fine[0].setMenu(gridMenu); mnu_fineMenu[0] = gridMenu; MenuItem mntmGridFineDefault = new MenuItem(gridMenu, I18n.I18N_NON_BIDIRECT()); mntm_gridFineDefault[0] = mntmGridFineDefault; mntmGridFineDefault.setEnabled(true); mntmGridFineDefault.setText(I18n.E3D_GridFineDefault); mntm_gridFineDefault[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { WorkbenchManager.getUserSettingState().setFine_move_snap(new BigDecimal("0.0001")); //$NON-NLS-1$ WorkbenchManager.getUserSettingState().setFine_rotate_snap(BigDecimal.ONE); WorkbenchManager.getUserSettingState().setFine_scale_snap(new BigDecimal("1.001")); //$NON-NLS-1$ BigDecimal m = WorkbenchManager.getUserSettingState().getFine_move_snap(); BigDecimal r = WorkbenchManager.getUserSettingState().getFine_rotate_snap(); BigDecimal s = WorkbenchManager.getUserSettingState().getFine_scale_snap(); snapSize = 0; spn_Move[0].setValue(m); spn_Rotate[0].setValue(r); spn_Scale[0].setValue(s); Manipulator.setSnap(m, r, s); } }); java.awt.Point b = java.awt.MouseInfo.getPointerInfo().getLocation(); final int x = (int) b.getX(); final int y = (int) b.getY(); Menu menu = mnu_fineMenu[0]; menu.setLocation(x, y); menu.setVisible(true); } } }); btn_SplitQuad[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null && !Project.getFileToEdit().isReadOnly()) { Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager().splitQuads(true); } } }); btn_CondlineToLine[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null && !Project.getFileToEdit().isReadOnly()) { Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager().condlineToLine(); } } }); btn_LineToCondline[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null && !Project.getFileToEdit().isReadOnly()) { Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager().lineToCondline(); } } }); btn_MoveOnLine[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null && !Project.getFileToEdit().isReadOnly()) { Project.getFileToEdit().getVertexManager().addSnapshot(); Set<Vertex> verts = Project.getFileToEdit().getVertexManager().getSelectedVertices(); CoordinatesDialog.setStart(null); CoordinatesDialog.setEnd(null); if (verts.size() == 2) { Iterator<Vertex> it = verts.iterator(); CoordinatesDialog.setStart(new Vector3d(it.next())); CoordinatesDialog.setEnd(new Vector3d(it.next())); } } } }); spn_Move[0].addValueChangeListener(new ValueChangeAdapter() { @Override public void valueChanged(BigDecimalSpinner spn) { BigDecimal m, r, s; m = spn.getValue(); switch (snapSize) { case 0: WorkbenchManager.getUserSettingState().setFine_move_snap(m); r = WorkbenchManager.getUserSettingState().getFine_rotate_snap(); s = WorkbenchManager.getUserSettingState().getFine_scale_snap(); break; case 2: WorkbenchManager.getUserSettingState().setCoarse_move_snap(m); r = WorkbenchManager.getUserSettingState().getCoarse_rotate_snap(); s = WorkbenchManager.getUserSettingState().getCoarse_scale_snap(); break; default: WorkbenchManager.getUserSettingState().setMedium_move_snap(m); r = WorkbenchManager.getUserSettingState().getMedium_rotate_snap(); s = WorkbenchManager.getUserSettingState().getMedium_scale_snap(); break; } Manipulator.setSnap(m, r, s); } }); spn_Rotate[0].addValueChangeListener(new ValueChangeAdapter() { @Override public void valueChanged(BigDecimalSpinner spn) { BigDecimal m, r, s; r = spn.getValue(); switch (snapSize) { case 0: m = WorkbenchManager.getUserSettingState().getFine_move_snap(); WorkbenchManager.getUserSettingState().setFine_rotate_snap(r); s = WorkbenchManager.getUserSettingState().getFine_scale_snap(); break; case 2: m = WorkbenchManager.getUserSettingState().getCoarse_move_snap(); WorkbenchManager.getUserSettingState().setCoarse_rotate_snap(r); s = WorkbenchManager.getUserSettingState().getCoarse_scale_snap(); break; default: m = WorkbenchManager.getUserSettingState().getMedium_move_snap(); WorkbenchManager.getUserSettingState().setMedium_rotate_snap(r); s = WorkbenchManager.getUserSettingState().getMedium_scale_snap(); break; } Manipulator.setSnap(m, r, s); } }); spn_Scale[0].addValueChangeListener(new ValueChangeAdapter() { @Override public void valueChanged(BigDecimalSpinner spn) { BigDecimal m, r, s; s = spn.getValue(); switch (snapSize) { case 0: m = WorkbenchManager.getUserSettingState().getFine_move_snap(); r = WorkbenchManager.getUserSettingState().getFine_rotate_snap(); WorkbenchManager.getUserSettingState().setFine_scale_snap(s); break; case 2: m = WorkbenchManager.getUserSettingState().getCoarse_move_snap(); r = WorkbenchManager.getUserSettingState().getCoarse_rotate_snap(); WorkbenchManager.getUserSettingState().setCoarse_scale_snap(s); break; default: m = WorkbenchManager.getUserSettingState().getMedium_move_snap(); r = WorkbenchManager.getUserSettingState().getMedium_rotate_snap(); WorkbenchManager.getUserSettingState().setMedium_scale_snap(s); break; } Manipulator.setSnap(m, r, s); } }); btn_PreviousSelection[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { updatingSelectionTab = true; NLogger.debug(getClass(), "Previous Selection..."); //$NON-NLS-1$ final DatFile df = Project.getFileToEdit(); if (df != null && !df.isReadOnly()) { final VertexManager vm = df.getVertexManager(); vm.addSnapshot(); final int count = vm.getSelectedData().size(); if (count > 0) { boolean breakIt = false; boolean firstRun = true; while (true) { int index = vm.getSelectedItemIndex(); index--; if (index < 0) { index = count - 1; if (!firstRun) breakIt = true; } if (index > count - 1) index = count - 1; firstRun = false; vm.setSelectedItemIndex(index); final GData gdata = (GData) vm.getSelectedData().toArray()[index]; if (vm.isNotInSubfileAndLinetype1to5(gdata)) { vm.setSelectedLine(gdata); disableSelectionTab(); updatingSelectionTab = true; switch (gdata.type()) { case 1: case 5: case 4: spn_SelectionX4[0].setEnabled(true); spn_SelectionY4[0].setEnabled(true); spn_SelectionZ4[0].setEnabled(true); case 3: spn_SelectionX3[0].setEnabled(true); spn_SelectionY3[0].setEnabled(true); spn_SelectionZ3[0].setEnabled(true); case 2: spn_SelectionX1[0].setEnabled(true); spn_SelectionY1[0].setEnabled(true); spn_SelectionZ1[0].setEnabled(true); spn_SelectionX2[0].setEnabled(true); spn_SelectionY2[0].setEnabled(true); spn_SelectionZ2[0].setEnabled(true); txt_Line[0].setText(gdata.toString()); breakIt = true; btn_MoveAdjacentData2[0].setEnabled(true); switch (gdata.type()) { case 5: BigDecimal[] g5 = GraphicalDataTools.getPreciseCoordinates(gdata); spn_SelectionX1[0].setValue(g5[0]); spn_SelectionY1[0].setValue(g5[1]); spn_SelectionZ1[0].setValue(g5[2]); spn_SelectionX2[0].setValue(g5[3]); spn_SelectionY2[0].setValue(g5[4]); spn_SelectionZ2[0].setValue(g5[5]); spn_SelectionX3[0].setValue(g5[6]); spn_SelectionY3[0].setValue(g5[7]); spn_SelectionZ3[0].setValue(g5[8]); spn_SelectionX4[0].setValue(g5[9]); spn_SelectionY4[0].setValue(g5[10]); spn_SelectionZ4[0].setValue(g5[11]); break; case 4: BigDecimal[] g4 = GraphicalDataTools.getPreciseCoordinates(gdata); spn_SelectionX1[0].setValue(g4[0]); spn_SelectionY1[0].setValue(g4[1]); spn_SelectionZ1[0].setValue(g4[2]); spn_SelectionX2[0].setValue(g4[3]); spn_SelectionY2[0].setValue(g4[4]); spn_SelectionZ2[0].setValue(g4[5]); spn_SelectionX3[0].setValue(g4[6]); spn_SelectionY3[0].setValue(g4[7]); spn_SelectionZ3[0].setValue(g4[8]); spn_SelectionX4[0].setValue(g4[9]); spn_SelectionY4[0].setValue(g4[10]); spn_SelectionZ4[0].setValue(g4[11]); break; case 3: BigDecimal[] g3 = GraphicalDataTools.getPreciseCoordinates(gdata); spn_SelectionX1[0].setValue(g3[0]); spn_SelectionY1[0].setValue(g3[1]); spn_SelectionZ1[0].setValue(g3[2]); spn_SelectionX2[0].setValue(g3[3]); spn_SelectionY2[0].setValue(g3[4]); spn_SelectionZ2[0].setValue(g3[5]); spn_SelectionX3[0].setValue(g3[6]); spn_SelectionY3[0].setValue(g3[7]); spn_SelectionZ3[0].setValue(g3[8]); break; case 2: BigDecimal[] g2 = GraphicalDataTools.getPreciseCoordinates(gdata); spn_SelectionX1[0].setValue(g2[0]); spn_SelectionY1[0].setValue(g2[1]); spn_SelectionZ1[0].setValue(g2[2]); spn_SelectionX2[0].setValue(g2[3]); spn_SelectionY2[0].setValue(g2[4]); spn_SelectionZ2[0].setValue(g2[5]); break; case 1: vm.getSelectedVertices().clear(); btn_MoveAdjacentData2[0].setEnabled(false); GData1 g1 = (GData1) gdata; spn_SelectionX1[0].setValue(g1.getAccurateProductMatrix().M30); spn_SelectionY1[0].setValue(g1.getAccurateProductMatrix().M31); spn_SelectionZ1[0].setValue(g1.getAccurateProductMatrix().M32); spn_SelectionX2[0].setValue(g1.getAccurateProductMatrix().M00); spn_SelectionY2[0].setValue(g1.getAccurateProductMatrix().M01); spn_SelectionZ2[0].setValue(g1.getAccurateProductMatrix().M02); spn_SelectionX3[0].setValue(g1.getAccurateProductMatrix().M10); spn_SelectionY3[0].setValue(g1.getAccurateProductMatrix().M11); spn_SelectionZ3[0].setValue(g1.getAccurateProductMatrix().M12); spn_SelectionX4[0].setValue(g1.getAccurateProductMatrix().M20); spn_SelectionY4[0].setValue(g1.getAccurateProductMatrix().M21); spn_SelectionZ4[0].setValue(g1.getAccurateProductMatrix().M22); break; default: disableSelectionTab(); updatingSelectionTab = true; break; } lbl_SelectionX1[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX1 : "") + " {" + spn_SelectionX1[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionY1[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY1 : "") + " {" + spn_SelectionY1[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionZ1[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ1 : "") + " {" + spn_SelectionZ1[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionX2[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX2 : "") + " {" + spn_SelectionX2[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionY2[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY2 : "") + " {" + spn_SelectionY2[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionZ2[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ2 : "") + " {" + spn_SelectionZ2[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionX3[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX3 : "") + " {" + spn_SelectionX3[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionY3[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY3 : "") + " {" + spn_SelectionY3[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionZ3[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ3 : "") + " {" + spn_SelectionZ3[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionX4[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX4 : "") + " {" + spn_SelectionX4[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionY4[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY4 : "") + " {" + spn_SelectionY4[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionZ4[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ4 : "") + " {" + spn_SelectionZ4[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionX1[0].getParent().layout(); updatingSelectionTab = false; break; default: disableSelectionTab(); break; } } else { disableSelectionTab(); } if (breakIt) break; } } else { disableSelectionTab(); } } else { disableSelectionTab(); } updatingSelectionTab = false; } }); btn_NextSelection[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { updatingSelectionTab = true; NLogger.debug(getClass(), "Next Selection..."); //$NON-NLS-1$ final DatFile df = Project.getFileToEdit(); if (df != null && !df.isReadOnly()) { final VertexManager vm = df.getVertexManager(); vm.addSnapshot(); final int count = vm.getSelectedData().size(); if (count > 0) { boolean breakIt = false; boolean firstRun = true; while (true) { int index = vm.getSelectedItemIndex(); index++; if (index >= count) { index = 0; if (!firstRun) breakIt = true; } firstRun = false; vm.setSelectedItemIndex(index); final GData gdata = (GData) vm.getSelectedData().toArray()[index]; if (vm.isNotInSubfileAndLinetype1to5(gdata)) { vm.setSelectedLine(gdata); disableSelectionTab(); updatingSelectionTab = true; switch (gdata.type()) { case 1: case 5: case 4: spn_SelectionX4[0].setEnabled(true); spn_SelectionY4[0].setEnabled(true); spn_SelectionZ4[0].setEnabled(true); case 3: spn_SelectionX3[0].setEnabled(true); spn_SelectionY3[0].setEnabled(true); spn_SelectionZ3[0].setEnabled(true); case 2: spn_SelectionX1[0].setEnabled(true); spn_SelectionY1[0].setEnabled(true); spn_SelectionZ1[0].setEnabled(true); spn_SelectionX2[0].setEnabled(true); spn_SelectionY2[0].setEnabled(true); spn_SelectionZ2[0].setEnabled(true); txt_Line[0].setText(gdata.toString()); breakIt = true; btn_MoveAdjacentData2[0].setEnabled(true); switch (gdata.type()) { case 5: BigDecimal[] g5 = GraphicalDataTools.getPreciseCoordinates(gdata); spn_SelectionX1[0].setValue(g5[0]); spn_SelectionY1[0].setValue(g5[1]); spn_SelectionZ1[0].setValue(g5[2]); spn_SelectionX2[0].setValue(g5[3]); spn_SelectionY2[0].setValue(g5[4]); spn_SelectionZ2[0].setValue(g5[5]); spn_SelectionX3[0].setValue(g5[6]); spn_SelectionY3[0].setValue(g5[7]); spn_SelectionZ3[0].setValue(g5[8]); spn_SelectionX4[0].setValue(g5[9]); spn_SelectionY4[0].setValue(g5[10]); spn_SelectionZ4[0].setValue(g5[11]); break; case 4: BigDecimal[] g4 = GraphicalDataTools.getPreciseCoordinates(gdata); spn_SelectionX1[0].setValue(g4[0]); spn_SelectionY1[0].setValue(g4[1]); spn_SelectionZ1[0].setValue(g4[2]); spn_SelectionX2[0].setValue(g4[3]); spn_SelectionY2[0].setValue(g4[4]); spn_SelectionZ2[0].setValue(g4[5]); spn_SelectionX3[0].setValue(g4[6]); spn_SelectionY3[0].setValue(g4[7]); spn_SelectionZ3[0].setValue(g4[8]); spn_SelectionX4[0].setValue(g4[9]); spn_SelectionY4[0].setValue(g4[10]); spn_SelectionZ4[0].setValue(g4[11]); break; case 3: BigDecimal[] g3 = GraphicalDataTools.getPreciseCoordinates(gdata); spn_SelectionX1[0].setValue(g3[0]); spn_SelectionY1[0].setValue(g3[1]); spn_SelectionZ1[0].setValue(g3[2]); spn_SelectionX2[0].setValue(g3[3]); spn_SelectionY2[0].setValue(g3[4]); spn_SelectionZ2[0].setValue(g3[5]); spn_SelectionX3[0].setValue(g3[6]); spn_SelectionY3[0].setValue(g3[7]); spn_SelectionZ3[0].setValue(g3[8]); break; case 2: BigDecimal[] g2 = GraphicalDataTools.getPreciseCoordinates(gdata); spn_SelectionX1[0].setValue(g2[0]); spn_SelectionY1[0].setValue(g2[1]); spn_SelectionZ1[0].setValue(g2[2]); spn_SelectionX2[0].setValue(g2[3]); spn_SelectionY2[0].setValue(g2[4]); spn_SelectionZ2[0].setValue(g2[5]); break; case 1: vm.getSelectedVertices().clear(); btn_MoveAdjacentData2[0].setEnabled(false); GData1 g1 = (GData1) gdata; spn_SelectionX1[0].setValue(g1.getAccurateProductMatrix().M30); spn_SelectionY1[0].setValue(g1.getAccurateProductMatrix().M31); spn_SelectionZ1[0].setValue(g1.getAccurateProductMatrix().M32); spn_SelectionX2[0].setValue(g1.getAccurateProductMatrix().M00); spn_SelectionY2[0].setValue(g1.getAccurateProductMatrix().M01); spn_SelectionZ2[0].setValue(g1.getAccurateProductMatrix().M02); spn_SelectionX3[0].setValue(g1.getAccurateProductMatrix().M10); spn_SelectionY3[0].setValue(g1.getAccurateProductMatrix().M11); spn_SelectionZ3[0].setValue(g1.getAccurateProductMatrix().M12); spn_SelectionX4[0].setValue(g1.getAccurateProductMatrix().M20); spn_SelectionY4[0].setValue(g1.getAccurateProductMatrix().M21); spn_SelectionZ4[0].setValue(g1.getAccurateProductMatrix().M22); break; default: disableSelectionTab(); updatingSelectionTab = true; break; } lbl_SelectionX1[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX1 : "X :") + " {" + spn_SelectionX1[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionY1[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY1 : "Y :") + " {" + spn_SelectionY1[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionZ1[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ1 : "Z :") + " {" + spn_SelectionZ1[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionX2[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX2 : "M00:") + " {" + spn_SelectionX2[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionY2[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY2 : "M01:") + " {" + spn_SelectionY2[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionZ2[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ2 : "M02:") + " {" + spn_SelectionZ2[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionX3[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX3 : "M10:") + " {" + spn_SelectionX3[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionY3[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY3 : "M11:") + " {" + spn_SelectionY3[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionZ3[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ3 : "M12:") + " {" + spn_SelectionZ3[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionX4[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX4 : "M20:") + " {" + spn_SelectionX4[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionY4[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY4 : "M21:") + " {" + spn_SelectionY4[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionZ4[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ4 : "M22:") + " {" + spn_SelectionZ4[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ lbl_SelectionX1[0].getParent().layout(); break; default: disableSelectionTab(); break; } } else { disableSelectionTab(); } if (breakIt) break; } } else { disableSelectionTab(); } } else { disableSelectionTab(); } updatingSelectionTab = false; } }); final ValueChangeAdapter va = new ValueChangeAdapter() { @Override public void valueChanged(BigDecimalSpinner spn) { if (updatingSelectionTab || Project.getFileToEdit() == null) return; Project.getFileToEdit().getVertexManager().addSnapshot(); final GData newLine = Project.getFileToEdit().getVertexManager().updateSelectedLine( spn_SelectionX1[0].getValue(), spn_SelectionY1[0].getValue(), spn_SelectionZ1[0].getValue(), spn_SelectionX2[0].getValue(), spn_SelectionY2[0].getValue(), spn_SelectionZ2[0].getValue(), spn_SelectionX3[0].getValue(), spn_SelectionY3[0].getValue(), spn_SelectionZ3[0].getValue(), spn_SelectionX4[0].getValue(), spn_SelectionY4[0].getValue(), spn_SelectionZ4[0].getValue(), btn_MoveAdjacentData2[0].getSelection() ); if (newLine == null) { disableSelectionTab(); } else { txt_Line[0].setText(newLine.toString()); } } }; spn_SelectionX1[0].addValueChangeListener(va); spn_SelectionY1[0].addValueChangeListener(va); spn_SelectionZ1[0].addValueChangeListener(va); spn_SelectionX2[0].addValueChangeListener(va); spn_SelectionY2[0].addValueChangeListener(va); spn_SelectionZ2[0].addValueChangeListener(va); spn_SelectionX3[0].addValueChangeListener(va); spn_SelectionY3[0].addValueChangeListener(va); spn_SelectionZ3[0].addValueChangeListener(va); spn_SelectionX4[0].addValueChangeListener(va); spn_SelectionY4[0].addValueChangeListener(va); spn_SelectionZ4[0].addValueChangeListener(va); // treeParts[0].addSelectionListener(new SelectionAdapter() { // @Override // public void widgetSelected(final SelectionEvent e) { // // } // }); treeParts[0].addListener(SWT.MouseDown, new Listener() { @Override public void handleEvent(Event event) { if (event.button == MouseButton.RIGHT) { NLogger.debug(getClass(), "Showing context menu."); //$NON-NLS-1$ try { if (treeParts[0].getTree().getMenu() != null) { treeParts[0].getTree().getMenu().dispose(); } } catch (Exception ex) {} Menu treeMenu = new Menu(treeParts[0].getTree()); treeParts[0].getTree().setMenu(treeMenu); mnu_treeMenu[0] = treeMenu; MenuItem mntmOpenIn3DEditor = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT()); mntm_OpenIn3DEditor[0] = mntmOpenIn3DEditor; mntmOpenIn3DEditor.setEnabled(true); mntmOpenIn3DEditor.setText(I18n.E3D_OpenIn3DEditor); MenuItem mntmOpenInTextEditor = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT()); mntm_OpenInTextEditor[0] = mntmOpenInTextEditor; mntmOpenInTextEditor.setEnabled(true); mntmOpenInTextEditor.setText(I18n.E3D_OpenInTextEditor); @SuppressWarnings("unused") MenuItem mntm_Separator = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT() | SWT.SEPARATOR); MenuItem mntmRename = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT()); mntm_Rename[0] = mntmRename; mntmRename.setEnabled(true); mntmRename.setText(I18n.E3D_RenameMove); MenuItem mntmRevert = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT()); mntm_Revert[0] = mntmRevert; mntmRevert.setEnabled(true); mntmRevert.setText(I18n.E3D_RevertAllChanges); MenuItem mntmDelete = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT()); mntm_Delete[0] = mntmDelete; mntmDelete.setEnabled(true); mntmDelete.setText(I18n.E3D_Delete); @SuppressWarnings("unused") MenuItem mntm_Separator2 = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT() | SWT.SEPARATOR); MenuItem mntmCopyToUnofficial = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT()); mntm_CopyToUnofficial[0] = mntmCopyToUnofficial; mntmCopyToUnofficial.setEnabled(true); mntmCopyToUnofficial.setText(I18n.E3D_CopyToUnofficialLibrary); mntm_OpenInTextEditor[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].getData() instanceof DatFile) { DatFile df = (DatFile) treeParts[0].getSelection()[0].getData(); for (EditorTextWindow w : Project.getOpenTextWindows()) { for (CTabItem t : w.getTabFolder().getItems()) { if (df.equals(((CompositeTab) t).getState().getFileNameObj())) { w.getTabFolder().setSelection(t); ((CompositeTab) t).getControl().getShell().forceActive(); w.open(); df.getVertexManager().setUpdated(true); return; } } } // Project.getParsedFiles().add(df); IS NECESSARY HERE Project.getParsedFiles().add(df); new EditorTextWindow().run(df); df.getVertexManager().addSnapshot(); } else { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK); messageBoxError.setText(I18n.DIALOG_UnavailableTitle); messageBoxError.setMessage(I18n.DIALOG_Unavailable); messageBoxError.open(); } cleanupClosedData(); } }); mntm_OpenIn3DEditor[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].getData() instanceof DatFile) { if (renders.isEmpty()) { if ("%EMPTY%".equals(Editor3DWindow.getSashForm().getChildren()[1].getData())) { //$NON-NLS-1$ int[] mainSashWeights = Editor3DWindow.getSashForm().getWeights(); Editor3DWindow.getSashForm().getChildren()[1].dispose(); CompositeContainer cmp_Container = new CompositeContainer(Editor3DWindow.getSashForm(), false); cmp_Container.moveBelow(Editor3DWindow.getSashForm().getChildren()[0]); DatFile df = (DatFile) treeParts[0].getSelection()[0].getData(); df.parseForData(true); Project.setFileToEdit(df); cmp_Container.getComposite3D().setLockableDatFileReference(df); df.getVertexManager().addSnapshot(); Editor3DWindow.getSashForm().getParent().layout(); Editor3DWindow.getSashForm().setWeights(mainSashWeights); } } else { boolean canUpdate = false; for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (!c3d.isDatFileLockedOnDisplay()) { canUpdate = true; break; } } if (canUpdate) { DatFile df = (DatFile) treeParts[0].getSelection()[0].getData(); final VertexManager vm = df.getVertexManager(); if (vm.isModified()) { df.setText(df.getText()); } df.parseForData(true); Project.setFileToEdit(df); for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (!c3d.isDatFileLockedOnDisplay()) { c3d.setLockableDatFileReference(df); c3d.getModifier().zoomToFit(); } } df.getVertexManager().addSnapshot(); } } } else { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK); messageBoxError.setText(I18n.DIALOG_UnavailableTitle); messageBoxError.setMessage(I18n.DIALOG_Unavailable); messageBoxError.open(); } cleanupClosedData(); } }); mntm_Revert[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].getData() instanceof DatFile) { DatFile df = (DatFile) treeParts[0].getSelection()[0].getData(); if (df.isReadOnly() || !Project.getUnsavedFiles().contains(df) || df.isVirtual() && df.getText().trim().isEmpty()) return; df.getVertexManager().addSnapshot(); MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.NO); messageBox.setText(I18n.DIALOG_RevertTitle); Object[] messageArguments = {df.getShortName(), df.getLastSavedOpened()}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.DIALOG_Revert); messageBox.setMessage(formatter.format(messageArguments)); int result = messageBox.open(); if (result == SWT.NO) { return; } boolean canUpdate = false; for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(df)) { canUpdate = true; break; } } EditorTextWindow tmpW = null; CTabItem tmpT = null; for (EditorTextWindow w : Project.getOpenTextWindows()) { for (CTabItem t : w.getTabFolder().getItems()) { if (df.equals(((CompositeTab) t).getState().getFileNameObj())) { canUpdate = true; tmpW = w; tmpT = t; break; } } } df.setText(df.getOriginalText()); df.setOldName(df.getNewName()); if (!df.isVirtual()) { Project.removeUnsavedFile(df); updateTree_unsavedEntries(); } if (canUpdate) { df.parseForData(true); df.getVertexManager().setModified(true, true); if (tmpW != null) { tmpW.getTabFolder().setSelection(tmpT); ((CompositeTab) tmpT).getControl().getShell().forceActive(); tmpW.open(); ((CompositeTab) tmpT).getTextComposite().forceFocus(); } } } else { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK); messageBoxError.setText(I18n.DIALOG_UnavailableTitle); messageBoxError.setMessage(I18n.DIALOG_Unavailable); messageBoxError.open(); } } }); mntm_Delete[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].getData() instanceof DatFile) { DatFile df = (DatFile) treeParts[0].getSelection()[0].getData(); if (df.isReadOnly()) { if (treeParts[0].getSelection()[0].getParentItem().getParentItem() == treeItem_Project[0]) { updateTree_removeEntry(df); cleanupClosedData(); } return; } updateTree_removeEntry(df); if (df.getOldName().startsWith(Project.getProjectPath()) && df.getNewName().startsWith(Project.getProjectPath())) { try { File f = new File(df.getOldName()); if (f.exists()) { File bakFile = new File(df.getOldName() + ".bak"); //$NON-NLS-1$ if (bakFile.exists()) { bakFile.delete(); } f.renameTo(bakFile); } } catch (Exception ex) {} } cleanupClosedData(); } else { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK); messageBoxError.setText(I18n.DIALOG_UnavailableTitle); messageBoxError.setMessage(I18n.DIALOG_Unavailable); messageBoxError.open(); } } }); mntm_Rename[0].addSelectionListener(new SelectionAdapter() { @SuppressWarnings("unchecked") @Override public void widgetSelected(SelectionEvent e) { if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].getData() instanceof DatFile) { DatFile df = (DatFile) treeParts[0].getSelection()[0].getData(); if (df.isReadOnly()) return; df.getVertexManager().addSnapshot(); FileDialog dlg = new FileDialog(Editor3DWindow.getWindow().getShell(), SWT.SAVE); File tmp = new File(df.getNewName()); dlg.setFilterPath(tmp.getAbsolutePath().substring(0, tmp.getAbsolutePath().length() - tmp.getName().length())); dlg.setFileName(tmp.getName()); dlg.setFilterExtensions(new String[]{"*.dat"}); //$NON-NLS-1$ dlg.setOverwrite(true); // Change the title bar text dlg.setText(I18n.DIALOG_RenameOrMove); // Calling open() will open and run the dialog. // It will return the selected file, or // null if user cancels String newPath = dlg.open(); if (newPath != null) { while (isFileNameAllocated(newPath, df, false)) { MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.RETRY | SWT.CANCEL); messageBox.setText(I18n.DIALOG_AlreadyAllocatedNameTitle); messageBox.setMessage(I18n.DIALOG_AlreadyAllocatedName); int result = messageBox.open(); if (result == SWT.CANCEL) { return; } newPath = dlg.open(); if (newPath == null) return; } if (df.isProjectFile() && !newPath.startsWith(Project.getProjectPath())) { MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_WARNING | SWT.YES | SWT.NO); messageBox.setText(I18n.DIALOG_NoProjectLocationTitle); Object[] messageArguments = {new File(newPath).getName()}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.DIALOG_NoProjectLocation); messageBox.setMessage(formatter.format(messageArguments)); int result = messageBox.open(); if (result == SWT.NO) { return; } } df.setNewName(newPath); if (!df.getOldName().equals(df.getNewName())) { if (!Project.getUnsavedFiles().contains(df)) { df.parseForData(true); df.getVertexManager().setModified(true, true); Project.getUnsavedFiles().add(df); } } else { if (df.getText().equals(df.getOriginalText()) && df.getOldName().equals(df.getNewName())) { Project.removeUnsavedFile(df); } } df.setProjectFile(df.getNewName().startsWith(Project.getProjectPath())); HashSet<EditorTextWindow> windows = new HashSet<EditorTextWindow>(Project.getOpenTextWindows()); for (EditorTextWindow win : windows) { win.updateTabWithDatfile(df); } updateTree_renamedEntries(); updateTree_unsavedEntries(); } } else if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].equals(treeItem_Project[0])) { if (Project.isDefaultProject()) { ProjectActions.createNewProject(Editor3DWindow.getWindow(), true); } else { int result = new NewProjectDialog(true).open(); if (result == IDialogConstants.OK_ID && !Project.getTempProjectPath().equals(Project.getProjectPath())) { try { while (new File(Project.getTempProjectPath()).isDirectory()) { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.YES | SWT.CANCEL | SWT.NO); messageBoxError.setText(I18n.PROJECT_ProjectOverwriteTitle); messageBoxError.setMessage(I18n.PROJECT_ProjectOverwrite); int result2 = messageBoxError.open(); if (result2 == SWT.CANCEL) { return; } else if (result2 == SWT.YES) { break; } else { result = new NewProjectDialog(true).open(); if (result == IDialogConstants.CANCEL_ID) { return; } } } Project.copyFolder(new File(Project.getProjectPath()), new File(Project.getTempProjectPath())); Project.deleteFolder(new File(Project.getProjectPath())); // Linked project parts need a new path, because they were copied to a new directory String defaultPrefix = new File(Project.getProjectPath()).getAbsolutePath() + File.separator; String projectPrefix = new File(Project.getTempProjectPath()).getAbsolutePath() + File.separator; Editor3DWindow.getWindow().getProjectParts().getParentItem().setData(Project.getTempProjectPath()); HashSet<DatFile> projectFiles = new HashSet<DatFile>(); projectFiles.addAll((ArrayList<DatFile>) Editor3DWindow.getWindow().getProjectParts().getData()); projectFiles.addAll((ArrayList<DatFile>) Editor3DWindow.getWindow().getProjectSubparts().getData()); projectFiles.addAll((ArrayList<DatFile>) Editor3DWindow.getWindow().getProjectPrimitives().getData()); projectFiles.addAll((ArrayList<DatFile>) Editor3DWindow.getWindow().getProjectPrimitives48().getData()); for (DatFile df : projectFiles) { df.getVertexManager().addSnapshot(); boolean isUnsaved = Project.getUnsavedFiles().contains(df); boolean isParsed = Project.getParsedFiles().contains(df); Project.getParsedFiles().remove(df); Project.getUnsavedFiles().remove(df); String newName = df.getNewName(); String oldName = df.getOldName(); df.updateLastModified(); if (!newName.startsWith(projectPrefix) && newName.startsWith(defaultPrefix)) { df.setNewName(projectPrefix + newName.substring(defaultPrefix.length())); } if (!oldName.startsWith(projectPrefix) && oldName.startsWith(defaultPrefix)) { df.setOldName(projectPrefix + oldName.substring(defaultPrefix.length())); } df.setProjectFile(df.getNewName().startsWith(Project.getProjectPath())); if (isUnsaved) Project.addUnsavedFile(df); if (isParsed) Project.getParsedFiles().add(df); } Project.setProjectName(Project.getTempProjectName()); Project.setProjectPath(Project.getTempProjectPath()); Editor3DWindow.getWindow().getProjectParts().getParentItem().setText(Project.getProjectName()); updateTree_unsavedEntries(); Project.updateEditor(); Editor3DWindow.getWindow().getShell().update(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } } else { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK); messageBoxError.setText(I18n.DIALOG_UnavailableTitle); messageBoxError.setMessage(I18n.DIALOG_Unavailable); messageBoxError.open(); } } }); mntm_CopyToUnofficial[0] .addSelectionListener(new SelectionAdapter() { @SuppressWarnings("unchecked") @Override public void widgetSelected(SelectionEvent e) { if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].getData() instanceof DatFile) { DatFile df = (DatFile) treeParts[0].getSelection()[0].getData(); TreeItem p = treeParts[0].getSelection()[0].getParentItem(); String targetPath_u; String targetPath_l; String targetPathDir_u; String targetPathDir_l; TreeItem targetTreeItem; boolean projectIsFileOrigin = false; if (treeItem_ProjectParts[0].equals(p)) { targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "PARTS"; //$NON-NLS-1$ targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "parts"; //$NON-NLS-1$ targetTreeItem = treeItem_UnofficialParts[0]; projectIsFileOrigin = true; } else if (treeItem_ProjectPrimitives[0].equals(p)) { targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P"; //$NON-NLS-1$ targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p"; //$NON-NLS-1$ targetTreeItem = treeItem_UnofficialPrimitives[0]; projectIsFileOrigin = true; } else if (treeItem_ProjectPrimitives48[0].equals(p)) { targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator + "48"; //$NON-NLS-1$ //$NON-NLS-2$ targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator + "48"; //$NON-NLS-1$ //$NON-NLS-2$ targetTreeItem = treeItem_UnofficialPrimitives48[0]; projectIsFileOrigin = true; } else if (treeItem_ProjectPrimitives8[0].equals(p)) { targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator + "8"; //$NON-NLS-1$ //$NON-NLS-2$ targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator + "8"; //$NON-NLS-1$ //$NON-NLS-2$ targetTreeItem = treeItem_UnofficialPrimitives8[0]; projectIsFileOrigin = true; } else if (treeItem_ProjectSubparts[0].equals(p)) { targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "PARTS"+ File.separator + "S"; //$NON-NLS-1$ //$NON-NLS-2$ targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "parts"+ File.separator + "s"; //$NON-NLS-1$ //$NON-NLS-2$ targetTreeItem = treeItem_UnofficialSubparts[0]; projectIsFileOrigin = true; } else if (treeItem_OfficialParts[0].equals(p)) { targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "PARTS"; //$NON-NLS-1$ targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "parts"; //$NON-NLS-1$ targetTreeItem = treeItem_UnofficialParts[0]; } else if (treeItem_OfficialPrimitives[0].equals(p)) { targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P"; //$NON-NLS-1$ targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p"; //$NON-NLS-1$ targetTreeItem = treeItem_UnofficialPrimitives[0]; } else if (treeItem_OfficialPrimitives48[0].equals(p)) { targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator + "48"; //$NON-NLS-1$ //$NON-NLS-2$ targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator + "48"; //$NON-NLS-1$ //$NON-NLS-2$ targetTreeItem = treeItem_UnofficialPrimitives48[0]; } else if (treeItem_OfficialPrimitives8[0].equals(p)) { targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator + "8"; //$NON-NLS-1$ //$NON-NLS-2$ targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator + "8"; //$NON-NLS-1$ //$NON-NLS-2$ targetTreeItem = treeItem_UnofficialPrimitives8[0]; } else if (treeItem_OfficialSubparts[0].equals(p)) { targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "PARTS"+ File.separator + "S"; //$NON-NLS-1$ //$NON-NLS-2$ targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "parts"+ File.separator + "s"; //$NON-NLS-1$ //$NON-NLS-2$ targetTreeItem = treeItem_UnofficialSubparts[0]; } else { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK); messageBoxError.setText(I18n.DIALOG_UnavailableTitle); messageBoxError.setMessage(I18n.DIALOG_Unavailable); messageBoxError.open(); return; } targetPathDir_l = targetPath_l; targetPathDir_u = targetPath_u; final String newName = new File(df.getNewName()).getName(); targetPath_u = targetPath_u + File.separator + newName; targetPath_l = targetPath_l + File.separator + newName; DatFile fileToOverwrite_u = new DatFile(targetPath_u); DatFile fileToOverwrite_l = new DatFile(targetPath_l); DatFile targetFile = null; TreeItem[] folders = new TreeItem[5]; folders[0] = treeItem_UnofficialParts[0]; folders[1] = treeItem_UnofficialPrimitives[0]; folders[2] = treeItem_UnofficialPrimitives48[0]; folders[3] = treeItem_UnofficialPrimitives8[0]; folders[4] = treeItem_UnofficialSubparts[0]; for (TreeItem folder : folders) { ArrayList<DatFile> cachedReferences =(ArrayList<DatFile>) folder.getData(); for (DatFile d : cachedReferences) { if (fileToOverwrite_u.equals(d) || fileToOverwrite_l.equals(d)) { targetFile = d; break; } } } if (new File(targetPath_u).exists() || new File(targetPath_l).exists() || targetFile != null) { MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_WARNING | SWT.OK | SWT.CANCEL); messageBox.setText(I18n.DIALOG_ReplaceTitle); Object[] messageArguments = {newName}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.DIALOG_Replace); messageBox.setMessage(formatter.format(messageArguments)); int result = messageBox.open(); if (result == SWT.CANCEL) { return; } } ArrayList<ArrayList<DatFile>> refResult = null; if (new File(targetPathDir_l).exists() || new File(targetPathDir_u).exists()) { if (targetFile == null) { int result = new CopyDialog(getShell(), new File(df.getNewName()).getName()).open(); switch (result) { case IDialogConstants.OK_ID: // Copy File Only break; case IDialogConstants.NO_ID: // Copy File and required and related if (projectIsFileOrigin) { refResult = ReferenceParser.checkForReferences(df, References.REQUIRED_AND_RELATED, treeItem_Project[0], treeItem_Unofficial[0], treeItem_Official[0]); } else { refResult = ReferenceParser.checkForReferences(df, References.REQUIRED_AND_RELATED, treeItem_Official[0], treeItem_Unofficial[0], treeItem_Project[0]); } break; case IDialogConstants.YES_ID: // Copy File and required if (projectIsFileOrigin) { refResult = ReferenceParser.checkForReferences(df, References.REQUIRED, treeItem_Project[0], treeItem_Unofficial[0], treeItem_Official[0]); } else { refResult = ReferenceParser.checkForReferences(df, References.REQUIRED, treeItem_Official[0], treeItem_Unofficial[0], treeItem_Project[0]); } break; default: return; } DatFile newDatFile = new DatFile(new File(targetPathDir_l).exists() ? targetPath_l : targetPath_u); // Text exchange includes description exchange newDatFile.setText(df.getText()); newDatFile.saveForced(); newDatFile.setType(df.getType()); ((ArrayList<DatFile>) targetTreeItem.getData()).add(newDatFile); TreeItem ti = new TreeItem(targetTreeItem, SWT.NONE); ti.setText(new File(df.getNewName()).getName()); ti.setData(newDatFile); } else if (targetFile.equals(df)) { // This can only happen if the user opens the unofficial parts folder as a project MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK); messageBox.setText(I18n.DIALOG_AlreadyAllocatedNameTitle); messageBox.setMessage(I18n.DIALOG_AlreadyAllocatedName); messageBox.open(); return; } else { int result = new CopyDialog(getShell(), new File(df.getNewName()).getName()).open(); switch (result) { case IDialogConstants.OK_ID: // Copy File Only break; case IDialogConstants.NO_ID: // Copy File and required and related if (projectIsFileOrigin) { refResult = ReferenceParser.checkForReferences(df, References.REQUIRED_AND_RELATED, treeItem_Project[0], treeItem_Unofficial[0], treeItem_Official[0]); } else { refResult = ReferenceParser.checkForReferences(df, References.REQUIRED_AND_RELATED, treeItem_Official[0], treeItem_Unofficial[0], treeItem_Project[0]); } break; case IDialogConstants.YES_ID: // Copy File and required if (projectIsFileOrigin) { refResult = ReferenceParser.checkForReferences(df, References.REQUIRED, treeItem_Project[0], treeItem_Unofficial[0], treeItem_Official[0]); } else { refResult = ReferenceParser.checkForReferences(df, References.REQUIRED, treeItem_Official[0], treeItem_Unofficial[0], treeItem_Project[0]); } break; default: return; } targetFile.disposeData(); updateTree_removeEntry(targetFile); DatFile newDatFile = new DatFile(new File(targetPathDir_l).exists() ? targetPath_l : targetPath_u); newDatFile.setText(df.getText()); newDatFile.saveForced(); ((ArrayList<DatFile>) targetTreeItem.getData()).add(newDatFile); TreeItem ti = new TreeItem(targetTreeItem, SWT.NONE); ti.setText(new File(df.getNewName()).getName()); ti.setData(newDatFile); } if (refResult != null) { // Remove old data for(int i = 0; i < 5; i++) { ArrayList<DatFile> toRemove = refResult.get(i); for (DatFile datToRemove : toRemove) { datToRemove.disposeData(); updateTree_removeEntry(datToRemove); } } // Create new data TreeItem[] targetTrees = new TreeItem[]{treeItem_UnofficialParts[0], treeItem_UnofficialSubparts[0], treeItem_UnofficialPrimitives[0], treeItem_UnofficialPrimitives48[0], treeItem_UnofficialPrimitives8[0]}; for(int i = 5; i < 10; i++) { ArrayList<DatFile> toCreate = refResult.get(i); for (DatFile datToCreate : toCreate) { DatFile newDatFile = new DatFile(datToCreate.getOldName()); String source = datToCreate.getTextDirect(); newDatFile.setText(source); newDatFile.setOriginalText(source); newDatFile.saveForced(); newDatFile.setType(datToCreate.getType()); ((ArrayList<DatFile>) targetTrees[i - 5].getData()).add(newDatFile); TreeItem ti = new TreeItem(targetTrees[i - 5], SWT.NONE); ti.setText(new File(datToCreate.getOldName()).getName()); ti.setData(newDatFile); } } } updateTree_unsavedEntries(); } } else { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK); messageBoxError.setText(I18n.DIALOG_UnavailableTitle); messageBoxError.setMessage(I18n.DIALOG_Unavailable); messageBoxError.open(); } } }); java.awt.Point b = java.awt.MouseInfo.getPointerInfo().getLocation(); final int x = (int) b.getX(); final int y = (int) b.getY(); Menu menu = mnu_treeMenu[0]; menu.setLocation(x, y); menu.setVisible(true); } } }); treeParts[0].addListener(SWT.MouseDoubleClick, new Listener() { @Override public void handleEvent(Event event) { if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null) { treeParts[0].getSelection()[0].setVisible(!treeParts[0].getSelection()[0].isVisible()); TreeItem sel = treeParts[0].getSelection()[0]; sh.getDisplay().asyncExec(new Runnable() { @Override public void run() { treeParts[0].build(); } }); treeParts[0].redraw(); treeParts[0].update(); treeParts[0].getTree().select(treeParts[0].getMapInv().get(sel)); } } }); txt_Search[0].addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { search(txt_Search[0].getText()); } }); btn_ResetSearch[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { txt_Search[0].setText(""); //$NON-NLS-1$ } }); txt_primitiveSearch[0].addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { getCompositePrimitive().collapseAll(); ArrayList<Primitive> prims = getCompositePrimitive().getPrimitives(); final String crit = txt_primitiveSearch[0].getText(); if (crit.trim().isEmpty()) { getCompositePrimitive().setSearchResults(new ArrayList<Primitive>()); Matrix4f.setIdentity(getCompositePrimitive().getTranslation()); getCompositePrimitive().getOpenGL().drawScene(-1, -1); return; } String criteria = ".*" + crit + ".*"; //$NON-NLS-1$ //$NON-NLS-2$ try { "DUMMY".matches(criteria); //$NON-NLS-1$ } catch (PatternSyntaxException pe) { getCompositePrimitive().setSearchResults(new ArrayList<Primitive>()); Matrix4f.setIdentity(getCompositePrimitive().getTranslation()); getCompositePrimitive().getOpenGL().drawScene(-1, -1); return; } final Pattern pattern = Pattern.compile(criteria); ArrayList<Primitive> results = new ArrayList<Primitive>(); for (Primitive p : prims) { p.search(pattern, results); } if (results.isEmpty()) { results.add(null); } getCompositePrimitive().setSearchResults(results); Matrix4f.setIdentity(getCompositePrimitive().getTranslation()); getCompositePrimitive().getOpenGL().drawScene(-1, -1); } }); btn_resetPrimitiveSearch[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { txt_primitiveSearch[0].setText(""); //$NON-NLS-1$ } }); btn_Hide[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager().hideSelection(); } } }); btn_ShowAll[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager().showAll(); } } }); btn_NoTransparentSelection[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { setNoTransparentSelection(btn_NoTransparentSelection[0].getSelection()); } }); btn_BFCToggle[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { setBfcToggle(btn_BFCToggle[0].getSelection()); } }); btn_Delete[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager().delete(Editor3DWindow.getWindow().isMovingAdjacentData(), true); } } }); btn_Copy[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager().copy(); } } }); btn_Cut[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager().copy(); Project.getFileToEdit().getVertexManager().delete(false, true); } } }); btn_Paste[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Project.getFileToEdit().getVertexManager().addSnapshot(); Project.getFileToEdit().getVertexManager().paste(); setMovingAdjacentData(false); } } }); btn_Manipulator_0_toOrigin[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { c3d.getManipulator().reset(); } } } } }); btn_Manipulator_XIII_toWorld[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { Vector4f t = new Vector4f(c3d.getManipulator().getPosition()); BigDecimal[] T = c3d.getManipulator().getAccuratePosition(); c3d.getManipulator().reset(); c3d.getManipulator().getPosition().set(t); c3d.getManipulator().setAccuratePosition(T[0], T[1], T[2]); ; } } } } }); btn_Manipulator_X_XReverse[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { Vector4f.sub(new Vector4f(0f, 0f, 0f, 2f), c3d.getManipulator().getXaxis(), c3d.getManipulator().getXaxis()); BigDecimal[] a = c3d.getManipulator().getAccurateXaxis(); c3d.getManipulator().setAccurateXaxis(a[0].negate(), a[1].negate(), a[2].negate()); } } } }); btn_Manipulator_XI_YReverse[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { Vector4f.sub(new Vector4f(0f, 0f, 0f, 2f), c3d.getManipulator().getYaxis(), c3d.getManipulator().getYaxis()); BigDecimal[] a = c3d.getManipulator().getAccurateYaxis(); c3d.getManipulator().setAccurateYaxis(a[0].negate(), a[1].negate(), a[2].negate()); } } } }); btn_Manipulator_XII_ZReverse[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { Vector4f.sub(new Vector4f(0f, 0f, 0f, 2f), c3d.getManipulator().getZaxis(), c3d.getManipulator().getZaxis()); BigDecimal[] a = c3d.getManipulator().getAccurateZaxis(); c3d.getManipulator().setAccurateZaxis(a[0].negate(), a[1].negate(), a[2].negate()); } } } }); btn_Manipulator_SwitchXY[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { Vector4f temp = new Vector4f(c3d.getManipulator().getXaxis()); c3d.getManipulator().getXaxis().set(c3d.getManipulator().getYaxis()); c3d.getManipulator().getYaxis().set(temp); BigDecimal[] a = c3d.getManipulator().getAccurateXaxis().clone(); BigDecimal[] b = c3d.getManipulator().getAccurateYaxis().clone(); c3d.getManipulator().setAccurateXaxis(b[0], b[1], b[2]); c3d.getManipulator().setAccurateYaxis(a[0], a[1], a[2]); } } } }); btn_Manipulator_SwitchXZ[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { Vector4f temp = new Vector4f(c3d.getManipulator().getXaxis()); c3d.getManipulator().getXaxis().set(c3d.getManipulator().getZaxis()); c3d.getManipulator().getZaxis().set(temp); BigDecimal[] a = c3d.getManipulator().getAccurateXaxis().clone(); BigDecimal[] b = c3d.getManipulator().getAccurateZaxis().clone(); c3d.getManipulator().setAccurateXaxis(b[0], b[1], b[2]); c3d.getManipulator().setAccurateZaxis(a[0], a[1], a[2]); } } } }); btn_Manipulator_SwitchYZ[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { Vector4f temp = new Vector4f(c3d.getManipulator().getZaxis()); c3d.getManipulator().getZaxis().set(c3d.getManipulator().getYaxis()); c3d.getManipulator().getYaxis().set(temp); BigDecimal[] a = c3d.getManipulator().getAccurateYaxis().clone(); BigDecimal[] b = c3d.getManipulator().getAccurateZaxis().clone(); c3d.getManipulator().setAccurateYaxis(b[0], b[1], b[2]); c3d.getManipulator().setAccurateZaxis(a[0], a[1], a[2]); } } } }); btn_Manipulator_1_cameraToPos[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); Vector4f pos = c3d.getManipulator().getPosition(); Vector4f a1 = c3d.getManipulator().getXaxis(); Vector4f a2 = c3d.getManipulator().getYaxis(); Vector4f a3 = c3d.getManipulator().getZaxis(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { c3d.setClassicPerspective(false); WidgetSelectionHelper.unselectAllChildButtons(c3d.getViewAnglesMenu()); Matrix4f rot = new Matrix4f(); Matrix4f.setIdentity(rot); rot.m00 = a1.x; rot.m10 = a1.y; rot.m20 = a1.z; rot.m01 = a2.x; rot.m11 = a2.y; rot.m21 = a2.z; rot.m02 = a3.x; rot.m12 = a3.y; rot.m22 = a3.z; c3d.getRotation().load(rot); Matrix4f trans = new Matrix4f(); Matrix4f.setIdentity(trans); trans.translate(new Vector3f(-pos.x, -pos.y, -pos.z)); c3d.getTranslation().load(trans); c3d.getPerspectiveCalculator().calculateOriginData(); } } } }); btn_Manipulator_2_toAverage[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Vector4f avg = Project.getFileToEdit().getVertexManager().getSelectionCenter(); for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { c3d.getManipulator().getPosition().set(avg.x, avg.y, avg.z, 1f); c3d.getManipulator().setAccuratePosition(new BigDecimal(avg.x / 1000f), new BigDecimal(avg.y / 1000f), new BigDecimal(avg.z / 1000f)); } } } } }); btn_Manipulator_3_toSubfile[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Set<GData1> subfiles = Project.getFileToEdit().getVertexManager().getSelectedSubfiles(); if (!subfiles.isEmpty()) { GData1 subfile = null; for (GData1 g1 : subfiles) { subfile = g1; break; } Matrix4f m = subfile.getProductMatrix(); Matrix M = subfile.getAccurateProductMatrix(); for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { c3d.getManipulator().getPosition().set(m.m30, m.m31, m.m32, 1f); c3d.getManipulator().setAccuratePosition(M.M30, M.M31, M.M32); Vector3f x = new Vector3f(m.m00, m.m01, m.m02); x.normalise(); Vector3f y = new Vector3f(m.m10, m.m11, m.m12); y.normalise(); Vector3f z = new Vector3f(m.m20, m.m21, m.m22); z.normalise(); c3d.getManipulator().getXaxis().set(x.x, x.y, x.z, 1f); c3d.getManipulator().getYaxis().set(y.x, y.y, y.z, 1f); c3d.getManipulator().getZaxis().set(z.x, z.y, z.z, 1f); c3d.getManipulator().setAccurateXaxis(new BigDecimal(c3d.getManipulator().getXaxis().x), new BigDecimal(c3d.getManipulator().getXaxis().y), new BigDecimal(c3d.getManipulator().getXaxis().z)); c3d.getManipulator().setAccurateYaxis(new BigDecimal(c3d.getManipulator().getYaxis().x), new BigDecimal(c3d.getManipulator().getYaxis().y), new BigDecimal(c3d.getManipulator().getYaxis().z)); c3d.getManipulator().setAccurateZaxis(new BigDecimal(c3d.getManipulator().getZaxis().x), new BigDecimal(c3d.getManipulator().getZaxis().y), new BigDecimal(c3d.getManipulator().getZaxis().z)); } } } } } }); btn_Manipulator_32_subfileTo[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { VertexManager vm = Project.getFileToEdit().getVertexManager(); Set<GData1> subfiles = vm.getSelectedSubfiles(); if (!subfiles.isEmpty()) { GData1 subfile = null; for (GData1 g1 : subfiles) { if (vm.getLineLinkedToVertices().containsKey(g1)) { subfile = g1; break; } } if (subfile == null) { return; } for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { vm.addSnapshot(); Manipulator ma = c3d.getManipulator(); vm.transformSubfile(subfile, ma.getAccurateMatrix(), true, true); break; } } } } } }); btn_Manipulator_4_toVertex[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { float minDist = Float.MAX_VALUE; Vector4f next = new Vector4f(c3d.getManipulator().getPosition()); Vector4f min = new Vector4f(c3d.getManipulator().getPosition()); VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); Set<Vertex> vertices; if (vm.getSelectedVertices().isEmpty()) { vertices = vm.getVertices(); } else { vertices = vm.getSelectedVertices(); } Vertex minVertex = new Vertex(0f, 0f, 0f); for (Vertex vertex : vertices) { Vector4f sub = Vector4f.sub(next, vertex.toVector4f(), null); float d2 = sub.lengthSquared(); if (d2 < minDist) { minVertex = vertex; minDist = d2; min = vertex.toVector4f(); } } c3d.getManipulator().getPosition().set(min.x, min.y, min.z, 1f); c3d.getManipulator().setAccuratePosition(minVertex.X, minVertex.Y, minVertex.Z); } } } }); btn_Manipulator_5_toEdge[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { Vector4f min = new Vector4f(c3d.getManipulator().getPosition()); VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); min = vm.getMinimalDistanceVertexToLines(new Vertex(c3d.getManipulator().getPosition())).toVector4f(); c3d.getManipulator().getPosition().set(min.x, min.y, min.z, 1f); c3d.getManipulator().setAccuratePosition(new BigDecimal(min.x / 1000f), new BigDecimal(min.y / 1000f), new BigDecimal(min.z / 1000f)); } } } }); btn_Manipulator_6_toSurface[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { Vector4f min = new Vector4f(c3d.getManipulator().getPosition()); VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); min = vm.getMinimalDistanceVertexToSurfaces(new Vertex(c3d.getManipulator().getPosition())).toVector4f(); c3d.getManipulator().getPosition().set(min.x, min.y, min.z, 1f); c3d.getManipulator().setAccuratePosition(new BigDecimal(min.x / 1000f), new BigDecimal(min.y / 1000f), new BigDecimal(min.z / 1000f)); } } } }); btn_Manipulator_7_toVertexNormal[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { float minDist = Float.MAX_VALUE; Vector4f next = new Vector4f(c3d.getManipulator().getPosition()); Vertex min = null; VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); Set<Vertex> vertices; if (vm.getSelectedVertices().isEmpty()) { vertices = vm.getVertices(); } else { vertices = vm.getSelectedVertices(); } for (Vertex vertex : vertices) { Vector4f sub = Vector4f.sub(next, vertex.toVector4f(), null); float d2 = sub.lengthSquared(); if (d2 < minDist) { minDist = d2; min = vertex; } } vm = c3d.getLockableDatFileReference().getVertexManager(); Vector4f n = vm.getVertexNormal(min); float tx = 1f; float ty = 0f; float tz = 0f; if (n.x <= 0f) { tx = -1; } if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) { tz = tx; tx = 0f; ty = 0f; } else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, 0f, 0f), null).length()) > .00001f) { // ty = 0f; // tz = 0f; } else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) { ty = tx; tx = 0f; tz = 0f; } else { return; } Vector3f cross = (Vector3f) Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, ty, tz), null).normalise(); c3d.getManipulator().getZaxis().set(n.x, n.y, n.z, 1f); c3d.getManipulator().getXaxis().set(cross.x, cross.y, cross.z, 1f); Vector4f zaxis = c3d.getManipulator().getZaxis(); Vector4f xaxis = c3d.getManipulator().getXaxis(); cross = Vector3f.cross(new Vector3f(xaxis.x, xaxis.y, xaxis.z), new Vector3f(zaxis.x, zaxis.y, zaxis.z), null); c3d.getManipulator().getYaxis().set(cross.x, cross.y, cross.z, 1f); c3d.getManipulator().setAccurateXaxis(new BigDecimal(c3d.getManipulator().getXaxis().x), new BigDecimal(c3d.getManipulator().getXaxis().y), new BigDecimal(c3d.getManipulator().getXaxis().z)); c3d.getManipulator().setAccurateYaxis(new BigDecimal(c3d.getManipulator().getYaxis().x), new BigDecimal(c3d.getManipulator().getYaxis().y), new BigDecimal(c3d.getManipulator().getYaxis().z)); c3d.getManipulator().setAccurateZaxis(new BigDecimal(c3d.getManipulator().getZaxis().x), new BigDecimal(c3d.getManipulator().getZaxis().y), new BigDecimal(c3d.getManipulator().getZaxis().z)); } } } }); btn_Manipulator_8_toEdgeNormal[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); Vector4f n = vm.getMinimalDistanceEdgeNormal(new Vertex(c3d.getManipulator().getPosition())); float tx = 1f; float ty = 0f; float tz = 0f; if (n.x <= 0f) { tx = -1; } if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) { tz = tx; tx = 0f; ty = 0f; } else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, 0f, 0f), null).length()) > .00001f) { // ty = 0f; // tz = 0f; } else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) { ty = tx; tx = 0f; tz = 0f; } else { return; } Vector3f cross = (Vector3f) Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, ty, tz), null).normalise(); c3d.getManipulator().getZaxis().set(n.x, n.y, n.z, 1f); c3d.getManipulator().getXaxis().set(cross.x, cross.y, cross.z, 1f); Vector4f zaxis = c3d.getManipulator().getZaxis(); Vector4f xaxis = c3d.getManipulator().getXaxis(); cross = Vector3f.cross(new Vector3f(xaxis.x, xaxis.y, xaxis.z), new Vector3f(zaxis.x, zaxis.y, zaxis.z), null); c3d.getManipulator().getYaxis().set(cross.x, cross.y, cross.z, 1f); c3d.getManipulator().setAccurateXaxis(new BigDecimal(c3d.getManipulator().getXaxis().x), new BigDecimal(c3d.getManipulator().getXaxis().y), new BigDecimal(c3d.getManipulator().getXaxis().z)); c3d.getManipulator().setAccurateYaxis(new BigDecimal(c3d.getManipulator().getYaxis().x), new BigDecimal(c3d.getManipulator().getYaxis().y), new BigDecimal(c3d.getManipulator().getYaxis().z)); c3d.getManipulator().setAccurateZaxis(new BigDecimal(c3d.getManipulator().getZaxis().x), new BigDecimal(c3d.getManipulator().getZaxis().y), new BigDecimal(c3d.getManipulator().getZaxis().z)); } } } }); btn_Manipulator_9_toSurfaceNormal[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); Vector4f n = vm.getMinimalDistanceSurfaceNormal(new Vertex(c3d.getManipulator().getPosition())); float tx = 1f; float ty = 0f; float tz = 0f; if (n.x <= 0f) { tx = -1; } if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) { tz = tx; tx = 0f; ty = 0f; } else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, 0f, 0f), null).length()) > .00001f) { // ty = 0f; // tz = 0f; } else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) { ty = tx; tx = 0f; tz = 0f; } else { return; } Vector3f cross = (Vector3f) Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, ty, tz), null).normalise(); c3d.getManipulator().getZaxis().set(n.x, n.y, n.z, 1f); c3d.getManipulator().getXaxis().set(cross.x, cross.y, cross.z, 1f); Vector4f zaxis = c3d.getManipulator().getZaxis(); Vector4f xaxis = c3d.getManipulator().getXaxis(); cross = Vector3f.cross(new Vector3f(xaxis.x, xaxis.y, xaxis.z), new Vector3f(zaxis.x, zaxis.y, zaxis.z), null); c3d.getManipulator().getYaxis().set(cross.x, cross.y, cross.z, 1f); c3d.getManipulator().setAccurateXaxis(new BigDecimal(c3d.getManipulator().getXaxis().x), new BigDecimal(c3d.getManipulator().getXaxis().y), new BigDecimal(c3d.getManipulator().getXaxis().z)); c3d.getManipulator().setAccurateYaxis(new BigDecimal(c3d.getManipulator().getYaxis().x), new BigDecimal(c3d.getManipulator().getYaxis().y), new BigDecimal(c3d.getManipulator().getYaxis().z)); c3d.getManipulator().setAccurateZaxis(new BigDecimal(c3d.getManipulator().getZaxis().x), new BigDecimal(c3d.getManipulator().getZaxis().y), new BigDecimal(c3d.getManipulator().getZaxis().z)); } } } }); btn_Manipulator_XIV_adjustRotationCenter[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.adjustRotationCenter(c3d, null); } } } }); mntm_SelectAll[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); loadSelectorSettings(); vm.selectAll(sels, true); vm.syncWithTextEditors(true); return; } } } }); mntm_SelectAllVisible[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); loadSelectorSettings(); vm.selectAll(sels, false); vm.syncWithTextEditors(true); return; } } } }); mntm_SelectAllWithColours[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); loadSelectorSettings(); vm.selectAllWithSameColours(sels, true); vm.syncWithTextEditors(true); return; } } } }); mntm_SelectAllVisibleWithColours[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); loadSelectorSettings(); vm.selectAllWithSameColours(sels, false); vm.syncWithTextEditors(true); return; } } } }); mntm_SelectNone[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); vm.clearSelection(); vm.syncWithTextEditors(true); return; } } } }); mntm_SelectInverse[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); loadSelectorSettings(); vm.selectInverse(sels); vm.syncWithTextEditors(true); return; } } } }); mntm_WithSameColour[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { mntm_SelectEverything[0].setEnabled( mntm_WithHiddenData[0].getSelection() || mntm_WithSameColour[0].getSelection() || mntm_WithSameOrientation[0].getSelection() || mntm_ExceptSubfiles[0].getSelection() ); showSelectMenu(); } }); } }); mntm_WithSameOrientation[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { mntm_SelectEverything[0].setEnabled( mntm_WithHiddenData[0].getSelection() || mntm_WithSameColour[0].getSelection() || mntm_WithSameOrientation[0].getSelection() || mntm_ExceptSubfiles[0].getSelection() ); if (mntm_WithSameOrientation[0].getSelection()) { new ValueDialog(getShell(), I18n.E3D_AngleDiff, I18n.E3D_ThreshInDeg) { @Override public void initializeSpinner() { this.spn_Value[0].setMinimum(new BigDecimal("-90")); //$NON-NLS-1$ this.spn_Value[0].setMaximum(new BigDecimal("180")); //$NON-NLS-1$ this.spn_Value[0].setValue(sels.getAngle()); } @Override public void applyValue() { sels.setAngle(this.spn_Value[0].getValue()); } }.open(); } showSelectMenu(); } }); } }); mntm_WithAccuracy[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { mntm_SelectEverything[0].setEnabled( mntm_WithHiddenData[0].getSelection() || mntm_WithSameColour[0].getSelection() || mntm_WithSameOrientation[0].getSelection() || mntm_ExceptSubfiles[0].getSelection() ); if (mntm_WithAccuracy[0].getSelection()) { new ValueDialog(getShell(), I18n.E3D_SetAccuracy, I18n.E3D_ThreshInLdu) { @Override public void initializeSpinner() { this.spn_Value[0].setMinimum(new BigDecimal("0")); //$NON-NLS-1$ this.spn_Value[0].setMaximum(new BigDecimal("1000")); //$NON-NLS-1$ this.spn_Value[0].setValue(sels.getEqualDistance()); } @Override public void applyValue() { sels.setEqualDistance(this.spn_Value[0].getValue()); } }.open(); } showSelectMenu(); } }); } }); mntm_WithHiddenData[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { mntm_SelectEverything[0].setEnabled( mntm_WithHiddenData[0].getSelection() || mntm_WithSameColour[0].getSelection() || mntm_WithSameOrientation[0].getSelection() || mntm_ExceptSubfiles[0].getSelection() ); showSelectMenu(); } }); } }); mntm_WithWholeSubfiles[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { showSelectMenu(); } }); } }); mntm_ExceptSubfiles[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { mntm_SelectEverything[0].setEnabled( mntm_WithHiddenData[0].getSelection() || mntm_WithSameColour[0].getSelection() || mntm_WithSameOrientation[0].getSelection() || mntm_ExceptSubfiles[0].getSelection() ); mntm_WithWholeSubfiles[0].setEnabled(!mntm_ExceptSubfiles[0].getSelection()); showSelectMenu(); } }); } }); mntm_StopAtEdges[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { showSelectMenu(); } }); } }); mntm_STriangles[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { showSelectMenu(); } }); } }); mntm_SQuads[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { showSelectMenu(); } }); } }); mntm_SCLines[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { showSelectMenu(); } }); } }); mntm_SVertices[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { showSelectMenu(); } }); } }); mntm_SLines[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { showSelectMenu(); } }); } }); mntm_SelectEverything[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); sels.setScope(SelectorSettings.EVERYTHING); loadSelectorSettings(); vm.selector(sels); vm.syncWithTextEditors(true); } } } }); mntm_SelectConnected[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); sels.setScope(SelectorSettings.CONNECTED); loadSelectorSettings(); vm.selector(sels); vm.syncWithTextEditors(true); } } } }); mntm_SelectTouching[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); sels.setScope(SelectorSettings.TOUCHING); loadSelectorSettings(); vm.selector(sels); vm.syncWithTextEditors(true); } } } }); mntm_SelectIsolatedVertices[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); vm.selectIsolatedVertices(); vm.syncWithTextEditors(true); } } } }); } }); mntm_Split[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); vm.split(2); } } } }); } }); mntm_SplitNTimes[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { final int[] frac = new int[]{2}; if (new ValueDialogInt(getShell(), I18n.E3D_SplitEdges, I18n.E3D_NumberOfFractions) { @Override public void initializeSpinner() { this.spn_Value[0].setMinimum(2); this.spn_Value[0].setMaximum(1000); this.spn_Value[0].setValue(2); } @Override public void applyValue() { frac[0] = this.spn_Value[0].getValue(); } }.open() == OK) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); vm.split(frac[0]); } } } } }); } }); mntm_MergeToAverage[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); vm.merge(MergeTo.AVERAGE, true); return; } } } }); mntm_MergeToLastSelected[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); vm.merge(MergeTo.LAST_SELECTED, true); return; } } } }); mntm_MergeToNearestVertex[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); vm.merge(MergeTo.NEAREST_VERTEX, true); return; } } } }); mntm_MergeToNearestEdge[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); vm.merge(MergeTo.NEAREST_EDGE, true); return; } } } }); mntm_MergeToNearestFace[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); vm.merge(MergeTo.NEAREST_FACE, true); return; } } } }); mntm_SelectSingleVertex[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { final VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); final Set<Vertex> sv = vm.getSelectedVertices(); if (new VertexDialog(getShell()).open() == IDialogConstants.OK_ID) { Vertex v = VertexDialog.getVertex(); if (vm.getVertices().contains(v)) { sv.add(v); vm.syncWithTextEditors(true); } } return; } } } }); mntm_setXYZ[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { Vertex v = null; final VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); final Set<Vertex> sv = vm.getSelectedVertices(); if (VertexManager.getClipboard().size() == 1) { GData vertex = VertexManager.getClipboard().get(0); if (vertex.type() == 0) { String line = vertex.toString(); line = line.replaceAll("\\s+", " ").trim(); //$NON-NLS-1$ //$NON-NLS-2$ String[] data_segments = line.split("\\s+"); //$NON-NLS-1$ if (line.startsWith("0 !LPE")) { //$NON-NLS-1$ if (line.startsWith("VERTEX ", 7)) { //$NON-NLS-1$ Vector3d start = new Vector3d(); boolean numberError = false; if (data_segments.length == 6) { try { start.setX(new BigDecimal(data_segments[3], Threshold.mc)); } catch (NumberFormatException nfe) { numberError = true; } try { start.setY(new BigDecimal(data_segments[4], Threshold.mc)); } catch (NumberFormatException nfe) { numberError = true; } try { start.setZ(new BigDecimal(data_segments[5], Threshold.mc)); } catch (NumberFormatException nfe) { numberError = true; } } else { numberError = true; } if (!numberError) { v = new Vertex(start); } } } } } else if (sv.size() == 1) { v = sv.iterator().next(); } if (new CoordinatesDialog(getShell(), v).open() == IDialogConstants.OK_ID) { vm.addSnapshot(); int coordCount = 0; coordCount += CoordinatesDialog.isX() ? 1 : 0; coordCount += CoordinatesDialog.isY() ? 1 : 0; coordCount += CoordinatesDialog.isZ() ? 1 : 0; if (coordCount == 1 && CoordinatesDialog.getStart() != null) { Vector3d delta = Vector3d.sub(CoordinatesDialog.getEnd(), CoordinatesDialog.getStart()); boolean doMoveOnLine = false; BigDecimal s = BigDecimal.ZERO; Vector3d v1 = CoordinatesDialog.getStart(); Vertex v2 = CoordinatesDialog.getVertex(); if (CoordinatesDialog.isX() && delta.X.compareTo(BigDecimal.ZERO) != 0) { doMoveOnLine = true; s = v2.X.subtract(CoordinatesDialog.getStart().X).divide(delta.X, Threshold.mc); } else if (CoordinatesDialog.isY() && delta.Y.compareTo(BigDecimal.ZERO) != 0) { doMoveOnLine = true; s = v2.Y.subtract(CoordinatesDialog.getStart().Y).divide(delta.Y, Threshold.mc); } else if (CoordinatesDialog.isZ() && delta.Z.compareTo(BigDecimal.ZERO) != 0) { doMoveOnLine = true; s = v2.Z.subtract(CoordinatesDialog.getStart().Z).divide(delta.Z, Threshold.mc); } if (doMoveOnLine) { CoordinatesDialog.setVertex(new Vertex(v1.X.add(delta.X.multiply(s)), v1.Y.add(delta.Y.multiply(s)), v1.Z.add(delta.Z.multiply(s)))); CoordinatesDialog.setX(true); CoordinatesDialog.setY(true); CoordinatesDialog.setZ(true); } } vm.setXyzOrTranslateOrTransform(CoordinatesDialog.getVertex(), null, TransformationMode.SET, CoordinatesDialog.isX(), CoordinatesDialog.isY(), CoordinatesDialog.isZ(), true, true); CoordinatesDialog.setStart(null); CoordinatesDialog.setEnd(null); } return; } } } }); mntm_Translate[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { if (new TranslateDialog(getShell(), null).open() == IDialogConstants.OK_ID) { c3d.getLockableDatFileReference().getVertexManager().addSnapshot(); c3d.getLockableDatFileReference().getVertexManager().setXyzOrTranslateOrTransform(TranslateDialog.getOffset(), null, TransformationMode.TRANSLATE, TranslateDialog.isX(), TranslateDialog.isY(), TranslateDialog.isZ(), isMovingAdjacentData(), true); } return; } } } }); mntm_Rotate[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { TreeSet<Vertex> clipboard = new TreeSet<Vertex>(); if (VertexManager.getClipboard().size() == 1) { GData vertex = VertexManager.getClipboard().get(0); if (vertex.type() == 0) { String line = vertex.toString(); line = line.replaceAll("\\s+", " ").trim(); //$NON-NLS-1$ //$NON-NLS-2$ String[] data_segments = line.split("\\s+"); //$NON-NLS-1$ if (line.startsWith("0 !LPE")) { //$NON-NLS-1$ if (line.startsWith("VERTEX ", 7)) { //$NON-NLS-1$ Vector3d start = new Vector3d(); boolean numberError = false; if (data_segments.length == 6) { try { start.setX(new BigDecimal(data_segments[3], Threshold.mc)); } catch (NumberFormatException nfe) { numberError = true; } try { start.setY(new BigDecimal(data_segments[4], Threshold.mc)); } catch (NumberFormatException nfe) { numberError = true; } try { start.setZ(new BigDecimal(data_segments[5], Threshold.mc)); } catch (NumberFormatException nfe) { numberError = true; } } else { numberError = true; } if (!numberError) { clipboard.add(new Vertex(start)); } } } } } if (new RotateDialog(getShell(), null, clipboard).open() == IDialogConstants.OK_ID) { c3d.getLockableDatFileReference().getVertexManager().addSnapshot(); c3d.getLockableDatFileReference().getVertexManager().setXyzOrTranslateOrTransform(RotateDialog.getAngles(), RotateDialog.getPivot(), TransformationMode.ROTATE, RotateDialog.isX(), RotateDialog.isY(), TranslateDialog.isZ(), isMovingAdjacentData(), true); } return; } } } }); mntm_Scale[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { TreeSet<Vertex> clipboard = new TreeSet<Vertex>(); if (VertexManager.getClipboard().size() == 1) { GData vertex = VertexManager.getClipboard().get(0); if (vertex.type() == 0) { String line = vertex.toString(); line = line.replaceAll("\\s+", " ").trim(); //$NON-NLS-1$ //$NON-NLS-2$ String[] data_segments = line.split("\\s+"); //$NON-NLS-1$ if (line.startsWith("0 !LPE")) { //$NON-NLS-1$ if (line.startsWith("VERTEX ", 7)) { //$NON-NLS-1$ Vector3d start = new Vector3d(); boolean numberError = false; if (data_segments.length == 6) { try { start.setX(new BigDecimal(data_segments[3], Threshold.mc)); } catch (NumberFormatException nfe) { numberError = true; } try { start.setY(new BigDecimal(data_segments[4], Threshold.mc)); } catch (NumberFormatException nfe) { numberError = true; } try { start.setZ(new BigDecimal(data_segments[5], Threshold.mc)); } catch (NumberFormatException nfe) { numberError = true; } } else { numberError = true; } if (!numberError) { clipboard.add(new Vertex(start)); } } } } } if (new ScaleDialog(getShell(), null, clipboard).open() == IDialogConstants.OK_ID) { c3d.getLockableDatFileReference().getVertexManager().addSnapshot(); c3d.getLockableDatFileReference().getVertexManager().setXyzOrTranslateOrTransform(ScaleDialog.getScaleFactors(), ScaleDialog.getPivot(), TransformationMode.SCALE, ScaleDialog.isX(), ScaleDialog.isY(), ScaleDialog.isZ(), isMovingAdjacentData(), true); } return; } } } }); mntm_Edger2[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); if (new EdgerDialog(getShell(), es).open() == IDialogConstants.OK_ID) { vm.addSnapshot(); vm.addEdges(es); } return; } } } }); mntm_Rectifier[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); if (new RectifierDialog(getShell(), rs).open() == IDialogConstants.OK_ID) { vm.addSnapshot(); vm.rectify(rs, true, true); } return; } } } }); mntm_Isecalc[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); if (new IsecalcDialog(getShell(), is).open() == IDialogConstants.OK_ID) { vm.addSnapshot(); vm.isecalc(is); } return; } } } }); mntm_SlicerPro[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); if (new SlicerProDialog(getShell(), ss).open() == IDialogConstants.OK_ID) { vm.addSnapshot(); vm.slicerpro(ss); } return; } } } }); mntm_Intersector[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); if (new IntersectorDialog(getShell(), ins).open() == IDialogConstants.OK_ID) { vm.addSnapshot(); vm.intersector(ins, true); } return; } } } }); mntm_Lines2Pattern[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); if (new Lines2PatternDialog(getShell()).open() == IDialogConstants.OK_ID) { vm.addSnapshot(); vm.lines2pattern(); } return; } } } }); mntm_PathTruder[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); if (new PathTruderDialog(getShell(), ps).open() == IDialogConstants.OK_ID) { vm.addSnapshot(); vm.pathTruder(ps); } return; } } } }); mntm_SymSplitter[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); if (new SymSplitterDialog(getShell(), sims).open() == IDialogConstants.OK_ID) { vm.addSnapshot(); vm.symSplitter(sims); } return; } } } }); mntm_Unificator[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); if (new UnificatorDialog(getShell(), us).open() == IDialogConstants.OK_ID) { vm.addSnapshot(); vm.unificator(us); } return; } } } }); mntm_RingsAndCones[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) { if (new RingsAndConesDialog(getShell(), ris).open() == IDialogConstants.OK_ID) { c3d.getLockableDatFileReference().getVertexManager().addSnapshot(); RingsAndCones.solve(Editor3DWindow.getWindow().getShell(), c3d.getLockableDatFileReference(), cmp_Primitives[0].getPrimitives(), ris, true); } return; } } } }); mntm_TJunctionFinder[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); DatFile df = c3d.getLockableDatFileReference(); if (df.equals(Project.getFileToEdit()) && !df.isReadOnly()) { if (new TJunctionDialog(getShell(), tjs).open() == IDialogConstants.OK_ID) { VertexManager vm = df.getVertexManager(); vm.addSnapshot(); vm.fixTjunctions(tjs.getMode() == 0); } return; } } } }); mntm_MeshReducer[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); DatFile df = c3d.getLockableDatFileReference(); if (df.equals(Project.getFileToEdit()) && !df.isReadOnly()) { VertexManager vm = df.getVertexManager(); vm.addSnapshot(); vm.meshReduce(); return; } } } }); mntm_Txt2Dat[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { DatFile df = c3d.getLockableDatFileReference(); if (df.isReadOnly()) return; VertexManager vm = df.getVertexManager(); vm.addSnapshot(); if (new Txt2DatDialog(getShell(), ts).open() == IDialogConstants.OK_ID && !ts.getText().trim().isEmpty()) { java.awt.Font myFont; if (ts.getFontData() == null) { myFont = new java.awt.Font(org.nschmidt.ldparteditor.enums.Font.MONOSPACE.getFontData()[0].getName(), java.awt.Font.PLAIN, 32); } else { FontData fd = ts.getFontData(); int style = 0; final int c2 = SWT.BOLD | SWT.ITALIC; switch (fd.getStyle()) { case c2: style = java.awt.Font.BOLD | java.awt.Font.ITALIC; break; case SWT.BOLD: style = java.awt.Font.BOLD; break; case SWT.ITALIC: style = java.awt.Font.ITALIC; break; case SWT.NORMAL: style = java.awt.Font.PLAIN; break; } myFont = new java.awt.Font(fd.getName(), style, fd.getHeight()); } GData anchorData = df.getDrawChainTail(); int lineNumber = df.getDrawPerLine_NOCLONE().getKey(anchorData); Set<GData> triangleSet = TextTriangulator.triangulateText(myFont, ts.getText().trim(), ts.getFlatness().doubleValue(), ts.getInterpolateFlatness().doubleValue(), View.DUMMY_REFERENCE, df, ts.getFontHeight().intValue(), ts.getDeltaAngle().doubleValue()); for (GData gda3 : triangleSet) { lineNumber++; df.getDrawPerLine_NOCLONE().put(lineNumber, gda3); GData gdata = gda3; anchorData.setNext(gda3); anchorData = gdata; } anchorData.setNext(null); df.setDrawChainTail(anchorData); vm.setModified(true, true); return; } } } } }); // MARK Options mntm_ResetSettingsOnRestart[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_WARNING | SWT.OK | SWT.CANCEL); messageBox.setText(I18n.DIALOG_Warning); messageBox.setMessage(I18n.E3D_DeleteConfig); int result = messageBox.open(); if (result == SWT.CANCEL) { return; } WorkbenchManager.getUserSettingState().setResetOnStart(true); } }); mntm_CustomiseKeys[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { KeyTableDialog dialog = new KeyTableDialog(getShell()); if (dialog.open() == IDialogConstants.OK_ID) { } } }); mntm_SelectAnotherLDConfig[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { FileDialog fd = new FileDialog(sh, SWT.OPEN); fd.setText(I18n.E3D_OpenLDConfig); fd.setFilterPath(WorkbenchManager.getUserSettingState().getLdrawFolderPath()); String[] filterExt = { "*.ldr", "LDConfig.ldr", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ fd.setFilterExtensions(filterExt); String[] filterNames = { I18n.E3D_LDrawConfigurationFile1, I18n.E3D_LDrawConfigurationFile2, I18n.E3D_AllFiles }; fd.setFilterNames(filterNames); String selected = fd.open(); System.out.println(selected); if (selected != null && View.loadLDConfig(selected)) { GData.CACHE_warningsAndErrors.clear(); WorkbenchManager.getUserSettingState().setLdConfigPath(selected); Set<DatFile> dfs = new HashSet<DatFile>(); for (OpenGLRenderer renderer : renders) { dfs.add(renderer.getC3D().getLockableDatFileReference()); } for (DatFile df : dfs) { df.getVertexManager().addSnapshot(); SubfileCompiler.compile(df, false, false); } } } }); mntm_UploadLogs[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { String source = ""; //$NON-NLS-1$ { UTF8BufferedReader b1 = null, b2 = null; StringBuilder code = new StringBuilder(); File l1 = new File("error_log.txt");//$NON-NLS-1$ File l2 = new File("error_log2.txt");//$NON-NLS-1$ if (l1.exists() || l2.exists()) { try { if (l1.exists()) { b1 = new UTF8BufferedReader("error_log.txt"); //$NON-NLS-1$ String line; while ((line = b1.readLine()) != null) { code.append(line); code.append(StringHelper.getLineDelimiter()); } } if (l2.exists()) { b2 = new UTF8BufferedReader("error_log2.txt"); //$NON-NLS-1$ String line; while ((line = b2.readLine()) != null) { code.append(line); code.append(StringHelper.getLineDelimiter()); } } source = code.toString(); } catch (Exception e1) { if (b1 != null) { try { b1.close(); } catch (Exception consumend) {} } if (b2 != null) { try { b2.close(); } catch (Exception consumend) {} } MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK); messageBox.setText(I18n.DIALOG_Error); messageBox.setMessage(I18n.E3D_LogUploadUnexpectedException); messageBox.open(); return; } finally { if (b1 != null) { try { b1.close(); } catch (Exception consumend) {} } if (b2 != null) { try { b2.close(); } catch (Exception consumend) {} } } } else { MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK); messageBox.setText(I18n.DIALOG_Info); messageBox.setMessage(I18n.E3D_LogUploadNoLogFiles); messageBox.open(); return; } } LogUploadDialog dialog = new LogUploadDialog(getShell(), source); if (dialog.open() == IDialogConstants.OK_ID) { UTF8BufferedReader b1 = null, b2 = null; if (mntm_UploadLogs[0].getData() == null) { mntm_UploadLogs[0].setData(0); } else { int uploadCount = (int) mntm_UploadLogs[0].getData(); uploadCount++; if (uploadCount > 16) { MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK); messageBox.setText(I18n.DIALOG_Warning); messageBox.setMessage(I18n.E3D_LogUploadLimit); messageBox.open(); return; } mntm_UploadLogs[0].setData(uploadCount); } try { Thread.sleep(2000); String url = "http://pastebin.com/api/api_post.php"; //$NON-NLS-1$ String charset = StandardCharsets.UTF_8.name(); // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name() String title = "[LDPartEditor " + I18n.VERSION_Version + "]"; //$NON-NLS-1$ //$NON-NLS-2$ String devKey = "79cf77977cd2d798dd02f07d93b01ddb"; //$NON-NLS-1$ StringBuilder code = new StringBuilder(); File l1 = new File("error_log.txt");//$NON-NLS-1$ File l2 = new File("error_log2.txt");//$NON-NLS-1$ if (l1.exists() || l2.exists()) { if (l1.exists()) { b1 = new UTF8BufferedReader("error_log.txt"); //$NON-NLS-1$ String line; while ((line = b1.readLine()) != null) { code.append(line); code.append(StringHelper.getLineDelimiter()); } } if (l2.exists()) { b2 = new UTF8BufferedReader("error_log2.txt"); //$NON-NLS-1$ String line; while ((line = b2.readLine()) != null) { code.append(line); code.append(StringHelper.getLineDelimiter()); } } String query = String.format("api_option=paste&api_user_key=%s&api_paste_private=%s&api_paste_name=%s&api_dev_key=%s&api_paste_code=%s", //$NON-NLS-1$ URLEncoder.encode("4cc892c8052bd17d805a1a2907ee8014", charset), //$NON-NLS-1$ URLEncoder.encode("0", charset),//$NON-NLS-1$ URLEncoder.encode(title, charset), URLEncoder.encode(devKey, charset), URLEncoder.encode(code.toString(), charset) ); URLConnection connection = new URL(url).openConnection(); connection.setDoOutput(true); // Triggers POST. connection.setRequestProperty("Accept-Charset", charset); //$NON-NLS-1$ connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset); //$NON-NLS-1$ //$NON-NLS-2$ try (OutputStream output = connection.getOutputStream()) { output.write(query.getBytes(charset)); } BufferedReader response =new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); //$NON-NLS-1$ MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK); messageBox.setText(I18n.DIALOG_Info); Object[] messageArguments = {response.readLine()}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.E3D_LogUploadSuccess); messageBox.setMessage(formatter.format(messageArguments)); messageBox.open(); } else { MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK); messageBox.setText(I18n.DIALOG_Info); messageBox.setMessage(I18n.E3D_LogUploadNoLogFiles); messageBox.open(); } } catch (Exception e1) { MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK); messageBox.setText(I18n.DIALOG_Info); messageBox.setMessage(I18n.E3D_LogUploadUnexpectedException); messageBox.open(); } finally { if (b1 != null) { try { b1.close(); } catch (Exception consumend) {} } if (b2 != null) { try { b2.close(); } catch (Exception consumend) {} } } } } }); mntm_SyncWithTextEditor[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { WorkbenchManager.getUserSettingState().getSyncWithTextEditor().set(mntm_SyncWithTextEditor[0].getSelection()); mntm_SyncLpeInline[0].setEnabled(mntm_SyncWithTextEditor[0].getSelection()); } }); mntm_SyncLpeInline[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { WorkbenchManager.getUserSettingState().getSyncWithLpeInline().set(mntm_SyncLpeInline[0].getSelection()); } }); // MARK Merge, split... mntm_Flip[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); vm.flipSelection(); return; } } } }); mntm_SubdivideCatmullClark[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); vm.subdivideCatmullClark(); return; } } } }); mntm_SubdivideLoop[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); vm.addSnapshot(); vm.subdivideLoop(); return; } } } }); // MARK Background PNG btn_PngFocus[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Composite3D c3d = null; for (OpenGLRenderer renderer : renders) { c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { c3d = c3d.getLockableDatFileReference().getLastSelectedComposite(); if (c3d == null) { c3d = renderer.getC3D(); } break; } } if (c3d == null) return; c3d.setClassicPerspective(false); WidgetSelectionHelper.unselectAllChildButtons(c3d.getViewAnglesMenu()); VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); GDataPNG png = vm.getSelectedBgPicture(); if (png == null) { if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) { vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$ vm.setModified(true, true); } vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0)); png = vm.getSelectedBgPicture(); updateBgPictureTab(); } Matrix4f tMatrix = new Matrix4f(); tMatrix.setIdentity(); tMatrix = tMatrix.scale(new Vector3f(png.scale.x, png.scale.y, png.scale.z)); Matrix4f dMatrix = new Matrix4f(); dMatrix.setIdentity(); Matrix4f.rotate((float) (png.angleB.doubleValue() / 180.0 * Math.PI), new Vector3f(1f, 0f, 0f), dMatrix, dMatrix); Matrix4f.rotate((float) (png.angleA.doubleValue() / 180.0 * Math.PI), new Vector3f(0f, 1f, 0f), dMatrix, dMatrix); Matrix4f.mul(dMatrix, tMatrix, tMatrix); Vector4f vx = Matrix4f.transform(dMatrix, new Vector4f(png.offset.x, 0f, 0f, 1f), null); Vector4f vy = Matrix4f.transform(dMatrix, new Vector4f(0f, png.offset.y, 0f, 1f), null); Vector4f vz = Matrix4f.transform(dMatrix, new Vector4f(0f, 0f, png.offset.z, 1f), null); Matrix4f transMatrix = new Matrix4f(); transMatrix.setIdentity(); transMatrix.m30 = -vx.x; transMatrix.m31 = -vx.y; transMatrix.m32 = -vx.z; transMatrix.m30 -= vy.x; transMatrix.m31 -= vy.y; transMatrix.m32 -= vy.z; transMatrix.m30 -= vz.x; transMatrix.m31 -= vz.y; transMatrix.m32 -= vz.z; Matrix4f rotMatrixD = new Matrix4f(); rotMatrixD.setIdentity(); Matrix4f.rotate((float) (png.angleB.doubleValue() / 180.0 * Math.PI), new Vector3f(1f, 0f, 0f), rotMatrixD, rotMatrixD); Matrix4f.rotate((float) (png.angleA.doubleValue() / 180.0 * Math.PI), new Vector3f(0f, 1f, 0f), rotMatrixD, rotMatrixD); rotMatrixD = rotMatrixD.scale(new Vector3f(-1f, 1f, -1f)); rotMatrixD.invert(); c3d.getRotation().load(rotMatrixD); c3d.getTranslation().load(transMatrix); c3d.getPerspectiveCalculator().calculateOriginData(); vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex())); return; } }); btn_PngImage[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); GDataPNG png = vm.getSelectedBgPicture(); if (updatingPngPictureTab) return; if (png == null) { if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeAllTextures(); } vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$ vm.setModified(true, true); } vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0)); png = vm.getSelectedBgPicture(); updateBgPictureTab(); } FileDialog fd = new FileDialog(getShell(), SWT.SAVE); fd.setText(I18n.E3D_OpenPngImage); try { File f = new File(png.texturePath); fd.setFilterPath(f.getParent()); fd.setFileName(f.getName()); } catch (Exception ex) { } String[] filterExt = { "*.png", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$ fd.setFilterExtensions(filterExt); String[] filterNames = { I18n.E3D_PortableNetworkGraphics, I18n.E3D_AllFiles}; fd.setFilterNames(filterNames); String texturePath = fd.open(); if (texturePath != null) { String newText = png.getString(png.offset, png.angleA, png.angleB, png.angleC, png.scale, texturePath); GDataPNG newPngPicture = new GDataPNG(newText, png.offset, png.angleA, png.angleB, png.angleC, png.scale, texturePath); replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference()); pngPictureUpdateCounter++; if (pngPictureUpdateCounter > 3) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeOldTextures(); } pngPictureUpdateCounter = 0; } vm.setModified(true, true); vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex())); } return; } } } }); btn_PngNext[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); DatFile df = c3d.getLockableDatFileReference(); if (df.equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) { VertexManager vm = df.getVertexManager(); GDataPNG sp = vm.getSelectedBgPicture(); boolean noBgPictures = df.hasNoBackgroundPictures(); vm.setSelectedBgPictureIndex(vm.getSelectedBgPictureIndex() + 1); boolean indexOutOfBounds = vm.getSelectedBgPictureIndex() >= df.getBackgroundPictureCount(); boolean noRealData = df.getDrawPerLine_NOCLONE().getKey(sp) == null; if (noBgPictures) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeAllTextures(); } vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$ vm.setModified(true, true); vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0)); } else { if (indexOutOfBounds) vm.setSelectedBgPictureIndex(0); if (noRealData) { vm.setSelectedBgPictureIndex(0); vm.setSelectedBgPicture(df.getBackgroundPicture(0)); } else { vm.setSelectedBgPicture(df.getBackgroundPicture(vm.getSelectedBgPictureIndex())); } } updateBgPictureTab(); } } } }); btn_PngPrevious[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); DatFile df = c3d.getLockableDatFileReference(); if (df.equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) { VertexManager vm = df.getVertexManager(); GDataPNG sp = vm.getSelectedBgPicture(); boolean noBgPictures = df.hasNoBackgroundPictures(); vm.setSelectedBgPictureIndex(vm.getSelectedBgPictureIndex() - 1); boolean indexOutOfBounds = vm.getSelectedBgPictureIndex() < 0; boolean noRealData = df.getDrawPerLine_NOCLONE().getKey(sp) == null; if (noBgPictures) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeAllTextures(); } vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$ vm.setModified(true, true); vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0)); } else { if (indexOutOfBounds) vm.setSelectedBgPictureIndex(df.getBackgroundPictureCount() - 1); if (noRealData) { vm.setSelectedBgPictureIndex(0); vm.setSelectedBgPicture(df.getBackgroundPicture(0)); } else { vm.setSelectedBgPicture(df.getBackgroundPicture(vm.getSelectedBgPictureIndex())); } } updateBgPictureTab(); } } } }); spn_PngA1[0].addValueChangeListener(new ValueChangeAdapter() { @Override public void valueChanged(BigDecimalSpinner spn) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); GDataPNG png = vm.getSelectedBgPicture(); if (updatingPngPictureTab) return; if (png == null) { if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeAllTextures(); } vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$ vm.setModified(true, true); } vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0)); png = vm.getSelectedBgPicture(); updateBgPictureTab(); } String newText = png.getString(png.offset, spn.getValue(), png.angleB, png.angleC, png.scale, png.texturePath); GDataPNG newPngPicture = new GDataPNG(newText, png.offset, spn.getValue(), png.angleB, png.angleC, png.scale, png.texturePath); replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference()); pngPictureUpdateCounter++; if (pngPictureUpdateCounter > 3) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeOldTextures(); } pngPictureUpdateCounter = 0; } vm.setModified(true, true); vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex())); return; } } } }); spn_PngA2[0].addValueChangeListener(new ValueChangeAdapter() { @Override public void valueChanged(BigDecimalSpinner spn) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); GDataPNG png = vm.getSelectedBgPicture(); if (updatingPngPictureTab) return; if (png == null) { if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeAllTextures(); } vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$ vm.setModified(true, true); } vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0)); png = vm.getSelectedBgPicture(); updateBgPictureTab(); } String newText = png.getString(png.offset, png.angleA, spn.getValue(), png.angleC, png.scale, png.texturePath); GDataPNG newPngPicture = new GDataPNG(newText, png.offset, png.angleA, spn.getValue(), png.angleC, png.scale, png.texturePath); replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference()); pngPictureUpdateCounter++; if (pngPictureUpdateCounter > 3) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeOldTextures(); } pngPictureUpdateCounter = 0; } vm.setModified(true, true); vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex())); return; } } } }); spn_PngA3[0].addValueChangeListener(new ValueChangeAdapter() { @Override public void valueChanged(BigDecimalSpinner spn) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); GDataPNG png = vm.getSelectedBgPicture(); if (updatingPngPictureTab) return; if (png == null) { if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeAllTextures(); } vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$ vm.setModified(true, true); } vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0)); png = vm.getSelectedBgPicture(); updateBgPictureTab(); } String newText = png.getString(png.offset, png.angleA, png.angleB, spn.getValue(), png.scale, png.texturePath); GDataPNG newPngPicture = new GDataPNG(newText, png.offset, png.angleA, png.angleB, spn.getValue(), png.scale, png.texturePath); replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference()); pngPictureUpdateCounter++; if (pngPictureUpdateCounter > 3) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeOldTextures(); } pngPictureUpdateCounter = 0; } vm.setModified(true, true); vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex())); return; } } } }); spn_PngSX[0].addValueChangeListener(new ValueChangeAdapter() { @Override public void valueChanged(BigDecimalSpinner spn) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); GDataPNG png = vm.getSelectedBgPicture(); if (updatingPngPictureTab) return; if (png == null) { if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeAllTextures(); } vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$ vm.setModified(true, true); } vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0)); png = vm.getSelectedBgPicture(); updateBgPictureTab(); } Vertex newScale = new Vertex(spn.getValue(), png.scale.Y, png.scale.Z); String newText = png.getString(png.offset, png.angleA, png.angleB, png.angleC, newScale, png.texturePath); GDataPNG newPngPicture = new GDataPNG(newText, png.offset, png.angleA, png.angleB, png.angleC, newScale, png.texturePath); replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference()); pngPictureUpdateCounter++; if (pngPictureUpdateCounter > 3) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeOldTextures(); } pngPictureUpdateCounter = 0; } vm.setModified(true, true); vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex())); return; } } } }); spn_PngSY[0].addValueChangeListener(new ValueChangeAdapter() { @Override public void valueChanged(BigDecimalSpinner spn) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); GDataPNG png = vm.getSelectedBgPicture(); if (updatingPngPictureTab) return; if (png == null) { if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeAllTextures(); } vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$ vm.setModified(true, true); } vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0)); png = vm.getSelectedBgPicture(); updateBgPictureTab(); } Vertex newScale = new Vertex(png.scale.X, spn.getValue(), png.scale.Z); String newText = png.getString(png.offset, png.angleA, png.angleB, png.angleC, newScale, png.texturePath); GDataPNG newPngPicture = new GDataPNG(newText, png.offset, png.angleA, png.angleB, png.angleC, newScale, png.texturePath); replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference()); vm.setModified(true, true); vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex())); return; } } } }); spn_PngX[0].addValueChangeListener(new ValueChangeAdapter() { @Override public void valueChanged(BigDecimalSpinner spn) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); GDataPNG png = vm.getSelectedBgPicture(); if (updatingPngPictureTab) return; if (png == null) { if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeAllTextures(); } vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$ vm.setModified(true, true); } vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0)); png = vm.getSelectedBgPicture(); updateBgPictureTab(); } Vertex newOffset = new Vertex(spn.getValue(), png.offset.Y, png.offset.Z); String newText = png.getString(newOffset, png.angleA, png.angleB, png.angleC, png.scale, png.texturePath); GDataPNG newPngPicture = new GDataPNG(newText, newOffset, png.angleA, png.angleB, png.angleC, png.scale, png.texturePath); replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference()); pngPictureUpdateCounter++; if (pngPictureUpdateCounter > 3) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeOldTextures(); } pngPictureUpdateCounter = 0; } vm.setModified(true, true); vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex())); return; } } } }); spn_PngY[0].addValueChangeListener(new ValueChangeAdapter() { @Override public void valueChanged(BigDecimalSpinner spn) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); GDataPNG png = vm.getSelectedBgPicture(); if (updatingPngPictureTab) return; if (png == null) { if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeAllTextures(); } vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$ vm.setModified(true, true); } vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0)); png = vm.getSelectedBgPicture(); updateBgPictureTab(); } Vertex newOffset = new Vertex(png.offset.X, spn.getValue(), png.offset.Z); String newText = png.getString(newOffset, png.angleA, png.angleB, png.angleC, png.scale, png.texturePath); GDataPNG newPngPicture = new GDataPNG(newText, newOffset, png.angleA, png.angleB, png.angleC, png.scale, png.texturePath); replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference()); pngPictureUpdateCounter++; if (pngPictureUpdateCounter > 3) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeOldTextures(); } pngPictureUpdateCounter = 0; } vm.setModified(true, true); vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex())); return; } } } }); spn_PngZ[0].addValueChangeListener(new ValueChangeAdapter() { @Override public void valueChanged(BigDecimalSpinner spn) { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); GDataPNG png = vm.getSelectedBgPicture(); if (updatingPngPictureTab) return; if (png == null) { if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeAllTextures(); } vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$ vm.setModified(true, true); } vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0)); png = vm.getSelectedBgPicture(); updateBgPictureTab(); } Vertex newOffset = new Vertex(png.offset.X, png.offset.Y, spn.getValue()); String newText = png.getString(newOffset, png.angleA, png.angleB, png.angleC, png.scale, png.texturePath); GDataPNG newPngPicture = new GDataPNG(newText, newOffset, png.angleA, png.angleB, png.angleC, png.scale, png.texturePath); replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference()); pngPictureUpdateCounter++; if (pngPictureUpdateCounter > 3) { for (OpenGLRenderer renderer2 : renders) { renderer2.disposeOldTextures(); } pngPictureUpdateCounter = 0; } vm.setModified(true, true); vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex())); return; } } } }); mntm_IconSize1[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { WorkbenchManager.getUserSettingState().setIconSize(0); } }); mntm_IconSize2[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { WorkbenchManager.getUserSettingState().setIconSize(1); } }); mntm_IconSize3[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { WorkbenchManager.getUserSettingState().setIconSize(2); } }); mntm_IconSize4[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { WorkbenchManager.getUserSettingState().setIconSize(3); } }); mntm_IconSize5[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { WorkbenchManager.getUserSettingState().setIconSize(4); } }); mntm_IconSize6[0].addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { WorkbenchManager.getUserSettingState().setIconSize(5); } }); Project.createDefault(); treeItem_Project[0].setData(Project.getProjectPath()); treeItem_Official[0].setData(WorkbenchManager.getUserSettingState().getLdrawFolderPath()); treeItem_Unofficial[0].setData(WorkbenchManager.getUserSettingState().getUnofficialFolderPath()); try { new ProgressMonitorDialog(Editor3DWindow.getWindow().getShell()).run(true, false, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask(I18n.E3D_LoadingLibrary, IProgressMonitor.UNKNOWN); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { LibraryManager.readUnofficialParts(treeItem_UnofficialParts[0]); LibraryManager.readUnofficialSubparts(treeItem_UnofficialSubparts[0]); LibraryManager.readUnofficialPrimitives(treeItem_UnofficialPrimitives[0]); LibraryManager.readUnofficialHiResPrimitives(treeItem_UnofficialPrimitives48[0]); LibraryManager.readUnofficialLowResPrimitives(treeItem_UnofficialPrimitives8[0]); LibraryManager.readOfficialParts(treeItem_OfficialParts[0]); LibraryManager.readOfficialSubparts(treeItem_OfficialSubparts[0]); LibraryManager.readOfficialPrimitives(treeItem_OfficialPrimitives[0]); LibraryManager.readOfficialHiResPrimitives(treeItem_OfficialPrimitives48[0]); LibraryManager.readOfficialLowResPrimitives(treeItem_OfficialPrimitives8[0]); } }); Thread.sleep(1500); } }); } catch (InvocationTargetException consumed) { } catch (InterruptedException consumed) { } txt_Search[0].setText(" "); //$NON-NLS-1$ txt_Search[0].setText(""); //$NON-NLS-1$ Project.getFileToEdit().setLastSelectedComposite(Editor3DWindow.renders.get(0).getC3D()); new EditorTextWindow().run(Project.getFileToEdit()); updateBgPictureTab(); Project.getFileToEdit().addHistory(); this.open(); // Dispose all resources (never delete this!) ResourceManager.dispose(); SWTResourceManager.dispose(); // Dispose the display (never delete this, too!) Display.getCurrent().dispose(); } protected void addRecentFile(String projectPath) { final int index = recentItems.indexOf(projectPath); if (index > -1) { recentItems.remove(index); } else if (recentItems.size() > 20) { recentItems.remove(0); } recentItems.add(projectPath); } public void addRecentFile(DatFile dat) { addRecentFile(dat.getNewName()); } private void replaceBgPicture(GDataPNG selectedBgPicture, GDataPNG newBgPicture, DatFile linkedDatFile) { if (linkedDatFile.getDrawPerLine_NOCLONE().getKey(selectedBgPicture) == null) return; GData before = selectedBgPicture.getBefore(); GData next = selectedBgPicture.getNext(); int index = linkedDatFile.getDrawPerLine_NOCLONE().getKey(selectedBgPicture); selectedBgPicture.setGoingToBeReplaced(true); linkedDatFile.getVertexManager().remove(selectedBgPicture); linkedDatFile.getDrawPerLine_NOCLONE().put(index, newBgPicture); before.setNext(newBgPicture); newBgPicture.setNext(next); linkedDatFile.getVertexManager().setSelectedBgPicture(newBgPicture); updateBgPictureTab(); return; } private void resetAddState() { setAddingSubfiles(false); setAddingVertices(false); setAddingLines(false); setAddingTriangles(false); setAddingQuads(false); setAddingCondlines(false); for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); DatFile df = c3d.getLockableDatFileReference(); df.setObjVertex1(null); df.setObjVertex2(null); df.setObjVertex3(null); df.setObjVertex4(null); df.setNearestObjVertex1(null); df.setNearestObjVertex2(null); } } public void setAddState(int type) { if (isAddingSomething()) { resetAddState(); btn_AddVertex[0].setSelection(false); btn_AddLine[0].setSelection(false); btn_AddTriangle[0].setSelection(false); btn_AddQuad[0].setSelection(false); btn_AddCondline[0].setSelection(false); btn_AddPrimitive[0].setSelection(false); setAddingSomething(false); } switch (type) { case 0: btn_AddComment[0].notifyListeners(SWT.Selection, new Event()); break; case 1: setAddingVertices(!isAddingVertices()); btn_AddVertex[0].setSelection(isAddingVertices()); setAddingSomething(isAddingVertices()); clickSingleBtn(btn_AddVertex[0]); break; case 2: setAddingLines(!isAddingLines()); btn_AddLine[0].setSelection(isAddingLines()); setAddingSomething(isAddingLines()); clickSingleBtn(btn_AddLine[0]); break; case 3: setAddingTriangles(!isAddingTriangles()); btn_AddTriangle[0].setSelection(isAddingTriangles()); setAddingSomething(isAddingTriangles()); clickSingleBtn(btn_AddTriangle[0]); break; case 4: setAddingQuads(!isAddingQuads()); btn_AddQuad[0].setSelection(isAddingQuads()); setAddingSomething(isAddingQuads()); clickSingleBtn(btn_AddQuad[0]); break; case 5: setAddingCondlines(!isAddingCondlines()); btn_AddCondline[0].setSelection(isAddingCondlines()); setAddingSomething(isAddingCondlines()); clickSingleBtn(btn_AddCondline[0]); break; } } public void setObjMode(int type) { switch (type) { case 0: btn_Vertices[0].setSelection(true); setWorkingType(ObjectMode.VERTICES); clickSingleBtn(btn_Vertices[0]); break; case 1: btn_TrisNQuads[0].setSelection(true); setWorkingType(ObjectMode.FACES); clickSingleBtn(btn_TrisNQuads[0]); break; case 2: btn_Lines[0].setSelection(true); setWorkingType(ObjectMode.LINES); clickSingleBtn(btn_Lines[0]); break; case 3: btn_Subfiles[0].setSelection(true); setWorkingType(ObjectMode.SUBFILES); clickSingleBtn(btn_Subfiles[0]); break; } } /** * The Shell-Close-Event */ @Override protected void handleShellCloseEvent() { boolean unsavedProjectFiles = false; Set<DatFile> unsavedFiles = new HashSet<DatFile>(Project.getUnsavedFiles()); for (DatFile df : unsavedFiles) { if (!df.getText().equals(df.getOriginalText()) || df.isVirtual() && !df.getText().trim().isEmpty()) { MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.CANCEL | SWT.NO); messageBox.setText(I18n.DIALOG_UnsavedChangesTitle); Object[] messageArguments = {df.getShortName()}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.DIALOG_UnsavedChanges); messageBox.setMessage(formatter.format(messageArguments)); int result = messageBox.open(); if (result == SWT.NO) { // Remove file from tree updateTree_removeEntry(df); } else if (result == SWT.YES) { if (df.save()) { Editor3DWindow.getWindow().addRecentFile(df); } else { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK); messageBoxError.setText(I18n.DIALOG_Error); messageBoxError.setMessage(I18n.DIALOG_CantSaveFile); messageBoxError.open(); cleanupClosedData(); updateTree_unsavedEntries(); return; } } else { cleanupClosedData(); updateTree_unsavedEntries(); return; } } } Set<EditorTextWindow> ow = new HashSet<EditorTextWindow>(Project.getOpenTextWindows()); for (EditorTextWindow w : ow) { w.getShell().close(); } { ArrayList<TreeItem> ta = getProjectParts().getItems(); for (TreeItem ti : ta) { unsavedProjectFiles = unsavedProjectFiles || !((DatFile) ti.getData()).getText().trim().equals("") || !Project.getUnsavedFiles().contains(ti.getData()); //$NON-NLS-1$ } } { ArrayList<TreeItem> ta = getProjectSubparts().getItems(); for (TreeItem ti : ta) { unsavedProjectFiles = unsavedProjectFiles || !((DatFile) ti.getData()).getText().trim().equals("") || !Project.getUnsavedFiles().contains(ti.getData()); ; //$NON-NLS-1$ } } { ArrayList<TreeItem> ta = getProjectPrimitives().getItems(); for (TreeItem ti : ta) { unsavedProjectFiles = unsavedProjectFiles || !((DatFile) ti.getData()).getText().trim().equals("") || !Project.getUnsavedFiles().contains(ti.getData()); ; //$NON-NLS-1$ } } { ArrayList<TreeItem> ta = getProjectPrimitives48().getItems(); for (TreeItem ti : ta) { unsavedProjectFiles = unsavedProjectFiles || !((DatFile) ti.getData()).getText().trim().equals("") || !Project.getUnsavedFiles().contains(ti.getData()); ; //$NON-NLS-1$ } } { ArrayList<TreeItem> ta = getProjectPrimitives8().getItems(); for (TreeItem ti : ta) { unsavedProjectFiles = unsavedProjectFiles || !((DatFile) ti.getData()).getText().trim().equals("") || !Project.getUnsavedFiles().contains(ti.getData()); ; //$NON-NLS-1$ } } if (unsavedProjectFiles && Project.isDefaultProject()) { // Save new project here, if the project contains at least one non-empty file boolean cancelIt = false; boolean secondRun = false; while (true) { int result = IDialogConstants.CANCEL_ID; if (secondRun) result = new NewProjectDialog(true).open(); if (result == IDialogConstants.OK_ID) { while (new File(Project.getTempProjectPath()).isDirectory()) { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.YES | SWT.CANCEL | SWT.NO); messageBoxError.setText(I18n.PROJECT_ProjectOverwriteTitle); messageBoxError.setMessage(I18n.PROJECT_ProjectOverwrite); int result2 = messageBoxError.open(); if (result2 == SWT.NO) { result = new NewProjectDialog(true).open(); } else if (result2 == SWT.YES) { break; } else { cancelIt = true; break; } } if (!cancelIt) { Project.setProjectName(Project.getTempProjectName()); Project.setProjectPath(Project.getTempProjectPath()); NLogger.debug(getClass(), "Saving new project..."); //$NON-NLS-1$ if (!Project.save()) { MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK); messageBoxError.setText(I18n.DIALOG_Error); messageBoxError.setMessage(I18n.DIALOG_CantSaveProject); } } break; } else { secondRun = true; MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.CANCEL | SWT.NO); messageBox.setText(I18n.DIALOG_UnsavedChangesTitle); Object[] messageArguments = {I18n.DIALOG_TheNewProject}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.DIALOG_UnsavedChanges); messageBox.setMessage(formatter.format(messageArguments)); int result2 = messageBox.open(); if (result2 == SWT.CANCEL) { cancelIt = true; break; } else if (result2 == SWT.NO) { break; } } } if (cancelIt) { cleanupClosedData(); updateTree_unsavedEntries(); return; } } // NEVER DELETE THIS! final int s = renders.size(); for (int i = 0; i < s; i++) { try { GLCanvas canvas = canvasList.get(i); OpenGLRenderer renderer = renders.get(i); if (!canvas.isCurrent()) { canvas.setCurrent(); try { GLContext.useContext(canvas); } catch (LWJGLException e) { NLogger.error(Editor3DWindow.class, e); } } renderer.dispose(); } catch (SWTException swtEx) { NLogger.error(Editor3DWindow.class, swtEx); } } // All "history threads" needs to know that the main window was closed alive.set(false); final Editor3DWindowState winState = WorkbenchManager.getEditor3DWindowState(); // Traverse the sash forms to store the 3D configuration final ArrayList<Composite3DState> c3dStates = new ArrayList<Composite3DState>(); Control c = Editor3DDesign.getSashForm().getChildren()[1]; if (c != null) { if (c instanceof SashForm|| c instanceof CompositeContainer) { // c instanceof CompositeContainer: Simple case, since its only one 3D view open -> No recursion! saveComposite3DStates(c, c3dStates, "", "|"); //$NON-NLS-1$ //$NON-NLS-2$ } else { // There is no 3D window open at the moment } } else { // There is no 3D window open at the moment } winState.setThreeDwindowConfig(c3dStates); winState.setLeftSashWeights(((SashForm) Editor3DDesign.getSashForm().getChildren()[0]).getWeights()); winState.setLeftSashWidth(Editor3DDesign.getSashForm().getWeights()); winState.setPrimitiveZoom(cmp_Primitives[0].getZoom()); winState.setPrimitiveZoomExponent(cmp_Primitives[0].getZoom_exponent()); winState.setPrimitiveViewport(cmp_Primitives[0].getViewport2()); WorkbenchManager.getUserSettingState().setRecentItems(getRecentItems()); // Save the workbench WorkbenchManager.saveWorkbench(); setReturnCode(CANCEL); close(); } private void saveComposite3DStates(Control c, ArrayList<Composite3DState> c3dStates, String parentPath, String path) { Composite3DState st = new Composite3DState(); st.setParentPath(parentPath); st.setPath(path); if (c instanceof CompositeContainer) { NLogger.debug(getClass(), "{0}C", path); //$NON-NLS-1$ final Composite3D c3d = ((CompositeContainer) c).getComposite3D(); st.setSash(false); st.setScales(c3d.getParent() instanceof CompositeScale); st.setVertical(false); st.setWeights(null); st.setPerspective(c3d.isClassicPerspective() ? c3d.getPerspectiveIndex() : Perspective.TWO_THIRDS); st.setRenderMode(c3d.getRenderMode()); st.setShowLabel(c3d.isShowingLabels()); st.setShowAxis(c3d.isShowingAxis()); st.setShowGrid(c3d.isGridShown()); st.setShowOrigin(c3d.isOriginShown()); st.setLights(c3d.isLightOn()); st.setMeshlines(c3d.isMeshLines()); st.setSubfileMeshlines(c3d.isSubMeshLines()); st.setVertices(c3d.isShowingVertices()); st.setHiddenVertices(c3d.isShowingHiddenVertices()); st.setStudLogo(c3d.isShowingLogo()); st.setLineMode(c3d.getLineMode()); st.setAlwaysBlackLines(c3d.isBlackEdges()); st.setAnaglyph3d(c3d.isAnaglyph3d()); st.setGridScale(c3d.getGrid_scale()); } else if (c instanceof SashForm) { NLogger.debug(getClass(), path); SashForm s = (SashForm) c; st.setSash(true); st.setVertical((s.getStyle() & SWT.VERTICAL) != 0); st.setWeights(s.getWeights()); Control c1 = s.getChildren()[0]; Control c2 = s.getChildren()[1]; saveComposite3DStates(c1, c3dStates, path, path + "s1|"); //$NON-NLS-1$ saveComposite3DStates(c2, c3dStates, path, path + "s2|"); //$NON-NLS-1$ } else { return; } c3dStates.add(st); } /** * @return The serializable window state of the Editor3DWindow */ public Editor3DWindowState getEditor3DWindowState() { return this.editor3DWindowState; } /** * @param editor3DWindowState * The serializable window state of the Editor3DWindow */ public void setEditor3DWindowState(Editor3DWindowState editor3DWindowState) { this.editor3DWindowState = editor3DWindowState; } /** * @return The current Editor3DWindow instance */ public static Editor3DWindow getWindow() { return Editor3DWindow.window; } /** * Updates the tree for new unsaved entries */ public void updateTree_unsavedEntries() { ArrayList<TreeItem> categories = new ArrayList<TreeItem>(); categories.add(this.treeItem_ProjectParts[0]); categories.add(this.treeItem_ProjectSubparts[0]); categories.add(this.treeItem_ProjectPrimitives[0]); categories.add(this.treeItem_ProjectPrimitives48[0]); categories.add(this.treeItem_ProjectPrimitives8[0]); categories.add(this.treeItem_UnofficialParts[0]); categories.add(this.treeItem_UnofficialSubparts[0]); categories.add(this.treeItem_UnofficialPrimitives[0]); categories.add(this.treeItem_UnofficialPrimitives48[0]); categories.add(this.treeItem_UnofficialPrimitives8[0]); int counter = 0; for (TreeItem item : categories) { counter++; ArrayList<TreeItem> datFileTreeItems = item.getItems(); for (TreeItem df : datFileTreeItems) { DatFile d = (DatFile) df.getData(); StringBuilder nameSb = new StringBuilder(new File(d.getNewName()).getName()); final String d2 = d.getDescription(); if (counter < 6 && (!d.getNewName().startsWith(Project.getProjectPath()) || !d.getNewName().replace(Project.getProjectPath() + File.separator, "").contains(File.separator))) { //$NON-NLS-1$ nameSb.insert(0, "(!) "); //$NON-NLS-1$ } // MARK For Debug Only! // DatType t = d.getType(); // if (t == DatType.PART) { // nameSb.append(" PART"); //$NON-NLS-1$ // } else if (t == DatType.SUBPART) { // nameSb.append(" SUBPART"); //$NON-NLS-1$ // } else if (t == DatType.PRIMITIVE) { // nameSb.append(" PRIMITIVE"); //$NON-NLS-1$ // } else if (t == DatType.PRIMITIVE48) { // nameSb.append(" PRIMITIVE48"); //$NON-NLS-1$ // } else if (t == DatType.PRIMITIVE8) { // nameSb.append(" PRIMITIVE8"); //$NON-NLS-1$ // } if (d2 != null) nameSb.append(d2); if (Project.getUnsavedFiles().contains(d)) { df.setText("* " + nameSb.toString()); //$NON-NLS-1$ } else { df.setText(nameSb.toString()); } } } this.treeItem_Unsaved[0].removeAll(); Set<DatFile> unsaved = Project.getUnsavedFiles(); for (DatFile df : unsaved) { TreeItem ti = new TreeItem(this.treeItem_Unsaved[0], SWT.NONE); StringBuilder nameSb = new StringBuilder(new File(df.getNewName()).getName()); final String d = df.getDescription(); if (d != null) nameSb.append(d); ti.setText(nameSb.toString()); ti.setData(df); } this.treeParts[0].build(); this.treeParts[0].redraw(); } /** * Updates the tree for renamed entries */ @SuppressWarnings("unchecked") public void updateTree_renamedEntries() { HashMap<String, TreeItem> categories = new HashMap<String, TreeItem>(); HashMap<String, DatType> types = new HashMap<String, DatType>(); ArrayList<String> validPrefixes = new ArrayList<String>(); { String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "PARTS" + File.separator + "S" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$ validPrefixes.add(s); categories.put(s, this.treeItem_UnofficialSubparts[0]); types.put(s, DatType.SUBPART); } { String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "parts" + File.separator + "s" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$ validPrefixes.add(s); categories.put(s, this.treeItem_UnofficialSubparts[0]); types.put(s, DatType.SUBPART); } { String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "PARTS" + File.separator; //$NON-NLS-1$ validPrefixes.add(s); categories.put(s, this.treeItem_UnofficialParts[0]); types.put(s, DatType.PART); } { String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "parts" + File.separator; //$NON-NLS-1$ validPrefixes.add(s); categories.put(s,this.treeItem_UnofficialParts[0]); types.put(s, DatType.PART); } { String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator + "48" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$ validPrefixes.add(s); categories.put(s, this.treeItem_UnofficialPrimitives48[0]); types.put(s, DatType.PRIMITIVE48); } { String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator + "48" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$ validPrefixes.add(s); categories.put(s, this.treeItem_UnofficialPrimitives48[0]); types.put(s, DatType.PRIMITIVE48); } { String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator + "8" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$ validPrefixes.add(s); categories.put(s, this.treeItem_UnofficialPrimitives8[0]); types.put(s, DatType.PRIMITIVE8); } { String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator + "8" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$ validPrefixes.add(s); categories.put(s, this.treeItem_UnofficialPrimitives8[0]); types.put(s, DatType.PRIMITIVE8); } { String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator; //$NON-NLS-1$ validPrefixes.add(s); categories.put(s, this.treeItem_UnofficialPrimitives[0]); types.put(s, DatType.PRIMITIVE); } { String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator; //$NON-NLS-1$ validPrefixes.add(s); categories.put(s, this.treeItem_UnofficialPrimitives[0]); types.put(s, DatType.PRIMITIVE); } { String s = Project.getProjectPath() + File.separator + "PARTS" + File.separator + "S" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$ validPrefixes.add(s); categories.put(s, this.treeItem_ProjectSubparts[0]); types.put(s, DatType.SUBPART); } { String s = Project.getProjectPath() + File.separator + "parts" + File.separator + "s" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$ validPrefixes.add(s); categories.put(s, this.treeItem_ProjectSubparts[0]); types.put(s, DatType.SUBPART); } { String s = Project.getProjectPath() + File.separator + "PARTS" + File.separator; //$NON-NLS-1$ validPrefixes.add(s); categories.put(s, this.treeItem_ProjectParts[0]); types.put(s, DatType.PART); } { String s = Project.getProjectPath() + File.separator + "parts" + File.separator; //$NON-NLS-1$ validPrefixes.add(s); categories.put(s, this.treeItem_ProjectParts[0]); types.put(s, DatType.PART); } { String s = Project.getProjectPath() + File.separator + "P" + File.separator + "48" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$ validPrefixes.add(s); categories.put(s, this.treeItem_ProjectPrimitives48[0]); types.put(s, DatType.PRIMITIVE48); } { String s = Project.getProjectPath() + File.separator + "p" + File.separator + "48" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$ validPrefixes.add(s); categories.put(s, this.treeItem_ProjectPrimitives48[0]); types.put(s, DatType.PRIMITIVE48); } { String s = Project.getProjectPath() + File.separator + "P" + File.separator + "8" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$ validPrefixes.add(s); categories.put(s, this.treeItem_ProjectPrimitives8[0]); types.put(s, DatType.PRIMITIVE8); } { String s = Project.getProjectPath() + File.separator + "p" + File.separator + "8" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$ validPrefixes.add(s); categories.put(s, this.treeItem_ProjectPrimitives8[0]); types.put(s, DatType.PRIMITIVE8); } { String s = Project.getProjectPath() + File.separator + "P" + File.separator; //$NON-NLS-1$ validPrefixes.add(s); categories.put(s, this.treeItem_ProjectPrimitives[0]); types.put(s, DatType.PRIMITIVE); } { String s = Project.getProjectPath() + File.separator + "p" + File.separator; //$NON-NLS-1$ validPrefixes.add(s); categories.put(s, this.treeItem_ProjectPrimitives[0]); types.put(s, DatType.PRIMITIVE); } Collections.sort(validPrefixes, new Comp()); for (String prefix : validPrefixes) { TreeItem item = categories.get(prefix); ArrayList<DatFile> dats = (ArrayList<DatFile>) item.getData(); ArrayList<TreeItem> datFileTreeItems = item.getItems(); Set<TreeItem> itemsToRemove = new HashSet<TreeItem>(); for (TreeItem df : datFileTreeItems) { DatFile d = (DatFile) df.getData(); String newName = d.getNewName(); String validPrefix = null; for (String p2 : validPrefixes) { if (newName.startsWith(p2)) { validPrefix = p2; break; } } if (validPrefix != null) { TreeItem item2 = categories.get(validPrefix); if (!item2.equals(item)) { itemsToRemove.add(df); dats.remove(d); ((ArrayList<DatFile>) item2.getData()).add(d); TreeItem nt = new TreeItem(item2, SWT.NONE); nt.setText(df.getText()); d.setType(types.get(validPrefix)); nt.setData(d); } } } datFileTreeItems.removeAll(itemsToRemove); } this.treeParts[0].build(); this.treeParts[0].redraw(); } private class Comp implements Comparator<String> { @Override public int compare(String o1, String o2) { if (o1.length() < o2.length()) { return 1; } else if (o1.length() > o2.length()) { return -1; } else { return 0; } } } /** * Removes an item from the tree,<br><br> * If it is open in a {@linkplain Composite3D}, this composite will be linked with a dummy file * If it is open in a {@linkplain CompositeTab}, this composite will be closed * */ public void updateTree_removeEntry(DatFile e) { ArrayList<TreeItem> categories = new ArrayList<TreeItem>(); categories.add(this.treeItem_ProjectParts[0]); categories.add(this.treeItem_ProjectSubparts[0]); categories.add(this.treeItem_ProjectPrimitives[0]); categories.add(this.treeItem_ProjectPrimitives8[0]); categories.add(this.treeItem_ProjectPrimitives48[0]); categories.add(this.treeItem_UnofficialParts[0]); categories.add(this.treeItem_UnofficialSubparts[0]); categories.add(this.treeItem_UnofficialPrimitives[0]); categories.add(this.treeItem_UnofficialPrimitives8[0]); categories.add(this.treeItem_UnofficialPrimitives48[0]); int counter = 0; for (TreeItem item : categories) { counter++; ArrayList<TreeItem> datFileTreeItems = new ArrayList<TreeItem>(item.getItems()); for (TreeItem df : datFileTreeItems) { DatFile d = (DatFile) df.getData(); if (e.equals(d)) { item.getItems().remove(df); } else { StringBuilder nameSb = new StringBuilder(new File(d.getNewName()).getName()); final String d2 = d.getDescription(); if (counter < 6 && (!d.getNewName().startsWith(Project.getProjectPath()) || !d.getNewName().replace(Project.getProjectPath() + File.separator, "").contains(File.separator))) { //$NON-NLS-1$ nameSb.insert(0, "(!) "); //$NON-NLS-1$ } if (d2 != null) nameSb.append(d2); if (Project.getUnsavedFiles().contains(d)) { df.setText("* " + nameSb.toString()); //$NON-NLS-1$ } else { df.setText(nameSb.toString()); } } } } this.treeItem_Unsaved[0].removeAll(); Project.removeUnsavedFile(e); for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(e)) { c3d.unlinkData(); } } HashSet<EditorTextWindow> windows = new HashSet<EditorTextWindow>(Project.getOpenTextWindows()); for (EditorTextWindow win : windows) { win.closeTabWithDatfile(e); } Set<DatFile> unsaved = Project.getUnsavedFiles(); for (DatFile df : unsaved) { TreeItem ti = new TreeItem(this.treeItem_Unsaved[0], SWT.NONE); StringBuilder nameSb = new StringBuilder(new File(df.getNewName()).getName()); final String d = df.getDescription(); if (d != null) nameSb.append(d); ti.setText(nameSb.toString()); ti.setData(df); } TreeItem[] folders = new TreeItem[10]; folders[0] = treeItem_ProjectParts[0]; folders[1] = treeItem_ProjectPrimitives[0]; folders[2] = treeItem_ProjectPrimitives8[0]; folders[3] = treeItem_ProjectPrimitives48[0]; folders[4] = treeItem_ProjectSubparts[0]; folders[5] = treeItem_UnofficialParts[0]; folders[6] = treeItem_UnofficialPrimitives[0]; folders[7] = treeItem_UnofficialPrimitives8[0]; folders[8] = treeItem_UnofficialPrimitives48[0]; folders[9] = treeItem_UnofficialSubparts[0]; for (TreeItem folder : folders) { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences =(ArrayList<DatFile>) folder.getData(); cachedReferences.remove(e); } this.treeParts[0].build(); this.treeParts[0].redraw(); } // Helper functions private void clickBtnTest(Button btn) { WidgetSelectionHelper.unselectAllChildButtons((ToolItem) btn.getParent()); btn.setSelection(true); } private void clickSingleBtn(Button btn) { boolean state = btn.getSelection(); WidgetSelectionHelper.unselectAllChildButtons((ToolItem) btn.getParent()); btn.setSelection(state); } public boolean isAddingSomething() { return addingSomething; } public void setAddingSomething(boolean addingSomething) { this.addingSomething = addingSomething; for (OpenGLRenderer renderer : renders) { renderer.getC3D().getLockableDatFileReference().getVertexManager().clearSelection(); } } public boolean isAddingVertices() { return addingVertices; } public void setAddingVertices(boolean addingVertices) { this.addingVertices = addingVertices; } public boolean isAddingLines() { return addingLines; } public void setAddingLines(boolean addingLines) { this.addingLines = addingLines; } public boolean isAddingTriangles() { return addingTriangles; } public void setAddingTriangles(boolean addingTriangles) { this.addingTriangles = addingTriangles; } public boolean isAddingQuads() { return addingQuads; } public void setAddingQuads(boolean addingQuads) { this.addingQuads = addingQuads; } public boolean isAddingCondlines() { return addingCondlines; } public void setAddingCondlines(boolean addingCondlines) { this.addingCondlines = addingCondlines; } public boolean isAddingSubfiles() { return addingSubfiles; } public void setAddingSubfiles(boolean addingSubfiles) { this.addingSubfiles = addingSubfiles; } public void disableAddAction() { addingSomething = false; addingVertices = false; addingLines = false; addingTriangles = false; addingQuads = false; addingCondlines = false; addingSubfiles = false; btn_AddVertex[0].setSelection(false); btn_AddLine[0].setSelection(false); btn_AddTriangle[0].setSelection(false); btn_AddQuad[0].setSelection(false); btn_AddCondline[0].setSelection(false); btn_AddPrimitive[0].setSelection(false); } public TreeItem getProjectParts() { return treeItem_ProjectParts[0]; } public TreeItem getProjectPrimitives() { return treeItem_ProjectPrimitives[0]; } public TreeItem getProjectPrimitives48() { return treeItem_ProjectPrimitives48[0]; } public TreeItem getProjectPrimitives8() { return treeItem_ProjectPrimitives8[0]; } public TreeItem getProjectSubparts() { return treeItem_ProjectSubparts[0]; } public TreeItem getUnofficialParts() { return treeItem_UnofficialParts[0]; } public TreeItem getUnofficialPrimitives() { return treeItem_UnofficialPrimitives[0]; } public TreeItem getUnofficialPrimitives48() { return treeItem_UnofficialPrimitives48[0]; } public TreeItem getUnofficialPrimitives8() { return treeItem_UnofficialPrimitives8[0]; } public TreeItem getUnofficialSubparts() { return treeItem_UnofficialSubparts[0]; } public TreeItem getOfficialParts() { return treeItem_OfficialParts[0]; } public TreeItem getOfficialPrimitives() { return treeItem_OfficialPrimitives[0]; } public TreeItem getOfficialPrimitives48() { return treeItem_OfficialPrimitives48[0]; } public TreeItem getOfficialPrimitives8() { return treeItem_OfficialPrimitives8[0]; } public TreeItem getOfficialSubparts() { return treeItem_OfficialSubparts[0]; } public TreeItem getUnsaved() { return treeItem_Unsaved[0]; } public ObjectMode getWorkingType() { return workingType; } public void setWorkingType(ObjectMode workingMode) { this.workingType = workingMode; } public boolean isMovingAdjacentData() { return movingAdjacentData; } public void setMovingAdjacentData(boolean movingAdjacentData) { btn_MoveAdjacentData[0].setSelection(movingAdjacentData); this.movingAdjacentData = movingAdjacentData; } public WorkingMode getWorkingAction() { return workingAction; } public void setWorkingAction(WorkingMode workingAction) { this.workingAction = workingAction; switch (workingAction) { case COMBINED: clickBtnTest(btn_Combined[0]); workingAction = WorkingMode.COMBINED; break; case MOVE: clickBtnTest(btn_Move[0]); workingAction = WorkingMode.MOVE; break; case ROTATE: clickBtnTest(btn_Rotate[0]); workingAction = WorkingMode.ROTATE; break; case SCALE: clickBtnTest(btn_Scale[0]); workingAction = WorkingMode.SCALE; break; case SELECT: clickBtnTest(btn_Select[0]); workingAction = WorkingMode.SELECT; break; default: break; } } public ManipulatorScope getTransformationMode() { return transformationMode; } public boolean hasNoTransparentSelection() { return noTransparentSelection; } public void setNoTransparentSelection(boolean noTransparentSelection) { this.noTransparentSelection = noTransparentSelection; } public boolean hasBfcToggle() { return bfcToggle; } public void setBfcToggle(boolean bfcToggle) { this.bfcToggle = bfcToggle; } public GColour getLastUsedColour() { return lastUsedColour; } public void setLastUsedColour(GColour lastUsedColour) { this.lastUsedColour = lastUsedColour; } public void setLastUsedColour2(GColour lastUsedColour) { final int imgSize; switch (Editor3DWindow.getIconsize()) { case 0: imgSize = 16; break; case 1: imgSize = 24; break; case 2: imgSize = 32; break; case 3: imgSize = 48; break; case 4: imgSize = 64; break; case 5: imgSize = 72; break; default: imgSize = 16; break; } final GColour[] gColour2 = new GColour[] { lastUsedColour }; int num = gColour2[0].getColourNumber(); if (View.hasLDConfigColour(num)) { gColour2[0] = View.getLDConfigColour(num); } else { num = -1; } Editor3DWindow.getWindow().setLastUsedColour(gColour2[0]); btn_LastUsedColour[0].removeListener(SWT.Paint, btn_LastUsedColour[0].getListeners(SWT.Paint)[0]); btn_LastUsedColour[0].removeListener(SWT.Selection, btn_LastUsedColour[0].getListeners(SWT.Selection)[0]); final Color col = SWTResourceManager.getColor((int) (gColour2[0].getR() * 255f), (int) (gColour2[0].getG() * 255f), (int) (gColour2[0].getB() * 255f)); final Point size = btn_LastUsedColour[0].computeSize(SWT.DEFAULT, SWT.DEFAULT); final int x = size.x / 4; final int y = size.y / 4; final int w = size.x / 2; final int h = size.y / 2; btn_LastUsedColour[0].addPaintListener(new PaintListener() { @Override public void paintControl(PaintEvent e) { e.gc.setBackground(col); e.gc.fillRectangle(x, y, w, h); if (gColour2[0].getA() == 1f) { e.gc.drawImage(ResourceManager.getImage("icon16_transparent.png"), 0, 0, imgSize, imgSize, x, y, w, h); //$NON-NLS-1$ } else { e.gc.drawImage(ResourceManager.getImage("icon16_halftrans.png"), 0, 0, imgSize, imgSize, x, y, w, h); //$NON-NLS-1$ } } }); btn_LastUsedColour[0].addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { if (Project.getFileToEdit() != null) { Editor3DWindow.getWindow().setLastUsedColour(gColour2[0]); int num = gColour2[0].getColourNumber(); if (!View.hasLDConfigColour(num)) { num = -1; } Project.getFileToEdit().getVertexManager().colourChangeSelection(num, gColour2[0].getR(), gColour2[0].getG(), gColour2[0].getB(), gColour2[0].getA()); } } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); if (num != -1) { Object[] messageArguments = {num, View.getLDConfigColourName(num)}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.EDITORTEXT_Colour1); btn_LastUsedColour[0].setToolTipText(formatter.format(messageArguments)); } else { StringBuilder colourBuilder = new StringBuilder(); colourBuilder.append("0x2"); //$NON-NLS-1$ colourBuilder.append(MathHelper.toHex((int) (255f * gColour2[0].getR())).toUpperCase()); colourBuilder.append(MathHelper.toHex((int) (255f * gColour2[0].getG())).toUpperCase()); colourBuilder.append(MathHelper.toHex((int) (255f * gColour2[0].getB())).toUpperCase()); Object[] messageArguments = {colourBuilder.toString()}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.EDITORTEXT_Colour2); btn_LastUsedColour[0].setToolTipText(formatter.format(messageArguments)); } btn_LastUsedColour[0].redraw(); } public void cleanupClosedData() { Set<DatFile> openFiles = new HashSet<DatFile>(Project.getUnsavedFiles()); for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); openFiles.add(c3d.getLockableDatFileReference()); } for (EditorTextWindow w : Project.getOpenTextWindows()) { for (CTabItem t : w.getTabFolder().getItems()) { openFiles.add(((CompositeTab) t).getState().getFileNameObj()); } } Set<DatFile> deadFiles = new HashSet<DatFile>(Project.getParsedFiles()); deadFiles.removeAll(openFiles); if (!deadFiles.isEmpty()) { GData.CACHE_viewByProjection.clear(); GData.parsedLines.clear(); GData.CACHE_parsedFilesSource.clear(); } for (DatFile datFile : deadFiles) { datFile.disposeData(); } if (!deadFiles.isEmpty()) { // TODO Debug only System.gc(); } } public String getSearchCriteria() { return txt_Search[0].getText(); } public void resetSearch() { search(""); //$NON-NLS-1$ } public void search(final String word) { this.getShell().getDisplay().asyncExec(new Runnable() { @SuppressWarnings("unchecked") @Override public void run() { String criteria = ".*" + word + ".*"; //$NON-NLS-1$ //$NON-NLS-2$ TreeItem[] folders = new TreeItem[15]; folders[0] = treeItem_OfficialParts[0]; folders[1] = treeItem_OfficialPrimitives[0]; folders[2] = treeItem_OfficialPrimitives8[0]; folders[3] = treeItem_OfficialPrimitives48[0]; folders[4] = treeItem_OfficialSubparts[0]; folders[5] = treeItem_UnofficialParts[0]; folders[6] = treeItem_UnofficialPrimitives[0]; folders[7] = treeItem_UnofficialPrimitives8[0]; folders[8] = treeItem_UnofficialPrimitives48[0]; folders[9] = treeItem_UnofficialSubparts[0]; folders[10] = treeItem_ProjectParts[0]; folders[11] = treeItem_ProjectPrimitives[0]; folders[12] = treeItem_ProjectPrimitives8[0]; folders[13] = treeItem_ProjectPrimitives48[0]; folders[14] = treeItem_ProjectSubparts[0]; if (folders[0].getData() == null) { for (TreeItem folder : folders) { folder.setData(new ArrayList<DatFile>()); for (TreeItem part : folder.getItems()) { ((ArrayList<DatFile>) folder.getData()).add((DatFile) part.getData()); } } } try { "42".matches(criteria); //$NON-NLS-1$ } catch (Exception ex) { criteria = ".*"; //$NON-NLS-1$ } final Pattern pattern = Pattern.compile(criteria); for (int i = 0; i < 15; i++) { TreeItem folder = folders[i]; folder.removeAll(); for (DatFile part : (ArrayList<DatFile>) folder.getData()) { StringBuilder nameSb = new StringBuilder(new File(part.getNewName()).getName()); if (i > 9 && (!part.getNewName().startsWith(Project.getProjectPath()) || !part.getNewName().replace(Project.getProjectPath() + File.separator, "").contains(File.separator))) { //$NON-NLS-1$ nameSb.insert(0, "(!) "); //$NON-NLS-1$ } final String d = part.getDescription(); if (d != null) nameSb.append(d); String name = nameSb.toString(); TreeItem finding = new TreeItem(folder, SWT.NONE); // Save the path finding.setData(part); // Set the filename if (Project.getUnsavedFiles().contains(part) || !part.getOldName().equals(part.getNewName())) { // Insert asterisk if the file was // modified finding.setText("* " + name); //$NON-NLS-1$ } else { finding.setText(name); } finding.setShown(!(d != null && d.startsWith(" - ~Moved to")) && pattern.matcher(name).matches()); //$NON-NLS-1$ } } folders[0].getParent().build(); folders[0].getParent().redraw(); folders[0].getParent().update(); } }); } public void closeAllComposite3D() { ArrayList<OpenGLRenderer> renders2 = new ArrayList<OpenGLRenderer>(renders); for (OpenGLRenderer renderer : renders2) { Composite3D c3d = renderer.getC3D(); c3d.getModifier().closeView(); } } public TreeData getDatFileTreeData(DatFile df) { TreeData result = new TreeData(); ArrayList<TreeItem> categories = new ArrayList<TreeItem>(); categories.add(this.treeItem_ProjectParts[0]); categories.add(this.treeItem_ProjectSubparts[0]); categories.add(this.treeItem_ProjectPrimitives[0]); categories.add(this.treeItem_ProjectPrimitives48[0]); categories.add(this.treeItem_ProjectPrimitives8[0]); categories.add(this.treeItem_UnofficialParts[0]); categories.add(this.treeItem_UnofficialSubparts[0]); categories.add(this.treeItem_UnofficialPrimitives[0]); categories.add(this.treeItem_UnofficialPrimitives48[0]); categories.add(this.treeItem_UnofficialPrimitives8[0]); categories.add(this.treeItem_OfficialParts[0]); categories.add(this.treeItem_OfficialSubparts[0]); categories.add(this.treeItem_OfficialPrimitives[0]); categories.add(this.treeItem_OfficialPrimitives48[0]); categories.add(this.treeItem_OfficialPrimitives8[0]); categories.add(this.treeItem_Unsaved[0]); for (TreeItem item : categories) { ArrayList<TreeItem> datFileTreeItems = item.getItems(); for (TreeItem ti : datFileTreeItems) { DatFile d = (DatFile) ti.getData(); if (df.equals(d)) { result.setLocation(ti); } else if (d.getShortName().equals(df.getShortName())) { result.getLocationsWithSameShortFilenames().add(ti); } } } return result; } /** * Updates the background picture tab */ public void updateBgPictureTab() { for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) { VertexManager vm = c3d.getLockableDatFileReference().getVertexManager(); GDataPNG png = vm.getSelectedBgPicture(); if (png == null) { updatingPngPictureTab = true; txt_PngPath[0].setText("---"); //$NON-NLS-1$ txt_PngPath[0].setToolTipText("---"); //$NON-NLS-1$ spn_PngX[0].setValue(BigDecimal.ZERO); spn_PngY[0].setValue(BigDecimal.ZERO); spn_PngZ[0].setValue(BigDecimal.ZERO); spn_PngA1[0].setValue(BigDecimal.ZERO); spn_PngA2[0].setValue(BigDecimal.ZERO); spn_PngA3[0].setValue(BigDecimal.ZERO); spn_PngSX[0].setValue(BigDecimal.ONE); spn_PngSY[0].setValue(BigDecimal.ONE); txt_PngPath[0].setEnabled(false); btn_PngFocus[0].setEnabled(false); btn_PngImage[0].setEnabled(false); spn_PngX[0].setEnabled(false); spn_PngY[0].setEnabled(false); spn_PngZ[0].setEnabled(false); spn_PngA1[0].setEnabled(false); spn_PngA2[0].setEnabled(false); spn_PngA3[0].setEnabled(false); spn_PngSX[0].setEnabled(false); spn_PngSY[0].setEnabled(false); spn_PngA1[0].getParent().update(); updatingPngPictureTab = false; return; } updatingPngPictureTab = true; txt_PngPath[0].setEnabled(true); btn_PngFocus[0].setEnabled(true); btn_PngImage[0].setEnabled(true); spn_PngX[0].setEnabled(true); spn_PngY[0].setEnabled(true); spn_PngZ[0].setEnabled(true); spn_PngA1[0].setEnabled(true); spn_PngA2[0].setEnabled(true); spn_PngA3[0].setEnabled(true); spn_PngSX[0].setEnabled(true); spn_PngSY[0].setEnabled(true); txt_PngPath[0].setText(png.texturePath); txt_PngPath[0].setToolTipText(png.texturePath); spn_PngX[0].setValue(png.offset.X); spn_PngY[0].setValue(png.offset.Y); spn_PngZ[0].setValue(png.offset.Z); spn_PngA1[0].setValue(png.angleA); spn_PngA2[0].setValue(png.angleB); spn_PngA3[0].setValue(png.angleC); spn_PngSX[0].setValue(png.scale.X); spn_PngSY[0].setValue(png.scale.Y); spn_PngA1[0].getParent().update(); updatingPngPictureTab = false; return; } } } public void unselectAddSubfile() { resetAddState(); btn_AddPrimitive[0].setSelection(false); setAddingSubfiles(false); setAddingSomething(false); } public DatFile createNewDatFile(Shell sh, OpenInWhat where) { FileDialog fd = new FileDialog(sh, SWT.SAVE); fd.setText(I18n.E3D_CreateNewDat); if ("project".equals(Project.getProjectPath())) { //$NON-NLS-1$ try { String path = LDPartEditor.class.getProtectionDomain().getCodeSource().getLocation().getPath(); String decodedPath = URLDecoder.decode(path, "UTF-8"); //$NON-NLS-1$ decodedPath = decodedPath.substring(0, decodedPath.length() - 4); fd.setFilterPath(decodedPath + "project"); //$NON-NLS-1$ } catch (Exception consumed) { fd.setFilterPath(Project.getProjectPath()); } } else { fd.setFilterPath(Project.getProjectPath()); } String[] filterExt = { "*.dat", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$ fd.setFilterExtensions(filterExt); String[] filterNames = { I18n.E3D_LDrawSourceFile, I18n.E3D_AllFiles }; fd.setFilterNames(filterNames); while (true) { String selected = fd.open(); System.out.println(selected); if (selected != null) { // Check if its already created DatFile df = new DatFile(selected); if (isFileNameAllocated(selected, df, true)) { MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.RETRY | SWT.CANCEL); messageBox.setText(I18n.DIALOG_AlreadyAllocatedNameTitle); messageBox.setMessage(I18n.DIALOG_AlreadyAllocatedName); int result = messageBox.open(); if (result == SWT.CANCEL) { break; } } else { TreeItem ti = new TreeItem(this.treeItem_ProjectParts[0], SWT.NONE); StringBuilder nameSb = new StringBuilder(new File(df.getNewName()).getName()); nameSb.append(I18n.E3D_NewFile); ti.setText(nameSb.toString()); ti.setData(df); @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectParts[0].getData(); cachedReferences.add(df); Project.addUnsavedFile(df); updateTree_renamedEntries(); updateTree_unsavedEntries(); openDatFile(df, where, null); return df; } } else { break; } } return null; } public DatFile openDatFile(Shell sh, OpenInWhat where, String filePath) { FileDialog fd = new FileDialog(sh, SWT.OPEN); fd.setText(I18n.E3D_OpenDatFile); if ("project".equals(Project.getProjectPath())) { //$NON-NLS-1$ try { String path = LDPartEditor.class.getProtectionDomain().getCodeSource().getLocation().getPath(); String decodedPath = URLDecoder.decode(path, "UTF-8"); //$NON-NLS-1$ decodedPath = decodedPath.substring(0, decodedPath.length() - 4); fd.setFilterPath(decodedPath + "project"); //$NON-NLS-1$ } catch (Exception consumed) { fd.setFilterPath(Project.getProjectPath()); } } else { fd.setFilterPath(Project.getProjectPath()); } String[] filterExt = { "*.dat", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$ fd.setFilterExtensions(filterExt); String[] filterNames = {I18n.E3D_LDrawSourceFile, I18n.E3D_AllFiles}; fd.setFilterNames(filterNames); String selected = filePath == null ? fd.open() : filePath; System.out.println(selected); if (selected != null) { // Check if its already created DatType type = DatType.PART; DatFile df = new DatFile(selected); DatFile original = isFileNameAllocated2(selected, df); if (original == null) { // Type Check and Description Parsing!! StringBuilder titleSb = new StringBuilder(); UTF8BufferedReader reader = null; File f = new File(selected); try { reader = new UTF8BufferedReader(f.getAbsolutePath()); String title = reader.readLine(); if (title != null) { title = title.trim(); if (title.length() > 0) { titleSb.append(" -"); //$NON-NLS-1$ titleSb.append(title.substring(1)); } } while (true) { String typ = reader.readLine(); if (typ != null) { typ = typ.trim(); if (!typ.startsWith("0")) { //$NON-NLS-1$ break; } else { int i1 = typ.indexOf("!LDRAW_ORG"); //$NON-NLS-1$ if (i1 > -1) { int i2; i2 = typ.indexOf("Subpart"); //$NON-NLS-1$ if (i2 > -1 && i1 < i2) { type = DatType.SUBPART; break; } i2 = typ.indexOf("Part"); //$NON-NLS-1$ if (i2 > -1 && i1 < i2) { type = DatType.PART; break; } i2 = typ.indexOf("48_Primitive"); //$NON-NLS-1$ if (i2 > -1 && i1 < i2) { type = DatType.PRIMITIVE48; break; } i2 = typ.indexOf("8_Primitive"); //$NON-NLS-1$ if (i2 > -1 && i1 < i2) { type = DatType.PRIMITIVE8; break; } i2 = typ.indexOf("Primitive"); //$NON-NLS-1$ if (i2 > -1 && i1 < i2) { type = DatType.PRIMITIVE; break; } } } } else { break; } } } catch (LDParsingException e) { } catch (FileNotFoundException e) { } catch (UnsupportedEncodingException e) { } finally { try { if (reader != null) reader.close(); } catch (LDParsingException e1) { } } df = new DatFile(selected, titleSb.toString(), false, type); df.setProjectFile(df.getNewName().startsWith(Project.getProjectPath())); } else { df.setProjectFile(df.getNewName().startsWith(Project.getProjectPath())); if (original.isProjectFile()) { openDatFile(df, where, null); return df; } { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectParts[0].getData(); if (cachedReferences.contains(df)) { openDatFile(df, where, null); return df; } } { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectSubparts[0].getData(); if (cachedReferences.contains(df)) { openDatFile(df, where, null); return df; } } { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectPrimitives[0].getData(); if (cachedReferences.contains(df)) { openDatFile(df, where, null); return df; } } { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectPrimitives48[0].getData(); if (cachedReferences.contains(df)) { openDatFile(df, where, null); return df; } } { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectPrimitives8[0].getData(); if (cachedReferences.contains(df)) { openDatFile(df, where, null); return df; } } type = original.getType(); df = original; } TreeItem ti; switch (type) { case PART: { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectParts[0].getData(); cachedReferences.add(df); } ti = new TreeItem(this.treeItem_ProjectParts[0], SWT.NONE); break; case SUBPART: { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectSubparts[0].getData(); cachedReferences.add(df); } ti = new TreeItem(this.treeItem_ProjectSubparts[0], SWT.NONE); break; case PRIMITIVE: { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectPrimitives[0].getData(); cachedReferences.add(df); } ti = new TreeItem(this.treeItem_ProjectPrimitives[0], SWT.NONE); break; case PRIMITIVE48: { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectPrimitives48[0].getData(); cachedReferences.add(df); } ti = new TreeItem(this.treeItem_ProjectPrimitives48[0], SWT.NONE); break; case PRIMITIVE8: { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectPrimitives8[0].getData(); cachedReferences.add(df); } ti = new TreeItem(this.treeItem_ProjectPrimitives8[0], SWT.NONE); break; default: { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectParts[0].getData(); cachedReferences.add(df); } ti = new TreeItem(this.treeItem_ProjectParts[0], SWT.NONE); break; } StringBuilder nameSb = new StringBuilder(new File(df.getNewName()).getName()); nameSb.append(I18n.E3D_NewFile); ti.setText(nameSb.toString()); ti.setData(df); updateTree_unsavedEntries(); openDatFile(df, where, null); return df; } return null; } public boolean openDatFile(DatFile df, OpenInWhat where, EditorTextWindow tWin) { if (where == OpenInWhat.EDITOR_3D || where == OpenInWhat.EDITOR_TEXT_AND_3D) { if (renders.isEmpty()) { if ("%EMPTY%".equals(Editor3DWindow.getSashForm().getChildren()[1].getData())) { //$NON-NLS-1$ int[] mainSashWeights = Editor3DWindow.getSashForm().getWeights(); Editor3DWindow.getSashForm().getChildren()[1].dispose(); CompositeContainer cmp_Container = new CompositeContainer(Editor3DWindow.getSashForm(), false); cmp_Container.moveBelow(Editor3DWindow.getSashForm().getChildren()[0]); df.parseForData(true); Project.setFileToEdit(df); cmp_Container.getComposite3D().setLockableDatFileReference(df); cmp_Container.getComposite3D().getModifier().zoomToFit(); Editor3DWindow.getSashForm().getParent().layout(); Editor3DWindow.getSashForm().setWeights(mainSashWeights); } } else { boolean canUpdate = false; for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (!c3d.isDatFileLockedOnDisplay()) { canUpdate = true; break; } } if (canUpdate) { final VertexManager vm = df.getVertexManager(); if (vm.isModified()) { df.setText(df.getText()); } df.parseForData(true); Project.setFileToEdit(df); for (OpenGLRenderer renderer : renders) { Composite3D c3d = renderer.getC3D(); if (!c3d.isDatFileLockedOnDisplay()) { c3d.setLockableDatFileReference(df); c3d.getModifier().zoomToFit(); } } } } } if (where == OpenInWhat.EDITOR_TEXT || where == OpenInWhat.EDITOR_TEXT_AND_3D) { for (EditorTextWindow w : Project.getOpenTextWindows()) { for (CTabItem t : w.getTabFolder().getItems()) { if (df.equals(((CompositeTab) t).getState().getFileNameObj())) { w.getTabFolder().setSelection(t); ((CompositeTab) t).getControl().getShell().forceActive(); w.open(); return w == tWin; } } } if (tWin == null) { // Project.getParsedFiles().add(df); IS NECESSARY HERE Project.getParsedFiles().add(df); new EditorTextWindow().run(df); } } return false; } public void disableSelectionTab() { if (Thread.currentThread() == Display.getDefault().getThread()) { updatingSelectionTab = true; txt_Line[0].setText(""); //$NON-NLS-1$ spn_SelectionX1[0].setEnabled(false); spn_SelectionY1[0].setEnabled(false); spn_SelectionZ1[0].setEnabled(false); spn_SelectionX2[0].setEnabled(false); spn_SelectionY2[0].setEnabled(false); spn_SelectionZ2[0].setEnabled(false); spn_SelectionX3[0].setEnabled(false); spn_SelectionY3[0].setEnabled(false); spn_SelectionZ3[0].setEnabled(false); spn_SelectionX4[0].setEnabled(false); spn_SelectionY4[0].setEnabled(false); spn_SelectionZ4[0].setEnabled(false); spn_SelectionX1[0].setValue(BigDecimal.ZERO); spn_SelectionY1[0].setValue(BigDecimal.ZERO); spn_SelectionZ1[0].setValue(BigDecimal.ZERO); spn_SelectionX2[0].setValue(BigDecimal.ZERO); spn_SelectionY2[0].setValue(BigDecimal.ZERO); spn_SelectionZ2[0].setValue(BigDecimal.ZERO); spn_SelectionX3[0].setValue(BigDecimal.ZERO); spn_SelectionY3[0].setValue(BigDecimal.ZERO); spn_SelectionZ3[0].setValue(BigDecimal.ZERO); spn_SelectionX4[0].setValue(BigDecimal.ZERO); spn_SelectionY4[0].setValue(BigDecimal.ZERO); spn_SelectionZ4[0].setValue(BigDecimal.ZERO); lbl_SelectionX1[0].setText(I18n.E3D_PositionX1); lbl_SelectionY1[0].setText(I18n.E3D_PositionY1); lbl_SelectionZ1[0].setText(I18n.E3D_PositionZ1); lbl_SelectionX2[0].setText(I18n.E3D_PositionX2); lbl_SelectionY2[0].setText(I18n.E3D_PositionY2); lbl_SelectionZ2[0].setText(I18n.E3D_PositionZ2); lbl_SelectionX3[0].setText(I18n.E3D_PositionX3); lbl_SelectionY3[0].setText(I18n.E3D_PositionY3); lbl_SelectionZ3[0].setText(I18n.E3D_PositionZ3); lbl_SelectionX4[0].setText(I18n.E3D_PositionX4); lbl_SelectionY4[0].setText(I18n.E3D_PositionY4); lbl_SelectionZ4[0].setText(I18n.E3D_PositionZ4); updatingSelectionTab = false; } else { NLogger.error(getClass(), new SWTException(SWT.ERROR_THREAD_INVALID_ACCESS, "A wrong thread tries to access the GUI!")); //$NON-NLS-1$ Display.getDefault().asyncExec(new Runnable() { @Override public void run() { try { updatingSelectionTab = true; txt_Line[0].setText(""); //$NON-NLS-1$ spn_SelectionX1[0].setEnabled(false); spn_SelectionY1[0].setEnabled(false); spn_SelectionZ1[0].setEnabled(false); spn_SelectionX2[0].setEnabled(false); spn_SelectionY2[0].setEnabled(false); spn_SelectionZ2[0].setEnabled(false); spn_SelectionX3[0].setEnabled(false); spn_SelectionY3[0].setEnabled(false); spn_SelectionZ3[0].setEnabled(false); spn_SelectionX4[0].setEnabled(false); spn_SelectionY4[0].setEnabled(false); spn_SelectionZ4[0].setEnabled(false); spn_SelectionX1[0].setValue(BigDecimal.ZERO); spn_SelectionY1[0].setValue(BigDecimal.ZERO); spn_SelectionZ1[0].setValue(BigDecimal.ZERO); spn_SelectionX2[0].setValue(BigDecimal.ZERO); spn_SelectionY2[0].setValue(BigDecimal.ZERO); spn_SelectionZ2[0].setValue(BigDecimal.ZERO); spn_SelectionX3[0].setValue(BigDecimal.ZERO); spn_SelectionY3[0].setValue(BigDecimal.ZERO); spn_SelectionZ3[0].setValue(BigDecimal.ZERO); spn_SelectionX4[0].setValue(BigDecimal.ZERO); spn_SelectionY4[0].setValue(BigDecimal.ZERO); spn_SelectionZ4[0].setValue(BigDecimal.ZERO); lbl_SelectionX1[0].setText(I18n.E3D_PositionX1); lbl_SelectionY1[0].setText(I18n.E3D_PositionY1); lbl_SelectionZ1[0].setText(I18n.E3D_PositionZ1); lbl_SelectionX2[0].setText(I18n.E3D_PositionX2); lbl_SelectionY2[0].setText(I18n.E3D_PositionY2); lbl_SelectionZ2[0].setText(I18n.E3D_PositionZ2); lbl_SelectionX3[0].setText(I18n.E3D_PositionX3); lbl_SelectionY3[0].setText(I18n.E3D_PositionY3); lbl_SelectionZ3[0].setText(I18n.E3D_PositionZ3); lbl_SelectionX4[0].setText(I18n.E3D_PositionX4); lbl_SelectionY4[0].setText(I18n.E3D_PositionY4); lbl_SelectionZ4[0].setText(I18n.E3D_PositionZ4); updatingSelectionTab = false; } catch (Exception ex) { NLogger.error(getClass(), ex); } } }); } } public static ArrayList<OpenGLRenderer> getRenders() { return renders; } public SearchWindow getSearchWindow() { return searchWindow; } public void setSearchWindow(SearchWindow searchWindow) { this.searchWindow = searchWindow; } public SelectorSettings loadSelectorSettings() { sels.setColour(mntm_WithSameColour[0].getSelection()); sels.setEdgeStop(mntm_StopAtEdges[0].getSelection()); sels.setHidden(mntm_WithHiddenData[0].getSelection()); sels.setNoSubfiles(mntm_ExceptSubfiles[0].getSelection()); sels.setOrientation(mntm_WithSameOrientation[0].getSelection()); sels.setDistance(mntm_WithAccuracy[0].getSelection()); sels.setWholeSubfiles(mntm_WithWholeSubfiles[0].getSelection()); sels.setVertices(mntm_SVertices[0].getSelection()); sels.setLines(mntm_SLines[0].getSelection()); sels.setTriangles(mntm_STriangles[0].getSelection()); sels.setQuads(mntm_SQuads[0].getSelection()); sels.setCondlines(mntm_SCLines[0].getSelection()); return sels; } public boolean isFileNameAllocated(String dir, DatFile df, boolean createNew) { TreeItem[] folders = new TreeItem[15]; folders[0] = treeItem_OfficialParts[0]; folders[1] = treeItem_OfficialPrimitives[0]; folders[2] = treeItem_OfficialPrimitives8[0]; folders[3] = treeItem_OfficialPrimitives48[0]; folders[4] = treeItem_OfficialSubparts[0]; folders[5] = treeItem_UnofficialParts[0]; folders[6] = treeItem_UnofficialPrimitives[0]; folders[7] = treeItem_UnofficialPrimitives8[0]; folders[8] = treeItem_UnofficialPrimitives48[0]; folders[9] = treeItem_UnofficialSubparts[0]; folders[10] = treeItem_ProjectParts[0]; folders[11] = treeItem_ProjectPrimitives[0]; folders[12] = treeItem_ProjectPrimitives8[0]; folders[13] = treeItem_ProjectPrimitives48[0]; folders[14] = treeItem_ProjectSubparts[0]; for (TreeItem folder : folders) { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences =(ArrayList<DatFile>) folder.getData(); for (DatFile d : cachedReferences) { if (createNew || !df.equals(d)) { if (dir.equals(d.getOldName()) || dir.equals(d.getNewName())) { return true; } } } } return false; } private DatFile isFileNameAllocated2(String dir, DatFile df) { TreeItem[] folders = new TreeItem[15]; folders[0] = treeItem_OfficialParts[0]; folders[1] = treeItem_OfficialPrimitives[0]; folders[2] = treeItem_OfficialPrimitives8[0]; folders[3] = treeItem_OfficialPrimitives48[0]; folders[4] = treeItem_OfficialSubparts[0]; folders[5] = treeItem_UnofficialParts[0]; folders[6] = treeItem_UnofficialPrimitives[0]; folders[7] = treeItem_UnofficialPrimitives8[0]; folders[8] = treeItem_UnofficialPrimitives48[0]; folders[9] = treeItem_UnofficialSubparts[0]; folders[10] = treeItem_ProjectParts[0]; folders[11] = treeItem_ProjectPrimitives[0]; folders[12] = treeItem_ProjectPrimitives8[0]; folders[13] = treeItem_ProjectPrimitives48[0]; folders[14] = treeItem_ProjectSubparts[0]; for (TreeItem folder : folders) { @SuppressWarnings("unchecked") ArrayList<DatFile> cachedReferences =(ArrayList<DatFile>) folder.getData(); for (DatFile d : cachedReferences) { if (dir.equals(d.getOldName()) || dir.equals(d.getNewName())) { return d; } } } return null; } public void updatePrimitiveLabel(Primitive p) { if (lbl_selectedPrimitiveItem[0] == null) return; if (p == null) { lbl_selectedPrimitiveItem[0].setText(I18n.E3D_NoPrimitiveSelected); } else { lbl_selectedPrimitiveItem[0].setText(p.toString()); } lbl_selectedPrimitiveItem[0].getParent().layout(); } public CompositePrimitive getCompositePrimitive() { return cmp_Primitives[0]; } public static AtomicBoolean getAlive() { return alive; } public MenuItem getMntmWithSameColour() { return mntm_WithSameColour[0]; } public ArrayList<String> getRecentItems() { return recentItems; } private void setLineSize(Sphere sp, Sphere sp_inv, float line_width1000, float line_width, float line_width_gl, Button btn) { GLPrimitives.SPHERE = sp; GLPrimitives.SPHERE_INV = sp_inv; View.lineWidth1000[0] = line_width1000; View.lineWidth[0] = line_width; View.lineWidthGL[0] = line_width_gl; Set<DatFile> dfs = new HashSet<DatFile>(); for (OpenGLRenderer renderer : renders) { dfs.add(renderer.getC3D().getLockableDatFileReference()); } for (DatFile df : dfs) { df.getVertexManager().addSnapshot(); SubfileCompiler.compile(df, false, false); } clickSingleBtn(btn); } }
Prepared fix for issue #139.
src/org/nschmidt/ldparteditor/shells/editor3d/Editor3DWindow.java
Prepared fix for issue #139.
<ide><path>rc/org/nschmidt/ldparteditor/shells/editor3d/Editor3DWindow.java <ide> loadSelectorSettings(); <ide> vm.selector(sels); <ide> vm.syncWithTextEditors(true); <add> return; <ide> } <ide> } <ide> } <ide> loadSelectorSettings(); <ide> vm.selector(sels); <ide> vm.syncWithTextEditors(true); <add> return; <ide> } <ide> } <ide> } <ide> loadSelectorSettings(); <ide> vm.selector(sels); <ide> vm.syncWithTextEditors(true); <add> return; <ide> } <ide> } <ide> }
Java
apache-2.0
b89635527319718e2f3b3bf2bf4b725c9b988dbb
0
markzhai/init
package cn.zhaiyifan.init; import android.content.Context; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * <p>Entry to add, start and manage init flow.</p> * Created by mark.zhai on 2015/10/2. */ public class Init { private static final int DEFAULT_THREAD_POOL_SIZE = 8; private static Map<String, Flow> sFlowMap = new HashMap<>(); private static Context sContext; private static int mThreadPoolSize = DEFAULT_THREAD_POOL_SIZE; /** * Init with context. * * @param context application context */ public static void init(Context context) { sContext = context; } /** * Init with context and log class. * * @param context application context * @param logProxy log class implements {@link ILog} */ public static void init(Context context, ILog logProxy) { sContext = context; LogImpl.setLogProxy(logProxy); } /** * Add flow to let Init manage. * * @param flow flow which unique name */ public static void addFlow(Flow flow) { sFlowMap.put(flow.getName(), flow); } /** * Add flow map to let Init manage. * * @param flowMap map which contains flow-name to flow mapping */ public static void addFlow(Map<String, Flow> flowMap) { sFlowMap.putAll(flowMap); } /** * Remove flow from Init. * * @param flowName flow name */ public static void removeFlow(String flowName) { sFlowMap.remove(flowName); } /** * Clear flow map. */ public static void clearFlow() { sFlowMap.clear(); } /** * Get application context for process information, package usage. * * @return application context */ public static Context getContext() { return sContext; } /** * Set thread pool size used by tasks. * * @param size thread pool size, value less or equal than 0 will produce a cached thread pool. */ public static void setThreadPoolSize(int size) { mThreadPoolSize = size; } public static Flow getFlow(String flowName) { Flow flow = sFlowMap.get(flowName); return flow != null ? flow : new Flow(flowName); } /** * start flow. * * @param flowName flow key, should be unique for each flow. */ public static void start(String flowName) { Flow flow = sFlowMap.get(flowName); if (flow != null) { flow.start(); } } /** * start flow and remove from Init management. * * @param flowName flow key, should be unique for each flow. */ public static void startAndRemove(String flowName) { Flow flow = sFlowMap.get(flowName); if (flow != null) { flow.start(); sFlowMap.remove(flowName); } } /** * start flow. */ public static void start(Flow flow) { flow.start(); } /** * Cancel the flow. * * @param flowName flow key, should be unique for each flow. */ public static void cancel(String flowName) { Flow flow = sFlowMap.get(flowName); if (flow != null) { flow.cancel(); } } /** * Get status of flow specified by given name, see {@link Status}. * * @param flowName flow key, should be unique for each flow. * @return flow status in {@code STATUS_UNKNOWN}, {@code STATUS_PENDING_START}, * {@code STATUS_EXECUTING} and {@code STATUS_DONE}. */ public static int getFlowStatus(String flowName) { Flow flow = sFlowMap.get(flowName); return flow != null ? flow.getFlowStatus() : Status.STATUS_UNKNOWN; } /** * Get thread pool used internally by Init library. * * @return thread pool */ public static ExecutorService getThreadPool() { if (mThreadPoolSize <= 0) { return Executors.newCachedThreadPool(); } else { return Executors.newFixedThreadPool(mThreadPoolSize); } } }
init/src/main/java/cn/zhaiyifan/init/Init.java
package cn.zhaiyifan.init; import android.content.Context; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * <p>Entry to add, start and manage init flow.</p> * Created by mark.zhai on 2015/10/2. */ public class Init { private static final int DEFAULT_THREAD_POOL_SIZE = 8; private static Map<String, Flow> sFlowMap = new HashMap<>(); private static Context sContext; private static int mThreadPoolSize = DEFAULT_THREAD_POOL_SIZE; /** * Init with context. * * @param context application context */ public static void init(Context context) { sContext = context; } /** * Init with context and log class. * * @param context application context * @param logProxy log class implements {@link ILog} */ public static void init(Context context, ILog logProxy) { sContext = context; LogImpl.setLogProxy(logProxy); } public static void addFlow(Flow flow) { sFlowMap.put(flow.getName(), flow); } public static void addFlow(Map<String, Flow> flowMap) { sFlowMap.putAll(flowMap); } /** * Get application context for process information, package usage. * * @return application context */ public static Context getContext() { return sContext; } /** * Set thread pool size used by tasks. * * @param size thread pool size, value less or equal than 0 will produce a cached thread pool. */ public static void setThreadPoolSize(int size) { mThreadPoolSize = size; } public static Flow getFlow(String flowName) { Flow flow = sFlowMap.get(flowName); return flow != null ? flow : new Flow(flowName); } /** * start flow. * * @param flowName flow key, should be unique for each flow. */ public static void start(String flowName) { Flow flow = sFlowMap.get(flowName); if (flow != null) { flow.start(); } } /** * start flow. */ public static void start(Flow flow) { flow.start(); } /** * Cancel the flow. * * @param flowName flow key, should be unique for each flow. */ public static void cancel(String flowName) { Flow flow = sFlowMap.get(flowName); if (flow != null) { flow.cancel(); } } /** * Get status of flow specified by given name, see {@link Status}. * * @param flowName flow key, should be unique for each flow. * @return flow status in {@code STATUS_UNKNOWN}, {@code STATUS_PENDING_START}, * {@code STATUS_EXECUTING} and {@code STATUS_DONE}. */ public static int getFlowStatus(String flowName) { Flow flow = sFlowMap.get(flowName); return flow != null ? flow.getFlowStatus() : Status.STATUS_UNKNOWN; } /** * Get thread pool used internally by Init library. * * @return thread pool */ public static ExecutorService getThreadPool() { if (mThreadPoolSize <= 0) { return Executors.newCachedThreadPool(); } else { return Executors.newFixedThreadPool(mThreadPoolSize); } } }
Add api to clear flow.
init/src/main/java/cn/zhaiyifan/init/Init.java
Add api to clear flow.
<ide><path>nit/src/main/java/cn/zhaiyifan/init/Init.java <ide> LogImpl.setLogProxy(logProxy); <ide> } <ide> <add> /** <add> * Add flow to let Init manage. <add> * <add> * @param flow flow which unique name <add> */ <ide> public static void addFlow(Flow flow) { <ide> sFlowMap.put(flow.getName(), flow); <ide> } <ide> <add> /** <add> * Add flow map to let Init manage. <add> * <add> * @param flowMap map which contains flow-name to flow mapping <add> */ <ide> public static void addFlow(Map<String, Flow> flowMap) { <ide> sFlowMap.putAll(flowMap); <add> } <add> <add> /** <add> * Remove flow from Init. <add> * <add> * @param flowName flow name <add> */ <add> public static void removeFlow(String flowName) { <add> sFlowMap.remove(flowName); <add> } <add> <add> /** <add> * Clear flow map. <add> */ <add> public static void clearFlow() { <add> sFlowMap.clear(); <ide> } <ide> <ide> /** <ide> Flow flow = sFlowMap.get(flowName); <ide> if (flow != null) { <ide> flow.start(); <add> } <add> } <add> <add> /** <add> * start flow and remove from Init management. <add> * <add> * @param flowName flow key, should be unique for each flow. <add> */ <add> public static void startAndRemove(String flowName) { <add> Flow flow = sFlowMap.get(flowName); <add> if (flow != null) { <add> flow.start(); <add> sFlowMap.remove(flowName); <ide> } <ide> } <ide>
JavaScript
mit
9d13309b40456fc242e3f15df6179220a6995e87
0
calmm-js/kral-todomvc,calmm-js/kral-todomvc
import Atom from "./kefir.atom" import K, {bind, classes} from "./kefir.react.html" import Kefir from "kefir" import L from "partial.lenses" import R from "ramda" import React from "react" import ReactDOM from "react-dom" const hash = Kefir.fromEvents(window, "hashchange") .merge(Kefir.constant(0)).toProperty() .map(() => window.location.hash) const TodoItem = ({model, editing = Atom(false)}) => <K.li {...classes(K(model, m => m && m.completed && "completed"), K(editing, e => e && "editing"))}> <K.input className="toggle" type="checkbox" hidden={editing} {...bind({checked: model.lens("completed")})}/> <K.label onDoubleClick={() => editing.set(true)} className="view">{model.view("title")}</K.label> <button className="destroy" onClick={() => model.set()}/> {K(editing, e => e && (() => { const exit = () => editing.set(false) const save = e => {const newTitle = e.target.value.trim() exit() newTitle === "" ? model.set() : model.lens("title").set(newTitle)} return <K.input type="text" onBlur={save} className="edit" key="x" mount={c => c && c.focus()} defaultValue={model.view("title")} onKeyDown={e => e.which === 13 && save(e) || e.which === 27 && exit()}/>})())} </K.li> const TodoApp = ({model: m}) => { const routes = [{hash: "#/", filter: () => true, title: "All"}, {hash: "#/active", filter: active, title: "Active"}, {hash: "#/completed", filter: completed, title: "Completed"}] const route = K(hash, h => R.find(r => r.hash === h, routes) || routes[0]) const indices = K(m.all, route, (all, {filter}) => R.flatten(all.map((it, i) => filter(it) ? [i] : []))) return <div> <section className="todoapp"> <header className="header"> <h1>todos</h1> <input type="text" className="new-todo" autoFocus placeholder="What needs to be done?" onKeyDown={e => { const t = e.target.value.trim() if (e.which === 13 && t !== "") { m.addItem({title: t}); e.target.value = ""}}}/> </header> <section className="main"> <K.input type="checkbox" className="toggle-all" hidden={m.isEmpty} {...bind({checked: m.allDone})}/> <K.ul className="todo-list">{Kefir.fromIds(indices, i => <TodoItem key={i} model={m.all.lens(i)}/>)}</K.ul> </section> <K.footer className="footer" hidden={m.isEmpty}> <K.span className="todo-count">{K(K(m.all, R.filter(active)), i => `${i.length} item${i.length === 1 ? "" : "s"} left`)}</K.span> <ul className="filters">{routes.map(r => <li key={r.title}> <K.a {...classes(route.map(cr => cr.hash === r.hash && "selected"))} href={r.hash}>{r.title}</K.a> </li>)}</ul> <K.button className="clear-completed" onClick={m.clean} hidden={K(m.all, R.all(active))}> Clear completed</K.button> </K.footer> </section> <footer className="info"><p>Double-click to edit a todo</p></footer> </div> } const active = i => !i.completed const completed = i => i.completed TodoApp.model = (all = Atom([])) => ({ all: all.lens(L.define([])), isEmpty: K(all, a => a.length === 0), addItem: ({title, completed = false}) => all.modify(R.append({title, completed})), allDone: all.lens(L.lens( R.all(completed), (completed, items) => items.map(i => ({...i, completed})))), clean: () => all.modify(R.filter(active)) }) const storeKey = "todos-react.kefir" const m = TodoApp.model(Atom(JSON.parse(localStorage.getItem(storeKey) || "[]"))) m.all.onValue(is => localStorage.setItem(storeKey, JSON.stringify(is))) ReactDOM.render(<TodoApp model={m}/>, document.getElementById("app"))
src/todomvc.js
import Atom from "./kefir.atom" import K, {bind, classes} from "./kefir.react.html" import Kefir from "kefir" import L from "partial.lenses" import R from "ramda" import React from "react" import ReactDOM from "react-dom" const hash = Kefir.fromEvents(window, "hashchange") .merge(Kefir.constant(0)).toProperty() .map(() => window.location.hash) const TodoItem = ({model, editing = Atom(false)}) => <K.li {...classes(K(model, m => m.completed && "completed"), K(editing, e => e && "editing"))}> <K.input className="toggle" type="checkbox" hidden={editing} {...bind({checked: model.lens("completed")})}/> <K.label onDoubleClick={() => editing.set(true)} className="view">{model.view("title")}</K.label> <button className="destroy" onClick={() => model.set()}/> {K(editing, e => e && (() => { const exit = () => editing.set(false) const save = e => {const newTitle = e.target.value.trim() exit() newTitle === "" ? model.set() : model.lens("title").set(newTitle)} return <K.input type="text" onBlur={save} className="edit" key="x" mount={c => c && c.focus()} defaultValue={model.view("title")} onKeyDown={e => e.which === 13 && save(e) || e.which === 27 && exit()}/>})())} </K.li> const TodoApp = ({model: m}) => { const routes = [{hash: "#/", filter: () => true, title: "All"}, {hash: "#/active", filter: active, title: "Active"}, {hash: "#/completed", filter: completed, title: "Completed"}] const route = K(hash, h => R.find(r => r.hash === h, routes) || routes[0]) const indices = K(m.all, route, (all, {filter}) => R.flatten(all.map((it, i) => filter(it) ? [i] : []))) return <div> <section className="todoapp"> <header className="header"> <h1>todos</h1> <input type="text" className="new-todo" autoFocus placeholder="What needs to be done?" onKeyDown={e => { const t = e.target.value.trim() if (e.which === 13 && t !== "") { m.addItem({title: t}); e.target.value = ""}}}/> </header> <section className="main"> <K.input type="checkbox" className="toggle-all" hidden={m.isEmpty} {...bind({checked: m.allDone})}/> <K.ul className="todo-list">{Kefir.fromIds(indices, i => <TodoItem key={i} model={m.all.lens(i)}/>)}</K.ul> </section> <K.footer className="footer" hidden={m.isEmpty}> <K.span className="todo-count">{K(K(m.all, R.filter(active)), i => `${i.length} item${i.length === 1 ? "" : "s"} left`)}</K.span> <ul className="filters">{routes.map(r => <li key={r.title}> <K.a {...classes(route.map(cr => cr.hash === r.hash && "selected"))} href={r.hash}>{r.title}</K.a> </li>)}</ul> <K.button className="clear-completed" onClick={m.clean} hidden={K(m.all, R.all(active))}> Clear completed</K.button> </K.footer> </section> <footer className="info"><p>Double-click to edit a todo</p></footer> </div> } const active = i => !i.completed const completed = i => i.completed TodoApp.model = (all = Atom([])) => ({ all: all.lens(L.define([])), isEmpty: K(all, a => a.length === 0), addItem: ({title, completed = false}) => all.modify(R.append({title, completed})), allDone: all.lens(L.lens( R.all(completed), (completed, items) => items.map(i => ({...i, completed})))), clean: () => all.modify(R.filter(active)) }) const storeKey = "todos-react.kefir" const m = TodoApp.model(Atom(JSON.parse(localStorage.getItem(storeKey) || "[]"))) m.all.onValue(is => localStorage.setItem(storeKey, JSON.stringify(is))) ReactDOM.render(<TodoApp model={m}/>, document.getElementById("app"))
Must allow for undefined.
src/todomvc.js
Must allow for undefined.
<ide><path>rc/todomvc.js <ide> .map(() => window.location.hash) <ide> <ide> const TodoItem = ({model, editing = Atom(false)}) => <del> <K.li {...classes(K(model, m => m.completed && "completed"), <add> <K.li {...classes(K(model, m => m && m.completed && "completed"), <ide> K(editing, e => e && "editing"))}> <ide> <K.input className="toggle" type="checkbox" hidden={editing} <ide> {...bind({checked: model.lens("completed")})}/>
JavaScript
mit
3a23ddeeaae4d52f3ae04a58e64b74f5d52bde1e
0
loiralae/WaterlooHacks-Winter-2016-v2,uptownhr/real-estate,nehiljain/rhime,vymarkov/hackathon-starter,jnaulty/brigadehub,ColdMonkey/vcoin,itsmomito/gitfood,jochan/mddb,yhnavein/express-starter,bowdenk7/express-typescript-starter,ak-zul/hackathon-starter,ak-zul/hackathon-starter,EvelynSun/fcc-vote1,CAYdenberg/wikode,ajijohn/brainprinter,dborncamp/shuttles,awarn/cashier-analytics,devneel/spitsomebars,benwells/admin.mrbenwells.com,crystalrood/piggie,estimmerman/pennappsxiii,mohi-io/mohi-io-api,colleenDunlap/PlayingOnInternet,itsmomito/gitfood,guilhermeasg/outspeak,JeffRice/Geolocation-Demo,hect1c/front-end-test,shareonbazaar/bazaar,awarn/bitcoins-trader,DrJukka/hackathon-starter,HappyGenes/HappyGenes,CodeJockey1337/frameworks_project4,JessedeGit/vegtable,webschoolfactory/tp-2019,erood/weight_tracker_app,uptownhr/lolgames,dischord01/hackathon-01,projectsm/hfmp,uptownhr/resume,adamnuttall/typing-app,KareemG/cirqulate,devneel/spitsomebars,Yixuan-Angela/hackathon-starter,gdiab/hackathon-starter,stenio123/ai-hackathon,flashsnake-so/hackathon-starter,cwesno/app_for_us,nehiljain/rhime,thomasythuang/Bugatti,MrMaksimize/hack-votr,uptownhr/resume,denniskkim/jackson5,uptownhr/lolgames,dischord01/hackathon-01,cmubick/sufficientlyridiculous,ahng1996/balloon-fight,ericmreid/pingypong,denniskkim/jackson5,dafyddPrys/contingency,colleenDunlap/PlayingOnInternet,mostley/backstab,gurneyman/riToolkit,caofb/hackathon-starter,ColdMonkey/vcoin,teogenesmoura/SoftwareEng12016,duchangyu/project-starter,estimmerman/pennappsxiii,rachidbch/learn,denniskkim/jackson5,bowdenk7/express-typescript-starter,ishan-marikar/hackathon-starter,pvijeh/node-express-mongo-api,bewest/samedrop-collector,stenio123/ai-hackathon,erood/weight_tracker_app,mackness/Routemetrics,ajijohn/brainprinter,rachidbch/learn,LucienBrule/carpool,awarn/cashier-analytics,therebelrobot/brigadehub,rachidbch/CIDokkuDigitalOcean,quazar11/portfolio,LovelyHorse/goodfaith,peterblazejewicz/hackathon-starter,niallobrien/hackathon-starter-plus,jakeki/futista_node,ReadingPlus/flog,nwhacks2016-travelRecommendation/travel-app,ajijohn/brainprinter,tendermario/binners-project,thomasythuang/Bugatti,wfpc92/cleansuit-backend,Jarvl/ENG2089-Project,bewest/samedrop-collector,jochan/mddb,thmr/tutm-nodejs-test,cmubick/sufficientlyridiculous,crystalrood/piggie,denniskkim/jackson5,ch4tml/fcc-voting-app,CAYdenberg/wikode,sfbrigade/brigadehub,vymarkov/hackathon-starter,webschoolfactory/tp-2019,erood/creepy_ghost,mostley/backstab,Carlosreyesk/boards-api,colleenDunlap/Lake-Map,ReadingPlus/flog,pvijeh/node-express-mongo-api,shareonbazaar/bazaar,bowdenk7/express-typescript-starter,carlos-guzman/VChronos,webschoolfactory/tp-2019,ibanzajoe/realTemp,jwalsh/hackbostonstrong2014-bostonrush,quazar11/portfolio,hect1c/front-end-test,gdiab/hackathon-starter,sinned/gifvision-node,ericmreid/pingypong,shareonbazaar/bazaar,nwhacks2016-travelRecommendation/travel-app,CahalKearney/node-boilerplate,ishan-marikar/hackathon-starter,uptownhr/real-estate,Torone/toro-starter,DrJukka/hackathon-starter,teogenesmoura/SoftwareEng12016,niallobrien/hackathon-starter-plus,therebelrobot/brigadehub,EvelynSun/fcc-vote1,loiralae/WaterlooHacks-Winter-2016-v2,stepheljobs/tentacool,MikeMichel/hackathon-starter,jnaulty/brigadehub,tendermario/binners-project,colleenDunlap/Lake-Map,mrwolfyu/meteo-bbb,suamorales/course-registration,denniskkim/jackson5,peterblazejewicz/hackathon-starter,extraBitsStudios/find-a-condom,sinned/gifvision-node,IsaacHardy/HOCO-FF-APP,LucienBrule/carpool,MikeMichel/hackathon-starter,thmr/tutm-nodejs-test,adamnuttall/typing-app,stepheljobs/tentacool,CodeJockey1337/frameworks_project4,HappyGenes/HappyGenes,KareemG/cirqulate,BlueAccords/vr-cinema,yhnavein/express-starter,mrwolfyu/meteo-bbb,denniskkim/jackson5,OperationSpark/Hackathon-Angel,baby03201/hackathon-starter,okeeffe/insurify,JessedeGit/vegtable,sinned/gifvision-node,rachidbch/Dokku1ClickDigitalOcean,denniskkim/jackson5,sfbrigade/brigadehub,sahat/hackathon-starter,BlueAccords/vr-cinema,duchangyu/project-starter,awarn/bitcoins-trader,MikeMichel/hackathon-starter,cwesno/app_for_us,nikvi/STEM-W,sahat/hackathon-starter,denniskkim/jackson5,dafyddPrys/contingency,Jarvl/ENG2089-Project,ahng1996/balloon-fight,Jarvl/ENG2089-Project,backjo/LAHacks,Yixuan-Angela/hackathon-starter,rachidbch/Dokku1ClickDigitalOcean,suamorales/course-registration,nehiljain/rhime,crystalrood/piggie,jakeki/futista_node,benwells/admin.mrbenwells.com,rachidbch/CIDokkuDigitalOcean,colleenDunlap/Lake-Map,mackness/Routemetrics,respectus/indel,sahat/hackathon-starter,gurneyman/riToolkit,peterblazejewicz/hackathon-starter,caofb/hackathon-starter,denniskkim/jackson5,dischord01/hackathon-01,projectsm/hfmp,colleenDunlap/PlayingOnInternet,flashsnake-so/hackathon-starter,carlos-guzman/VChronos,Torone/toro-starter,baby03201/hackathon-starter,respectus/indel,fenwick67/fcc-voting-app,fenwick67/fcc-voting-app,dborncamp/shuttles,ajijohn/brainprinter,LovelyHorse/goodfaith,tilast/lubiko,GeneralZero/StarTreck-node,wfpc92/cleansuit-backend,Carlosreyesk/boards-api,IsaacHardy/HOCO-FF-APP,ibanzajoe/realTemp,erood/creepy_ghost,ch4tml/fcc-voting-app,guilhermeasg/outspeak,CahalKearney/node-boilerplate,carlos-guzman/VChronos,rickitan/2014-Brazil-World-Cup-Pool,OperationSpark/Hackathon-Angel
var secrets = require('../config/secrets'); var nodemailer = require("nodemailer"); var smtpTransport = nodemailer.createTransport('SMTP', { // service: 'Mailgun', // auth: { // user: secrets.mailgun.login, // pass: secrets.mailgun.password // } service: 'SendGrid', auth: { user: secrets.sendgrid.user, pass: secrets.sendgrid.password } }); /** * GET /contact * Contact form page. */ exports.getContact = function(req, res) { res.render('contact', { title: 'Contact' }); }; /** * POST /contact * Send a contact form via Nodemailer. * @param email * @param name * @param message */ exports.postContact = function(req, res) { req.assert('name', 'Name cannot be blank').notEmpty(); req.assert('email', 'Email is not valid').isEmail(); req.assert('message', 'Message cannot be blank').notEmpty(); var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/contact'); } var from = req.body.email; var name = req.body.name; var body = req.body.message; var to = '[email protected]'; var subject = 'Contact Form | Hackathon Starter'; var mailOptions = { to: to, from: from, subject: subject, text: body }; smtpTransport.sendMail(mailOptions, function(err) { if (err) { req.flash('errors', { msg: err.message }); return res.redirect('/contact'); } req.flash('success', { msg: 'Email has been sent successfully!' }); res.redirect('/contact'); }); };
controllers/contact.js
var secrets = require('../config/secrets'); var nodemailer = require("nodemailer"); var smtpTransport = nodemailer.createTransport('SMTP', { // service: 'Mailgun', // auth: { // user: secrets.mailgun.login, // pass: secrets.mailgun.password // } service: 'SendGrid', auth: { user: secrets.sendgrid.user, pass: secrets.sendgrid.password } }); /** * GET /contact * Contact form page. */ exports.getContact = function(req, res) { res.render('contact', { title: 'Contact' }); }; /** * POST /contact * Send a contact form via Nodemailer. * @param email * @param name * @param message */ exports.postContact = function(req, res) { req.assert('name', 'Name cannot be blank').notEmpty(); req.assert('email', 'Email is not valid').isEmail(); req.assert('message', 'Message cannot be blank').notEmpty(); var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/contact'); } var from = req.body.email; var name = req.body.name; var body = req.body.message; var to = '[email protected]'; var subject = 'API Example | Contact Form'; var mailOptions = { to: to, from: from, subject: subject, text: body + '\n\n' + name }; smtpTransport.sendMail(mailOptions, function(err) { if (err) { req.flash('errors', { msg: err.message }); return res.redirect('/contact'); } req.flash('success', { msg: 'Email has been sent successfully!' }); res.redirect('/contact'); }); };
Updated contact form mail options
controllers/contact.js
Updated contact form mail options
<ide><path>ontrollers/contact.js <ide> var name = req.body.name; <ide> var body = req.body.message; <ide> var to = '[email protected]'; <del> var subject = 'API Example | Contact Form'; <add> var subject = 'Contact Form | Hackathon Starter'; <ide> <ide> var mailOptions = { <ide> to: to, <ide> from: from, <ide> subject: subject, <del> text: body + '\n\n' + name <add> text: body <ide> }; <ide> <ide> smtpTransport.sendMail(mailOptions, function(err) {
Java
apache-2.0
9f914a37e3f0a2d234cc43cfadd124986a19865c
0
rvesse/airline,rvesse/airline
package com.github.rvesse.airline.help; import javax.inject.Inject; import com.github.rvesse.airline.Arguments; import com.github.rvesse.airline.Command; import com.github.rvesse.airline.Option; import com.github.rvesse.airline.help.cli.CliCommandGroupUsageGenerator; import com.github.rvesse.airline.help.cli.CliCommandUsageGenerator; import com.github.rvesse.airline.help.cli.CliGlobalUsageGenerator; import com.github.rvesse.airline.help.cli.CliGlobalUsageSummaryGenerator; import com.github.rvesse.airline.model.CommandGroupMetadata; import com.github.rvesse.airline.model.CommandMetadata; import com.github.rvesse.airline.model.GlobalMetadata; import com.github.rvesse.airline.parser.AbbreviatedCommandFinder; import com.github.rvesse.airline.parser.AbbreviatedGroupFinder; import com.google.common.base.Predicate; import java.io.IOException; import java.io.OutputStream; import java.util.List; import java.util.concurrent.Callable; import static com.google.common.base.Predicates.compose; import static com.google.common.base.Predicates.equalTo; import static com.google.common.collect.Iterables.find; import static com.google.common.collect.Lists.newArrayList; @Command(name = "help", description = "Display help information") public class Help implements Runnable, Callable<Void> { @Inject public GlobalMetadata global; @Arguments public List<String> command = newArrayList(); @Option(name = "--include-hidden", description = "When set the help output will include hidden commands and options", hidden = true) public boolean includeHidden = false; @Override public void run() { try { help(global, command, this.includeHidden); } catch (IOException e) { throw new RuntimeException("Error generating usage documentation", e); } } @Override public Void call() { run(); return null; } /** * Displays plain text format help for the given command to standard out * * @param command * Command * @throws IOException */ public static void help(CommandMetadata command) throws IOException { help(command, System.out); } /** * Displays plain text format help for the given command to standard out * * @param command * Command * @throws IOException */ public static void help(CommandMetadata command, boolean includeHidden) throws IOException { help(command, includeHidden, System.out); } /** * Displays plain text format help or the given command to the given output * stream * * @param command * Command * @param out * Output stream * @throws IOException */ public static void help(CommandMetadata command, OutputStream out) throws IOException { help(command, false, out); } /** * Displays plain text format help or the given command to the given output * stream * * @param command * Command * @param out * Output stream * @throws IOException */ public static void help(CommandMetadata command, boolean includeHidden, OutputStream out) throws IOException { new CliCommandUsageGenerator(includeHidden).usage(null, null, command.getName(), command, out); } /** * Displays plain text format program help to standard out * * @param global * Program metadata * @param commandNames * Command Names * @throws IOException */ public static void help(GlobalMetadata global, List<String> commandNames) throws IOException { help(global, commandNames, false, System.out); } /** * Displays plain text format program help to standard out * * @param global * Program metadata * @param commandNames * Command Names * @param includeHidden * Whether to include hidden commands and options in the output * @throws IOException */ public static void help(GlobalMetadata global, List<String> commandNames, boolean includeHidden) throws IOException { help(global, commandNames, includeHidden, System.out); } /** * Displays plain text format program help to the given output stream * * @param global * Program metadata * @param commandNames * Command Names * @param out * Output Stream * @throws IOException */ public static void help(GlobalMetadata global, List<String> commandNames, OutputStream out) throws IOException { help(global, commandNames, false, out); } /** * Displays plain text format program help to the given output stream * * @param global * Program metadata * @param commandNames * Command Names * @param out * Output Stream * @throws IOException */ public static void help(GlobalMetadata global, List<String> commandNames, boolean includeHidden, OutputStream out) throws IOException { if (commandNames.isEmpty()) { new CliGlobalUsageSummaryGenerator().usage(global, out); return; } String name = commandNames.get(0); // Main program? if (name.equals(global.getName())) { // Main program help new CliGlobalUsageGenerator().usage(global, out); return; } // Predicates we may need Predicate<? super CommandGroupMetadata> findGroupPredicate; Predicate<? super CommandMetadata> findCommandPredicate; //@formatter:off findGroupPredicate = global.allowsAbbreviatedCommands() ? new AbbreviatedGroupFinder(name, global.getCommandGroups()) : compose(equalTo(name), CommandGroupMetadata.nameGetter()); //@formatter:on // A command in the default group? //@formatter:off findCommandPredicate = global.allowsAbbreviatedCommands() ? new AbbreviatedCommandFinder(name, global.getDefaultGroupCommands()) : compose(equalTo(name), CommandMetadata.nameGetter()); //@formatter:on CommandMetadata command = find(global.getDefaultGroupCommands(), findCommandPredicate, null); if (command != null) { // Command in default group help new CliCommandUsageGenerator().usage(global.getName(), null, command.getName(), command, out); return; } // A command in a group? CommandGroupMetadata group = find(global.getCommandGroups(), findGroupPredicate, null); if (group != null) { // General group help or specific group command help? if (commandNames.size() == 1) { // General group help new CliCommandGroupUsageGenerator().usage(global, group, out); return; } else { // Group command help String commandName = commandNames.get(1); //@formatter:off findCommandPredicate = global.allowsAbbreviatedCommands() ? new AbbreviatedCommandFinder(commandName, group.getCommands()) : compose(equalTo(commandName), CommandMetadata.nameGetter()); //@formatter:on command = find(group.getCommands(), findCommandPredicate, null); if (command != null) { new CliCommandUsageGenerator().usage(global.getName(), group.getName(), command.getName(), command, out); return; } // Didn't find an appropriate command if (global.allowsAbbreviatedCommands()) { System.out.println("Unknown command " + name + " " + commandName + " or an ambiguous abbreviation"); } else { System.out.println("Unknown command " + name + " " + commandName); } } } // Didn't find an appropriate group if (global.allowsAbbreviatedCommands()) { System.out.println("Unknown command " + name + " or an ambiguous abbreviation"); } else { System.out.println("Unknown command " + name); } } }
lib/src/main/java/com/github/rvesse/airline/help/Help.java
package com.github.rvesse.airline.help; import javax.inject.Inject; import com.github.rvesse.airline.Arguments; import com.github.rvesse.airline.Command; import com.github.rvesse.airline.Option; import com.github.rvesse.airline.help.cli.CliCommandGroupUsageGenerator; import com.github.rvesse.airline.help.cli.CliCommandUsageGenerator; import com.github.rvesse.airline.help.cli.CliGlobalUsageGenerator; import com.github.rvesse.airline.help.cli.CliGlobalUsageSummaryGenerator; import com.github.rvesse.airline.model.CommandGroupMetadata; import com.github.rvesse.airline.model.CommandMetadata; import com.github.rvesse.airline.model.GlobalMetadata; import com.github.rvesse.airline.parser.AbbreviatedCommandFinder; import com.github.rvesse.airline.parser.AbbreviatedGroupFinder; import com.google.common.base.Predicate; import java.io.IOException; import java.io.OutputStream; import java.util.List; import java.util.concurrent.Callable; import static com.google.common.base.Predicates.compose; import static com.google.common.base.Predicates.equalTo; import static com.google.common.collect.Iterables.find; import static com.google.common.collect.Lists.newArrayList; @Command(name = "help", description = "Display help information") public class Help implements Runnable, Callable<Void> { @Inject public GlobalMetadata global; @Arguments public List<String> command = newArrayList(); @Option(name = "--include-hidden", description = "When set the help output will include hidden commands and options") public boolean includeHidden = false; @Override public void run() { try { help(global, command); } catch (IOException e) { throw new RuntimeException("Error generating usage documentation", e); } } @Override public Void call() { run(); return null; } /** * Displays plain text format help for the given command to standard out * * @param command * Command * @throws IOException */ public static void help(CommandMetadata command) throws IOException { help(command, System.out); } /** * Displays plain text format help for the given command to standard out * * @param command * Command * @throws IOException */ public static void help(CommandMetadata command, boolean includeHidden) throws IOException { help(command, includeHidden, System.out); } /** * Displays plain text format help or the given command to the given output * stream * * @param command * Command * @param out * Output stream * @throws IOException */ public static void help(CommandMetadata command, OutputStream out) throws IOException { help(command, false, out); } /** * Displays plain text format help or the given command to the given output * stream * * @param command * Command * @param out * Output stream * @throws IOException */ public static void help(CommandMetadata command, boolean includeHidden, OutputStream out) throws IOException { new CliCommandUsageGenerator(includeHidden).usage(null, null, command.getName(), command, out); } /** * Displays plain text format program help to standard out * * @param global * Program metadata * @param commandNames * Command Names * @throws IOException */ public static void help(GlobalMetadata global, List<String> commandNames) throws IOException { help(global, commandNames, System.out); } /** * Displays plain text format program help to the given output stream * * @param global * Program metadata * @param commandNames * Command Names * @param out * Output Stream * @throws IOException */ public static void help(GlobalMetadata global, List<String> commandNames, OutputStream out) throws IOException { if (commandNames.isEmpty()) { new CliGlobalUsageSummaryGenerator().usage(global, out); return; } String name = commandNames.get(0); // Main program? if (name.equals(global.getName())) { // Main program help new CliGlobalUsageGenerator().usage(global, out); return; } // Predicates we may need Predicate<? super CommandGroupMetadata> findGroupPredicate; Predicate<? super CommandMetadata> findCommandPredicate; //@formatter:off findGroupPredicate = global.allowsAbbreviatedCommands() ? new AbbreviatedGroupFinder(name, global.getCommandGroups()) : compose(equalTo(name), CommandGroupMetadata.nameGetter()); //@formatter:on // A command in the default group? //@formatter:off findCommandPredicate = global.allowsAbbreviatedCommands() ? new AbbreviatedCommandFinder(name, global.getDefaultGroupCommands()) : compose(equalTo(name), CommandMetadata.nameGetter()); //@formatter:on CommandMetadata command = find(global.getDefaultGroupCommands(), findCommandPredicate, null); if (command != null) { // Command in default group help new CliCommandUsageGenerator().usage(global.getName(), null, command.getName(), command, out); return; } // A command in a group? CommandGroupMetadata group = find(global.getCommandGroups(), findGroupPredicate, null); if (group != null) { // General group help or specific group command help? if (commandNames.size() == 1) { // General group help new CliCommandGroupUsageGenerator().usage(global, group, out); return; } else { // Group command help String commandName = commandNames.get(1); //@formatter:off findCommandPredicate = global.allowsAbbreviatedCommands() ? new AbbreviatedCommandFinder(commandName, group.getCommands()) : compose(equalTo(commandName), CommandMetadata.nameGetter()); //@formatter:on command = find(group.getCommands(), findCommandPredicate, null); if (command != null) { new CliCommandUsageGenerator().usage(global.getName(), group.getName(), command.getName(), command, out); return; } // Didn't find an appropriate command if (global.allowsAbbreviatedCommands()) { System.out.println("Unknown command " + name + " " + commandName + " or an ambiguous abbreviation"); } else { System.out.println("Unknown command " + name + " " + commandName); } } } // Didn't find an appropriate group if (global.allowsAbbreviatedCommands()) { System.out.println("Unknown command " + name + " or an ambiguous abbreviation"); } else { System.out.println("Unknown command " + name); } } }
Further improve Help class - More overloads for `Help.help()` - Add hidden `--include-hidden` option which does what it says on the tin
lib/src/main/java/com/github/rvesse/airline/help/Help.java
Further improve Help class
<ide><path>ib/src/main/java/com/github/rvesse/airline/help/Help.java <ide> <ide> @Arguments <ide> public List<String> command = newArrayList(); <del> <del> @Option(name = "--include-hidden", description = "When set the help output will include hidden commands and options") <add> <add> @Option(name = "--include-hidden", description = "When set the help output will include hidden commands and options", hidden = true) <ide> public boolean includeHidden = false; <ide> <ide> @Override <ide> public void run() { <ide> try { <del> help(global, command); <add> help(global, command, this.includeHidden); <ide> } catch (IOException e) { <ide> throw new RuntimeException("Error generating usage documentation", e); <ide> } <ide> public static void help(CommandMetadata command) throws IOException { <ide> help(command, System.out); <ide> } <del> <add> <ide> /** <ide> * Displays plain text format help for the given command to standard out <ide> * <ide> public static void help(CommandMetadata command, boolean includeHidden) throws IOException { <ide> help(command, includeHidden, System.out); <ide> } <del> <add> <ide> /** <ide> * Displays plain text format help or the given command to the given output <ide> * stream <ide> * @throws IOException <ide> */ <ide> public static void help(GlobalMetadata global, List<String> commandNames) throws IOException { <del> help(global, commandNames, System.out); <del> } <del> <add> help(global, commandNames, false, System.out); <add> } <add> <add> /** <add> * Displays plain text format program help to standard out <add> * <add> * @param global <add> * Program metadata <add> * @param commandNames <add> * Command Names <add> * @param includeHidden <add> * Whether to include hidden commands and options in the output <add> * @throws IOException <add> */ <add> public static void help(GlobalMetadata global, List<String> commandNames, boolean includeHidden) throws IOException { <add> help(global, commandNames, includeHidden, System.out); <add> } <add> <ide> /** <ide> * Displays plain text format program help to the given output stream <ide> * <ide> * @throws IOException <ide> */ <ide> public static void help(GlobalMetadata global, List<String> commandNames, OutputStream out) throws IOException { <add> help(global, commandNames, false, out); <add> } <add> <add> /** <add> * Displays plain text format program help to the given output stream <add> * <add> * @param global <add> * Program metadata <add> * @param commandNames <add> * Command Names <add> * @param out <add> * Output Stream <add> * @throws IOException <add> */ <add> public static void help(GlobalMetadata global, List<String> commandNames, boolean includeHidden, OutputStream out) throws IOException { <ide> if (commandNames.isEmpty()) { <ide> new CliGlobalUsageSummaryGenerator().usage(global, out); <ide> return;
Java
apache-2.0
7d7279ac000f8ad65b19eb680939727440a5c0d4
0
joakimkistowski/HTTP-Load-Generator
/** * Copyright 2017 Joakim von Kistowski * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tools.descartes.dlim.httploadgenerator.runner; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Scanner; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Logger; import tools.descartes.dlim.httploadgenerator.generator.ArrivalRateTuple; import tools.descartes.dlim.httploadgenerator.power.IPowerCommunicator; /** * Director that is run in director mode. * @author Joakim von Kistowski * */ public class Director extends Thread { private static final Logger LOG = Logger.getLogger(Director.class.getName()); private static int seed = 5; private List<LoadGeneratorCommunicator> communicators; /** * Execute the director with the given parameters. * Parameters may be null. Director asks the user for null parameters if they are required. * @param profilePath The path of the LIMBO-generated load profile. * @param outName The name of the output log file. * @param powerAddress The address of the power daemon (optional). * @param generator The address of the load generator(s). * @param randomSeed The random seed for exponentially distributed request arrivals. * @param threadCount The number of threads that generate load. * @param urlTimeout The url connection timeout. * @param scriptPath The path of the script file that generates the specific requests. * @param powerCommunicatorClassName Fully qualified class name of the power communicator class. */ public static void executeDirector(String profilePath, String outName, String powerAddress, String generator, String randomSeed, String threadCount, String urlTimeout, String scriptPath, String powerCommunicatorClassName) { Scanner scanner = new Scanner(System.in); List<IPowerCommunicator> powerCommunicators = new LinkedList<>(); //Load Profile File file = null; if (profilePath != null) { file = new File(profilePath); } else { System.out.print("Load Profile Path: "); file = new File(scanner.nextLine()); } //Logfile if (outName == null) { LOG.info("Using default log: " + IRunnerConstants.DEFAULT_LOG); outName = IRunnerConstants.DEFAULT_LOG; } //Power measurement if (powerCommunicatorClassName != null && !powerCommunicatorClassName.trim().isEmpty() && powerAddress != null && !powerAddress.isEmpty()) { initializePowerCommunicators(powerCommunicators, powerCommunicatorClassName, powerAddress); } else { LOG.warning("No power measurements"); } //Director Address String generatorAddress; if (generator != null) { generatorAddress = generator.trim(); } else { LOG.warning("No load generator address, using localhost."); generatorAddress = IRunnerConstants.LOCALHOST_IP; } //Random Seed boolean randomBatchTimes = true; String seedStr = randomSeed; if (seedStr == null) { LOG.info("No Random Seed for Batch Generation specified. " + "This parameter is unneeded for request time stamp generation."); randomBatchTimes = false; LOG.info("Using equi-distant non-random inter batch times."); } else { try { seed = Integer.parseInt(seedStr.trim()); System.out.println("Seed set to: " + seedStr.trim()); } catch (NumberFormatException e) { randomBatchTimes = false; LOG.warning("Invalid seed, using equi-distant non-random inter batch times."); } } //Thread Count int threadNum = IRunnerConstants.DEFAULT_THREAD_NUM; if (threadCount != null) { try { threadNum = Integer.parseInt(threadCount); LOG.info("Load Generator Thread Count set to " + threadCount); } catch (NumberFormatException e) { LOG.warning("Invalid Thread Count: " + threadCount); } } else { LOG.info("Using default load generation thread count: " + threadNum); } //Thread Count int timout = -1; if (urlTimeout != null) { try { timout = Integer.parseInt(urlTimeout); LOG.info("URL connection timout set to " + urlTimeout + " ms"); } catch (NumberFormatException e) { LOG.warning("Invalid timout: " + urlTimeout); } } else { LOG.info("No timout specified."); } //Script Path String scriptPathRead; if (scriptPath != null) { scriptPathRead = scriptPath.trim(); } else { LOG.warning("No Lua script path provided. Using: " + IRunnerConstants.DEFAULT_LUA_PATH); scriptPathRead = IRunnerConstants.DEFAULT_LUA_PATH; } if (file != null && outName != null && !outName.isEmpty()) { Director director = new Director(generatorAddress.split(":")[0].trim()); director.process(file, outName, randomBatchTimes, threadNum, timout, scriptPathRead, powerCommunicators); } powerCommunicators.forEach(pc -> pc.stopCommunicator()); scanner.close(); } /** * Inititializes a director with a load generator address. * @param loadGenerators Addresses of the load generator. Seperated by ",". */ public Director(String loadGenerators) { String[] addresses = loadGenerators.split("[,;]"); communicators = new ArrayList<>(addresses.length); for (String address : addresses) { String[] addressTokens = address.split(":"); String ip = addressTokens[0].trim(); if (!ip.isEmpty()) { int port = IRunnerConstants.DEFAULT_PORT; if (addressTokens.length > 1 && !addressTokens[1].trim().isEmpty()) { try { port = Integer.parseInt(addressTokens[1].trim()); } catch (NumberFormatException e) { port = IRunnerConstants.DEFAULT_PORT; } } communicators.add(new LoadGeneratorCommunicator(ip, port)); } } } /** * Actually run the director. Sends the messages to the load generator and collects data. * @param file The arrival rate file. * @param outName The name of the output log. * @param scanner The scanner for reading user start signal from console. * @param randomBatchTimes True if batches are scheduled using a randomized distribution. * @param threadCount The number of threads that generate load. * @param timeout The connection timeout for the HTTP url connections. * @param scriptPath The path of the script file that generates the specific requests. * @param powerCommunicators Communicators for communicating with power daemon (optional). */ public void process(File file, String outName, boolean randomBatchTimes, int threadCount, int timeout, String scriptPath, List<IPowerCommunicator> powerCommunicators) { try { List<ArrivalRateTuple> arrRates = Main.readFileToList(file, 0); LOG.info("Read " + arrRates.size() + " Arrival Rate Tuples"); communicators.parallelStream().forEach(c-> c.sendArrivalRates(arrRates, communicators.size())); LOG.info("Arrival Rates sent to Load Generator(s)."); communicators.parallelStream().forEach(c-> c.sendThreadCount(threadCount)); LOG.info("Thread Count sent to Load Generator(s): " + threadCount); communicators.parallelStream().forEach(c-> c.sendTimeout(timeout)); if (timeout > 0) { LOG.info("URL connection timeout sent to Load Generator(s): " + timeout); } communicators.parallelStream().forEach(c-> c.sendLUAScript(scriptPath)); LOG.info("Contents of script sent to Load Generator: " + scriptPath); String parentPath = file.getParent(); if (parentPath == null || parentPath.isEmpty()) { parentPath = "."; } PrintWriter writer = new PrintWriter(parentPath + "/" + outName); writer.print("Target Time,Load Intensity,Successful Transactions," + "Failed Transactions,Avg Response Time,Final Batch Dispatch Time"); powerCommunicators.stream().forEachOrdered(pc -> writer.print(",Watts(" + pc.getCommunicatorName() + ")")); LOG.info("Starting Load Generation"); //setup initial run Variables ExecutorService executor = null; SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy;HH:mm:ssSSS"); if (powerCommunicators != null && !powerCommunicators.isEmpty()) { executor = Executors.newFixedThreadPool(powerCommunicators.size()); for (IPowerCommunicator pc : powerCommunicators) { executor.execute(pc); } } long timeZero = communicators.parallelStream() .mapToLong(c -> c.startBenchmarking(randomBatchTimes, seed)).min().getAsLong(); String dateString = sdf.format(new Date(timeZero)); System.out.println("Beginning Run @" + timeZero + "(" + dateString + ")"); writer.println("," + dateString); //get Data from LoadGenerator while (!collectResultRound(powerCommunicators, writer)) { /* collectResultRound blocking waits. We don't need to wait here. */ } System.out.println("Workload finished."); writer.close(); System.out.println("Log finished."); if (powerCommunicators != null && !powerCommunicators.isEmpty()) { powerCommunicators.forEach(pc -> pc.stopCommunicator()); executor.shutdown(); } } catch (IOException e) { LOG.severe("File not found."); e.printStackTrace(); } } private static void initializePowerCommunicators(List<IPowerCommunicator> pcList, String pcClassName, String addresses) { String[] singleAddresses = addresses.trim().split("[,;]"); for (String address : singleAddresses) { if (!address.trim().isEmpty()) { String[] host = address.split(":"); int port = 22444; if (host.length > 1) { port = Integer.parseInt(host[1].trim()); } try { Class<? extends IPowerCommunicator> pcClass = Class.forName(pcClassName.trim()).asSubclass(IPowerCommunicator.class); IPowerCommunicator powerCommunicator = pcClass.newInstance(); powerCommunicator.initializePowerCommunicator(host[0].trim(), port); LOG.info("Initializing Power Communicator for address: " + host[0].trim() + ":" + port); pcList.add(powerCommunicator); } catch (ClassNotFoundException e) { LOG.severe("PowerCommunicator class not found: " + pcClassName); } catch (InstantiationException e) { LOG.severe("PowerCommunicator class could not be instantiated: " + pcClassName); LOG.severe(e.getMessage()); } catch (IllegalAccessException e) { LOG.severe("PowerCommunicator class could not be accessed: " + pcClassName); LOG.severe(e.getMessage()); } catch (IOException e) { LOG.severe("IOException initializing power communicator: " + e.getMessage()); } } } } /** * Collects one iteration of the results, aggregates them and logs them. * Returns false if more results are expected in the future. * Returns true if the measurements have concluded and the "done" signal was received from all communicators. * @return True, if the measurement has concluded. */ private boolean collectResultRound(List<IPowerCommunicator> powerCommunicator, PrintWriter writer) { int finishedCommunicators = 0; double targetTime = 0; int loadIntensity = 0; int successfulTransactions = 0; int failedTransactions = 0; ArrayList<Double> responseTimes = new ArrayList<Double>(); ArrayList<Double> finalBatchTimes = new ArrayList<Double>(); for (LoadGeneratorCommunicator communicator : communicators) { if (communicator.isFinished()) { finishedCommunicators++; if (finishedCommunicators == communicators.size()) { return true; } } else { String receivedResults = communicator.getLatestResultMessageBlocking(); if (receivedResults == null) { finishedCommunicators++; if (finishedCommunicators == communicators.size()) { return true; } } else { String[] tokens = receivedResults.split(","); double receivedTargetTime = Double.parseDouble(tokens[0].trim()); if (targetTime == 0) { targetTime = receivedTargetTime; } else { if (targetTime != receivedTargetTime) { LOG.severe("Time mismatch in load generator responses! Measurement invalid."); } } loadIntensity += Integer.parseInt(tokens[1].trim()); successfulTransactions += Integer.parseInt(tokens[2].trim()); responseTimes.add(Double.parseDouble(tokens[3].trim())); failedTransactions += Integer.parseInt(tokens[4].trim()); finalBatchTimes.add(Double.parseDouble(tokens[5].trim())); } } } double avgResponseTime = responseTimes.stream().mapToDouble(d -> d.doubleValue()).average().getAsDouble(); double finalBatchTime = finalBatchTimes.stream().mapToDouble(d -> d.doubleValue()).max().getAsDouble(); logState(targetTime, loadIntensity, successfulTransactions, failedTransactions, avgResponseTime, finalBatchTime, powerCommunicator, writer); return false; } private void logState(double targetTime, int loadIntensity, int successfulTransactions, int failedTransactions, double avgResponseTime, double finalBatchTime, List<IPowerCommunicator> powerCommunicators, PrintWriter writer) { //get Power List<Double> powers = null; if (powerCommunicators != null && !powerCommunicators.isEmpty()) { powers = new ArrayList<>(powerCommunicators.size()); for (IPowerCommunicator pc : powerCommunicators) { powers.add(pc.getPowerMeasurement()); } } System.out.println("Target Time = " + targetTime + "; Load Intensity = " + loadIntensity + "; Successful Transactions = " + successfulTransactions + "; Failed Transactions = " + failedTransactions); writer.print(targetTime + "," + loadIntensity + "," + successfulTransactions + "," + failedTransactions + "," + avgResponseTime + "," + finalBatchTime); if (powers != null && !powers.isEmpty()) { powers.stream().forEachOrdered(p -> writer.print("," + p)); } writer.println(""); } }
tools.descartes.dlim.httploadgenerator/src/main/java/tools/descartes/dlim/httploadgenerator/runner/Director.java
/** * Copyright 2017 Joakim von Kistowski * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tools.descartes.dlim.httploadgenerator.runner; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Scanner; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Logger; import tools.descartes.dlim.httploadgenerator.generator.ArrivalRateTuple; import tools.descartes.dlim.httploadgenerator.power.IPowerCommunicator; /** * Director that is run in director mode. * @author Joakim von Kistowski * */ public class Director extends Thread { private static final Logger LOG = Logger.getLogger(Director.class.getName()); private static int seed = 5; private List<LoadGeneratorCommunicator> communicators; /** * Execute the director with the given parameters. * Parameters may be null. Director asks the user for null parameters if they are required. * @param profilePath The path of the LIMBO-generated load profile. * @param outName The name of the output log file. * @param powerAddress The address of the power daemon (optional). * @param generator The address of the load generator(s). * @param randomSeed The random seed for exponentially distributed request arrivals. * @param threadCount The number of threads that generate load. * @param urlTimeout The url connection timeout. * @param scriptPath The path of the script file that generates the specific requests. * @param powerCommunicatorClassName Fully qualified class name of the power communicator class. */ public static void executeDirector(String profilePath, String outName, String powerAddress, String generator, String randomSeed, String threadCount, String urlTimeout, String scriptPath, String powerCommunicatorClassName) { Scanner scanner = new Scanner(System.in); List<IPowerCommunicator> powerCommunicators = new LinkedList<>(); //Load Profile File file = null; if (profilePath != null) { file = new File(profilePath); } else { System.out.print("Load Profile Path: "); file = new File(scanner.nextLine()); } //Logfile if (outName == null) { LOG.info("Using default log: " + IRunnerConstants.DEFAULT_LOG); outName = IRunnerConstants.DEFAULT_LOG; } //Power measurement if (powerCommunicatorClassName != null && !powerCommunicatorClassName.trim().isEmpty() && powerAddress != null && !powerAddress.isEmpty()) { initializePowerCommunicators(powerCommunicators, powerCommunicatorClassName, powerAddress); } else { LOG.warning("No power measurements"); } //Director Address String generatorAddress; if (generator != null) { generatorAddress = generator.trim(); } else { LOG.warning("No load generator address, using localhost."); generatorAddress = IRunnerConstants.LOCALHOST_IP; } //Random Seed boolean randomBatchTimes = true; String seedStr = randomSeed; if (seedStr == null) { LOG.info("No Random Seed for Batch Generation specified. " + "This parameter is unneeded for request time stamp generation."); randomBatchTimes = false; LOG.info("Using equi-distant non-random inter batch times."); } else { try { seed = Integer.parseInt(seedStr.trim()); System.out.println("Seed set to: " + seedStr.trim()); } catch (NumberFormatException e) { randomBatchTimes = false; LOG.warning("Invalid seed, using equi-distant non-random inter batch times."); } } //Thread Count int threadNum = IRunnerConstants.DEFAULT_THREAD_NUM; if (threadCount != null) { try { threadNum = Integer.parseInt(threadCount); LOG.info("Load Generator Thread Count set to " + threadCount); } catch (NumberFormatException e) { LOG.warning("Invalid Thread Count: " + threadCount); } } else { LOG.info("Using default load generation thread count: " + threadNum); } //Thread Count int timout = -1; if (urlTimeout != null) { try { timout = Integer.parseInt(urlTimeout); LOG.info("URL connection timout set to " + urlTimeout + " ms"); } catch (NumberFormatException e) { LOG.warning("Invalid timout: " + urlTimeout); } } else { LOG.info("No timout specified."); } //Script Path String scriptPathRead; if (scriptPath != null) { scriptPathRead = scriptPath.trim(); } else { LOG.warning("No Lua script path provided. Using: " + IRunnerConstants.DEFAULT_LUA_PATH); scriptPathRead = IRunnerConstants.DEFAULT_LUA_PATH; } if (file != null && outName != null && !outName.isEmpty()) { Director director = new Director(generatorAddress.split(":")[0].trim()); director.process(file, outName, scanner, randomBatchTimes, threadNum, timout, scriptPathRead, powerCommunicators); } powerCommunicators.forEach(pc -> pc.stopCommunicator()); scanner.close(); } /** * Inititializes a director with a load generator address. * @param loadGenerators Addresses of the load generator. Seperated by ",". */ public Director(String loadGenerators) { String[] addresses = loadGenerators.split("[,;]"); communicators = new ArrayList<>(addresses.length); for (String address : addresses) { String[] addressTokens = address.split(":"); String ip = addressTokens[0].trim(); if (!ip.isEmpty()) { int port = IRunnerConstants.DEFAULT_PORT; if (addressTokens.length > 1 && !addressTokens[1].trim().isEmpty()) { try { port = Integer.parseInt(addressTokens[1].trim()); } catch (NumberFormatException e) { port = IRunnerConstants.DEFAULT_PORT; } } communicators.add(new LoadGeneratorCommunicator(ip, port)); } } } /** * Actually run the director. Sends the messages to the load generator and collects data. * @param file The arrival rate file. * @param outName The name of the output log. * @param scanner The scanner for reading user start signal from console. * @param randomBatchTimes True if batches are scheduled using a randomized distribution. * @param threadCount The number of threads that generate load. * @param timeout The connection timeout for the HTTP url connections. * @param scriptPath The path of the script file that generates the specific requests. * @param powerCommunicators Communicators for communicating with power daemon (optional). */ public void process(File file, String outName, Scanner scanner, boolean randomBatchTimes, int threadCount, int timeout, String scriptPath, List<IPowerCommunicator> powerCommunicators) { try { List<ArrivalRateTuple> arrRates = Main.readFileToList(file, 0); LOG.info("Read " + arrRates.size() + " Arrival Rate Tuples"); communicators.parallelStream().forEach(c-> c.sendArrivalRates(arrRates, communicators.size())); LOG.info("Arrival Rates sent to Load Generator(s)."); communicators.parallelStream().forEach(c-> c.sendThreadCount(threadCount)); LOG.info("Thread Count sent to Load Generator(s): " + threadCount); communicators.parallelStream().forEach(c-> c.sendTimeout(timeout)); if (timeout > 0) { LOG.info("URL connection timeout sent to Load Generator(s): " + timeout); } communicators.parallelStream().forEach(c-> c.sendLUAScript(scriptPath)); LOG.info("Contents of script sent to Load Generator: " + scriptPath); String parentPath = file.getParent(); if (parentPath == null || parentPath.isEmpty()) { parentPath = "."; } PrintWriter writer = new PrintWriter(parentPath + "/" + outName); writer.print("Target Time,Load Intensity,Successful Transactions," + "Failed Transactions,Avg Response Time,Final Batch Dispatch Time"); powerCommunicators.stream().forEachOrdered(pc -> writer.print(",Watts(" + pc.getCommunicatorName() + ")")); System.out.print("Press Enter to begin Execution"); outName = scanner.nextLine(); //setup initial run Variables ExecutorService executor = null; SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy;HH:mm:ssSSS"); if (powerCommunicators != null && !powerCommunicators.isEmpty()) { executor = Executors.newFixedThreadPool(powerCommunicators.size()); for (IPowerCommunicator pc : powerCommunicators) { executor.execute(pc); } } long timeZero = communicators.parallelStream() .mapToLong(c -> c.startBenchmarking(randomBatchTimes, seed)).min().getAsLong(); String dateString = sdf.format(new Date(timeZero)); System.out.println("Beginning Run @" + timeZero + "(" + dateString + ")"); writer.println("," + dateString); //get Data from LoadGenerator while (!collectResultRound(powerCommunicators, writer)) { /* collectResultRound blocking waits. We don't need to wait here. */ } System.out.println("Workload finished."); writer.close(); System.out.println("Log finished."); if (powerCommunicators != null && !powerCommunicators.isEmpty()) { powerCommunicators.forEach(pc -> pc.stopCommunicator()); executor.shutdown(); } } catch (IOException e) { LOG.severe("File not found."); e.printStackTrace(); } } private static void initializePowerCommunicators(List<IPowerCommunicator> pcList, String pcClassName, String addresses) { String[] singleAddresses = addresses.trim().split("[,;]"); for (String address : singleAddresses) { if (!address.trim().isEmpty()) { String[] host = address.split(":"); int port = 22444; if (host.length > 1) { port = Integer.parseInt(host[1].trim()); } try { Class<? extends IPowerCommunicator> pcClass = Class.forName(pcClassName.trim()).asSubclass(IPowerCommunicator.class); IPowerCommunicator powerCommunicator = pcClass.newInstance(); powerCommunicator.initializePowerCommunicator(host[0].trim(), port); LOG.info("Initializing Power Communicator for address: " + host[0].trim() + ":" + port); pcList.add(powerCommunicator); } catch (ClassNotFoundException e) { LOG.severe("PowerCommunicator class not found: " + pcClassName); } catch (InstantiationException e) { LOG.severe("PowerCommunicator class could not be instantiated: " + pcClassName); LOG.severe(e.getMessage()); } catch (IllegalAccessException e) { LOG.severe("PowerCommunicator class could not be accessed: " + pcClassName); LOG.severe(e.getMessage()); } catch (IOException e) { LOG.severe("IOException initializing power communicator: " + e.getMessage()); } } } } /** * Collects one iteration of the results, aggregates them and logs them. * Returns false if more results are expected in the future. * Returns true if the measurements have concluded and the "done" signal was received from all communicators. * @return True, if the measurement has concluded. */ private boolean collectResultRound(List<IPowerCommunicator> powerCommunicator, PrintWriter writer) { int finishedCommunicators = 0; double targetTime = 0; int loadIntensity = 0; int successfulTransactions = 0; int failedTransactions = 0; ArrayList<Double> responseTimes = new ArrayList<Double>(); ArrayList<Double> finalBatchTimes = new ArrayList<Double>(); for (LoadGeneratorCommunicator communicator : communicators) { if (communicator.isFinished()) { finishedCommunicators++; if (finishedCommunicators == communicators.size()) { return true; } } else { String receivedResults = communicator.getLatestResultMessageBlocking(); if (receivedResults == null) { finishedCommunicators++; if (finishedCommunicators == communicators.size()) { return true; } } else { String[] tokens = receivedResults.split(","); double receivedTargetTime = Double.parseDouble(tokens[0].trim()); if (targetTime == 0) { targetTime = receivedTargetTime; } else { if (targetTime != receivedTargetTime) { LOG.severe("Time mismatch in load generator responses! Measurement invalid."); } } loadIntensity += Integer.parseInt(tokens[1].trim()); successfulTransactions += Integer.parseInt(tokens[2].trim()); responseTimes.add(Double.parseDouble(tokens[3].trim())); failedTransactions += Integer.parseInt(tokens[4].trim()); finalBatchTimes.add(Double.parseDouble(tokens[5].trim())); } } } double avgResponseTime = responseTimes.stream().mapToDouble(d -> d.doubleValue()).average().getAsDouble(); double finalBatchTime = finalBatchTimes.stream().mapToDouble(d -> d.doubleValue()).max().getAsDouble(); logState(targetTime, loadIntensity, successfulTransactions, failedTransactions, avgResponseTime, finalBatchTime, powerCommunicator, writer); return false; } private void logState(double targetTime, int loadIntensity, int successfulTransactions, int failedTransactions, double avgResponseTime, double finalBatchTime, List<IPowerCommunicator> powerCommunicators, PrintWriter writer) { //get Power List<Double> powers = null; if (powerCommunicators != null && !powerCommunicators.isEmpty()) { powers = new ArrayList<>(powerCommunicators.size()); for (IPowerCommunicator pc : powerCommunicators) { powers.add(pc.getPowerMeasurement()); } } System.out.println("Target Time = " + targetTime + "; Load Intensity = " + loadIntensity + "; Successful Transactions = " + successfulTransactions + "; Failed Transactions = " + failedTransactions); writer.print(targetTime + "," + loadIntensity + "," + successfulTransactions + "," + failedTransactions + "," + avgResponseTime + "," + finalBatchTime); if (powers != null && !powers.isEmpty()) { powers.stream().forEachOrdered(p -> writer.print("," + p)); } writer.println(""); } }
removed manual enter press
tools.descartes.dlim.httploadgenerator/src/main/java/tools/descartes/dlim/httploadgenerator/runner/Director.java
removed manual enter press
<ide><path>ools.descartes.dlim.httploadgenerator/src/main/java/tools/descartes/dlim/httploadgenerator/runner/Director.java <ide> <ide> if (file != null && outName != null && !outName.isEmpty()) { <ide> Director director = new Director(generatorAddress.split(":")[0].trim()); <del> director.process(file, outName, scanner, randomBatchTimes, <add> director.process(file, outName, randomBatchTimes, <ide> threadNum, timout, scriptPathRead, powerCommunicators); <ide> } <ide> powerCommunicators.forEach(pc -> pc.stopCommunicator()); <ide> * @param scriptPath The path of the script file that generates the specific requests. <ide> * @param powerCommunicators Communicators for communicating with power daemon (optional). <ide> */ <del> public void process(File file, String outName, Scanner scanner, boolean randomBatchTimes, <add> public void process(File file, String outName, boolean randomBatchTimes, <ide> int threadCount, int timeout, String scriptPath, List<IPowerCommunicator> powerCommunicators) { <ide> <ide> try { <ide> + "Failed Transactions,Avg Response Time,Final Batch Dispatch Time"); <ide> powerCommunicators.stream().forEachOrdered(pc -> writer.print(",Watts(" + pc.getCommunicatorName() + ")")); <ide> <del> System.out.print("Press Enter to begin Execution"); <del> outName = scanner.nextLine(); <add> LOG.info("Starting Load Generation"); <ide> <ide> //setup initial run Variables <ide> ExecutorService executor = null;
Java
mit
d623dd57ab5fc01a58f26d10a4d2453f2956aa85
0
jenkinsci/git-plugin,jacob-keller/git-plugin,jenkinsci/git-plugin,MarkEWaite/git-plugin,v1v/git-plugin,MarkEWaite/git-plugin,MarkEWaite/git-plugin,jacob-keller/git-plugin,jacob-keller/git-plugin,martinda/git-plugin,v1v/git-plugin,MarkEWaite/git-plugin,v1v/git-plugin,martinda/git-plugin,jenkinsci/git-plugin,jenkinsci/git-plugin,martinda/git-plugin
/* * The MIT License * * Copyright (c) 2013-2017, CloudBees, Inc., Stephen Connolly, Amadeus IT Group. * * 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. */ package jenkins.plugins.git; import com.cloudbees.plugins.credentials.CredentialsMatchers; import com.cloudbees.plugins.credentials.CredentialsNameProvider; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardCredentials; import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials; import com.cloudbees.plugins.credentials.domains.URIRequirementBuilder; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.EnvVars; import hudson.Extension; import hudson.RestrictedSince; import hudson.Util; import hudson.model.Action; import hudson.model.Actionable; import hudson.model.Item; import hudson.model.TaskListener; import hudson.plugins.git.Branch; import hudson.plugins.git.GitException; import hudson.plugins.git.GitSCM; import hudson.plugins.git.GitTool; import hudson.plugins.git.Revision; import hudson.plugins.git.UserRemoteConfig; import hudson.plugins.git.browser.GitRepositoryBrowser; import hudson.plugins.git.extensions.GitSCMExtension; import hudson.plugins.git.util.Build; import hudson.plugins.git.util.BuildChooser; import hudson.plugins.git.util.BuildChooserContext; import hudson.plugins.git.util.BuildChooserDescriptor; import hudson.plugins.git.util.BuildData; import hudson.scm.SCM; import hudson.security.ACL; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import jenkins.model.Jenkins; import jenkins.plugins.git.traits.GitBrowserSCMSourceTrait; import jenkins.plugins.git.traits.GitSCMExtensionTrait; import jenkins.plugins.git.traits.GitToolSCMSourceTrait; import jenkins.plugins.git.traits.RefSpecsSCMSourceTrait; import jenkins.plugins.git.traits.RemoteNameSCMSourceTrait; import jenkins.scm.api.SCMFile; import jenkins.scm.api.SCMFileSystem; import jenkins.scm.api.SCMHead; import jenkins.scm.api.SCMHeadCategory; import jenkins.scm.api.SCMHeadEvent; import jenkins.scm.api.SCMHeadObserver; import jenkins.scm.api.SCMProbe; import jenkins.scm.api.SCMProbeStat; import jenkins.scm.api.SCMRevision; import jenkins.scm.api.SCMSource; import jenkins.scm.api.SCMSourceCriteria; import jenkins.scm.api.SCMSourceEvent; import jenkins.scm.api.SCMSourceOwner; import jenkins.scm.api.metadata.PrimaryInstanceMetadataAction; import jenkins.scm.api.trait.SCMSourceRequest; import jenkins.scm.api.trait.SCMSourceTrait; import jenkins.scm.api.trait.SCMTrait; import jenkins.scm.impl.TagSCMHeadCategory; import jenkins.scm.impl.trait.WildcardSCMHeadFilterTrait; import jenkins.scm.impl.trait.WildcardSCMSourceFilterTrait; import net.jcip.annotations.GuardedBy; import org.apache.commons.lang.StringUtils; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.FileMode; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevTree; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.transport.RefSpec; import org.eclipse.jgit.transport.URIish; import org.eclipse.jgit.treewalk.TreeWalk; import org.jenkinsci.plugins.gitclient.FetchCommand; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.DoNotUse; import org.kohsuke.accmod.restrictions.NoExternalUse; /** * Base class for {@link SCMSource} implementations that produce {@link GitSCM} implementations. * * @since 2.0 */ public abstract class AbstractGitSCMSource extends SCMSource { /** * The default remote name to use when configuring the ref specs to use with fetch operations. * * @since 3.4.0 */ public static final String DEFAULT_REMOTE_NAME = "origin"; /** * The placeholder to use in ref spec templates in order to correctly ensure that the ref spec remote name * matches the remote name. * <p> * The template uses {@code @{...}} as that is an illegal sequence in a remote name * * @see <a href="https://github.com/git/git/blob/027a3b943b444a3e3a76f9a89803fc10245b858f/refs.c#L61-L68">git * source code rules on ref spec names</a> * @since 3.4.0 */ public static final String REF_SPEC_REMOTE_NAME_PLACEHOLDER_STR = "@{remote}"; /** * The regex for {@link #REF_SPEC_REMOTE_NAME_PLACEHOLDER_STR}. * * @since 3.4.0 */ public static final String REF_SPEC_REMOTE_NAME_PLACEHOLDER = "(?i)"+Pattern.quote(REF_SPEC_REMOTE_NAME_PLACEHOLDER_STR); /** * The default ref spec template. * * @since 3.4.0 */ public static final String REF_SPEC_DEFAULT = "+refs/heads/*:refs/remotes/" + REF_SPEC_REMOTE_NAME_PLACEHOLDER_STR + "/*"; /** * Keep one lock per cache directory. Lazy populated, but never purge, except on restart. */ private static final ConcurrentMap<String, Lock> cacheLocks = new ConcurrentHashMap<>(); private static final Logger LOGGER = Logger.getLogger(AbstractGitSCMSource.class.getName()); public AbstractGitSCMSource() { } @Deprecated public AbstractGitSCMSource(String id) { setId(id); } @CheckForNull public abstract String getCredentialsId(); /** * @return Git remote URL */ public abstract String getRemote(); /** * @deprecated use {@link WildcardSCMSourceFilterTrait} * @return the includes. */ @Deprecated @Restricted(NoExternalUse.class) @RestrictedSince("3.4.0") public String getIncludes() { WildcardSCMHeadFilterTrait trait = SCMTrait.find(getTraits(), WildcardSCMHeadFilterTrait.class); return trait != null ? trait.getIncludes() : "*"; } /** * @return the excludes. * @deprecated use {@link WildcardSCMSourceFilterTrait} */ @Deprecated @Restricted(NoExternalUse.class) @RestrictedSince("3.4.0") public String getExcludes() { WildcardSCMHeadFilterTrait trait = SCMTrait.find(getTraits(), WildcardSCMHeadFilterTrait.class); return trait != null ? trait.getExcludes() : ""; } /** * Gets {@link GitRepositoryBrowser} to be used with this SCMSource. * @return Repository browser or {@code null} if the default tool should be used. * @since 2.5.1 * @deprecated use {@link GitBrowserSCMSourceTrait} */ @CheckForNull @Deprecated @Restricted(NoExternalUse.class) @RestrictedSince("3.4.0") public GitRepositoryBrowser getBrowser() { GitBrowserSCMSourceTrait trait = SCMTrait.find(getTraits(), GitBrowserSCMSourceTrait.class); return trait != null ? trait.getBrowser() : null; } /** * Gets Git tool to be used for this SCM Source. * @return Git Tool or {@code null} if the default tool should be used. * @since 2.5.1 * @deprecated use {@link GitToolSCMSourceTrait} */ @CheckForNull @Deprecated @Restricted(NoExternalUse.class) @RestrictedSince("3.4.0") public String getGitTool() { GitToolSCMSourceTrait trait = SCMTrait.find(getTraits(), GitToolSCMSourceTrait.class); return trait != null ? trait.getGitTool() : null; } /** * Gets list of extensions, which should be used with this branch source. * @return List of Extensions to be used. May be empty * @since 2.5.1 * @deprecated use corresponding {@link GitSCMExtensionTrait} (and if there isn't one then likely the * {@link GitSCMExtension} is not appropriate to use in the context of a {@link SCMSource}) */ @NonNull @Deprecated @Restricted(NoExternalUse.class) @RestrictedSince("3.4.0") public List<GitSCMExtension> getExtensions() { List<GitSCMExtension> extensions = new ArrayList<>(); for (SCMSourceTrait t : getTraits()) { if (t instanceof GitSCMExtensionTrait) { extensions.add(((GitSCMExtensionTrait) t).getExtension()); } } return Collections.unmodifiableList(extensions); } /** * Returns the {@link SCMSourceTrait} instances for this {@link AbstractGitSCMSource}. * @return the {@link SCMSourceTrait} instances * @since 3.4.0 */ @NonNull public List<SCMSourceTrait> getTraits() { // Always return empty list (we expect subclasses to override) return Collections.emptyList(); } /** * @deprecated use {@link RemoteNameSCMSourceTrait} * @return the remote name. */ @Deprecated @Restricted(NoExternalUse.class) @RestrictedSince("3.4.0") public String getRemoteName() { RemoteNameSCMSourceTrait trait = SCMTrait.find(getTraits(), RemoteNameSCMSourceTrait.class); return trait != null ? trait.getRemoteName() : DEFAULT_REMOTE_NAME; } /** * Resolves the {@link GitTool}. * @return the {@link GitTool}. * @deprecated use {@link #resolveGitTool(String)}. */ @CheckForNull @Deprecated @Restricted(DoNotUse.class) @RestrictedSince("3.4.0") protected GitTool resolveGitTool() { return resolveGitTool(getGitTool()); } /** * Resolves the {@link GitTool}. * @param gitTool the {@link GitTool#getName()} to resolve. * @return the {@link GitTool} * @since 3.4.0 */ @CheckForNull protected GitTool resolveGitTool(String gitTool) { return StringUtils.isBlank(gitTool) ? GitTool.getDefaultInstallation() : Jenkins.getActiveInstance() .getDescriptorByType(GitTool.DescriptorImpl.class) .getInstallation(gitTool); } private interface Retriever<T> { T run(GitClient client, String remoteName) throws IOException, InterruptedException; } @NonNull private <T, C extends GitSCMSourceContext<C, R>, R extends GitSCMSourceRequest> T doRetrieve(Retriever<T> retriever, @NonNull C context, @NonNull TaskListener listener, boolean prune) throws IOException, InterruptedException { String cacheEntry = getCacheEntry(); Lock cacheLock = getCacheLock(cacheEntry); cacheLock.lock(); try { File cacheDir = getCacheDir(cacheEntry); Git git = Git.with(listener, new EnvVars(EnvVars.masterEnvVars)).in(cacheDir); GitTool tool = resolveGitTool(context.gitTool()); if (tool != null) { git.using(tool.getGitExe()); } GitClient client = git.getClient(); client.addDefaultCredentials(getCredentials()); if (!client.hasGitRepo()) { listener.getLogger().println("Creating git repository in " + cacheDir); client.init(); } String remoteName = context.remoteName(); listener.getLogger().println("Setting " + remoteName + " to " + getRemote()); client.setRemoteUrl(remoteName, getRemote()); listener.getLogger().println((prune ? "Fetching & pruning " : "Fetching ") + remoteName + "..."); FetchCommand fetch = client.fetch_(); if (prune) { fetch = fetch.prune(); } URIish remoteURI = null; try { remoteURI = new URIish(remoteName); } catch (URISyntaxException ex) { listener.getLogger().println("URI syntax exception for '" + remoteName + "' " + ex); } fetch.from(remoteURI, context.asRefSpecs()).execute(); return retriever.run(client, remoteName); } finally { cacheLock.unlock(); } } /** * {@inheritDoc} */ @CheckForNull @Override protected SCMRevision retrieve(@NonNull final SCMHead head, @NonNull TaskListener listener) throws IOException, InterruptedException { final GitSCMSourceContext context = new GitSCMSourceContext<>(null, SCMHeadObserver.none()).withTraits(getTraits()); GitSCMTelescope telescope = GitSCMTelescope.of(this); if (telescope != null) { String remote = getRemote(); StandardUsernameCredentials credentials = getCredentials(); telescope.validate(remote, credentials); return telescope.getRevision(remote, credentials, head); } return doRetrieve(new Retriever<SCMRevision>() { @Override public SCMRevision run(GitClient client, String remoteName) throws IOException, InterruptedException { if (head instanceof GitTagSCMHead) { try { ObjectId objectId = client.revParse(Constants.R_TAGS + head.getName()); return new GitTagSCMRevision((GitTagSCMHead) head, objectId.name()); } catch (GitException e) { // tag does not exist return null; } } else { for (Branch b : client.getRemoteBranches()) { String branchName = StringUtils.removeStart(b.getName(), remoteName + "/"); if (branchName.equals(head.getName())) { return new SCMRevisionImpl(head, b.getSHA1String()); } } } return null; } }, context, listener, /* we don't prune remotes here, as we just want one head's revision */false); } /** * {@inheritDoc} */ @Override @SuppressFBWarnings(value="SE_BAD_FIELD", justification="Known non-serializable this") protected void retrieve(@CheckForNull SCMSourceCriteria criteria, @NonNull SCMHeadObserver observer, @CheckForNull SCMHeadEvent<?> event, @NonNull final TaskListener listener) throws IOException, InterruptedException { final GitSCMSourceContext context = new GitSCMSourceContext<>(criteria, observer).withTraits(getTraits()); final GitSCMTelescope telescope = GitSCMTelescope.of(this); if (telescope != null) { final String remote = getRemote(); final StandardUsernameCredentials credentials = getCredentials(); telescope.validate(remote, credentials); Set<GitSCMTelescope.ReferenceType> referenceTypes = new HashSet<>(); if (context.wantBranches()) { referenceTypes.add(GitSCMTelescope.ReferenceType.HEAD); } if (context.wantTags()) { referenceTypes.add(GitSCMTelescope.ReferenceType.TAG); } if (!referenceTypes.isEmpty()) { try (GitSCMSourceRequest request = context.newRequest(AbstractGitSCMSource.this, listener)) { listener.getLogger().println("Listing remote references..."); Iterable<SCMRevision> revisions = telescope.getRevisions(remote, credentials, referenceTypes); if (context.wantBranches()) { listener.getLogger().println("Checking branches..."); int count = 0; for (final SCMRevision revision : revisions) { if (!(revision instanceof SCMRevisionImpl) || (revision instanceof GitTagSCMRevision)) { continue; } count++; if (request.process(revision.getHead(), new SCMSourceRequest.RevisionLambda<SCMHead, SCMRevisionImpl>() { @NonNull @Override public SCMRevisionImpl create(@NonNull SCMHead head) throws IOException, InterruptedException { listener.getLogger() .println(" Checking branch " + revision.getHead().getName()); return (SCMRevisionImpl) revision; } }, new SCMSourceRequest.ProbeLambda<SCMHead, SCMRevisionImpl>() { @NonNull @Override public SCMSourceCriteria.Probe create(@NonNull SCMHead head, @NonNull SCMRevisionImpl revision) throws IOException, InterruptedException { return new TelescopingSCMProbe(telescope, remote, credentials, revision); } }, new SCMSourceRequest.Witness() { @Override public void record(@NonNull SCMHead head, SCMRevision revision, boolean isMatch) { if (isMatch) { listener.getLogger().println(" Met criteria"); } else { listener.getLogger().println(" Does not meet criteria"); } } } )) { listener.getLogger().format("Processed %d branches (query complete)%n", count); return; } } listener.getLogger().format("Processed %d branches%n", count); } if (context.wantTags()) { listener.getLogger().println("Checking tags..."); int count = 0; for (final SCMRevision revision : revisions) { if (!(revision instanceof GitTagSCMRevision)) { continue; } count++; if (request.process((GitTagSCMHead) revision.getHead(), new SCMSourceRequest.RevisionLambda<GitTagSCMHead, GitTagSCMRevision>() { @NonNull @Override public GitTagSCMRevision create(@NonNull GitTagSCMHead head) throws IOException, InterruptedException { listener.getLogger() .println(" Checking tag " + revision.getHead().getName()); return (GitTagSCMRevision) revision; } }, new SCMSourceRequest.ProbeLambda<GitTagSCMHead, GitTagSCMRevision>() { @NonNull @Override public SCMSourceCriteria.Probe create(@NonNull final GitTagSCMHead head, @NonNull GitTagSCMRevision revision) throws IOException, InterruptedException { return new TelescopingSCMProbe(telescope, remote, credentials, revision); } }, new SCMSourceRequest.Witness() { @Override public void record(@NonNull SCMHead head, SCMRevision revision, boolean isMatch) { if (isMatch) { listener.getLogger().println(" Met criteria"); } else { listener.getLogger().println(" Does not meet criteria"); } } } )) { listener.getLogger().format("Processed %d tags (query complete)%n", count); return; } } listener.getLogger().format("Processed %d tags%n", count); } } return; } } doRetrieve(new Retriever<Void>() { @Override public Void run(GitClient client, String remoteName) throws IOException, InterruptedException { final Repository repository = client.getRepository(); try (RevWalk walk = new RevWalk(repository); GitSCMSourceRequest request = context.newRequest(AbstractGitSCMSource.this, listener)) { Map<String, ObjectId> remoteReferences = null; if (context.wantBranches() || context.wantTags()) { listener.getLogger().println("Listing remote references..."); remoteReferences = client.getRemoteReferences( client.getRemoteUrl(remoteName), null, context.wantBranches(), context.wantTags() ); } if (context.wantBranches()) { discoverBranches(repository, walk, request, remoteReferences); } if (context.wantTags()) { discoverTags(repository, walk, request, remoteReferences); } } return null; } private void discoverBranches(final Repository repository, final RevWalk walk, GitSCMSourceRequest request, Map<String, ObjectId> remoteReferences) throws IOException, InterruptedException { listener.getLogger().println("Checking branches..."); walk.setRetainBody(false); int count = 0; for (final Map.Entry<String, ObjectId> ref : remoteReferences.entrySet()) { if (!ref.getKey().startsWith(Constants.R_HEADS)) { continue; } count++; final String branchName = StringUtils.removeStart(ref.getKey(), Constants.R_HEADS); if (request.process(new SCMHead(branchName), new SCMSourceRequest.IntermediateLambda<ObjectId>() { @Nullable @Override public ObjectId create() throws IOException, InterruptedException { listener.getLogger().println(" Checking branch " + branchName); return ref.getValue(); } }, new SCMSourceRequest.ProbeLambda<SCMHead, ObjectId>() { @NonNull @Override public SCMSourceCriteria.Probe create(@NonNull SCMHead head, @Nullable ObjectId revisionInfo) throws IOException, InterruptedException { RevCommit commit = walk.parseCommit(revisionInfo); final long lastModified = TimeUnit.SECONDS.toMillis(commit.getCommitTime()); final RevTree tree = commit.getTree(); return new TreeWalkingSCMProbe(branchName, lastModified, repository, tree); } }, new SCMSourceRequest.LazyRevisionLambda<SCMHead, SCMRevision, ObjectId>() { @NonNull @Override public SCMRevision create(@NonNull SCMHead head, @Nullable ObjectId intermediate) throws IOException, InterruptedException { return new SCMRevisionImpl(head, ref.getValue().name()); } }, new SCMSourceRequest.Witness() { @Override public void record(@NonNull SCMHead head, SCMRevision revision, boolean isMatch) { if (isMatch) { listener.getLogger().println(" Met criteria"); } else { listener.getLogger().println(" Does not meet criteria"); } } } )) { listener.getLogger().format("Processed %d branches (query complete)%n", count); return; } } listener.getLogger().format("Processed %d branches%n", count); } private void discoverTags(final Repository repository, final RevWalk walk, GitSCMSourceRequest request, Map<String, ObjectId> remoteReferences) throws IOException, InterruptedException { listener.getLogger().println("Checking tags..."); walk.setRetainBody(false); int count = 0; for (final Map.Entry<String, ObjectId> ref : remoteReferences.entrySet()) { if (!ref.getKey().startsWith(Constants.R_TAGS)) { continue; } count++; final String tagName = StringUtils.removeStart(ref.getKey(), Constants.R_TAGS); RevCommit commit = walk.parseCommit(ref.getValue()); final long lastModified = TimeUnit.SECONDS.toMillis(commit.getCommitTime()); if (request.process(new GitTagSCMHead(tagName, lastModified), new SCMSourceRequest.IntermediateLambda<ObjectId>() { @Nullable @Override public ObjectId create() throws IOException, InterruptedException { listener.getLogger().println(" Checking tag " + tagName); return ref.getValue(); } }, new SCMSourceRequest.ProbeLambda<GitTagSCMHead, ObjectId>() { @NonNull @Override public SCMSourceCriteria.Probe create(@NonNull GitTagSCMHead head, @Nullable ObjectId revisionInfo) throws IOException, InterruptedException { RevCommit commit = walk.parseCommit(revisionInfo); final long lastModified = TimeUnit.SECONDS.toMillis(commit.getCommitTime()); final RevTree tree = commit.getTree(); return new TreeWalkingSCMProbe(tagName, lastModified, repository, tree); } }, new SCMSourceRequest.LazyRevisionLambda<GitTagSCMHead, GitTagSCMRevision, ObjectId>() { @NonNull @Override public GitTagSCMRevision create(@NonNull GitTagSCMHead head, @Nullable ObjectId intermediate) throws IOException, InterruptedException { return new GitTagSCMRevision(head, ref.getValue().name()); } }, new SCMSourceRequest.Witness() { @Override public void record(@NonNull SCMHead head, SCMRevision revision, boolean isMatch) { if (isMatch) { listener.getLogger().println(" Met criteria"); } else { listener.getLogger().println(" Does not meet criteria"); } } } )) { listener.getLogger().format("Processed %d tags (query complete)%n", count); return; } } listener.getLogger().format("Processed %d tags%n", count); } }, context, listener, true); } /** * {@inheritDoc} */ @CheckForNull @Override protected SCMRevision retrieve(@NonNull final String revision, @NonNull final TaskListener listener) throws IOException, InterruptedException { final GitSCMSourceContext context = new GitSCMSourceContext<>(null, SCMHeadObserver.none()).withTraits(getTraits()); final GitSCMTelescope telescope = GitSCMTelescope.of(this); if (telescope != null) { final String remote = getRemote(); final StandardUsernameCredentials credentials = getCredentials(); telescope.validate(remote, credentials); SCMRevision result = telescope.getRevision(remote, credentials, revision); if (result != null) { return result; } result = telescope.getRevision(remote, credentials, Constants.R_HEADS + revision); if (result != null) { return result; } result = telescope.getRevision(remote, credentials, Constants.R_TAGS + revision); if (result != null) { return result; } return null; } return doRetrieve(new Retriever<SCMRevision>() { @Override public SCMRevision run(GitClient client, String remoteName) throws IOException, InterruptedException { String hash; try { hash = client.revParse(revision).name(); } catch (GitException x) { // Try prepending remote name in case it was a branch. try { hash = client.revParse(context.remoteName() + "/" + revision).name(); } catch (GitException x2) { listener.getLogger().println(x.getMessage()); listener.getLogger().println(x2.getMessage()); return null; } } return new SCMRevisionImpl(new SCMHead(revision), hash); } }, context, listener, false); } /** * {@inheritDoc} */ @NonNull @Override protected Set<String> retrieveRevisions(@NonNull final TaskListener listener) throws IOException, InterruptedException { final GitSCMSourceContext context = new GitSCMSourceContext<>(null, SCMHeadObserver.none()).withTraits(getTraits()); final GitSCMTelescope telescope = GitSCMTelescope.of(this); if (telescope != null) { final String remote = getRemote(); final StandardUsernameCredentials credentials = getCredentials(); telescope.validate(remote, credentials); Set<GitSCMTelescope.ReferenceType> referenceTypes = new HashSet<>(); if (context.wantBranches()) { referenceTypes.add(GitSCMTelescope.ReferenceType.HEAD); } if (context.wantTags()) { referenceTypes.add(GitSCMTelescope.ReferenceType.TAG); } Set<String> result = new HashSet<>(); for (SCMRevision r : telescope.getRevisions(remote, credentials, referenceTypes)) { if (r instanceof GitTagSCMRevision && context.wantTags()) { result.add(r.getHead().getName()); } else if (!(r instanceof GitTagSCMRevision) && context.wantBranches()) { result.add(r.getHead().getName()); } } return result; } Git git = Git.with(listener, new EnvVars(EnvVars.masterEnvVars)); GitTool tool = resolveGitTool(context.gitTool()); if (tool != null) { git.using(tool.getGitExe()); } GitClient client = git.getClient(); Set<String> revisions = new HashSet<>(); if (context.wantBranches() || context.wantTags()) { listener.getLogger().println("Listing remote references..."); Map<String, ObjectId> remoteReferences = client.getRemoteReferences( getRemote(), null, context.wantBranches(), context.wantTags() ); for (String name : remoteReferences.keySet()) { if (context.wantBranches()) { if (name.startsWith(Constants.R_HEADS)) { revisions.add(StringUtils.removeStart(name, Constants.R_HEADS)); } } if (context.wantTags()) { if (name.startsWith(Constants.R_TAGS)) { revisions.add(StringUtils.removeStart(name, Constants.R_TAGS)); } } } } return revisions; } /** * {@inheritDoc} */ @NonNull @Override protected List<Action> retrieveActions(@CheckForNull SCMSourceEvent event, @NonNull TaskListener listener) throws IOException, InterruptedException { final GitSCMTelescope telescope = GitSCMTelescope.of(this); if (telescope != null) { final String remote = getRemote(); final StandardUsernameCredentials credentials = getCredentials(); telescope.validate(remote, credentials); String target = telescope.getDefaultTarget(remote, credentials); if (target.startsWith(Constants.R_HEADS)) { // shorten standard names target = target.substring(Constants.R_HEADS.length()); } List<Action> result = new ArrayList<>(); if (StringUtils.isNotBlank(target)) { result.add(new GitRemoteHeadRefAction(getRemote(), target)); } return result; } final GitSCMSourceContext context = new GitSCMSourceContext<>(null, SCMHeadObserver.none()).withTraits(getTraits()); Git git = Git.with(listener, new EnvVars(EnvVars.masterEnvVars)); GitTool tool = resolveGitTool(context.gitTool()); if (tool != null) { git.using(tool.getGitExe()); } GitClient client = git.getClient(); Map<String, String> symrefs = client.getRemoteSymbolicReferences(getRemote(), null); if (symrefs.containsKey(Constants.HEAD)) { // Hurrah! The Server is Git 1.8.5 or newer and our client has symref reporting String target = symrefs.get(Constants.HEAD); if (target.startsWith(Constants.R_HEADS)) { // shorten standard names target = target.substring(Constants.R_HEADS.length()); } List<Action> result = new ArrayList<>(); if (StringUtils.isNotBlank(target)) { result.add(new GitRemoteHeadRefAction(getRemote(), target)); } return result; } // Ok, now we do it the old-school way... see what ref has the same hash as HEAD // I think we will still need to keep this code path even if JGit implements // https://bugs.eclipse.org/bugs/show_bug.cgi?id=514052 as there is always the potential that // the remote server is Git 1.8.4 or earlier, or that the local CLI git implementation is // older than git 2.8.0 (CentOS 6, CentOS 7, Debian 7, Debian 8, Ubuntu 14, and // Ubuntu 16) Map<String, ObjectId> remoteReferences = client.getRemoteReferences(getRemote(), null, false, false); if (remoteReferences.containsKey(Constants.HEAD)) { ObjectId head = remoteReferences.get(Constants.HEAD); Set<String> names = new TreeSet<>(); for (Map.Entry<String, ObjectId> entry : remoteReferences.entrySet()) { if (entry.getKey().equals(Constants.HEAD)) continue; if (head.equals(entry.getValue())) { names.add(entry.getKey()); } } // if there is one and only one match, that's the winner if (names.size() == 1) { String target = names.iterator().next(); if (target.startsWith(Constants.R_HEADS)) { // shorten standard names target = target.substring(Constants.R_HEADS.length()); } List<Action> result = new ArrayList<>(); if (StringUtils.isNotBlank(target)) { result.add(new GitRemoteHeadRefAction(getRemote(), target)); } return result; } // if there are multiple matches, prefer `master` if (names.contains(Constants.R_HEADS + Constants.MASTER)) { List<Action> result = new ArrayList<>(); result.add(new GitRemoteHeadRefAction(getRemote(), Constants.MASTER)); return result; } } // Give up, there's no way to get the primary branch return new ArrayList<>(); } /** * {@inheritDoc} */ @NonNull @Override protected List<Action> retrieveActions(@NonNull SCMHead head, @CheckForNull SCMHeadEvent event, @NonNull TaskListener listener) throws IOException, InterruptedException { SCMSourceOwner owner = getOwner(); if (owner instanceof Actionable) { for (GitRemoteHeadRefAction a: ((Actionable) owner).getActions(GitRemoteHeadRefAction.class)) { if (getRemote().equals(a.getRemote())) { if (head.getName().equals(a.getName())) { return Collections.<Action>singletonList(new PrimaryInstanceMetadataAction()); } } } } return Collections.emptyList(); } /** * {@inheritDoc} */ @Override protected boolean isCategoryEnabled(@NonNull SCMHeadCategory category) { if (super.isCategoryEnabled(category)) { for (SCMSourceTrait trait : getTraits()) { if (trait.isCategoryEnabled(category)) { return true; } } } return false; } protected String getCacheEntry() { return getCacheEntry(getRemote()); } protected static File getCacheDir(String cacheEntry) { Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { LOGGER.severe("Jenkins instance is null in AbstractGitSCMSource.getCacheDir"); return null; } File cacheDir = new File(new File(jenkins.getRootDir(), "caches"), cacheEntry); if (!cacheDir.isDirectory()) { boolean ok = cacheDir.mkdirs(); if (!ok) { LOGGER.log(Level.WARNING, "Failed mkdirs of {0}", cacheDir); } } return cacheDir; } protected static Lock getCacheLock(String cacheEntry) { Lock cacheLock; while (null == (cacheLock = cacheLocks.get(cacheEntry))) { cacheLocks.putIfAbsent(cacheEntry, new ReentrantLock()); } return cacheLock; } @CheckForNull protected StandardUsernameCredentials getCredentials() { String credentialsId = getCredentialsId(); if (credentialsId == null) { return null; } return CredentialsMatchers .firstOrNull( CredentialsProvider.lookupCredentials(StandardUsernameCredentials.class, getOwner(), ACL.SYSTEM, URIRequirementBuilder.fromUri(getRemote()).build()), CredentialsMatchers.allOf(CredentialsMatchers.withId(credentialsId), GitClient.CREDENTIALS_MATCHER)); } /** * @return the ref specs. * @deprecated use {@link RefSpecsSCMSourceTrait} */ @Deprecated @Restricted(NoExternalUse.class) @RestrictedSince("3.4.0") protected List<RefSpec> getRefSpecs() { return Collections.emptyList(); } /** * Instantiates a new {@link GitSCMBuilder}. * Subclasses should override this method if they want to use a custom {@link GitSCMBuilder} or if they need * to pre-decorare the builder. * * @param head the {@link SCMHead}. * @param revision the {@link SCMRevision}. * @return the {@link GitSCMBuilder} * @see #decorate(GitSCMBuilder) for post-decoration. */ protected GitSCMBuilder<?> newBuilder(@NonNull SCMHead head, @CheckForNull SCMRevision revision) { return new GitSCMBuilder<>(head, revision, getRemote(), getCredentialsId()); } /** * Performs final decoration of the {@link GitSCMBuilder}. This method is called by * {@link #build(SCMHead, SCMRevision)} immediately prior to returning {@link GitSCMBuilder#build()}. * Subclasses should override this method if they need to overrule builder behaviours defined by traits. * * @param builder the builder to decorate. */ protected void decorate(GitSCMBuilder<?> builder) { } /** * {@inheritDoc} */ @NonNull @Override public SCM build(@NonNull SCMHead head, @CheckForNull SCMRevision revision) { GitSCMBuilder<?> builder = newBuilder(head, revision); if (MethodUtils.isOverridden(AbstractGitSCMSource.class, getClass(), "getExtensions")) { builder.withExtensions(getExtensions()); } if (MethodUtils.isOverridden(AbstractGitSCMSource.class, getClass(), "getBrowser")) { builder.withBrowser(getBrowser()); } if (MethodUtils.isOverridden(AbstractGitSCMSource.class, getClass(), "getGitTool")) { builder.withGitTool(getGitTool()); } if (MethodUtils.isOverridden(AbstractGitSCMSource.class, getClass(), "getRefSpecs")) { List<String> specs = new ArrayList<>(); for (RefSpec spec: getRefSpecs()) { specs.add(spec.toString()); } builder.withoutRefSpecs().withRefSpecs(specs); } builder.withTraits(getTraits()); decorate(builder); return builder.build(); } /** * @return the {@link UserRemoteConfig} instances. * @deprecated use {@link GitSCMBuilder#asRemoteConfigs()} */ @Deprecated @Restricted(DoNotUse.class) @RestrictedSince("3.4.0") protected List<UserRemoteConfig> getRemoteConfigs() { List<RefSpec> refSpecs = getRefSpecs(); List<UserRemoteConfig> result = new ArrayList<>(refSpecs.size()); String remote = getRemote(); for (RefSpec refSpec : refSpecs) { result.add(new UserRemoteConfig(remote, getRemoteName(), refSpec.toString(), getCredentialsId())); } return result; } /** * Returns true if the branchName isn't matched by includes or is matched by excludes. * * @param branchName name of branch to be tested * @return true if branchName is excluded or is not included * @deprecated use {@link WildcardSCMSourceFilterTrait} */ @Deprecated @Restricted(DoNotUse.class) @RestrictedSince("3.4.0") protected boolean isExcluded (String branchName){ return !Pattern.matches(getPattern(getIncludes()), branchName) || (Pattern.matches(getPattern(getExcludes()), branchName)); } /** * Returns the pattern corresponding to the branches containing wildcards. * * @param branches branch names to evaluate * @return pattern corresponding to the branches containing wildcards */ private String getPattern(String branches){ StringBuilder quotedBranches = new StringBuilder(); for (String wildcard : branches.split(" ")){ StringBuilder quotedBranch = new StringBuilder(); for(String branch : wildcard.split("(?=[*])|(?<=[*])")){ if (branch.equals("*")) { quotedBranch.append(".*"); } else if (!branch.isEmpty()) { quotedBranch.append(Pattern.quote(branch)); } } if (quotedBranches.length()>0) { quotedBranches.append("|"); } quotedBranches.append(quotedBranch); } return quotedBranches.toString(); } /*package*/ static String getCacheEntry(String remote) { return "git-" + Util.getDigestOf(remote); } /** * Our implementation. */ public static class SCMRevisionImpl extends SCMRevision { /** * The subversion revision. */ private String hash; public SCMRevisionImpl(SCMHead head, String hash) { super(head); this.hash = hash; } public String getHash() { return hash; } /** * {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SCMRevisionImpl that = (SCMRevisionImpl) o; return StringUtils.equals(hash, that.hash) && getHead().equals(that.getHead()); } /** * {@inheritDoc} */ @Override public int hashCode() { return hash != null ? hash.hashCode() : 0; } /** * {@inheritDoc} */ @Override public String toString() { return hash; } } public static class SpecificRevisionBuildChooser extends BuildChooser { private final Revision revision; public SpecificRevisionBuildChooser(SCMRevisionImpl revision) { ObjectId sha1 = ObjectId.fromString(revision.getHash()); String name = revision.getHead().getName(); this.revision = new Revision(sha1, Collections.singleton(new Branch(name, sha1))); } /** * {@inheritDoc} */ @Override public Collection<Revision> getCandidateRevisions(boolean isPollCall, String singleBranch, GitClient git, TaskListener listener, BuildData buildData, BuildChooserContext context) throws GitException, IOException, InterruptedException { return Collections.singleton(revision); } /** * {@inheritDoc} */ @Override public Build prevBuildForChangelog(String branch, @Nullable BuildData data, GitClient git, BuildChooserContext context) throws IOException, InterruptedException { // we have ditched that crazy multiple branch stuff from the regular GIT SCM. return data == null ? null : data.lastBuild; } @Extension public static class DescriptorImpl extends BuildChooserDescriptor { /** * {@inheritDoc} */ @Override public String getDisplayName() { return "Specific revision"; } /** * {@inheritDoc} */ @Override public boolean isApplicable(java.lang.Class<? extends Item> job) { return SCMSourceOwner.class.isAssignableFrom(job); } } } /** * A {@link SCMProbe} that uses a local cache of the repository. * * @since TODO */ private static class TreeWalkingSCMProbe extends SCMProbe { private final String name; private final long lastModified; private final Repository repository; private final RevTree tree; public TreeWalkingSCMProbe(String name, long lastModified, Repository repository, RevTree tree) { this.name = name; this.lastModified = lastModified; this.repository = repository; this.tree = tree; } /** * {@inheritDoc} */ @Override public void close() throws IOException { // no-op } /** * {@inheritDoc} */ @Override public String name() { return name; } /** * {@inheritDoc} */ @Override public long lastModified() { return lastModified; } /** * {@inheritDoc} */ @Override @NonNull @SuppressFBWarnings(value = "NP_LOAD_OF_KNOWN_NULL_VALUE", justification = "TreeWalk.forPath can return null, compiler " + "generated code for try with resources handles it") public SCMProbeStat stat(@NonNull String path) throws IOException { try (TreeWalk tw = TreeWalk.forPath(repository, path, tree)) { if (tw == null) { return SCMProbeStat.fromType(SCMFile.Type.NONEXISTENT); } FileMode fileMode = tw.getFileMode(0); if (fileMode == FileMode.MISSING) { return SCMProbeStat.fromType(SCMFile.Type.NONEXISTENT); } if (fileMode == FileMode.EXECUTABLE_FILE) { return SCMProbeStat.fromType(SCMFile.Type.REGULAR_FILE); } if (fileMode == FileMode.REGULAR_FILE) { return SCMProbeStat.fromType(SCMFile.Type.REGULAR_FILE); } if (fileMode == FileMode.SYMLINK) { return SCMProbeStat.fromType(SCMFile.Type.LINK); } if (fileMode == FileMode.TREE) { return SCMProbeStat.fromType(SCMFile.Type.DIRECTORY); } return SCMProbeStat.fromType(SCMFile.Type.OTHER); } } } /** * A {@link SCMProbe} that uses a {@link GitSCMTelescope}. * * @since TODO */ private static class TelescopingSCMProbe extends SCMProbe { /** * Our telescope. */ @NonNull private final GitSCMTelescope telescope; /** * The repository URL. */ @NonNull private final String remote; /** * The credentials to use. */ @CheckForNull private final StandardCredentials credentials; /** * The revision this probe operates on. */ @NonNull private final SCMRevision revision; /** * The filesystem (lazy init). */ @GuardedBy("this") @CheckForNull private SCMFileSystem fileSystem; /** * The last modified timestamp (lazy init). */ @GuardedBy("this") @CheckForNull private Long lastModified; /** * Constructor. * @param telescope the telescope. * @param remote the repository URL * @param credentials the credentials to use. * @param revision the revision to probe. */ public TelescopingSCMProbe(GitSCMTelescope telescope, String remote, StandardCredentials credentials, SCMRevision revision) { this.telescope = telescope; this.remote = remote; this.credentials = credentials; this.revision = revision; } /** * {@inheritDoc} */ @NonNull @Override public SCMProbeStat stat(@NonNull String path) throws IOException { try { SCMFileSystem fileSystem; synchronized (this) { if (this.fileSystem == null) { this.fileSystem = telescope.build(remote, credentials, revision.getHead(), revision); } fileSystem = this.fileSystem; } if (fileSystem == null) { throw new IOException("Cannot connect to " + remote + " as " + (credentials == null ? "anonymous" : CredentialsNameProvider.name(credentials))); } return SCMProbeStat.fromType(fileSystem.child(path).getType()); } catch (InterruptedException e) { throw new IOException(e); } } /** * {@inheritDoc} */ @Override public synchronized void close() throws IOException { if (fileSystem != null) { fileSystem.close(); } fileSystem = null; } /** * {@inheritDoc} */ @Override public String name() { return revision.getHead().getName(); } /** * {@inheritDoc} */ @Override public long lastModified() { synchronized (this) { if (lastModified != null) { return lastModified; } } long lastModified; try { lastModified = telescope.getTimestamp(remote, credentials, revision.getHead()); } catch (IOException | InterruptedException e) { return -1L; } synchronized (this) { this.lastModified = lastModified; } return lastModified; } } }
src/main/java/jenkins/plugins/git/AbstractGitSCMSource.java
/* * The MIT License * * Copyright (c) 2013-2017, CloudBees, Inc., Stephen Connolly, Amadeus IT Group. * * 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. */ package jenkins.plugins.git; import com.cloudbees.plugins.credentials.CredentialsMatchers; import com.cloudbees.plugins.credentials.CredentialsNameProvider; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardCredentials; import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials; import com.cloudbees.plugins.credentials.domains.URIRequirementBuilder; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.EnvVars; import hudson.Extension; import hudson.RestrictedSince; import hudson.Util; import hudson.model.Action; import hudson.model.Actionable; import hudson.model.Item; import hudson.model.TaskListener; import hudson.plugins.git.Branch; import hudson.plugins.git.GitException; import hudson.plugins.git.GitSCM; import hudson.plugins.git.GitTool; import hudson.plugins.git.Revision; import hudson.plugins.git.UserRemoteConfig; import hudson.plugins.git.browser.GitRepositoryBrowser; import hudson.plugins.git.extensions.GitSCMExtension; import hudson.plugins.git.util.Build; import hudson.plugins.git.util.BuildChooser; import hudson.plugins.git.util.BuildChooserContext; import hudson.plugins.git.util.BuildChooserDescriptor; import hudson.plugins.git.util.BuildData; import hudson.scm.SCM; import hudson.security.ACL; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import jenkins.model.Jenkins; import jenkins.plugins.git.traits.GitBrowserSCMSourceTrait; import jenkins.plugins.git.traits.GitSCMExtensionTrait; import jenkins.plugins.git.traits.GitToolSCMSourceTrait; import jenkins.plugins.git.traits.RefSpecsSCMSourceTrait; import jenkins.plugins.git.traits.RemoteNameSCMSourceTrait; import jenkins.scm.api.SCMFile; import jenkins.scm.api.SCMFileSystem; import jenkins.scm.api.SCMHead; import jenkins.scm.api.SCMHeadCategory; import jenkins.scm.api.SCMHeadEvent; import jenkins.scm.api.SCMHeadObserver; import jenkins.scm.api.SCMProbe; import jenkins.scm.api.SCMProbeStat; import jenkins.scm.api.SCMRevision; import jenkins.scm.api.SCMSource; import jenkins.scm.api.SCMSourceCriteria; import jenkins.scm.api.SCMSourceEvent; import jenkins.scm.api.SCMSourceOwner; import jenkins.scm.api.metadata.PrimaryInstanceMetadataAction; import jenkins.scm.api.trait.SCMSourceRequest; import jenkins.scm.api.trait.SCMSourceTrait; import jenkins.scm.api.trait.SCMTrait; import jenkins.scm.impl.TagSCMHeadCategory; import jenkins.scm.impl.trait.WildcardSCMHeadFilterTrait; import jenkins.scm.impl.trait.WildcardSCMSourceFilterTrait; import net.jcip.annotations.GuardedBy; import org.apache.commons.lang.StringUtils; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.FileMode; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevTree; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.transport.RefSpec; import org.eclipse.jgit.transport.URIish; import org.eclipse.jgit.treewalk.TreeWalk; import org.jenkinsci.plugins.gitclient.FetchCommand; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.DoNotUse; import org.kohsuke.accmod.restrictions.NoExternalUse; /** * Base class for {@link SCMSource} implementations that produce {@link GitSCM} implementations. * * @since 2.0 */ public abstract class AbstractGitSCMSource extends SCMSource { /** * The default remote name to use when configuring the ref specs to use with fetch operations. * * @since 3.4.0 */ public static final String DEFAULT_REMOTE_NAME = "origin"; /** * The placeholder to use in ref spec templates in order to correctly ensure that the ref spec remote name * matches the remote name. * <p> * The template uses {@code @{...}} as that is an illegal sequence in a remote name * * @see <a href="https://github.com/git/git/blob/027a3b943b444a3e3a76f9a89803fc10245b858f/refs.c#L61-L68">git * source code rules on ref spec names</a> * @since 3.4.0 */ public static final String REF_SPEC_REMOTE_NAME_PLACEHOLDER_STR = "@{remote}"; /** * The regex for {@link #REF_SPEC_REMOTE_NAME_PLACEHOLDER_STR}. * * @since 3.4.0 */ public static final String REF_SPEC_REMOTE_NAME_PLACEHOLDER = "(?i)"+Pattern.quote(REF_SPEC_REMOTE_NAME_PLACEHOLDER_STR); /** * The default ref spec template. * * @since 3.4.0 */ public static final String REF_SPEC_DEFAULT = "+refs/heads/*:refs/remotes/" + REF_SPEC_REMOTE_NAME_PLACEHOLDER_STR + "/*"; /** * Keep one lock per cache directory. Lazy populated, but never purge, except on restart. */ private static final ConcurrentMap<String, Lock> cacheLocks = new ConcurrentHashMap<>(); private static final Logger LOGGER = Logger.getLogger(AbstractGitSCMSource.class.getName()); public AbstractGitSCMSource() { } @Deprecated public AbstractGitSCMSource(String id) { setId(id); } @CheckForNull public abstract String getCredentialsId(); /** * @return Git remote URL */ public abstract String getRemote(); /** * @deprecated use {@link WildcardSCMSourceFilterTrait} * @return the includes. */ @Deprecated @Restricted(NoExternalUse.class) @RestrictedSince("3.4.0") public String getIncludes() { WildcardSCMHeadFilterTrait trait = SCMTrait.find(getTraits(), WildcardSCMHeadFilterTrait.class); return trait != null ? trait.getIncludes() : "*"; } /** * @return the excludes. * @deprecated use {@link WildcardSCMSourceFilterTrait} */ @Deprecated @Restricted(NoExternalUse.class) @RestrictedSince("3.4.0") public String getExcludes() { WildcardSCMHeadFilterTrait trait = SCMTrait.find(getTraits(), WildcardSCMHeadFilterTrait.class); return trait != null ? trait.getExcludes() : ""; } /** * Gets {@link GitRepositoryBrowser} to be used with this SCMSource. * @return Repository browser or {@code null} if the default tool should be used. * @since 2.5.1 * @deprecated use {@link GitBrowserSCMSourceTrait} */ @CheckForNull @Deprecated @Restricted(NoExternalUse.class) @RestrictedSince("3.4.0") public GitRepositoryBrowser getBrowser() { GitBrowserSCMSourceTrait trait = SCMTrait.find(getTraits(), GitBrowserSCMSourceTrait.class); return trait != null ? trait.getBrowser() : null; } /** * Gets Git tool to be used for this SCM Source. * @return Git Tool or {@code null} if the default tool should be used. * @since 2.5.1 * @deprecated use {@link GitToolSCMSourceTrait} */ @CheckForNull @Deprecated @Restricted(NoExternalUse.class) @RestrictedSince("3.4.0") public String getGitTool() { GitToolSCMSourceTrait trait = SCMTrait.find(getTraits(), GitToolSCMSourceTrait.class); return trait != null ? trait.getGitTool() : null; } /** * Gets list of extensions, which should be used with this branch source. * @return List of Extensions to be used. May be empty * @since 2.5.1 * @deprecated use corresponding {@link GitSCMExtensionTrait} (and if there isn't one then likely the * {@link GitSCMExtension} is not appropriate to use in the context of a {@link SCMSource}) */ @NonNull @Deprecated @Restricted(NoExternalUse.class) @RestrictedSince("3.4.0") public List<GitSCMExtension> getExtensions() { List<GitSCMExtension> extensions = new ArrayList<>(); for (SCMSourceTrait t : getTraits()) { if (t instanceof GitSCMExtensionTrait) { extensions.add(((GitSCMExtensionTrait) t).getExtension()); } } return Collections.unmodifiableList(extensions); } /** * Returns the {@link SCMSourceTrait} instances for this {@link AbstractGitSCMSource}. * @return the {@link SCMSourceTrait} instances * @since 3.4.0 */ @NonNull public List<SCMSourceTrait> getTraits() { // Always return empty list (we expect subclasses to override) return Collections.emptyList(); } /** * @deprecated use {@link RemoteNameSCMSourceTrait} * @return the remote name. */ @Deprecated @Restricted(NoExternalUse.class) @RestrictedSince("3.4.0") public String getRemoteName() { RemoteNameSCMSourceTrait trait = SCMTrait.find(getTraits(), RemoteNameSCMSourceTrait.class); return trait != null ? trait.getRemoteName() : DEFAULT_REMOTE_NAME; } /** * Resolves the {@link GitTool}. * @return the {@link GitTool}. * @deprecated use {@link #resolveGitTool(String)}. */ @CheckForNull @Deprecated @Restricted(DoNotUse.class) @RestrictedSince("3.4.0") protected GitTool resolveGitTool() { return resolveGitTool(getGitTool()); } /** * Resolves the {@link GitTool}. * @param gitTool the {@link GitTool#getName()} to resolve. * @return the {@link GitTool} * @since 3.4.0 */ @CheckForNull protected GitTool resolveGitTool(String gitTool) { return StringUtils.isBlank(gitTool) ? GitTool.getDefaultInstallation() : Jenkins.getActiveInstance() .getDescriptorByType(GitTool.DescriptorImpl.class) .getInstallation(gitTool); } private interface Retriever<T> { T run(GitClient client, String remoteName) throws IOException, InterruptedException; } @NonNull private <T, C extends GitSCMSourceContext<C, R>, R extends GitSCMSourceRequest> T doRetrieve(Retriever<T> retriever, @NonNull C context, @NonNull TaskListener listener, boolean prune) throws IOException, InterruptedException { String cacheEntry = getCacheEntry(); Lock cacheLock = getCacheLock(cacheEntry); cacheLock.lock(); try { File cacheDir = getCacheDir(cacheEntry); Git git = Git.with(listener, new EnvVars(EnvVars.masterEnvVars)).in(cacheDir); GitTool tool = resolveGitTool(context.gitTool()); if (tool != null) { git.using(tool.getGitExe()); } GitClient client = git.getClient(); client.addDefaultCredentials(getCredentials()); if (!client.hasGitRepo()) { listener.getLogger().println("Creating git repository in " + cacheDir); client.init(); } String remoteName = context.remoteName(); listener.getLogger().println("Setting " + remoteName + " to " + getRemote()); client.setRemoteUrl(remoteName, getRemote()); listener.getLogger().println((prune ? "Fetching & pruning " : "Fetching ") + remoteName + "..."); FetchCommand fetch = client.fetch_(); if (prune) { fetch = fetch.prune(); } URIish remoteURI = null; try { remoteURI = new URIish(remoteName); } catch (URISyntaxException ex) { listener.getLogger().println("URI syntax exception for '" + remoteName + "' " + ex); } fetch.from(remoteURI, context.asRefSpecs()).execute(); return retriever.run(client, remoteName); } finally { cacheLock.unlock(); } } /** * {@inheritDoc} */ @CheckForNull @Override protected SCMRevision retrieve(@NonNull final SCMHead head, @NonNull TaskListener listener) throws IOException, InterruptedException { final GitSCMSourceContext context = new GitSCMSourceContext<>(null, SCMHeadObserver.none()).withTraits(getTraits()); GitSCMTelescope telescope = GitSCMTelescope.of(this); if (telescope != null) { String remote = getRemote(); StandardUsernameCredentials credentials = getCredentials(); telescope.validate(remote, credentials); return telescope.getRevision(remote, credentials, head); } return doRetrieve(new Retriever<SCMRevision>() { @Override public SCMRevision run(GitClient client, String remoteName) throws IOException, InterruptedException { if (head instanceof GitTagSCMHead) { try { ObjectId objectId = client.revParse(Constants.R_TAGS + head.getName()); return new GitTagSCMRevision((GitTagSCMHead) head, objectId.name()); } catch (GitException e) { // tag does not exist return null; } } else { for (Branch b : client.getRemoteBranches()) { String branchName = StringUtils.removeStart(b.getName(), remoteName + "/"); if (branchName.equals(head.getName())) { return new SCMRevisionImpl(head, b.getSHA1String()); } } } return null; } }, context, listener, /* we don't prune remotes here, as we just want one head's revision */false); } /** * {@inheritDoc} */ @Override @SuppressFBWarnings(value="SE_BAD_FIELD", justification="Known non-serializable this") protected void retrieve(@CheckForNull SCMSourceCriteria criteria, @NonNull SCMHeadObserver observer, @CheckForNull SCMHeadEvent<?> event, @NonNull final TaskListener listener) throws IOException, InterruptedException { final GitSCMSourceContext context = new GitSCMSourceContext<>(criteria, observer).withTraits(getTraits()); final GitSCMTelescope telescope = GitSCMTelescope.of(this); if (telescope != null) { final String remote = getRemote(); final StandardUsernameCredentials credentials = getCredentials(); telescope.validate(remote, credentials); Set<GitSCMTelescope.ReferenceType> referenceTypes = new HashSet<>(); if (context.wantBranches()) { referenceTypes.add(GitSCMTelescope.ReferenceType.HEAD); } if (context.wantTags()) { referenceTypes.add(GitSCMTelescope.ReferenceType.TAG); } if (!referenceTypes.isEmpty()) { try (GitSCMSourceRequest request = context.newRequest(AbstractGitSCMSource.this, listener)) { listener.getLogger().println("Listing remote references..."); Iterable<SCMRevision> revisions = telescope.getRevisions(remote, credentials, referenceTypes); if (context.wantBranches()) { listener.getLogger().println("Checking branches..."); int count = 0; for (final SCMRevision revision : revisions) { if (!(revision instanceof SCMRevisionImpl) || (revision instanceof GitTagSCMRevision)) { continue; } count++; if (request.process(revision.getHead(), new SCMSourceRequest.RevisionLambda<SCMHead, SCMRevisionImpl>() { @NonNull @Override public SCMRevisionImpl create(@NonNull SCMHead head) throws IOException, InterruptedException { listener.getLogger() .println(" Checking branch " + revision.getHead().getName()); return (SCMRevisionImpl) revision; } }, new SCMSourceRequest.ProbeLambda<SCMHead, SCMRevisionImpl>() { @NonNull @Override public SCMSourceCriteria.Probe create(@NonNull SCMHead head, @Nullable SCMRevisionImpl revision) throws IOException, InterruptedException { return new TelescopingSCMProbe(telescope, remote, credentials, revision); } }, new SCMSourceRequest.Witness() { @Override public void record(@NonNull SCMHead head, SCMRevision revision, boolean isMatch) { if (isMatch) { listener.getLogger().println(" Met criteria"); } else { listener.getLogger().println(" Does not meet criteria"); } } } )) { listener.getLogger().format("Processed %d branches (query complete)%n", count); return; } } listener.getLogger().format("Processed %d branches%n", count); } if (context.wantTags()) { listener.getLogger().println("Checking tags..."); int count = 0; for (final SCMRevision revision : revisions) { if (!(revision instanceof GitTagSCMRevision)) { continue; } count++; if (request.process((GitTagSCMHead) revision.getHead(), new SCMSourceRequest.RevisionLambda<GitTagSCMHead, GitTagSCMRevision>() { @NonNull @Override public GitTagSCMRevision create(@NonNull GitTagSCMHead head) throws IOException, InterruptedException { listener.getLogger() .println(" Checking tag " + revision.getHead().getName()); return (GitTagSCMRevision) revision; } }, new SCMSourceRequest.ProbeLambda<GitTagSCMHead, GitTagSCMRevision>() { @NonNull @Override public SCMSourceCriteria.Probe create(@NonNull final GitTagSCMHead head, @Nullable GitTagSCMRevision revision) throws IOException, InterruptedException { return new TelescopingSCMProbe(telescope, remote, credentials, revision); } }, new SCMSourceRequest.Witness() { @Override public void record(@NonNull SCMHead head, SCMRevision revision, boolean isMatch) { if (isMatch) { listener.getLogger().println(" Met criteria"); } else { listener.getLogger().println(" Does not meet criteria"); } } } )) { listener.getLogger().format("Processed %d tags (query complete)%n", count); return; } } listener.getLogger().format("Processed %d tags%n", count); } } return; } } doRetrieve(new Retriever<Void>() { @Override public Void run(GitClient client, String remoteName) throws IOException, InterruptedException { final Repository repository = client.getRepository(); try (RevWalk walk = new RevWalk(repository); GitSCMSourceRequest request = context.newRequest(AbstractGitSCMSource.this, listener)) { Map<String, ObjectId> remoteReferences = null; if (context.wantBranches() || context.wantTags()) { listener.getLogger().println("Listing remote references..."); remoteReferences = client.getRemoteReferences( client.getRemoteUrl(remoteName), null, context.wantBranches(), context.wantTags() ); } if (context.wantBranches()) { discoverBranches(repository, walk, request, remoteReferences); } if (context.wantTags()) { discoverTags(repository, walk, request, remoteReferences); } } return null; } private void discoverBranches(final Repository repository, final RevWalk walk, GitSCMSourceRequest request, Map<String, ObjectId> remoteReferences) throws IOException, InterruptedException { listener.getLogger().println("Checking branches..."); walk.setRetainBody(false); int count = 0; for (final Map.Entry<String, ObjectId> ref : remoteReferences.entrySet()) { if (!ref.getKey().startsWith(Constants.R_HEADS)) { continue; } count++; final String branchName = StringUtils.removeStart(ref.getKey(), Constants.R_HEADS); if (request.process(new SCMHead(branchName), new SCMSourceRequest.IntermediateLambda<ObjectId>() { @Nullable @Override public ObjectId create() throws IOException, InterruptedException { listener.getLogger().println(" Checking branch " + branchName); return ref.getValue(); } }, new SCMSourceRequest.ProbeLambda<SCMHead, ObjectId>() { @NonNull @Override public SCMSourceCriteria.Probe create(@NonNull SCMHead head, @Nullable ObjectId revisionInfo) throws IOException, InterruptedException { RevCommit commit = walk.parseCommit(revisionInfo); final long lastModified = TimeUnit.SECONDS.toMillis(commit.getCommitTime()); final RevTree tree = commit.getTree(); return new TreeWalkingSCMProbe(branchName, lastModified, repository, tree); } }, new SCMSourceRequest.LazyRevisionLambda<SCMHead, SCMRevision, ObjectId>() { @NonNull @Override public SCMRevision create(@NonNull SCMHead head, @Nullable ObjectId intermediate) throws IOException, InterruptedException { return new SCMRevisionImpl(head, ref.getValue().name()); } }, new SCMSourceRequest.Witness() { @Override public void record(@NonNull SCMHead head, SCMRevision revision, boolean isMatch) { if (isMatch) { listener.getLogger().println(" Met criteria"); } else { listener.getLogger().println(" Does not meet criteria"); } } } )) { listener.getLogger().format("Processed %d branches (query complete)%n", count); return; } } listener.getLogger().format("Processed %d branches%n", count); } private void discoverTags(final Repository repository, final RevWalk walk, GitSCMSourceRequest request, Map<String, ObjectId> remoteReferences) throws IOException, InterruptedException { listener.getLogger().println("Checking tags..."); walk.setRetainBody(false); int count = 0; for (final Map.Entry<String, ObjectId> ref : remoteReferences.entrySet()) { if (!ref.getKey().startsWith(Constants.R_TAGS)) { continue; } count++; final String tagName = StringUtils.removeStart(ref.getKey(), Constants.R_TAGS); RevCommit commit = walk.parseCommit(ref.getValue()); final long lastModified = TimeUnit.SECONDS.toMillis(commit.getCommitTime()); if (request.process(new GitTagSCMHead(tagName, lastModified), new SCMSourceRequest.IntermediateLambda<ObjectId>() { @Nullable @Override public ObjectId create() throws IOException, InterruptedException { listener.getLogger().println(" Checking tag " + tagName); return ref.getValue(); } }, new SCMSourceRequest.ProbeLambda<GitTagSCMHead, ObjectId>() { @NonNull @Override public SCMSourceCriteria.Probe create(@NonNull GitTagSCMHead head, @Nullable ObjectId revisionInfo) throws IOException, InterruptedException { RevCommit commit = walk.parseCommit(revisionInfo); final long lastModified = TimeUnit.SECONDS.toMillis(commit.getCommitTime()); final RevTree tree = commit.getTree(); return new TreeWalkingSCMProbe(tagName, lastModified, repository, tree); } }, new SCMSourceRequest.LazyRevisionLambda<GitTagSCMHead, GitTagSCMRevision, ObjectId>() { @NonNull @Override public GitTagSCMRevision create(@NonNull GitTagSCMHead head, @Nullable ObjectId intermediate) throws IOException, InterruptedException { return new GitTagSCMRevision(head, ref.getValue().name()); } }, new SCMSourceRequest.Witness() { @Override public void record(@NonNull SCMHead head, SCMRevision revision, boolean isMatch) { if (isMatch) { listener.getLogger().println(" Met criteria"); } else { listener.getLogger().println(" Does not meet criteria"); } } } )) { listener.getLogger().format("Processed %d tags (query complete)%n", count); return; } } listener.getLogger().format("Processed %d tags%n", count); } }, context, listener, true); } /** * {@inheritDoc} */ @CheckForNull @Override protected SCMRevision retrieve(@NonNull final String revision, @NonNull final TaskListener listener) throws IOException, InterruptedException { final GitSCMSourceContext context = new GitSCMSourceContext<>(null, SCMHeadObserver.none()).withTraits(getTraits()); final GitSCMTelescope telescope = GitSCMTelescope.of(this); if (telescope != null) { final String remote = getRemote(); final StandardUsernameCredentials credentials = getCredentials(); telescope.validate(remote, credentials); SCMRevision result = telescope.getRevision(remote, credentials, revision); if (result != null) { return result; } result = telescope.getRevision(remote, credentials, Constants.R_HEADS + revision); if (result != null) { return result; } result = telescope.getRevision(remote, credentials, Constants.R_TAGS + revision); if (result != null) { return result; } return null; } return doRetrieve(new Retriever<SCMRevision>() { @Override public SCMRevision run(GitClient client, String remoteName) throws IOException, InterruptedException { String hash; try { hash = client.revParse(revision).name(); } catch (GitException x) { // Try prepending remote name in case it was a branch. try { hash = client.revParse(context.remoteName() + "/" + revision).name(); } catch (GitException x2) { listener.getLogger().println(x.getMessage()); listener.getLogger().println(x2.getMessage()); return null; } } return new SCMRevisionImpl(new SCMHead(revision), hash); } }, context, listener, false); } /** * {@inheritDoc} */ @NonNull @Override protected Set<String> retrieveRevisions(@NonNull final TaskListener listener) throws IOException, InterruptedException { final GitSCMSourceContext context = new GitSCMSourceContext<>(null, SCMHeadObserver.none()).withTraits(getTraits()); final GitSCMTelescope telescope = GitSCMTelescope.of(this); if (telescope != null) { final String remote = getRemote(); final StandardUsernameCredentials credentials = getCredentials(); telescope.validate(remote, credentials); Set<GitSCMTelescope.ReferenceType> referenceTypes = new HashSet<>(); if (context.wantBranches()) { referenceTypes.add(GitSCMTelescope.ReferenceType.HEAD); } if (context.wantTags()) { referenceTypes.add(GitSCMTelescope.ReferenceType.TAG); } Set<String> result = new HashSet<>(); for (SCMRevision r : telescope.getRevisions(remote, credentials, referenceTypes)) { if (r instanceof GitTagSCMRevision && context.wantTags()) { result.add(r.getHead().getName()); } else if (!(r instanceof GitTagSCMRevision) && context.wantBranches()) { result.add(r.getHead().getName()); } } return result; } Git git = Git.with(listener, new EnvVars(EnvVars.masterEnvVars)); GitTool tool = resolveGitTool(context.gitTool()); if (tool != null) { git.using(tool.getGitExe()); } GitClient client = git.getClient(); Set<String> revisions = new HashSet<>(); if (context.wantBranches() || context.wantTags()) { listener.getLogger().println("Listing remote references..."); Map<String, ObjectId> remoteReferences = client.getRemoteReferences( getRemote(), null, context.wantBranches(), context.wantTags() ); for (String name : remoteReferences.keySet()) { if (context.wantBranches()) { if (name.startsWith(Constants.R_HEADS)) { revisions.add(StringUtils.removeStart(name, Constants.R_HEADS)); } } if (context.wantTags()) { if (name.startsWith(Constants.R_TAGS)) { revisions.add(StringUtils.removeStart(name, Constants.R_TAGS)); } } } } return revisions; } /** * {@inheritDoc} */ @NonNull @Override protected List<Action> retrieveActions(@CheckForNull SCMSourceEvent event, @NonNull TaskListener listener) throws IOException, InterruptedException { final GitSCMTelescope telescope = GitSCMTelescope.of(this); if (telescope != null) { final String remote = getRemote(); final StandardUsernameCredentials credentials = getCredentials(); telescope.validate(remote, credentials); String target = telescope.getDefaultTarget(remote, credentials); if (target.startsWith(Constants.R_HEADS)) { // shorten standard names target = target.substring(Constants.R_HEADS.length()); } List<Action> result = new ArrayList<>(); if (StringUtils.isNotBlank(target)) { result.add(new GitRemoteHeadRefAction(getRemote(), target)); } return result; } final GitSCMSourceContext context = new GitSCMSourceContext<>(null, SCMHeadObserver.none()).withTraits(getTraits()); Git git = Git.with(listener, new EnvVars(EnvVars.masterEnvVars)); GitTool tool = resolveGitTool(context.gitTool()); if (tool != null) { git.using(tool.getGitExe()); } GitClient client = git.getClient(); Map<String, String> symrefs = client.getRemoteSymbolicReferences(getRemote(), null); if (symrefs.containsKey(Constants.HEAD)) { // Hurrah! The Server is Git 1.8.5 or newer and our client has symref reporting String target = symrefs.get(Constants.HEAD); if (target.startsWith(Constants.R_HEADS)) { // shorten standard names target = target.substring(Constants.R_HEADS.length()); } List<Action> result = new ArrayList<>(); if (StringUtils.isNotBlank(target)) { result.add(new GitRemoteHeadRefAction(getRemote(), target)); } return result; } // Ok, now we do it the old-school way... see what ref has the same hash as HEAD // I think we will still need to keep this code path even if JGit implements // https://bugs.eclipse.org/bugs/show_bug.cgi?id=514052 as there is always the potential that // the remote server is Git 1.8.4 or earlier, or that the local CLI git implementation is // older than git 2.8.0 (CentOS 6, CentOS 7, Debian 7, Debian 8, Ubuntu 14, and // Ubuntu 16) Map<String, ObjectId> remoteReferences = client.getRemoteReferences(getRemote(), null, false, false); if (remoteReferences.containsKey(Constants.HEAD)) { ObjectId head = remoteReferences.get(Constants.HEAD); Set<String> names = new TreeSet<>(); for (Map.Entry<String, ObjectId> entry : remoteReferences.entrySet()) { if (entry.getKey().equals(Constants.HEAD)) continue; if (head.equals(entry.getValue())) { names.add(entry.getKey()); } } // if there is one and only one match, that's the winner if (names.size() == 1) { String target = names.iterator().next(); if (target.startsWith(Constants.R_HEADS)) { // shorten standard names target = target.substring(Constants.R_HEADS.length()); } List<Action> result = new ArrayList<>(); if (StringUtils.isNotBlank(target)) { result.add(new GitRemoteHeadRefAction(getRemote(), target)); } return result; } // if there are multiple matches, prefer `master` if (names.contains(Constants.R_HEADS + Constants.MASTER)) { List<Action> result = new ArrayList<>(); result.add(new GitRemoteHeadRefAction(getRemote(), Constants.MASTER)); return result; } } // Give up, there's no way to get the primary branch return new ArrayList<>(); } /** * {@inheritDoc} */ @NonNull @Override protected List<Action> retrieveActions(@NonNull SCMHead head, @CheckForNull SCMHeadEvent event, @NonNull TaskListener listener) throws IOException, InterruptedException { SCMSourceOwner owner = getOwner(); if (owner instanceof Actionable) { for (GitRemoteHeadRefAction a: ((Actionable) owner).getActions(GitRemoteHeadRefAction.class)) { if (getRemote().equals(a.getRemote())) { if (head.getName().equals(a.getName())) { return Collections.<Action>singletonList(new PrimaryInstanceMetadataAction()); } } } } return Collections.emptyList(); } /** * {@inheritDoc} */ @Override protected boolean isCategoryEnabled(@NonNull SCMHeadCategory category) { if (super.isCategoryEnabled(category)) { for (SCMSourceTrait trait : getTraits()) { if (trait.isCategoryEnabled(category)) { return true; } } } return false; } protected String getCacheEntry() { return getCacheEntry(getRemote()); } protected static File getCacheDir(String cacheEntry) { Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { LOGGER.severe("Jenkins instance is null in AbstractGitSCMSource.getCacheDir"); return null; } File cacheDir = new File(new File(jenkins.getRootDir(), "caches"), cacheEntry); if (!cacheDir.isDirectory()) { boolean ok = cacheDir.mkdirs(); if (!ok) { LOGGER.log(Level.WARNING, "Failed mkdirs of {0}", cacheDir); } } return cacheDir; } protected static Lock getCacheLock(String cacheEntry) { Lock cacheLock; while (null == (cacheLock = cacheLocks.get(cacheEntry))) { cacheLocks.putIfAbsent(cacheEntry, new ReentrantLock()); } return cacheLock; } @CheckForNull protected StandardUsernameCredentials getCredentials() { String credentialsId = getCredentialsId(); if (credentialsId == null) { return null; } return CredentialsMatchers .firstOrNull( CredentialsProvider.lookupCredentials(StandardUsernameCredentials.class, getOwner(), ACL.SYSTEM, URIRequirementBuilder.fromUri(getRemote()).build()), CredentialsMatchers.allOf(CredentialsMatchers.withId(credentialsId), GitClient.CREDENTIALS_MATCHER)); } /** * @return the ref specs. * @deprecated use {@link RefSpecsSCMSourceTrait} */ @Deprecated @Restricted(NoExternalUse.class) @RestrictedSince("3.4.0") protected List<RefSpec> getRefSpecs() { return Collections.emptyList(); } /** * Instantiates a new {@link GitSCMBuilder}. * Subclasses should override this method if they want to use a custom {@link GitSCMBuilder} or if they need * to pre-decorare the builder. * * @param head the {@link SCMHead}. * @param revision the {@link SCMRevision}. * @return the {@link GitSCMBuilder} * @see #decorate(GitSCMBuilder) for post-decoration. */ protected GitSCMBuilder<?> newBuilder(@NonNull SCMHead head, @CheckForNull SCMRevision revision) { return new GitSCMBuilder<>(head, revision, getRemote(), getCredentialsId()); } /** * Performs final decoration of the {@link GitSCMBuilder}. This method is called by * {@link #build(SCMHead, SCMRevision)} immediately prior to returning {@link GitSCMBuilder#build()}. * Subclasses should override this method if they need to overrule builder behaviours defined by traits. * * @param builder the builder to decorate. */ protected void decorate(GitSCMBuilder<?> builder) { } /** * {@inheritDoc} */ @NonNull @Override public SCM build(@NonNull SCMHead head, @CheckForNull SCMRevision revision) { GitSCMBuilder<?> builder = newBuilder(head, revision); if (MethodUtils.isOverridden(AbstractGitSCMSource.class, getClass(), "getExtensions")) { builder.withExtensions(getExtensions()); } if (MethodUtils.isOverridden(AbstractGitSCMSource.class, getClass(), "getBrowser")) { builder.withBrowser(getBrowser()); } if (MethodUtils.isOverridden(AbstractGitSCMSource.class, getClass(), "getGitTool")) { builder.withGitTool(getGitTool()); } if (MethodUtils.isOverridden(AbstractGitSCMSource.class, getClass(), "getRefSpecs")) { List<String> specs = new ArrayList<>(); for (RefSpec spec: getRefSpecs()) { specs.add(spec.toString()); } builder.withoutRefSpecs().withRefSpecs(specs); } builder.withTraits(getTraits()); decorate(builder); return builder.build(); } /** * @return the {@link UserRemoteConfig} instances. * @deprecated use {@link GitSCMBuilder#asRemoteConfigs()} */ @Deprecated @Restricted(DoNotUse.class) @RestrictedSince("3.4.0") protected List<UserRemoteConfig> getRemoteConfigs() { List<RefSpec> refSpecs = getRefSpecs(); List<UserRemoteConfig> result = new ArrayList<>(refSpecs.size()); String remote = getRemote(); for (RefSpec refSpec : refSpecs) { result.add(new UserRemoteConfig(remote, getRemoteName(), refSpec.toString(), getCredentialsId())); } return result; } /** * Returns true if the branchName isn't matched by includes or is matched by excludes. * * @param branchName name of branch to be tested * @return true if branchName is excluded or is not included * @deprecated use {@link WildcardSCMSourceFilterTrait} */ @Deprecated @Restricted(DoNotUse.class) @RestrictedSince("3.4.0") protected boolean isExcluded (String branchName){ return !Pattern.matches(getPattern(getIncludes()), branchName) || (Pattern.matches(getPattern(getExcludes()), branchName)); } /** * Returns the pattern corresponding to the branches containing wildcards. * * @param branches branch names to evaluate * @return pattern corresponding to the branches containing wildcards */ private String getPattern(String branches){ StringBuilder quotedBranches = new StringBuilder(); for (String wildcard : branches.split(" ")){ StringBuilder quotedBranch = new StringBuilder(); for(String branch : wildcard.split("(?=[*])|(?<=[*])")){ if (branch.equals("*")) { quotedBranch.append(".*"); } else if (!branch.isEmpty()) { quotedBranch.append(Pattern.quote(branch)); } } if (quotedBranches.length()>0) { quotedBranches.append("|"); } quotedBranches.append(quotedBranch); } return quotedBranches.toString(); } /*package*/ static String getCacheEntry(String remote) { return "git-" + Util.getDigestOf(remote); } /** * Our implementation. */ public static class SCMRevisionImpl extends SCMRevision { /** * The subversion revision. */ private String hash; public SCMRevisionImpl(SCMHead head, String hash) { super(head); this.hash = hash; } public String getHash() { return hash; } /** * {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SCMRevisionImpl that = (SCMRevisionImpl) o; return StringUtils.equals(hash, that.hash) && getHead().equals(that.getHead()); } /** * {@inheritDoc} */ @Override public int hashCode() { return hash != null ? hash.hashCode() : 0; } /** * {@inheritDoc} */ @Override public String toString() { return hash; } } public static class SpecificRevisionBuildChooser extends BuildChooser { private final Revision revision; public SpecificRevisionBuildChooser(SCMRevisionImpl revision) { ObjectId sha1 = ObjectId.fromString(revision.getHash()); String name = revision.getHead().getName(); this.revision = new Revision(sha1, Collections.singleton(new Branch(name, sha1))); } /** * {@inheritDoc} */ @Override public Collection<Revision> getCandidateRevisions(boolean isPollCall, String singleBranch, GitClient git, TaskListener listener, BuildData buildData, BuildChooserContext context) throws GitException, IOException, InterruptedException { return Collections.singleton(revision); } /** * {@inheritDoc} */ @Override public Build prevBuildForChangelog(String branch, @Nullable BuildData data, GitClient git, BuildChooserContext context) throws IOException, InterruptedException { // we have ditched that crazy multiple branch stuff from the regular GIT SCM. return data == null ? null : data.lastBuild; } @Extension public static class DescriptorImpl extends BuildChooserDescriptor { /** * {@inheritDoc} */ @Override public String getDisplayName() { return "Specific revision"; } /** * {@inheritDoc} */ @Override public boolean isApplicable(java.lang.Class<? extends Item> job) { return SCMSourceOwner.class.isAssignableFrom(job); } } } /** * A {@link SCMProbe} that uses a local cache of the repository. * * @since TODO */ private static class TreeWalkingSCMProbe extends SCMProbe { private final String name; private final long lastModified; private final Repository repository; private final RevTree tree; public TreeWalkingSCMProbe(String name, long lastModified, Repository repository, RevTree tree) { this.name = name; this.lastModified = lastModified; this.repository = repository; this.tree = tree; } /** * {@inheritDoc} */ @Override public void close() throws IOException { // no-op } /** * {@inheritDoc} */ @Override public String name() { return name; } /** * {@inheritDoc} */ @Override public long lastModified() { return lastModified; } /** * {@inheritDoc} */ @Override @NonNull @SuppressFBWarnings(value = "NP_LOAD_OF_KNOWN_NULL_VALUE", justification = "TreeWalk.forPath can return null, compiler " + "generated code for try with resources handles it") public SCMProbeStat stat(@NonNull String path) throws IOException { try (TreeWalk tw = TreeWalk.forPath(repository, path, tree)) { if (tw == null) { return SCMProbeStat.fromType(SCMFile.Type.NONEXISTENT); } FileMode fileMode = tw.getFileMode(0); if (fileMode == FileMode.MISSING) { return SCMProbeStat.fromType(SCMFile.Type.NONEXISTENT); } if (fileMode == FileMode.EXECUTABLE_FILE) { return SCMProbeStat.fromType(SCMFile.Type.REGULAR_FILE); } if (fileMode == FileMode.REGULAR_FILE) { return SCMProbeStat.fromType(SCMFile.Type.REGULAR_FILE); } if (fileMode == FileMode.SYMLINK) { return SCMProbeStat.fromType(SCMFile.Type.LINK); } if (fileMode == FileMode.TREE) { return SCMProbeStat.fromType(SCMFile.Type.DIRECTORY); } return SCMProbeStat.fromType(SCMFile.Type.OTHER); } } } /** * A {@link SCMProbe} that uses a {@link GitSCMTelescope}. * * @since TODO */ private static class TelescopingSCMProbe extends SCMProbe { /** * Our telescope. */ @NonNull private final GitSCMTelescope telescope; /** * The repository URL. */ @NonNull private final String remote; /** * The credentials to use. */ @CheckForNull private final StandardCredentials credentials; /** * The revision this probe operates on. */ @NonNull private final SCMRevision revision; /** * The filesystem (lazy init). */ @GuardedBy("this") @CheckForNull private SCMFileSystem fileSystem; /** * The last modified timestamp (lazy init). */ @GuardedBy("this") @CheckForNull private Long lastModified; /** * Constructor. * @param telescope the telescope. * @param remote the repository URL * @param credentials the credentials to use. * @param revision the revision to probe. */ public TelescopingSCMProbe(GitSCMTelescope telescope, String remote, StandardCredentials credentials, SCMRevision revision) { this.telescope = telescope; this.remote = remote; this.credentials = credentials; this.revision = revision; } /** * {@inheritDoc} */ @NonNull @Override public SCMProbeStat stat(@NonNull String path) throws IOException { try { SCMFileSystem fileSystem; synchronized (this) { if (this.fileSystem == null) { this.fileSystem = telescope.build(remote, credentials, revision.getHead(), revision); } fileSystem = this.fileSystem; } if (fileSystem == null) { throw new IOException("Cannot connect to " + remote + " as " + (credentials == null ? "anonymous" : CredentialsNameProvider.name(credentials))); } return SCMProbeStat.fromType(fileSystem.child(path).getType()); } catch (InterruptedException e) { throw new IOException(e); } } /** * {@inheritDoc} */ @Override public synchronized void close() throws IOException { if (fileSystem != null) { fileSystem.close(); } fileSystem = null; } /** * {@inheritDoc} */ @Override public String name() { return revision.getHead().getName(); } /** * {@inheritDoc} */ @Override public long lastModified() { synchronized (this) { if (lastModified != null) { return lastModified; } } long lastModified; try { lastModified = telescope.getTimestamp(remote, credentials, revision.getHead()); } catch (IOException | InterruptedException e) { return -1L; } synchronized (this) { this.lastModified = lastModified; } return lastModified; } } }
Annotate Probe.create(head, @NonNull revision) The revision argument to TelescopingSCMProbe is annotated as @NonNull, so the method that passes it to TelescopingSCMProbe should also be annotated @NonNull. To see the findbugs warning before this change: mvn clean -Dtest=KilnGitTest install
src/main/java/jenkins/plugins/git/AbstractGitSCMSource.java
Annotate Probe.create(head, @NonNull revision)
<ide><path>rc/main/java/jenkins/plugins/git/AbstractGitSCMSource.java <ide> @NonNull <ide> @Override <ide> public SCMSourceCriteria.Probe create(@NonNull SCMHead head, <del> @Nullable SCMRevisionImpl revision) <add> @NonNull SCMRevisionImpl revision) <ide> throws IOException, InterruptedException { <ide> return new TelescopingSCMProbe(telescope, remote, credentials, revision); <ide> } <ide> @NonNull <ide> @Override <ide> public SCMSourceCriteria.Probe create(@NonNull final GitTagSCMHead head, <del> @Nullable GitTagSCMRevision revision) <add> @NonNull GitTagSCMRevision revision) <ide> throws IOException, InterruptedException { <ide> return new TelescopingSCMProbe(telescope, remote, credentials, revision); <ide> }
JavaScript
apache-2.0
32ca42f57332daa3ead84e69ae3a9286569eb157
0
apuckey/thalassa-aqueduct,apuckey/thalassa-aqueduct,PearsonEducation/thalassa-aqueduct
var assert = require('assert') , Hapi = require('hapi'); var Api = module.exports = function (opts) { if (typeof opts !== 'object') opts = {}; assert(opts.data, 'opts.data required'); assert(opts.haproxyManager, 'opts.haproxyManager required'); this.data = opts.data; this.haproxyManager = opts.haproxyManager; this.prefix = opts.prefix || ''; }; Api.prototype.routes = function() { var self = this; return [ { method: 'GET', path: self.prefix + '/frontends/{name}', config: { handler: self.handleGetFrontend() } }, { method: 'GET', path: self.prefix + '/backends/{name}', config: { handler: self.handleGetBackend() } }, { method: 'GET', path: self.prefix + '/backends/{name}/members', config: { handler: self.handleGetBackendMembers() } }, { method: 'GET', path: self.prefix + '/frontends', config: { handler: self.handleGetFrontends() } }, { method: 'GET', path: self.prefix + '/backends', config: { handler: self.handleGetBackends() } }, { method: 'PUT', path: self.prefix + '/frontends/{name}', config: { handler: self.handlePutFrontend(), payload: 'parse', validate: self.validatePutFrontend() } }, { method: 'PUT', path: self.prefix + '/backends/{name}', config: { handler: self.handlePutBackend(), payload: 'parse', validate: self.validatePutBackend() } }, { method: 'DELETE', path: self.prefix + '/frontends/{name}', config: { handler: self.handleDeleteFrontend() } }, { method: 'DELETE', path: self.prefix + '/backends/{name}', config: { handler: self.handleDeleteBackend() } }, { method: 'GET', path: self.prefix + '/haproxy/config', config: { handler: self.handleGetHaproxyConfig() } } ]; }; Api.prototype.handleGetFrontend = function () { var self = this; return function(request, reply) { var name = this.params.name; var id = self.data.frontendId(name); var row = self.data.frontends.get(id); if (!row) return reply('frontend ' + name + ' not found').code(404); return reply(row.toJSON()); }; }; Api.prototype.handleGetBackend = function () { var self = this; return function(request, reply) { var name = this.params.name; var id = self.data.backendId(name); var row = self.data.backends.get(id); if (!row) return reply('backend ' + name + ' not found').code(404); return reply(row.toJSON()); }; }; Api.prototype.handleGetBackendMembers = function () { var self = this; return function(request, reply) { var name = this.params.name; var id = self.data.backendId(name); var row = self.data.backends.get(id); if (!row) return reply('backend ' + name + ' not found').code(404); return reply(row.toJSON().members); }; }; Api.prototype.handleGetFrontends = function () { var self = this; return function(request, reply) { return reply(self.data.frontends.toJSON()); }; }; Api.prototype.handleGetBackends = function () { var self = this; return function(request, reply) { return reply(self.data.backends.toJSON()); }; }; Api.prototype.handlePutFrontend = function () { var self = this; return function(request, reply) { var name = this.params.name; var id = self.data.frontendId(name); var obj = request.payload; obj.name = name; self.data.setFrontend(obj); return reply(200); }; }; Api.prototype.validatePutFrontend = function () { return { payload: { _type : Hapi.types.String().optional(), name : Hapi.types.String(), bind : Hapi.types.String(), backend : Hapi.types.String(), mode : Hapi.types.String().valid(['http', 'tcp']).optional(), keepalive : Hapi.types.String().valid(['default','close','server-close']).optional(), rules : Hapi.types.Array().optional(), natives : Hapi.types.Array().optional() } }; }; Api.prototype.handlePutBackend = function () { var self = this; return function(request, reply) { var name = this.params.name; var id = self.data.backendId(name); var obj = request.payload; obj.name = name; self.data.setBackend(obj); return reply(200); }; }; Api.prototype.validatePutBackend = function () { return { payload: { _type : Hapi.types.String().optional(), name : Hapi.types.String(), type : Hapi.types.String().valid(['spindrift', 'static']), role : Hapi.types.String().optional(), version : Hapi.types.String().optional(), balance : Hapi.types.String().optional(), host : Hapi.types.String().optional(), mode : Hapi.types.String().valid(['http', 'tcp']).optional(), members : Hapi.types.Array().optional(), natives : Hapi.types.Array().optional() } }; }; Api.prototype.handleDeleteFrontend = function () { var self = this; return function(request, reply) { var name = this.params.name; var id = self.data.frontendId(name); var row = self.data.frontends.get(id); if (!row) return reply('frontend ' + name + ' not found').code(404); self.data.frontends.rm(id); return reply(200); }; }; Api.prototype.handleDeleteBackend = function () { var self = this; return function(request, reply) { var name = this.params.name; var id = self.data.backendId(name); var row = self.data.backends.get(id); if (!row) return reply('backend ' + name + ' not found').code(404); self.data.backends.rm(id); return reply(200); }; }; Api.prototype.handleGetHaproxyConfig = function () { var self = this; return function(request, reply) { return reply(self.haproxyManager.latestConfig).type('text/plain'); }; };
lib/Api.js
var assert = require('assert') , Hapi = require('Hapi'); var Api = module.exports = function (opts) { if (typeof opts !== 'object') opts = {}; assert(opts.data, 'opts.data required'); assert(opts.haproxyManager, 'opts.haproxyManager required'); this.data = opts.data; this.haproxyManager = opts.haproxyManager; this.prefix = opts.prefix || ''; }; Api.prototype.routes = function() { var self = this; return [ { method: 'GET', path: self.prefix + '/frontends/{name}', config: { handler: self.handleGetFrontend() } }, { method: 'GET', path: self.prefix + '/backends/{name}', config: { handler: self.handleGetBackend() } }, { method: 'GET', path: self.prefix + '/backends/{name}/members', config: { handler: self.handleGetBackendMembers() } }, { method: 'GET', path: self.prefix + '/frontends', config: { handler: self.handleGetFrontends() } }, { method: 'GET', path: self.prefix + '/backends', config: { handler: self.handleGetBackends() } }, { method: 'PUT', path: self.prefix + '/frontends/{name}', config: { handler: self.handlePutFrontend(), payload: 'parse', validate: self.validatePutFrontend() } }, { method: 'PUT', path: self.prefix + '/backends/{name}', config: { handler: self.handlePutBackend(), payload: 'parse', validate: self.validatePutBackend() } }, { method: 'DELETE', path: self.prefix + '/frontends/{name}', config: { handler: self.handleDeleteFrontend() } }, { method: 'DELETE', path: self.prefix + '/backends/{name}', config: { handler: self.handleDeleteBackend() } }, { method: 'GET', path: self.prefix + '/haproxy/config', config: { handler: self.handleGetHaproxyConfig() } } ]; }; Api.prototype.handleGetFrontend = function () { var self = this; return function(request, reply) { var name = this.params.name; var id = self.data.frontendId(name); var row = self.data.frontends.get(id); if (!row) return reply('frontend ' + name + ' not found').code(404); return reply(row.toJSON()); }; }; Api.prototype.handleGetBackend = function () { var self = this; return function(request, reply) { var name = this.params.name; var id = self.data.backendId(name); var row = self.data.backends.get(id); if (!row) return reply('backend ' + name + ' not found').code(404); return reply(row.toJSON()); }; }; Api.prototype.handleGetBackendMembers = function () { var self = this; return function(request, reply) { var name = this.params.name; var id = self.data.backendId(name); var row = self.data.backends.get(id); if (!row) return reply('backend ' + name + ' not found').code(404); return reply(row.toJSON().members); }; }; Api.prototype.handleGetFrontends = function () { var self = this; return function(request, reply) { return reply(self.data.frontends.toJSON()); }; }; Api.prototype.handleGetBackends = function () { var self = this; return function(request, reply) { return reply(self.data.backends.toJSON()); }; }; Api.prototype.handlePutFrontend = function () { var self = this; return function(request, reply) { var name = this.params.name; var id = self.data.frontendId(name); var obj = request.payload; obj.name = name; self.data.setFrontend(obj); return reply(200); }; }; Api.prototype.validatePutFrontend = function () { return { payload: { _type : Hapi.types.String().optional(), name : Hapi.types.String(), bind : Hapi.types.String(), backend : Hapi.types.String(), mode : Hapi.types.String().valid(['http', 'tcp']).optional(), keepalive : Hapi.types.String().valid(['default','close','server-close']).optional(), rules : Hapi.types.Array().optional(), natives : Hapi.types.Array().optional() } }; }; Api.prototype.handlePutBackend = function () { var self = this; return function(request, reply) { var name = this.params.name; var id = self.data.backendId(name); var obj = request.payload; obj.name = name; self.data.setBackend(obj); return reply(200); }; }; Api.prototype.validatePutBackend = function () { return { payload: { _type : Hapi.types.String().optional(), name : Hapi.types.String(), type : Hapi.types.String().valid(['spindrift', 'static']), role : Hapi.types.String().optional(), version : Hapi.types.String().optional(), balance : Hapi.types.String().optional(), host : Hapi.types.String().optional(), mode : Hapi.types.String().valid(['http', 'tcp']).optional(), members : Hapi.types.Array().optional(), natives : Hapi.types.Array().optional() } }; }; Api.prototype.handleDeleteFrontend = function () { var self = this; return function(request, reply) { var name = this.params.name; var id = self.data.frontendId(name); var row = self.data.frontends.get(id); if (!row) return reply('frontend ' + name + ' not found').code(404); self.data.frontends.rm(id); return reply(200); }; }; Api.prototype.handleDeleteBackend = function () { var self = this; return function(request, reply) { var name = this.params.name; var id = self.data.backendId(name); var row = self.data.backends.get(id); if (!row) return reply('backend ' + name + ' not found').code(404); self.data.backends.rm(id); return reply(200); }; }; Api.prototype.handleGetHaproxyConfig = function () { var self = this; return function(request, reply) { return reply(self.haproxyManager.latestConfig).type('text/plain'); }; };
fixed chase issue on hapi require
lib/Api.js
fixed chase issue on hapi require
<ide><path>ib/Api.js <ide> var assert = require('assert') <del> , Hapi = require('Hapi'); <add> , Hapi = require('hapi'); <ide> <ide> var Api = module.exports = function (opts) { <ide> if (typeof opts !== 'object') opts = {};
Java
apache-2.0
2b97e5c6a9bf4cebfa5f97cd3c197aaee5a94977
0
fabric8io/kubernetes-client,fabric8io/kubernetes-client,fabric8io/kubernetes-client
/** * Copyright (C) 2015 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.kubernetes.api.model; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.ObjectCodec; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import io.sundr.builder.annotations.Buildable; import io.sundr.builder.annotations.Inline; import java.io.IOException; import java.math.BigDecimal; import java.math.MathContext; import java.util.HashMap; import java.util.Map; import java.io.Serializable; /** * Quantity is fixed point representation of a number. * It provides convenient marshalling/unmarshalling in JSON or YAML, * in addition to String or getAmountInBytes accessors. * */ @JsonDeserialize(using = Quantity.Deserializer.class) @JsonSerialize(using = Quantity.Serializer.class) @Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage=true, builderPackage = "io.fabric8.kubernetes.api.builder", inline = @Inline(type = Doneable.class, prefix = "Doneable", value = "done")) public class Quantity implements Serializable { private static final String AT_LEAST_ONE_DIGIT_REGEX = ".*\\d+.*"; private String amount; private String format; private Map<String, Object> additionalProperties = new HashMap<String, Object>(); /** * No args constructor for use in serialization * */ public Quantity() { } /** * Single argument constructor for setting amount. * * @param amount amount of quantity specified. */ public Quantity(String amount) { Quantity parsedQuantity = parse(amount); this.amount = parsedQuantity.getAmount(); this.format = parsedQuantity.getFormat(); } /** * Double argument constructor for setting amount along with format. * * @param amount amount of quantity specified * @param format format for the amount. */ public Quantity(String amount, String format) { this.amount = amount; this.format = format; } public String getAmount() { return amount; } public void setAmount(String amount) { this.amount = amount; } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } public static BigDecimal getAmountInBytes(Quantity quantity) throws ArithmeticException { String value = ""; if (quantity.getAmount() != null && quantity.getFormat() != null) { value = quantity.getAmount() + quantity.getFormat(); } else if (quantity.getAmount() != null) { value = quantity.getAmount(); } if (value == null || value.isEmpty()) { throw new IllegalArgumentException("Invalid quantity value passed to parse"); } // Append Extra zeroes if starting with decimal if (!Character.isDigit(value.indexOf(0)) && value.startsWith(".")) { value = "0" + value; } Quantity amountFormatPair = parse(value); String formatStr = amountFormatPair.getFormat(); // Handle Decimal exponent case if ((formatStr.matches(AT_LEAST_ONE_DIGIT_REGEX)) && formatStr.length() > 1) { int exponent = Integer.parseInt(formatStr.substring(1)); return new BigDecimal("10").pow(exponent, MathContext.DECIMAL64).multiply(new BigDecimal(amountFormatPair.getAmount())); } BigDecimal digit = new BigDecimal(amountFormatPair.getAmount()); BigDecimal multiple = new BigDecimal("1"); BigDecimal binaryFactor = new BigDecimal("2"); BigDecimal decimalFactor = new BigDecimal("10"); switch (formatStr) { case "Ki": multiple = binaryFactor.pow(10, MathContext.DECIMAL64); break; case "Mi": multiple = binaryFactor.pow(20, MathContext.DECIMAL64); break; case "Gi": multiple = binaryFactor.pow(30, MathContext.DECIMAL64); break; case "Ti": multiple = binaryFactor.pow(40, MathContext.DECIMAL64); break; case "Pi": multiple = binaryFactor.pow(50, MathContext.DECIMAL64); break; case "Ei": multiple = binaryFactor.pow(60, MathContext.DECIMAL64); break; case "n": multiple = decimalFactor.pow(-9, MathContext.DECIMAL64); break; case "u": multiple = decimalFactor.pow(-6, MathContext.DECIMAL64); break; case "m": multiple = decimalFactor.pow(-3, MathContext.DECIMAL64); break; case "k": multiple = decimalFactor.pow(3, MathContext.DECIMAL64); break; case "M": multiple = decimalFactor.pow(6, MathContext.DECIMAL64); break; case "G": multiple = decimalFactor.pow(9, MathContext.DECIMAL64); break; case "T": multiple = decimalFactor.pow(12, MathContext.DECIMAL64); break; case "P": multiple = decimalFactor.pow(15, MathContext.DECIMAL64); break; case "E": multiple = decimalFactor.pow(18, MathContext.DECIMAL64); break; } return digit.multiply(multiple); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Quantity quantity = (Quantity) o; return getAmountInBytes(this) .compareTo(getAmountInBytes(quantity)) == 0; } @Override public int hashCode() { return getAmountInBytes(this).toBigInteger().hashCode(); } @Override public String toString() { StringBuilder b = new StringBuilder(); if (getAmount() != null) { b.append(getAmount()); } if (getFormat() != null) { b.append(getFormat()); } return b.toString(); } public static Quantity parse(String quantityAsString) { if (quantityAsString == null || quantityAsString.isEmpty()) { throw new IllegalArgumentException("Invalid quantity string format passed."); } String[] quantityComponents = quantityAsString.split("[eEinumkKMGTP]+"); String amountStr = quantityComponents[0]; String formatStr = quantityAsString.substring(quantityComponents[0].length()); // For cases like 4e9 or 129e-6, formatStr would be e9 and e-6 respectively // we need to check whether this is valid too. It must not end with character. if (formatStr.matches(AT_LEAST_ONE_DIGIT_REGEX) && Character.isAlphabetic(formatStr.charAt(formatStr.length() - 1))) { throw new IllegalArgumentException("Invalid quantity string format passed"); } return new Quantity(amountStr, formatStr); } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } public static class Serializer extends JsonSerializer<Quantity> { @Override public void serialize(Quantity value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { if (value != null) { StringBuilder objAsStringBuilder = new StringBuilder(); if (value.getAmount() != null) { objAsStringBuilder.append(value.getAmount()); } if (value.getFormat() != null) { objAsStringBuilder.append(value.getFormat()); } jgen.writeString(objAsStringBuilder.toString()); } else { jgen.writeNull(); } } } public static class Deserializer extends JsonDeserializer<Quantity> { @Override public Quantity deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException { ObjectCodec oc = jsonParser.getCodec(); JsonNode node = oc.readTree(jsonParser); Quantity quantity = null; if (node.get("amount") != null && node.get("format") != null) { quantity = new Quantity(node.get("amount").toString(), node.get("format").toString()); } else if (node.get("amount") != null) { quantity = new Quantity(node.get("amount").toString()); } else { quantity = new Quantity(node.asText()); } return quantity; } } }
kubernetes-model-generator/kubernetes-model-core/src/main/java/io/fabric8/kubernetes/api/model/Quantity.java
/** * Copyright (C) 2015 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.kubernetes.api.model; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.ObjectCodec; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import io.sundr.builder.annotations.Buildable; import io.sundr.builder.annotations.Inline; import lombok.EqualsAndHashCode; import lombok.ToString; import java.io.IOException; import java.math.BigDecimal; import java.math.MathContext; import java.util.HashMap; import java.util.Map; import java.io.Serializable; /** * Quantity is fixed point representation of a number. * It provides convenient marshalling/unmarshalling in JSON or YAML, * in addition to String or getAmountInBytes accessors. * */ @JsonDeserialize(using = Quantity.Deserializer.class) @JsonSerialize(using = Quantity.Serializer.class) @ToString @EqualsAndHashCode @Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage=true, builderPackage = "io.fabric8.kubernetes.api.builder", inline = @Inline(type = Doneable.class, prefix = "Doneable", value = "done")) public class Quantity implements Serializable { private static final String AT_LEAST_ONE_DIGIT_REGEX = ".*\\d+.*"; private String amount; private String format; private Map<String, Object> additionalProperties = new HashMap<String, Object>(); /** * No args constructor for use in serialization * */ public Quantity() { } /** * Single argument constructor for setting amount. * * @param amount amount of quantity specified. */ public Quantity(String amount) { Quantity parsedQuantity = parse(amount); this.amount = parsedQuantity.getAmount(); this.format = parsedQuantity.getFormat(); } /** * Double argument constructor for setting amount along with format. * * @param amount amount of quantity specified * @param format format for the amount. */ public Quantity(String amount, String format) { this.amount = amount; this.format = format; } public String getAmount() { return amount; } public void setAmount(String amount) { this.amount = amount; } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } public static BigDecimal getAmountInBytes(Quantity quantity) throws ArithmeticException { String value = ""; if (quantity.getAmount() != null && quantity.getFormat() != null) { value = quantity.getAmount() + quantity.getFormat(); } else if (quantity.getAmount() != null) { value = quantity.getAmount(); } if (value == null || value.isEmpty()) { throw new IllegalArgumentException("Invalid quantity value passed to parse"); } // Append Extra zeroes if starting with decimal if (!Character.isDigit(value.indexOf(0)) && value.startsWith(".")) { value = "0" + value; } Quantity amountFormatPair = parse(value); String formatStr = amountFormatPair.getFormat(); // Handle Decimal exponent case if ((formatStr.matches(AT_LEAST_ONE_DIGIT_REGEX)) && formatStr.length() > 1) { int exponent = Integer.parseInt(formatStr.substring(1)); return new BigDecimal("10").pow(exponent, MathContext.DECIMAL64).multiply(new BigDecimal(amountFormatPair.getAmount())); } BigDecimal digit = new BigDecimal(amountFormatPair.getAmount()); BigDecimal multiple = new BigDecimal("1"); BigDecimal binaryFactor = new BigDecimal("2"); BigDecimal decimalFactor = new BigDecimal("10"); switch (formatStr) { case "Ki": multiple = binaryFactor.pow(10, MathContext.DECIMAL64); break; case "Mi": multiple = binaryFactor.pow(20, MathContext.DECIMAL64); break; case "Gi": multiple = binaryFactor.pow(30, MathContext.DECIMAL64); break; case "Ti": multiple = binaryFactor.pow(40, MathContext.DECIMAL64); break; case "Pi": multiple = binaryFactor.pow(50, MathContext.DECIMAL64); break; case "Ei": multiple = binaryFactor.pow(60, MathContext.DECIMAL64); break; case "n": multiple = decimalFactor.pow(-9, MathContext.DECIMAL64); break; case "u": multiple = decimalFactor.pow(-6, MathContext.DECIMAL64); break; case "m": multiple = decimalFactor.pow(-3, MathContext.DECIMAL64); break; case "k": multiple = decimalFactor.pow(3, MathContext.DECIMAL64); break; case "M": multiple = decimalFactor.pow(6, MathContext.DECIMAL64); break; case "G": multiple = decimalFactor.pow(9, MathContext.DECIMAL64); break; case "T": multiple = decimalFactor.pow(12, MathContext.DECIMAL64); break; case "P": multiple = decimalFactor.pow(15, MathContext.DECIMAL64); break; case "E": multiple = decimalFactor.pow(18, MathContext.DECIMAL64); break; } return digit.multiply(multiple); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Quantity quantity = (Quantity) o; return getAmountInBytes(this) .compareTo(getAmountInBytes(quantity)) == 0; } @Override public int hashCode() { return getAmountInBytes(this).toBigInteger().hashCode(); } @Override public String toString() { StringBuilder b = new StringBuilder(); if (getAmount() != null) { b.append(getAmount()); } if (getFormat() != null) { b.append(getFormat()); } return b.toString(); } public static Quantity parse(String quantityAsString) { if (quantityAsString == null || quantityAsString.isEmpty()) { throw new IllegalArgumentException("Invalid quantity string format passed."); } String[] quantityComponents = quantityAsString.split("[eEinumkKMGTP]+"); String amountStr = quantityComponents[0]; String formatStr = quantityAsString.substring(quantityComponents[0].length()); // For cases like 4e9 or 129e-6, formatStr would be e9 and e-6 respectively // we need to check whether this is valid too. It must not end with character. if (formatStr.matches(AT_LEAST_ONE_DIGIT_REGEX) && Character.isAlphabetic(formatStr.charAt(formatStr.length() - 1))) { throw new IllegalArgumentException("Invalid quantity string format passed"); } return new Quantity(amountStr, formatStr); } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } public static class Serializer extends JsonSerializer<Quantity> { @Override public void serialize(Quantity value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { if (value != null) { StringBuilder objAsStringBuilder = new StringBuilder(); if (value.getAmount() != null) { objAsStringBuilder.append(value.getAmount()); } if (value.getFormat() != null) { objAsStringBuilder.append(value.getFormat()); } jgen.writeString(objAsStringBuilder.toString()); } else { jgen.writeNull(); } } } public static class Deserializer extends JsonDeserializer<Quantity> { @Override public Quantity deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException { ObjectCodec oc = jsonParser.getCodec(); JsonNode node = oc.readTree(jsonParser); Quantity quantity = null; if (node.get("amount") != null && node.get("format") != null) { quantity = new Quantity(node.get("amount").toString(), node.get("format").toString()); } else if (node.get("amount") != null) { quantity = new Quantity(node.get("amount").toString()); } else { quantity = new Quantity(node.asText()); } return quantity; } } }
Remove lombok annotations from Quantity class Signed-off-by: Stanislav Knot <[email protected]>
kubernetes-model-generator/kubernetes-model-core/src/main/java/io/fabric8/kubernetes/api/model/Quantity.java
Remove lombok annotations from Quantity class
<ide><path>ubernetes-model-generator/kubernetes-model-core/src/main/java/io/fabric8/kubernetes/api/model/Quantity.java <ide> import com.fasterxml.jackson.databind.annotation.JsonSerialize; <ide> import io.sundr.builder.annotations.Buildable; <ide> import io.sundr.builder.annotations.Inline; <del>import lombok.EqualsAndHashCode; <del>import lombok.ToString; <ide> <ide> import java.io.IOException; <ide> import java.math.BigDecimal; <ide> */ <ide> @JsonDeserialize(using = Quantity.Deserializer.class) <ide> @JsonSerialize(using = Quantity.Serializer.class) <del>@ToString <del>@EqualsAndHashCode <ide> @Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage=true, builderPackage = "io.fabric8.kubernetes.api.builder", inline = @Inline(type = Doneable.class, prefix = "Doneable", value = "done")) <ide> public class Quantity implements Serializable { <ide>
Java
apache-2.0
d89d9ccc058372948a776ba6cf81866512c22163
0
gxa/gxa,gxa/gxa,gxa/gxa,gxa/gxa,gxa/gxa
/* * Copyright 2008-2010 Microarray Informatics Team, EMBL-European Bioinformatics Institute * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * For further details of the Gene Expression Atlas project, including source code, * downloads and documentation, please see: * * http://gxa.github.com/gxa */ package uk.ac.ebi.gxa.index.builder.service; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.common.SolrInputDocument; import uk.ac.ebi.gxa.efo.Efo; import uk.ac.ebi.gxa.efo.EfoTerm; import uk.ac.ebi.gxa.index.GeneExpressionAnalyticsTable; import uk.ac.ebi.gxa.index.builder.IndexBuilderException; import uk.ac.ebi.gxa.index.builder.IndexAllCommand; import uk.ac.ebi.gxa.index.builder.UpdateIndexForExperimentCommand; import uk.ac.ebi.gxa.utils.ChunkedSublistIterator; import uk.ac.ebi.gxa.utils.EscapeUtil; import uk.ac.ebi.gxa.utils.SequenceIterator; import uk.ac.ebi.microarray.atlas.model.*; import uk.ac.ebi.gxa.properties.AtlasProperties; import java.io.IOException; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; /** * An {@link IndexBuilderService} that generates index documents from the genes in the Atlas database, and enriches the * data with expression values, links to EFO and other useful measurements. * <p/> * This is a heavily modified version of an original class first adapted to Atlas purposes by Pavel Kurnosov. * <p/> * Note that this implementation does NOT support updates - regardless of whether the update flag is set to true, this * will rebuild the index every time. * * @author Tony Burdett * @date 22-Sep-2009 */ public class GeneAtlasIndexBuilderService extends IndexBuilderService { private Map<String, Collection<String>> ontomap = new HashMap<String, Collection<String>>(); private Efo efo; private AtlasProperties atlasProperties; public void setAtlasProperties(AtlasProperties atlasProperties) { this.atlasProperties = atlasProperties; } public AtlasProperties getAtlasProperties() { return atlasProperties; } public Efo getEfo() { return efo; } public void setEfo(Efo efo) { this.efo = efo; } @Override public void processCommand(IndexAllCommand indexAll, ProgressUpdater progressUpdater) throws IndexBuilderException { super.processCommand(indexAll, progressUpdater); //To change body of overridden methods use File | Settings | File Templates. getLog().info("Indexing all genes..."); indexGenes(progressUpdater, getAtlasDAO().getAllGenesFast()); } @Override public void processCommand(UpdateIndexForExperimentCommand cmd, ProgressUpdater progressUpdater) throws IndexBuilderException { super.processCommand(cmd, progressUpdater); getLog().info("Indexing genes for experiment " + cmd.getAccession() + "..."); indexGenes(progressUpdater, getAtlasDAO().getGenesByExperimentAccession(cmd.getAccession())); } private void indexGenes(final ProgressUpdater progressUpdater, final List<Gene> genes) throws IndexBuilderException { java.util.Collections.shuffle(genes); final int total = genes.size(); getLog().info("Found " + total + " genes to index"); loadEfoMapping(); final AtomicInteger processed = new AtomicInteger(0); final long timeStart = System.currentTimeMillis(); final int fnothnum = atlasProperties.getGeneAtlasIndexBuilderNumberOfThreads(); final int chunksize = atlasProperties.getGeneAtlasIndexBuilderChunksize(); final int commitfreq = atlasProperties.getGeneAtlasIndexBuilderCommitfreq(); getLog().info("Using " + fnothnum + " threads, " + chunksize + " chunk size, committing every " + commitfreq + " genes"); ExecutorService tpool = Executors.newFixedThreadPool(fnothnum); List<Callable<Boolean>> tasks = new ArrayList<Callable<Boolean>>(genes.size()); // index all genes in parallel for (final List<Gene> genelist : new Iterable<List<Gene>>() { public Iterator<List<Gene>> iterator() { return new ChunkedSublistIterator<List<Gene>>(genes, chunksize); } }) { // for each gene, submit a new task to the executor tasks.add(new Callable<Boolean>() { public Boolean call() throws IOException, SolrServerException { try { StringBuilder sblog = new StringBuilder(); long timeTaskStart = System.currentTimeMillis(); List<Long> geneids = new ArrayList<Long>(chunksize); for (Gene gene : genelist) { geneids.add(gene.getGeneID()); } getAtlasDAO().getPropertiesForGenes(genelist); Map<Long,List<ExpressionAnalysis>> eas = getAtlasDAO().getExpressionAnalyticsForGeneIDs(geneids); int eascount = 0; for (List<ExpressionAnalysis> easlist : eas.values()) eascount += easlist.size(); sblog.append("[ ").append(System.currentTimeMillis() - timeTaskStart).append(" ] got " + eascount + " EA's for " + geneids.size() + " genes.\n"); Iterator<Gene> geneiter = genelist.iterator(); List<SolrInputDocument> solrDocs = new ArrayList<SolrInputDocument>(genelist.size()); while(geneiter.hasNext()) { final Gene gene = geneiter.next(); geneiter.remove(); SolrInputDocument solrInputDoc = createGeneSolrInputDocument(gene); Set<String> designElements = new HashSet<String>(); for(DesignElement de : getAtlasDAO().getDesignElementsByGeneID(gene.getGeneID())) { designElements.add(de.getName()); designElements.add(de.getAccession()); } solrInputDoc.addField("property_designelement", designElements); solrInputDoc.addField("properties", "designelement"); // add EFO counts for this gene List<ExpressionAnalysis> eal = eas.get(gene.getGeneID()); if(eal == null) eal = Collections.emptyList(); if(eal.size() > 0) { addEfoCounts(solrInputDoc, new HashSet<ExpressionAnalysis>(eal)); // finally, add the document solrDocs.add(solrInputDoc); } int processedNow = processed.incrementAndGet(); if(processedNow % commitfreq == 0 || processedNow == total) { long timeNow = System.currentTimeMillis(); long elapsed = timeNow - timeStart; double speed = (processedNow / (elapsed / Double.valueOf(commitfreq))); // (item/s) double estimated = (total - processedNow) / (speed * 60); getLog().info( String.format("Processed %d/%d genes %d%%, %.1f genes/sec overall, estimated %.1f min remaining", processedNow, total, (processedNow * 100/total), speed, estimated)); progressUpdater.update(processedNow + "/" + total); } } sblog.append("[ ").append(System.currentTimeMillis() - timeTaskStart).append(" ] adding genes to Solr index...\n"); getSolrServer().add(solrDocs); sblog.append("[ ").append(System.currentTimeMillis() - timeTaskStart).append(" ] ... batch complete.\n"); getLog().info("Gene chunk done:\n" + sblog); return true; } catch (RuntimeException e) { getLog().error("Runtime exception occurred: " + e.getMessage(), e); return false; } } }); } genes.clear(); try { List<Future<Boolean>> results = tpool.invokeAll(tasks); Iterator<Future<Boolean>> iresults = results.iterator(); while(iresults.hasNext()) { Future<Boolean> result = iresults.next(); result.get(); iresults.remove(); } } catch (InterruptedException e) { getLog().error("Indexing interrupted!", e); } catch (ExecutionException e) { throw new IndexBuilderException("Error in indexing!", e.getCause()); } finally { // shutdown the service getLog().info("Gene index building tasks finished, cleaning up resources and exiting"); tpool.shutdown(); } } private void addEfoCounts(SolrInputDocument solrDoc, Iterable<ExpressionAnalysis> studies) { Map<String, UpDnSet> efoupdn = new HashMap<String, UpDnSet>(); Map<String, UpDn> efvupdn = new HashMap<String, UpDn>(); Set<Long> noexp = new HashSet<Long>(); Set<Long> upexp = new HashSet<Long>(); Set<Long> dnexp = new HashSet<Long>(); Map<String, Set<String>> noefv = new HashMap<String, Set<String>>(); Map<String, Set<String>> upefv = new HashMap<String, Set<String>>(); Map<String, Set<String>> dnefv = new HashMap<String, Set<String>>(); GeneExpressionAnalyticsTable expTable = new GeneExpressionAnalyticsTable(); for (ExpressionAnalysis expressionAnalytic : studies) { Long experimentId = expressionAnalytic.getExperimentID(); if (experimentId == 0) { getLog().debug("Gene " + solrDoc.getField("id") + " references an experiment where " + "experimentid=0, this design element will be excluded"); continue; } boolean isUp = expressionAnalytic.isUp(); boolean isNo = expressionAnalytic.isNo(); float pval = expressionAnalytic.getPValAdjusted(); final String ef = expressionAnalytic.getEfName(); final String efv = expressionAnalytic.getEfvName(); Collection<String> accessions = ontomap.get(experimentId + "_" + ef + "_" + efv); String efvid = EscapeUtil.encode(ef, efv); // String.valueOf(expressionAnalytic.getEfvId()); // TODO: is efvId enough? if (!efvupdn.containsKey(efvid)) { efvupdn.put(efvid, new UpDn()); } if (isNo) { /* HACK: ignore non-differentially-expressed genes efvupdn.get(efvid).cno ++; if (!noefv.containsKey(ef)) { noefv.put(ef, new HashSet<String>()); } noefv.get(ef).add(efv); *******/ } else if (isUp) { efvupdn.get(efvid).cup ++; efvupdn.get(efvid).pup = Math.min(efvupdn.get(efvid).pup, pval); if (!upefv.containsKey(ef)) { upefv.put(ef, new HashSet<String>()); } upefv.get(ef).add(efv); } else { efvupdn.get(efvid).cdn ++; efvupdn.get(efvid).pdn = Math.min(efvupdn.get(efvid).pdn, pval); if (!dnefv.containsKey(ef)) { dnefv.put(ef, new HashSet<String>()); } dnefv.get(ef).add(efv); } if (accessions != null) { for (String acc : accessions) { if (!efoupdn.containsKey(acc)) { efoupdn.put(acc, new UpDnSet()); } if (isNo) { // efoupdn.get(acc).no.add(experimentId); } else if (isUp) { efoupdn.get(acc).up.add(experimentId); efoupdn.get(acc).minpvalUp = Math.min(efoupdn.get(acc).minpvalUp, pval); } else { efoupdn.get(acc).dn.add(experimentId); efoupdn.get(acc).minpvalDn = Math.min(efoupdn.get(acc).minpvalDn, pval); } } } if (isUp) { upexp.add(experimentId); } else { dnexp.add(experimentId); } expressionAnalytic.setEfoAccessions(accessions != null ? accessions.toArray(new String[accessions.size()]) : new String[0]); expTable.add(expressionAnalytic); } solrDoc.addField("exp_info", expTable.serialize()); for (String rootId : efo.getRootIds()) { calcChildren(rootId, efoupdn); } storeEfoCounts(solrDoc, efoupdn); storeEfvCounts(solrDoc, efvupdn); storeExperimentIds(solrDoc, noexp, upexp, dnexp); storeEfvs(solrDoc, noefv, upefv, dnefv); } private void calcChildren(String currentId, Map<String, UpDnSet> efoupdn) { UpDnSet current = efoupdn.get(currentId); if (current == null) { current = new UpDnSet(); efoupdn.put(currentId, current); } else if (current.processed) { return; } for (EfoTerm child : efo.getTermChildren(currentId)) { calcChildren(child.getId(), efoupdn); current.addChild(efoupdn.get(child.getId())); } current.processed = true; } private <T> Set<T> union(Set<T> a, Set<T> b) { Set<T> x = new HashSet<T>(); if (a != null) { x.addAll(a); } if (b != null) { x.addAll(b); } return x; } private SolrInputDocument createGeneSolrInputDocument(final Gene gene) { // create a new solr document for this gene SolrInputDocument solrInputDoc = new SolrInputDocument(); getLog().debug("Updating index with properties for " + gene.getIdentifier()); // add the gene id field solrInputDoc.addField("id", gene.getGeneID()); solrInputDoc.addField("species", gene.getSpecies()); solrInputDoc.addField("name", gene.getName()); solrInputDoc.addField("identifier", gene.getIdentifier()); Set<String> propNames = new HashSet<String>(); for (Property prop : gene.getProperties()) { String pv = prop.getValue(); String p = prop.getName(); if(pv == null) continue; if(p.toLowerCase().contains("ortholog")) { solrInputDoc.addField("orthologs", pv); } else { getLog().trace("Updating index, gene property " + p + " = " + pv); solrInputDoc.addField("property_" + p, pv); propNames.add(p); } } if(!propNames.isEmpty()) solrInputDoc.setField("properties", propNames); getLog().debug("Properties for " + gene.getIdentifier() + " updated"); return solrInputDoc; } private void storeEfvs(SolrInputDocument solrDoc, Map<String, Set<String>> noefv, Map<String, Set<String>> upefv, Map<String, Set<String>> dnefv) { for (Map.Entry<String, Set<String>> e : noefv.entrySet()) { for (String i : e.getValue()) { solrDoc.addField("efvs_no_" + EscapeUtil.encode(e.getKey()), i); } } for (Map.Entry<String, Set<String>> e : upefv.entrySet()) { for (String i : e.getValue()) { solrDoc.addField("efvs_up_" + EscapeUtil.encode(e.getKey()), i); } } for (Map.Entry<String, Set<String>> e : dnefv.entrySet()) { for (String i : e.getValue()) { solrDoc.addField("efvs_dn_" + EscapeUtil.encode(e.getKey()), i); } } for (String factor : union(upefv.keySet(), dnefv.keySet())) { for (String i : union(upefv.get(factor), dnefv.get(factor))) { solrDoc.addField("efvs_ud_" + EscapeUtil.encode(factor), i); } } } private void storeExperimentIds(SolrInputDocument solrDoc, Set<Long> noexp, Set<Long> upexp, Set<Long> dnexp) { for (Long i : noexp) { solrDoc.addField("exp_no_ids", i); } for (Long i : upexp) { solrDoc.addField("exp_up_ids", i); } for (Long i : dnexp) { solrDoc.addField("exp_dn_ids", i); } for (Long i : union(upexp, dnexp)) { solrDoc.addField("exp_ud_ids", i); } } private void storeEfoCounts(SolrInputDocument solrDoc, Map<String, UpDnSet> efoupdn) { for (Map.Entry<String, UpDnSet> e : efoupdn.entrySet()) { String accession = e.getKey(); String accessionE = EscapeUtil.encode(accession); UpDnSet ud = e.getValue(); ud.childrenUp.addAll(ud.up); ud.childrenDn.addAll(ud.dn); ud.childrenNo.addAll(ud.no); int cup = ud.childrenUp.size(); int cdn = ud.childrenDn.size(); int cno = ud.childrenNo.size(); float pup = Math.min(ud.minpvalChildrenUp, ud.minpvalUp); float pdn = Math.min(ud.minpvalChildrenDn, ud.minpvalDn); if (cup > 0) { solrDoc.addField("cnt_efo_" + accessionE + "_up", cup); solrDoc.addField("minpval_efo_" + accessionE + "_up", pup); } if (cdn > 0) { solrDoc.addField("cnt_efo_" + accessionE + "_dn", cdn); solrDoc.addField("minpval_efo_" + accessionE + "_dn", pdn); } if (cno > 0) { solrDoc.addField("cnt_efo_" + accessionE + "_no", cno); } if (ud.up.size() > 0) { solrDoc.addField("cnt_efo_" + accessionE + "_s_up", ud.up.size()); solrDoc.addField("minpval_efo_" + accessionE + "_s_up", ud.minpvalUp); } if (ud.dn.size() > 0) { solrDoc.addField("cnt_efo_" + accessionE + "_s_dn", ud.dn.size()); solrDoc.addField("minpval_efo_" + accessionE + "_s_dn", ud.minpvalDn); } if (ud.no.size() > 0) { solrDoc.addField("cnt_efo_" + accessionE + "_s_no", ud.no.size()); } if (cup > 0) { solrDoc.addField("s_efo_" + accessionE + "_up", shorten(cup * (1.0f - pup) - cdn * (1.0f - pdn))); } if (cdn > 0) { solrDoc.addField("s_efo_" + accessionE + "_dn", shorten(cdn * (1.0f - pdn) - cup * (1.0f - pup))); } if (cup + cdn > 0) { solrDoc.addField("s_efo_" + accessionE + "_ud", shorten(cup * (1.0f - pup) + cdn * (1.0f - pdn))); } if (cno > 0) { solrDoc.addField("s_efo_" + accessionE + "_no", shorten(cno)); } if (cup > 0) { solrDoc.addField("efos_up", accession); } if (cdn > 0) { solrDoc.addField("efos_dn", accession); } if (cup + cdn > 0) { solrDoc.addField("efos_ud", accession); } if (cno > 0) { solrDoc.addField("efos_no", accession); } } } private void storeEfvCounts(SolrInputDocument solrDoc, Map<String, UpDn> efvupdn) { for (Map.Entry<String, UpDn> e : efvupdn.entrySet()) { String efvid = e.getKey(); UpDn ud = e.getValue(); int cup = ud.cup; int cdn = ud.cdn; int cno = ud.cno; float pvup = ud.pup; float pvdn = ud.pdn; if (cno != 0) { solrDoc.addField("cnt_" + efvid + "_no", cno); } if (cup != 0) { solrDoc.addField("cnt_" + efvid + "_up", cup); solrDoc.addField("minpval_" + efvid + "_up", pvup); } if (cdn != 0) { solrDoc.addField("cnt_" + efvid + "_dn", cdn); solrDoc.addField("minpval_" + efvid + "_dn", pvdn); } solrDoc.addField("s_" + efvid + "_no", shorten(cno)); solrDoc.addField("s_" + efvid + "_up", shorten(cup * (1.0f - pvup) - cdn * (1.0f - pvdn))); solrDoc.addField("s_" + efvid + "_dn", shorten(cdn * (1.0f - pvdn) - cup * (1.0f - pvup))); solrDoc.addField("s_" + efvid + "_ud", shorten(cup * (1.0f - pvup) + cdn * (1.0f - pvdn))); } } private void loadEfoMapping() { getLog().info("Fetching ontology mappings..."); // we don't support enything else yet List<OntologyMapping> mappings = getAtlasDAO().getOntologyMappingsByOntology("EFO"); for (OntologyMapping mapping : mappings) { String mapKey = mapping.getExperimentId() + "_" + mapping.getProperty() + "_" + mapping.getPropertyValue(); if (ontomap.containsKey(mapKey)) { // fetch the existing array and add this term // fixme: should actually add ontology term accession ontomap.get(mapKey).add(mapping.getOntologyTerm()); } else { // add a new array Collection<String> values = new HashSet<String>(); // fixme: should actually add ontology term accession values.add(mapping.getOntologyTerm()); ontomap.put(mapKey, values); } } getLog().info("Ontology mappings loaded"); } private short shorten(float f) { f = f * 256; if (f > Short.MAX_VALUE) { return Short.MAX_VALUE; } if (f < Short.MIN_VALUE) { return Short.MIN_VALUE; } return (short) f; } private static class UpDnSet { Set<Long> up = new HashSet<Long>(); Set<Long> dn = new HashSet<Long>(); Set<Long> no = new HashSet<Long>(); Set<Long> childrenUp = new HashSet<Long>(); Set<Long> childrenDn = new HashSet<Long>(); Set<Long> childrenNo = new HashSet<Long>(); boolean processed = false; float minpvalUp = 1; float minpvalDn = 1; float minpvalChildrenUp = 1; float minpvalChildrenDn = 1; void addChild(UpDnSet child) { childrenUp.addAll(child.childrenUp); childrenDn.addAll(child.childrenDn); childrenNo.addAll(child.childrenNo); childrenUp.addAll(child.up); childrenDn.addAll(child.dn); childrenNo.addAll(child.no); minpvalChildrenDn = Math.min(Math.min(minpvalChildrenDn, child.minpvalChildrenDn), child.minpvalDn); minpvalChildrenUp = Math.min(Math.min(minpvalChildrenUp, child.minpvalChildrenUp), child.minpvalUp); } } private static class UpDn { int cup = 0; int cdn = 0; int cno = 0; float pup = 1; float pdn = 1; } @Override public void finalizeCommand(UpdateIndexForExperimentCommand updateIndexForExperimentCommand, ProgressUpdater progressUpdater) throws IndexBuilderException { commit(); // do not optimize } public String getName() { return "genes"; } }
indexbuilder/src/main/java/uk/ac/ebi/gxa/index/builder/service/GeneAtlasIndexBuilderService.java
/* * Copyright 2008-2010 Microarray Informatics Team, EMBL-European Bioinformatics Institute * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * For further details of the Gene Expression Atlas project, including source code, * downloads and documentation, please see: * * http://gxa.github.com/gxa */ package uk.ac.ebi.gxa.index.builder.service; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.common.SolrInputDocument; import uk.ac.ebi.gxa.efo.Efo; import uk.ac.ebi.gxa.efo.EfoTerm; import uk.ac.ebi.gxa.index.GeneExpressionAnalyticsTable; import uk.ac.ebi.gxa.index.builder.IndexBuilderException; import uk.ac.ebi.gxa.index.builder.IndexAllCommand; import uk.ac.ebi.gxa.index.builder.UpdateIndexForExperimentCommand; import uk.ac.ebi.gxa.utils.ChunkedSublistIterator; import uk.ac.ebi.gxa.utils.EscapeUtil; import uk.ac.ebi.gxa.utils.SequenceIterator; import uk.ac.ebi.microarray.atlas.model.*; import uk.ac.ebi.gxa.properties.AtlasProperties; import java.io.IOException; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; /** * An {@link IndexBuilderService} that generates index documents from the genes in the Atlas database, and enriches the * data with expression values, links to EFO and other useful measurements. * <p/> * This is a heavily modified version of an original class first adapted to Atlas purposes by Pavel Kurnosov. * <p/> * Note that this implementation does NOT support updates - regardless of whether the update flag is set to true, this * will rebuild the index every time. * * @author Tony Burdett * @date 22-Sep-2009 */ public class GeneAtlasIndexBuilderService extends IndexBuilderService { private Map<String, Collection<String>> ontomap = new HashMap<String, Collection<String>>(); private Efo efo; private AtlasProperties atlasProperties; public void setAtlasProperties(AtlasProperties atlasProperties) { this.atlasProperties = atlasProperties; } public AtlasProperties getAtlasProperties() { return atlasProperties; } public Efo getEfo() { return efo; } public void setEfo(Efo efo) { this.efo = efo; } @Override public void processCommand(IndexAllCommand indexAll, ProgressUpdater progressUpdater) throws IndexBuilderException { super.processCommand(indexAll, progressUpdater); //To change body of overridden methods use File | Settings | File Templates. getLog().info("Indexing all genes..."); indexGenes(progressUpdater, getAtlasDAO().getAllGenesFast()); } @Override public void processCommand(UpdateIndexForExperimentCommand cmd, ProgressUpdater progressUpdater) throws IndexBuilderException { super.processCommand(cmd, progressUpdater); getLog().info("Indexing genes for experiment " + cmd.getAccession() + "..."); indexGenes(progressUpdater, getAtlasDAO().getGenesByExperimentAccession(cmd.getAccession())); } private void indexGenes(final ProgressUpdater progressUpdater, final List<Gene> genes) throws IndexBuilderException { java.util.Collections.shuffle(genes); final int total = genes.size(); getLog().info("Found " + total + " genes to index"); loadEfoMapping(); final AtomicInteger processed = new AtomicInteger(0); final long timeStart = System.currentTimeMillis(); final int fnothnum = atlasProperties.getGeneAtlasIndexBuilderNumberOfThreads(); final int chunksize = atlasProperties.getGeneAtlasIndexBuilderChunksize(); final int commitfreq = atlasProperties.getGeneAtlasIndexBuilderCommitfreq(); getLog().info("Using " + fnothnum + " threads, " + chunksize + " chunk size, committing every " + commitfreq + " genes"); ExecutorService tpool = Executors.newFixedThreadPool(fnothnum); List<Callable<Boolean>> tasks = new ArrayList<Callable<Boolean>>(genes.size()); // index all genes in parallel for (final List<Gene> genelist : new Iterable<List<Gene>>() { public Iterator<List<Gene>> iterator() { return new ChunkedSublistIterator<List<Gene>>(genes, chunksize); } }) { // for each gene, submit a new task to the executor tasks.add(new Callable<Boolean>() { public Boolean call() throws IOException, SolrServerException { try { StringBuilder sblog = new StringBuilder(); long timeTaskStart = System.currentTimeMillis(); List<Long> geneids = new ArrayList<Long>(chunksize); for (Gene gene : genelist) { geneids.add(gene.getGeneID()); } getAtlasDAO().getPropertiesForGenes(genelist); Map<Long,List<ExpressionAnalysis>> eas = getAtlasDAO().getExpressionAnalyticsForGeneIDs(geneids); int eascount = 0; for (List<ExpressionAnalysis> easlist : eas.values()) eascount += easlist.size(); sblog.append("[ ").append(System.currentTimeMillis() - timeTaskStart).append(" ] got " + eascount + " EA's for " + geneids.size() + " genes.\n"); Iterator<Gene> geneiter = genelist.iterator(); List<SolrInputDocument> solrDocs = new ArrayList<SolrInputDocument>(genelist.size()); while(geneiter.hasNext()) { final Gene gene = geneiter.next(); geneiter.remove(); SolrInputDocument solrInputDoc = createGeneSolrInputDocument(gene); Set<String> designElements = new HashSet<String>(); for(DesignElement de : getAtlasDAO().getDesignElementsByGeneID(gene.getGeneID())) { designElements.add(de.getName()); designElements.add(de.getAccession()); } solrInputDoc.addField("property_designelement", designElements); solrInputDoc.addField("properties", "designelement"); // add EFO counts for this gene List<ExpressionAnalysis> eal = eas.get(gene.getGeneID()); if(eal == null) eal = Collections.emptyList(); if(eal.size() > 0) { addEfoCounts(solrInputDoc, new HashSet<ExpressionAnalysis>(eal)); // finally, add the document solrDocs.add(solrInputDoc); } int processedNow = processed.incrementAndGet(); if(processedNow % commitfreq == 0 || processedNow == total) { long timeNow = System.currentTimeMillis(); long elapsed = timeNow - timeStart; double speed = (processedNow / (elapsed / Double.valueOf(commitfreq))); // (item/s) double estimated = (total - processedNow) / (speed * 60); getLog().info( String.format("Processed %d/%d genes %d%%, %.1f genes/sec overall, estimated %.1f min remaining", processedNow, total, (processedNow * 100/total), speed, estimated)); progressUpdater.update(processedNow + "/" + total); } } sblog.append("[ ").append(System.currentTimeMillis() - timeTaskStart).append(" ] adding genes to Solr index...\n"); getSolrServer().add(solrDocs); sblog.append("[ ").append(System.currentTimeMillis() - timeTaskStart).append(" ] ... batch complete.\n"); getLog().info("Gene chunk done:\n" + sblog); return true; } catch (RuntimeException e) { getLog().error("Runtime exception occurred: " + e.getMessage(), e); return false; } } }); } genes.clear(); try { List<Future<Boolean>> results = tpool.invokeAll(tasks); Iterator<Future<Boolean>> iresults = results.iterator(); while(iresults.hasNext()) { Future<Boolean> result = iresults.next(); result.get(); iresults.remove(); } } catch (InterruptedException e) { getLog().error("Indexing interrupted!", e); } catch (ExecutionException e) { throw new IndexBuilderException("Error in indexing!", e.getCause()); } finally { // shutdown the service getLog().info("Gene index building tasks finished, cleaning up resources and exiting"); tpool.shutdown(); } } private void addEfoCounts(SolrInputDocument solrDoc, Iterable<ExpressionAnalysis> studies) { Map<String, UpDnSet> efoupdn = new HashMap<String, UpDnSet>(); Map<String, UpDn> efvupdn = new HashMap<String, UpDn>(); Set<Long> noexp = new HashSet<Long>(); Set<Long> upexp = new HashSet<Long>(); Set<Long> dnexp = new HashSet<Long>(); Map<String, Set<String>> noefv = new HashMap<String, Set<String>>(); Map<String, Set<String>> upefv = new HashMap<String, Set<String>>(); Map<String, Set<String>> dnefv = new HashMap<String, Set<String>>(); GeneExpressionAnalyticsTable expTable = new GeneExpressionAnalyticsTable(); for (ExpressionAnalysis expressionAnalytic : studies) { Long experimentId = expressionAnalytic.getExperimentID(); if (experimentId == 0) { getLog().debug("Gene " + solrDoc.getField("id") + " references an experiment where " + "experimentid=0, this design element will be excluded"); continue; } boolean isUp = expressionAnalytic.isUp(); boolean isNo = expressionAnalytic.isNo(); float pval = expressionAnalytic.getPValAdjusted(); final String ef = expressionAnalytic.getEfName(); final String efv = expressionAnalytic.getEfvName(); Collection<String> accessions = ontomap.get(experimentId + "_" + ef + "_" + efv); String efvid = EscapeUtil.encode(ef, efv); // String.valueOf(expressionAnalytic.getEfvId()); // TODO: is efvId enough? if (!efvupdn.containsKey(efvid)) { efvupdn.put(efvid, new UpDn()); } if (isNo) { /* HACK: ignore non-differentially-expressed genes efvupdn.get(efvid).cno ++; if (!noefv.containsKey(ef)) { noefv.put(ef, new HashSet<String>()); } noefv.get(ef).add(efv); *******/ } else if (isUp) { efvupdn.get(efvid).cup ++; efvupdn.get(efvid).pup = Math.min(efvupdn.get(efvid).pup, pval); if (!upefv.containsKey(ef)) { upefv.put(ef, new HashSet<String>()); } upefv.get(ef).add(efv); } else { efvupdn.get(efvid).cdn ++; efvupdn.get(efvid).pdn = Math.min(efvupdn.get(efvid).pdn, pval); if (!dnefv.containsKey(ef)) { dnefv.put(ef, new HashSet<String>()); } dnefv.get(ef).add(efv); } if (accessions != null) { for (String acc : accessions) { if (!efoupdn.containsKey(acc)) { efoupdn.put(acc, new UpDnSet()); } if (isNo) { efoupdn.get(acc).no.add(experimentId); } else if (isUp) { efoupdn.get(acc).up.add(experimentId); efoupdn.get(acc).minpvalUp = Math.min(efoupdn.get(acc).minpvalUp, pval); } else { efoupdn.get(acc).dn.add(experimentId); efoupdn.get(acc).minpvalDn = Math.min(efoupdn.get(acc).minpvalDn, pval); } } } if (isUp) { upexp.add(experimentId); } else { dnexp.add(experimentId); } expressionAnalytic.setEfoAccessions(accessions != null ? accessions.toArray(new String[accessions.size()]) : new String[0]); expTable.add(expressionAnalytic); } solrDoc.addField("exp_info", expTable.serialize()); for (String rootId : efo.getRootIds()) { calcChildren(rootId, efoupdn); } storeEfoCounts(solrDoc, efoupdn); storeEfvCounts(solrDoc, efvupdn); storeExperimentIds(solrDoc, noexp, upexp, dnexp); storeEfvs(solrDoc, noefv, upefv, dnefv); } private void calcChildren(String currentId, Map<String, UpDnSet> efoupdn) { UpDnSet current = efoupdn.get(currentId); if (current == null) { current = new UpDnSet(); efoupdn.put(currentId, current); } else if (current.processed) { return; } for (EfoTerm child : efo.getTermChildren(currentId)) { calcChildren(child.getId(), efoupdn); current.addChild(efoupdn.get(child.getId())); } current.processed = true; } private <T> Set<T> union(Set<T> a, Set<T> b) { Set<T> x = new HashSet<T>(); if (a != null) { x.addAll(a); } if (b != null) { x.addAll(b); } return x; } private SolrInputDocument createGeneSolrInputDocument(final Gene gene) { // create a new solr document for this gene SolrInputDocument solrInputDoc = new SolrInputDocument(); getLog().debug("Updating index with properties for " + gene.getIdentifier()); // add the gene id field solrInputDoc.addField("id", gene.getGeneID()); solrInputDoc.addField("species", gene.getSpecies()); solrInputDoc.addField("name", gene.getName()); solrInputDoc.addField("identifier", gene.getIdentifier()); Set<String> propNames = new HashSet<String>(); for (Property prop : gene.getProperties()) { String pv = prop.getValue(); String p = prop.getName(); if(pv == null) continue; if(p.toLowerCase().contains("ortholog")) { solrInputDoc.addField("orthologs", pv); } else { getLog().trace("Updating index, gene property " + p + " = " + pv); solrInputDoc.addField("property_" + p, pv); propNames.add(p); } } if(!propNames.isEmpty()) solrInputDoc.setField("properties", propNames); getLog().debug("Properties for " + gene.getIdentifier() + " updated"); return solrInputDoc; } private void storeEfvs(SolrInputDocument solrDoc, Map<String, Set<String>> noefv, Map<String, Set<String>> upefv, Map<String, Set<String>> dnefv) { for (Map.Entry<String, Set<String>> e : noefv.entrySet()) { for (String i : e.getValue()) { solrDoc.addField("efvs_no_" + EscapeUtil.encode(e.getKey()), i); } } for (Map.Entry<String, Set<String>> e : upefv.entrySet()) { for (String i : e.getValue()) { solrDoc.addField("efvs_up_" + EscapeUtil.encode(e.getKey()), i); } } for (Map.Entry<String, Set<String>> e : dnefv.entrySet()) { for (String i : e.getValue()) { solrDoc.addField("efvs_dn_" + EscapeUtil.encode(e.getKey()), i); } } for (String factor : union(upefv.keySet(), dnefv.keySet())) { for (String i : union(upefv.get(factor), dnefv.get(factor))) { solrDoc.addField("efvs_ud_" + EscapeUtil.encode(factor), i); } } } private void storeExperimentIds(SolrInputDocument solrDoc, Set<Long> noexp, Set<Long> upexp, Set<Long> dnexp) { for (Long i : noexp) { solrDoc.addField("exp_no_ids", i); } for (Long i : upexp) { solrDoc.addField("exp_up_ids", i); } for (Long i : dnexp) { solrDoc.addField("exp_dn_ids", i); } for (Long i : union(upexp, dnexp)) { solrDoc.addField("exp_ud_ids", i); } } private void storeEfoCounts(SolrInputDocument solrDoc, Map<String, UpDnSet> efoupdn) { for (Map.Entry<String, UpDnSet> e : efoupdn.entrySet()) { String accession = e.getKey(); String accessionE = EscapeUtil.encode(accession); UpDnSet ud = e.getValue(); ud.childrenUp.addAll(ud.up); ud.childrenDn.addAll(ud.dn); ud.childrenNo.addAll(ud.no); int cup = ud.childrenUp.size(); int cdn = ud.childrenDn.size(); int cno = ud.childrenNo.size(); float pup = Math.min(ud.minpvalChildrenUp, ud.minpvalUp); float pdn = Math.min(ud.minpvalChildrenDn, ud.minpvalDn); if (cup > 0) { solrDoc.addField("cnt_efo_" + accessionE + "_up", cup); solrDoc.addField("minpval_efo_" + accessionE + "_up", pup); } if (cdn > 0) { solrDoc.addField("cnt_efo_" + accessionE + "_dn", cdn); solrDoc.addField("minpval_efo_" + accessionE + "_dn", pdn); } if (cno > 0) { solrDoc.addField("cnt_efo_" + accessionE + "_no", cno); } if (ud.up.size() > 0) { solrDoc.addField("cnt_efo_" + accessionE + "_s_up", ud.up.size()); solrDoc.addField("minpval_efo_" + accessionE + "_s_up", ud.minpvalUp); } if (ud.dn.size() > 0) { solrDoc.addField("cnt_efo_" + accessionE + "_s_dn", ud.dn.size()); solrDoc.addField("minpval_efo_" + accessionE + "_s_dn", ud.minpvalDn); } if (ud.no.size() > 0) { solrDoc.addField("cnt_efo_" + accessionE + "_s_no", ud.no.size()); } if (cup > 0) { solrDoc.addField("s_efo_" + accessionE + "_up", shorten(cup * (1.0f - pup) - cdn * (1.0f - pdn))); } if (cdn > 0) { solrDoc.addField("s_efo_" + accessionE + "_dn", shorten(cdn * (1.0f - pdn) - cup * (1.0f - pup))); } if (cup + cdn > 0) { solrDoc.addField("s_efo_" + accessionE + "_ud", shorten(cup * (1.0f - pup) + cdn * (1.0f - pdn))); } if (cno > 0) { solrDoc.addField("s_efo_" + accessionE + "_no", shorten(cno)); } if (cup > 0) { solrDoc.addField("efos_up", accession); } if (cdn > 0) { solrDoc.addField("efos_dn", accession); } if (cup + cdn > 0) { solrDoc.addField("efos_ud", accession); } if (cno > 0) { solrDoc.addField("efos_no", accession); } } } private void storeEfvCounts(SolrInputDocument solrDoc, Map<String, UpDn> efvupdn) { for (Map.Entry<String, UpDn> e : efvupdn.entrySet()) { String efvid = e.getKey(); UpDn ud = e.getValue(); int cup = ud.cup; int cdn = ud.cdn; int cno = ud.cno; float pvup = ud.pup; float pvdn = ud.pdn; if (cno != 0) { solrDoc.addField("cnt_" + efvid + "_no", cno); } if (cup != 0) { solrDoc.addField("cnt_" + efvid + "_up", cup); solrDoc.addField("minpval_" + efvid + "_up", pvup); } if (cdn != 0) { solrDoc.addField("cnt_" + efvid + "_dn", cdn); solrDoc.addField("minpval_" + efvid + "_dn", pvdn); } solrDoc.addField("s_" + efvid + "_no", shorten(cno)); solrDoc.addField("s_" + efvid + "_up", shorten(cup * (1.0f - pvup) - cdn * (1.0f - pvdn))); solrDoc.addField("s_" + efvid + "_dn", shorten(cdn * (1.0f - pvdn) - cup * (1.0f - pvup))); solrDoc.addField("s_" + efvid + "_ud", shorten(cup * (1.0f - pvup) + cdn * (1.0f - pvdn))); } } private void loadEfoMapping() { getLog().info("Fetching ontology mappings..."); // we don't support enything else yet List<OntologyMapping> mappings = getAtlasDAO().getOntologyMappingsByOntology("EFO"); for (OntologyMapping mapping : mappings) { String mapKey = mapping.getExperimentId() + "_" + mapping.getProperty() + "_" + mapping.getPropertyValue(); if (ontomap.containsKey(mapKey)) { // fetch the existing array and add this term // fixme: should actually add ontology term accession ontomap.get(mapKey).add(mapping.getOntologyTerm()); } else { // add a new array Collection<String> values = new HashSet<String>(); // fixme: should actually add ontology term accession values.add(mapping.getOntologyTerm()); ontomap.put(mapKey, values); } } getLog().info("Ontology mappings loaded"); } private short shorten(float f) { f = f * 256; if (f > Short.MAX_VALUE) { return Short.MAX_VALUE; } if (f < Short.MIN_VALUE) { return Short.MIN_VALUE; } return (short) f; } private static class UpDnSet { Set<Long> up = new HashSet<Long>(); Set<Long> dn = new HashSet<Long>(); Set<Long> no = new HashSet<Long>(); Set<Long> childrenUp = new HashSet<Long>(); Set<Long> childrenDn = new HashSet<Long>(); Set<Long> childrenNo = new HashSet<Long>(); boolean processed = false; float minpvalUp = 1; float minpvalDn = 1; float minpvalChildrenUp = 1; float minpvalChildrenDn = 1; void addChild(UpDnSet child) { childrenUp.addAll(child.childrenUp); childrenDn.addAll(child.childrenDn); childrenNo.addAll(child.childrenNo); childrenUp.addAll(child.up); childrenDn.addAll(child.dn); childrenNo.addAll(child.no); minpvalChildrenDn = Math.min(Math.min(minpvalChildrenDn, child.minpvalChildrenDn), child.minpvalDn); minpvalChildrenUp = Math.min(Math.min(minpvalChildrenUp, child.minpvalChildrenUp), child.minpvalUp); } } private static class UpDn { int cup = 0; int cdn = 0; int cno = 0; float pup = 1; float pdn = 1; } @Override public void finalizeCommand(UpdateIndexForExperimentCommand updateIndexForExperimentCommand, ProgressUpdater progressUpdater) throws IndexBuilderException { commit(); // do not optimize } public String getName() { return "genes"; } }
Forgot about this non-de add, now removed git-svn-id: 410459702e6123a874d92574e1336b0959d85891@13835 2913f559-6b04-0410-9a09-c530ee9f5186
indexbuilder/src/main/java/uk/ac/ebi/gxa/index/builder/service/GeneAtlasIndexBuilderService.java
Forgot about this non-de add, now removed
<ide><path>ndexbuilder/src/main/java/uk/ac/ebi/gxa/index/builder/service/GeneAtlasIndexBuilderService.java <ide> efoupdn.put(acc, new UpDnSet()); <ide> } <ide> if (isNo) { <del> efoupdn.get(acc).no.add(experimentId); <add> // efoupdn.get(acc).no.add(experimentId); <ide> } else if (isUp) { <ide> efoupdn.get(acc).up.add(experimentId); <ide> efoupdn.get(acc).minpvalUp =
Java
mit
eeb4aa9ad103d31fada299cab38237a38d604274
0
wizzardo/Tools,wizzardo/Tools
package com.wizzardo.tools.json; import org.junit.Assert; import org.junit.Test; /** * Created by wizzardo on 14.09.15. */ public class JsonParseBytesTest { static class TestBinder implements JsonBinder { Object value; @Override public void add(Object value) { this.value = value; } @Override public void add(JsonItem value) { this.value = value; } @Override public Object getObject() { return null; } @Override public JsonBinder getObjectBinder() { return null; } @Override public JsonBinder getArrayBinder() { return null; } @Override public void setTemporaryKey(String key) { } @Override public JsonFieldSetter getFieldSetter() { return null; } } @Test public void parse_number_1() { byte[] data = "123,".getBytes(); TestBinder binder = new TestBinder(); JsonUtils.parseNumber(binder, data, 0, data.length, new NumberParsingContext()); Assert.assertEquals(123l, binder.value); } @Test public void parse_number_2() { byte[] data = "123.1,".getBytes(); TestBinder binder = new TestBinder(); JsonUtils.parseNumber(binder, data, 0, data.length, new NumberParsingContext()); Assert.assertEquals(123.1, binder.value); } @Test public void parse_number_3() { byte[] data = "123,".getBytes(); TestBinder binder = new TestBinder(); JsonUtils.parseNumber(binder, data, 0, data.length, new NumberParsingContext()); Assert.assertEquals(123l, binder.value); data = "1234}".getBytes(); JsonUtils.parseNumber(binder, data, 0, data.length, new NumberParsingContext()); Assert.assertEquals(1234l, binder.value); data = "12345]".getBytes(); JsonUtils.parseNumber(binder, data, 0, data.length, new NumberParsingContext()); Assert.assertEquals(12345l, binder.value); data = "123456\n".getBytes(); JsonUtils.parseNumber(binder, data, 0, data.length, new NumberParsingContext()); Assert.assertEquals(123456l, binder.value); data = "1234567\r".getBytes(); JsonUtils.parseNumber(binder, data, 0, data.length, new NumberParsingContext()); Assert.assertEquals(1234567l, binder.value); data = "12345678 ".getBytes(); JsonUtils.parseNumber(binder, data, 0, data.length, new NumberParsingContext()); Assert.assertEquals(12345678l, binder.value); } }
src/test/java/com/wizzardo/tools/json/JsonParseBytesTest.java
package com.wizzardo.tools.json; import org.junit.Assert; import org.junit.Test; /** * Created by wizzardo on 14.09.15. */ public class JsonParseBytesTest { static class TestBinder implements JsonBinder { Object value; @Override public void add(Object value) { this.value = value; } @Override public void add(JsonItem value) { this.value = value; } @Override public Object getObject() { return null; } @Override public JsonBinder getObjectBinder() { return null; } @Override public JsonBinder getArrayBinder() { return null; } @Override public void setTemporaryKey(String key) { } @Override public JsonFieldSetter getFieldSetter() { return null; } } @Test public void parse_number_1() { byte[] data = "123,".getBytes(); TestBinder binder = new TestBinder(); JsonUtils.parseNumber(binder, data, 0, data.length, new NumberParsingContext()); Assert.assertEquals(123l, binder.value); } @Test public void parse_number_2() { byte[] data = "123.1,".getBytes(); TestBinder binder = new TestBinder(); JsonUtils.parseNumber(binder, data, 0, data.length, new NumberParsingContext()); Assert.assertEquals(123.1, binder.value); } @Test public void parse_number_3() { byte[] data = "123,".getBytes(); TestBinder binder = new TestBinder(); JsonUtils.parseNumber(binder, data, 0, data.length, new NumberParsingContext()); Assert.assertEquals(123l, binder.value); data = "1234}".getBytes(); JsonUtils.parseNumber(binder, data, 0, data.length, new NumberParsingContext()); Assert.assertEquals(1234l, binder.value); data = "12345]".getBytes(); JsonUtils.parseNumber(binder, data, 0, data.length, new NumberParsingContext()); Assert.assertEquals(12345l, binder.value); } }
improve tests
src/test/java/com/wizzardo/tools/json/JsonParseBytesTest.java
improve tests
<ide><path>rc/test/java/com/wizzardo/tools/json/JsonParseBytesTest.java <ide> data = "12345]".getBytes(); <ide> JsonUtils.parseNumber(binder, data, 0, data.length, new NumberParsingContext()); <ide> Assert.assertEquals(12345l, binder.value); <add> <add> data = "123456\n".getBytes(); <add> JsonUtils.parseNumber(binder, data, 0, data.length, new NumberParsingContext()); <add> Assert.assertEquals(123456l, binder.value); <add> <add> data = "1234567\r".getBytes(); <add> JsonUtils.parseNumber(binder, data, 0, data.length, new NumberParsingContext()); <add> Assert.assertEquals(1234567l, binder.value); <add> <add> data = "12345678 ".getBytes(); <add> JsonUtils.parseNumber(binder, data, 0, data.length, new NumberParsingContext()); <add> Assert.assertEquals(12345678l, binder.value); <ide> } <ide> }
Java
apache-2.0
06a81988d3fa7fd5828cb9f4e67432e23b1af21b
0
lookout/commons-compress,mohanaraosv/commons-compress,apache/commons-compress,mohanaraosv/commons-compress,apache/commons-compress,lookout/commons-compress,krosenvold/commons-compress,mohanaraosv/commons-compress,krosenvold/commons-compress,apache/commons-compress,krosenvold/commons-compress,lookout/commons-compress
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.commons.compress.archivers.sevenz; import java.io.ByteArrayOutputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.BitSet; import java.util.Date; import java.util.List; import java.util.zip.CRC32; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.utils.CountingOutputStream; /** * Writes a 7z file. * @since 1.6 */ public class SevenZOutputFile { private final RandomAccessFile file; private final List<SevenZArchiveEntry> files = new ArrayList<SevenZArchiveEntry>(); private int numNonEmptyStreams = 0; private CRC32 crc32 = new CRC32(); private CRC32 compressedCrc32 = new CRC32(); private long fileBytesWritten = 0; private boolean finished = false; private CountingOutputStream currentOutputStream; private SevenZMethod contentCompression = SevenZMethod.LZMA2; /** * Opens file to write a 7z archive to. * * @param filename name of the file to write to * @throws IOException if opening the file fails */ public SevenZOutputFile(final File filename) throws IOException { file = new RandomAccessFile(filename, "rw"); file.seek(SevenZFile.SIGNATURE_HEADER_SIZE); } /** * Sets the compression method to use for entry contents - the * default is LZMA2. * * <p>Currently only {@link SevenZMethod#COPY}, {@link * SevenZMethod#LZMA2}, {@link SevenZMethod#BZIP2} and {@link * SevenZMethod#DEFLATE} are supported.</p> */ public void setContentCompression(SevenZMethod method) { this.contentCompression = method; } /** * Closes the archive, calling {@link #finish} if necessary. */ public void close() { try { if (!finished) { finish(); } file.close(); } catch (IOException ioEx) { // NOPMD } } /** * Create an archive entry using the inputFile and entryName provided. * * @param inputFile * @param entryName * @return the ArchiveEntry set up with details from the file * * @throws IOException */ public SevenZArchiveEntry createArchiveEntry(final File inputFile, final String entryName) throws IOException { final SevenZArchiveEntry entry = new SevenZArchiveEntry(); entry.setDirectory(inputFile.isDirectory()); entry.setName(entryName); entry.setLastModifiedDate(new Date(inputFile.lastModified())); return entry; } /** * Records an archive entry to add. * * The caller must then write the content to the archive and call * {@link #closeArchiveEntry()} to complete the process. * * @param archiveEntry describes the entry * @throws IOException */ public void putArchiveEntry(final ArchiveEntry archiveEntry) throws IOException { final SevenZArchiveEntry entry = (SevenZArchiveEntry) archiveEntry; files.add(entry); currentOutputStream = setupFileOutputStream(); } /** * Closes the archive entry. * @throws IOException */ public void closeArchiveEntry() throws IOException { currentOutputStream.flush(); currentOutputStream.close(); final SevenZArchiveEntry entry = files.get(files.size() - 1); if (fileBytesWritten > 0) { entry.setHasStream(true); ++numNonEmptyStreams; entry.setSize(currentOutputStream.getBytesWritten()); entry.setCompressedSize(fileBytesWritten); entry.setCrc((int) crc32.getValue()); entry.setCompressedCrc((int) compressedCrc32.getValue()); entry.setHasCrc(true); } else { entry.setHasStream(false); entry.setSize(0); entry.setCompressedSize(0); entry.setHasCrc(false); } crc32.reset(); compressedCrc32.reset(); fileBytesWritten = 0; } /** * Writes a byte to the current archive entry. * @param b The byte to be written. * @throws IOException on error */ public void write(final int b) throws IOException { currentOutputStream.write(b); } /** * Writes a byte array to the current archive entry. * @param b The byte array to be written. * @throws IOException on error */ public void write(final byte[] b) throws IOException { currentOutputStream.write(b); } /** * Writes part of a byte array to the current archive entry. * @param b The byte array to be written. * @param off offset into the array to start writing from * @param len number of bytes to write * @throws IOException on error */ public void write(final byte[] b, final int off, final int len) throws IOException { currentOutputStream.write(b, off, len); } /** * Finishes the addition of entries to this archive, without closing it. * * @throws IOException if archive is already closed. */ public void finish() throws IOException { if (finished) { throw new IOException("This archive has already been finished"); } finished = true; final long headerPosition = file.getFilePointer(); final ByteArrayOutputStream headerBaos = new ByteArrayOutputStream(); final DataOutputStream header = new DataOutputStream(headerBaos); writeHeader(header); header.flush(); final byte[] headerBytes = headerBaos.toByteArray(); file.write(headerBytes); final CRC32 crc32 = new CRC32(); // signature header file.seek(0); file.write(SevenZFile.sevenZSignature); // version file.write(0); file.write(2); // start header final ByteArrayOutputStream startHeaderBaos = new ByteArrayOutputStream(); final DataOutputStream startHeaderStream = new DataOutputStream(startHeaderBaos); startHeaderStream.writeLong(Long.reverseBytes(headerPosition - SevenZFile.SIGNATURE_HEADER_SIZE)); startHeaderStream.writeLong(Long.reverseBytes(0xffffFFFFL & headerBytes.length)); crc32.reset(); crc32.update(headerBytes); startHeaderStream.writeInt(Integer.reverseBytes((int)crc32.getValue())); startHeaderStream.flush(); final byte[] startHeaderBytes = startHeaderBaos.toByteArray(); crc32.reset(); crc32.update(startHeaderBytes); file.writeInt(Integer.reverseBytes((int)crc32.getValue())); file.write(startHeaderBytes); } private CountingOutputStream setupFileOutputStream() throws IOException { OutputStream out = new OutputStreamWrapper(); return new CountingOutputStream(Coders .addEncoder(out, contentCompression, null)) { @Override public void write(final int b) throws IOException { super.write(b); crc32.update(b); } @Override public void write(final byte[] b) throws IOException { super.write(b); crc32.update(b); } @Override public void write(final byte[] b, final int off, final int len) throws IOException { super.write(b, off, len); crc32.update(b, off, len); } }; } private void writeHeader(final DataOutput header) throws IOException { header.write(NID.kHeader); header.write(NID.kMainStreamsInfo); writeStreamsInfo(header); writeFilesInfo(header); header.write(NID.kEnd); } private void writeStreamsInfo(final DataOutput header) throws IOException { if (numNonEmptyStreams > 0) { writePackInfo(header); writeUnpackInfo(header); } writeSubStreamsInfo(header); header.write(NID.kEnd); } private void writePackInfo(final DataOutput header) throws IOException { header.write(NID.kPackInfo); writeUint64(header, 0); writeUint64(header, 0xffffFFFFL & numNonEmptyStreams); header.write(NID.kSize); for (final SevenZArchiveEntry entry : files) { if (entry.hasStream()) { writeUint64(header, entry.getCompressedSize()); } } header.write(NID.kCRC); header.write(1); for (final SevenZArchiveEntry entry : files) { if (entry.hasStream()) { header.writeInt(Integer.reverseBytes(entry.getCompressedCrc())); } } header.write(NID.kEnd); } private void writeUnpackInfo(final DataOutput header) throws IOException { header.write(NID.kUnpackInfo); header.write(NID.kFolder); writeUint64(header, numNonEmptyStreams); header.write(0); for (int i = 0; i < numNonEmptyStreams; i++) { writeFolder(header); } header.write(NID.kCodersUnpackSize); for (final SevenZArchiveEntry entry : files) { if (entry.hasStream()) { writeUint64(header, entry.getSize()); } } header.write(NID.kCRC); header.write(1); for (final SevenZArchiveEntry entry : files) { if (entry.hasStream()) { header.writeInt(Integer.reverseBytes(entry.getCrc())); } } header.write(NID.kEnd); } private void writeFolder(final DataOutput header) throws IOException { // one coder writeUint64(header, 1); byte[] id = contentCompression.getId(); byte[] properties = contentCompression.getProperties(); int codecFlags = id.length; if (properties.length > 0) { codecFlags |= 0x20; } header.write(codecFlags); header.write(id); if (properties.length > 0) { header.write(properties.length); header.write(properties); } } private void writeSubStreamsInfo(final DataOutput header) throws IOException { header.write(NID.kSubStreamsInfo); // // header.write(NID.kCRC); // header.write(1); // for (final SevenZArchiveEntry entry : files) { // if (entry.getHasCrc()) { // header.writeInt(Integer.reverseBytes(entry.getCrc())); // } // } // header.write(NID.kEnd); } private void writeFilesInfo(final DataOutput header) throws IOException { header.write(NID.kFilesInfo); writeUint64(header, files.size()); writeFileEmptyStreams(header); writeFileEmptyFiles(header); writeFileAntiItems(header); writeFileNames(header); writeFileCTimes(header); writeFileATimes(header); writeFileMTimes(header); writeFileWindowsAttributes(header); header.write(0); } private void writeFileEmptyStreams(final DataOutput header) throws IOException { boolean hasEmptyStreams = false; for (final SevenZArchiveEntry entry : files) { if (!entry.hasStream()) { hasEmptyStreams = true; break; } } if (hasEmptyStreams) { header.write(NID.kEmptyStream); final BitSet emptyStreams = new BitSet(files.size()); for (int i = 0; i < files.size(); i++) { emptyStreams.set(i, !files.get(i).hasStream()); } final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream out = new DataOutputStream(baos); writeBits(out, emptyStreams, files.size()); out.flush(); final byte[] contents = baos.toByteArray(); writeUint64(header, contents.length); header.write(contents); } } private void writeFileEmptyFiles(final DataOutput header) throws IOException { boolean hasEmptyFiles = false; int emptyStreamCounter = 0; final BitSet emptyFiles = new BitSet(0); for (int i = 0; i < files.size(); i++) { if (!files.get(i).hasStream()) { boolean isDir = files.get(i).isDirectory(); emptyFiles.set(emptyStreamCounter++, !isDir); hasEmptyFiles |= !isDir; } } if (hasEmptyFiles) { header.write(NID.kEmptyFile); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream out = new DataOutputStream(baos); writeBits(out, emptyFiles, emptyStreamCounter); out.flush(); final byte[] contents = baos.toByteArray(); writeUint64(header, contents.length); header.write(contents); } } private void writeFileAntiItems(final DataOutput header) throws IOException { boolean hasAntiItems = false; final BitSet antiItems = new BitSet(0); int antiItemCounter = 0; for (int i = 0; i < files.size(); i++) { if (!files.get(i).hasStream()) { boolean isAnti = files.get(i).isAntiItem(); antiItems.set(antiItemCounter++, isAnti); hasAntiItems |= isAnti; } } if (hasAntiItems) { header.write(NID.kAnti); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream out = new DataOutputStream(baos); writeBits(out, antiItems, antiItemCounter); out.flush(); final byte[] contents = baos.toByteArray(); writeUint64(header, contents.length); header.write(contents); } } private void writeFileNames(final DataOutput header) throws IOException { header.write(NID.kName); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream out = new DataOutputStream(baos); out.write(0); for (final SevenZArchiveEntry entry : files) { out.write(entry.getName().getBytes("UTF-16LE")); out.writeShort(0); } out.flush(); final byte[] contents = baos.toByteArray(); writeUint64(header, contents.length); header.write(contents); } private void writeFileCTimes(final DataOutput header) throws IOException { int numCreationDates = 0; for (final SevenZArchiveEntry entry : files) { if (entry.getHasCreationDate()) { ++numCreationDates; } } if (numCreationDates > 0) { header.write(NID.kCTime); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream out = new DataOutputStream(baos); if (numCreationDates != files.size()) { out.write(0); final BitSet cTimes = new BitSet(files.size()); for (int i = 0; i < files.size(); i++) { cTimes.set(i, files.get(i).getHasCreationDate()); } writeBits(out, cTimes, files.size()); } else { out.write(1); } out.write(0); for (final SevenZArchiveEntry entry : files) { if (entry.getHasCreationDate()) { out.writeLong(Long.reverseBytes( SevenZArchiveEntry.javaTimeToNtfsTime(entry.getCreationDate()))); } } out.flush(); final byte[] contents = baos.toByteArray(); writeUint64(header, contents.length); header.write(contents); } } private void writeFileATimes(final DataOutput header) throws IOException { int numAccessDates = 0; for (final SevenZArchiveEntry entry : files) { if (entry.getHasAccessDate()) { ++numAccessDates; } } if (numAccessDates > 0) { header.write(NID.kATime); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream out = new DataOutputStream(baos); if (numAccessDates != files.size()) { out.write(0); final BitSet aTimes = new BitSet(files.size()); for (int i = 0; i < files.size(); i++) { aTimes.set(i, files.get(i).getHasAccessDate()); } writeBits(out, aTimes, files.size()); } else { out.write(1); } out.write(0); for (final SevenZArchiveEntry entry : files) { if (entry.getHasAccessDate()) { out.writeLong(Long.reverseBytes( SevenZArchiveEntry.javaTimeToNtfsTime(entry.getAccessDate()))); } } out.flush(); final byte[] contents = baos.toByteArray(); writeUint64(header, contents.length); header.write(contents); } } private void writeFileMTimes(final DataOutput header) throws IOException { int numLastModifiedDates = 0; for (final SevenZArchiveEntry entry : files) { if (entry.getHasLastModifiedDate()) { ++numLastModifiedDates; } } if (numLastModifiedDates > 0) { header.write(NID.kMTime); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream out = new DataOutputStream(baos); if (numLastModifiedDates != files.size()) { out.write(0); final BitSet mTimes = new BitSet(files.size()); for (int i = 0; i < files.size(); i++) { mTimes.set(i, files.get(i).getHasLastModifiedDate()); } writeBits(out, mTimes, files.size()); } else { out.write(1); } out.write(0); for (final SevenZArchiveEntry entry : files) { if (entry.getHasLastModifiedDate()) { out.writeLong(Long.reverseBytes( SevenZArchiveEntry.javaTimeToNtfsTime(entry.getLastModifiedDate()))); } } out.flush(); final byte[] contents = baos.toByteArray(); writeUint64(header, contents.length); header.write(contents); } } private void writeFileWindowsAttributes(final DataOutput header) throws IOException { int numWindowsAttributes = 0; for (final SevenZArchiveEntry entry : files) { if (entry.getHasWindowsAttributes()) { ++numWindowsAttributes; } } if (numWindowsAttributes > 0) { header.write(NID.kWinAttributes); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream out = new DataOutputStream(baos); if (numWindowsAttributes != files.size()) { out.write(0); final BitSet attributes = new BitSet(files.size()); for (int i = 0; i < files.size(); i++) { attributes.set(i, files.get(i).getHasWindowsAttributes()); } writeBits(out, attributes, files.size()); } else { out.write(1); } out.write(0); for (final SevenZArchiveEntry entry : files) { if (entry.getHasWindowsAttributes()) { out.writeInt(Integer.reverseBytes(entry.getWindowsAttributes())); } } out.flush(); final byte[] contents = baos.toByteArray(); writeUint64(header, contents.length); header.write(contents); } } private void writeUint64(final DataOutput header, long value) throws IOException { int firstByte = 0; int mask = 0x80; int i; for (i = 0; i < 8; i++) { if (value < ((1L << ( 7 * (i + 1))))) { firstByte |= (value >>> (8 * i)); break; } firstByte |= mask; mask >>>= 1; } header.write(firstByte); for (; i > 0; i--) { header.write((int) (0xff & value)); value >>>= 8; } } private void writeBits(final DataOutput header, final BitSet bits, final int length) throws IOException { int cache = 0; int shift = 7; for (int i = 0; i < length; i++) { cache |= ((bits.get(i) ? 1 : 0) << shift); --shift; if (shift == 0) { header.write(cache); shift = 7; cache = 0; } } if (length > 0 && shift > 0) { header.write(cache); } } private class OutputStreamWrapper extends OutputStream { @Override public void write(final int b) throws IOException { file.write(b); compressedCrc32.update(b); fileBytesWritten++; } @Override public void write(final byte[] b) throws IOException { OutputStreamWrapper.this.write(b, 0, b.length); } @Override public void write(final byte[] b, final int off, final int len) throws IOException { file.write(b, off, len); compressedCrc32.update(b, off, len); fileBytesWritten += len; } @Override public void flush() throws IOException { // no reason to flush a RandomAccessFile } @Override public void close() throws IOException { // the file will be closed by the containing class's close method } } }
src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZOutputFile.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.commons.compress.archivers.sevenz; import java.io.ByteArrayOutputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.BitSet; import java.util.Date; import java.util.List; import java.util.zip.CRC32; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.utils.CountingOutputStream; /** * Writes a 7z file. * @since 1.6 */ public class SevenZOutputFile { private final RandomAccessFile file; private final List<SevenZArchiveEntry> files = new ArrayList<SevenZArchiveEntry>(); private int numNonEmptyStreams = 0; private CRC32 crc32 = new CRC32(); private CRC32 compressedCrc32 = new CRC32(); private long fileBytesWritten = 0; private boolean finished = false; private CountingOutputStream currentOutputStream; private SevenZMethod contentCompression = SevenZMethod.LZMA2; /** * Opens file to write a 7z archive to. * * @param filename name of the file to write to * @throws IOException if opening the file fails */ public SevenZOutputFile(final File filename) throws IOException { file = new RandomAccessFile(filename, "rw"); file.seek(SevenZFile.SIGNATURE_HEADER_SIZE); } /** * Sets the compression method to use for entry contents - the * default is LZMA2. * * <p>Currently only {@link SevenZMethod#COPY}, {@link * SevenZMethod#LZMA2}, {@link SevenZMethod#BZIP2} and {@link * SevenZMethod#DEFLATE} are supported.</p> */ public void setContentCompression(SevenZMethod method) { this.contentCompression = method; } /** * Closes the archive, calling {@link #finish} if necessary. */ public void close() { try { if (!finished) { finish(); } file.close(); } catch (IOException ioEx) { // NOPMD } } /** * Create an archive entry using the inputFile and entryName provided. * * @param inputFile * @param entryName * @return the ArchiveEntry set up with details from the file * * @throws IOException */ public SevenZArchiveEntry createArchiveEntry(final File inputFile, final String entryName) throws IOException { final SevenZArchiveEntry entry = new SevenZArchiveEntry(); entry.setDirectory(inputFile.isDirectory()); entry.setName(entryName); entry.setLastModifiedDate(new Date(inputFile.lastModified())); return entry; } /** * Records an archive entry to add. * * The caller must then write the content to the archive and call * {@link #closeArchiveEntry()} to complete the process. * * @param archiveEntry describes the entry * @throws IOException */ public void putArchiveEntry(final ArchiveEntry archiveEntry) throws IOException { final SevenZArchiveEntry entry = (SevenZArchiveEntry) archiveEntry; files.add(entry); currentOutputStream = setupFileOutputStream(); } /** * Closes the archive entry. * @throws IOException */ public void closeArchiveEntry() throws IOException { currentOutputStream.flush(); currentOutputStream.close(); final SevenZArchiveEntry entry = files.get(files.size() - 1); if (fileBytesWritten > 0) { entry.setHasStream(true); ++numNonEmptyStreams; entry.setSize(currentOutputStream.getBytesWritten()); entry.setCompressedSize(fileBytesWritten); entry.setCrc((int) crc32.getValue()); entry.setCompressedCrc((int) compressedCrc32.getValue()); entry.setHasCrc(true); } else { entry.setHasStream(false); entry.setSize(0); entry.setCompressedSize(0); entry.setHasCrc(false); } crc32.reset(); compressedCrc32.reset(); fileBytesWritten = 0; } /** * Writes a byte to the current archive entry. * @param b The byte to be written. * @throws IOException on error */ public void write(final int b) throws IOException { currentOutputStream.write(b); } /** * Writes a byte array to the current archive entry. * @param b The byte array to be written. * @throws IOException on error */ public void write(final byte[] b) throws IOException { currentOutputStream.write(b); } /** * Writes part of a byte array to the current archive entry. * @param b The byte array to be written. * @param off offset into the array to start writing from * @param len number of bytes to write * @throws IOException on error */ public void write(final byte[] b, final int off, final int len) throws IOException { currentOutputStream.write(b, off, len); } /** * Finishes the addition of entries to this archive, without closing it. * * @throws IOException if archive is already closed. */ public void finish() throws IOException { if (finished) { throw new IOException("This archive has already been finished"); } finished = true; final long headerPosition = file.getFilePointer(); final ByteArrayOutputStream headerBaos = new ByteArrayOutputStream(); final DataOutputStream header = new DataOutputStream(headerBaos); writeHeader(header); header.flush(); final byte[] headerBytes = headerBaos.toByteArray(); file.write(headerBytes); final CRC32 crc32 = new CRC32(); // signature header file.seek(0); file.write(SevenZFile.sevenZSignature); // version file.write(0); file.write(2); // start header final ByteArrayOutputStream startHeaderBaos = new ByteArrayOutputStream(); final DataOutputStream startHeaderStream = new DataOutputStream(startHeaderBaos); startHeaderStream.writeLong(Long.reverseBytes(headerPosition - SevenZFile.SIGNATURE_HEADER_SIZE)); startHeaderStream.writeLong(Long.reverseBytes(0xffffFFFFL & headerBytes.length)); crc32.reset(); crc32.update(headerBytes); startHeaderStream.writeInt(Integer.reverseBytes((int)crc32.getValue())); startHeaderStream.flush(); final byte[] startHeaderBytes = startHeaderBaos.toByteArray(); crc32.reset(); crc32.update(startHeaderBytes); file.writeInt(Integer.reverseBytes((int)crc32.getValue())); file.write(startHeaderBytes); } private CountingOutputStream setupFileOutputStream() throws IOException { OutputStream out = new OutputStreamWrapper(); return new CountingOutputStream(Coders .addEncoder(out, contentCompression, null)) { @Override public void write(final int b) throws IOException { super.write(b); crc32.update(b); } @Override public void write(final byte[] b) throws IOException { super.write(b); crc32.update(b); } @Override public void write(final byte[] b, final int off, final int len) throws IOException { super.write(b, off, len); crc32.update(b, off, len); } }; } private void writeHeader(final DataOutput header) throws IOException { header.write(NID.kHeader); header.write(NID.kMainStreamsInfo); writeStreamsInfo(header); writeFilesInfo(header); header.write(NID.kEnd); } private void writeStreamsInfo(final DataOutput header) throws IOException { if (numNonEmptyStreams > 0) { writePackInfo(header); writeUnpackInfo(header); } writeSubStreamsInfo(header); header.write(NID.kEnd); } private void writePackInfo(final DataOutput header) throws IOException { header.write(NID.kPackInfo); writeUint64(header, 0); writeUint64(header, 0xffffFFFFL & numNonEmptyStreams); header.write(NID.kSize); for (final SevenZArchiveEntry entry : files) { if (entry.hasStream()) { writeUint64(header, entry.getCompressedSize()); } } header.write(NID.kCRC); header.write(1); for (final SevenZArchiveEntry entry : files) { if (entry.hasStream()) { header.writeInt(Integer.reverseBytes(entry.getCompressedCrc())); } } header.write(NID.kEnd); } private void writeUnpackInfo(final DataOutput header) throws IOException { header.write(NID.kUnpackInfo); header.write(NID.kFolder); writeUint64(header, numNonEmptyStreams); header.write(0); for (int i = 0; i < numNonEmptyStreams; i++) { writeFolder(header); } header.write(NID.kCodersUnpackSize); for (final SevenZArchiveEntry entry : files) { if (entry.hasStream()) { writeUint64(header, entry.getSize()); } } header.write(NID.kCRC); header.write(1); for (final SevenZArchiveEntry entry : files) { if (entry.hasStream()) { header.writeInt(Integer.reverseBytes(entry.getCrc())); } } header.write(NID.kEnd); } private void writeFolder(final DataOutput header) throws IOException { // one coder writeUint64(header, 1); byte[] id = contentCompression.getId(); byte[] properties = contentCompression.getProperties(); int codecFlags = id.length; if (properties.length > 0) { codecFlags |= 0x20; } header.write(codecFlags); header.write(id); if (properties.length > 0) { header.write(properties.length); header.write(properties); } } private void writeSubStreamsInfo(final DataOutput header) throws IOException { header.write(NID.kSubStreamsInfo); // // header.write(NID.kCRC); // header.write(1); // for (final SevenZArchiveEntry entry : files) { // if (entry.getHasCrc()) { // header.writeInt(Integer.reverseBytes(entry.getCrc())); // } // } // header.write(NID.kEnd); } private void writeFilesInfo(final DataOutput header) throws IOException { header.write(NID.kFilesInfo); writeUint64(header, files.size()); writeFileEmptyStreams(header); writeFileEmptyFiles(header); writeFileAntiItems(header); writeFileNames(header); writeFileCTimes(header); writeFileATimes(header); writeFileMTimes(header); writeFileWindowsAttributes(header); header.write(0); } private void writeFileEmptyStreams(final DataOutput header) throws IOException { boolean hasEmptyStreams = false; for (final SevenZArchiveEntry entry : files) { if (!entry.hasStream()) { hasEmptyStreams = true; break; } } if (hasEmptyStreams) { header.write(NID.kEmptyStream); final BitSet emptyStreams = new BitSet(files.size()); for (int i = 0; i < files.size(); i++) { emptyStreams.set(i, !files.get(i).hasStream()); } final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream out = new DataOutputStream(baos); writeBits(out, emptyStreams, files.size()); out.flush(); final byte[] contents = baos.toByteArray(); writeUint64(header, contents.length); header.write(contents); } } private void writeFileEmptyFiles(final DataOutput header) throws IOException { boolean hasEmptyFiles = false; for (final SevenZArchiveEntry entry : files) { if (!entry.hasStream() && !entry.isDirectory()) { hasEmptyFiles = true; break; } } if (hasEmptyFiles) { header.write(NID.kEmptyFile); final BitSet emptyFiles = new BitSet(files.size()); for (int i = 0; i < files.size(); i++) { emptyFiles.set(i, !files.get(i).hasStream() && !files.get(i).isDirectory()); } final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream out = new DataOutputStream(baos); writeBits(out, emptyFiles, files.size()); out.flush(); final byte[] contents = baos.toByteArray(); writeUint64(header, contents.length); header.write(contents); } } private void writeFileAntiItems(final DataOutput header) throws IOException { boolean hasAntiItems = false; for (final SevenZArchiveEntry entry : files) { if (entry.isAntiItem()) { hasAntiItems = true; break; } } if (hasAntiItems) { header.write(NID.kAnti); final BitSet antiItems = new BitSet(files.size()); for (int i = 0; i < files.size(); i++) { antiItems.set(i, files.get(i).isAntiItem()); } final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream out = new DataOutputStream(baos); writeBits(out, antiItems, files.size()); out.flush(); final byte[] contents = baos.toByteArray(); writeUint64(header, contents.length); header.write(contents); } } private void writeFileNames(final DataOutput header) throws IOException { header.write(NID.kName); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream out = new DataOutputStream(baos); out.write(0); for (final SevenZArchiveEntry entry : files) { out.write(entry.getName().getBytes("UTF-16LE")); out.writeShort(0); } out.flush(); final byte[] contents = baos.toByteArray(); writeUint64(header, contents.length); header.write(contents); } private void writeFileCTimes(final DataOutput header) throws IOException { int numCreationDates = 0; for (final SevenZArchiveEntry entry : files) { if (entry.getHasCreationDate()) { ++numCreationDates; } } if (numCreationDates > 0) { header.write(NID.kCTime); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream out = new DataOutputStream(baos); if (numCreationDates != files.size()) { out.write(0); final BitSet cTimes = new BitSet(files.size()); for (int i = 0; i < files.size(); i++) { cTimes.set(i, files.get(i).getHasCreationDate()); } writeBits(out, cTimes, files.size()); } else { out.write(1); } out.write(0); for (final SevenZArchiveEntry entry : files) { if (entry.getHasCreationDate()) { out.writeLong(Long.reverseBytes( SevenZArchiveEntry.javaTimeToNtfsTime(entry.getCreationDate()))); } } out.flush(); final byte[] contents = baos.toByteArray(); writeUint64(header, contents.length); header.write(contents); } } private void writeFileATimes(final DataOutput header) throws IOException { int numAccessDates = 0; for (final SevenZArchiveEntry entry : files) { if (entry.getHasAccessDate()) { ++numAccessDates; } } if (numAccessDates > 0) { header.write(NID.kATime); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream out = new DataOutputStream(baos); if (numAccessDates != files.size()) { out.write(0); final BitSet aTimes = new BitSet(files.size()); for (int i = 0; i < files.size(); i++) { aTimes.set(i, files.get(i).getHasAccessDate()); } writeBits(out, aTimes, files.size()); } else { out.write(1); } out.write(0); for (final SevenZArchiveEntry entry : files) { if (entry.getHasAccessDate()) { out.writeLong(Long.reverseBytes( SevenZArchiveEntry.javaTimeToNtfsTime(entry.getAccessDate()))); } } out.flush(); final byte[] contents = baos.toByteArray(); writeUint64(header, contents.length); header.write(contents); } } private void writeFileMTimes(final DataOutput header) throws IOException { int numLastModifiedDates = 0; for (final SevenZArchiveEntry entry : files) { if (entry.getHasLastModifiedDate()) { ++numLastModifiedDates; } } if (numLastModifiedDates > 0) { header.write(NID.kMTime); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream out = new DataOutputStream(baos); if (numLastModifiedDates != files.size()) { out.write(0); final BitSet mTimes = new BitSet(files.size()); for (int i = 0; i < files.size(); i++) { mTimes.set(i, files.get(i).getHasLastModifiedDate()); } writeBits(out, mTimes, files.size()); } else { out.write(1); } out.write(0); for (final SevenZArchiveEntry entry : files) { if (entry.getHasLastModifiedDate()) { out.writeLong(Long.reverseBytes( SevenZArchiveEntry.javaTimeToNtfsTime(entry.getLastModifiedDate()))); } } out.flush(); final byte[] contents = baos.toByteArray(); writeUint64(header, contents.length); header.write(contents); } } private void writeFileWindowsAttributes(final DataOutput header) throws IOException { int numWindowsAttributes = 0; for (final SevenZArchiveEntry entry : files) { if (entry.getHasWindowsAttributes()) { ++numWindowsAttributes; } } if (numWindowsAttributes > 0) { header.write(NID.kWinAttributes); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream out = new DataOutputStream(baos); if (numWindowsAttributes != files.size()) { out.write(0); final BitSet attributes = new BitSet(files.size()); for (int i = 0; i < files.size(); i++) { attributes.set(i, files.get(i).getHasWindowsAttributes()); } writeBits(out, attributes, files.size()); } else { out.write(1); } out.write(0); for (final SevenZArchiveEntry entry : files) { if (entry.getHasWindowsAttributes()) { out.writeInt(Integer.reverseBytes(entry.getWindowsAttributes())); } } out.flush(); final byte[] contents = baos.toByteArray(); writeUint64(header, contents.length); header.write(contents); } } private void writeUint64(final DataOutput header, long value) throws IOException { int firstByte = 0; int mask = 0x80; int i; for (i = 0; i < 8; i++) { if (value < ((1L << ( 7 * (i + 1))))) { firstByte |= (value >>> (8 * i)); break; } firstByte |= mask; mask >>>= 1; } header.write(firstByte); for (; i > 0; i--) { header.write((int) (0xff & value)); value >>>= 8; } } private void writeBits(final DataOutput header, final BitSet bits, final int length) throws IOException { int cache = 0; int shift = 7; for (int i = 0; i < length; i++) { cache |= ((bits.get(i) ? 1 : 0) << shift); --shift; if (shift == 0) { header.write(cache); shift = 7; cache = 0; } } if (length > 0 && shift > 0) { header.write(cache); } } private class OutputStreamWrapper extends OutputStream { @Override public void write(final int b) throws IOException { file.write(b); compressedCrc32.update(b); fileBytesWritten++; } @Override public void write(final byte[] b) throws IOException { OutputStreamWrapper.this.write(b, 0, b.length); } @Override public void write(final byte[] b, final int off, final int len) throws IOException { file.write(b, off, len); compressedCrc32.update(b, off, len); fileBytesWritten += len; } @Override public void flush() throws IOException { // no reason to flush a RandomAccessFile } @Override public void close() throws IOException { // the file will be closed by the containing class's close method } } }
emptyFiles and antiItems bitsets only iterate over entries without streams git-svn-id: fb13a56e2874bbe7f090676f40e1dce4dcf67111@1534210 13f79535-47bb-0310-9956-ffa450edef68
src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZOutputFile.java
emptyFiles and antiItems bitsets only iterate over entries without streams
<ide><path>rc/main/java/org/apache/commons/compress/archivers/sevenz/SevenZOutputFile.java <ide> <ide> private void writeFileEmptyFiles(final DataOutput header) throws IOException { <ide> boolean hasEmptyFiles = false; <del> for (final SevenZArchiveEntry entry : files) { <del> if (!entry.hasStream() && !entry.isDirectory()) { <del> hasEmptyFiles = true; <del> break; <add> int emptyStreamCounter = 0; <add> final BitSet emptyFiles = new BitSet(0); <add> for (int i = 0; i < files.size(); i++) { <add> if (!files.get(i).hasStream()) { <add> boolean isDir = files.get(i).isDirectory(); <add> emptyFiles.set(emptyStreamCounter++, !isDir); <add> hasEmptyFiles |= !isDir; <ide> } <ide> } <ide> if (hasEmptyFiles) { <ide> header.write(NID.kEmptyFile); <del> final BitSet emptyFiles = new BitSet(files.size()); <del> for (int i = 0; i < files.size(); i++) { <del> emptyFiles.set(i, !files.get(i).hasStream() && !files.get(i).isDirectory()); <del> } <ide> final ByteArrayOutputStream baos = new ByteArrayOutputStream(); <ide> final DataOutputStream out = new DataOutputStream(baos); <del> writeBits(out, emptyFiles, files.size()); <add> writeBits(out, emptyFiles, emptyStreamCounter); <ide> out.flush(); <ide> final byte[] contents = baos.toByteArray(); <ide> writeUint64(header, contents.length); <ide> <ide> private void writeFileAntiItems(final DataOutput header) throws IOException { <ide> boolean hasAntiItems = false; <del> for (final SevenZArchiveEntry entry : files) { <del> if (entry.isAntiItem()) { <del> hasAntiItems = true; <del> break; <add> final BitSet antiItems = new BitSet(0); <add> int antiItemCounter = 0; <add> for (int i = 0; i < files.size(); i++) { <add> if (!files.get(i).hasStream()) { <add> boolean isAnti = files.get(i).isAntiItem(); <add> antiItems.set(antiItemCounter++, isAnti); <add> hasAntiItems |= isAnti; <ide> } <ide> } <ide> if (hasAntiItems) { <ide> header.write(NID.kAnti); <del> final BitSet antiItems = new BitSet(files.size()); <del> for (int i = 0; i < files.size(); i++) { <del> antiItems.set(i, files.get(i).isAntiItem()); <del> } <ide> final ByteArrayOutputStream baos = new ByteArrayOutputStream(); <ide> final DataOutputStream out = new DataOutputStream(baos); <del> writeBits(out, antiItems, files.size()); <add> writeBits(out, antiItems, antiItemCounter); <ide> out.flush(); <ide> final byte[] contents = baos.toByteArray(); <ide> writeUint64(header, contents.length);
JavaScript
mpl-2.0
efb6c91b1f50c19018f452261b183899f40bbe46
0
beloitcollegecomputerscience/OED,OpenEnergyDashboard/OED,beloitcollegecomputerscience/OED,beloitcollegecomputerscience/OED,OpenEnergyDashboard/OED,beloitcollegecomputerscience/OED,OpenEnergyDashboard/OED,OpenEnergyDashboard/OED
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import _ from 'lodash'; import * as groupsActions from '../actions/groups'; /** * @typedef {Object} State~Groups * @property {boolean} isFetching * @property {Object<number, Object>} byGroupID */ const defaultState = { isFetching: false, byGroupID: {}, selectedGroups: [] }; /** * @param {State~Groups} state * @param action * @return {State~Groups} */ export default function groups(state = defaultState, action) { switch (action.type) { case groupsActions.REQUEST_GROUPS_DETAILS: return { ...state, isFetching: true }; case groupsActions.RECEIVE_GROUPS_DETAILS: { /* add new fields to each group object: isFetching flag for each group arrays to store the IDs of child groups and Meters. We get all other data from other parts of state. NOTE: if you get an error here saying `action.data.map` is not a function, please comment on this issue: https://github.com/beloitcollegecomputerscience/OED/issues/86 */ const newGroups = action.data.map(group => ({ ...group, isFetching: false, childGroups: [], childMeters: [], selectedGroups: [], selectedMeters: [], })); // newGroups is an array: this converts it into a nested object where the key to each group is its ID. // Without this, byGroupID will not be keyed by group ID. const newGroupsByID = _.keyBy(newGroups, 'id'); // Note that there is an `isFetching` for groups as a whole AND one for each group. return { ...state, isFetching: false, byGroupID: newGroupsByID, groupInEditing: null, }; } case groupsActions.REQUEST_GROUP_CHILDREN: { // Make no changes except setting isFetching = true for the group whose children we are fetching. return { ...state, byGroupID: { ...state.byGroupID, [action.groupID]: { ...state.byGroupID[action.groupID], isFetching: true, } } }; } case groupsActions.RECEIVE_GROUP_CHILDREN: { // Set isFetching = false for the group, and set the group's children to the arrays in the response. return { ...state, byGroupID: { ...state.byGroupID, [action.groupID]: { ...state.byGroupID[action.groupID], isFetching: false, childGroups: action.data.groups, childMeters: action.data.meters, } } }; } case groupsActions.GROUPSUI_CHANGE_SELECTED_GROUPS_PER_GROUP: { return { ...state, byGroupID: { ...state.byGroupID, [action.parentID]: { ...state.byGroupID[action.parentID], selectedGroups: action.groupIDs, } } }; } case groupsActions.GROUPSUI_CHANGE_SELECTED_METERS_PER_GROUP: { return { ...state, byGroupID: { ...state.byGroupID, [action.parentID]: { ...state.byGroupID[action.parentID], selectedMeters: action.meterIDs, } } }; } case groupsActions.GROUPSUI_CHANGE_DISPLAYED_GROUPS: { return { ...state, selectedGroups: action.groupIDs, }; } default: return state; } }
src/client/app/reducers/groups.js
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import _ from 'lodash'; import * as groupsActions from '../actions/groups'; /** * @typedef {Object} State~Groups * @property {boolean} isFetching * @property {Object<number, Object>} byGroupID */ const defaultState = { isFetching: false, byGroupID: {}, selectedGroups: [] }; /** * @param {State~Groups} state * @param action * @return {State~Groups} */ export default function groups(state = defaultState, action) { switch (action.type) { case groupsActions.REQUEST_GROUPS_DETAILS: return { ...state, isFetching: true }; case groupsActions.RECEIVE_GROUPS_DETAILS: { // add new fields to each group object: // isFetching flag for each group // arrays to store the IDs of child groups and Meters. We get all other data from other parts of state. // TODO: action.data isn't an array, looks like a lot of stuff at least for me -PT const newGroups = action.data.map(group => ({ ...group, isFetching: false, childGroups: [], childMeters: [], selectedGroups: [], selectedMeters: [], })); // newGroups is an array: this converts it into a nested object where the key to each group is its ID. // Without this, byGroupID will not be keyed by group ID. const newGroupsByID = _.keyBy(newGroups, 'id'); // Note that there is an `isFetching` for groups as a whole AND one for each group. return { ...state, isFetching: false, byGroupID: newGroupsByID, // todo: this is not going to be used immediately, is there anywhere else to set it? // I don't think so, but I'm trying to avoid getting bogged down in this for now, I can change it later. showEditGroupModal: false, // todo: Is this necessary? Is there anywhere else I can set it? Do the proper thinking! // This will be set to a copy of a group being edited to store the edits, my plan is for it to be null // whenever a group is not being edited. -JKM groupInEditing: null, }; } case groupsActions.REQUEST_GROUP_CHILDREN: { // Make no changes except setting isFetching = true for the group whose children we are fetching. return { ...state, byGroupID: { ...state.byGroupID, [action.groupID]: { ...state.byGroupID[action.groupID], isFetching: true, } } }; } case groupsActions.RECEIVE_GROUP_CHILDREN: { // Set isFetching = false for the group, and set the group's children to the arrays in the response. return { ...state, byGroupID: { ...state.byGroupID, [action.groupID]: { ...state.byGroupID[action.groupID], isFetching: false, childGroups: action.data.groups, childMeters: action.data.meters, } } }; } case groupsActions.GROUPSUI_CHANGE_SELECTED_GROUPS_PER_GROUP: { return { ...state, byGroupID: { ...state.byGroupID, [action.parentID]: { ...state.byGroupID[action.parentID], selectedGroups: action.groupIDs, } } }; } case groupsActions.GROUPSUI_CHANGE_SELECTED_METERS_PER_GROUP: { return { ...state, byGroupID: { ...state.byGroupID, [action.parentID]: { ...state.byGroupID[action.parentID], selectedMeters: action.meterIDs, } } }; } case groupsActions.GROUPSUI_CHANGE_DISPLAYED_GROUPS: { return { ...state, selectedGroups: action.groupIDs, }; } default: return state; } }
Replace todo comment in `reducers/groups.js` Replace Paul's todo with a comment specifically about the relevant bug.
src/client/app/reducers/groups.js
Replace todo comment in `reducers/groups.js`
<ide><path>rc/client/app/reducers/groups.js <ide> isFetching: true <ide> }; <ide> case groupsActions.RECEIVE_GROUPS_DETAILS: { <del> // add new fields to each group object: <del> // isFetching flag for each group <del> // arrays to store the IDs of child groups and Meters. We get all other data from other parts of state. <del> // TODO: action.data isn't an array, looks like a lot of stuff at least for me -PT <add> /* <add> add new fields to each group object: <add> isFetching flag for each group <add> arrays to store the IDs of child groups and Meters. We get all other data from other parts of state. <add> <add> NOTE: if you get an error here saying `action.data.map` is not a function, please comment on <add> this issue: https://github.com/beloitcollegecomputerscience/OED/issues/86 <add> */ <ide> const newGroups = action.data.map(group => ({ <ide> ...group, <ide> isFetching: false, <ide> ...state, <ide> isFetching: false, <ide> byGroupID: newGroupsByID, <del> <del> // todo: this is not going to be used immediately, is there anywhere else to set it? <del> // I don't think so, but I'm trying to avoid getting bogged down in this for now, I can change it later. <del> showEditGroupModal: false, <del> <del> // todo: Is this necessary? Is there anywhere else I can set it? Do the proper thinking! <del> // This will be set to a copy of a group being edited to store the edits, my plan is for it to be null <del> // whenever a group is not being edited. -JKM <ide> groupInEditing: null, <ide> }; <ide> }
Java
apache-2.0
8979556456014d5dd8990380b3ce31a83fbec6c1
0
gamerson/liferay-blade-cli,gamerson/liferay-blade-cli,gamerson/liferay-blade-cli
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.liferay.blade.cli; import com.liferay.blade.cli.util.WorkspaceUtil; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; /** * @author Gregory Amerson */ public class BladeTest extends BladeCLI { public static BladeTestBuilder builder() { return new BladeTestBuilder(); } @Override public BladeSettings getBladeSettings() throws IOException { final File settingsFile; if (WorkspaceUtil.isWorkspace(this)) { File workspaceDir = WorkspaceUtil.getWorkspaceDir(this); settingsFile = new File(workspaceDir, ".blade/settings.properties"); } else { Path settingsPath = _settingsDir.resolve("settings.properties"); settingsFile = settingsPath.toFile(); } return new BladeSettings(settingsFile); } @Override public Path getExtensionsPath() { try { Files.createDirectories(_extensionsDir); } catch (IOException ioe) { } return _extensionsDir; } @Override public void postRunCommand() { } @Override public void run(String[] args) throws Exception { super.run(args); if (_assertErrors) { PrintStream error = error(); if (error instanceof StringPrintStream) { StringPrintStream stringPrintStream = (StringPrintStream)error; String errors = stringPrintStream.get(); errors = errors.replaceAll( "sh: warning: setlocale: LC_ALL: cannot change locale \\(en_US.UTF-8\\)", ""); errors = errors.trim(); errors = errors.replaceAll("^\\/bin\\/$", ""); if (!errors.isEmpty()) { throw new Exception("Errors not empty:\n" + errors); } } } } public static class BladeTestBuilder { public BladeTest build() { if (_extensionsDir == null) { _extensionsDir = _userHomePath.resolve(".blade/extensions"); } if (_settingsDir == null) { _settingsDir = _userHomePath.resolve(".blade"); } if (_stdIn == null) { _stdIn = System.in; } if (_stdOut == null) { _stdOut = StringPrintStream.newInstance(); } if (_stdError == null) { _stdError = StringPrintStream.newInstance(); } BladeTest bladeTest = new BladeTest(_stdOut, _stdError, _stdIn); bladeTest._assertErrors = _assertErrors; bladeTest._extensionsDir = _extensionsDir; bladeTest._settingsDir = _settingsDir; return bladeTest; } public void setAssertErrors(boolean assertErrors) { _assertErrors = assertErrors; } public void setExtensionsDir(Path extensionsDir) { _extensionsDir = extensionsDir; } public void setSettingsDir(Path settingsDir) { _settingsDir = settingsDir; } public void setStdError(PrintStream printStream) { _stdError = printStream; } public void setStdIn(InputStream inputStream) { _stdIn = inputStream; } public void setStdOut(PrintStream printStream) { _stdOut = printStream; } private boolean _assertErrors = true; private Path _extensionsDir = null; private Path _settingsDir = null; private PrintStream _stdError = null; private InputStream _stdIn = null; private PrintStream _stdOut = null; private Path _userHomePath = Paths.get(System.getProperty("user.home")); } protected BladeTest(PrintStream out, PrintStream err, InputStream in) { super(out, err, in); } private boolean _assertErrors = true; private Path _extensionsDir; private Path _settingsDir; }
cli/src/test/java/com/liferay/blade/cli/BladeTest.java
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.liferay.blade.cli; import com.liferay.blade.cli.util.WorkspaceUtil; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; /** * @author Gregory Amerson */ public class BladeTest extends BladeCLI { public static BladeTestBuilder builder() { return new BladeTestBuilder(); } @Override public BladeSettings getBladeSettings() throws IOException { final File settingsFile; if (WorkspaceUtil.isWorkspace(this)) { File workspaceDir = WorkspaceUtil.getWorkspaceDir(this); settingsFile = new File(workspaceDir, ".blade/settings.properties"); } else { settingsFile = _settingsDir.resolve("settings.properties").toFile(); } return new BladeSettings(settingsFile); } @Override public Path getExtensionsPath() { try { Files.createDirectories(_extensionsDir); } catch (IOException ioe) { } return _extensionsDir; } @Override public void postRunCommand() { } @Override public void run(String[] args) throws Exception { super.run(args); if (_assertErrors) { PrintStream error = error(); if (error instanceof StringPrintStream) { StringPrintStream stringPrintStream = (StringPrintStream)error; String errors = stringPrintStream.get(); errors = errors.replaceAll( "sh: warning: setlocale: LC_ALL: cannot change locale \\(en_US.UTF-8\\)", ""); errors = errors.trim(); errors = errors.replaceAll("^\\/bin\\/$", ""); if (!errors.isEmpty()) { throw new Exception("Errors not empty:\n" + errors); } } } } public static class BladeTestBuilder { public BladeTest build() { if (_extensionsDir == null) { _extensionsDir = _userHomePath.resolve(".blade/extensions"); } if (_settingsDir == null) { _settingsDir = _userHomePath.resolve(".blade"); } if (_stdIn == null) { _stdIn = System.in; } if (_stdOut == null) { _stdOut = StringPrintStream.newInstance(); } if (_stdError == null) { _stdError = StringPrintStream.newInstance(); } BladeTest bladeTest = new BladeTest(_stdOut, _stdError, _stdIn); bladeTest._assertErrors = _assertErrors; bladeTest._extensionsDir = _extensionsDir; bladeTest._settingsDir = _settingsDir; return bladeTest; } public void setAssertErrors(boolean assertErrors) { _assertErrors = assertErrors; } public void setExtensionsDir(Path extensionsDir) { _extensionsDir = extensionsDir; } public void setSettingsDir(Path settingsDir) { _settingsDir = settingsDir; } public void setStdError(PrintStream printStream) { _stdError = printStream; } public void setStdIn(InputStream inputStream) { _stdIn = inputStream; } public void setStdOut(PrintStream printStream) { _stdOut = printStream; } private boolean _assertErrors = true; private Path _extensionsDir = null; private Path _settingsDir = null; private PrintStream _stdError = null; private InputStream _stdIn = null; private PrintStream _stdOut = null; private Path _userHomePath = Paths.get(System.getProperty("user.home")); } protected BladeTest(PrintStream out, PrintStream err, InputStream in) { super(out, err, in); } private boolean _assertErrors = true; private Path _extensionsDir; private Path _settingsDir; }
BLADE-380 remove chaining
cli/src/test/java/com/liferay/blade/cli/BladeTest.java
BLADE-380 remove chaining
<ide><path>li/src/test/java/com/liferay/blade/cli/BladeTest.java <ide> settingsFile = new File(workspaceDir, ".blade/settings.properties"); <ide> } <ide> else { <del> settingsFile = _settingsDir.resolve("settings.properties").toFile(); <add> Path settingsPath = _settingsDir.resolve("settings.properties"); <add> <add> settingsFile = settingsPath.toFile(); <ide> } <ide> <ide> return new BladeSettings(settingsFile);
Java
apache-2.0
23f5c0756a6fa440038c0544255e8db62164e620
0
ExplorViz/ExplorViz,ExplorViz/ExplorViz,ExplorViz/ExplorViz,ExplorViz/ExplorViz
package explorviz.server.util; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.text.SimpleDateFormat; import java.util.*; import javax.xml.bind.DatatypeConverter; import org.apache.commons.codec.binary.Base64; import org.json.*; import org.zeroturnaround.zip.ZipUtil; import com.fasterxml.jackson.databind.JsonNode; import com.github.fge.jackson.JsonLoader; import com.github.fge.jsonschema.core.exceptions.ProcessingException; import com.github.fge.jsonschema.core.report.ProcessingReport; import com.github.fge.jsonschema.main.JsonSchema; import com.github.fge.jsonschema.main.JsonSchemaFactory; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import explorviz.server.database.DBConnection; import explorviz.server.landscapeexchange.LandscapeExchangeServiceImpl; import explorviz.server.main.Configuration; import explorviz.server.main.FileSystemHelper; import explorviz.shared.auth.User; import explorviz.shared.experiment.Question; import explorviz.visualization.experiment.services.JSONService; public class JSONServiceImpl extends RemoteServiceServlet implements JSONService { private static final long serialVersionUID = 6576514774419481521L; public static String EXP_FOLDER = FileSystemHelper.getExplorVizDirectory() + File.separator + "experiment"; public static String EXP_ANSWER_FOLDER = FileSystemHelper.getExplorVizDirectory() + File.separator + "experiment" + File.separator + "answers"; public static String LANDSCAPE_FOLDER = FileSystemHelper.getExplorVizDirectory() + File.separator + "replay"; public static String Tracking_FOLDER = FileSystemHelper.getExplorVizDirectory() + File.separator + "usertracking"; ///////////////// // RPC Methods // ///////////////// @Override public void saveJSONOnServer(final String json) throws IOException { JSONObject jsonObj = null; try { jsonObj = new JSONObject(json); } catch (final JSONException e) { System.err.println("Method: saveJSONOnServer; Couldn't create JSONObject"); } if (jsonObj == null) { return; } final long timestamp = new Date().getTime(); jsonObj.put("lastModified", timestamp); boolean isValid = false; try { isValid = validateExperiment(jsonObj.toString()); } catch (final ProcessingException e) { System.err.println("There was an error while saving an experiment. Exception: " + e); return; } if (isValid) { final String filename = jsonObj.getString("filename"); final Path experimentFolder = Paths.get(EXP_FOLDER + File.separator + filename); final byte[] bytes = jsonObj.toString(4).getBytes(StandardCharsets.UTF_8); createFileByPath(experimentFolder, bytes); } } @Override public void saveQuestionnaireServer(final String data) throws IOException { final JSONObject filenameAndQuestionnaire = new JSONObject(data); final String filename = filenameAndQuestionnaire.getString("filename"); final String jsonString = getExperiment(filename); final JSONObject jsonExperiment = new JSONObject(jsonString); // TODO check if change crashes live // final JSONObject questionnaire = new // JSONObject(filenameAndQuestionnaire.getString("questionnaire")); final JSONObject questionnaire = filenameAndQuestionnaire.getJSONObject("questionnaire"); final JSONArray questionnaires = jsonExperiment.getJSONArray("questionnaires"); boolean questionnaireUpdated = false; for (int i = 0; i < questionnaires.length(); i++) { final JSONObject questionnaireTemp = questionnaires.getJSONObject(i); // find questionnaire to update if (questionnaireTemp.has("questionnareTitle") && questionnaireTemp.getString("questionnareID") .equals(questionnaire.getString("questionnareID"))) { questionnaireUpdated = true; questionnaires.put(i, questionnaire); } } if (!questionnaireUpdated) { // not added => new questionnaire // TODO Check ifs crashed: .toString() was removed here questionnaires.put(questionnaire); } try { saveJSONOnServer(jsonExperiment.toString()); } catch (final IOException e) { System.err.println("Couldn't save experiment when removing questionnaire."); } } @Override public List<String> getExperimentFilenames() { final List<String> filenames = new ArrayList<String>(); final File directory = new File(EXP_FOLDER); final File[] fList = directory.listFiles(new FileFilter() { @Override public boolean accept(final File pathname) { final String name = pathname.getName().toLowerCase(); return name.endsWith(".json") && pathname.isFile(); } }); if (fList != null) { for (final File f : fList) { filenames.add(f.getName()); } } return filenames; } @Override public List<String> getExperimentTitles() throws IOException { final List<String> titles = new ArrayList<String>(); final File directory = new File(EXP_FOLDER); // Filters Files only; no folders are added final File[] fList = directory.listFiles(new FileFilter() { @Override public boolean accept(final File pathname) { final String name = pathname.getName().toLowerCase(); return name.endsWith(".json") && pathname.isFile(); } }); if (fList != null) { for (final File f : fList) { final String filename = f.getName(); final String json = getExperiment(filename); final JSONObject jsonObj = new JSONObject(json); titles.add(jsonObj.getString("title")); } } return titles; } @Override public String getExperiment(final String filename) throws IOException { byte[] jsonBytes = null; createExperimentFoldersIfNotExist(); jsonBytes = Files.readAllBytes(Paths.get(EXP_FOLDER + File.separator + filename)); return new String(jsonBytes, StandardCharsets.UTF_8); } @Override public void removeExperiment(final String filename) throws JSONException, IOException { final JSONObject jsonExperiment = new JSONObject(getExperiment(filename)); final JSONArray questionnaires = jsonExperiment.getJSONArray("questionnaires"); for (int i = 0; i < questionnaires.length(); i++) { final JSONObject questionnaire = questionnaires.getJSONObject(i); final JSONObject data = new JSONObject(); data.put("filename", filename); data.put("questionnareID", questionnaire.getString("questionnareID")); removeQuestionnaire(data.toString()); } final Path experimentFile = Paths.get(EXP_FOLDER + File.separator + filename); removeFileByPath(experimentFile); } @Override public String getExperimentDetails(final String filename) throws IOException { final String jsonString = getExperiment(filename); final JSONObject jsonExperiment = new JSONObject(jsonString); final JSONObject jsonDetails = new JSONObject(); final SimpleDateFormat df = new SimpleDateFormat("HH:mm - dd-MM-yyyy"); jsonDetails.put("title", jsonExperiment.get("title")); jsonDetails.put("filename", jsonExperiment.get("filename")); final int numberOfQuestionnaires = jsonExperiment.getJSONArray("questionnaires").length(); jsonDetails.put("numQuestionnaires", numberOfQuestionnaires); final List<String> landscapeNames = getLandScapeNamesOfExperiment(filename); jsonDetails.put("landscapes", landscapeNames.toArray()); final int userCount = getExperimentUsers(jsonExperiment); jsonDetails.put("userCount", userCount); final long lastStarted = jsonExperiment.getLong("lastStarted"); if (lastStarted != 0) { jsonDetails.put("lastStarted", df.format(new Date(lastStarted))); } else { jsonDetails.put("lastStarted", ""); } final long lastEnded = jsonExperiment.getLong("lastEnded"); if (lastEnded != 0) { jsonDetails.put("lastEnded", df.format(new Date(lastEnded))); } else { jsonDetails.put("lastEnded", ""); } final long lastModified = jsonExperiment.getLong("lastModified"); jsonDetails.put("lastModified", df.format(new Date(lastModified))); return jsonDetails.toString(); } @Override public void removeQuestionnaire(final String data) throws JSONException, IOException { final JSONObject jsonData = new JSONObject(data); final String filename = jsonData.getString("filename"); String jsonString; jsonString = getExperiment(filename); final JSONObject jsonExperiment = new JSONObject(jsonString); final String questionnaireID = jsonData.getString("questionnareID"); final JSONArray questionnaires = jsonExperiment.getJSONArray("questionnaires"); for (int i = 0; i < questionnaires.length(); i++) { final JSONObject questionnaire = questionnaires.getJSONObject(i); if (questionnaire.get("questionnareID").equals(questionnaireID)) { // remove users final String prefix = jsonExperiment.getString("ID") + "_" + getQuestionnairePrefix( questionnaire.getString("questionnareID"), questionnaires); removeQuestionnaireUsers(prefix); // remove answers final Path answers = Paths.get(EXP_ANSWER_FOLDER + File.separator + prefix); removeFileByPath(answers); // remove user logs final Path logs = Paths.get(Tracking_FOLDER + File.separator + prefix); removeFileByPath(logs); // remove file and save new json on server questionnaires.remove(i); try { saveJSONOnServer(jsonExperiment.toString()); } catch (final IOException e) { System.err.println("Couldn't save experiment when removing questionnaire."); } } } } @Override public String getQuestionnaire(final String data) throws IOException { final JSONObject filenameAndQuestionnaireID = new JSONObject(data); final String filename = filenameAndQuestionnaireID.getString("filename"); final String jsonString = getExperiment(filename); final JSONObject jsonExperiment = new JSONObject(jsonString); final String questionnareID = filenameAndQuestionnaireID.getString("questionnareID"); final JSONArray questionnaires = jsonExperiment.getJSONArray("questionnaires"); for (int i = 0; i < questionnaires.length(); i++) { final JSONObject questionnaire = questionnaires.getJSONObject(i); if (questionnaire.get("questionnareID").equals(questionnareID)) { return questionnaire.toString(); } } return null; } @Override public Boolean isUserInCurrentExperiment(final String username) throws JSONException, IOException { final User tempUser = DBConnection.getUserByName(username); if (tempUser == null) { return false; } final String questionnairePrefix = tempUser.getQuestionnairePrefix(); JSONObject experiment = null; try { experiment = new JSONObject(getExperiment(Configuration.experimentFilename)); } catch (final IOException e) { // System.err.println("Could not read experiment. This may not be // bad. Exception: " + e); return false; } final String prefix = experiment.getString("ID"); return questionnairePrefix.startsWith(prefix); } @Override public Question[] getQuestionnaireQuestionsForUser(final String filename, final String userName) throws IOException { final ArrayList<Question> questions = new ArrayList<Question>(); final String jsonString = getExperiment(filename); final JSONObject jsonExperiment = new JSONObject(jsonString); String questionnairePrefix = DBConnection.getUserByName(userName).getQuestionnairePrefix(); questionnairePrefix = questionnairePrefix.replace(jsonExperiment.getString("ID") + "_", ""); final JSONArray questionnaires = jsonExperiment.getJSONArray("questionnaires"); for (int i = 0; i < questionnaires.length(); i++) { final JSONObject questionnaire = questionnaires.getJSONObject(i); if (questionnaire.getString("questionnareID").equals(questionnairePrefix)) { final JSONArray jsonQuestions = questionnaire.getJSONArray("questions"); for (int w = 0; w < jsonQuestions.length(); w++) { final JSONObject jsonQuestion = jsonQuestions.getJSONObject(w); final String text = jsonQuestion.getString("questionText"); final String type = jsonQuestion.getString("type"); final int procTime = Integer.parseInt(jsonQuestion.getString("workingTime")); final String timestampData = jsonQuestion.getString("expLandscape"); String maybeApplication = ""; try { maybeApplication = jsonQuestion.getString("expApplication"); } catch (final JSONException e) { // there was no application for this question // => no problem => landscape question } final long timestamp = Long.parseLong(timestampData.split("-")[0]); final long activity = Long .parseLong(timestampData.split("-")[1].split(".expl")[0]); final JSONArray correctsArray = jsonQuestion.getJSONArray("answers"); final int lengthQuestions = correctsArray.length(); final ArrayList<String> corrects = new ArrayList<String>(); final String[] answers = new String[lengthQuestions]; for (int j = 0; j < lengthQuestions; j++) { final JSONObject jsonAnswer = correctsArray.getJSONObject(j); if (jsonAnswer.getString("answerText") != "") { answers[j] = jsonAnswer.getString("answerText"); if (jsonAnswer.getBoolean("checkboxChecked")) { corrects.add(answers[j]); } } } final Question question = new Question(i, type, text, answers, corrects.toArray(new String[0]), procTime, timestamp, activity, maybeApplication); questions.add(question); } } } return questions.toArray(new Question[0]); } @Override public void duplicateExperiment(final String filename) throws IOException { final JSONObject jsonObj = new JSONObject(getExperiment(filename)); final String title = jsonObj.getString("title"); jsonObj.put("title", title + "_dup"); final long timestamp = new Date().getTime(); jsonObj.put("filename", "exp_" + timestamp + ".json"); jsonObj.put("ID", "exp" + timestamp); saveJSONOnServer(jsonObj.toString()); } @Override public boolean uploadExperiment(final String jsonExperimentFile) throws IOException { final JSONObject encodedExpFile = new JSONObject(jsonExperimentFile); String encodedExperiment = null; try { encodedExperiment = new String(encodedExpFile.getString("fileData").split(",")[1] .getBytes(StandardCharsets.UTF_8)); } catch (final ArrayIndexOutOfBoundsException e) { e.printStackTrace(); return false; } byte[] bytes = null; try { bytes = DatatypeConverter.parseBase64Binary(encodedExperiment); } catch (final IllegalArgumentException e) { e.printStackTrace(); return false; } final String jsonExperiment = new String(bytes); boolean isValidExperiment = false; try { isValidExperiment = validateExperiment(jsonExperiment); } catch (IOException | ProcessingException e) { System.err.println( "Method: uploadExperiment. Couldn't upload experiment. Exception: " + e); return false; } if (isValidExperiment) { saveJSONOnServer(jsonExperiment); return true; } else { return false; } } @Override public String downloadExperimentData(final String filename) throws IOException { // # add user results and logs to zip # final JSONObject experimentJson = new JSONObject(getExperiment(filename)); // # create zip # final File zip = new File(EXP_FOLDER + File.separator + "experimentData.zip"); // # add .json to zip # final File experimentFile = new File(EXP_FOLDER + File.separator + filename); ZipUtil.packEntries(new File[] { experimentFile }, zip); final JSONArray jsonQuestionnaires = experimentJson.getJSONArray("questionnaires"); final int length = jsonQuestionnaires.length(); for (int i = 0; i < length; i++) { final JSONObject questionnaire = jsonQuestionnaires.getJSONObject(i); final String questPrefix = experimentJson.getString("ID") + "_" + getQuestionnairePrefix(questionnaire.getString("questionnareID"), jsonQuestionnaires); final File answersFolder = new File(EXP_ANSWER_FOLDER + File.separator + questPrefix); File[] listOfFiles = answersFolder.listFiles(); if (listOfFiles != null) { for (final File file : listOfFiles) { if (file.isFile()) { ZipUtil.addEntry(zip, "answers/" + questPrefix + "/" + file.getName(), file); } } } final File trackingFolder = new File(FileSystemHelper.getExplorVizDirectory() + File.separator + "usertracking" + File.separator + questPrefix); listOfFiles = trackingFolder.listFiles(); if (listOfFiles != null) { for (final File file : listOfFiles) { if (file.isFile()) { ZipUtil.addEntry(zip, "usertracking/" + questPrefix + "/" + file.getName(), file); } } } } // # add all related landscapes to zip # final List<String> landscapeNames = getLandScapeNamesOfExperiment(filename); for (final String landscapeName : landscapeNames) { final File landscape = new File( LANDSCAPE_FOLDER + File.separator + landscapeName + ".expl"); ZipUtil.addEntry(zip, "landscapes/" + landscapeName + ".expl", landscape); } // # Now encode to Base64 # final List<Byte> result = new ArrayList<Byte>(); final byte[] buffer = new byte[1024]; final InputStream is = new FileInputStream(zip); int b = is.read(buffer); while (b != -1) { for (int i = 0; i < b; i++) { result.add(buffer[i]); } b = is.read(buffer); } is.close(); final byte[] buf = new byte[result.size()]; for (int i = 0; i < result.size(); i++) { buf[i] = result.get(i); } final String encoded = Base64.encodeBase64String(buf); // # Send back to client # return encoded; } @Override public String getExperimentTitlesAndFilenames() throws IOException { final JSONObject returnObj = new JSONObject(); final File directory = new File(EXP_FOLDER); final JSONArray failingExperiments = new JSONArray(); // Filter valid experiments out in experiment folder final File[] fList = directory.listFiles(new FileFilter() { @Override public boolean accept(final File pathname) { final String name = pathname.getName().toLowerCase(); try { if (!name.endsWith(".json") || !pathname.isFile()) { return false; } final boolean isValidExperiment = validateExperiment(getExperiment(name)); if (!isValidExperiment) { failingExperiments.put(name); } return isValidExperiment; } catch (IOException | ProcessingException e) { System.err.println("Couldn't process file " + name + ". Exception: " + e); } return false; } }); returnObj.put("failingExperiments", failingExperiments); final JSONArray experimentsData = new JSONArray(); returnObj.put("experimentsData", experimentsData); // collect necessary data of experiments for // experiment overview if (fList != null) { JSONObject tmpData = null; long tmpLastModified = 0; for (final File f : fList) { final JSONObject data = new JSONObject(); final String filename = f.getName(); final String jsonExperiment = getExperiment(filename); JSONObject jsonObj = null; try { jsonObj = new JSONObject(jsonExperiment); } catch (final JSONException e) { System.err.println( "Method: getExperimentTitlesAndFilenames; Couldn't create JSONObject for file: " + filename); continue; } final long lastModified = jsonObj.getLong("lastModified"); if (lastModified > tmpLastModified) { data.put("lastTouched", "true"); if (tmpData != null) { tmpData.put("lastTouched", "false"); } tmpLastModified = lastModified; tmpData = data; } else { data.put("lastTouched", "false"); } data.put("filename", jsonObj.get("filename").toString()); data.put("title", jsonObj.get("title").toString()); final JSONArray questionnairesData = new JSONArray(); if ((jsonObj != null) && jsonObj.has("questionnaires")) { final JSONArray questionnaires = jsonObj.getJSONArray("questionnaires"); for (int i = 0; i < questionnaires.length(); i++) { final JSONObject questionnaireObj = questionnaires.getJSONObject(i); final JSONObject questionnaireData = new JSONObject(); questionnaireData.put("questionnareTitle", questionnaireObj.getString("questionnareTitle")); questionnaireData.put("questionnareID", questionnaireObj.getString("questionnareID")); questionnairesData.put(questionnaireData); } data.put("questionnaires", questionnairesData); } experimentsData.put(data); } } return returnObj.toString(); } @Override public String createUsersForQuestionnaire(final int count, final String prefix, final String filename) { final JSONArray users = DBConnection.createUsersForQuestionnaire(prefix, count); final JSONObject returnObj = new JSONObject(); returnObj.put("users", users); // update lastModified stamp JSONObject experiment = null; try { experiment = new JSONObject(getExperiment(filename)); } catch (IOException | JSONException e) { System.err.println("Couldn not update timestamp. Exception: " + e); } experiment.put("lastModified", new Date().getTime()); try { saveJSONOnServer(experiment.toString()); } catch (final IOException e) { System.err.println("Could not save updated experiment. Exception: " + e); } return returnObj.toString(); } @Override public String isExperimentReadyToStart(final String filename) throws JSONException, IOException { final JSONObject experiment = new JSONObject(getExperiment(filename)); final JSONArray questionnaires = experiment.getJSONArray("questionnaires"); final int length = questionnaires.length(); if (length == 0) { return "Add a questionnaire first."; } for (int i = 0; i < length; i++) { final JSONObject questionnaire = questionnaires.getJSONObject(i); final JSONArray questions = questionnaire.getJSONArray("questions"); if (questions.length() == 0) { return "Add at least one question to the questionnaire: " + questionnaire.getString("questionnareTitle"); } if (questionnaire.getString("questionnareTitle").equals("")) { return "There is at least one questionnaire without a name"; } } // experiment is ready try { saveJSONOnServer(experiment.toString()); } catch (final IOException e) { System.err.println(e); } return "ready"; } @Override public void setExperimentTimeAttr(final String filename, final boolean isLastStarted) throws JSONException, IOException { final JSONObject experiment = new JSONObject(getExperiment(filename)); // => update time attributes if (isLastStarted) { experiment.put("lastStarted", new Date().getTime()); } else { experiment.put("lastEnded", new Date().getTime()); } try { saveJSONOnServer(experiment.toString()); } catch (final IOException e) { e.printStackTrace(); } } @Override public String getExperimentTitle(final String filename) throws JSONException, IOException { final JSONObject experiment = new JSONObject(getExperiment(filename)); return experiment.getString("title"); } @Override public String removeQuestionnaireUser(final String data) throws IOException { final JSONObject jsonData = new JSONObject(data); final JSONArray usernames = jsonData.getJSONArray("users"); final String filename = jsonData.getString("filename"); final String questionnareID = jsonData.getString("questionnareID"); final JSONObject filenameAndQuestID = new JSONObject(); filenameAndQuestID.put("filename", filename); filenameAndQuestID.put("questionnareID", questionnareID); final int length = usernames.length(); for (int i = 0; i < length; i++) { final String username = usernames.getString(i); removeUserData(username); DBConnection.removeUser(username); } // update lastModified stamp JSONObject experiment = null; try { experiment = new JSONObject(getExperiment(filename)); } catch (IOException | JSONException e) { System.err.println("Couldn not update timestamp. Exception: " + e); } experiment.put("lastModified", new Date().getTime()); try { saveJSONOnServer(experiment.toString()); } catch (final IOException e) { System.err.println("Could not save updated experiment. Exception: " + e); } return getExperimentAndUsers(filenameAndQuestID.toString()); } @Override public boolean uploadLandscape(final String data) throws IOException { final JSONObject encodedLandscapeFile = new JSONObject(data); final String filename = encodedLandscapeFile.getString("filename"); // first validation check -> filename long timestamp; long activity; try { timestamp = Long.parseLong(filename.split("-")[0]); activity = Long.parseLong(filename.split("-")[1].split(".expl")[0]); } catch (final NumberFormatException e) { return false; } final Path landscapePath = Paths.get(LANDSCAPE_FOLDER + File.separator + filename); String encodedLandscape = null; try { encodedLandscape = new String(encodedLandscapeFile.getString("fileData").split(",")[1] .getBytes(StandardCharsets.UTF_8)); } catch (final ArrayIndexOutOfBoundsException e) { return false; } byte[] bytes = null; try { bytes = DatatypeConverter.parseBase64Binary(encodedLandscape); } catch (ArrayIndexOutOfBoundsException | IllegalArgumentException e) { return false; } createFileByPath(landscapePath, bytes); // second validation check -> deserialization try { LandscapeExchangeServiceImpl.getLandscapeStatic(timestamp, activity); } catch (final Exception e) { // e.printStackTrace(); removeFileByPath(landscapePath); return false; } return true; } @Override public String getQuestionnaireDetails(final String data) throws IOException { final JSONObject filenameAndQuestionnaireID = new JSONObject(data); final String filename = filenameAndQuestionnaireID.getString("filename"); final String jsonString = getExperiment(filename); final JSONObject jsonExperiment = new JSONObject(jsonString); final String questionnaireID = filenameAndQuestionnaireID.getString("questionnareID"); final JSONArray questionnaires = jsonExperiment.getJSONArray("questionnaires"); final JSONObject jsonDetails = new JSONObject(); jsonDetails.put("filename", filename); for (int i = 0; i < questionnaires.length(); i++) { final JSONObject questionnaire = questionnaires.getJSONObject(i); if (questionnaire.get("questionnareID").equals(questionnaireID)) { jsonDetails.putOnce("questionnareTitle", questionnaire.get("questionnareTitle")); jsonDetails.putOnce("questionnareID", questionnaire.get("questionnareID")); final int numberOfQuestionnaires = questionnaire.getJSONArray("questions").length(); jsonDetails.putOnce("numQuestions", numberOfQuestionnaires); final List<String> landscapeNames = getLandscapesUsedInQuestionnaire(jsonExperiment, questionnaireID); jsonDetails.putOnce("landscapes", landscapeNames.toArray()); final String jsonUserList = getQuestionnaireUsers(jsonExperiment, questionnaireID); jsonDetails.putOnce("numUsers", new JSONArray(jsonUserList).length()); break; } } return jsonDetails.toString(); } @Override public String getExperimentAndUsers(final String data) throws IOException { final JSONObject filenameAndQuestionnaireID = new JSONObject(data); final String filename = filenameAndQuestionnaireID.getString("filename"); final String jsonString = getExperiment(filename); final JSONObject jsonExperiment = new JSONObject(jsonString); final JSONObject returnObj = new JSONObject(); returnObj.put("experiment", jsonExperiment.toString()); final String questionnaireID = filenameAndQuestionnaireID.getString("questionnareID"); final JSONArray questionnaires = jsonExperiment.getJSONArray("questionnaires"); // calculate prefix for questionnaire => get users final String prefix = jsonExperiment.getString("ID") + "_" + getQuestionnairePrefix(questionnaireID, questionnaires); final JSONArray jsonUsers = DBConnection.getQuestionnaireUsers(prefix); returnObj.put("users", jsonUsers); returnObj.put("questionnareID", questionnaireID); return returnObj.toString(); } //////////// // Helper // //////////// private String getQuestionnaireUsers(final JSONObject experiment, final String questionnaireID) { final JSONArray questionnaires = experiment.getJSONArray("questionnaires"); final String prefix = experiment.getString("ID") + "_" + getQuestionnairePrefix(questionnaireID, questionnaires); final JSONArray jsonUsers = DBConnection.getQuestionnaireUsers(prefix); return jsonUsers.toString(); } private int getExperimentUsers(final JSONObject experiment) { final JSONArray questionnaires = experiment.getJSONArray("questionnaires"); int userCount = 0; for (int i = 0; i < questionnaires.length(); i++) { final JSONObject questionnaire = questionnaires.getJSONObject(i); final String prefix = experiment.getString("ID") + "_" + getQuestionnairePrefix( questionnaire.getString("questionnareID"), questionnaires); final JSONArray jsonUsers = DBConnection.getQuestionnaireUsers(prefix); if (jsonUsers == null) { break; } userCount += jsonUsers.length(); } return userCount; } private String getQuestionnairePrefix(final String questionnaireID, final JSONArray questionnaires) { for (int i = 0; i < questionnaires.length(); i++) { final JSONObject questionnaire = questionnaires.getJSONObject(i); if (questionnaire.get("questionnareID").equals(questionnaireID)) { return questionnaire.getString("questionnareID"); } } return null; } private List<String> getLandScapeNamesOfExperiment(final String filename) throws IOException { final ArrayList<String> names = new ArrayList<>(); final String jsonString = getExperiment(filename); final JSONArray jsonQuestionnaires = new JSONObject(jsonString) .getJSONArray("questionnaires"); final int length = jsonQuestionnaires.length(); for (int i = 0; i < length; i++) { final JSONObject questionnaire = jsonQuestionnaires.getJSONObject(i); JSONArray questions = null; try { questions = questionnaire.getJSONArray("questions"); final int lengthQuestions = questions.length(); for (int j = 0; j < lengthQuestions; j++) { final JSONObject question = questions.getJSONObject(j); try { if (!names.contains(question.getString("expLandscape"))) { names.add(question.getString("expLandscape")); } } catch (final JSONException e) { // no landscape for this question } } } catch (final JSONException e) { // no questions for this questionnaire } } return names; } private List<String> getLandscapesUsedInQuestionnaire(final JSONObject jsonExperiment, final String questionnaireID) { final ArrayList<String> names = new ArrayList<>(); final JSONArray jsonQuestionnaires = jsonExperiment.getJSONArray("questionnaires"); final int length = jsonQuestionnaires.length(); for (int i = 0; i < length; i++) { final JSONObject questionnaire = jsonQuestionnaires.getJSONObject(i); if (questionnaire.getString("questionnareID").equals(questionnaireID)) { JSONArray questions = null; try { questions = questionnaire.getJSONArray("questions"); final int lengthQuestions = questions.length(); for (int j = 0; j < lengthQuestions; j++) { final JSONObject question = questions.getJSONObject(j); try { if (!names.contains(question.getString("expLandscape"))) { names.add(question.getString("expLandscape")); } } catch (final JSONException e) { // no landscape for this question } } } catch (final JSONException e) { // no questions for this questionnaire } } } return names; } private void removeUserData(final String username) { final User user = DBConnection.getUserByName(username); final String filenameResults = EXP_ANSWER_FOLDER + File.separator + user.getQuestionnairePrefix() + File.separator + username + ".csv"; final String filenameTracking = Tracking_FOLDER + File.separator + user.getQuestionnairePrefix() + File.separator + username + "_tracking.log"; Path path = Paths.get(filenameResults); removeFileByPath(path); path = Paths.get(filenameTracking); removeFileByPath(path); } public static void createExperimentFoldersIfNotExist() { final File expDirectory = new File(EXP_FOLDER); final File replayDirectory = new File(LANDSCAPE_FOLDER); final File answersDirectory = new File(EXP_ANSWER_FOLDER); final File trackingDirectory = new File(Tracking_FOLDER); if (!expDirectory.exists()) { expDirectory.mkdir(); } if (!replayDirectory.exists()) { replayDirectory.mkdir(); } if (!answersDirectory.exists()) { answersDirectory.mkdir(); } if (!trackingDirectory.exists()) { trackingDirectory.mkdir(); } } private void removeQuestionnaireUsers(final String questionnairePrefix) { final JSONArray jsonUsers = DBConnection.getQuestionnaireUsers(questionnairePrefix); final int length = jsonUsers.length(); for (int i = 0; i < length; i++) { final JSONObject user = jsonUsers.getJSONObject(i); DBConnection.removeUser(user.getString("username")); } } private void createFileByPath(final Path toCreate, final byte[] bytes) throws IOException { createExperimentFoldersIfNotExist(); try { Files.write(toCreate, bytes, StandardOpenOption.CREATE_NEW); } catch (final java.nio.file.FileAlreadyExistsException e) { Files.write(toCreate, bytes, StandardOpenOption.TRUNCATE_EXISTING); } } private void removeFileByPath(final Path toDelete) { createExperimentFoldersIfNotExist(); try { Files.delete(toDelete); } catch (final DirectoryNotEmptyException e) { // if directory, remove everything inside // and then the parent folder final File directory = toDelete.toFile(); final String[] fList = directory.list(); for (final String filename : fList) { removeFileByPath(Paths.get(directory + File.separator + filename)); } removeFileByPath(toDelete); } catch (final NoSuchFileException e) { // System.err.println("Couldn't delete file with path: " + toDelete // + ". It doesn't exist. Exception: " + e); } catch (final IOException e) { System.err.println("Couldn't delete file with path: " + toDelete + ". Exception: " + e); } } private boolean validateExperiment(final String jsonExperiment) throws IOException, ProcessingException { final JsonNode experiment = JsonLoader.fromString(jsonExperiment); String schemaPath = null; try { schemaPath = getServletContext().getRealPath("/experiment/") + "/" + "experimentJSONSchema.json"; } catch (final IllegalStateException e) { // catched => no servlet context => try to use // relative path of project for Unit testing schemaPath = "./war/experiment/experimentJSONSchema.json"; } final JsonNode schemaNode = JsonLoader.fromPath(schemaPath); final JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); final JsonSchema schema = factory.getJsonSchema(schemaNode); final ProcessingReport report = schema.validate(experiment); return report.isSuccess(); } }
src/explorviz/server/util/JSONServiceImpl.java
package explorviz.server.util; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.text.SimpleDateFormat; import java.util.*; import javax.xml.bind.DatatypeConverter; import org.apache.commons.codec.binary.Base64; import org.json.*; import org.zeroturnaround.zip.ZipUtil; import com.fasterxml.jackson.databind.JsonNode; import com.github.fge.jackson.JsonLoader; import com.github.fge.jsonschema.core.exceptions.ProcessingException; import com.github.fge.jsonschema.core.report.ProcessingReport; import com.github.fge.jsonschema.main.JsonSchema; import com.github.fge.jsonschema.main.JsonSchemaFactory; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import explorviz.server.database.DBConnection; import explorviz.server.landscapeexchange.LandscapeExchangeServiceImpl; import explorviz.server.main.Configuration; import explorviz.server.main.FileSystemHelper; import explorviz.shared.auth.User; import explorviz.shared.experiment.Question; import explorviz.visualization.experiment.services.JSONService; public class JSONServiceImpl extends RemoteServiceServlet implements JSONService { private static final long serialVersionUID = 6576514774419481521L; public static String EXP_FOLDER = FileSystemHelper.getExplorVizDirectory() + File.separator + "experiment"; public static String EXP_ANSWER_FOLDER = FileSystemHelper.getExplorVizDirectory() + File.separator + "experiment" + File.separator + "answers"; public static String LANDSCAPE_FOLDER = FileSystemHelper.getExplorVizDirectory() + File.separator + "replay"; public static String Tracking_FOLDER = FileSystemHelper.getExplorVizDirectory() + File.separator + "usertracking"; ///////////////// // RPC Methods // ///////////////// @Override public void saveJSONOnServer(final String json) throws IOException { JSONObject jsonObj = null; try { jsonObj = new JSONObject(json); } catch (final JSONException e) { System.err.println("Method: saveJSONOnServer; Couldn't create JSONObject"); } if (jsonObj == null) { return; } final long timestamp = new Date().getTime(); jsonObj.put("lastModified", timestamp); final String filename = jsonObj.getString("filename"); final Path experimentFolder = Paths.get(EXP_FOLDER + File.separator + filename); final byte[] bytes = jsonObj.toString(4).getBytes(StandardCharsets.UTF_8); createFileByPath(experimentFolder, bytes); } @Override public void saveQuestionnaireServer(final String data) throws IOException { final JSONObject filenameAndQuestionnaire = new JSONObject(data); final String filename = filenameAndQuestionnaire.getString("filename"); final String jsonString = getExperiment(filename); final JSONObject jsonExperiment = new JSONObject(jsonString); // TODO check if change crashes live // final JSONObject questionnaire = new // JSONObject(filenameAndQuestionnaire.getString("questionnaire")); final JSONObject questionnaire = filenameAndQuestionnaire.getJSONObject("questionnaire"); final JSONArray questionnaires = jsonExperiment.getJSONArray("questionnaires"); boolean questionnaireUpdated = false; for (int i = 0; i < questionnaires.length(); i++) { final JSONObject questionnaireTemp = questionnaires.getJSONObject(i); // find questionnaire to update if (questionnaireTemp.has("questionnareTitle") && questionnaireTemp.getString("questionnareID") .equals(questionnaire.getString("questionnareID"))) { questionnaireUpdated = true; questionnaires.put(i, questionnaire); } } if (!questionnaireUpdated) { // not added => new questionnaire // TODO Check ifs crashed: .toString() was removed here questionnaires.put(questionnaire); } try { saveJSONOnServer(jsonExperiment.toString()); } catch (final IOException e) { System.err.println("Couldn't save experiment when removing questionnaire."); } } @Override public List<String> getExperimentFilenames() { final List<String> filenames = new ArrayList<String>(); final File directory = new File(EXP_FOLDER); final File[] fList = directory.listFiles(new FileFilter() { @Override public boolean accept(final File pathname) { final String name = pathname.getName().toLowerCase(); return name.endsWith(".json") && pathname.isFile(); } }); if (fList != null) { for (final File f : fList) { filenames.add(f.getName()); } } return filenames; } @Override public List<String> getExperimentTitles() throws IOException { final List<String> titles = new ArrayList<String>(); final File directory = new File(EXP_FOLDER); // Filters Files only; no folders are added final File[] fList = directory.listFiles(new FileFilter() { @Override public boolean accept(final File pathname) { final String name = pathname.getName().toLowerCase(); return name.endsWith(".json") && pathname.isFile(); } }); if (fList != null) { for (final File f : fList) { final String filename = f.getName(); final String json = getExperiment(filename); final JSONObject jsonObj = new JSONObject(json); titles.add(jsonObj.getString("title")); } } return titles; } @Override public String getExperiment(final String filename) throws IOException { byte[] jsonBytes = null; createExperimentFoldersIfNotExist(); jsonBytes = Files.readAllBytes(Paths.get(EXP_FOLDER + File.separator + filename)); return new String(jsonBytes, StandardCharsets.UTF_8); } @Override public void removeExperiment(final String filename) throws JSONException, IOException { final JSONObject jsonExperiment = new JSONObject(getExperiment(filename)); final JSONArray questionnaires = jsonExperiment.getJSONArray("questionnaires"); for (int i = 0; i < questionnaires.length(); i++) { final JSONObject questionnaire = questionnaires.getJSONObject(i); final JSONObject data = new JSONObject(); data.put("filename", filename); data.put("questionnareID", questionnaire.getString("questionnareID")); removeQuestionnaire(data.toString()); } final Path experimentFile = Paths.get(EXP_FOLDER + File.separator + filename); removeFileByPath(experimentFile); } @Override public String getExperimentDetails(final String filename) throws IOException { final String jsonString = getExperiment(filename); final JSONObject jsonExperiment = new JSONObject(jsonString); final JSONObject jsonDetails = new JSONObject(); final SimpleDateFormat df = new SimpleDateFormat("HH:mm - dd-MM-yyyy"); jsonDetails.put("title", jsonExperiment.get("title")); jsonDetails.put("filename", jsonExperiment.get("filename")); final int numberOfQuestionnaires = jsonExperiment.getJSONArray("questionnaires").length(); jsonDetails.put("numQuestionnaires", numberOfQuestionnaires); final List<String> landscapeNames = getLandScapeNamesOfExperiment(filename); jsonDetails.put("landscapes", landscapeNames.toArray()); final int userCount = getExperimentUsers(jsonExperiment); jsonDetails.put("userCount", userCount); final long lastStarted = jsonExperiment.getLong("lastStarted"); if (lastStarted != 0) { jsonDetails.put("lastStarted", df.format(new Date(lastStarted))); } else { jsonDetails.put("lastStarted", ""); } final long lastEnded = jsonExperiment.getLong("lastEnded"); if (lastEnded != 0) { jsonDetails.put("lastEnded", df.format(new Date(lastEnded))); } else { jsonDetails.put("lastEnded", ""); } final long lastModified = jsonExperiment.getLong("lastModified"); jsonDetails.put("lastModified", df.format(new Date(lastModified))); return jsonDetails.toString(); } @Override public void removeQuestionnaire(final String data) throws JSONException, IOException { final JSONObject jsonData = new JSONObject(data); final String filename = jsonData.getString("filename"); String jsonString; jsonString = getExperiment(filename); final JSONObject jsonExperiment = new JSONObject(jsonString); final String questionnaireID = jsonData.getString("questionnareID"); final JSONArray questionnaires = jsonExperiment.getJSONArray("questionnaires"); for (int i = 0; i < questionnaires.length(); i++) { final JSONObject questionnaire = questionnaires.getJSONObject(i); if (questionnaire.get("questionnareID").equals(questionnaireID)) { // remove users final String prefix = jsonExperiment.getString("ID") + "_" + getQuestionnairePrefix( questionnaire.getString("questionnareID"), questionnaires); removeQuestionnaireUsers(prefix); // remove answers final Path answers = Paths.get(EXP_ANSWER_FOLDER + File.separator + prefix); removeFileByPath(answers); // remove user logs final Path logs = Paths.get(Tracking_FOLDER + File.separator + prefix); removeFileByPath(logs); // remove file and save new json on server questionnaires.remove(i); try { saveJSONOnServer(jsonExperiment.toString()); } catch (final IOException e) { System.err.println("Couldn't save experiment when removing questionnaire."); } } } } @Override public String getQuestionnaire(final String data) throws IOException { final JSONObject filenameAndQuestionnaireID = new JSONObject(data); final String filename = filenameAndQuestionnaireID.getString("filename"); final String jsonString = getExperiment(filename); final JSONObject jsonExperiment = new JSONObject(jsonString); final String questionnareID = filenameAndQuestionnaireID.getString("questionnareID"); final JSONArray questionnaires = jsonExperiment.getJSONArray("questionnaires"); for (int i = 0; i < questionnaires.length(); i++) { final JSONObject questionnaire = questionnaires.getJSONObject(i); if (questionnaire.get("questionnareID").equals(questionnareID)) { return questionnaire.toString(); } } return null; } @Override public Boolean isUserInCurrentExperiment(final String username) throws JSONException, IOException { final User tempUser = DBConnection.getUserByName(username); if (tempUser == null) { return false; } final String questionnairePrefix = tempUser.getQuestionnairePrefix(); JSONObject experiment = null; try { experiment = new JSONObject(getExperiment(Configuration.experimentFilename)); } catch (final IOException e) { // System.err.println("Could not read experiment. This may not be // bad. Exception: " + e); return false; } final String prefix = experiment.getString("ID"); return questionnairePrefix.startsWith(prefix); } @Override public Question[] getQuestionnaireQuestionsForUser(final String filename, final String userName) throws IOException { final ArrayList<Question> questions = new ArrayList<Question>(); final String jsonString = getExperiment(filename); final JSONObject jsonExperiment = new JSONObject(jsonString); String questionnairePrefix = DBConnection.getUserByName(userName).getQuestionnairePrefix(); questionnairePrefix = questionnairePrefix.replace(jsonExperiment.getString("ID") + "_", ""); final JSONArray questionnaires = jsonExperiment.getJSONArray("questionnaires"); for (int i = 0; i < questionnaires.length(); i++) { final JSONObject questionnaire = questionnaires.getJSONObject(i); if (questionnaire.getString("questionnareID").equals(questionnairePrefix)) { final JSONArray jsonQuestions = questionnaire.getJSONArray("questions"); for (int w = 0; w < jsonQuestions.length(); w++) { final JSONObject jsonQuestion = jsonQuestions.getJSONObject(w); final String text = jsonQuestion.getString("questionText"); final String type = jsonQuestion.getString("type"); final int procTime = Integer.parseInt(jsonQuestion.getString("workingTime")); final String timestampData = jsonQuestion.getString("expLandscape"); String maybeApplication = ""; try { maybeApplication = jsonQuestion.getString("expApplication"); } catch (final JSONException e) { // there was no application for this question // => no problem => landscape question } final long timestamp = Long.parseLong(timestampData.split("-")[0]); final long activity = Long .parseLong(timestampData.split("-")[1].split(".expl")[0]); final JSONArray correctsArray = jsonQuestion.getJSONArray("answers"); final int lengthQuestions = correctsArray.length(); final ArrayList<String> corrects = new ArrayList<String>(); final String[] answers = new String[lengthQuestions]; for (int j = 0; j < lengthQuestions; j++) { final JSONObject jsonAnswer = correctsArray.getJSONObject(j); if (jsonAnswer.getString("answerText") != "") { answers[j] = jsonAnswer.getString("answerText"); if (jsonAnswer.getBoolean("checkboxChecked")) { corrects.add(answers[j]); } } } final Question question = new Question(i, type, text, answers, corrects.toArray(new String[0]), procTime, timestamp, activity, maybeApplication); questions.add(question); } } } return questions.toArray(new Question[0]); } @Override public void duplicateExperiment(final String filename) throws IOException { final JSONObject jsonObj = new JSONObject(getExperiment(filename)); final String title = jsonObj.getString("title"); jsonObj.put("title", title + "_dup"); final long timestamp = new Date().getTime(); jsonObj.put("filename", "exp_" + timestamp + ".json"); jsonObj.put("ID", "exp" + timestamp); saveJSONOnServer(jsonObj.toString()); } @Override public boolean uploadExperiment(final String jsonExperimentFile) throws IOException { final JSONObject encodedExpFile = new JSONObject(jsonExperimentFile); String encodedExperiment = null; try { encodedExperiment = new String(encodedExpFile.getString("fileData").split(",")[1] .getBytes(StandardCharsets.UTF_8)); } catch (final ArrayIndexOutOfBoundsException e) { e.printStackTrace(); return false; } byte[] bytes = null; try { bytes = DatatypeConverter.parseBase64Binary(encodedExperiment); } catch (final IllegalArgumentException e) { e.printStackTrace(); return false; } final String jsonExperiment = new String(bytes); boolean isValidExperiment = false; try { isValidExperiment = validateExperiment(jsonExperiment); } catch (IOException | ProcessingException e) { System.err.println( "Method: uploadExperiment. Couldn't upload experiment. Exception: " + e); return false; } if (isValidExperiment) { saveJSONOnServer(jsonExperiment); return true; } else { return false; } } @Override public String downloadExperimentData(final String filename) throws IOException { // # add user results and logs to zip # final JSONObject experimentJson = new JSONObject(getExperiment(filename)); // # create zip # final File zip = new File(EXP_FOLDER + File.separator + "experimentData.zip"); // # add .json to zip # final File experimentFile = new File(EXP_FOLDER + File.separator + filename); ZipUtil.packEntries(new File[] { experimentFile }, zip); final JSONArray jsonQuestionnaires = experimentJson.getJSONArray("questionnaires"); final int length = jsonQuestionnaires.length(); for (int i = 0; i < length; i++) { final JSONObject questionnaire = jsonQuestionnaires.getJSONObject(i); final String questPrefix = experimentJson.getString("ID") + "_" + getQuestionnairePrefix(questionnaire.getString("questionnareID"), jsonQuestionnaires); final File answersFolder = new File(EXP_ANSWER_FOLDER + File.separator + questPrefix); File[] listOfFiles = answersFolder.listFiles(); if (listOfFiles != null) { for (final File file : listOfFiles) { if (file.isFile()) { ZipUtil.addEntry(zip, "answers/" + questPrefix + "/" + file.getName(), file); } } } final File trackingFolder = new File(FileSystemHelper.getExplorVizDirectory() + File.separator + "usertracking" + File.separator + questPrefix); listOfFiles = trackingFolder.listFiles(); if (listOfFiles != null) { for (final File file : listOfFiles) { if (file.isFile()) { ZipUtil.addEntry(zip, "usertracking/" + questPrefix + "/" + file.getName(), file); } } } } // # add all related landscapes to zip # final List<String> landscapeNames = getLandScapeNamesOfExperiment(filename); for (final String landscapeName : landscapeNames) { final File landscape = new File( LANDSCAPE_FOLDER + File.separator + landscapeName + ".expl"); ZipUtil.addEntry(zip, "landscapes/" + landscapeName + ".expl", landscape); } // # Now encode to Base64 # final List<Byte> result = new ArrayList<Byte>(); final byte[] buffer = new byte[1024]; final InputStream is = new FileInputStream(zip); int b = is.read(buffer); while (b != -1) { for (int i = 0; i < b; i++) { result.add(buffer[i]); } b = is.read(buffer); } is.close(); final byte[] buf = new byte[result.size()]; for (int i = 0; i < result.size(); i++) { buf[i] = result.get(i); } final String encoded = Base64.encodeBase64String(buf); // # Send back to client # return encoded; } @Override public String getExperimentTitlesAndFilenames() throws IOException { final JSONObject returnObj = new JSONObject(); final File directory = new File(EXP_FOLDER); final JSONArray failingExperiments = new JSONArray(); // Filter valid experiments out in experiment folder final File[] fList = directory.listFiles(new FileFilter() { @Override public boolean accept(final File pathname) { final String name = pathname.getName().toLowerCase(); try { if (!name.endsWith(".json") || !pathname.isFile()) { return false; } final boolean isValidExperiment = validateExperiment(getExperiment(name)); if (!isValidExperiment) { failingExperiments.put(name); } return isValidExperiment; } catch (IOException | ProcessingException e) { System.err.println("Couldn't process file " + name + ". Exception: " + e); } return false; } }); returnObj.put("failingExperiments", failingExperiments); final JSONArray experimentsData = new JSONArray(); returnObj.put("experimentsData", experimentsData); // collect necessary data of experiments for // experiment overview if (fList != null) { JSONObject tmpData = null; long tmpLastModified = 0; for (final File f : fList) { final JSONObject data = new JSONObject(); final String filename = f.getName(); final String jsonExperiment = getExperiment(filename); JSONObject jsonObj = null; try { jsonObj = new JSONObject(jsonExperiment); } catch (final JSONException e) { System.err.println( "Method: getExperimentTitlesAndFilenames; Couldn't create JSONObject for file: " + filename); continue; } final long lastModified = jsonObj.getLong("lastModified"); if (lastModified > tmpLastModified) { data.put("lastTouched", "true"); if (tmpData != null) { tmpData.put("lastTouched", "false"); } tmpLastModified = lastModified; tmpData = data; } else { data.put("lastTouched", "false"); } data.put("filename", jsonObj.get("filename").toString()); data.put("title", jsonObj.get("title").toString()); final JSONArray questionnairesData = new JSONArray(); if ((jsonObj != null) && jsonObj.has("questionnaires")) { final JSONArray questionnaires = jsonObj.getJSONArray("questionnaires"); for (int i = 0; i < questionnaires.length(); i++) { final JSONObject questionnaireObj = questionnaires.getJSONObject(i); final JSONObject questionnaireData = new JSONObject(); questionnaireData.put("questionnareTitle", questionnaireObj.getString("questionnareTitle")); questionnaireData.put("questionnareID", questionnaireObj.getString("questionnareID")); questionnairesData.put(questionnaireData); } data.put("questionnaires", questionnairesData); } experimentsData.put(data); } } return returnObj.toString(); } @Override public String createUsersForQuestionnaire(final int count, final String prefix, final String filename) { final JSONArray users = DBConnection.createUsersForQuestionnaire(prefix, count); final JSONObject returnObj = new JSONObject(); returnObj.put("users", users); // update lastModified stamp JSONObject experiment = null; try { experiment = new JSONObject(getExperiment(filename)); } catch (IOException | JSONException e) { System.err.println("Couldn not update timestamp. Exception: " + e); } experiment.put("lastModified", new Date().getTime()); try { saveJSONOnServer(experiment.toString()); } catch (final IOException e) { System.err.println("Could not save updated experiment. Exception: " + e); } return returnObj.toString(); } @Override public String isExperimentReadyToStart(final String filename) throws JSONException, IOException { final JSONObject experiment = new JSONObject(getExperiment(filename)); final JSONArray questionnaires = experiment.getJSONArray("questionnaires"); final int length = questionnaires.length(); if (length == 0) { return "Add a questionnaire first."; } for (int i = 0; i < length; i++) { final JSONObject questionnaire = questionnaires.getJSONObject(i); final JSONArray questions = questionnaire.getJSONArray("questions"); if (questions.length() == 0) { return "Add at least one question to the questionnaire: " + questionnaire.getString("questionnareTitle"); } if (questionnaire.getString("questionnareTitle").equals("")) { return "There is at least one questionnaire without a name"; } } // experiment is ready try { saveJSONOnServer(experiment.toString()); } catch (final IOException e) { System.err.println(e); } return "ready"; } @Override public void setExperimentTimeAttr(final String filename, final boolean isLastStarted) throws JSONException, IOException { final JSONObject experiment = new JSONObject(getExperiment(filename)); // => update time attributes if (isLastStarted) { experiment.put("lastStarted", new Date().getTime()); } else { experiment.put("lastEnded", new Date().getTime()); } try { saveJSONOnServer(experiment.toString()); } catch (final IOException e) { e.printStackTrace(); } } @Override public String getExperimentTitle(final String filename) throws JSONException, IOException { final JSONObject experiment = new JSONObject(getExperiment(filename)); return experiment.getString("title"); } @Override public String removeQuestionnaireUser(final String data) throws IOException { final JSONObject jsonData = new JSONObject(data); final JSONArray usernames = jsonData.getJSONArray("users"); final String filename = jsonData.getString("filename"); final String questionnareID = jsonData.getString("questionnareID"); final JSONObject filenameAndQuestID = new JSONObject(); filenameAndQuestID.put("filename", filename); filenameAndQuestID.put("questionnareID", questionnareID); final int length = usernames.length(); for (int i = 0; i < length; i++) { final String username = usernames.getString(i); removeUserData(username); DBConnection.removeUser(username); } // update lastModified stamp JSONObject experiment = null; try { experiment = new JSONObject(getExperiment(filename)); } catch (IOException | JSONException e) { System.err.println("Couldn not update timestamp. Exception: " + e); } experiment.put("lastModified", new Date().getTime()); try { saveJSONOnServer(experiment.toString()); } catch (final IOException e) { System.err.println("Could not save updated experiment. Exception: " + e); } return getExperimentAndUsers(filenameAndQuestID.toString()); } @Override public boolean uploadLandscape(final String data) throws IOException { final JSONObject encodedLandscapeFile = new JSONObject(data); final String filename = encodedLandscapeFile.getString("filename"); // first validation check -> filename long timestamp; long activity; try { timestamp = Long.parseLong(filename.split("-")[0]); activity = Long.parseLong(filename.split("-")[1].split(".expl")[0]); } catch (final NumberFormatException e) { return false; } final Path landscapePath = Paths.get(LANDSCAPE_FOLDER + File.separator + filename); String encodedLandscape = null; try { encodedLandscape = new String(encodedLandscapeFile.getString("fileData").split(",")[1] .getBytes(StandardCharsets.UTF_8)); } catch (final ArrayIndexOutOfBoundsException e) { return false; } byte[] bytes = null; try { bytes = DatatypeConverter.parseBase64Binary(encodedLandscape); } catch (ArrayIndexOutOfBoundsException | IllegalArgumentException e) { return false; } createFileByPath(landscapePath, bytes); // second validation check -> deserialization try { LandscapeExchangeServiceImpl.getLandscapeStatic(timestamp, activity); } catch (final Exception e) { // e.printStackTrace(); removeFileByPath(landscapePath); return false; } return true; } @Override public String getQuestionnaireDetails(final String data) throws IOException { final JSONObject filenameAndQuestionnaireID = new JSONObject(data); final String filename = filenameAndQuestionnaireID.getString("filename"); final String jsonString = getExperiment(filename); final JSONObject jsonExperiment = new JSONObject(jsonString); final String questionnaireID = filenameAndQuestionnaireID.getString("questionnareID"); final JSONArray questionnaires = jsonExperiment.getJSONArray("questionnaires"); final JSONObject jsonDetails = new JSONObject(); jsonDetails.put("filename", filename); for (int i = 0; i < questionnaires.length(); i++) { final JSONObject questionnaire = questionnaires.getJSONObject(i); if (questionnaire.get("questionnareID").equals(questionnaireID)) { jsonDetails.putOnce("questionnareTitle", questionnaire.get("questionnareTitle")); jsonDetails.putOnce("questionnareID", questionnaire.get("questionnareID")); final int numberOfQuestionnaires = questionnaire.getJSONArray("questions").length(); jsonDetails.putOnce("numQuestions", numberOfQuestionnaires); final List<String> landscapeNames = getLandscapesUsedInQuestionnaire(jsonExperiment, questionnaireID); jsonDetails.putOnce("landscapes", landscapeNames.toArray()); final String jsonUserList = getQuestionnaireUsers(jsonExperiment, questionnaireID); jsonDetails.putOnce("numUsers", new JSONArray(jsonUserList).length()); break; } } return jsonDetails.toString(); } @Override public String getExperimentAndUsers(final String data) throws IOException { final JSONObject filenameAndQuestionnaireID = new JSONObject(data); final String filename = filenameAndQuestionnaireID.getString("filename"); final String jsonString = getExperiment(filename); final JSONObject jsonExperiment = new JSONObject(jsonString); final JSONObject returnObj = new JSONObject(); returnObj.put("experiment", jsonExperiment.toString()); final String questionnaireID = filenameAndQuestionnaireID.getString("questionnareID"); final JSONArray questionnaires = jsonExperiment.getJSONArray("questionnaires"); // calculate prefix for questionnaire => get users final String prefix = jsonExperiment.getString("ID") + "_" + getQuestionnairePrefix(questionnaireID, questionnaires); final JSONArray jsonUsers = DBConnection.getQuestionnaireUsers(prefix); returnObj.put("users", jsonUsers); returnObj.put("questionnareID", questionnaireID); return returnObj.toString(); } //////////// // Helper // //////////// private String getQuestionnaireUsers(final JSONObject experiment, final String questionnaireID) { final JSONArray questionnaires = experiment.getJSONArray("questionnaires"); final String prefix = experiment.getString("ID") + "_" + getQuestionnairePrefix(questionnaireID, questionnaires); final JSONArray jsonUsers = DBConnection.getQuestionnaireUsers(prefix); return jsonUsers.toString(); } private int getExperimentUsers(final JSONObject experiment) { final JSONArray questionnaires = experiment.getJSONArray("questionnaires"); int userCount = 0; for (int i = 0; i < questionnaires.length(); i++) { final JSONObject questionnaire = questionnaires.getJSONObject(i); final String prefix = experiment.getString("ID") + "_" + getQuestionnairePrefix( questionnaire.getString("questionnareID"), questionnaires); final JSONArray jsonUsers = DBConnection.getQuestionnaireUsers(prefix); if (jsonUsers == null) { break; } userCount += jsonUsers.length(); } return userCount; } private String getQuestionnairePrefix(final String questionnaireID, final JSONArray questionnaires) { for (int i = 0; i < questionnaires.length(); i++) { final JSONObject questionnaire = questionnaires.getJSONObject(i); if (questionnaire.get("questionnareID").equals(questionnaireID)) { return questionnaire.getString("questionnareID"); } } return null; } private List<String> getLandScapeNamesOfExperiment(final String filename) throws IOException { final ArrayList<String> names = new ArrayList<>(); final String jsonString = getExperiment(filename); final JSONArray jsonQuestionnaires = new JSONObject(jsonString) .getJSONArray("questionnaires"); final int length = jsonQuestionnaires.length(); for (int i = 0; i < length; i++) { final JSONObject questionnaire = jsonQuestionnaires.getJSONObject(i); JSONArray questions = null; try { questions = questionnaire.getJSONArray("questions"); final int lengthQuestions = questions.length(); for (int j = 0; j < lengthQuestions; j++) { final JSONObject question = questions.getJSONObject(j); try { if (!names.contains(question.getString("expLandscape"))) { names.add(question.getString("expLandscape")); } } catch (final JSONException e) { // no landscape for this question } } } catch (final JSONException e) { // no questions for this questionnaire } } return names; } private List<String> getLandscapesUsedInQuestionnaire(final JSONObject jsonExperiment, final String questionnaireID) { final ArrayList<String> names = new ArrayList<>(); final JSONArray jsonQuestionnaires = jsonExperiment.getJSONArray("questionnaires"); final int length = jsonQuestionnaires.length(); for (int i = 0; i < length; i++) { final JSONObject questionnaire = jsonQuestionnaires.getJSONObject(i); if (questionnaire.getString("questionnareID").equals(questionnaireID)) { JSONArray questions = null; try { questions = questionnaire.getJSONArray("questions"); final int lengthQuestions = questions.length(); for (int j = 0; j < lengthQuestions; j++) { final JSONObject question = questions.getJSONObject(j); try { if (!names.contains(question.getString("expLandscape"))) { names.add(question.getString("expLandscape")); } } catch (final JSONException e) { // no landscape for this question } } } catch (final JSONException e) { // no questions for this questionnaire } } } return names; } private void removeUserData(final String username) { final User user = DBConnection.getUserByName(username); final String filenameResults = EXP_ANSWER_FOLDER + File.separator + user.getQuestionnairePrefix() + File.separator + username + ".csv"; final String filenameTracking = Tracking_FOLDER + File.separator + user.getQuestionnairePrefix() + File.separator + username + "_tracking.log"; Path path = Paths.get(filenameResults); removeFileByPath(path); path = Paths.get(filenameTracking); removeFileByPath(path); } public static void createExperimentFoldersIfNotExist() { final File expDirectory = new File(EXP_FOLDER); final File replayDirectory = new File(LANDSCAPE_FOLDER); final File answersDirectory = new File(EXP_ANSWER_FOLDER); final File trackingDirectory = new File(Tracking_FOLDER); if (!expDirectory.exists()) { expDirectory.mkdir(); } if (!replayDirectory.exists()) { replayDirectory.mkdir(); } if (!answersDirectory.exists()) { answersDirectory.mkdir(); } if (!trackingDirectory.exists()) { trackingDirectory.mkdir(); } } private void removeQuestionnaireUsers(final String questionnairePrefix) { final JSONArray jsonUsers = DBConnection.getQuestionnaireUsers(questionnairePrefix); final int length = jsonUsers.length(); for (int i = 0; i < length; i++) { final JSONObject user = jsonUsers.getJSONObject(i); DBConnection.removeUser(user.getString("username")); } } private void createFileByPath(final Path toCreate, final byte[] bytes) throws IOException { createExperimentFoldersIfNotExist(); try { Files.write(toCreate, bytes, StandardOpenOption.CREATE_NEW); } catch (final java.nio.file.FileAlreadyExistsException e) { Files.write(toCreate, bytes, StandardOpenOption.TRUNCATE_EXISTING); } } private void removeFileByPath(final Path toDelete) { createExperimentFoldersIfNotExist(); try { Files.delete(toDelete); } catch (final DirectoryNotEmptyException e) { // if directory, remove everything inside // and then the parent folder final File directory = toDelete.toFile(); final String[] fList = directory.list(); for (final String filename : fList) { removeFileByPath(Paths.get(directory + File.separator + filename)); } removeFileByPath(toDelete); } catch (final NoSuchFileException e) { // System.err.println("Couldn't delete file with path: " + toDelete // + ". It doesn't exist. Exception: " + e); } catch (final IOException e) { System.err.println("Couldn't delete file with path: " + toDelete + ". Exception: " + e); } } private boolean validateExperiment(final String jsonExperiment) throws IOException, ProcessingException { final JsonNode experiment = JsonLoader.fromString(jsonExperiment); String schemaPath = null; try { schemaPath = getServletContext().getRealPath("/experiment/") + "/" + "experimentJSONSchema.json"; } catch (final IllegalStateException e) { // catched => no servlet context => try to use // relative path of project for Unit testing schemaPath = "./war/experiment/experimentJSONSchema.json"; } final JsonNode schemaNode = JsonLoader.fromPath(schemaPath); final JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); final JsonSchema schema = factory.getJsonSchema(schemaNode); final ProcessingReport report = schema.validate(experiment); return report.isSuccess(); } }
validate before saving
src/explorviz/server/util/JSONServiceImpl.java
validate before saving
<ide><path>rc/explorviz/server/util/JSONServiceImpl.java <ide> final long timestamp = new Date().getTime(); <ide> jsonObj.put("lastModified", timestamp); <ide> <del> final String filename = jsonObj.getString("filename"); <del> final Path experimentFolder = Paths.get(EXP_FOLDER + File.separator + filename); <del> <del> final byte[] bytes = jsonObj.toString(4).getBytes(StandardCharsets.UTF_8); <del> <del> createFileByPath(experimentFolder, bytes); <add> boolean isValid = false; <add> <add> try { <add> isValid = validateExperiment(jsonObj.toString()); <add> } catch (final ProcessingException e) { <add> System.err.println("There was an error while saving an experiment. Exception: " + e); <add> return; <add> } <add> <add> if (isValid) { <add> final String filename = jsonObj.getString("filename"); <add> final Path experimentFolder = Paths.get(EXP_FOLDER + File.separator + filename); <add> <add> final byte[] bytes = jsonObj.toString(4).getBytes(StandardCharsets.UTF_8); <add> <add> createFileByPath(experimentFolder, bytes); <add> } <ide> } <ide> <ide> @Override
JavaScript
bsd-3-clause
94c1e1535d66838106472d6623b24ac8df81179e
0
nteract/nteract,jdetle/nteract,temogen/nteract,captainsafia/nteract,captainsafia/nteract,jdfreder/nteract,nteract/composition,captainsafia/nteract,captainsafia/nteract,jdetle/nteract,nteract/nteract,jdfreder/nteract,0u812/nteract,rgbkrk/nteract,nteract/composition,rgbkrk/nteract,temogen/nteract,nteract/nteract,nteract/composition,rgbkrk/nteract,nteract/nteract,rgbkrk/nteract,jdfreder/nteract,temogen/nteract,0u812/nteract,jdfreder/nteract,nteract/nteract,0u812/nteract,rgbkrk/nteract,0u812/nteract,jdetle/nteract,jdetle/nteract
import { createStore, applyMiddleware } from 'redux'; import { reduxObservable } from 'redux-observable'; import rootReducer from '../reducers'; import * as constants from '../constants'; import { setBackwardCheckpoint } from '../actions'; const triggerUndo = store => next => action => { console.log('triggerUndo'); if (action.type === constants.REMOVE_CELL) { store.dispatch(setBackwardCheckpoint(store.getState().document)); } return next(action); }; export default function configureStore(initialState) { return createStore( rootReducer, initialState, applyMiddleware(reduxObservable(), triggerUndo) ); }
src/notebook/store/index.js
import { createStore, applyMiddleware } from 'redux'; import { reduxObservable } from 'redux-observable'; // import createLogger from 'redux-logger'; import rootReducer from '../reducers'; // const logger = createLogger(); const exposeState = store => next => action => { return next(Object.assign({}, action, { getState: store.getState, })); }; export default function configureStore(initialState) { return createStore( rootReducer, initialState, applyMiddleware(reduxObservable(), exposeState) ); }
Added triggerUndo middleware
src/notebook/store/index.js
Added triggerUndo middleware
<ide><path>rc/notebook/store/index.js <ide> import { createStore, applyMiddleware } from 'redux'; <ide> import { reduxObservable } from 'redux-observable'; <del>// import createLogger from 'redux-logger'; <ide> import rootReducer from '../reducers'; <ide> <del>// const logger = createLogger(); <add>import * as constants from '../constants'; <add>import { setBackwardCheckpoint } from '../actions'; <ide> <del>const exposeState = store => next => action => { <del> return next(Object.assign({}, action, { <del> getState: store.getState, <del> })); <add>const triggerUndo = store => next => action => { <add> console.log('triggerUndo'); <add> if (action.type === constants.REMOVE_CELL) { <add> store.dispatch(setBackwardCheckpoint(store.getState().document)); <add> } <add> return next(action); <ide> }; <ide> <ide> export default function configureStore(initialState) { <ide> return createStore( <ide> rootReducer, <ide> initialState, <del> applyMiddleware(reduxObservable(), exposeState) <add> applyMiddleware(reduxObservable(), triggerUndo) <ide> ); <ide> }
Java
agpl-3.0
9c5b77c96053dc4ad58d4c41e70a2c632f4a1dbd
0
flybird119/voltdb,flybird119/voltdb,zuowang/voltdb,migue/voltdb,creative-quant/voltdb,flybird119/voltdb,zuowang/voltdb,wolffcm/voltdb,migue/voltdb,kumarrus/voltdb,flybird119/voltdb,creative-quant/voltdb,migue/voltdb,migue/voltdb,creative-quant/voltdb,kumarrus/voltdb,simonzhangsm/voltdb,paulmartel/voltdb,wolffcm/voltdb,simonzhangsm/voltdb,deerwalk/voltdb,deerwalk/voltdb,creative-quant/voltdb,VoltDB/voltdb,wolffcm/voltdb,deerwalk/voltdb,ingted/voltdb,kumarrus/voltdb,simonzhangsm/voltdb,VoltDB/voltdb,paulmartel/voltdb,creative-quant/voltdb,simonzhangsm/voltdb,deerwalk/voltdb,paulmartel/voltdb,wolffcm/voltdb,simonzhangsm/voltdb,ingted/voltdb,flybird119/voltdb,ingted/voltdb,migue/voltdb,deerwalk/voltdb,paulmartel/voltdb,kumarrus/voltdb,zuowang/voltdb,deerwalk/voltdb,VoltDB/voltdb,kumarrus/voltdb,kumarrus/voltdb,VoltDB/voltdb,zuowang/voltdb,ingted/voltdb,ingted/voltdb,zuowang/voltdb,migue/voltdb,zuowang/voltdb,ingted/voltdb,ingted/voltdb,paulmartel/voltdb,simonzhangsm/voltdb,kumarrus/voltdb,flybird119/voltdb,VoltDB/voltdb,deerwalk/voltdb,wolffcm/voltdb,creative-quant/voltdb,simonzhangsm/voltdb,paulmartel/voltdb,zuowang/voltdb,zuowang/voltdb,flybird119/voltdb,wolffcm/voltdb,paulmartel/voltdb,creative-quant/voltdb,deerwalk/voltdb,creative-quant/voltdb,ingted/voltdb,paulmartel/voltdb,wolffcm/voltdb,kumarrus/voltdb,VoltDB/voltdb,VoltDB/voltdb,simonzhangsm/voltdb,wolffcm/voltdb,migue/voltdb,migue/voltdb,flybird119/voltdb
/* This file is part of VoltDB. * Copyright (C) 2008-2013 VoltDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Sets; import com.google.common.collect.TreeMultimap; import java.util.*; /** * Helper class for distributing a fixed number of buckets over some number of partitions. * Can handle adding new partitions by taking buckets from existing partitions and assigning them * to new ones */ public class Buckets { private final List<TreeSet<Integer>> m_partitionTokens = new ArrayList<TreeSet<Integer>>(); private final int m_tokenCount; private final long m_tokenInterval; public Buckets(int partitionCount, int tokenCount) { Preconditions.checkArgument(partitionCount > 0); Preconditions.checkArgument(tokenCount > partitionCount); Preconditions.checkArgument(tokenCount % 2 == 0); m_tokenCount = tokenCount; m_tokenInterval = calculateTokenInterval(tokenCount); m_partitionTokens.add(Sets.<Integer>newTreeSet()); long token = Integer.MIN_VALUE; for (int ii = 0; ii < tokenCount; ii++) { m_partitionTokens.get(0).add((int)token); token += m_tokenInterval; } addPartitions(partitionCount - 1); } public void addPartitions(int partitionCount) { //Can't have more partitions than tokens Preconditions.checkArgument(m_tokenCount > m_partitionTokens.size() + partitionCount); TreeSet<LoadPair> loadSet = Sets.newTreeSet(); for (int ii = 0; ii < m_partitionTokens.size(); ii++) { loadSet.add(new LoadPair(ii, m_partitionTokens.get(ii))); } for (int ii = 0; ii < partitionCount; ii++) { TreeSet<Integer> d = Sets.newTreeSet(); m_partitionTokens.add(d); loadSet.add(new LoadPair(m_partitionTokens.size() - 1, d)) ; addPartition(loadSet); } } /* * Loop and balance data after a partition is added until no * more balancing can be done */ private void addPartition(TreeSet<LoadPair> loadSet) { while (doNextBalanceOp(loadSet)) {} } private static long calculateTokenInterval(int bucketCount) { return Integer.MAX_VALUE / (bucketCount / 2); } public Buckets(SortedMap<Integer, Integer> tokens) { Preconditions.checkNotNull(tokens); Preconditions.checkArgument(tokens.size() > 1); Preconditions.checkArgument(tokens.size() % 2 == 0); m_tokenCount = tokens.size(); m_tokenInterval = calculateTokenInterval(m_tokenCount); int partitionCount = new HashSet<Integer>(tokens.values()).size(); for (int partition = 0; partition < partitionCount; partition++) { m_partitionTokens.add(Sets.<Integer>newTreeSet()); } for (Map.Entry<Integer, Integer> e : tokens.entrySet()) { TreeSet<Integer> buckets = m_partitionTokens.get(e.getValue()); int token = e.getKey(); buckets.add(token); } } public SortedMap<Integer, Integer> getTokens() { ImmutableSortedMap.Builder<Integer, Integer> b = ImmutableSortedMap.naturalOrder(); for (int partition = 0; partition < m_partitionTokens.size(); partition++) { TreeSet<Integer> tokens = m_partitionTokens.get(partition); for (Integer token : tokens) { b.put( token, partition); } } return b.build(); } /* * Take a token from the most loaded partition and move it to the least loaded partition * If no available balancing operation is available return false */ private boolean doNextBalanceOp(TreeSet<LoadPair> loadSet) { LoadPair mostLoaded = loadSet.pollLast(); LoadPair leastLoaded = loadSet.pollFirst(); try { //Perfection if (mostLoaded.tokens.size() == leastLoaded.tokens.size()) return false; //Can't improve on off by one, just end up off by one again if (mostLoaded.tokens.size() == (leastLoaded.tokens.size() + 1)) return false; int token = mostLoaded.tokens.pollFirst(); leastLoaded.tokens.add(token); } finally { loadSet.add(mostLoaded); loadSet.add(leastLoaded); } return true; } /* * Wrapper that orders and compares on load and then partition id for determinism */ private static class LoadPair implements Comparable<LoadPair> { private final Integer partition; private final TreeSet<Integer> tokens; public LoadPair(Integer partition, TreeSet<Integer> tokens) { this.partition = partition; this.tokens = tokens; } @Override public int hashCode() { return partition.hashCode(); } @Override public int compareTo(LoadPair o) { Preconditions.checkNotNull(o); int comparison = new Integer(tokens.size()).compareTo(o.tokens.size()); if (comparison == 0) { return partition.compareTo(o.partition); } else { return comparison; } } @Override public boolean equals(Object o) { if (o == null) return false; if (o.getClass() != LoadPair.class) return false; LoadPair lp = (LoadPair)o; return partition.equals(lp.partition); } @Override public String toString() { return "Partition " + partition + " tokens " + tokens.size(); } } }
src/frontend/org/voltdb/Buckets.java
/* This file is part of VoltDB. * Copyright (C) 2008-2013 VoltDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Sets; import com.google.common.collect.TreeMultimap; import java.util.*; /** * Helper class for distributing a fixed number of buckets over some number of partitions. * Can handle adding new partitions by taking buckets from existing partitions and assigning them * to new ones */ public class Buckets { private final List<TreeSet<Integer>> m_partitionTokens = new ArrayList<TreeSet<Integer>>(); private final int m_tokenCount; private final long m_tokenInterval; public Buckets(int partitionCount, int tokenCount) { Preconditions.checkArgument(partitionCount > 0); Preconditions.checkArgument(tokenCount > partitionCount); Preconditions.checkArgument(tokenCount % 2 == 0); m_tokenCount = tokenCount; m_tokenInterval = calculateTokenInterval(tokenCount); m_partitionTokens.add(Sets.<Integer>newTreeSet()); long token = Integer.MIN_VALUE; for (int ii = 0; ii < tokenCount; ii++) { m_partitionTokens.get(0).add((int)token); token += m_tokenInterval; } addPartitions(partitionCount - 1); } public void addPartitions(int partitionCount) { TreeSet<LoadPair> loadSet = Sets.newTreeSet(); for (int ii = 0; ii < m_partitionTokens.size(); ii++) { loadSet.add(new LoadPair(ii, m_partitionTokens.get(ii))); } for (int ii = 0; ii < partitionCount; ii++) { TreeSet<Integer> d = Sets.newTreeSet(); m_partitionTokens.add(d); loadSet.add(new LoadPair(m_partitionTokens.size() - 1, d)) ; addPartition(loadSet); } } /* * Loop and balance data after a partition is added until no * more balancing can be done */ private void addPartition(TreeSet<LoadPair> loadSet) { while (doNextBalanceOp(loadSet)) {} } private static long calculateTokenInterval(int bucketCount) { return Integer.MAX_VALUE / (bucketCount / 2); } public Buckets(SortedMap<Integer, Integer> tokens) { Preconditions.checkNotNull(tokens); Preconditions.checkArgument(tokens.size() > 1); Preconditions.checkArgument(tokens.size() % 2 == 0); m_tokenCount = tokens.size(); m_tokenInterval = calculateTokenInterval(m_tokenCount); int partitionCount = new HashSet<Integer>(tokens.values()).size(); for (int partition = 0; partition < partitionCount; partition++) { m_partitionTokens.add(Sets.<Integer>newTreeSet()); } for (Map.Entry<Integer, Integer> e : tokens.entrySet()) { TreeSet<Integer> buckets = m_partitionTokens.get(e.getValue()); int token = e.getKey(); buckets.add(token); } } public SortedMap<Integer, Integer> getTokens() { ImmutableSortedMap.Builder<Integer, Integer> b = ImmutableSortedMap.naturalOrder(); for (int partition = 0; partition < m_partitionTokens.size(); partition++) { TreeSet<Integer> tokens = m_partitionTokens.get(partition); for (Integer token : tokens) { b.put( token, partition); } } return b.build(); } /* * Take a token from the most loaded partition and move it to the least loaded partition * If no available balancing operation is available return false */ private boolean doNextBalanceOp(TreeSet<LoadPair> loadSet) { LoadPair mostLoaded = loadSet.pollLast(); LoadPair leastLoaded = loadSet.pollFirst(); try { //Perfection if (mostLoaded.tokens.size() == leastLoaded.tokens.size()) return false; //Can't improve on off by one, just end up off by one again if (mostLoaded.tokens.size() == (leastLoaded.tokens.size() + 1)) return false; int token = mostLoaded.tokens.pollFirst(); leastLoaded.tokens.add(token); } finally { loadSet.add(mostLoaded); loadSet.add(leastLoaded); } return true; } /* * Wrapper that orders and compares on load and then partition id for determinism */ private static class LoadPair implements Comparable<LoadPair> { private final Integer partition; private final TreeSet<Integer> tokens; public LoadPair(Integer partition, TreeSet<Integer> tokens) { this.partition = partition; this.tokens = tokens; } @Override public int hashCode() { return partition.hashCode(); } @Override public int compareTo(LoadPair o) { Preconditions.checkNotNull(o); int comparison = new Integer(tokens.size()).compareTo(o.tokens.size()); if (comparison == 0) { return partition.compareTo(o.partition); } else { return comparison; } } @Override public boolean equals(Object o) { if (o == null) return false; if (o.getClass() != LoadPair.class) return false; LoadPair lp = (LoadPair)o; return partition.equals(lp.partition); } @Override public String toString() { return "Partition " + partition + " tokens " + tokens.size(); } } }
For ENG-5256, add a precondition check to prevent more partitions then tokens
src/frontend/org/voltdb/Buckets.java
For ENG-5256, add a precondition check to prevent more partitions then tokens
<ide><path>rc/frontend/org/voltdb/Buckets.java <ide> } <ide> <ide> public void addPartitions(int partitionCount) { <add> //Can't have more partitions than tokens <add> Preconditions.checkArgument(m_tokenCount > m_partitionTokens.size() + partitionCount); <ide> TreeSet<LoadPair> loadSet = Sets.newTreeSet(); <ide> for (int ii = 0; ii < m_partitionTokens.size(); ii++) { <ide> loadSet.add(new LoadPair(ii, m_partitionTokens.get(ii)));
JavaScript
mit
36bd65e7825ee7ba3f38ca24c08ea31e08e977d8
0
Jean1715/alien_invaders
var AlienFlock = function AlienFlock() { this.invulnrable = true; this.dx = 10; this.dy = 0; this.hit = 1; this.lastHit = 0; this.speed = 10; /* controls speed of enemy attacking and moving*/ this.draw = function() {}; this.die = function() { if(Game.board.nextLevel()) { Game.loadBoard(new GameBoard(Game.board.nextLevel())); } else { Game.callbacks['win'](); } } this.step = function(dt) { if(this.hit && this.hit != this.lastHit) { this.lastHit = this.hit; this.dy = this.speed; } else { this.dy=0; } this.dx = this.speed * this.hit; var max = {}, cnt = 0; this.board.iterate(function() { if(this instanceof Alien) { if(!max[this.x] || this.y > max[this.x]) { max[this.x] = this.y; } cnt++; } }); if(cnt == 0) { this.die(); } this.max_y = max; return true; }; } var Alien = function Alien(opts) { this.flock = opts['flock']; this.frame = 0; this.mx = 0; } /* calls up sprites draw function*/ Alien.prototype.draw = function(canvas) { Sprites.draw(canvas,this.name,this.x,this.y,this.frame); } Alien.prototype.die = function() { GameAudio.play('die'); this.flock.speed += 1; /*Each time an alien dies, this controls how much faster they move*/ this.board.remove(this); } Alien.prototype.step = function(dt) { this.mx += dt * this.flock.dx; this.y += this.flock.dy; if(Math.abs(this.mx) > 5) /*controls how fast the alien frames begin*/ { if(this.y == this.flock.max_y[this.x]) { this.fireSometimes(); } this.x += this.mx; this.mx = 0; this.frame = (this.frame+1) % 2; if(this.x > Game.width - Sprites.map.alien1.w * 2) this.flock.hit = -1; if(this.x < Sprites.map.alien1.w) this.flock.hit = 1; } return true; } Alien.prototype.fireSometimes = function() { if(Math.random()*100 < 10) /*How often aliens fire*/ { this.board.addSprite('missile2',this.x + this.w/2 - Sprites.map.missile2.w/2, this.y + this.h, { dy: 100 }); } } var Player = function Player(opts) { this.reloading = 0; } Player.prototype.draw = function(canvas) { Sprites.draw(canvas,'player',this.x,this.y); } Player.prototype.die = function() { GameAudio.play('die'); Game.callbacks['die'](); } /* this bit is the control of left and right it gets its values from level.js */ Player.prototype.step = function(dt) { if(Game.keys['left']) { this.x -= 500 * dt; } /*controls speedmiss of player moving*/ if(Game.keys['right']) { this.x += 500 * dt; } if(this.x < 0) this.x = 0; if(this.x > Game.width-this.w) this.x = Game.width-this.w; this.reloading--; /*How many missiles to shoot*/ if(Game.keys['fire'] && this.reloading <= 0 && this.board.missiles < 100) { GameAudio.play('fire'); this.board.addSprite('missile', this.x + this.w/2 - Sprites.map.missile.w/2, this.y-this.h, { dy: -100, player: true }); this.board.missiles++; /*lower the number, the faster the reload*/ this.reloading = 5; } return true; } var Missile = function Missile(opts) { this.dy = opts.dy; this.player = opts.player; } Missile.prototype.draw = function(canvas) { Sprites.draw(canvas,'missile',this.x,this.y); } Missile.prototype.step = function(dt) { this.y += this.dy * dt; var enemy = this.board.collide(this); if(enemy) { enemy.die(); return false; } return (this.y < 0 || this.y > Game.height) ? false : true; } Missile.prototype.die = function() { if(this.player) this.board.missiles--; if(this.board.missiles < 0) this.board.missiles=0; this.board.remove(this); } var Missile2 = function Missile2(opts) { this.dy = opts.dy; this.player = opts.player; } Missile2.prototype.draw = function(canvas) { Sprites.draw(canvas,'missile2',this.x,this.y); } Missile2.prototype.step = function(dt) { this.y += this.dy * dt; var enemy = this.board.collide(this); if(enemy) { enemy.die(); return false; } return (this.y < 0 || this.y > Game.height) ? false : true; } Missile2.prototype.die = function() { if(this.player) this.board.missiles--; if(this.board.missiles < 0) this.board.missiles=0; this.board.remove(this); }
js/game.js
var AlienFlock = function AlienFlock() { this.invulnrable = true; this.dx = 10; this.dy = 0; this.hit = 1; this.lastHit = 0; this.speed = 10; /* controls speed of enemy attacking and moving*/ this.draw = function() {}; this.die = function() { if(Game.board.nextLevel()) { Game.loadBoard(new GameBoard(Game.board.nextLevel())); } else { Game.callbacks['win'](); } } this.step = function(dt) { if(this.hit && this.hit != this.lastHit) { this.lastHit = this.hit; this.dy = this.speed; } else { this.dy=0; } this.dx = this.speed * this.hit; var max = {}, cnt = 0; this.board.iterate(function() { if(this instanceof Alien) { if(!max[this.x] || this.y > max[this.x]) { max[this.x] = this.y; } cnt++; } }); if(cnt == 0) { this.die(); } this.max_y = max; return true; }; } var Alien = function Alien(opts) { this.flock = opts['flock']; this.frame = 0; this.mx = 0; } /* calls up sprites draw function*/ Alien.prototype.draw = function(canvas) { Sprites.draw(canvas,this.name,this.x,this.y,this.frame); } Alien.prototype.die = function() { GameAudio.play('die'); this.flock.speed += 1; /*Each time an alien dies, this controls how much faster they move*/ this.board.remove(this); } Alien.prototype.step = function(dt) { this.mx += dt * this.flock.dx; this.y += this.flock.dy; if(Math.abs(this.mx) > 5) /*controls how fast the alien frames begin*/ { if(this.y == this.flock.max_y[this.x]) { this.fireSometimes(); } this.x += this.mx; this.mx = 0; this.frame = (this.frame+1) % 2; if(this.x > Game.width - Sprites.map.alien1.w * 2) this.flock.hit = -1; if(this.x < Sprites.map.alien1.w) this.flock.hit = 1; } return true; } Alien.prototype.fireSometimes = function() { if(Math.random()*100 < 10) /*How often aliens fire*/ { this.board.addSprite('missile',this.x + this.w/2 - Sprites.map.missile.w/2, this.y + this.h, { dy: 100 }); } } var Player = function Player(opts) { this.reloading = 0; } Player.prototype.draw = function(canvas) { Sprites.draw(canvas,'player',this.x,this.y); } Player.prototype.die = function() { GameAudio.play('die'); Game.callbacks['die'](); } /* this bit is the control of left and right it gets its values from level.js */ Player.prototype.step = function(dt) { if(Game.keys['left']) { this.x -= 500 * dt; } /*controls speed of player moving*/ if(Game.keys['right']) { this.x += 500 * dt; } if(this.x < 0) this.x = 0; if(this.x > Game.width-this.w) this.x = Game.width-this.w; this.reloading--; /*How many missiles to shoot*/ if(Game.keys['fire'] && this.reloading <= 0 && this.board.missiles < 100) { GameAudio.play('fire'); this.board.addSprite('missile', this.x + this.w/2 - Sprites.map.missile.w/2, this.y-this.h, { dy: -100, player: true }); this.board.missiles++; /*lower the number, the faster the reload*/ this.reloading = 5; } return true; } var Missile = function Missile(opts) { this.dy = opts.dy; this.player = opts.player; } Missile.prototype.draw = function(canvas) { Sprites.draw(canvas,'missile',this.x,this.y); } Missile.prototype.step = function(dt) { this.y += this.dy * dt; var enemy = this.board.collide(this); if(enemy) { enemy.die(); return false; } return (this.y < 0 || this.y > Game.height) ? false : true; } Missile.prototype.die = function() { if(this.player) this.board.missiles--; if(this.board.missiles < 0) this.board.missiles=0; this.board.remove(this); }
Fixed alien's sprite missile to work
js/game.js
Fixed alien's sprite missile to work
<ide><path>s/game.js <ide> <ide> Alien.prototype.fireSometimes = function() { <ide> if(Math.random()*100 < 10) /*How often aliens fire*/ { <del> this.board.addSprite('missile',this.x + this.w/2 - Sprites.map.missile.w/2, <add> this.board.addSprite('missile2',this.x + this.w/2 - Sprites.map.missile2.w/2, <ide> this.y + this.h, <ide> { dy: 100 }); <ide> } <ide> } <ide> /* this bit is the control of left and right it gets its values from level.js */ <ide> Player.prototype.step = function(dt) { <del> if(Game.keys['left']) { this.x -= 500 * dt; } /*controls speed of player moving*/ <add> if(Game.keys['left']) { this.x -= 500 * dt; } /*controls speedmiss of player moving*/ <ide> if(Game.keys['right']) { this.x += 500 * dt; } <ide> <ide> if(this.x < 0) this.x = 0; <ide> this.board.missiles++; <ide> /*lower the number, the faster the reload*/ <ide> this.reloading = 5; <del> } <add> } <ide> return true; <ide> } <ide> <ide> Missile.prototype.draw = function(canvas) { <ide> Sprites.draw(canvas,'missile',this.x,this.y); <ide> } <add> <ide> <ide> Missile.prototype.step = function(dt) { <ide> this.y += this.dy * dt; <ide> if(this.board.missiles < 0) this.board.missiles=0; <ide> this.board.remove(this); <ide> } <add> <add>var Missile2 = function Missile2(opts) { <add> this.dy = opts.dy; <add> this.player = opts.player; <add>} <add> <add>Missile2.prototype.draw = function(canvas) { <add> Sprites.draw(canvas,'missile2',this.x,this.y); <add>} <add> <add> <add>Missile2.prototype.step = function(dt) { <add> this.y += this.dy * dt; <add> <add> var enemy = this.board.collide(this); <add> if(enemy) { <add> enemy.die(); <add> return false; <add> } <add> return (this.y < 0 || this.y > Game.height) ? false : true; <add>} <add> <add>Missile2.prototype.die = function() { <add> if(this.player) this.board.missiles--; <add> if(this.board.missiles < 0) this.board.missiles=0; <add> this.board.remove(this); <add>}
JavaScript
mit
2a7fd49f5af327c7b034af2ba88c249f3f4030c9
0
scottwernervt/ember-cli-group-by,scottwernervt/ember-cli-group-by
module.exports = { root: true, parserOptions: { ecmaVersion: 2017, sourceType: 'module' }, extends: [ 'eslint:recommended', 'plugin:ember/recommended' ], env: { browser: true }, rules: { 'ember/no-observers': 0 } };
.eslintrc.js
module.exports = { root: true, parserOptions: { ecmaVersion: 2017, sourceType: 'module' }, extends: [ 'eslint:recommended', 'plugin:ember/recommended', ], env: { browser: true }, rules: { 'ember/no-observers': 0, } };
Remove trailing commas
.eslintrc.js
Remove trailing commas
<ide><path>eslintrc.js <ide> }, <ide> extends: [ <ide> 'eslint:recommended', <del> 'plugin:ember/recommended', <add> 'plugin:ember/recommended' <ide> ], <ide> env: { <ide> browser: true <ide> }, <ide> rules: { <del> 'ember/no-observers': 0, <add> 'ember/no-observers': 0 <ide> } <ide> };
Java
apache-2.0
769a08937b1beac1841bea84390ccfba83fab51e
0
srbala/kaptcha,codenon/kaptcha,yojeajie/kaptcha,widenerc/kaptcha,linvar/kaptcha,JRed1989/kaptcha,seastar-ss/kaptcha,dudw/kaptcha,alpapad/kaptcha,hwajdrv/kaptcha,jamespatriot/kaptcha,siamcomm/kaptcha,tx1103mark/kaptcha,derrick-hoh/kaptcha,njucsxj/kaptcha,abcijkxyz/kaptcha,Pankajpatelletsnurture/kaptcha,rockzeng/kaptcha,systembugtj/kaptcha-origrin,passwind/kaptcha,ansys/kaptcha,wy163storm/kaptcha,tanliyuan/kaptcha,jetwong0115/kaptcha,Baozi2/kaptcha,nagyistoce/kaptcha,alongchengtian0/kaptcha,zodiake/kaptcha,hamedcse/kaptcha,fengbaicanhe/kaptcha,clauberf-cit/kaptcha,fatherican/kaptcha,izerui/kaptcha,Sonaldessai/kaptcha,ycaihua/kaptcha,qianye2015/kaptcha,zhoupan/kaptcha,lookfirst/kaptcha,barbolo/kaptcha,konradkg/kaptcha,vohoaiviet/kaptcha,AlineBocucci/kaptcha,ziz0u/kaptcha,junlapong/kaptcha
package com.google.code.kaptcha.text.impl; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.font.FontRenderContext; import java.awt.font.GlyphVector; import java.awt.image.BufferedImage; import java.util.Random; import com.google.code.kaptcha.text.WordRenderer; import com.google.code.kaptcha.util.Configurable; /** * The default implementation of {@link WordRenderer}, creates an image with a * word rendered on it. */ public class DefaultWordRenderer extends Configurable implements WordRenderer { /** * Renders a word to an image. * * @param word * The word to be rendered. * @param width * The width of the image to be created. * @param height * The height of the image to be created. * @return The BufferedImage created from the word. */ public BufferedImage renderWord(String word, int width, int height) { int fontSize = getConfig().getTextProducerFontSize(); Font[] fonts = getConfig().getTextProducerFonts(fontSize); Color color = getConfig().getTextProducerFontColor(); int charSpace = getConfig().getTextProducerCharSpace(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2D = image.createGraphics(); g2D.setColor(color); RenderingHints hints = new RenderingHints( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); hints.add(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY)); g2D.setRenderingHints(hints); FontRenderContext frc = g2D.getFontRenderContext(); Random random = new Random(); int startPosY = (height - fontSize) / 5 + fontSize; char[] wordChars = word.toCharArray(); Font[] chosenFonts = new Font[wordChars.length]; int [] charWidths = new int[wordChars.length]; int widthNeeded = 0; for (int i = 0; i < wordChars.length; i++) { chosenFonts[i] = fonts[random.nextInt(fonts.length)]; char[] charToDraw = new char[]{ wordChars[i] }; GlyphVector gv = chosenFonts[i].createGlyphVector(frc, charToDraw); charWidths[i] = (int)gv.getVisualBounds().getWidth(); if (i > 0) { widthNeeded = widthNeeded + 2; } widthNeeded = widthNeeded + charWidths[i]; } int startPosX = (width - widthNeeded) / 2; for (int i = 0; i < wordChars.length; i++) { g2D.setFont(chosenFonts[i]); char[] charToDraw = new char[] { wordChars[i] }; g2D.drawChars(charToDraw, 0, charToDraw.length, startPosX, startPosY); startPosX = startPosX + (int) charWidths[i] + charSpace; } return image; } }
src/java/com/google/code/kaptcha/text/impl/DefaultWordRenderer.java
package com.google.code.kaptcha.text.impl; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.font.FontRenderContext; import java.awt.font.GlyphVector; import java.awt.image.BufferedImage; import java.util.Random; import com.google.code.kaptcha.text.WordRenderer; import com.google.code.kaptcha.util.Configurable; /** * The default implementation of {@link WordRenderer}, creates an image with a * word rendered on it. */ public class DefaultWordRenderer extends Configurable implements WordRenderer { /** * Renders a word to an image. * * @param word * The word to be rendered. * @param width * The width of the image to be created. * @param height * The height of the image to be created. * @return The BufferedImage created from the word. */ public BufferedImage renderWord(String word, int width, int height) { int fontSize = getConfig().getTextProducerFontSize(); Font[] fonts = getConfig().getTextProducerFonts(fontSize); Color color = getConfig().getTextProducerFontColor(); int charSpace = getConfig().getTextProducerCharSpace(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2D = image.createGraphics(); g2D.setColor(color); RenderingHints hints = new RenderingHints( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); hints.add(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY)); g2D.setRenderingHints(hints); FontRenderContext frc = g2D.getFontRenderContext(); Random random = new Random(); int startPosX = width / (2 + word.length()); int startPosY = (height - fontSize) / 5 + fontSize; char[] wordChars = word.toCharArray(); for (int i = 0; i < wordChars.length; i++) { Font chosenFont = fonts[random.nextInt(fonts.length)]; g2D.setFont(chosenFont); char[] charToDraw = new char[]{ wordChars[i] }; GlyphVector gv = chosenFont.createGlyphVector(frc, charToDraw); double charWidth = gv.getVisualBounds().getWidth(); g2D.drawChars(charToDraw, 0, charToDraw.length, startPosX, startPosY); startPosX = startPosX + (int) charWidth + charSpace; } return image; } }
fixes issue #56 suggested patch : slightly better centering on DefaultWordRenderer.java
src/java/com/google/code/kaptcha/text/impl/DefaultWordRenderer.java
fixes issue #56
<ide><path>rc/java/com/google/code/kaptcha/text/impl/DefaultWordRenderer.java <ide> FontRenderContext frc = g2D.getFontRenderContext(); <ide> Random random = new Random(); <ide> <del> int startPosX = width / (2 + word.length()); <ide> int startPosY = (height - fontSize) / 5 + fontSize; <ide> <ide> char[] wordChars = word.toCharArray(); <add> Font[] chosenFonts = new Font[wordChars.length]; <add> int [] charWidths = new int[wordChars.length]; <add> int widthNeeded = 0; <ide> for (int i = 0; i < wordChars.length; i++) <ide> { <del> Font chosenFont = fonts[random.nextInt(fonts.length)]; <del> g2D.setFont(chosenFont); <add> chosenFonts[i] = fonts[random.nextInt(fonts.length)]; <ide> <ide> char[] charToDraw = new char[]{ <ide> wordChars[i] <ide> }; <del> GlyphVector gv = chosenFont.createGlyphVector(frc, charToDraw); <del> double charWidth = gv.getVisualBounds().getWidth(); <del> <add> GlyphVector gv = chosenFonts[i].createGlyphVector(frc, charToDraw); <add> charWidths[i] = (int)gv.getVisualBounds().getWidth(); <add> if (i > 0) <add> { <add> widthNeeded = widthNeeded + 2; <add> } <add> widthNeeded = widthNeeded + charWidths[i]; <add> } <add> <add> int startPosX = (width - widthNeeded) / 2; <add> for (int i = 0; i < wordChars.length; i++) <add> { <add> g2D.setFont(chosenFonts[i]); <add> char[] charToDraw = new char[] { <add> wordChars[i] <add> }; <ide> g2D.drawChars(charToDraw, 0, charToDraw.length, startPosX, startPosY); <del> startPosX = startPosX + (int) charWidth + charSpace; <add> startPosX = startPosX + (int) charWidths[i] + charSpace; <ide> } <ide> <ide> return image;
JavaScript
epl-1.0
50297f6efebd6a6038bfa367575c745e40a45352
0
git497/pdf-pin,git497/pdf-pin
!function t(e,r){"object"==typeof exports&&"object"==typeof module?module.exports=r():"function"==typeof define&&define.amd?define("bundle",[],r):"object"==typeof exports?exports.bundle=r():e.bundle=r()}(this,function(){return function(t){function e(r){if(i[r])return i[r].exports;var n=i[r]={i:r,l:!1,exports:{}};return t[r].call(n.exports,n,n.exports,e),n.l=!0,n.exports}var r=window.webpackJsonpbundle;window.webpackJsonpbundle=function e(i,o,a){for(var s,c,l=0,h=[],u;l<i.length;l++)c=i[l],n[c]&&h.push(n[c][0]),n[c]=0;for(s in o)Object.prototype.hasOwnProperty.call(o,s)&&(t[s]=o[s]);for(r&&r(i,o,a);h.length;)h.shift()()};var i={},n={1:0};return e.e=function t(r){function i(){c.onerror=c.onload=null,clearTimeout(l);var t=n[r];0!==t&&(t&&t[1](new Error("Loading chunk "+r+" failed.")),n[r]=void 0)}var o=n[r];if(0===o)return new Promise(function(t){t()});if(o)return o[2];var a=new Promise(function(t,e){o=n[r]=[t,e]});o[2]=a;var s=document.getElementsByTagName("head")[0],c=document.createElement("script");c.type="text/javascript",c.charset="utf-8",c.async=!0,c.timeout=12e4,e.nc&&c.setAttribute("nonce",e.nc),c.src=e.p+""+r+".bundle.min.js";var l=setTimeout(i,12e4);return c.onerror=c.onload=i,s.appendChild(c),a},e.m=t,e.c=i,e.d=function(t,r,i){e.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var r=t&&t.__esModule?function e(){return t.default}:function e(){return t};return e.d(r,"a",r),r},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e.oe=function(t){throw console.error(t),t},e(e.s=29)}([function(t,e){var r;r=function(){return this}();try{r=r||Function("return this")()||(0,eval)("this")}catch(t){"object"==typeof window&&(r=window)}t.exports=r},function(t,e){function r(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}function n(t){if(u===setTimeout)return setTimeout(t,0);if((u===r||!u)&&setTimeout)return u=setTimeout,setTimeout(t,0);try{return u(t,0)}catch(e){try{return u.call(null,t,0)}catch(e){return u.call(this,t,0)}}}function o(t){if(f===clearTimeout)return clearTimeout(t);if((f===i||!f)&&clearTimeout)return f=clearTimeout,clearTimeout(t);try{return f(t)}catch(e){try{return f.call(null,t)}catch(e){return f.call(this,t)}}}function a(){p&&g&&(p=!1,g.length?d=g.concat(d):v=-1,d.length&&s())}function s(){if(!p){var t=n(a);p=!0;for(var e=d.length;e;){for(g=d,d=[];++v<e;)g&&g[v].run();v=-1,e=d.length}g=null,p=!1,o(t)}}function c(t,e){this.fun=t,this.array=e}function l(){}var h=t.exports={},u,f;!function(){try{u="function"==typeof setTimeout?setTimeout:r}catch(t){u=r}try{f="function"==typeof clearTimeout?clearTimeout:i}catch(t){f=i}}();var d=[],p=!1,g,v=-1;h.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)e[r-1]=arguments[r];d.push(new c(t,e)),1!==d.length||p||n(s)},c.prototype.run=function(){this.fun.apply(null,this.array)},h.title="browser",h.browser=!0,h.env={},h.argv=[],h.version="",h.versions={},h.on=l,h.addListener=l,h.once=l,h.off=l,h.removeListener=l,h.removeAllListeners=l,h.emit=l,h.prependListener=l,h.prependOnceListener=l,h.listeners=function(t){return[]},h.binding=function(t){throw new Error("process.binding is not supported")},h.cwd=function(){return"/"},h.chdir=function(t){throw new Error("process.chdir is not supported")},h.umask=function(){return 0}},function(t,e,r){"use strict";(function(t){function i(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===t.foo()&&"function"==typeof t.subarray&&0===t.subarray(1,1).byteLength}catch(t){return!1}}function n(){return a.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function o(t,e){if(n()<e)throw new RangeError("Invalid typed array length");return a.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e),t.__proto__=a.prototype):(null===t&&(t=new a(e)),t.length=e),t}function a(t,e,r){if(!(a.TYPED_ARRAY_SUPPORT||this instanceof a))return new a(t,e,r);if("number"==typeof t){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a string");return h(this,t)}return s(this,t,e,r)}function s(t,e,r,i){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer?d(t,e,r,i):"string"==typeof e?u(t,e,r):p(t,e)}function c(t){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative')}function l(t,e,r,i){return c(e),e<=0?o(t,e):void 0!==r?"string"==typeof i?o(t,e).fill(r,i):o(t,e).fill(r):o(t,e)}function h(t,e){if(c(e),t=o(t,e<0?0:0|g(e)),!a.TYPED_ARRAY_SUPPORT)for(var r=0;r<e;++r)t[r]=0;return t}function u(t,e,r){if("string"==typeof r&&""!==r||(r="utf8"),!a.isEncoding(r))throw new TypeError('"encoding" must be a valid string encoding');var i=0|m(e,r);t=o(t,i);var n=t.write(e,r);return n!==i&&(t=t.slice(0,n)),t}function f(t,e){var r=e.length<0?0:0|g(e.length);t=o(t,r);for(var i=0;i<r;i+=1)t[i]=255&e[i];return t}function d(t,e,r,i){if(e.byteLength,r<0||e.byteLength<r)throw new RangeError("'offset' is out of bounds");if(e.byteLength<r+(i||0))throw new RangeError("'length' is out of bounds");return e=void 0===r&&void 0===i?new Uint8Array(e):void 0===i?new Uint8Array(e,r):new Uint8Array(e,r,i),a.TYPED_ARRAY_SUPPORT?(t=e,t.__proto__=a.prototype):t=f(t,e),t}function p(t,e){if(a.isBuffer(e)){var r=0|g(e.length);return t=o(t,r),0===t.length?t:(e.copy(t,0,0,r),t)}if(e){if("undefined"!=typeof ArrayBuffer&&e.buffer instanceof ArrayBuffer||"length"in e)return"number"!=typeof e.length||J(e.length)?o(t,0):f(t,e);if("Buffer"===e.type&&$(e.data))return f(t,e.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function g(t){if(t>=n())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+n().toString(16)+" bytes");return 0|t}function v(t){return+t!=t&&(t=0),a.alloc(+t)}function m(t,e){if(a.isBuffer(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var i=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return G(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return V(t).length;default:if(i)return G(t).length;e=(""+e).toLowerCase(),i=!0}}function b(t,e,r){var i=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if(r>>>=0,e>>>=0,r<=e)return"";for(t||(t="utf8");;)switch(t){case"hex":return D(this,e,r);case"utf8":case"utf-8":return E(this,e,r);case"ascii":return R(this,e,r);case"latin1":case"binary":return L(this,e,r);case"base64":return P(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,e,r);default:if(i)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),i=!0}}function y(t,e,r){var i=t[e];t[e]=t[r],t[r]=i}function _(t,e,r,i,n){if(0===t.length)return-1;if("string"==typeof r?(i=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=n?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(n)return-1;r=t.length-1}else if(r<0){if(!n)return-1;r=0}if("string"==typeof e&&(e=a.from(e,i)),a.isBuffer(e))return 0===e.length?-1:w(t,e,r,i,n);if("number"==typeof e)return e&=255,a.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?n?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):w(t,[e],r,i,n);throw new TypeError("val must be string, number or Buffer")}function w(t,e,r,i,n){function o(t,e){return 1===a?t[e]:t.readUInt16BE(e*a)}var a=1,s=t.length,c=e.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(t.length<2||e.length<2)return-1;a=2,s/=2,c/=2,r/=2}var l;if(n){var h=-1;for(l=r;l<s;l++)if(o(t,l)===o(e,-1===h?0:l-h)){if(-1===h&&(h=l),l-h+1===c)return h*a}else-1!==h&&(l-=l-h),h=-1}else for(r+c>s&&(r=s-c),l=r;l>=0;l--){for(var u=!0,f=0;f<c;f++)if(o(t,l+f)!==o(e,f)){u=!1;break}if(u)return l}return-1}function S(t,e,r,i){r=Number(r)||0;var n=t.length-r;i?(i=Number(i))>n&&(i=n):i=n;var o=e.length;if(o%2!=0)throw new TypeError("Invalid hex string");i>o/2&&(i=o/2);for(var a=0;a<i;++a){var s=parseInt(e.substr(2*a,2),16);if(isNaN(s))return a;t[r+a]=s}return a}function x(t,e,r,i){return Z(G(e,t.length-r),t,r,i)}function C(t,e,r,i){return Z(H(e),t,r,i)}function A(t,e,r,i){return C(t,e,r,i)}function T(t,e,r,i){return Z(V(e),t,r,i)}function k(t,e,r,i){return Z(Y(e,t.length-r),t,r,i)}function P(t,e,r){return 0===e&&r===t.length?K.fromByteArray(t):K.fromByteArray(t.slice(e,r))}function E(t,e,r){r=Math.min(t.length,r);for(var i=[],n=e;n<r;){var o=t[n],a=null,s=o>239?4:o>223?3:o>191?2:1;if(n+s<=r){var c,l,h,u;switch(s){case 1:o<128&&(a=o);break;case 2:c=t[n+1],128==(192&c)&&(u=(31&o)<<6|63&c)>127&&(a=u);break;case 3:c=t[n+1],l=t[n+2],128==(192&c)&&128==(192&l)&&(u=(15&o)<<12|(63&c)<<6|63&l)>2047&&(u<55296||u>57343)&&(a=u);break;case 4:c=t[n+1],l=t[n+2],h=t[n+3],128==(192&c)&&128==(192&l)&&128==(192&h)&&(u=(15&o)<<18|(63&c)<<12|(63&l)<<6|63&h)>65535&&u<1114112&&(a=u)}}null===a?(a=65533,s=1):a>65535&&(a-=65536,i.push(a>>>10&1023|55296),a=56320|1023&a),i.push(a),n+=s}return O(i)}function O(t){var e=t.length;if(e<=tt)return String.fromCharCode.apply(String,t);for(var r="",i=0;i<e;)r+=String.fromCharCode.apply(String,t.slice(i,i+=tt));return r}function R(t,e,r){var i="";r=Math.min(t.length,r);for(var n=e;n<r;++n)i+=String.fromCharCode(127&t[n]);return i}function L(t,e,r){var i="";r=Math.min(t.length,r);for(var n=e;n<r;++n)i+=String.fromCharCode(t[n]);return i}function D(t,e,r){var i=t.length;(!e||e<0)&&(e=0),(!r||r<0||r>i)&&(r=i);for(var n="",o=e;o<r;++o)n+=X(t[o]);return n}function I(t,e,r){for(var i=t.slice(e,r),n="",o=0;o<i.length;o+=2)n+=String.fromCharCode(i[o]+256*i[o+1]);return n}function j(t,e,r){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}function M(t,e,r,i,n,o){if(!a.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>n||e<o)throw new RangeError('"value" argument is out of bounds');if(r+i>t.length)throw new RangeError("Index out of range")}function F(t,e,r,i){e<0&&(e=65535+e+1);for(var n=0,o=Math.min(t.length-r,2);n<o;++n)t[r+n]=(e&255<<8*(i?n:1-n))>>>8*(i?n:1-n)}function N(t,e,r,i){e<0&&(e=4294967295+e+1);for(var n=0,o=Math.min(t.length-r,4);n<o;++n)t[r+n]=e>>>8*(i?n:3-n)&255}function B(t,e,r,i,n,o){if(r+i>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function U(t,e,r,i,n){return n||B(t,e,r,4,3.4028234663852886e38,-3.4028234663852886e38),Q.write(t,e,r,i,23,4),r+4}function z(t,e,r,i,n){return n||B(t,e,r,8,1.7976931348623157e308,-1.7976931348623157e308),Q.write(t,e,r,i,52,8),r+8}function W(t){if(t=q(t).replace(et,""),t.length<2)return"";for(;t.length%4!=0;)t+="=";return t}function q(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function X(t){return t<16?"0"+t.toString(16):t.toString(16)}function G(t,e){e=e||1/0;for(var r,i=t.length,n=null,o=[],a=0;a<i;++a){if((r=t.charCodeAt(a))>55295&&r<57344){if(!n){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(a+1===i){(e-=3)>-1&&o.push(239,191,189);continue}n=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),n=r;continue}r=65536+(n-55296<<10|r-56320)}else n&&(e-=3)>-1&&o.push(239,191,189);if(n=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function H(t){for(var e=[],r=0;r<t.length;++r)e.push(255&t.charCodeAt(r));return e}function Y(t,e){for(var r,i,n,o=[],a=0;a<t.length&&!((e-=2)<0);++a)r=t.charCodeAt(a),i=r>>8,n=r%256,o.push(n),o.push(i);return o}function V(t){return K.toByteArray(W(t))}function Z(t,e,r,i){for(var n=0;n<i&&!(n+r>=e.length||n>=t.length);++n)e[n+r]=t[n];return n}function J(t){return t!==t}/*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <[email protected]> <http://feross.org> * @license MIT */ var K=r(40),Q=r(41),$=r(13);e.Buffer=a,e.SlowBuffer=v,e.INSPECT_MAX_BYTES=50,a.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:i(),e.kMaxLength=n(),a.poolSize=8192,a._augment=function(t){return t.__proto__=a.prototype,t},a.from=function(t,e,r){return s(null,t,e,r)},a.TYPED_ARRAY_SUPPORT&&(a.prototype.__proto__=Uint8Array.prototype,a.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&a[Symbol.species]===a&&Object.defineProperty(a,Symbol.species,{value:null,configurable:!0})),a.alloc=function(t,e,r){return l(null,t,e,r)},a.allocUnsafe=function(t){return h(null,t)},a.allocUnsafeSlow=function(t){return h(null,t)},a.isBuffer=function t(e){return!(null==e||!e._isBuffer)},a.compare=function t(e,r){if(!a.isBuffer(e)||!a.isBuffer(r))throw new TypeError("Arguments must be Buffers");if(e===r)return 0;for(var i=e.length,n=r.length,o=0,s=Math.min(i,n);o<s;++o)if(e[o]!==r[o]){i=e[o],n=r[o];break}return i<n?-1:n<i?1:0},a.isEncoding=function t(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function t(e,r){if(!$(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return a.alloc(0);var i;if(void 0===r)for(r=0,i=0;i<e.length;++i)r+=e[i].length;var n=a.allocUnsafe(r),o=0;for(i=0;i<e.length;++i){var s=e[i];if(!a.isBuffer(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(n,o),o+=s.length}return n},a.byteLength=m,a.prototype._isBuffer=!0,a.prototype.swap16=function t(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var r=0;r<e;r+=2)y(this,r,r+1);return this},a.prototype.swap32=function t(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var r=0;r<e;r+=4)y(this,r,r+3),y(this,r+1,r+2);return this},a.prototype.swap64=function t(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var r=0;r<e;r+=8)y(this,r,r+7),y(this,r+1,r+6),y(this,r+2,r+5),y(this,r+3,r+4);return this},a.prototype.toString=function t(){var e=0|this.length;return 0===e?"":0===arguments.length?E(this,0,e):b.apply(this,arguments)},a.prototype.equals=function t(e){if(!a.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===a.compare(this,e)},a.prototype.inspect=function t(){var r="",i=e.INSPECT_MAX_BYTES;return this.length>0&&(r=this.toString("hex",0,i).match(/.{2}/g).join(" "),this.length>i&&(r+=" ... ")),"<Buffer "+r+">"},a.prototype.compare=function t(e,r,i,n,o){if(!a.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===r&&(r=0),void 0===i&&(i=e?e.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),r<0||i>e.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&r>=i)return 0;if(n>=o)return-1;if(r>=i)return 1;if(r>>>=0,i>>>=0,n>>>=0,o>>>=0,this===e)return 0;for(var s=o-n,c=i-r,l=Math.min(s,c),h=this.slice(n,o),u=e.slice(r,i),f=0;f<l;++f)if(h[f]!==u[f]){s=h[f],c=u[f];break}return s<c?-1:c<s?1:0},a.prototype.includes=function t(e,r,i){return-1!==this.indexOf(e,r,i)},a.prototype.indexOf=function t(e,r,i){return _(this,e,r,i,!0)},a.prototype.lastIndexOf=function t(e,r,i){return _(this,e,r,i,!1)},a.prototype.write=function t(e,r,i,n){if(void 0===r)n="utf8",i=this.length,r=0;else if(void 0===i&&"string"==typeof r)n=r,i=this.length,r=0;else{if(!isFinite(r))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");r|=0,isFinite(i)?(i|=0,void 0===n&&(n="utf8")):(n=i,i=void 0)}var o=this.length-r;if((void 0===i||i>o)&&(i=o),e.length>0&&(i<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var a=!1;;)switch(n){case"hex":return S(this,e,r,i);case"utf8":case"utf-8":return x(this,e,r,i);case"ascii":return C(this,e,r,i);case"latin1":case"binary":return A(this,e,r,i);case"base64":return T(this,e,r,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,e,r,i);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},a.prototype.toJSON=function t(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var tt=4096;a.prototype.slice=function t(e,r){var i=this.length;e=~~e,r=void 0===r?i:~~r,e<0?(e+=i)<0&&(e=0):e>i&&(e=i),r<0?(r+=i)<0&&(r=0):r>i&&(r=i),r<e&&(r=e);var n;if(a.TYPED_ARRAY_SUPPORT)n=this.subarray(e,r),n.__proto__=a.prototype;else{var o=r-e;n=new a(o,void 0);for(var s=0;s<o;++s)n[s]=this[s+e]}return n},a.prototype.readUIntLE=function t(e,r,i){e|=0,r|=0,i||j(e,r,this.length);for(var n=this[e],o=1,a=0;++a<r&&(o*=256);)n+=this[e+a]*o;return n},a.prototype.readUIntBE=function t(e,r,i){e|=0,r|=0,i||j(e,r,this.length);for(var n=this[e+--r],o=1;r>0&&(o*=256);)n+=this[e+--r]*o;return n},a.prototype.readUInt8=function t(e,r){return r||j(e,1,this.length),this[e]},a.prototype.readUInt16LE=function t(e,r){return r||j(e,2,this.length),this[e]|this[e+1]<<8},a.prototype.readUInt16BE=function t(e,r){return r||j(e,2,this.length),this[e]<<8|this[e+1]},a.prototype.readUInt32LE=function t(e,r){return r||j(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},a.prototype.readUInt32BE=function t(e,r){return r||j(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},a.prototype.readIntLE=function t(e,r,i){e|=0,r|=0,i||j(e,r,this.length);for(var n=this[e],o=1,a=0;++a<r&&(o*=256);)n+=this[e+a]*o;return o*=128,n>=o&&(n-=Math.pow(2,8*r)),n},a.prototype.readIntBE=function t(e,r,i){e|=0,r|=0,i||j(e,r,this.length);for(var n=r,o=1,a=this[e+--n];n>0&&(o*=256);)a+=this[e+--n]*o;return o*=128,a>=o&&(a-=Math.pow(2,8*r)),a},a.prototype.readInt8=function t(e,r){return r||j(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},a.prototype.readInt16LE=function t(e,r){r||j(e,2,this.length);var i=this[e]|this[e+1]<<8;return 32768&i?4294901760|i:i},a.prototype.readInt16BE=function t(e,r){r||j(e,2,this.length);var i=this[e+1]|this[e]<<8;return 32768&i?4294901760|i:i},a.prototype.readInt32LE=function t(e,r){return r||j(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},a.prototype.readInt32BE=function t(e,r){return r||j(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},a.prototype.readFloatLE=function t(e,r){return r||j(e,4,this.length),Q.read(this,e,!0,23,4)},a.prototype.readFloatBE=function t(e,r){return r||j(e,4,this.length),Q.read(this,e,!1,23,4)},a.prototype.readDoubleLE=function t(e,r){return r||j(e,8,this.length),Q.read(this,e,!0,52,8)},a.prototype.readDoubleBE=function t(e,r){return r||j(e,8,this.length),Q.read(this,e,!1,52,8)},a.prototype.writeUIntLE=function t(e,r,i,n){if(e=+e,r|=0,i|=0,!n){M(this,e,r,i,Math.pow(2,8*i)-1,0)}var o=1,a=0;for(this[r]=255&e;++a<i&&(o*=256);)this[r+a]=e/o&255;return r+i},a.prototype.writeUIntBE=function t(e,r,i,n){if(e=+e,r|=0,i|=0,!n){M(this,e,r,i,Math.pow(2,8*i)-1,0)}var o=i-1,a=1;for(this[r+o]=255&e;--o>=0&&(a*=256);)this[r+o]=e/a&255;return r+i},a.prototype.writeUInt8=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,1,255,0),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[r]=255&e,r+1},a.prototype.writeUInt16LE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[r]=255&e,this[r+1]=e>>>8):F(this,e,r,!0),r+2},a.prototype.writeUInt16BE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[r]=e>>>8,this[r+1]=255&e):F(this,e,r,!1),r+2},a.prototype.writeUInt32LE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=255&e):N(this,e,r,!0),r+4},a.prototype.writeUInt32BE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=255&e):N(this,e,r,!1),r+4},a.prototype.writeIntLE=function t(e,r,i,n){if(e=+e,r|=0,!n){var o=Math.pow(2,8*i-1);M(this,e,r,i,o-1,-o)}var a=0,s=1,c=0;for(this[r]=255&e;++a<i&&(s*=256);)e<0&&0===c&&0!==this[r+a-1]&&(c=1),this[r+a]=(e/s>>0)-c&255;return r+i},a.prototype.writeIntBE=function t(e,r,i,n){if(e=+e,r|=0,!n){var o=Math.pow(2,8*i-1);M(this,e,r,i,o-1,-o)}var a=i-1,s=1,c=0;for(this[r+a]=255&e;--a>=0&&(s*=256);)e<0&&0===c&&0!==this[r+a+1]&&(c=1),this[r+a]=(e/s>>0)-c&255;return r+i},a.prototype.writeInt8=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,1,127,-128),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[r]=255&e,r+1},a.prototype.writeInt16LE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[r]=255&e,this[r+1]=e>>>8):F(this,e,r,!0),r+2},a.prototype.writeInt16BE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[r]=e>>>8,this[r+1]=255&e):F(this,e,r,!1),r+2},a.prototype.writeInt32LE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,4,2147483647,-2147483648),a.TYPED_ARRAY_SUPPORT?(this[r]=255&e,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24):N(this,e,r,!0),r+4},a.prototype.writeInt32BE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),a.TYPED_ARRAY_SUPPORT?(this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=255&e):N(this,e,r,!1),r+4},a.prototype.writeFloatLE=function t(e,r,i){return U(this,e,r,!0,i)},a.prototype.writeFloatBE=function t(e,r,i){return U(this,e,r,!1,i)},a.prototype.writeDoubleLE=function t(e,r,i){return z(this,e,r,!0,i)},a.prototype.writeDoubleBE=function t(e,r,i){return z(this,e,r,!1,i)},a.prototype.copy=function t(e,r,i,n){if(i||(i=0),n||0===n||(n=this.length),r>=e.length&&(r=e.length),r||(r=0),n>0&&n<i&&(n=i),n===i)return 0;if(0===e.length||0===this.length)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(i<0||i>=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-r<n-i&&(n=e.length-r+i);var o=n-i,s;if(this===e&&i<r&&r<n)for(s=o-1;s>=0;--s)e[s+r]=this[s+i];else if(o<1e3||!a.TYPED_ARRAY_SUPPORT)for(s=0;s<o;++s)e[s+r]=this[s+i];else Uint8Array.prototype.set.call(e,this.subarray(i,i+o),r);return o},a.prototype.fill=function t(e,r,i,n){if("string"==typeof e){if("string"==typeof r?(n=r,r=0,i=this.length):"string"==typeof i&&(n=i,i=this.length),1===e.length){var o=e.charCodeAt(0);o<256&&(e=o)}if(void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!a.isEncoding(n))throw new TypeError("Unknown encoding: "+n)}else"number"==typeof e&&(e&=255);if(r<0||this.length<r||this.length<i)throw new RangeError("Out of range index");if(i<=r)return this;r>>>=0,i=void 0===i?this.length:i>>>0,e||(e=0);var s;if("number"==typeof e)for(s=r;s<i;++s)this[s]=e;else{var c=a.isBuffer(e)?e:G(new a(e,n).toString()),l=c.length;for(s=0;s<i-r;++s)this[s+r]=c[s%l]}return this};var et=/[^+\/0-9A-Za-z-_]/g}).call(e,r(0))},function(t,e){"function"==typeof Object.create?t.exports=function t(e,r){e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function t(e,r){e.super_=r;var i=function(){};i.prototype=r.prototype,e.prototype=new i,e.prototype.constructor=e}},function(t,e,r){"use strict";function i(t){if(!(this instanceof i))return new i(t);h.call(this,t),u.call(this,t),t&&!1===t.readable&&(this.readable=!1),t&&!1===t.writable&&(this.writable=!1),this.allowHalfOpen=!0,t&&!1===t.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",n)}function n(){this.allowHalfOpen||this._writableState.ended||s(o,this)}function o(t){t.end()}function a(t,e){for(var r=0,i=t.length;r<i;r++)e(t[r],r)}var s=r(7),c=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e};t.exports=i;var l=r(5);l.inherits=r(3);var h=r(14),u=r(18);l.inherits(i,h);for(var f=c(u.prototype),d=0;d<f.length;d++){var p=f[d];i.prototype[p]||(i.prototype[p]=u.prototype[p])}Object.defineProperty(i.prototype,"destroyed",{get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed&&this._writableState.destroyed)},set:function(t){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=t,this._writableState.destroyed=t)}}),i.prototype._destroy=function(t,e){this.push(null),this.end(),s(e,t)}},function(t,e,r){(function(t){function r(t){return Array.isArray?Array.isArray(t):"[object Array]"===v(t)}function i(t){return"boolean"==typeof t}function n(t){return null===t}function o(t){return null==t}function a(t){return"number"==typeof t}function s(t){return"string"==typeof t}function c(t){return"symbol"==typeof t}function l(t){return void 0===t}function h(t){return"[object RegExp]"===v(t)}function u(t){return"object"==typeof t&&null!==t}function f(t){return"[object Date]"===v(t)}function d(t){return"[object Error]"===v(t)||t instanceof Error}function p(t){return"function"==typeof t}function g(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t}function v(t){return Object.prototype.toString.call(t)}e.isArray=r,e.isBoolean=i,e.isNull=n,e.isNullOrUndefined=o,e.isNumber=a,e.isString=s,e.isSymbol=c,e.isUndefined=l,e.isRegExp=h,e.isObject=u,e.isDate=f,e.isError=d,e.isFunction=p,e.isPrimitive=g,e.isBuffer=t.isBuffer}).call(e,r(2).Buffer)},function(t,e,r){"use strict";function i(){p=!1}function n(t){if(!t)return void(f!==u&&(f=u,i()));if(t!==f){if(t.length!==u.length)throw new Error("Custom alphabet for shortid must be "+u.length+" unique characters. You submitted "+t.length+" characters: "+t);var e=t.split("").filter(function(t,e,r){return e!==r.lastIndexOf(t)});if(e.length)throw new Error("Custom alphabet for shortid must be "+u.length+" unique characters. These characters were not unique: "+e.join(", "));f=t,i()}}function o(t){return n(t),f}function a(t){h.seed(t),d!==t&&(i(),d=t)}function s(){f||n(u);for(var t=f.split(""),e=[],r=h.nextValue(),i;t.length>0;)r=h.nextValue(),i=Math.floor(r*t.length),e.push(t.splice(i,1)[0]);return e.join("")}function c(){return p||(p=s())}function l(t){return c()[t]}var h=r(32),u="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-",f,d,p;t.exports={characters:o,seed:a,lookup:l,shuffled:c}},function(t,e,r){"use strict";(function(e){function r(t,r,i,n){if("function"!=typeof t)throw new TypeError('"callback" argument must be a function');var o=arguments.length,a,s;switch(o){case 0:case 1:return e.nextTick(t);case 2:return e.nextTick(function e(){t.call(null,r)});case 3:return e.nextTick(function e(){t.call(null,r,i)});case 4:return e.nextTick(function e(){t.call(null,r,i,n)});default:for(a=new Array(o-1),s=0;s<a.length;)a[s++]=arguments[s];return e.nextTick(function e(){t.apply(null,a)})}}!e.version||0===e.version.indexOf("v0.")||0===e.version.indexOf("v1.")&&0!==e.version.indexOf("v1.8.")?t.exports=r:t.exports=e.nextTick}).call(e,r(1))},function(t,e,r){"use strict";var i="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;e.assign=function(t){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var r=e.shift();if(r){if("object"!=typeof r)throw new TypeError(r+"must be non-object");for(var i in r)r.hasOwnProperty(i)&&(t[i]=r[i])}}return t},e.shrinkBuf=function(t,e){return t.length===e?t:t.subarray?t.subarray(0,e):(t.length=e,t)};var n={arraySet:function(t,e,r,i,n){if(e.subarray&&t.subarray)return void t.set(e.subarray(r,r+i),n);for(var o=0;o<i;o++)t[n+o]=e[r+o]},flattenChunks:function(t){var e,r,i,n,o,a;for(i=0,e=0,r=t.length;e<r;e++)i+=t[e].length;for(a=new Uint8Array(i),n=0,e=0,r=t.length;e<r;e++)o=t[e],a.set(o,n),n+=o.length;return a}},o={arraySet:function(t,e,r,i,n){for(var o=0;o<i;o++)t[n+o]=e[r+o]},flattenChunks:function(t){return[].concat.apply([],t)}};e.setTyped=function(t){t?(e.Buf8=Uint8Array,e.Buf16=Uint16Array,e.Buf32=Int32Array,e.assign(e,n)):(e.Buf8=Array,e.Buf16=Array,e.Buf32=Array,e.assign(e,o))},e.setTyped(i)},function(t,e,r){e=t.exports=r(14),e.Stream=e,e.Readable=e,e.Writable=r(18),e.Duplex=r(4),e.Transform=r(20),e.PassThrough=r(49)},function(t,e,r){function i(t,e){for(var r in t)e[r]=t[r]}function n(t,e,r){return a(t,e,r)}var o=r(2),a=o.Buffer;a.from&&a.alloc&&a.allocUnsafe&&a.allocUnsafeSlow?t.exports=o:(i(o,e),e.Buffer=n),i(a,n),n.from=function(t,e,r){if("number"==typeof t)throw new TypeError("Argument must not be a number");return a(t,e,r)},n.alloc=function(t,e,r){if("number"!=typeof t)throw new TypeError("Argument must be a number");var i=a(t);return void 0!==e?"string"==typeof r?i.fill(e,r):i.fill(e):i.fill(0),i},n.allocUnsafe=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return a(t)},n.allocUnsafeSlow=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return o.SlowBuffer(t)}},function(t,e,r){"use strict";function i(t,e){for(var r=0,i,o="";!i;)o+=t(e>>4*r&15|n()),i=e<Math.pow(16,r+1),r++;return o}var n=r(33);t.exports=i},function(t,e,r){(function(e,i,n){!function e(r,i){t.exports=i()}(this,function(){return function(t){function e(i){if(r[i])return r[i].exports;var n=r[i]={i:i,l:!1,exports:{}};return t[i].call(n.exports,n,n.exports,e),n.l=!0,n.exports}var r={};return e.m=t,e.c=r,e.i=function(t){return t},e.d=function(t,r,i){e.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var r=t&&t.__esModule?function e(){return t.default}:function e(){return t};return e.d(r,"a",r),r},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=13)}([function(t,r,n){"use strict";function o(t){lt=t}function a(){return lt}function s(t){lt>=at.infos&&console.log("Info: "+t)}function c(t){lt>=at.warnings&&console.log("Warning: "+t)}function l(t){console.log("Deprecated API usage: "+t)}function h(t){throw new Error(t)}function u(t,e){t||h(e)}function f(t,e){try{var r=new URL(t);if(!r.origin||"null"===r.origin)return!1}catch(t){return!1}var i=new URL(e,r);return r.origin===i.origin}function d(t){if(!t)return!1;switch(t.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function p(t,e){if(!t)return null;try{var r=e?new URL(t,e):new URL(t);if(d(r))return r}catch(t){}return null}function g(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!1}),r}function v(t){var e;return function(){return t&&(e=Object.create(null),t(e),t=null),e}}function m(t){return"string"!=typeof t?(c("The argument for removeNullCharacters must be a string."),t):t.replace(wt,"")}function b(t){u(null!==t&&"object"===(void 0===t?"undefined":Y(t))&&void 0!==t.length,"Invalid argument for bytesToString");var e=t.length,r=8192;if(e<8192)return String.fromCharCode.apply(null,t);for(var i=[],n=0;n<e;n+=8192){var o=Math.min(n+8192,e),a=t.subarray(n,o);i.push(String.fromCharCode.apply(null,a))}return i.join("")}function y(t){u("string"==typeof t,"Invalid argument for stringToBytes");for(var e=t.length,r=new Uint8Array(e),i=0;i<e;++i)r[i]=255&t.charCodeAt(i);return r}function _(t){return void 0!==t.length?t.length:(u(void 0!==t.byteLength),t.byteLength)}function w(t){if(1===t.length&&t[0]instanceof Uint8Array)return t[0];var e=0,r,i=t.length,n,o;for(r=0;r<i;r++)n=t[r],o=_(n),e+=o;var a=0,s=new Uint8Array(e);for(r=0;r<i;r++)n=t[r],n instanceof Uint8Array||(n="string"==typeof n?y(n):new Uint8Array(n)),o=n.byteLength,s.set(n,a),a+=o;return s}function S(t){return String.fromCharCode(t>>24&255,t>>16&255,t>>8&255,255&t)}function x(t){for(var e=1,r=0;t>e;)e<<=1,r++;return r}function C(t,e){return t[e]<<24>>24}function A(t,e){return t[e]<<8|t[e+1]}function T(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}function k(){var t=new Uint8Array(4);return t[0]=1,1===new Uint32Array(t.buffer,0,1)[0]}function P(){try{return new Function(""),!0}catch(t){return!1}}function E(t){var e,r=t.length,i=[];if("þ"===t[0]&&"ÿ"===t[1])for(e=2;e<r;e+=2)i.push(String.fromCharCode(t.charCodeAt(e)<<8|t.charCodeAt(e+1)));else for(e=0;e<r;++e){var n=At[t.charCodeAt(e)];i.push(n?String.fromCharCode(n):t.charAt(e))}return i.join("")}function O(t){return decodeURIComponent(escape(t))}function R(t){return unescape(encodeURIComponent(t))}function L(t){for(var e in t)return!1;return!0}function D(t){return"boolean"==typeof t}function I(t){return"number"==typeof t&&(0|t)===t}function j(t){return"number"==typeof t}function M(t){return"string"==typeof t}function F(t){return t instanceof Array}function N(t){return"object"===(void 0===t?"undefined":Y(t))&&null!==t&&void 0!==t.byteLength}function B(t){return 32===t||9===t||13===t||10===t}function U(){return"object"===(void 0===i?"undefined":Y(i))&&i+""=="[object process]"}function z(){var t={};return t.promise=new Promise(function(e,r){t.resolve=e,t.reject=r}),t}function W(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;return t?new Promise(function(i,n){i(t.apply(r,e))}):Promise.resolve(void 0)}function q(t,e,r){e?t.resolve():t.reject(r)}function X(t){return Promise.resolve(t).catch(function(){})}function G(t,e,r){var i=this;this.sourceName=t,this.targetName=e,this.comObj=r,this.callbackId=1,this.streamId=1,this.postMessageTransfers=!0,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null);var n=this.callbacksCapabilities=Object.create(null),o=this.actionHandler=Object.create(null);this._onComObjOnMessage=function(t){var e=t.data;if(e.targetName===i.sourceName)if(e.stream)i._processStreamMessage(e);else if(e.isReply){var a=e.callbackId;if(!(e.callbackId in n))throw new Error("Cannot resolve callback "+a);var s=n[a];delete n[a],"error"in e?s.reject(e.error):s.resolve(e.data)}else{if(!(e.action in o))throw new Error("Unknown action from worker: "+e.action);var c=o[e.action];if(e.callbackId){var l=i.sourceName,h=e.sourceName;Promise.resolve().then(function(){return c[0].call(c[1],e.data)}).then(function(t){r.postMessage({sourceName:l,targetName:h,isReply:!0,callbackId:e.callbackId,data:t})},function(t){t instanceof Error&&(t+=""),r.postMessage({sourceName:l,targetName:h,isReply:!0,callbackId:e.callbackId,error:t})})}else e.streamId?i._createStreamSink(e):c[0].call(c[1],e.data)}},r.addEventListener("message",this._onComObjOnMessage)}function H(t,e,r){var i=new Image;i.onload=function e(){r.resolve(t,i)},i.onerror=function e(){r.resolve(t,null),c("Error during JPEG image loading")},i.src=e}Object.defineProperty(r,"__esModule",{value:!0}),r.unreachable=r.warn=r.utf8StringToString=r.stringToUTF8String=r.stringToPDFString=r.stringToBytes=r.string32=r.shadow=r.setVerbosityLevel=r.ReadableStream=r.removeNullCharacters=r.readUint32=r.readUint16=r.readInt8=r.log2=r.loadJpegStream=r.isEvalSupported=r.isLittleEndian=r.createValidAbsoluteUrl=r.isSameOrigin=r.isNodeJS=r.isSpace=r.isString=r.isNum=r.isInt=r.isEmptyObj=r.isBool=r.isArrayBuffer=r.isArray=r.info=r.globalScope=r.getVerbosityLevel=r.getLookupTableFactory=r.deprecated=r.createObjectURL=r.createPromiseCapability=r.createBlob=r.bytesToString=r.assert=r.arraysToBytes=r.arrayByteLength=r.FormatError=r.XRefParseException=r.Util=r.UnknownErrorException=r.UnexpectedResponseException=r.TextRenderingMode=r.StreamType=r.StatTimer=r.PasswordResponses=r.PasswordException=r.PageViewport=r.NotImplementedException=r.NativeImageDecoding=r.MissingPDFException=r.MissingDataException=r.MessageHandler=r.InvalidPDFException=r.CMapCompressionType=r.ImageKind=r.FontType=r.AnnotationType=r.AnnotationFlag=r.AnnotationFieldFlag=r.AnnotationBorderStyleType=r.UNSUPPORTED_FEATURES=r.VERBOSITY_LEVELS=r.OPS=r.IDENTITY_MATRIX=r.FONT_IDENTITY_MATRIX=void 0;var Y="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};n(14);var V=n(9),Z="undefined"!=typeof window&&window.Math===Math?window:void 0!==e&&e.Math===Math?e:"undefined"!=typeof self&&self.Math===Math?self:void 0,J=[.001,0,0,.001,0,0],K={NONE:"none",DECODE:"decode",DISPLAY:"display"},Q={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},$={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},tt={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},et={INVISIBLE:1,HIDDEN:2,PRINT:4,NOZOOM:8,NOROTATE:16,NOVIEW:32,READONLY:64,LOCKED:128,TOGGLENOVIEW:256,LOCKEDCONTENTS:512},rt={READONLY:1,REQUIRED:2,NOEXPORT:4,MULTILINE:4096,PASSWORD:8192,NOTOGGLETOOFF:16384,RADIO:32768,PUSHBUTTON:65536,COMBO:131072,EDIT:262144,SORT:524288,FILESELECT:1048576,MULTISELECT:2097152,DONOTSPELLCHECK:4194304,DONOTSCROLL:8388608,COMB:16777216,RICHTEXT:33554432,RADIOSINUNISON:33554432,COMMITONSELCHANGE:67108864},it={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},nt={UNKNOWN:0,FLATE:1,LZW:2,DCT:3,JPX:4,JBIG:5,A85:6,AHX:7,CCF:8,RL:9},ot={UNKNOWN:0,TYPE1:1,TYPE1C:2,CIDFONTTYPE0:3,CIDFONTTYPE0C:4,TRUETYPE:5,CIDFONTTYPE2:6,TYPE3:7,OPENTYPE:8,TYPE0:9,MMTYPE1:10},at={errors:0,warnings:1,infos:5},st={NONE:0,BINARY:1,STREAM:2},ct={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotations:78,endAnnotations:79,beginAnnotation:80,endAnnotation:81,paintJpegXObject:82,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91},lt=at.warnings,ht={unknown:"unknown",forms:"forms",javaScript:"javaScript",smask:"smask",shadingPattern:"shadingPattern",font:"font"},ut={NEED_PASSWORD:1,INCORRECT_PASSWORD:2},ft=function t(){function e(t,e){this.name="PasswordException",this.message=t,this.code=e}return e.prototype=new Error,e.constructor=e,e}(),dt=function t(){function e(t,e){this.name="UnknownErrorException",this.message=t,this.details=e}return e.prototype=new Error,e.constructor=e,e}(),pt=function t(){function e(t){this.name="InvalidPDFException",this.message=t}return e.prototype=new Error,e.constructor=e,e}(),gt=function t(){function e(t){this.name="MissingPDFException",this.message=t}return e.prototype=new Error,e.constructor=e,e}(),vt=function t(){function e(t,e){this.name="UnexpectedResponseException",this.message=t,this.status=e}return e.prototype=new Error,e.constructor=e,e}(),mt=function t(){function e(t){this.message=t}return e.prototype=new Error,e.prototype.name="NotImplementedException",e.constructor=e,e}(),bt=function t(){function e(t,e){this.begin=t,this.end=e,this.message="Missing data ["+t+", "+e+")"}return e.prototype=new Error,e.prototype.name="MissingDataException",e.constructor=e,e}(),yt=function t(){function e(t){this.message=t}return e.prototype=new Error,e.prototype.name="XRefParseException",e.constructor=e,e}(),_t=function t(){function e(t){this.message=t}return e.prototype=new Error,e.prototype.name="FormatError",e.constructor=e,e}(),wt=/\x00/g,St=[1,0,0,1,0,0],xt=function t(){function e(){}var r=["rgb(",0,",",0,",",0,")"];e.makeCssRgb=function t(e,i,n){return r[1]=e,r[3]=i,r[5]=n,r.join("")},e.transform=function t(e,r){return[e[0]*r[0]+e[2]*r[1],e[1]*r[0]+e[3]*r[1],e[0]*r[2]+e[2]*r[3],e[1]*r[2]+e[3]*r[3],e[0]*r[4]+e[2]*r[5]+e[4],e[1]*r[4]+e[3]*r[5]+e[5]]},e.applyTransform=function t(e,r){return[e[0]*r[0]+e[1]*r[2]+r[4],e[0]*r[1]+e[1]*r[3]+r[5]]},e.applyInverseTransform=function t(e,r){var i=r[0]*r[3]-r[1]*r[2];return[(e[0]*r[3]-e[1]*r[2]+r[2]*r[5]-r[4]*r[3])/i,(-e[0]*r[1]+e[1]*r[0]+r[4]*r[1]-r[5]*r[0])/i]},e.getAxialAlignedBoundingBox=function t(r,i){var n=e.applyTransform(r,i),o=e.applyTransform(r.slice(2,4),i),a=e.applyTransform([r[0],r[3]],i),s=e.applyTransform([r[2],r[1]],i);return[Math.min(n[0],o[0],a[0],s[0]),Math.min(n[1],o[1],a[1],s[1]),Math.max(n[0],o[0],a[0],s[0]),Math.max(n[1],o[1],a[1],s[1])]},e.inverseTransform=function t(e){var r=e[0]*e[3]-e[1]*e[2];return[e[3]/r,-e[1]/r,-e[2]/r,e[0]/r,(e[2]*e[5]-e[4]*e[3])/r,(e[4]*e[1]-e[5]*e[0])/r]},e.apply3dTransform=function t(e,r){return[e[0]*r[0]+e[1]*r[1]+e[2]*r[2],e[3]*r[0]+e[4]*r[1]+e[5]*r[2],e[6]*r[0]+e[7]*r[1]+e[8]*r[2]]},e.singularValueDecompose2dScale=function t(e){var r=[e[0],e[2],e[1],e[3]],i=e[0]*r[0]+e[1]*r[2],n=e[0]*r[1]+e[1]*r[3],o=e[2]*r[0]+e[3]*r[2],a=e[2]*r[1]+e[3]*r[3],s=(i+a)/2,c=Math.sqrt((i+a)*(i+a)-4*(i*a-o*n))/2,l=s+c||1,h=s-c||1;return[Math.sqrt(l),Math.sqrt(h)]},e.normalizeRect=function t(e){var r=e.slice(0);return e[0]>e[2]&&(r[0]=e[2],r[2]=e[0]),e[1]>e[3]&&(r[1]=e[3],r[3]=e[1]),r},e.intersect=function t(r,i){function n(t,e){return t-e}var o=[r[0],r[2],i[0],i[2]].sort(n),a=[r[1],r[3],i[1],i[3]].sort(n),s=[];return r=e.normalizeRect(r),i=e.normalizeRect(i),(o[0]===r[0]&&o[1]===i[0]||o[0]===i[0]&&o[1]===r[0])&&(s[0]=o[1],s[2]=o[2],(a[0]===r[1]&&a[1]===i[1]||a[0]===i[1]&&a[1]===r[1])&&(s[1]=a[1],s[3]=a[2],s))},e.sign=function t(e){return e<0?-1:1};var i=["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM","","X","XX","XXX","XL","L","LX","LXX","LXXX","XC","","I","II","III","IV","V","VI","VII","VIII","IX"];return e.toRoman=function t(e,r){u(I(e)&&e>0,"The number should be a positive integer.");for(var n,o=[];e>=1e3;)e-=1e3,o.push("M");n=e/100|0,e%=100,o.push(i[n]),n=e/10|0,e%=10,o.push(i[10+n]),o.push(i[20+e]);var a=o.join("");return r?a.toLowerCase():a},e.appendToArray=function t(e,r){Array.prototype.push.apply(e,r)},e.prependToArray=function t(e,r){Array.prototype.unshift.apply(e,r)},e.extendObj=function t(e,r){for(var i in r)e[i]=r[i]},e.getInheritableProperty=function t(e,r,i){for(;e&&!e.has(r);)e=e.get("Parent");return e?i?e.getArray(r):e.get(r):null},e.inherit=function t(e,r,i){e.prototype=Object.create(r.prototype),e.prototype.constructor=e;for(var n in i)e.prototype[n]=i[n]},e.loadScript=function t(e,r){var i=document.createElement("script"),n=!1;i.setAttribute("src",e),r&&(i.onload=function(){n||r(),n=!0}),document.getElementsByTagName("head")[0].appendChild(i)},e}(),Ct=function t(){function e(t,e,r,i,n,o){this.viewBox=t,this.scale=e,this.rotation=r,this.offsetX=i,this.offsetY=n;var a=(t[2]+t[0])/2,s=(t[3]+t[1])/2,c,l,h,u;switch(r%=360,r=r<0?r+360:r){case 180:c=-1,l=0,h=0,u=1;break;case 90:c=0,l=1,h=1,u=0;break;case 270:c=0,l=-1,h=-1,u=0;break;default:c=1,l=0,h=0,u=-1}o&&(h=-h,u=-u);var f,d,p,g;0===c?(f=Math.abs(s-t[1])*e+i,d=Math.abs(a-t[0])*e+n,p=Math.abs(t[3]-t[1])*e,g=Math.abs(t[2]-t[0])*e):(f=Math.abs(a-t[0])*e+i,d=Math.abs(s-t[1])*e+n,p=Math.abs(t[2]-t[0])*e,g=Math.abs(t[3]-t[1])*e),this.transform=[c*e,l*e,h*e,u*e,f-c*e*a-h*e*s,d-l*e*a-u*e*s],this.width=p,this.height=g,this.fontScale=e}return e.prototype={clone:function t(r){r=r||{};var i="scale"in r?r.scale:this.scale,n="rotation"in r?r.rotation:this.rotation;return new e(this.viewBox.slice(),i,n,this.offsetX,this.offsetY,r.dontFlip)},convertToViewportPoint:function t(e,r){return xt.applyTransform([e,r],this.transform)},convertToViewportRectangle:function t(e){var r=xt.applyTransform([e[0],e[1]],this.transform),i=xt.applyTransform([e[2],e[3]],this.transform);return[r[0],r[1],i[0],i[1]]},convertToPdfPoint:function t(e,r){return xt.applyInverseTransform([e,r],this.transform)}},e}(),At=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,728,711,710,729,733,731,730,732,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8226,8224,8225,8230,8212,8211,402,8260,8249,8250,8722,8240,8222,8220,8221,8216,8217,8218,8482,64257,64258,321,338,352,376,381,305,322,339,353,382,0,8364],Tt=function t(){function e(t,e,r){for(;t.length<r;)t+=e;return t}function r(){this.started=Object.create(null),this.times=[],this.enabled=!0}return r.prototype={time:function t(e){this.enabled&&(e in this.started&&c("Timer is already running for "+e),this.started[e]=Date.now())},timeEnd:function t(e){this.enabled&&(e in this.started||c("Timer has not been started for "+e),this.times.push({name:e,start:this.started[e],end:Date.now()}),delete this.started[e])},toString:function t(){var r,i,n=this.times,o="",a=0;for(r=0,i=n.length;r<i;++r){var s=n[r].name;s.length>a&&(a=s.length)}for(r=0,i=n.length;r<i;++r){var c=n[r],l=c.end-c.start;o+=e(c.name," ",a)+" "+l+"ms\n"}return o}},r}(),kt=function t(e,r){if("undefined"!=typeof Blob)return new Blob([e],{type:r});throw new Error('The "Blob" constructor is not supported.')},Pt=function t(){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";return function t(r,i){if(!(arguments.length>2&&void 0!==arguments[2]&&arguments[2])&&URL.createObjectURL){var n=kt(r,i);return URL.createObjectURL(n)}for(var o="data:"+i+";base64,",a=0,s=r.length;a<s;a+=3){var c=255&r[a],l=255&r[a+1],h=255&r[a+2];o+=e[c>>2]+e[(3&c)<<4|l>>4]+e[a+1<s?(15&l)<<2|h>>6:64]+e[a+2<s?63&h:64]}return o}}();G.prototype={on:function t(e,r,i){var n=this.actionHandler;if(n[e])throw new Error('There is already an actionName called "'+e+'"');n[e]=[r,i]},send:function t(e,r,i){var n={sourceName:this.sourceName,targetName:this.targetName,action:e,data:r};this.postMessage(n,i)},sendWithPromise:function t(e,r,i){var n=this.callbackId++,o={sourceName:this.sourceName,targetName:this.targetName,action:e,data:r,callbackId:n},a=z();this.callbacksCapabilities[n]=a;try{this.postMessage(o,i)}catch(t){a.reject(t)}return a.promise},sendWithStream:function t(e,r,i,n){var o=this,a=this.streamId++,s=this.sourceName,c=this.targetName;return new V.ReadableStream({start:function t(i){var n=z();return o.streamControllers[a]={controller:i,startCall:n,isClosed:!1},o.postMessage({sourceName:s,targetName:c,action:e,streamId:a,data:r,desiredSize:i.desiredSize}),n.promise},pull:function t(e){var r=z();return o.streamControllers[a].pullCall=r,o.postMessage({sourceName:s,targetName:c,stream:"pull",streamId:a,desiredSize:e.desiredSize}),r.promise},cancel:function t(e){var r=z();return o.streamControllers[a].cancelCall=r,o.streamControllers[a].isClosed=!0,o.postMessage({sourceName:s,targetName:c,stream:"cancel",reason:e,streamId:a}),r.promise}},i)},_createStreamSink:function t(e){var r=this,i=this,n=this.actionHandler[e.action],o=e.streamId,a=e.desiredSize,s=this.sourceName,c=e.sourceName,l=z(),h=function t(e){var i=e.stream,n=e.chunk,a=e.success,l=e.reason;r.comObj.postMessage({sourceName:s,targetName:c,stream:i,streamId:o,chunk:n,success:a,reason:l})},u={enqueue:function t(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;if(!this.isCancelled){var i=this.desiredSize;this.desiredSize-=r,i>0&&this.desiredSize<=0&&(this.sinkCapability=z(),this.ready=this.sinkCapability.promise),h({stream:"enqueue",chunk:e})}},close:function t(){this.isCancelled||(h({stream:"close"}),delete i.streamSinks[o])},error:function t(e){h({stream:"error",reason:e})},sinkCapability:l,onPull:null,onCancel:null,isCancelled:!1,desiredSize:a,ready:null};u.sinkCapability.resolve(),u.ready=u.sinkCapability.promise,this.streamSinks[o]=u,W(n[0],[e.data,u],n[1]).then(function(){h({stream:"start_complete",success:!0})},function(t){h({stream:"start_complete",success:!1,reason:t})})},_processStreamMessage:function t(e){var r=this,i=this.sourceName,n=e.sourceName,o=e.streamId,a=function t(e){var a=e.stream,s=e.success,c=e.reason;r.comObj.postMessage({sourceName:i,targetName:n,stream:a,success:s,streamId:o,reason:c})},s=function t(){Promise.all([r.streamControllers[e.streamId].startCall,r.streamControllers[e.streamId].pullCall,r.streamControllers[e.streamId].cancelCall].map(function(t){return t&&X(t.promise)})).then(function(){delete r.streamControllers[e.streamId]})};switch(e.stream){case"start_complete":q(this.streamControllers[e.streamId].startCall,e.success,e.reason);break;case"pull_complete":q(this.streamControllers[e.streamId].pullCall,e.success,e.reason);break;case"pull":if(!this.streamSinks[e.streamId]){a({stream:"pull_complete",success:!0});break}this.streamSinks[e.streamId].desiredSize<=0&&e.desiredSize>0&&this.streamSinks[e.streamId].sinkCapability.resolve(),this.streamSinks[e.streamId].desiredSize=e.desiredSize,W(this.streamSinks[e.streamId].onPull).then(function(){a({stream:"pull_complete",success:!0})},function(t){a({stream:"pull_complete",success:!1,reason:t})});break;case"enqueue":this.streamControllers[e.streamId].isClosed||this.streamControllers[e.streamId].controller.enqueue(e.chunk);break;case"close":if(this.streamControllers[e.streamId].isClosed)break;this.streamControllers[e.streamId].isClosed=!0,this.streamControllers[e.streamId].controller.close(),s();break;case"error":this.streamControllers[e.streamId].controller.error(e.reason),s();break;case"cancel_complete":q(this.streamControllers[e.streamId].cancelCall,e.success,e.reason),s();break;case"cancel":if(!this.streamSinks[e.streamId])break;W(this.streamSinks[e.streamId].onCancel,[e.reason]).then(function(){a({stream:"cancel_complete",success:!0})},function(t){a({stream:"cancel_complete",success:!1,reason:t})}),this.streamSinks[e.streamId].sinkCapability.reject(e.reason),this.streamSinks[e.streamId].isCancelled=!0,delete this.streamSinks[e.streamId];break;default:throw new Error("Unexpected stream case")}},postMessage:function t(e,r){r&&this.postMessageTransfers?this.comObj.postMessage(e,r):this.comObj.postMessage(e)},destroy:function t(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}},r.FONT_IDENTITY_MATRIX=J,r.IDENTITY_MATRIX=St,r.OPS=ct,r.VERBOSITY_LEVELS=at,r.UNSUPPORTED_FEATURES=ht,r.AnnotationBorderStyleType=it,r.AnnotationFieldFlag=rt,r.AnnotationFlag=et,r.AnnotationType=tt,r.FontType=ot,r.ImageKind=$,r.CMapCompressionType=st,r.InvalidPDFException=pt,r.MessageHandler=G,r.MissingDataException=bt,r.MissingPDFException=gt,r.NativeImageDecoding=K,r.NotImplementedException=mt,r.PageViewport=Ct,r.PasswordException=ft,r.PasswordResponses=ut,r.StatTimer=Tt,r.StreamType=nt,r.TextRenderingMode=Q,r.UnexpectedResponseException=vt,r.UnknownErrorException=dt,r.Util=xt,r.XRefParseException=yt,r.FormatError=_t,r.arrayByteLength=_,r.arraysToBytes=w,r.assert=u,r.bytesToString=b,r.createBlob=kt,r.createPromiseCapability=z,r.createObjectURL=Pt,r.deprecated=l,r.getLookupTableFactory=v,r.getVerbosityLevel=a,r.globalScope=Z,r.info=s,r.isArray=F,r.isArrayBuffer=N,r.isBool=D,r.isEmptyObj=L,r.isInt=I,r.isNum=j,r.isString=M,r.isSpace=B,r.isNodeJS=U,r.isSameOrigin=f,r.createValidAbsoluteUrl=p,r.isLittleEndian=k,r.isEvalSupported=P,r.loadJpegStream=H,r.log2=x,r.readInt8=C,r.readUint16=A,r.readUint32=T,r.removeNullCharacters=m,r.ReadableStream=V.ReadableStream,r.setVerbosityLevel=o,r.shadow=g,r.string32=S,r.stringToBytes=y,r.stringToPDFString=E,r.stringToUTF8String=O,r.utf8StringToString=R,r.warn=c,r.unreachable=h},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){var r=e&&e.url;if(t.href=t.title=r?(0,h.removeNullCharacters)(r):"",r){var i=e.target;void 0===i&&(i=a("externalLinkTarget")),t.target=m[i];var n=e.rel;void 0===n&&(n=a("externalLinkRel")),t.rel=n}}function o(t){var e=t.indexOf("#"),r=t.indexOf("?"),i=Math.min(e>0?e:t.length,r>0?r:t.length);return t.substring(t.lastIndexOf("/",i)+1,i)}function a(t){var e=h.globalScope.PDFJS;switch(t){case"pdfBug":return!!e&&e.pdfBug;case"disableAutoFetch":return!!e&&e.disableAutoFetch;case"disableStream":return!!e&&e.disableStream;case"disableRange":return!!e&&e.disableRange;case"disableFontFace":return!!e&&e.disableFontFace;case"disableCreateObjectURL":return!!e&&e.disableCreateObjectURL;case"disableWebGL":return!e||e.disableWebGL;case"cMapUrl":return e?e.cMapUrl:null;case"cMapPacked":return!!e&&e.cMapPacked;case"postMessageTransfers":return!e||e.postMessageTransfers;case"workerPort":return e?e.workerPort:null;case"workerSrc":return e?e.workerSrc:null;case"disableWorker":return!!e&&e.disableWorker;case"maxImageSize":return e?e.maxImageSize:-1;case"imageResourcesPath":return e?e.imageResourcesPath:"";case"isEvalSupported":return!e||e.isEvalSupported;case"externalLinkTarget":if(!e)return v.NONE;switch(e.externalLinkTarget){case v.NONE:case v.SELF:case v.BLANK:case v.PARENT:case v.TOP:return e.externalLinkTarget}return(0,h.warn)("PDFJS.externalLinkTarget is invalid: "+e.externalLinkTarget),e.externalLinkTarget=v.NONE,v.NONE;case"externalLinkRel":return e?e.externalLinkRel:u;case"enableStats":return!(!e||!e.enableStats);case"pdfjsNext":return!(!e||!e.pdfjsNext);default:throw new Error("Unknown default setting: "+t)}}function s(){switch(a("externalLinkTarget")){case v.NONE:return!1;case v.SELF:case v.BLANK:case v.PARENT:case v.TOP:return!0}}function c(t,e){(0,h.deprecated)("isValidUrl(), please use createValidAbsoluteUrl() instead.");var r=e?"http://example.com":null;return null!==(0,h.createValidAbsoluteUrl)(t,r)}Object.defineProperty(e,"__esModule",{value:!0}),e.DOMCMapReaderFactory=e.DOMCanvasFactory=e.DEFAULT_LINK_REL=e.getDefaultSetting=e.LinkTarget=e.getFilenameFromUrl=e.isValidUrl=e.isExternalLinkTargetSet=e.addLinkAttributes=e.RenderingCancelledException=e.CustomStyle=void 0;var l=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),h=r(0),u="noopener noreferrer nofollow",f=function(){function t(){i(this,t)}return l(t,[{key:"create",value:function t(e,r){if(e<=0||r<=0)throw new Error("invalid canvas size");var i=document.createElement("canvas"),n=i.getContext("2d");return i.width=e,i.height=r,{canvas:i,context:n}}},{key:"reset",value:function t(e,r,i){if(!e.canvas)throw new Error("canvas is not specified");if(r<=0||i<=0)throw new Error("invalid canvas size");e.canvas.width=r,e.canvas.height=i}},{key:"destroy",value:function t(e){if(!e.canvas)throw new Error("canvas is not specified");e.canvas.width=0,e.canvas.height=0,e.canvas=null,e.context=null}}]),t}(),d=function(){function t(e){var r=e.baseUrl,n=void 0===r?null:r,o=e.isCompressed,a=void 0!==o&&o;i(this,t),this.baseUrl=n,this.isCompressed=a}return l(t,[{key:"fetch",value:function t(e){var r=this,i=e.name;return i?new Promise(function(t,e){var n=r.baseUrl+i+(r.isCompressed?".bcmap":""),o=new XMLHttpRequest;o.open("GET",n,!0),r.isCompressed&&(o.responseType="arraybuffer"),o.onreadystatechange=function(){if(o.readyState===XMLHttpRequest.DONE){if(200===o.status||0===o.status){var i=void 0;if(r.isCompressed&&o.response?i=new Uint8Array(o.response):!r.isCompressed&&o.responseText&&(i=(0,h.stringToBytes)(o.responseText)),i)return void t({cMapData:i,compressionType:r.isCompressed?h.CMapCompressionType.BINARY:h.CMapCompressionType.NONE})}e(new Error("Unable to load "+(r.isCompressed?"binary ":"")+"CMap at: "+n))}},o.send(null)}):Promise.reject(new Error("CMap name must be specified."))}}]),t}(),p=function t(){function e(){}var r=["ms","Moz","Webkit","O"],i=Object.create(null);return e.getProp=function t(e,n){if(1===arguments.length&&"string"==typeof i[e])return i[e];n=n||document.documentElement;var o=n.style,a,s;if("string"==typeof o[e])return i[e]=e;s=e.charAt(0).toUpperCase()+e.slice(1);for(var c=0,l=r.length;c<l;c++)if(a=r[c]+s,"string"==typeof o[a])return i[e]=a;return i[e]="undefined"},e.setProp=function t(e,r,i){var n=this.getProp(e);"undefined"!==n&&(r.style[n]=i)},e}(),g=function t(){function t(t,e){this.message=t,this.type=e}return t.prototype=new Error,t.prototype.name="RenderingCancelledException",t.constructor=t,t}(),v={NONE:0,SELF:1,BLANK:2,PARENT:3,TOP:4},m=["","_self","_blank","_parent","_top"];e.CustomStyle=p,e.RenderingCancelledException=g,e.addLinkAttributes=n,e.isExternalLinkTargetSet=s,e.isValidUrl=c,e.getFilenameFromUrl=o,e.LinkTarget=v,e.getDefaultSetting=a,e.DEFAULT_LINK_REL=u,e.DOMCanvasFactory=f,e.DOMCMapReaderFactory=d},function(t,e,r){"use strict";function i(){}Object.defineProperty(e,"__esModule",{value:!0}),e.AnnotationLayer=void 0;var n=r(1),o=r(0);i.prototype={create:function t(e){switch(e.data.annotationType){case o.AnnotationType.LINK:return new s(e);case o.AnnotationType.TEXT:return new c(e);case o.AnnotationType.WIDGET:switch(e.data.fieldType){case"Tx":return new h(e);case"Btn":if(e.data.radioButton)return new f(e);if(e.data.checkBox)return new u(e);(0,o.warn)("Unimplemented button widget annotation: pushbutton");break;case"Ch":return new d(e)}return new l(e);case o.AnnotationType.POPUP:return new p(e);case o.AnnotationType.LINE:return new v(e);case o.AnnotationType.HIGHLIGHT:return new m(e);case o.AnnotationType.UNDERLINE:return new b(e);case o.AnnotationType.SQUIGGLY:return new y(e);case o.AnnotationType.STRIKEOUT:return new _(e);case o.AnnotationType.FILEATTACHMENT:return new w(e);default:return new a(e)}}};var a=function t(){function e(t,e,r){this.isRenderable=e||!1,this.data=t.data,this.layer=t.layer,this.page=t.page,this.viewport=t.viewport,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderInteractiveForms=t.renderInteractiveForms,e&&(this.container=this._createContainer(r))}return e.prototype={_createContainer:function t(e){var r=this.data,i=this.page,a=this.viewport,s=document.createElement("section"),c=r.rect[2]-r.rect[0],l=r.rect[3]-r.rect[1];s.setAttribute("data-annotation-id",r.id);var h=o.Util.normalizeRect([r.rect[0],i.view[3]-r.rect[1]+i.view[1],r.rect[2],i.view[3]-r.rect[3]+i.view[1]]);if(n.CustomStyle.setProp("transform",s,"matrix("+a.transform.join(",")+")"),n.CustomStyle.setProp("transformOrigin",s,-h[0]+"px "+-h[1]+"px"),!e&&r.borderStyle.width>0){s.style.borderWidth=r.borderStyle.width+"px",r.borderStyle.style!==o.AnnotationBorderStyleType.UNDERLINE&&(c-=2*r.borderStyle.width,l-=2*r.borderStyle.width);var u=r.borderStyle.horizontalCornerRadius,f=r.borderStyle.verticalCornerRadius;if(u>0||f>0){var d=u+"px / "+f+"px";n.CustomStyle.setProp("borderRadius",s,d)}switch(r.borderStyle.style){case o.AnnotationBorderStyleType.SOLID:s.style.borderStyle="solid";break;case o.AnnotationBorderStyleType.DASHED:s.style.borderStyle="dashed";break;case o.AnnotationBorderStyleType.BEVELED:(0,o.warn)("Unimplemented border style: beveled");break;case o.AnnotationBorderStyleType.INSET:(0,o.warn)("Unimplemented border style: inset");break;case o.AnnotationBorderStyleType.UNDERLINE:s.style.borderBottomStyle="solid"}r.color?s.style.borderColor=o.Util.makeCssRgb(0|r.color[0],0|r.color[1],0|r.color[2]):s.style.borderWidth=0}return s.style.left=h[0]+"px",s.style.top=h[1]+"px",s.style.width=c+"px",s.style.height=l+"px",s},_createPopup:function t(e,r,i){r||(r=document.createElement("div"),r.style.height=e.style.height,r.style.width=e.style.width,e.appendChild(r));var n=new g({container:e,trigger:r,color:i.color,title:i.title,contents:i.contents,hideWrapper:!0}),o=n.render();o.style.left=e.style.width,e.appendChild(o)},render:function t(){throw new Error("Abstract method AnnotationElement.render called")}},e}(),s=function t(){function e(t){a.call(this,t,!0)}return o.Util.inherit(e,a,{render:function t(){this.container.className="linkAnnotation";var e=document.createElement("a");return(0,n.addLinkAttributes)(e,{url:this.data.url,target:this.data.newWindow?n.LinkTarget.BLANK:void 0}),this.data.url||(this.data.action?this._bindNamedAction(e,this.data.action):this._bindLink(e,this.data.dest)),this.container.appendChild(e),this.container},_bindLink:function t(e,r){var i=this;e.href=this.linkService.getDestinationHash(r),e.onclick=function(){return r&&i.linkService.navigateTo(r),!1},r&&(e.className="internalLink")},_bindNamedAction:function t(e,r){var i=this;e.href=this.linkService.getAnchorUrl(""),e.onclick=function(){return i.linkService.executeNamedAction(r),!1},e.className="internalLink"}}),e}(),c=function t(){function e(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);a.call(this,t,e)}return o.Util.inherit(e,a,{render:function t(){this.container.className="textAnnotation";var e=document.createElement("img");return e.style.height=this.container.style.height,e.style.width=this.container.style.width,e.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",e.alt="[{{type}} Annotation]",e.dataset.l10nId="text_annotation_type",e.dataset.l10nArgs=JSON.stringify({type:this.data.name}),this.data.hasPopup||this._createPopup(this.container,e,this.data),this.container.appendChild(e),this.container}}),e}(),l=function t(){function e(t,e){a.call(this,t,e)}return o.Util.inherit(e,a,{render:function t(){return this.container}}),e}(),h=function t(){function e(t){var e=t.renderInteractiveForms||!t.data.hasAppearance&&!!t.data.fieldValue;l.call(this,t,e)}var r=["left","center","right"];return o.Util.inherit(e,l,{render:function t(){this.container.className="textWidgetAnnotation";var e=null;if(this.renderInteractiveForms){if(this.data.multiLine?(e=document.createElement("textarea"),e.textContent=this.data.fieldValue):(e=document.createElement("input"),e.type="text",e.setAttribute("value",this.data.fieldValue)),e.disabled=this.data.readOnly,null!==this.data.maxLen&&(e.maxLength=this.data.maxLen),this.data.comb){var i=this.data.rect[2]-this.data.rect[0],n=i/this.data.maxLen;e.classList.add("comb"),e.style.letterSpacing="calc("+n+"px - 1ch)"}}else{e=document.createElement("div"),e.textContent=this.data.fieldValue,e.style.verticalAlign="middle",e.style.display="table-cell";var o=null;this.data.fontRefName&&(o=this.page.commonObjs.getData(this.data.fontRefName)),this._setTextStyle(e,o)}return null!==this.data.textAlignment&&(e.style.textAlign=r[this.data.textAlignment]),this.container.appendChild(e),this.container},_setTextStyle:function t(e,r){var i=e.style;if(i.fontSize=this.data.fontSize+"px",i.direction=this.data.fontDirection<0?"rtl":"ltr",r){i.fontWeight=r.black?r.bold?"900":"bold":r.bold?"bold":"normal",i.fontStyle=r.italic?"italic":"normal";var n=r.loadedName?'"'+r.loadedName+'", ':"",o=r.fallbackName||"Helvetica, sans-serif";i.fontFamily=n+o}}}),e}(),u=function t(){function e(t){l.call(this,t,t.renderInteractiveForms)}return o.Util.inherit(e,l,{render:function t(){this.container.className="buttonWidgetAnnotation checkBox";var e=document.createElement("input");return e.disabled=this.data.readOnly,e.type="checkbox",this.data.fieldValue&&"Off"!==this.data.fieldValue&&e.setAttribute("checked",!0),this.container.appendChild(e),this.container}}),e}(),f=function t(){function e(t){l.call(this,t,t.renderInteractiveForms)}return o.Util.inherit(e,l,{render:function t(){this.container.className="buttonWidgetAnnotation radioButton";var e=document.createElement("input");return e.disabled=this.data.readOnly,e.type="radio",e.name=this.data.fieldName,this.data.fieldValue===this.data.buttonValue&&e.setAttribute("checked",!0),this.container.appendChild(e),this.container}}),e}(),d=function t(){function e(t){l.call(this,t,t.renderInteractiveForms)}return o.Util.inherit(e,l,{render:function t(){this.container.className="choiceWidgetAnnotation";var e=document.createElement("select");e.disabled=this.data.readOnly,this.data.combo||(e.size=this.data.options.length,this.data.multiSelect&&(e.multiple=!0));for(var r=0,i=this.data.options.length;r<i;r++){var n=this.data.options[r],o=document.createElement("option");o.textContent=n.displayValue,o.value=n.exportValue,this.data.fieldValue.indexOf(n.displayValue)>=0&&o.setAttribute("selected",!0),e.appendChild(o)}return this.container.appendChild(e),this.container}}),e}(),p=function t(){function e(t){var e=!(!t.data.title&&!t.data.contents);a.call(this,t,e)}var r=["Line"];return o.Util.inherit(e,a,{render:function t(){if(this.container.className="popupAnnotation",r.indexOf(this.data.parentType)>=0)return this.container;var e='[data-annotation-id="'+this.data.parentId+'"]',i=this.layer.querySelector(e);if(!i)return this.container;var o=new g({container:this.container,trigger:i,color:this.data.color,title:this.data.title,contents:this.data.contents}),a=parseFloat(i.style.left),s=parseFloat(i.style.width);return n.CustomStyle.setProp("transformOrigin",this.container,-(a+s)+"px -"+i.style.top),this.container.style.left=a+s+"px",this.container.appendChild(o.render()),this.container}}),e}(),g=function t(){function e(t){this.container=t.container,this.trigger=t.trigger,this.color=t.color,this.title=t.title,this.contents=t.contents,this.hideWrapper=t.hideWrapper||!1,this.pinned=!1}var r=.7;return e.prototype={render:function t(){var e=document.createElement("div");e.className="popupWrapper",this.hideElement=this.hideWrapper?e:this.container,this.hideElement.setAttribute("hidden",!0);var r=document.createElement("div");r.className="popup";var i=this.color;if(i){var n=.7*(255-i[0])+i[0],a=.7*(255-i[1])+i[1],s=.7*(255-i[2])+i[2];r.style.backgroundColor=o.Util.makeCssRgb(0|n,0|a,0|s)}var c=this._formatContents(this.contents),l=document.createElement("h1");return l.textContent=this.title,this.trigger.addEventListener("click",this._toggle.bind(this)),this.trigger.addEventListener("mouseover",this._show.bind(this,!1)),this.trigger.addEventListener("mouseout",this._hide.bind(this,!1)),r.addEventListener("click",this._hide.bind(this,!0)),r.appendChild(l),r.appendChild(c),e.appendChild(r),e},_formatContents:function t(e){for(var r=document.createElement("p"),i=e.split(/(?:\r\n?|\n)/),n=0,o=i.length;n<o;++n){var a=i[n];r.appendChild(document.createTextNode(a)),n<o-1&&r.appendChild(document.createElement("br"))}return r},_toggle:function t(){this.pinned?this._hide(!0):this._show(!0)},_show:function t(e){e&&(this.pinned=!0),this.hideElement.hasAttribute("hidden")&&(this.hideElement.removeAttribute("hidden"),this.container.style.zIndex+=1)},_hide:function t(e){e&&(this.pinned=!1),this.hideElement.hasAttribute("hidden")||this.pinned||(this.hideElement.setAttribute("hidden",!0),this.container.style.zIndex-=1)}},e}(),v=function t(){function e(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);a.call(this,t,e,!0)}var r="http://www.w3.org/2000/svg";return o.Util.inherit(e,a,{render:function t(){this.container.className="lineAnnotation";var e=this.data,i=e.rect[2]-e.rect[0],n=e.rect[3]-e.rect[1],o=document.createElementNS(r,"svg:svg");o.setAttributeNS(null,"version","1.1"),o.setAttributeNS(null,"width",i+"px"),o.setAttributeNS(null,"height",n+"px"),o.setAttributeNS(null,"preserveAspectRatio","none"),o.setAttributeNS(null,"viewBox","0 0 "+i+" "+n);var a=document.createElementNS(r,"svg:line");return a.setAttributeNS(null,"x1",e.rect[2]-e.lineCoordinates[0]),a.setAttributeNS(null,"y1",e.rect[3]-e.lineCoordinates[1]),a.setAttributeNS(null,"x2",e.rect[2]-e.lineCoordinates[2]),a.setAttributeNS(null,"y2",e.rect[3]-e.lineCoordinates[3]),a.setAttributeNS(null,"stroke-width",e.borderStyle.width),a.setAttributeNS(null,"stroke","transparent"),o.appendChild(a),this.container.append(o),this._createPopup(this.container,a,this.data),this.container}}),e}(),m=function t(){function e(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);a.call(this,t,e,!0)}return o.Util.inherit(e,a,{render:function t(){return this.container.className="highlightAnnotation",this.data.hasPopup||this._createPopup(this.container,null,this.data),this.container}}),e}(),b=function t(){function e(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);a.call(this,t,e,!0)}return o.Util.inherit(e,a,{render:function t(){return this.container.className="underlineAnnotation",this.data.hasPopup||this._createPopup(this.container,null,this.data),this.container}}),e}(),y=function t(){function e(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);a.call(this,t,e,!0)}return o.Util.inherit(e,a,{render:function t(){return this.container.className="squigglyAnnotation",this.data.hasPopup||this._createPopup(this.container,null,this.data),this.container}}),e}(),_=function t(){function e(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);a.call(this,t,e,!0)}return o.Util.inherit(e,a,{render:function t(){return this.container.className="strikeoutAnnotation",this.data.hasPopup||this._createPopup(this.container,null,this.data),this.container}}),e}(),w=function t(){function e(t){a.call(this,t,!0);var e=this.data.file;this.filename=(0,n.getFilenameFromUrl)(e.filename),this.content=e.content,this.linkService.onFileAttachmentAnnotation({id:(0,o.stringToPDFString)(e.filename),filename:e.filename,content:e.content})}return o.Util.inherit(e,a,{render:function t(){this.container.className="fileAttachmentAnnotation";var e=document.createElement("div");return e.style.height=this.container.style.height,e.style.width=this.container.style.width,e.addEventListener("dblclick",this._download.bind(this)),this.data.hasPopup||!this.data.title&&!this.data.contents||this._createPopup(this.container,e,this.data),this.container.appendChild(e),this.container},_download:function t(){if(!this.downloadManager)return void(0,o.warn)("Download cannot be started due to unavailable download manager");this.downloadManager.downloadData(this.content,this.filename,"")}}),e}(),S=function t(){return{render:function t(e){for(var r=new i,o=0,a=e.annotations.length;o<a;o++){var s=e.annotations[o];if(s){var c=r.create({data:s,layer:e.div,page:e.page,viewport:e.viewport,linkService:e.linkService,downloadManager:e.downloadManager,imageResourcesPath:e.imageResourcesPath||(0,n.getDefaultSetting)("imageResourcesPath"),renderInteractiveForms:e.renderInteractiveForms||!1});c.isRenderable&&e.div.appendChild(c.render())}}},update:function t(e){for(var r=0,i=e.annotations.length;r<i;r++){var o=e.annotations[r],a=e.div.querySelector('[data-annotation-id="'+o.id+'"]');a&&n.CustomStyle.setProp("transform",a,"matrix("+e.viewport.transform.join(",")+")")}e.div.removeAttribute("hidden")}}}();e.AnnotationLayer=S},function(t,e,i){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e,r,i){var n=new S;arguments.length>1&&(0,l.deprecated)("getDocument is called with pdfDataRangeTransport, passwordCallback or progressCallback argument"),e&&(e instanceof x||(e=Object.create(e),e.length=t.length,e.initialData=t.initialData,e.abort||(e.abort=function(){})),t=Object.create(t),t.range=e),n.onPassword=r||null,n.onProgress=i||null;var o;if("string"==typeof t)o={url:t};else if((0,l.isArrayBuffer)(t))o={data:t};else if(t instanceof x)o={range:t};else{if("object"!==(void 0===t?"undefined":c(t)))throw new Error("Invalid parameter in getDocument, need either Uint8Array, string or a parameter object");if(!t.url&&!t.data&&!t.range)throw new Error("Invalid parameter object: need either .data, .range or .url");o=t}var s={},u=null,f=null,d=h.DOMCMapReaderFactory;for(var g in o)if("url"!==g||"undefined"==typeof window)if("range"!==g)if("worker"!==g)if("data"!==g||o[g]instanceof Uint8Array)"CMapReaderFactory"!==g?s[g]=o[g]:d=o[g];else{var v=o[g];if("string"==typeof v)s[g]=(0,l.stringToBytes)(v);else if("object"!==(void 0===v?"undefined":c(v))||null===v||isNaN(v.length)){if(!(0,l.isArrayBuffer)(v))throw new Error("Invalid PDF binary data: either typed array, string or array-like object is expected in the data property.");s[g]=new Uint8Array(v)}else s[g]=new Uint8Array(v)}else f=o[g];else u=o[g];else s[g]=new URL(o[g],window.location).href;if(s.rangeChunkSize=s.rangeChunkSize||p,s.ignoreErrors=!0!==s.stopAtErrors,void 0!==s.disableNativeImageDecoder&&(0,l.deprecated)("parameter disableNativeImageDecoder, use nativeImageDecoderSupport instead"),s.nativeImageDecoderSupport=s.nativeImageDecoderSupport||(!0===s.disableNativeImageDecoder?l.NativeImageDecoding.NONE:l.NativeImageDecoding.DECODE),s.nativeImageDecoderSupport!==l.NativeImageDecoding.DECODE&&s.nativeImageDecoderSupport!==l.NativeImageDecoding.NONE&&s.nativeImageDecoderSupport!==l.NativeImageDecoding.DISPLAY&&((0,l.warn)("Invalid parameter nativeImageDecoderSupport: need a state of enum {NativeImageDecoding}"),s.nativeImageDecoderSupport=l.NativeImageDecoding.DECODE),!f){var m=(0,h.getDefaultSetting)("workerPort");f=m?k.fromPort(m):new k,n._worker=f}var b=n.docId;return f.promise.then(function(){if(n.destroyed)throw new Error("Loading aborted");return a(f,s,u,b).then(function(t){if(n.destroyed)throw new Error("Loading aborted");var e=new l.MessageHandler(b,t,f.port),r=new P(e,n,u,d);n._transport=r,e.send("Ready",null)})}).catch(n._capability.reject),n}function a(t,e,r,i){return t.destroyed?Promise.reject(new Error("Worker was destroyed")):(e.disableAutoFetch=(0,h.getDefaultSetting)("disableAutoFetch"),e.disableStream=(0,h.getDefaultSetting)("disableStream"),e.chunkedViewerLoading=!!r,r&&(e.length=r.length,e.initialData=r.initialData),t.messageHandler.sendWithPromise("GetDocRequest",{docId:i,source:e,disableRange:(0,h.getDefaultSetting)("disableRange"),maxImageSize:(0,h.getDefaultSetting)("maxImageSize"),disableFontFace:(0,h.getDefaultSetting)("disableFontFace"),disableCreateObjectURL:(0,h.getDefaultSetting)("disableCreateObjectURL"),postMessageTransfers:(0,h.getDefaultSetting)("postMessageTransfers")&&!m,docBaseUrl:e.docBaseUrl,nativeImageDecoderSupport:e.nativeImageDecoderSupport,ignoreErrors:e.ignoreErrors}).then(function(e){if(t.destroyed)throw new Error("Worker was destroyed");return e}))}Object.defineProperty(e,"__esModule",{value:!0}),e.build=e.version=e._UnsupportedManager=e.PDFPageProxy=e.PDFDocumentProxy=e.PDFWorker=e.PDFDataRangeTransport=e.LoopbackPort=e.getDocument=void 0;var s=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},l=i(0),h=i(1),u=i(11),f=i(10),d=i(6),p=65536,g=!1,v,m=!1,b="undefined"!=typeof document&&document.currentScript?document.currentScript.src:null,y=null,_=!1;"undefined"==typeof window?(g=!0,_=!0):_=!0,"undefined"!=typeof requirejs&&requirejs.toUrl&&(v=requirejs.toUrl("pdfjs-dist/build/pdf.worker.js"));var w="undefined"!=typeof requirejs&&requirejs.load;y=_?function(t){r.e(0).then(function(){var e;e=r(81),t(e.WorkerMessageHandler)}.bind(null,r)).catch(r.oe)}:w?function(t){requirejs(["pdfjs-dist/build/pdf.worker"],function(e){t(e.WorkerMessageHandler)})}:null;var S=function t(){function e(){this._capability=(0,l.createPromiseCapability)(),this._transport=null,this._worker=null,this.docId="d"+r++,this.destroyed=!1,this.onPassword=null,this.onProgress=null,this.onUnsupportedFeature=null}var r=0;return e.prototype={get promise(){return this._capability.promise},destroy:function t(){var e=this;return this.destroyed=!0,(this._transport?this._transport.destroy():Promise.resolve()).then(function(){e._transport=null,e._worker&&(e._worker.destroy(),e._worker=null)})},then:function t(e,r){return this.promise.then.apply(this.promise,arguments)}},e}(),x=function t(){function e(t,e){this.length=t,this.initialData=e,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._readyCapability=(0,l.createPromiseCapability)()}return e.prototype={addRangeListener:function t(e){this._rangeListeners.push(e)},addProgressListener:function t(e){this._progressListeners.push(e)},addProgressiveReadListener:function t(e){this._progressiveReadListeners.push(e)},onDataRange:function t(e,r){for(var i=this._rangeListeners,n=0,o=i.length;n<o;++n)i[n](e,r)},onDataProgress:function t(e){var r=this;this._readyCapability.promise.then(function(){for(var t=r._progressListeners,i=0,n=t.length;i<n;++i)t[i](e)})},onDataProgressiveRead:function t(e){var r=this;this._readyCapability.promise.then(function(){for(var t=r._progressiveReadListeners,i=0,n=t.length;i<n;++i)t[i](e)})},transportReady:function t(){this._readyCapability.resolve()},requestDataRange:function t(e,r){throw new Error("Abstract method PDFDataRangeTransport.requestDataRange")},abort:function t(){}},e}(),C=function t(){function e(t,e,r){this.pdfInfo=t,this.transport=e,this.loadingTask=r}return e.prototype={get numPages(){return this.pdfInfo.numPages},get fingerprint(){return this.pdfInfo.fingerprint},getPage:function t(e){return this.transport.getPage(e)},getPageIndex:function t(e){return this.transport.getPageIndex(e)},getDestinations:function t(){return this.transport.getDestinations()},getDestination:function t(e){return this.transport.getDestination(e)},getPageLabels:function t(){return this.transport.getPageLabels()},getPageMode:function t(){return this.transport.getPageMode()},getAttachments:function t(){return this.transport.getAttachments()},getJavaScript:function t(){return this.transport.getJavaScript()},getOutline:function t(){return this.transport.getOutline()},getMetadata:function t(){return this.transport.getMetadata()},getData:function t(){return this.transport.getData()},getDownloadInfo:function t(){return this.transport.downloadInfoCapability.promise},getStats:function t(){return this.transport.getStats()},cleanup:function t(){this.transport.startCleanup()},destroy:function t(){return this.loadingTask.destroy()}},e}(),A=function t(){function e(t,e,r){this.pageIndex=t,this.pageInfo=e,this.transport=r,this.stats=new l.StatTimer,this.stats.enabled=(0,h.getDefaultSetting)("enableStats"),this.commonObjs=r.commonObjs,this.objs=new E,this.cleanupAfterRender=!1,this.pendingCleanup=!1,this.intentStates=Object.create(null),this.destroyed=!1}return e.prototype={get pageNumber(){return this.pageIndex+1},get rotate(){return this.pageInfo.rotate},get ref(){return this.pageInfo.ref},get userUnit(){return this.pageInfo.userUnit},get view(){return this.pageInfo.view},getViewport:function t(e,r){return arguments.length<2&&(r=this.rotate),new l.PageViewport(this.view,e,r,0,0)},getAnnotations:function t(e){var r=e&&e.intent||null;return this.annotationsPromise&&this.annotationsIntent===r||(this.annotationsPromise=this.transport.getAnnotations(this.pageIndex,r),this.annotationsIntent=r),this.annotationsPromise},render:function t(e){var r=this,i=this.stats;i.time("Overall"),this.pendingCleanup=!1;var n="print"===e.intent?"print":"display",o=e.canvasFactory||new h.DOMCanvasFactory;this.intentStates[n]||(this.intentStates[n]=Object.create(null));var a=this.intentStates[n];a.displayReadyCapability||(a.receivingOperatorList=!0,a.displayReadyCapability=(0,l.createPromiseCapability)(),a.operatorList={fnArray:[],argsArray:[],lastChunk:!1},this.stats.time("Page Request"),this.transport.messageHandler.send("RenderPageRequest",{pageIndex:this.pageNumber-1,intent:n,renderInteractiveForms:!0===e.renderInteractiveForms}));var s=function t(e){var n=a.renderTasks.indexOf(c);n>=0&&a.renderTasks.splice(n,1),r.cleanupAfterRender&&(r.pendingCleanup=!0),r._tryCleanup(),e?c.capability.reject(e):c.capability.resolve(),i.timeEnd("Rendering"),i.timeEnd("Overall")},c=new R(s,e,this.objs,this.commonObjs,a.operatorList,this.pageNumber,o);c.useRequestAnimationFrame="print"!==n,a.renderTasks||(a.renderTasks=[]),a.renderTasks.push(c);var u=c.task;return e.continueCallback&&((0,l.deprecated)("render is used with continueCallback parameter"),u.onContinue=e.continueCallback),a.displayReadyCapability.promise.then(function(t){if(r.pendingCleanup)return void s();i.time("Rendering"),c.initializeGraphics(t),c.operatorListChanged()}).catch(s),u},getOperatorList:function t(){function e(){if(i.operatorList.lastChunk){i.opListReadCapability.resolve(i.operatorList);var t=i.renderTasks.indexOf(n);t>=0&&i.renderTasks.splice(t,1)}}var r="oplist";this.intentStates.oplist||(this.intentStates.oplist=Object.create(null));var i=this.intentStates.oplist,n;return i.opListReadCapability||(n={},n.operatorListChanged=e,i.receivingOperatorList=!0,i.opListReadCapability=(0,l.createPromiseCapability)(),i.renderTasks=[],i.renderTasks.push(n),i.operatorList={fnArray:[],argsArray:[],lastChunk:!1},this.transport.messageHandler.send("RenderPageRequest",{pageIndex:this.pageIndex,intent:"oplist"})),i.opListReadCapability.promise},streamTextContent:function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=100;return this.transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this.pageNumber-1,normalizeWhitespace:!0===e.normalizeWhitespace,combineTextItems:!0!==e.disableCombineTextItems},{highWaterMark:100,size:function t(e){return e.items.length}})},getTextContent:function t(e){e=e||{};var r=this.streamTextContent(e);return new Promise(function(t,e){function i(){n.read().then(function(e){var r=e.value;if(e.done)return void t(o);l.Util.extendObj(o.styles,r.styles),l.Util.appendToArray(o.items,r.items),i()},e)}var n=r.getReader(),o={items:[],styles:Object.create(null)};i()})},_destroy:function t(){this.destroyed=!0,this.transport.pageCache[this.pageIndex]=null;var e=[];return Object.keys(this.intentStates).forEach(function(t){if("oplist"!==t){this.intentStates[t].renderTasks.forEach(function(t){var r=t.capability.promise.catch(function(){});e.push(r),t.cancel()})}},this),this.objs.clear(),this.annotationsPromise=null,this.pendingCleanup=!1,Promise.all(e)},destroy:function t(){(0,l.deprecated)("page destroy method, use cleanup() instead"),this.cleanup()},cleanup:function t(){this.pendingCleanup=!0,this._tryCleanup()},_tryCleanup:function t(){this.pendingCleanup&&!Object.keys(this.intentStates).some(function(t){var e=this.intentStates[t];return 0!==e.renderTasks.length||e.receivingOperatorList},this)&&(Object.keys(this.intentStates).forEach(function(t){delete this.intentStates[t]},this),this.objs.clear(),this.annotationsPromise=null,this.pendingCleanup=!1)},_startRenderPage:function t(e,r){var i=this.intentStates[r];i.displayReadyCapability&&i.displayReadyCapability.resolve(e)},_renderPageChunk:function t(e,r){var i=this.intentStates[r],n,o;for(n=0,o=e.length;n<o;n++)i.operatorList.fnArray.push(e.fnArray[n]),i.operatorList.argsArray.push(e.argsArray[n]);for(i.operatorList.lastChunk=e.lastChunk,n=0;n<i.renderTasks.length;n++)i.renderTasks[n].operatorListChanged();e.lastChunk&&(i.receivingOperatorList=!1,this._tryCleanup())}},e}(),T=function(){function t(e){n(this,t),this._listeners=[],this._defer=e,this._deferred=Promise.resolve(void 0)}return s(t,[{key:"postMessage",value:function t(e,r){function i(t){if("object"!==(void 0===t?"undefined":c(t))||null===t)return t;if(o.has(t))return o.get(t);var e,n;if((n=t.buffer)&&(0,l.isArrayBuffer)(n)){var a=r&&r.indexOf(n)>=0;return e=t===n?t:a?new t.constructor(n,t.byteOffset,t.byteLength):new t.constructor(t),o.set(t,e),e}e=(0,l.isArray)(t)?[]:{},o.set(t,e);for(var s in t){for(var h,u=t;!(h=Object.getOwnPropertyDescriptor(u,s));)u=Object.getPrototypeOf(u);void 0!==h.value&&"function"!=typeof h.value&&(e[s]=i(h.value))}return e}var n=this;if(!this._defer)return void this._listeners.forEach(function(t){t.call(this,{data:e})},this);var o=new WeakMap,a={data:i(e)};this._deferred.then(function(){n._listeners.forEach(function(t){t.call(this,a)},n)})}},{key:"addEventListener",value:function t(e,r){this._listeners.push(r)}},{key:"removeEventListener",value:function t(e,r){var i=this._listeners.indexOf(r);this._listeners.splice(i,1)}},{key:"terminate",value:function t(){this._listeners=[]}}]),t}(),k=function t(){function e(){if(void 0!==v)return v;if((0,h.getDefaultSetting)("workerSrc"))return(0,h.getDefaultSetting)("workerSrc");if(b)return b.replace(/(\.(?:min\.)?js)(\?.*)?$/i,".worker$1$2");throw new Error("No PDFJS.workerSrc specified")}function r(){var t;return a?a.promise:(a=(0,l.createPromiseCapability)(),(y||function(t){l.Util.loadScript(e(),function(){t(window.pdfjsDistBuildPdfWorker.WorkerMessageHandler)})})(a.resolve),a.promise)}function i(t){var e="importScripts('"+t+"');";return URL.createObjectURL(new Blob([e]))}function n(t,e){if(e&&s.has(e))throw new Error("Cannot use more than one PDFWorker per port");if(this.name=t,this.destroyed=!1,this._readyCapability=(0,l.createPromiseCapability)(),this._port=null,this._webWorker=null,this._messageHandler=null,e)return s.set(e,this),void this._initializeFromPort(e);this._initialize()}var o=0,a=void 0,s=new WeakMap;return n.prototype={get promise(){return this._readyCapability.promise},get port(){return this._port},get messageHandler(){return this._messageHandler},_initializeFromPort:function t(e){this._port=e,this._messageHandler=new l.MessageHandler("main","worker",e),this._messageHandler.on("ready",function(){}),this._readyCapability.resolve()},_initialize:function t(){var r=this;if(!g&&!(0,h.getDefaultSetting)("disableWorker")&&"undefined"!=typeof Worker){var n=e();try{(0,l.isSameOrigin)(window.location.href,n)||(n=i(new URL(n,window.location).href));var o=new Worker(n),a=new l.MessageHandler("main","worker",o),s=function t(){o.removeEventListener("error",c),a.destroy(),o.terminate(),r.destroyed?r._readyCapability.reject(new Error("Worker was destroyed")):r._setupFakeWorker()},c=function t(){r._webWorker||s()};o.addEventListener("error",c),a.on("test",function(t){if(o.removeEventListener("error",c),r.destroyed)return void s();t&&t.supportTypedArray?(r._messageHandler=a,r._port=o,r._webWorker=o,t.supportTransfers||(m=!0),r._readyCapability.resolve(),a.send("configure",{verbosity:(0,l.getVerbosityLevel)()})):(r._setupFakeWorker(),a.destroy(),o.terminate())}),a.on("console_log",function(t){console.log.apply(console,t)}),a.on("console_error",function(t){console.error.apply(console,t)}),a.on("ready",function(t){if(o.removeEventListener("error",c),r.destroyed)return void s();try{u()}catch(t){r._setupFakeWorker()}});var u=function t(){var e=(0,h.getDefaultSetting)("postMessageTransfers")&&!m,r=new Uint8Array([e?255:0]);try{a.send("test",r,[r.buffer])}catch(t){(0,l.info)("Cannot use postMessage transfers"),r[0]=0,a.send("test",r)}};return void u()}catch(t){(0,l.info)("The worker has been disabled.")}}this._setupFakeWorker()},_setupFakeWorker:function t(){var e=this;g||(0,h.getDefaultSetting)("disableWorker")||((0,l.warn)("Setting up fake worker."),g=!0),r().then(function(t){if(e.destroyed)return void e._readyCapability.reject(new Error("Worker was destroyed"));var r=Uint8Array!==Float32Array,i=new T(r);e._port=i;var n="fake"+o++,a=new l.MessageHandler(n+"_worker",n,i);t.setup(a,i);var s=new l.MessageHandler(n,n+"_worker",i);e._messageHandler=s,e._readyCapability.resolve()})},destroy:function t(){this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}},n.fromPort=function(t){return s.has(t)?s.get(t):new n(null,t)},n}(),P=function t(){function e(t,e,r,i){this.messageHandler=t,this.loadingTask=e,this.pdfDataRangeTransport=r,this.commonObjs=new E,this.fontLoader=new u.FontLoader(e.docId),this.CMapReaderFactory=new i({baseUrl:(0,h.getDefaultSetting)("cMapUrl"),isCompressed:(0,h.getDefaultSetting)("cMapPacked")}),this.destroyed=!1,this.destroyCapability=null,this._passwordCapability=null,this.pageCache=[],this.pagePromises=[],this.downloadInfoCapability=(0,l.createPromiseCapability)(),this.setupMessageHandler()}return e.prototype={destroy:function t(){var e=this;if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=(0,l.createPromiseCapability)(),this._passwordCapability&&this._passwordCapability.reject(new Error("Worker was destroyed during onPassword callback"));var r=[];this.pageCache.forEach(function(t){t&&r.push(t._destroy())}),this.pageCache=[],this.pagePromises=[];var i=this.messageHandler.sendWithPromise("Terminate",null);return r.push(i),Promise.all(r).then(function(){e.fontLoader.clear(),e.pdfDataRangeTransport&&(e.pdfDataRangeTransport.abort(),e.pdfDataRangeTransport=null),e.messageHandler&&(e.messageHandler.destroy(),e.messageHandler=null),e.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise},setupMessageHandler:function t(){var e=this.messageHandler,r=this.loadingTask,i=this.pdfDataRangeTransport;i&&(i.addRangeListener(function(t,r){e.send("OnDataRange",{begin:t,chunk:r})}),i.addProgressListener(function(t){e.send("OnDataProgress",{loaded:t})}),i.addProgressiveReadListener(function(t){e.send("OnDataRange",{chunk:t})}),e.on("RequestDataRange",function t(e){i.requestDataRange(e.begin,e.end)},this)),e.on("GetDoc",function t(e){var r=e.pdfInfo;this.numPages=e.pdfInfo.numPages;var i=this.loadingTask,n=new C(r,this,i);this.pdfDocument=n,i._capability.resolve(n)},this),e.on("PasswordRequest",function t(e){var i=this;if(this._passwordCapability=(0,l.createPromiseCapability)(),r.onPassword){var n=function t(e){i._passwordCapability.resolve({password:e})};r.onPassword(n,e.code)}else this._passwordCapability.reject(new l.PasswordException(e.message,e.code));return this._passwordCapability.promise},this),e.on("PasswordException",function t(e){r._capability.reject(new l.PasswordException(e.message,e.code))},this),e.on("InvalidPDF",function t(e){this.loadingTask._capability.reject(new l.InvalidPDFException(e.message))},this),e.on("MissingPDF",function t(e){this.loadingTask._capability.reject(new l.MissingPDFException(e.message))},this),e.on("UnexpectedResponse",function t(e){this.loadingTask._capability.reject(new l.UnexpectedResponseException(e.message,e.status))},this),e.on("UnknownError",function t(e){this.loadingTask._capability.reject(new l.UnknownErrorException(e.message,e.details))},this),e.on("DataLoaded",function t(e){this.downloadInfoCapability.resolve(e)},this),e.on("PDFManagerReady",function t(e){this.pdfDataRangeTransport&&this.pdfDataRangeTransport.transportReady()},this),e.on("StartRenderPage",function t(e){if(!this.destroyed){var r=this.pageCache[e.pageIndex];r.stats.timeEnd("Page Request"),r._startRenderPage(e.transparency,e.intent)}},this),e.on("RenderPageChunk",function t(e){if(!this.destroyed){this.pageCache[e.pageIndex]._renderPageChunk(e.operatorList,e.intent)}},this),e.on("commonobj",function t(e){var r=this;if(!this.destroyed){var i=e[0],n=e[1];if(!this.commonObjs.hasData(i))switch(n){case"Font":var o=e[2];if("error"in o){var a=o.error;(0,l.warn)("Error during font loading: "+a),this.commonObjs.resolve(i,a);break}var s=null;(0,h.getDefaultSetting)("pdfBug")&&l.globalScope.FontInspector&&l.globalScope.FontInspector.enabled&&(s={registerFont:function t(e,r){l.globalScope.FontInspector.fontAdded(e,r)}});var c=new u.FontFaceObject(o,{isEvalSuported:(0,h.getDefaultSetting)("isEvalSupported"),disableFontFace:(0,h.getDefaultSetting)("disableFontFace"),fontRegistry:s}),f=function t(e){r.commonObjs.resolve(i,c)};this.fontLoader.bind([c],f);break;case"FontPath":this.commonObjs.resolve(i,e[2]);break;default:throw new Error("Got unknown common object type "+n)}}},this),e.on("obj",function t(e){if(!this.destroyed){var r=e[0],i=e[1],n=e[2],o=this.pageCache[i],a;if(!o.objs.hasData(r))switch(n){case"JpegStream":a=e[3],(0,l.loadJpegStream)(r,a,o.objs);break;case"Image":a=e[3],o.objs.resolve(r,a);var s=8e6;a&&"data"in a&&a.data.length>8e6&&(o.cleanupAfterRender=!0);break;default:throw new Error("Got unknown object type "+n)}}},this),e.on("DocProgress",function t(e){if(!this.destroyed){var r=this.loadingTask;r.onProgress&&r.onProgress({loaded:e.loaded,total:e.total})}},this),e.on("PageError",function t(e){if(!this.destroyed){var r=this.pageCache[e.pageNum-1],i=r.intentStates[e.intent];if(!i.displayReadyCapability)throw new Error(e.error);if(i.displayReadyCapability.reject(e.error),i.operatorList){i.operatorList.lastChunk=!0;for(var n=0;n<i.renderTasks.length;n++)i.renderTasks[n].operatorListChanged()}}},this),e.on("UnsupportedFeature",function t(e){if(!this.destroyed){var r=e.featureId,i=this.loadingTask;i.onUnsupportedFeature&&i.onUnsupportedFeature(r),L.notify(r)}},this),e.on("JpegDecode",function(t){if(this.destroyed)return Promise.reject(new Error("Worker was destroyed"));if("undefined"==typeof document)return Promise.reject(new Error('"document" is not defined.'));var e=t[0],r=t[1];return 3!==r&&1!==r?Promise.reject(new Error("Only 3 components or 1 component can be returned")):new Promise(function(t,i){var n=new Image;n.onload=function(){var e=n.width,i=n.height,o=e*i,a=4*o,s=new Uint8Array(o*r),c=document.createElement("canvas");c.width=e,c.height=i;var l=c.getContext("2d");l.drawImage(n,0,0);var h=l.getImageData(0,0,e,i).data,u,f;if(3===r)for(u=0,f=0;u<a;u+=4,f+=3)s[f]=h[u],s[f+1]=h[u+1],s[f+2]=h[u+2];else if(1===r)for(u=0,f=0;u<a;u+=4,f++)s[f]=h[u];t({data:s,width:e,height:i})},n.onerror=function(){i(new Error("JpegDecode failed to load image"))},n.src=e})},this),e.on("FetchBuiltInCMap",function(t){return this.destroyed?Promise.reject(new Error("Worker was destroyed")):this.CMapReaderFactory.fetch({name:t.name})},this)},getData:function t(){return this.messageHandler.sendWithPromise("GetData",null)},getPage:function t(e,r){var i=this;if(!(0,l.isInt)(e)||e<=0||e>this.numPages)return Promise.reject(new Error("Invalid page request"));var n=e-1;if(n in this.pagePromises)return this.pagePromises[n];var o=this.messageHandler.sendWithPromise("GetPage",{pageIndex:n}).then(function(t){if(i.destroyed)throw new Error("Transport destroyed");var e=new A(n,t,i);return i.pageCache[n]=e,e});return this.pagePromises[n]=o,o},getPageIndex:function t(e){return this.messageHandler.sendWithPromise("GetPageIndex",{ref:e}).catch(function(t){return Promise.reject(new Error(t))})},getAnnotations:function t(e,r){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:e,intent:r})},getDestinations:function t(){return this.messageHandler.sendWithPromise("GetDestinations",null)},getDestination:function t(e){return this.messageHandler.sendWithPromise("GetDestination",{id:e})},getPageLabels:function t(){return this.messageHandler.sendWithPromise("GetPageLabels",null)},getPageMode:function t(){return this.messageHandler.sendWithPromise("GetPageMode",null)},getAttachments:function t(){return this.messageHandler.sendWithPromise("GetAttachments",null)},getJavaScript:function t(){return this.messageHandler.sendWithPromise("GetJavaScript",null)},getOutline:function t(){return this.messageHandler.sendWithPromise("GetOutline",null)},getMetadata:function t(){return this.messageHandler.sendWithPromise("GetMetadata",null).then(function t(e){return{info:e[0],metadata:e[1]?new d.Metadata(e[1]):null}})},getStats:function t(){return this.messageHandler.sendWithPromise("GetStats",null)},startCleanup:function t(){var e=this;this.messageHandler.sendWithPromise("Cleanup",null).then(function(){for(var t=0,r=e.pageCache.length;t<r;t++){var i=e.pageCache[t];i&&i.cleanup()}e.commonObjs.clear(),e.fontLoader.clear()})}},e}(),E=function t(){function e(){this.objs=Object.create(null)}return e.prototype={ensureObj:function t(e){if(this.objs[e])return this.objs[e];var r={capability:(0,l.createPromiseCapability)(),data:null,resolved:!1};return this.objs[e]=r,r},get:function t(e,r){if(r)return this.ensureObj(e).capability.promise.then(r),null;var i=this.objs[e];if(!i||!i.resolved)throw new Error("Requesting object that isn't resolved yet "+e);return i.data},resolve:function t(e,r){var i=this.ensureObj(e);i.resolved=!0,i.data=r,i.capability.resolve(r)},isResolved:function t(e){var r=this.objs;return!!r[e]&&r[e].resolved},hasData:function t(e){return this.isResolved(e)},getData:function t(e){var r=this.objs;return r[e]&&r[e].resolved?r[e].data:null},clear:function t(){this.objs=Object.create(null)}},e}(),O=function t(){function e(t){this._internalRenderTask=t,this.onContinue=null}return e.prototype={get promise(){return this._internalRenderTask.capability.promise},cancel:function t(){this._internalRenderTask.cancel()},then:function t(e,r){return this.promise.then.apply(this.promise,arguments)}},e}(),R=function t(){function e(t,e,r,i,n,o,a){this.callback=t,this.params=e,this.objs=r,this.commonObjs=i,this.operatorListIdx=null,this.operatorList=n,this.pageNumber=o,this.canvasFactory=a,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this.useRequestAnimationFrame=!1,this.cancelled=!1,this.capability=(0,l.createPromiseCapability)(),this.task=new O(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=e.canvasContext.canvas}var r=new WeakMap;return e.prototype={initializeGraphics:function t(e){if(this._canvas){if(r.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");r.set(this._canvas,this)}if(!this.cancelled){(0,h.getDefaultSetting)("pdfBug")&&l.globalScope.StepperManager&&l.globalScope.StepperManager.enabled&&(this.stepper=l.globalScope.StepperManager.create(this.pageNumber-1),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());var i=this.params;this.gfx=new f.CanvasGraphics(i.canvasContext,this.commonObjs,this.objs,this.canvasFactory,i.imageLayer),this.gfx.beginDrawing({transform:i.transform,viewport:i.viewport,transparency:e,background:i.background}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback&&this.graphicsReadyCallback()}},cancel:function t(){this.running=!1,this.cancelled=!0,this._canvas&&r.delete(this._canvas),(0,h.getDefaultSetting)("pdfjsNext")?this.callback(new h.RenderingCancelledException("Rendering cancelled, page "+this.pageNumber,"canvas")):this.callback("cancelled")},operatorListChanged:function t(){if(!this.graphicsReady)return void(this.graphicsReadyCallback||(this.graphicsReadyCallback=this._continueBound));this.stepper&&this.stepper.updateOperatorList(this.operatorList),this.running||this._continue()},_continue:function t(){this.running=!0,this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())},_scheduleNext:function t(){this.useRequestAnimationFrame&&"undefined"!=typeof window?window.requestAnimationFrame(this._nextBound):Promise.resolve(void 0).then(this._nextBound)},_next:function t(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),this._canvas&&r.delete(this._canvas),this.callback())))}},e}(),L=function t(){var e=[];return{listen:function t(r){(0,l.deprecated)("Global UnsupportedManager.listen is used: use PDFDocumentLoadingTask.onUnsupportedFeature instead"),e.push(r)},notify:function t(r){for(var i=0,n=e.length;i<n;i++)e[i](r)}}}(),D,I;e.version=D="1.8.575",e.build=I="bd8c1211",e.getDocument=o,e.LoopbackPort=T,e.PDFDataRangeTransport=x,e.PDFWorker=k,e.PDFDocumentProxy=C,e.PDFPageProxy=A,e._UnsupportedManager=L,e.version=D,e.build=I},function(t,e,o){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.SVGGraphics=void 0;var a=o(0),s=function t(){throw new Error("Not implemented: SVGGraphics")},c={fontStyle:"normal",fontWeight:"normal",fillColor:"#000000"},l=function t(){function e(t,e,r){for(var i=-1,n=e;n<r;n++){var o=255&(i^t[n]);i=i>>>8^d[o]}return-1^i}function o(t,r,i,n){var o=n,a=r.length;i[o]=a>>24&255,i[o+1]=a>>16&255,i[o+2]=a>>8&255,i[o+3]=255&a,o+=4,i[o]=255&t.charCodeAt(0),i[o+1]=255&t.charCodeAt(1),i[o+2]=255&t.charCodeAt(2),i[o+3]=255&t.charCodeAt(3),o+=4,i.set(r,o),o+=r.length;var s=e(i,n+4,o);i[o]=s>>24&255,i[o+1]=s>>16&255,i[o+2]=s>>8&255,i[o+3]=255&s}function s(t,e,r){for(var i=1,n=0,o=e;o<r;++o)i=(i+(255&t[o]))%65521,n=(n+i)%65521;return n<<16|i}function c(t){if(!(0,a.isNodeJS)())return l(t);try{var e;e=parseInt(i.versions.node)>=8?t:new n(t);var o=r(42).deflateSync(e,{level:9});return o instanceof Uint8Array?o:new Uint8Array(o)}catch(t){(0,a.warn)("Not compressing PNG because zlib.deflateSync is unavailable: "+t)}return l(t)}function l(t){var e=t.length,r=65535,i=Math.ceil(e/65535),n=new Uint8Array(2+e+5*i+4),o=0;n[o++]=120,n[o++]=156;for(var a=0;e>65535;)n[o++]=0,n[o++]=255,n[o++]=255,n[o++]=0,n[o++]=0,n.set(t.subarray(a,a+65535),o),o+=65535,a+=65535,e-=65535;n[o++]=1,n[o++]=255&e,n[o++]=e>>8&255,n[o++]=255&~e,n[o++]=(65535&~e)>>8&255,n.set(t.subarray(a),o),o+=t.length-a;var c=s(t,0,t.length);return n[o++]=c>>24&255,n[o++]=c>>16&255,n[o++]=c>>8&255,n[o++]=255&c,n}function h(t,e,r){var i=t.width,n=t.height,s,l,h,d=t.data;switch(e){case a.ImageKind.GRAYSCALE_1BPP:l=0,s=1,h=i+7>>3;break;case a.ImageKind.RGB_24BPP:l=2,s=8,h=3*i;break;case a.ImageKind.RGBA_32BPP:l=6,s=8,h=4*i;break;default:throw new Error("invalid format")}var p=new Uint8Array((1+h)*n),g=0,v=0,m,b;for(m=0;m<n;++m)p[g++]=0,p.set(d.subarray(v,v+h),g),v+=h,g+=h;if(e===a.ImageKind.GRAYSCALE_1BPP)for(g=0,m=0;m<n;m++)for(g++,b=0;b<h;b++)p[g++]^=255;var y=new Uint8Array([i>>24&255,i>>16&255,i>>8&255,255&i,n>>24&255,n>>16&255,n>>8&255,255&n,s,l,0,0,0]),_=c(p),w=u.length+3*f+y.length+_.length,S=new Uint8Array(w),x=0;return S.set(u,x),x+=u.length,o("IHDR",y,S,x),x+=f+y.length,o("IDATA",_,S,x),x+=f+_.length,o("IEND",new Uint8Array(0),S,x),(0,a.createObjectURL)(S,"image/png",r)}for(var u=new Uint8Array([137,80,78,71,13,10,26,10]),f=12,d=new Int32Array(256),p=0;p<256;p++){for(var g=p,v=0;v<8;v++)g=1&g?3988292384^g>>1&2147483647:g>>1&2147483647;d[p]=g}return function t(e,r){return h(e,void 0===e.kind?a.ImageKind.GRAYSCALE_1BPP:e.kind,r)}}(),h=function t(){function e(){this.fontSizeScale=1,this.fontWeight=c.fontWeight,this.fontSize=0,this.textMatrix=a.IDENTITY_MATRIX,this.fontMatrix=a.FONT_IDENTITY_MATRIX,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRise=0,this.fillColor=c.fillColor,this.strokeColor="#000000",this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.lineJoin="",this.lineCap="",this.miterLimit=0,this.dashArray=[],this.dashPhase=0,this.dependencies=[],this.activeClipUrl=null,this.clipGroup=null,this.maskId=""}return e.prototype={clone:function t(){return Object.create(this)},setCurrentPoint:function t(e,r){this.x=e,this.y=r}},e}();e.SVGGraphics=s=function t(){function e(t){for(var e=[],r=[],i=t.length,n=0;n<i;n++)"save"!==t[n].fn?"restore"===t[n].fn?e=r.pop():e.push(t[n]):(e.push({fnId:92,fn:"group",items:[]}),r.push(e),e=e[e.length-1].items);return e}function r(t){if(t===(0|t))return t.toString();var e=t.toFixed(10),r=e.length-1;if("0"!==e[r])return e;do{r--}while("0"===e[r]);return e.substr(0,"."===e[r]?r:r+1)}function i(t){if(0===t[4]&&0===t[5]){if(0===t[1]&&0===t[2])return 1===t[0]&&1===t[3]?"":"scale("+r(t[0])+" "+r(t[3])+")";if(t[0]===t[3]&&t[1]===-t[2]){return"rotate("+r(180*Math.acos(t[0])/Math.PI)+")"}}else if(1===t[0]&&0===t[1]&&0===t[2]&&1===t[3])return"translate("+r(t[4])+" "+r(t[5])+")";return"matrix("+r(t[0])+" "+r(t[1])+" "+r(t[2])+" "+r(t[3])+" "+r(t[4])+" "+r(t[5])+")"}function n(t,e,r){this.current=new h,this.transformMatrix=a.IDENTITY_MATRIX,this.transformStack=[],this.extraStack=[],this.commonObjs=t,this.objs=e,this.pendingClip=null,this.pendingEOFill=!1,this.embedFonts=!1,this.embeddedFonts=Object.create(null),this.cssStyle=null,this.forceDataSchema=!!r}var o="http://www.w3.org/2000/svg",s="http://www.w3.org/1999/xlink",u=["butt","round","square"],f=["miter","round","bevel"],d=0,p=0;return n.prototype={save:function t(){this.transformStack.push(this.transformMatrix);var e=this.current;this.extraStack.push(e),this.current=e.clone()},restore:function t(){this.transformMatrix=this.transformStack.pop(),this.current=this.extraStack.pop(),this.pendingClip=null,this.tgrp=null},group:function t(e){this.save(),this.executeOpTree(e),this.restore()},loadDependencies:function t(e){for(var r=this,i=e.fnArray,n=i.length,o=e.argsArray,s=0;s<n;s++)if(a.OPS.dependency===i[s])for(var c=o[s],l=0,h=c.length;l<h;l++){var u=c[l],f="g_"===u.substring(0,2),d;d=f?new Promise(function(t){r.commonObjs.get(u,t)}):new Promise(function(t){r.objs.get(u,t)}),this.current.dependencies.push(d)}return Promise.all(this.current.dependencies)},transform:function t(e,r,i,n,o,s){var c=[e,r,i,n,o,s];this.transformMatrix=a.Util.transform(this.transformMatrix,c),this.tgrp=null},getSVG:function t(e,r){var i=this;this.viewport=r;var n=this._initialize(r);return this.loadDependencies(e).then(function(){i.transformMatrix=a.IDENTITY_MATRIX;var t=i.convertOpList(e);return i.executeOpTree(t),n})},convertOpList:function t(r){var i=r.argsArray,n=r.fnArray,o=n.length,s=[],c=[];for(var l in a.OPS)s[a.OPS[l]]=l;for(var h=0;h<o;h++){var u=n[h];c.push({fnId:u,fn:s[u],args:i[h]})}return e(c)},executeOpTree:function t(e){for(var r=e.length,i=0;i<r;i++){var n=e[i].fn,o=e[i].fnId,s=e[i].args;switch(0|o){case a.OPS.beginText:this.beginText();break;case a.OPS.setLeading:this.setLeading(s);break;case a.OPS.setLeadingMoveText:this.setLeadingMoveText(s[0],s[1]);break;case a.OPS.setFont:this.setFont(s);break;case a.OPS.showText:case a.OPS.showSpacedText:this.showText(s[0]);break;case a.OPS.endText:this.endText();break;case a.OPS.moveText:this.moveText(s[0],s[1]);break;case a.OPS.setCharSpacing:this.setCharSpacing(s[0]);break;case a.OPS.setWordSpacing:this.setWordSpacing(s[0]);break;case a.OPS.setHScale:this.setHScale(s[0]);break;case a.OPS.setTextMatrix:this.setTextMatrix(s[0],s[1],s[2],s[3],s[4],s[5]);break;case a.OPS.setLineWidth:this.setLineWidth(s[0]);break;case a.OPS.setLineJoin:this.setLineJoin(s[0]);break;case a.OPS.setLineCap:this.setLineCap(s[0]);break;case a.OPS.setMiterLimit:this.setMiterLimit(s[0]);break;case a.OPS.setFillRGBColor:this.setFillRGBColor(s[0],s[1],s[2]);break;case a.OPS.setStrokeRGBColor:this.setStrokeRGBColor(s[0],s[1],s[2]);break;case a.OPS.setDash:this.setDash(s[0],s[1]);break;case a.OPS.setGState:this.setGState(s[0]);break;case a.OPS.fill:this.fill();break;case a.OPS.eoFill:this.eoFill();break;case a.OPS.stroke:this.stroke();break;case a.OPS.fillStroke:this.fillStroke();break;case a.OPS.eoFillStroke:this.eoFillStroke();break;case a.OPS.clip:this.clip("nonzero");break;case a.OPS.eoClip:this.clip("evenodd");break;case a.OPS.paintSolidColorImageMask:this.paintSolidColorImageMask();break;case a.OPS.paintJpegXObject:this.paintJpegXObject(s[0],s[1],s[2]);break;case a.OPS.paintImageXObject:this.paintImageXObject(s[0]);break;case a.OPS.paintInlineImageXObject:this.paintInlineImageXObject(s[0]);break;case a.OPS.paintImageMaskXObject:this.paintImageMaskXObject(s[0]);break;case a.OPS.paintFormXObjectBegin:this.paintFormXObjectBegin(s[0],s[1]);break;case a.OPS.paintFormXObjectEnd:this.paintFormXObjectEnd();break;case a.OPS.closePath:this.closePath();break;case a.OPS.closeStroke:this.closeStroke();break;case a.OPS.closeFillStroke:this.closeFillStroke();break;case a.OPS.nextLine:this.nextLine();break;case a.OPS.transform:this.transform(s[0],s[1],s[2],s[3],s[4],s[5]);break;case a.OPS.constructPath:this.constructPath(s[0],s[1]);break;case a.OPS.endPath:this.endPath();break;case 92:this.group(e[i].items);break;default:(0,a.warn)("Unimplemented operator "+n)}}},setWordSpacing:function t(e){this.current.wordSpacing=e},setCharSpacing:function t(e){this.current.charSpacing=e},nextLine:function t(){this.moveText(0,this.current.leading)},setTextMatrix:function t(e,i,n,a,s,c){var l=this.current;this.current.textMatrix=this.current.lineMatrix=[e,i,n,a,s,c],this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0,l.xcoords=[],l.tspan=document.createElementNS(o,"svg:tspan"),l.tspan.setAttributeNS(null,"font-family",l.fontFamily),l.tspan.setAttributeNS(null,"font-size",r(l.fontSize)+"px"),l.tspan.setAttributeNS(null,"y",r(-l.y)),l.txtElement=document.createElementNS(o,"svg:text"),l.txtElement.appendChild(l.tspan)},beginText:function t(){this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0,this.current.textMatrix=a.IDENTITY_MATRIX,this.current.lineMatrix=a.IDENTITY_MATRIX,this.current.tspan=document.createElementNS(o,"svg:tspan"),this.current.txtElement=document.createElementNS(o,"svg:text"),this.current.txtgrp=document.createElementNS(o,"svg:g"),this.current.xcoords=[]},moveText:function t(e,i){var n=this.current;this.current.x=this.current.lineX+=e,this.current.y=this.current.lineY+=i,n.xcoords=[],n.tspan=document.createElementNS(o,"svg:tspan"),n.tspan.setAttributeNS(null,"font-family",n.fontFamily),n.tspan.setAttributeNS(null,"font-size",r(n.fontSize)+"px"),n.tspan.setAttributeNS(null,"y",r(-n.y))},showText:function t(e){var n=this.current,o=n.font,s=n.fontSize;if(0!==s){var l=n.charSpacing,h=n.wordSpacing,u=n.fontDirection,f=n.textHScale*u,d=e.length,p=o.vertical,g=s*n.fontMatrix[0],v=0,m;for(m=0;m<d;++m){var b=e[m];if(null!==b)if((0,a.isNum)(b))v+=-b*s*.001;else{n.xcoords.push(n.x+v*f);var y=b.width,_=b.fontChar,w=(b.isSpace?h:0)+l,S=y*g+w*u;v+=S,n.tspan.textContent+=_}else v+=u*h}p?n.y-=v*f:n.x+=v*f,n.tspan.setAttributeNS(null,"x",n.xcoords.map(r).join(" ")),n.tspan.setAttributeNS(null,"y",r(-n.y)),n.tspan.setAttributeNS(null,"font-family",n.fontFamily),n.tspan.setAttributeNS(null,"font-size",r(n.fontSize)+"px"),n.fontStyle!==c.fontStyle&&n.tspan.setAttributeNS(null,"font-style",n.fontStyle),n.fontWeight!==c.fontWeight&&n.tspan.setAttributeNS(null,"font-weight",n.fontWeight),n.fillColor!==c.fillColor&&n.tspan.setAttributeNS(null,"fill",n.fillColor),n.txtElement.setAttributeNS(null,"transform",i(n.textMatrix)+" scale(1, -1)"),n.txtElement.setAttributeNS("http://www.w3.org/XML/1998/namespace","xml:space","preserve"),n.txtElement.appendChild(n.tspan),n.txtgrp.appendChild(n.txtElement),this._ensureTransformGroup().appendChild(n.txtElement)}},setLeadingMoveText:function t(e,r){this.setLeading(-r),this.moveText(e,r)},addFontStyle:function t(e){this.cssStyle||(this.cssStyle=document.createElementNS(o,"svg:style"),this.cssStyle.setAttributeNS(null,"type","text/css"),this.defs.appendChild(this.cssStyle));var r=(0,a.createObjectURL)(e.data,e.mimetype,this.forceDataSchema);this.cssStyle.textContent+='@font-face { font-family: "'+e.loadedName+'"; src: url('+r+"); }\n"},setFont:function t(e){var i=this.current,n=this.commonObjs.get(e[0]),s=e[1];this.current.font=n,this.embedFonts&&n.data&&!this.embeddedFonts[n.loadedName]&&(this.addFontStyle(n),this.embeddedFonts[n.loadedName]=n),i.fontMatrix=n.fontMatrix?n.fontMatrix:a.FONT_IDENTITY_MATRIX;var c=n.black?n.bold?"bolder":"bold":n.bold?"bold":"normal",l=n.italic?"italic":"normal";s<0?(s=-s,i.fontDirection=-1):i.fontDirection=1,i.fontSize=s,i.fontFamily=n.loadedName,i.fontWeight=c,i.fontStyle=l,i.tspan=document.createElementNS(o,"svg:tspan"),i.tspan.setAttributeNS(null,"y",r(-i.y)),i.xcoords=[]},endText:function t(){},setLineWidth:function t(e){this.current.lineWidth=e},setLineCap:function t(e){this.current.lineCap=u[e]},setLineJoin:function t(e){this.current.lineJoin=f[e]},setMiterLimit:function t(e){this.current.miterLimit=e},setStrokeAlpha:function t(e){this.current.strokeAlpha=e},setStrokeRGBColor:function t(e,r,i){var n=a.Util.makeCssRgb(e,r,i);this.current.strokeColor=n},setFillAlpha:function t(e){this.current.fillAlpha=e},setFillRGBColor:function t(e,r,i){var n=a.Util.makeCssRgb(e,r,i);this.current.fillColor=n,this.current.tspan=document.createElementNS(o,"svg:tspan"),this.current.xcoords=[]},setDash:function t(e,r){this.current.dashArray=e,this.current.dashPhase=r},constructPath:function t(e,i){var n=this.current,s=n.x,c=n.y;n.path=document.createElementNS(o,"svg:path");for(var l=[],h=e.length,u=0,f=0;u<h;u++)switch(0|e[u]){case a.OPS.rectangle:s=i[f++],c=i[f++];var d=i[f++],p=i[f++],g=s+d,v=c+p;l.push("M",r(s),r(c),"L",r(g),r(c),"L",r(g),r(v),"L",r(s),r(v),"Z");break;case a.OPS.moveTo:s=i[f++],c=i[f++],l.push("M",r(s),r(c));break;case a.OPS.lineTo:s=i[f++],c=i[f++],l.push("L",r(s),r(c));break;case a.OPS.curveTo:s=i[f+4],c=i[f+5],l.push("C",r(i[f]),r(i[f+1]),r(i[f+2]),r(i[f+3]),r(s),r(c)),f+=6;break;case a.OPS.curveTo2:s=i[f+2],c=i[f+3],l.push("C",r(s),r(c),r(i[f]),r(i[f+1]),r(i[f+2]),r(i[f+3])),f+=4;break;case a.OPS.curveTo3:s=i[f+2],c=i[f+3],l.push("C",r(i[f]),r(i[f+1]),r(s),r(c),r(s),r(c)),f+=4;break;case a.OPS.closePath:l.push("Z")}n.path.setAttributeNS(null,"d",l.join(" ")),n.path.setAttributeNS(null,"fill","none"),this._ensureTransformGroup().appendChild(n.path),n.element=n.path,n.setCurrentPoint(s,c)},endPath:function t(){if(this.pendingClip){var e=this.current,r="clippath"+d;d++;var n=document.createElementNS(o,"svg:clipPath");n.setAttributeNS(null,"id",r),n.setAttributeNS(null,"transform",i(this.transformMatrix));var a=e.element.cloneNode();"evenodd"===this.pendingClip?a.setAttributeNS(null,"clip-rule","evenodd"):a.setAttributeNS(null,"clip-rule","nonzero"),this.pendingClip=null,n.appendChild(a),this.defs.appendChild(n),e.activeClipUrl&&(e.clipGroup=null,this.extraStack.forEach(function(t){t.clipGroup=null})),e.activeClipUrl="url(#"+r+")",this.tgrp=null}},clip:function t(e){this.pendingClip=e},closePath:function t(){var e=this.current,r=e.path.getAttributeNS(null,"d");r+="Z",e.path.setAttributeNS(null,"d",r)},setLeading:function t(e){this.current.leading=-e},setTextRise:function t(e){this.current.textRise=e},setHScale:function t(e){this.current.textHScale=e/100},setGState:function t(e){for(var r=0,i=e.length;r<i;r++){var n=e[r],o=n[0],s=n[1];switch(o){case"LW":this.setLineWidth(s);break;case"LC":this.setLineCap(s);break;case"LJ":this.setLineJoin(s);break;case"ML":this.setMiterLimit(s);break;case"D":this.setDash(s[0],s[1]);break;case"Font":this.setFont(s);break;case"CA":this.setStrokeAlpha(s);break;case"ca":this.setFillAlpha(s);break;default:(0,a.warn)("Unimplemented graphic state "+o)}}},fill:function t(){var e=this.current;e.element.setAttributeNS(null,"fill",e.fillColor),e.element.setAttributeNS(null,"fill-opacity",e.fillAlpha)},stroke:function t(){var e=this.current;e.element.setAttributeNS(null,"stroke",e.strokeColor),e.element.setAttributeNS(null,"stroke-opacity",e.strokeAlpha),e.element.setAttributeNS(null,"stroke-miterlimit",r(e.miterLimit)),e.element.setAttributeNS(null,"stroke-linecap",e.lineCap),e.element.setAttributeNS(null,"stroke-linejoin",e.lineJoin),e.element.setAttributeNS(null,"stroke-width",r(e.lineWidth)+"px"),e.element.setAttributeNS(null,"stroke-dasharray",e.dashArray.map(r).join(" ")),e.element.setAttributeNS(null,"stroke-dashoffset",r(e.dashPhase)+"px"),e.element.setAttributeNS(null,"fill","none")},eoFill:function t(){this.current.element.setAttributeNS(null,"fill-rule","evenodd"),this.fill()},fillStroke:function t(){this.stroke(),this.fill()},eoFillStroke:function t(){this.current.element.setAttributeNS(null,"fill-rule","evenodd"),this.fillStroke()},closeStroke:function t(){this.closePath(),this.stroke()},closeFillStroke:function t(){this.closePath(),this.fillStroke()},paintSolidColorImageMask:function t(){var e=this.current,r=document.createElementNS(o,"svg:rect");r.setAttributeNS(null,"x","0"),r.setAttributeNS(null,"y","0"),r.setAttributeNS(null,"width","1px"),r.setAttributeNS(null,"height","1px"),r.setAttributeNS(null,"fill",e.fillColor),this._ensureTransformGroup().appendChild(r)},paintJpegXObject:function t(e,i,n){var a=this.objs.get(e),c=document.createElementNS(o,"svg:image");c.setAttributeNS(s,"xlink:href",a.src),c.setAttributeNS(null,"width",r(i)),c.setAttributeNS(null,"height",r(n)),c.setAttributeNS(null,"x","0"),c.setAttributeNS(null,"y",r(-n)),c.setAttributeNS(null,"transform","scale("+r(1/i)+" "+r(-1/n)+")"),this._ensureTransformGroup().appendChild(c)},paintImageXObject:function t(e){var r=this.objs.get(e);if(!r)return void(0,a.warn)("Dependent image isn't ready yet");this.paintInlineImageXObject(r)},paintInlineImageXObject:function t(e,i){var n=e.width,a=e.height,c=l(e,this.forceDataSchema),h=document.createElementNS(o,"svg:rect");h.setAttributeNS(null,"x","0"),h.setAttributeNS(null,"y","0"),h.setAttributeNS(null,"width",r(n)),h.setAttributeNS(null,"height",r(a)),this.current.element=h,this.clip("nonzero");var u=document.createElementNS(o,"svg:image");u.setAttributeNS(s,"xlink:href",c),u.setAttributeNS(null,"x","0"),u.setAttributeNS(null,"y",r(-a)),u.setAttributeNS(null,"width",r(n)+"px"),u.setAttributeNS(null,"height",r(a)+"px"),u.setAttributeNS(null,"transform","scale("+r(1/n)+" "+r(-1/a)+")"),i?i.appendChild(u):this._ensureTransformGroup().appendChild(u)},paintImageMaskXObject:function t(e){var i=this.current,n=e.width,a=e.height,s=i.fillColor;i.maskId="mask"+p++;var c=document.createElementNS(o,"svg:mask");c.setAttributeNS(null,"id",i.maskId);var l=document.createElementNS(o,"svg:rect");l.setAttributeNS(null,"x","0"),l.setAttributeNS(null,"y","0"),l.setAttributeNS(null,"width",r(n)),l.setAttributeNS(null,"height",r(a)),l.setAttributeNS(null,"fill",s),l.setAttributeNS(null,"mask","url(#"+i.maskId+")"),this.defs.appendChild(c),this._ensureTransformGroup().appendChild(l),this.paintInlineImageXObject(e,c)},paintFormXObjectBegin:function t(e,i){if((0,a.isArray)(e)&&6===e.length&&this.transform(e[0],e[1],e[2],e[3],e[4],e[5]),(0,a.isArray)(i)&&4===i.length){var n=i[2]-i[0],s=i[3]-i[1],c=document.createElementNS(o,"svg:rect");c.setAttributeNS(null,"x",i[0]),c.setAttributeNS(null,"y",i[1]),c.setAttributeNS(null,"width",r(n)),c.setAttributeNS(null,"height",r(s)),this.current.element=c,this.clip("nonzero"),this.endPath()}},paintFormXObjectEnd:function t(){},_initialize:function t(e){var r=document.createElementNS(o,"svg:svg");r.setAttributeNS(null,"version","1.1"),r.setAttributeNS(null,"width",e.width+"px"),r.setAttributeNS(null,"height",e.height+"px"),r.setAttributeNS(null,"preserveAspectRatio","none"),r.setAttributeNS(null,"viewBox","0 0 "+e.width+" "+e.height);var n=document.createElementNS(o,"svg:defs");r.appendChild(n),this.defs=n;var a=document.createElementNS(o,"svg:g");return a.setAttributeNS(null,"transform",i(e.transform)),r.appendChild(a),this.svg=a,r},_ensureClipGroup:function t(){if(!this.current.clipGroup){var e=document.createElementNS(o,"svg:g");e.setAttributeNS(null,"clip-path",this.current.activeClipUrl),this.svg.appendChild(e),this.current.clipGroup=e}return this.current.clipGroup},_ensureTransformGroup:function t(){return this.tgrp||(this.tgrp=document.createElementNS(o,"svg:g"),this.tgrp.setAttributeNS(null,"transform",i(this.transformMatrix)),this.current.activeClipUrl?this._ensureClipGroup().appendChild(this.tgrp):this.svg.appendChild(this.tgrp)),this.tgrp}},n}(),e.SVGGraphics=s},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.renderTextLayer=void 0;var i=r(0),n=r(1),o=function t(){function e(t){return!f.test(t)}function r(t,r,o){var a=document.createElement("div"),s={style:null,angle:0,canvasWidth:0,isWhitespace:!1,originalTransform:null,paddingBottom:0,paddingLeft:0,paddingRight:0,paddingTop:0,scale:1};if(t._textDivs.push(a),e(r.str))return s.isWhitespace=!0,void t._textDivProperties.set(a,s);var c=i.Util.transform(t._viewport.transform,r.transform),l=Math.atan2(c[1],c[0]),h=o[r.fontName];h.vertical&&(l+=Math.PI/2);var u=Math.sqrt(c[2]*c[2]+c[3]*c[3]),f=u;h.ascent?f=h.ascent*f:h.descent&&(f=(1+h.descent)*f);var p,g;if(0===l?(p=c[4],g=c[5]-f):(p=c[4]+f*Math.sin(l),g=c[5]-f*Math.cos(l)),d[1]=p,d[3]=g,d[5]=u,d[7]=h.fontFamily,s.style=d.join(""),a.setAttribute("style",s.style),a.textContent=r.str,(0,n.getDefaultSetting)("pdfBug")&&(a.dataset.fontName=r.fontName),0!==l&&(s.angle=l*(180/Math.PI)),r.str.length>1&&(h.vertical?s.canvasWidth=r.height*t._viewport.scale:s.canvasWidth=r.width*t._viewport.scale),t._textDivProperties.set(a,s),t._textContentStream&&t._layoutText(a),t._enhanceTextSelection){var v=1,m=0;0!==l&&(v=Math.cos(l),m=Math.sin(l));var b=(h.vertical?r.height:r.width)*t._viewport.scale,y=u,_,w;0!==l?(_=[v,m,-m,v,p,g],w=i.Util.getAxialAlignedBoundingBox([0,0,b,y],_)):w=[p,g,p+b,g+y],t._bounds.push({left:w[0],top:w[1],right:w[2],bottom:w[3],div:a,size:[b,y],m:_})}}function o(t){if(!t._canceled){var e=t._textDivs,r=t._capability,i=e.length;if(i>u)return t._renderingDone=!0,void r.resolve();if(!t._textContentStream)for(var n=0;n<i;n++)t._layoutText(e[n]);t._renderingDone=!0,r.resolve()}}function a(t){for(var e=t._bounds,r=t._viewport,n=s(r.width,r.height,e),o=0;o<n.length;o++){var a=e[o].div,c=t._textDivProperties.get(a);if(0!==c.angle){var l=n[o],h=e[o],u=h.m,f=u[0],d=u[1],p=[[0,0],[0,h.size[1]],[h.size[0],0],h.size],g=new Float64Array(64);p.forEach(function(t,e){var r=i.Util.applyTransform(t,u);g[e+0]=f&&(l.left-r[0])/f,g[e+4]=d&&(l.top-r[1])/d,g[e+8]=f&&(l.right-r[0])/f,g[e+12]=d&&(l.bottom-r[1])/d,g[e+16]=d&&(l.left-r[0])/-d,g[e+20]=f&&(l.top-r[1])/f,g[e+24]=d&&(l.right-r[0])/-d,g[e+28]=f&&(l.bottom-r[1])/f,g[e+32]=f&&(l.left-r[0])/-f,g[e+36]=d&&(l.top-r[1])/-d,g[e+40]=f&&(l.right-r[0])/-f,g[e+44]=d&&(l.bottom-r[1])/-d,g[e+48]=d&&(l.left-r[0])/d,g[e+52]=f&&(l.top-r[1])/-f,g[e+56]=d&&(l.right-r[0])/d,g[e+60]=f&&(l.bottom-r[1])/-f});var v=function t(e,r,i){for(var n=0,o=0;o<i;o++){var a=e[r++];a>0&&(n=n?Math.min(a,n):a)}return n},m=1+Math.min(Math.abs(f),Math.abs(d));c.paddingLeft=v(g,32,16)/m,c.paddingTop=v(g,48,16)/m,c.paddingRight=v(g,0,16)/m,c.paddingBottom=v(g,16,16)/m,t._textDivProperties.set(a,c)}else c.paddingLeft=e[o].left-n[o].left,c.paddingTop=e[o].top-n[o].top,c.paddingRight=n[o].right-e[o].right,c.paddingBottom=n[o].bottom-e[o].bottom,t._textDivProperties.set(a,c)}}function s(t,e,r){var i=r.map(function(t,e){return{x1:t.left,y1:t.top,x2:t.right,y2:t.bottom,index:e,x1New:void 0,x2New:void 0}});c(t,i);var n=new Array(r.length);return i.forEach(function(t){var e=t.index;n[e]={left:t.x1New,top:0,right:t.x2New,bottom:0}}),r.map(function(e,r){var o=n[r],a=i[r];a.x1=e.top,a.y1=t-o.right,a.x2=e.bottom,a.y2=t-o.left,a.index=r,a.x1New=void 0,a.x2New=void 0}),c(e,i),i.forEach(function(t){var e=t.index;n[e].top=t.x1New,n[e].bottom=t.x2New}),n}function c(t,e){e.sort(function(t,e){return t.x1-e.x1||t.index-e.index});var r={x1:-1/0,y1:-1/0,x2:0,y2:1/0,index:-1,x1New:0,x2New:0},i=[{start:-1/0,end:1/0,boundary:r}];e.forEach(function(t){for(var e=0;e<i.length&&i[e].end<=t.y1;)e++;for(var r=i.length-1;r>=0&&i[r].start>=t.y2;)r--;var n,o,a,s,c=-1/0;for(a=e;a<=r;a++){n=i[a],o=n.boundary;var l;l=o.x2>t.x1?o.index>t.index?o.x1New:t.x1:void 0===o.x2New?(o.x2+t.x1)/2:o.x2New,l>c&&(c=l)}for(t.x1New=c,a=e;a<=r;a++)n=i[a],o=n.boundary,void 0===o.x2New?o.x2>t.x1?o.index>t.index&&(o.x2New=o.x2):o.x2New=c:o.x2New>c&&(o.x2New=Math.max(c,o.x2));var h=[],u=null;for(a=e;a<=r;a++){n=i[a],o=n.boundary;var f=o.x2>t.x2?o:t;u===f?h[h.length-1].end=n.end:(h.push({start:n.start,end:n.end,boundary:f}),u=f)}for(i[e].start<t.y1&&(h[0].start=t.y1,h.unshift({start:i[e].start,end:t.y1,boundary:i[e].boundary})),t.y2<i[r].end&&(h[h.length-1].end=t.y2,h.push({start:t.y2,end:i[r].end,boundary:i[r].boundary})),a=e;a<=r;a++)if(n=i[a],o=n.boundary,void 0===o.x2New){var d=!1;for(s=e-1;!d&&s>=0&&i[s].start>=o.y1;s--)d=i[s].boundary===o;for(s=r+1;!d&&s<i.length&&i[s].end<=o.y2;s++)d=i[s].boundary===o;for(s=0;!d&&s<h.length;s++)d=h[s].boundary===o;d||(o.x2New=c)}Array.prototype.splice.apply(i,[e,r-e+1].concat(h))}),i.forEach(function(e){var r=e.boundary;void 0===r.x2New&&(r.x2New=Math.max(t,r.x2))})}function l(t){var e=t.textContent,r=t.textContentStream,n=t.container,o=t.viewport,a=t.textDivs,s=t.textContentItemsStr,c=t.enhanceTextSelection;this._textContent=e,this._textContentStream=r,this._container=n,this._viewport=o,this._textDivs=a||[],this._textContentItemsStr=s||[],this._enhanceTextSelection=!!c,this._reader=null,this._layoutTextLastFontSize=null,this._layoutTextLastFontFamily=null,this._layoutTextCtx=null,this._textDivProperties=new WeakMap,this._renderingDone=!1,this._canceled=!1,this._capability=(0,i.createPromiseCapability)(),this._renderTimer=null,this._bounds=[]}function h(t){var e=new l({textContent:t.textContent,textContentStream:t.textContentStream,container:t.container,viewport:t.viewport,textDivs:t.textDivs,textContentItemsStr:t.textContentItemsStr,enhanceTextSelection:t.enhanceTextSelection});return e._render(t.timeout),e}var u=1e5,f=/\S/,d=["left: ",0,"px; top: ",0,"px; font-size: ",0,"px; font-family: ","",";"];return l.prototype={get promise(){return this._capability.promise},cancel:function t(){this._reader&&(this._reader.cancel(),this._reader=null),this._canceled=!0,null!==this._renderTimer&&(clearTimeout(this._renderTimer),this._renderTimer=null),this._capability.reject("canceled")},_processItems:function t(e,i){for(var n=0,o=e.length;n<o;n++)this._textContentItemsStr.push(e[n].str),r(this,e[n],i)},_layoutText:function t(e){var r=this._container,i=this._textDivProperties.get(e);if(!i.isWhitespace){var o=e.style.fontSize,a=e.style.fontFamily;o===this._layoutTextLastFontSize&&a===this._layoutTextLastFontFamily||(this._layoutTextCtx.font=o+" "+a,this._lastFontSize=o,this._lastFontFamily=a);var s=this._layoutTextCtx.measureText(e.textContent).width,c="";0!==i.canvasWidth&&s>0&&(i.scale=i.canvasWidth/s,c="scaleX("+i.scale+")"),0!==i.angle&&(c="rotate("+i.angle+"deg) "+c),""!==c&&(i.originalTransform=c,n.CustomStyle.setProp("transform",e,c)),this._textDivProperties.set(e,i),r.appendChild(e)}},_render:function t(e){var r=this,n=(0,i.createPromiseCapability)(),a=Object.create(null),s=document.createElement("canvas");if(s.mozOpaque=!0,this._layoutTextCtx=s.getContext("2d",{alpha:!1}),this._textContent){var c=this._textContent.items,l=this._textContent.styles;this._processItems(c,l),n.resolve()}else{if(!this._textContentStream)throw new Error('Neither "textContent" nor "textContentStream" parameters specified.');var h=function t(){r._reader.read().then(function(e){var o=e.value;if(e.done)return void n.resolve();i.Util.extendObj(a,o.styles),r._processItems(o.items,a),t()},n.reject)};this._reader=this._textContentStream.getReader(),h()}n.promise.then(function(){a=null,e?r._renderTimer=setTimeout(function(){o(r),r._renderTimer=null},e):o(r)},this._capability.reject)},expandTextDivs:function t(e){if(this._enhanceTextSelection&&this._renderingDone){null!==this._bounds&&(a(this),this._bounds=null);for(var r=0,i=this._textDivs.length;r<i;r++){var o=this._textDivs[r],s=this._textDivProperties.get(o);if(!s.isWhitespace)if(e){var c="",l="";1!==s.scale&&(c="scaleX("+s.scale+")"),0!==s.angle&&(c="rotate("+s.angle+"deg) "+c),0!==s.paddingLeft&&(l+=" padding-left: "+s.paddingLeft/s.scale+"px;",c+=" translateX("+-s.paddingLeft/s.scale+"px)"),0!==s.paddingTop&&(l+=" padding-top: "+s.paddingTop+"px;",c+=" translateY("+-s.paddingTop+"px)"),0!==s.paddingRight&&(l+=" padding-right: "+s.paddingRight/s.scale+"px;"),0!==s.paddingBottom&&(l+=" padding-bottom: "+s.paddingBottom+"px;"),""!==l&&o.setAttribute("style",s.style+l),""!==c&&n.CustomStyle.setProp("transform",o,c)}else o.style.padding=0,n.CustomStyle.setProp("transform",o,s.originalTransform||"")}}}},h}();e.renderTextLayer=o},function(t,e,r){"use strict";function i(t){return t.replace(/>\\376\\377([^<]+)/g,function(t,e){for(var r=e.replace(/\\([0-3])([0-7])([0-7])/g,function(t,e,r,i){return String.fromCharCode(64*e+8*r+1*i)}),i="",n=0;n<r.length;n+=2){var o=256*r.charCodeAt(n)+r.charCodeAt(n+1);i+=o>=32&&o<127&&60!==o&&62!==o&&38!==o?String.fromCharCode(o):"&#x"+(65536+o).toString(16).substring(1)+";"}return">"+i})}function n(t){if("string"==typeof t){t=i(t);t=(new DOMParser).parseFromString(t,"application/xml")}else if(!(t instanceof Document))throw new Error("Metadata: Invalid metadata object");this.metaDocument=t,this.metadata=Object.create(null),this.parse()}Object.defineProperty(e,"__esModule",{value:!0}),n.prototype={parse:function t(){var e=this.metaDocument,r=e.documentElement;if("rdf:rdf"!==r.nodeName.toLowerCase())for(r=r.firstChild;r&&"rdf:rdf"!==r.nodeName.toLowerCase();)r=r.nextSibling;var i=r?r.nodeName.toLowerCase():null;if(r&&"rdf:rdf"===i&&r.hasChildNodes()){var n=r.childNodes,o,a,s,c,l,h,u;for(c=0,h=n.length;c<h;c++)if(o=n[c],"rdf:description"===o.nodeName.toLowerCase())for(l=0,u=o.childNodes.length;l<u;l++)"#text"!==o.childNodes[l].nodeName.toLowerCase()&&(a=o.childNodes[l],s=a.nodeName.toLowerCase(),this.metadata[s]=a.textContent.trim())}},get:function t(e){return this.metadata[e]||null},has:function t(e){return void 0!==this.metadata[e]}},e.Metadata=n},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.WebGLUtils=void 0;var i=r(1),n=r(0),o=function t(){function e(t,e,r){var i=t.createShader(r);if(t.shaderSource(i,e),t.compileShader(i),!t.getShaderParameter(i,t.COMPILE_STATUS)){var n=t.getShaderInfoLog(i);throw new Error("Error during shader compilation: "+n)}return i}function r(t,r){return e(t,r,t.VERTEX_SHADER)}function o(t,r){return e(t,r,t.FRAGMENT_SHADER)}function a(t,e){for(var r=t.createProgram(),i=0,n=e.length;i<n;++i)t.attachShader(r,e[i]);if(t.linkProgram(r),!t.getProgramParameter(r,t.LINK_STATUS)){var o=t.getProgramInfoLog(r);throw new Error("Error during program linking: "+o)}return r}function s(t,e,r){t.activeTexture(r);var i=t.createTexture();return t.bindTexture(t.TEXTURE_2D,i),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),i}function c(){p||(g=document.createElement("canvas"),p=g.getContext("webgl",{premultipliedalpha:!1}))}function l(){var t,e;c(),t=g,g=null,e=p,p=null;var i=r(e,v),n=o(e,m),s=a(e,[i,n]);e.useProgram(s);var l={};l.gl=e,l.canvas=t,l.resolutionLocation=e.getUniformLocation(s,"u_resolution"),l.positionLocation=e.getAttribLocation(s,"a_position"),l.backdropLocation=e.getUniformLocation(s,"u_backdrop"),l.subtypeLocation=e.getUniformLocation(s,"u_subtype");var h=e.getAttribLocation(s,"a_texCoord"),u=e.getUniformLocation(s,"u_image"),f=e.getUniformLocation(s,"u_mask"),d=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,d),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),e.STATIC_DRAW),e.enableVertexAttribArray(h),e.vertexAttribPointer(h,2,e.FLOAT,!1,0,0),e.uniform1i(u,0),e.uniform1i(f,1),b=l}function h(t,e,r){var i=t.width,n=t.height;b||l();var o=b,a=o.canvas,c=o.gl;a.width=i,a.height=n,c.viewport(0,0,c.drawingBufferWidth,c.drawingBufferHeight),c.uniform2f(o.resolutionLocation,i,n),r.backdrop?c.uniform4f(o.resolutionLocation,r.backdrop[0],r.backdrop[1],r.backdrop[2],1):c.uniform4f(o.resolutionLocation,0,0,0,0),c.uniform1i(o.subtypeLocation,"Luminosity"===r.subtype?1:0);var h=s(c,t,c.TEXTURE0),u=s(c,e,c.TEXTURE1),f=c.createBuffer();return c.bindBuffer(c.ARRAY_BUFFER,f),c.bufferData(c.ARRAY_BUFFER,new Float32Array([0,0,i,0,0,n,0,n,i,0,i,n]),c.STATIC_DRAW),c.enableVertexAttribArray(o.positionLocation),c.vertexAttribPointer(o.positionLocation,2,c.FLOAT,!1,0,0),c.clearColor(0,0,0,0),c.enable(c.BLEND),c.blendFunc(c.ONE,c.ONE_MINUS_SRC_ALPHA),c.clear(c.COLOR_BUFFER_BIT),c.drawArrays(c.TRIANGLES,0,6),c.flush(),c.deleteTexture(h),c.deleteTexture(u),c.deleteBuffer(f),a}function u(){var t,e;c(),t=g,g=null,e=p,p=null;var i=r(e,y),n=o(e,_),s=a(e,[i,n]);e.useProgram(s);var l={};l.gl=e,l.canvas=t,l.resolutionLocation=e.getUniformLocation(s,"u_resolution"),l.scaleLocation=e.getUniformLocation(s,"u_scale"),l.offsetLocation=e.getUniformLocation(s,"u_offset"),l.positionLocation=e.getAttribLocation(s,"a_position"),l.colorLocation=e.getAttribLocation(s,"a_color"),w=l}function f(t,e,r,i,n){w||u();var o=w,a=o.canvas,s=o.gl;a.width=t,a.height=e,s.viewport(0,0,s.drawingBufferWidth,s.drawingBufferHeight),s.uniform2f(o.resolutionLocation,t,e);var c=0,l,h,f;for(l=0,h=i.length;l<h;l++)switch(i[l].type){case"lattice":f=i[l].coords.length/i[l].verticesPerRow|0,c+=(f-1)*(i[l].verticesPerRow-1)*6;break;case"triangles":c+=i[l].coords.length}var d=new Float32Array(2*c),p=new Uint8Array(3*c),g=n.coords,v=n.colors,m=0,b=0;for(l=0,h=i.length;l<h;l++){var y=i[l],_=y.coords,S=y.colors;switch(y.type){case"lattice":var x=y.verticesPerRow;f=_.length/x|0;for(var C=1;C<f;C++)for(var A=C*x+1,T=1;T<x;T++,A++)d[m]=g[_[A-x-1]],d[m+1]=g[_[A-x-1]+1],d[m+2]=g[_[A-x]],d[m+3]=g[_[A-x]+1],d[m+4]=g[_[A-1]],d[m+5]=g[_[A-1]+1],p[b]=v[S[A-x-1]],p[b+1]=v[S[A-x-1]+1],p[b+2]=v[S[A-x-1]+2],p[b+3]=v[S[A-x]],p[b+4]=v[S[A-x]+1],p[b+5]=v[S[A-x]+2],p[b+6]=v[S[A-1]],p[b+7]=v[S[A-1]+1],p[b+8]=v[S[A-1]+2],d[m+6]=d[m+2],d[m+7]=d[m+3],d[m+8]=d[m+4],d[m+9]=d[m+5],d[m+10]=g[_[A]],d[m+11]=g[_[A]+1],p[b+9]=p[b+3],p[b+10]=p[b+4],p[b+11]=p[b+5],p[b+12]=p[b+6],p[b+13]=p[b+7],p[b+14]=p[b+8],p[b+15]=v[S[A]],p[b+16]=v[S[A]+1],p[b+17]=v[S[A]+2],m+=12,b+=18;break;case"triangles":for(var k=0,P=_.length;k<P;k++)d[m]=g[_[k]],d[m+1]=g[_[k]+1],p[b]=v[S[k]],p[b+1]=v[S[k]+1],p[b+2]=v[S[k]+2],m+=2,b+=3}}r?s.clearColor(r[0]/255,r[1]/255,r[2]/255,1):s.clearColor(0,0,0,0),s.clear(s.COLOR_BUFFER_BIT);var E=s.createBuffer();s.bindBuffer(s.ARRAY_BUFFER,E),s.bufferData(s.ARRAY_BUFFER,d,s.STATIC_DRAW),s.enableVertexAttribArray(o.positionLocation),s.vertexAttribPointer(o.positionLocation,2,s.FLOAT,!1,0,0);var O=s.createBuffer();return s.bindBuffer(s.ARRAY_BUFFER,O),s.bufferData(s.ARRAY_BUFFER,p,s.STATIC_DRAW),s.enableVertexAttribArray(o.colorLocation),s.vertexAttribPointer(o.colorLocation,3,s.UNSIGNED_BYTE,!1,0,0),s.uniform2f(o.scaleLocation,n.scaleX,n.scaleY),s.uniform2f(o.offsetLocation,n.offsetX,n.offsetY),s.drawArrays(s.TRIANGLES,0,c),s.flush(),s.deleteBuffer(E),s.deleteBuffer(O),a}function d(){b&&b.canvas&&(b.canvas.width=0,b.canvas.height=0),w&&w.canvas&&(w.canvas.width=0,w.canvas.height=0),b=null,w=null}var p,g,v=" attribute vec2 a_position; attribute vec2 a_texCoord; uniform vec2 u_resolution; varying vec2 v_texCoord; void main() { vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); v_texCoord = a_texCoord; } ",m=" precision mediump float; uniform vec4 u_backdrop; uniform int u_subtype; uniform sampler2D u_image; uniform sampler2D u_mask; varying vec2 v_texCoord; void main() { vec4 imageColor = texture2D(u_image, v_texCoord); vec4 maskColor = texture2D(u_mask, v_texCoord); if (u_backdrop.a > 0.0) { maskColor.rgb = maskColor.rgb * maskColor.a + u_backdrop.rgb * (1.0 - maskColor.a); } float lum; if (u_subtype == 0) { lum = maskColor.a; } else { lum = maskColor.r * 0.3 + maskColor.g * 0.59 + maskColor.b * 0.11; } imageColor.a *= lum; imageColor.rgb *= imageColor.a; gl_FragColor = imageColor; } ",b=null,y=" attribute vec2 a_position; attribute vec3 a_color; uniform vec2 u_resolution; uniform vec2 u_scale; uniform vec2 u_offset; varying vec4 v_color; void main() { vec2 position = (a_position + u_offset) * u_scale; vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); v_color = vec4(a_color / 255.0, 1.0); } ",_=" precision mediump float; varying vec4 v_color; void main() { gl_FragColor = v_color; } ",w=null;return{get isEnabled(){if((0,i.getDefaultSetting)("disableWebGL"))return!1;var t=!1;try{c(),t=!!p}catch(t){}return(0,n.shadow)(this,"isEnabled",t)},composeSMask:h,drawFigures:f,clear:d}}();e.WebGLUtils=o},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.PDFJS=e.isWorker=e.globalScope=void 0;var i=r(3),n=r(1),o=r(0),a=r(2),s=r(6),c=r(5),l=r(4),h="undefined"==typeof window;o.globalScope.PDFJS||(o.globalScope.PDFJS={});var u=o.globalScope.PDFJS;u.version="1.8.575",u.build="bd8c1211",u.pdfBug=!1,void 0!==u.verbosity&&(0,o.setVerbosityLevel)(u.verbosity),delete u.verbosity,Object.defineProperty(u,"verbosity",{get:function t(){return(0,o.getVerbosityLevel)()},set:function t(e){(0,o.setVerbosityLevel)(e)},enumerable:!0,configurable:!0}),u.VERBOSITY_LEVELS=o.VERBOSITY_LEVELS,u.OPS=o.OPS,u.UNSUPPORTED_FEATURES=o.UNSUPPORTED_FEATURES,u.isValidUrl=n.isValidUrl,u.shadow=o.shadow,u.createBlob=o.createBlob,u.createObjectURL=function t(e,r){return(0,o.createObjectURL)(e,r,u.disableCreateObjectURL)},Object.defineProperty(u,"isLittleEndian",{configurable:!0,get:function t(){return(0,o.shadow)(u,"isLittleEndian",(0,o.isLittleEndian)())}}),u.removeNullCharacters=o.removeNullCharacters,u.PasswordResponses=o.PasswordResponses,u.PasswordException=o.PasswordException,u.UnknownErrorException=o.UnknownErrorException,u.InvalidPDFException=o.InvalidPDFException,u.MissingPDFException=o.MissingPDFException,u.UnexpectedResponseException=o.UnexpectedResponseException,u.Util=o.Util,u.PageViewport=o.PageViewport,u.createPromiseCapability=o.createPromiseCapability,u.maxImageSize=void 0===u.maxImageSize?-1:u.maxImageSize,u.cMapUrl=void 0===u.cMapUrl?null:u.cMapUrl,u.cMapPacked=void 0!==u.cMapPacked&&u.cMapPacked,u.disableFontFace=void 0!==u.disableFontFace&&u.disableFontFace,u.imageResourcesPath=void 0===u.imageResourcesPath?"":u.imageResourcesPath,u.disableWorker=void 0!==u.disableWorker&&u.disableWorker,u.workerSrc=void 0===u.workerSrc?null:u.workerSrc,u.workerPort=void 0===u.workerPort?null:u.workerPort,u.disableRange=void 0!==u.disableRange&&u.disableRange,u.disableStream=void 0!==u.disableStream&&u.disableStream,u.disableAutoFetch=void 0!==u.disableAutoFetch&&u.disableAutoFetch,u.pdfBug=void 0!==u.pdfBug&&u.pdfBug,u.postMessageTransfers=void 0===u.postMessageTransfers||u.postMessageTransfers,u.disableCreateObjectURL=void 0!==u.disableCreateObjectURL&&u.disableCreateObjectURL,u.disableWebGL=void 0===u.disableWebGL||u.disableWebGL,u.externalLinkTarget=void 0===u.externalLinkTarget?n.LinkTarget.NONE:u.externalLinkTarget,u.externalLinkRel=void 0===u.externalLinkRel?n.DEFAULT_LINK_REL:u.externalLinkRel,u.isEvalSupported=void 0===u.isEvalSupported||u.isEvalSupported,u.pdfjsNext=void 0!==u.pdfjsNext&&u.pdfjsNext;var f=u.openExternalLinksInNewWindow;delete u.openExternalLinksInNewWindow,Object.defineProperty(u,"openExternalLinksInNewWindow",{get:function t(){return u.externalLinkTarget===n.LinkTarget.BLANK},set:function t(e){if(e&&(0,o.deprecated)('PDFJS.openExternalLinksInNewWindow, please use "PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK" instead.'),u.externalLinkTarget!==n.LinkTarget.NONE)return void(0,o.warn)("PDFJS.externalLinkTarget is already initialized");u.externalLinkTarget=e?n.LinkTarget.BLANK:n.LinkTarget.NONE},enumerable:!0,configurable:!0}),f&&(u.openExternalLinksInNewWindow=f),u.getDocument=i.getDocument,u.LoopbackPort=i.LoopbackPort,u.PDFDataRangeTransport=i.PDFDataRangeTransport,u.PDFWorker=i.PDFWorker,u.hasCanvasTypedArrays=!0,u.CustomStyle=n.CustomStyle,u.LinkTarget=n.LinkTarget,u.addLinkAttributes=n.addLinkAttributes,u.getFilenameFromUrl=n.getFilenameFromUrl,u.isExternalLinkTargetSet=n.isExternalLinkTargetSet,u.AnnotationLayer=a.AnnotationLayer,u.renderTextLayer=c.renderTextLayer,u.Metadata=s.Metadata,u.SVGGraphics=l.SVGGraphics,u.UnsupportedManager=i._UnsupportedManager,e.globalScope=o.globalScope,e.isWorker=h,e.PDFJS=u},function(t,e,r){"use strict";var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};!function(t,e){for(var r in e)t[r]=e[r]}(e,function(t){function e(i){if(r[i])return r[i].exports;var n=r[i]={i:i,l:!1,exports:{}};return t[i].call(n.exports,n,n.exports,e),n.l=!0,n.exports}var r={};return e.m=t,e.c=r,e.i=function(t){return t},e.d=function(t,r,i){e.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var r=t&&t.__esModule?function e(){return t.default}:function e(){return t};return e.d(r,"a",r),r},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=7)}([function(t,e,r){function n(t){return"string"==typeof t||"symbol"===(void 0===t?"undefined":a(t))}function o(t,e,r){if("function"!=typeof t)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(t,e,r)}var a="function"==typeof Symbol&&"symbol"===i(Symbol.iterator)?function(t){return void 0===t?"undefined":i(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":void 0===t?"undefined":i(t)},s=r(1),c=s.assert;e.typeIsObject=function(t){return"object"===(void 0===t?"undefined":a(t))&&null!==t||"function"==typeof t},e.createDataProperty=function(t,r,i){c(e.typeIsObject(t)),Object.defineProperty(t,r,{value:i,writable:!0,enumerable:!0,configurable:!0})},e.createArrayFromList=function(t){return t.slice()},e.ArrayBufferCopy=function(t,e,r,i,n){new Uint8Array(t).set(new Uint8Array(r,i,n),e)},e.CreateIterResultObject=function(t,e){c("boolean"==typeof e);var r={};return Object.defineProperty(r,"value",{value:t,enumerable:!0,writable:!0,configurable:!0}),Object.defineProperty(r,"done",{value:e,enumerable:!0,writable:!0,configurable:!0}),r},e.IsFiniteNonNegativeNumber=function(t){return!Number.isNaN(t)&&(t!==1/0&&!(t<0))},e.InvokeOrNoop=function(t,e,r){c(void 0!==t),c(n(e)),c(Array.isArray(r));var i=t[e];if(void 0!==i)return o(i,t,r)},e.PromiseInvokeOrNoop=function(t,r,i){c(void 0!==t),c(n(r)),c(Array.isArray(i));try{return Promise.resolve(e.InvokeOrNoop(t,r,i))}catch(t){return Promise.reject(t)}},e.PromiseInvokeOrPerformFallback=function(t,e,r,i,a){c(void 0!==t),c(n(e)),c(Array.isArray(r)),c(Array.isArray(a));var s=void 0;try{s=t[e]}catch(t){return Promise.reject(t)}if(void 0===s)return i.apply(null,a);try{return Promise.resolve(o(s,t,r))}catch(t){return Promise.reject(t)}},e.TransferArrayBuffer=function(t){return t.slice()},e.ValidateAndNormalizeHighWaterMark=function(t){if(t=Number(t),Number.isNaN(t)||t<0)throw new RangeError("highWaterMark property of a queuing strategy must be non-negative and non-NaN");return t},e.ValidateAndNormalizeQueuingStrategy=function(t,r){if(void 0!==t&&"function"!=typeof t)throw new TypeError("size property of a queuing strategy must be a function");return r=e.ValidateAndNormalizeHighWaterMark(r),{size:t,highWaterMark:r}}},function(t,e,r){function i(t){t&&t.constructor===n&&setTimeout(function(){throw t},0)}function n(t){this.name="AssertionError",this.message=t||"",this.stack=(new Error).stack}function o(t,e){if(!t)throw new n(e)}n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,t.exports={rethrowAssertionErrorRejection:i,AssertionError:n,assert:o}},function(t,e,r){function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t){return new yt(t)}function o(t){return!!lt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_writableStreamController")}function a(t){return ut(!0===o(t),"IsWritableStreamLocked should only be used on known writable streams"),void 0!==t._writer}function s(t,e){var r=t._state;if("closed"===r)return Promise.resolve(void 0);if("errored"===r)return Promise.reject(t._storedError);var i=new TypeError("Requested to abort");if(void 0!==t._pendingAbortRequest)return Promise.reject(i);ut("writable"===r||"erroring"===r,"state must be writable or erroring");var n=!1;"erroring"===r&&(n=!0,e=void 0);var o=new Promise(function(r,i){t._pendingAbortRequest={_resolve:r,_reject:i,_reason:e,_wasAlreadyErroring:n}});return!1===n&&h(t,i),o}function c(t){return ut(!0===a(t)),ut("writable"===t._state),new Promise(function(e,r){var i={_resolve:e,_reject:r};t._writeRequests.push(i)})}function l(t,e){var r=t._state;if("writable"===r)return void h(t,e);ut("erroring"===r),u(t)}function h(t,e){ut(void 0===t._storedError,"stream._storedError === undefined"),ut("writable"===t._state,"state must be writable");var r=t._writableStreamController;ut(void 0!==r,"controller must not be undefined"),t._state="erroring",t._storedError=e;var i=t._writer;void 0!==i&&k(i,e),!1===m(t)&&!0===r._started&&u(t)}function u(t){ut("erroring"===t._state,"stream._state === erroring"),ut(!1===m(t),"WritableStreamHasOperationMarkedInFlight(stream) === false"),t._state="errored",t._writableStreamController.__errorSteps();for(var e=t._storedError,r=0;r<t._writeRequests.length;r++){t._writeRequests[r]._reject(e)}if(t._writeRequests=[],void 0===t._pendingAbortRequest)return void _(t);var i=t._pendingAbortRequest;if(t._pendingAbortRequest=void 0,!0===i._wasAlreadyErroring)return i._reject(e),void _(t);t._writableStreamController.__abortSteps(i._reason).then(function(){i._resolve(),_(t)},function(e){i._reject(e),_(t)})}function f(t){ut(void 0!==t._inFlightWriteRequest),t._inFlightWriteRequest._resolve(void 0),t._inFlightWriteRequest=void 0}function d(t,e){ut(void 0!==t._inFlightWriteRequest),t._inFlightWriteRequest._reject(e),t._inFlightWriteRequest=void 0,ut("writable"===t._state||"erroring"===t._state),l(t,e)}function p(t){ut(void 0!==t._inFlightCloseRequest),t._inFlightCloseRequest._resolve(void 0),t._inFlightCloseRequest=void 0;var e=t._state;ut("writable"===e||"erroring"===e),"erroring"===e&&(t._storedError=void 0,void 0!==t._pendingAbortRequest&&(t._pendingAbortRequest._resolve(),t._pendingAbortRequest=void 0)),t._state="closed";var r=t._writer;void 0!==r&&J(r),ut(void 0===t._pendingAbortRequest,"stream._pendingAbortRequest === undefined"),ut(void 0===t._storedError,"stream._storedError === undefined")}function g(t,e){ut(void 0!==t._inFlightCloseRequest),t._inFlightCloseRequest._reject(e),t._inFlightCloseRequest=void 0,ut("writable"===t._state||"erroring"===t._state),void 0!==t._pendingAbortRequest&&(t._pendingAbortRequest._reject(e),t._pendingAbortRequest=void 0),l(t,e)}function v(t){return void 0!==t._closeRequest||void 0!==t._inFlightCloseRequest}function m(t){return void 0!==t._inFlightWriteRequest||void 0!==t._inFlightCloseRequest}function b(t){ut(void 0===t._inFlightCloseRequest),ut(void 0!==t._closeRequest),t._inFlightCloseRequest=t._closeRequest,t._closeRequest=void 0}function y(t){ut(void 0===t._inFlightWriteRequest,"there must be no pending write request"),ut(0!==t._writeRequests.length,"writeRequests must not be empty"),t._inFlightWriteRequest=t._writeRequests.shift()}function _(t){ut("errored"===t._state,'_stream_.[[state]] is `"errored"`'),void 0!==t._closeRequest&&(ut(void 0===t._inFlightCloseRequest),t._closeRequest._reject(t._storedError),t._closeRequest=void 0);var e=t._writer;void 0!==e&&(V(e,t._storedError),e._closedPromise.catch(function(){}))}function w(t,e){ut("writable"===t._state),ut(!1===v(t));var r=t._writer;void 0!==r&&e!==t._backpressure&&(!0===e?et(r):(ut(!1===e),it(r))),t._backpressure=e}function S(t){return!!lt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_ownerWritableStream")}function x(t,e){var r=t._ownerWritableStream;return ut(void 0!==r),s(r,e)}function C(t){var e=t._ownerWritableStream;ut(void 0!==e);var r=e._state;if("closed"===r||"errored"===r)return Promise.reject(new TypeError("The stream (in "+r+" state) is not in the writable state and cannot be closed"));ut("writable"===r||"erroring"===r),ut(!1===v(e));var i=new Promise(function(t,r){var i={_resolve:t,_reject:r};e._closeRequest=i});return!0===e._backpressure&&"writable"===r&&it(t),R(e._writableStreamController),i}function A(t){var e=t._ownerWritableStream;ut(void 0!==e);var r=e._state;return!0===v(e)||"closed"===r?Promise.resolve():"errored"===r?Promise.reject(e._storedError):(ut("writable"===r||"erroring"===r),C(t))}function T(t,e){"pending"===t._closedPromiseState?V(t,e):Z(t,e),t._closedPromise.catch(function(){})}function k(t,e){"pending"===t._readyPromiseState?tt(t,e):rt(t,e),t._readyPromise.catch(function(){})}function P(t){var e=t._ownerWritableStream,r=e._state;return"errored"===r||"erroring"===r?null:"closed"===r?0:D(e._writableStreamController)}function E(t){var e=t._ownerWritableStream;ut(void 0!==e),ut(e._writer===t);var r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");k(t,r),T(t,r),e._writer=void 0,t._ownerWritableStream=void 0}function O(t,e){var r=t._ownerWritableStream;ut(void 0!==r);var i=r._writableStreamController,n=L(i,e);if(r!==t._ownerWritableStream)return Promise.reject(X("write to"));var o=r._state;if("errored"===o)return Promise.reject(r._storedError);if(!0===v(r)||"closed"===o)return Promise.reject(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===o)return Promise.reject(r._storedError);ut("writable"===o);var a=c(r);return I(i,e,n),a}function R(t){gt(t,"close",0),M(t)}function L(t,e){var r=t._strategySize;if(void 0===r)return 1;try{return r(e)}catch(e){return F(t,e),1}}function D(t){return t._strategyHWM-t._queueTotalSize}function I(t,e,r){var i={chunk:e};try{gt(t,i,r)}catch(e){return void F(t,e)}var n=t._controlledWritableStream;if(!1===v(n)&&"writable"===n._state){w(n,U(t))}M(t)}function j(t){return!!lt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_underlyingSink")}function M(t){var e=t._controlledWritableStream;if(!1!==t._started&&void 0===e._inFlightWriteRequest){var r=e._state;if("closed"!==r&&"errored"!==r){if("erroring"===r)return void u(e);if(0!==t._queue.length){var i=vt(t);"close"===i?N(t):B(t,i.chunk)}}}}function F(t,e){"writable"===t._controlledWritableStream._state&&z(t,e)}function N(t){var e=t._controlledWritableStream;b(e),pt(t),ut(0===t._queue.length,"queue must be empty once the final write record is dequeued"),st(t._underlyingSink,"close",[]).then(function(){p(e)},function(t){g(e,t)}).catch(ft)}function B(t,e){var r=t._controlledWritableStream;y(r),st(t._underlyingSink,"write",[e,t]).then(function(){f(r);var e=r._state;if(ut("writable"===e||"erroring"===e),pt(t),!1===v(r)&&"writable"===e){var i=U(t);w(r,i)}M(t)},function(t){d(r,t)}).catch(ft)}function U(t){return D(t)<=0}function z(t,e){var r=t._controlledWritableStream;ut("writable"===r._state),h(r,e)}function W(t){return new TypeError("WritableStream.prototype."+t+" can only be used on a WritableStream")}function q(t){return new TypeError("WritableStreamDefaultWriter.prototype."+t+" can only be used on a WritableStreamDefaultWriter")}function X(t){return new TypeError("Cannot "+t+" a stream using a released writer")}function G(t){t._closedPromise=new Promise(function(e,r){t._closedPromise_resolve=e,t._closedPromise_reject=r,t._closedPromiseState="pending"})}function H(t,e){t._closedPromise=Promise.reject(e),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0,t._closedPromiseState="rejected"}function Y(t){t._closedPromise=Promise.resolve(void 0),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0,t._closedPromiseState="resolved"}function V(t,e){ut(void 0!==t._closedPromise_resolve,"writer._closedPromise_resolve !== undefined"),ut(void 0!==t._closedPromise_reject,"writer._closedPromise_reject !== undefined"),ut("pending"===t._closedPromiseState,"writer._closedPromiseState is pending"),t._closedPromise_reject(e),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0,t._closedPromiseState="rejected"}function Z(t,e){ut(void 0===t._closedPromise_resolve,"writer._closedPromise_resolve === undefined"),ut(void 0===t._closedPromise_reject,"writer._closedPromise_reject === undefined"),ut("pending"!==t._closedPromiseState,"writer._closedPromiseState is not pending"),t._closedPromise=Promise.reject(e),t._closedPromiseState="rejected"}function J(t){ut(void 0!==t._closedPromise_resolve,"writer._closedPromise_resolve !== undefined"),ut(void 0!==t._closedPromise_reject,"writer._closedPromise_reject !== undefined"),ut("pending"===t._closedPromiseState,"writer._closedPromiseState is pending"),t._closedPromise_resolve(void 0),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0,t._closedPromiseState="resolved"}function K(t){t._readyPromise=new Promise(function(e,r){t._readyPromise_resolve=e,t._readyPromise_reject=r}),t._readyPromiseState="pending"}function Q(t,e){t._readyPromise=Promise.reject(e),t._readyPromise_resolve=void 0,t._readyPromise_reject=void 0,t._readyPromiseState="rejected"}function $(t){t._readyPromise=Promise.resolve(void 0),t._readyPromise_resolve=void 0,t._readyPromise_reject=void 0,t._readyPromiseState="fulfilled"}function tt(t,e){ut(void 0!==t._readyPromise_resolve,"writer._readyPromise_resolve !== undefined"),ut(void 0!==t._readyPromise_reject,"writer._readyPromise_reject !== undefined"),t._readyPromise_reject(e),t._readyPromise_resolve=void 0,t._readyPromise_reject=void 0,t._readyPromiseState="rejected"}function et(t){ut(void 0===t._readyPromise_resolve,"writer._readyPromise_resolve === undefined"),ut(void 0===t._readyPromise_reject,"writer._readyPromise_reject === undefined"),t._readyPromise=new Promise(function(e,r){t._readyPromise_resolve=e,t._readyPromise_reject=r}),t._readyPromiseState="pending"}function rt(t,e){ut(void 0===t._readyPromise_resolve,"writer._readyPromise_resolve === undefined"),ut(void 0===t._readyPromise_reject,"writer._readyPromise_reject === undefined"),t._readyPromise=Promise.reject(e),t._readyPromiseState="rejected"}function it(t){ut(void 0!==t._readyPromise_resolve,"writer._readyPromise_resolve !== undefined"),ut(void 0!==t._readyPromise_reject,"writer._readyPromise_reject !== undefined"),t._readyPromise_resolve(void 0),t._readyPromise_resolve=void 0,t._readyPromise_reject=void 0,t._readyPromiseState="fulfilled"}var nt=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),ot=r(0),at=ot.InvokeOrNoop,st=ot.PromiseInvokeOrNoop,ct=ot.ValidateAndNormalizeQueuingStrategy,lt=ot.typeIsObject,ht=r(1),ut=ht.assert,ft=ht.rethrowAssertionErrorRejection,dt=r(3),pt=dt.DequeueValue,gt=dt.EnqueueValueWithSize,vt=dt.PeekQueueValue,mt=dt.ResetQueue,bt=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=r.size,o=r.highWaterMark,a=void 0===o?1:o;if(i(this,t),this._state="writable",this._storedError=void 0,this._writer=void 0,this._writableStreamController=void 0,this._writeRequests=[],this._inFlightWriteRequest=void 0,this._closeRequest=void 0,this._inFlightCloseRequest=void 0,this._pendingAbortRequest=void 0,this._backpressure=!1,void 0!==e.type)throw new RangeError("Invalid type is specified");this._writableStreamController=new _t(this,e,n,a),this._writableStreamController.__startSteps()}return nt(t,[{key:"abort",value:function t(e){return!1===o(this)?Promise.reject(W("abort")):!0===a(this)?Promise.reject(new TypeError("Cannot abort a stream that already has a writer")):s(this,e)}},{key:"getWriter",value:function t(){if(!1===o(this))throw W("getWriter");return n(this)}},{key:"locked",get:function t(){if(!1===o(this))throw W("locked");return a(this)}}]),t}();t.exports={AcquireWritableStreamDefaultWriter:n,IsWritableStream:o,IsWritableStreamLocked:a,WritableStream:bt,WritableStreamAbort:s,WritableStreamDefaultControllerError:z,WritableStreamDefaultWriterCloseWithErrorPropagation:A,WritableStreamDefaultWriterRelease:E,WritableStreamDefaultWriterWrite:O,WritableStreamCloseQueuedOrInFlight:v};var yt=function(){function t(e){if(i(this,t),!1===o(e))throw new TypeError("WritableStreamDefaultWriter can only be constructed with a WritableStream instance");if(!0===a(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;var r=e._state;if("writable"===r)!1===v(e)&&!0===e._backpressure?K(this):$(this),G(this);else if("erroring"===r)Q(this,e._storedError),this._readyPromise.catch(function(){}),G(this);else if("closed"===r)$(this),Y(this);else{ut("errored"===r,"state must be errored");var n=e._storedError;Q(this,n),this._readyPromise.catch(function(){}),H(this,n),this._closedPromise.catch(function(){})}}return nt(t,[{key:"abort",value:function t(e){return!1===S(this)?Promise.reject(q("abort")):void 0===this._ownerWritableStream?Promise.reject(X("abort")):x(this,e)}},{key:"close",value:function t(){if(!1===S(this))return Promise.reject(q("close"));var e=this._ownerWritableStream;return void 0===e?Promise.reject(X("close")):!0===v(e)?Promise.reject(new TypeError("cannot close an already-closing stream")):C(this)}},{key:"releaseLock",value:function t(){if(!1===S(this))throw q("releaseLock");var e=this._ownerWritableStream;void 0!==e&&(ut(void 0!==e._writer),E(this))}},{key:"write",value:function t(e){return!1===S(this)?Promise.reject(q("write")):void 0===this._ownerWritableStream?Promise.reject(X("write to")):O(this,e)}},{key:"closed",get:function t(){return!1===S(this)?Promise.reject(q("closed")):this._closedPromise}},{key:"desiredSize",get:function t(){if(!1===S(this))throw q("desiredSize");if(void 0===this._ownerWritableStream)throw X("desiredSize");return P(this)}},{key:"ready",get:function t(){return!1===S(this)?Promise.reject(q("ready")):this._readyPromise}}]),t}(),_t=function(){function t(e,r,n,a){if(i(this,t),!1===o(e))throw new TypeError("WritableStreamDefaultController can only be constructed with a WritableStream instance");if(void 0!==e._writableStreamController)throw new TypeError("WritableStreamDefaultController instances can only be created by the WritableStream constructor");this._controlledWritableStream=e,this._underlyingSink=r,this._queue=void 0,this._queueTotalSize=void 0,mt(this),this._started=!1;var s=ct(n,a);this._strategySize=s.size,this._strategyHWM=s.highWaterMark,w(e,U(this))}return nt(t,[{key:"error",value:function t(e){if(!1===j(this))throw new TypeError("WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController");"writable"===this._controlledWritableStream._state&&z(this,e)}},{key:"__abortSteps",value:function t(e){return st(this._underlyingSink,"abort",[e])}},{key:"__errorSteps",value:function t(){mt(this)}},{key:"__startSteps",value:function t(){var e=this,r=at(this._underlyingSink,"start",[this]),i=this._controlledWritableStream;Promise.resolve(r).then(function(){ut("writable"===i._state||"erroring"===i._state),e._started=!0,M(e)},function(t){ut("writable"===i._state||"erroring"===i._state),e._started=!0,l(i,t)}).catch(ft)}}]),t}()},function(t,e,r){var i=r(0),n=i.IsFiniteNonNegativeNumber,o=r(1),a=o.assert;e.DequeueValue=function(t){a("_queue"in t&&"_queueTotalSize"in t,"Spec-level failure: DequeueValue should only be used on containers with [[queue]] and [[queueTotalSize]]."),a(t._queue.length>0,"Spec-level failure: should never dequeue from an empty queue.");var e=t._queue.shift();return t._queueTotalSize-=e.size,t._queueTotalSize<0&&(t._queueTotalSize=0),e.value},e.EnqueueValueWithSize=function(t,e,r){if(a("_queue"in t&&"_queueTotalSize"in t,"Spec-level failure: EnqueueValueWithSize should only be used on containers with [[queue]] and [[queueTotalSize]]."),r=Number(r),!n(r))throw new RangeError("Size must be a finite, non-NaN, non-negative number.");t._queue.push({value:e,size:r}),t._queueTotalSize+=r},e.PeekQueueValue=function(t){return a("_queue"in t&&"_queueTotalSize"in t,"Spec-level failure: PeekQueueValue should only be used on containers with [[queue]] and [[queueTotalSize]]."),a(t._queue.length>0,"Spec-level failure: should never peek at an empty queue."),t._queue[0].value},e.ResetQueue=function(t){a("_queue"in t&&"_queueTotalSize"in t,"Spec-level failure: ResetQueue should only be used on containers with [[queue]] and [[queueTotalSize]]."),t._queue=[],t._queueTotalSize=0}},function(t,e,r){function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t){return new ee(t)}function o(t){return new te(t)}function a(t){return!!Mt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_readableStreamController")}function s(t){return Nt(!0===a(t),"IsReadableStreamDisturbed should only be used on known readable streams"),t._disturbed}function c(t){return Nt(!0===a(t),"IsReadableStreamLocked should only be used on known readable streams"),void 0!==t._reader}function l(t,e){Nt(!0===a(t)),Nt("boolean"==typeof e);var r=o(t),i={closedOrErrored:!1,canceled1:!1,canceled2:!1,reason1:void 0,reason2:void 0};i.promise=new Promise(function(t){i._resolve=t});var n=h();n._reader=r,n._teeState=i,n._cloneForBranch2=e;var s=u();s._stream=t,s._teeState=i;var c=f();c._stream=t,c._teeState=i;var l=Object.create(Object.prototype);jt(l,"pull",n),jt(l,"cancel",s);var d=new $t(l),p=Object.create(Object.prototype);jt(p,"pull",n),jt(p,"cancel",c);var g=new $t(p);return n._branch1=d._readableStreamController,n._branch2=g._readableStreamController,r._closedPromise.catch(function(t){!0!==i.closedOrErrored&&(M(n._branch1,t),M(n._branch2,t),i.closedOrErrored=!0)}),[d,g]}function h(){function t(){var e=t._reader,r=t._branch1,i=t._branch2,n=t._teeState;return O(e).then(function(t){Nt(Mt(t));var e=t.value,o=t.done;if(Nt("boolean"==typeof o),!0===o&&!1===n.closedOrErrored&&(!1===n.canceled1&&I(r),!1===n.canceled2&&I(i),n.closedOrErrored=!0),!0!==n.closedOrErrored){var a=e,s=e;!1===n.canceled1&&j(r,a),!1===n.canceled2&&j(i,s)}})}return t}function u(){function t(e){var r=t._stream,i=t._teeState;if(i.canceled1=!0,i.reason1=e,!0===i.canceled2){var n=It([i.reason1,i.reason2]),o=g(r,n);i._resolve(o)}return i.promise}return t}function f(){function t(e){var r=t._stream,i=t._teeState;if(i.canceled2=!0,i.reason2=e,!0===i.canceled1){var n=It([i.reason1,i.reason2]),o=g(r,n);i._resolve(o)}return i.promise}return t}function d(t){return Nt(!0===C(t._reader)),Nt("readable"===t._state||"closed"===t._state),new Promise(function(e,r){var i={_resolve:e,_reject:r};t._reader._readIntoRequests.push(i)})}function p(t){return Nt(!0===A(t._reader)),Nt("readable"===t._state),new Promise(function(e,r){var i={_resolve:e,_reject:r};t._reader._readRequests.push(i)})}function g(t,e){return t._disturbed=!0,"closed"===t._state?Promise.resolve(void 0):"errored"===t._state?Promise.reject(t._storedError):(v(t),t._readableStreamController.__cancelSteps(e).then(function(){}))}function v(t){Nt("readable"===t._state),t._state="closed";var e=t._reader;if(void 0!==e){if(!0===A(e)){for(var r=0;r<e._readRequests.length;r++){(0,e._readRequests[r]._resolve)(Tt(void 0,!0))}e._readRequests=[]}mt(e)}}function m(t,e){Nt(!0===a(t),"stream must be ReadableStream"),Nt("readable"===t._state,"state must be readable"),t._state="errored",t._storedError=e;var r=t._reader;if(void 0!==r){if(!0===A(r)){for(var i=0;i<r._readRequests.length;i++){r._readRequests[i]._reject(e)}r._readRequests=[]}else{Nt(C(r),"reader must be ReadableStreamBYOBReader");for(var n=0;n<r._readIntoRequests.length;n++){r._readIntoRequests[n]._reject(e)}r._readIntoRequests=[]}gt(r,e),r._closedPromise.catch(function(){})}}function b(t,e,r){var i=t._reader;Nt(i._readIntoRequests.length>0),i._readIntoRequests.shift()._resolve(Tt(e,r))}function y(t,e,r){var i=t._reader;Nt(i._readRequests.length>0),i._readRequests.shift()._resolve(Tt(e,r))}function _(t){return t._reader._readIntoRequests.length}function w(t){return t._reader._readRequests.length}function S(t){var e=t._reader;return void 0!==e&&!1!==C(e)}function x(t){var e=t._reader;return void 0!==e&&!1!==A(e)}function C(t){return!!Mt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_readIntoRequests")}function A(t){return!!Mt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_readRequests")}function T(t,e){t._ownerReadableStream=e,e._reader=t,"readable"===e._state?ft(t):"closed"===e._state?pt(t):(Nt("errored"===e._state,"state must be errored"),dt(t,e._storedError),t._closedPromise.catch(function(){}))}function k(t,e){var r=t._ownerReadableStream;return Nt(void 0!==r),g(r,e)}function P(t){Nt(void 0!==t._ownerReadableStream),Nt(t._ownerReadableStream._reader===t),"readable"===t._ownerReadableStream._state?gt(t,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):vt(t,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),t._closedPromise.catch(function(){}),t._ownerReadableStream._reader=void 0,t._ownerReadableStream=void 0}function E(t,e){var r=t._ownerReadableStream;return Nt(void 0!==r),r._disturbed=!0,"errored"===r._state?Promise.reject(r._storedError):K(r._readableStreamController,e)}function O(t){var e=t._ownerReadableStream;return Nt(void 0!==e),e._disturbed=!0,"closed"===e._state?Promise.resolve(Tt(void 0,!0)):"errored"===e._state?Promise.reject(e._storedError):(Nt("readable"===e._state),e._readableStreamController.__pullSteps())}function R(t){return!!Mt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_underlyingSource")}function L(t){if(!1!==D(t)){if(!0===t._pulling)return void(t._pullAgain=!0);Nt(!1===t._pullAgain),t._pulling=!0,Et(t._underlyingSource,"pull",[t]).then(function(){if(t._pulling=!1,!0===t._pullAgain)return t._pullAgain=!1,L(t)},function(e){F(t,e)}).catch(Bt)}}function D(t){var e=t._controlledReadableStream;return"closed"!==e._state&&"errored"!==e._state&&(!0!==t._closeRequested&&(!1!==t._started&&(!0===c(e)&&w(e)>0||N(t)>0)))}function I(t){var e=t._controlledReadableStream;Nt(!1===t._closeRequested),Nt("readable"===e._state),t._closeRequested=!0,0===t._queue.length&&v(e)}function j(t,e){var r=t._controlledReadableStream;if(Nt(!1===t._closeRequested),Nt("readable"===r._state),!0===c(r)&&w(r)>0)y(r,e,!1);else{var i=1;if(void 0!==t._strategySize){var n=t._strategySize;try{i=n(e)}catch(e){throw F(t,e),e}}try{Wt(t,e,i)}catch(e){throw F(t,e),e}}L(t)}function M(t,e){var r=t._controlledReadableStream;Nt("readable"===r._state),qt(t),m(r,e)}function F(t,e){"readable"===t._controlledReadableStream._state&&M(t,e)}function N(t){var e=t._controlledReadableStream,r=e._state;return"errored"===r?null:"closed"===r?0:t._strategyHWM-t._queueTotalSize}function B(t){return!!Mt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_underlyingByteSource")}function U(t){return!!Mt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_associatedReadableByteStreamController")}function z(t){if(!1!==rt(t)){if(!0===t._pulling)return void(t._pullAgain=!0);Nt(!1===t._pullAgain),t._pulling=!0,Et(t._underlyingByteSource,"pull",[t]).then(function(){t._pulling=!1,!0===t._pullAgain&&(t._pullAgain=!1,z(t))},function(e){"readable"===t._controlledReadableStream._state&&ot(t,e)}).catch(Bt)}}function W(t){Z(t),t._pendingPullIntos=[]}function q(t,e){Nt("errored"!==t._state,"state must not be errored");var r=!1;"closed"===t._state&&(Nt(0===e.bytesFilled),r=!0);var i=X(e);"default"===e.readerType?y(t,i,r):(Nt("byob"===e.readerType),b(t,i,r))}function X(t){var e=t.bytesFilled,r=t.elementSize;return Nt(e<=t.byteLength),Nt(e%r==0),new t.ctor(t.buffer,t.byteOffset,e/r)}function G(t,e,r,i){t._queue.push({buffer:e,byteOffset:r,byteLength:i}),t._queueTotalSize+=i}function H(t,e){var r=e.elementSize,i=e.bytesFilled-e.bytesFilled%r,n=Math.min(t._queueTotalSize,e.byteLength-e.bytesFilled),o=e.bytesFilled+n,a=o-o%r,s=n,c=!1;a>i&&(s=a-e.bytesFilled,c=!0);for(var l=t._queue;s>0;){var h=l[0],u=Math.min(s,h.byteLength),f=e.byteOffset+e.bytesFilled;At(e.buffer,f,h.buffer,h.byteOffset,u),h.byteLength===u?l.shift():(h.byteOffset+=u,h.byteLength-=u),t._queueTotalSize-=u,Y(t,u,e),s-=u}return!1===c&&(Nt(0===t._queueTotalSize,"queue must be empty"),Nt(e.bytesFilled>0),Nt(e.bytesFilled<e.elementSize)),c}function Y(t,e,r){Nt(0===t._pendingPullIntos.length||t._pendingPullIntos[0]===r),Z(t),r.bytesFilled+=e}function V(t){Nt("readable"===t._controlledReadableStream._state),0===t._queueTotalSize&&!0===t._closeRequested?v(t._controlledReadableStream):z(t)}function Z(t){void 0!==t._byobRequest&&(t._byobRequest._associatedReadableByteStreamController=void 0,t._byobRequest._view=void 0,t._byobRequest=void 0)}function J(t){for(Nt(!1===t._closeRequested);t._pendingPullIntos.length>0;){if(0===t._queueTotalSize)return;var e=t._pendingPullIntos[0];!0===H(t,e)&&(et(t),q(t._controlledReadableStream,e))}}function K(t,e){var r=t._controlledReadableStream,i=1;e.constructor!==DataView&&(i=e.constructor.BYTES_PER_ELEMENT);var n=e.constructor,o={buffer:e.buffer,byteOffset:e.byteOffset,byteLength:e.byteLength,bytesFilled:0,elementSize:i,ctor:n,readerType:"byob"};if(t._pendingPullIntos.length>0)return o.buffer=Ot(o.buffer),t._pendingPullIntos.push(o),d(r);if("closed"===r._state){var a=new e.constructor(o.buffer,o.byteOffset,0);return Promise.resolve(Tt(a,!0))}if(t._queueTotalSize>0){if(!0===H(t,o)){var s=X(o);return V(t),Promise.resolve(Tt(s,!1))}if(!0===t._closeRequested){var c=new TypeError("Insufficient bytes to fill elements in the given buffer");return ot(t,c),Promise.reject(c)}}o.buffer=Ot(o.buffer),t._pendingPullIntos.push(o);var l=d(r);return z(t),l}function Q(t,e){e.buffer=Ot(e.buffer),Nt(0===e.bytesFilled,"bytesFilled must be 0");var r=t._controlledReadableStream;if(!0===S(r))for(;_(r)>0;){var i=et(t);q(r,i)}}function $(t,e,r){if(r.bytesFilled+e>r.byteLength)throw new RangeError("bytesWritten out of range");if(Y(t,e,r),!(r.bytesFilled<r.elementSize)){et(t);var i=r.bytesFilled%r.elementSize;if(i>0){var n=r.byteOffset+r.bytesFilled,o=r.buffer.slice(n-i,n);G(t,o,0,o.byteLength)}r.buffer=Ot(r.buffer),r.bytesFilled-=i,q(t._controlledReadableStream,r),J(t)}}function tt(t,e){var r=t._pendingPullIntos[0],i=t._controlledReadableStream;if("closed"===i._state){if(0!==e)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream");Q(t,r)}else Nt("readable"===i._state),$(t,e,r)}function et(t){var e=t._pendingPullIntos.shift();return Z(t),e}function rt(t){var e=t._controlledReadableStream;return"readable"===e._state&&(!0!==t._closeRequested&&(!1!==t._started&&(!0===x(e)&&w(e)>0||(!0===S(e)&&_(e)>0||at(t)>0))))}function it(t){var e=t._controlledReadableStream;if(Nt(!1===t._closeRequested),Nt("readable"===e._state),t._queueTotalSize>0)return void(t._closeRequested=!0);if(t._pendingPullIntos.length>0){if(t._pendingPullIntos[0].bytesFilled>0){var r=new TypeError("Insufficient bytes to fill elements in the given buffer");throw ot(t,r),r}}v(e)}function nt(t,e){var r=t._controlledReadableStream;Nt(!1===t._closeRequested),Nt("readable"===r._state);var i=e.buffer,n=e.byteOffset,o=e.byteLength,a=Ot(i);if(!0===x(r))if(0===w(r))G(t,a,n,o);else{Nt(0===t._queue.length);var s=new Uint8Array(a,n,o);y(r,s,!1)}else!0===S(r)?(G(t,a,n,o),J(t)):(Nt(!1===c(r),"stream must not be locked"),G(t,a,n,o))}function ot(t,e){var r=t._controlledReadableStream;Nt("readable"===r._state),W(t),qt(t),m(r,e)}function at(t){var e=t._controlledReadableStream,r=e._state;return"errored"===r?null:"closed"===r?0:t._strategyHWM-t._queueTotalSize}function st(t,e){if(e=Number(e),!1===kt(e))throw new RangeError("bytesWritten must be a finite");Nt(t._pendingPullIntos.length>0),tt(t,e)}function ct(t,e){Nt(t._pendingPullIntos.length>0);var r=t._pendingPullIntos[0];if(r.byteOffset+r.bytesFilled!==e.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.byteLength!==e.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");r.buffer=e.buffer,tt(t,e.byteLength)}function lt(t){return new TypeError("ReadableStream.prototype."+t+" can only be used on a ReadableStream")}function ht(t){return new TypeError("Cannot "+t+" a stream using a released reader")}function ut(t){return new TypeError("ReadableStreamDefaultReader.prototype."+t+" can only be used on a ReadableStreamDefaultReader")}function ft(t){t._closedPromise=new Promise(function(e,r){t._closedPromise_resolve=e,t._closedPromise_reject=r})}function dt(t,e){t._closedPromise=Promise.reject(e),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0}function pt(t){t._closedPromise=Promise.resolve(void 0),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0}function gt(t,e){Nt(void 0!==t._closedPromise_resolve),Nt(void 0!==t._closedPromise_reject),t._closedPromise_reject(e),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0}function vt(t,e){Nt(void 0===t._closedPromise_resolve),Nt(void 0===t._closedPromise_reject),t._closedPromise=Promise.reject(e)}function mt(t){Nt(void 0!==t._closedPromise_resolve),Nt(void 0!==t._closedPromise_reject),t._closedPromise_resolve(void 0),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0}function bt(t){return new TypeError("ReadableStreamBYOBReader.prototype."+t+" can only be used on a ReadableStreamBYOBReader")}function yt(t){return new TypeError("ReadableStreamDefaultController.prototype."+t+" can only be used on a ReadableStreamDefaultController")}function _t(t){return new TypeError("ReadableStreamBYOBRequest.prototype."+t+" can only be used on a ReadableStreamBYOBRequest")}function wt(t){return new TypeError("ReadableByteStreamController.prototype."+t+" can only be used on a ReadableByteStreamController")}function St(t){try{Promise.prototype.then.call(t,void 0,function(){})}catch(t){}}var xt=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),Ct=r(0),At=Ct.ArrayBufferCopy,Tt=Ct.CreateIterResultObject,kt=Ct.IsFiniteNonNegativeNumber,Pt=Ct.InvokeOrNoop,Et=Ct.PromiseInvokeOrNoop,Ot=Ct.TransferArrayBuffer,Rt=Ct.ValidateAndNormalizeQueuingStrategy,Lt=Ct.ValidateAndNormalizeHighWaterMark,Dt=r(0),It=Dt.createArrayFromList,jt=Dt.createDataProperty,Mt=Dt.typeIsObject,Ft=r(1),Nt=Ft.assert,Bt=Ft.rethrowAssertionErrorRejection,Ut=r(3),zt=Ut.DequeueValue,Wt=Ut.EnqueueValueWithSize,qt=Ut.ResetQueue,Xt=r(2),Gt=Xt.AcquireWritableStreamDefaultWriter,Ht=Xt.IsWritableStream,Yt=Xt.IsWritableStreamLocked,Vt=Xt.WritableStreamAbort,Zt=Xt.WritableStreamDefaultWriterCloseWithErrorPropagation,Jt=Xt.WritableStreamDefaultWriterRelease,Kt=Xt.WritableStreamDefaultWriterWrite,Qt=Xt.WritableStreamCloseQueuedOrInFlight,$t=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=r.size,o=r.highWaterMark;i(this,t),this._state="readable",this._reader=void 0,this._storedError=void 0,this._disturbed=!1,this._readableStreamController=void 0;var a=e.type;if("bytes"===String(a))void 0===o&&(o=0),this._readableStreamController=new ne(this,e,o);else{if(void 0!==a)throw new RangeError("Invalid type is specified");void 0===o&&(o=1),this._readableStreamController=new re(this,e,n,o)}}return xt(t,[{key:"cancel",value:function t(e){return!1===a(this)?Promise.reject(lt("cancel")):!0===c(this)?Promise.reject(new TypeError("Cannot cancel a stream that already has a reader")):g(this,e)}},{key:"getReader",value:function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=e.mode;if(!1===a(this))throw lt("getReader");if(void 0===r)return o(this);if("byob"===(r=String(r)))return n(this);throw new RangeError("Invalid mode is specified")}},{key:"pipeThrough",value:function t(e,r){var i=e.writable,n=e.readable;return St(this.pipeTo(i,r)),n}},{key:"pipeTo",value:function t(e){var r=this,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=i.preventClose,s=i.preventAbort,l=i.preventCancel;if(!1===a(this))return Promise.reject(lt("pipeTo"));if(!1===Ht(e))return Promise.reject(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));if(n=Boolean(n),s=Boolean(s),l=Boolean(l),!0===c(this))return Promise.reject(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream"));if(!0===Yt(e))return Promise.reject(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream"));var h=o(this),u=Gt(e),f=!1,d=Promise.resolve();return new Promise(function(t,i){function o(){return d=Promise.resolve(),!0===f?Promise.resolve():u._readyPromise.then(function(){return O(h).then(function(t){var e=t.value;!0!==t.done&&(d=Kt(u,e).catch(function(){}))})}).then(o)}function a(){var t=d;return d.then(function(){return t!==d?a():void 0})}function c(t,e,r){"errored"===t._state?r(t._storedError):e.catch(r).catch(Bt)}function p(t,e,r){"closed"===t._state?r():e.then(r).catch(Bt)}function v(t,r,i){function n(){t().then(function(){return b(r,i)},function(t){return b(!0,t)}).catch(Bt)}!0!==f&&(f=!0,"writable"===e._state&&!1===Qt(e)?a().then(n):n())}function m(t,r){!0!==f&&(f=!0,"writable"===e._state&&!1===Qt(e)?a().then(function(){return b(t,r)}).catch(Bt):b(t,r))}function b(e,r){Jt(u),P(h),e?i(r):t(void 0)}if(c(r,h._closedPromise,function(t){!1===s?v(function(){return Vt(e,t)},!0,t):m(!0,t)}),c(e,u._closedPromise,function(t){!1===l?v(function(){return g(r,t)},!0,t):m(!0,t)}),p(r,h._closedPromise,function(){!1===n?v(function(){return Zt(u)}):m()}),!0===Qt(e)||"closed"===e._state){var y=new TypeError("the destination writable stream closed before all data could be piped to it");!1===l?v(function(){return g(r,y)},!0,y):m(!0,y)}o().catch(function(t){d=Promise.resolve(),Bt(t)})})}},{key:"tee",value:function t(){if(!1===a(this))throw lt("tee");var e=l(this,!1);return It(e)}},{key:"locked",get:function t(){if(!1===a(this))throw lt("locked");return c(this)}}]),t}();t.exports={ReadableStream:$t,IsReadableStreamDisturbed:s,ReadableStreamDefaultControllerClose:I,ReadableStreamDefaultControllerEnqueue:j,ReadableStreamDefaultControllerError:M,ReadableStreamDefaultControllerGetDesiredSize:N};var te=function(){function t(e){if(i(this,t),!1===a(e))throw new TypeError("ReadableStreamDefaultReader can only be constructed with a ReadableStream instance");if(!0===c(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");T(this,e),this._readRequests=[]}return xt(t,[{key:"cancel",value:function t(e){return!1===A(this)?Promise.reject(ut("cancel")):void 0===this._ownerReadableStream?Promise.reject(ht("cancel")):k(this,e)}},{key:"read",value:function t(){return!1===A(this)?Promise.reject(ut("read")):void 0===this._ownerReadableStream?Promise.reject(ht("read from")):O(this)}},{key:"releaseLock",value:function t(){if(!1===A(this))throw ut("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");P(this)}}},{key:"closed",get:function t(){return!1===A(this)?Promise.reject(ut("closed")):this._closedPromise}}]),t}(),ee=function(){function t(e){if(i(this,t),!a(e))throw new TypeError("ReadableStreamBYOBReader can only be constructed with a ReadableStream instance given a byte source");if(!1===B(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");if(c(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");T(this,e),this._readIntoRequests=[]}return xt(t,[{key:"cancel",value:function t(e){return C(this)?void 0===this._ownerReadableStream?Promise.reject(ht("cancel")):k(this,e):Promise.reject(bt("cancel"))}},{key:"read",value:function t(e){return C(this)?void 0===this._ownerReadableStream?Promise.reject(ht("read from")):ArrayBuffer.isView(e)?0===e.byteLength?Promise.reject(new TypeError("view must have non-zero byteLength")):E(this,e):Promise.reject(new TypeError("view must be an array buffer view")):Promise.reject(bt("read"))}},{key:"releaseLock",value:function t(){if(!C(this))throw bt("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readIntoRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");P(this)}}},{key:"closed",get:function t(){return C(this)?this._closedPromise:Promise.reject(bt("closed"))}}]),t}(),re=function(){function t(e,r,n,o){if(i(this,t),!1===a(e))throw new TypeError("ReadableStreamDefaultController can only be constructed with a ReadableStream instance");if(void 0!==e._readableStreamController)throw new TypeError("ReadableStreamDefaultController instances can only be created by the ReadableStream constructor");this._controlledReadableStream=e,this._underlyingSource=r,this._queue=void 0,this._queueTotalSize=void 0,qt(this),this._started=!1,this._closeRequested=!1,this._pullAgain=!1,this._pulling=!1;var s=Rt(n,o);this._strategySize=s.size,this._strategyHWM=s.highWaterMark;var c=this,l=Pt(r,"start",[this]);Promise.resolve(l).then(function(){c._started=!0,Nt(!1===c._pulling),Nt(!1===c._pullAgain),L(c)},function(t){F(c,t)}).catch(Bt)}return xt(t,[{key:"close",value:function t(){if(!1===R(this))throw yt("close");if(!0===this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");var e=this._controlledReadableStream._state;if("readable"!==e)throw new TypeError("The stream (in "+e+" state) is not in the readable state and cannot be closed");I(this)}},{key:"enqueue",value:function t(e){if(!1===R(this))throw yt("enqueue");if(!0===this._closeRequested)throw new TypeError("stream is closed or draining");var r=this._controlledReadableStream._state;if("readable"!==r)throw new TypeError("The stream (in "+r+" state) is not in the readable state and cannot be enqueued to");return j(this,e)}},{key:"error",value:function t(e){if(!1===R(this))throw yt("error");var r=this._controlledReadableStream;if("readable"!==r._state)throw new TypeError("The stream is "+r._state+" and so cannot be errored");M(this,e)}},{key:"__cancelSteps",value:function t(e){return qt(this),Et(this._underlyingSource,"cancel",[e])}},{key:"__pullSteps",value:function t(){var e=this._controlledReadableStream;if(this._queue.length>0){var r=zt(this);return!0===this._closeRequested&&0===this._queue.length?v(e):L(this),Promise.resolve(Tt(r,!1))}var i=p(e);return L(this),i}},{key:"desiredSize",get:function t(){if(!1===R(this))throw yt("desiredSize");return N(this)}}]),t}(),ie=function(){function t(e,r){i(this,t),this._associatedReadableByteStreamController=e,this._view=r}return xt(t,[{key:"respond",value:function t(e){if(!1===U(this))throw _t("respond");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");st(this._associatedReadableByteStreamController,e)}},{key:"respondWithNewView",value:function t(e){if(!1===U(this))throw _t("respond");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");ct(this._associatedReadableByteStreamController,e)}},{key:"view",get:function t(){return this._view}}]),t}(),ne=function(){function t(e,r,n){if(i(this,t),!1===a(e))throw new TypeError("ReadableByteStreamController can only be constructed with a ReadableStream instance given a byte source");if(void 0!==e._readableStreamController)throw new TypeError("ReadableByteStreamController instances can only be created by the ReadableStream constructor given a byte source");this._controlledReadableStream=e,this._underlyingByteSource=r,this._pullAgain=!1,this._pulling=!1,W(this),this._queue=this._queueTotalSize=void 0,qt(this),this._closeRequested=!1,this._started=!1,this._strategyHWM=Lt(n);var o=r.autoAllocateChunkSize;if(void 0!==o&&(!1===Number.isInteger(o)||o<=0))throw new RangeError("autoAllocateChunkSize must be a positive integer");this._autoAllocateChunkSize=o,this._pendingPullIntos=[];var s=this,c=Pt(r,"start",[this]);Promise.resolve(c).then(function(){s._started=!0,Nt(!1===s._pulling),Nt(!1===s._pullAgain),z(s)},function(t){"readable"===e._state&&ot(s,t)}).catch(Bt)}return xt(t,[{key:"close",value:function t(){if(!1===B(this))throw wt("close");if(!0===this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");var e=this._controlledReadableStream._state;if("readable"!==e)throw new TypeError("The stream (in "+e+" state) is not in the readable state and cannot be closed");it(this)}},{key:"enqueue",value:function t(e){if(!1===B(this))throw wt("enqueue");if(!0===this._closeRequested)throw new TypeError("stream is closed or draining");var r=this._controlledReadableStream._state;if("readable"!==r)throw new TypeError("The stream (in "+r+" state) is not in the readable state and cannot be enqueued to");if(!ArrayBuffer.isView(e))throw new TypeError("You can only enqueue array buffer views when using a ReadableByteStreamController");nt(this,e)}},{key:"error",value:function t(e){if(!1===B(this))throw wt("error");var r=this._controlledReadableStream;if("readable"!==r._state)throw new TypeError("The stream is "+r._state+" and so cannot be errored");ot(this,e)}},{key:"__cancelSteps",value:function t(e){if(this._pendingPullIntos.length>0){this._pendingPullIntos[0].bytesFilled=0}return qt(this),Et(this._underlyingByteSource,"cancel",[e])}},{key:"__pullSteps",value:function t(){var e=this._controlledReadableStream;if(Nt(!0===x(e)),this._queueTotalSize>0){Nt(0===w(e));var r=this._queue.shift();this._queueTotalSize-=r.byteLength,V(this);var i=void 0;try{i=new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}catch(t){return Promise.reject(t)}return Promise.resolve(Tt(i,!1))}var n=this._autoAllocateChunkSize;if(void 0!==n){var o=void 0;try{o=new ArrayBuffer(n)}catch(t){return Promise.reject(t)}var a={buffer:o,byteOffset:0,byteLength:n,bytesFilled:0,elementSize:1,ctor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(a)}var s=p(e);return z(this),s}},{key:"byobRequest",get:function t(){if(!1===B(this))throw wt("byobRequest");if(void 0===this._byobRequest&&this._pendingPullIntos.length>0){var e=this._pendingPullIntos[0],r=new Uint8Array(e.buffer,e.byteOffset+e.bytesFilled,e.byteLength-e.bytesFilled);this._byobRequest=new ie(this,r)}return this._byobRequest}},{key:"desiredSize",get:function t(){if(!1===B(this))throw wt("desiredSize");return at(this)}}]),t}()},function(t,e,r){var i=r(6),n=r(4),o=r(2);e.TransformStream=i.TransformStream,e.ReadableStream=n.ReadableStream,e.IsReadableStreamDisturbed=n.IsReadableStreamDisturbed,e.ReadableStreamDefaultControllerClose=n.ReadableStreamDefaultControllerClose,e.ReadableStreamDefaultControllerEnqueue=n.ReadableStreamDefaultControllerEnqueue,e.ReadableStreamDefaultControllerError=n.ReadableStreamDefaultControllerError,e.ReadableStreamDefaultControllerGetDesiredSize=n.ReadableStreamDefaultControllerGetDesiredSize,e.AcquireWritableStreamDefaultWriter=o.AcquireWritableStreamDefaultWriter,e.IsWritableStream=o.IsWritableStream,e.IsWritableStreamLocked=o.IsWritableStreamLocked,e.WritableStream=o.WritableStream,e.WritableStreamAbort=o.WritableStreamAbort,e.WritableStreamDefaultControllerError=o.WritableStreamDefaultControllerError,e.WritableStreamDefaultWriterCloseWithErrorPropagation=o.WritableStreamDefaultWriterCloseWithErrorPropagation,e.WritableStreamDefaultWriterRelease=o.WritableStreamDefaultWriterRelease,e.WritableStreamDefaultWriterWrite=o.WritableStreamDefaultWriterWrite},function(t,e,r){function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t){if(!0===t._errored)throw new TypeError("TransformStream is already errored");if(!0===t._readableClosed)throw new TypeError("Readable side is already closed");s(t)}function o(t,e){if(!0===t._errored)throw new TypeError("TransformStream is already errored");if(!0===t._readableClosed)throw new TypeError("Readable side is already closed");var r=t._readableController;try{E(r,e)}catch(e){throw t._readableClosed=!0,c(t,e),t._storedError}!0==R(r)<=0&&!1===t._backpressure&&u(t,!0)}function a(t,e){if(!0===t._errored)throw new TypeError("TransformStream is already errored");l(t,e)}function s(t){_(!1===t._errored),_(!1===t._readableClosed);try{P(t._readableController)}catch(t){_(!1)}t._readableClosed=!0}function c(t,e){!1===t._errored&&l(t,e)}function l(t,e){_(!1===t._errored),t._errored=!0,t._storedError=e,!1===t._writableDone&&I(t._writableController,e),!1===t._readableClosed&&O(t._readableController,e)}function h(t){return _(void 0!==t._backpressureChangePromise,"_backpressureChangePromise should have been initialized"),!1===t._backpressure?Promise.resolve():(_(!0===t._backpressure,"_backpressure should have been initialized"),t._backpressureChangePromise)}function u(t,e){_(t._backpressure!==e,"TransformStreamSetBackpressure() should be called only when backpressure is changed"),void 0!==t._backpressureChangePromise&&t._backpressureChangePromise_resolve(e),t._backpressureChangePromise=new Promise(function(e){t._backpressureChangePromise_resolve=e}),t._backpressureChangePromise.then(function(t){_(t!==e,"_backpressureChangePromise should be fulfilled only when backpressure is changed")}),t._backpressure=e}function f(t,e){return o(e._controlledTransformStream,t),Promise.resolve()}function d(t,e){_(!1===t._errored),_(!1===t._transforming),_(!1===t._backpressure),t._transforming=!0;var r=t._transformer,i=t._transformStreamController;return x(r,"transform",[e,i],f,[e,i]).then(function(){return t._transforming=!1,h(t)},function(e){return c(t,e),Promise.reject(e)})}function p(t){return!!A(t)&&!!Object.prototype.hasOwnProperty.call(t,"_controlledTransformStream")}function g(t){return!!A(t)&&!!Object.prototype.hasOwnProperty.call(t,"_transformStreamController")}function v(t){return new TypeError("TransformStreamDefaultController.prototype."+t+" can only be used on a TransformStreamDefaultController")}function m(t){return new TypeError("TransformStream.prototype."+t+" can only be used on a TransformStream")}var b=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),y=r(1),_=y.assert,w=r(0),S=w.InvokeOrNoop,x=w.PromiseInvokeOrPerformFallback,C=w.PromiseInvokeOrNoop,A=w.typeIsObject,T=r(4),k=T.ReadableStream,P=T.ReadableStreamDefaultControllerClose,E=T.ReadableStreamDefaultControllerEnqueue,O=T.ReadableStreamDefaultControllerError,R=T.ReadableStreamDefaultControllerGetDesiredSize,L=r(2),D=L.WritableStream,I=L.WritableStreamDefaultControllerError,j=function(){function t(e,r){i(this,t),this._transformStream=e,this._startPromise=r}return b(t,[{key:"start",value:function t(e){var r=this._transformStream;return r._writableController=e,this._startPromise.then(function(){return h(r)})}},{key:"write",value:function t(e){return d(this._transformStream,e)}},{key:"abort",value:function t(){var e=this._transformStream;e._writableDone=!0,l(e,new TypeError("Writable side aborted"))}},{key:"close",value:function t(){var e=this._transformStream;return _(!1===e._transforming),e._writableDone=!0,C(e._transformer,"flush",[e._transformStreamController]).then(function(){return!0===e._errored?Promise.reject(e._storedError):(!1===e._readableClosed&&s(e),Promise.resolve())}).catch(function(t){return c(e,t),Promise.reject(e._storedError)})}}]),t}(),M=function(){function t(e,r){i(this,t),this._transformStream=e,this._startPromise=r}return b(t,[{key:"start",value:function t(e){var r=this._transformStream;return r._readableController=e,this._startPromise.then(function(){return _(void 0!==r._backpressureChangePromise,"_backpressureChangePromise should have been initialized"),!0===r._backpressure?Promise.resolve():(_(!1===r._backpressure,"_backpressure should have been initialized"),r._backpressureChangePromise)})}},{key:"pull",value:function t(){var e=this._transformStream;return _(!0===e._backpressure,"pull() should be never called while _backpressure is false"),_(void 0!==e._backpressureChangePromise,"_backpressureChangePromise should have been initialized"),u(e,!1),e._backpressureChangePromise}},{key:"cancel",value:function t(){var e=this._transformStream;e._readableClosed=!0,l(e,new TypeError("Readable side canceled"))}}]),t}(),F=function(){function t(e){if(i(this,t),!1===g(e))throw new TypeError("TransformStreamDefaultController can only be constructed with a TransformStream instance");if(void 0!==e._transformStreamController)throw new TypeError("TransformStreamDefaultController instances can only be created by the TransformStream constructor");this._controlledTransformStream=e}return b(t,[{key:"enqueue",value:function t(e){if(!1===p(this))throw v("enqueue");o(this._controlledTransformStream,e)}},{key:"close",value:function t(){if(!1===p(this))throw v("close");n(this._controlledTransformStream)}},{key:"error",value:function t(e){if(!1===p(this))throw v("error");a(this._controlledTransformStream,e)}},{key:"desiredSize",get:function t(){if(!1===p(this))throw v("desiredSize");var e=this._controlledTransformStream,r=e._readableController;return R(r)}}]),t}(),N=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};i(this,t),this._transformer=e;var r=e.readableStrategy,n=e.writableStrategy;this._transforming=!1,this._errored=!1,this._storedError=void 0,this._writableController=void 0,this._readableController=void 0,this._transformStreamController=void 0,this._writableDone=!1,this._readableClosed=!1,this._backpressure=void 0,this._backpressureChangePromise=void 0,this._backpressureChangePromise_resolve=void 0,this._transformStreamController=new F(this);var o=void 0,a=new Promise(function(t){o=t}),s=new M(this,a);this._readable=new k(s,r);var c=new j(this,a);this._writable=new D(c,n),_(void 0!==this._writableController),_(void 0!==this._readableController),u(this,R(this._readableController)<=0);var l=this,h=S(e,"start",[l._transformStreamController]);o(h),a.catch(function(t){!1===l._errored&&(l._errored=!0,l._storedError=t)})}return b(t,[{key:"readable",get:function t(){if(!1===g(this))throw m("readable");return this._readable}},{key:"writable",get:function t(){if(!1===g(this))throw m("writable");return this._writable}}]),t}();t.exports={TransformStream:N}},function(t,e,r){t.exports=r(5)}]))},function(t,e,r){"use strict";function i(t){t.mozCurrentTransform||(t._originalSave=t.save,t._originalRestore=t.restore,t._originalRotate=t.rotate,t._originalScale=t.scale,t._originalTranslate=t.translate,t._originalTransform=t.transform,t._originalSetTransform=t.setTransform,t._transformMatrix=t._transformMatrix||[1,0,0,1,0,0],t._transformStack=[],Object.defineProperty(t,"mozCurrentTransform",{get:function t(){return this._transformMatrix}}),Object.defineProperty(t,"mozCurrentTransformInverse",{get:function t(){var e=this._transformMatrix,r=e[0],i=e[1],n=e[2],o=e[3],a=e[4],s=e[5],c=r*o-i*n,l=i*n-r*o;return[o/c,i/l,n/l,r/c,(o*a-n*s)/l,(i*a-r*s)/c]}}),t.save=function t(){var e=this._transformMatrix;this._transformStack.push(e),this._transformMatrix=e.slice(0,6),this._originalSave()},t.restore=function t(){var e=this._transformStack.pop();e&&(this._transformMatrix=e,this._originalRestore())},t.translate=function t(e,r){var i=this._transformMatrix;i[4]=i[0]*e+i[2]*r+i[4],i[5]=i[1]*e+i[3]*r+i[5],this._originalTranslate(e,r)},t.scale=function t(e,r){var i=this._transformMatrix;i[0]=i[0]*e,i[1]=i[1]*e,i[2]=i[2]*r,i[3]=i[3]*r,this._originalScale(e,r)},t.transform=function e(r,i,n,o,a,s){var c=this._transformMatrix;this._transformMatrix=[c[0]*r+c[2]*i,c[1]*r+c[3]*i,c[0]*n+c[2]*o,c[1]*n+c[3]*o,c[0]*a+c[2]*s+c[4],c[1]*a+c[3]*s+c[5]],t._originalTransform(r,i,n,o,a,s)},t.setTransform=function e(r,i,n,o,a,s){this._transformMatrix=[r,i,n,o,a,s],t._originalSetTransform(r,i,n,o,a,s)},t.rotate=function t(e){var r=Math.cos(e),i=Math.sin(e),n=this._transformMatrix;this._transformMatrix=[n[0]*r+n[2]*i,n[1]*r+n[3]*i,n[0]*-i+n[2]*r,n[1]*-i+n[3]*r,n[4],n[5]],this._originalRotate(e)})}function n(t){var e=1e3,r=t.width,i=t.height,n,o,a,s=r+1,c=new Uint8Array(s*(i+1)),l=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),h=r+7&-8,u=t.data,f=new Uint8Array(h*i),d=0,p;for(n=0,p=u.length;n<p;n++)for(var g=128,v=u[n];g>0;)f[d++]=v&g?0:255,g>>=1;var m=0;for(d=0,0!==f[d]&&(c[0]=1,++m),o=1;o<r;o++)f[d]!==f[d+1]&&(c[o]=f[d]?2:1,++m),d++;for(0!==f[d]&&(c[o]=2,++m),n=1;n<i;n++){d=n*h,a=n*s,f[d-h]!==f[d]&&(c[a]=f[d]?1:8,++m);var b=(f[d]?4:0)+(f[d-h]?8:0);for(o=1;o<r;o++)b=(b>>2)+(f[d+1]?4:0)+(f[d-h+1]?8:0),l[b]&&(c[a+o]=l[b],++m),d++;if(f[d-h]!==f[d]&&(c[a+o]=f[d]?2:4,++m),m>1e3)return null}for(d=h*(i-1),a=n*s,0!==f[d]&&(c[a]=8,++m),o=1;o<r;o++)f[d]!==f[d+1]&&(c[a+o]=f[d]?4:8,++m),d++;if(0!==f[d]&&(c[a+o]=4,++m),m>1e3)return null;var y=new Int32Array([0,s,-1,0,-s,0,0,0,1]),_=[];for(n=0;m&&n<=i;n++){for(var w=n*s,S=w+r;w<S&&!c[w];)w++;if(w!==S){var x=[w%s,n],C=c[w],A=w,T;do{var k=y[C];do{w+=k}while(!c[w]);T=c[w],5!==T&&10!==T?(C=T,c[w]=0):(C=T&51*C>>4,c[w]&=C>>2|C<<2),x.push(w%s),x.push(w/s|0),--m}while(A!==w);_.push(x),--n}}return function t(e){e.save(),e.scale(1/r,-1/i),e.translate(0,-i),e.beginPath();for(var n=0,o=_.length;n<o;n++){var a=_[n];e.moveTo(a[0],a[1]);for(var s=2,c=a.length;s<c;s+=2)e.lineTo(a[s],a[s+1])}e.fill(),e.beginPath(),e.restore()}}Object.defineProperty(e,"__esModule",{value:!0}),e.CanvasGraphics=void 0;var o=r(0),a=r(12),s=r(7),c=16,l=100,h=4096,u=.65,f=!0,d=1e3,p=16,g={get value(){return(0,o.shadow)(g,"value",(0,o.isLittleEndian)())}},v=function t(){function e(t){this.canvasFactory=t,this.cache=Object.create(null)}return e.prototype={getCanvas:function t(e,r,n,o){var a;return void 0!==this.cache[e]?(a=this.cache[e],this.canvasFactory.reset(a,r,n),a.context.setTransform(1,0,0,1,0,0)):(a=this.canvasFactory.create(r,n),this.cache[e]=a),o&&i(a.context),a},clear:function t(){for(var e in this.cache){var r=this.cache[e];this.canvasFactory.destroy(r),delete this.cache[e]}}},e}(),m=function t(){function e(){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=o.IDENTITY_MATRIX,this.textMatrixScale=1,this.fontMatrix=o.FONT_IDENTITY_MATRIX,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=o.TextRenderingMode.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.resumeSMaskCtx=null}return e.prototype={clone:function t(){return Object.create(this)},setCurrentPoint:function t(e,r){this.x=e,this.y=r}},e}(),b=function t(){function e(t,e,r,n,o){this.ctx=t,this.current=new m,this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=e,this.objs=r,this.canvasFactory=n,this.imageLayer=o,this.groupStack=[],this.processingType3=null,this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.smaskCounter=0,this.tempSMask=null,this.cachedCanvases=new v(this.canvasFactory),t&&i(t),this.cachedGetSinglePixelWidth=null}function r(t,e){if("undefined"!=typeof ImageData&&e instanceof ImageData)return void t.putImageData(e,0,0);var r=e.height,i=e.width,n=r%p,a=(r-n)/p,s=0===n?a:a+1,c=t.createImageData(i,p),l=0,h,u=e.data,f=c.data,d,v,m,b;if(e.kind===o.ImageKind.GRAYSCALE_1BPP){var y=u.byteLength,_=new Uint32Array(f.buffer,0,f.byteLength>>2),w=_.length,S=i+7>>3,x=4294967295,C=g.value?4278190080:255;for(d=0;d<s;d++){for(m=d<a?p:n,h=0,v=0;v<m;v++){for(var A=y-l,T=0,k=A>S?i:8*A-7,P=-8&k,E=0,O=0;T<P;T+=8)O=u[l++],_[h++]=128&O?x:C,_[h++]=64&O?x:C,_[h++]=32&O?x:C,_[h++]=16&O?x:C,_[h++]=8&O?x:C,_[h++]=4&O?x:C,_[h++]=2&O?x:C,_[h++]=1&O?x:C;for(;T<k;T++)0===E&&(O=u[l++],E=128),_[h++]=O&E?x:C,E>>=1}for(;h<w;)_[h++]=0;t.putImageData(c,0,d*p)}}else if(e.kind===o.ImageKind.RGBA_32BPP){for(v=0,b=i*p*4,d=0;d<a;d++)f.set(u.subarray(l,l+b)),l+=b,t.putImageData(c,0,v),v+=p;d<s&&(b=i*n*4,f.set(u.subarray(l,l+b)),t.putImageData(c,0,v))}else{if(e.kind!==o.ImageKind.RGB_24BPP)throw new Error("bad image kind: "+e.kind);for(m=p,b=i*m,d=0;d<s;d++){for(d>=a&&(m=n,b=i*m),h=0,v=b;v--;)f[h++]=u[l++],f[h++]=u[l++],f[h++]=u[l++],f[h++]=255;t.putImageData(c,0,d*p)}}}function c(t,e){for(var r=e.height,i=e.width,n=r%p,o=(r-n)/p,a=0===n?o:o+1,s=t.createImageData(i,p),c=0,l=e.data,h=s.data,u=0;u<a;u++){for(var f=u<o?p:n,d=3,g=0;g<f;g++)for(var v=0,m=0;m<i;m++){if(!v){var b=l[c++];v=128}h[d]=b&v?0:255,d+=4,v>>=1}t.putImageData(s,0,u*p)}}function l(t,e){for(var r=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font"],i=0,n=r.length;i<n;i++){var o=r[i];void 0!==t[o]&&(e[o]=t[o])}void 0!==t.setLineDash&&(e.setLineDash(t.getLineDash()),e.lineDashOffset=t.lineDashOffset)}function h(t){t.strokeStyle="#000000",t.fillStyle="#000000",t.fillRule="nonzero",t.globalAlpha=1,t.lineWidth=1,t.lineCap="butt",t.lineJoin="miter",t.miterLimit=10,t.globalCompositeOperation="source-over",t.font="10px sans-serif",void 0!==t.setLineDash&&(t.setLineDash([]),t.lineDashOffset=0)}function u(t,e,r,i){for(var n=t.length,o=3;o<n;o+=4){var a=t[o];if(0===a)t[o-3]=e,t[o-2]=r,t[o-1]=i;else if(a<255){var s=255-a;t[o-3]=t[o-3]*a+e*s>>8,t[o-2]=t[o-2]*a+r*s>>8,t[o-1]=t[o-1]*a+i*s>>8}}}function f(t,e,r){for(var i=t.length,n=1/255,o=3;o<i;o+=4){var a=r?r[t[o]]:t[o];e[o]=e[o]*a*(1/255)|0}}function d(t,e,r){for(var i=t.length,n=3;n<i;n+=4){var o=77*t[n-3]+152*t[n-2]+28*t[n-1];e[n]=r?e[n]*r[o>>8]>>8:e[n]*o>>16}}function b(t,e,r,i,n,o,a){var s=!!o,c=s?o[0]:0,l=s?o[1]:0,h=s?o[2]:0,p;p="Luminosity"===n?d:f;for(var g=1048576,v=Math.min(i,Math.ceil(1048576/r)),m=0;m<i;m+=v){var b=Math.min(v,i-m),y=t.getImageData(0,m,r,b),_=e.getImageData(0,m,r,b);s&&u(y.data,c,l,h),p(y.data,_.data,a),t.putImageData(_,0,m)}}function y(t,e,r){var i=e.canvas,n=e.context;t.setTransform(e.scaleX,0,0,e.scaleY,e.offsetX,e.offsetY);var o=e.backdrop||null;if(!e.transferMap&&s.WebGLUtils.isEnabled){var a=s.WebGLUtils.composeSMask(r.canvas,i,{subtype:e.subtype,backdrop:o});return t.setTransform(1,0,0,1,0,0),void t.drawImage(a,e.offsetX,e.offsetY)}b(n,r,i.width,i.height,e.subtype,o,e.transferMap),t.drawImage(i,0,0)}var _=15,w=10,S=["butt","round","square"],x=["miter","round","bevel"],C={},A={};e.prototype={beginDrawing:function t(e){var r=e.transform,i=e.viewport,n=e.transparency,o=e.background,a=void 0===o?null:o,s=this.ctx.canvas.width,c=this.ctx.canvas.height;if(this.ctx.save(),this.ctx.fillStyle=a||"rgb(255, 255, 255)",this.ctx.fillRect(0,0,s,c),this.ctx.restore(),n){var l=this.cachedCanvases.getCanvas("transparent",s,c,!0);this.compositeCtx=this.ctx,this.transparentCanvas=l.canvas,this.ctx=l.context,this.ctx.save(),this.ctx.transform.apply(this.ctx,this.compositeCtx.mozCurrentTransform)}this.ctx.save(),h(this.ctx),r&&this.ctx.transform.apply(this.ctx,r),this.ctx.transform.apply(this.ctx,i.transform),this.baseTransform=this.ctx.mozCurrentTransform.slice(),this.imageLayer&&this.imageLayer.beginLayout()},executeOperatorList:function t(e,r,i,n){var a=e.argsArray,s=e.fnArray,c=r||0,l=a.length;if(l===c)return c;for(var h=l-c>10&&"function"==typeof i,u=h?Date.now()+15:0,f=0,d=this.commonObjs,p=this.objs,g;;){if(void 0!==n&&c===n.nextBreakPoint)return n.breakIt(c,i),c;if((g=s[c])!==o.OPS.dependency)this[g].apply(this,a[c]);else for(var v=a[c],m=0,b=v.length;m<b;m++){var y=v[m],_="g"===y[0]&&"_"===y[1],w=_?d:p;if(!w.isResolved(y))return w.get(y,i),c}if(++c===l)return c;if(h&&++f>10){if(Date.now()>u)return i(),c;f=0}}},endDrawing:function t(){null!==this.current.activeSMask&&this.endSMaskGroup(),this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null),this.cachedCanvases.clear(),s.WebGLUtils.clear(),this.imageLayer&&this.imageLayer.endLayout()},setLineWidth:function t(e){this.current.lineWidth=e,this.ctx.lineWidth=e},setLineCap:function t(e){this.ctx.lineCap=S[e]},setLineJoin:function t(e){this.ctx.lineJoin=x[e]},setMiterLimit:function t(e){this.ctx.miterLimit=e},setDash:function t(e,r){var i=this.ctx;void 0!==i.setLineDash&&(i.setLineDash(e),i.lineDashOffset=r)},setRenderingIntent:function t(e){},setFlatness:function t(e){},setGState:function t(e){for(var r=0,i=e.length;r<i;r++){var n=e[r],o=n[0],a=n[1];switch(o){case"LW":this.setLineWidth(a);break;case"LC":this.setLineCap(a);break;case"LJ":this.setLineJoin(a);break;case"ML":this.setMiterLimit(a);break;case"D":this.setDash(a[0],a[1]);break;case"RI":this.setRenderingIntent(a);break;case"FL":this.setFlatness(a);break;case"Font":this.setFont(a[0],a[1]);break;case"CA":this.current.strokeAlpha=n[1];break;case"ca":this.current.fillAlpha=n[1],this.ctx.globalAlpha=n[1];break;case"BM":this.ctx.globalCompositeOperation=a;break;case"SMask":this.current.activeSMask&&(this.stateStack.length>0&&this.stateStack[this.stateStack.length-1].activeSMask===this.current.activeSMask?this.suspendSMaskGroup():this.endSMaskGroup()),this.current.activeSMask=a?this.tempSMask:null,this.current.activeSMask&&this.beginSMaskGroup(),this.tempSMask=null}}},beginSMaskGroup:function t(){var e=this.current.activeSMask,r=e.canvas.width,i=e.canvas.height,n="smaskGroupAt"+this.groupLevel,o=this.cachedCanvases.getCanvas(n,r,i,!0),a=this.ctx,s=a.mozCurrentTransform;this.ctx.save();var c=o.context;c.scale(1/e.scaleX,1/e.scaleY),c.translate(-e.offsetX,-e.offsetY),c.transform.apply(c,s),e.startTransformInverse=c.mozCurrentTransformInverse,l(a,c),this.ctx=c,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(a),this.groupLevel++},suspendSMaskGroup:function t(){var e=this.ctx;this.groupLevel--,this.ctx=this.groupStack.pop(),y(this.ctx,this.current.activeSMask,e),this.ctx.restore(),this.ctx.save(),l(e,this.ctx),this.current.resumeSMaskCtx=e;var r=o.Util.transform(this.current.activeSMask.startTransformInverse,e.mozCurrentTransform);this.ctx.transform.apply(this.ctx,r),e.save(),e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,e.canvas.width,e.canvas.height),e.restore()},resumeSMaskGroup:function t(){var e=this.current.resumeSMaskCtx,r=this.ctx;this.ctx=e,this.groupStack.push(r),this.groupLevel++},endSMaskGroup:function t(){var e=this.ctx;this.groupLevel--,this.ctx=this.groupStack.pop(),y(this.ctx,this.current.activeSMask,e),this.ctx.restore(),l(e,this.ctx);var r=o.Util.transform(this.current.activeSMask.startTransformInverse,e.mozCurrentTransform);this.ctx.transform.apply(this.ctx,r)},save:function t(){this.ctx.save();var e=this.current;this.stateStack.push(e),this.current=e.clone(),this.current.resumeSMaskCtx=null},restore:function t(){this.current.resumeSMaskCtx&&this.resumeSMaskGroup(),null===this.current.activeSMask||0!==this.stateStack.length&&this.stateStack[this.stateStack.length-1].activeSMask===this.current.activeSMask||this.endSMaskGroup(),0!==this.stateStack.length&&(this.current=this.stateStack.pop(),this.ctx.restore(),this.pendingClip=null,this.cachedGetSinglePixelWidth=null)},transform:function t(e,r,i,n,o,a){this.ctx.transform(e,r,i,n,o,a),this.cachedGetSinglePixelWidth=null},constructPath:function t(e,r){for(var i=this.ctx,n=this.current,a=n.x,s=n.y,c=0,l=0,h=e.length;c<h;c++)switch(0|e[c]){case o.OPS.rectangle:a=r[l++],s=r[l++];var u=r[l++],f=r[l++];0===u&&(u=this.getSinglePixelWidth()),0===f&&(f=this.getSinglePixelWidth());var d=a+u,p=s+f;this.ctx.moveTo(a,s),this.ctx.lineTo(d,s),this.ctx.lineTo(d,p),this.ctx.lineTo(a,p),this.ctx.lineTo(a,s),this.ctx.closePath();break;case o.OPS.moveTo:a=r[l++],s=r[l++],i.moveTo(a,s);break;case o.OPS.lineTo:a=r[l++],s=r[l++],i.lineTo(a,s);break;case o.OPS.curveTo:a=r[l+4],s=r[l+5],i.bezierCurveTo(r[l],r[l+1],r[l+2],r[l+3],a,s),l+=6;break;case o.OPS.curveTo2:i.bezierCurveTo(a,s,r[l],r[l+1],r[l+2],r[l+3]),a=r[l+2],s=r[l+3],l+=4;break;case o.OPS.curveTo3:a=r[l+2],s=r[l+3],i.bezierCurveTo(r[l],r[l+1],a,s,a,s),l+=4;break;case o.OPS.closePath:i.closePath()}n.setCurrentPoint(a,s)},closePath:function t(){this.ctx.closePath()},stroke:function t(e){e=void 0===e||e;var r=this.ctx,i=this.current.strokeColor;r.lineWidth=Math.max(.65*this.getSinglePixelWidth(),this.current.lineWidth),r.globalAlpha=this.current.strokeAlpha,i&&i.hasOwnProperty("type")&&"Pattern"===i.type?(r.save(),r.strokeStyle=i.getPattern(r,this),r.stroke(),r.restore()):r.stroke(),e&&this.consumePath(),r.globalAlpha=this.current.fillAlpha},closeStroke:function t(){this.closePath(),this.stroke()},fill:function t(e){e=void 0===e||e;var r=this.ctx,i=this.current.fillColor,n=this.current.patternFill,o=!1;n&&(r.save(),this.baseTransform&&r.setTransform.apply(r,this.baseTransform),r.fillStyle=i.getPattern(r,this),o=!0),this.pendingEOFill?(r.fill("evenodd"),this.pendingEOFill=!1):r.fill(),o&&r.restore(),e&&this.consumePath()},eoFill:function t(){this.pendingEOFill=!0,this.fill()},fillStroke:function t(){this.fill(!1),this.stroke(!1),this.consumePath()},eoFillStroke:function t(){this.pendingEOFill=!0,this.fillStroke()},closeFillStroke:function t(){this.closePath(),this.fillStroke()},closeEOFillStroke:function t(){this.pendingEOFill=!0,this.closePath(),this.fillStroke()},endPath:function t(){this.consumePath()},clip:function t(){this.pendingClip=C},eoClip:function t(){this.pendingClip=A},beginText:function t(){this.current.textMatrix=o.IDENTITY_MATRIX,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0},endText:function t(){var e=this.pendingTextPaths,r=this.ctx;if(void 0===e)return void r.beginPath();r.save(),r.beginPath();for(var i=0;i<e.length;i++){var n=e[i];r.setTransform.apply(r,n.transform),r.translate(n.x,n.y),n.addToPath(r,n.fontSize)}r.restore(),r.clip(),r.beginPath(),delete this.pendingTextPaths},setCharSpacing:function t(e){this.current.charSpacing=e},setWordSpacing:function t(e){this.current.wordSpacing=e},setHScale:function t(e){this.current.textHScale=e/100},setLeading:function t(e){this.current.leading=-e},setFont:function t(e,r){var i=this.commonObjs.get(e),n=this.current;if(!i)throw new Error("Can't find font for "+e);if(n.fontMatrix=i.fontMatrix?i.fontMatrix:o.FONT_IDENTITY_MATRIX,0!==n.fontMatrix[0]&&0!==n.fontMatrix[3]||(0,o.warn)("Invalid font matrix for font "+e),r<0?(r=-r,n.fontDirection=-1):n.fontDirection=1,this.current.font=i,this.current.fontSize=r,!i.isType3Font){var a=i.loadedName||"sans-serif",s=i.black?"900":i.bold?"bold":"normal",c=i.italic?"italic":"normal",l='"'+a+'", '+i.fallbackName,h=r<16?16:r>100?100:r;this.current.fontSizeScale=r/h;var u=c+" "+s+" "+h+"px "+l;this.ctx.font=u}},setTextRenderingMode:function t(e){this.current.textRenderingMode=e},setTextRise:function t(e){this.current.textRise=e},moveText:function t(e,r){this.current.x=this.current.lineX+=e,this.current.y=this.current.lineY+=r},setLeadingMoveText:function t(e,r){this.setLeading(-r),this.moveText(e,r)},setTextMatrix:function t(e,r,i,n,o,a){this.current.textMatrix=[e,r,i,n,o,a],this.current.textMatrixScale=Math.sqrt(e*e+r*r),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0},nextLine:function t(){this.moveText(0,this.current.leading)},paintChar:function t(e,r,i){var n=this.ctx,a=this.current,s=a.font,c=a.textRenderingMode,l=a.fontSize/a.fontSizeScale,h=c&o.TextRenderingMode.FILL_STROKE_MASK,u=!!(c&o.TextRenderingMode.ADD_TO_PATH_FLAG),f;if((s.disableFontFace||u)&&(f=s.getPathGenerator(this.commonObjs,e)),s.disableFontFace?(n.save(),n.translate(r,i),n.beginPath(),f(n,l),h!==o.TextRenderingMode.FILL&&h!==o.TextRenderingMode.FILL_STROKE||n.fill(),h!==o.TextRenderingMode.STROKE&&h!==o.TextRenderingMode.FILL_STROKE||n.stroke(),n.restore()):(h!==o.TextRenderingMode.FILL&&h!==o.TextRenderingMode.FILL_STROKE||n.fillText(e,r,i),h!==o.TextRenderingMode.STROKE&&h!==o.TextRenderingMode.FILL_STROKE||n.strokeText(e,r,i)),u){(this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:n.mozCurrentTransform,x:r,y:i,fontSize:l,addToPath:f})}},get isFontSubpixelAAEnabled(){var t=this.canvasFactory.create(10,10).context;t.scale(1.5,1),t.fillText("I",0,10);for(var e=t.getImageData(0,0,10,10).data,r=!1,i=3;i<e.length;i+=4)if(e[i]>0&&e[i]<255){r=!0;break}return(0,o.shadow)(this,"isFontSubpixelAAEnabled",r)},showText:function t(e){var r=this.current,i=r.font;if(i.isType3Font)return this.showType3Text(e);var n=r.fontSize;if(0!==n){var a=this.ctx,s=r.fontSizeScale,c=r.charSpacing,l=r.wordSpacing,h=r.fontDirection,u=r.textHScale*h,f=e.length,d=i.vertical,p=d?1:-1,g=i.defaultVMetrics,v=n*r.fontMatrix[0],m=r.textRenderingMode===o.TextRenderingMode.FILL&&!i.disableFontFace;a.save(),a.transform.apply(a,r.textMatrix),a.translate(r.x,r.y+r.textRise),r.patternFill&&(a.fillStyle=r.fillColor.getPattern(a,this)),h>0?a.scale(u,-1):a.scale(u,1);var b=r.lineWidth,y=r.textMatrixScale;if(0===y||0===b){var _=r.textRenderingMode&o.TextRenderingMode.FILL_STROKE_MASK;_!==o.TextRenderingMode.STROKE&&_!==o.TextRenderingMode.FILL_STROKE||(this.cachedGetSinglePixelWidth=null,b=.65*this.getSinglePixelWidth())}else b/=y;1!==s&&(a.scale(s,s),b/=s),a.lineWidth=b;var w=0,S;for(S=0;S<f;++S){var x=e[S];if((0,o.isNum)(x))w+=p*x*n/1e3;else{var C=!1,A=(x.isSpace?l:0)+c,T=x.fontChar,k=x.accent,P,E,O,R,L=x.width;if(d){var D,I,j;D=x.vmetric||g,I=x.vmetric?D[1]:.5*L,I=-I*v,j=D[2]*v,L=D?-D[0]:L,P=I/s,E=(w+j)/s}else P=w/s,E=0;if(i.remeasure&&L>0){var M=1e3*a.measureText(T).width/n*s;if(L<M&&this.isFontSubpixelAAEnabled){var F=L/M;C=!0,a.save(),a.scale(F,1),P/=F}else L!==M&&(P+=(L-M)/2e3*n/s)}(x.isInFont||i.missingFile)&&(m&&!k?a.fillText(T,P,E):(this.paintChar(T,P,E),k&&(O=P+k.offset.x/s,R=E-k.offset.y/s,this.paintChar(k.fontChar,O,R))));w+=L*v+A*h,C&&a.restore()}}d?r.y-=w*u:r.x+=w*u,a.restore()}},showType3Text:function t(e){var r=this.ctx,i=this.current,n=i.font,a=i.fontSize,s=i.fontDirection,c=n.vertical?1:-1,l=i.charSpacing,h=i.wordSpacing,u=i.textHScale*s,f=i.fontMatrix||o.FONT_IDENTITY_MATRIX,d=e.length,p=i.textRenderingMode===o.TextRenderingMode.INVISIBLE,g,v,m,b;if(!p&&0!==a){for(this.cachedGetSinglePixelWidth=null,r.save(),r.transform.apply(r,i.textMatrix),r.translate(i.x,i.y),r.scale(u,s),g=0;g<d;++g)if(v=e[g],(0,o.isNum)(v))b=c*v*a/1e3,this.ctx.translate(b,0),i.x+=b*u;else{var y=(v.isSpace?h:0)+l,_=n.charProcOperatorList[v.operatorListId];if(_){this.processingType3=v,this.save(),r.scale(a,a),r.transform.apply(r,f),this.executeOperatorList(_),this.restore();var w=o.Util.applyTransform([v.width,0],f);m=w[0]*a+y,r.translate(m,0),i.x+=m*u}else(0,o.warn)('Type3 character "'+v.operatorListId+'" is not available.')}r.restore(),this.processingType3=null}},setCharWidth:function t(e,r){},setCharWidthAndBounds:function t(e,r,i,n,o,a){this.ctx.rect(i,n,o-i,a-n),this.clip(),this.endPath()},getColorN_Pattern:function t(r){var i=this,n;if("TilingPattern"===r[0]){var o=r[1],s=this.baseTransform||this.ctx.mozCurrentTransform.slice(),c={createCanvasGraphics:function t(r){return new e(r,i.commonObjs,i.objs,i.canvasFactory)}};n=new a.TilingPattern(r,o,this.ctx,c,s)}else n=(0,a.getShadingPatternFromIR)(r);return n},setStrokeColorN:function t(){this.current.strokeColor=this.getColorN_Pattern(arguments)},setFillColorN:function t(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0},setStrokeRGBColor:function t(e,r,i){var n=o.Util.makeCssRgb(e,r,i);this.ctx.strokeStyle=n,this.current.strokeColor=n},setFillRGBColor:function t(e,r,i){var n=o.Util.makeCssRgb(e,r,i);this.ctx.fillStyle=n,this.current.fillColor=n,this.current.patternFill=!1},shadingFill:function t(e){var r=this.ctx;this.save();var i=(0,a.getShadingPatternFromIR)(e);r.fillStyle=i.getPattern(r,this,!0);var n=r.mozCurrentTransformInverse;if(n){var s=r.canvas,c=s.width,l=s.height,h=o.Util.applyTransform([0,0],n),u=o.Util.applyTransform([0,l],n),f=o.Util.applyTransform([c,0],n),d=o.Util.applyTransform([c,l],n),p=Math.min(h[0],u[0],f[0],d[0]),g=Math.min(h[1],u[1],f[1],d[1]),v=Math.max(h[0],u[0],f[0],d[0]),m=Math.max(h[1],u[1],f[1],d[1]);this.ctx.fillRect(p,g,v-p,m-g)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.restore()},beginInlineImage:function t(){throw new Error("Should not call beginInlineImage")},beginImageData:function t(){throw new Error("Should not call beginImageData")},paintFormXObjectBegin:function t(e,r){if(this.save(),this.baseTransformStack.push(this.baseTransform),(0,o.isArray)(e)&&6===e.length&&this.transform.apply(this,e),this.baseTransform=this.ctx.mozCurrentTransform,(0,o.isArray)(r)&&4===r.length){var i=r[2]-r[0],n=r[3]-r[1];this.ctx.rect(r[0],r[1],i,n),this.clip(),this.endPath()}},paintFormXObjectEnd:function t(){this.restore(),this.baseTransform=this.baseTransformStack.pop()},beginGroup:function t(e){this.save();var r=this.ctx;e.isolated||(0,o.info)("TODO: Support non-isolated groups."),e.knockout&&(0,o.warn)("Knockout groups not supported.");var i=r.mozCurrentTransform;if(e.matrix&&r.transform.apply(r,e.matrix),!e.bbox)throw new Error("Bounding box is required.");var n=o.Util.getAxialAlignedBoundingBox(e.bbox,r.mozCurrentTransform),a=[0,0,r.canvas.width,r.canvas.height];n=o.Util.intersect(n,a)||[0,0,0,0];var s=Math.floor(n[0]),c=Math.floor(n[1]),h=Math.max(Math.ceil(n[2])-s,1),u=Math.max(Math.ceil(n[3])-c,1),f=1,d=1;h>4096&&(f=h/4096,h=4096),u>4096&&(d=u/4096,u=4096);var p="groupAt"+this.groupLevel;e.smask&&(p+="_smask_"+this.smaskCounter++%2);var g=this.cachedCanvases.getCanvas(p,h,u,!0),v=g.context;v.scale(1/f,1/d),v.translate(-s,-c),v.transform.apply(v,i),e.smask?this.smaskStack.push({canvas:g.canvas,context:v,offsetX:s,offsetY:c,scaleX:f,scaleY:d,subtype:e.smask.subtype,backdrop:e.smask.backdrop,transferMap:e.smask.transferMap||null,startTransformInverse:null}):(r.setTransform(1,0,0,1,0,0),r.translate(s,c),r.scale(f,d)),l(r,v),this.ctx=v,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(r),this.groupLevel++,this.current.activeSMask=null},endGroup:function t(e){this.groupLevel--;var r=this.ctx;this.ctx=this.groupStack.pop(),void 0!==this.ctx.imageSmoothingEnabled?this.ctx.imageSmoothingEnabled=!1:this.ctx.mozImageSmoothingEnabled=!1,e.smask?this.tempSMask=this.smaskStack.pop():this.ctx.drawImage(r.canvas,0,0),this.restore()},beginAnnotations:function t(){this.save(),this.baseTransform&&this.ctx.setTransform.apply(this.ctx,this.baseTransform)},endAnnotations:function t(){this.restore()},beginAnnotation:function t(e,r,i){if(this.save(),h(this.ctx),this.current=new m,(0,o.isArray)(e)&&4===e.length){var n=e[2]-e[0],a=e[3]-e[1];this.ctx.rect(e[0],e[1],n,a),this.clip(),this.endPath()}this.transform.apply(this,r),this.transform.apply(this,i)},endAnnotation:function t(){this.restore()},paintJpegXObject:function t(e,r,i){var n=this.objs.get(e);if(!n)return void(0,o.warn)("Dependent image isn't ready yet");this.save();var a=this.ctx;if(a.scale(1/r,-1/i),a.drawImage(n,0,0,n.width,n.height,0,-i,r,i),this.imageLayer){var s=a.mozCurrentTransformInverse,c=this.getCanvasPosition(0,0);this.imageLayer.appendImage({objId:e,left:c[0],top:c[1],width:r/s[0],height:i/s[3]})}this.restore()},paintImageMaskXObject:function t(e){var r=this.ctx,i=e.width,o=e.height,a=this.current.fillColor,s=this.current.patternFill,l=this.processingType3;if(l&&void 0===l.compiled&&(l.compiled=i<=1e3&&o<=1e3?n({data:e.data,width:i,height:o}):null),l&&l.compiled)return void l.compiled(r);var h=this.cachedCanvases.getCanvas("maskCanvas",i,o),u=h.context;u.save(),c(u,e),u.globalCompositeOperation="source-in",u.fillStyle=s?a.getPattern(u,this):a,u.fillRect(0,0,i,o),u.restore(),this.paintInlineImageXObject(h.canvas)},paintImageMaskXObjectRepeat:function t(e,r,i,n){var o=e.width,a=e.height,s=this.current.fillColor,l=this.current.patternFill,h=this.cachedCanvases.getCanvas("maskCanvas",o,a),u=h.context;u.save(),c(u,e),u.globalCompositeOperation="source-in",u.fillStyle=l?s.getPattern(u,this):s,u.fillRect(0,0,o,a),u.restore();for(var f=this.ctx,d=0,p=n.length;d<p;d+=2)f.save(),f.transform(r,0,0,i,n[d],n[d+1]),f.scale(1,-1),f.drawImage(h.canvas,0,0,o,a,0,-1,1,1),f.restore()},paintImageMaskXObjectGroup:function t(e){for(var r=this.ctx,i=this.current.fillColor,n=this.current.patternFill,o=0,a=e.length;o<a;o++){var s=e[o],l=s.width,h=s.height,u=this.cachedCanvases.getCanvas("maskCanvas",l,h),f=u.context;f.save(),c(f,s),f.globalCompositeOperation="source-in",f.fillStyle=n?i.getPattern(f,this):i,f.fillRect(0,0,l,h),f.restore(),r.save(),r.transform.apply(r,s.transform),r.scale(1,-1),r.drawImage(u.canvas,0,0,l,h,0,-1,1,1),r.restore()}},paintImageXObject:function t(e){var r=this.objs.get(e);if(!r)return void(0,o.warn)("Dependent image isn't ready yet");this.paintInlineImageXObject(r)},paintImageXObjectRepeat:function t(e,r,i,n){var a=this.objs.get(e);if(!a)return void(0,o.warn)("Dependent image isn't ready yet");for(var s=a.width,c=a.height,l=[],h=0,u=n.length;h<u;h+=2)l.push({transform:[r,0,0,i,n[h],n[h+1]],x:0,y:0,w:s,h:c});this.paintInlineImageXObjectGroup(a,l)},paintInlineImageXObject:function t(e){var i=e.width,n=e.height,o=this.ctx;this.save(),o.scale(1/i,-1/n);var a=o.mozCurrentTransformInverse,s=a[0],c=a[1],l=Math.max(Math.sqrt(s*s+c*c),1),h=a[2],u=a[3],f=Math.max(Math.sqrt(h*h+u*u),1),d,p;if(e instanceof HTMLElement||!e.data)d=e;else{p=this.cachedCanvases.getCanvas("inlineImage",i,n);var g=p.context;r(g,e),d=p.canvas}for(var v=i,m=n,b="prescale1";l>2&&v>1||f>2&&m>1;){var y=v,_=m;l>2&&v>1&&(y=Math.ceil(v/2),l/=v/y),f>2&&m>1&&(_=Math.ceil(m/2),f/=m/_),p=this.cachedCanvases.getCanvas(b,y,_),g=p.context,g.clearRect(0,0,y,_),g.drawImage(d,0,0,v,m,0,0,y,_),d=p.canvas,v=y,m=_,b="prescale1"===b?"prescale2":"prescale1"}if(o.drawImage(d,0,0,v,m,0,-n,i,n),this.imageLayer){var w=this.getCanvasPosition(0,-n);this.imageLayer.appendImage({imgData:e,left:w[0],top:w[1],width:i/a[0],height:n/a[3]})}this.restore()},paintInlineImageXObjectGroup:function t(e,i){var n=this.ctx,o=e.width,a=e.height,s=this.cachedCanvases.getCanvas("inlineImage",o,a);r(s.context,e);for(var c=0,l=i.length;c<l;c++){var h=i[c];if(n.save(),n.transform.apply(n,h.transform),n.scale(1,-1),n.drawImage(s.canvas,h.x,h.y,h.w,h.h,0,-1,1,1),this.imageLayer){var u=this.getCanvasPosition(h.x,h.y);this.imageLayer.appendImage({imgData:e,left:u[0],top:u[1],width:o,height:a})}n.restore()}},paintSolidColorImageMask:function t(){this.ctx.fillRect(0,0,1,1)},paintXObject:function t(){(0,o.warn)("Unsupported 'paintXObject' command.")},markPoint:function t(e){},markPointProps:function t(e,r){},beginMarkedContent:function t(e){},beginMarkedContentProps:function t(e,r){},endMarkedContent:function t(){},beginCompat:function t(){},endCompat:function t(){},consumePath:function t(){var e=this.ctx;this.pendingClip&&(this.pendingClip===A?e.clip("evenodd"):e.clip(),this.pendingClip=null),e.beginPath()},getSinglePixelWidth:function t(e){if(null===this.cachedGetSinglePixelWidth){this.ctx.save();var r=this.ctx.mozCurrentTransformInverse;this.ctx.restore(),this.cachedGetSinglePixelWidth=Math.sqrt(Math.max(r[0]*r[0]+r[1]*r[1],r[2]*r[2]+r[3]*r[3]))}return this.cachedGetSinglePixelWidth},getCanvasPosition:function t(e,r){var i=this.ctx.mozCurrentTransform;return[i[0]*e+i[2]*r+i[4],i[1]*e+i[3]*r+i[5]]}};for(var T in o.OPS)e.prototype[o.OPS[T]]=e.prototype[T];return e}();e.CanvasGraphics=b},function(t,e,r){"use strict";function i(t){this.docId=t,this.styleElement=null,this.nativeFontFaces=[],this.loadTestFontId=0,this.loadingContext={requests:[],nextRequestId:0}}Object.defineProperty(e,"__esModule",{value:!0}),e.FontLoader=e.FontFaceObject=void 0;var n=r(0);i.prototype={insertRule:function t(e){var r=this.styleElement;r||(r=this.styleElement=document.createElement("style"),r.id="PDFJS_FONT_STYLE_TAG_"+this.docId,document.documentElement.getElementsByTagName("head")[0].appendChild(r));var i=r.sheet;i.insertRule(e,i.cssRules.length)},clear:function t(){this.styleElement&&(this.styleElement.remove(),this.styleElement=null),this.nativeFontFaces.forEach(function(t){document.fonts.delete(t)}),this.nativeFontFaces.length=0}};var o=function t(){return atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==")};Object.defineProperty(i.prototype,"loadTestFont",{get:function t(){return(0,n.shadow)(this,"loadTestFont",o())},configurable:!0}),i.prototype.addNativeFontFace=function t(e){this.nativeFontFaces.push(e),document.fonts.add(e)},i.prototype.bind=function t(e,r){for(var o=[],a=[],s=[],c=function t(e){return e.loaded.catch(function(t){(0,n.warn)('Failed to load font "'+e.family+'": '+t)})},l=i.isFontLoadingAPISupported&&!i.isSyncFontLoadingSupported,h=0,u=e.length;h<u;h++){var f=e[h];if(!f.attached&&!1!==f.loading)if(f.attached=!0,l){var d=f.createNativeFontFace();d&&(this.addNativeFontFace(d),s.push(c(d)))}else{var p=f.createFontFaceRule();p&&(this.insertRule(p),o.push(p),a.push(f))}}var g=this.queueLoadingCallback(r);l?Promise.all(s).then(function(){g.complete()}):o.length>0&&!i.isSyncFontLoadingSupported?this.prepareFontLoadEvent(o,a,g):g.complete()},i.prototype.queueLoadingCallback=function t(e){function r(){for((0,n.assert)(!a.end,"completeRequest() cannot be called twice"),a.end=Date.now();i.requests.length>0&&i.requests[0].end;){var t=i.requests.shift();setTimeout(t.callback,0)}}var i=this.loadingContext,o="pdfjs-font-loading-"+i.nextRequestId++,a={id:o,complete:r,callback:e,started:Date.now()};return i.requests.push(a),a},i.prototype.prepareFontLoadEvent=function t(e,r,i){function o(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function a(t,e,r,i){return t.substr(0,e)+i+t.substr(e+r)}function s(t,e){return++f>30?((0,n.warn)("Load test font never loaded."),void e()):(u.font="30px "+t,u.fillText(".",0,20),u.getImageData(0,0,1,1).data[3]>0?void e():void setTimeout(s.bind(null,t,e)))}var c,l,h=document.createElement("canvas");h.width=1,h.height=1;var u=h.getContext("2d"),f=0,d="lt"+Date.now()+this.loadTestFontId++,p=this.loadTestFont,g=976;p=a(p,976,d.length,d);var v=16,m=1482184792,b=o(p,16);for(c=0,l=d.length-3;c<l;c+=4)b=b-1482184792+o(d,c)|0;c<d.length&&(b=b-1482184792+o(d+"XXX",c)|0),p=a(p,16,4,(0,n.string32)(b));var y="url(data:font/opentype;base64,"+btoa(p)+");",_='@font-face { font-family:"'+d+'";src:'+y+"}";this.insertRule(_);var w=[];for(c=0,l=r.length;c<l;c++)w.push(r[c].loadedName);w.push(d);var S=document.createElement("div");for(S.setAttribute("style","visibility: hidden;width: 10px; height: 10px;position: absolute; top: 0px; left: 0px;"),c=0,l=w.length;c<l;++c){var x=document.createElement("span");x.textContent="Hi",x.style.fontFamily=w[c],S.appendChild(x)}document.body.appendChild(S),s(d,function(){document.body.removeChild(S),i.complete()})},i.isFontLoadingAPISupported="undefined"!=typeof document&&!!document.fonts;var a=function t(){if("undefined"==typeof navigator)return!0;var e=!1,r=/Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);return r&&r[1]>=14&&(e=!0),e};Object.defineProperty(i,"isSyncFontLoadingSupported",{get:function t(){return(0,n.shadow)(i,"isSyncFontLoadingSupported",a())},enumerable:!0,configurable:!0});var s={get value(){return(0,n.shadow)(this,"value",(0,n.isEvalSupported)())}},c=function t(){function e(t,e){this.compiledGlyphs=Object.create(null);for(var r in t)this[r]=t[r];this.options=e}return e.prototype={createNativeFontFace:function t(){if(!this.data)return null;if(this.options.disableFontFace)return this.disableFontFace=!0,null;var e=new FontFace(this.loadedName,this.data,{});return this.options.fontRegistry&&this.options.fontRegistry.registerFont(this),e},createFontFaceRule:function t(){if(!this.data)return null;if(this.options.disableFontFace)return this.disableFontFace=!0,null;var e=(0,n.bytesToString)(new Uint8Array(this.data)),r=this.loadedName,i="url(data:"+this.mimetype+";base64,"+btoa(e)+");",o='@font-face { font-family:"'+r+'";src:'+i+"}";return this.options.fontRegistry&&this.options.fontRegistry.registerFont(this,i),o},getPathGenerator:function t(e,r){if(!(r in this.compiledGlyphs)){var i=e.get(this.loadedName+"_path_"+r),n,o,a;if(this.options.isEvalSupported&&s.value){var c,l="";for(o=0,a=i.length;o<a;o++)n=i[o],c=void 0!==n.args?n.args.join(","):"",l+="c."+n.cmd+"("+c+");\n";this.compiledGlyphs[r]=new Function("c","size",l)}else this.compiledGlyphs[r]=function(t,e){for(o=0,a=i.length;o<a;o++)n=i[o],"scale"===n.cmd&&(n.args=[e,-e]),t[n.cmd].apply(t,n.args)}}return this.compiledGlyphs[r]}},e}();e.FontFaceObject=c,e.FontLoader=i},function(t,e,r){"use strict";function i(t){var e=a[t[0]];if(!e)throw new Error("Unknown IR type: "+t[0]);return e.fromIR(t)}Object.defineProperty(e,"__esModule",{value:!0}),e.TilingPattern=e.getShadingPatternFromIR=void 0;var n=r(0),o=r(7),a={};a.RadialAxial={fromIR:function t(e){var r=e[1],i=e[2],n=e[3],o=e[4],a=e[5],s=e[6];return{type:"Pattern",getPattern:function t(e){var c;"axial"===r?c=e.createLinearGradient(n[0],n[1],o[0],o[1]):"radial"===r&&(c=e.createRadialGradient(n[0],n[1],a,o[0],o[1],s));for(var l=0,h=i.length;l<h;++l){var u=i[l];c.addColorStop(u[0],u[1])}return c}}}};var s=function t(){function e(t,e,r,i,n,o,a,s){var c=e.coords,l=e.colors,h=t.data,u=4*t.width,f;c[r+1]>c[i+1]&&(f=r,r=i,i=f,f=o,o=a,a=f),c[i+1]>c[n+1]&&(f=i,i=n,n=f,f=a,a=s,s=f),c[r+1]>c[i+1]&&(f=r,r=i,i=f,f=o,o=a,a=f);var d=(c[r]+e.offsetX)*e.scaleX,p=(c[r+1]+e.offsetY)*e.scaleY,g=(c[i]+e.offsetX)*e.scaleX,v=(c[i+1]+e.offsetY)*e.scaleY,m=(c[n]+e.offsetX)*e.scaleX,b=(c[n+1]+e.offsetY)*e.scaleY;if(!(p>=b))for(var y=l[o],_=l[o+1],w=l[o+2],S=l[a],x=l[a+1],C=l[a+2],A=l[s],T=l[s+1],k=l[s+2],P=Math.round(p),E=Math.round(b),O,R,L,D,I,j,M,F,N,B=P;B<=E;B++){B<v?(N=B<p?0:p===v?1:(p-B)/(p-v),O=d-(d-g)*N,R=y-(y-S)*N,L=_-(_-x)*N,D=w-(w-C)*N):(N=B>b?1:v===b?0:(v-B)/(v-b),O=g-(g-m)*N,R=S-(S-A)*N,L=x-(x-T)*N,D=C-(C-k)*N),N=B<p?0:B>b?1:(p-B)/(p-b),I=d-(d-m)*N,j=y-(y-A)*N,M=_-(_-T)*N,F=w-(w-k)*N;for(var U=Math.round(Math.min(O,I)),z=Math.round(Math.max(O,I)),W=u*B+4*U,q=U;q<=z;q++)N=(O-q)/(O-I),N=N<0?0:N>1?1:N,h[W++]=R-(R-j)*N|0,h[W++]=L-(L-M)*N|0,h[W++]=D-(D-F)*N|0,h[W++]=255}}function r(t,r,i){var n=r.coords,o=r.colors,a,s;switch(r.type){case"lattice":var c=r.verticesPerRow,l=Math.floor(n.length/c)-1,h=c-1;for(a=0;a<l;a++)for(var u=a*c,f=0;f<h;f++,u++)e(t,i,n[u],n[u+1],n[u+c],o[u],o[u+1],o[u+c]),e(t,i,n[u+c+1],n[u+1],n[u+c],o[u+c+1],o[u+1],o[u+c]);break;case"triangles":for(a=0,s=n.length;a<s;a+=3)e(t,i,n[a],n[a+1],n[a+2],o[a],o[a+1],o[a+2]);break;default:throw new Error("illegal figure")}}function i(t,e,i,n,a,s,c){var l=1.1,h=3e3,u=2,f=Math.floor(t[0]),d=Math.floor(t[1]),p=Math.ceil(t[2])-f,g=Math.ceil(t[3])-d,v=Math.min(Math.ceil(Math.abs(p*e[0]*1.1)),3e3),m=Math.min(Math.ceil(Math.abs(g*e[1]*1.1)),3e3),b=p/v,y=g/m,_={coords:i,colors:n,offsetX:-f,offsetY:-d,scaleX:1/b,scaleY:1/y},w=v+4,S=m+4,x,C,A,T;if(o.WebGLUtils.isEnabled)x=o.WebGLUtils.drawFigures(v,m,s,a,_),C=c.getCanvas("mesh",w,S,!1),C.context.drawImage(x,2,2),x=C.canvas;else{C=c.getCanvas("mesh",w,S,!1);var k=C.context,P=k.createImageData(v,m);if(s){var E=P.data;for(A=0,T=E.length;A<T;A+=4)E[A]=s[0],E[A+1]=s[1],E[A+2]=s[2],E[A+3]=255}for(A=0;A<a.length;A++)r(P,a[A],_);k.putImageData(P,2,2),x=C.canvas}return{canvas:x,offsetX:f-2*b,offsetY:d-2*y,scaleX:b,scaleY:y}}return i}();a.Mesh={fromIR:function t(e){var r=e[2],i=e[3],o=e[4],a=e[5],c=e[6],l=e[8];return{type:"Pattern",getPattern:function t(e,h,u){var f;if(u)f=n.Util.singularValueDecompose2dScale(e.mozCurrentTransform);else if(f=n.Util.singularValueDecompose2dScale(h.baseTransform),c){var d=n.Util.singularValueDecompose2dScale(c);f=[f[0]*d[0],f[1]*d[1]]}var p=s(a,f,r,i,o,u?null:l,h.cachedCanvases);return u||(e.setTransform.apply(e,h.baseTransform),c&&e.transform.apply(e,c)),e.translate(p.offsetX,p.offsetY),e.scale(p.scaleX,p.scaleY),e.createPattern(p.canvas,"no-repeat")}}}},a.Dummy={fromIR:function t(){return{type:"Pattern",getPattern:function t(){return"hotpink"}}}};var c=function t(){function e(t,e,r,i,n){this.operatorList=t[2],this.matrix=t[3]||[1,0,0,1,0,0],this.bbox=t[4],this.xstep=t[5],this.ystep=t[6],this.paintType=t[7],this.tilingType=t[8],this.color=e,this.canvasGraphicsFactory=i,this.baseTransform=n,this.type="Pattern",this.ctx=r}var r={COLORED:1,UNCOLORED:2},i=3e3;return e.prototype={createPatternCanvas:function t(e){var r=this.operatorList,i=this.bbox,o=this.xstep,a=this.ystep,s=this.paintType,c=this.tilingType,l=this.color,h=this.canvasGraphicsFactory;(0,n.info)("TilingType: "+c);var u=i[0],f=i[1],d=i[2],p=i[3],g=[u,f],v=[u+o,f+a],m=v[0]-g[0],b=v[1]-g[1],y=n.Util.singularValueDecompose2dScale(this.matrix),_=n.Util.singularValueDecompose2dScale(this.baseTransform),w=[y[0]*_[0],y[1]*_[1]];m=Math.min(Math.ceil(Math.abs(m*w[0])),3e3),b=Math.min(Math.ceil(Math.abs(b*w[1])),3e3);var S=e.cachedCanvases.getCanvas("pattern",m,b,!0),x=S.context,C=h.createCanvasGraphics(x);C.groupLevel=e.groupLevel,this.setFillAndStrokeStyleToContext(x,s,l),this.setScale(m,b,o,a),this.transformToScale(C);var A=[1,0,0,1,-g[0],-g[1]];return C.transform.apply(C,A),this.clipBbox(C,i,u,f,d,p),C.executeOperatorList(r),S.canvas},setScale:function t(e,r,i,n){this.scale=[e/i,r/n]},transformToScale:function t(e){var r=this.scale,i=[r[0],0,0,r[1],0,0];e.transform.apply(e,i)},scaleToContext:function t(){var e=this.scale;this.ctx.scale(1/e[0],1/e[1])},clipBbox:function t(e,r,i,o,a,s){if((0,n.isArray)(r)&&4===r.length){var c=a-i,l=s-o;e.ctx.rect(i,o,c,l),e.clip(),e.endPath()}},setFillAndStrokeStyleToContext:function t(e,i,o){switch(i){case r.COLORED:var a=this.ctx;e.fillStyle=a.fillStyle,e.strokeStyle=a.strokeStyle;break;case r.UNCOLORED:var s=n.Util.makeCssRgb(o[0],o[1],o[2]);e.fillStyle=s,e.strokeStyle=s;break;default:throw new n.FormatError("Unsupported paint type: "+i)}},getPattern:function t(e,r){var i=this.createPatternCanvas(r);return e=this.ctx,e.setTransform.apply(e,this.baseTransform),e.transform.apply(e,this.matrix),this.scaleToContext(),e.createPattern(i,"repeat")}},e}();e.getShadingPatternFromIR=i,e.TilingPattern=c},function(t,e,r){"use strict";var i="1.8.575",n="bd8c1211",o=r(0),a=r(8),s=r(3),c=r(5),l=r(2),h=r(1),u=r(4);e.PDFJS=a.PDFJS,e.build=s.build,e.version=s.version,e.getDocument=s.getDocument,e.LoopbackPort=s.LoopbackPort,e.PDFDataRangeTransport=s.PDFDataRangeTransport,e.PDFWorker=s.PDFWorker,e.renderTextLayer=c.renderTextLayer,e.AnnotationLayer=l.AnnotationLayer,e.CustomStyle=h.CustomStyle,e.createPromiseCapability=o.createPromiseCapability,e.PasswordResponses=o.PasswordResponses,e.InvalidPDFException=o.InvalidPDFException,e.MissingPDFException=o.MissingPDFException,e.SVGGraphics=u.SVGGraphics,e.NativeImageDecoding=o.NativeImageDecoding,e.UnexpectedResponseException=o.UnexpectedResponseException,e.OPS=o.OPS,e.UNSUPPORTED_FEATURES=o.UNSUPPORTED_FEATURES,e.isValidUrl=h.isValidUrl,e.createValidAbsoluteUrl=o.createValidAbsoluteUrl,e.createObjectURL=o.createObjectURL,e.removeNullCharacters=o.removeNullCharacters,e.shadow=o.shadow,e.createBlob=o.createBlob,e.RenderingCancelledException=h.RenderingCancelledException,e.getFilenameFromUrl=h.getFilenameFromUrl,e.addLinkAttributes=h.addLinkAttributes,e.StatTimer=o.StatTimer},function(t,r,i){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};if("undefined"==typeof PDFJS||!PDFJS.compatibilityChecked){var o="undefined"!=typeof window&&window.Math===Math?window:void 0!==e&&e.Math===Math?e:"undefined"!=typeof self&&self.Math===Math?self:void 0,a="undefined"!=typeof navigator&&navigator.userAgent||"",s=/Android/.test(a),c=/Android\s[0-2][^\d]/.test(a),l=/Android\s[0-4][^\d]/.test(a),h=a.indexOf("Chrom")>=0,u=/Chrome\/(39|40)\./.test(a),f=a.indexOf("CriOS")>=0,d=a.indexOf("Trident")>=0,p=/\b(iPad|iPhone|iPod)(?=;)/.test(a),g=a.indexOf("Opera")>=0,v=/Safari\//.test(a)&&!/(Chrome\/|Android\s)/.test(a),m="object"===("undefined"==typeof window?"undefined":n(window))&&"object"===("undefined"==typeof document?"undefined":n(document));"undefined"==typeof PDFJS&&(o.PDFJS={}),PDFJS.compatibilityChecked=!0,function t(){function e(t,e){return new c(this.slice(t,e))}function r(t,e){arguments.length<2&&(e=0);for(var r=0,i=t.length;r<i;++r,++e)this[e]=255&t[r]}function i(t,e){this.buffer=t,this.byteLength=t.length,this.length=e,s(this.length)}function a(t){return{get:function e(){var r=this.buffer,i=t<<2;return(r[i]|r[i+1]<<8|r[i+2]<<16|r[i+3]<<24)>>>0},set:function e(r){var i=this.buffer,n=t<<2;i[n]=255&r,i[n+1]=r>>8&255,i[n+2]=r>>16&255,i[n+3]=r>>>24&255}}}function s(t){for(;l<t;)Object.defineProperty(i.prototype,l,a(l)),l++}function c(t){var i,o,a;if("number"==typeof t)for(i=[],o=0;o<t;++o)i[o]=0;else if("slice"in t)i=t.slice(0);else for(i=[],o=0,a=t.length;o<a;++o)i[o]=t[o];return i.subarray=e,i.buffer=i,i.byteLength=i.length,i.set=r,"object"===(void 0===t?"undefined":n(t))&&t.buffer&&(i.buffer=t.buffer),i}if("undefined"!=typeof Uint8Array)return void 0===Uint8Array.prototype.subarray&&(Uint8Array.prototype.subarray=function t(e,r){return new Uint8Array(this.slice(e,r))},Float32Array.prototype.subarray=function t(e,r){return new Float32Array(this.slice(e,r))}),void("undefined"==typeof Float64Array&&(o.Float64Array=Float32Array));i.prototype=Object.create(null);var l=0;o.Uint8Array=c,o.Int8Array=c,o.Int32Array=c,o.Uint16Array=c,o.Float32Array=c,o.Float64Array=c,o.Uint32Array=function(){if(3===arguments.length){if(0!==arguments[1])throw new Error("offset !== 0 is not supported");return new i(arguments[0],arguments[2])}return c.apply(this,arguments)}}(),function t(){if(m&&window.CanvasPixelArray){var e=window.CanvasPixelArray.prototype;"buffer"in e||(Object.defineProperty(e,"buffer",{get:function t(){return this},enumerable:!1,configurable:!0}),Object.defineProperty(e,"byteLength",{get:function t(){return this.length},enumerable:!1,configurable:!0}))}}(),function t(){o.URL||(o.URL=o.webkitURL)}(),function t(){if(void 0!==Object.defineProperty){var e=!0;try{m&&Object.defineProperty(new Image,"id",{value:"test"});var r=function t(){};r.prototype={get id(){}},Object.defineProperty(new r,"id",{value:"",configurable:!0,enumerable:!0,writable:!1})}catch(t){e=!1}if(e)return}Object.defineProperty=function t(e,r,i){delete e[r],"get"in i&&e.__defineGetter__(r,i.get),"set"in i&&e.__defineSetter__(r,i.set),"value"in i&&(e.__defineSetter__(r,function t(e){return this.__defineGetter__(r,function t(){return e}),e}),e[r]=i.value)}}(),function t(){if("undefined"!=typeof XMLHttpRequest){var e=XMLHttpRequest.prototype,r=new XMLHttpRequest;if("overrideMimeType"in r||Object.defineProperty(e,"overrideMimeType",{value:function t(e){}}),!("responseType"in r)){if(Object.defineProperty(e,"responseType",{get:function t(){return this._responseType||"text"},set:function t(e){"text"!==e&&"arraybuffer"!==e||(this._responseType=e,"arraybuffer"===e&&"function"==typeof this.overrideMimeType&&this.overrideMimeType("text/plain; charset=x-user-defined"))}}),"undefined"!=typeof VBArray)return void Object.defineProperty(e,"response",{get:function t(){return"arraybuffer"===this.responseType?new Uint8Array(new VBArray(this.responseBody).toArray()):this.responseText}});Object.defineProperty(e,"response",{get:function t(){if("arraybuffer"!==this.responseType)return this.responseText;var e=this.responseText,r,i=e.length,n=new Uint8Array(i);for(r=0;r<i;++r)n[r]=255&e.charCodeAt(r);return n.buffer}})}}}(),function t(){if(!("btoa"in o)){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";o.btoa=function(t){var r="",i,n;for(i=0,n=t.length;i<n;i+=3){var o=255&t.charCodeAt(i),a=255&t.charCodeAt(i+1),s=255&t.charCodeAt(i+2),c=o>>2,l=(3&o)<<4|a>>4,h=i+1<n?(15&a)<<2|s>>6:64,u=i+2<n?63&s:64;r+=e.charAt(c)+e.charAt(l)+e.charAt(h)+e.charAt(u)}return r}}}(),function t(){if(!("atob"in o)){o.atob=function(t){if(t=t.replace(/=+$/,""),t.length%4==1)throw new Error("bad atob input");for(var e=0,r,i,n=0,o="";i=t.charAt(n++);~i&&(r=e%4?64*r+i:i,e++%4)?o+=String.fromCharCode(255&r>>(-2*e&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return o}}}(),function t(){void 0===Function.prototype.bind&&(Function.prototype.bind=function t(e){var r=this,i=Array.prototype.slice.call(arguments,1);return function t(){var n=i.concat(Array.prototype.slice.call(arguments));return r.apply(e,n)}})}(),function t(){if(m){"dataset"in document.createElement("div")||Object.defineProperty(HTMLElement.prototype,"dataset",{get:function t(){if(this._dataset)return this._dataset;for(var e={},r=0,i=this.attributes.length;r<i;r++){var n=this.attributes[r];if("data-"===n.name.substring(0,5)){e[n.name.substring(5).replace(/\-([a-z])/g,function(t,e){return e.toUpperCase()})]=n.value}}return Object.defineProperty(this,"_dataset",{value:e,writable:!1,enumerable:!1}),e},enumerable:!0})}}(),function t(){function e(t,e,r,i){var n=t.className||"",o=n.split(/\s+/g);""===o[0]&&o.shift();var a=o.indexOf(e);return a<0&&r&&o.push(e),a>=0&&i&&o.splice(a,1),t.className=o.join(" "),a>=0}if(m){if(!("classList"in document.createElement("div"))){var r={add:function t(r){e(this.element,r,!0,!1)},contains:function t(r){return e(this.element,r,!1,!1)},remove:function t(r){e(this.element,r,!1,!0)},toggle:function t(r){e(this.element,r,!0,!0)}};Object.defineProperty(HTMLElement.prototype,"classList",{get:function t(){if(this._classList)return this._classList;var e=Object.create(r,{element:{value:this,writable:!1,enumerable:!0}});return Object.defineProperty(this,"_classList",{value:e,writable:!1,enumerable:!1}),e},enumerable:!0})}}}(),function t(){if(!("undefined"==typeof importScripts||"console"in o)){var e={},r={log:function t(){var e=Array.prototype.slice.call(arguments);o.postMessage({targetName:"main",action:"console_log",data:e})},error:function t(){var e=Array.prototype.slice.call(arguments);o.postMessage({targetName:"main",action:"console_error",data:e})},time:function t(r){e[r]=Date.now()},timeEnd:function t(r){var i=e[r];if(!i)throw new Error("Unknown timer name "+r);this.log("Timer:",r,Date.now()-i)}};o.console=r}}(),function t(){if(m)"console"in window?"bind"in console.log||(console.log=function(t){return function(e){return t(e)}}(console.log),console.error=function(t){return function(e){return t(e)}}(console.error),console.warn=function(t){return function(e){return t(e)}}(console.warn)):window.console={log:function t(){},error:function t(){},warn:function t(){}}}(),function t(){function e(t){r(t.target)&&t.stopPropagation()}function r(t){return t.disabled||t.parentNode&&r(t.parentNode)}g&&document.addEventListener("click",e,!0)}(),function t(){(d||f)&&(PDFJS.disableCreateObjectURL=!0)}(),function t(){"undefined"!=typeof navigator&&("language"in navigator||(PDFJS.locale=navigator.userLanguage||"en-US"))}(),function t(){(v||c||u||p)&&(PDFJS.disableRange=!0,PDFJS.disableStream=!0)}(),function t(){m&&(history.pushState&&!c||(PDFJS.disableHistory=!0))}(),function t(){if(m)if(window.CanvasPixelArray)"function"!=typeof window.CanvasPixelArray.prototype.set&&(window.CanvasPixelArray.prototype.set=function(t){for(var e=0,r=this.length;e<r;e++)this[e]=t[e]});else{var e=!1,r;if(h?(r=a.match(/Chrom(e|ium)\/([0-9]+)\./),e=r&&parseInt(r[2])<21):s?e=l:v&&(r=a.match(/Version\/([0-9]+)\.([0-9]+)\.([0-9]+) Safari\//),e=r&&parseInt(r[1])<6),e){var i=window.CanvasRenderingContext2D.prototype,n=i.createImageData;i.createImageData=function(t,e){var r=n.call(this,t,e);return r.data.set=function(t){for(var e=0,r=this.length;e<r;e++)this[e]=t[e]},r},i=null}}}(),function t(){function e(){window.requestAnimationFrame=function(t){return window.setTimeout(t,20)},window.cancelAnimationFrame=function(t){window.clearTimeout(t)}}if(m)p?e():"requestAnimationFrame"in window||(window.requestAnimationFrame=window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame,window.requestAnimationFrame||e())}(),function t(){(p||s)&&(PDFJS.maxCanvasPixels=5242880)}(),function t(){m&&d&&window.parent!==window&&(PDFJS.disableFullscreen=!0)}(),function t(){m&&("currentScript"in document||Object.defineProperty(document,"currentScript",{get:function t(){var e=document.getElementsByTagName("script");return e[e.length-1]},enumerable:!0,configurable:!0}))}(),function t(){if(m){var e=document.createElement("input");try{e.type="number"}catch(t){var r=e.constructor.prototype,i=Object.getOwnPropertyDescriptor(r,"type");Object.defineProperty(r,"type",{get:function t(){return i.get.call(this)},set:function t(e){i.set.call(this,"number"===e?"text":e)},enumerable:!0,configurable:!0})}}}(),function t(){if(m&&document.attachEvent){var e=document.constructor.prototype,r=Object.getOwnPropertyDescriptor(e,"readyState");Object.defineProperty(e,"readyState",{get:function t(){var e=r.get.call(this);return"interactive"===e?"loading":e},set:function t(e){r.set.call(this,e)},enumerable:!0,configurable:!0})}}(),function t(){m&&void 0===Element.prototype.remove&&(Element.prototype.remove=function(){this.parentNode&&this.parentNode.removeChild(this)})}(),function t(){Number.isNaN||(Number.isNaN=function(t){return"number"==typeof t&&isNaN(t)})}(),function t(){Number.isInteger||(Number.isInteger=function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t})}(),function t(){if(o.Promise)return"function"!=typeof o.Promise.all&&(o.Promise.all=function(t){var e=0,r=[],i,n,a=new o.Promise(function(t,e){i=t,n=e});return t.forEach(function(t,o){e++,t.then(function(t){r[o]=t,0===--e&&i(r)},n)}),0===e&&i(r),a}),"function"!=typeof o.Promise.resolve&&(o.Promise.resolve=function(t){return new o.Promise(function(e){e(t)})}),"function"!=typeof o.Promise.reject&&(o.Promise.reject=function(t){return new o.Promise(function(e,r){r(t)})}),void("function"!=typeof o.Promise.prototype.catch&&(o.Promise.prototype.catch=function(t){return o.Promise.prototype.then(void 0,t)}));var e=0,r=1,i=2,n=500,a={handlers:[],running:!1,unhandledRejections:[],pendingRejectionCheck:!1,scheduleHandlers:function t(e){0!==e._status&&(this.handlers=this.handlers.concat(e._handlers),e._handlers=[],this.running||(this.running=!0,setTimeout(this.runHandlers.bind(this),0)))},runHandlers:function t(){for(var e=1,r=Date.now()+1;this.handlers.length>0;){var n=this.handlers.shift(),o=n.thisPromise._status,a=n.thisPromise._value;try{1===o?"function"==typeof n.onResolve&&(a=n.onResolve(a)):"function"==typeof n.onReject&&(a=n.onReject(a),o=1,n.thisPromise._unhandledRejection&&this.removeUnhandeledRejection(n.thisPromise))}catch(t){o=i,a=t}if(n.nextPromise._updateStatus(o,a),Date.now()>=r)break}if(this.handlers.length>0)return void setTimeout(this.runHandlers.bind(this),0);this.running=!1},addUnhandledRejection:function t(e){this.unhandledRejections.push({promise:e,time:Date.now()}),this.scheduleRejectionCheck()},removeUnhandeledRejection:function t(e){e._unhandledRejection=!1;for(var r=0;r<this.unhandledRejections.length;r++)this.unhandledRejections[r].promise===e&&(this.unhandledRejections.splice(r),r--)},scheduleRejectionCheck:function t(){var e=this;this.pendingRejectionCheck||(this.pendingRejectionCheck=!0,setTimeout(function(){e.pendingRejectionCheck=!1;for(var t=Date.now(),r=0;r<e.unhandledRejections.length;r++)if(t-e.unhandledRejections[r].time>500){var i=e.unhandledRejections[r].promise._value,n="Unhandled rejection: "+i;i.stack&&(n+="\n"+i.stack);try{throw new Error(n)}catch(t){console.warn(n)}e.unhandledRejections.splice(r),r--}e.unhandledRejections.length&&e.scheduleRejectionCheck()},500))}},s=function t(e){this._status=0,this._handlers=[];try{e.call(this,this._resolve.bind(this),this._reject.bind(this))}catch(t){this._reject(t)}};s.all=function t(e){function r(t){a._status!==i&&(l=[],o(t))}var n,o,a=new s(function(t,e){n=t,o=e}),c=e.length,l=[];if(0===c)return n(l),a;for(var h=0,u=e.length;h<u;++h){var f=e[h],d=function(t){return function(e){a._status!==i&&(l[t]=e,0===--c&&n(l))}}(h);s.isPromise(f)?f.then(d,r):d(f)}return a},s.isPromise=function t(e){return e&&"function"==typeof e.then},s.resolve=function t(e){return new s(function(t){t(e)})},s.reject=function t(e){return new s(function(t,r){r(e)})},s.prototype={_status:null,_value:null,_handlers:null,_unhandledRejection:null,_updateStatus:function t(e,r){if(1!==this._status&&this._status!==i){if(1===e&&s.isPromise(r))return void r.then(this._updateStatus.bind(this,1),this._updateStatus.bind(this,i));this._status=e,this._value=r,e===i&&0===this._handlers.length&&(this._unhandledRejection=!0,a.addUnhandledRejection(this)),a.scheduleHandlers(this)}},_resolve:function t(e){this._updateStatus(1,e)},_reject:function t(e){this._updateStatus(i,e)},then:function t(e,r){var i=new s(function(t,e){this.resolve=t,this.reject=e});return this._handlers.push({thisPromise:this,onResolve:e,onReject:r,nextPromise:i}),a.scheduleHandlers(this),i},catch:function t(e){return this.then(void 0,e)}},o.Promise=s}(),function t(){function e(){this.id="$weakmap"+r++}if(!o.WeakMap){var r=0;e.prototype={has:function t(e){return("object"===(void 0===e?"undefined":n(e))||"function"==typeof e)&&null!==e&&!!Object.getOwnPropertyDescriptor(e,this.id)},get:function t(e){return this.has(e)?e[this.id]:void 0},set:function t(e,r){Object.defineProperty(e,this.id,{value:r,enumerable:!1,configurable:!0})},delete:function t(e){delete e[this.id]}},o.WeakMap=e}}(),function t(){function e(t){return void 0!==d[t]}function r(){l.call(this),this._isInvalid=!0}function i(t){return""===t&&r.call(this),t.toLowerCase()}function a(t){var e=t.charCodeAt(0);return e>32&&e<127&&-1===[34,35,60,62,63,96].indexOf(e)?t:encodeURIComponent(t)}function s(t){var e=t.charCodeAt(0);return e>32&&e<127&&-1===[34,35,60,62,96].indexOf(e)?t:encodeURIComponent(t)}function c(t,n,o){function c(t){y.push(t)}var l=n||"scheme start",h=0,u="",f=!1,b=!1,y=[];t:for(;(t[h-1]!==g||0===h)&&!this._isInvalid;){var _=t[h];switch(l){case"scheme start":if(!_||!v.test(_)){if(n){c("Invalid scheme.");break t}u="",l="no scheme";continue}u+=_.toLowerCase(),l="scheme";break;case"scheme":if(_&&m.test(_))u+=_.toLowerCase();else{if(":"!==_){if(n){if(_===g)break t;c("Code point not allowed in scheme: "+_);break t}u="",h=0,l="no scheme";continue}if(this._scheme=u,u="",n)break t;e(this._scheme)&&(this._isRelative=!0),l="file"===this._scheme?"relative":this._isRelative&&o&&o._scheme===this._scheme?"relative or authority":this._isRelative?"authority first slash":"scheme data"}break;case"scheme data":"?"===_?(this._query="?",l="query"):"#"===_?(this._fragment="#",l="fragment"):_!==g&&"\t"!==_&&"\n"!==_&&"\r"!==_&&(this._schemeData+=a(_));break;case"no scheme":if(o&&e(o._scheme)){l="relative";continue}c("Missing scheme."),r.call(this);break;case"relative or authority":if("/"!==_||"/"!==t[h+1]){c("Expected /, got: "+_),l="relative";continue}l="authority ignore slashes";break;case"relative":if(this._isRelative=!0,"file"!==this._scheme&&(this._scheme=o._scheme),_===g){this._host=o._host,this._port=o._port,this._path=o._path.slice(),this._query=o._query,this._username=o._username,this._password=o._password;break t}if("/"===_||"\\"===_)"\\"===_&&c("\\ is an invalid code point."),l="relative slash";else if("?"===_)this._host=o._host,this._port=o._port,this._path=o._path.slice(),this._query="?",this._username=o._username,this._password=o._password,l="query";else{if("#"!==_){var w=t[h+1],S=t[h+2];("file"!==this._scheme||!v.test(_)||":"!==w&&"|"!==w||S!==g&&"/"!==S&&"\\"!==S&&"?"!==S&&"#"!==S)&&(this._host=o._host,this._port=o._port,this._username=o._username,this._password=o._password,this._path=o._path.slice(),this._path.pop()),l="relative path";continue}this._host=o._host,this._port=o._port,this._path=o._path.slice(),this._query=o._query,this._fragment="#",this._username=o._username,this._password=o._password,l="fragment"}break;case"relative slash":if("/"!==_&&"\\"!==_){"file"!==this._scheme&&(this._host=o._host,this._port=o._port,this._username=o._username,this._password=o._password),l="relative path";continue}"\\"===_&&c("\\ is an invalid code point."),l="file"===this._scheme?"file host":"authority ignore slashes";break;case"authority first slash":if("/"!==_){c("Expected '/', got: "+_),l="authority ignore slashes";continue}l="authority second slash";break;case"authority second slash":if(l="authority ignore slashes","/"!==_){c("Expected '/', got: "+_);continue}break;case"authority ignore slashes":if("/"!==_&&"\\"!==_){l="authority";continue}c("Expected authority, got: "+_);break;case"authority":if("@"===_){f&&(c("@ already seen."),u+="%40"),f=!0;for(var x=0;x<u.length;x++){var C=u[x];if("\t"!==C&&"\n"!==C&&"\r"!==C)if(":"!==C||null!==this._password){var A=a(C);null!==this._password?this._password+=A:this._username+=A}else this._password="";else c("Invalid whitespace in authority.")}u=""}else{if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_){h-=u.length,u="",l="host";continue}u+=_}break;case"file host":if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_){2!==u.length||!v.test(u[0])||":"!==u[1]&&"|"!==u[1]?0===u.length?l="relative path start":(this._host=i.call(this,u),u="",l="relative path start"):l="relative path";continue}"\t"===_||"\n"===_||"\r"===_?c("Invalid whitespace in file host."):u+=_;break;case"host":case"hostname":if(":"!==_||b){if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_){if(this._host=i.call(this,u),u="",l="relative path start",n)break t;continue}"\t"!==_&&"\n"!==_&&"\r"!==_?("["===_?b=!0:"]"===_&&(b=!1),u+=_):c("Invalid code point in host/hostname: "+_)}else if(this._host=i.call(this,u),u="",l="port","hostname"===n)break t;break;case"port":if(/[0-9]/.test(_))u+=_;else{if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_||n){if(""!==u){var T=parseInt(u,10);T!==d[this._scheme]&&(this._port=T+""),u=""}if(n)break t;l="relative path start";continue}"\t"===_||"\n"===_||"\r"===_?c("Invalid code point in port: "+_):r.call(this)}break;case"relative path start":if("\\"===_&&c("'\\' not allowed in path."),l="relative path","/"!==_&&"\\"!==_)continue;break;case"relative path":if(_!==g&&"/"!==_&&"\\"!==_&&(n||"?"!==_&&"#"!==_))"\t"!==_&&"\n"!==_&&"\r"!==_&&(u+=a(_));else{"\\"===_&&c("\\ not allowed in relative path.");var k;(k=p[u.toLowerCase()])&&(u=k),".."===u?(this._path.pop(),"/"!==_&&"\\"!==_&&this._path.push("")):"."===u&&"/"!==_&&"\\"!==_?this._path.push(""):"."!==u&&("file"===this._scheme&&0===this._path.length&&2===u.length&&v.test(u[0])&&"|"===u[1]&&(u=u[0]+":"),this._path.push(u)),u="","?"===_?(this._query="?",l="query"):"#"===_&&(this._fragment="#",l="fragment")}break;case"query":n||"#"!==_?_!==g&&"\t"!==_&&"\n"!==_&&"\r"!==_&&(this._query+=s(_)):(this._fragment="#",l="fragment");break;case"fragment":_!==g&&"\t"!==_&&"\n"!==_&&"\r"!==_&&(this._fragment+=_)}h++}}function l(){this._scheme="",this._schemeData="",this._username="",this._password=null,this._host="",this._port="",this._path=[],this._query="",this._fragment="",this._isInvalid=!1,this._isRelative=!1}function h(t,e){void 0===e||e instanceof h||(e=new h(String(e))),this._url=t,l.call(this);var r=t.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g,"");c.call(this,r,null,e)}var u=!1;try{if("function"==typeof URL&&"object"===n(URL.prototype)&&"origin"in URL.prototype){var f=new URL("b","http://a");f.pathname="c%20d",u="http://a/c%20d"===f.href}}catch(t){}if(!u){var d=Object.create(null);d.ftp=21,d.file=0,d.gopher=70,d.http=80,d.https=443,d.ws=80,d.wss=443;var p=Object.create(null);p["%2e"]=".",p[".%2e"]="..",p["%2e."]="..",p["%2e%2e"]="..";var g,v=/[a-zA-Z]/,m=/[a-zA-Z0-9\+\-\.]/;h.prototype={toString:function t(){return this.href},get href(){if(this._isInvalid)return this._url;var t="";return""===this._username&&null===this._password||(t=this._username+(null!==this._password?":"+this._password:"")+"@"),this.protocol+(this._isRelative?"//"+t+this.host:"")+this.pathname+this._query+this._fragment},set href(t){l.call(this),c.call(this,t)},get protocol(){return this._scheme+":"},set protocol(t){this._isInvalid||c.call(this,t+":","scheme start")},get host(){return this._isInvalid?"":this._port?this._host+":"+this._port:this._host},set host(t){!this._isInvalid&&this._isRelative&&c.call(this,t,"host")},get hostname(){return this._host},set hostname(t){!this._isInvalid&&this._isRelative&&c.call(this,t,"hostname")},get port(){return this._port},set port(t){!this._isInvalid&&this._isRelative&&c.call(this,t,"port")},get pathname(){return this._isInvalid?"":this._isRelative?"/"+this._path.join("/"):this._schemeData},set pathname(t){!this._isInvalid&&this._isRelative&&(this._path=[],c.call(this,t,"relative path start"))},get search(){return this._isInvalid||!this._query||"?"===this._query?"":this._query},set search(t){!this._isInvalid&&this._isRelative&&(this._query="?","?"===t[0]&&(t=t.slice(1)),c.call(this,t,"query"))},get hash(){return this._isInvalid||!this._fragment||"#"===this._fragment?"":this._fragment},set hash(t){this._isInvalid||(this._fragment="#","#"===t[0]&&(t=t.slice(1)),c.call(this,t,"fragment"))},get origin(){var t;if(this._isInvalid||!this._scheme)return"";switch(this._scheme){case"data":case"file":case"javascript":case"mailto":return"null";case"blob":try{return new h(this._schemeData).origin||"null"}catch(t){}return"null"}return t=this.host,t?this._scheme+"://"+t:""}};var b=o.URL;b&&(h.createObjectURL=function(t){return b.createObjectURL.apply(b,arguments)},h.revokeObjectURL=function(t){b.revokeObjectURL(t)}),o.URL=h}}()}}])})}).call(e,r(0),r(1),r(2).Buffer)},function(t,e){var r={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==r.call(t)}},function(t,e,r){"use strict";(function(e,i){function n(t){return B.from(t)}function o(t){return B.isBuffer(t)||t instanceof U}function a(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?I(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}function s(t,e){j=j||r(4),t=t||{},this.objectMode=!!t.objectMode,e instanceof j&&(this.objectMode=this.objectMode||!!t.readableObjectMode);var i=t.highWaterMark,n=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:n,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new X,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(H||(H=r(19).StringDecoder),this.decoder=new H(t.encoding),this.encoding=t.encoding)}function c(t){if(j=j||r(4),!(this instanceof c))return new c(t);this._readableState=new s(t,this),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),N.call(this)}function l(t,e,r,i,o){var a=t._readableState;if(null===e)a.reading=!1,g(t,a);else{var s;o||(s=u(a,e)),s?t.emit("error",s):a.objectMode||e&&e.length>0?("string"==typeof e||a.objectMode||Object.getPrototypeOf(e)===B.prototype||(e=n(e)),i?a.endEmitted?t.emit("error",new Error("stream.unshift() after end event")):h(t,a,e,!0):a.ended?t.emit("error",new Error("stream.push() after EOF")):(a.reading=!1,a.decoder&&!r?(e=a.decoder.write(e),a.objectMode||0!==e.length?h(t,a,e,!1):b(t,a)):h(t,a,e,!1))):i||(a.reading=!1)}return f(a)}function h(t,e,r,i){e.flowing&&0===e.length&&!e.sync?(t.emit("data",r),t.read(0)):(e.length+=e.objectMode?1:r.length,i?e.buffer.unshift(r):e.buffer.push(r),e.needReadable&&v(t)),b(t,e)}function u(t,e){var r;return o(e)||"string"==typeof e||void 0===e||t.objectMode||(r=new TypeError("Invalid non-string/buffer chunk")),r}function f(t){return!t.ended&&(t.needReadable||t.length<t.highWaterMark||0===t.length)}function d(t){return t>=V?t=V:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}function p(t,e){return t<=0||0===e.length&&e.ended?0:e.objectMode?1:t!==t?e.flowing&&e.length?e.buffer.head.data.length:e.length:(t>e.highWaterMark&&(e.highWaterMark=d(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function g(t,e){if(!e.ended){if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,v(t)}}function v(t){var e=t._readableState;e.needReadable=!1,e.emittedReadable||(q("emitReadable",e.flowing),e.emittedReadable=!0,e.sync?D(m,t):m(t))}function m(t){q("emit readable"),t.emit("readable"),C(t)}function b(t,e){e.readingMore||(e.readingMore=!0,D(y,t,e))}function y(t,e){for(var r=e.length;!e.reading&&!e.flowing&&!e.ended&&e.length<e.highWaterMark&&(q("maybeReadMore read 0"),t.read(0),r!==e.length);)r=e.length;e.readingMore=!1}function _(t){return function(){var e=t._readableState;q("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&F(t,"data")&&(e.flowing=!0,C(t))}}function w(t){q("readable nexttick read 0"),t.read(0)}function S(t,e){e.resumeScheduled||(e.resumeScheduled=!0,D(x,t,e))}function x(t,e){e.reading||(q("resume read 0"),t.read(0)),e.resumeScheduled=!1,e.awaitDrain=0,t.emit("resume"),C(t),e.flowing&&!e.reading&&t.read(0)}function C(t){var e=t._readableState;for(q("flow",e.flowing);e.flowing&&null!==t.read(););}function A(t,e){if(0===e.length)return null;var r;return e.objectMode?r=e.buffer.shift():!t||t>=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.head.data:e.buffer.concat(e.length),e.buffer.clear()):r=T(t,e.buffer,e.decoder),r}function T(t,e,r){var i;return t<e.head.data.length?(i=e.head.data.slice(0,t),e.head.data=e.head.data.slice(t)):i=t===e.head.data.length?e.shift():r?k(t,e):P(t,e),i}function k(t,e){var r=e.head,i=1,n=r.data;for(t-=n.length;r=r.next;){var o=r.data,a=t>o.length?o.length:t;if(a===o.length?n+=o:n+=o.slice(0,t),0===(t-=a)){a===o.length?(++i,r.next?e.head=r.next:e.head=e.tail=null):(e.head=r,r.data=o.slice(a));break}++i}return e.length-=i,n}function P(t,e){var r=B.allocUnsafe(t),i=e.head,n=1;for(i.data.copy(r),t-=i.data.length;i=i.next;){var o=i.data,a=t>o.length?o.length:t;if(o.copy(r,r.length-t,0,a),0===(t-=a)){a===o.length?(++n,i.next?e.head=i.next:e.head=e.tail=null):(e.head=i,i.data=o.slice(a));break}++n}return e.length-=n,r}function E(t){var e=t._readableState;if(e.length>0)throw new Error('"endReadable()" called on non-empty stream');e.endEmitted||(e.ended=!0,D(O,e,t))}function O(t,e){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}function R(t,e){for(var r=0,i=t.length;r<i;r++)e(t[r],r)}function L(t,e){for(var r=0,i=t.length;r<i;r++)if(t[r]===e)return r;return-1}var D=r(7);t.exports=c;var I=r(13),j;c.ReadableState=s;var M=r(15).EventEmitter,F=function(t,e){return t.listeners(e).length},N=r(16),B=r(10).Buffer,U=e.Uint8Array||function(){},z=r(5);z.inherits=r(3);var W=r(44),q=void 0;q=W&&W.debuglog?W.debuglog("stream"):function(){};var X=r(45),G=r(17),H;z.inherits(c,N);var Y=["error","close","destroy","pause","resume"];Object.defineProperty(c.prototype,"destroyed",{get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(t){this._readableState&&(this._readableState.destroyed=t)}}),c.prototype.destroy=G.destroy,c.prototype._undestroy=G.undestroy,c.prototype._destroy=function(t,e){this.push(null),e(t)},c.prototype.push=function(t,e){var r=this._readableState,i;return r.objectMode?i=!0:"string"==typeof t&&(e=e||r.defaultEncoding,e!==r.encoding&&(t=B.from(t,e),e=""),i=!0),l(this,t,e,!1,i)},c.prototype.unshift=function(t){return l(this,t,null,!0,!1)},c.prototype.isPaused=function(){return!1===this._readableState.flowing},c.prototype.setEncoding=function(t){return H||(H=r(19).StringDecoder),this._readableState.decoder=new H(t),this._readableState.encoding=t,this};var V=8388608;c.prototype.read=function(t){q("read",t),t=parseInt(t,10);var e=this._readableState,r=t;if(0!==t&&(e.emittedReadable=!1),0===t&&e.needReadable&&(e.length>=e.highWaterMark||e.ended))return q("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?E(this):v(this),null;if(0===(t=p(t,e))&&e.ended)return 0===e.length&&E(this),null;var i=e.needReadable;q("need readable",i),(0===e.length||e.length-t<e.highWaterMark)&&(i=!0,q("length less than watermark",i)),e.ended||e.reading?(i=!1,q("reading or ended",i)):i&&(q("do read"),e.reading=!0,e.sync=!0,0===e.length&&(e.needReadable=!0),this._read(e.highWaterMark),e.sync=!1,e.reading||(t=p(r,e)));var n;return n=t>0?A(t,e):null,null===n?(e.needReadable=!0,t=0):e.length-=t,0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&E(this)),null!==n&&this.emit("data",n),n},c.prototype._read=function(t){this.emit("error",new Error("_read() is not implemented"))},c.prototype.pipe=function(t,e){function r(t,e){q("onunpipe"),t===f&&e&&!1===e.hasUnpiped&&(e.hasUnpiped=!0,o())}function n(){q("onend"),t.end()}function o(){q("cleanup"),t.removeListener("close",l),t.removeListener("finish",h),t.removeListener("drain",v),t.removeListener("error",c),t.removeListener("unpipe",r),f.removeListener("end",n),f.removeListener("end",u),f.removeListener("data",s),m=!0,!d.awaitDrain||t._writableState&&!t._writableState.needDrain||v()}function s(e){q("ondata"),b=!1,!1!==t.write(e)||b||((1===d.pipesCount&&d.pipes===t||d.pipesCount>1&&-1!==L(d.pipes,t))&&!m&&(q("false write response, pause",f._readableState.awaitDrain),f._readableState.awaitDrain++,b=!0),f.pause())}function c(e){q("onerror",e),u(),t.removeListener("error",c),0===F(t,"error")&&t.emit("error",e)}function l(){t.removeListener("finish",h),u()}function h(){q("onfinish"),t.removeListener("close",l),u()}function u(){q("unpipe"),f.unpipe(t)}var f=this,d=this._readableState;switch(d.pipesCount){case 0:d.pipes=t;break;case 1:d.pipes=[d.pipes,t];break;default:d.pipes.push(t)}d.pipesCount+=1,q("pipe count=%d opts=%j",d.pipesCount,e);var p=(!e||!1!==e.end)&&t!==i.stdout&&t!==i.stderr,g=p?n:u;d.endEmitted?D(g):f.once("end",g),t.on("unpipe",r);var v=_(f);t.on("drain",v);var m=!1,b=!1;return f.on("data",s),a(t,"error",c),t.once("close",l),t.once("finish",h),t.emit("pipe",f),d.flowing||(q("pipe resume"),f.resume()),t},c.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes?this:(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r),this);if(!t){var i=e.pipes,n=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var o=0;o<n;o++)i[o].emit("unpipe",this,r);return this}var a=L(e.pipes,t);return-1===a?this:(e.pipes.splice(a,1),e.pipesCount-=1,1===e.pipesCount&&(e.pipes=e.pipes[0]),t.emit("unpipe",this,r),this)},c.prototype.on=function(t,e){var r=N.prototype.on.call(this,t,e);if("data"===t)!1!==this._readableState.flowing&&this.resume();else if("readable"===t){var i=this._readableState;i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.emittedReadable=!1,i.reading?i.length&&v(this):D(w,this))}return r},c.prototype.addListener=c.prototype.on,c.prototype.resume=function(){var t=this._readableState;return t.flowing||(q("resume"),t.flowing=!0,S(this,t)),this},c.prototype.pause=function(){return q("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(q("pause"),this._readableState.flowing=!1,this.emit("pause")),this},c.prototype.wrap=function(t){var e=this._readableState,r=!1,i=this;t.on("end",function(){if(q("wrapped end"),e.decoder&&!e.ended){var t=e.decoder.end();t&&t.length&&i.push(t)}i.push(null)}),t.on("data",function(n){if(q("wrapped data"),e.decoder&&(n=e.decoder.write(n)),(!e.objectMode||null!==n&&void 0!==n)&&(e.objectMode||n&&n.length)){i.push(n)||(r=!0,t.pause())}});for(var n in t)void 0===this[n]&&"function"==typeof t[n]&&(this[n]=function(e){return function(){return t[e].apply(t,arguments)}}(n));for(var o=0;o<Y.length;o++)t.on(Y[o],i.emit.bind(i,Y[o]));return i._read=function(e){q("wrapped _read",e),r&&(r=!1,t.resume())},i},c._fromList=A}).call(e,r(0),r(1))},function(t,e){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(t){return"function"==typeof t}function n(t){return"number"==typeof t}function o(t){return"object"==typeof t&&null!==t}function a(t){return void 0===t}t.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(t){if(!n(t)||t<0||isNaN(t))throw TypeError("n must be a positive number");return this._maxListeners=t,this},r.prototype.emit=function(t){var e,r,n,s,c,l;if(this._events||(this._events={}),"error"===t&&(!this._events.error||o(this._events.error)&&!this._events.error.length)){if((e=arguments[1])instanceof Error)throw e;var h=new Error('Uncaught, unspecified "error" event. ('+e+")");throw h.context=e,h}if(r=this._events[t],a(r))return!1;if(i(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:s=Array.prototype.slice.call(arguments,1),r.apply(this,s)}else if(o(r))for(s=Array.prototype.slice.call(arguments,1),l=r.slice(),n=l.length,c=0;c<n;c++)l[c].apply(this,s);return!0},r.prototype.addListener=function(t,e){var n;if(!i(e))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",t,i(e.listener)?e.listener:e),this._events[t]?o(this._events[t])?this._events[t].push(e):this._events[t]=[this._events[t],e]:this._events[t]=e,o(this._events[t])&&!this._events[t].warned&&(n=a(this._maxListeners)?r.defaultMaxListeners:this._maxListeners)&&n>0&&this._events[t].length>n&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace()),this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(t,e){function r(){this.removeListener(t,r),n||(n=!0,e.apply(this,arguments))}if(!i(e))throw TypeError("listener must be a function");var n=!1;return r.listener=e,this.on(t,r),this},r.prototype.removeListener=function(t,e){var r,n,a,s;if(!i(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(r=this._events[t],a=r.length,n=-1,r===e||i(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(o(r)){for(s=a;s-- >0;)if(r[s]===e||r[s].listener&&r[s].listener===e){n=s;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},r.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[t],i(r))this.removeListener(t,r);else if(r)for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},r.prototype.listeners=function(t){var e;return e=this._events&&this._events[t]?i(this._events[t])?[this._events[t]]:this._events[t].slice():[]},r.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(i(e))return 1;if(e)return e.length}return 0},r.listenerCount=function(t,e){return t.listenerCount(e)}},function(t,e,r){t.exports=r(15).EventEmitter},function(t,e,r){"use strict";function i(t,e){var r=this,i=this._readableState&&this._readableState.destroyed,n=this._writableState&&this._writableState.destroyed;if(i||n)return void(e?e(t):!t||this._writableState&&this._writableState.errorEmitted||a(o,this,t));this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,function(t){!e&&t?(a(o,r,t),r._writableState&&(r._writableState.errorEmitted=!0)):e&&e(t)})}function n(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function o(t,e){t.emit("error",e)}var a=r(7);t.exports={destroy:i,undestroy:n}},function(t,e,r){"use strict";(function(e,i,n){function o(t,e,r){this.chunk=t,this.encoding=e,this.callback=r,this.next=null}function a(t){var e=this;this.next=null,this.entry=null,this.finish=function(){P(e,t)}}function s(t){return j.from(t)}function c(t){return j.isBuffer(t)||t instanceof M}function l(){}function h(t,e){R=R||r(4),t=t||{},this.objectMode=!!t.objectMode,e instanceof R&&(this.objectMode=this.objectMode||!!t.writableObjectMode);var i=t.highWaterMark,n=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:n,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var o=!1===t.decodeStrings;this.decodeStrings=!o,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(t){y(e,t)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new a(this)}function u(t){if(R=R||r(4),!(N.call(u,this)||this instanceof R))return new u(t);this._writableState=new h(t,this),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),I.call(this)}function f(t,e){var r=new Error("write after end");t.emit("error",r),E(e,r)}function d(t,e,r,i){var n=!0,o=!1;return null===r?o=new TypeError("May not write null values to stream"):"string"==typeof r||void 0===r||e.objectMode||(o=new TypeError("Invalid non-string/buffer chunk")),o&&(t.emit("error",o),E(i,o),n=!1),n}function p(t,e,r){return t.objectMode||!1===t.decodeStrings||"string"!=typeof e||(e=j.from(e,r)),e}function g(t,e,r,i,n,o){if(!r){var a=p(e,i,n);i!==a&&(r=!0,n="buffer",i=a)}var s=e.objectMode?1:i.length;e.length+=s;var c=e.length<e.highWaterMark;if(c||(e.needDrain=!0),e.writing||e.corked){var l=e.lastBufferedRequest;e.lastBufferedRequest={chunk:i,encoding:n,isBuf:r,callback:o,next:null},l?l.next=e.lastBufferedRequest:e.bufferedRequest=e.lastBufferedRequest,e.bufferedRequestCount+=1}else v(t,e,!1,s,i,n,o);return c}function v(t,e,r,i,n,o,a){e.writelen=i,e.writecb=a,e.writing=!0,e.sync=!0,r?t._writev(n,e.onwrite):t._write(n,o,e.onwrite),e.sync=!1}function m(t,e,r,i,n){--e.pendingcb,r?(E(n,i),E(T,t,e),t._writableState.errorEmitted=!0,t.emit("error",i)):(n(i),t._writableState.errorEmitted=!0,t.emit("error",i),T(t,e))}function b(t){t.writing=!1,t.writecb=null,t.length-=t.writelen,t.writelen=0}function y(t,e){var r=t._writableState,i=r.sync,n=r.writecb;if(b(r),e)m(t,r,i,e,n);else{var o=x(r);o||r.corked||r.bufferProcessing||!r.bufferedRequest||S(t,r),i?O(_,t,r,o,n):_(t,r,o,n)}}function _(t,e,r,i){r||w(t,e),e.pendingcb--,i(),T(t,e)}function w(t,e){0===e.length&&e.needDrain&&(e.needDrain=!1,t.emit("drain"))}function S(t,e){e.bufferProcessing=!0;var r=e.bufferedRequest;if(t._writev&&r&&r.next){var i=e.bufferedRequestCount,n=new Array(i),o=e.corkedRequestsFree;o.entry=r;for(var s=0,c=!0;r;)n[s]=r,r.isBuf||(c=!1),r=r.next,s+=1;n.allBuffers=c,v(t,e,!0,e.length,n,"",o.finish),e.pendingcb++,e.lastBufferedRequest=null,o.next?(e.corkedRequestsFree=o.next,o.next=null):e.corkedRequestsFree=new a(e)}else{for(;r;){var l=r.chunk,h=r.encoding,u=r.callback;if(v(t,e,!1,e.objectMode?1:l.length,l,h,u),r=r.next,e.writing)break}null===r&&(e.lastBufferedRequest=null)}e.bufferedRequestCount=0,e.bufferedRequest=r,e.bufferProcessing=!1}function x(t){return t.ending&&0===t.length&&null===t.bufferedRequest&&!t.finished&&!t.writing}function C(t,e){t._final(function(r){e.pendingcb--,r&&t.emit("error",r),e.prefinished=!0,t.emit("prefinish"),T(t,e)})}function A(t,e){e.prefinished||e.finalCalled||("function"==typeof t._final?(e.pendingcb++,e.finalCalled=!0,E(C,t,e)):(e.prefinished=!0,t.emit("prefinish")))}function T(t,e){var r=x(e);return r&&(A(t,e),0===e.pendingcb&&(e.finished=!0,t.emit("finish"))),r}function k(t,e,r){e.ending=!0,T(t,e),r&&(e.finished?E(r):t.once("finish",r)),e.ended=!0,t.writable=!1}function P(t,e,r){var i=t.entry;for(t.entry=null;i;){var n=i.callback;e.pendingcb--,n(r),i=i.next}e.corkedRequestsFree?e.corkedRequestsFree.next=t:e.corkedRequestsFree=t}var E=r(7);t.exports=u;var O=!e.browser&&["v0.10","v0.9."].indexOf(e.version.slice(0,5))>-1?i:E,R;u.WritableState=h;var L=r(5);L.inherits=r(3);var D={deprecate:r(48)},I=r(16),j=r(10).Buffer,M=n.Uint8Array||function(){},F=r(17);L.inherits(u,I),h.prototype.getBuffer=function t(){for(var e=this.bufferedRequest,r=[];e;)r.push(e),e=e.next;return r},function(){try{Object.defineProperty(h.prototype,"buffer",{get:D.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(t){}}();var N;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(N=Function.prototype[Symbol.hasInstance],Object.defineProperty(u,Symbol.hasInstance,{value:function(t){return!!N.call(this,t)||t&&t._writableState instanceof h}})):N=function(t){return t instanceof this},u.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},u.prototype.write=function(t,e,r){var i=this._writableState,n=!1,o=c(t)&&!i.objectMode;return o&&!j.isBuffer(t)&&(t=s(t)),"function"==typeof e&&(r=e,e=null),o?e="buffer":e||(e=i.defaultEncoding),"function"!=typeof r&&(r=l),i.ended?f(this,r):(o||d(this,i,t,r))&&(i.pendingcb++,n=g(this,i,o,t,e,r)),n},u.prototype.cork=function(){this._writableState.corked++},u.prototype.uncork=function(){var t=this._writableState;t.corked&&(t.corked--,t.writing||t.corked||t.finished||t.bufferProcessing||!t.bufferedRequest||S(this,t))},u.prototype.setDefaultEncoding=function t(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},u.prototype._write=function(t,e,r){r(new Error("_write() is not implemented"))},u.prototype._writev=null,u.prototype.end=function(t,e,r){var i=this._writableState;"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!==t&&void 0!==t&&this.write(t,e),i.corked&&(i.corked=1,this.uncork()),i.ending||i.finished||k(this,i,r)},Object.defineProperty(u.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t)}}),u.prototype.destroy=F.destroy,u.prototype._undestroy=F.undestroy,u.prototype._destroy=function(t,e){this.end(),e(t)}}).call(e,r(1),r(46).setImmediate,r(0))},function(t,e,r){function i(t){if(t&&!c(t))throw new Error("Unknown encoding: "+t)}function n(t){return t.toString(this.encoding)}function o(t){this.charReceived=t.length%2,this.charLength=this.charReceived?2:0}function a(t){this.charReceived=t.length%3,this.charLength=this.charReceived?3:0}var s=r(2).Buffer,c=s.isEncoding||function(t){switch(t&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}},l=e.StringDecoder=function(t){switch(this.encoding=(t||"utf8").toLowerCase().replace(/[-_]/,""),i(t),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=o;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=a;break;default:return void(this.write=n)}this.charBuffer=new s(6),this.charReceived=0,this.charLength=0};l.prototype.write=function(t){for(var e="";this.charLength;){var r=t.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:t.length;if(t.copy(this.charBuffer,this.charReceived,0,r),this.charReceived+=r,this.charReceived<this.charLength)return"";t=t.slice(r,t.length),e=this.charBuffer.slice(0,this.charLength).toString(this.encoding);var i=e.charCodeAt(e.length-1);if(!(i>=55296&&i<=56319)){if(this.charReceived=this.charLength=0,0===t.length)return e;break}this.charLength+=this.surrogateSize,e=""}this.detectIncompleteChar(t);var n=t.length;this.charLength&&(t.copy(this.charBuffer,0,t.length-this.charReceived,n),n-=this.charReceived),e+=t.toString(this.encoding,0,n);var n=e.length-1,i=e.charCodeAt(n);if(i>=55296&&i<=56319){var o=this.surrogateSize;return this.charLength+=o,this.charReceived+=o,this.charBuffer.copy(this.charBuffer,o,0,o),t.copy(this.charBuffer,0,0,o),e.substring(0,n)}return e},l.prototype.detectIncompleteChar=function(t){for(var e=t.length>=3?3:t.length;e>0;e--){var r=t[t.length-e];if(1==e&&r>>5==6){this.charLength=2;break}if(e<=2&&r>>4==14){this.charLength=3;break}if(e<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=e},l.prototype.end=function(t){var e="";if(t&&t.length&&(e=this.write(t)),this.charReceived){var r=this.charReceived,i=this.charBuffer,n=this.encoding;e+=i.slice(0,r).toString(n)}return e}},function(t,e,r){"use strict";function i(t){this.afterTransform=function(e,r){return n(t,e,r)},this.needTransform=!1,this.transforming=!1,this.writecb=null,this.writechunk=null,this.writeencoding=null}function n(t,e,r){var i=t._transformState;i.transforming=!1;var n=i.writecb;if(!n)return t.emit("error",new Error("write callback called multiple times"));i.writechunk=null,i.writecb=null,null!==r&&void 0!==r&&t.push(r),n(e);var o=t._readableState;o.reading=!1,(o.needReadable||o.length<o.highWaterMark)&&t._read(o.highWaterMark)}function o(t){if(!(this instanceof o))return new o(t);s.call(this,t),this._transformState=new i(this);var e=this;this._readableState.needReadable=!0,this._readableState.sync=!1,t&&("function"==typeof t.transform&&(this._transform=t.transform),"function"==typeof t.flush&&(this._flush=t.flush)),this.once("prefinish",function(){"function"==typeof this._flush?this._flush(function(t,r){a(e,t,r)}):a(e)})}function a(t,e,r){if(e)return t.emit("error",e);null!==r&&void 0!==r&&t.push(r);var i=t._writableState,n=t._transformState;if(i.length)throw new Error("Calling transform done when ws.length != 0");if(n.transforming)throw new Error("Calling transform done when still transforming");return t.push(null)}t.exports=o;var s=r(4),c=r(5);c.inherits=r(3),c.inherits(o,s),o.prototype.push=function(t,e){return this._transformState.needTransform=!1,s.prototype.push.call(this,t,e)},o.prototype._transform=function(t,e,r){throw new Error("_transform() is not implemented")},o.prototype._write=function(t,e,r){var i=this._transformState;if(i.writecb=r,i.writechunk=t,i.writeencoding=e,!i.transforming){var n=this._readableState;(i.needTransform||n.needReadable||n.length<n.highWaterMark)&&this._read(n.highWaterMark)}},o.prototype._read=function(t){var e=this._transformState;null!==e.writechunk&&e.writecb&&!e.transforming?(e.transforming=!0,this._transform(e.writechunk,e.writeencoding,e.afterTransform)):e.needTransform=!0},o.prototype._destroy=function(t,e){var r=this;s.prototype._destroy.call(this,t,function(t){e(t),r.emit("close")})}},function(t,e,r){"use strict";t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},function(t,e,r){"use strict";function i(t,e,r,i){for(var n=65535&t|0,o=t>>>16&65535|0,a=0;0!==r;){a=r>2e3?2e3:r,r-=a;do{n=n+e[i++]|0,o=o+n|0}while(--a);n%=65521,o%=65521}return n|o<<16|0}t.exports=i},function(t,e,r){"use strict";function i(){for(var t,e=[],r=0;r<256;r++){t=r;for(var i=0;i<8;i++)t=1&t?3988292384^t>>>1:t>>>1;e[r]=t}return e}function n(t,e,r,i){var n=o,a=i+r;t^=-1;for(var s=i;s<a;s++)t=t>>>8^n[255&(t^e[s])];return-1^t}var o=i();t.exports=n},function(t,e,r){(function(t,i){function n(t,r){var i={seen:[],stylize:a};return arguments.length>=3&&(i.depth=arguments[2]),arguments.length>=4&&(i.colors=arguments[3]),g(r)?i.showHidden=r:r&&e._extend(i,r),w(i.showHidden)&&(i.showHidden=!1),w(i.depth)&&(i.depth=2),w(i.colors)&&(i.colors=!1),w(i.customInspect)&&(i.customInspect=!0),i.colors&&(i.stylize=o),c(i,t,i.depth)}function o(t,e){var r=n.styles[e];return r?"["+n.colors[r][0]+"m"+t+"["+n.colors[r][1]+"m":t}function a(t,e){return t}function s(t){var e={};return t.forEach(function(t,r){e[t]=!0}),e}function c(t,r,i){if(t.customInspect&&r&&T(r.inspect)&&r.inspect!==e.inspect&&(!r.constructor||r.constructor.prototype!==r)){var n=r.inspect(i,t);return y(n)||(n=c(t,n,i)),n}var o=l(t,r);if(o)return o;var a=Object.keys(r),g=s(a);if(t.showHidden&&(a=Object.getOwnPropertyNames(r)),A(r)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return h(r);if(0===a.length){if(T(r)){var v=r.name?": "+r.name:"";return t.stylize("[Function"+v+"]","special")}if(S(r))return t.stylize(RegExp.prototype.toString.call(r),"regexp");if(C(r))return t.stylize(Date.prototype.toString.call(r),"date");if(A(r))return h(r)}var m="",b=!1,_=["{","}"];if(p(r)&&(b=!0,_=["[","]"]),T(r)){m=" [Function"+(r.name?": "+r.name:"")+"]"}if(S(r)&&(m=" "+RegExp.prototype.toString.call(r)),C(r)&&(m=" "+Date.prototype.toUTCString.call(r)),A(r)&&(m=" "+h(r)),0===a.length&&(!b||0==r.length))return _[0]+m+_[1];if(i<0)return S(r)?t.stylize(RegExp.prototype.toString.call(r),"regexp"):t.stylize("[Object]","special");t.seen.push(r);var w;return w=b?u(t,r,i,g,a):a.map(function(e){return f(t,r,i,g,e,b)}),t.seen.pop(),d(w,m,_)}function l(t,e){if(w(e))return t.stylize("undefined","undefined");if(y(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}return b(e)?t.stylize(""+e,"number"):g(e)?t.stylize(""+e,"boolean"):v(e)?t.stylize("null","null"):void 0}function h(t){return"["+Error.prototype.toString.call(t)+"]"}function u(t,e,r,i,n){for(var o=[],a=0,s=e.length;a<s;++a)R(e,String(a))?o.push(f(t,e,r,i,String(a),!0)):o.push("");return n.forEach(function(n){n.match(/^\d+$/)||o.push(f(t,e,r,i,n,!0))}),o}function f(t,e,r,i,n,o){var a,s,l;if(l=Object.getOwnPropertyDescriptor(e,n)||{value:e[n]},l.get?s=l.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):l.set&&(s=t.stylize("[Setter]","special")),R(i,n)||(a="["+n+"]"),s||(t.seen.indexOf(l.value)<0?(s=v(r)?c(t,l.value,null):c(t,l.value,r-1),s.indexOf("\n")>-1&&(s=o?s.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+s.split("\n").map(function(t){return" "+t}).join("\n"))):s=t.stylize("[Circular]","special")),w(a)){if(o&&n.match(/^\d+$/))return s;a=JSON.stringify(""+n),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=t.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=t.stylize(a,"string"))}return a+": "+s}function d(t,e,r){var i=0;return t.reduce(function(t,e){return i++,e.indexOf("\n")>=0&&i++,t+e.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1]:r[0]+e+" "+t.join(", ")+" "+r[1]}function p(t){return Array.isArray(t)}function g(t){return"boolean"==typeof t}function v(t){return null===t}function m(t){return null==t}function b(t){return"number"==typeof t}function y(t){return"string"==typeof t}function _(t){return"symbol"==typeof t}function w(t){return void 0===t}function S(t){return x(t)&&"[object RegExp]"===P(t)}function x(t){return"object"==typeof t&&null!==t}function C(t){return x(t)&&"[object Date]"===P(t)}function A(t){return x(t)&&("[object Error]"===P(t)||t instanceof Error)}function T(t){return"function"==typeof t}function k(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t}function P(t){return Object.prototype.toString.call(t)}function E(t){return t<10?"0"+t.toString(10):t.toString(10)}function O(){var t=new Date,e=[E(t.getHours()),E(t.getMinutes()),E(t.getSeconds())].join(":");return[t.getDate(),j[t.getMonth()],e].join(" ")}function R(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var L=/%[sdj%]/g;e.format=function(t){if(!y(t)){for(var e=[],r=0;r<arguments.length;r++)e.push(n(arguments[r]));return e.join(" ")}for(var r=1,i=arguments,o=i.length,a=String(t).replace(L,function(t){if("%%"===t)return"%";if(r>=o)return t;switch(t){case"%s":return String(i[r++]);case"%d":return Number(i[r++]);case"%j":try{return JSON.stringify(i[r++])}catch(t){return"[Circular]"}default:return t}}),s=i[r];r<o;s=i[++r])v(s)||!x(s)?a+=" "+s:a+=" "+n(s);return a},e.deprecate=function(r,n){function o(){if(!a){if(i.throwDeprecation)throw new Error(n);i.traceDeprecation?console.trace(n):console.error(n),a=!0}return r.apply(this,arguments)}if(w(t.process))return function(){return e.deprecate(r,n).apply(this,arguments)};if(!0===i.noDeprecation)return r;var a=!1;return o};var D={},I;e.debuglog=function(t){if(w(I)&&(I=i.env.NODE_DEBUG||""),t=t.toUpperCase(),!D[t])if(new RegExp("\\b"+t+"\\b","i").test(I)){var r=i.pid;D[t]=function(){var i=e.format.apply(e,arguments);console.error("%s %d: %s",t,r,i)}}else D[t]=function(){};return D[t]},e.inspect=n,n.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},n.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},e.isArray=p,e.isBoolean=g,e.isNull=v,e.isNullOrUndefined=m,e.isNumber=b,e.isString=y,e.isSymbol=_,e.isUndefined=w,e.isRegExp=S,e.isObject=x,e.isDate=C,e.isError=A,e.isFunction=T,e.isPrimitive=k,e.isBuffer=r(58);var j=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];e.log=function(){console.log("%s - %s",O(),e.format.apply(e,arguments))},e.inherits=r(59),e._extend=function(t,e){if(!e||!x(e))return t;for(var r=Object.keys(e),i=r.length;i--;)t[r[i]]=e[r[i]];return t}}).call(e,r(0),r(1))},function(t,e,r){"use strict";function i(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}function n(t,e,r){if(t&&l.isObject(t)&&t instanceof i)return t;var n=new i;return n.parse(t,e,r),n}function o(t){return l.isString(t)&&(t=n(t)),t instanceof i?t.format():i.prototype.format.call(t)}function a(t,e){return n(t,!1,!0).resolve(e)}function s(t,e){return t?n(t,!1,!0).resolveObject(e):e}var c=r(66),l=r(68);e.parse=n,e.resolve=a,e.resolveObject=s,e.format=o,e.Url=i;var h=/^([a-z0-9.+-]+:)/i,u=/:[0-9]*$/,f=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,d=["<",">",'"',"`"," ","\r","\n","\t"],p=["{","}","|","\\","^","`"].concat(d),g=["'"].concat(p),v=["%","/","?",";","#"].concat(g),m=["/","?","#"],b=255,y=/^[+a-z0-9A-Z_-]{0,63}$/,_=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,w={javascript:!0,"javascript:":!0},S={javascript:!0,"javascript:":!0},x={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},C=r(69);i.prototype.parse=function(t,e,r){if(!l.isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var i=t.indexOf("?"),n=-1!==i&&i<t.indexOf("#")?"?":"#",o=t.split(n),a=/\\/g;o[0]=o[0].replace(a,"/"),t=o.join(n);var s=t;if(s=s.trim(),!r&&1===t.split("#").length){var u=f.exec(s);if(u)return this.path=s,this.href=s,this.pathname=u[1],u[2]?(this.search=u[2],this.query=e?C.parse(this.search.substr(1)):this.search.substr(1)):e&&(this.search="",this.query={}),this}var d=h.exec(s);if(d){d=d[0];var p=d.toLowerCase();this.protocol=p,s=s.substr(d.length)}if(r||d||s.match(/^\/\/[^@\/]+@[^@\/]+/)){var b="//"===s.substr(0,2);!b||d&&S[d]||(s=s.substr(2),this.slashes=!0)}if(!S[d]&&(b||d&&!x[d])){for(var A=-1,T=0;T<m.length;T++){var k=s.indexOf(m[T]);-1!==k&&(-1===A||k<A)&&(A=k)}var P,E;E=-1===A?s.lastIndexOf("@"):s.lastIndexOf("@",A),-1!==E&&(P=s.slice(0,E),s=s.slice(E+1),this.auth=decodeURIComponent(P)),A=-1;for(var T=0;T<v.length;T++){var k=s.indexOf(v[T]);-1!==k&&(-1===A||k<A)&&(A=k)}-1===A&&(A=s.length),this.host=s.slice(0,A),s=s.slice(A),this.parseHost(),this.hostname=this.hostname||"";var O="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!O)for(var R=this.hostname.split(/\./),T=0,L=R.length;T<L;T++){var D=R[T];if(D&&!D.match(y)){for(var I="",j=0,M=D.length;j<M;j++)D.charCodeAt(j)>127?I+="x":I+=D[j];if(!I.match(y)){var F=R.slice(0,T),N=R.slice(T+1),B=D.match(_);B&&(F.push(B[1]),N.unshift(B[2])),N.length&&(s="/"+N.join(".")+s),this.hostname=F.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),O||(this.hostname=c.toASCII(this.hostname));var U=this.port?":"+this.port:"",z=this.hostname||"";this.host=z+U,this.href+=this.host,O&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==s[0]&&(s="/"+s))}if(!w[p])for(var T=0,L=g.length;T<L;T++){var W=g[T];if(-1!==s.indexOf(W)){var q=encodeURIComponent(W);q===W&&(q=escape(W)),s=s.split(W).join(q)}}var X=s.indexOf("#");-1!==X&&(this.hash=s.substr(X),s=s.slice(0,X));var G=s.indexOf("?");if(-1!==G?(this.search=s.substr(G),this.query=s.substr(G+1),e&&(this.query=C.parse(this.query)),s=s.slice(0,G)):e&&(this.search="",this.query={}),s&&(this.pathname=s),x[p]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var U=this.pathname||"",H=this.search||"";this.path=U+H}return this.href=this.format(),this},i.prototype.format=function(){var t=this.auth||"";t&&(t=encodeURIComponent(t),t=t.replace(/%3A/i,":"),t+="@");var e=this.protocol||"",r=this.pathname||"",i=this.hash||"",n=!1,o="";this.host?n=t+this.host:this.hostname&&(n=t+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(n+=":"+this.port)),this.query&&l.isObject(this.query)&&Object.keys(this.query).length&&(o=C.stringify(this.query));var a=this.search||o&&"?"+o||"";return e&&":"!==e.substr(-1)&&(e+=":"),this.slashes||(!e||x[e])&&!1!==n?(n="//"+(n||""),r&&"/"!==r.charAt(0)&&(r="/"+r)):n||(n=""),i&&"#"!==i.charAt(0)&&(i="#"+i),a&&"?"!==a.charAt(0)&&(a="?"+a),r=r.replace(/[?#]/g,function(t){return encodeURIComponent(t)}),a=a.replace("#","%23"),e+n+r+a+i},i.prototype.resolve=function(t){return this.resolveObject(n(t,!1,!0)).format()},i.prototype.resolveObject=function(t){if(l.isString(t)){var e=new i;e.parse(t,!1,!0),t=e}for(var r=new i,n=Object.keys(this),o=0;o<n.length;o++){var a=n[o];r[a]=this[a]}if(r.hash=t.hash,""===t.href)return r.href=r.format(),r;if(t.slashes&&!t.protocol){for(var s=Object.keys(t),c=0;c<s.length;c++){var h=s[c];"protocol"!==h&&(r[h]=t[h])}return x[r.protocol]&&r.hostname&&!r.pathname&&(r.path=r.pathname="/"),r.href=r.format(),r}if(t.protocol&&t.protocol!==r.protocol){if(!x[t.protocol]){for(var u=Object.keys(t),f=0;f<u.length;f++){var d=u[f];r[d]=t[d]}return r.href=r.format(),r}if(r.protocol=t.protocol,t.host||S[t.protocol])r.pathname=t.pathname;else{for(var p=(t.pathname||"").split("/");p.length&&!(t.host=p.shift()););t.host||(t.host=""),t.hostname||(t.hostname=""),""!==p[0]&&p.unshift(""),p.length<2&&p.unshift(""),r.pathname=p.join("/")}if(r.search=t.search,r.query=t.query,r.host=t.host||"",r.auth=t.auth,r.hostname=t.hostname||t.host,r.port=t.port,r.pathname||r.search){var g=r.pathname||"",v=r.search||"";r.path=g+v}return r.slashes=r.slashes||t.slashes,r.href=r.format(),r}var m=r.pathname&&"/"===r.pathname.charAt(0),b=t.host||t.pathname&&"/"===t.pathname.charAt(0),y=b||m||r.host&&t.pathname,_=y,w=r.pathname&&r.pathname.split("/")||[],p=t.pathname&&t.pathname.split("/")||[],C=r.protocol&&!x[r.protocol];if(C&&(r.hostname="",r.port=null,r.host&&(""===w[0]?w[0]=r.host:w.unshift(r.host)),r.host="",t.protocol&&(t.hostname=null,t.port=null,t.host&&(""===p[0]?p[0]=t.host:p.unshift(t.host)),t.host=null),y=y&&(""===p[0]||""===w[0])),b)r.host=t.host||""===t.host?t.host:r.host,r.hostname=t.hostname||""===t.hostname?t.hostname:r.hostname,r.search=t.search,r.query=t.query,w=p;else if(p.length)w||(w=[]),w.pop(),w=w.concat(p),r.search=t.search,r.query=t.query;else if(!l.isNullOrUndefined(t.search)){if(C){r.hostname=r.host=w.shift();var A=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@");A&&(r.auth=A.shift(),r.host=r.hostname=A.shift())}return r.search=t.search,r.query=t.query,l.isNull(r.pathname)&&l.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!w.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var T=w.slice(-1)[0],k=(r.host||t.host||w.length>1)&&("."===T||".."===T)||""===T,P=0,E=w.length;E>=0;E--)T=w[E],"."===T?w.splice(E,1):".."===T?(w.splice(E,1),P++):P&&(w.splice(E,1),P--);if(!y&&!_)for(;P--;P)w.unshift("..");!y||""===w[0]||w[0]&&"/"===w[0].charAt(0)||w.unshift(""),k&&"/"!==w.join("/").substr(-1)&&w.push("");var O=""===w[0]||w[0]&&"/"===w[0].charAt(0);if(C){r.hostname=r.host=O?"":w.length?w.shift():"";var A=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@");A&&(r.auth=A.shift(),r.host=r.hostname=A.shift())}return y=y||r.host&&w.length,y&&!O&&w.unshift(""),w.length?r.pathname=w.join("/"):(r.pathname=null,r.path=null),l.isNull(r.pathname)&&l.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=t.auth||r.auth,r.slashes=r.slashes||t.slashes,r.href=r.format(),r},i.prototype.parseHost=function(){var t=this.host,e=u.exec(t);e&&(e=e[0],":"!==e&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)}},function(t,e,r){(function(t){var i=r(72),n=r(75),o=r(76),a=r(25),s=e;s.request=function(e,r){e="string"==typeof e?a.parse(e):n(e);var o=-1===t.location.protocol.search(/^https?:$/)?"http:":"",s=e.protocol||o,c=e.hostname||e.host,l=e.port,h=e.path||"/";c&&-1!==c.indexOf(":")&&(c="["+c+"]"),e.url=(c?s+"//"+c:"")+(l?":"+l:"")+h,e.method=(e.method||"GET").toUpperCase(),e.headers=e.headers||{};var u=new i(e);return r&&u.on("response",r),u},s.get=function t(e,r){var i=s.request(e,r);return i.end(),i},s.Agent=function(){},s.Agent.defaultMaxSockets=4,s.STATUS_CODES=o,s.METHODS=["CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REPORT","SEARCH","SUBSCRIBE","TRACE","UNLOCK","UNSUBSCRIBE"]}).call(e,r(0))},function(t,e,r){(function(t){function r(){if(void 0!==o)return o;if(t.XMLHttpRequest){o=new t.XMLHttpRequest;try{o.open("GET",t.XDomainRequest?"/":"https://example.com")}catch(t){o=null}}else o=null;return o}function i(t){var e=r();if(!e)return!1;try{return e.responseType=t,e.responseType===t}catch(t){}return!1}function n(t){return"function"==typeof t}e.fetch=n(t.fetch)&&n(t.ReadableStream),e.blobConstructor=!1;try{new Blob([new ArrayBuffer(1)]),e.blobConstructor=!0}catch(t){}var o,a=void 0!==t.ArrayBuffer,s=a&&n(t.ArrayBuffer.prototype.slice);e.arraybuffer=e.fetch||a&&i("arraybuffer"),e.msstream=!e.fetch&&s&&i("ms-stream"),e.mozchunkedarraybuffer=!e.fetch&&a&&i("moz-chunked-arraybuffer"),e.overrideMimeType=e.fetch||!!r()&&n(r().overrideMimeType),e.vbArray=n(t.VBArray),o=null}).call(e,r(0))},function(t,e){function r(t){throw new Error("Cannot find module '"+t+"'.")}r.keys=function(){return[]},r.resolve=r,t.exports=r,r.id=28},function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t){function e(e){function i(t,e){return e.getPage(1).then(function(e){return A=e,x=A.getViewport(1),t.clientWidth/(x.width*v)})}return(0,l.getDocument)(e).then(function(e){return Promise.all([i(t,e),T.setDocument(e)])}).then(function(t){var e=o(t,1),i=e[0];T.currentScale=i,x=A.getViewport(i),r(x.width*v,x.height*v)})}function r(e,r){var i=document.createElement("canvas");i.id=s.default.generate(),i.width=e,i.height=r,t.appendChild(i),C=new h.fabric.Canvas(i.id),C.selection=!1,h.fabric.util.addListener(document.getElementsByClassName("upper-canvas")[0],"contextmenu",function(t){var e=C.getPointer(t),r=C.findTarget(t);w.emit("contextmenu",t,e,r),t.preventDefault()}),C.on("mouse:dblclick",function(t){var e=C.getPointer(t.e);w.emit("mouse:dblclick",t.e,e),t.e.preventDefault()}),C.on("mouse:up",function(t){var e=C.getPointer(t.e),r=C.findTarget(t.e);w.emit("mouse:up",t.e,e,r),t.e.preventDefault()}),C.on("mouse:down",function(t){var e=C.getPointer(t.e),r=C.findTarget(t.e);w.emit("mouse:down",t.e,e,r),t.e.preventDefault()}),C.on("mouse:wheel",function(t){var e=(0,p.default)(t.e).pixelY/3600;w.emit("mouse:wheel",t.e,e),t.e.preventDefault()}),C.on("object:selected",function(t){var e=t.target;w.emit("object:selected",e)})}function i(t,e){function r(e){return new Promise(function(r){h.fabric.Image.fromURL(e,function(e){e.top=t.y-e.height,e.left=t.x-e.width/2,e.topRate=t.y/C.height,e.leftRate=t.x/C.width,e.opacity=w.pinOpacity,e.hasControls=!1,e.hasRotatingPoint=!1;var i=b(t),n=o(i,2),s=n[0],c=n[1];e.pdfPoint={x:s,y:c},e.index=C.size(),e.on("moving",function(t){return y(t,e)}),Object.assign(e,a),C.add(e),r(e)})})}var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return e&&(w.pinImgURL=e),i.text?n(w.pinImgURL,i).then(r):r(w.pinImgURL)}function n(e,r){return new Promise(function(i){h.fabric.Image.fromURL(e,function(e){var n=document.createElement("canvas");n.id=s.default.generate(),n.width=e.width,n.height=e.height,n.style.display="none",t.appendChild(n);var o=new h.fabric.Canvas(n.id);e.left=0,e.top=0,o.add(e);var a=new h.fabric.Text(r.text,{fontSize:r.fontSize||20,fill:r.color||"red",fontFamily:r.fontFamily||"Comic Sans",fontWeight:r.fontWeight||"normal"});a.left=e.left+(e.width-a.width)/2,a.top=e.top+(e.height-a.height)/2.5,o.add(a),i(o.toDataURL()),o.dispose(),t.removeChild(n)})})}function a(t,e,r,n){var a=x.convertToViewportPoint(t.x,t.y),s=o(a,2);return i({x:s[0],y:s[1]},e,r,n)}function c(t,e,r,n,o){return i({x:t*C.width,y:e*C.height},r,n,o)}function u(t){var e=C.item(t);e&&(C.remove(e),e.text&&C.remove(e.text))}function d(t){}function m(t){var e=T.currentScale,r=e+t,i=r/e;T.currentScale=r,x=A.getViewport(r);var n=C.getHeight(),o=C.getWidth();C.setHeight(n*i),C.setWidth(o*i),C.getObjects().forEach(function(t){t.set("top",C.height*t.topRate-t.height),t.set("left",C.width*t.leftRate-t.width/2),t.setCoords()}),C.renderAll(),C.calcOffset()}function b(t){return x.convertToPdfPoint(t.x,t.y)}function y(t,e){e.topRate=(e.top+e.height)/C.height,e.leftRate=(e.left+e.width/2)/C.width;var r=b({x:e.left+e.width/2,y:e.top+e.height}),i=o(r,2),n=i[0],a=i[1];e.pdfPoint={x:n,y:a},e.setCoords(),w.emit("object:moving",e)}var _=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};f.default.call(this);var w=this;w.load=e,w.addPin=i,w.addPinWithRate=c,w.addPinWithPdfPoint=a,w.removePin=u,w.zoomIn=m,w.zoomOut=d,w.pinImgURL=_.pinImgURL||"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACEAAAAvCAYAAABt7qMfAAAJKklEQVRYR61YfXBU1RX/nfdYEoyQooKY7AappaWDBUuKu+8ljKGVFMpQsQOCfLT8g6NQC1ItVSvy0TLaGaso2kFrrJXWqSgWYaCIpZnKvrcJRGescawoluwGUygfgkCy+947nfNyN25eNiSLPX8l+84593fPPR+/ewn9lLZx40oyJSW1xHyjRzSeiCrAfBmASwCcB3ACzCkA/yTgjY5MZvc1TU2f9sc99aXUZprDM0AtmOcCqAZQ2pcNgM8AWABeYk3bVRGPH7mQTa8gmseOHThkyJBZRLSCmccDGBBw5IFIdp8GEAIwNK8O0Axgg55Ov1jW1HQuH5i8ID6qrCwdGArdC6IfAyjJMTzhh5v5gEf0HjE3a7p+ymUeogFjGLiWmScQIKCH5diliehZraNjVVlT03+DQHqAaJ04MeLp+noQzQeQ/d4C5hcBvBo6d+7dEe+8c7a38CYNY5DO/HWX6CYA4uOarC4RvaYxryyz7fdz7buB+Lim5ksDOjqeAzCzS4n576Tr94Xj8UQ/cqGbSso0r2Pm9QCm5myoPkQ0Z4RlHe0Cl/3j4LRpRcWnTq0GsFIZuGCuC2naL3INCgVyuLp6qOY4q0F0h8odcfFk6OzZldmIdkUiaZoLwPw0gEGixcCmQZp2z7B4/EyhCwf15YiIeR0TrVAbdBhYXmHbT4quD+JQNHplSNO2A5ioHOwNEd3aWwQYoLZJk65wHGeE53mleih0Jp3JtI1qaDhGgJcPtESEXPd5Amao78060fQyyzrsg2iJxRZJ9gLQAJz2PG/WyIaGPfmc/XvSpKt0x7kdwM0ARqhm1U7AUSbarmUyG8v370/ms02ZpsHMfwEw3P/O/JNIIvEEHauqGtzBvJmZv6+O4dGj6fTKbzU1ZYKOUqY53WNeS8A3cxItqNYM5lWRRGJr8INEMBWLrQKR5J5Ifcbz5lLSMGRHzwMYDOC4zlxblki8ledcJcMlWmU5304DkJy5NNBJjzGwrMK2pay7yRHDGOMCbwAoByCNbgmlTPMRZpaEEflHUVHR9OH19dJ2uyQVjYY9TdtGwAT1YyuYn9GI9njAUdK0K9jzagDcBmCUr0P0AZinR2z7w1xffhWePLkVRN/z1Zifo2QsthdEk5XihohtLw+ibzHNJcTsZ7LkDAM/qrBtOdtu0hqLyXD7U7ZbEvP94URC+kQ3SZrmajA/qH58W47jAwCjFfplEct6PNeCZ8/WW5PJzUwkA0yS6fFwcfFPqb7eCTr3z9wwHgAgZ05g3tk+dOgPRu/a1ZGrqwqhTuXVEQEhE+4qdJbWwohty0665GA0OqSYaDeIYgDOep43dWRDw74ggOz/qerq8ey6fwNwOYD3QkSTg6WejMWmgUgiORBAhyBvY+BKAC4xzwsnEi/lLiD1rXveHmauBHBSZ74xX+JmbZLR6GhoWr1K4EPkeTeEGxqEZ3RJi2kKL3kNQJG/btIwDgL4igq1X7e5BtLtAOwA8G0AGQLmh217S2+ROByNTtE0TXYpZKcxnU7XBslNyjQXMrNUJBHwH6mO15l5ijgl5qfCicTSHolkGAJMxjqIaA8c59ZwY+PxoJ7qOc8w8xz17YWwbS8KdtEW0/wVMd+ndA7IcaxlQJJJpNHT9akj9+07mSd80nyEWzCYf8e6vjqXMX0yadIwx3HuV2B1vwcQzYtY1iu5vhRNlKOQyIpspFRV1WT2vD+rsvqUNG1qcGwfqay8xA2FNoFoQY5Dm5lf1oAUE0liy/i/IdtJGdieSacXBo8iaRjfQGezktb9GYgWkU/jSkvrwCwERErw4XAicS/5g/Rz8bkm86MA5gWOwQUgO+8SATCA6E4ZTj2O1jRXgvkh9fuOds+b7w8wlSi/VwOs1dO0746Mx4UbdpPU9ddfzpomvV96RucQ6i4nQLTVyWQeGLV/f1vw4+Hq6i9rnrcLzF/190u0tMKynvJBHKmurnBd93UAX1OGD0Zse22eRcA1NQM+aW8f5wA1BIwB0aUgErr3ITyv/vSZM2+PbW6WmdBDkoaxDMBj6kOLpmm15fH4v7pITYth/IaAu5TCu47jTMm3m6BnBrTeOESurqKOOwEY6ve6sG0vFtvPQZjmRGJ+GUAFAGnJt0dsW6bm/0VShjGbgT8AKAZwjIjmhi1rrzjvRnQD5fo+ue5N4cZGmS1fSJKGIWP71SxzY+CxiG2vyCZ/dxCdfX+XmiWycK+5UQgqlQtSWbLecSKaEbYsO+ujGwg1BUVZEkjkI0/Xa0fu23eokEVzdVuqqsrI8/4KQPqDzx/KI5HFtGWLlLYvPS4/agBJd7y2U4PWhMvL1+UaFQIoZRjLGXhElf8hnXl2cADmvQYqErNRgTzFwNwK295dyOKi2xqLVXlEkuxCiGVDP49Y1sNBP/lBSAhddyeI5E4pXfQVp7h4waj6+vb+ApF+0ppOyzBbpGwOqrnU42h7vZW3xGJziGiTIrDnifmOcCIh47df0mIYM6mzJIVAnyei5WHLkstVD+kVhOwk2dHxLAE/zO4Enjc90tAg/OOCIsSYOy9T1ynFrU5R0fzeInnBR5IjsdgEl0icddJ8oifC5eV39ZWkKdP8JTPLWBc5zpp2c0U8/mZvyC8Iwi9Z03wIzD9TDo5pwMxy25ZXmLySjEbHQdd3gDmiFJ4Oh8NLLgS8z+cif3Lq+mZ1vRe/luY4c/Nd9dS4l2k8TQF4kzxvXpBjBtH3CUIMFDEVhiQ3LamW1ZFEYk3QWUsstoKIpCeIdMhDS5BZ5Qtfv0AI8SkdPHg9E8nFSAhMijRtdi4DU4xJ5kP2ZaZOT6fv7O2dKhdMv0CIQdIwLiOibcwsL3hCu+Ku48ySce8/hLjuH7PHwMBb0LQZfb3aZYH0G4R/LN1r32/pEctarY7h1ypK7SBaHLEsyaN+SUEg/C7Y3r6BiZaId7kzeMA6DbibgavVii84RUW3FdJdCwIhi6hHErnyC7MWEWonFx3xdcB13Vuubmz8uF8hUEoFgxC7lGF8hwGpltzX3XNMNK/CsrYVAkBFtFAT4EBlZWj4wIFrCLhHveLKZfq3TlHR3YUcw0UlZi5cuUmlS0rqCLhFngC8AQMWBG9u/d3eRR1H1nkyFqsBkbzILQ3btlyaL0r+B7tw5ax4J5d3AAAAAElFTkSuQmCC",w.pinOpacity=_.pinOpacity||1;var S=document.createElement("div");S.id=s.default.generate(),S.style.position="absolute",t.appendChild(S);var x=null,C=null,A=null,T=new g({container:t,viewer:S})}Object.defineProperty(e,"__esModule",{value:!0});var o=function(){function t(t,e){var r=[],i=!0,n=!1,o=void 0;try{for(var a=t[Symbol.iterator](),s;!(i=(s=a.next()).done)&&(r.push(s.value),!e||r.length!==e);i=!0);}catch(t){n=!0,o=t}finally{try{!i&&a.return&&a.return()}finally{if(n)throw o}}return r}return function(e,r){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return t(e,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),a=r(30),s=i(a);r(38);var c=r(39),l=r(61),h=r(63),u=r(79),f=i(u),d=r(80),p=i(d),g=c.PDFJS.PDFViewer,v=96/72;c.PDFJS.disableTextLayer=!0,h.fabric.devicePixelRatio=1,n.prototype=Object.create(f.default.prototype),n.prototype.constructor=n,e.default=n},function(t,e,r){"use strict";t.exports=r(31)},function(t,e,r){"use strict";function i(e){return s.seed(e),t.exports}function n(e){return f=e,t.exports}function o(t){return void 0!==t&&s.characters(t),s.shuffled()}function a(){return h(f)}var s=r(6),c=r(11),l=r(34),h=r(35),u=r(36),f=r(37)||0;t.exports=a,t.exports.generate=a,t.exports.seed=i,t.exports.worker=n,t.exports.characters=o,t.exports.decode=l,t.exports.isValid=u},function(t,e,r){"use strict";function i(){return(o=(9301*o+49297)%233280)/233280}function n(t){o=t}var o=1;t.exports={nextValue:i,seed:n}},function(t,e,r){"use strict";function i(){if(!n||!n.getRandomValues)return 48&Math.floor(256*Math.random());var t=new Uint8Array(1);return n.getRandomValues(t),48&t[0]}var n="object"==typeof window&&(window.crypto||window.msCrypto);t.exports=i},function(t,e,r){"use strict";function i(t){var e=n.shuffled();return{version:15&e.indexOf(t.substr(0,1)),worker:15&e.indexOf(t.substr(1,1))}}var n=r(6);t.exports=i},function(t,e,r){"use strict";function i(t){var e="",r=Math.floor(.001*(Date.now()-a));return r===l?c++:(c=0,l=r),e+=n(o.lookup,s),e+=n(o.lookup,t),c>0&&(e+=n(o.lookup,c)),e+=n(o.lookup,r)}var n=r(11),o=r(6),a=1459707606518,s=6,c,l;t.exports=i},function(t,e,r){"use strict";function i(t){if(!t||"string"!=typeof t||t.length<6)return!1;for(var e=n.characters(),r=t.length,i=0;i<r;i++)if(-1===e.indexOf(t[i]))return!1;return!0}var n=r(6);t.exports=i},function(t,e,r){"use strict";t.exports=0},function(t,e,r){(function(e){!function e(r,i){t.exports=i()}(this,function(){return function(t){function e(i){if(r[i])return r[i].exports;var n=r[i]={i:i,l:!1,exports:{}};return t[i].call(n.exports,n,n.exports,e),n.l=!0,n.exports}var r={};return e.m=t,e.c=r,e.i=function(t){return t},e.d=function(t,r,i){e.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var r=t&&t.__esModule?function e(){return t.default}:function e(){return t};return e.d(r,"a",r),r},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=1)}([function(t,r,i){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};if("undefined"==typeof PDFJS||!PDFJS.compatibilityChecked){var o="undefined"!=typeof window&&window.Math===Math?window:void 0!==e&&e.Math===Math?e:"undefined"!=typeof self&&self.Math===Math?self:void 0,a="undefined"!=typeof navigator&&navigator.userAgent||"",s=/Android/.test(a),c=/Android\s[0-2][^\d]/.test(a),l=/Android\s[0-4][^\d]/.test(a),h=a.indexOf("Chrom")>=0,u=/Chrome\/(39|40)\./.test(a),f=a.indexOf("CriOS")>=0,d=a.indexOf("Trident")>=0,p=/\b(iPad|iPhone|iPod)(?=;)/.test(a),g=a.indexOf("Opera")>=0,v=/Safari\//.test(a)&&!/(Chrome\/|Android\s)/.test(a),m="object"===("undefined"==typeof window?"undefined":n(window))&&"object"===("undefined"==typeof document?"undefined":n(document));"undefined"==typeof PDFJS&&(o.PDFJS={}),PDFJS.compatibilityChecked=!0,function t(){function e(t,e){return new c(this.slice(t,e))}function r(t,e){arguments.length<2&&(e=0);for(var r=0,i=t.length;r<i;++r,++e)this[e]=255&t[r]}function i(t,e){this.buffer=t,this.byteLength=t.length,this.length=e,s(this.length)}function a(t){return{get:function e(){var r=this.buffer,i=t<<2;return(r[i]|r[i+1]<<8|r[i+2]<<16|r[i+3]<<24)>>>0},set:function e(r){var i=this.buffer,n=t<<2;i[n]=255&r,i[n+1]=r>>8&255,i[n+2]=r>>16&255,i[n+3]=r>>>24&255}}}function s(t){for(;l<t;)Object.defineProperty(i.prototype,l,a(l)),l++}function c(t){var i,o,a;if("number"==typeof t)for(i=[],o=0;o<t;++o)i[o]=0;else if("slice"in t)i=t.slice(0);else for(i=[],o=0,a=t.length;o<a;++o)i[o]=t[o];return i.subarray=e,i.buffer=i,i.byteLength=i.length,i.set=r,"object"===(void 0===t?"undefined":n(t))&&t.buffer&&(i.buffer=t.buffer),i}if("undefined"!=typeof Uint8Array)return void 0===Uint8Array.prototype.subarray&&(Uint8Array.prototype.subarray=function t(e,r){return new Uint8Array(this.slice(e,r))},Float32Array.prototype.subarray=function t(e,r){return new Float32Array(this.slice(e,r))}),void("undefined"==typeof Float64Array&&(o.Float64Array=Float32Array));i.prototype=Object.create(null);var l=0;o.Uint8Array=c,o.Int8Array=c,o.Int32Array=c,o.Uint16Array=c,o.Float32Array=c,o.Float64Array=c,o.Uint32Array=function(){if(3===arguments.length){if(0!==arguments[1])throw new Error("offset !== 0 is not supported");return new i(arguments[0],arguments[2])}return c.apply(this,arguments)}}(),function t(){if(m&&window.CanvasPixelArray){var e=window.CanvasPixelArray.prototype;"buffer"in e||(Object.defineProperty(e,"buffer",{get:function t(){return this},enumerable:!1,configurable:!0}),Object.defineProperty(e,"byteLength",{get:function t(){return this.length},enumerable:!1,configurable:!0}))}}(),function t(){o.URL||(o.URL=o.webkitURL)}(),function t(){if(void 0!==Object.defineProperty){var e=!0;try{m&&Object.defineProperty(new Image,"id",{value:"test"});var r=function t(){};r.prototype={get id(){}},Object.defineProperty(new r,"id",{value:"",configurable:!0,enumerable:!0,writable:!1})}catch(t){e=!1}if(e)return}Object.defineProperty=function t(e,r,i){delete e[r],"get"in i&&e.__defineGetter__(r,i.get),"set"in i&&e.__defineSetter__(r,i.set),"value"in i&&(e.__defineSetter__(r,function t(e){return this.__defineGetter__(r,function t(){return e}),e}),e[r]=i.value)}}(),function t(){if("undefined"!=typeof XMLHttpRequest){var e=XMLHttpRequest.prototype,r=new XMLHttpRequest;if("overrideMimeType"in r||Object.defineProperty(e,"overrideMimeType",{value:function t(e){}}),!("responseType"in r)){if(Object.defineProperty(e,"responseType",{get:function t(){return this._responseType||"text"},set:function t(e){"text"!==e&&"arraybuffer"!==e||(this._responseType=e,"arraybuffer"===e&&"function"==typeof this.overrideMimeType&&this.overrideMimeType("text/plain; charset=x-user-defined"))}}),"undefined"!=typeof VBArray)return void Object.defineProperty(e,"response",{get:function t(){return"arraybuffer"===this.responseType?new Uint8Array(new VBArray(this.responseBody).toArray()):this.responseText}});Object.defineProperty(e,"response",{get:function t(){if("arraybuffer"!==this.responseType)return this.responseText;var e=this.responseText,r,i=e.length,n=new Uint8Array(i);for(r=0;r<i;++r)n[r]=255&e.charCodeAt(r);return n.buffer}})}}}(),function t(){if(!("btoa"in o)){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";o.btoa=function(t){var r="",i,n;for(i=0,n=t.length;i<n;i+=3){var o=255&t.charCodeAt(i),a=255&t.charCodeAt(i+1),s=255&t.charCodeAt(i+2),c=o>>2,l=(3&o)<<4|a>>4,h=i+1<n?(15&a)<<2|s>>6:64,u=i+2<n?63&s:64;r+=e.charAt(c)+e.charAt(l)+e.charAt(h)+e.charAt(u)}return r}}}(),function t(){if(!("atob"in o)){o.atob=function(t){if(t=t.replace(/=+$/,""),t.length%4==1)throw new Error("bad atob input");for(var e=0,r,i,n=0,o="";i=t.charAt(n++);~i&&(r=e%4?64*r+i:i,e++%4)?o+=String.fromCharCode(255&r>>(-2*e&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return o}}}(),function t(){void 0===Function.prototype.bind&&(Function.prototype.bind=function t(e){var r=this,i=Array.prototype.slice.call(arguments,1);return function t(){var n=i.concat(Array.prototype.slice.call(arguments));return r.apply(e,n)}})}(),function t(){if(m){"dataset"in document.createElement("div")||Object.defineProperty(HTMLElement.prototype,"dataset",{get:function t(){if(this._dataset)return this._dataset;for(var e={},r=0,i=this.attributes.length;r<i;r++){var n=this.attributes[r];if("data-"===n.name.substring(0,5)){e[n.name.substring(5).replace(/\-([a-z])/g,function(t,e){return e.toUpperCase()})]=n.value}}return Object.defineProperty(this,"_dataset",{value:e,writable:!1,enumerable:!1}),e},enumerable:!0})}}(),function t(){function e(t,e,r,i){var n=t.className||"",o=n.split(/\s+/g);""===o[0]&&o.shift();var a=o.indexOf(e);return a<0&&r&&o.push(e),a>=0&&i&&o.splice(a,1),t.className=o.join(" "),a>=0}if(m){if(!("classList"in document.createElement("div"))){var r={add:function t(r){e(this.element,r,!0,!1)},contains:function t(r){return e(this.element,r,!1,!1)},remove:function t(r){e(this.element,r,!1,!0)},toggle:function t(r){e(this.element,r,!0,!0)}};Object.defineProperty(HTMLElement.prototype,"classList",{get:function t(){if(this._classList)return this._classList;var e=Object.create(r,{element:{value:this,writable:!1,enumerable:!0}});return Object.defineProperty(this,"_classList",{value:e,writable:!1,enumerable:!1}),e},enumerable:!0})}}}(),function t(){if(!("undefined"==typeof importScripts||"console"in o)){var e={},r={log:function t(){var e=Array.prototype.slice.call(arguments);o.postMessage({targetName:"main",action:"console_log",data:e})},error:function t(){var e=Array.prototype.slice.call(arguments);o.postMessage({targetName:"main",action:"console_error",data:e})},time:function t(r){e[r]=Date.now()},timeEnd:function t(r){var i=e[r];if(!i)throw new Error("Unknown timer name "+r);this.log("Timer:",r,Date.now()-i)}};o.console=r}}(),function t(){if(m)"console"in window?"bind"in console.log||(console.log=function(t){return function(e){return t(e)}}(console.log),console.error=function(t){return function(e){return t(e)}}(console.error),console.warn=function(t){return function(e){return t(e)}}(console.warn)):window.console={log:function t(){},error:function t(){},warn:function t(){}}}(),function t(){function e(t){r(t.target)&&t.stopPropagation()}function r(t){return t.disabled||t.parentNode&&r(t.parentNode)}g&&document.addEventListener("click",e,!0)}(),function t(){(d||f)&&(PDFJS.disableCreateObjectURL=!0)}(),function t(){"undefined"!=typeof navigator&&("language"in navigator||(PDFJS.locale=navigator.userLanguage||"en-US"))}(),function t(){(v||c||u||p)&&(PDFJS.disableRange=!0,PDFJS.disableStream=!0)}(),function t(){m&&(history.pushState&&!c||(PDFJS.disableHistory=!0))}(),function t(){if(m)if(window.CanvasPixelArray)"function"!=typeof window.CanvasPixelArray.prototype.set&&(window.CanvasPixelArray.prototype.set=function(t){for(var e=0,r=this.length;e<r;e++)this[e]=t[e]});else{var e=!1,r;if(h?(r=a.match(/Chrom(e|ium)\/([0-9]+)\./),e=r&&parseInt(r[2])<21):s?e=l:v&&(r=a.match(/Version\/([0-9]+)\.([0-9]+)\.([0-9]+) Safari\//),e=r&&parseInt(r[1])<6),e){var i=window.CanvasRenderingContext2D.prototype,n=i.createImageData;i.createImageData=function(t,e){var r=n.call(this,t,e);return r.data.set=function(t){for(var e=0,r=this.length;e<r;e++)this[e]=t[e]},r},i=null}}}(),function t(){function e(){window.requestAnimationFrame=function(t){return window.setTimeout(t,20)},window.cancelAnimationFrame=function(t){window.clearTimeout(t)}}if(m)p?e():"requestAnimationFrame"in window||(window.requestAnimationFrame=window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame,window.requestAnimationFrame||e())}(),function t(){(p||s)&&(PDFJS.maxCanvasPixels=5242880)}(),function t(){m&&d&&window.parent!==window&&(PDFJS.disableFullscreen=!0)}(),function t(){m&&("currentScript"in document||Object.defineProperty(document,"currentScript",{get:function t(){var e=document.getElementsByTagName("script");return e[e.length-1]},enumerable:!0,configurable:!0}))}(),function t(){if(m){var e=document.createElement("input");try{e.type="number"}catch(t){var r=e.constructor.prototype,i=Object.getOwnPropertyDescriptor(r,"type");Object.defineProperty(r,"type",{get:function t(){return i.get.call(this)},set:function t(e){i.set.call(this,"number"===e?"text":e)},enumerable:!0,configurable:!0})}}}(),function t(){if(m&&document.attachEvent){var e=document.constructor.prototype,r=Object.getOwnPropertyDescriptor(e,"readyState");Object.defineProperty(e,"readyState",{get:function t(){var e=r.get.call(this);return"interactive"===e?"loading":e},set:function t(e){r.set.call(this,e)},enumerable:!0,configurable:!0})}}(),function t(){m&&void 0===Element.prototype.remove&&(Element.prototype.remove=function(){this.parentNode&&this.parentNode.removeChild(this)})}(),function t(){Number.isNaN||(Number.isNaN=function(t){return"number"==typeof t&&isNaN(t)})}(),function t(){Number.isInteger||(Number.isInteger=function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t})}(),function t(){if(o.Promise)return"function"!=typeof o.Promise.all&&(o.Promise.all=function(t){var e=0,r=[],i,n,a=new o.Promise(function(t,e){i=t,n=e});return t.forEach(function(t,o){e++,t.then(function(t){r[o]=t,0===--e&&i(r)},n)}),0===e&&i(r),a}),"function"!=typeof o.Promise.resolve&&(o.Promise.resolve=function(t){return new o.Promise(function(e){e(t)})}),"function"!=typeof o.Promise.reject&&(o.Promise.reject=function(t){return new o.Promise(function(e,r){r(t)})}),void("function"!=typeof o.Promise.prototype.catch&&(o.Promise.prototype.catch=function(t){return o.Promise.prototype.then(void 0,t)}));var e=0,r=1,i=2,n=500,a={handlers:[],running:!1,unhandledRejections:[],pendingRejectionCheck:!1,scheduleHandlers:function t(e){0!==e._status&&(this.handlers=this.handlers.concat(e._handlers),e._handlers=[],this.running||(this.running=!0,setTimeout(this.runHandlers.bind(this),0)))},runHandlers:function t(){for(var e=1,r=Date.now()+1;this.handlers.length>0;){var n=this.handlers.shift(),o=n.thisPromise._status,a=n.thisPromise._value;try{1===o?"function"==typeof n.onResolve&&(a=n.onResolve(a)):"function"==typeof n.onReject&&(a=n.onReject(a),o=1,n.thisPromise._unhandledRejection&&this.removeUnhandeledRejection(n.thisPromise))}catch(t){o=i,a=t}if(n.nextPromise._updateStatus(o,a),Date.now()>=r)break}if(this.handlers.length>0)return void setTimeout(this.runHandlers.bind(this),0);this.running=!1},addUnhandledRejection:function t(e){this.unhandledRejections.push({promise:e,time:Date.now()}),this.scheduleRejectionCheck()},removeUnhandeledRejection:function t(e){e._unhandledRejection=!1;for(var r=0;r<this.unhandledRejections.length;r++)this.unhandledRejections[r].promise===e&&(this.unhandledRejections.splice(r),r--)},scheduleRejectionCheck:function t(){var e=this;this.pendingRejectionCheck||(this.pendingRejectionCheck=!0,setTimeout(function(){e.pendingRejectionCheck=!1;for(var t=Date.now(),r=0;r<e.unhandledRejections.length;r++)if(t-e.unhandledRejections[r].time>500){var i=e.unhandledRejections[r].promise._value,n="Unhandled rejection: "+i;i.stack&&(n+="\n"+i.stack);try{throw new Error(n)}catch(t){console.warn(n)}e.unhandledRejections.splice(r),r--}e.unhandledRejections.length&&e.scheduleRejectionCheck()},500))}},s=function t(e){this._status=0,this._handlers=[];try{e.call(this,this._resolve.bind(this),this._reject.bind(this))}catch(t){this._reject(t)}};s.all=function t(e){function r(t){a._status!==i&&(l=[],o(t))}var n,o,a=new s(function(t,e){n=t,o=e}),c=e.length,l=[];if(0===c)return n(l),a;for(var h=0,u=e.length;h<u;++h){var f=e[h],d=function(t){return function(e){a._status!==i&&(l[t]=e,0===--c&&n(l))}}(h);s.isPromise(f)?f.then(d,r):d(f)}return a},s.isPromise=function t(e){return e&&"function"==typeof e.then},s.resolve=function t(e){return new s(function(t){t(e)})},s.reject=function t(e){return new s(function(t,r){r(e)})},s.prototype={_status:null,_value:null,_handlers:null,_unhandledRejection:null,_updateStatus:function t(e,r){if(1!==this._status&&this._status!==i){if(1===e&&s.isPromise(r))return void r.then(this._updateStatus.bind(this,1),this._updateStatus.bind(this,i));this._status=e,this._value=r,e===i&&0===this._handlers.length&&(this._unhandledRejection=!0,a.addUnhandledRejection(this)),a.scheduleHandlers(this)}},_resolve:function t(e){this._updateStatus(1,e)},_reject:function t(e){this._updateStatus(i,e)},then:function t(e,r){var i=new s(function(t,e){this.resolve=t,this.reject=e});return this._handlers.push({thisPromise:this,onResolve:e,onReject:r,nextPromise:i}),a.scheduleHandlers(this),i},catch:function t(e){return this.then(void 0,e)}},o.Promise=s}(),function t(){function e(){this.id="$weakmap"+r++}if(!o.WeakMap){var r=0;e.prototype={has:function t(e){return("object"===(void 0===e?"undefined":n(e))||"function"==typeof e)&&null!==e&&!!Object.getOwnPropertyDescriptor(e,this.id)},get:function t(e){return this.has(e)?e[this.id]:void 0},set:function t(e,r){Object.defineProperty(e,this.id,{value:r,enumerable:!1,configurable:!0})},delete:function t(e){delete e[this.id]}},o.WeakMap=e}}(),function t(){function e(t){return void 0!==d[t]}function r(){l.call(this),this._isInvalid=!0}function i(t){return""===t&&r.call(this),t.toLowerCase()}function a(t){var e=t.charCodeAt(0);return e>32&&e<127&&-1===[34,35,60,62,63,96].indexOf(e)?t:encodeURIComponent(t)}function s(t){var e=t.charCodeAt(0);return e>32&&e<127&&-1===[34,35,60,62,96].indexOf(e)?t:encodeURIComponent(t)}function c(t,n,o){function c(t){y.push(t)}var l=n||"scheme start",h=0,u="",f=!1,b=!1,y=[];t:for(;(t[h-1]!==g||0===h)&&!this._isInvalid;){var _=t[h];switch(l){case"scheme start":if(!_||!v.test(_)){if(n){c("Invalid scheme.");break t}u="",l="no scheme";continue}u+=_.toLowerCase(),l="scheme";break;case"scheme":if(_&&m.test(_))u+=_.toLowerCase();else{if(":"!==_){if(n){if(_===g)break t;c("Code point not allowed in scheme: "+_);break t}u="",h=0,l="no scheme";continue}if(this._scheme=u,u="",n)break t;e(this._scheme)&&(this._isRelative=!0),l="file"===this._scheme?"relative":this._isRelative&&o&&o._scheme===this._scheme?"relative or authority":this._isRelative?"authority first slash":"scheme data"}break;case"scheme data":"?"===_?(this._query="?",l="query"):"#"===_?(this._fragment="#",l="fragment"):_!==g&&"\t"!==_&&"\n"!==_&&"\r"!==_&&(this._schemeData+=a(_));break;case"no scheme":if(o&&e(o._scheme)){l="relative";continue}c("Missing scheme."),r.call(this);break;case"relative or authority":if("/"!==_||"/"!==t[h+1]){c("Expected /, got: "+_),l="relative";continue}l="authority ignore slashes";break;case"relative":if(this._isRelative=!0,"file"!==this._scheme&&(this._scheme=o._scheme),_===g){this._host=o._host,this._port=o._port,this._path=o._path.slice(),this._query=o._query,this._username=o._username,this._password=o._password;break t}if("/"===_||"\\"===_)"\\"===_&&c("\\ is an invalid code point."),l="relative slash";else if("?"===_)this._host=o._host,this._port=o._port,this._path=o._path.slice(),this._query="?",this._username=o._username,this._password=o._password,l="query";else{if("#"!==_){var w=t[h+1],S=t[h+2];("file"!==this._scheme||!v.test(_)||":"!==w&&"|"!==w||S!==g&&"/"!==S&&"\\"!==S&&"?"!==S&&"#"!==S)&&(this._host=o._host,this._port=o._port,this._username=o._username,this._password=o._password,this._path=o._path.slice(),this._path.pop()),l="relative path";continue}this._host=o._host,this._port=o._port,this._path=o._path.slice(),this._query=o._query,this._fragment="#",this._username=o._username,this._password=o._password,l="fragment"}break;case"relative slash":if("/"!==_&&"\\"!==_){"file"!==this._scheme&&(this._host=o._host,this._port=o._port,this._username=o._username,this._password=o._password),l="relative path";continue}"\\"===_&&c("\\ is an invalid code point."),l="file"===this._scheme?"file host":"authority ignore slashes";break;case"authority first slash":if("/"!==_){c("Expected '/', got: "+_),l="authority ignore slashes";continue}l="authority second slash";break;case"authority second slash":if(l="authority ignore slashes","/"!==_){c("Expected '/', got: "+_);continue}break;case"authority ignore slashes":if("/"!==_&&"\\"!==_){l="authority";continue}c("Expected authority, got: "+_);break;case"authority":if("@"===_){f&&(c("@ already seen."),u+="%40"),f=!0;for(var x=0;x<u.length;x++){var C=u[x];if("\t"!==C&&"\n"!==C&&"\r"!==C)if(":"!==C||null!==this._password){var A=a(C);null!==this._password?this._password+=A:this._username+=A}else this._password="";else c("Invalid whitespace in authority.")}u=""}else{if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_){h-=u.length,u="",l="host";continue}u+=_}break;case"file host":if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_){2!==u.length||!v.test(u[0])||":"!==u[1]&&"|"!==u[1]?0===u.length?l="relative path start":(this._host=i.call(this,u),u="",l="relative path start"):l="relative path";continue}"\t"===_||"\n"===_||"\r"===_?c("Invalid whitespace in file host."):u+=_;break;case"host":case"hostname":if(":"!==_||b){if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_){if(this._host=i.call(this,u),u="",l="relative path start",n)break t;continue}"\t"!==_&&"\n"!==_&&"\r"!==_?("["===_?b=!0:"]"===_&&(b=!1),u+=_):c("Invalid code point in host/hostname: "+_)}else if(this._host=i.call(this,u),u="",l="port","hostname"===n)break t;break;case"port":if(/[0-9]/.test(_))u+=_;else{if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_||n){if(""!==u){var T=parseInt(u,10);T!==d[this._scheme]&&(this._port=T+""),u=""}if(n)break t;l="relative path start";continue}"\t"===_||"\n"===_||"\r"===_?c("Invalid code point in port: "+_):r.call(this)}break;case"relative path start":if("\\"===_&&c("'\\' not allowed in path."),l="relative path","/"!==_&&"\\"!==_)continue;break;case"relative path":if(_!==g&&"/"!==_&&"\\"!==_&&(n||"?"!==_&&"#"!==_))"\t"!==_&&"\n"!==_&&"\r"!==_&&(u+=a(_));else{"\\"===_&&c("\\ not allowed in relative path.");var k;(k=p[u.toLowerCase()])&&(u=k),".."===u?(this._path.pop(),"/"!==_&&"\\"!==_&&this._path.push("")):"."===u&&"/"!==_&&"\\"!==_?this._path.push(""):"."!==u&&("file"===this._scheme&&0===this._path.length&&2===u.length&&v.test(u[0])&&"|"===u[1]&&(u=u[0]+":"),this._path.push(u)),u="","?"===_?(this._query="?",l="query"):"#"===_&&(this._fragment="#",l="fragment")}break;case"query":n||"#"!==_?_!==g&&"\t"!==_&&"\n"!==_&&"\r"!==_&&(this._query+=s(_)):(this._fragment="#",l="fragment");break;case"fragment":_!==g&&"\t"!==_&&"\n"!==_&&"\r"!==_&&(this._fragment+=_)}h++}}function l(){this._scheme="",this._schemeData="",this._username="",this._password=null,this._host="",this._port="",this._path=[],this._query="",this._fragment="",this._isInvalid=!1,this._isRelative=!1}function h(t,e){void 0===e||e instanceof h||(e=new h(String(e))),this._url=t,l.call(this);var r=t.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g,"");c.call(this,r,null,e)}var u=!1;try{if("function"==typeof URL&&"object"===n(URL.prototype)&&"origin"in URL.prototype){var f=new URL("b","http://a");f.pathname="c%20d",u="http://a/c%20d"===f.href}}catch(t){}if(!u){var d=Object.create(null);d.ftp=21,d.file=0,d.gopher=70,d.http=80,d.https=443,d.ws=80,d.wss=443;var p=Object.create(null);p["%2e"]=".",p[".%2e"]="..",p["%2e."]="..",p["%2e%2e"]="..";var g,v=/[a-zA-Z]/,m=/[a-zA-Z0-9\+\-\.]/;h.prototype={toString:function t(){return this.href},get href(){if(this._isInvalid)return this._url;var t="";return""===this._username&&null===this._password||(t=this._username+(null!==this._password?":"+this._password:"")+"@"),this.protocol+(this._isRelative?"//"+t+this.host:"")+this.pathname+this._query+this._fragment},set href(t){l.call(this),c.call(this,t)},get protocol(){return this._scheme+":"},set protocol(t){this._isInvalid||c.call(this,t+":","scheme start")},get host(){return this._isInvalid?"":this._port?this._host+":"+this._port:this._host},set host(t){!this._isInvalid&&this._isRelative&&c.call(this,t,"host")},get hostname(){return this._host},set hostname(t){!this._isInvalid&&this._isRelative&&c.call(this,t,"hostname")},get port(){return this._port},set port(t){!this._isInvalid&&this._isRelative&&c.call(this,t,"port")},get pathname(){return this._isInvalid?"":this._isRelative?"/"+this._path.join("/"):this._schemeData},set pathname(t){!this._isInvalid&&this._isRelative&&(this._path=[],c.call(this,t,"relative path start"))},get search(){return this._isInvalid||!this._query||"?"===this._query?"":this._query},set search(t){!this._isInvalid&&this._isRelative&&(this._query="?","?"===t[0]&&(t=t.slice(1)),c.call(this,t,"query"))},get hash(){return this._isInvalid||!this._fragment||"#"===this._fragment?"":this._fragment},set hash(t){this._isInvalid||(this._fragment="#","#"===t[0]&&(t=t.slice(1)),c.call(this,t,"fragment"))},get origin(){var t;if(this._isInvalid||!this._scheme)return"";switch(this._scheme){case"data":case"file":case"javascript":case"mailto":return"null";case"blob":try{return new h(this._schemeData).origin||"null"}catch(t){}return"null"}return t=this.host,t?this._scheme+"://"+t:""}};var b=o.URL;b&&(h.createObjectURL=function(t){return b.createObjectURL.apply(b,arguments)},h.revokeObjectURL=function(t){b.revokeObjectURL(t)}),o.URL=h}}()}},function(t,e,r){"use strict";r(0)}])})}).call(e,r(0))},function(t,e,r){!function e(r,i){t.exports=i()}(this,function(){return function(t){function e(i){if(r[i])return r[i].exports;var n=r[i]={i:i,l:!1,exports:{}};return t[i].call(n.exports,n,n.exports,e),n.l=!0,n.exports}var r={};return e.m=t,e.c=r,e.i=function(t){return t},e.d=function(t,r,i){e.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var r=t&&t.__esModule?function e(){return t.default}:function e(){return t};return e.d(r,"a",r),r},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=14)}([function(t,e,i){"use strict";var n;n="undefined"!=typeof window&&window["pdfjs-dist/build/pdf"]?window["pdfjs-dist/build/pdf"]:r(12),t.exports=n},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){return e?t.replace(/\{\{\s*(\w+)\s*\}\}/g,function(t,r){return r in e?e[r]:"{{"+r+"}}"}):t}function o(t){var e=window.devicePixelRatio||1,r=t.webkitBackingStorePixelRatio||t.mozBackingStorePixelRatio||t.msBackingStorePixelRatio||t.oBackingStorePixelRatio||t.backingStorePixelRatio||1,i=e/r;return{sx:i,sy:i,scaled:1!==i}}function a(t,e){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=t.offsetParent;if(!i)return void console.error("offsetParent is not set -- cannot scroll");for(var n=t.offsetTop+t.clientTop,o=t.offsetLeft+t.clientLeft;i.clientHeight===i.scrollHeight||r&&"hidden"===getComputedStyle(i).overflow;)if(i.dataset._scaleY&&(n/=i.dataset._scaleY,o/=i.dataset._scaleX),n+=i.offsetTop,o+=i.offsetLeft,!(i=i.offsetParent))return;e&&(void 0!==e.top&&(n+=e.top),void 0!==e.left&&(o+=e.left,i.scrollLeft=o)),i.scrollTop=n}function s(t,e){var r=function r(o){n||(n=window.requestAnimationFrame(function r(){n=null;var o=t.scrollTop,a=i.lastY;o!==a&&(i.down=o>a),i.lastY=o,e(i)}))},i={down:!0,lastY:t.scrollTop,_eventHandler:r},n=null;return t.addEventListener("scroll",r,!0),i}function c(t){for(var e=t.split("&"),r=Object.create(null),i=0,n=e.length;i<n;++i){var o=e[i].split("="),a=o[0].toLowerCase(),s=o.length>1?o[1]:null;r[decodeURIComponent(a)]=decodeURIComponent(s)}return r}function l(t,e){var r=0,i=t.length-1;if(0===t.length||!e(t[i]))return t.length;if(e(t[r]))return r;for(;r<i;){var n=r+i>>1;e(t[n])?i=n:r=n+1}return r}function h(t){if(Math.floor(t)===t)return[t,1];var e=1/t,r=8;if(e>8)return[1,8];if(Math.floor(e)===e)return[1,e];for(var i=t>1?e:t,n=0,o=1,a=1,s=1;;){var c=n+a,l=o+s;if(l>8)break;i<=c/l?(a=c,s=l):(n=c,o=l)}var h=void 0;return h=i-n/o<a/s-i?i===t?[n,o]:[o,n]:i===t?[a,s]:[s,a]}function u(t,e){var r=t%e;return 0===r?t:Math.round(t-r+e)}function f(t,e){function r(t){var e=t.div;return e.offsetTop+e.clientTop+e.clientHeight>n}for(var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=t.scrollTop,o=n+t.clientHeight,a=t.scrollLeft,s=a+t.clientWidth,c=[],h=void 0,u=void 0,f=void 0,d=void 0,p=void 0,g=void 0,v=void 0,m=void 0,b=0===e.length?0:l(e,r),y=b,_=e.length;y<_&&(h=e[y],u=h.div,f=u.offsetTop+u.clientTop,d=u.clientHeight,!(f>o));y++)v=u.offsetLeft+u.clientLeft,m=u.clientWidth,v+m<a||v>s||(p=Math.max(0,n-f)+Math.max(0,f+d-o),g=100*(d-p)/d|0,c.push({id:h.id,x:v,y:f,view:h,percent:g}));var w=c[0],S=c[c.length-1];return i&&c.sort(function(t,e){var r=t.percent-e.percent;return Math.abs(r)>.001?-r:t.id-e.id}),{first:w,last:S,views:c}}function d(t){t.preventDefault()}function p(t){for(var e=0,r=t.length;e<r&&""===t[e].trim();)e++;return"data:"===t.substr(e,5).toLowerCase()}function g(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"document.pdf";if(p(t))return console.warn('getPDFFileNameFromURL: ignoring "data:" URL for performance reasons.'),e;var r=/^(?:(?:[^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/,i=/[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i,n=r.exec(t),o=i.exec(n[1])||i.exec(n[2])||i.exec(n[3]);if(o&&(o=o[0],-1!==o.indexOf("%")))try{o=i.exec(decodeURIComponent(o))[0]}catch(t){}return o||e}function v(t){var e=Math.sqrt(t.deltaX*t.deltaX+t.deltaY*t.deltaY),r=Math.atan2(t.deltaY,t.deltaX);-.25*Math.PI<r&&r<.75*Math.PI&&(e=-e);var i=0,n=1,o=30,a=30;return 0===t.deltaMode?e/=900:1===t.deltaMode&&(e/=30),e}function m(t){var e=Object.create(null);for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e}function b(t,e,r){return Math.min(Math.max(t,e),r)}Object.defineProperty(e,"__esModule",{value:!0}),e.localized=e.animationStarted=e.normalizeWheelEventDelta=e.binarySearchFirstItem=e.watchScroll=e.scrollIntoView=e.getOutputScale=e.approximateFraction=e.roundToDivide=e.getVisibleElements=e.parseQueryString=e.noContextMenuHandler=e.getPDFFileNameFromURL=e.ProgressBar=e.EventBus=e.NullL10n=e.mozL10n=e.RendererType=e.cloneObj=e.VERTICAL_PADDING=e.SCROLLBAR_PADDING=e.MAX_AUTO_SCALE=e.UNKNOWN_SCALE=e.MAX_SCALE=e.MIN_SCALE=e.DEFAULT_SCALE=e.DEFAULT_SCALE_VALUE=e.CSS_UNITS=void 0;var y=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),_=r(0),w=96/72,S="auto",x=1,C=.25,A=10,T=0,k=1.25,P=40,E=5,O={CANVAS:"canvas",SVG:"svg"},R={get:function t(e,r,i){return Promise.resolve(n(i,r))},translate:function t(e){return Promise.resolve()}};_.PDFJS.disableFullscreen=void 0!==_.PDFJS.disableFullscreen&&_.PDFJS.disableFullscreen,_.PDFJS.useOnlyCssZoom=void 0!==_.PDFJS.useOnlyCssZoom&&_.PDFJS.useOnlyCssZoom,_.PDFJS.maxCanvasPixels=void 0===_.PDFJS.maxCanvasPixels?16777216:_.PDFJS.maxCanvasPixels,_.PDFJS.disableHistory=void 0!==_.PDFJS.disableHistory&&_.PDFJS.disableHistory,_.PDFJS.disableTextLayer=void 0!==_.PDFJS.disableTextLayer&&_.PDFJS.disableTextLayer,_.PDFJS.ignoreCurrentPositionOnZoom=void 0!==_.PDFJS.ignoreCurrentPositionOnZoom&&_.PDFJS.ignoreCurrentPositionOnZoom,_.PDFJS.locale=void 0===_.PDFJS.locale&&"undefined"!=typeof navigator?navigator.language:_.PDFJS.locale;var L=new Promise(function(t){window.requestAnimationFrame(t)}),D=void 0,I=Promise.resolve(),j=function(){function t(){i(this,t),this._listeners=Object.create(null)}return y(t,[{key:"on",value:function t(e,r){var i=this._listeners[e];i||(i=[],this._listeners[e]=i),i.push(r)}},{key:"off",value:function t(e,r){var i=this._listeners[e],n=void 0;!i||(n=i.indexOf(r))<0||i.splice(n,1)}},{key:"dispatch",value:function t(e){var r=this._listeners[e];if(r&&0!==r.length){var i=Array.prototype.slice.call(arguments,1);r.slice(0).forEach(function(t){t.apply(null,i)})}}}]),t}(),M=function(){function t(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=r.height,o=r.width,a=r.units;i(this,t),this.visible=!0,this.div=document.querySelector(e+" .progress"),this.bar=this.div.parentNode,this.height=n||100,this.width=o||100,this.units=a||"%",this.div.style.height=this.height+this.units,this.percent=0}return y(t,[{key:"_updateBar",value:function t(){if(this._indeterminate)return this.div.classList.add("indeterminate"),void(this.div.style.width=this.width+this.units);this.div.classList.remove("indeterminate");var e=this.width*this._percent/100;this.div.style.width=e+this.units}},{key:"setWidth",value:function t(e){if(e){var r=e.parentNode,i=r.offsetWidth-e.offsetWidth;i>0&&this.bar.setAttribute("style","width: calc(100% - "+i+"px);")}}},{key:"hide",value:function t(){this.visible&&(this.visible=!1,this.bar.classList.add("hidden"),document.body.classList.remove("loadingInProgress"))}},{key:"show",value:function t(){this.visible||(this.visible=!0,document.body.classList.add("loadingInProgress"),this.bar.classList.remove("hidden"))}},{key:"percent",get:function t(){return this._percent},set:function t(e){this._indeterminate=isNaN(e),this._percent=b(e,0,100),this._updateBar()}}]),t}();e.CSS_UNITS=96/72,e.DEFAULT_SCALE_VALUE="auto",e.DEFAULT_SCALE=1,e.MIN_SCALE=.25,e.MAX_SCALE=10,e.UNKNOWN_SCALE=0,e.MAX_AUTO_SCALE=1.25,e.SCROLLBAR_PADDING=40,e.VERTICAL_PADDING=5,e.cloneObj=m,e.RendererType=O,e.mozL10n=void 0,e.NullL10n=R,e.EventBus=j,e.ProgressBar=M,e.getPDFFileNameFromURL=g,e.noContextMenuHandler=d,e.parseQueryString=c,e.getVisibleElements=f,e.roundToDivide=u,e.approximateFraction=h,e.getOutputScale=o,e.scrollIntoView=a,e.watchScroll=s,e.binarySearchFirstItem=l,e.normalizeWheelEventDelta=v,e.animationStarted=L,e.localized=I},function(t,e,r){"use strict";function i(t){t.on("documentload",function(){var t=document.createEvent("CustomEvent");t.initCustomEvent("documentload",!0,!0,{}),window.dispatchEvent(t)}),t.on("pagerendered",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("pagerendered",!0,!0,{pageNumber:t.pageNumber,cssTransform:t.cssTransform}),t.source.div.dispatchEvent(e)}),t.on("textlayerrendered",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("textlayerrendered",!0,!0,{pageNumber:t.pageNumber}),t.source.textLayerDiv.dispatchEvent(e)}),t.on("pagechange",function(t){var e=document.createEvent("UIEvents");e.initUIEvent("pagechange",!0,!0,window,0),e.pageNumber=t.pageNumber,t.source.container.dispatchEvent(e)}),t.on("pagesinit",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("pagesinit",!0,!0,null),t.source.container.dispatchEvent(e)}),t.on("pagesloaded",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("pagesloaded",!0,!0,{pagesCount:t.pagesCount}),t.source.container.dispatchEvent(e)}),t.on("scalechange",function(t){var e=document.createEvent("UIEvents");e.initUIEvent("scalechange",!0,!0,window,0),e.scale=t.scale,e.presetValue=t.presetValue,t.source.container.dispatchEvent(e)}),t.on("updateviewarea",function(t){var e=document.createEvent("UIEvents");e.initUIEvent("updateviewarea",!0,!0,window,0),e.location=t.location,t.source.container.dispatchEvent(e)}),t.on("find",function(t){if(t.source!==window){var e=document.createEvent("CustomEvent");e.initCustomEvent("find"+t.type,!0,!0,{query:t.query,phraseSearch:t.phraseSearch,caseSensitive:t.caseSensitive,highlightAll:t.highlightAll,findPrevious:t.findPrevious}),window.dispatchEvent(e)}}),t.on("attachmentsloaded",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("attachmentsloaded",!0,!0,{attachmentsCount:t.attachmentsCount}),t.source.container.dispatchEvent(e)}),t.on("sidebarviewchanged",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("sidebarviewchanged",!0,!0,{view:t.view}),t.source.outerContainer.dispatchEvent(e)}),t.on("pagemode",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("pagemode",!0,!0,{mode:t.mode}),t.source.pdfViewer.container.dispatchEvent(e)}),t.on("namedaction",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("namedaction",!0,!0,{action:t.action}),t.source.pdfViewer.container.dispatchEvent(e)}),t.on("presentationmodechanged",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("presentationmodechanged",!0,!0,{active:t.active,switchInProgress:t.switchInProgress}),window.dispatchEvent(e)}),t.on("outlineloaded",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("outlineloaded",!0,!0,{outlineCount:t.outlineCount}),t.source.container.dispatchEvent(e)})}function n(){return a||(a=new o.EventBus,i(a),a)}Object.defineProperty(e,"__esModule",{value:!0}),e.getGlobalEventBus=e.attachDOMEventsToEventBus=void 0;var o=r(1),a=null;e.attachDOMEventsToEventBus=i,e.getGlobalEventBus=n},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t){if(!(t instanceof Array))return!1;var e=t.length,r=!0;if(e<2)return!1;var i=t[0];if(!("object"===(void 0===i?"undefined":o(i))&&"number"==typeof i.num&&(0|i.num)===i.num&&"number"==typeof i.gen&&(0|i.gen)===i.gen||"number"==typeof i&&(0|i)===i&&i>=0))return!1;var n=t[1];if("object"!==(void 0===n?"undefined":o(n))||"string"!=typeof n.name)return!1;switch(n.name){case"XYZ":if(5!==e)return!1;break;case"Fit":case"FitB":return 2===e;case"FitH":case"FitBH":case"FitV":case"FitBV":if(3!==e)return!1;break;case"FitR":if(6!==e)return!1;r=!1;break;default:return!1}for(var a=2;a<e;a++){var s=t[a];if(!("number"==typeof s||r&&null===s))return!1}return!0}Object.defineProperty(e,"__esModule",{value:!0}),e.SimpleLinkService=e.PDFLinkService=void 0;var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},a=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),s=r(2),c=r(1),l=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=e.eventBus;i(this,t),this.eventBus=r||(0,s.getGlobalEventBus)(),this.baseUrl=null,this.pdfDocument=null,this.pdfViewer=null,this.pdfHistory=null,this._pagesRefCache=null}return a(t,[{key:"setDocument",value:function t(e,r){this.baseUrl=r,this.pdfDocument=e,this._pagesRefCache=Object.create(null)}},{key:"setViewer",value:function t(e){this.pdfViewer=e}},{key:"setHistory",value:function t(e){this.pdfHistory=e}},{key:"navigateTo",value:function t(e){var r=this,i=function t(i){var n=i.namedDest,o=i.explicitDest,a=o[0],s=void 0;if(a instanceof Object){if(null===(s=r._cachedPageNumber(a)))return void r.pdfDocument.getPageIndex(a).then(function(e){r.cachePageRef(e+1,a),t({namedDest:n,explicitDest:o})}).catch(function(){console.error('PDFLinkService.navigateTo: "'+a+'" is not a valid page reference, for dest="'+e+'".')})}else{if((0|a)!==a)return void console.error('PDFLinkService.navigateTo: "'+a+'" is not a valid destination reference, for dest="'+e+'".');s=a+1}if(!s||s<1||s>r.pagesCount)return void console.error('PDFLinkService.navigateTo: "'+s+'" is not a valid page number, for dest="'+e+'".');r.pdfViewer.scrollPageIntoView({pageNumber:s,destArray:o}),r.pdfHistory&&r.pdfHistory.push({dest:o,hash:n,page:s})};new Promise(function(t,i){if("string"==typeof e)return void r.pdfDocument.getDestination(e).then(function(r){t({namedDest:e,explicitDest:r})});t({namedDest:"",explicitDest:e})}).then(function(t){if(!(t.explicitDest instanceof Array))return void console.error('PDFLinkService.navigateTo: "'+t.explicitDest+'" is not a valid destination array, for dest="'+e+'".');i(t)})}},{key:"getDestinationHash",value:function t(e){if("string"==typeof e)return this.getAnchorUrl("#"+escape(e));if(e instanceof Array){var r=JSON.stringify(e);return this.getAnchorUrl("#"+escape(r))}return this.getAnchorUrl("")}},{key:"getAnchorUrl",value:function t(e){return(this.baseUrl||"")+e}},{key:"setHash",value:function t(e){var r=void 0,i=void 0;if(e.indexOf("=")>=0){var o=(0,c.parseQueryString)(e);if("search"in o&&this.eventBus.dispatch("findfromurlhash",{source:this,query:o.search.replace(/"/g,""),phraseSearch:"true"===o.phrase}),"nameddest"in o)return this.pdfHistory&&this.pdfHistory.updateNextHashParam(o.nameddest),void this.navigateTo(o.nameddest);if("page"in o&&(r=0|o.page||1),"zoom"in o){var a=o.zoom.split(","),s=a[0],l=parseFloat(s);-1===s.indexOf("Fit")?i=[null,{name:"XYZ"},a.length>1?0|a[1]:null,a.length>2?0|a[2]:null,l?l/100:s]:"Fit"===s||"FitB"===s?i=[null,{name:s}]:"FitH"===s||"FitBH"===s||"FitV"===s||"FitBV"===s?i=[null,{name:s},a.length>1?0|a[1]:null]:"FitR"===s?5!==a.length?console.error('PDFLinkService.setHash: Not enough parameters for "FitR".'):i=[null,{name:s},0|a[1],0|a[2],0|a[3],0|a[4]]:console.error('PDFLinkService.setHash: "'+s+'" is not a valid zoom value.')}i?this.pdfViewer.scrollPageIntoView({pageNumber:r||this.page,destArray:i,allowNegativeOffset:!0}):r&&(this.page=r),"pagemode"in o&&this.eventBus.dispatch("pagemode",{source:this,mode:o.pagemode})}else{/^\d+$/.test(e)&&e<=this.pagesCount&&(console.warn('PDFLinkService_setHash: specifying a page number directly after the hash symbol (#) is deprecated, please use the "#page='+e+'" form instead.'),this.page=0|e),i=unescape(e);try{i=JSON.parse(i),i instanceof Array||(i=i.toString())}catch(t){}if("string"==typeof i||n(i))return this.pdfHistory&&this.pdfHistory.updateNextHashParam(i),void this.navigateTo(i);console.error('PDFLinkService.setHash: "'+unescape(e)+'" is not a valid destination.')}}},{key:"executeNamedAction",value:function t(e){switch(e){case"GoBack":this.pdfHistory&&this.pdfHistory.back();break;case"GoForward":this.pdfHistory&&this.pdfHistory.forward();break;case"NextPage":this.page<this.pagesCount&&this.page++;break;case"PrevPage":this.page>1&&this.page--;break;case"LastPage":this.page=this.pagesCount;break;case"FirstPage":this.page=1}this.eventBus.dispatch("namedaction",{source:this,action:e})}},{key:"onFileAttachmentAnnotation",value:function t(e){var r=e.id,i=e.filename,n=e.content;this.eventBus.dispatch("fileattachmentannotation",{source:this,id:r,filename:i,content:n})}},{key:"cachePageRef",value:function t(e,r){var i=r.num+" "+r.gen+" R";this._pagesRefCache[i]=e}},{key:"_cachedPageNumber",value:function t(e){var r=e.num+" "+e.gen+" R";return this._pagesRefCache&&this._pagesRefCache[r]||null}},{key:"pagesCount",get:function t(){return this.pdfDocument?this.pdfDocument.numPages:0}},{key:"page",get:function t(){return this.pdfViewer.currentPageNumber},set:function t(e){this.pdfViewer.currentPageNumber=e}}]),t}(),h=function(){function t(){i(this,t)}return a(t,[{key:"navigateTo",value:function t(e){}},{key:"getDestinationHash",value:function t(e){return"#"}},{key:"getAnchorUrl",value:function t(e){return"#"}},{key:"setHash",value:function t(e){}},{key:"executeNamedAction",value:function t(e){}},{key:"onFileAttachmentAnnotation",value:function t(e){var r=e.id,i=e.filename,n=e.content}},{key:"cachePageRef",value:function t(e,r){}},{key:"page",get:function t(){return 0},set:function t(e){}}]),t}();e.PDFLinkService=l,e.SimpleLinkService=h},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.DefaultAnnotationLayerFactory=e.AnnotationLayerBuilder=void 0;var n=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),o=r(0),a=r(1),s=r(3),c=function(){function t(e){var r=e.pageDiv,n=e.pdfPage,o=e.linkService,s=e.downloadManager,c=e.renderInteractiveForms,l=void 0!==c&&c,h=e.l10n,u=void 0===h?a.NullL10n:h;i(this,t),this.pageDiv=r,this.pdfPage=n,this.linkService=o,this.downloadManager=s,this.renderInteractiveForms=l,this.l10n=u,this.div=null}return n(t,[{key:"render",value:function t(e){var r=this,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"display";this.pdfPage.getAnnotations({intent:i}).then(function(t){var i={viewport:e.clone({dontFlip:!0}),div:r.div,annotations:t,page:r.pdfPage,renderInteractiveForms:r.renderInteractiveForms,linkService:r.linkService,downloadManager:r.downloadManager};if(r.div)o.AnnotationLayer.update(i);else{if(0===t.length)return;r.div=document.createElement("div"),r.div.className="annotationLayer",r.pageDiv.appendChild(r.div),i.div=r.div,o.AnnotationLayer.render(i),r.l10n.translate(r.div)}})}},{key:"hide",value:function t(){this.div&&this.div.setAttribute("hidden","true")}}]),t}(),l=function(){function t(){i(this,t)}return n(t,[{key:"createAnnotationLayerBuilder",value:function t(e,r){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:a.NullL10n;return new c({pageDiv:e,pdfPage:r,renderInteractiveForms:i,linkService:new s.SimpleLinkService,l10n:n})}}]),t}();e.AnnotationLayerBuilder=c,e.DefaultAnnotationLayerFactory=l},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.PDFPageView=void 0;var n=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),o=r(1),a=r(0),s=r(2),c=r(7),l=function(){function t(e){i(this,t);var r=e.container,n=e.defaultViewport;this.id=e.id,this.renderingId="page"+this.id,this.pageLabel=null,this.rotation=0,this.scale=e.scale||o.DEFAULT_SCALE,this.viewport=n,this.pdfPageRotate=n.rotation,this.hasRestrictedScaling=!1,this.enhanceTextSelection=e.enhanceTextSelection||!1,this.renderInteractiveForms=e.renderInteractiveForms||!1,this.eventBus=e.eventBus||(0,s.getGlobalEventBus)(),this.renderingQueue=e.renderingQueue,this.textLayerFactory=e.textLayerFactory,this.annotationLayerFactory=e.annotationLayerFactory,this.renderer=e.renderer||o.RendererType.CANVAS,this.l10n=e.l10n||o.NullL10n,this.paintTask=null,this.paintedViewportMap=new WeakMap,this.renderingState=c.RenderingStates.INITIAL,this.resume=null,this.error=null,this.onBeforeDraw=null,this.onAfterDraw=null,this.annotationLayer=null,this.textLayer=null,this.zoomLayer=null;var a=document.createElement("div");a.className="page",a.style.width=Math.floor(this.viewport.width)+"px",a.style.height=Math.floor(this.viewport.height)+"px",a.setAttribute("data-page-number",this.id),this.div=a,r.appendChild(a)}return n(t,[{key:"setPdfPage",value:function t(e){this.pdfPage=e,this.pdfPageRotate=e.rotate;var r=(this.rotation+this.pdfPageRotate)%360;this.viewport=e.getViewport(this.scale*o.CSS_UNITS,r),this.stats=e.stats,this.reset()}},{key:"destroy",value:function t(){this.reset(),this.pdfPage&&this.pdfPage.cleanup()}},{key:"_resetZoomLayer",value:function t(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(this.zoomLayer){var r=this.zoomLayer.firstChild;this.paintedViewportMap.delete(r),r.width=0,r.height=0,e&&this.zoomLayer.remove(),this.zoomLayer=null}}},{key:"reset",value:function t(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.cancelRendering();var i=this.div;i.style.width=Math.floor(this.viewport.width)+"px",i.style.height=Math.floor(this.viewport.height)+"px";for(var n=i.childNodes,o=e&&this.zoomLayer||null,a=r&&this.annotationLayer&&this.annotationLayer.div||null,s=n.length-1;s>=0;s--){var c=n[s];o!==c&&a!==c&&i.removeChild(c)}i.removeAttribute("data-loaded"),a?this.annotationLayer.hide():this.annotationLayer=null,o||(this.canvas&&(this.paintedViewportMap.delete(this.canvas),this.canvas.width=0,this.canvas.height=0,delete this.canvas),this._resetZoomLayer()),this.svg&&(this.paintedViewportMap.delete(this.svg),delete this.svg),this.loadingIconDiv=document.createElement("div"),this.loadingIconDiv.className="loadingIcon",i.appendChild(this.loadingIconDiv)}},{key:"update",value:function t(e,r){this.scale=e||this.scale,void 0!==r&&(this.rotation=r);var i=(this.rotation+this.pdfPageRotate)%360;if(this.viewport=this.viewport.clone({scale:this.scale*o.CSS_UNITS,rotation:i}),this.svg)return this.cssTransform(this.svg,!0),void this.eventBus.dispatch("pagerendered",{source:this,pageNumber:this.id,cssTransform:!0});var n=!1;if(this.canvas&&a.PDFJS.maxCanvasPixels>0){var s=this.outputScale;(Math.floor(this.viewport.width)*s.sx|0)*(Math.floor(this.viewport.height)*s.sy|0)>a.PDFJS.maxCanvasPixels&&(n=!0)}if(this.canvas){if(a.PDFJS.useOnlyCssZoom||this.hasRestrictedScaling&&n)return this.cssTransform(this.canvas,!0),void this.eventBus.dispatch("pagerendered",{source:this,pageNumber:this.id,cssTransform:!0});this.zoomLayer||this.canvas.hasAttribute("hidden")||(this.zoomLayer=this.canvas.parentNode,this.zoomLayer.style.position="absolute")}this.zoomLayer&&this.cssTransform(this.zoomLayer.firstChild),this.reset(!0,!0)}},{key:"cancelRendering",value:function t(){this.paintTask&&(this.paintTask.cancel(),this.paintTask=null),this.renderingState=c.RenderingStates.INITIAL,this.resume=null,this.textLayer&&(this.textLayer.cancel(),this.textLayer=null)}},{key:"cssTransform",value:function t(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=this.viewport.width,n=this.viewport.height,o=this.div;e.style.width=e.parentNode.style.width=o.style.width=Math.floor(i)+"px",e.style.height=e.parentNode.style.height=o.style.height=Math.floor(n)+"px";var s=this.viewport.rotation-this.paintedViewportMap.get(e).rotation,c=Math.abs(s),l=1,h=1;90!==c&&270!==c||(l=n/i,h=i/n);var t="rotate("+s+"deg) scale("+l+","+h+")";if(a.CustomStyle.setProp("transform",e,t),this.textLayer){var u=this.textLayer.viewport,f=this.viewport.rotation-u.rotation,d=Math.abs(f),p=i/u.width;90!==d&&270!==d||(p=i/u.height);var g=this.textLayer.textLayerDiv,v=void 0,m=void 0;switch(d){case 0:v=m=0;break;case 90:v=0,m="-"+g.style.height;break;case 180:v="-"+g.style.width,m="-"+g.style.height;break;case 270:v="-"+g.style.width,m=0;break;default:console.error("Bad rotation value.")}a.CustomStyle.setProp("transform",g,"rotate("+d+"deg) scale("+p+", "+p+") translate("+v+", "+m+")"),a.CustomStyle.setProp("transformOrigin",g,"0% 0%")}r&&this.annotationLayer&&this.annotationLayer.render(this.viewport,"display")}},{key:"getPagePoint",value:function t(e,r){return this.viewport.convertToPdfPoint(e,r)}},{key:"draw",value:function t(){var e=this;this.renderingState!==c.RenderingStates.INITIAL&&(console.error("Must be in new state before drawing"),this.reset()),this.renderingState=c.RenderingStates.RUNNING;var r=this.pdfPage,i=this.div,n=document.createElement("div");n.style.width=i.style.width,n.style.height=i.style.height,n.classList.add("canvasWrapper"),this.annotationLayer&&this.annotationLayer.div?i.insertBefore(n,this.annotationLayer.div):i.appendChild(n);var s=null;if(this.textLayerFactory){var l=document.createElement("div");l.className="textLayer",l.style.width=n.style.width,l.style.height=n.style.height,this.annotationLayer&&this.annotationLayer.div?i.insertBefore(l,this.annotationLayer.div):i.appendChild(l),s=this.textLayerFactory.createTextLayerBuilder(l,this.id-1,this.viewport,this.enhanceTextSelection)}this.textLayer=s;var h=null;this.renderingQueue&&(h=function t(r){if(!e.renderingQueue.isHighestPriority(e))return e.renderingState=c.RenderingStates.PAUSED,void(e.resume=function(){e.renderingState=c.RenderingStates.RUNNING,r()});r()});var u=function t(n){return f===e.paintTask&&(e.paintTask=null),"cancelled"===n||n instanceof a.RenderingCancelledException?(e.error=null,Promise.resolve(void 0)):(e.renderingState=c.RenderingStates.FINISHED,e.loadingIconDiv&&(i.removeChild(e.loadingIconDiv),delete e.loadingIconDiv),e._resetZoomLayer(!0),e.error=n,e.stats=r.stats,e.onAfterDraw&&e.onAfterDraw(),e.eventBus.dispatch("pagerendered",{source:e,pageNumber:e.id,cssTransform:!1}),n?Promise.reject(n):Promise.resolve(void 0))},f=this.renderer===o.RendererType.SVG?this.paintOnSvg(n):this.paintOnCanvas(n);f.onRenderContinue=h,this.paintTask=f;var d=f.promise.then(function(){return u(null).then(function(){if(s){var t=r.streamTextContent({normalizeWhitespace:!0});s.setTextContentStream(t),s.render()}})},function(t){return u(t)});return this.annotationLayerFactory&&(this.annotationLayer||(this.annotationLayer=this.annotationLayerFactory.createAnnotationLayerBuilder(i,r,this.renderInteractiveForms,this.l10n)),this.annotationLayer.render(this.viewport,"display")),i.setAttribute("data-loaded",!0),this.onBeforeDraw&&this.onBeforeDraw(),d}},{key:"paintOnCanvas",value:function t(e){var r=(0,a.createPromiseCapability)(),i={promise:r.promise,onRenderContinue:function t(e){e()},cancel:function t(){y.cancel()}},n=this.viewport,s=document.createElement("canvas");s.id=this.renderingId,s.setAttribute("hidden","hidden");var c=!0,l=function t(){c&&(s.removeAttribute("hidden"),c=!1)};e.appendChild(s),this.canvas=s,s.mozOpaque=!0;var h=s.getContext("2d",{alpha:!1}),u=(0,o.getOutputScale)(h);if(this.outputScale=u,a.PDFJS.useOnlyCssZoom){var f=n.clone({scale:o.CSS_UNITS});u.sx*=f.width/n.width,u.sy*=f.height/n.height,u.scaled=!0}if(a.PDFJS.maxCanvasPixels>0){var d=n.width*n.height,p=Math.sqrt(a.PDFJS.maxCanvasPixels/d);u.sx>p||u.sy>p?(u.sx=p,u.sy=p,u.scaled=!0,this.hasRestrictedScaling=!0):this.hasRestrictedScaling=!1}var g=(0,o.approximateFraction)(u.sx),v=(0,o.approximateFraction)(u.sy);s.width=(0,o.roundToDivide)(n.width*u.sx,g[0]),s.height=(0,o.roundToDivide)(n.height*u.sy,v[0]),s.style.width=(0,o.roundToDivide)(n.width,g[1])+"px",s.style.height=(0,o.roundToDivide)(n.height,v[1])+"px",this.paintedViewportMap.set(s,n);var m=u.scaled?[u.sx,0,0,u.sy,0,0]:null,b={canvasContext:h,transform:m,viewport:this.viewport,renderInteractiveForms:this.renderInteractiveForms},y=this.pdfPage.render(b);return y.onContinue=function(t){l(),i.onRenderContinue?i.onRenderContinue(t):t()},y.promise.then(function(){l(),r.resolve(void 0)},function(t){l(),r.reject(t)}),i}},{key:"paintOnSvg",value:function t(e){var r=this,i=!1,n=function t(){if(i)throw a.PDFJS.pdfjsNext?new a.RenderingCancelledException("Rendering cancelled, page "+r.id,"svg"):"cancelled"},s=this.pdfPage,l=this.viewport.clone({scale:o.CSS_UNITS});return{promise:s.getOperatorList().then(function(t){return n(),new a.SVGGraphics(s.commonObjs,s.objs).getSVG(t,l).then(function(t){n(),r.svg=t,r.paintedViewportMap.set(t,l),t.style.width=e.style.width,t.style.height=e.style.height,r.renderingState=c.RenderingStates.FINISHED,e.appendChild(t)})}),onRenderContinue:function t(e){e()},cancel:function t(){i=!0}}}},{key:"setPageLabel",value:function t(e){this.pageLabel="string"==typeof e?e:null,null!==this.pageLabel?this.div.setAttribute("data-page-label",this.pageLabel):this.div.removeAttribute("data-page-label")}},{key:"width",get:function t(){return this.viewport.width}},{key:"height",get:function t(){return this.viewport.height}}]),t}();e.PDFPageView=l},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.DefaultTextLayerFactory=e.TextLayerBuilder=void 0;var n=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),o=r(2),a=r(0),s=300,c=function(){function t(e){var r=e.textLayerDiv,n=e.eventBus,a=e.pageIndex,s=e.viewport,c=e.findController,l=void 0===c?null:c,h=e.enhanceTextSelection,u=void 0!==h&&h;i(this,t),this.textLayerDiv=r,this.eventBus=n||(0,o.getGlobalEventBus)(),this.textContent=null,this.textContentItemsStr=[],this.textContentStream=null,this.renderingDone=!1,this.pageIdx=a,this.pageNumber=this.pageIdx+1,this.matches=[],this.viewport=s,this.textDivs=[],this.findController=l,this.textLayerRenderTask=null,this.enhanceTextSelection=u,this._bindMouse()}return n(t,[{key:"_finishRendering",value:function t(){if(this.renderingDone=!0,!this.enhanceTextSelection){var e=document.createElement("div");e.className="endOfContent",this.textLayerDiv.appendChild(e)}this.eventBus.dispatch("textlayerrendered",{source:this,pageNumber:this.pageNumber,numTextDivs:this.textDivs.length})}},{key:"render",value:function t(){var e=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;if((this.textContent||this.textContentStream)&&!this.renderingDone){this.cancel(),this.textDivs=[];var i=document.createDocumentFragment();this.textLayerRenderTask=(0,a.renderTextLayer)({textContent:this.textContent,textContentStream:this.textContentStream,container:i,viewport:this.viewport,textDivs:this.textDivs,textContentItemsStr:this.textContentItemsStr,timeout:r,enhanceTextSelection:this.enhanceTextSelection}),this.textLayerRenderTask.promise.then(function(){e.textLayerDiv.appendChild(i),e._finishRendering(),e.updateMatches()},function(t){})}}},{key:"cancel",value:function t(){this.textLayerRenderTask&&(this.textLayerRenderTask.cancel(),this.textLayerRenderTask=null)}},{key:"setTextContentStream",value:function t(e){this.cancel(),this.textContentStream=e}},{key:"setTextContent",value:function t(e){this.cancel(),this.textContent=e}},{key:"convertMatches",value:function t(e,r){var i=0,n=0,o=this.textContentItemsStr,a=o.length-1,s=null===this.findController?0:this.findController.state.query.length,c=[];if(!e)return c;for(var l=0,h=e.length;l<h;l++){for(var u=e[l];i!==a&&u>=n+o[i].length;)n+=o[i].length,i++;i===o.length&&console.error("Could not find a matching mapping");var f={begin:{divIdx:i,offset:u-n}};for(u+=r?r[l]:s;i!==a&&u>n+o[i].length;)n+=o[i].length,i++;f.end={divIdx:i,offset:u-n},c.push(f)}return c}},{key:"renderMatches",value:function t(e){function r(t,e){var r=t.divIdx;o[r].textContent="",i(r,0,t.offset,e)}function i(t,e,r,i){var a=o[t],s=n[t].substring(e,r),c=document.createTextNode(s);if(i){var l=document.createElement("span");return l.className=i,l.appendChild(c),void a.appendChild(l)}a.appendChild(c)}if(0!==e.length){var n=this.textContentItemsStr,o=this.textDivs,a=null,s=this.pageIdx,c=null!==this.findController&&s===this.findController.selected.pageIdx,l=null===this.findController?-1:this.findController.selected.matchIdx,h=null!==this.findController&&this.findController.state.highlightAll,u={divIdx:-1,offset:void 0},f=l,d=f+1;if(h)f=0,d=e.length;else if(!c)return;for(var p=f;p<d;p++){var g=e[p],v=g.begin,m=g.end,b=c&&p===l,y=b?" selected":"";if(this.findController&&this.findController.updateMatchPosition(s,p,o,v.divIdx),a&&v.divIdx===a.divIdx?i(a.divIdx,a.offset,v.offset):(null!==a&&i(a.divIdx,a.offset,u.offset),r(v)),v.divIdx===m.divIdx)i(v.divIdx,v.offset,m.offset,"highlight"+y);else{i(v.divIdx,v.offset,u.offset,"highlight begin"+y);for(var _=v.divIdx+1,w=m.divIdx;_<w;_++)o[_].className="highlight middle"+y;r(m,"highlight end"+y)}a=m}a&&i(a.divIdx,a.offset,u.offset)}}},{key:"updateMatches",value:function t(){if(this.renderingDone){for(var e=this.matches,r=this.textDivs,i=this.textContentItemsStr,n=-1,o=0,a=e.length;o<a;o++){for(var s=e[o],c=Math.max(n,s.begin.divIdx),l=c,h=s.end.divIdx;l<=h;l++){var u=r[l];u.textContent=i[l],u.className=""}n=s.end.divIdx+1}if(null!==this.findController&&this.findController.active){var f=void 0,d=void 0;null!==this.findController&&(f=this.findController.pageMatches[this.pageIdx]||null,d=this.findController.pageMatchesLength?this.findController.pageMatchesLength[this.pageIdx]||null:null),this.matches=this.convertMatches(f,d),this.renderMatches(this.matches)}}}},{key:"_bindMouse",value:function t(){var e=this,r=this.textLayerDiv,i=null;r.addEventListener("mousedown",function(t){if(e.enhanceTextSelection&&e.textLayerRenderTask)return e.textLayerRenderTask.expandTextDivs(!0),void(i&&(clearTimeout(i),i=null));var n=r.querySelector(".endOfContent");if(n){var o=t.target!==r;if(o=o&&"none"!==window.getComputedStyle(n).getPropertyValue("-moz-user-select")){var a=r.getBoundingClientRect(),s=Math.max(0,(t.pageY-a.top)/a.height);n.style.top=(100*s).toFixed(2)+"%"}n.classList.add("active")}}),r.addEventListener("mouseup",function(){if(e.enhanceTextSelection&&e.textLayerRenderTask)return void(i=setTimeout(function(){e.textLayerRenderTask&&e.textLayerRenderTask.expandTextDivs(!1),i=null},300));var t=r.querySelector(".endOfContent");t&&(t.style.top="",t.classList.remove("active"))})}}]),t}(),l=function(){function t(){i(this,t)}return n(t,[{key:"createTextLayerBuilder",value:function t(e,r,i){var n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return new c({textLayerDiv:e,pageIndex:r,viewport:i,enhanceTextSelection:n})}}]),t}();e.TextLayerBuilder=c,e.DefaultTextLayerFactory=l},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),o=3e4,a={INITIAL:0,RUNNING:1,PAUSED:2,FINISHED:3},s=function(){function t(){i(this,t),this.pdfViewer=null,this.pdfThumbnailViewer=null,this.onIdle=null,this.highestPriorityPage=null,this.idleTimeout=null,this.printing=!1,this.isThumbnailViewEnabled=!1}return n(t,[{key:"setViewer",value:function t(e){this.pdfViewer=e}},{key:"setThumbnailViewer",value:function t(e){this.pdfThumbnailViewer=e}},{key:"isHighestPriority",value:function t(e){return this.highestPriorityPage===e.renderingId}},{key:"renderHighestPriority",value:function t(e){this.idleTimeout&&(clearTimeout(this.idleTimeout),this.idleTimeout=null),this.pdfViewer.forceRendering(e)||this.pdfThumbnailViewer&&this.isThumbnailViewEnabled&&this.pdfThumbnailViewer.forceRendering()||this.printing||this.onIdle&&(this.idleTimeout=setTimeout(this.onIdle.bind(this),3e4))}},{key:"getHighestPriority",value:function t(e,r,i){var n=e.views,o=n.length;if(0===o)return!1;for(var a=0;a<o;++a){var s=n[a].view;if(!this.isViewFinished(s))return s}if(i){var c=e.last.id;if(r[c]&&!this.isViewFinished(r[c]))return r[c]}else{var l=e.first.id-2;if(r[l]&&!this.isViewFinished(r[l]))return r[l]}return null}},{key:"isViewFinished",value:function t(e){return e.renderingState===a.FINISHED}},{key:"renderView",value:function t(e){var r=this;switch(e.renderingState){case a.FINISHED:return!1;case a.PAUSED:this.highestPriorityPage=e.renderingId,e.resume();break;case a.RUNNING:this.highestPriorityPage=e.renderingId;break;case a.INITIAL:this.highestPriorityPage=e.renderingId;var i=function t(){r.renderHighestPriority()};e.draw().then(i,i)}return!0}}]),t}();e.RenderingStates=a,e.PDFRenderingQueue=s},function(t,e,r){"use strict";function i(t,e){var r=document.createElement("a");if(r.click)r.href=t,r.target="_parent","download"in r&&(r.download=e),(document.body||document.documentElement).appendChild(r),r.click(),r.parentNode.removeChild(r);else{if(window.top===window&&t.split("#")[0]===window.location.href.split("#")[0]){var i=-1===t.indexOf("?")?"?":"&";t=t.replace(/#|$/,i+"$&")}window.open(t,"_parent")}}function n(){}Object.defineProperty(e,"__esModule",{value:!0}),e.DownloadManager=void 0;var o=r(0);n.prototype={downloadUrl:function t(e,r){(0,o.createValidAbsoluteUrl)(e,"http://example.com")&&i(e+"#pdfjs.action=download",r)},downloadData:function t(e,r,n){if(navigator.msSaveBlob)return navigator.msSaveBlob(new Blob([e],{type:n}),r);i((0,o.createObjectURL)(e,n,o.PDFJS.disableCreateObjectURL),r)},download:function t(e,r,n){return navigator.msSaveBlob?void(navigator.msSaveBlob(e,n)||this.downloadUrl(r,n)):o.PDFJS.disableCreateObjectURL?void this.downloadUrl(r,n):void i(URL.createObjectURL(e),n)}},e.DownloadManager=n},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.GenericL10n=void 0;var n=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}();r(13);var o=document.webL10n,a=function(){function t(e){i(this,t),this._lang=e,this._ready=new Promise(function(t,r){o.setLanguage(e,function(){t(o)})})}return n(t,[{key:"getDirection",value:function t(){return this._ready.then(function(t){return t.getDirection()})}},{key:"get",value:function t(e,r,i){return this._ready.then(function(t){return t.get(e,r,i)})}},{key:"translate",value:function t(e){return this._ready.then(function(t){return t.translate(e)})}}]),t}();e.GenericL10n=a},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.PDFFindController=e.FindState=void 0;var n=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),o=r(0),a=r(1),s={FOUND:0,NOT_FOUND:1,WRAPPED:2,PENDING:3},c=-50,l=-400,h=250,u={"‘":"'","’":"'","‚":"'","‛":"'","“":'"',"”":'"',"„":'"',"‟":'"',"¼":"1/4","½":"1/2","¾":"3/4"},f=function(){function t(e){var r=e.pdfViewer;i(this,t),this.pdfViewer=r,this.onUpdateResultsCount=null,this.onUpdateState=null,this.reset();var n=Object.keys(u).join("");this.normalizationRegex=new RegExp("["+n+"]","g")}return n(t,[{key:"reset",value:function t(){var e=this;this.startedTextExtraction=!1,this.extractTextPromises=[],this.pendingFindMatches=Object.create(null),this.active=!1,this.pageContents=[],this.pageMatches=[],this.pageMatchesLength=null,this.matchCount=0,this.selected={pageIdx:-1,matchIdx:-1},this.offset={pageIdx:null,matchIdx:null},this.pagesToSearch=null,this.resumePageIdx=null,this.state=null,this.dirtyMatch=!1,this.findTimeout=null,this._firstPagePromise=new Promise(function(t){e.resolveFirstPage=t})}},{key:"normalize",value:function t(e){return e.replace(this.normalizationRegex,function(t){return u[t]})}},{key:"_prepareMatches",value:function t(e,r,i){function n(t,e){var r=t[e],i=t[e+1];if(e<t.length-1&&r.match===i.match)return r.skipped=!0,!0;for(var n=e-1;n>=0;n--){var o=t[n];if(!o.skipped){if(o.match+o.matchLength<r.match)break;if(o.match+o.matchLength>=r.match+r.matchLength)return r.skipped=!0,!0}}return!1}e.sort(function(t,e){return t.match===e.match?t.matchLength-e.matchLength:t.match-e.match});for(var o=0,a=e.length;o<a;o++)n(e,o)||(r.push(e[o].match),i.push(e[o].matchLength))}},{key:"calcFindPhraseMatch",value:function t(e,r,i){for(var n=[],o=e.length,a=-o;;){if(-1===(a=i.indexOf(e,a+o)))break;n.push(a)}this.pageMatches[r]=n}},{key:"calcFindWordMatch",value:function t(e,r,i){for(var n=[],o=e.match(/\S+/g),a=0,s=o.length;a<s;a++)for(var c=o[a],l=c.length,h=-l;;){if(-1===(h=i.indexOf(c,h+l)))break;n.push({match:h,matchLength:l,skipped:!1})}this.pageMatchesLength||(this.pageMatchesLength=[]),this.pageMatchesLength[r]=[],this.pageMatches[r]=[],this._prepareMatches(n,this.pageMatches[r],this.pageMatchesLength[r])}},{key:"calcFindMatch",value:function t(e){var r=this.normalize(this.pageContents[e]),i=this.normalize(this.state.query),n=this.state.caseSensitive,o=this.state.phraseSearch;0!==i.length&&(n||(r=r.toLowerCase(),i=i.toLowerCase()),o?this.calcFindPhraseMatch(i,e,r):this.calcFindWordMatch(i,e,r),this.updatePage(e),this.resumePageIdx===e&&(this.resumePageIdx=null,this.nextPageMatch()),this.pageMatches[e].length>0&&(this.matchCount+=this.pageMatches[e].length,this.updateUIResultsCount()))}},{key:"extractText",value:function t(){var e=this;if(!this.startedTextExtraction){this.startedTextExtraction=!0,this.pageContents.length=0;for(var r=Promise.resolve(),i=function t(i,n){var a=(0,o.createPromiseCapability)();e.extractTextPromises[i]=a.promise,r=r.then(function(){return e.pdfViewer.getPageTextContent(i).then(function(t){for(var r=t.items,n=[],o=0,s=r.length;o<s;o++)n.push(r[o].str);e.pageContents[i]=n.join(""),a.resolve(i)})})},n=0,a=this.pdfViewer.pagesCount;n<a;n++)i(n,a)}}},{key:"executeCommand",value:function t(e,r){var i=this;null!==this.state&&"findagain"===e||(this.dirtyMatch=!0),this.state=r,this.updateUIState(s.PENDING),this._firstPagePromise.then(function(){i.extractText(),clearTimeout(i.findTimeout),"find"===e?i.findTimeout=setTimeout(i.nextMatch.bind(i),250):i.nextMatch()})}},{key:"updatePage",value:function t(e){this.selected.pageIdx===e&&(this.pdfViewer.currentPageNumber=e+1);var r=this.pdfViewer.getPageView(e);r.textLayer&&r.textLayer.updateMatches()}},{key:"nextMatch",value:function t(){var e=this,r=this.state.findPrevious,i=this.pdfViewer.currentPageNumber-1,n=this.pdfViewer.pagesCount;if(this.active=!0,this.dirtyMatch){this.dirtyMatch=!1,this.selected.pageIdx=this.selected.matchIdx=-1,this.offset.pageIdx=i,this.offset.matchIdx=null,this.hadMatch=!1,this.resumePageIdx=null,this.pageMatches=[],this.matchCount=0,this.pageMatchesLength=null;for(var o=0;o<n;o++)this.updatePage(o),o in this.pendingFindMatches||(this.pendingFindMatches[o]=!0,this.extractTextPromises[o].then(function(t){delete e.pendingFindMatches[t],e.calcFindMatch(t)}))}if(""===this.state.query)return void this.updateUIState(s.FOUND);if(!this.resumePageIdx){var a=this.offset;if(this.pagesToSearch=n,null!==a.matchIdx){var c=this.pageMatches[a.pageIdx].length;if(!r&&a.matchIdx+1<c||r&&a.matchIdx>0)return this.hadMatch=!0,a.matchIdx=r?a.matchIdx-1:a.matchIdx+1,void this.updateMatch(!0);this.advanceOffsetPage(r)}this.nextPageMatch()}}},{key:"matchesReady",value:function t(e){var r=this.offset,i=e.length,n=this.state.findPrevious;return i?(this.hadMatch=!0,r.matchIdx=n?i-1:0,this.updateMatch(!0),!0):(this.advanceOffsetPage(n),!!(r.wrapped&&(r.matchIdx=null,this.pagesToSearch<0))&&(this.updateMatch(!1),!0))}},{key:"updateMatchPosition",value:function t(e,r,i,n){if(this.selected.matchIdx===r&&this.selected.pageIdx===e){var o={top:-50,left:-400};(0,a.scrollIntoView)(i[n],o,!0)}}},{key:"nextPageMatch",value:function t(){null!==this.resumePageIdx&&console.error("There can only be one pending page.");var e=null;do{var r=this.offset.pageIdx;if(!(e=this.pageMatches[r])){this.resumePageIdx=r;break}}while(!this.matchesReady(e))}},{key:"advanceOffsetPage",value:function t(e){var r=this.offset,i=this.extractTextPromises.length;r.pageIdx=e?r.pageIdx-1:r.pageIdx+1,r.matchIdx=null,this.pagesToSearch--,(r.pageIdx>=i||r.pageIdx<0)&&(r.pageIdx=e?i-1:0,r.wrapped=!0)}},{key:"updateMatch",value:function t(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],r=s.NOT_FOUND,i=this.offset.wrapped;if(this.offset.wrapped=!1,e){var n=this.selected.pageIdx;this.selected.pageIdx=this.offset.pageIdx,this.selected.matchIdx=this.offset.matchIdx,r=i?s.WRAPPED:s.FOUND,-1!==n&&n!==this.selected.pageIdx&&this.updatePage(n)}this.updateUIState(r,this.state.findPrevious),-1!==this.selected.pageIdx&&this.updatePage(this.selected.pageIdx)}},{key:"updateUIResultsCount",value:function t(){this.onUpdateResultsCount&&this.onUpdateResultsCount(this.matchCount)}},{key:"updateUIState",value:function t(e,r){this.onUpdateState&&this.onUpdateState(e,r,this.matchCount)}}]),t}();e.FindState=s,e.PDFFindController=f},function(t,e,r){"use strict";function i(t){this.linkService=t.linkService,this.eventBus=t.eventBus||(0,n.getGlobalEventBus)(),this.initialized=!1,this.initialDestination=null,this.initialBookmark=null}Object.defineProperty(e,"__esModule",{value:!0}),e.PDFHistory=void 0;var n=r(2);i.prototype={initialize:function t(e){function r(){a.previousHash=window.location.hash.slice(1),a._pushToHistory({hash:a.previousHash},!1,!0),a._updatePreviousBookmark()}function i(t,e){function r(){window.removeEventListener("popstate",r),window.addEventListener("popstate",i),a._pushToHistory(t,!1,!0),history.forward()}function i(){window.removeEventListener("popstate",i),a.allowHashChange=!0,a.historyUnlocked=!0,e()}a.historyUnlocked=!1,a.allowHashChange=!1,window.addEventListener("popstate",r),history.back()}function n(){var t=a._getPreviousParams(null,!0);if(t){var e=!a.current.dest&&a.current.hash!==a.previousHash;a._pushToHistory(t,!1,e),a._updatePreviousBookmark()}window.removeEventListener("beforeunload",n)}this.initialized=!0,this.reInitialized=!1,this.allowHashChange=!0,this.historyUnlocked=!0,this.isViewerInPresentationMode=!1,this.previousHash=window.location.hash.substring(1),this.currentBookmark="",this.currentPage=0,this.updatePreviousBookmark=!1,this.previousBookmark="",this.previousPage=0,this.nextHashParam="",this.fingerprint=e,this.currentUid=this.uid=0,this.current={};var o=window.history.state;this._isStateObjectDefined(o)?(o.target.dest?this.initialDestination=o.target.dest:this.initialBookmark=o.target.hash,this.currentUid=o.uid,this.uid=o.uid+1,this.current=o.target):(o&&o.fingerprint&&this.fingerprint!==o.fingerprint&&(this.reInitialized=!0),this._pushOrReplaceState({fingerprint:this.fingerprint},!0));var a=this;window.addEventListener("popstate",function t(e){if(a.historyUnlocked){if(e.state)return void a._goTo(e.state);if(0===a.uid){i(a.previousHash&&a.currentBookmark&&a.previousHash!==a.currentBookmark?{hash:a.currentBookmark,page:a.currentPage}:{page:1},function(){r()})}else r()}}),window.addEventListener("beforeunload",n),window.addEventListener("pageshow",function t(e){window.addEventListener("beforeunload",n)}),a.eventBus.on("presentationmodechanged",function(t){a.isViewerInPresentationMode=t.active})},clearHistoryState:function t(){this._pushOrReplaceState(null,!0)},_isStateObjectDefined:function t(e){return!!(e&&e.uid>=0&&e.fingerprint&&this.fingerprint===e.fingerprint&&e.target&&e.target.hash)},_pushOrReplaceState:function t(e,r){r?window.history.replaceState(e,"",document.URL):window.history.pushState(e,"",document.URL)},get isHashChangeUnlocked(){return!this.initialized||this.allowHashChange},_updatePreviousBookmark:function t(){this.updatePreviousBookmark&&this.currentBookmark&&this.currentPage&&(this.previousBookmark=this.currentBookmark,this.previousPage=this.currentPage,this.updatePreviousBookmark=!1)},updateCurrentBookmark:function t(e,r){this.initialized&&(this.currentBookmark=e.substring(1),this.currentPage=0|r,this._updatePreviousBookmark())},updateNextHashParam:function t(e){this.initialized&&(this.nextHashParam=e)},push:function t(e,r){if(this.initialized&&this.historyUnlocked){if(e.dest&&!e.hash&&(e.hash=this.current.hash&&this.current.dest&&this.current.dest===e.dest?this.current.hash:this.linkService.getDestinationHash(e.dest).split("#")[1]),e.page&&(e.page|=0),r){var i=window.history.state.target;return i||(this._pushToHistory(e,!1),this.previousHash=window.location.hash.substring(1)),this.updatePreviousBookmark=!this.nextHashParam,void(i&&this._updatePreviousBookmark())}if(this.nextHashParam){if(this.nextHashParam===e.hash)return this.nextHashParam=null,void(this.updatePreviousBookmark=!0);this.nextHashParam=null}e.hash?this.current.hash?this.current.hash!==e.hash?this._pushToHistory(e,!0):(!this.current.page&&e.page&&this._pushToHistory(e,!1,!0),this.updatePreviousBookmark=!0):this._pushToHistory(e,!0):this.current.page&&e.page&&this.current.page!==e.page&&this._pushToHistory(e,!0)}},_getPreviousParams:function t(e,r){if(!this.currentBookmark||!this.currentPage)return null;if(this.updatePreviousBookmark&&(this.updatePreviousBookmark=!1),this.uid>0&&(!this.previousBookmark||!this.previousPage))return null;if(!this.current.dest&&!e||r){if(this.previousBookmark===this.currentBookmark)return null}else{if(!this.current.page&&!e)return null;if(this.previousPage===this.currentPage)return null}var i={hash:this.currentBookmark,page:this.currentPage};return this.isViewerInPresentationMode&&(i.hash=null),i},_stateObj:function t(e){return{fingerprint:this.fingerprint,uid:this.uid,target:e}},_pushToHistory:function t(e,r,i){if(this.initialized){if(!e.hash&&e.page&&(e.hash="page="+e.page),r&&!i){var n=this._getPreviousParams();if(n){var o=!this.current.dest&&this.current.hash!==this.previousHash;this._pushToHistory(n,!1,o)}}this._pushOrReplaceState(this._stateObj(e),i||0===this.uid),this.currentUid=this.uid++,this.current=e,this.updatePreviousBookmark=!0}},_goTo:function t(e){if(this.initialized&&this.historyUnlocked&&this._isStateObjectDefined(e)){if(!this.reInitialized&&e.uid<this.currentUid){var r=this._getPreviousParams(!0);if(r)return this._pushToHistory(this.current,!1),this._pushToHistory(r,!1),this.currentUid=e.uid,void window.history.back()}this.historyUnlocked=!1,e.target.dest?this.linkService.navigateTo(e.target.dest):this.linkService.setHash(e.target.hash),this.currentUid=e.uid,e.uid>this.uid&&(this.uid=e.uid),this.current=e.target,this.updatePreviousBookmark=!0;var i=window.location.hash.substring(1);this.previousHash!==i&&(this.allowHashChange=!1),this.previousHash=i,this.historyUnlocked=!0}},back:function t(){this.go(-1)},forward:function t(){this.go(1)},go:function t(e){if(this.initialized&&this.historyUnlocked){var r=window.history.state;-1===e&&r&&r.uid>0?window.history.back():1===e&&r&&r.uid<this.uid-1&&window.history.forward()}}},e.PDFHistory=i},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t){var e=[];this.push=function r(i){var n=e.indexOf(i);n>=0&&e.splice(n,1),e.push(i),e.length>t&&e.shift().destroy()},this.resize=function(r){for(t=r;e.length>t;)e.shift().destroy()}}function o(t,e){return e===t||Math.abs(e-t)<1e-15}function a(t){return t.width<=t.height}Object.defineProperty(e,"__esModule",{value:!0}),e.PDFViewer=e.PresentationModeState=void 0;var s=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),c=r(0),l=r(1),h=r(7),u=r(4),f=r(2),d=r(5),p=r(3),g=r(6),v={UNKNOWN:0,NORMAL:1,CHANGING:2,FULLSCREEN:3},m=10,b=function(){function t(e){i(this,t),this.container=e.container,this.viewer=e.viewer||e.container.firstElementChild,this.eventBus=e.eventBus||(0,f.getGlobalEventBus)(),this.linkService=e.linkService||new p.SimpleLinkService,this.downloadManager=e.downloadManager||null,this.removePageBorders=e.removePageBorders||!1,this.enhanceTextSelection=e.enhanceTextSelection||!1,this.renderInteractiveForms=e.renderInteractiveForms||!1,this.enablePrintAutoRotate=e.enablePrintAutoRotate||!1,this.renderer=e.renderer||l.RendererType.CANVAS,this.l10n=e.l10n||l.NullL10n,this.defaultRenderingQueue=!e.renderingQueue,this.defaultRenderingQueue?(this.renderingQueue=new h.PDFRenderingQueue,this.renderingQueue.setViewer(this)):this.renderingQueue=e.renderingQueue,this.scroll=(0,l.watchScroll)(this.container,this._scrollUpdate.bind(this)),this.presentationModeState=v.UNKNOWN,this._resetView(),this.removePageBorders&&this.viewer.classList.add("removePageBorders")}return s(t,[{key:"getPageView",value:function t(e){return this._pages[e]}},{key:"_setCurrentPageNumber",value:function t(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(this._currentPageNumber===e)return void(r&&this._resetCurrentPageView());if(!(0<e&&e<=this.pagesCount))return void console.error('PDFViewer._setCurrentPageNumber: "'+e+'" is out of bounds.');var i={source:this,pageNumber:e,pageLabel:this._pageLabels&&this._pageLabels[e-1]};this._currentPageNumber=e,this.eventBus.dispatch("pagechanging",i),this.eventBus.dispatch("pagechange",i),r&&this._resetCurrentPageView()}},{key:"setDocument",value:function t(e){var r=this;if(this.pdfDocument&&(this._cancelRendering(),this._resetView()),this.pdfDocument=e,e){var i=e.numPages,n=(0,c.createPromiseCapability)();this.pagesPromise=n.promise,n.promise.then(function(){r._pageViewsReady=!0,r.eventBus.dispatch("pagesloaded",{source:r,pagesCount:i})});var o=!1,a=(0,c.createPromiseCapability)();this.onePageRendered=a.promise;var s=function t(e){e.onBeforeDraw=function(){r._buffer.push(e)},e.onAfterDraw=function(){o||(o=!0,a.resolve())}},h=e.getPage(1);return this.firstPagePromise=h,h.then(function(t){for(var o=r.currentScale,h=t.getViewport(o*l.CSS_UNITS),u=1;u<=i;++u){var f=null;c.PDFJS.disableTextLayer||(f=r);var p=new d.PDFPageView({container:r.viewer,eventBus:r.eventBus,id:u,scale:o,defaultViewport:h.clone(),renderingQueue:r.renderingQueue,textLayerFactory:f,annotationLayerFactory:r,enhanceTextSelection:r.enhanceTextSelection,renderInteractiveForms:r.renderInteractiveForms,renderer:r.renderer,l10n:r.l10n});s(p),r._pages.push(p)}a.promise.then(function(){if(c.PDFJS.disableAutoFetch)return void n.resolve();for(var t=i,o=function i(o){e.getPage(o).then(function(e){var i=r._pages[o-1];i.pdfPage||i.setPdfPage(e),r.linkService.cachePageRef(o,e.ref),0==--t&&n.resolve()})},a=1;a<=i;++a)o(a)}),r.eventBus.dispatch("pagesinit",{source:r}),r.defaultRenderingQueue&&r.update(),r.findController&&r.findController.resolveFirstPage()})}}},{key:"setPageLabels",value:function t(e){if(this.pdfDocument){e?e instanceof Array&&this.pdfDocument.numPages===e.length?this._pageLabels=e:(this._pageLabels=null,console.error("PDFViewer.setPageLabels: Invalid page labels.")):this._pageLabels=null;for(var r=0,i=this._pages.length;r<i;r++){var n=this._pages[r],o=this._pageLabels&&this._pageLabels[r];n.setPageLabel(o)}}}},{key:"_resetView",value:function t(){this._pages=[],this._currentPageNumber=1,this._currentScale=l.UNKNOWN_SCALE,this._currentScaleValue=null,this._pageLabels=null,this._buffer=new n(10),this._location=null,this._pagesRotation=0,this._pagesRequests=[],this._pageViewsReady=!1,this.viewer.textContent=""}},{key:"_scrollUpdate",value:function t(){0!==this.pagesCount&&this.update()}},{key:"_setScaleDispatchEvent",value:function t(e,r){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n={source:this,scale:e,presetValue:i?r:void 0};this.eventBus.dispatch("scalechanging",n),this.eventBus.dispatch("scalechange",n)}},{key:"_setScaleUpdatePages",value:function t(e,r){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(this._currentScaleValue=r.toString(),o(this._currentScale,e))return void(n&&this._setScaleDispatchEvent(e,r,!0));for(var a=0,s=this._pages.length;a<s;a++)this._pages[a].update(e);if(this._currentScale=e,!i){var l=this._currentPageNumber,h=void 0;!this._location||c.PDFJS.ignoreCurrentPositionOnZoom||this.isInPresentationMode||this.isChangingPresentationMode||(l=this._location.pageNumber,h=[null,{name:"XYZ"},this._location.left,this._location.top,null]),this.scrollPageIntoView({pageNumber:l,destArray:h,allowNegativeOffset:!0})}this._setScaleDispatchEvent(e,r,n),this.defaultRenderingQueue&&this.update()}},{key:"_setScale",value:function t(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=parseFloat(e);if(i>0)this._setScaleUpdatePages(i,e,r,!1);else{var n=this._pages[this._currentPageNumber-1];if(!n)return;var o=this.isInPresentationMode||this.removePageBorders?0:l.SCROLLBAR_PADDING,a=this.isInPresentationMode||this.removePageBorders?0:l.VERTICAL_PADDING,s=(this.container.clientWidth-o)/n.width*n.scale,c=(this.container.clientHeight-a)/n.height*n.scale;switch(e){case"page-actual":i=1;break;case"page-width":i=s;break;case"page-height":i=c;break;case"page-fit":i=Math.min(s,c);break;case"auto":var h=n.width>n.height,u=h?Math.min(c,s):s;i=Math.min(l.MAX_AUTO_SCALE,u);break;default:return void console.error('PDFViewer._setScale: "'+e+'" is an unknown zoom value.')}this._setScaleUpdatePages(i,e,r,!0)}}},{key:"_resetCurrentPageView",value:function t(){this.isInPresentationMode&&this._setScale(this._currentScaleValue,!0);var e=this._pages[this._currentPageNumber-1];(0,l.scrollIntoView)(e.div)}},{key:"scrollPageIntoView",value:function t(e){if(this.pdfDocument){if(arguments.length>1||"number"==typeof e){console.warn("Call of scrollPageIntoView() with obsolete signature.");var r={};"number"==typeof e&&(r.pageNumber=e),arguments[1]instanceof Array&&(r.destArray=arguments[1]),e=r}var i=e.pageNumber||0,n=e.destArray||null,o=e.allowNegativeOffset||!1;if(this.isInPresentationMode||!n)return void this._setCurrentPageNumber(i,!0);var a=this._pages[i-1];if(!a)return void console.error('PDFViewer.scrollPageIntoView: Invalid "pageNumber" parameter.');var s=0,c=0,h=0,u=0,f=void 0,d=void 0,p=a.rotation%180!=0,g=(p?a.height:a.width)/a.scale/l.CSS_UNITS,v=(p?a.width:a.height)/a.scale/l.CSS_UNITS,m=0;switch(n[1].name){case"XYZ":s=n[2],c=n[3],m=n[4],s=null!==s?s:0,c=null!==c?c:v;break;case"Fit":case"FitB":m="page-fit";break;case"FitH":case"FitBH":c=n[2],m="page-width",null===c&&this._location&&(s=this._location.left,c=this._location.top);break;case"FitV":case"FitBV":s=n[2],h=g,u=v,m="page-height";break;case"FitR":s=n[2],c=n[3],h=n[4]-s,u=n[5]-c;var b=this.removePageBorders?0:l.SCROLLBAR_PADDING,y=this.removePageBorders?0:l.VERTICAL_PADDING;f=(this.container.clientWidth-b)/h/l.CSS_UNITS,d=(this.container.clientHeight-y)/u/l.CSS_UNITS,m=Math.min(Math.abs(f),Math.abs(d));break;default:return void console.error('PDFViewer.scrollPageIntoView: "'+n[1].name+'" is not a valid destination type.')}if(m&&m!==this._currentScale?this.currentScaleValue=m:this._currentScale===l.UNKNOWN_SCALE&&(this.currentScaleValue=l.DEFAULT_SCALE_VALUE),"page-fit"===m&&!n[4])return void(0,l.scrollIntoView)(a.div);var _=[a.viewport.convertToViewportPoint(s,c),a.viewport.convertToViewportPoint(s+h,c+u)],w=Math.min(_[0][0],_[1][0]),S=Math.min(_[0][1],_[1][1]);o||(w=Math.max(w,0),S=Math.max(S,0)),(0,l.scrollIntoView)(a.div,{left:w,top:S})}}},{key:"_updateLocation",value:function t(e){var r=this._currentScale,i=this._currentScaleValue,n=parseFloat(i)===r?Math.round(1e4*r)/100:i,o=e.id,a="#page="+o;a+="&zoom="+n;var s=this._pages[o-1],c=this.container,l=s.getPagePoint(c.scrollLeft-e.x,c.scrollTop-e.y),h=Math.round(l[0]),u=Math.round(l[1]);a+=","+h+","+u,this._location={pageNumber:o,scale:n,top:u,left:h,pdfOpenParams:a}}},{key:"update",value:function t(){var e=this._getVisiblePages(),r=e.views;if(0!==r.length){var i=Math.max(10,2*r.length+1);this._buffer.resize(i),this.renderingQueue.renderHighestPriority(e);for(var n=this._currentPageNumber,o=e.first,a=!1,s=0,c=r.length;s<c;++s){var l=r[s];if(l.percent<100)break;if(l.id===n){a=!0;break}}a||(n=r[0].id),this.isInPresentationMode||this._setCurrentPageNumber(n),this._updateLocation(o),this.eventBus.dispatch("updateviewarea",{source:this,location:this._location})}}},{key:"containsElement",value:function t(e){return this.container.contains(e)}},{key:"focus",value:function t(){this.container.focus()}},{key:"_getVisiblePages",value:function t(){if(!this.isInPresentationMode)return(0,l.getVisibleElements)(this.container,this._pages,!0);var e=[],r=this._pages[this._currentPageNumber-1];return e.push({id:r.id,view:r}),{first:r,last:r,views:e}}},{key:"cleanup",value:function t(){for(var e=0,r=this._pages.length;e<r;e++)this._pages[e]&&this._pages[e].renderingState!==h.RenderingStates.FINISHED&&this._pages[e].reset()}},{key:"_cancelRendering",value:function t(){for(var e=0,r=this._pages.length;e<r;e++)this._pages[e]&&this._pages[e].cancelRendering()}},{key:"_ensurePdfPageLoaded",value:function t(e){var r=this;if(e.pdfPage)return Promise.resolve(e.pdfPage);var i=e.id;if(this._pagesRequests[i])return this._pagesRequests[i];var n=this.pdfDocument.getPage(i).then(function(t){return e.pdfPage||e.setPdfPage(t),r._pagesRequests[i]=null,t});return this._pagesRequests[i]=n,n}},{key:"forceRendering",value:function t(e){var r=this,i=e||this._getVisiblePages(),n=this.renderingQueue.getHighestPriority(i,this._pages,this.scroll.down);return!!n&&(this._ensurePdfPageLoaded(n).then(function(){r.renderingQueue.renderView(n)}),!0)}},{key:"getPageTextContent",value:function t(e){return this.pdfDocument.getPage(e+1).then(function(t){return t.getTextContent({normalizeWhitespace:!0})})}},{key:"createTextLayerBuilder",value:function t(e,r,i){var n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return new g.TextLayerBuilder({textLayerDiv:e,eventBus:this.eventBus,pageIndex:r,viewport:i,findController:this.isInPresentationMode?null:this.findController,enhanceTextSelection:!this.isInPresentationMode&&n})}},{key:"createAnnotationLayerBuilder",value:function t(e,r){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:l.NullL10n;return new u.AnnotationLayerBuilder({pageDiv:e,pdfPage:r,renderInteractiveForms:i,linkService:this.linkService,downloadManager:this.downloadManager,l10n:n})}},{key:"setFindController",value:function t(e){this.findController=e}},{key:"getPagesOverview",value:function t(){var e=this._pages.map(function(t){var e=t.pdfPage.getViewport(1);return{width:e.width,height:e.height,rotation:e.rotation}});if(!this.enablePrintAutoRotate)return e;var r=a(e[0]);return e.map(function(t){return r===a(t)?t:{width:t.height,height:t.width,rotation:(t.rotation+90)%360}})}},{key:"pagesCount",get:function t(){return this._pages.length}},{key:"pageViewsReady",get:function t(){return this._pageViewsReady}},{key:"currentPageNumber",get:function t(){return this._currentPageNumber},set:function t(e){if((0|e)!==e)throw new Error("Invalid page number.");this.pdfDocument&&this._setCurrentPageNumber(e,!0)}},{key:"currentPageLabel",get:function t(){return this._pageLabels&&this._pageLabels[this._currentPageNumber-1]},set:function t(e){var r=0|e;if(this._pageLabels){var i=this._pageLabels.indexOf(e);i>=0&&(r=i+1)}this.currentPageNumber=r}},{key:"currentScale",get:function t(){return this._currentScale!==l.UNKNOWN_SCALE?this._currentScale:l.DEFAULT_SCALE},set:function t(e){if(isNaN(e))throw new Error("Invalid numeric scale");this.pdfDocument&&this._setScale(e,!1)}},{key:"currentScaleValue",get:function t(){return this._currentScaleValue},set:function t(e){this.pdfDocument&&this._setScale(e,!1)}},{key:"pagesRotation",get:function t(){return this._pagesRotation},set:function t(e){if("number"!=typeof e||e%90!=0)throw new Error("Invalid pages rotation angle.");if(this.pdfDocument){this._pagesRotation=e;for(var r=0,i=this._pages.length;r<i;r++){var n=this._pages[r];n.update(n.scale,e)}this._setScale(this._currentScaleValue,!0),this.defaultRenderingQueue&&this.update()}}},{key:"isInPresentationMode",get:function t(){return this.presentationModeState===v.FULLSCREEN}},{key:"isChangingPresentationMode",get:function t(){return this.presentationModeState===v.CHANGING}},{key:"isHorizontalScrollbarEnabled",get:function t(){return!this.isInPresentationMode&&this.container.scrollWidth>this.container.clientWidth}},{key:"hasEqualPageSizes",get:function t(){for(var e=this._pages[0],r=1,i=this._pages.length;r<i;++r){var n=this._pages[r];if(n.width!==e.width||n.height!==e.height)return!1}return!0}}]),t}();e.PresentationModeState=v,e.PDFViewer=b},function(t,e,r){"use strict";document.webL10n=function(t,e,r){function i(){return e.querySelectorAll('link[type="application/l10n"]')}function n(){var t=e.querySelector('script[type="application/l10n"]');return t?JSON.parse(t.innerHTML):null}function o(t){return t?t.querySelectorAll("*[data-l10n-id]"):[]}function a(t){if(!t)return{};var e=t.getAttribute("data-l10n-id"),r=t.getAttribute("data-l10n-args"),i={};if(r)try{i=JSON.parse(r)}catch(t){console.warn("could not parse arguments for #"+e)}return{id:e,args:i}}function s(t){var r=e.createEvent("Event");r.initEvent("localized",!0,!1),r.language=t,e.dispatchEvent(r)}function c(t,e,r){e=e||function t(e){},r=r||function t(){};var i=new XMLHttpRequest;i.open("GET",t,A),i.overrideMimeType&&i.overrideMimeType("text/plain; charset=utf-8"),i.onreadystatechange=function(){4==i.readyState&&(200==i.status||0===i.status?e(i.responseText):r())},i.onerror=r,i.ontimeout=r;try{i.send(null)}catch(t){r()}}function l(t,e,r,i){function n(t){return t.lastIndexOf("\\")<0?t:t.replace(/\\\\/g,"\\").replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\b/g,"\b").replace(/\\f/g,"\f").replace(/\\{/g,"{").replace(/\\}/g,"}").replace(/\\"/g,'"').replace(/\\'/g,"'")}function o(t,r){function i(t,r,i){function c(){for(;;){if(!p.length)return void i();var t=p.shift();if(!h.test(t)){if(r){if(b=u.exec(t)){g=b[1].toLowerCase(),m="*"!==g&&g!==e&&g!==v;continue}if(m)continue;if(b=f.exec(t))return void o(a+b[1],c)}var l=t.match(d);l&&3==l.length&&(s[l[1]]=n(l[2]))}}}var p=t.replace(l,"").split(/[\r\n]+/),g="*",v=e.split("-",1)[0],m=!1,b="";c()}function o(t,e){c(t,function(t){i(t,!1,e)},function(){console.warn(t+" not found."),e()})}var s={},l=/^\s*|\s*$/,h=/^\s*#|^\s*$/,u=/^\s*\[(.*)\]\s*$/,f=/^\s*@import\s+url\((.*)\)\s*$/i,d=/^([^=\s]*)\s*=\s*(.+)$/;i(t,!0,function(){r(s)})}var a=t.replace(/[^\/]*$/,"")||"./";c(t,function(t){_+=t,o(t,function(t){for(var e in t){var i,n,o=e.lastIndexOf(".");o>0?(i=e.substring(0,o),n=e.substr(o+1)):(i=e,n=w),y[i]||(y[i]={}),y[i][n]=t[e]}r&&r()})},i)}function h(t,e){function r(t){var e=t.href;this.load=function(t,r){l(e,t,r,function(){console.warn(e+" not found."),console.warn('"'+t+'" resource not found'),S="",r()})}}t&&(t=t.toLowerCase()),e=e||function t(){},u(),S=t;var o=i(),a=o.length;if(0===a){var c=n();if(c&&c.locales&&c.default_locale){if(console.log("using the embedded JSON directory, early way out"),!(y=c.locales[t])){var h=c.default_locale.toLowerCase();for(var f in c.locales){if((f=f.toLowerCase())===t){y=c.locales[t];break}f===h&&(y=c.locales[h])}}e()}else console.log("no resource to load, early way out");return s(t),void(C="complete")}var d=null,p=0;d=function r(){++p>=a&&(e(),s(t),C="complete")};for(var g=0;g<a;g++){new r(o[g]).load(t,d)}}function u(){y={},_="",S=""}function f(t){function e(t,e){return-1!==e.indexOf(t)}function r(t,e,r){return e<=t&&t<=r}var i={af:3,ak:4,am:4,ar:1,asa:3,az:0,be:11,bem:3,bez:3,bg:3,bh:4,bm:0,bn:3,bo:0,br:20,brx:3,bs:11,ca:3,cgg:3,chr:3,cs:12,cy:17,da:3,de:3,dv:3,dz:0,ee:3,el:3,en:3,eo:3,es:3,et:3,eu:3,fa:0,ff:5,fi:3,fil:4,fo:3,fr:5,fur:3,fy:3,ga:8,gd:24,gl:3,gsw:3,gu:3,guw:4,gv:23,ha:3,haw:3,he:2,hi:4,hr:11,hu:0,id:0,ig:0,ii:0,is:3,it:3,iu:7,ja:0,jmc:3,jv:0,ka:0,kab:5,kaj:3,kcg:3,kde:0,kea:0,kk:3,kl:3,km:0,kn:0,ko:0,ksb:3,ksh:21,ku:3,kw:7,lag:18,lb:3,lg:3,ln:4,lo:0,lt:10,lv:6,mas:3,mg:4,mk:16,ml:3,mn:3,mo:9,mr:3,ms:0,mt:15,my:0,nah:3,naq:7,nb:3,nd:3,ne:3,nl:3,nn:3,no:3,nr:3,nso:4,ny:3,nyn:3,om:3,or:3,pa:3,pap:3,pl:13,ps:3,pt:3,rm:3,ro:9,rof:3,ru:11,rwk:3,sah:0,saq:3,se:7,seh:3,ses:0,sg:0,sh:11,shi:19,sk:12,sl:14,sma:7,smi:7,smj:7,smn:7,sms:7,sn:3,so:3,sq:3,sr:11,ss:3,ssy:3,st:3,sv:3,sw:3,syr:3,ta:3,te:3,teo:3,th:0,ti:4,tig:3,tk:3,tl:4,tn:3,to:0,tr:0,ts:3,tzm:22,uk:11,ur:3,ve:3,vi:0,vun:3,wa:4,wae:3,wo:0,xh:3,xog:3,yo:0,zh:0,zu:3},n={0:function t(e){return"other"},1:function t(e){return r(e%100,3,10)?"few":0===e?"zero":r(e%100,11,99)?"many":2==e?"two":1==e?"one":"other"},2:function t(e){return 0!==e&&e%10==0?"many":2==e?"two":1==e?"one":"other"},3:function t(e){return 1==e?"one":"other"},4:function t(e){return r(e,0,1)?"one":"other"},5:function t(e){return r(e,0,2)&&2!=e?"one":"other"},6:function t(e){return 0===e?"zero":e%10==1&&e%100!=11?"one":"other"},7:function t(e){return 2==e?"two":1==e?"one":"other"},8:function t(e){return r(e,3,6)?"few":r(e,7,10)?"many":2==e?"two":1==e?"one":"other"},9:function t(e){return 0===e||1!=e&&r(e%100,1,19)?"few":1==e?"one":"other"},10:function t(e){return r(e%10,2,9)&&!r(e%100,11,19)?"few":e%10!=1||r(e%100,11,19)?"other":"one"},11:function t(e){return r(e%10,2,4)&&!r(e%100,12,14)?"few":e%10==0||r(e%10,5,9)||r(e%100,11,14)?"many":e%10==1&&e%100!=11?"one":"other"},12:function t(e){return r(e,2,4)?"few":1==e?"one":"other"},13:function t(e){return r(e%10,2,4)&&!r(e%100,12,14)?"few":1!=e&&r(e%10,0,1)||r(e%10,5,9)||r(e%100,12,14)?"many":1==e?"one":"other"},14:function t(e){return r(e%100,3,4)?"few":e%100==2?"two":e%100==1?"one":"other"},15:function t(e){return 0===e||r(e%100,2,10)?"few":r(e%100,11,19)?"many":1==e?"one":"other"},16:function t(e){return e%10==1&&11!=e?"one":"other"},17:function t(e){return 3==e?"few":0===e?"zero":6==e?"many":2==e?"two":1==e?"one":"other"},18:function t(e){return 0===e?"zero":r(e,0,2)&&0!==e&&2!=e?"one":"other"},19:function t(e){return r(e,2,10)?"few":r(e,0,1)?"one":"other"},20:function t(i){return!r(i%10,3,4)&&i%10!=9||r(i%100,10,19)||r(i%100,70,79)||r(i%100,90,99)?i%1e6==0&&0!==i?"many":i%10!=2||e(i%100,[12,72,92])?i%10!=1||e(i%100,[11,71,91])?"other":"one":"two":"few"},21:function t(e){return 0===e?"zero":1==e?"one":"other"},22:function t(e){return r(e,0,1)||r(e,11,99)?"one":"other"},23:function t(e){return r(e%10,1,2)||e%20==0?"one":"other"},24:function t(i){return r(i,3,10)||r(i,13,19)?"few":e(i,[2,12])?"two":e(i,[1,11])?"one":"other"}},o=i[t.replace(/-.*$/,"")];return o in n?n[o]:(console.warn("plural form unknown for ["+t+"]"),function(){return"other"})}function d(t,e,r){var i=y[t];if(!i){if(console.warn("#"+t+" is undefined."),!r)return null;i=r}var n={};for(var o in i){var a=i[o];a=p(a,e,t,o),a=g(a,e,t),n[o]=a}return n}function p(t,e,r,i){var n=/\{\[\s*([a-zA-Z]+)\(([a-zA-Z]+)\)\s*\]\}/,o=n.exec(t);if(!o||!o.length)return t;var a=o[1],s=o[2],c;if(e&&s in e?c=e[s]:s in y&&(c=y[s]),a in x){t=(0,x[a])(t,c,r,i)}return t}function g(t,e,r){var i=/\{\{\s*(.+?)\s*\}\}/g;return t.replace(i,function(t,i){return e&&i in e?e[i]:i in y?y[i]:(console.log("argument {{"+i+"}} for #"+r+" is undefined."),t)})}function v(t){var r=a(t);if(r.id){var i=d(r.id,r.args);if(!i)return void console.warn("#"+r.id+" is undefined.");if(i[w]){if(0===m(t))t[w]=i[w];else{for(var n=t.childNodes,o=!1,s=0,c=n.length;s<c;s++)3===n[s].nodeType&&/\S/.test(n[s].nodeValue)&&(o?n[s].nodeValue="":(n[s].nodeValue=i[w],o=!0));if(!o){var l=e.createTextNode(i[w]);t.insertBefore(l,t.firstChild)}}delete i[w]}for(var h in i)t[h]=i[h]}}function m(t){if(t.children)return t.children.length;if(void 0!==t.childElementCount)return t.childElementCount;for(var e=0,r=0;r<t.childNodes.length;r++)e+=1===t.nodeType?1:0;return e}function b(t){t=t||e.documentElement;for(var r=o(t),i=r.length,n=0;n<i;n++)v(r[n]);v(t)}var y={},_="",w="textContent",S="",x={},C="loading",A=!0;return x.plural=function(t,e,r,i){var n=parseFloat(e);if(isNaN(n))return t;if(i!=w)return t;x._pluralRules||(x._pluralRules=f(S));var o="["+x._pluralRules(n)+"]";return 0===n&&r+"[zero]"in y?t=y[r+"[zero]"][i]:1==n&&r+"[one]"in y?t=y[r+"[one]"][i]:2==n&&r+"[two]"in y?t=y[r+"[two]"][i]:r+o in y?t=y[r+o][i]:r+"[other]"in y&&(t=y[r+"[other]"][i]),t},{get:function t(e,r,i){var n=e.lastIndexOf("."),o=w;n>0&&(o=e.substr(n+1),e=e.substring(0,n));var a;i&&(a={},a[o]=i);var s=d(e,r,a);return s&&o in s?s[o]:"{{"+e+"}}"},getData:function t(){return y},getText:function t(){return _},getLanguage:function t(){return S},setLanguage:function t(e,r){h(e,function(){r&&r()})},getDirection:function t(){var e=["ar","he","fa","ps","ur"],r=S.split("-",1)[0];return e.indexOf(r)>=0?"rtl":"ltr"},translate:b,getReadyState:function t(){return C},ready:function r(i){i&&("complete"==C||"interactive"==C?t.setTimeout(function(){i()}):e.addEventListener&&e.addEventListener("localized",function t(){e.removeEventListener("localized",t),i()}))}}}(window,document)},function(t,e,r){"use strict";var i=r(0),n=r(12),o=r(5),a=r(3),s=r(6),c=r(4),l=r(11),h=r(10),u=r(1),f=r(8),d=r(9),p=i.PDFJS;p.PDFViewer=n.PDFViewer,p.PDFPageView=o.PDFPageView,p.PDFLinkService=a.PDFLinkService,p.TextLayerBuilder=s.TextLayerBuilder,p.DefaultTextLayerFactory=s.DefaultTextLayerFactory,p.AnnotationLayerBuilder=c.AnnotationLayerBuilder,p.DefaultAnnotationLayerFactory=c.DefaultAnnotationLayerFactory,p.PDFHistory=l.PDFHistory,p.PDFFindController=h.PDFFindController,p.EventBus=u.EventBus,p.DownloadManager=f.DownloadManager,p.ProgressBar=u.ProgressBar,p.GenericL10n=d.GenericL10n,p.NullL10n=u.NullL10n,e.PDFJS=p}])})},function(t,e,r){"use strict";function i(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===t[e-2]?2:"="===t[e-1]?1:0}function n(t){return 3*t.length/4-i(t)}function o(t){var e,r,n,o,a,s=t.length;o=i(t),a=new u(3*s/4-o),r=o>0?s-4:s;var c=0;for(e=0;e<r;e+=4)n=h[t.charCodeAt(e)]<<18|h[t.charCodeAt(e+1)]<<12|h[t.charCodeAt(e+2)]<<6|h[t.charCodeAt(e+3)],a[c++]=n>>16&255,a[c++]=n>>8&255,a[c++]=255&n;return 2===o?(n=h[t.charCodeAt(e)]<<2|h[t.charCodeAt(e+1)]>>4,a[c++]=255&n):1===o&&(n=h[t.charCodeAt(e)]<<10|h[t.charCodeAt(e+1)]<<4|h[t.charCodeAt(e+2)]>>2,a[c++]=n>>8&255,a[c++]=255&n),a}function a(t){return l[t>>18&63]+l[t>>12&63]+l[t>>6&63]+l[63&t]}function s(t,e,r){for(var i,n=[],o=e;o<r;o+=3)i=(t[o]<<16)+(t[o+1]<<8)+t[o+2],n.push(a(i));return n.join("")}function c(t){for(var e,r=t.length,i=r%3,n="",o=[],a=16383,c=0,h=r-i;c<h;c+=16383)o.push(s(t,c,c+16383>h?h:c+16383));return 1===i?(e=t[r-1],n+=l[e>>2],n+=l[e<<4&63],n+="=="):2===i&&(e=(t[r-2]<<8)+t[r-1],n+=l[e>>10],n+=l[e>>4&63],n+=l[e<<2&63],n+="="),o.push(n),o.join("")}e.byteLength=n,e.toByteArray=o,e.fromByteArray=c;for(var l=[],h=[],u="undefined"!=typeof Uint8Array?Uint8Array:Array,f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",d=0,p=f.length;d<p;++d)l[d]=f[d],h[f.charCodeAt(d)]=d;h["-".charCodeAt(0)]=62,h["_".charCodeAt(0)]=63},function(t,e){e.read=function(t,e,r,i,n){var o,a,s=8*n-i-1,c=(1<<s)-1,l=c>>1,h=-7,u=r?n-1:0,f=r?-1:1,d=t[e+u];for(u+=f,o=d&(1<<-h)-1,d>>=-h,h+=s;h>0;o=256*o+t[e+u],u+=f,h-=8);for(a=o&(1<<-h)-1,o>>=-h,h+=i;h>0;a=256*a+t[e+u],u+=f,h-=8);if(0===o)o=1-l;else{if(o===c)return a?NaN:1/0*(d?-1:1);a+=Math.pow(2,i),o-=l}return(d?-1:1)*a*Math.pow(2,o-i)},e.write=function(t,e,r,i,n,o){var a,s,c,l=8*o-n-1,h=(1<<l)-1,u=h>>1,f=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,d=i?0:o-1,p=i?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,a=h):(a=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-a))<1&&(a--,c*=2),e+=a+u>=1?f/c:f*Math.pow(2,1-u),e*c>=2&&(a++,c/=2),a+u>=h?(s=0,a=h):a+u>=1?(s=(e*c-1)*Math.pow(2,n),a+=u):(s=e*Math.pow(2,u-1)*Math.pow(2,n),a=0));n>=8;t[r+d]=255&s,d+=p,s/=256,n-=8);for(a=a<<n|s,l+=n;l>0;t[r+d]=255&a,d+=p,a/=256,l-=8);t[r+d-p]|=128*g}},function(t,e,r){(function(t,i){function n(e,r,i){function n(){for(var t;null!==(t=e.read());)s.push(t),c+=t.length;e.once("readable",n)}function o(t){e.removeListener("end",a),e.removeListener("readable",n),i(t)}function a(){var r=t.concat(s,c);s=[],i(null,r),e.close()}var s=[],c=0;e.on("error",o),e.on("end",a),e.end(r),n()}function o(e,r){if("string"==typeof r&&(r=new t(r)),!t.isBuffer(r))throw new TypeError("Not a string or buffer");var i=g.Z_FINISH;return e._processChunk(r,i)}function a(t){if(!(this instanceof a))return new a(t);d.call(this,t,g.DEFLATE)}function s(t){if(!(this instanceof s))return new s(t);d.call(this,t,g.INFLATE)}function c(t){if(!(this instanceof c))return new c(t);d.call(this,t,g.GZIP)}function l(t){if(!(this instanceof l))return new l(t);d.call(this,t,g.GUNZIP)}function h(t){if(!(this instanceof h))return new h(t);d.call(this,t,g.DEFLATERAW)}function u(t){if(!(this instanceof u))return new u(t);d.call(this,t,g.INFLATERAW)}function f(t){if(!(this instanceof f))return new f(t);d.call(this,t,g.UNZIP)}function d(r,i){if(this._opts=r=r||{},this._chunkSize=r.chunkSize||e.Z_DEFAULT_CHUNK,p.call(this,r),r.flush&&r.flush!==g.Z_NO_FLUSH&&r.flush!==g.Z_PARTIAL_FLUSH&&r.flush!==g.Z_SYNC_FLUSH&&r.flush!==g.Z_FULL_FLUSH&&r.flush!==g.Z_FINISH&&r.flush!==g.Z_BLOCK)throw new Error("Invalid flush flag: "+r.flush);if(this._flushFlag=r.flush||g.Z_NO_FLUSH,r.chunkSize&&(r.chunkSize<e.Z_MIN_CHUNK||r.chunkSize>e.Z_MAX_CHUNK))throw new Error("Invalid chunk size: "+r.chunkSize);if(r.windowBits&&(r.windowBits<e.Z_MIN_WINDOWBITS||r.windowBits>e.Z_MAX_WINDOWBITS))throw new Error("Invalid windowBits: "+r.windowBits);if(r.level&&(r.level<e.Z_MIN_LEVEL||r.level>e.Z_MAX_LEVEL))throw new Error("Invalid compression level: "+r.level);if(r.memLevel&&(r.memLevel<e.Z_MIN_MEMLEVEL||r.memLevel>e.Z_MAX_MEMLEVEL))throw new Error("Invalid memLevel: "+r.memLevel);if(r.strategy&&r.strategy!=e.Z_FILTERED&&r.strategy!=e.Z_HUFFMAN_ONLY&&r.strategy!=e.Z_RLE&&r.strategy!=e.Z_FIXED&&r.strategy!=e.Z_DEFAULT_STRATEGY)throw new Error("Invalid strategy: "+r.strategy);if(r.dictionary&&!t.isBuffer(r.dictionary))throw new Error("Invalid dictionary: it should be a Buffer instance");this._binding=new g.Zlib(i);var n=this;this._hadError=!1,this._binding.onerror=function(t,r){n._binding=null,n._hadError=!0;var i=new Error(t);i.errno=r,i.code=e.codes[r],n.emit("error",i)};var o=e.Z_DEFAULT_COMPRESSION;"number"==typeof r.level&&(o=r.level);var a=e.Z_DEFAULT_STRATEGY;"number"==typeof r.strategy&&(a=r.strategy),this._binding.init(r.windowBits||e.Z_DEFAULT_WINDOWBITS,o,r.memLevel||e.Z_DEFAULT_MEMLEVEL,a,r.dictionary),this._buffer=new t(this._chunkSize),this._offset=0,this._closed=!1,this._level=o,this._strategy=a,this.once("end",this.close)}var p=r(43),g=r(50),v=r(24),m=r(60).ok;g.Z_MIN_WINDOWBITS=8,g.Z_MAX_WINDOWBITS=15,g.Z_DEFAULT_WINDOWBITS=15,g.Z_MIN_CHUNK=64,g.Z_MAX_CHUNK=1/0,g.Z_DEFAULT_CHUNK=16384,g.Z_MIN_MEMLEVEL=1,g.Z_MAX_MEMLEVEL=9,g.Z_DEFAULT_MEMLEVEL=8,g.Z_MIN_LEVEL=-1,g.Z_MAX_LEVEL=9,g.Z_DEFAULT_LEVEL=g.Z_DEFAULT_COMPRESSION,Object.keys(g).forEach(function(t){t.match(/^Z/)&&(e[t]=g[t])}),e.codes={Z_OK:g.Z_OK,Z_STREAM_END:g.Z_STREAM_END,Z_NEED_DICT:g.Z_NEED_DICT,Z_ERRNO:g.Z_ERRNO,Z_STREAM_ERROR:g.Z_STREAM_ERROR,Z_DATA_ERROR:g.Z_DATA_ERROR,Z_MEM_ERROR:g.Z_MEM_ERROR,Z_BUF_ERROR:g.Z_BUF_ERROR,Z_VERSION_ERROR:g.Z_VERSION_ERROR},Object.keys(e.codes).forEach(function(t){e.codes[e.codes[t]]=t}),e.Deflate=a,e.Inflate=s,e.Gzip=c,e.Gunzip=l,e.DeflateRaw=h,e.InflateRaw=u,e.Unzip=f,e.createDeflate=function(t){return new a(t)},e.createInflate=function(t){return new s(t)},e.createDeflateRaw=function(t){return new h(t)},e.createInflateRaw=function(t){return new u(t)},e.createGzip=function(t){return new c(t)},e.createGunzip=function(t){return new l(t)},e.createUnzip=function(t){return new f(t)},e.deflate=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new a(e),t,r)},e.deflateSync=function(t,e){return o(new a(e),t)},e.gzip=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new c(e),t,r)},e.gzipSync=function(t,e){return o(new c(e),t)},e.deflateRaw=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new h(e),t,r)},e.deflateRawSync=function(t,e){return o(new h(e),t)},e.unzip=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new f(e),t,r)},e.unzipSync=function(t,e){return o(new f(e),t)},e.inflate=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new s(e),t,r)},e.inflateSync=function(t,e){return o(new s(e),t)},e.gunzip=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new l(e),t,r)},e.gunzipSync=function(t,e){return o(new l(e),t)},e.inflateRaw=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new u(e),t,r)},e.inflateRawSync=function(t,e){return o(new u(e),t)},v.inherits(d,p),d.prototype.params=function(t,r,n){if(t<e.Z_MIN_LEVEL||t>e.Z_MAX_LEVEL)throw new RangeError("Invalid compression level: "+t);if(r!=e.Z_FILTERED&&r!=e.Z_HUFFMAN_ONLY&&r!=e.Z_RLE&&r!=e.Z_FIXED&&r!=e.Z_DEFAULT_STRATEGY)throw new TypeError("Invalid strategy: "+r);if(this._level!==t||this._strategy!==r){var o=this;this.flush(g.Z_SYNC_FLUSH,function(){o._binding.params(t,r),o._hadError||(o._level=t,o._strategy=r,n&&n())})}else i.nextTick(n)},d.prototype.reset=function(){return this._binding.reset()},d.prototype._flush=function(e){this._transform(new t(0),"",e)},d.prototype.flush=function(e,r){var n=this._writableState;if(("function"==typeof e||void 0===e&&!r)&&(r=e,e=g.Z_FULL_FLUSH),n.ended)r&&i.nextTick(r);else if(n.ending)r&&this.once("end",r);else if(n.needDrain){var o=this;this.once("drain",function(){o.flush(r)})}else this._flushFlag=e,this.write(new t(0),"",r)},d.prototype.close=function(t){if(t&&i.nextTick(t),!this._closed){this._closed=!0,this._binding.close();var e=this;i.nextTick(function(){e.emit("close")})}},d.prototype._transform=function(e,r,i){var n,o=this._writableState,a=o.ending||o.ended,s=a&&(!e||o.length===e.length);if(null===!e&&!t.isBuffer(e))return i(new Error("invalid input"));s?n=g.Z_FINISH:(n=this._flushFlag,e.length>=o.length&&(this._flushFlag=this._opts.flush||g.Z_NO_FLUSH));var c=this;this._processChunk(e,n,i)},d.prototype._processChunk=function(e,r,i){function n(f,d){if(!c._hadError){var p=a-d;if(m(p>=0,"have should not go down"),p>0){var g=c._buffer.slice(c._offset,c._offset+p);c._offset+=p,l?c.push(g):(h.push(g),u+=g.length)}if((0===d||c._offset>=c._chunkSize)&&(a=c._chunkSize,c._offset=0,c._buffer=new t(c._chunkSize)),0===d){if(s+=o-f,o=f,!l)return!0;var v=c._binding.write(r,e,s,o,c._buffer,c._offset,c._chunkSize);return v.callback=n,void(v.buffer=e)}if(!l)return!1;i()}}var o=e&&e.length,a=this._chunkSize-this._offset,s=0,c=this,l="function"==typeof i;if(!l){var h=[],u=0,f;this.on("error",function(t){f=t});do{var d=this._binding.writeSync(r,e,s,o,this._buffer,this._offset,a)}while(!this._hadError&&n(d[0],d[1]));if(this._hadError)throw f;var p=t.concat(h,u);return this.close(),p}var g=this._binding.write(r,e,s,o,this._buffer,this._offset,a);g.buffer=e,g.callback=n},v.inherits(a,d),v.inherits(s,d),v.inherits(c,d),v.inherits(l,d),v.inherits(h,d),v.inherits(u,d),v.inherits(f,d)}).call(e,r(2).Buffer,r(1))},function(t,e,r){t.exports=r(9).Transform},function(t,e){},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e,r){t.copy(e,r)}var o=r(10).Buffer;t.exports=function(){function t(){i(this,t),this.head=null,this.tail=null,this.length=0}return t.prototype.push=function t(e){var r={data:e,next:null};this.length>0?this.tail.next=r:this.head=r,this.tail=r,++this.length},t.prototype.unshift=function t(e){var r={data:e,next:this.head};0===this.length&&(this.tail=r),this.head=r,++this.length},t.prototype.shift=function t(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},t.prototype.clear=function t(){this.head=this.tail=null,this.length=0},t.prototype.join=function t(e){if(0===this.length)return"";for(var r=this.head,i=""+r.data;r=r.next;)i+=e+r.data;return i},t.prototype.concat=function t(e){if(0===this.length)return o.alloc(0);if(1===this.length)return this.head.data;for(var r=o.allocUnsafe(e>>>0),i=this.head,a=0;i;)n(i.data,r,a),a+=i.data.length,i=i.next;return r},t}()},function(t,e,r){function i(t,e){this._id=t,this._clearFn=e}var n=Function.prototype.apply;e.setTimeout=function(){return new i(n.call(setTimeout,window,arguments),clearTimeout)},e.setInterval=function(){return new i(n.call(setInterval,window,arguments),clearInterval)},e.clearTimeout=e.clearInterval=function(t){t&&t.close()},i.prototype.unref=i.prototype.ref=function(){},i.prototype.close=function(){this._clearFn.call(window,this._id)},e.enroll=function(t,e){clearTimeout(t._idleTimeoutId),t._idleTimeout=e},e.unenroll=function(t){clearTimeout(t._idleTimeoutId),t._idleTimeout=-1},e._unrefActive=e.active=function(t){clearTimeout(t._idleTimeoutId);var e=t._idleTimeout;e>=0&&(t._idleTimeoutId=setTimeout(function e(){t._onTimeout&&t._onTimeout()},e))},r(47),e.setImmediate=setImmediate,e.clearImmediate=clearImmediate},function(t,e,r){(function(t,e){!function(t,r){"use strict";function i(t){"function"!=typeof t&&(t=new Function(""+t));for(var e=new Array(arguments.length-1),r=0;r<e.length;r++)e[r]=arguments[r+1];var i={callback:t,args:e};return p[d]=i,m(d),d++}function n(t){delete p[t]}function o(t){var e=t.callback,i=t.args;switch(i.length){case 0:e();break;case 1:e(i[0]);break;case 2:e(i[0],i[1]);break;case 3:e(i[0],i[1],i[2]);break;default:e.apply(r,i)}}function a(t){if(g)setTimeout(a,0,t);else{var e=p[t];if(e){g=!0;try{o(e)}finally{n(t),g=!1}}}}function s(){m=function(t){e.nextTick(function(){a(t)})}}function c(){if(t.postMessage&&!t.importScripts){var e=!0,r=t.onmessage;return t.onmessage=function(){e=!1},t.postMessage("","*"),t.onmessage=r,e}}function l(){var e="setImmediate$"+Math.random()+"$",r=function(r){r.source===t&&"string"==typeof r.data&&0===r.data.indexOf(e)&&a(+r.data.slice(e.length))};t.addEventListener?t.addEventListener("message",r,!1):t.attachEvent("onmessage",r),m=function(r){t.postMessage(e+r,"*")}}function h(){var t=new MessageChannel;t.port1.onmessage=function(t){a(t.data)},m=function(e){t.port2.postMessage(e)}}function u(){var t=v.documentElement;m=function(e){var r=v.createElement("script");r.onreadystatechange=function(){a(e),r.onreadystatechange=null,t.removeChild(r),r=null},t.appendChild(r)}}function f(){m=function(t){setTimeout(a,0,t)}}if(!t.setImmediate){var d=1,p={},g=!1,v=t.document,m,b=Object.getPrototypeOf&&Object.getPrototypeOf(t);b=b&&b.setTimeout?b:t,"[object process]"==={}.toString.call(t.process)?s():c()?l():t.MessageChannel?h():v&&"onreadystatechange"in v.createElement("script")?u():f(),b.setImmediate=i,b.clearImmediate=n}}("undefined"==typeof self?void 0===t?this:t:self)}).call(e,r(0),r(1))},function(t,e,r){(function(e){function r(t,e){function r(){if(!n){if(i("throwDeprecation"))throw new Error(e);i("traceDeprecation")?console.trace(e):console.warn(e),n=!0}return t.apply(this,arguments)}if(i("noDeprecation"))return t;var n=!1;return r}function i(t){try{if(!e.localStorage)return!1}catch(t){return!1}var r=e.localStorage[t];return null!=r&&"true"===String(r).toLowerCase()}t.exports=r}).call(e,r(0))},function(t,e,r){"use strict";function i(t){if(!(this instanceof i))return new i(t);n.call(this,t)}t.exports=i;var n=r(20),o=r(5);o.inherits=r(3),o.inherits(i,n),i.prototype._transform=function(t,e,r){r(null,t)}},function(t,e,r){(function(t,i){function n(t){if(t<e.DEFLATE||t>e.UNZIP)throw new TypeError("Bad argument");this.mode=t,this.init_done=!1,this.write_in_progress=!1,this.pending_close=!1,this.windowBits=0,this.level=0,this.memLevel=0,this.strategy=0,this.dictionary=null}function o(t,e){for(var r=0;r<t.length;r++)this[e+r]=t[r]}var a=r(21),s=r(51),c=r(52),l=r(54),h=r(57);for(var u in h)e[u]=h[u];e.NONE=0,e.DEFLATE=1,e.INFLATE=2,e.GZIP=3,e.GUNZIP=4,e.DEFLATERAW=5,e.INFLATERAW=6,e.UNZIP=7,n.prototype.init=function(t,r,i,n,o){switch(this.windowBits=t,this.level=r,this.memLevel=i,this.strategy=n,this.mode!==e.GZIP&&this.mode!==e.GUNZIP||(this.windowBits+=16),this.mode===e.UNZIP&&(this.windowBits+=32),this.mode!==e.DEFLATERAW&&this.mode!==e.INFLATERAW||(this.windowBits=-this.windowBits),this.strm=new s,this.mode){case e.DEFLATE:case e.GZIP:case e.DEFLATERAW:var a=c.deflateInit2(this.strm,this.level,e.Z_DEFLATED,this.windowBits,this.memLevel,this.strategy);break;case e.INFLATE:case e.GUNZIP:case e.INFLATERAW:case e.UNZIP:var a=l.inflateInit2(this.strm,this.windowBits);break;default:throw new Error("Unknown mode "+this.mode)}if(a!==e.Z_OK)return void this._error(a);this.write_in_progress=!1,this.init_done=!0},n.prototype.params=function(){throw new Error("deflateParams Not supported")},n.prototype._writeCheck=function(){if(!this.init_done)throw new Error("write before init");if(this.mode===e.NONE)throw new Error("already finalized");if(this.write_in_progress)throw new Error("write already in progress");if(this.pending_close)throw new Error("close is pending")},n.prototype.write=function(e,r,i,n,o,a,s){this._writeCheck(),this.write_in_progress=!0;var c=this;return t.nextTick(function(){c.write_in_progress=!1;var t=c._write(e,r,i,n,o,a,s);c.callback(t[0],t[1]),c.pending_close&&c.close()}),this},n.prototype.writeSync=function(t,e,r,i,n,o,a){return this._writeCheck(),this._write(t,e,r,i,n,o,a)},n.prototype._write=function(t,r,n,a,s,h,u){if(this.write_in_progress=!0,t!==e.Z_NO_FLUSH&&t!==e.Z_PARTIAL_FLUSH&&t!==e.Z_SYNC_FLUSH&&t!==e.Z_FULL_FLUSH&&t!==e.Z_FINISH&&t!==e.Z_BLOCK)throw new Error("Invalid flush value");null==r&&(r=new i(0),a=0,n=0),s._set?s.set=s._set:s.set=o;var f=this.strm;switch(f.avail_in=a,f.input=r,f.next_in=n,f.avail_out=u,f.output=s,f.next_out=h,this.mode){case e.DEFLATE:case e.GZIP:case e.DEFLATERAW:var d=c.deflate(f,t);break;case e.UNZIP:case e.INFLATE:case e.GUNZIP:case e.INFLATERAW:var d=l.inflate(f,t);break;default:throw new Error("Unknown mode "+this.mode)}return d!==e.Z_STREAM_END&&d!==e.Z_OK&&this._error(d),this.write_in_progress=!1,[f.avail_in,f.avail_out]},n.prototype.close=function(){if(this.write_in_progress)return void(this.pending_close=!0);this.pending_close=!1,this.mode===e.DEFLATE||this.mode===e.GZIP||this.mode===e.DEFLATERAW?c.deflateEnd(this.strm):l.inflateEnd(this.strm),this.mode=e.NONE},n.prototype.reset=function(){switch(this.mode){case e.DEFLATE:case e.DEFLATERAW:var t=c.deflateReset(this.strm);break;case e.INFLATE:case e.INFLATERAW:var t=l.inflateReset(this.strm)}t!==e.Z_OK&&this._error(t)},n.prototype._error=function(t){this.onerror(a[t]+": "+this.strm.msg,t),this.write_in_progress=!1,this.pending_close&&this.close()},e.Zlib=n}).call(e,r(1),r(2).Buffer)},function(t,e,r){"use strict";function i(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}t.exports=i},function(t,e,r){"use strict";function i(t,e){return t.msg=D[e],e}function n(t){return(t<<1)-(t>4?9:0)}function o(t){for(var e=t.length;--e>=0;)t[e]=0}function a(t){var e=t.state,r=e.pending;r>t.avail_out&&(r=t.avail_out),0!==r&&(E.arraySet(t.output,e.pending_buf,e.pending_out,r,t.next_out),t.next_out+=r,e.pending_out+=r,t.total_out+=r,t.avail_out-=r,e.pending-=r,0===e.pending&&(e.pending_out=0))}function s(t,e){O._tr_flush_block(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,a(t.strm)}function c(t,e){t.pending_buf[t.pending++]=e}function l(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e}function h(t,e,r,i){var n=t.avail_in;return n>i&&(n=i),0===n?0:(t.avail_in-=n,E.arraySet(e,t.input,t.next_in,n,r),1===t.state.wrap?t.adler=R(t.adler,e,n,r):2===t.state.wrap&&(t.adler=L(t.adler,e,n,r)),t.next_in+=n,t.total_in+=n,n)}function u(t,e){var r=t.max_chain_length,i=t.strstart,n,o,a=t.prev_length,s=t.nice_match,c=t.strstart>t.w_size-ht?t.strstart-(t.w_size-ht):0,l=t.window,h=t.w_mask,u=t.prev,f=t.strstart+lt,d=l[i+a-1],p=l[i+a];t.prev_length>=t.good_match&&(r>>=2),s>t.lookahead&&(s=t.lookahead);do{if(n=e,l[n+a]===p&&l[n+a-1]===d&&l[n]===l[i]&&l[++n]===l[i+1]){i+=2,n++;do{}while(l[++i]===l[++n]&&l[++i]===l[++n]&&l[++i]===l[++n]&&l[++i]===l[++n]&&l[++i]===l[++n]&&l[++i]===l[++n]&&l[++i]===l[++n]&&l[++i]===l[++n]&&i<f);if(o=lt-(f-i),i=f-lt,o>a){if(t.match_start=e,a=o,o>=s)break;d=l[i+a-1],p=l[i+a]}}}while((e=u[e&h])>c&&0!=--r);return a<=t.lookahead?a:t.lookahead}function f(t){var e=t.w_size,r,i,n,o,a;do{if(o=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-ht)){E.arraySet(t.window,t.window,e,e,0),t.match_start-=e,t.strstart-=e,t.block_start-=e,i=t.hash_size,r=i;do{n=t.head[--r],t.head[r]=n>=e?n-e:0}while(--i);i=e,r=i;do{n=t.prev[--r],t.prev[r]=n>=e?n-e:0}while(--i);o+=e}if(0===t.strm.avail_in)break;if(i=h(t.strm,t.window,t.strstart+t.lookahead,o),t.lookahead+=i,t.lookahead+t.insert>=ct)for(a=t.strstart-t.insert,t.ins_h=t.window[a],t.ins_h=(t.ins_h<<t.hash_shift^t.window[a+1])&t.hash_mask;t.insert&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[a+ct-1])&t.hash_mask,t.prev[a&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=a,a++,t.insert--,!(t.lookahead+t.insert<ct)););}while(t.lookahead<ht&&0!==t.strm.avail_in)}function d(t,e){var r=65535;for(r>t.pending_buf_size-5&&(r=t.pending_buf_size-5);;){if(t.lookahead<=1){if(f(t),0===t.lookahead&&e===I)return yt;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;var i=t.block_start+r;if((0===t.strstart||t.strstart>=i)&&(t.lookahead=t.strstart-i,t.strstart=i,s(t,!1),0===t.strm.avail_out))return yt;if(t.strstart-t.block_start>=t.w_size-ht&&(s(t,!1),0===t.strm.avail_out))return yt}return t.insert=0,e===F?(s(t,!0),0===t.strm.avail_out?wt:St):(t.strstart>t.block_start&&(s(t,!1),t.strm.avail_out),yt)}function p(t,e){for(var r,i;;){if(t.lookahead<ht){if(f(t),t.lookahead<ht&&e===I)return yt;if(0===t.lookahead)break}if(r=0,t.lookahead>=ct&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+ct-1])&t.hash_mask,r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==r&&t.strstart-r<=t.w_size-ht&&(t.match_length=u(t,r)),t.match_length>=ct)if(i=O._tr_tally(t,t.strstart-t.match_start,t.match_length-ct),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=ct){t.match_length--;do{t.strstart++,t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+ct-1])&t.hash_mask,r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!=--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+1])&t.hash_mask;else i=O._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(i&&(s(t,!1),0===t.strm.avail_out))return yt}return t.insert=t.strstart<ct-1?t.strstart:ct-1,e===F?(s(t,!0),0===t.strm.avail_out?wt:St):t.last_lit&&(s(t,!1),0===t.strm.avail_out)?yt:_t}function g(t,e){for(var r,i,n;;){if(t.lookahead<ht){if(f(t),t.lookahead<ht&&e===I)return yt;if(0===t.lookahead)break}if(r=0,t.lookahead>=ct&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+ct-1])&t.hash_mask,r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=ct-1,0!==r&&t.prev_length<t.max_lazy_match&&t.strstart-r<=t.w_size-ht&&(t.match_length=u(t,r),t.match_length<=5&&(t.strategy===G||t.match_length===ct&&t.strstart-t.match_start>4096)&&(t.match_length=ct-1)),t.prev_length>=ct&&t.match_length<=t.prev_length){n=t.strstart+t.lookahead-ct,i=O._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-ct),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=n&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+ct-1])&t.hash_mask,r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!=--t.prev_length);if(t.match_available=0,t.match_length=ct-1,t.strstart++,i&&(s(t,!1),0===t.strm.avail_out))return yt}else if(t.match_available){if(i=O._tr_tally(t,0,t.window[t.strstart-1]),i&&s(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return yt}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(i=O._tr_tally(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<ct-1?t.strstart:ct-1,e===F?(s(t,!0),0===t.strm.avail_out?wt:St):t.last_lit&&(s(t,!1),0===t.strm.avail_out)?yt:_t}function v(t,e){for(var r,i,n,o,a=t.window;;){if(t.lookahead<=lt){if(f(t),t.lookahead<=lt&&e===I)return yt;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=ct&&t.strstart>0&&(n=t.strstart-1,(i=a[n])===a[++n]&&i===a[++n]&&i===a[++n])){o=t.strstart+lt;do{}while(i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&n<o);t.match_length=lt-(o-n),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=ct?(r=O._tr_tally(t,1,t.match_length-ct),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(r=O._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),r&&(s(t,!1),0===t.strm.avail_out))return yt}return t.insert=0,e===F?(s(t,!0),0===t.strm.avail_out?wt:St):t.last_lit&&(s(t,!1),0===t.strm.avail_out)?yt:_t}function m(t,e){for(var r;;){if(0===t.lookahead&&(f(t),0===t.lookahead)){if(e===I)return yt;break}if(t.match_length=0,r=O._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,r&&(s(t,!1),0===t.strm.avail_out))return yt}return t.insert=0,e===F?(s(t,!0),0===t.strm.avail_out?wt:St):t.last_lit&&(s(t,!1),0===t.strm.avail_out)?yt:_t}function b(t,e,r,i,n){this.good_length=t,this.max_lazy=e,this.nice_length=r,this.max_chain=i,this.func=n}function y(t){t.window_size=2*t.w_size,o(t.head),t.max_lazy_match=Ct[t.level].max_lazy,t.good_match=Ct[t.level].good_length,t.nice_match=Ct[t.level].nice_length,t.max_chain_length=Ct[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=ct-1,t.match_available=0,t.ins_h=0}function _(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=K,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new E.Buf16(2*at),this.dyn_dtree=new E.Buf16(2*(2*nt+1)),this.bl_tree=new E.Buf16(2*(2*ot+1)),o(this.dyn_ltree),o(this.dyn_dtree),o(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new E.Buf16(st+1),this.heap=new E.Buf16(2*it+1),o(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new E.Buf16(2*it+1),o(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function w(t){var e;return t&&t.state?(t.total_in=t.total_out=0,t.data_type=J,e=t.state,e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?ft:mt,t.adler=2===e.wrap?0:1,e.last_flush=I,O._tr_init(e),B):i(t,z)}function S(t){var e=w(t);return e===B&&y(t.state),e}function x(t,e){return t&&t.state?2!==t.state.wrap?z:(t.state.gzhead=e,B):z}function C(t,e,r,n,o,a){if(!t)return z;var s=1;if(e===X&&(e=6),n<0?(s=0,n=-n):n>15&&(s=2,n-=16),o<1||o>Q||r!==K||n<8||n>15||e<0||e>9||a<0||a>V)return i(t,z);8===n&&(n=9);var c=new _;return t.state=c,c.strm=t,c.wrap=s,c.gzhead=null,c.w_bits=n,c.w_size=1<<c.w_bits,c.w_mask=c.w_size-1,c.hash_bits=o+7,c.hash_size=1<<c.hash_bits,c.hash_mask=c.hash_size-1,c.hash_shift=~~((c.hash_bits+ct-1)/ct),c.window=new E.Buf8(2*c.w_size),c.head=new E.Buf16(c.hash_size),c.prev=new E.Buf16(c.w_size),c.lit_bufsize=1<<o+6,c.pending_buf_size=4*c.lit_bufsize,c.pending_buf=new E.Buf8(c.pending_buf_size),c.d_buf=1*c.lit_bufsize,c.l_buf=3*c.lit_bufsize,c.level=e,c.strategy=a,c.method=r,S(t)}function A(t,e){return C(t,e,K,$,tt,Z)}function T(t,e){var r,s,h,u;if(!t||!t.state||e>N||e<0)return t?i(t,z):z;if(s=t.state,!t.output||!t.input&&0!==t.avail_in||s.status===bt&&e!==F)return i(t,0===t.avail_out?q:z);if(s.strm=t,r=s.last_flush,s.last_flush=e,s.status===ft)if(2===s.wrap)t.adler=0,c(s,31),c(s,139),c(s,8),s.gzhead?(c(s,(s.gzhead.text?1:0)+(s.gzhead.hcrc?2:0)+(s.gzhead.extra?4:0)+(s.gzhead.name?8:0)+(s.gzhead.comment?16:0)),c(s,255&s.gzhead.time),c(s,s.gzhead.time>>8&255),c(s,s.gzhead.time>>16&255),c(s,s.gzhead.time>>24&255),c(s,9===s.level?2:s.strategy>=H||s.level<2?4:0),c(s,255&s.gzhead.os),s.gzhead.extra&&s.gzhead.extra.length&&(c(s,255&s.gzhead.extra.length),c(s,s.gzhead.extra.length>>8&255)),s.gzhead.hcrc&&(t.adler=L(t.adler,s.pending_buf,s.pending,0)),s.gzindex=0,s.status=dt):(c(s,0),c(s,0),c(s,0),c(s,0),c(s,0),c(s,9===s.level?2:s.strategy>=H||s.level<2?4:0),c(s,xt),s.status=mt);else{var f=K+(s.w_bits-8<<4)<<8,d=-1;d=s.strategy>=H||s.level<2?0:s.level<6?1:6===s.level?2:3,f|=d<<6,0!==s.strstart&&(f|=ut),f+=31-f%31,s.status=mt,l(s,f),0!==s.strstart&&(l(s,t.adler>>>16),l(s,65535&t.adler)),t.adler=1}if(s.status===dt)if(s.gzhead.extra){for(h=s.pending;s.gzindex<(65535&s.gzhead.extra.length)&&(s.pending!==s.pending_buf_size||(s.gzhead.hcrc&&s.pending>h&&(t.adler=L(t.adler,s.pending_buf,s.pending-h,h)),a(t),h=s.pending,s.pending!==s.pending_buf_size));)c(s,255&s.gzhead.extra[s.gzindex]),s.gzindex++;s.gzhead.hcrc&&s.pending>h&&(t.adler=L(t.adler,s.pending_buf,s.pending-h,h)),s.gzindex===s.gzhead.extra.length&&(s.gzindex=0,s.status=pt)}else s.status=pt;if(s.status===pt)if(s.gzhead.name){h=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>h&&(t.adler=L(t.adler,s.pending_buf,s.pending-h,h)),a(t),h=s.pending,s.pending===s.pending_buf_size)){u=1;break}u=s.gzindex<s.gzhead.name.length?255&s.gzhead.name.charCodeAt(s.gzindex++):0,c(s,u)}while(0!==u);s.gzhead.hcrc&&s.pending>h&&(t.adler=L(t.adler,s.pending_buf,s.pending-h,h)),0===u&&(s.gzindex=0,s.status=gt)}else s.status=gt;if(s.status===gt)if(s.gzhead.comment){h=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>h&&(t.adler=L(t.adler,s.pending_buf,s.pending-h,h)),a(t),h=s.pending,s.pending===s.pending_buf_size)){u=1;break}u=s.gzindex<s.gzhead.comment.length?255&s.gzhead.comment.charCodeAt(s.gzindex++):0,c(s,u)}while(0!==u);s.gzhead.hcrc&&s.pending>h&&(t.adler=L(t.adler,s.pending_buf,s.pending-h,h)),0===u&&(s.status=vt)}else s.status=vt;if(s.status===vt&&(s.gzhead.hcrc?(s.pending+2>s.pending_buf_size&&a(t),s.pending+2<=s.pending_buf_size&&(c(s,255&t.adler),c(s,t.adler>>8&255),t.adler=0,s.status=mt)):s.status=mt),0!==s.pending){if(a(t),0===t.avail_out)return s.last_flush=-1,B}else if(0===t.avail_in&&n(e)<=n(r)&&e!==F)return i(t,q);if(s.status===bt&&0!==t.avail_in)return i(t,q);if(0!==t.avail_in||0!==s.lookahead||e!==I&&s.status!==bt){var p=s.strategy===H?m(s,e):s.strategy===Y?v(s,e):Ct[s.level].func(s,e);if(p!==wt&&p!==St||(s.status=bt),p===yt||p===wt)return 0===t.avail_out&&(s.last_flush=-1),B;if(p===_t&&(e===j?O._tr_align(s):e!==N&&(O._tr_stored_block(s,0,0,!1),e===M&&(o(s.head),0===s.lookahead&&(s.strstart=0,s.block_start=0,s.insert=0))),a(t),0===t.avail_out))return s.last_flush=-1,B}return e!==F?B:s.wrap<=0?U:(2===s.wrap?(c(s,255&t.adler),c(s,t.adler>>8&255),c(s,t.adler>>16&255),c(s,t.adler>>24&255),c(s,255&t.total_in),c(s,t.total_in>>8&255),c(s,t.total_in>>16&255),c(s,t.total_in>>24&255)):(l(s,t.adler>>>16),l(s,65535&t.adler)),a(t),s.wrap>0&&(s.wrap=-s.wrap),0!==s.pending?B:U)}function k(t){var e;return t&&t.state?(e=t.state.status)!==ft&&e!==dt&&e!==pt&&e!==gt&&e!==vt&&e!==mt&&e!==bt?i(t,z):(t.state=null,e===mt?i(t,W):B):z}function P(t,e){var r=e.length,i,n,a,s,c,l,h,u;if(!t||!t.state)return z;if(i=t.state,2===(s=i.wrap)||1===s&&i.status!==ft||i.lookahead)return z;for(1===s&&(t.adler=R(t.adler,e,r,0)),i.wrap=0,r>=i.w_size&&(0===s&&(o(i.head),i.strstart=0,i.block_start=0,i.insert=0),u=new E.Buf8(i.w_size),E.arraySet(u,e,r-i.w_size,i.w_size,0),e=u,r=i.w_size),c=t.avail_in,l=t.next_in,h=t.input,t.avail_in=r,t.next_in=0,t.input=e,f(i);i.lookahead>=ct;){n=i.strstart,a=i.lookahead-(ct-1);do{i.ins_h=(i.ins_h<<i.hash_shift^i.window[n+ct-1])&i.hash_mask,i.prev[n&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=n,n++}while(--a);i.strstart=n,i.lookahead=ct-1,f(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=ct-1,i.match_available=0,t.next_in=l,t.input=h,t.avail_in=c,i.wrap=s,B}var E=r(8),O=r(53),R=r(22),L=r(23),D=r(21),I=0,j=1,M=3,F=4,N=5,B=0,U=1,z=-2,W=-3,q=-5,X=-1,G=1,H=2,Y=3,V=4,Z=0,J=2,K=8,Q=9,$=15,tt=8,et=29,rt=256,it=286,nt=30,ot=19,at=2*it+1,st=15,ct=3,lt=258,ht=lt+ct+1,ut=32,ft=42,dt=69,pt=73,gt=91,vt=103,mt=113,bt=666,yt=1,_t=2,wt=3,St=4,xt=3,Ct;Ct=[new b(0,0,0,0,d),new b(4,4,8,4,p),new b(4,5,16,8,p),new b(4,6,32,32,p),new b(4,4,16,16,g),new b(8,16,32,32,g),new b(8,16,128,128,g),new b(8,32,128,256,g),new b(32,128,258,1024,g),new b(32,258,258,4096,g)],e.deflateInit=A,e.deflateInit2=C,e.deflateReset=S,e.deflateResetKeep=w,e.deflateSetHeader=x,e.deflate=T,e.deflateEnd=k,e.deflateSetDictionary=P,e.deflateInfo="pako deflate (from Nodeca project)"},function(t,e,r){"use strict";function i(t){for(var e=t.length;--e>=0;)t[e]=0}function n(t,e,r,i,n){this.static_tree=t,this.extra_bits=e,this.extra_base=r,this.elems=i,this.max_length=n,this.has_stree=t&&t.length}function o(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}function a(t){return t<256?ct[t]:ct[256+(t>>>7)]}function s(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255}function c(t,e,r){t.bi_valid>Z-r?(t.bi_buf|=e<<t.bi_valid&65535,s(t,t.bi_buf),t.bi_buf=e>>Z-t.bi_valid,t.bi_valid+=r-Z):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=r)}function l(t,e,r){c(t,r[2*e],r[2*e+1])}function h(t,e){var r=0;do{r|=1&t,t>>>=1,r<<=1}while(--e>0);return r>>>1}function u(t){16===t.bi_valid?(s(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)}function f(t,e){var r=e.dyn_tree,i=e.max_code,n=e.stat_desc.static_tree,o=e.stat_desc.has_stree,a=e.stat_desc.extra_bits,s=e.stat_desc.extra_base,c=e.stat_desc.max_length,l,h,u,f,d,p,g=0;for(f=0;f<=V;f++)t.bl_count[f]=0;for(r[2*t.heap[t.heap_max]+1]=0,l=t.heap_max+1;l<Y;l++)h=t.heap[l],f=r[2*r[2*h+1]+1]+1,f>c&&(f=c,g++),r[2*h+1]=f,h>i||(t.bl_count[f]++,d=0,h>=s&&(d=a[h-s]),p=r[2*h],t.opt_len+=p*(f+d),o&&(t.static_len+=p*(n[2*h+1]+d)));if(0!==g){do{for(f=c-1;0===t.bl_count[f];)f--;t.bl_count[f]--,t.bl_count[f+1]+=2,t.bl_count[c]--,g-=2}while(g>0);for(f=c;0!==f;f--)for(h=t.bl_count[f];0!==h;)(u=t.heap[--l])>i||(r[2*u+1]!==f&&(t.opt_len+=(f-r[2*u+1])*r[2*u],r[2*u+1]=f),h--)}}function d(t,e,r){var i=new Array(V+1),n=0,o,a;for(o=1;o<=V;o++)i[o]=n=n+r[o-1]<<1;for(a=0;a<=e;a++){var s=t[2*a+1];0!==s&&(t[2*a]=h(i[s]++,s))}}function p(){var t,e,r,i,o,a=new Array(V+1);for(r=0,i=0;i<W-1;i++)for(ht[i]=r,t=0;t<1<<et[i];t++)lt[r++]=i;for(lt[r-1]=i,o=0,i=0;i<16;i++)for(ut[i]=o,t=0;t<1<<rt[i];t++)ct[o++]=i;for(o>>=7;i<G;i++)for(ut[i]=o<<7,t=0;t<1<<rt[i]-7;t++)ct[256+o++]=i;for(e=0;e<=V;e++)a[e]=0;for(t=0;t<=143;)at[2*t+1]=8,t++,a[8]++;for(;t<=255;)at[2*t+1]=9,t++,a[9]++;for(;t<=279;)at[2*t+1]=7,t++,a[7]++;for(;t<=287;)at[2*t+1]=8,t++,a[8]++;for(d(at,X+1,a),t=0;t<G;t++)st[2*t+1]=5,st[2*t]=h(t,5);ft=new n(at,et,q+1,X,V),dt=new n(st,rt,0,G,V),pt=new n(new Array(0),it,0,H,J)}function g(t){var e;for(e=0;e<X;e++)t.dyn_ltree[2*e]=0;for(e=0;e<G;e++)t.dyn_dtree[2*e]=0;for(e=0;e<H;e++)t.bl_tree[2*e]=0;t.dyn_ltree[2*K]=1,t.opt_len=t.static_len=0,t.last_lit=t.matches=0}function v(t){t.bi_valid>8?s(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0}function m(t,e,r,i){v(t),i&&(s(t,r),s(t,~r)),L.arraySet(t.pending_buf,t.window,e,r,t.pending),t.pending+=r}function b(t,e,r,i){var n=2*e,o=2*r;return t[n]<t[o]||t[n]===t[o]&&i[e]<=i[r]}function y(t,e,r){for(var i=t.heap[r],n=r<<1;n<=t.heap_len&&(n<t.heap_len&&b(e,t.heap[n+1],t.heap[n],t.depth)&&n++,!b(e,i,t.heap[n],t.depth));)t.heap[r]=t.heap[n],r=n,n<<=1;t.heap[r]=i}function _(t,e,r){var i,n,o=0,s,h;if(0!==t.last_lit)do{i=t.pending_buf[t.d_buf+2*o]<<8|t.pending_buf[t.d_buf+2*o+1],n=t.pending_buf[t.l_buf+o],o++,0===i?l(t,n,e):(s=lt[n],l(t,s+q+1,e),h=et[s],0!==h&&(n-=ht[s],c(t,n,h)),i--,s=a(i),l(t,s,r),0!==(h=rt[s])&&(i-=ut[s],c(t,i,h)))}while(o<t.last_lit);l(t,K,e)}function w(t,e){var r=e.dyn_tree,i=e.stat_desc.static_tree,n=e.stat_desc.has_stree,o=e.stat_desc.elems,a,s,c=-1,l;for(t.heap_len=0,t.heap_max=Y,a=0;a<o;a++)0!==r[2*a]?(t.heap[++t.heap_len]=c=a,t.depth[a]=0):r[2*a+1]=0;for(;t.heap_len<2;)l=t.heap[++t.heap_len]=c<2?++c:0,r[2*l]=1,t.depth[l]=0,t.opt_len--,n&&(t.static_len-=i[2*l+1]);for(e.max_code=c,a=t.heap_len>>1;a>=1;a--)y(t,r,a);l=o;do{a=t.heap[1],t.heap[1]=t.heap[t.heap_len--],y(t,r,1),s=t.heap[1],t.heap[--t.heap_max]=a,t.heap[--t.heap_max]=s,r[2*l]=r[2*a]+r[2*s],t.depth[l]=(t.depth[a]>=t.depth[s]?t.depth[a]:t.depth[s])+1,r[2*a+1]=r[2*s+1]=l,t.heap[1]=l++,y(t,r,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],f(t,e),d(r,c,t.bl_count)}function S(t,e,r){var i,n=-1,o,a=e[1],s=0,c=7,l=4;for(0===a&&(c=138,l=3),e[2*(r+1)+1]=65535,i=0;i<=r;i++)o=a,a=e[2*(i+1)+1],++s<c&&o===a||(s<l?t.bl_tree[2*o]+=s:0!==o?(o!==n&&t.bl_tree[2*o]++,t.bl_tree[2*Q]++):s<=10?t.bl_tree[2*$]++:t.bl_tree[2*tt]++,s=0,n=o,0===a?(c=138,l=3):o===a?(c=6,l=3):(c=7,l=4))}function x(t,e,r){var i,n=-1,o,a=e[1],s=0,h=7,u=4;for(0===a&&(h=138,u=3),i=0;i<=r;i++)if(o=a,a=e[2*(i+1)+1],!(++s<h&&o===a)){if(s<u)do{l(t,o,t.bl_tree)}while(0!=--s);else 0!==o?(o!==n&&(l(t,o,t.bl_tree),s--),l(t,Q,t.bl_tree),c(t,s-3,2)):s<=10?(l(t,$,t.bl_tree),c(t,s-3,3)):(l(t,tt,t.bl_tree),c(t,s-11,7));s=0,n=o,0===a?(h=138,u=3):o===a?(h=6,u=3):(h=7,u=4)}}function C(t){var e;for(S(t,t.dyn_ltree,t.l_desc.max_code),S(t,t.dyn_dtree,t.d_desc.max_code),w(t,t.bl_desc),e=H-1;e>=3&&0===t.bl_tree[2*nt[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e}function A(t,e,r,i){var n;for(c(t,e-257,5),c(t,r-1,5),c(t,i-4,4),n=0;n<i;n++)c(t,t.bl_tree[2*nt[n]+1],3);x(t,t.dyn_ltree,e-1),x(t,t.dyn_dtree,r-1)}function T(t){var e=4093624447,r;for(r=0;r<=31;r++,e>>>=1)if(1&e&&0!==t.dyn_ltree[2*r])return I;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return j;for(r=32;r<q;r++)if(0!==t.dyn_ltree[2*r])return j;return I}function k(t){gt||(p(),gt=!0),t.l_desc=new o(t.dyn_ltree,ft),t.d_desc=new o(t.dyn_dtree,dt),t.bl_desc=new o(t.bl_tree,pt),t.bi_buf=0,t.bi_valid=0,g(t)}function P(t,e,r,i){c(t,(F<<1)+(i?1:0),3),m(t,e,r,!0)}function E(t){c(t,N<<1,3),l(t,K,at),u(t)}function O(t,e,r,i){var n,o,a=0;t.level>0?(t.strm.data_type===M&&(t.strm.data_type=T(t)),w(t,t.l_desc),w(t,t.d_desc),a=C(t),n=t.opt_len+3+7>>>3,(o=t.static_len+3+7>>>3)<=n&&(n=o)):n=o=r+5,r+4<=n&&-1!==e?P(t,e,r,i):t.strategy===D||o===n?(c(t,(N<<1)+(i?1:0),3),_(t,at,st)):(c(t,(B<<1)+(i?1:0),3),A(t,t.l_desc.max_code+1,t.d_desc.max_code+1,a+1),_(t,t.dyn_ltree,t.dyn_dtree)),g(t),i&&v(t)}function R(t,e,r){return t.pending_buf[t.d_buf+2*t.last_lit]=e>>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&r,t.last_lit++,0===e?t.dyn_ltree[2*r]++:(t.matches++,e--,t.dyn_ltree[2*(lt[r]+q+1)]++,t.dyn_dtree[2*a(e)]++),t.last_lit===t.lit_bufsize-1}var L=r(8),D=4,I=0,j=1,M=2,F=0,N=1,B=2,U=3,z=258,W=29,q=256,X=q+1+W,G=30,H=19,Y=2*X+1,V=15,Z=16,J=7,K=256,Q=16,$=17,tt=18,et=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],rt=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],it=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],nt=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],ot=512,at=new Array(2*(X+2));i(at);var st=new Array(2*G);i(st);var ct=new Array(512);i(ct);var lt=new Array(256);i(lt);var ht=new Array(W);i(ht);var ut=new Array(G);i(ut);var ft,dt,pt,gt=!1;e._tr_init=k,e._tr_stored_block=P,e._tr_flush_block=O,e._tr_tally=R,e._tr_align=E},function(t,e,r){"use strict";function i(t){return(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24)}function n(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new v.Buf16(320),this.work=new v.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function o(t){var e;return t&&t.state?(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=j,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new v.Buf32(dt),e.distcode=e.distdyn=new v.Buf32(pt),e.sane=1,e.back=-1,k):O}function a(t){var e;return t&&t.state?(e=t.state,e.wsize=0,e.whave=0,e.wnext=0,o(t)):O}function s(t,e){var r,i;return t&&t.state?(i=t.state,e<0?(r=0,e=-e):(r=1+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?O:(null!==i.window&&i.wbits!==e&&(i.window=null),i.wrap=r,i.wbits=e,a(t))):O}function c(t,e){var r,i;return t?(i=new n,t.state=i,i.window=null,r=s(t,e),r!==k&&(t.state=null),r):O}function l(t){return c(t,vt)}function h(t){if(mt){var e;for(bt=new v.Buf32(512),yt=new v.Buf32(32),e=0;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(_(S,t.lens,0,288,bt,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;_(x,t.lens,0,32,yt,0,t.work,{bits:5}),mt=!1}t.lencode=bt,t.lenbits=9,t.distcode=yt,t.distbits=5}function u(t,e,r,i){var n,o=t.state;return null===o.window&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new v.Buf8(o.wsize)),i>=o.wsize?(v.arraySet(o.window,e,r-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(n=o.wsize-o.wnext,n>i&&(n=i),v.arraySet(o.window,e,r-i,n,o.wnext),i-=n,i?(v.arraySet(o.window,e,r-i,i,0),o.wnext=i,o.whave=o.wsize):(o.wnext+=n,o.wnext===o.wsize&&(o.wnext=0),o.whave<o.wsize&&(o.whave+=n))),0}function f(t,e){var r,n,o,a,s,c,l,f,d,p,g,dt,pt,gt,vt=0,mt,bt,yt,_t,wt,St,xt,Ct,At=new v.Buf8(4),Tt,kt,Pt=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!t||!t.state||!t.output||!t.input&&0!==t.avail_in)return O;r=t.state,r.mode===H&&(r.mode=Y),s=t.next_out,o=t.output,l=t.avail_out,a=t.next_in,n=t.input,c=t.avail_in,f=r.hold,d=r.bits,p=c,g=l,Ct=k;t:for(;;)switch(r.mode){case j:if(0===r.wrap){r.mode=Y;break}for(;d<16;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(2&r.wrap&&35615===f){r.check=0,At[0]=255&f,At[1]=f>>>8&255,r.check=b(r.check,At,2,0),f=0,d=0,r.mode=M;break}if(r.flags=0,r.head&&(r.head.done=!1),!(1&r.wrap)||(((255&f)<<8)+(f>>8))%31){t.msg="incorrect header check",r.mode=ht;break}if((15&f)!==I){t.msg="unknown compression method",r.mode=ht;break}if(f>>>=4,d-=4,xt=8+(15&f),0===r.wbits)r.wbits=xt;else if(xt>r.wbits){t.msg="invalid window size",r.mode=ht;break}r.dmax=1<<xt,t.adler=r.check=1,r.mode=512&f?X:H,f=0,d=0;break;case M:for(;d<16;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(r.flags=f,(255&r.flags)!==I){t.msg="unknown compression method",r.mode=ht;break}if(57344&r.flags){t.msg="unknown header flags set",r.mode=ht;break}r.head&&(r.head.text=f>>8&1),512&r.flags&&(At[0]=255&f,At[1]=f>>>8&255,r.check=b(r.check,At,2,0)),f=0,d=0,r.mode=F;case F:for(;d<32;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}r.head&&(r.head.time=f),512&r.flags&&(At[0]=255&f,At[1]=f>>>8&255,At[2]=f>>>16&255,At[3]=f>>>24&255,r.check=b(r.check,At,4,0)),f=0,d=0,r.mode=N;case N:for(;d<16;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}r.head&&(r.head.xflags=255&f,r.head.os=f>>8),512&r.flags&&(At[0]=255&f,At[1]=f>>>8&255,r.check=b(r.check,At,2,0)),f=0,d=0,r.mode=B;case B:if(1024&r.flags){for(;d<16;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}r.length=f,r.head&&(r.head.extra_len=f),512&r.flags&&(At[0]=255&f,At[1]=f>>>8&255,r.check=b(r.check,At,2,0)),f=0,d=0}else r.head&&(r.head.extra=null);r.mode=U;case U:if(1024&r.flags&&(dt=r.length,dt>c&&(dt=c),dt&&(r.head&&(xt=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),v.arraySet(r.head.extra,n,a,dt,xt)),512&r.flags&&(r.check=b(r.check,n,dt,a)),c-=dt,a+=dt,r.length-=dt),r.length))break t;r.length=0,r.mode=z;case z:if(2048&r.flags){if(0===c)break t;dt=0;do{xt=n[a+dt++],r.head&&xt&&r.length<65536&&(r.head.name+=String.fromCharCode(xt))}while(xt&&dt<c);if(512&r.flags&&(r.check=b(r.check,n,dt,a)),c-=dt,a+=dt,xt)break t}else r.head&&(r.head.name=null);r.length=0,r.mode=W;case W:if(4096&r.flags){if(0===c)break t;dt=0;do{xt=n[a+dt++],r.head&&xt&&r.length<65536&&(r.head.comment+=String.fromCharCode(xt))}while(xt&&dt<c);if(512&r.flags&&(r.check=b(r.check,n,dt,a)),c-=dt,a+=dt,xt)break t}else r.head&&(r.head.comment=null);r.mode=q;case q:if(512&r.flags){for(;d<16;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(f!==(65535&r.check)){t.msg="header crc mismatch",r.mode=ht;break}f=0,d=0}r.head&&(r.head.hcrc=r.flags>>9&1,r.head.done=!0),t.adler=r.check=0,r.mode=H;break;case X:for(;d<32;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}t.adler=r.check=i(f),f=0,d=0,r.mode=G;case G:if(0===r.havedict)return t.next_out=s,t.avail_out=l,t.next_in=a,t.avail_in=c,r.hold=f,r.bits=d,E;t.adler=r.check=1,r.mode=H;case H:if(e===A||e===T)break t;case Y:if(r.last){f>>>=7&d,d-=7&d,r.mode=st;break}for(;d<3;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}switch(r.last=1&f,f>>>=1,d-=1,3&f){case 0:r.mode=V;break;case 1:if(h(r),r.mode=tt,e===T){f>>>=2,d-=2;break t}break;case 2:r.mode=K;break;case 3:t.msg="invalid block type",r.mode=ht}f>>>=2,d-=2;break;case V:for(f>>>=7&d,d-=7&d;d<32;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if((65535&f)!=(f>>>16^65535)){t.msg="invalid stored block lengths",r.mode=ht;break}if(r.length=65535&f,f=0,d=0,r.mode=Z,e===T)break t;case Z:r.mode=J;case J:if(dt=r.length){if(dt>c&&(dt=c),dt>l&&(dt=l),0===dt)break t;v.arraySet(o,n,a,dt,s),c-=dt,a+=dt,l-=dt,s+=dt,r.length-=dt;break}r.mode=H;break;case K:for(;d<14;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(r.nlen=257+(31&f),f>>>=5,d-=5,r.ndist=1+(31&f),f>>>=5,d-=5,r.ncode=4+(15&f),f>>>=4,d-=4,r.nlen>286||r.ndist>30){t.msg="too many length or distance symbols",r.mode=ht;break}r.have=0,r.mode=Q;case Q:for(;r.have<r.ncode;){for(;d<3;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}r.lens[Pt[r.have++]]=7&f,f>>>=3,d-=3}for(;r.have<19;)r.lens[Pt[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,Tt={bits:r.lenbits},Ct=_(w,r.lens,0,19,r.lencode,0,r.work,Tt),r.lenbits=Tt.bits,Ct){t.msg="invalid code lengths set",r.mode=ht;break}r.have=0,r.mode=$;case $:for(;r.have<r.nlen+r.ndist;){for(;vt=r.lencode[f&(1<<r.lenbits)-1],mt=vt>>>24,bt=vt>>>16&255,yt=65535&vt,!(mt<=d);){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(yt<16)f>>>=mt,d-=mt,r.lens[r.have++]=yt;else{if(16===yt){for(kt=mt+2;d<kt;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(f>>>=mt,d-=mt,0===r.have){t.msg="invalid bit length repeat",r.mode=ht;break}xt=r.lens[r.have-1],dt=3+(3&f),f>>>=2,d-=2}else if(17===yt){for(kt=mt+3;d<kt;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}f>>>=mt,d-=mt,xt=0,dt=3+(7&f),f>>>=3,d-=3}else{for(kt=mt+7;d<kt;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}f>>>=mt,d-=mt,xt=0,dt=11+(127&f),f>>>=7,d-=7}if(r.have+dt>r.nlen+r.ndist){t.msg="invalid bit length repeat",r.mode=ht;break}for(;dt--;)r.lens[r.have++]=xt}}if(r.mode===ht)break;if(0===r.lens[256]){t.msg="invalid code -- missing end-of-block",r.mode=ht;break}if(r.lenbits=9,Tt={bits:r.lenbits},Ct=_(S,r.lens,0,r.nlen,r.lencode,0,r.work,Tt),r.lenbits=Tt.bits,Ct){t.msg="invalid literal/lengths set",r.mode=ht;break}if(r.distbits=6,r.distcode=r.distdyn,Tt={bits:r.distbits},Ct=_(x,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,Tt),r.distbits=Tt.bits,Ct){t.msg="invalid distances set",r.mode=ht;break}if(r.mode=tt,e===T)break t;case tt:r.mode=et;case et:if(c>=6&&l>=258){t.next_out=s,t.avail_out=l,t.next_in=a,t.avail_in=c,r.hold=f,r.bits=d,y(t,g),s=t.next_out,o=t.output,l=t.avail_out,a=t.next_in,n=t.input,c=t.avail_in,f=r.hold,d=r.bits,r.mode===H&&(r.back=-1);break}for(r.back=0;vt=r.lencode[f&(1<<r.lenbits)-1],mt=vt>>>24,bt=vt>>>16&255,yt=65535&vt,!(mt<=d);){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(bt&&0==(240&bt)){for(_t=mt,wt=bt,St=yt;vt=r.lencode[St+((f&(1<<_t+wt)-1)>>_t)],mt=vt>>>24,bt=vt>>>16&255,yt=65535&vt,!(_t+mt<=d);){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}f>>>=_t,d-=_t,r.back+=_t}if(f>>>=mt,d-=mt,r.back+=mt,r.length=yt,0===bt){r.mode=at;break}if(32&bt){r.back=-1,r.mode=H;break}if(64&bt){t.msg="invalid literal/length code",r.mode=ht;break}r.extra=15&bt,r.mode=rt;case rt:if(r.extra){for(kt=r.extra;d<kt;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}r.length+=f&(1<<r.extra)-1,f>>>=r.extra,d-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=it;case it:for(;vt=r.distcode[f&(1<<r.distbits)-1],mt=vt>>>24,bt=vt>>>16&255,yt=65535&vt,!(mt<=d);){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(0==(240&bt)){for(_t=mt,wt=bt,St=yt;vt=r.distcode[St+((f&(1<<_t+wt)-1)>>_t)],mt=vt>>>24,bt=vt>>>16&255,yt=65535&vt,!(_t+mt<=d);){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}f>>>=_t,d-=_t,r.back+=_t}if(f>>>=mt,d-=mt,r.back+=mt,64&bt){t.msg="invalid distance code",r.mode=ht;break}r.offset=yt,r.extra=15&bt,r.mode=nt;case nt:if(r.extra){for(kt=r.extra;d<kt;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}r.offset+=f&(1<<r.extra)-1,f>>>=r.extra,d-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){t.msg="invalid distance too far back",r.mode=ht;break}r.mode=ot;case ot:if(0===l)break t;if(dt=g-l,r.offset>dt){if((dt=r.offset-dt)>r.whave&&r.sane){t.msg="invalid distance too far back",r.mode=ht;break}dt>r.wnext?(dt-=r.wnext,pt=r.wsize-dt):pt=r.wnext-dt,dt>r.length&&(dt=r.length),gt=r.window}else gt=o,pt=s-r.offset,dt=r.length;dt>l&&(dt=l),l-=dt,r.length-=dt;do{o[s++]=gt[pt++]}while(--dt);0===r.length&&(r.mode=et);break;case at:if(0===l)break t;o[s++]=r.length,l--,r.mode=et;break;case st:if(r.wrap){for(;d<32;){if(0===c)break t;c--,f|=n[a++]<<d,d+=8}if(g-=l,t.total_out+=g,r.total+=g,g&&(t.adler=r.check=r.flags?b(r.check,o,g,s-g):m(r.check,o,g,s-g)),g=l,(r.flags?f:i(f))!==r.check){t.msg="incorrect data check",r.mode=ht;break}f=0,d=0}r.mode=ct;case ct:if(r.wrap&&r.flags){for(;d<32;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(f!==(4294967295&r.total)){t.msg="incorrect length check",r.mode=ht;break}f=0,d=0}r.mode=lt;case lt:Ct=P;break t;case ht:Ct=R;break t;case ut:return L;case ft:default:return O}return t.next_out=s,t.avail_out=l,t.next_in=a,t.avail_in=c,r.hold=f,r.bits=d,(r.wsize||g!==t.avail_out&&r.mode<ht&&(r.mode<st||e!==C))&&u(t,t.output,t.next_out,g-t.avail_out)?(r.mode=ut,L):(p-=t.avail_in,g-=t.avail_out,t.total_in+=p,t.total_out+=g,r.total+=g,r.wrap&&g&&(t.adler=r.check=r.flags?b(r.check,o,g,t.next_out-g):m(r.check,o,g,t.next_out-g)),t.data_type=r.bits+(r.last?64:0)+(r.mode===H?128:0)+(r.mode===tt||r.mode===Z?256:0),(0===p&&0===g||e===C)&&Ct===k&&(Ct=D),Ct)}function d(t){if(!t||!t.state)return O;var e=t.state;return e.window&&(e.window=null),t.state=null,k}function p(t,e){var r;return t&&t.state?(r=t.state,0==(2&r.wrap)?O:(r.head=e,e.done=!1,k)):O}function g(t,e){var r=e.length,i,n,o;return t&&t.state?(i=t.state,0!==i.wrap&&i.mode!==G?O:i.mode===G&&(n=1,(n=m(n,e,r,0))!==i.check)?R:(o=u(t,e,r,r))?(i.mode=ut,L):(i.havedict=1,k)):O}var v=r(8),m=r(22),b=r(23),y=r(55),_=r(56),w=0,S=1,x=2,C=4,A=5,T=6,k=0,P=1,E=2,O=-2,R=-3,L=-4,D=-5,I=8,j=1,M=2,F=3,N=4,B=5,U=6,z=7,W=8,q=9,X=10,G=11,H=12,Y=13,V=14,Z=15,J=16,K=17,Q=18,$=19,tt=20,et=21,rt=22,it=23,nt=24,ot=25,at=26,st=27,ct=28,lt=29,ht=30,ut=31,ft=32,dt=852,pt=592,gt=15,vt=15,mt=!0,bt,yt;e.inflateReset=a,e.inflateReset2=s,e.inflateResetKeep=o,e.inflateInit=l,e.inflateInit2=c,e.inflate=f,e.inflateEnd=d,e.inflateGetHeader=p,e.inflateSetDictionary=g,e.inflateInfo="pako inflate (from Nodeca project)"},function(t,e,r){"use strict";var i=30,n=12;t.exports=function t(e,r){var i,n,o,a,s,c,l,h,u,f,d,p,g,v,m,b,y,_,w,S,x,C,A,T,k;i=e.state,n=e.next_in,T=e.input,o=n+(e.avail_in-5),a=e.next_out,k=e.output,s=a-(r-e.avail_out),c=a+(e.avail_out-257),l=i.dmax,h=i.wsize,u=i.whave,f=i.wnext,d=i.window,p=i.hold,g=i.bits,v=i.lencode,m=i.distcode,b=(1<<i.lenbits)-1,y=(1<<i.distbits)-1;t:do{g<15&&(p+=T[n++]<<g,g+=8,p+=T[n++]<<g,g+=8),_=v[p&b];e:for(;;){if(w=_>>>24,p>>>=w,g-=w,0===(w=_>>>16&255))k[a++]=65535&_;else{if(!(16&w)){if(0==(64&w)){_=v[(65535&_)+(p&(1<<w)-1)];continue e}if(32&w){i.mode=12;break t}e.msg="invalid literal/length code",i.mode=30;break t}S=65535&_,w&=15,w&&(g<w&&(p+=T[n++]<<g,g+=8),S+=p&(1<<w)-1,p>>>=w,g-=w),g<15&&(p+=T[n++]<<g,g+=8,p+=T[n++]<<g,g+=8),_=m[p&y];r:for(;;){if(w=_>>>24,p>>>=w,g-=w,!(16&(w=_>>>16&255))){if(0==(64&w)){_=m[(65535&_)+(p&(1<<w)-1)];continue r}e.msg="invalid distance code",i.mode=30;break t}if(x=65535&_,w&=15,g<w&&(p+=T[n++]<<g,(g+=8)<w&&(p+=T[n++]<<g,g+=8)),(x+=p&(1<<w)-1)>l){e.msg="invalid distance too far back",i.mode=30;break t}if(p>>>=w,g-=w,w=a-s,x>w){if((w=x-w)>u&&i.sane){e.msg="invalid distance too far back",i.mode=30;break t}if(C=0,A=d,0===f){if(C+=h-w,w<S){S-=w;do{k[a++]=d[C++]}while(--w);C=a-x,A=k}}else if(f<w){if(C+=h+f-w,(w-=f)<S){S-=w;do{k[a++]=d[C++]}while(--w);if(C=0,f<S){w=f,S-=w;do{k[a++]=d[C++]}while(--w);C=a-x,A=k}}}else if(C+=f-w,w<S){S-=w;do{k[a++]=d[C++]}while(--w);C=a-x,A=k}for(;S>2;)k[a++]=A[C++],k[a++]=A[C++],k[a++]=A[C++],S-=3;S&&(k[a++]=A[C++],S>1&&(k[a++]=A[C++]))}else{C=a-x;do{k[a++]=k[C++],k[a++]=k[C++],k[a++]=k[C++],S-=3}while(S>2);S&&(k[a++]=k[C++],S>1&&(k[a++]=k[C++]))}break}}break}}while(n<o&&a<c);S=g>>3,n-=S,g-=S<<3,p&=(1<<g)-1,e.next_in=n,e.next_out=a,e.avail_in=n<o?o-n+5:5-(n-o),e.avail_out=a<c?c-a+257:257-(a-c),i.hold=p,i.bits=g}},function(t,e,r){"use strict";var i=r(8),n=15,o=852,a=592,s=0,c=1,l=2,h=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],u=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],f=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],d=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function t(e,r,n,o,a,s,c,l){var p=l.bits,g=0,v=0,m=0,b=0,y=0,_=0,w=0,S=0,x=0,C=0,A,T,k,P,E,O=null,R=0,L,D=new i.Buf16(16),I=new i.Buf16(16),j=null,M=0,F,N,B;for(g=0;g<=15;g++)D[g]=0;for(v=0;v<o;v++)D[r[n+v]]++;for(y=p,b=15;b>=1&&0===D[b];b--);if(y>b&&(y=b),0===b)return a[s++]=20971520,a[s++]=20971520,l.bits=1,0;for(m=1;m<b&&0===D[m];m++);for(y<m&&(y=m),S=1,g=1;g<=15;g++)if(S<<=1,(S-=D[g])<0)return-1;if(S>0&&(0===e||1!==b))return-1;for(I[1]=0,g=1;g<15;g++)I[g+1]=I[g]+D[g];for(v=0;v<o;v++)0!==r[n+v]&&(c[I[r[n+v]]++]=v);if(0===e?(O=j=c,L=19):1===e?(O=h,R-=257,j=u,M-=257,L=256):(O=f,j=d,L=-1),C=0,v=0,g=m,E=s,_=y,w=0,k=-1,x=1<<y,P=x-1,1===e&&x>852||2===e&&x>592)return 1;for(var U=0;;){U++,F=g-w,c[v]<L?(N=0,B=c[v]):c[v]>L?(N=j[M+c[v]],B=O[R+c[v]]):(N=96,B=0),A=1<<g-w,T=1<<_,m=T;do{T-=A,a[E+(C>>w)+T]=F<<24|N<<16|B|0}while(0!==T);for(A=1<<g-1;C&A;)A>>=1;if(0!==A?(C&=A-1,C+=A):C=0,v++,0==--D[g]){if(g===b)break;g=r[n+c[v]]}if(g>y&&(C&P)!==k){for(0===w&&(w=y),E+=m,_=g-w,S=1<<_;_+w<b&&!((S-=D[_+w])<=0);)_++,S<<=1;if(x+=1<<_,1===e&&x>852||2===e&&x>592)return 1;k=C&P,a[k]=y<<24|_<<16|E-s|0}}return 0!==C&&(a[E+C]=g-w<<24|64<<16|0),l.bits=y,0}},function(t,e,r){"use strict";t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},function(t,e){t.exports=function t(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},function(t,e){"function"==typeof Object.create?t.exports=function t(e,r){e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function t(e,r){e.super_=r;var i=function(){};i.prototype=r.prototype,e.prototype=new i,e.prototype.constructor=e}},function(t,e,r){"use strict";(function(e){/*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <[email protected]> <http://feross.org> * @license MIT */ function i(t,e){if(t===e)return 0;for(var r=t.length,i=e.length,n=0,o=Math.min(r,i);n<o;++n)if(t[n]!==e[n]){r=t[n],i=e[n];break}return r<i?-1:i<r?1:0}function n(t){return e.Buffer&&"function"==typeof e.Buffer.isBuffer?e.Buffer.isBuffer(t):!(null==t||!t._isBuffer)}function o(t){return Object.prototype.toString.call(t)}function a(t){return!n(t)&&("function"==typeof e.ArrayBuffer&&("function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):!!t&&(t instanceof DataView||!!(t.buffer&&t.buffer instanceof ArrayBuffer))))}function s(t){if(_.isFunction(t)){if(x)return t.name;var e=t.toString(),r=e.match(A);return r&&r[1]}}function c(t,e){return"string"==typeof t?t.length<e?t:t.slice(0,e):t}function l(t){if(x||!_.isFunction(t))return _.inspect(t);var e=s(t);return"[Function"+(e?": "+e:"")+"]"}function h(t){return c(l(t.actual),128)+" "+t.operator+" "+c(l(t.expected),128)}function u(t,e,r,i,n){throw new C.AssertionError({message:r,actual:t,expected:e,operator:i,stackStartFunction:n})}function f(t,e){t||u(t,!0,e,"==",C.ok)}function d(t,e,r,s){if(t===e)return!0;if(n(t)&&n(e))return 0===i(t,e);if(_.isDate(t)&&_.isDate(e))return t.getTime()===e.getTime();if(_.isRegExp(t)&&_.isRegExp(e))return t.source===e.source&&t.global===e.global&&t.multiline===e.multiline&&t.lastIndex===e.lastIndex&&t.ignoreCase===e.ignoreCase;if(null!==t&&"object"==typeof t||null!==e&&"object"==typeof e){if(a(t)&&a(e)&&o(t)===o(e)&&!(t instanceof Float32Array||t instanceof Float64Array))return 0===i(new Uint8Array(t.buffer),new Uint8Array(e.buffer));if(n(t)!==n(e))return!1;s=s||{actual:[],expected:[]};var c=s.actual.indexOf(t);return-1!==c&&c===s.expected.indexOf(e)||(s.actual.push(t),s.expected.push(e),g(t,e,r,s))}return r?t===e:t==e}function p(t){return"[object Arguments]"==Object.prototype.toString.call(t)}function g(t,e,r,i){if(null===t||void 0===t||null===e||void 0===e)return!1;if(_.isPrimitive(t)||_.isPrimitive(e))return t===e;if(r&&Object.getPrototypeOf(t)!==Object.getPrototypeOf(e))return!1;var n=p(t),o=p(e);if(n&&!o||!n&&o)return!1;if(n)return t=S.call(t),e=S.call(e),d(t,e,r);var a=T(t),s=T(e),c,l;if(a.length!==s.length)return!1;for(a.sort(),s.sort(),l=a.length-1;l>=0;l--)if(a[l]!==s[l])return!1;for(l=a.length-1;l>=0;l--)if(c=a[l],!d(t[c],e[c],r,i))return!1;return!0}function v(t,e,r){d(t,e,!0)&&u(t,e,r,"notDeepStrictEqual",v)}function m(t,e){if(!t||!e)return!1;if("[object RegExp]"==Object.prototype.toString.call(e))return e.test(t);try{if(t instanceof e)return!0}catch(t){}return!Error.isPrototypeOf(e)&&!0===e.call({},t)}function b(t){var e;try{t()}catch(t){e=t}return e}function y(t,e,r,i){var n;if("function"!=typeof e)throw new TypeError('"block" argument must be a function');"string"==typeof r&&(i=r,r=null),n=b(e),i=(r&&r.name?" ("+r.name+").":".")+(i?" "+i:"."),t&&!n&&u(n,r,"Missing expected exception"+i);var o="string"==typeof i,a=!t&&_.isError(n),s=!t&&n&&!r;if((a&&o&&m(n,r)||s)&&u(n,r,"Got unwanted exception"+i),t&&n&&r&&!m(n,r)||!t&&n)throw n}var _=r(24),w=Object.prototype.hasOwnProperty,S=Array.prototype.slice,x=function(){return"foo"===function t(){}.name}(),C=t.exports=f,A=/\s*function\s+([^\(\s]*)\s*/;C.AssertionError=function t(e){this.name="AssertionError",this.actual=e.actual,this.expected=e.expected,this.operator=e.operator,e.message?(this.message=e.message,this.generatedMessage=!1):(this.message=h(this),this.generatedMessage=!0);var r=e.stackStartFunction||u;if(Error.captureStackTrace)Error.captureStackTrace(this,r);else{var i=new Error;if(i.stack){var n=i.stack,o=s(r),a=n.indexOf("\n"+o);if(a>=0){var c=n.indexOf("\n",a+1);n=n.substring(c+1)}this.stack=n}}},_.inherits(C.AssertionError,Error),C.fail=u,C.ok=f,C.equal=function t(e,r,i){e!=r&&u(e,r,i,"==",C.equal)},C.notEqual=function t(e,r,i){e==r&&u(e,r,i,"!=",C.notEqual)},C.deepEqual=function t(e,r,i){d(e,r,!1)||u(e,r,i,"deepEqual",C.deepEqual)},C.deepStrictEqual=function t(e,r,i){d(e,r,!0)||u(e,r,i,"deepStrictEqual",C.deepStrictEqual)},C.notDeepEqual=function t(e,r,i){d(e,r,!1)&&u(e,r,i,"notDeepEqual",C.notDeepEqual)},C.notDeepStrictEqual=v,C.strictEqual=function t(e,r,i){e!==r&&u(e,r,i,"===",C.strictEqual)},C.notStrictEqual=function t(e,r,i){e===r&&u(e,r,i,"!==",C.notStrictEqual)},C.throws=function(t,e,r){y(!0,t,e,r)},C.doesNotThrow=function(t,e,r){y(!1,t,e,r)},C.ifError=function(t){if(t)throw t};var T=Object.keys||function(t){var e=[];for(var r in t)w.call(t,r)&&e.push(r);return e}}).call(e,r(0))},function(t,e,r){"use strict";var i=r(12),n=r(62);"undefined"!=typeof window&&"Worker"in window?i.PDFJS.workerPort=new n:i.PDFJS.disableWorker=!0,t.exports=i},function(t,e,r){t.exports=function(){return new Worker(r.p+"cdd3fcf50f101cabb45a.worker.js")}},function(module,exports,__webpack_require__){(function(Buffer,process){function copyGLTo2DDrawImage(t,e){var r=t.canvas,i=e.getContext("2d");i.translate(0,e.height),i.scale(1,-1);var n=r.height-e.height;i.drawImage(r,0,n,e.width,e.height,0,0,e.width,e.height)}function copyGLTo2DPutImageData(t,e){var r=e.getContext("2d"),i=e.width,n=e.height,o=i*n*4,a=new Uint8Array(this.imageBuffer,0,o),s=new Uint8ClampedArray(this.imageBuffer,0,o);t.readPixels(0,0,i,n,t.RGBA,t.UNSIGNED_BYTE,a);var c=new ImageData(s,i);r.putImageData(c,0,0)}/*! Fabric.js Copyright 2008-2015, Printio (Juriy Zaytsev, Maxim Chernyak) */ var fabric=fabric||{version:"2.0.0-beta4"};exports.fabric=fabric,"undefined"!=typeof document&&"undefined"!=typeof window?(fabric.document=document,fabric.window=window,window.fabric=fabric):(fabric.document=__webpack_require__(64).jsdom(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]}}),fabric.window=fabric.document.defaultView),fabric.isTouchSupported="ontouchstart"in fabric.document.documentElement,fabric.isLikelyNode=void 0!==Buffer&&"undefined"==typeof window,fabric.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id"],fabric.DPI=96,fabric.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:e[-+]?\\d+)?)",fabric.fontPaths={},fabric.iMatrix=[1,0,0,1,0,0],fabric.canvasModule="canvas",fabric.perfLimitSizeTotal=2097152,fabric.maxCacheSideLimit=4096,fabric.minCacheSideLimit=256,fabric.charWidthsCache={},fabric.textureSize=2048,fabric.enableGLFiltering=!0,fabric.devicePixelRatio=fabric.window.devicePixelRatio||fabric.window.webkitDevicePixelRatio||fabric.window.mozDevicePixelRatio||1,fabric.initFilterBackend=function(){return fabric.isWebglSupported&&fabric.isWebglSupported(fabric.textureSize)&&fabric.enableGLFiltering?(console.log("max texture size: "+fabric.maxTextureSize),new fabric.WebglFilterBackend({tileSize:fabric.textureSize})):fabric.Canvas2dFilterBackend?new fabric.Canvas2dFilterBackend:void 0},function(){function t(t,e){if(this.__eventListeners[t]){var r=this.__eventListeners[t];e?r[r.indexOf(e)]=!1:fabric.util.array.fill(r,!1)}}function e(t,e){if(this.__eventListeners||(this.__eventListeners={}),1===arguments.length)for(var r in t)this.on(r,t[r]);else this.__eventListeners[t]||(this.__eventListeners[t]=[]),this.__eventListeners[t].push(e);return this}function r(e,r){if(this.__eventListeners){if(0===arguments.length)for(e in this.__eventListeners)t.call(this,e);else if(1===arguments.length&&"object"==typeof arguments[0])for(var i in e)t.call(this,i,e[i]);else t.call(this,e,r);return this}}function i(t,e){if(this.__eventListeners){var r=this.__eventListeners[t];if(r){for(var i=0,n=r.length;i<n;i++)r[i]&&r[i].call(this,e||{});return this.__eventListeners[t]=r.filter(function(t){return!1!==t}),this}}}fabric.Observable={observe:e,stopObserving:r,fire:i,on:e,off:r,trigger:i}}(),fabric.Collection={_objects:[],add:function(){if(this._objects.push.apply(this._objects,arguments),this._onObjectAdded)for(var t=0,e=arguments.length;t<e;t++)this._onObjectAdded(arguments[t]);return this.renderOnAddRemove&&this.requestRenderAll(),this},insertAt:function(t,e,r){var i=this.getObjects();return r?i[e]=t:i.splice(e,0,t),this._onObjectAdded&&this._onObjectAdded(t),this.renderOnAddRemove&&this.requestRenderAll(),this},remove:function(){for(var t=this.getObjects(),e,r=!1,i=0,n=arguments.length;i<n;i++)-1!==(e=t.indexOf(arguments[i]))&&(r=!0,t.splice(e,1),this._onObjectRemoved&&this._onObjectRemoved(arguments[i]));return this.renderOnAddRemove&&r&&this.requestRenderAll(),this},forEachObject:function(t,e){for(var r=this.getObjects(),i=0,n=r.length;i<n;i++)t.call(e,r[i],i,r);return this},getObjects:function(t){return void 0===t?this._objects:this._objects.filter(function(e){return e.type===t})},item:function(t){return this.getObjects()[t]},isEmpty:function(){return 0===this.getObjects().length},size:function(){return this.getObjects().length},contains:function(t){return this.getObjects().indexOf(t)>-1},complexity:function(){return this.getObjects().reduce(function(t,e){return t+=e.complexity?e.complexity():0},0)}},fabric.CommonMethods={_setOptions:function(t){for(var e in t)this.set(e,t[e])},_initGradient:function(t,e){!t||!t.colorStops||t instanceof fabric.Gradient||this.set(e,new fabric.Gradient(t))},_initPattern:function(t,e,r){!t||!t.source||t instanceof fabric.Pattern?r&&r():this.set(e,new fabric.Pattern(t,r))},_initClipping:function(t){if(t.clipTo&&"string"==typeof t.clipTo){var e=fabric.util.getFunctionBody(t.clipTo);void 0!==e&&(this.clipTo=new Function("ctx",e))}},_setObject:function(t){for(var e in t)this._set(e,t[e])},set:function(t,e){return"object"==typeof t?this._setObject(t):"function"==typeof e&&"clipTo"!==t?this._set(t,e(this.get(t))):this._set(t,e),this},_set:function(t,e){this[t]=e},toggle:function(t){var e=this.get(t);return"boolean"==typeof e&&this.set(t,!e),this},get:function(t){return this[t]}},function(t){var e=Math.sqrt,r=Math.atan2,i=Math.pow,n=Math.abs,o=Math.PI/180;fabric.util={removeFromArray:function(t,e){var r=t.indexOf(e);return-1!==r&&t.splice(r,1),t},getRandomInt:function(t,e){return Math.floor(Math.random()*(e-t+1))+t},degreesToRadians:function(t){return t*o},radiansToDegrees:function(t){return t/o},rotatePoint:function(t,e,r){t.subtractEquals(e);var i=fabric.util.rotateVector(t,r);return new fabric.Point(i.x,i.y).addEquals(e)},rotateVector:function(t,e){var r=Math.sin(e),i=Math.cos(e);return{x:t.x*i-t.y*r,y:t.x*r+t.y*i}},transformPoint:function(t,e,r){return r?new fabric.Point(e[0]*t.x+e[2]*t.y,e[1]*t.x+e[3]*t.y):new fabric.Point(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])},makeBoundingBoxFromPoints:function(t){var e=[t[0].x,t[1].x,t[2].x,t[3].x],r=fabric.util.array.min(e),i=fabric.util.array.max(e),n=Math.abs(r-i),o=[t[0].y,t[1].y,t[2].y,t[3].y],a=fabric.util.array.min(o),s=fabric.util.array.max(o);return{left:r,top:a,width:n,height:Math.abs(a-s)}},invertTransform:function(t){var e=1/(t[0]*t[3]-t[1]*t[2]),r=[e*t[3],-e*t[1],-e*t[2],e*t[0]],i=fabric.util.transformPoint({x:t[4],y:t[5]},r,!0);return r[4]=-i.x,r[5]=-i.y,r},toFixed:function(t,e){return parseFloat(Number(t).toFixed(e))},parseUnit:function(t,e){var r=/\D{0,2}$/.exec(t),i=parseFloat(t);switch(e||(e=fabric.Text.DEFAULT_SVG_FONT_SIZE),r[0]){case"mm":return i*fabric.DPI/25.4;case"cm":return i*fabric.DPI/2.54;case"in":return i*fabric.DPI;case"pt":return i*fabric.DPI/72;case"pc":return i*fabric.DPI/72*12;case"em":return i*e;default:return i}},falseFunction:function(){return!1},getKlass:function(t,e){return t=fabric.util.string.camelize(t.charAt(0).toUpperCase()+t.slice(1)),fabric.util.resolveNamespace(e)[t]},resolveNamespace:function(e){if(!e)return fabric;var r=e.split("."),i=r.length,n,o=t||fabric.window;for(n=0;n<i;++n)o=o[r[n]];return o},loadImage:function(t,e,r,i){if(!t)return void(e&&e.call(r,t));var n=fabric.util.createImage();n.onload=function(){e&&e.call(r,n),n=n.onload=n.onerror=null},n.onerror=function(){fabric.log("Error loading "+n.src),e&&e.call(r,null,!0),n=n.onload=n.onerror=null},0!==t.indexOf("data")&&i&&(n.crossOrigin=i),n.src=t},enlivenObjects:function(t,e,r,i){function n(){++a===s&&e&&e(o)}t=t||[];var o=[],a=0,s=t.length;if(!s)return void(e&&e(o));t.forEach(function(t,e){if(!t||!t.type)return void n();fabric.util.getKlass(t.type,r).fromObject(t,function(r,a){a||(o[e]=r),i&&i(t,r,a),n()})})},enlivenPatterns:function(t,e){function r(){++n===o&&e&&e(i)}t=t||[];var i=[],n=0,o=t.length;if(!o)return void(e&&e(i));t.forEach(function(t,e){t&&t.source?new fabric.Pattern(t,function(t){i[e]=t,r()}):(i[e]=t,r())})},groupSVGElements:function(t,e,r){var i;return 1===t.length?t[0]:(e&&(e.width&&e.height?e.centerPoint={x:e.width/2,y:e.height/2}:(delete e.width,delete e.height)),i=new fabric.Group(t,e),void 0!==r&&(i.sourcePath=r),i)},populateWithProperties:function(t,e,r){if(r&&"[object Array]"===Object.prototype.toString.call(r))for(var i=0,n=r.length;i<n;i++)r[i]in t&&(e[r[i]]=t[r[i]])},drawDashedLine:function(t,i,n,o,a,s){var c=o-i,l=a-n,h=e(c*c+l*l),u=r(l,c),f=s.length,d=0,p=!0;for(t.save(),t.translate(i,n),t.moveTo(0,0),t.rotate(u),i=0;h>i;)i+=s[d++%f],i>h&&(i=h),t[p?"lineTo":"moveTo"](i,0),p=!p;t.restore()},createCanvasElement:function(t){return t||(t=fabric.document.createElement("canvas")),t},createImage:function(){return fabric.document.createElement("img")},clipContext:function(t,e){e.save(),e.beginPath(),t.clipTo(e),e.clip()},multiplyTransformMatrices:function(t,e,r){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],r?0:t[0]*e[4]+t[2]*e[5]+t[4],r?0:t[1]*e[4]+t[3]*e[5]+t[5]]},qrDecompose:function(t){var n=r(t[1],t[0]),a=i(t[0],2)+i(t[1],2),s=e(a),c=(t[0]*t[3]-t[2]*t[1])/s,l=r(t[0]*t[2]+t[1]*t[3],a);return{angle:n/o,scaleX:s,scaleY:c,skewX:l/o,skewY:0,translateX:t[4],translateY:t[5]}},customTransformMatrix:function(t,e,r){var i=[1,0,n(Math.tan(r*o)),1],a=[n(t),0,0,n(e)];return fabric.util.multiplyTransformMatrices(a,i,!0)},resetObjectTransform:function(t){t.scaleX=1,t.scaleY=1,t.skewX=0,t.skewY=0,t.flipX=!1,t.flipY=!1,t.setAngle(0)},getFunctionBody:function(t){return(String(t).match(/function[^{]*\{([\s\S]*)\}/)||{})[1]},isTransparent:function(t,e,r,i){i>0&&(e>i?e-=i:e=0,r>i?r-=i:r=0);var n=!0,o,a,s=t.getImageData(e,r,2*i||1,2*i||1),c=s.data.length;for(o=3;o<c&&(a=s.data[o],!1!==(n=a<=0));o+=4);return s=null,n},parsePreserveAspectRatioAttribute:function(t){var e="meet",r="Mid",i="Mid",n=t.split(" "),o;return n&&n.length&&(e=n.pop(),"meet"!==e&&"slice"!==e?(o=e,e="meet"):n.length&&(o=n.pop())),r="none"!==o?o.slice(1,4):"none",i="none"!==o?o.slice(5,8):"none",{meetOrSlice:e,alignX:r,alignY:i}},clearFabricFontCache:function(t){t?fabric.charWidthsCache[t]&&delete fabric.charWidthsCache[t]:fabric.charWidthsCache={}},limitDimsByArea:function(t,e){var r=Math.sqrt(e*t),i=Math.floor(e/r);return{x:Math.floor(r),y:i}},capValue:function(t,e,r){return Math.max(t,Math.min(e,r))},findScaleToFit:function(t,e){return Math.min(e.width/t.width,e.height/t.height)},findScaleToCover:function(t,e){return Math.max(e.width/t.width,e.height/t.height)}}}(exports),function(){function t(t,i,o,a,c,l,h){var u=s.call(arguments);if(n[u])return n[u];var f=Math.PI,d=h*f/180,p=Math.sin(d),g=Math.cos(d),v=0,m=0;o=Math.abs(o),a=Math.abs(a);var b=-g*t*.5-p*i*.5,y=-g*i*.5+p*t*.5,_=o*o,w=a*a,S=y*y,x=b*b,C=_*w-_*S-w*x,A=0;if(C<0){var T=Math.sqrt(1-C/(_*w));o*=T,a*=T}else A=(c===l?-1:1)*Math.sqrt(C/(_*S+w*x));var k=A*o*y/a,P=-A*a*b/o,E=g*k-p*P+.5*t,O=p*k+g*P+.5*i,R=r(1,0,(b-k)/o,(y-P)/a),L=r((b-k)/o,(y-P)/a,(-b-k)/o,(-y-P)/a);0===l&&L>0?L-=2*f:1===l&&L<0&&(L+=2*f);for(var D=Math.ceil(Math.abs(L/f*2)),I=[],j=L/D,M=8/3*Math.sin(j/4)*Math.sin(j/4)/Math.sin(j/2),F=R+j,N=0;N<D;N++)I[N]=e(R,F,g,p,o,a,E,O,M,v,m),v=I[N][4],m=I[N][5],R=F,F+=j;return n[u]=I,I}function e(t,e,r,i,n,a,c,l,h,u,f){var d=s.call(arguments);if(o[d])return o[d];var p=Math.cos(t),g=Math.sin(t),v=Math.cos(e),m=Math.sin(e),b=r*n*v-i*a*m+c,y=i*n*v+r*a*m+l,_=u+h*(-r*n*g-i*a*p),w=f+h*(-i*n*g+r*a*p),S=b+h*(r*n*m+i*a*v),x=y+h*(i*n*m-r*a*v);return o[d]=[_,w,S,x,b,y],o[d]}function r(t,e,r,i){var n=Math.atan2(e,t),o=Math.atan2(i,r);return o>=n?o-n:2*Math.PI-(n-o)}function i(t,e,r,i,n,o,c,l){var h=s.call(arguments);if(a[h])return a[h];var u=Math.sqrt,f=Math.min,d=Math.max,p=Math.abs,g=[],v=[[],[]],m,b,y,_,w,S,x,C;b=6*t-12*r+6*n,m=-3*t+9*r-9*n+3*c,y=3*r-3*t;for(var A=0;A<2;++A)if(A>0&&(b=6*e-12*i+6*o,m=-3*e+9*i-9*o+3*l,y=3*i-3*e),p(m)<1e-12){if(p(b)<1e-12)continue;0<(_=-y/b)&&_<1&&g.push(_)}else(x=b*b-4*y*m)<0||(C=u(x),w=(-b+C)/(2*m),0<w&&w<1&&g.push(w),0<(S=(-b-C)/(2*m))&&S<1&&g.push(S));for(var T,k,P=g.length,E=P,O;P--;)_=g[P],O=1-_,T=O*O*O*t+3*O*O*_*r+3*O*_*_*n+_*_*_*c,v[0][P]=T,k=O*O*O*e+3*O*O*_*i+3*O*_*_*o+_*_*_*l,v[1][P]=k;v[0][E]=t,v[1][E]=e,v[0][E+1]=c,v[1][E+1]=l;var R=[{x:f.apply(null,v[0]),y:f.apply(null,v[1])},{x:d.apply(null,v[0]),y:d.apply(null,v[1])}];return a[h]=R,R}var n={},o={},a={},s=Array.prototype.join;fabric.util.drawArc=function(e,r,i,n){for(var o=n[0],a=n[1],s=n[2],c=n[3],l=n[4],h=n[5],u=n[6],f=[[],[],[],[]],d=t(h-r,u-i,o,a,c,l,s),p=0,g=d.length;p<g;p++)f[p][0]=d[p][0]+r,f[p][1]=d[p][1]+i,f[p][2]=d[p][2]+r,f[p][3]=d[p][3]+i,f[p][4]=d[p][4]+r,f[p][5]=d[p][5]+i,e.bezierCurveTo.apply(e,f[p])},fabric.util.getBoundsOfArc=function(e,r,n,o,a,s,c,l,h){for(var u=0,f=0,d,p=[],g=t(l-e,h-r,n,o,s,c,a),v=0,m=g.length;v<m;v++)d=i(u,f,g[v][0],g[v][1],g[v][2],g[v][3],g[v][4],g[v][5]),p.push({x:d[0].x+e,y:d[0].y+r}),p.push({x:d[1].x+e,y:d[1].y+r}),u=g[v][4],f=g[v][5];return p},fabric.util.getBoundsOfCurve=i}(),function(){function t(t,e){for(var r=o.call(arguments,2),i=[],n=0,a=t.length;n<a;n++)i[n]=r.length?t[n][e].apply(t[n],r):t[n][e].call(t[n]);return i}function e(t,e){return n(t,e,function(t,e){return t>=e})}function r(t,e){return n(t,e,function(t,e){return t<e})}function i(t,e){for(var r=t.length;r--;)t[r]=e;return t}function n(t,e,r){if(t&&0!==t.length){var i=t.length-1,n=e?t[i][e]:t[i];if(e)for(;i--;)r(t[i][e],n)&&(n=t[i][e]);else for(;i--;)r(t[i],n)&&(n=t[i]);return n}}var o=Array.prototype.slice;fabric.util.array={fill:i,invoke:t,min:r,max:e}}(),function(){function t(e,r,i){if(i)if(!fabric.isLikelyNode&&r instanceof Element)e=r;else if(r instanceof Array){e=[];for(var n=0,o=r.length;n<o;n++)e[n]=t({},r[n],i)}else if(r&&"object"==typeof r)for(var a in r)r.hasOwnProperty(a)&&(e[a]=t({},r[a],i));else e=r;else for(var a in r)e[a]=r[a];return e}function e(e,r){return t({},e,r)}fabric.util.object={extend:t,clone:e}}(),function(){function t(t){return t.replace(/-+(.)?/g,function(t,e){return e?e.toUpperCase():""})}function e(t,e){return t.charAt(0).toUpperCase()+(e?t.slice(1):t.slice(1).toLowerCase())}function r(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function i(t){for(var e=0,r=[],e=0,i;e<t.length;e++)!1!==(i=n(t,e))&&r.push(i);return r}function n(t,e){var r=t.charCodeAt(e);if(isNaN(r))return"";if(r<55296||r>57343)return t.charAt(e);if(55296<=r&&r<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";var i=t.charCodeAt(e+1);if(56320>i||i>57343)throw"High surrogate without following low surrogate";return t.charAt(e)+t.charAt(e+1)}if(0===e)throw"Low surrogate without preceding high surrogate";var n=t.charCodeAt(e-1);if(55296>n||n>56319)throw"Low surrogate without preceding high surrogate";return!1}fabric.util.string={camelize:t,capitalize:e,escapeXml:r,graphemeSplit:i}}(),function(){function t(){}function e(t){for(var e=null,r=this;r.constructor.superclass;){var n=r.constructor.superclass.prototype[t];if(r[t]!==n){e=n;break}r=r.constructor.superclass.prototype}return e?arguments.length>1?e.apply(this,i.call(arguments,1)):e.call(this):console.log("tried to callSuper "+t+", method not found in prototype chain",this)}function r(){function r(){this.initialize.apply(this,arguments)}var o=null,s=i.call(arguments,0);"function"==typeof s[0]&&(o=s.shift()),r.superclass=o,r.subclasses=[],o&&(t.prototype=o.prototype,r.prototype=new t,o.subclasses.push(r));for(var c=0,l=s.length;c<l;c++)a(r,s[c],o);return r.prototype.initialize||(r.prototype.initialize=n),r.prototype.constructor=r,r.prototype.callSuper=e,r}var i=Array.prototype.slice,n=function(){},o=function(){for(var t in{toString:1})if("toString"===t)return!1;return!0}(),a=function(t,e,r){for(var i in e)i in t.prototype&&"function"==typeof t.prototype[i]&&(e[i]+"").indexOf("callSuper")>-1?t.prototype[i]=function(t){return function(){var i=this.constructor.superclass;this.constructor.superclass=r;var n=e[t].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==t)return n}}(i):t.prototype[i]=e[i],o&&(e.toString!==Object.prototype.toString&&(t.prototype.toString=e.toString),e.valueOf!==Object.prototype.valueOf&&(t.prototype.valueOf=e.valueOf))};fabric.util.createClass=r}(),function(){function t(t){var e=Array.prototype.slice.call(arguments,1),r,i,n=e.length;for(i=0;i<n;i++)if(r=typeof t[e[i]],!/^(?:function|object|unknown)$/.test(r))return!1;return!0}function e(t,e){return{handler:e,wrappedHandler:r(t,e)}}function r(t,e){return function(r){e.call(s(t),r||fabric.window.event)}}function i(t,e){return function(r){if(d[t]&&d[t][e])for(var i=d[t][e],n=0,o=i.length;n<o;n++)i[n].call(this,r||fabric.window.event)}}function n(t){t||(t=fabric.window.event);var e=t.target||(typeof t.srcElement!==a?t.srcElement:null),r=fabric.util.getScrollLeftTop(e);return{x:v(t)+r.left,y:m(t)+r.top}}function o(t,e,r){var i="touchend"===t.type?"changedTouches":"touches";return t[i]&&t[i][0]?t[i][0][e]-(t[i][0][e]-t[i][0][r])||t[r]:t[r]}var a="unknown",s,c,l=function(){var t=0;return function(e){return e.__uniqueID||(e.__uniqueID="uniqueID__"+t++)}}();!function(){var t={};s=function(e){return t[e]},c=function(e,r){t[e]=r}}();var h=t(fabric.document.documentElement,"addEventListener","removeEventListener")&&t(fabric.window,"addEventListener","removeEventListener"),u=t(fabric.document.documentElement,"attachEvent","detachEvent")&&t(fabric.window,"attachEvent","detachEvent"),f={},d={},p,g;h?(p=function(t,e,r,i){t&&t.addEventListener(e,r,!u&&i)},g=function(t,e,r,i){t&&t.removeEventListener(e,r,!u&&i)}):u?(p=function(t,r,i){if(t){var n=l(t);c(n,t),f[n]||(f[n]={}),f[n][r]||(f[n][r]=[]);var o=e(n,i);f[n][r].push(o),t.attachEvent("on"+r,o.wrappedHandler)}},g=function(t,e,r){if(t){var i=l(t),n;if(f[i]&&f[i][e])for(var o=0,a=f[i][e].length;o<a;o++)(n=f[i][e][o])&&n.handler===r&&(t.detachEvent("on"+e,n.wrappedHandler),f[i][e][o]=null)}}):(p=function(t,e,r){if(t){var n=l(t);if(d[n]||(d[n]={}),!d[n][e]){d[n][e]=[];var o=t["on"+e];o&&d[n][e].push(o),t["on"+e]=i(n,e)}d[n][e].push(r)}},g=function(t,e,r){if(t){var i=l(t);if(d[i]&&d[i][e])for(var n=d[i][e],o=0,a=n.length;o<a;o++)n[o]===r&&n.splice(o,1)}}),fabric.util.addListener=p,fabric.util.removeListener=g;var v=function(t){return t.clientX},m=function(t){return t.clientY};fabric.isTouchSupported&&(v=function(t){return o(t,"pageX","clientX")},m=function(t){return o(t,"pageY","clientY")}),fabric.util.getPointer=n,fabric.util.object.extend(fabric.util,fabric.Observable)}(),function(){function t(t,e){var r=t.style;if(!r)return t;if("string"==typeof e)return t.style.cssText+=";"+e,e.indexOf("opacity")>-1?o(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var i in e)if("opacity"===i)o(t,e[i]);else{var n="float"===i||"cssFloat"===i?void 0===r.styleFloat?"cssFloat":"styleFloat":i;r[n]=e[i]}return t}var e=fabric.document.createElement("div"),r="string"==typeof e.style.opacity,i="string"==typeof e.style.filter,n=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,o=function(t){return t};r?o=function(t,e){return t.style.opacity=e,t}:i&&(o=function(t,e){var r=t.style;return t.currentStyle&&!t.currentStyle.hasLayout&&(r.zoom=1),n.test(r.filter)?(e=e>=.9999?"":"alpha(opacity="+100*e+")",r.filter=r.filter.replace(n,e)):r.filter+=" alpha(opacity="+100*e+")",t}),fabric.util.setStyle=t}(),function(){function t(t){return"string"==typeof t?fabric.document.getElementById(t):t}function e(t,e){var r=fabric.document.createElement(t);for(var i in e)"class"===i?r.className=e[i]:"for"===i?r.htmlFor=e[i]:r.setAttribute(i,e[i]);return r}function r(t,e){t&&-1===(" "+t.className+" ").indexOf(" "+e+" ")&&(t.className+=(t.className?" ":"")+e)}function i(t,r,i){return"string"==typeof r&&(r=e(r,i)),t.parentNode&&t.parentNode.replaceChild(r,t),r.appendChild(t),r}function n(t){for(var e=0,r=0,i=fabric.document.documentElement,n=fabric.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&(t=t.parentNode||t.host,t===fabric.document?(e=n.scrollLeft||i.scrollLeft||0,r=n.scrollTop||i.scrollTop||0):(e+=t.scrollLeft||0,r+=t.scrollTop||0),1!==t.nodeType||"fixed"!==fabric.util.getElementStyle(t,"position")););return{left:e,top:r}}function o(t){var e,r=t&&t.ownerDocument,i={left:0,top:0},o={left:0,top:0},a,s={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!r)return o;for(var c in s)o[s[c]]+=parseInt(l(t,c),10)||0;return e=r.documentElement,void 0!==t.getBoundingClientRect&&(i=t.getBoundingClientRect()),a=n(t),{left:i.left+a.left-(e.clientLeft||0)+o.left,top:i.top+a.top-(e.clientTop||0)+o.top}}var a=Array.prototype.slice,s,c=function(t){return a.call(t,0)};try{s=c(fabric.document.childNodes)instanceof Array}catch(t){}s||(c=function(t){for(var e=new Array(t.length),r=t.length;r--;)e[r]=t[r];return e});var l;l=fabric.document.defaultView&&fabric.document.defaultView.getComputedStyle?function(t,e){var r=fabric.document.defaultView.getComputedStyle(t,null);return r?r[e]:void 0}:function(t,e){var r=t.style[e];return!r&&t.currentStyle&&(r=t.currentStyle[e]),r},function(){function t(t){return void 0!==t.onselectstart&&(t.onselectstart=fabric.util.falseFunction),i?t.style[i]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t}function e(t){return void 0!==t.onselectstart&&(t.onselectstart=null),i?t.style[i]="":"string"==typeof t.unselectable&&(t.unselectable=""),t}var r=fabric.document.documentElement.style,i="userSelect"in r?"userSelect":"MozUserSelect"in r?"MozUserSelect":"WebkitUserSelect"in r?"WebkitUserSelect":"KhtmlUserSelect"in r?"KhtmlUserSelect":"";fabric.util.makeElementUnselectable=t,fabric.util.makeElementSelectable=e}(),function(){function t(t,e){var r=fabric.document.getElementsByTagName("head")[0],i=fabric.document.createElement("script"),n=!0;i.onload=i.onreadystatechange=function(t){if(n){if("string"==typeof this.readyState&&"loaded"!==this.readyState&&"complete"!==this.readyState)return;n=!1,e(t||fabric.window.event),i=i.onload=i.onreadystatechange=null}},i.src=t,r.appendChild(i)}fabric.util.getScript=t}(),fabric.util.getById=t,fabric.util.toArray=c,fabric.util.makeElement=e,fabric.util.addClass=r,fabric.util.wrapElement=i,fabric.util.getScrollLeftTop=n,fabric.util.getElementOffset=o,fabric.util.getElementStyle=l}(),function(){function t(t,e){return t+(/\?/.test(t)?"&":"?")+e}function e(){}function r(r,n){n||(n={});var o=n.method?n.method.toUpperCase():"GET",a=n.onComplete||function(){},s=i(),c=n.body||n.parameters;return s.onreadystatechange=function(){4===s.readyState&&(a(s),s.onreadystatechange=e)},"GET"===o&&(c=null,"string"==typeof n.parameters&&(r=t(r,n.parameters))),s.open(o,r,!0),"POST"!==o&&"PUT"!==o||s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.send(c),s}var i=function(){for(var t=[function(){return new ActiveXObject("Microsoft.XMLHTTP")},function(){return new ActiveXObject("Msxml2.XMLHTTP")},function(){return new ActiveXObject("Msxml2.XMLHTTP.3.0")},function(){return new XMLHttpRequest}],e=t.length;e--;)try{if(t[e]())return t[e]}catch(t){}}();fabric.util.request=r}(),fabric.log=function(){},fabric.warn=function(){},"undefined"!=typeof console&&["log","warn"].forEach(function(t){void 0!==console[t]&&"function"==typeof console[t].apply&&(fabric[t]=function(){return console[t].apply(console,arguments)})}),function(){function t(){return!1}function e(e){r(function(i){e||(e={});var n=i||+new Date,o=e.duration||500,a=n+o,s,c=e.onChange||t,l=e.abort||t,h=e.onComplete||t,u=e.easing||function(t,e,r,i){return-r*Math.cos(t/i*(Math.PI/2))+r+e},f="startValue"in e?e.startValue:0,d="endValue"in e?e.endValue:100,p=e.byValue||d-f;e.onStart&&e.onStart(),function t(i){if(l())return void h(d,1,1);s=i||+new Date;var g=s>a?o:s-n,v=g/o,m=u(g,f,p,o),b=Math.abs((m-f)/p);if(c(m,b,v),s>a)return void(e.onComplete&&e.onComplete());r(t)}(n)})}function r(){return i.apply(fabric.window,arguments)}var i=fabric.window.requestAnimationFrame||fabric.window.webkitRequestAnimationFrame||fabric.window.mozRequestAnimationFrame||fabric.window.oRequestAnimationFrame||fabric.window.msRequestAnimationFrame||function(t){fabric.window.setTimeout(t,1e3/60)};fabric.util.animate=e,fabric.util.requestAnimFrame=r}(),function(){function t(t,e,r){var i="rgba("+parseInt(t[0]+r*(e[0]-t[0]),10)+","+parseInt(t[1]+r*(e[1]-t[1]),10)+","+parseInt(t[2]+r*(e[2]-t[2]),10);return i+=","+(t&&e?parseFloat(t[3]+r*(e[3]-t[3])):1),i+=")"}function e(e,r,i,n){var o=new fabric.Color(e).getSource(),a=new fabric.Color(r).getSource();n=n||{},fabric.util.animate(fabric.util.object.extend(n,{duration:i||500,startValue:o,endValue:a,byValue:a,easing:function(e,r,i,o){return t(r,i,n.colorEasing?n.colorEasing(e,o):1-Math.cos(e/o*(Math.PI/2)))}}))}fabric.util.animateColor=e}(),function(){function t(t,e,r,i){return t<Math.abs(e)?(t=e,i=r/4):i=0===e&&0===t?r/(2*Math.PI)*Math.asin(1):r/(2*Math.PI)*Math.asin(e/t),{a:t,c:e,p:r,s:i}}function e(t,e,r){return t.a*Math.pow(2,10*(e-=1))*Math.sin((e*r-t.s)*(2*Math.PI)/t.p)}function r(t,e,r,i){return r*((t=t/i-1)*t*t+1)+e}function i(t,e,r,i){return t/=i/2,t<1?r/2*t*t*t+e:r/2*((t-=2)*t*t+2)+e}function n(t,e,r,i){return r*(t/=i)*t*t*t+e}function o(t,e,r,i){return-r*((t=t/i-1)*t*t*t-1)+e}function a(t,e,r,i){return t/=i/2,t<1?r/2*t*t*t*t+e:-r/2*((t-=2)*t*t*t-2)+e}function s(t,e,r,i){return r*(t/=i)*t*t*t*t+e}function c(t,e,r,i){return r*((t=t/i-1)*t*t*t*t+1)+e}function l(t,e,r,i){return t/=i/2,t<1?r/2*t*t*t*t*t+e:r/2*((t-=2)*t*t*t*t+2)+e}function h(t,e,r,i){return-r*Math.cos(t/i*(Math.PI/2))+r+e}function u(t,e,r,i){return r*Math.sin(t/i*(Math.PI/2))+e}function f(t,e,r,i){return-r/2*(Math.cos(Math.PI*t/i)-1)+e}function d(t,e,r,i){return 0===t?e:r*Math.pow(2,10*(t/i-1))+e}function p(t,e,r,i){return t===i?e+r:r*(1-Math.pow(2,-10*t/i))+e}function g(t,e,r,i){return 0===t?e:t===i?e+r:(t/=i/2,t<1?r/2*Math.pow(2,10*(t-1))+e:r/2*(2-Math.pow(2,-10*--t))+e)}function v(t,e,r,i){return-r*(Math.sqrt(1-(t/=i)*t)-1)+e}function m(t,e,r,i){return r*Math.sqrt(1-(t=t/i-1)*t)+e}function b(t,e,r,i){return t/=i/2,t<1?-r/2*(Math.sqrt(1-t*t)-1)+e:r/2*(Math.sqrt(1-(t-=2)*t)+1)+e}function y(r,i,n,o){var a=0,s=n;return 0===r?i:1==(r/=o)?i+n:(a||(a=.3*o),-e(t(s,n,a,1.70158),r,o)+i)}function _(e,r,i,n){var o=1.70158,a=0,s=i;if(0===e)return r;if(1===(e/=n))return r+i;a||(a=.3*n);var c=t(s,i,a,o);return c.a*Math.pow(2,-10*e)*Math.sin((e*n-c.s)*(2*Math.PI)/c.p)+c.c+r}function w(r,i,n,o){var a=1.70158,s=0,c=n;if(0===r)return i;if(2===(r/=o/2))return i+n;s||(s=o*(.3*1.5));var l=t(c,n,s,a);return r<1?-.5*e(l,r,o)+i:l.a*Math.pow(2,-10*(r-=1))*Math.sin((r*o-l.s)*(2*Math.PI)/l.p)*.5+l.c+i}function S(t,e,r,i,n){return void 0===n&&(n=1.70158),r*(t/=i)*t*((n+1)*t-n)+e}function x(t,e,r,i,n){return void 0===n&&(n=1.70158),r*((t=t/i-1)*t*((n+1)*t+n)+1)+e}function C(t,e,r,i,n){return void 0===n&&(n=1.70158),t/=i/2,t<1?r/2*(t*t*((1+(n*=1.525))*t-n))+e:r/2*((t-=2)*t*((1+(n*=1.525))*t+n)+2)+e}function A(t,e,r,i){return r-T(i-t,0,r,i)+e}function T(t,e,r,i){return(t/=i)<1/2.75?r*(7.5625*t*t)+e:t<2/2.75?r*(7.5625*(t-=1.5/2.75)*t+.75)+e:t<2.5/2.75?r*(7.5625*(t-=2.25/2.75)*t+.9375)+e:r*(7.5625*(t-=2.625/2.75)*t+.984375)+e}function k(t,e,r,i){return t<i/2?.5*A(2*t,0,r,i)+e:.5*T(2*t-i,0,r,i)+.5*r+e}fabric.util.ease={easeInQuad:function(t,e,r,i){return r*(t/=i)*t+e},easeOutQuad:function(t,e,r,i){return-r*(t/=i)*(t-2)+e},easeInOutQuad:function(t,e,r,i){return t/=i/2,t<1?r/2*t*t+e:-r/2*(--t*(t-2)-1)+e},easeInCubic:function(t,e,r,i){return r*(t/=i)*t*t+e},easeOutCubic:r,easeInOutCubic:i,easeInQuart:n,easeOutQuart:o,easeInOutQuart:a,easeInQuint:s,easeOutQuint:c,easeInOutQuint:l,easeInSine:h,easeOutSine:u,easeInOutSine:f,easeInExpo:d,easeOutExpo:p,easeInOutExpo:g,easeInCirc:v,easeOutCirc:m,easeInOutCirc:b,easeInElastic:y,easeOutElastic:_,easeInOutElastic:w,easeInBack:S,easeOutBack:x,easeInOutBack:C,easeInBounce:A,easeOutBounce:T,easeInOutBounce:k}}(),function(t){"use strict";function e(t){return t in A?A[t]:t}function r(t,e,r,i){var n="[object Array]"===Object.prototype.toString.call(e),o;return"fill"!==t&&"stroke"!==t||"none"!==e?"strokeDashArray"===t?e="none"===e?null:e.replace(/,/g," ").split(/\s+/).map(function(t){return parseFloat(t)}):"transformMatrix"===t?e=r&&r.transformMatrix?_(r.transformMatrix,g.parseTransformAttribute(e)):g.parseTransformAttribute(e):"visible"===t?(e="none"!==e&&"hidden"!==e,r&&!1===r.visible&&(e=!1)):"opacity"===t?(e=parseFloat(e),r&&void 0!==r.opacity&&(e*=r.opacity)):"originX"===t?e="start"===e?"left":"end"===e?"right":"center":o=n?e.map(y):y(e,i):e="",!n&&isNaN(o)?e:o}function i(t){for(var e in T)if(void 0!==t[T[e]]&&""!==t[e]){if(void 0===t[e]){if(!g.Object.prototype[e])continue;t[e]=g.Object.prototype[e]}if(0!==t[e].indexOf("url(")){var r=new g.Color(t[e]);t[e]=r.setAlpha(b(r.getAlpha()*t[T[e]],2)).toRgba()}}return t}function n(t,e){for(var r,i=[],n,o=0;o<e.length;o++)r=e[o],n=t.getElementsByTagName(r),i=i.concat(Array.prototype.slice.call(n));return i}function o(t,e){var r,i;t.replace(/;\s*$/,"").split(";").forEach(function(t){var n=t.split(":");r=n[0].trim().toLowerCase(),i=n[1].trim(),e[r]=i})}function a(t,e){var r,i;for(var n in t)void 0!==t[n]&&(r=n.toLowerCase(),i=t[n],e[r]=i)}function s(t,e){var r={};for(var i in g.cssRules[e])if(c(t,i.split(" ")))for(var n in g.cssRules[e][i])r[n]=g.cssRules[e][i][n];return r}function c(t,e){var r,i=!0;return r=h(t,e.pop()),r&&e.length&&(i=l(t,e)),r&&i&&0===e.length}function l(t,e){for(var r,i=!0;t.parentNode&&1===t.parentNode.nodeType&&e.length;)i&&(r=e.pop()),t=t.parentNode,i=h(t,r);return 0===e.length}function h(t,e){var r=t.nodeName,i=t.getAttribute("class"),n=t.getAttribute("id"),o;if(o=new RegExp("^"+r,"i"),e=e.replace(o,""),n&&e.length&&(o=new RegExp("#"+n+"(?![a-zA-Z\\-]+)","i"),e=e.replace(o,"")),i&&e.length){i=i.split(" ");for(var a=i.length;a--;)o=new RegExp("\\."+i[a]+"(?![a-zA-Z\\-]+)","i"),e=e.replace(o,"")}return 0===e.length}function u(t,e){var r;if(t.getElementById&&(r=t.getElementById(e)),r)return r;var i,n,o=t.getElementsByTagName("*");for(n=0;n<o.length;n++)if(i=o[n],e===i.getAttribute("id"))return i}function f(t){for(var e=n(t,["use","svg:use"]),r=0;e.length&&r<e.length;){var i=e[r],o=i.getAttribute("xlink:href").substr(1),a=i.getAttribute("x")||0,s=i.getAttribute("y")||0,c=u(t,o).cloneNode(!0),l=(c.getAttribute("transform")||"")+" translate("+a+", "+s+")",h,f=e.length,p,g,v,m;if(d(c),/^svg$/i.test(c.nodeName)){var b=c.ownerDocument.createElement("g");for(g=0,v=c.attributes,m=v.length;g<m;g++)p=v.item(g),b.setAttribute(p.nodeName,p.nodeValue);for(;c.firstChild;)b.appendChild(c.firstChild);c=b}for(g=0,v=i.attributes,m=v.length;g<m;g++)p=v.item(g),"x"!==p.nodeName&&"y"!==p.nodeName&&"xlink:href"!==p.nodeName&&("transform"===p.nodeName?l=p.nodeValue+" "+l:c.setAttribute(p.nodeName,p.nodeValue));c.setAttribute("transform",l),c.setAttribute("instantiated_by_use","1"),c.removeAttribute("id"),h=i.parentNode,h.replaceChild(c,i),e.length===f&&r++}}function d(t){var e=t.getAttribute("viewBox"),r=1,i=1,n=0,o=0,a,s,c,l,h=t.getAttribute("width"),u=t.getAttribute("height"),f=t.getAttribute("x")||0,d=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",v=!e||!S.test(t.nodeName)||!(e=e.match(k)),m=!h||!u||"100%"===h||"100%"===u,b=v&&m,_={},w="";if(_.width=0,_.height=0,_.toBeParsed=b,b)return _;if(v)return _.width=y(h),_.height=y(u),_;if(n=-parseFloat(e[1]),o=-parseFloat(e[2]),a=parseFloat(e[3]),s=parseFloat(e[4]),m?(_.width=a,_.height=s):(_.width=y(h),_.height=y(u),r=_.width/a,i=_.height/s),p=g.util.parsePreserveAspectRatioAttribute(p),"none"!==p.alignX&&(i=r=r>i?i:r),1===r&&1===i&&0===n&&0===o&&0===f&&0===d)return _;if((f||d)&&(w=" translate("+y(f)+" "+y(d)+") "),c=w+" matrix("+r+" 0 0 "+i+" "+n*r+" "+o*i+") ","svg"===t.nodeName){for(l=t.ownerDocument.createElement("g");t.firstChild;)l.appendChild(t.firstChild);t.appendChild(l)}else l=t,c=l.getAttribute("transform")+c;return l.setAttribute("transform",c),_}function p(t,e){for(;t&&(t=t.parentNode);)if(t.nodeName&&e.test(t.nodeName.replace("svg:",""))&&!t.getAttribute("instantiated_by_use"))return!0;return!1}var g=t.fabric||(t.fabric={}),v=g.util.object.extend,m=g.util.object.clone,b=g.util.toFixed,y=g.util.parseUnit,_=g.util.multiplyTransformMatrices,w=/^(path|circle|polygon|polyline|ellipse|rect|line|image|text)$/i,S=/^(symbol|image|marker|pattern|view|svg)$/i,x=/^(?:pattern|defs|symbol|metadata|clipPath|mask)$/i,C=/^(symbol|g|a|svg)$/i,A={cx:"left",x:"left",r:"radius",cy:"top",y:"top",display:"visible",visibility:"visible",transform:"transformMatrix","fill-opacity":"fillOpacity","fill-rule":"fillRule","font-family":"fontFamily","font-size":"fontSize","font-style":"fontStyle","font-weight":"fontWeight","stroke-dasharray":"strokeDashArray","stroke-linecap":"strokeLineCap","stroke-linejoin":"strokeLineJoin","stroke-miterlimit":"strokeMiterLimit","stroke-opacity":"strokeOpacity","stroke-width":"strokeWidth","text-decoration":"textDecoration","text-anchor":"originX",opacity:"opacity"},T={stroke:"strokeOpacity",fill:"fillOpacity"};g.cssRules={},g.gradientDefs={},g.parseTransformAttribute=function(){function t(t,e){var r=Math.cos(e[0]),i=Math.sin(e[0]),n=0,o=0;3===e.length&&(n=e[1],o=e[2]),t[0]=r,t[1]=i,t[2]=-i,t[3]=r,t[4]=n-(r*n-i*o),t[5]=o-(i*n+r*o)}function e(t,e){var r=e[0],i=2===e.length?e[1]:e[0];t[0]=r,t[3]=i}function r(t,e,r){t[r]=Math.tan(g.util.degreesToRadians(e[0]))}function i(t,e){t[4]=e[0],2===e.length&&(t[5]=e[1])}var n=[1,0,0,1,0,0],o=g.reNum,a="(?:\\s+,?\\s*|,\\s*)",s="(?:(skewX)\\s*\\(\\s*("+o+")\\s*\\))",c="(?:(skewY)\\s*\\(\\s*("+o+")\\s*\\))",l="(?:(rotate)\\s*\\(\\s*("+o+")(?:"+a+"("+o+")"+a+"("+o+"))?\\s*\\))",h="(?:(scale)\\s*\\(\\s*("+o+")(?:"+a+"("+o+"))?\\s*\\))",u="(?:(translate)\\s*\\(\\s*("+o+")(?:"+a+"("+o+"))?\\s*\\))",f="(?:(matrix)\\s*\\(\\s*("+o+")"+a+"("+o+")"+a+"("+o+")"+a+"("+o+")"+a+"("+o+")"+a+"("+o+")\\s*\\))",d="(?:"+f+"|"+u+"|"+h+"|"+l+"|"+s+"|"+c+")",p="(?:"+d+"(?:"+a+"*"+d+")*)",v="^\\s*(?:"+p+"?)\\s*$",m=new RegExp(v),b=new RegExp(d,"g");return function(o){var a=n.concat(),s=[];if(!o||o&&!m.test(o))return a;o.replace(b,function(o){var c=new RegExp(d).exec(o).filter(function(t){return!!t}),l=c[1],h=c.slice(2).map(parseFloat);switch(l){case"translate":i(a,h);break;case"rotate":h[0]=g.util.degreesToRadians(h[0]),t(a,h);break;case"scale":e(a,h);break;case"skewX":r(a,h,2);break;case"skewY":r(a,h,1);break;case"matrix":a=h}s.push(a.concat()),a=n.concat()});for(var c=s[0];s.length>1;)s.shift(),c=g.util.multiplyTransformMatrices(c,s[0]);return c}}();var k=new RegExp("^\\s*("+g.reNum+"+)\\s*,?\\s*("+g.reNum+"+)\\s*,?\\s*("+g.reNum+"+)\\s*,?\\s*("+g.reNum+"+)\\s*$");g.parseSVGDocument=function(t,e,r,i){if(t){f(t);var n=g.Object.__uid++,o=d(t),a=g.util.toArray(t.getElementsByTagName("*"));if(o.crossOrigin=i&&i.crossOrigin,o.svgUid=n,0===a.length&&g.isLikelyNode){a=t.selectNodes('//*[name(.)!="svg"]');for(var s=[],c=0,l=a.length;c<l;c++)s[c]=a[c];a=s}var h=a.filter(function(t){return d(t),w.test(t.nodeName.replace("svg:",""))&&!p(t,x)});if(!h||h&&!h.length)return void(e&&e([],{}));g.gradientDefs[n]=g.getGradientDefs(t),g.cssRules[n]=g.getCSSRules(t),g.parseElements(h,function(t,r){e&&e(t,o,r,a)},m(o),r,i)}};var P=new RegExp("(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*("+g.reNum+"(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|"+g.reNum+"))?\\s+(.*)");v(g,{parseFontDeclaration:function(t,e){var r=t.match(P);if(r){var i=r[1],n=r[3],o=r[4],a=r[5],s=r[6];i&&(e.fontStyle=i),n&&(e.fontWeight=isNaN(parseFloat(n))?n:parseFloat(n)),o&&(e.fontSize=y(o)),s&&(e.fontFamily=s),a&&(e.lineHeight="normal"===a?1:a)}},getGradientDefs:function(t){var e=["linearGradient","radialGradient","svg:linearGradient","svg:radialGradient"],r=n(t,e),i,o=0,a,s,c={},l={};for(o=r.length;o--;)i=r[o],s=i.getAttribute("xlink:href"),a=i.getAttribute("id"),s&&(l[a]=s.substr(1)),c[a]=i;for(a in l){var h=c[l[a]].cloneNode(!0);for(i=c[a];h.firstChild;)i.appendChild(h.firstChild)}return c},parseAttributes:function(t,n,o){if(t){var a,c={},l;void 0===o&&(o=t.getAttribute("svgUid")),t.parentNode&&C.test(t.parentNode.nodeName)&&(c=g.parseAttributes(t.parentNode,n,o)),l=c&&c.fontSize||t.getAttribute("font-size")||g.Text.DEFAULT_SVG_FONT_SIZE;var h=n.reduce(function(e,r){return a=t.getAttribute(r),a&&(e[r]=a),e},{});h=v(h,v(s(t,o),g.parseStyleAttribute(t)));var u,f,d={};for(var p in h)u=e(p),f=r(u,h[p],c,l),d[u]=f;d&&d.font&&g.parseFontDeclaration(d.font,d);var m=v(c,d);return C.test(t.nodeName)?m:i(m)}},parseElements:function(t,e,r,i,n){new g.ElementsParser(t,e,r,i,n).parse()},parseStyleAttribute:function(t){var e={},r=t.getAttribute("style");return r?("string"==typeof r?o(r,e):a(r,e),e):e},parsePointsAttribute:function(t){if(!t)return null;t=t.replace(/,/g," ").trim(),t=t.split(/\s+/);var e=[],r,i;for(r=0,i=t.length;r<i;r+=2)e.push({x:parseFloat(t[r]),y:parseFloat(t[r+1])});return e},getCSSRules:function(t){for(var e=t.getElementsByTagName("style"),r={},i,n=0,o=e.length;n<o;n++){var a=e[n].textContent||e[n].text;a=a.replace(/\/\*[\s\S]*?\*\//g,""),""!==a.trim()&&(i=a.match(/[^{]*\{[\s\S]*?\}/g),i=i.map(function(t){return t.trim()}),i.forEach(function(t){for(var e=t.match(/([\s\S]*?)\s*\{([^}]*)\}/),i={},n=e[2].trim(),o=n.replace(/;$/,"").split(/\s*;\s*/),a=0,s=o.length;a<s;a++){var c=o[a].split(/\s*:\s*/),l=c[0],h=c[1];i[l]=h}t=e[1],t.split(",").forEach(function(t){""!==(t=t.replace(/^svg/i,"").trim())&&(r[t]?g.util.object.extend(r[t],i):r[t]=g.util.object.clone(i))})}))}return r},loadSVGFromURL:function(t,e,r,i){function n(t){var n=t.responseXML;n&&!n.documentElement&&g.window.ActiveXObject&&t.responseText&&(n=new ActiveXObject("Microsoft.XMLDOM"),n.async="false",n.loadXML(t.responseText.replace(/<!DOCTYPE[\s\S]*?(\[[\s\S]*\])*?>/i,""))),n&&n.documentElement||e&&e(null),g.parseSVGDocument(n.documentElement,function(t,r,i,n){e&&e(t,r,i,n)},r,i)}t=t.replace(/^\n\s*/,"").trim(),new g.util.request(t,{method:"get",onComplete:n})},loadSVGFromString:function(t,e,r,i){t=t.trim();var n;if("undefined"!=typeof DOMParser){var o=new DOMParser;o&&o.parseFromString&&(n=o.parseFromString(t,"text/xml"))}else g.window.ActiveXObject&&(n=new ActiveXObject("Microsoft.XMLDOM"),n.async="false",n.loadXML(t.replace(/<!DOCTYPE[\s\S]*?(\[[\s\S]*\])*?>/i,"")));g.parseSVGDocument(n.documentElement,function(t,r,i,n){e(t,r,i,n)},r,i)}})}(exports),fabric.ElementsParser=function(t,e,r,i,n){this.elements=t,this.callback=e,this.options=r,this.reviver=i,this.svgUid=r&&r.svgUid||0,this.parsingOptions=n},fabric.ElementsParser.prototype.parse=function(){this.instances=new Array(this.elements.length),this.numElements=this.elements.length,this.createObjects()},fabric.ElementsParser.prototype.createObjects=function(){for(var t=0,e=this.elements.length;t<e;t++)this.elements[t].setAttribute("svgUid",this.svgUid),function(t,e){setTimeout(function(){t.createObject(t.elements[e],e)},0)}(this,t)},fabric.ElementsParser.prototype.createObject=function(t,e){var r=fabric[fabric.util.string.capitalize(t.tagName.replace("svg:",""))];if(r&&r.fromElement)try{this._createObject(r,t,e)}catch(t){fabric.log(t)}else this.checkIfDone()},fabric.ElementsParser.prototype._createObject=function(t,e,r){t.fromElement(e,this.createCallback(r,e),this.options)},fabric.ElementsParser.prototype.createCallback=function(t,e){var r=this;return function(i){r.resolveGradient(i,"fill"),r.resolveGradient(i,"stroke"),i._removeTransformMatrix(),i instanceof fabric.Image&&i.parsePreserveAspectRatioAttribute(e),r.reviver&&r.reviver(e,i),r.instances[t]=i,r.checkIfDone()}},fabric.ElementsParser.prototype.resolveGradient=function(t,e){var r=t.get(e);if(/^url\(/.test(r)){var i=r.slice(5,r.length-1);fabric.gradientDefs[this.svgUid][i]&&t.set(e,fabric.Gradient.fromElement(fabric.gradientDefs[this.svgUid][i],t))}},fabric.ElementsParser.prototype.checkIfDone=function(){0==--this.numElements&&(this.instances=this.instances.filter(function(t){return null!=t}),this.callback(this.instances,this.elements))},function(t){"use strict";function e(t,e){this.x=t,this.y=e}var r=t.fabric||(t.fabric={});if(r.Point)return void r.warn("fabric.Point is already defined");r.Point=e,e.prototype={type:"point",constructor:e,add:function(t){return new e(this.x+t.x,this.y+t.y)},addEquals:function(t){return this.x+=t.x,this.y+=t.y,this},scalarAdd:function(t){return new e(this.x+t,this.y+t)},scalarAddEquals:function(t){return this.x+=t,this.y+=t,this},subtract:function(t){return new e(this.x-t.x,this.y-t.y)},subtractEquals:function(t){return this.x-=t.x,this.y-=t.y,this},scalarSubtract:function(t){return new e(this.x-t,this.y-t)},scalarSubtractEquals:function(t){return this.x-=t,this.y-=t,this},multiply:function(t){return new e(this.x*t,this.y*t)},multiplyEquals:function(t){return this.x*=t,this.y*=t,this},divide:function(t){return new e(this.x/t,this.y/t)},divideEquals:function(t){return this.x/=t,this.y/=t,this},eq:function(t){return this.x===t.x&&this.y===t.y},lt:function(t){return this.x<t.x&&this.y<t.y},lte:function(t){return this.x<=t.x&&this.y<=t.y},gt:function(t){return this.x>t.x&&this.y>t.y},gte:function(t){return this.x>=t.x&&this.y>=t.y},lerp:function(t,r){return void 0===r&&(r=.5),r=Math.max(Math.min(1,r),0),new e(this.x+(t.x-this.x)*r,this.y+(t.y-this.y)*r)},distanceFrom:function(t){var e=this.x-t.x,r=this.y-t.y;return Math.sqrt(e*e+r*r)},midPointFrom:function(t){return this.lerp(t)},min:function(t){return new e(Math.min(this.x,t.x),Math.min(this.y,t.y))},max:function(t){return new e(Math.max(this.x,t.x),Math.max(this.y,t.y))},toString:function(){return this.x+","+this.y},setXY:function(t,e){return this.x=t,this.y=e,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setFromPoint:function(t){return this.x=t.x,this.y=t.y,this},swap:function(t){var e=this.x,r=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=r},clone:function(){return new e(this.x,this.y)}}}(exports),function(t){"use strict";function e(t){this.status=t,this.points=[]}var r=t.fabric||(t.fabric={});if(r.Intersection)return void r.warn("fabric.Intersection is already defined");r.Intersection=e,r.Intersection.prototype={constructor:e,appendPoint:function(t){return this.points.push(t),this},appendPoints:function(t){return this.points=this.points.concat(t),this}},r.Intersection.intersectLineLine=function(t,i,n,o){var a,s=(o.x-n.x)*(t.y-n.y)-(o.y-n.y)*(t.x-n.x),c=(i.x-t.x)*(t.y-n.y)-(i.y-t.y)*(t.x-n.x),l=(o.y-n.y)*(i.x-t.x)-(o.x-n.x)*(i.y-t.y);if(0!==l){var h=s/l,u=c/l;0<=h&&h<=1&&0<=u&&u<=1?(a=new e("Intersection"),a.appendPoint(new r.Point(t.x+h*(i.x-t.x),t.y+h*(i.y-t.y)))):a=new e}else a=new e(0===s||0===c?"Coincident":"Parallel");return a},r.Intersection.intersectLinePolygon=function(t,r,i){for(var n=new e,o=i.length,a,s,c,l=0;l<o;l++)a=i[l],s=i[(l+1)%o],c=e.intersectLineLine(t,r,a,s),n.appendPoints(c.points);return n.points.length>0&&(n.status="Intersection"),n},r.Intersection.intersectPolygonPolygon=function(t,r){for(var i=new e,n=t.length,o=0;o<n;o++){var a=t[o],s=t[(o+1)%n],c=e.intersectLinePolygon(a,s,r);i.appendPoints(c.points)}return i.points.length>0&&(i.status="Intersection"),i},r.Intersection.intersectPolygonRectangle=function(t,i,n){var o=i.min(n),a=i.max(n),s=new r.Point(a.x,o.y),c=new r.Point(o.x,a.y),l=e.intersectLinePolygon(o,s,t),h=e.intersectLinePolygon(s,a,t),u=e.intersectLinePolygon(a,c,t),f=e.intersectLinePolygon(c,o,t),d=new e;return d.appendPoints(l.points),d.appendPoints(h.points),d.appendPoints(u.points),d.appendPoints(f.points),d.points.length>0&&(d.status="Intersection"),d}}(exports),function(t){"use strict";function e(t){t?this._tryParsingColor(t):this.setSource([0,0,0,1])}function r(t,e,r){return r<0&&(r+=1),r>1&&(r-=1),r<1/6?t+6*(e-t)*r:r<.5?e:r<2/3?t+(e-t)*(2/3-r)*6:t}var i=t.fabric||(t.fabric={});if(i.Color)return void i.warn("fabric.Color is already defined.");i.Color=e,i.Color.prototype={_tryParsingColor:function(t){var r;t in e.colorNameMap&&(t=e.colorNameMap[t]),"transparent"===t&&(r=[255,255,255,0]),r||(r=e.sourceFromHex(t)),r||(r=e.sourceFromRgb(t)),r||(r=e.sourceFromHsl(t)),r||(r=[0,0,0,1]),r&&this.setSource(r)},_rgbToHsl:function(t,e,r){t/=255,e/=255,r/=255;var n,o,a,s=i.util.array.max([t,e,r]),c=i.util.array.min([t,e,r]);if(a=(s+c)/2,s===c)n=o=0;else{var l=s-c;switch(o=a>.5?l/(2-s-c):l/(s+c),s){case t:n=(e-r)/l+(e<r?6:0);break;case e:n=(r-t)/l+2;break;case r:n=(t-e)/l+4}n/=6}return[Math.round(360*n),Math.round(100*o),Math.round(100*a)]},getSource:function(){return this._source},setSource:function(t){this._source=t},toRgb:function(){var t=this.getSource();return"rgb("+t[0]+","+t[1]+","+t[2]+")"},toRgba:function(){var t=this.getSource();return"rgba("+t[0]+","+t[1]+","+t[2]+","+t[3]+")"},toHsl:function(){var t=this.getSource(),e=this._rgbToHsl(t[0],t[1],t[2]);return"hsl("+e[0]+","+e[1]+"%,"+e[2]+"%)"},toHsla:function(){var t=this.getSource(),e=this._rgbToHsl(t[0],t[1],t[2]);return"hsla("+e[0]+","+e[1]+"%,"+e[2]+"%,"+t[3]+")"},toHex:function(){var t=this.getSource(),e,r,i;return e=t[0].toString(16),e=1===e.length?"0"+e:e,r=t[1].toString(16),r=1===r.length?"0"+r:r,i=t[2].toString(16),i=1===i.length?"0"+i:i,e.toUpperCase()+r.toUpperCase()+i.toUpperCase()},toHexa:function(){var t=this.getSource(),e;return e=255*t[3],e=e.toString(16),e=1===e.length?"0"+e:e,this.toHex()+e.toUpperCase()},getAlpha:function(){return this.getSource()[3]},setAlpha:function(t){var e=this.getSource();return e[3]=t,this.setSource(e),this},toGrayscale:function(){var t=this.getSource(),e=parseInt((.3*t[0]+.59*t[1]+.11*t[2]).toFixed(0),10),r=t[3];return this.setSource([e,e,e,r]),this},toBlackWhite:function(t){var e=this.getSource(),r=(.3*e[0]+.59*e[1]+.11*e[2]).toFixed(0),i=e[3];return t=t||127,r=Number(r)<Number(t)?0:255,this.setSource([r,r,r,i]),this},overlayWith:function(t){t instanceof e||(t=new e(t));for(var r=[],i=this.getAlpha(),n=.5,o=this.getSource(),a=t.getSource(),s=0;s<3;s++)r.push(Math.round(.5*o[s]+.5*a[s]));return r[3]=i,this.setSource(r),this}},i.Color.reRGBa=/^rgba?\(\s*(\d{1,3}(?:\.\d+)?\%?)\s*,\s*(\d{1,3}(?:\.\d+)?\%?)\s*,\s*(\d{1,3}(?:\.\d+)?\%?)\s*(?:\s*,\s*((?:\d*\.?\d+)?)\s*)?\)$/,i.Color.reHSLa=/^hsla?\(\s*(\d{1,3})\s*,\s*(\d{1,3}\%)\s*,\s*(\d{1,3}\%)\s*(?:\s*,\s*(\d+(?:\.\d+)?)\s*)?\)$/,i.Color.reHex=/^#?([0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{4}|[0-9a-f]{3})$/i,i.Color.colorNameMap={aqua:"#00FFFF",black:"#000000",blue:"#0000FF",fuchsia:"#FF00FF",gray:"#808080",grey:"#808080",green:"#008000",lime:"#00FF00",maroon:"#800000",navy:"#000080",olive:"#808000",orange:"#FFA500",purple:"#800080",red:"#FF0000",silver:"#C0C0C0",teal:"#008080",white:"#FFFFFF",yellow:"#FFFF00"},i.Color.fromRgb=function(t){return e.fromSource(e.sourceFromRgb(t))},i.Color.sourceFromRgb=function(t){var r=t.match(e.reRGBa);if(r){var i=parseInt(r[1],10)/(/%$/.test(r[1])?100:1)*(/%$/.test(r[1])?255:1),n=parseInt(r[2],10)/(/%$/.test(r[2])?100:1)*(/%$/.test(r[2])?255:1),o=parseInt(r[3],10)/(/%$/.test(r[3])?100:1)*(/%$/.test(r[3])?255:1);return[parseInt(i,10),parseInt(n,10),parseInt(o,10),r[4]?parseFloat(r[4]):1]}},i.Color.fromRgba=e.fromRgb,i.Color.fromHsl=function(t){return e.fromSource(e.sourceFromHsl(t))},i.Color.sourceFromHsl=function(t){var i=t.match(e.reHSLa);if(i){var n=(parseFloat(i[1])%360+360)%360/360,o=parseFloat(i[2])/(/%$/.test(i[2])?100:1),a=parseFloat(i[3])/(/%$/.test(i[3])?100:1),s,c,l;if(0===o)s=c=l=a;else{var h=a<=.5?a*(o+1):a+o-a*o,u=2*a-h;s=r(u,h,n+1/3),c=r(u,h,n),l=r(u,h,n-1/3)}return[Math.round(255*s),Math.round(255*c),Math.round(255*l),i[4]?parseFloat(i[4]):1]}},i.Color.fromHsla=e.fromHsl,i.Color.fromHex=function(t){return e.fromSource(e.sourceFromHex(t))},i.Color.sourceFromHex=function(t){if(t.match(e.reHex)){var r=t.slice(t.indexOf("#")+1),i=3===r.length||4===r.length,n=8===r.length||4===r.length,o=i?r.charAt(0)+r.charAt(0):r.substring(0,2),a=i?r.charAt(1)+r.charAt(1):r.substring(2,4),s=i?r.charAt(2)+r.charAt(2):r.substring(4,6),c=n?i?r.charAt(3)+r.charAt(3):r.substring(6,8):"FF";return[parseInt(o,16),parseInt(a,16),parseInt(s,16),parseFloat((parseInt(c,16)/255).toFixed(2))]}},i.Color.fromSource=function(t){var r=new e;return r.setSource(t),r}}(exports),function(){function t(t){var e=t.getAttribute("style"),r=t.getAttribute("offset")||0,i,n,o;if(r=parseFloat(r)/(/%$/.test(r)?100:1),r=r<0?0:r>1?1:r,e){var a=e.split(/\s*;\s*/);""===a[a.length-1]&&a.pop();for(var s=a.length;s--;){var c=a[s].split(/\s*:\s*/),l=c[0].trim(),h=c[1].trim();"stop-color"===l?i=h:"stop-opacity"===l&&(o=h)}}return i||(i=t.getAttribute("stop-color")||"rgb(0,0,0)"),o||(o=t.getAttribute("stop-opacity")),i=new fabric.Color(i),n=i.getAlpha(),o=isNaN(parseFloat(o))?1:parseFloat(o),o*=n,{offset:r,color:i.toRgb(),opacity:o}}function e(t){return{x1:t.getAttribute("x1")||0,y1:t.getAttribute("y1")||0,x2:t.getAttribute("x2")||"100%",y2:t.getAttribute("y2")||0}}function r(t){return{x1:t.getAttribute("fx")||t.getAttribute("cx")||"50%",y1:t.getAttribute("fy")||t.getAttribute("cy")||"50%",r1:0,x2:t.getAttribute("cx")||"50%",y2:t.getAttribute("cy")||"50%",r2:t.getAttribute("r")||"50%"}}function i(t,e,r){var i,n=0,o=1,a="";for(var s in e)"Infinity"===e[s]?e[s]=1:"-Infinity"===e[s]&&(e[s]=0),i=parseFloat(e[s],10),o="string"==typeof e[s]&&/^\d+%$/.test(e[s])?.01:1,"x1"===s||"x2"===s||"r2"===s?(o*="objectBoundingBox"===r?t.width:1,n="objectBoundingBox"===r?t.left||0:0):"y1"!==s&&"y2"!==s||(o*="objectBoundingBox"===r?t.height:1,n="objectBoundingBox"===r?t.top||0:0),e[s]=i*o+n;if("ellipse"===t.type&&null!==e.r2&&"objectBoundingBox"===r&&t.rx!==t.ry){var c=t.ry/t.rx;a=" scale(1, "+c+")",e.y1&&(e.y1/=c),e.y2&&(e.y2/=c)}return a}var n=fabric.util.object.clone;fabric.Gradient=fabric.util.createClass({offsetX:0,offsetY:0,initialize:function(t){t||(t={});var e={};this.id=fabric.Object.__uid++,this.type=t.type||"linear",e={x1:t.coords.x1||0,y1:t.coords.y1||0,x2:t.coords.x2||0,y2:t.coords.y2||0},"radial"===this.type&&(e.r1=t.coords.r1||0,e.r2=t.coords.r2||0),this.coords=e,this.colorStops=t.colorStops.slice(),t.gradientTransform&&(this.gradientTransform=t.gradientTransform),this.offsetX=t.offsetX||this.offsetX,this.offsetY=t.offsetY||this.offsetY},addColorStop:function(t){for(var e in t){var r=new fabric.Color(t[e]);this.colorStops.push({offset:parseFloat(e),color:r.toRgb(),opacity:r.getAlpha()})}return this},toObject:function(t){var e={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return fabric.util.populateWithProperties(this,e,t),e},toSVG:function(t){var e=n(this.coords,!0),r,i,o=n(this.colorStops,!0),a=e.r1>e.r2;o.sort(function(t,e){return t.offset-e.offset});for(var s in e)"x1"===s||"x2"===s?e[s]+=this.offsetX-t.width/2:"y1"!==s&&"y2"!==s||(e[s]+=this.offsetY-t.height/2);if(i='id="SVGID_'+this.id+'" gradientUnits="userSpaceOnUse"',this.gradientTransform&&(i+=' gradientTransform="matrix('+this.gradientTransform.join(" ")+')" '),"linear"===this.type?r=["<linearGradient ",i,' x1="',e.x1,'" y1="',e.y1,'" x2="',e.x2,'" y2="',e.y2,'">\n']:"radial"===this.type&&(r=["<radialGradient ",i,' cx="',a?e.x1:e.x2,'" cy="',a?e.y1:e.y2,'" r="',a?e.r1:e.r2,'" fx="',a?e.x2:e.x1,'" fy="',a?e.y2:e.y1,'">\n']),"radial"===this.type){if(a){o=o.concat(),o.reverse();for(var c=0;c<o.length;c++)o[c].offset=1-o[c].offset}var l=Math.min(e.r1,e.r2);if(l>0)for(var h=Math.max(e.r1,e.r2),u=l/h,c=0;c<o.length;c++)o[c].offset+=u*(1-o[c].offset)}for(var c=0;c<o.length;c++){var f=o[c];r.push("<stop ",'offset="',100*f.offset+"%",'" style="stop-color:',f.color,null!==f.opacity?";stop-opacity: "+f.opacity:";",'"/>\n')}return r.push("linear"===this.type?"</linearGradient>\n":"</radialGradient>\n"),r.join("")},toLive:function(t){var e,r=fabric.util.object.clone(this.coords);if(this.type){"linear"===this.type?e=t.createLinearGradient(r.x1,r.y1,r.x2,r.y2):"radial"===this.type&&(e=t.createRadialGradient(r.x1,r.y1,r.r1,r.x2,r.y2,r.r2));for(var i=0,n=this.colorStops.length;i<n;i++){var o=this.colorStops[i].color,a=this.colorStops[i].opacity,s=this.colorStops[i].offset;void 0!==a&&(o=new fabric.Color(o).setAlpha(a).toRgba()),e.addColorStop(s,o)}return e}}}),fabric.util.object.extend(fabric.Gradient,{fromElement:function(n,o){var a=n.getElementsByTagName("stop"),s,c=n.getAttribute("gradientUnits")||"objectBoundingBox",l=n.getAttribute("gradientTransform"),h=[],u,f;s="linearGradient"===n.nodeName||"LINEARGRADIENT"===n.nodeName?"linear":"radial","linear"===s?u=e(n):"radial"===s&&(u=r(n));for(var d=a.length;d--;)h.push(t(a[d]));f=i(o,u,c);var p=new fabric.Gradient({type:s,coords:u,colorStops:h,offsetX:-o.left,offsetY:-o.top});return(l||""!==f)&&(p.gradientTransform=fabric.parseTransformAttribute((l||"")+f)),p},forObject:function(t,e){return e||(e={}),i(t,e.coords,"userSpaceOnUse"),new fabric.Gradient(e)}})}(),function(){"use strict";var t=fabric.util.toFixed;fabric.Pattern=fabric.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,initialize:function(t,e){if(t||(t={}),this.id=fabric.Object.__uid++,this.setOptions(t),!t.source||t.source&&"string"!=typeof t.source)return void(e&&e(this));if(void 0!==fabric.util.getFunctionBody(t.source))this.source=new Function(fabric.util.getFunctionBody(t.source)),e&&e(this);else{var r=this;this.source=fabric.util.createImage(),fabric.util.loadImage(t.source,function(t){r.source=t,e&&e(r)})}},toObject:function(e){var r=fabric.Object.NUM_FRACTION_DIGITS,i,n;return"function"==typeof this.source?i=String(this.source):"string"==typeof this.source.src?i=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(i=this.source.toDataURL()),n={type:"pattern",source:i,repeat:this.repeat,offsetX:t(this.offsetX,r),offsetY:t(this.offsetY,r)},fabric.util.populateWithProperties(this,n,e),n},toSVG:function(t){var e="function"==typeof this.source?this.source():this.source,r=e.width/t.width,i=e.height/t.height,n=this.offsetX/t.width,o=this.offsetY/t.height,a="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(i=1),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(r=1),e.src?a=e.src:e.toDataURL&&(a=e.toDataURL()),'<pattern id="SVGID_'+this.id+'" x="'+n+'" y="'+o+'" width="'+r+'" height="'+i+'">\n<image x="0" y="0" width="'+e.width+'" height="'+e.height+'" xlink:href="'+a+'"></image>\n</pattern>\n'},setOptions:function(t){for(var e in t)this[e]=t[e]},toLive:function(t){var e="function"==typeof this.source?this.source():this.source;if(!e)return"";if(void 0!==e.src){if(!e.complete)return"";if(0===e.naturalWidth||0===e.naturalHeight)return""}return t.createPattern(e,this.repeat)}})}(),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.util.toFixed;if(e.Shadow)return void e.warn("fabric.Shadow is already defined.");e.Shadow=e.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,initialize:function(t){"string"==typeof t&&(t=this._parseShadow(t));for(var r in t)this[r]=t[r];this.id=e.Object.__uid++},_parseShadow:function(t){var r=t.trim(),i=e.Shadow.reOffsetsAndBlur.exec(r)||[];return{color:(r.replace(e.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseInt(i[1],10)||0,offsetY:parseInt(i[2],10)||0,blur:parseInt(i[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(t){var i=40,n=40,o=e.Object.NUM_FRACTION_DIGITS,a=e.util.rotateVector({x:this.offsetX,y:this.offsetY},e.util.degreesToRadians(-t.angle)),s=20;return t.width&&t.height&&(i=100*r((Math.abs(a.x)+this.blur)/t.width,o)+20,n=100*r((Math.abs(a.y)+this.blur)/t.height,o)+20),t.flipX&&(a.x*=-1),t.flipY&&(a.y*=-1),'<filter id="SVGID_'+this.id+'" y="-'+n+'%" height="'+(100+2*n)+'%" x="-'+i+'%" width="'+(100+2*i)+'%" >\n\t<feGaussianBlur in="SourceAlpha" stdDeviation="'+r(this.blur?this.blur/2:0,o)+'"></feGaussianBlur>\n\t<feOffset dx="'+r(a.x,o)+'" dy="'+r(a.y,o)+'" result="oBlur" ></feOffset>\n\t<feFlood flood-color="'+this.color+'"/>\n\t<feComposite in2="oBlur" operator="in" />\n\t<feMerge>\n\t\t<feMergeNode></feMergeNode>\n\t\t<feMergeNode in="SourceGraphic"></feMergeNode>\n\t</feMerge>\n</filter>\n'},toObject:function(){if(this.includeDefaultValues)return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke};var t={},r=e.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke"].forEach(function(e){this[e]!==r[e]&&(t[e]=this[e])},this),t}}),e.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:px)?(?:\s?|$))?(-?\d+(?:px)?(?:\s?|$))?(\d+(?:px)?)?(?:\s?|$)(?:$|\s)/}(exports),function(){"use strict";if(fabric.StaticCanvas)return void fabric.warn("fabric.StaticCanvas is already defined.");var t=fabric.util.object.extend,e=fabric.util.getElementOffset,r=fabric.util.removeFromArray,i=fabric.util.toFixed,n=fabric.util.transformPoint,o=fabric.util.invertTransform,a=new Error("Could not initialize `canvas` element");fabric.StaticCanvas=fabric.util.createClass(fabric.CommonMethods,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(t,e)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,clipTo:null,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:fabric.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,onBeforeScaleRotate:function(){},enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,_initStatic:function(t,e){var r=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(t),this._initOptions(e),this._setImageSmoothing(),this.interactive||this._initRetinaScaling(),e.overlayImage&&this.setOverlayImage(e.overlayImage,r),e.backgroundImage&&this.setBackgroundImage(e.backgroundImage,r),e.backgroundColor&&this.setBackgroundColor(e.backgroundColor,r),e.overlayColor&&this.setOverlayColor(e.overlayColor,r),this.calcOffset()},_isRetinaScaling:function(){return 1!==fabric.devicePixelRatio&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?fabric.devicePixelRatio:1},_initRetinaScaling:function(){this._isRetinaScaling()&&(this.lowerCanvasEl.setAttribute("width",this.width*fabric.devicePixelRatio),this.lowerCanvasEl.setAttribute("height",this.height*fabric.devicePixelRatio),this.contextContainer.scale(fabric.devicePixelRatio,fabric.devicePixelRatio))},calcOffset:function(){return this._offset=e(this.lowerCanvasEl),this},setOverlayImage:function(t,e,r){return this.__setBgOverlayImage("overlayImage",t,e,r)},setBackgroundImage:function(t,e,r){return this.__setBgOverlayImage("backgroundImage",t,e,r)},setOverlayColor:function(t,e){return this.__setBgOverlayColor("overlayColor",t,e)},setBackgroundColor:function(t,e){return this.__setBgOverlayColor("backgroundColor",t,e)},_setImageSmoothing:function(){var t=this.getContext();t.imageSmoothingEnabled=t.imageSmoothingEnabled||t.webkitImageSmoothingEnabled||t.mozImageSmoothingEnabled||t.msImageSmoothingEnabled||t.oImageSmoothingEnabled,t.imageSmoothingEnabled=this.imageSmoothingEnabled},__setBgOverlayImage:function(t,e,r,i){return"string"==typeof e?fabric.util.loadImage(e,function(e){e&&(this[t]=new fabric.Image(e,i)),r&&r(e)},this,i&&i.crossOrigin):(i&&e.setOptions(i),this[t]=e,r&&r(e)),this},__setBgOverlayColor:function(t,e,r){return this[t]=e,this._initGradient(e,t),this._initPattern(e,t,r),this},_createCanvasElement:function(t){var e=fabric.util.createCanvasElement(t);if(e.style||(e.style={}),!e)throw a;if(void 0===e.getContext)throw a;return e},_initOptions:function(t){this._setOptions(t),this.width=this.width||parseInt(this.lowerCanvasEl.width,10)||0,this.height=this.height||parseInt(this.lowerCanvasEl.height,10)||0,this.lowerCanvasEl.style&&(this.lowerCanvasEl.width=this.width,this.lowerCanvasEl.height=this.height,this.lowerCanvasEl.style.width=this.width+"px",this.lowerCanvasEl.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(t){this.lowerCanvasEl=fabric.util.getById(t)||this._createCanvasElement(t),fabric.util.addClass(this.lowerCanvasEl,"lower-canvas"),this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(t,e){return this.setDimensions({width:t},e)},setHeight:function(t,e){return this.setDimensions({height:t},e)},setDimensions:function(t,e){var r;e=e||{};for(var i in t)r=t[i],e.cssOnly||(this._setBackstoreDimension(i,t[i]),r+="px"),e.backstoreOnly||this._setCssDimension(i,r);return this._initRetinaScaling(),this._setImageSmoothing(),this.calcOffset(),e.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(t,e){return this.lowerCanvasEl[t]=e,this.upperCanvasEl&&(this.upperCanvasEl[t]=e),this.cacheCanvasEl&&(this.cacheCanvasEl[t]=e),this[t]=e,this},_setCssDimension:function(t,e){return this.lowerCanvasEl.style[t]=e,this.upperCanvasEl&&(this.upperCanvasEl.style[t]=e),this.wrapperEl&&(this.wrapperEl.style[t]=e),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(t){var e=this._activeObject,r,i=!1,n=!0;this.viewportTransform=t;for(var o=0,a=this._objects.length;o<a;o++)r=this._objects[o],r.group||r.setCoords(!1,!0);return e&&"activeSelection"===e.type&&e.setCoords(!1,!0),this.calcViewportBoundaries(),this.renderOnAddRemove&&this.requestRenderAll(),this},zoomToPoint:function(t,e){var r=t,i=this.viewportTransform.slice(0);t=n(t,o(this.viewportTransform)),i[0]=e,i[3]=e;var a=n(t,i);return i[4]+=r.x-a.x,i[5]+=r.y-a.y,this.setViewportTransform(i)},setZoom:function(t){return this.zoomToPoint(new fabric.Point(0,0),t),this},absolutePan:function(t){var e=this.viewportTransform.slice(0);return e[4]=-t.x,e[5]=-t.y,this.setViewportTransform(e)},relativePan:function(t){return this.absolutePan(new fabric.Point(-t.x-this.viewportTransform[4],-t.y-this.viewportTransform[5]))},getElement:function(){return this.lowerCanvasEl},_onObjectAdded:function(t){this.stateful&&t.setupState(),t._set("canvas",this),t.setCoords(),this.fire("object:added",{target:t}),t.fire("added")},_onObjectRemoved:function(t){this.fire("object:removed",{target:t}),t.fire("removed"),delete t.canvas},clearContext:function(t){return t.clearRect(0,0,this.width,this.height),this},getContext:function(){return this.contextContainer},clear:function(){return this._objects.length=0,this.backgroundImage=null,this.overlayImage=null,this.backgroundColor="",this.overlayColor="",this._hasITextHandlers&&(this.off("mouse:up",this._mouseUpITextHandler),this._iTextInstances=null,this._hasITextHandlers=!1),this.clearContext(this.contextContainer),this.fire("canvas:cleared"),this.renderOnAddRemove&&this.requestRenderAll(),this},renderAll:function(){var t=this.contextContainer;return this.renderCanvas(t,this._objects),this},renderAndReset:function(){this.renderAll(),this.isRendering=!1},requestRenderAll:function(){return this.isRendering||(this.isRendering=!0,fabric.util.requestAnimFrame(this.renderAndResetBound)),this},calcViewportBoundaries:function(){var t={},e=this.width,r=this.height,i=o(this.viewportTransform);return t.tl=n({x:0,y:0},i),t.br=n({x:e,y:r},i),t.tr=new fabric.Point(t.br.x,t.tl.y),t.bl=new fabric.Point(t.tl.x,t.br.y),this.vptCoords=t,t},renderCanvas:function(t,e){this.calcViewportBoundaries(),this.clearContext(t),this.fire("before:render"),this.clipTo&&fabric.util.clipContext(this,t),this._renderBackground(t),t.save(),t.transform.apply(t,this.viewportTransform),this._renderObjects(t,e),t.restore(),!this.controlsAboveOverlay&&this.interactive&&this.drawControls(t),this.clipTo&&t.restore(),this._renderOverlay(t),this.controlsAboveOverlay&&this.interactive&&this.drawControls(t),this.fire("after:render")},_renderObjects:function(t,e){for(var r=0,i=e.length;r<i;++r)e[r]&&e[r].render(t)},_renderBackgroundOrOverlay:function(t,e){var r=this[e+"Color"];r&&(t.fillStyle=r.toLive?r.toLive(t,this):r,t.fillRect(r.offsetX||0,r.offsetY||0,this.width,this.height)),(r=this[e+"Image"])&&(this[e+"Vpt"]&&(t.save(),t.transform.apply(t,this.viewportTransform)),r.render(t),this[e+"Vpt"]&&t.restore())},_renderBackground:function(t){this._renderBackgroundOrOverlay(t,"background")},_renderOverlay:function(t){this._renderBackgroundOrOverlay(t,"overlay")},getCenter:function(){return{top:this.height/2,left:this.width/2}},centerObjectH:function(t){return this._centerObject(t,new fabric.Point(this.getCenter().left,t.getCenterPoint().y))},centerObjectV:function(t){return this._centerObject(t,new fabric.Point(t.getCenterPoint().x,this.getCenter().top))},centerObject:function(t){var e=this.getCenter();return this._centerObject(t,new fabric.Point(e.left,e.top))},viewportCenterObject:function(t){var e=this.getVpCenter();return this._centerObject(t,e)},viewportCenterObjectH:function(t){var e=this.getVpCenter();return this._centerObject(t,new fabric.Point(e.x,t.getCenterPoint().y)),this},viewportCenterObjectV:function(t){var e=this.getVpCenter();return this._centerObject(t,new fabric.Point(t.getCenterPoint().x,e.y))},getVpCenter:function(){var t=this.getCenter(),e=o(this.viewportTransform);return n({x:t.left,y:t.top},e)},_centerObject:function(t,e){return t.setPositionByOrigin(e,"center","center"),this.requestRenderAll(),this},toDatalessJSON:function(t){return this.toDatalessObject(t)},toObject:function(t){return this._toObjectMethod("toObject",t)},toDatalessObject:function(t){return this._toObjectMethod("toDatalessObject",t)},_toObjectMethod:function(e,r){var i={objects:this._toObjects(e,r)};return t(i,this.__serializeBgOverlay(e,r)),fabric.util.populateWithProperties(this,i,r),i},_toObjects:function(t,e){return this.getObjects().filter(function(t){return!t.excludeFromExport}).map(function(r){return this._toObject(r,t,e)},this)},_toObject:function(t,e,r){var i;this.includeDefaultValues||(i=t.includeDefaultValues,t.includeDefaultValues=!1);var n=t[e](r);return this.includeDefaultValues||(t.includeDefaultValues=i),n},__serializeBgOverlay:function(t,e){var r={},i=this.backgroundImage,n=this.overlayImage;return this.backgroundColor&&(r.background=this.backgroundColor.toObject?this.backgroundColor.toObject(e):this.backgroundColor),this.overlayColor&&(r.overlay=this.overlayColor.toObject?this.overlayColor.toObject(e):this.overlayColor),i&&!i.excludeFromExport&&(r.backgroundImage=this._toObject(i,t,e)),n&&!n.excludeFromExport&&(r.overlayImage=this._toObject(n,t,e)),r},svgViewportTransformation:!0,toSVG:function(t,e){t||(t={});var r=[];return this._setSVGPreamble(r,t),this._setSVGHeader(r,t),this._setSVGBgOverlayColor(r,"backgroundColor"),this._setSVGBgOverlayImage(r,"backgroundImage",e),this._setSVGObjects(r,e),this._setSVGBgOverlayColor(r,"overlayColor"),this._setSVGBgOverlayImage(r,"overlayImage",e),r.push("</svg>"),r.join("")},_setSVGPreamble:function(t,e){e.suppressPreamble||t.push('<?xml version="1.0" encoding="',e.encoding||"UTF-8",'" standalone="no" ?>\n','<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ','"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n')},_setSVGHeader:function(t,e){var r=e.width||this.width,n=e.height||this.height,o,a='viewBox="0 0 '+this.width+" "+this.height+'" ',s=fabric.Object.NUM_FRACTION_DIGITS;e.viewBox?a='viewBox="'+e.viewBox.x+" "+e.viewBox.y+" "+e.viewBox.width+" "+e.viewBox.height+'" ':this.svgViewportTransformation&&(o=this.viewportTransform,a='viewBox="'+i(-o[4]/o[0],s)+" "+i(-o[5]/o[3],s)+" "+i(this.width/o[0],s)+" "+i(this.height/o[3],s)+'" '),t.push("<svg ",'xmlns="http://www.w3.org/2000/svg" ','xmlns:xlink="http://www.w3.org/1999/xlink" ','version="1.1" ','width="',r,'" ','height="',n,'" ',a,'xml:space="preserve">\n',"<desc>Created with Fabric.js ",fabric.version,"</desc>\n","<defs>\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),"</defs>\n")},createSVGRefElementsMarkup:function(){var t=this;return["backgroundColor","overlayColor"].map(function(e){var r=t[e];if(r&&r.toLive)return r.toSVG(t,!1)}).join("")},createSVGFontFacesMarkup:function(){for(var t="",e={},r,i,n,o,a,s,c,l=fabric.fontPaths,h=this.getObjects(),u=0,f=h.length;u<f;u++)if(r=h[u],i=r.fontFamily,-1!==r.type.indexOf("text")&&!e[i]&&l[i]&&(e[i]=!0,r.styles)){n=r.styles;for(a in n){o=n[a];for(c in o)s=o[c],i=s.fontFamily,!e[i]&&l[i]&&(e[i]=!0)}}for(var d in e)t+=["\t\t@font-face {\n","\t\t\tfont-family: '",d,"';\n","\t\t\tsrc: url('",l[d],"');\n","\t\t}\n"].join("");return t&&(t=['\t<style type="text/css">',"<![CDATA[\n",t,"]]>","</style>\n"].join("")),t},_setSVGObjects:function(t,e){for(var r,i=0,n=this.getObjects(),o=n.length;i<o;i++)r=n[i],r.excludeFromExport||this._setSVGObject(t,r,e)},_setSVGObject:function(t,e,r){t.push(e.toSVG(r))},_setSVGBgOverlayImage:function(t,e,r){this[e]&&this[e].toSVG&&t.push(this[e].toSVG(r))},_setSVGBgOverlayColor:function(t,e){var r=this[e];if(r)if(r.toLive){var i=r.repeat;t.push('<rect transform="translate(',this.width/2,",",this.height/2,')"',' x="',r.offsetX-this.width/2,'" y="',r.offsetY-this.height/2,'" ','width="',"repeat-y"===i||"no-repeat"===i?r.source.width:this.width,'" height="',"repeat-x"===i||"no-repeat"===i?r.source.height:this.height,'" fill="url(#SVGID_'+r.id+')"',"></rect>\n")}else t.push('<rect x="0" y="0" ','width="',this.width,'" height="',this.height,'" fill="',this[e],'"',"></rect>\n")},sendToBack:function(t){if(!t)return this;var e=this._activeObject,i,n,o;if(t===e&&"activeSelection"===t.type)for(o=e._objects,i=o.length;i--;)n=o[i],r(this._objects,n),this._objects.unshift(n);else r(this._objects,t),this._objects.unshift(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(t){if(!t)return this;var e=this._activeObject,i,n,o;if(t===e&&"activeSelection"===t.type)for(o=e._objects,i=0;i<o.length;i++)n=o[i],r(this._objects,n),this._objects.push(n);else r(this._objects,t),this._objects.push(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},sendBackwards:function(t,e){if(!t)return this;var i=this._activeObject,n,o,a,s,c,l=0;if(t===i&&"activeSelection"===t.type)for(c=i._objects,n=0;n<c.length;n++)o=c[n],a=this._objects.indexOf(o),a>0+l&&(s=a-1,r(this._objects,o),this._objects.splice(s,0,o)),l++;else 0!==(a=this._objects.indexOf(t))&&(s=this._findNewLowerIndex(t,a,e),r(this._objects,t),this._objects.splice(s,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(t,e,r){var i;if(r){i=e;for(var n=e-1;n>=0;--n){if(t.intersectsWithObject(this._objects[n])||t.isContainedWithinObject(this._objects[n])||this._objects[n].isContainedWithinObject(t)){i=n;break}}}else i=e-1;return i},bringForward:function(t,e){if(!t)return this;var i=this._activeObject,n,o,a,s,c,l=0;if(t===i&&"activeSelection"===t.type)for(c=i._objects,n=c.length;n--;)o=c[n],a=this._objects.indexOf(o),a<this._objects.length-1-l&&(s=a+1,r(this._objects,o),this._objects.splice(s,0,o)),l++;else(a=this._objects.indexOf(t))!==this._objects.length-1&&(s=this._findNewUpperIndex(t,a,e),r(this._objects,t),this._objects.splice(s,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewUpperIndex:function(t,e,r){var i;if(r){i=e;for(var n=e+1;n<this._objects.length;++n){if(t.intersectsWithObject(this._objects[n])||t.isContainedWithinObject(this._objects[n])||this._objects[n].isContainedWithinObject(t)){i=n;break}}}else i=e+1;return i},moveTo:function(t,e){return r(this._objects,t),this._objects.splice(e,0,t),this.renderOnAddRemove&&this.requestRenderAll()},dispose:function(){return this.clear(),this},toString:function(){return"#<fabric.Canvas ("+this.complexity()+"): { objects: "+this.getObjects().length+" }>"}}),t(fabric.StaticCanvas.prototype,fabric.Observable),t(fabric.StaticCanvas.prototype,fabric.Collection),t(fabric.StaticCanvas.prototype,fabric.DataURLExporter),t(fabric.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(t){var e=fabric.util.createCanvasElement();if(!e||!e.getContext)return null;var r=e.getContext("2d");if(!r)return null;switch(t){case"getImageData":return void 0!==r.getImageData;case"setLineDash":return void 0!==r.setLineDash;case"toDataURL":return void 0!==e.toDataURL;case"toDataURLWithQuality":try{return e.toDataURL("image/jpeg",0),!0}catch(t){}return!1;default:return null}}}),fabric.StaticCanvas.prototype.toJSON=fabric.StaticCanvas.prototype.toObject}(),fabric.BaseBrush=fabric.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeDashArray:null,setShadow:function(t){return this.shadow=new fabric.Shadow(t),this},_setBrushStyles:function(){var t=this.canvas.contextTop;t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.lineJoin=this.strokeLineJoin,this.strokeDashArray&&fabric.StaticCanvas.supports("setLineDash")&&t.setLineDash(this.strokeDashArray)},_setShadow:function(){if(this.shadow){var t=this.canvas.contextTop,e=this.canvas.getZoom();t.shadowColor=this.shadow.color,t.shadowBlur=this.shadow.blur*e,t.shadowOffsetX=this.shadow.offsetX*e,t.shadowOffsetY=this.shadow.offsetY*e}},_resetShadow:function(){var t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0}}),function(){fabric.PencilBrush=fabric.util.createClass(fabric.BaseBrush,{initialize:function(t){this.canvas=t,this._points=[]},onMouseDown:function(t){this._prepareForDrawing(t),this._captureDrawingPath(t),this._render()},onMouseMove:function(t){this._captureDrawingPath(t),this.canvas.clearContext(this.canvas.contextTop),this._render()},onMouseUp:function(){this._finalizeAndAddPath()},_prepareForDrawing:function(t){var e=new fabric.Point(t.x,t.y);this._reset(),this._addPoint(e),this.canvas.contextTop.moveTo(e.x,e.y)},_addPoint:function(t){this._points.push(t)},_reset:function(){this._points.length=0,this._setBrushStyles(),this._setShadow()},_captureDrawingPath:function(t){var e=new fabric.Point(t.x,t.y);this._addPoint(e)},_render:function(){var t=this.canvas.contextTop,e=this.canvas.viewportTransform,r=this._points[0],i=this._points[1];t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5]),t.beginPath(),2===this._points.length&&r.x===i.x&&r.y===i.y&&(r.x-=.5,i.x+=.5),t.moveTo(r.x,r.y);for(var n=1,o=this._points.length;n<o;n++){var a=r.midPointFrom(i);t.quadraticCurveTo(r.x,r.y,a.x,a.y),r=this._points[n],i=this._points[n+1]}t.lineTo(r.x,r.y),t.stroke(),t.restore()},convertPointsToSVGPath:function(t){var e=[],r=new fabric.Point(t[0].x,t[0].y),i=new fabric.Point(t[1].x,t[1].y);e.push("M ",t[0].x," ",t[0].y," ");for(var n=1,o=t.length;n<o;n++){var a=r.midPointFrom(i);e.push("Q ",r.x," ",r.y," ",a.x," ",a.y," "),r=new fabric.Point(t[n].x,t[n].y),n+1<t.length&&(i=new fabric.Point(t[n+1].x,t[n+1].y))}return e.push("L ",r.x," ",r.y," "),e},createPath:function(t){var e=new fabric.Path(t,{fill:null,stroke:this.color,strokeWidth:this.width,strokeLineCap:this.strokeLineCap,strokeLineJoin:this.strokeLineJoin,strokeDashArray:this.strokeDashArray,originX:"center",originY:"center"});return this.shadow&&(this.shadow.affectStroke=!0,e.setShadow(this.shadow)),e},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath();var t=this.convertPointsToSVGPath(this._points).join("");if("M 0 0 Q 0 0 0 0 L 0 0"===t)return void this.canvas.requestRenderAll();var e=this.createPath(t);this.canvas.add(e),e.setCoords(),this.canvas.clearContext(this.canvas.contextTop),this._resetShadow(),this.canvas.requestRenderAll(),this.canvas.fire("path:created",{path:e})}})}(),fabric.CircleBrush=fabric.util.createClass(fabric.BaseBrush,{width:10,initialize:function(t){this.canvas=t,this.points=[]},drawDot:function(t){var e=this.addPoint(t),r=this.canvas.contextTop,i=this.canvas.viewportTransform;r.save(),r.transform(i[0],i[1],i[2],i[3],i[4],i[5]),r.fillStyle=e.fill,r.beginPath(),r.arc(e.x,e.y,e.radius,0,2*Math.PI,!1),r.closePath(),r.fill(),r.restore()},onMouseDown:function(t){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(t)},onMouseMove:function(t){this.drawDot(t)},onMouseUp:function(){var t=this.canvas.renderOnAddRemove;this.canvas.renderOnAddRemove=!1;for(var e=[],r=0,i=this.points.length;r<i;r++){var n=this.points[r],o=new fabric.Circle({radius:n.radius,left:n.x,top:n.y,originX:"center",originY:"center",fill:n.fill});this.shadow&&o.setShadow(this.shadow),e.push(o)}var a=new fabric.Group(e,{originX:"center",originY:"center"});a.canvas=this.canvas,this.canvas.add(a),this.canvas.fire("path:created",{path:a}),this.canvas.clearContext(this.canvas.contextTop),this._resetShadow(),this.canvas.renderOnAddRemove=t,this.canvas.requestRenderAll()},addPoint:function(t){var e=new fabric.Point(t.x,t.y),r=fabric.util.getRandomInt(Math.max(0,this.width-20),this.width+20)/2,i=new fabric.Color(this.color).setAlpha(fabric.util.getRandomInt(0,100)/100).toRgba();return e.radius=r,e.fill=i,this.points.push(e),e}}),fabric.SprayBrush=fabric.util.createClass(fabric.BaseBrush,{width:10,density:20,dotWidth:1,dotWidthVariance:1,randomOpacity:!1,optimizeOverlapping:!0,initialize:function(t){this.canvas=t,this.sprayChunks=[]},onMouseDown:function(t){this.sprayChunks.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.addSprayChunk(t),this.render()},onMouseMove:function(t){this.addSprayChunk(t),this.render()},onMouseUp:function(){var t=this.canvas.renderOnAddRemove;this.canvas.renderOnAddRemove=!1;for(var e=[],r=0,i=this.sprayChunks.length;r<i;r++)for(var n=this.sprayChunks[r],o=0,a=n.length;o<a;o++){var s=new fabric.Rect({width:n[o].width,height:n[o].width,left:n[o].x+1,top:n[o].y+1,originX:"center",originY:"center",fill:this.color});this.shadow&&s.setShadow(this.shadow),e.push(s)}this.optimizeOverlapping&&(e=this._getOptimizedRects(e));var c=new fabric.Group(e,{originX:"center",originY:"center"});c.canvas=this.canvas,this.canvas.add(c),this.canvas.fire("path:created",{path:c}),this.canvas.clearContext(this.canvas.contextTop),this._resetShadow(),this.canvas.renderOnAddRemove=t,this.canvas.requestRenderAll()},_getOptimizedRects:function(t){for(var e={},r,i=0,n=t.length;i<n;i++)r=t[i].left+""+t[i].top,e[r]||(e[r]=t[i]);var o=[];for(r in e)o.push(e[r]);return o},render:function(){var t=this.canvas.contextTop;t.fillStyle=this.color;var e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5]);for(var r=0,i=this.sprayChunkPoints.length;r<i;r++){var n=this.sprayChunkPoints[r];void 0!==n.opacity&&(t.globalAlpha=n.opacity),t.fillRect(n.x,n.y,n.width,n.width)}t.restore()},addSprayChunk:function(t){this.sprayChunkPoints=[];for(var e,r,i,n=this.width/2,o=0;o<this.density;o++){e=fabric.util.getRandomInt(t.x-n,t.x+n),r=fabric.util.getRandomInt(t.y-n,t.y+n),i=this.dotWidthVariance?fabric.util.getRandomInt(Math.max(1,this.dotWidth-this.dotWidthVariance),this.dotWidth+this.dotWidthVariance):this.dotWidth;var a=new fabric.Point(e,r);a.width=i,this.randomOpacity&&(a.opacity=fabric.util.getRandomInt(0,100)/100),this.sprayChunkPoints.push(a)}this.sprayChunks.push(this.sprayChunkPoints)}}),fabric.PatternBrush=fabric.util.createClass(fabric.PencilBrush,{getPatternSrc:function(){var t=20,e=5,r=fabric.document.createElement("canvas"),i=r.getContext("2d");return r.width=r.height=25,i.fillStyle=this.color,i.beginPath(),i.arc(10,10,10,0,2*Math.PI,!1),i.closePath(),i.fill(),r},getPatternSrcFunction:function(){return String(this.getPatternSrc).replace("this.color",'"'+this.color+'"')},getPattern:function(){return this.canvas.contextTop.createPattern(this.source||this.getPatternSrc(),"repeat")},_setBrushStyles:function(){this.callSuper("_setBrushStyles"),this.canvas.contextTop.strokeStyle=this.getPattern()},createPath:function(t){var e=this.callSuper("createPath",t),r=e._getLeftTopCoords().scalarAdd(e.strokeWidth/2);return e.stroke=new fabric.Pattern({source:this.source||this.getPatternSrcFunction(),offsetX:-r.x,offsetY:-r.y}),e}}),function(){var t=fabric.util.getPointer,e=fabric.util.degreesToRadians,r=fabric.util.radiansToDegrees,i=Math.atan2,n=Math.abs,o=fabric.StaticCanvas.supports("setLineDash"),a=.5;fabric.Canvas=fabric.util.createClass(fabric.StaticCanvas,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this._initStatic(t,e),this._initInteractive(),this._createCacheCanvas()},uniScaleTransform:!1,uniScaleKey:"shiftKey",centeredScaling:!1,centeredRotation:!1,centeredKey:"altKey",altActionKey:"shiftKey",interactive:!0,selection:!0,selectionKey:"shiftKey",altSelectionKey:null,selectionColor:"rgba(100, 100, 255, 0.3)",selectionDashArray:[],selectionBorderColor:"rgba(255, 255, 255, 0.3)",selectionLineWidth:1,hoverCursor:"move",moveCursor:"move",defaultCursor:"default",freeDrawingCursor:"crosshair",rotationCursor:"crosshair",notAllowedCursor:"not-allowed",containerClass:"canvas-container",perPixelTargetFind:!1,targetFindTolerance:0,skipTargetFind:!1,isDrawingMode:!1,preserveObjectStacking:!1,snapAngle:0,snapThreshold:null,stopContextMenu:!1,fireRightClick:!1,fireMiddleClick:!1,_initInteractive:function(){this._currentTransform=null,this._groupSelector=null,this._initWrapperElement(),this._createUpperCanvas(),this._initEventListeners(),this._initRetinaScaling(),this.freeDrawingBrush=fabric.PencilBrush&&new fabric.PencilBrush(this),this.calcOffset()},_chooseObjectsToRender:function(){var t=this.getActiveObjects(),e,r,i;if(t.length>0&&!this.preserveObjectStacking){r=[],i=[];for(var n=0,o=this._objects.length;n<o;n++)e=this._objects[n],-1===t.indexOf(e)?r.push(e):i.push(e);t.length>1&&(this._activeObject._objects=i),r.push.apply(r,i)}else r=this._objects;return r},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1);var t=this.contextContainer;return this.renderCanvas(t,this._chooseObjectsToRender()),this},renderTop:function(){var t=this.contextTop;return this.clearContext(t),this.selection&&this._groupSelector&&this._drawSelection(t),this.fire("after:render"),this.contextTopDirty=!0,this},_resetCurrentTransform:function(){var t=this._currentTransform;t.target.set({scaleX:t.original.scaleX,scaleY:t.original.scaleY,skewX:t.original.skewX,skewY:t.original.skewY,left:t.original.left,top:t.original.top}),this._shouldCenterTransform(t.target)?"rotate"===t.action?this._setOriginToCenter(t.target):("center"!==t.originX&&("right"===t.originX?t.mouseXSign=-1:t.mouseXSign=1),"center"!==t.originY&&("bottom"===t.originY?t.mouseYSign=-1:t.mouseYSign=1),t.originX="center",t.originY="center"):(t.originX=t.original.originX,t.originY=t.original.originY)},containsPoint:function(t,e,r){var i=!0,n=r||this.getPointer(t,!0),o;return o=e.group&&e.group===this._activeObject&&"activeSelection"===e.group.type?this._normalizePointer(e.group,n):{x:n.x,y:n.y},e.containsPoint(o)||e._findTargetCorner(n)},_normalizePointer:function(t,e){var r=t.calcTransformMatrix(),i=fabric.util.invertTransform(r),n=this.restorePointerVpt(e);return fabric.util.transformPoint(n,i)},isTargetTransparent:function(t,e,r){var i=t.hasBorders,n=t.transparentCorners,o=this.contextCache,a=t.selectionBackgroundColor;t.hasBorders=t.transparentCorners=!1,t.selectionBackgroundColor="",o.save(),o.transform.apply(o,this.viewportTransform),t.render(o),o.restore(),t.active&&t._renderControls(o),t.hasBorders=i,t.transparentCorners=n,t.selectionBackgroundColor=a;var s=fabric.util.isTransparent(o,e,r,this.targetFindTolerance);return this.clearContext(o),s},_shouldClearSelection:function(t,e){var r=this.getActiveObjects(),i=this._activeObject;return!e||e&&i&&r.length>1&&-1===r.indexOf(e)&&i!==e&&!t[this.selectionKey]||e&&!e.evented||e&&!e.selectable&&i&&i!==e},_shouldCenterTransform:function(t){if(t){var e=this._currentTransform,r;return"scale"===e.action||"scaleX"===e.action||"scaleY"===e.action?r=this.centeredScaling||t.centeredScaling:"rotate"===e.action&&(r=this.centeredRotation||t.centeredRotation),r?!e.altKey:e.altKey}},_getOriginFromCorner:function(t,e){var r={x:t.originX,y:t.originY};return"ml"===e||"tl"===e||"bl"===e?r.x="right":"mr"!==e&&"tr"!==e&&"br"!==e||(r.x="left"),"tl"===e||"mt"===e||"tr"===e?r.y="bottom":"bl"!==e&&"mb"!==e&&"br"!==e||(r.y="top"),r},_getActionFromCorner:function(t,e,r){if(!e)return"drag";switch(e){case"mtr":return"rotate";case"ml":case"mr":return r[this.altActionKey]?"skewY":"scaleX";case"mt":case"mb":return r[this.altActionKey]?"skewX":"scaleY";default:return"scale"}},_setupCurrentTransform:function(t,r){if(r){var i=this.getPointer(t),n=r._findTargetCorner(this.getPointer(t,!0)),o=this._getActionFromCorner(r,n,t),a=this._getOriginFromCorner(r,n);this._currentTransform={target:r,action:o,corner:n,scaleX:r.scaleX,scaleY:r.scaleY,skewX:r.skewX,skewY:r.skewY,offsetX:i.x-r.left,offsetY:i.y-r.top,originX:a.x,originY:a.y,ex:i.x,ey:i.y,lastX:i.x,lastY:i.y,left:r.left,top:r.top,theta:e(r.angle),width:r.width*r.scaleX,mouseXSign:1,mouseYSign:1,shiftKey:t.shiftKey,altKey:t[this.centeredKey]},this._currentTransform.original={left:r.left,top:r.top,scaleX:r.scaleX,scaleY:r.scaleY,skewX:r.skewX,skewY:r.skewY,originX:a.x,originY:a.y},this._resetCurrentTransform()}},_translateObject:function(t,e){var r=this._currentTransform,i=r.target,n=t-r.offsetX,o=e-r.offsetY,a=!i.get("lockMovementX")&&i.left!==n,s=!i.get("lockMovementY")&&i.top!==o;return a&&i.set("left",n),s&&i.set("top",o),a||s},_changeSkewTransformOrigin:function(t,e,r){var i="originX",n={0:"center"},o=e.target.skewX,a="left",s="right",c="mt"===e.corner||"ml"===e.corner?1:-1,l=1;t=t>0?1:-1,"y"===r&&(o=e.target.skewY,a="top",s="bottom",i="originY"),n[-1]=a,n[1]=s,e.target.flipX&&(l*=-1),e.target.flipY&&(l*=-1),0===o?(e.skewSign=-c*t*l,e[i]=n[-t]):(o=o>0?1:-1,e.skewSign=o,e[i]=n[o*c*l])},_skewObject:function(t,e,r){var i=this._currentTransform,n=i.target,o=!1,a=n.get("lockSkewingX"),s=n.get("lockSkewingY");if(a&&"x"===r||s&&"y"===r)return!1;var c=n.getCenterPoint(),l=n.toLocalPoint(new fabric.Point(t,e),"center","center")[r],h=n.toLocalPoint(new fabric.Point(i.lastX,i.lastY),"center","center")[r],u,f,d=n._getTransformedDimensions();return this._changeSkewTransformOrigin(l-h,i,r),u=n.toLocalPoint(new fabric.Point(t,e),i.originX,i.originY)[r],f=n.translateToOriginPoint(c,i.originX,i.originY),o=this._setObjectSkew(u,i,r,d),i.lastX=t,i.lastY=e,n.setPositionByOrigin(f,i.originX,i.originY),o},_setObjectSkew:function(t,e,r,i){var n=e.target,o,a=!1,s=e.skewSign,c,l,h,u,f,d,p,g;return"x"===r?(h="y",u="Y",f="X",p=0,g=n.skewY):(h="x",u="X",f="Y",p=n.skewX,g=0),l=n._getTransformedDimensions(p,g),d=2*Math.abs(t)-l[r],d<=2?o=0:(o=s*Math.atan(d/n["scale"+f]/(l[h]/n["scale"+u])),o=fabric.util.radiansToDegrees(o)),a=n["skew"+f]!==o,n.set("skew"+f,o),0!==n["skew"+u]&&(c=n._getTransformedDimensions(),o=i[h]/c[h]*n["scale"+u],n.set("scale"+u,o)),a},_scaleObject:function(t,e,r){var i=this._currentTransform,n=i.target,o=n.get("lockScalingX"),a=n.get("lockScalingY"),s=n.get("lockScalingFlip");if(o&&a)return!1;var c=n.translateToOriginPoint(n.getCenterPoint(),i.originX,i.originY),l=n.toLocalPoint(new fabric.Point(t,e),i.originX,i.originY),h=n._getTransformedDimensions(),u=!1;return this._setLocalMouse(l,i),u=this._setObjectScale(l,i,o,a,r,s,h),n.setPositionByOrigin(c,i.originX,i.originY),u},_setObjectScale:function(t,e,r,i,n,o,a){var s=e.target,c=!1,l=!1,h=!1,u,f,d,p;return d=t.x*s.scaleX/a.x,p=t.y*s.scaleY/a.y,u=s.scaleX!==d,f=s.scaleY!==p,o&&d<=0&&d<s.scaleX&&(c=!0),o&&p<=0&&p<s.scaleY&&(l=!0),"equally"!==n||r||i?n?"x"!==n||s.get("lockUniScaling")?"y"!==n||s.get("lockUniScaling")||l||i||s.set("scaleY",p)&&(h=h||f):c||r||s.set("scaleX",d)&&(h=h||u):(c||r||s.set("scaleX",d)&&(h=h||u),l||i||s.set("scaleY",p)&&(h=h||f)):c||l||(h=this._scaleObjectEqually(t,s,e,a)),e.newScaleX=d,e.newScaleY=p,c||l||this._flipObject(e,n),h},_scaleObjectEqually:function(t,e,r,i){var n=t.y+t.x,o=i.y*r.original.scaleY/e.scaleY+i.x*r.original.scaleX/e.scaleX,a;return r.newScaleX=r.original.scaleX*n/o,r.newScaleY=r.original.scaleY*n/o,a=r.newScaleX!==e.scaleX||r.newScaleY!==e.scaleY,e.set("scaleX",r.newScaleX),e.set("scaleY",r.newScaleY),a},_flipObject:function(t,e){t.newScaleX<0&&"y"!==e&&("left"===t.originX?t.originX="right":"right"===t.originX&&(t.originX="left")),t.newScaleY<0&&"x"!==e&&("top"===t.originY?t.originY="bottom":"bottom"===t.originY&&(t.originY="top"))},_setLocalMouse:function(t,e){var r=e.target,i=this.getZoom(),o=r.padding/i;"right"===e.originX?t.x*=-1:"center"===e.originX&&(t.x*=2*e.mouseXSign,t.x<0&&(e.mouseXSign=-e.mouseXSign)),"bottom"===e.originY?t.y*=-1:"center"===e.originY&&(t.y*=2*e.mouseYSign,t.y<0&&(e.mouseYSign=-e.mouseYSign)),n(t.x)>o?t.x<0?t.x+=o:t.x-=o:t.x=0,n(t.y)>o?t.y<0?t.y+=o:t.y-=o:t.y=0},_rotateObject:function(t,e){var n=this._currentTransform;if(n.target.get("lockRotation"))return!1;var o=i(n.ey-n.top,n.ex-n.left),a=i(e-n.top,t-n.left),s=r(a-o+n.theta),c=!0;if(n.target.snapAngle>0){var l=n.target.snapAngle,h=n.target.snapThreshold||l,u=Math.ceil(s/l)*l,f=Math.floor(s/l)*l;Math.abs(s-f)<h?s=f:Math.abs(s-u)<h&&(s=u)}return s<0&&(s=360+s),s%=360,n.target.angle===s?c=!1:n.target.angle=s,c},setCursor:function(t){this.upperCanvasEl.style.cursor=t},_resetObjectTransform:function(t){t.scaleX=1,t.scaleY=1,t.skewX=0,t.skewY=0,t.setAngle(0)},_drawSelection:function(t){var e=this._groupSelector,r=e.left,i=e.top,a=n(r),s=n(i);if(this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(e.ex-(r>0?0:-r),e.ey-(i>0?0:-i),a,s)),this.selectionLineWidth&&this.selectionBorderColor)if(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,this.selectionDashArray.length>1&&!o){var c=e.ex+.5-(r>0?0:a),l=e.ey+.5-(i>0?0:s);t.beginPath(),fabric.util.drawDashedLine(t,c,l,c+a,l,this.selectionDashArray),fabric.util.drawDashedLine(t,c,l+s-1,c+a,l+s-1,this.selectionDashArray),fabric.util.drawDashedLine(t,c,l,c,l+s,this.selectionDashArray),fabric.util.drawDashedLine(t,c+a-1,l,c+a-1,l+s,this.selectionDashArray),t.closePath(),t.stroke()}else fabric.Object.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(e.ex+.5-(r>0?0:a),e.ey+.5-(i>0?0:s),a,s)},findTarget:function(t,e){if(!this.skipTargetFind){var r=!0,i=this.getPointer(t,!0),n=this._activeObject,o=this.getActiveObjects(),a;if(this.targets=[],o.length>1&&!e&&n===this._searchPossibleTargets([n],i))return this._fireOverOutEvents(n,t),n;if(1===o.length&&n._findTargetCorner(i))return this._fireOverOutEvents(n,t),n;if(1===o.length&&n===this._searchPossibleTargets([n],i)){if(!this.preserveObjectStacking)return this._fireOverOutEvents(n,t),n;a=n}var s=this._searchPossibleTargets(this._objects,i);return t[this.altSelectionKey]&&s&&a&&s!==a&&(s=a),this._fireOverOutEvents(s,t),s}},_fireOverOutEvents:function(t,e){var r,i,n=this._hoveredTarget;n!==t&&(r={e:e,target:t,previousTarget:this._hoveredTarget},i={e:e,target:this._hoveredTarget,nextTarget:t},this._hoveredTarget=t),t?n!==t&&(n&&(this.fire("mouse:out",i),n.fire("mouseout",i)),this.fire("mouse:over",r),t.fire("mouseover",r)):n&&(this.fire("mouse:out",i),n.fire("mouseout",i))},_checkTarget:function(t,e){if(e&&e.visible&&e.evented&&this.containsPoint(null,e,t)){if(!this.perPixelTargetFind&&!e.perPixelTargetFind||e.isEditing)return!0;if(!this.isTargetTransparent(e,t.x,t.y))return!0}},_searchPossibleTargets:function(t,e){for(var r,i=t.length,n,o;i--;)if(this._checkTarget(e,t[i])){r=t[i],"group"===r.type&&r.subTargetCheck&&(n=this._normalizePointer(r,e),(o=this._searchPossibleTargets(r._objects,n))&&this.targets.push(o));break}return r},restorePointerVpt:function(t){return fabric.util.transformPoint(t,fabric.util.invertTransform(this.viewportTransform))},getPointer:function(e,r,i){i||(i=this.upperCanvasEl);var n=t(e),o=i.getBoundingClientRect(),a=o.width||0,s=o.height||0,c;return a&&s||("top"in o&&"bottom"in o&&(s=Math.abs(o.top-o.bottom)),"right"in o&&"left"in o&&(a=Math.abs(o.right-o.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,r||(n=this.restorePointerVpt(n)),c=0===a||0===s?{width:1,height:1}:{width:i.width/a,height:i.height/s},{x:n.x*c.width,y:n.y*c.height}},_createUpperCanvas:function(){var t=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,"");this.upperCanvasEl?this.upperCanvasEl.className="":this.upperCanvasEl=this._createCanvasElement(),fabric.util.addClass(this.upperCanvasEl,"upper-canvas "+t),this.wrapperEl.appendChild(this.upperCanvasEl),this._copyCanvasStyle(this.lowerCanvasEl,this.upperCanvasEl),this._applyCanvasStyle(this.upperCanvasEl),this.contextTop=this.upperCanvasEl.getContext("2d")},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=fabric.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),fabric.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),fabric.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(t){var e=this.width||t.width,r=this.height||t.height;fabric.util.setStyle(t,{position:"absolute",width:e+"px",height:r+"px",left:0,top:0,"touch-action":"none"}),t.width=e,t.height=r,fabric.util.makeElementUnselectable(t)},_copyCanvasStyle:function(t,e){e.style.cssText=t.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var t=this._activeObject;return t?"activeSelection"===t.type&&t._objects?t._objects:[t]:[]},_onObjectRemoved:function(t){t===this._activeObject&&(this.fire("before:selection:cleared",{target:t}),this._discardActiveObject(),this.fire("selection:cleared",{target:t}),t.fire("deselected")),this._hoveredTarget===t&&(this._hoveredTarget=null),this.callSuper("_onObjectRemoved",t)},setActiveObject:function(t,e){var r=this._activeObject;return t===r?this:(this._setActiveObject(t)&&(r&&r.fire("deselected",{e:e}),this.fire("object:selected",{target:t,e:e}),t.fire("selected",{e:e})),this)},_setActiveObject:function(t){return this._activeObject!==t&&!!this._discardActiveObject()&&(this._activeObject=t,t.set("active",!0),!0)},_discardActiveObject:function(){var t=this._activeObject;if(t&&t.onDeselect&&"function"==typeof t.onDeselect){if(t.onDeselect())return!1;t.set("active",!1),this._activeObject=null}return!0},discardActiveObject:function(t){var e=this._activeObject;return e&&(this.fire("before:selection:cleared",{target:e,e:t}),this._discardActiveObject()&&(this.fire("selection:cleared",{e:t}),e.fire("deselected",{e:t}))),this},dispose:function(){fabric.StaticCanvas.prototype.dispose.call(this);var t=this.wrapperEl;return this.removeListeners(),t.removeChild(this.upperCanvasEl),t.removeChild(this.lowerCanvasEl),delete this.upperCanvasEl,t.parentNode&&t.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(t){var e=this._activeObject;e&&e._renderControls(t)},_toObject:function(t,e,r){var i=this._realizeGroupTransformOnObject(t),n=this.callSuper("_toObject",t,e,r);return this._unwindGroupTransformOnObject(t,i),n},_realizeGroupTransformOnObject:function(t){if(t.group&&"activeSelection"===t.group.type&&this._activeObject===t.group){var e=["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"],r={};return e.forEach(function(e){r[e]=t[e]}),this._activeObject.realizeTransform(t),r}return null},_unwindGroupTransformOnObject:function(t,e){e&&t.set(e)},_setSVGObject:function(t,e,r){var i=this._realizeGroupTransformOnObject(e);this.callSuper("_setSVGObject",t,e,r),this._unwindGroupTransformOnObject(e,i)}});for(var s in fabric.StaticCanvas)"prototype"!==s&&(fabric.Canvas[s]=fabric.StaticCanvas[s]);fabric.isTouchSupported&&(fabric.Canvas.prototype._setCursorFromEvent=function(){})}(),function(){function t(t,e){return"which"in t?t.which===e:t.button===e-1}var e={mt:0,tr:1,mr:2,br:3,mb:4,bl:5,ml:6,tl:7},r=fabric.util.addListener,i=fabric.util.removeListener,n=3,o=2,a=1;fabric.util.object.extend(fabric.Canvas.prototype,{cursorMap:["n-resize","ne-resize","e-resize","se-resize","s-resize","sw-resize","w-resize","nw-resize"],_initEventListeners:function(){this.removeListeners(),this._bindEvents(),r(fabric.window,"resize",this._onResize),r(this.upperCanvasEl,"mousedown",this._onMouseDown),r(this.upperCanvasEl,"dblclick",this._onDoubleClick),r(this.upperCanvasEl,"mousemove",this._onMouseMove),r(this.upperCanvasEl,"mouseout",this._onMouseOut),r(this.upperCanvasEl,"mouseenter",this._onMouseEnter),r(this.upperCanvasEl,"wheel",this._onMouseWheel),r(this.upperCanvasEl,"contextmenu",this._onContextMenu),r(this.upperCanvasEl,"touchstart",this._onMouseDown,{passive:!1}),r(this.upperCanvasEl,"touchmove",this._onMouseMove,{passive:!1}),"undefined"!=typeof eventjs&&"add"in eventjs&&(eventjs.add(this.upperCanvasEl,"gesture",this._onGesture),eventjs.add(this.upperCanvasEl,"drag",this._onDrag),eventjs.add(this.upperCanvasEl,"orientation",this._onOrientationChange),eventjs.add(this.upperCanvasEl,"shake",this._onShake),eventjs.add(this.upperCanvasEl,"longpress",this._onLongPress))},_bindEvents:function(){this.eventsBinded||(this._onMouseDown=this._onMouseDown.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this.eventsBinded=!0)},removeListeners:function(){i(fabric.window,"resize",this._onResize),i(this.upperCanvasEl,"mousedown",this._onMouseDown),i(this.upperCanvasEl,"mousemove",this._onMouseMove),i(this.upperCanvasEl,"mouseout",this._onMouseOut),i(this.upperCanvasEl,"mouseenter",this._onMouseEnter),i(this.upperCanvasEl,"wheel",this._onMouseWheel),i(this.upperCanvasEl,"contextmenu",this._onContextMenu),i(this.upperCanvasEl,"doubleclick",this._onDoubleClick),i(this.upperCanvasEl,"touchstart",this._onMouseDown),i(this.upperCanvasEl,"touchmove",this._onMouseMove),"undefined"!=typeof eventjs&&"remove"in eventjs&&(eventjs.remove(this.upperCanvasEl,"gesture",this._onGesture),eventjs.remove(this.upperCanvasEl,"drag",this._onDrag),eventjs.remove(this.upperCanvasEl,"orientation",this._onOrientationChange),eventjs.remove(this.upperCanvasEl,"shake",this._onShake),eventjs.remove(this.upperCanvasEl,"longpress",this._onLongPress))},_onGesture:function(t,e){this.__onTransformGesture&&this.__onTransformGesture(t,e)},_onDrag:function(t,e){this.__onDrag&&this.__onDrag(t,e)},_onMouseWheel:function(t){this.__onMouseWheel(t)},_onMouseOut:function(t){var e=this._hoveredTarget;this.fire("mouse:out",{target:e,e:t}),this._hoveredTarget=null,e&&e.fire("mouseout",{e:t}),this._iTextInstances&&this._iTextInstances.forEach(function(t){t.isEditing&&t.hiddenTextarea.focus()})},_onMouseEnter:function(t){this.findTarget(t)||(this.fire("mouse:over",{target:null,e:t}),this._hoveredTarget=null)},_onOrientationChange:function(t,e){this.__onOrientationChange&&this.__onOrientationChange(t,e)},_onShake:function(t,e){this.__onShake&&this.__onShake(t,e)},_onLongPress:function(t,e){this.__onLongPress&&this.__onLongPress(t,e)},_onContextMenu:function(t){return this.stopContextMenu&&(t.stopPropagation(),t.preventDefault()),!1},_onDoubleClick:function(t){var e;this._handleEvent(t,"dblclick",void 0)},_onMouseDown:function(t){this.__onMouseDown(t),r(fabric.document,"touchend",this._onMouseUp,{passive:!1}),r(fabric.document,"touchmove",this._onMouseMove,{passive:!1}),i(this.upperCanvasEl,"mousemove",this._onMouseMove),i(this.upperCanvasEl,"touchmove",this._onMouseMove),"touchstart"===t.type?i(this.upperCanvasEl,"mousedown",this._onMouseDown):(r(fabric.document,"mouseup",this._onMouseUp),r(fabric.document,"mousemove",this._onMouseMove))},_onMouseUp:function(t){if(this.__onMouseUp(t),i(fabric.document,"mouseup",this._onMouseUp),i(fabric.document,"touchend",this._onMouseUp),i(fabric.document,"mousemove",this._onMouseMove),i(fabric.document,"touchmove",this._onMouseMove),r(this.upperCanvasEl,"mousemove",this._onMouseMove),r(this.upperCanvasEl,"touchmove",this._onMouseMove,{passive:!1}),"touchend"===t.type){var e=this;setTimeout(function(){r(e.upperCanvasEl,"mousedown",e._onMouseDown)},400)}},_onMouseMove:function(t){!this.allowTouchScrolling&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)},_onResize:function(){this.calcOffset()},_shouldRender:function(t,e){var r=this._activeObject;return(!r||!r.isEditing||t!==r)&&!!(t&&(t.isMoving||t!==r)||!t&&r||!t&&!r&&!this._groupSelector||e&&this._previousPointer&&this.selection&&(e.x!==this._previousPointer.x||e.y!==this._previousPointer.y))},__onMouseUp:function(e){var r;if(t(e,3))return void(this.fireRightClick&&this._handleEvent(e,"up",r,3));if(t(e,2))return void(this.fireMiddleClick&&this._handleEvent(e,"up",r,2));if(this.isDrawingMode&&this._isCurrentlyDrawing)return void this._onMouseUpInDrawingMode(e);var i=!0,n=this._currentTransform,o=this._groupSelector,a=!o||0===o.left&&0===o.top;n&&(this._finalizeCurrentTransform(e),i=!n.actionPerformed),r=i?this.findTarget(e,!0):n.target;var s=this._shouldRender(r,this.getPointer(e));r||!a?this._maybeGroupObjects(e):(this._groupSelector=null,this._currentTransform=null),r&&(r.isMoving=!1),this._setCursorFromEvent(e,r),this._handleEvent(e,"up",r||null,1,a),r&&(r.__corner=0),s&&this.requestRenderAll()},_handleEvent:function(t,e,r,i,n){var o=void 0===r?this.findTarget(t):r,a=this.targets||[],s={e:t,target:o,subTargets:a,button:i||1,isClick:n||!1};this.fire("mouse:"+e,s),o&&o.fire("mouse"+e,s);for(var c=0;c<a.length;c++)a[c].fire("mouse"+e,s)},_finalizeCurrentTransform:function(t){var e=this._currentTransform,r=e.target;r._scaling&&(r._scaling=!1),r.setCoords(),this._restoreOriginXY(r),(e.actionPerformed||this.stateful&&r.hasStateChanged())&&(this.fire("object:modified",{target:r,e:t}),r.fire("modified",{e:t}))},_restoreOriginXY:function(t){if(this._previousOriginX&&this._previousOriginY){var e=t.translateToOriginPoint(t.getCenterPoint(),this._previousOriginX,this._previousOriginY);t.originX=this._previousOriginX,t.originY=this._previousOriginY,t.left=e.x,t.top=e.y,this._previousOriginX=null,this._previousOriginY=null}},_onMouseDownInDrawingMode:function(t){this._isCurrentlyDrawing=!0,this.discardActiveObject(t).requestRenderAll(),this.clipTo&&fabric.util.clipContext(this,this.contextTop);var e=this.getPointer(t);this.freeDrawingBrush.onMouseDown(e),this._handleEvent(t,"down")},_onMouseMoveInDrawingMode:function(t){if(this._isCurrentlyDrawing){var e=this.getPointer(t);this.freeDrawingBrush.onMouseMove(e)}this.setCursor(this.freeDrawingCursor),this._handleEvent(t,"move")},_onMouseUpInDrawingMode:function(t){this._isCurrentlyDrawing=!1,this.clipTo&&this.contextTop.restore(),this.freeDrawingBrush.onMouseUp(),this._handleEvent(t,"up")},__onMouseDown:function(e){var r=this.findTarget(e);if(t(e,3))return void(this.fireRightClick&&this._handleEvent(e,"down",r||null,3));if(t(e,2))return void(this.fireMiddleClick&&this._handleEvent(e,"down",r||null,2));if(this.isDrawingMode)return void this._onMouseDownInDrawingMode(e);if(!this._currentTransform){var i=this.getPointer(e,!0);this._previousPointer=i;var n=this._shouldRender(r,i),o=this._shouldGroup(e,r);this._shouldClearSelection(e,r)?this.discardActiveObject(e):o&&(this._handleGrouping(e,r),r=this._activeObject),!this.selection||r&&(r.selectable||r.isEditing)||(this._groupSelector={ex:i.x,ey:i.y,top:0,left:0}),r&&(!r.selectable||!r.__corner&&o||(this._beforeTransform(e,r),this._setupCurrentTransform(e,r)),r.selectable?this.setActiveObject(r,e):this.discardActiveObject()),this._handleEvent(e,"down",r||null),n&&this.requestRenderAll()}},_beforeTransform:function(t,e){this.stateful&&e.saveState(),e._findTargetCorner(this.getPointer(t))&&this.onBeforeScaleRotate(e)},_setOriginToCenter:function(t){this._previousOriginX=this._currentTransform.target.originX,this._previousOriginY=this._currentTransform.target.originY;var e=t.getCenterPoint();t.originX="center",t.originY="center",t.left=e.x,t.top=e.y,this._currentTransform.left=t.left,this._currentTransform.top=t.top},_setCenterToOrigin:function(t){var e=t.translateToOriginPoint(t.getCenterPoint(),this._previousOriginX,this._previousOriginY);t.originX=this._previousOriginX,t.originY=this._previousOriginY,t.left=e.x,t.top=e.y,this._previousOriginX=null,this._previousOriginY=null},__onMouseMove:function(t){var e,r;if(this.isDrawingMode)return void this._onMouseMoveInDrawingMode(t);if(!(void 0!==t.touches&&t.touches.length>1)){var i=this._groupSelector;i?(r=this.getPointer(t,!0),i.left=r.x-i.ex,i.top=r.y-i.ey,this.renderTop()):this._currentTransform?this._transformObject(t):(e=this.findTarget(t),this._setCursorFromEvent(t,e)),this._handleEvent(t,"move",e||null)}},__onMouseWheel:function(t){this._handleEvent(t,"wheel")},_transformObject:function(t){var e=this.getPointer(t),r=this._currentTransform;r.reset=!1,r.target.isMoving=!0,r.shiftKey=t.shiftKey,r.altKey=t[this.centeredKey],this._beforeScaleTransform(t,r),this._performTransformAction(t,r,e),r.actionPerformed&&this.requestRenderAll()},_performTransformAction:function(t,e,r){var i=r.x,n=r.y,o=e.target,a=e.action,s=!1;"rotate"===a?(s=this._rotateObject(i,n))&&this._fire("rotating",o,t):"scale"===a?(s=this._onScale(t,e,i,n))&&this._fire("scaling",o,t):"scaleX"===a?(s=this._scaleObject(i,n,"x"))&&this._fire("scaling",o,t):"scaleY"===a?(s=this._scaleObject(i,n,"y"))&&this._fire("scaling",o,t):"skewX"===a?(s=this._skewObject(i,n,"x"))&&this._fire("skewing",o,t):"skewY"===a?(s=this._skewObject(i,n,"y"))&&this._fire("skewing",o,t):(s=this._translateObject(i,n))&&(this._fire("moving",o,t),this.setCursor(o.moveCursor||this.moveCursor)),e.actionPerformed=e.actionPerformed||s},_fire:function(t,e,r){this.fire("object:"+t,{target:e,e:r}),e.fire(t,{e:r})},_beforeScaleTransform:function(t,e){if("scale"===e.action||"scaleX"===e.action||"scaleY"===e.action){var r=this._shouldCenterTransform(e.target);(r&&("center"!==e.originX||"center"!==e.originY)||!r&&"center"===e.originX&&"center"===e.originY)&&(this._resetCurrentTransform(),e.reset=!0)}},_onScale:function(t,e,r,i){return this._isUniscalePossible(t,e.target)?(e.currentAction="scale",this._scaleObject(r,i)):(e.reset||"scale"!==e.currentAction||this._resetCurrentTransform(),e.currentAction="scaleEqually",this._scaleObject(r,i,"equally"))},_isUniscalePossible:function(t,e){return(t[this.uniScaleKey]||this.uniScaleTransform)&&!e.get("lockUniScaling")},_setCursorFromEvent:function(t,e){if(!e)return this.setCursor(this.defaultCursor),!1;var r=e.hoverCursor||this.hoverCursor,i=this._activeObject&&"activeSelection"===this._activeObject.type?this._activeObject:null,n=(!i||!i.contains(e))&&e._findTargetCorner(this.getPointer(t,!0));n?this.setCursor(this.getCornerCursor(n,e,t)):this.setCursor(r)},getCornerCursor:function(t,r,i){return this.actionIsDisabled(t,r,i)?this.notAllowedCursor:t in e?this._getRotatedCornerCursor(t,r,i):"mtr"===t&&r.hasRotatingPoint?this.rotationCursor:this.defaultCursor},actionIsDisabled:function(t,e,r){return"mt"===t||"mb"===t?r[this.altActionKey]?e.lockSkewingX:e.lockScalingY:"ml"===t||"mr"===t?r[this.altActionKey]?e.lockSkewingY:e.lockScalingX:"mtr"===t?e.lockRotation:this._isUniscalePossible(r,e)?e.lockScalingX&&e.lockScalingY:e.lockScalingX||e.lockScalingY},_getRotatedCornerCursor:function(t,r,i){var n=Math.round(r.angle%360/45);return n<0&&(n+=8),n+=e[t],i[this.altActionKey]&&e[t]%2==0&&(n+=2),n%=8,this.cursorMap[n]}})}(),function(){var t=Math.min,e=Math.max;fabric.util.object.extend(fabric.Canvas.prototype,{_shouldGroup:function(t,e){var r=this._activeObject;return t[this.selectionKey]&&e&&e.selectable&&this.selection&&(r!==e||"activeSelection"===r.type)},_handleGrouping:function(t,e){var r=this._activeObject;0===r.__corner&&(e!==r||(e=this.findTarget(t,!0)))&&(r&&"activeSelection"===r.type?this._updateActiveSelection(e,t):this._createActiveSelection(e,t))},_updateActiveSelection:function(t,e){var r=this._activeObject;if(r.contains(t)){if(r.removeWithUpdate(t),1===r.size())return void this.setActiveObject(r.item(0),e)}else r.addWithUpdate(t);this.fire("selection:created",{target:r,e:e})},_createActiveSelection:function(t,e){var r=this._createGroup(t);this.setActiveObject(r,e),this.fire("selection:created",{target:r,e:e})},_createGroup:function(t){var e=this.getObjects(),r=e.indexOf(this._activeObject)<e.indexOf(t),i=r?[this._activeObject,t]:[t,this._activeObject];return this._activeObject.isEditing&&this._activeObject.exitEditing(),new fabric.ActiveSelection(i,{canvas:this})},_groupSelectedObjects:function(t){var e=this._collectObjects();1===e.length?this.setActiveObject(e[0],t):e.length>1&&(e=new fabric.ActiveSelection(e.reverse(),{canvas:this}),this.setActiveObject(e,t),this.fire("selection:created",{target:e,e:t}),this.requestRenderAll())},_collectObjects:function(){for(var r=[],i,n=this._groupSelector.ex,o=this._groupSelector.ey,a=n+this._groupSelector.left,s=o+this._groupSelector.top,c=new fabric.Point(t(n,a),t(o,s)),l=new fabric.Point(e(n,a),e(o,s)),h=n===a&&o===s,u=this._objects.length;u--&&!((i=this._objects[u])&&i.selectable&&i.visible&&(i.intersectsWithRect(c,l)||i.isContainedWithinRect(c,l)||i.containsPoint(c)||i.containsPoint(l))&&(r.push(i),h)););return r},_maybeGroupObjects:function(t){this.selection&&this._groupSelector&&this._groupSelectedObjects(t),this.setCursor(this.defaultCursor),this._groupSelector=null,this._currentTransform=null}})}(),function(){var t=fabric.StaticCanvas.supports("toDataURLWithQuality");fabric.util.object.extend(fabric.StaticCanvas.prototype,{toDataURL:function(t){t||(t={});var e=t.format||"png",r=t.quality||1,i=t.multiplier||1,n={left:t.left||0,top:t.top||0,width:t.width||0,height:t.height||0};return this.__toDataURLWithMultiplier(e,r,n,i)},__toDataURLWithMultiplier:function(t,e,r,i){var n=this.width,o=this.height,a=(r.width||this.width)*i,s=(r.height||this.height)*i,c=this.getZoom(),l=c*i,h=this.viewportTransform,u=(h[4]-r.left)*i,f=(h[5]-r.top)*i,d=[l,0,0,l,u,f],p=this.interactive;this.viewportTransform=d,this.interactive&&(this.interactive=!1),n!==a||o!==s?this.setDimensions({width:a,height:s}):this.renderAll();var g=this.__toDataURL(t,e,r);return p&&(this.interactive=p),this.viewportTransform=h,this.setDimensions({width:n,height:o}),g},__toDataURL:function(e,r){var i=this.contextContainer.canvas;return"jpg"===e&&(e="jpeg"),t?i.toDataURL("image/"+e,r):i.toDataURL("image/"+e)},toDataURLWithMultiplier:function(t,e,r){return this.toDataURL({format:t,multiplier:e,quality:r})}})}(),fabric.util.object.extend(fabric.StaticCanvas.prototype,{loadFromDatalessJSON:function(t,e,r){return this.loadFromJSON(t,e,r)},loadFromJSON:function(t,e,r){if(t){var i="string"==typeof t?JSON.parse(t):fabric.util.object.clone(t),n=this,o=this.renderOnAddRemove;return this.renderOnAddRemove=!1,this._enlivenObjects(i.objects,function(t){n.clear(),n._setBgOverlay(i,function(){t.forEach(function(t,e){n.insertAt(t,e)}),n.renderOnAddRemove=o,delete i.objects,delete i.backgroundImage,delete i.overlayImage,delete i.background,delete i.overlay,n._setOptions(i),n.renderAll(),e&&e()})},r),this}},_setBgOverlay:function(t,e){var r={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(!(t.backgroundImage||t.overlayImage||t.background||t.overlay))return void(e&&e());var i=function(){r.backgroundImage&&r.overlayImage&&r.backgroundColor&&r.overlayColor&&e&&e()};this.__setBgOverlay("backgroundImage",t.backgroundImage,r,i),this.__setBgOverlay("overlayImage",t.overlayImage,r,i),this.__setBgOverlay("backgroundColor",t.background,r,i),this.__setBgOverlay("overlayColor",t.overlay,r,i)},__setBgOverlay:function(t,e,r,i){var n=this;if(!e)return r[t]=!0,void(i&&i());"backgroundImage"===t||"overlayImage"===t?fabric.util.enlivenObjects([e],function(e){n[t]=e[0],r[t]=!0,i&&i()}):this["set"+fabric.util.string.capitalize(t,!0)](e,function(){r[t]=!0,i&&i()})},_enlivenObjects:function(t,e,r){if(!t||0===t.length)return void(e&&e([]));fabric.util.enlivenObjects(t,function(t){e&&e(t)},null,r)},_toDataURL:function(t,e){this.clone(function(r){e(r.toDataURL(t))})},_toDataURLWithMultiplier:function(t,e,r){this.clone(function(i){r(i.toDataURLWithMultiplier(t,e))})},clone:function(t,e){var r=JSON.stringify(this.toJSON(e));this.cloneWithoutData(function(e){e.loadFromJSON(r,function(){t&&t(e)})})},cloneWithoutData:function(t){var e=fabric.document.createElement("canvas");e.width=this.width,e.height=this.height;var r=new fabric.Canvas(e);r.clipTo=this.clipTo,this.backgroundImage?(r.setBackgroundImage(this.backgroundImage.src,function(){r.renderAll(),t&&t(r)}),r.backgroundImageOpacity=this.backgroundImageOpacity,r.backgroundImageStretch=this.backgroundImageStretch):t&&t(r)}}),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.util.object.extend,i=e.util.object.clone,n=e.util.toFixed,o=e.util.string.capitalize,a=e.util.degreesToRadians,s=e.StaticCanvas.supports("setLineDash"),c=!e.isLikelyNode,l=2;e.Object||(e.Object=e.util.createClass(e.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgba(102,153,255,0.75)",borderDashArray:null,cornerColor:"rgba(102,153,255,0.5)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:10,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,transformMatrix:null,minScaleLimit:.01,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,hasRotatingPoint:!0,rotatingPointOffset:40,perPixelTargetFind:!1,includeDefaultValues:!0,clipTo:null,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockUniScaling:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:c,statefullCache:!1,noScaleCache:!0,dirty:!0,stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow clipTo visible backgroundColor skewX skewY fillRule".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height strokeLineCap strokeLineJoin strokeMiterLimit backgroundColor".split(" "),initialize:function(t){(t=t||{})&&this.setOptions(t)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=e.document.createElement("canvas"),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas()},_limitCacheSize:function(t){var r=e.perfLimitSizeTotal,i=e.cacheSideLimit,n=t.width,o=t.height,a=n/o,s=e.util.limitDimsByArea(a,r,i),c=e.util.capValue,l=e.maxCacheSideLimit,h=e.minCacheSideLimit,u=c(h,s.x,l),f=c(h,s.y,l);return n>u?(t.zoomX/=n/u,t.width=u):n<h&&(t.width=h),o>f?(t.zoomY/=o/f,t.height=f):o<h&&(t.height=h),t},_getCacheCanvasDimensions:function(){var t=this.canvas&&this.canvas.getZoom()||1,r=this.getObjectScaling(),i=this._getNonTransformedDimensions(),n=this.canvas&&this.canvas._isRetinaScaling()?e.devicePixelRatio:1,o=r.scaleX*t*n,a=r.scaleY*t*n;return{width:i.x*o+2,height:i.y*a+2,zoomX:o,zoomY:a}},_updateCacheCanvas:function(){if(this.noScaleCache&&this.canvas&&this.canvas._currentTransform){var t=this.canvas._currentTransform.action;if(t.slice&&"scale"===t.slice(0,5))return!1}var r=this._limitCacheSize(this._getCacheCanvasDimensions()),i=e.minCacheSideLimit,n=r.width,o=r.height,a=r.zoomX,s=r.zoomY,c=n!==this.cacheWidth||o!==this.cacheHeight,l=this.zoomX!==a||this.zoomY!==s,h=c||l,u=0,f=0,d=!1;if(c){var p=this._cacheCanvas.width,g=this._cacheCanvas.height,v=n>p||o>g,m=(n<.9*p||o<.9*g)&&p>i&&g>i;d=v||m,v&&(u=.1*n&-2,f=.1*o&-2)}return!!h&&(d?(this._cacheCanvas.width=Math.max(Math.ceil(n)+u,i),this._cacheCanvas.height=Math.max(Math.ceil(o)+f,i),this.cacheTranslationX=(n+u)/2,this.cacheTranslationY=(o+f)/2):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,this._cacheCanvas.width,this._cacheCanvas.height)),this.cacheWidth=n,this.cacheHeight=o,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(a,s),this.zoomX=a,this.zoomY=s,!0)},setOptions:function(t){this._setOptions(t),this._initGradient(t.fill,"fill"),this._initGradient(t.stroke,"stroke"),this._initClipping(t),this._initPattern(t.fill,"fill"),this._initPattern(t.stroke,"stroke")},transform:function(t,e){this.group&&!this.group._transformDone&&this.group.transform(t);var r=e?this._getLeftTopCoords():this.getCenterPoint();t.translate(r.x,r.y),this.angle&&t.rotate(a(this.angle)),t.scale(this.scaleX*(this.flipX?-1:1),this.scaleY*(this.flipY?-1:1)),this.skewX&&t.transform(1,0,Math.tan(a(this.skewX)),1,0,0),this.skewY&&t.transform(1,Math.tan(a(this.skewY)),0,1,0,0)},toObject:function(t){var r=e.Object.NUM_FRACTION_DIGITS,i={type:this.type,originX:this.originX,originY:this.originY,left:n(this.left,r),top:n(this.top,r),width:n(this.width,r),height:n(this.height,r),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:n(this.strokeWidth,r),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeLineJoin:this.strokeLineJoin,strokeMiterLimit:n(this.strokeMiterLimit,r),scaleX:n(this.scaleX,r),scaleY:n(this.scaleY,r),angle:n(this.angle,r),flipX:this.flipX,flipY:this.flipY,opacity:n(this.opacity,r),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,clipTo:this.clipTo&&String(this.clipTo),backgroundColor:this.backgroundColor,fillRule:this.fillRule,globalCompositeOperation:this.globalCompositeOperation,transformMatrix:this.transformMatrix?this.transformMatrix.concat():null,skewX:n(this.skewX,r),skewY:n(this.skewY,r)};return e.util.populateWithProperties(this,i,t),this.includeDefaultValues||(i=this._removeDefaultValues(i)),i},toDatalessObject:function(t){return this.toObject(t)},_removeDefaultValues:function(t){var r=e.util.getKlass(t.type).prototype;return r.stateProperties.forEach(function(e){t[e]===r[e]&&delete t[e],"[object Array]"===Object.prototype.toString.call(t[e])&&"[object Array]"===Object.prototype.toString.call(r[e])&&0===t[e].length&&0===r[e].length&&delete t[e]}),t},toString:function(){return"#<fabric."+o(this.type)+">"},getObjectScaling:function(){var t=this.scaleX,e=this.scaleY;if(this.group){var r=this.group.getObjectScaling();t*=r.scaleX,e*=r.scaleY}return{scaleX:t,scaleY:e}},getObjectOpacity:function(){var t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t},_set:function(t,r){return("scaleX"===t||"scaleY"===t)&&(r=this._constrainScale(r)),"scaleX"===t&&r<0?(this.flipX=!this.flipX,r*=-1):"scaleY"===t&&r<0?(this.flipY=!this.flipY,r*=-1):"shadow"!==t||!r||r instanceof e.Shadow?"dirty"===t&&this.group&&this.group.set("dirty",r):r=new e.Shadow(r),this[t]=r,this.cacheProperties.indexOf(t)>-1&&(this.group&&this.group.set("dirty",!0),this.dirty=!0),this.group&&this.stateProperties.indexOf(t)>-1&&this.group.isOnACache()&&this.group.set("dirty",!0),"width"!==t&&"height"!==t||(this.minScaleLimit=Math.min(.1,1/Math.max(this.width,this.height))),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:e.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||0===this.width&&0===this.height||!this.visible},render:function(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t,this),this.transformMatrix&&t.transform.apply(t,this.transformMatrix),this.clipTo&&e.util.clipContext(this,t),this.shouldCache()?(this._cacheCanvas||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext),this.dirty=!1),this.drawCacheOnCanvas(t)):(this.dirty=!1,this.drawObject(t),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),this.clipTo&&t.restore(),t.restore())},needsItsOwnCache:function(){return!1},shouldCache:function(){return this.ownCaching=this.objectCaching&&(!this.group||this.needsItsOwnCache()||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawObject:function(t){this._renderBackground(t),this._setStrokeStyles(t,this),this._setFillStyles(t,this),this._render(t)},drawCacheOnCanvas:function(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(t){if(this.isNotVisible())return!1;if(this._cacheCanvas&&!t&&this._updateCacheCanvas())return!0;if(this.dirty||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&!t){var e=this.cacheWidth/this.zoomX,r=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-e/2,-r/2,e,r)}return!0}return!1},_renderBackground:function(t){if(this.backgroundColor){var e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}},_setOpacity:function(t){this.group&&!this.group.transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity},_setStrokeStyles:function(t,e){e.stroke&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,t.strokeStyle=e.stroke.toLive?e.stroke.toLive(t,this):e.stroke)},_setFillStyles:function(t,e){e.fill&&(t.fillStyle=e.fill.toLive?e.fill.toLive(t,this):e.fill)},_setLineDash:function(t,e,r){e&&(1&e.length&&e.push.apply(e,e),s?t.setLineDash(e):r&&r(t))},_renderControls:function(t,r){var i=this.getViewportTransform(),n=this.calcTransformMatrix(),o,s,c;r=r||{},s=void 0!==r.hasBorders?r.hasBorders:this.hasBorders,c=void 0!==r.hasControls?r.hasControls:this.hasControls,n=e.util.multiplyTransformMatrices(i,n),o=e.util.qrDecompose(n),t.save(),t.translate(o.translateX,o.translateY),t.lineWidth=1*this.borderScaleFactor,this.group||(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),r.forActiveSelection?(t.rotate(a(o.angle)),s&&this.drawBordersInGroup(t,o,r)):(t.rotate(a(this.angle)),s&&this.drawBorders(t,r)),c&&this.drawControls(t,r),t.restore()},_setShadow:function(t){if(this.shadow){var r=this.canvas&&this.canvas.viewportTransform[0]||1,i=this.canvas&&this.canvas.viewportTransform[3]||1,n=this.getObjectScaling();this.canvas&&this.canvas._isRetinaScaling()&&(r*=e.devicePixelRatio,i*=e.devicePixelRatio),t.shadowColor=this.shadow.color,t.shadowBlur=this.shadow.blur*(r+i)*(n.scaleX+n.scaleY)/4,t.shadowOffsetX=this.shadow.offsetX*r*n.scaleX,t.shadowOffsetY=this.shadow.offsetY*i*n.scaleY}},_removeShadow:function(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)},_applyPatternGradientTransform:function(t,e){if(e.toLive){var r=e.gradientTransform||e.patternTransform,i=-this.width/2+e.offsetX||0,n=-this.height/2+e.offsetY||0;t.translate(i,n),r&&t.transform.apply(t,r)}},_renderFill:function(t){this.fill&&(t.save(),this._applyPatternGradientTransform(t,this.fill),"evenodd"===this.fillRule?t.fill("evenodd"):t.fill(),t.restore())},_renderStroke:function(t){this.stroke&&0!==this.strokeWidth&&(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this._setLineDash(t,this.strokeDashArray,this._renderDashedStroke),this._applyPatternGradientTransform(t,this.stroke),t.stroke(),t.restore())},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_removeTransformMatrix:function(){var t=this._findCenterFromElement();if(this.transformMatrix){var r=e.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",r.scaleX),this.set("scaleY",r.scaleY),this.angle=r.angle,this.skewX=r.skewX,this.skewY=0,t=e.util.transformPoint(t,this.transformMatrix)}this.transformMatrix=null,this.setPositionByOrigin(t,"center","center")},clone:function(t,r){var i=this.toObject(r);this.constructor.fromObject?this.constructor.fromObject(i,t):e.Object._fromObject("Object",i,t)},cloneAsImage:function(t,r){var i=this.toDataURL(r);return e.util.loadImage(i,function(r){t&&t(new e.Image(r))}),this},toDataURL:function(t){t||(t={});var r=e.util.createCanvasElement(),i=this.getBoundingRect();r.width=i.width,r.height=i.height,e.util.wrapElement(r,"div");var n=new e.StaticCanvas(r,{enableRetinaScaling:t.enableRetinaScaling});"jpg"===t.format&&(t.format="jpeg"),"jpeg"===t.format&&(n.backgroundColor="#fff");var o={active:this.active,left:this.left,top:this.top};this.set("active",!1),this.setPositionByOrigin(new e.Point(n.width/2,n.height/2),"center","center");var a=this.canvas;n.add(this);var s=n.toDataURL(t);return this.set(o).setCoords(),this.canvas=a,n.dispose(),n=null,s},isType:function(t){return this.type===t},complexity:function(){return 1},toJSON:function(t){return this.toObject(t)},setGradient:function(t,r){r||(r={});var i={colorStops:[]};return i.type=r.type||(r.r1||r.r2?"radial":"linear"),i.coords={x1:r.x1,y1:r.y1,x2:r.x2,y2:r.y2},(r.r1||r.r2)&&(i.coords.r1=r.r1,i.coords.r2=r.r2),i.gradientTransform=r.gradientTransform,e.Gradient.prototype.addColorStop.call(i,r.colorStops),this.set(t,e.Gradient.forObject(this,i))},setPatternFill:function(t){return this.set("fill",new e.Pattern(t))},setShadow:function(t){return this.set("shadow",t?new e.Shadow(t):null)},setColor:function(t){return this.set("fill",t),this},setAngle:function(t){var e=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return e&&this._setOriginToCenter(),this.set("angle",t),e&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},remove:function(){return this.canvas&&this.canvas.remove(this),this},getLocalPointer:function(t,r){r=r||this.canvas.getPointer(t);var i=new e.Point(r.x,r.y),n=this._getLeftTopCoords();return this.angle&&(i=e.util.rotatePoint(i,n,a(-this.angle))),{x:i.x-n.x,y:i.y-n.y}},_setupCompositeOperation:function(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)}}),e.util.createAccessors&&e.util.createAccessors(e.Object),e.Object.prototype.rotate=e.Object.prototype.setAngle,r(e.Object.prototype,e.Observable),e.Object.NUM_FRACTION_DIGITS=2,e.Object._fromObject=function(t,r,n,o){var a=e[t];r=i(r,!0),e.util.enlivenPatterns([r.fill,r.stroke],function(t){void 0!==t[0]&&(r.fill=t[0]),void 0!==t[1]&&(r.stroke=t[1]);var e=o?new a(r[o],r):new a(r);n&&n(e)})},e.Object.__uid=0)}(exports),function(){var t=fabric.util.degreesToRadians,e={left:-.5,center:0,right:.5},r={top:-.5,center:0,bottom:.5};fabric.util.object.extend(fabric.Object.prototype,{translateToGivenOrigin:function(t,i,n,o,a){var s=t.x,c=t.y,l,h,u;return"string"==typeof i?i=e[i]:i-=.5,"string"==typeof o?o=e[o]:o-=.5,l=o-i,"string"==typeof n?n=r[n]:n-=.5,"string"==typeof a?a=r[a]:a-=.5,h=a-n,(l||h)&&(u=this._getTransformedDimensions(),s=t.x+l*u.x,c=t.y+h*u.y),new fabric.Point(s,c)},translateToCenterPoint:function(e,r,i){var n=this.translateToGivenOrigin(e,r,i,"center","center");return this.angle?fabric.util.rotatePoint(n,e,t(this.angle)):n},translateToOriginPoint:function(e,r,i){var n=this.translateToGivenOrigin(e,"center","center",r,i);return this.angle?fabric.util.rotatePoint(n,e,t(this.angle)):n},getCenterPoint:function(){var t=new fabric.Point(this.left,this.top);return this.translateToCenterPoint(t,this.originX,this.originY)},getPointByOrigin:function(t,e){var r=this.getCenterPoint();return this.translateToOriginPoint(r,t,e)},toLocalPoint:function(e,r,i){var n=this.getCenterPoint(),o,a;return o=void 0!==r&&void 0!==i?this.translateToGivenOrigin(n,"center","center",r,i):new fabric.Point(this.left,this.top),a=new fabric.Point(e.x,e.y),this.angle&&(a=fabric.util.rotatePoint(a,n,-t(this.angle))),a.subtractEquals(o)},setPositionByOrigin:function(t,e,r){var i=this.translateToCenterPoint(t,e,r),n=this.translateToOriginPoint(i,this.originX,this.originY);this.set("left",n.x),this.set("top",n.y)},adjustPosition:function(r){var i=t(this.angle),n=this.getScaledWidth(),o=Math.cos(i)*n,a=Math.sin(i)*n,s,c;s="string"==typeof this.originX?e[this.originX]:this.originX-.5,c="string"==typeof r?e[r]:r-.5,this.left+=o*(c-s),this.top+=a*(c-s),this.setCoords(),this.originX=r},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var t=this.getCenterPoint();this.originX="center",this.originY="center",this.left=t.x,this.top=t.y},_resetOrigin:function(){var t=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=t.x,this.top=t.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")},onDeselect:function(){}})}(),function(){function t(t){return[new fabric.Point(t.tl.x,t.tl.y),new fabric.Point(t.tr.x,t.tr.y),new fabric.Point(t.br.x,t.br.y),new fabric.Point(t.bl.x,t.bl.y)]}var e=fabric.util.degreesToRadians,r=fabric.util.multiplyTransformMatrices;fabric.util.object.extend(fabric.Object.prototype,{oCoords:null,aCoords:null,getCoords:function(e,r){this.oCoords||this.setCoords();var i=e?this.aCoords:this.oCoords;return t(r?this.calcCoords(e):i)},intersectsWithRect:function(t,e,r,i){var n=this.getCoords(r,i);return"Intersection"===fabric.Intersection.intersectPolygonRectangle(n,t,e).status},intersectsWithObject:function(t,e,r){return"Intersection"===fabric.Intersection.intersectPolygonPolygon(this.getCoords(e,r),t.getCoords(e,r)).status||t.isContainedWithinObject(this,e,r)||this.isContainedWithinObject(t,e,r)},isContainedWithinObject:function(t,e,r){for(var i=this.getCoords(e,r),n=0,o=t._getImageLines(r?t.calcCoords(e):e?t.aCoords:t.oCoords);n<4;n++)if(!t.containsPoint(i[n],o))return!1;return!0},isContainedWithinRect:function(t,e,r,i){var n=this.getBoundingRect(r,i);return n.left>=t.x&&n.left+n.width<=e.x&&n.top>=t.y&&n.top+n.height<=e.y},containsPoint:function(t,e,r,i){var e=e||this._getImageLines(i?this.calcCoords(r):r?this.aCoords:this.oCoords),n=this._findCrossPoints(t,e);return 0!==n&&n%2==1},isOnScreen:function(t){if(!this.canvas)return!1;for(var e=this.canvas.vptCoords.tl,r=this.canvas.vptCoords.br,i=this.getCoords(!0,t),n,o=0;o<4;o++)if(n=i[o],n.x<=r.x&&n.x>=e.x&&n.y<=r.y&&n.y>=e.y)return!0;if(this.intersectsWithRect(e,r,!0))return!0;var a={x:(e.x+r.x)/2,y:(e.y+r.y)/2};return!!this.containsPoint(a,null,!0)},_getImageLines:function(t){return{topline:{o:t.tl,d:t.tr},rightline:{o:t.tr,d:t.br},bottomline:{o:t.br,d:t.bl},leftline:{o:t.bl,d:t.tl}}},_findCrossPoints:function(t,e){var r,i,n,o,a,s=0,c;for(var l in e)if(c=e[l],!(c.o.y<t.y&&c.d.y<t.y||c.o.y>=t.y&&c.d.y>=t.y||(c.o.x===c.d.x&&c.o.x>=t.x?a=c.o.x:(r=0,i=(c.d.y-c.o.y)/(c.d.x-c.o.x),n=t.y-r*t.x,o=c.o.y-i*c.o.x,a=-(n-o)/(r-i)),a>=t.x&&(s+=1),2!==s)))break;return s},getBoundingRectWidth:function(){return this.getBoundingRect().width},getBoundingRectHeight:function(){return this.getBoundingRect().height},getBoundingRect:function(t,e){var r=this.getCoords(t,e);return fabric.util.makeBoundingBoxFromPoints(r)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(t){return Math.abs(t)<this.minScaleLimit?t<0?-this.minScaleLimit:this.minScaleLimit:t},scale:function(t){return t=this._constrainScale(t),t<0&&(this.flipX=!this.flipX,this.flipY=!this.flipY,t*=-1),this.scaleX=t,this.scaleY=t,this.setCoords()},scaleToWidth:function(t){var e=this.getBoundingRect().width/this.getScaledWidth();return this.scale(t/this.width/e)},scaleToHeight:function(t){var e=this.getBoundingRect().height/this.getScaledHeight();return this.scale(t/this.height/e)},calcCoords:function(t){var r=e(this.angle),i=this.getViewportTransform(),n=t?this._getTransformedDimensions():this._calculateCurrentDimensions(),o=n.x,a=n.y,s=Math.sin(r),c=Math.cos(r),l=o>0?Math.atan(a/o):0,h=o/Math.cos(l)/2,u=Math.cos(l+r)*h,f=Math.sin(l+r)*h,d=this.getCenterPoint(),p=t?d:fabric.util.transformPoint(d,i),g=new fabric.Point(p.x-u,p.y-f),v=new fabric.Point(g.x+o*c,g.y+o*s),m=new fabric.Point(g.x-a*s,g.y+a*c),b=new fabric.Point(p.x+u,p.y+f);if(!t)var y=new fabric.Point((g.x+m.x)/2,(g.y+m.y)/2),_=new fabric.Point((v.x+g.x)/2,(v.y+g.y)/2),w=new fabric.Point((b.x+v.x)/2,(b.y+v.y)/2),S=new fabric.Point((b.x+m.x)/2,(b.y+m.y)/2),x=new fabric.Point(_.x+s*this.rotatingPointOffset,_.y-c*this.rotatingPointOffset);var p={tl:g,tr:v,br:b,bl:m};return t||(p.ml=y,p.mt=_,p.mr=w,p.mb=S,p.mtr=x),p},setCoords:function(t,e){return this.oCoords=this.calcCoords(t),e||(this.aCoords=this.calcCoords(!0)),t||this._setCornerCoords&&this._setCornerCoords(),this},_calcRotateMatrix:function(){if(this.angle){var t=e(this.angle),r=Math.cos(t),i=Math.sin(t);return 6.123233995736766e-17!==r&&-1.8369701987210297e-16!==r||(r=0),[r,i,-i,r,0,0]}return fabric.iMatrix.concat()},calcTransformMatrix:function(t){var e=this.getCenterPoint(),i=[1,0,0,1,e.x,e.y],n,o=this._calcDimensionsTransformMatrix(this.skewX,this.skewY,!0),a;return a=this.group&&!t?r(this.group.calcTransformMatrix(),i):i,this.angle&&(n=this._calcRotateMatrix(),a=r(a,n)),a=r(a,o)},_calcDimensionsTransformMatrix:function(t,i,n){var o,a=this.scaleX*(n&&this.flipX?-1:1),s=this.scaleY*(n&&this.flipY?-1:1),c=[a,0,0,s,0,0];return t&&(o=[1,0,Math.tan(e(t)),1],c=r(c,o,!0)),i&&(o=[1,Math.tan(e(i)),0,1],c=r(c,o,!0)),c},_getNonTransformedDimensions:function(){var t=this.strokeWidth;return{x:this.width+t,y:this.height+t}},_getTransformedDimensions:function(t,e){void 0===t&&(t=this.skewX),void 0===e&&(e=this.skewY);var r=this._getNonTransformedDimensions(),i=r.x/2,n=r.y/2,o=[{x:-i,y:-n},{x:i,y:-n},{x:-i,y:n},{x:i,y:n}],a,s=this._calcDimensionsTransformMatrix(t,e,!1),c;for(a=0;a<o.length;a++)o[a]=fabric.util.transformPoint(o[a],s);return c=fabric.util.makeBoundingBoxFromPoints(o),{x:c.width,y:c.height}},_calculateCurrentDimensions:function(){var t=this.getViewportTransform(),e=this._getTransformedDimensions();return fabric.util.transformPoint(e,t,!0).scalarAdd(2*this.padding)}})}(),fabric.util.object.extend(fabric.Object.prototype,{sendToBack:function(){return this.group?fabric.StaticCanvas.prototype.sendToBack.call(this.group,this):this.canvas.sendToBack(this),this},bringToFront:function(){return this.group?fabric.StaticCanvas.prototype.bringToFront.call(this.group,this):this.canvas.bringToFront(this),this},sendBackwards:function(t){return this.group?fabric.StaticCanvas.prototype.sendBackwards.call(this.group,this,t):this.canvas.sendBackwards(this,t),this},bringForward:function(t){return this.group?fabric.StaticCanvas.prototype.bringForward.call(this.group,this,t):this.canvas.bringForward(this,t),this},moveTo:function(t){return this.group?fabric.StaticCanvas.prototype.moveTo.call(this.group,this,t):this.canvas.moveTo(this,t),this}}),function(){function t(t,e){if(e){if(e.toLive)return t+": url(#SVGID_"+e.id+"); ";var r=new fabric.Color(e),i=t+": "+r.toRgb()+"; ",n=r.getAlpha();return 1!==n&&(i+=t+"-opacity: "+n.toString()+"; "),i}return t+": none; "}var e=fabric.Object.NUM_FRACTION_DIGITS,r=fabric.util.toFixed;fabric.util.object.extend(fabric.Object.prototype,{getSvgStyles:function(e){var r=this.fillRule,i=this.strokeWidth?this.strokeWidth:"0",n=this.strokeDashArray?this.strokeDashArray.join(" "):"none",o=this.strokeLineCap?this.strokeLineCap:"butt",a=this.strokeLineJoin?this.strokeLineJoin:"miter",s=this.strokeMiterLimit?this.strokeMiterLimit:"4",c=void 0!==this.opacity?this.opacity:"1",l=this.visible?"":" visibility: hidden;",h=e?"":this.getSvgFilter(),u=t("fill",this.fill);return[t("stroke",this.stroke),"stroke-width: ",i,"; ","stroke-dasharray: ",n,"; ","stroke-linecap: ",o,"; ","stroke-linejoin: ",a,"; ","stroke-miterlimit: ",s,"; ",u,"fill-rule: ",r,"; ","opacity: ",c,";",h,l].join("")},getSvgSpanStyles:function(e){var r=e.strokeWidth?"stroke-width: "+e.strokeWidth+"; ":"",i=e.fontFamily?"font-family: "+e.fontFamily.replace(/"/g,"'")+"; ":"",n=e.fontSize?"font-size: "+e.fontSize+"; ":"",o=e.fontStyle?"font-style: "+e.fontStyle+"; ":"",a=e.fontWeight?"font-weight: "+e.fontWeight+"; ":"",s=e.fill?t("fill",e.fill):"";return[e.stroke?t("stroke",e.stroke):"",r,i,n,o,a,this.getSvgTextDecoration(e),s].join("")},getSvgTextDecoration:function(t){return"overline"in t||"underline"in t||"linethrough"in t?"text-decoration: "+(t.overline?"overline ":"")+(t.underline?"underline ":"")+(t.linethrough?"line-through ":"")+";":""},getSvgFilter:function(){return this.shadow?"filter: url(#SVGID_"+this.shadow.id+");":""},getSvgId:function(){return this.id?'id="'+this.id+'" ':""},getSvgTransform:function(){var t=this.angle,e=this.skewX%360,i=this.skewY%360,n=this.getCenterPoint(),o=fabric.Object.NUM_FRACTION_DIGITS,a="translate("+r(n.x,o)+" "+r(n.y,o)+")",s=0!==t?" rotate("+r(t,o)+")":"",c=1===this.scaleX&&1===this.scaleY?"":" scale("+r(this.scaleX,o)+" "+r(this.scaleY,o)+")",l=0!==e?" skewX("+r(e,o)+")":"",h=0!==i?" skewY("+r(i,o)+")":"";return[a,s,c,this.flipX?" matrix(-1 0 0 1 0 0) ":"",this.flipY?" matrix(1 0 0 -1 0 0)":"",l,h].join("")},getSvgTransformMatrix:function(){return this.transformMatrix?" matrix("+this.transformMatrix.join(" ")+") ":""},_setSVGBg:function(t){this.backgroundColor&&t.push("\t\t<rect ",this._getFillAttributes(this.backgroundColor),' x="',r(-this.width/2,e),'" y="',r(-this.height/2,e),'" width="',r(this.width,e),'" height="',r(this.height,e),'"></rect>\n')},_createBaseSVGMarkup:function(){var t=[];return this.fill&&this.fill.toLive&&t.push(this.fill.toSVG(this,!1)),this.stroke&&this.stroke.toLive&&t.push(this.stroke.toSVG(this,!1)),this.shadow&&t.push(this.shadow.toSVG(this)),t}})}(),function(){function t(t,e,i){var n={},o=!0;i.forEach(function(e){n[e]=t[e]}),r(t[e],n,!0)}function e(t,r,i){if(t===r)return!0;if(Array.isArray(t)){if(t.length!==r.length)return!1;for(var n=0,o=t.length;n<o;n++)if(!e(t[n],r[n]))return!1;return!0}if(t&&"object"==typeof t){var a=Object.keys(t),s;if(!i&&a.length!==Object.keys(r).length)return!1;for(var n=0,o=a.length;n<o;n++)if(s=a[n],!e(t[s],r[s]))return!1;return!0}}var r=fabric.util.object.extend,i="stateProperties";fabric.util.object.extend(fabric.Object.prototype,{hasStateChanged:function(t){t=t||i;var r="_"+t;return Object.keys(this[r]).length<this[t].length||!e(this[r],this,!0)},saveState:function(e){var r=e&&e.propertySet||i,n="_"+r;return this[n]?(t(this,n,this[r]),e&&e.stateProperties&&t(this,n,e.stateProperties),this):this.setupState(e)},setupState:function(t){t=t||{};var e=t.propertySet||i;return t.propertySet=e,this["_"+e]={},this.saveState(t),this}})}(),function(){var t=fabric.util.degreesToRadians;fabric.util.object.extend(fabric.Object.prototype,{_controlsVisibility:null,_findTargetCorner:function(t){if(!this.hasControls||!this.active||this.group)return!1;var e=t.x,r=t.y,i,n;this.__corner=0;for(var o in this.oCoords)if(this.isControlVisible(o)&&("mtr"!==o||this.hasRotatingPoint)&&(!this.get("lockUniScaling")||"mt"!==o&&"mr"!==o&&"mb"!==o&&"ml"!==o)&&(n=this._getImageLines(this.oCoords[o].corner),0!==(i=this._findCrossPoints({x:e,y:r},n))&&i%2==1))return this.__corner=o,o;return!1},_setCornerCoords:function(){var e=this.oCoords,r=t(45-this.angle),i=.707106*this.cornerSize,n=i*Math.cos(r),o=i*Math.sin(r),a,s;for(var c in e)a=e[c].x,s=e[c].y,e[c].corner={tl:{x:a-o,y:s-n},tr:{x:a+n,y:s-o},bl:{x:a-n,y:s+o},br:{x:a+o,y:s+n}}},drawSelectionBackground:function(e){if(!this.selectionBackgroundColor||!this.active||this.canvas&&!this.canvas.interactive)return this;e.save();var r=this.getCenterPoint(),i=this._calculateCurrentDimensions(),n=this.canvas.viewportTransform;return e.translate(r.x,r.y),e.scale(1/n[0],1/n[3]),e.rotate(t(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-i.x/2,-i.y/2,i.x,i.y),e.restore(),this},drawBorders:function(t,e){e=e||{};var r=this._calculateCurrentDimensions(),i=1/this.borderScaleFactor,n=r.x+i,o=r.y+i,a=void 0!==e.hasRotatingPoint?e.hasRotatingPoint:this.hasRotatingPoint,s=void 0!==e.hasControls?e.hasControls:this.hasControls,c=void 0!==e.rotatingPointOffset?e.rotatingPointOffset:this.rotatingPointOffset;if(t.save(),t.strokeStyle=e.borderColor||this.borderColor,this._setLineDash(t,e.borderDashArray||this.borderDashArray,null),t.strokeRect(-n/2,-o/2,n,o),a&&this.isControlVisible("mtr")&&s){var l=-o/2;t.beginPath(),t.moveTo(0,l),t.lineTo(0,l-c),t.closePath(),t.stroke()}return t.restore(),this},drawBordersInGroup:function(t,e,r){r=r||{};var i=this._getNonTransformedDimensions(),n=fabric.util.customTransformMatrix(e.scaleX,e.scaleY,e.skewX),o=fabric.util.transformPoint(i,n),a=1/this.borderScaleFactor,s=o.x+a,c=o.y+a;return t.save(),this._setLineDash(t,r.borderDashArray||this.borderDashArray,null),t.strokeStyle=r.borderColor||this.borderColor,t.strokeRect(-s/2,-c/2,s,c),t.restore(),this},drawControls:function(t,e){e=e||{};var r=this._calculateCurrentDimensions(),i=r.x,n=r.y,o=e.cornerSize||this.cornerSize,a=-(i+o)/2,s=-(n+o)/2,c=void 0!==e.transparentCorners?e.transparentCorners:this.transparentCorners,l=void 0!==e.hasRotatingPoint?e.hasRotatingPoint:this.hasRotatingPoint,h=c?"stroke":"fill";return t.save(),t.strokeStyle=t.fillStyle=e.cornerColor||this.cornerColor,this.transparentCorners||(t.strokeStyle=e.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(t,e.cornerDashArray||this.cornerDashArray,null),this._drawControl("tl",t,h,a,s,e),this._drawControl("tr",t,h,a+i,s,e),this._drawControl("bl",t,h,a,s+n,e),this._drawControl("br",t,h,a+i,s+n,e),this.get("lockUniScaling")||(this._drawControl("mt",t,h,a+i/2,s,e),this._drawControl("mb",t,h,a+i/2,s+n,e),this._drawControl("mr",t,h,a+i,s+n/2,e),this._drawControl("ml",t,h,a,s+n/2,e)),l&&this._drawControl("mtr",t,h,a+i/2,s-this.rotatingPointOffset,e),t.restore(),this},_drawControl:function(t,e,r,i,n,o){if(o=o||{},this.isControlVisible(t)){var a=this.cornerSize,s=!this.transparentCorners&&this.cornerStrokeColor;switch(o.cornerStyle||this.cornerStyle){case"circle":e.beginPath(),e.arc(i+a/2,n+a/2,a/2,0,2*Math.PI,!1),e[r](),s&&e.stroke();break;default:this.transparentCorners||e.clearRect(i,n,a,a),e[r+"Rect"](i,n,a,a),s&&e.strokeRect(i,n,a,a)}}},isControlVisible:function(t){return this._getControlsVisibility()[t]},setControlVisible:function(t,e){return this._getControlsVisibility()[t]=e,this},setControlsVisibility:function(t){t||(t={});for(var e in t)this.setControlVisible(e,t[e]);return this},_getControlsVisibility:function(){return this._controlsVisibility||(this._controlsVisibility={tl:!0,tr:!0,br:!0,bl:!0,ml:!0,mt:!0,mr:!0,mb:!0,mtr:!0}),this._controlsVisibility}})}(),fabric.util.object.extend(fabric.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(t,e){e=e||{};var r=function(){},i=e.onComplete||r,n=e.onChange||r,o=this;return fabric.util.animate({startValue:t.left,endValue:this.getCenter().left,duration:this.FX_DURATION,onChange:function(e){t.set("left",e),o.requestRenderAll(),n()},onComplete:function(){t.setCoords(),i()}}),this},fxCenterObjectV:function(t,e){e=e||{};var r=function(){},i=e.onComplete||r,n=e.onChange||r,o=this;return fabric.util.animate({startValue:t.top,endValue:this.getCenter().top,duration:this.FX_DURATION,onChange:function(e){t.set("top",e),o.requestRenderAll(),n()},onComplete:function(){t.setCoords(),i()}}),this},fxRemove:function(t,e){e=e||{};var r=function(){},i=e.onComplete||r,n=e.onChange||r,o=this;return fabric.util.animate({startValue:t.opacity,endValue:0,duration:this.FX_DURATION,onStart:function(){t.set("active",!1)},onChange:function(e){t.set("opacity",e),o.requestRenderAll(),n()},onComplete:function(){o.remove(t),i()}}),this}}),fabric.util.object.extend(fabric.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var t=[],e,r;for(e in arguments[0])t.push(e);for(var i=0,n=t.length;i<n;i++)e=t[i],r=i!==n-1,this._animate(e,arguments[0][e],arguments[1],r)}else this._animate.apply(this,arguments);return this},_animate:function(t,e,r,i){var n=this,o;e=e.toString(),r=r?fabric.util.object.clone(r):{},~t.indexOf(".")&&(o=t.split("."));var a=o?this.get(o[0])[o[1]]:this.get(t);"from"in r||(r.from=a),e=~e.indexOf("=")?a+parseFloat(e.replace("=","")):parseFloat(e),fabric.util.animate({startValue:r.from,endValue:e,byValue:r.by,easing:r.easing,duration:r.duration,abort:r.abort&&function(){return r.abort.call(n)},onChange:function(e,a,s){o?n[o[0]][o[1]]=e:n.set(t,e),i||r.onChange&&r.onChange(e,a,s)},onComplete:function(t,e,o){i||(n.setCoords(),r.onComplete&&r.onComplete(t,e,o))}})}}),function(t){"use strict";function e(t,e){var r=t.origin,i=t.axis1,n=t.axis2,o=t.dimension,a=e.nearest,s=e.center,c=e.farthest;return function(){switch(this.get(r)){case a:return Math.min(this.get(i),this.get(n));case s:return Math.min(this.get(i),this.get(n))+.5*this.get(o);case c:return Math.max(this.get(i),this.get(n))}}}var r=t.fabric||(t.fabric={}),i=r.util.object.extend,n=r.util.object.clone,o={x1:1,x2:1,y1:1,y2:1},a=r.StaticCanvas.supports("setLineDash");if(r.Line)return void r.warn("fabric.Line is already defined");var s=r.Object.prototype.cacheProperties.concat();s.push("x1","x2","y1","y2"),r.Line=r.util.createClass(r.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:s,initialize:function(t,e){t||(t=[0,0,0,0]),this.callSuper("initialize",e),this.set("x1",t[0]),this.set("y1",t[1]),this.set("x2",t[2]),this.set("y2",t[3]),this._setWidthHeight(e)},_setWidthHeight:function(t){t||(t={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in t?t.left:this._getLeftToOriginX(),this.top="top"in t?t.top:this._getTopToOriginY()},_set:function(t,e){return this.callSuper("_set",t,e),void 0!==o[t]&&this._setWidthHeight(),this},_getLeftToOriginX:e({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:e({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(t){if(t.beginPath(),!this.strokeDashArray||this.strokeDashArray&&a){var e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2)}t.lineWidth=this.strokeWidth;var r=t.strokeStyle;t.strokeStyle=this.stroke||t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=r},_renderDashedStroke:function(t){var e=this.calcLinePoints();t.beginPath(),r.util.drawDashedLine(t,e.x1,e.y1,e.x2,e.y2,this.strokeDashArray),t.closePath()},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(t){return i(this.callSuper("toObject",t),this.calcLinePoints())},_getNonTransformedDimensions:function(){var t=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(t.y-=this.strokeWidth),0===this.height&&(t.x-=this.strokeWidth)),t},calcLinePoints:function(){var t=this.x1<=this.x2?-1:1,e=this.y1<=this.y2?-1:1,r=t*this.width*.5,i=e*this.height*.5;return{x1:r,x2:t*this.width*-.5,y1:i,y2:e*this.height*-.5}},toSVG:function(t){var e=this._createBaseSVGMarkup(),r=this.calcLinePoints();return e.push("<line ",this.getSvgId(),'x1="',r.x1,'" y1="',r.y1,'" x2="',r.x2,'" y2="',r.y2,'" style="',this.getSvgStyles(),'" transform="',this.getSvgTransform(),this.getSvgTransformMatrix(),'"/>\n'),t?t(e.join("")):e.join("")}}),r.Line.ATTRIBUTE_NAMES=r.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),r.Line.fromElement=function(t,e,n){n=n||{};var o=r.parseAttributes(t,r.Line.ATTRIBUTE_NAMES),a=[o.x1||0,o.y1||0,o.x2||0,o.y2||0];n.originX="left",n.originY="top",e(new r.Line(a,i(o,n)))},r.Line.fromObject=function(t,e){function i(t){delete t.points,e&&e(t)}var o=n(t,!0);o.points=[t.x1,t.y1,t.x2,t.y2],r.Object._fromObject("Line",o,i,"points")}}(exports),function(t){"use strict";function e(t){return"radius"in t&&t.radius>=0}var r=t.fabric||(t.fabric={}),i=Math.PI,n=r.util.object.extend;if(r.Circle)return void r.warn("fabric.Circle is already defined.");var o=r.Object.prototype.cacheProperties.concat();o.push("radius"),r.Circle=r.util.createClass(r.Object,{type:"circle",radius:0,startAngle:0,endAngle:2*i,cacheProperties:o,initialize:function(t){this.callSuper("initialize",t),this.set("radius",t&&t.radius||0)},_set:function(t,e){return this.callSuper("_set",t,e),"radius"===t&&this.setRadius(e),this},toObject:function(t){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(t))},toSVG:function(t){var e=this._createBaseSVGMarkup(),r=0,n=0,o=(this.endAngle-this.startAngle)%(2*i);if(0===o)e.push("<circle ",this.getSvgId(),'cx="0" cy="0" ','r="',this.radius,'" style="',this.getSvgStyles(),'" transform="',this.getSvgTransform()," ",this.getSvgTransformMatrix(),'"/>\n');else{var a=Math.cos(this.startAngle)*this.radius,s=Math.sin(this.startAngle)*this.radius,c=Math.cos(this.endAngle)*this.radius,l=Math.sin(this.endAngle)*this.radius,h=o>i?"1":"0";e.push('<path d="M '+a+" "+s," A "+this.radius+" "+this.radius," 0 ",+h+" 1"," "+c+" "+l,'" style="',this.getSvgStyles(),'" transform="',this.getSvgTransform()," ",this.getSvgTransformMatrix(),'"/>\n')}return t?t(e.join("")):e.join("")},_render:function(t){t.beginPath(),t.arc(0,0,this.radius,this.startAngle,this.endAngle,!1),this._renderFill(t),this._renderStroke(t)},getRadiusX:function(){return this.get("radius")*this.get("scaleX")},getRadiusY:function(){return this.get("radius")*this.get("scaleY")},setRadius:function(t){return this.radius=t,this.set("width",2*t).set("height",2*t)}}),r.Circle.ATTRIBUTE_NAMES=r.SHARED_ATTRIBUTES.concat("cx cy r".split(" ")),r.Circle.fromElement=function(t,i,o){o||(o={});var a=r.parseAttributes(t,r.Circle.ATTRIBUTE_NAMES);if(!e(a))throw new Error("value of `r` attribute is required and can not be negative");a.left=(a.left||0)-a.radius,a.top=(a.top||0)-a.radius,a.originX="left",a.originY="top",i(new r.Circle(n(a,o)))},r.Circle.fromObject=function(t,e){return r.Object._fromObject("Circle",t,e)}}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={});if(e.Triangle)return void e.warn("fabric.Triangle is already defined");e.Triangle=e.util.createClass(e.Object,{type:"triangle",initialize:function(t){this.callSuper("initialize",t),this.set("width",t&&t.width||100).set("height",t&&t.height||100)},_render:function(t){var e=this.width/2,r=this.height/2;t.beginPath(),t.moveTo(-e,r),t.lineTo(0,-r),t.lineTo(e,r),t.closePath(),this._renderFill(t),this._renderStroke(t)},_renderDashedStroke:function(t){var r=this.width/2,i=this.height/2;t.beginPath(),e.util.drawDashedLine(t,-r,i,0,-i,this.strokeDashArray),e.util.drawDashedLine(t,0,-i,r,i,this.strokeDashArray),e.util.drawDashedLine(t,r,i,-r,i,this.strokeDashArray),t.closePath()},toSVG:function(t){var e=this._createBaseSVGMarkup(),r=this.width/2,i=this.height/2,n=[-r+" "+i,"0 "+-i,r+" "+i].join(",");return e.push("<polygon ",this.getSvgId(),'points="',n,'" style="',this.getSvgStyles(),'" transform="',this.getSvgTransform(),'"/>'),t?t(e.join("")):e.join("")}}),e.Triangle.fromObject=function(t,r){return e.Object._fromObject("Triangle",t,r)}}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=2*Math.PI,i=e.util.object.extend;if(e.Ellipse)return void e.warn("fabric.Ellipse is already defined.");var n=e.Object.prototype.cacheProperties.concat();n.push("rx","ry"),e.Ellipse=e.util.createClass(e.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:n,initialize:function(t){this.callSuper("initialize",t),this.set("rx",t&&t.rx||0),this.set("ry",t&&t.ry||0)},_set:function(t,e){switch(this.callSuper("_set",t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},toSVG:function(t){var e=this._createBaseSVGMarkup(),r=0,i=0;return e.push("<ellipse ",this.getSvgId(),'cx="',0,'" cy="',0,'" ','rx="',this.rx,'" ry="',this.ry,'" style="',this.getSvgStyles(),'" transform="',this.getSvgTransform(),this.getSvgTransformMatrix(),'"/>\n'),t?t(e.join("")):e.join("")},_render:function(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,r,!1),t.restore(),this._renderFill(t),this._renderStroke(t)}}),e.Ellipse.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),e.Ellipse.fromElement=function(t,r,n){n||(n={});var o=e.parseAttributes(t,e.Ellipse.ATTRIBUTE_NAMES);o.left=(o.left||0)-o.rx,o.top=(o.top||0)-o.ry,o.originX="left",o.originY="top",r(new e.Ellipse(i(o,n)))},e.Ellipse.fromObject=function(t,r){return e.Object._fromObject("Ellipse",t,r)}}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.util.object.extend;if(e.Rect)return void e.warn("fabric.Rect is already defined");var i=e.Object.prototype.stateProperties.concat();i.push("rx","ry");var n=e.Object.prototype.cacheProperties.concat();n.push("rx","ry"),e.Rect=e.util.createClass(e.Object,{stateProperties:i,type:"rect",rx:0,ry:0,cacheProperties:n,initialize:function(t){this.callSuper("initialize",t),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(t){if(1===this.width&&1===this.height)return void t.fillRect(-.5,-.5,1,1);var e=this.rx?Math.min(this.rx,this.width/2):0,r=this.ry?Math.min(this.ry,this.height/2):0,i=this.width,n=this.height,o=-this.width/2,a=-this.height/2,s=0!==e||0!==r,c=.4477152502;t.beginPath(),t.moveTo(o+e,a),t.lineTo(o+i-e,a),s&&t.bezierCurveTo(o+i-c*e,a,o+i,a+c*r,o+i,a+r),t.lineTo(o+i,a+n-r),s&&t.bezierCurveTo(o+i,a+n-c*r,o+i-c*e,a+n,o+i-e,a+n),t.lineTo(o+e,a+n),s&&t.bezierCurveTo(o+c*e,a+n,o,a+n-c*r,o,a+n-r),t.lineTo(o,a+r),s&&t.bezierCurveTo(o,a+c*r,o+c*e,a,o+e,a),t.closePath(),this._renderFill(t),this._renderStroke(t)},_renderDashedStroke:function(t){var r=-this.width/2,i=-this.height/2,n=this.width,o=this.height;t.beginPath(),e.util.drawDashedLine(t,r,i,r+n,i,this.strokeDashArray),e.util.drawDashedLine(t,r+n,i,r+n,i+o,this.strokeDashArray),e.util.drawDashedLine(t,r+n,i+o,r,i+o,this.strokeDashArray),e.util.drawDashedLine(t,r,i+o,r,i,this.strokeDashArray),t.closePath()},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},toSVG:function(t){var e=this._createBaseSVGMarkup(),r=-this.width/2,i=-this.height/2;return e.push("<rect ",this.getSvgId(),'x="',r,'" y="',i,'" rx="',this.get("rx"),'" ry="',this.get("ry"),'" width="',this.width,'" height="',this.height,'" style="',this.getSvgStyles(),'" transform="',this.getSvgTransform(),this.getSvgTransformMatrix(),'"/>\n'),t?t(e.join("")):e.join("")}}),e.Rect.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),e.Rect.fromElement=function(t,i,n){if(!t)return i(null);n=n||{};var o=e.parseAttributes(t,e.Rect.ATTRIBUTE_NAMES);o.left=o.left||0,o.top=o.top||0,o.originX="left",o.originY="top";var a=new e.Rect(r(n?e.util.object.clone(n):{},o));a.visible=a.visible&&a.width>0&&a.height>0,i(a)},e.Rect.fromObject=function(t,r){return e.Object._fromObject("Rect",t,r)}}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.util.object.extend,i=e.util.array.min,n=e.util.array.max,o=e.util.toFixed,a=e.Object.NUM_FRACTION_DIGITS;if(e.Polyline)return void e.warn("fabric.Polyline is already defined");var s=e.Object.prototype.cacheProperties.concat();s.push("points"),e.Polyline=e.util.createClass(e.Object,{type:"polyline",points:null,minX:0,minY:0,cacheProperties:s,initialize:function(t,e){e=e||{},this.points=t||[],this.callSuper("initialize",e),this._calcDimensions(),"top"in e||(this.top=this.minY),"left"in e||(this.left=this.minX),this.pathOffset={x:this.minX+this.width/2,y:this.minY+this.height/2}},_calcDimensions:function(){var t=this.points,e=i(t,"x"),r=i(t,"y"),o=n(t,"x"),a=n(t,"y");this.width=o-e||0,this.height=a-r||0,this.minX=e||0,this.minY=r||0},toObject:function(t){return r(this.callSuper("toObject",t),{points:this.points.concat()})},toSVG:function(t){for(var e=[],r=this.pathOffset.x,i=this.pathOffset.y,n=this._createBaseSVGMarkup(),s=0,c=this.points.length;s<c;s++)e.push(o(this.points[s].x-r,a),",",o(this.points[s].y-i,a)," ");return n.push("<",this.type," ",this.getSvgId(),'points="',e.join(""),'" style="',this.getSvgStyles(),'" transform="',this.getSvgTransform()," ",this.getSvgTransformMatrix(),'"/>\n'),t?t(n.join("")):n.join("")},commonRender:function(t){var e,r=this.points.length,i=this.pathOffset.x,n=this.pathOffset.y;if(!r||isNaN(this.points[r-1].y))return!1;t.beginPath(),t.moveTo(this.points[0].x-i,this.points[0].y-n);for(var o=0;o<r;o++)e=this.points[o],t.lineTo(e.x-i,e.y-n);return!0},_render:function(t){this.commonRender(t)&&(this._renderFill(t),this._renderStroke(t))},_renderDashedStroke:function(t){var r,i;t.beginPath();for(var n=0,o=this.points.length;n<o;n++)r=this.points[n],i=this.points[n+1]||r,e.util.drawDashedLine(t,r.x,r.y,i.x,i.y,this.strokeDashArray)},complexity:function(){return this.get("points").length}}),e.Polyline.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat(),e.Polyline.fromElement=function(t,r,i){if(!t)return r(null);i||(i={});var n=e.parsePointsAttribute(t.getAttribute("points")),o=e.parseAttributes(t,e.Polyline.ATTRIBUTE_NAMES);r(new e.Polyline(n,e.util.object.extend(o,i)))},e.Polyline.fromObject=function(t,r){return e.Object._fromObject("Polyline",t,r,"points")}}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.util.object.extend;if(e.Polygon)return void e.warn("fabric.Polygon is already defined");e.Polygon=e.util.createClass(e.Polyline,{type:"polygon",_render:function(t){this.commonRender(t)&&(t.closePath(),this._renderFill(t),this._renderStroke(t))},_renderDashedStroke:function(t){this.callSuper("_renderDashedStroke",t),t.closePath()}}),e.Polygon.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat(),e.Polygon.fromElement=function(t,i,n){if(!t)return i(null);n||(n={});var o=e.parsePointsAttribute(t.getAttribute("points")),a=e.parseAttributes(t,e.Polygon.ATTRIBUTE_NAMES);i(new e.Polygon(o,r(a,n)))},e.Polygon.fromObject=function(t,r){return e.Object._fromObject("Polygon",t,r,"points")}}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.util.array.min,i=e.util.array.max,n=e.util.object.extend,o=Object.prototype.toString,a=e.util.drawArc,s={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},c={m:"l",M:"L"};if(e.Path)return void e.warn("fabric.Path is already defined");var l=e.Object.prototype.stateProperties.concat();l.push("path");var h=e.Object.prototype.cacheProperties.concat();h.push("path","fillRule"),e.Path=e.util.createClass(e.Object,{type:"path",path:null,minX:0,minY:0,cacheProperties:h,stateProperties:l,initialize:function(t,e){e=e||{},this.callSuper("initialize",e),t||(t=[]);var r="[object Array]"===o.call(t);this.path=r?t:t.match&&t.match(/[mzlhvcsqta][^mzlhvcsqta]*/gi),this.path&&(r||(this.path=this._parsePath()),this._setPositionDimensions(e))},_setPositionDimensions:function(t){var e=this._parseDimensions();this.minX=e.left,this.minY=e.top,this.width=e.width,this.height=e.height,void 0===t.left&&(this.left=e.left+("center"===this.originX?this.width/2:"right"===this.originX?this.width:0)),void 0===t.top&&(this.top=e.top+("center"===this.originY?this.height/2:"bottom"===this.originY?this.height:0)),this.pathOffset=this.pathOffset||{x:this.minX+this.width/2,y:this.minY+this.height/2}},_renderPathCommands:function(t){var e,r=null,i=0,n=0,o=0,s=0,c=0,l=0,h,u,f=-this.pathOffset.x,d=-this.pathOffset.y;t.beginPath();for(var p=0,g=this.path.length;p<g;++p){switch(e=this.path[p],e[0]){case"l":o+=e[1],s+=e[2],t.lineTo(o+f,s+d);break;case"L":o=e[1],s=e[2],t.lineTo(o+f,s+d);break;case"h":o+=e[1],t.lineTo(o+f,s+d);break;case"H":o=e[1],t.lineTo(o+f,s+d);break;case"v":s+=e[1],t.lineTo(o+f,s+d);break;case"V":s=e[1],t.lineTo(o+f,s+d);break;case"m":o+=e[1],s+=e[2],i=o,n=s,t.moveTo(o+f,s+d);break;case"M":o=e[1],s=e[2],i=o,n=s,t.moveTo(o+f,s+d);break;case"c":h=o+e[5],u=s+e[6],c=o+e[3],l=s+e[4],t.bezierCurveTo(o+e[1]+f,s+e[2]+d,c+f,l+d,h+f,u+d),o=h,s=u;break;case"C":o=e[5],s=e[6],c=e[3],l=e[4],t.bezierCurveTo(e[1]+f,e[2]+d,c+f,l+d,o+f,s+d);break;case"s":h=o+e[3],u=s+e[4],null===r[0].match(/[CcSs]/)?(c=o,l=s):(c=2*o-c,l=2*s-l),t.bezierCurveTo(c+f,l+d,o+e[1]+f,s+e[2]+d,h+f,u+d),c=o+e[1],l=s+e[2],o=h,s=u;break;case"S":h=e[3],u=e[4],null===r[0].match(/[CcSs]/)?(c=o,l=s):(c=2*o-c,l=2*s-l),t.bezierCurveTo(c+f,l+d,e[1]+f,e[2]+d,h+f,u+d),o=h,s=u,c=e[1],l=e[2];break;case"q":h=o+e[3],u=s+e[4],c=o+e[1],l=s+e[2],t.quadraticCurveTo(c+f,l+d,h+f,u+d),o=h,s=u;break;case"Q":h=e[3],u=e[4],t.quadraticCurveTo(e[1]+f,e[2]+d,h+f,u+d),o=h,s=u,c=e[1],l=e[2];break;case"t":h=o+e[1],u=s+e[2],null===r[0].match(/[QqTt]/)?(c=o,l=s):(c=2*o-c,l=2*s-l),t.quadraticCurveTo(c+f,l+d,h+f,u+d),o=h,s=u;break;case"T":h=e[1],u=e[2],null===r[0].match(/[QqTt]/)?(c=o,l=s):(c=2*o-c,l=2*s-l),t.quadraticCurveTo(c+f,l+d,h+f,u+d),o=h,s=u;break;case"a":a(t,o+f,s+d,[e[1],e[2],e[3],e[4],e[5],e[6]+o+f,e[7]+s+d]),o+=e[6],s+=e[7];break;case"A":a(t,o+f,s+d,[e[1],e[2],e[3],e[4],e[5],e[6]+f,e[7]+d]),o=e[6],s=e[7];break;case"z":case"Z":o=i,s=n,t.closePath()}r=e}},_render:function(t){this._renderPathCommands(t),this._renderFill(t),this._renderStroke(t)},toString:function(){return"#<fabric.Path ("+this.complexity()+'): { "top": '+this.top+', "left": '+this.left+" }>"},toObject:function(t){return n(this.callSuper("toObject",t),{path:this.path.map(function(t){return t.slice()}),top:this.top,left:this.left})},toDatalessObject:function(t){var e=this.toObject(["sourcePath"].concat(t));return e.sourcePath&&delete e.path,e},toSVG:function(t){for(var e=[],r=this._createBaseSVGMarkup(),i="",n=0,o=this.path.length;n<o;n++)e.push(this.path[n].join(" "));var a=e.join(" ");return i=" translate("+-this.pathOffset.x+", "+-this.pathOffset.y+") ",r.push("<path ",this.getSvgId(),'d="',a,'" style="',this.getSvgStyles(),'" transform="',this.getSvgTransform(),i,this.getSvgTransformMatrix(),'" stroke-linecap="round" ',"/>\n"),t?t(r.join("")):r.join("")},complexity:function(){return this.path.length},_parsePath:function(){for(var t=[],e=[],r,i,n=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:e[-+]?\d+)?)/gi,o,a,l=0,h,u=this.path.length;l<u;l++){for(r=this.path[l],a=r.slice(1).trim(),e.length=0;o=n.exec(a);)e.push(o[0]);h=[r.charAt(0)];for(var f=0,d=e.length;f<d;f++)i=parseFloat(e[f]),isNaN(i)||h.push(i);var p=h[0],g=s[p.toLowerCase()],v=c[p]||p;if(h.length-1>g)for(var m=1,b=h.length;m<b;m+=g)t.push([p].concat(h.slice(m,m+g))),p=v;else t.push(h)}return t},_parseDimensions:function(){for(var t=[],n=[],o,a=null,s=0,c=0,l=0,h=0,u=0,f=0,d,p,g,v=0,m=this.path.length;v<m;++v){switch(o=this.path[v],o[0]){case"l":l+=o[1],h+=o[2],g=[];break;case"L":l=o[1],h=o[2],g=[];break;case"h":l+=o[1],g=[];break;case"H":l=o[1],g=[];break;case"v":h+=o[1],g=[];break;case"V":h=o[1],g=[];break;case"m":l+=o[1],h+=o[2],s=l,c=h,g=[];break;case"M":l=o[1],h=o[2],s=l,c=h,g=[];break;case"c":d=l+o[5],p=h+o[6],u=l+o[3],f=h+o[4],g=e.util.getBoundsOfCurve(l,h,l+o[1],h+o[2],u,f,d,p),l=d,h=p;break;case"C":u=o[3],f=o[4],g=e.util.getBoundsOfCurve(l,h,o[1],o[2],u,f,o[5],o[6]),l=o[5],h=o[6];break;case"s":d=l+o[3],p=h+o[4],null===a[0].match(/[CcSs]/)?(u=l,f=h):(u=2*l-u,f=2*h-f),g=e.util.getBoundsOfCurve(l,h,u,f,l+o[1],h+o[2],d,p),u=l+o[1],f=h+o[2],l=d,h=p;break;case"S":d=o[3],p=o[4],null===a[0].match(/[CcSs]/)?(u=l,f=h):(u=2*l-u,f=2*h-f),g=e.util.getBoundsOfCurve(l,h,u,f,o[1],o[2],d,p),l=d,h=p,u=o[1],f=o[2];break;case"q":d=l+o[3],p=h+o[4],u=l+o[1],f=h+o[2],g=e.util.getBoundsOfCurve(l,h,u,f,u,f,d,p),l=d,h=p;break;case"Q":u=o[1],f=o[2],g=e.util.getBoundsOfCurve(l,h,u,f,u,f,o[3],o[4]),l=o[3],h=o[4];break;case"t":d=l+o[1],p=h+o[2],null===a[0].match(/[QqTt]/)?(u=l,f=h):(u=2*l-u,f=2*h-f),g=e.util.getBoundsOfCurve(l,h,u,f,u,f,d,p),l=d,h=p;break;case"T":d=o[1],p=o[2],null===a[0].match(/[QqTt]/)?(u=l,f=h):(u=2*l-u,f=2*h-f),g=e.util.getBoundsOfCurve(l,h,u,f,u,f,d,p),l=d,h=p;break;case"a":g=e.util.getBoundsOfArc(l,h,o[1],o[2],o[3],o[4],o[5],o[6]+l,o[7]+h),l+=o[6],h+=o[7];break;case"A":g=e.util.getBoundsOfArc(l,h,o[1],o[2],o[3],o[4],o[5],o[6],o[7]),l=o[6],h=o[7];break;case"z":case"Z":l=s,h=c}a=o,g.forEach(function(e){t.push(e.x),n.push(e.y)}),t.push(l),n.push(h)}var b=r(t)||0,y=r(n)||0;return{left:b,top:y,width:(i(t)||0)-b,height:(i(n)||0)-y}}}),e.Path.fromObject=function(t,r){if("string"==typeof t.sourcePath){var i=t.sourcePath;e.loadSVGFromURL(i,function(e){var i=e[0];i.setOptions(t),r&&r(i)})}else e.Object._fromObject("Path",t,r,"path")},e.Path.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat(["d"]),e.Path.fromElement=function(t,r,i){var o=e.parseAttributes(t,e.Path.ATTRIBUTE_NAMES);o.originX="left",o.originY="top",r(new e.Path(o.d,n(o,i)))}}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.util.object.extend,i=e.util.array.min,n=e.util.array.max;e.Group||(e.Group=e.util.createClass(e.Object,e.Collection,{type:"group",strokeWidth:0,subTargetCheck:!1,cacheProperties:[],useSetOnGroup:!1,initialize:function(t,e,r){e=e||{},this._objects=[],r&&this.callSuper("initialize",e),this._objects=t||[];for(var i=this._objects.length;i--;)this._objects[i].group=this;if(e.originX&&(this.originX=e.originX),e.originY&&(this.originY=e.originY),!r){var n=e&&e.centerPoint;n||this._calcBounds(),this._updateObjectsCoords(n),delete e.centerPont,this.callSuper("initialize",e)}this.setCoords()},_updateObjectsCoords:function(t){for(var t=t||this.getCenterPoint(),e=this._objects.length;e--;)this._updateObjectCoords(this._objects[e],t)},_updateObjectCoords:function(t,e){var r=t.left,i=t.top,n=!0,o=!0;t.set({left:r-e.x,top:i-e.y}),t.group=this,t.setCoords(!0,!0)},toString:function(){return"#<fabric.Group: ("+this.complexity()+")>"},addWithUpdate:function(t){return this._restoreObjectsState(),e.util.resetObjectTransform(this),t&&(this._objects.push(t),t.group=this,t._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},removeWithUpdate:function(t){return this._restoreObjectsState(),e.util.resetObjectTransform(this),this.remove(t),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(t){this.dirty=!0,t.group=this},_onObjectRemoved:function(t){this.dirty=!0,delete t.group},_set:function(t,e){var r=this._objects.length;if(this.useSetOnGroup)for(;r--;)this._objects[r].setOnGroup(t,e);this.callSuper("_set",t,e)},toObject:function(t){var e=this.getObjects().map(function(e){var r=e.includeDefaultValues;e.includeDefaultValues=e.group.includeDefaultValues;var i=e.toObject(t);return e.includeDefaultValues=r,i});return r(this.callSuper("toObject",t),{objects:e})},toDatalessObject:function(t){var e,i=this.sourcePath;return e=i||this.getObjects().map(function(e){var r=e.includeDefaultValues;e.includeDefaultValues=e.group.includeDefaultValues;var i=e.toDatalessObject(t);return e.includeDefaultValues=r,i}),r(this.callSuper("toDatalessObject",t),{objects:e})},render:function(t){this._transformDone=!0,this.callSuper("render",t),this._transformDone=!1},shouldCache:function(){var t=this.objectCaching&&(!this.group||this.needsItsOwnCache()||!this.group.isOnACache());if(this.ownCaching=t,t)for(var e=0,r=this._objects.length;e<r;e++)if(this._objects[e].willDrawShadow())return this.ownCaching=!1,!1;return t},willDrawShadow:function(){if(this.shadow)return this.callSuper("willDrawShadow");for(var t=0,e=this._objects.length;t<e;t++)if(this._objects[t].willDrawShadow())return!0;return!1},isOnACache:function(){return this.ownCaching||this.group&&this.group.isOnACache()},drawObject:function(t){for(var e=0,r=this._objects.length;e<r;e++)this._objects[e].render(t)},isCacheDirty:function(){if(this.callSuper("isCacheDirty"))return!0;if(!this.statefullCache)return!1;for(var t=0,e=this._objects.length;t<e;t++)if(this._objects[t].isCacheDirty(!0)){if(this._cacheCanvas){var r=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-r/2,-i/2,r,i)}return!0}return!1},_restoreObjectsState:function(){return this._objects.forEach(this._restoreObjectState,this),this},realizeTransform:function(t){var r=t.calcTransformMatrix(),i=e.util.qrDecompose(r),n=new e.Point(i.translateX,i.translateY);return t.flipX=!1,t.flipY=!1,t.set("scaleX",i.scaleX),t.set("scaleY",i.scaleY),t.skewX=i.skewX,t.skewY=i.skewY,t.angle=i.angle,t.setPositionByOrigin(n,"center","center"),t},_restoreObjectState:function(t){return this.realizeTransform(t),t.setCoords(),delete t.group,this},destroy:function(){return this._restoreObjectsState()},toActiveSelection:function(){if(this.canvas){var t=this._objects,r=this.canvas;this._objects=[];var i=this.toObject(),n=new e.ActiveSelection([]);return n.set(i),n.type="activeSelection",r.remove(this),t.forEach(function(t){t.group=n,t.dirty=!0,r.add(t)}),n._objects=t,r._activeObject=n,n.setCoords(),n}},ungroupOnCanvas:function(){return this._restoreObjectsState()},setObjectsCoords:function(){var t=!0,e=!0;return this.forEachObject(function(t){t.setCoords(!0,!0)}),this},_calcBounds:function(t){for(var e=[],r=[],i,n,o=["tr","br","bl","tl"],a=0,s=this._objects.length,c,l=o.length,h=!0;a<s;++a)for(i=this._objects[a],i.setCoords(!0),c=0;c<l;c++)n=o[c],e.push(i.oCoords[n].x),r.push(i.oCoords[n].y);this.set(this._getBounds(e,r,t))},_getBounds:function(t,r,o){var a=new e.Point(i(t),i(r)),s=new e.Point(n(t),n(r)),c={width:s.x-a.x||0,height:s.y-a.y||0};return o||(c.left=a.x||0,c.top=a.y||0,"center"===this.originX&&(c.left+=c.width/2),"right"===this.originX&&(c.left+=c.width),"center"===this.originY&&(c.top+=c.height/2),"bottom"===this.originY&&(c.top+=c.height)),c},toSVG:function(t){var e=this._createBaseSVGMarkup();e.push("<g ",this.getSvgId(),'transform="',this.getSvgTransform(),this.getSvgTransformMatrix(),'" style="',this.getSvgFilter(),'">\n');for(var r=0,i=this._objects.length;r<i;r++)e.push("\t",this._objects[r].toSVG(t));return e.push("</g>\n"),t?t(e.join("")):e.join("")}}),e.Group.fromObject=function(t,r){e.util.enlivenObjects(t.objects,function(i){var n=e.util.object.clone(t,!0);delete n.objects,r&&r(new e.Group(i,n,!0))})})}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={});e.ActiveSelection||(e.ActiveSelection=e.util.createClass(e.Group,{type:"activeSelection",initialize:function(t,r){r=r||{},this._objects=t||[];for(var i=this._objects.length;i--;)this._objects[i].group=this;r.originX&&(this.originX=r.originX),r.originY&&(this.originY=r.originY),this._calcBounds(),this._updateObjectsCoords(),e.Object.prototype.initialize.call(this,r),this.setCoords()},toGroup:function(){var t=this._objects;this._objects=[];var r=this.toObject(),i=new e.Group([]);if(i.set(r),i.type="group",t.forEach(function(t){t.group=i,t.canvas.remove(t)}),i._objects=t,!this.canvas)return i;var n=this.canvas;return n._activeObject=i,n.add(i),i.setCoords(),i},onDeselect:function(){return this.destroy(),!1},toString:function(){return"#<fabric.ActiveSelection: ("+this.complexity()+")>"},_set:function(t,r){var i=this._objects.length;if("canvas"===t)for(;i--;)this._objects[i].set(t,r);if(this.useSetOnGroup)for(;i--;)this._objects[i].setOnGroup(t,r);e.Object.prototype._set.call(this,t,r)},shouldCache:function(){return!1},willDrawShadow:function(){if(this.shadow)return this.callSuper("willDrawShadow");for(var t=0,e=this._objects.length;t<e;t++)if(this._objects[t].willDrawShadow())return!0;return!1},isOnACache:function(){return!1},_renderControls:function(t,e,r){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",t,e),r=r||{},void 0===r.hasControls&&(r.hasControls=!1),void 0===r.hasRotatingPoint&&(r.hasRotatingPoint=!1),r.forActiveSelection=!0;for(var i=0,n=this._objects.length;i<n;i++)this._objects[i]._renderControls(t,r);t.restore()}}),e.ActiveSelection.fromObject=function(t,r){e.util.enlivenObjects(t.objects,function(i){delete t.objects,r&&r(new e.ActiveSelection(i,t,!0))})})}(exports),function(t){"use strict";var e=fabric.util.object.extend;if(t.fabric||(t.fabric={}),t.fabric.Image)return void fabric.warn("fabric.Image is already defined.");var r=fabric.Object.prototype.stateProperties.concat();r.push("cropX","cropY"),fabric.Image=fabric.util.createClass(fabric.Object,{type:"image",crossOrigin:"",strokeWidth:0,_lastScaleX:1,_lastScaleY:1,_filterScalingX:1,_filterScalingY:1,minimumScaleTrigger:.5,stateProperties:r,objectCaching:!1,cacheKey:"",cropX:0,cropY:0,initialize:function(t,e){e||(e={}),this.filters=[],this.callSuper("initialize",e),this._initElement(t,e),this.cacheKey="texture"+fabric.Object.__uid++},getElement:function(){return this._element},setElement:function(t,e){return this._element=t,this._originalElement=t,this._initConfig(e),this.resizeFilter&&this.applyResizeFilters(),0!==this.filters.length&&this.applyFilters(),this},setCrossOrigin:function(t){return this.crossOrigin=t,this._element.crossOrigin=t,this},getOriginalSize:function(){var t=this.getElement();return{width:t.width,height:t.height}},_stroke:function(t){if(this.stroke&&0!==this.strokeWidth){var e=this.width/2,r=this.height/2;t.beginPath(),t.moveTo(-e,-r),t.lineTo(e,-r),t.lineTo(e,r),t.lineTo(-e,r),t.lineTo(-e,-r),t.closePath()}},_renderDashedStroke:function(t){var e=-this.width/2,r=-this.height/2,i=this.width,n=this.height;t.save(),this._setStrokeStyles(t,this),t.beginPath(),fabric.util.drawDashedLine(t,e,r,e+i,r,this.strokeDashArray),fabric.util.drawDashedLine(t,e+i,r,e+i,r+n,this.strokeDashArray),fabric.util.drawDashedLine(t,e+i,r+n,e,r+n,this.strokeDashArray),fabric.util.drawDashedLine(t,e,r+n,e,r,this.strokeDashArray),t.closePath(),t.restore()},toObject:function(t){var r=[];this.filters.forEach(function(t){t&&r.push(t.toObject())});var i=e(this.callSuper("toObject",["crossOrigin","cropX","cropY"].concat(t)),{src:this.getSrc(),filters:r});return this.resizeFilter&&(i.resizeFilter=this.resizeFilter.toObject()),i.width/=this._filterScalingX,i.height/=this._filterScalingY,i},toSVG:function(t){var e=this._createBaseSVGMarkup(),r=-this.width/2,i=-this.height/2,n=!0;if(e.push('<g transform="',this.getSvgTransform(),this.getSvgTransformMatrix(),'">\n',"\t<image ",this.getSvgId(),'xlink:href="',this.getSvgSrc(!0),'" x="',r,'" y="',i,'" style="',this.getSvgStyles(),'" width="',this.width,'" height="',this.height,'"></image>\n'),this.stroke||this.strokeDashArray){var o=this.fill;this.fill=null,e.push("<rect ",'x="',r,'" y="',i,'" width="',this.width,'" height="',this.height,'" style="',this.getSvgStyles(),'"/>\n'),this.fill=o}return e.push("</g>\n"),t?t(e.join("")):e.join("")},getSrc:function(t){var e=t?this._element:this._originalElement;return e?fabric.isLikelyNode?e._src:e.src:this.src||""},setSrc:function(t,e,r){return fabric.util.loadImage(t,function(t){this.setElement(t,r),e(this)},this,r&&r.crossOrigin),this},toString:function(){return'#<fabric.Image: { src: "'+this.getSrc()+'" }>'},applyResizeFilters:function(){var t=this.resizeFilter,e=this.canvas?this.canvas.getRetinaScaling():1,r=this.minimumScaleTrigger,i=this.scaleX<r?this.scaleX:1,n=this.scaleY<r?this.scaleY:1;if(i*e<1&&(i*=e),n*e<1&&(n*=e),!t||i>=1&&n>=1)return void(this._element=this._filteredEl);fabric.filterBackend||(fabric.filterBackend=fabric.initFilterBackend());var o=this._filteredEl||this._originalElement,a;if(this._element===this._originalElement){var s=fabric.util.createCanvasElement();s.width=o.width,s.height=o.height,this._element=s}var c=this._element.getContext("2d");o.getContext?a=o.getContext("2d").getImageData(0,0,o.width,o.height):(c.drawImage(o,0,0),a=c.getImageData(0,0,o.width,o.height));var l={imageData:a,scaleX:i,scaleY:n};t.applyTo2d(l),this.width=this._element.width=l.imageData.width,this.height=this._element.height=l.imageData.height,c.putImageData(l.imageData,0,0)},applyFilters:function(t){if(t=t||this.filters||[],t=t.filter(function(t){return t}),0===t.length)return this._element=this._originalElement,this._filterScalingX=1,this._filterScalingY=1,this;var e=this._originalElement,r=e.naturalWidth||e.width,i=e.naturalHeight||e.height;if(this._element===this._originalElement){var n=fabric.util.createCanvasElement();n.width=e.width,n.height=e.height,this._element=n}else this._element.getContext("2d").clearRect(0,0,r,i);return fabric.filterBackend||(fabric.filterBackend=fabric.initFilterBackend()),fabric.filterBackend.applyFilters(t,this._originalElement,r,i,this._element,this.cacheKey),this.width===this._element.width&&this.height===this._element.height||(this._filterScalingX=this._element.width/this.width,this._filterScalingY=this._element.height/this.height,this.width=this._element.width,this.height=this._element.height),this},_render:function(t){var e=-this.width/2,r=-this.height/2,i;!1===this.isMoving&&this.resizeFilter&&this._needsResize()&&(this._lastScaleX=this.scaleX,this._lastScaleY=this.scaleY,this.applyResizeFilters()),i=this._element,i&&t.drawImage(i,this.cropX,this.cropY,this.width,this.height,e,r,this.width,this.height),this._stroke(t),this._renderStroke(t)},_needsResize:function(){return this.scaleX!==this._lastScaleX||this.scaleY!==this._lastScaleY},_resetWidthHeight:function(){var t=this.getElement();this.set("width",t.width),this.set("height",t.height)},_initElement:function(t,e){this.setElement(fabric.util.getById(t),e),fabric.util.addClass(this.getElement(),fabric.Image.CSS_CANVAS)},_initConfig:function(t){t||(t={}),this.setOptions(t),this._setWidthHeight(t),this._element&&this.crossOrigin&&(this._element.crossOrigin=this.crossOrigin)},_initFilters:function(t,e){t&&t.length?fabric.util.enlivenObjects(t,function(t){e&&e(t)},"fabric.Image.filters"):e&&e()},_setWidthHeight:function(t){this.width="width"in t?t.width:this.getElement()?this.getElement().width||0:0,this.height="height"in t?t.height:this.getElement()?this.getElement().height||0:0},parsePreserveAspectRatioAttribute:function(){if(this.preserveAspectRatio){var t=fabric.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio),e=this._element.width,r=this._element.height,i,n=this.width,o=this.height,a={width:n,height:o};!t||"none"===t.alignX&&"none"===t.alignY?(this.scaleX=n/e,this.scaleY=o/r):("meet"===t.meetOrSlice&&(this.width=e,this.height=r,this.scaleX=this.scaleY=i=fabric.util.findScaleToFit(this._element,a),"Mid"===t.alignX&&(this.left+=(n-e*i)/2),"Max"===t.alignX&&(this.left+=n-e*i),"Mid"===t.alignY&&(this.top+=(o-r*i)/2),"Max"===t.alignY&&(this.top+=o-r*i)),"slice"===t.meetOrSlice&&(this.scaleX=this.scaleY=i=fabric.util.findScaleToCover(this._element,a),this.width=n/i,this.height=o/i,"Mid"===t.alignX&&(this.cropX=(e-this.width)/2),"Max"===t.alignX&&(this.cropX=e-this.width),"Mid"===t.alignY&&(this.cropY=(r-this.height)/2),"Max"===t.alignY&&(this.cropY=r-this.height)))}}}),fabric.Image.CSS_CANVAS="canvas-img",fabric.Image.prototype.getSvgSrc=fabric.Image.prototype.getSrc,fabric.Image.fromObject=function(t,e){fabric.util.loadImage(t.src,function(r,i){if(i)return void(e&&e(null,i));fabric.Image.prototype._initFilters.call(t,t.filters,function(i){t.filters=i||[],fabric.Image.prototype._initFilters.call(t,[t.resizeFilter],function(i){t.resizeFilter=i[0];var n=new fabric.Image(r,t);e(n)})})},null,t.crossOrigin)},fabric.Image.fromURL=function(t,e,r){fabric.util.loadImage(t,function(t){e&&e(new fabric.Image(t,r))},null,r&&r.crossOrigin)},fabric.Image.ATTRIBUTE_NAMES=fabric.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin".split(" ")),fabric.Image.fromElement=function(t,r,i){var n=fabric.parseAttributes(t,fabric.Image.ATTRIBUTE_NAMES);fabric.Image.fromURL(n["xlink:href"],r,e(i?fabric.util.object.clone(i):{},n))}}(exports),fabric.util.object.extend(fabric.Object.prototype,{_getAngleValueForStraighten:function(){var t=this.angle%360;return t>0?90*Math.round((t-1)/90):90*Math.round(t/90)},straighten:function(){return this.setAngle(this._getAngleValueForStraighten()),this},fxStraighten:function(t){t=t||{};var e=function(){},r=t.onComplete||e,i=t.onChange||e,n=this;return fabric.util.animate({startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(t){n.setAngle(t),i()},onComplete:function(){n.setCoords(),r()},onStart:function(){n.set("active",!1)}}),this}}),fabric.util.object.extend(fabric.StaticCanvas.prototype,{straightenObject:function(t){return t.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(t){return t.fxStraighten({onChange:this.requestRenderAllBound}),this}}),function(){"use strict";function t(t){t&&t.tileSize&&(this.tileSize=t.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}fabric.isWebglSupported=function(t){if(fabric.isLikelyNode)return!1;t=t||fabric.WebglFilterBackend.prototype.tileSize;var e=document.createElement("canvas"),r=e.getContext("webgl")||e.getContext("experimental-webgl"),i=!1;return r&&(fabric.maxTextureSize=r.getParameter(r.MAX_TEXTURE_SIZE),i=fabric.maxTextureSize>=t),this.isSupported=i,i},fabric.WebglFilterBackend=t,t.prototype={tileSize:2048,resources:{},setupGLContext:function(t,e){this.dispose(),this.createWebGLCanvas(t,e),this.squareVertices=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(t,e)},chooseFastestCopyGLTo2DMethod:function(t,e){var r=void 0!==window.performance,i;try{new ImageData(1,1),i=!0}catch(t){i=!1}var n="undefined"!=typeof ArrayBuffer,o="undefined"!=typeof Uint8ClampedArray;if(r&&i&&n&&o){var a=fabric.util.createCanvasElement(),s=new ArrayBuffer(t*e*4),c={imageBuffer:s},l,h,u;a.width=t,a.height=e,l=window.performance.now(),copyGLTo2DDrawImage.call(c,this.gl,a),h=window.performance.now()-l,l=window.performance.now(),copyGLTo2DPutImageData.call(c,this.gl,a),u=window.performance.now()-l,h>u?(this.imageBuffer=s,this.copyGLTo2D=copyGLTo2DPutImageData):this.copyGLTo2D=copyGLTo2DDrawImage}},createWebGLCanvas:function(t,e){var r=fabric.util.createCanvasElement();r.width=t,r.height=e;var i={premultipliedAlpha:!1},n=r.getContext("webgl",i);n||(n=r.getContext("experimental-webgl",i)),n&&(n.clearColor(0,0,0,0),this.canvas=r,this.gl=n)},applyFilters:function(t,e,r,i,n,o){var a=this.gl,s;o&&(s=this.getCachedTexture(o,e));var c={originalWidth:e.width||e.originalWidth,originalHeight:e.height||e.originalHeight,sourceWidth:r,sourceHeight:i,context:a,sourceTexture:this.createTexture(a,r,i,!s&&e),targetTexture:this.createTexture(a,r,i),originalTexture:s||this.createTexture(a,r,i,!s&&e),passes:t.length,webgl:!0,squareVertices:this.squareVertices,programCache:this.programCache,pass:0,filterBackend:this},l=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,l),t.forEach(function(t){t&&t.applyTo(c)}),this.copyGLTo2D(a,n),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(c.sourceTexture),a.deleteTexture(c.targetTexture),a.deleteFramebuffer(l),n.getContext("2d").setTransform(1,0,0,1,0,0),c},applyFiltersDebug:function(t,e,r,i,n,o){var a=this.gl,s=this.applyFilters(t,e,r,i,n,o),c=a.getError();if(c!==a.NO_ERROR){var l=this.glErrorToString(a,c),h=new Error("WebGL Error "+l);throw h.glErrorCode=c,h}return s},glErrorToString:function(t,e){if(!t)return"Context undefined for error code: "+e;if("number"!=typeof e)return"Error code is not a number";switch(e){case t.NO_ERROR:return"NO_ERROR";case t.INVALID_ENUM:return"INVALID_ENUM";case t.INVALID_VALUE:return"INVALID_VALUE";case t.INVALID_OPERATION:return"INVALID_OPERATION";case t.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case t.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case t.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return"UNKNOWN_ERROR"}},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(t,e,r,i){var n=t.createTexture();return t.bindTexture(t.TEXTURE_2D,n),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),i?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,i):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,r,0,t.RGBA,t.UNSIGNED_BYTE,null),n},getCachedTexture:function(t,e){if(this.textureCache[t])return this.textureCache[t];var r=this.createTexture(this.gl,e.width,e.height,e);return this.textureCache[t]=r,r},evictCachesForKey:function(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])},copyGLTo2D:copyGLTo2DDrawImage,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var t=this.gl,e=t.getExtension("WEBGL_debug_renderer_info"),r={renderer:"",vendor:""};if(e){var i=t.getParameter(e.UNMASKED_RENDERER_WEBGL),n=t.getParameter(e.UNMASKED_VENDOR_WEBGL);i&&(r.renderer=i.toLowerCase()),n&&(r.vendor=n.toLowerCase())}return this.gpuInfo=r,r}}}(),function(){"use strict";function t(){}var e=function(){};fabric.Canvas2dFilterBackend=t,t.prototype={evictCachesForKey:e,dispose:e,clearWebGLCaches:e,resources:{},applyFilters:function(t,e,r,i,n){var o=n.getContext("2d");o.drawImage(e,0,0,r,i);var a=o.getImageData(0,0,r,i),s=o.getImageData(0,0,r,i),c={sourceWidth:r,sourceHeight:i,imageData:a,originalEl:e,originalImageData:s,canvasEl:n,ctx:o,filterBackend:this};return t.forEach(function(t){t.applyTo(c)}),c.imageData.width===r&&c.imageData.height===i||(n.width=c.imageData.width,n.height=c.imageData.height),o.putImageData(c.imageData,0,0),c}}}(),fabric.Image.filters=fabric.Image.filters||{},fabric.Image.filters.BaseFilter=fabric.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nattribute vec2 aTexCoord;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aTexCoord;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2d uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(t){t&&this.setOptions(t)},setOptions:function(t){for(var e in t)this[e]=t[e]},createProgram:function(t,e,r){if(this.vertexSource&&this.fragmentSource){var i=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(i,r||this.vertexSource),t.compileShader(i),!t.getShaderParameter(i,t.COMPILE_STATUS))throw new Error('Vertex shader compile error for "${this.type}": '+t.getShaderInfoLog(i));var n=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(n,e||this.fragmentSource),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Error('Fragment shader compile error for "${this.type}": '+t.getShaderInfoLog(n));var o=t.createProgram();if(t.attachShader(o,i),t.attachShader(o,n),t.linkProgram(o),!t.getProgramParameter(o,t.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+t.getProgramInfoLog(o));var a=this.getAttributeLocations(t,o),s=this.getUniformLocations(t,o)||{};return s.uStepW=t.getUniformLocation(o,"uStepW"),s.uStepH=t.getUniformLocation(o,"uStepH"),{program:o,attributeLocations:a,uniformLocations:s}}},getAttributeLocations:function(t,e){return{aPosition:t.getAttribLocation(e,"aPosition"),aTexCoord:t.getAttribLocation(e,"aTexCoord")}},getUniformLocations:function(){},sendAttributeData:function(t,e,r){["aPosition","aTexCoord"].forEach(function(i){var n=e[i],o=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,o),t.enableVertexAttribArray(n),t.vertexAttribPointer(n,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,r,t.STATIC_DRAW)})},_setupFrameBuffer:function(t){var e=t.context;t.passes>1?e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t.targetTexture,0):(e.bindFramebuffer(e.FRAMEBUFFER,null),e.finish())},_swapTextures:function(t){t.passes--,t.pass++;var e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e},isNeutralState:function(){return!1},applyTo:function(t){if(t.webgl){if(t.passes>1&&this.isNeutralState(t))return;this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)}else this.applyTo2d(t)},retrieveShader:function(t){return t.programCache.hasOwnProperty(this.type)||(t.programCache[this.type]=this.createProgram(t.context)),t.programCache[this.type]},applyToWebGL:function(t){var e=t.context,r=this.retrieveShader(t);0===t.pass&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(r.program),this.sendAttributeData(e,r.attributeLocations,t.squareVertices),e.uniform1f(r.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(r.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,r.uniformLocations),e.viewport(0,0,t.sourceWidth,t.sourceHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(t,e,r){t.activeTexture(r),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)},unbindAdditionalTexture:function(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(t){this[this.mainParameter]=t},sendUniformData:function(){},createHelpLayer:function(t){if(!t.helpLayer){var e=document.createElement("canvas");e.width=t.sourceWidth,e.height=t.sourceHeight,t.helpLayer=e}},toObject:function(){var t={type:this.type},e=this.mainParameter;return e&&(t[e]=this[e]),t},toJSON:function(){return this.toObject()}}),fabric.Image.filters.BaseFilter.fromObject=function(t,e){var r=new fabric.Image.filters[t.type](t);return e&&e(r),r},function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.Image.filters,i=e.util.createClass;r.ColorMatrix=i(r.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(t){this.callSuper("initialize",t),this.matrix=this.matrix.slice(0)},applyTo2d:function(t){var e=t.imageData,r=e.data,i=r.length,n=this.matrix,o,a,s,c,l,h=this.colorsOnly;for(l=0;l<i;l+=4)o=r[l],a=r[l+1],s=r[l+2],h?(r[l]=o*n[0]+a*n[1]+s*n[2]+255*n[4],r[l+1]=o*n[5]+a*n[6]+s*n[7]+255*n[9],r[l+2]=o*n[10]+a*n[11]+s*n[12]+255*n[14]):(c=r[l+3],r[l]=o*n[0]+a*n[1]+s*n[2]+c*n[3]+255*n[4],r[l+1]=o*n[5]+a*n[6]+s*n[7]+c*n[8]+255*n[9],r[l+2]=o*n[10]+a*n[11]+s*n[12]+c*n[13]+255*n[14],r[l+3]=o*n[15]+a*n[16]+s*n[17]+c*n[18]+255*n[19])},getUniformLocations:function(t,e){return{uColorMatrix:t.getUniformLocation(e,"uColorMatrix"),uConstants:t.getUniformLocation(e,"uConstants")}},sendUniformData:function(t,e){var r=this.matrix,i=[r[0],r[1],r[2],r[3],r[5],r[6],r[7],r[8],r[10],r[11],r[12],r[13],r[15],r[16],r[17],r[18]],n=[r[4],r[9],r[14],r[19]];t.uniformMatrix4fv(e.uColorMatrix,!1,i),t.uniform4fv(e.uConstants,n)}}),e.Image.filters.ColorMatrix.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.Image.filters,i=e.util.createClass;r.Brightness=i(r.BaseFilter,{type:"Brightness",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uBrightness;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor.rgb += uBrightness;\ngl_FragColor = color;\n}",brightness:0,mainParameter:"brightness",applyTo2d:function(t){if(0!==this.brightness){var e=t.imageData,r=e.data,i,n=r.length,o=Math.round(255*this.brightness);for(i=0;i<n;i+=4)r[i]=r[i]+o,r[i+1]=r[i+1]+o,r[i+2]=r[i+2]+o}},getUniformLocations:function(t,e){return{uBrightness:t.getUniformLocation(e,"uBrightness")}},sendUniformData:function(t,e){t.uniform1f(e.uBrightness,this.brightness)}}),e.Image.filters.Brightness.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.util.object.extend,i=e.Image.filters,n=e.util.createClass;i.Convolute=n(i.BaseFilter,{type:"Convolute",opaque:!1,matrix:[0,0,0,0,1,0,0,0,0],fragmentSource:{Convolute_3_1:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[9];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 0);\nfor (float h = 0.0; h < 3.0; h+=1.0) {\nfor (float w = 0.0; w < 3.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 1), uStepH * (h - 1));\ncolor += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 3.0 + w)];\n}\n}\ngl_FragColor = color;\n}",Convolute_3_0:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[9];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 1);\nfor (float h = 0.0; h < 3.0; h+=1.0) {\nfor (float w = 0.0; w < 3.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 1.0), uStepH * (h - 1.0));\ncolor.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 3.0 + w)];\n}\n}\nfloat alpha = texture2D(uTexture, vTexCoord).a;\ngl_FragColor = color;\ngl_FragColor.a = alpha;\n}",Convolute_5_1:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[25];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 0);\nfor (float h = 0.0; h < 5.0; h+=1.0) {\nfor (float w = 0.0; w < 5.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));\ncolor += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 5.0 + w)];\n}\n}\ngl_FragColor = color;\n}",Convolute_5_0:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[25];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 1);\nfor (float h = 0.0; h < 5.0; h+=1.0) {\nfor (float w = 0.0; w < 5.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));\ncolor.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 5.0 + w)];\n}\n}\nfloat alpha = texture2D(uTexture, vTexCoord).a;\ngl_FragColor = color;\ngl_FragColor.a = alpha;\n}",Convolute_7_1:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[49];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 0);\nfor (float h = 0.0; h < 7.0; h+=1.0) {\nfor (float w = 0.0; w < 7.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));\ncolor += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 7.0 + w)];\n}\n}\ngl_FragColor = color;\n}",Convolute_7_0:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[49];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 1);\nfor (float h = 0.0; h < 7.0; h+=1.0) {\nfor (float w = 0.0; w < 7.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));\ncolor.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 7.0 + w)];\n}\n}\nfloat alpha = texture2D(uTexture, vTexCoord).a;\ngl_FragColor = color;\ngl_FragColor.a = alpha;\n}",Convolute_9_1:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[81];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 0);\nfor (float h = 0.0; h < 9.0; h+=1.0) {\nfor (float w = 0.0; w < 9.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));\ncolor += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 9.0 + w)];\n}\n}\ngl_FragColor = color;\n}",Convolute_9_0:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[81];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 1);\nfor (float h = 0.0; h < 9.0; h+=1.0) {\nfor (float w = 0.0; w < 9.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));\ncolor.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 9.0 + w)];\n}\n}\nfloat alpha = texture2D(uTexture, vTexCoord).a;\ngl_FragColor = color;\ngl_FragColor.a = alpha;\n}"},retrieveShader:function(t){var e=Math.sqrt(this.matrix.length),r=this.type+"_"+e+"_"+this.opaque?1:0,i=this.fragmentSource[r];return t.programCache.hasOwnProperty(r)||(t.programCache[r]=this.createProgram(t.context,i)),t.programCache[r]},applyTo2d:function(t){var e=t.imageData,r=e.data,i=this.matrix,n=Math.round(Math.sqrt(i.length)),o=Math.floor(n/2),a=e.width,s=e.height,c=t.ctx.createImageData(a,s),l=c.data,h=this.opaque?1:0,u,f,d,p,g,v,m,b,y,_,w,S,x;for(w=0;w<s;w++)for(_=0;_<a;_++){for(g=4*(w*a+_),u=0,f=0,d=0,p=0,x=0;x<n;x++)for(S=0;S<n;S++)m=w+x-o,v=_+S-o,m<0||m>s||v<0||v>a||(b=4*(m*a+v),y=i[x*n+S],u+=r[b]*y,f+=r[b+1]*y,d+=r[b+2]*y,h||(p+=r[b+3]*y));l[g]=u,l[g+1]=f,l[g+2]=d,l[g+3]=h?r[g+3]:p}t.imageData=c},getUniformLocations:function(t,e){return{uMatrix:t.getUniformLocation(e,"uMatrix"),uOpaque:t.getUniformLocation(e,"uOpaque"),uHalfSize:t.getUniformLocation(e,"uHalfSize"),uSize:t.getUniformLocation(e,"uSize")}},sendUniformData:function(t,e){t.uniform1fv(e.uMatrix,this.matrix)},toObject:function(){return r(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),e.Image.filters.Convolute.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.Image.filters,i=e.util.createClass;r.Grayscale=i(r.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(t){var e=t.imageData,r=e.data,i,n=r.length,o,a=this.mode;for(i=0;i<n;i+=4)"average"===a?o=(r[i]+r[i+1]+r[i+2])/3:"lightness"===a?o=(Math.min(r[i],r[i+1],r[i+2])+Math.max(r[i],r[i+1],r[i+2]))/2:"luminosity"===a&&(o=.21*r[i]+.72*r[i+1]+.07*r[i+2]),r[i]=o,r[i+1]=o,r[i+2]=o},retrieveShader:function(t){var e=this.type+"_"+this.mode,r=this.fragmentSource[this.mode];return t.programCache.hasOwnProperty(e)||(t.programCache[e]=this.createProgram(t.context,r)),t.programCache[e]},getUniformLocations:function(t,e){return{uMode:t.getUniformLocation(e,"uMode")}},sendUniformData:function(t,e){var r=1;t.uniform1i(e.uMode,1)}}),e.Image.filters.Grayscale.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.Image.filters,i=e.util.createClass;r.Invert=i(r.BaseFilter,{type:"Invert",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uInvert;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nif (uInvert == 1) {\ngl_FragColor = vec4(1.0 - color.r,1.0 -color.g,1.0 -color.b,color.a);\n} else {\ngl_FragColor = color;\n}\n}",invert:!0,mainParameter:"invert",applyTo2d:function(t){if(this.invert){var e=t.imageData,r=e.data,i,n=r.length;for(i=0;i<n;i+=4)r[i]=255-r[i],r[i+1]=255-r[i+1],r[i+2]=255-r[i+2]}},getUniformLocations:function(t,e){return{uInvert:t.getUniformLocation(e,"uInvert")}},sendUniformData:function(t,e){t.uniform1i(e.uInvert,this.invert)}}),e.Image.filters.Invert.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.util.object.extend,i=e.Image.filters,n=e.util.createClass;i.Noise=n(i.BaseFilter,{type:"Noise",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uStepH;\nuniform float uNoise;\nuniform float uSeed;\nvarying vec2 vTexCoord;\nfloat rand(vec2 co, float seed, float vScale) {\nreturn fract(sin(dot(co.xy * vScale ,vec2(12.9898 , 78.233))) * 43758.5453 * (seed + 0.01) / 2.0);\n}\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor.rgb += (0.5 - rand(vTexCoord, uSeed, 0.1 / uStepH)) * uNoise;\ngl_FragColor = color;\n}",mainParameter:"noise",noise:0,applyTo2d:function(t){if(0!==this.noise)for(var e=t.imageData,r=e.data,i,n=r.length,o=this.noise,a,i=0,n=r.length;i<n;i+=4)a=(.5-Math.random())*o,r[i]+=a,r[i+1]+=a,r[i+2]+=a},getUniformLocations:function(t,e){return{uNoise:t.getUniformLocation(e,"uNoise"),uSeed:t.getUniformLocation(e,"uSeed")}},sendUniformData:function(t,e){t.uniform1f(e.uNoise,this.noise/255),t.uniform1f(e.uSeed,Math.random())},toObject:function(){return r(this.callSuper("toObject"),{noise:this.noise})}}),e.Image.filters.Noise.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.Image.filters,i=e.util.createClass;r.Pixelate=i(r.BaseFilter,{type:"Pixelate",blocksize:4,mainParameter:"blocksize",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uBlocksize;\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nfloat blockW = uBlocksize * uStepW;\nfloat blockH = uBlocksize * uStepW;\nint posX = int(vTexCoord.x / blockW);\nint posY = int(vTexCoord.y / blockH);\nfloat fposX = float(posX);\nfloat fposY = float(posY);\nvec2 squareCoords = vec2(fposX * blockW, fposY * blockH);\nvec4 color = texture2D(uTexture, squareCoords);\ngl_FragColor = color;\n}",applyTo2d:function(t){if(1!==this.blocksize){var e=t.imageData,r=e.data,i=e.height,n=e.width,o,a,s,c,l,h,u,f,d,p,g;for(a=0;a<i;a+=this.blocksize)for(s=0;s<n;s+=this.blocksize)for(o=4*a*n+4*s,c=r[o],l=r[o+1],h=r[o+2],u=r[o+3],p=Math.min(a+this.blocksize,i),g=Math.min(s+this.blocksize,n),f=a;f<p;f++)for(d=s;d<g;d++)o=4*f*n+4*d,r[o]=c,r[o+1]=l,r[o+2]=h,r[o+3]=u}},getUniformLocations:function(t,e){return{uBlocksize:t.getUniformLocation(e,"uBlocksize"),uStepW:t.getUniformLocation(e,"uStepW"),uStepH:t.getUniformLocation(e,"uStepH")}},sendUniformData:function(t,e){t.uniform1f(e.uBlocksize,this.blocksize)}}),e.Image.filters.Pixelate.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.util.object.extend,i=e.Image.filters,n=e.util.createClass;i.RemoveColor=n(i.BaseFilter,{type:"RemoveColor",color:"#FFFFFF",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uLow;\nuniform vec4 uHigh;\nvarying vec2 vTexCoord;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\nif(all(greaterThan(gl_FragColor.rgb,uLow.rgb)) && all(greaterThan(uHigh.rgb,gl_FragColor.rgb))) {\ngl_FragColor.a = 0.0;\n}\n}",distance:.02,useAlpha:!1,applyTo2d:function(t){var r=t.imageData,i=r.data,n,o=255*this.distance,a,s,c,l=new e.Color(this.color).getSource(),h=[l[0]-o,l[1]-o,l[2]-o],u=[l[0]+o,l[1]+o,l[2]+o];for(n=0;n<i.length;n+=4)a=i[n],s=i[n+1],c=i[n+2],a>h[0]&&s>h[1]&&c>h[2]&&a<u[0]&&s<u[1]&&c<u[2]&&(i[n+3]=0)},getUniformLocations:function(t,e){return{uLow:t.getUniformLocation(e,"uLow"),uHigh:t.getUniformLocation(e,"uHigh")}},sendUniformData:function(t,r){var i=new e.Color(this.color).getSource(),n=parseFloat(this.distance),o=[0+i[0]/255-n,0+i[1]/255-n,0+i[2]/255-n,1],a=[i[0]/255+n,i[1]/255+n,i[2]/255+n,1];t.uniform4fv(r.uLow,o),t.uniform4fv(r.uHigh,a)},toObject:function(){return r(this.callSuper("toObject"),{color:this.color,distance:this.distance})}}),e.Image.filters.RemoveColor.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.Image.filters,i=e.util.createClass,n={Brownie:[.5997,.34553,-.27082,0,.186,-.0377,.86095,.15059,0,-.1449,.24113,-.07441,.44972,0,-.02965,0,0,0,1,0],Vintage:[.62793,.32021,-.03965,0,.03784,.02578,.64411,.03259,0,.02926,.0466,-.08512,.52416,0,.02023,0,0,0,1,0],Kodachrome:[1.12855,-.39673,-.03992,0,.24991,-.16404,1.08352,-.05498,0,.09698,-.16786,-.56034,1.60148,0,.13972,0,0,0,1,0],Technicolor:[1.91252,-.85453,-.09155,0,.04624,-.30878,1.76589,-.10601,0,-.27589,-.2311,-.75018,1.84759,0,.12137,0,0,0,1,0],Polaroid:[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0],Sepia:[.393,.769,.189,0,0,.349,.686,.168,0,0,.272,.534,.131,0,0,0,0,0,1,0],BlackWhite:[1.5,1.5,1.5,0,-1,1.5,1.5,1.5,0,-1,1.5,1.5,1.5,0,-1,0,0,0,1,0]};for(var o in n)r[o]=i(r.ColorMatrix,{type:o,matrix:n[o],mainParameter:!1,colorsOnly:!0}),e.Image.filters[o].fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric,r=e.Image.filters,i=e.util.createClass;r.BlendColor=i(r.BaseFilter,{type:"BlendColor",color:"#F95C63",mode:"multiply",alpha:1,fragmentSource:{multiply:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor.rgb *= uColor.rgb;\ngl_FragColor = color;\n}",screen:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor.rgb = 1.0 - (1.0 - color.rgb) * (1.0 - uColor.rgb);\ngl_FragColor = color;\n}",add:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\ngl_FragColor.rgb += uColor.rgb;\n}",diff:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\ngl_FragColor.rgb = abs(gl_FragColor.rgb - uColor.rgb);\n}",subtract:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\ngl_FragColor.rgb -= uColor.rgb;\n}",lighten:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\ngl_FragColor.rgb = max(gl_FragColor.rgb, uColor.rgb);\n}",darken:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\ngl_FragColor.rgb = min(gl_FragColor.rgb, uColor.rgb);\n}",exclusion:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\ngl_FragColor.rgb += uColor.rgb - 2.0 * (uColor.rgb * gl_FragColor.rgb);\n}",overlay:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\nif (uColor.r < 0.5) {\ngl_FragColor.r *= 2.0 * uColor.r;\n} else {\ngl_FragColor.r = 1.0 - 2.0 * (1.0 - gl_FragColor.r) * (1.0 - uColor.r);\n}\nif (uColor.g < 0.5) {\ngl_FragColor.g *= 2.0 * uColor.g;\n} else {\ngl_FragColor.g = 1.0 - 2.0 * (1.0 - gl_FragColor.g) * (1.0 - uColor.g);\n}\nif (uColor.b < 0.5) {\ngl_FragColor.b *= 2.0 * uColor.b;\n} else {\ngl_FragColor.b = 1.0 - 2.0 * (1.0 - gl_FragColor.b) * (1.0 - uColor.b);\n}\n}",tint:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\ngl_FragColor.rgb *= (1.0 - uColor.a);\ngl_FragColor.rgb += uColor.rgb;\n}"},retrieveShader:function(t){var e=this.type+"_"+this.mode,r=this.fragmentSource[this.mode];return t.programCache.hasOwnProperty(e)||(t.programCache[e]=this.createProgram(t.context,r)),t.programCache[e]},applyTo2d:function(t){var r=t.imageData,i=r.data,n=i.length,o,a,s,c,l,h,u,f=1-this.alpha;u=new e.Color(this.color).getSource(),o=u[0]*this.alpha,a=u[1]*this.alpha,s=u[2]*this.alpha;for(var d=0;d<n;d+=4)switch(c=i[d],l=i[d+1],h=i[d+2],this.mode){case"multiply":i[d]=c*o/255,i[d+1]=l*a/255,i[d+2]=h*s/255;break;case"screen":i[d]=255-(255-c)*(255-o)/255,i[d+1]=255-(255-l)*(255-a)/255,i[d+2]=255-(255-h)*(255-s)/255;break;case"add":i[d]=c+o,i[d+1]=l+a,i[d+2]=h+s;break;case"diff":case"difference":i[d]=Math.abs(c-o),i[d+1]=Math.abs(l-a),i[d+2]=Math.abs(h-s);break;case"subtract":i[d]=c-o,i[d+1]=l-a,i[d+2]=h-s;break;case"darken":i[d]=Math.min(c,o),i[d+1]=Math.min(l,a),i[d+2]=Math.min(h,s);break;case"lighten":i[d]=Math.max(c,o),i[d+1]=Math.max(l,a),i[d+2]=Math.max(h,s);break;case"overlay":i[d]=o<128?2*c*o/255:255-2*(255-c)*(255-o)/255,i[d+1]=a<128?2*l*a/255:255-2*(255-l)*(255-a)/255,i[d+2]=s<128?2*h*s/255:255-2*(255-h)*(255-s)/255;break;case"exclusion":i[d]=o+c-2*o*c/255,i[d+1]=a+l-2*a*l/255,i[d+2]=s+h-2*s*h/255;break;case"tint":i[d]=o+c*f,i[d+1]=a+l*f,i[d+2]=s+h*f}},getUniformLocations:function(t,e){return{uColor:t.getUniformLocation(e,"uColor")}},sendUniformData:function(t,r){var i=new e.Color(this.color).getSource();i[0]=this.alpha*i[0]/255,i[1]=this.alpha*i[1]/255,i[2]=this.alpha*i[2]/255,i[3]=this.alpha,t.uniform4fv(r.uColor,i)},toObject:function(){return{type:this.type,color:this.color,mode:this.mode,alpha:this.alpha}}}),e.Image.filters.BlendColor.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric,r=e.Image.filters,i=e.util.createClass;r.BlendImage=i(r.BaseFilter,{type:"BlendImage",image:null,mode:"multiply",alpha:1,vertexSource:"attribute vec2 aPosition;\nattribute vec2 aTexCoord;\nvarying vec2 vTexCoord;\nvarying vec2 vTexCoord2;\nuniform mat3 uTransformMatrix;\nvoid main() {\nvTexCoord = aTexCoord;\nvTexCoord2 = (uTransformMatrix * vec3(aTexCoord, 1.0)).xy;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:{multiply:"precision highp float;\nuniform sampler2D uTexture;\nuniform sampler2D uImage;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvarying vec2 vTexCoord2;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec4 color2 = texture2D(uImage, vTexCoord2);\ncolor.rgba *= color2.rgba;\ngl_FragColor = color;\n}",mask:"precision highp float;\nuniform sampler2D uTexture;\nuniform sampler2D uImage;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvarying vec2 vTexCoord2;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec4 color2 = texture2D(uImage, vTexCoord2);\ncolor.a = color2.a;\ngl_FragColor = color;\n}"},retrieveShader:function(t){var e=this.type+"_"+this.mode,r=this.fragmentSource[this.mode];return t.programCache.hasOwnProperty(e)||(t.programCache[e]=this.createProgram(t.context,r)),t.programCache[e]},applyToWebGL:function(t){var e=t.context,r=this.createTexture(t.filterBackend,this.image);this.bindAdditionalTexture(e,r,e.TEXTURE1),this.callSuper("applyToWebGL",t),this.unbindAdditionalTexture(e,e.TEXTURE1)},createTexture:function(t,e){return t.getCachedTexture(e.cacheKey,e._element)},calculateMatrix:function(){var t=this.image,e=t._element.width,r=t._element.height;return[1/t.scaleX,0,0,0,1/t.scaleY,0,-t.left/e,-t.top/r,1]},applyTo2d:function(t){var e=t.imageData,r=t.filterBackend.resources,i=e.data,n=i.length,o=t.imageData.width,a=t.imageData.height,s,c,l,h,u,f,d,p,g,v,m=this.image,b;r.blendImage||(r.blendImage=document.createElement("canvas")),g=r.blendImage,g.width===o&&g.height===a||(g.width=o,g.height=a),v=g.getContext("2d"),v.setTransform(m.scaleX,0,0,m.scaleY,m.left,m.top),v.drawImage(m._element,0,0,o,a),b=v.getImageData(0,0,o,a).data;for(var y=0;y<n;y+=4)switch(u=i[y],f=i[y+1],d=i[y+2],p=i[y+3],s=b[y],c=b[y+1],l=b[y+2],h=b[y+3],this.mode){case"multiply":i[y]=u*s/255,i[y+1]=f*c/255,i[y+2]=d*l/255,i[y+3]=p*h/255;break;case"mask":i[y+3]=h}},getUniformLocations:function(t,e){return{uTransformMatrix:t.getUniformLocation(e,"uTransformMatrix"),uImage:t.getUniformLocation(e,"uImage")}},sendUniformData:function(t,e){var r=this.calculateMatrix();t.uniform1i(e.uImage,1),t.uniformMatrix3fv(e.uTransformMatrix,!1,r)},toObject:function(){return{type:this.type,image:this.image&&this.image.toObject(),mode:this.mode,alpha:this.alpha}}}),e.Image.filters.BlendImage.fromObject=function(t,r){e.Image.fromObject(t.image,function(i){var n=e.util.object.clone(t);n.image=i,r(new e.Image.filters.BlendImage(n))})}}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=Math.pow,i=Math.floor,n=Math.sqrt,o=Math.abs,a=Math.round,s=Math.sin,c=Math.ceil,l=e.Image.filters,h=e.util.createClass;l.Resize=h(l.BaseFilter,{type:"Resize",resizeType:"hermite",scaleX:0,scaleY:0,lanczosLobes:3,applyTo2d:function(t){var e=t.imageData,r=t.scaleX||this.scaleX,i=t.scaleY||this.scaleY;if(1!==r||1!==i){this.rcpScaleX=1/r,this.rcpScaleY=1/i;var n=e.width,o=e.height,s=a(n*r),c=a(o*i),l;"sliceHack"===this.resizeType?l=this.sliceByTwo(t,n,o,s,c):"hermite"===this.resizeType?l=this.hermiteFastResize(t,n,o,s,c):"bilinear"===this.resizeType?l=this.bilinearFiltering(t,n,o,s,c):"lanczos"===this.resizeType&&(l=this.lanczosResize(t,n,o,s,c)),t.imageData=l}},sliceByTwo:function(t,r,n,o,a){var s=t.imageData,c=.5,l=!1,h=!1,u=.5*r,f=.5*n,d=e.filterBackend.resources,p,g,v=0,m=0,b=r,y=0;for(d.sliceByTwo||(d.sliceByTwo=document.createElement("canvas")),p=d.sliceByTwo,(p.width<1.5*r||p.height<n)&&(p.width=1.5*r,p.height=n),g=p.getContext("2d"),g.clearRect(0,0,1.5*r,n),g.putImageData(s,0,0),o=i(o),a=i(a);!l||!h;)r=u,n=f,o<i(.5*u)?u=i(.5*u):(u=o,l=!0),a<i(.5*f)?f=i(.5*f):(f=a,h=!0),g.drawImage(p,v,m,r,n,b,y,u,f),v=b,m=y,y+=f;return g.getImageData(v,m,o,a)},lanczosResize:function(t,e,a,l,h){function u(t){return function(e){if(e>t)return 0;if(e*=Math.PI,o(e)<1e-16)return 1;var r=e/t;return s(e)*s(r)/e/r}}function f(t){var s,c,u,T,k,P,E,O,R,L,D;for(C.x=(t+.5)*m,A.x=i(C.x),s=0;s<h;s++){for(C.y=(s+.5)*b,A.y=i(C.y),k=0,P=0,E=0,O=0,R=0,c=A.x-w;c<=A.x+w;c++)if(!(c<0||c>=e)){L=i(1e3*o(c-C.x)),x[L]||(x[L]={});for(var I=A.y-S;I<=A.y+S;I++)I<0||I>=a||(D=i(1e3*o(I-C.y)),x[L][D]||(x[L][D]=v(n(r(L*y,2)+r(D*_,2))/1e3)),(u=x[L][D])>0&&(T=4*(I*e+c),k+=u,P+=u*d[T],E+=u*d[T+1],O+=u*d[T+2],R+=u*d[T+3]))}T=4*(s*l+t),g[T]=P/k,g[T+1]=E/k,g[T+2]=O/k,g[T+3]=R/k}return++t<l?f(t):p}var d=t.imageData.data,p=t.ctx.creteImageData(l,h),g=p.data,v=u(this.lanczosLobes),m=this.rcpScaleX,b=this.rcpScaleY,y=2/this.rcpScaleX,_=2/this.rcpScaleY,w=c(m*this.lanczosLobes/2),S=c(b*this.lanczosLobes/2),x={},C={},A={};return f(0)},bilinearFiltering:function(t,e,r,n,o){var a,s,c,l,h,u,f,d,p,g,v,m,b=0,y,_=this.rcpScaleX,w=this.rcpScaleY,S=4*(e-1),x=t.imageData,C=x.data,A=t.ctx.createImageData(n,o),T=A.data;for(f=0;f<o;f++)for(d=0;d<n;d++)for(h=i(_*d),u=i(w*f),p=_*d-h,g=w*f-u,y=4*(u*e+h),v=0;v<4;v++)a=C[y+v],s=C[y+4+v],c=C[y+S+v],l=C[y+S+4+v],m=a*(1-p)*(1-g)+s*p*(1-g)+c*g*(1-p)+l*p*g,T[b++]=m;return A},hermiteFastResize:function(t,e,r,a,s){for(var l=this.rcpScaleX,h=this.rcpScaleY,u=c(l/2),f=c(h/2),d=t.imageData,p=d.data,g=t.ctx.createImageData(a,s),v=g.data,m=0;m<s;m++)for(var b=0;b<a;b++){for(var y=4*(b+m*a),_=0,w=0,S=0,x=0,C=0,A=0,T=0,k=(m+.5)*h,P=i(m*h);P<(m+1)*h;P++)for(var E=o(k-(P+.5))/f,O=(b+.5)*l,R=E*E,L=i(b*l);L<(b+1)*l;L++){var D=o(O-(L+.5))/u,I=n(R+D*D);I>1&&I<-1||(_=2*I*I*I-3*I*I+1)>0&&(D=4*(L+P*e),T+=_*p[D+3],S+=_,p[D+3]<255&&(_=_*p[D+3]/250),x+=_*p[D],C+=_*p[D+1],A+=_*p[D+2],w+=_)}v[y]=x/w,v[y+1]=C/w,v[y+2]=A/w,v[y+3]=T/S}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),e.Image.filters.Resize.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.Image.filters,i=e.util.createClass;r.Contrast=i(r.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(t){if(0!==this.contrast){var e=t.imageData,r,i,n=e.data,i=n.length,o=Math.floor(255*this.contrast),a=259*(o+255)/(255*(259-o));for(r=0;r<i;r+=4)n[r]=a*(n[r]-128)+128,n[r+1]=a*(n[r+1]-128)+128,n[r+2]=a*(n[r+2]-128)+128}},getUniformLocations:function(t,e){return{uContrast:t.getUniformLocation(e,"uContrast")}},sendUniformData:function(t,e){t.uniform1f(e.uContrast,this.contrast)}}),e.Image.filters.Contrast.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.Image.filters,i=e.util.createClass;r.Saturation=i(r.BaseFilter,{type:"Saturation",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uSaturation;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat rgMax = max(color.r, color.g);\nfloat rgbMax = max(rgMax, color.b);\ncolor.r += rgbMax != color.r ? (rgbMax - color.r) * uSaturation : 0.00;\ncolor.g += rgbMax != color.g ? (rgbMax - color.g) * uSaturation : 0.00;\ncolor.b += rgbMax != color.b ? (rgbMax - color.b) * uSaturation : 0.00;\ngl_FragColor = color;\n}",saturation:0,mainParameter:"saturation",applyTo2d:function(t){if(0!==this.saturation){var e=t.imageData,r=e.data,i=r.length,n=-this.saturation,o,a;for(o=0;o<i;o+=4)a=Math.max(r[o],r[o+1],r[o+2]),r[o]+=a!==r[o]?(a-r[o])*n:0,r[o+1]+=a!==r[o+1]?(a-r[o+1])*n:0,r[o+2]+=a!==r[o+2]?(a-r[o+2])*n:0}},getUniformLocations:function(t,e){return{uSaturation:t.getUniformLocation(e,"uSaturation")}},sendUniformData:function(t,e){t.uniform1f(e.uSaturation,-this.saturation)}}),e.Image.filters.Saturation.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.Image.filters,i=e.util.createClass;r.Blur=i(r.BaseFilter,{type:"Blur",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec2 uDelta;\nvarying vec2 vTexCoord;\nconst float nSamples = 15.0;\nvec3 v3offset = vec3(12.9898, 78.233, 151.7182);\nfloat random(vec3 scale) {\nreturn fract(sin(dot(gl_FragCoord.xyz, scale)) * 43758.5453);\n}\nvoid main() {\nvec4 color = vec4(0.0);\nfloat total = 0.0;\nfloat offset = random(v3offset);\nfor (float t = -nSamples; t <= nSamples; t++) {\nfloat percent = (t + offset - 0.5) / nSamples;\nfloat weight = 1.0 - abs(percent);\ncolor += texture2D(uTexture, vTexCoord + uDelta * percent) * weight;\ntotal += weight;\n}\ngl_FragColor = color / total;\n}",blur:0,mainParameter:"blur",applyTo:function(t){t.webgl?(this.aspectRatio=t.sourceWidth/t.sourceHeight,t.passes++,this._setupFrameBuffer(t),this.horizontal=!0,this.applyToWebGL(t),this._swapTextures(t),this._setupFrameBuffer(t),this.horizontal=!1,this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)},applyTo2d:function(t){t.imageData=this.simpleBlur(t)},simpleBlur:function(t){var e=t.filterBackend.resources,r,i,n=t.imageData.width,o=t.imageData.height;e.blurLayer1||(e.blurLayer1=document.createElement("canvas"),e.blurLayer2=document.createElement("canvas")),r=e.blurLayer1,i=e.blurLayer2,r.width===n&&r.height===o||(i.width=r.width=n,i.height=r.height=o);var a=r.getContext("2d"),s=i.getContext("2d"),c=15,l,h,u,f,d=.06*this.blur*.5;for(a.putImageData(t.imageData,0,0),s.clearRect(0,0,n,o),f=-15;f<=15;f++)l=(Math.random()-.5)/4,h=f/15,u=d*h*n+l,s.globalAlpha=1-Math.abs(h),s.drawImage(r,u,l),a.drawImage(i,0,0),s.globalAlpha=1,s.clearRect(0,0,i.width,i.height);for(f=-15;f<=15;f++)l=(Math.random()-.5)/4,h=f/15,u=d*h*o+l,s.globalAlpha=1-Math.abs(h),s.drawImage(r,l,u),a.drawImage(i,0,0),s.globalAlpha=1,s.clearRect(0,0,i.width,i.height);t.ctx.drawImage(r,0,0);var p=t.ctx.getImageData(0,0,r.width,r.height);return a.globalAlpha=1,a.clearRect(0,0,r.width,r.height),p},getUniformLocations:function(t,e){return{delta:t.getUniformLocation(e,"uDelta")}},sendUniformData:function(t,e){var r=this.chooseRightDelta();t.uniform2fv(e.delta,r)},chooseRightDelta:function(){var t=1,e=[0,0],r;return this.horizontal?this.aspectRatio>1&&(t=1/this.aspectRatio):this.aspectRatio<1&&(t=this.aspectRatio),r=t*this.blur*.12,this.horizontal?e[0]=r:e[1]=r,e}}),r.Blur.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.Image.filters,i=e.util.createClass;r.Gamma=i(r.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",applyTo2d:function(t){var e=t.imageData,r=e.data,i=this.gamma,n=r.length,o=1/i[0],a=1/i[1],s=1/i[2],c;for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),c=0,n=256;c<n;c++)this.rVals[c]=255*Math.pow(c/255,o),this.gVals[c]=255*Math.pow(c/255,a),this.bVals[c]=255*Math.pow(c/255,s);for(c=0,n=r.length;c<n;c+=4)r[c]=this.rVals[r[c]],r[c+1]=this.gVals[r[c+1]],r[c+2]=this.bVals[r[c+2]]},getUniformLocations:function(t,e){return{uGamma:t.getUniformLocation(e,"uGamma")}},sendUniformData:function(t,e){t.uniform3fv(e.uGamma,this.gamma)}}),e.Image.filters.Gamma.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.Image.filters,i=e.util.createClass;r.Composed=i(r.BaseFilter,{type:"Composed",subFilters:[],initialize:function(t){this.callSuper("initialize",t),this.subFilters=this.subFilters.slice(0)},applyTo:function(t){t.passes+=this.subFilters.length-1,this.subFilters.forEach(function(e){e.applyTo(t)})},toObject:function(){return e.util.object.extend(this.callSuper("toObject"),{subFilters:this.subFilters.map(function(t){return t.toObject()})})}}),e.Image.filters.Composed.fromObject=function(t,r){var i=t.subFilters||[],n=i.map(function(t){return new e.Image.filters[t.type](t)}),o=new e.Image.filters.Composed({subFilters:n});return r&&r(o),o}}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.util.object.clone,i=2,n=200;if(e.Text)return void e.warn("fabric.Text is already defined");var o=e.Object.prototype.stateProperties.concat();o.push("fontFamily","fontWeight","fontSize","text","underline","overline","linethrough","textAlign","fontStyle","lineHeight","textBackgroundColor","charSpacing","styles");var a=e.Object.prototype.cacheProperties.concat();a.push("fontFamily","fontWeight","fontSize","text","underline","overline","linethrough","textAlign","fontStyle","lineHeight","textBackgroundColor","charSpacing","styles"),e.Text=e.util.createClass(e.Object,{_dimensionAffectingProps:["fontSize","fontWeight","fontFamily","fontStyle","lineHeight","text","charSpacing","textAlign","styles"],_reNewline:/\r?\n/,_reSpacesAndTabs:/[ \t\r]/g,_reSpaceAndTab:/[ \t\r]/,_reWords:/\S+/g,type:"text",fontSize:40,fontWeight:"normal",fontFamily:"Times New Roman",underline:!1,overline:!1,linethrough:!1,textAlign:"left",fontStyle:"normal",lineHeight:1.16,textBackgroundColor:"",stateProperties:o,cacheProperties:a,stroke:null,shadow:null,_fontSizeFraction:.222,offsets:{underline:.1,linethrough:-.315,overline:-.88},_fontSizeMult:1.13,charSpacing:0,styles:null,_measuringContext:null,_styleProperties:["stroke","strokeWidth","fill","fontFamily","fontSize","fontWeight","fontStyle","underline","overline","linethrough"],__charBounds:[],initialize:function(t,e){e=e||{},this.text=t,this.__skipDimension=!0,this.callSuper("initialize",e),this.__skipDimension=!1,this.initDimensions(),this.setCoords(),this.setupState({propertySet:"_dimensionAffectingProps"})},getMeasuringContext:function(){return e._measuringContext||(e._measuringContext=this.canvas&&this.canvas.contextCache||e.util.createCanvasElement().getContext("2d")),e._measuringContext},isEmptyStyles:function(t){if(!this.styles)return!0;if(void 0!==t&&!this.styles[t])return!0;var e=void 0===t?this.styles:{line:this.styles[t]};for(var r in e)for(var i in e[r])for(var n in e[r][i])return!1;return!0},styleHas:function(t,e){if(!this.styles||!t||""===t)return!1;if(void 0!==e&&!this.styles[e])return!1;var r=void 0===e?this.styles:{line:this.styles[e]};for(var i in r)for(var n in r[i])if(void 0!==r[i][n][t])return!0;return!1},cleanStyle:function(t){if(!this.styles||!t||""===t)return!1;var e=this.styles,r=0,i,n=!1,o,a=!0,s=0;for(var c in e){i=0;for(var l in e[c])r++,n?e[c][l][t]!==o&&(a=!1):(o=e[c][l][t],n=!0),e[c][l][t]===this[t]&&delete e[c][l][t],0!==Object.keys(e[c][l]).length?i++:delete e[c][l];0===i&&delete e[c]}for(var h=0;h<this._textLines.length;h++)s+=this._textLines[h].length;a&&r===s&&(this[t]=o,this.removeStyle(t))},removeStyle:function(t){if(this.styles&&t&&""!==t){var e=this.styles,r,i,n;for(i in e){var r=e[i];for(n in r)delete r[n][t],0===Object.keys(r[n]).length&&delete r[n];0===Object.keys(r).length&&delete e[i]}}},_extendStyles:function(t,r){var i=this.get2DCursorLocation(t);this._getLineStyle(i.lineIndex)||this._setLineStyle(i.lineIndex,{}),this._getStyleDeclaration(i.lineIndex,i.charIndex)||this._setStyleDeclaration(i.lineIndex,i.charIndex,{}),e.util.object.extend(this._getStyleDeclaration(i.lineIndex,i.charIndex),r)},initDimensions:function(){if(!this.__skipDimension){var t=this._splitTextIntoLines(this.text);this.textLines=t.lines,this._unwrappedTextLines=t._unwrappedLines,this._textLines=t.graphemeLines,this._text=t.graphemeText,this._clearCache(),this.width=this.calcTextWidth()||this.cursorWidth||2,"justify"===this.textAlign&&this.enlargeSpaces(),this.height=this.calcTextHeight()}},enlargeSpaces:function(){for(var t,e,r,i,n,o,a,s=0,c=this._textLines.length;s<c;s++)if(i=0,n=this._textLines[s],(e=this.getLineWidth(s))<this.width&&(a=this.textLines[s].match(this._reSpacesAndTabs))){r=a.length,t=(this.width-e)/r;for(var l=0,h=n.length;l<=h;l++)o=this.__charBounds[s][l],this._reSpaceAndTab.test(n[l])?(o.width+=t,o.kernedWidth+=t,o.left+=i,i+=t):o.left+=i}},toString:function(){return"#<fabric.Text ("+this.complexity()+'): { "text": "'+this.text+'", "fontFamily": "'+this.fontFamily+'" }>'},_getCacheCanvasDimensions:function(){var t=this.callSuper("_getCacheCanvasDimensions"),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t},_render:function(t){this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")},_renderText:function(t){this._renderTextFill(t),this._renderTextStroke(t)},_setTextStyles:function(t,e,r){t.textBaseline="alphabetic",t.font=this._getFontDeclaration(e,r)},calcTextWidth:function(){for(var t=this.getLineWidth(0),e=1,r=this._textLines.length;e<r;e++){var i=this.getLineWidth(e);i>t&&(t=i)}return t},_renderTextLine:function(t,e,r,i,n,o){this._renderChars(t,e,r,i,n,o)},_renderTextLinesBackground:function(t){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var e=0,r,i,n=t.fillStyle,o,a,s=this._getLeftOffset(),c=this._getTopOffset(),l=0,h=0,u,f,d=0,p=this._textLines.length;d<p;d++)if(r=this.getHeightOfLine(d),this.textBackgroundColor||this.styleHas("textBackgroundColor",d)){o=this._textLines[d],i=this._getLineLeftOffset(d),h=0,l=0,a=this.getValueOfPropertyAt(d,0,"textBackgroundColor");for(var g=0,v=o.length;g<v;g++)u=this.__charBounds[d][g],f=this.getValueOfPropertyAt(d,g,"textBackgroundColor"),f!==a?(t.fillStyle=a,a&&t.fillRect(s+i+l,c+e,h,r/this.lineHeight),l=u.left,h=u.width,a=f):h+=u.kernedWidth;f&&(t.fillStyle=f,t.fillRect(s+i+l,c+e,h,r/this.lineHeight)),e+=r}else e+=r;t.fillStyle=n,this._removeShadow(t)}},getFontCache:function(t){var r=t.fontFamily.toLowerCase();e.charWidthsCache[r]||(e.charWidthsCache[r]={});var i=e.charWidthsCache[r],n=t.fontStyle.toLowerCase()+"_"+(t.fontWeight+"").toLowerCase();return i[n]||(i[n]={}),i[n]},_applyCharStyles:function(t,e,r,i,n){this._setFillStyles(e,n),this._setStrokeStyles(e,n),e.font=this._getFontDeclaration(n)},_getStyleDeclaration:function(t,e){var r=this.styles&&this.styles[t];return r?r[e]:null},getCompleteStyleDeclaration:function(t,e){for(var r=this._getStyleDeclaration(t,e)||{},i={},n,o=0;o<this._styleProperties.length;o++)n=this._styleProperties[o],i[n]=void 0===r[n]?this[n]:r[n];return i},_setStyleDeclaration:function(t,e,r){this.styles[t][e]=r},_deleteStyleDeclaration:function(t,e){delete this.styles[t][e]},_getLineStyle:function(t){return this.styles[t]},_setLineStyle:function(t,e){this.styles[t]=e},_deleteLineStyle:function(t){delete this.styles[t]},_measureChar:function(t,e,r,i){var n=this.getFontCache(e),o=this._getFontDeclaration(e),a=this._getFontDeclaration(i),s=r+t,c=o===a,l,h,u,f=e.fontSize/200,d;if(r&&n[r]&&(u=n[r]),n[t]&&(d=l=n[t]),c&&n[s]&&(h=n[s],d=h-u),!l||!u||!h){var p=this.getMeasuringContext();this._setTextStyles(p,e,!0)}if(l||(d=l=p.measureText(t).width,n[t]=l),!u&&c&&r&&(u=p.measureText(r).width,n[r]=u),c&&!h&&(h=p.measureText(s).width,n[s]=h,(d=h-u)>l)){var g=d-l;n[t]=d,n[s]+=g,l=d}return{width:l*f,kernedWidth:d*f}},getHeightOfChar:function(t,e){return this.getValueOfPropertyAt(t,e,"fontSize")},measureLine:function(t){var e=this._measureLine(t);return 0!==this.charSpacing&&(e.width-=this._getWidthOfCharSpacing()),e.width<0&&(e.width=0),e},_measureLine:function(t){var e=0,r,i,n=this._textLines[t],o,a,s=0,c=new Array(n.length);for(this.__charBounds[t]=c,r=0;r<n.length;r++)i=n[r],a=this._getGraphemeBox(i,t,r,o),c[r]=a,e+=a.kernedWidth,o=i;return c[r]={left:a?a.left+a.width:0,width:0,kernedWidth:0,height:this.fontSize},{width:e,numOfSpaces:0}},_getGraphemeBox:function(t,e,r,i,n){var o=this.getCompleteStyleDeclaration(e,r),a=i?this.getCompleteStyleDeclaration(e,r-1):{},s=this._measureChar(t,o,i,a),c=s.kernedWidth,l=s.width;0!==this.charSpacing&&(l+=this._getWidthOfCharSpacing(),c+=this._getWidthOfCharSpacing());var h={width:l,left:0,height:o.fontSize,kernedWidth:c};if(r>0&&!n){var u=this.__charBounds[e][r-1];h.left=u.left+u.width+s.kernedWidth-s.width}return h},getHeightOfLine:function(t){if(this.__lineHeights[t])return this.__lineHeights[t];for(var e=this._textLines[t],r=this.getHeightOfChar(t,0),i=1,n=e.length;i<n;i++){var o=this.getHeightOfChar(t,i);o>r&&(r=o)}return this.__lineHeights[t]=r*this.lineHeight*this._fontSizeMult,this.__lineHeights[t]},calcTextHeight:function(){for(var t,e=0,r=0,i=this._textLines.length;r<i;r++)t=this.getHeightOfLine(r),e+=r===i-1?t/this.lineHeight:t;return e},_getLeftOffset:function(){return-this.width/2},_getTopOffset:function(){return-this.height/2},_renderTextCommon:function(t,e){for(var r=0,i=this._getLeftOffset(),n=this._getTopOffset(),o=0,a=this._textLines.length;o<a;o++){var s=this.getHeightOfLine(o),c=s/this.lineHeight,l=this._getLineLeftOffset(o);this._renderTextLine(e,t,this._textLines[o],i+l,n+r+c,o),r+=s}},_renderTextFill:function(t){(this.fill||this.styleHas("fill"))&&this._renderTextCommon(t,"fillText")},_renderTextStroke:function(t){(this.stroke&&0!==this.strokeWidth||!this.isEmptyStyles())&&(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this._setLineDash(t,this.strokeDashArray),t.beginPath(),this._renderTextCommon(t,"strokeText"),t.closePath(),t.restore())},_renderChars:function(t,e,r,i,n,o){var a=this.getHeightOfLine(o),s,c,l="",h,u=0,f;e.save(),n-=a*this._fontSizeFraction/this.lineHeight;for(var d=0,p=r.length-1;d<=p;d++)f=d===p||this.charSpacing,l+=r[d],h=this.__charBounds[o][d],0===u&&(i+=h.kernedWidth-h.width),u+=h.kernedWidth,"justify"!==this.textAlign||f||this._reSpaceAndTab.test(r[d])&&(f=!0),f||(s=s||this.getCompleteStyleDeclaration(o,d),c=this.getCompleteStyleDeclaration(o,d+1),f=this._hasStyleChanged(s,c)),f&&(this._renderChar(t,e,o,d,l,i,n,a),l="",s=c,i+=u,u=0);e.restore()},_renderChar:function(t,e,r,i,n,o,a){var s=this._getStyleDeclaration(r,i),c=this.getCompleteStyleDeclaration(r,i),l="fillText"===t&&c.fill,h="strokeText"===t&&c.stroke&&c.strokeWidth;(h||l)&&(s&&e.save(),this._applyCharStyles(t,e,r,i,c),s&&s.textBackgroundColor&&this._removeShadow(e),l&&e.fillText(n,o,a),h&&e.strokeText(n,o,a),s&&e.restore())},_hasStyleChanged:function(t,e){return t.fill!==e.fill||t.stroke!==e.stroke||t.strokeWidth!==e.strokeWidth||t.fontSize!==e.fontSize||t.fontFamily!==e.fontFamily||t.fontWeight!==e.fontWeight||t.fontStyle!==e.fontStyle},_getLineLeftOffset:function(t){var e=this.getLineWidth(t);return"center"===this.textAlign?(this.width-e)/2:"right"===this.textAlign?this.width-e:0},_clearCache:function(){this.__lineWidths=[],this.__lineHeights=[],this.__numberOfSpaces=[],this.__charBounds=[]},_shouldClearDimensionCache:function(){var t=this._forceClearCache;return t||(t=this.hasStateChanged("_dimensionAffectingProps")),t&&(this.saveState({propertySet:"_dimensionAffectingProps"}),this.dirty=!0,this._forceClearCache=!1),t},getLineWidth:function(t){if(this.__lineWidths[t])return this.__lineWidths[t];var e,r=this._textLines[t],i;return""===r?e=0:(i=this.measureLine(t),e=i.width),this.__lineWidths[t]=e,this.__numberOfSpaces[t]=i.numberOfSpaces,e},_getWidthOfCharSpacing:function(){return 0!==this.charSpacing?this.fontSize*this.charSpacing/1e3:0},getValueOfPropertyAt:function(t,e,r){var i=this._getStyleDeclaration(t,e);return i&&void 0!==i[r]?i[r]:this[r]},_renderTextDecoration:function(t,e){if(this[e]||this.styleHas(e)){for(var r,i,n,o,a=this._getLeftOffset(),s=this._getTopOffset(),c,l,h,u,f,d,p,g=0,v=this._textLines.length;g<v;g++)if(r=this.getHeightOfLine(g),this[e]||this.styleHas(e,g)){n=this._textLines[g],f=r/this.lineHeight,i=this._getLineLeftOffset(g),c=0,l=0,o=this.getValueOfPropertyAt(g,0,e),p=this.getValueOfPropertyAt(g,0,"fill");for(var m=0,b=n.length;m<b;m++)h=this.__charBounds[g][m],u=this.getValueOfPropertyAt(g,m,e),d=this.getValueOfPropertyAt(g,m,"fill"),(u!==o||d!==p)&&l>0?(t.fillStyle=p,o&&p&&t.fillRect(a+i+c,s+f*(1-this._fontSizeFraction)+this.offsets[e]*this.fontSize,l,this.fontSize/15),c=h.left,l=h.width,o=u,p=d):l+=h.kernedWidth;t.fillStyle=d,u&&d&&t.fillRect(a+i+c,s+f*(1-this._fontSizeFraction)+this.offsets[e]*this.fontSize,l,this.fontSize/15),s+=r}else s+=r;this._removeShadow(t)}},_getFontDeclaration:function(t,r){var i=t||this;return[e.isLikelyNode?i.fontWeight:i.fontStyle,e.isLikelyNode?i.fontStyle:i.fontWeight,r?"200px":i.fontSize+"px",e.isLikelyNode?'"'+i.fontFamily+'"':i.fontFamily].join(" ")},render:function(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",t)))},_splitTextIntoLines:function(t){for(var r=t.split(this._reNewline),i=new Array(r.length),n=["\n"],o=[],a=0;a<r.length;a++)i[a]=e.util.string.graphemeSplit(r[a]),o=o.concat(i[a],n);return o.pop(),{_unwrappedLines:i,lines:r,graphemeText:o,graphemeLines:i}},toObject:function(t){var e=["text","fontSize","fontWeight","fontFamily","fontStyle","lineHeight","underline","overline","linethrough","textAlign","textBackgroundColor","charSpacing"].concat(t),i=this.callSuper("toObject",e);return i.styles=r(this.styles,!0),i},_set:function(t,e){this.callSuper("_set",t,e),this._dimensionAffectingProps.indexOf(t)>-1&&(this.initDimensions(),this.setCoords())},complexity:function(){return 1}}),e.Text.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y dx dy font-family font-style font-weight font-size text-decoration text-anchor".split(" ")),e.Text.DEFAULT_SVG_FONT_SIZE=16,e.Text.fromElement=function(t,i,n){if(!t)return i(null);var o=e.parseAttributes(t,e.Text.ATTRIBUTE_NAMES);if(n=e.util.object.extend(n?r(n):{},o),n.top=n.top||0,n.left=n.left||0,o.textDecoration){var a=o.textDecoration;-1!==a.indexOf("underline")&&(n.underline=!0),-1!==a.indexOf("overline")&&(n.overline=!0),-1!==a.indexOf("line-through")&&(n.linethrough=!0),delete n.textDecoration}"dx"in o&&(n.left+=o.dx),"dy"in o&&(n.top+=o.dy),"fontSize"in n||(n.fontSize=e.Text.DEFAULT_SVG_FONT_SIZE),n.originX||(n.originX="left");var s="";"textContent"in t?s=t.textContent:"firstChild"in t&&null!==t.firstChild&&"data"in t.firstChild&&null!==t.firstChild.data&&(s=t.firstChild.data),s=s.replace(/^\s+|\s+$|\n+/g,"").replace(/\s+/g," ");var c=new e.Text(s,n),l=c.getScaledHeight()/c.height,h=(c.height+c.strokeWidth)*c.lineHeight-c.height,u=h*l,f=c.getScaledHeight()+u,d=0;"center"===c.originX&&(d=c.getScaledWidth()/2),"right"===c.originX&&(d=c.getScaledWidth()),c.set({left:c.left-d,top:c.top-(f-c.fontSize*(.18+c._fontSizeFraction))/c.lineHeight}),c.originX="left",c.originY="top",i(c)},e.Text.fromObject=function(t,r){return e.Object._fromObject("Text",t,r,"text")},e.util.createAccessors&&e.util.createAccessors(e.Text)}(exports),function(){function t(t){t.textDecoration&&(t.textDecoration.indexOf("underline")>-1&&(t.underline=!0),t.textDecoration.indexOf("line-through")>-1&&(t.linethrough=!0),t.textDecoration.indexOf("overline")>-1&&(t.overline=!0),delete t.textDecoration)}fabric.IText=fabric.util.createClass(fabric.Text,fabric.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"#333",cursorDelay:1e3,cursorDuration:600,caching:!0,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(t,e){this.styles=e?e.styles||{}:{},this.callSuper("initialize",t,e),this.initBehavior()},setSelectionStart:function(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)},setSelectionEnd:function(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)},_updateAndFire:function(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},getSelectionStyles:function(t,e){if(2===arguments.length){for(var r=[],i=t;i<e;i++)r.push(this.getSelectionStyles(i));return r}var n=this.get2DCursorLocation(t);return this._getStyleDeclaration(n.lineIndex,n.charIndex)||{}},setSelectionStyles:function(t){if(this.selectionStart===this.selectionEnd)return this;for(var e=this.selectionStart;e<this.selectionEnd;e++)this._extendStyles(e,t);return this._forceClearCache=!0,this},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(t){this.clearContextTop(),this.callSuper("render",t),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(t){this.callSuper("_render",t),this.ctx=t},clearContextTop:function(t){if(this.active&&this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this.canvas.contextTop;e.save(),e.transform.apply(e,this.canvas.viewportTransform),this.transform(e),this.transformMatrix&&e.transform.apply(e,this.transformMatrix),this._clearTextArea(e),t||e.restore()}},renderCursorOrSelection:function(){if(this.active&&this.isEditing){var t=this._getCursorBoundaries(),e;this.canvas&&this.canvas.contextTop?(e=this.canvas.contextTop,this.clearContextTop(!0)):(e=this.ctx,e.save()),this.selectionStart===this.selectionEnd?this.renderCursor(t,e):this.renderSelection(t,e),e.restore()}},_clearTextArea:function(t){var e=this.width+4,r=this.height+4;t.clearRect(-e/2,-r/2,e,r)},get2DCursorLocation:function(t,e){void 0===t&&(t=this.selectionStart);for(var r=e?this._unwrappedTextLines:this._textLines,i=r.length,n=0;n<i;n++){if(t<=r[n].length)return{lineIndex:n,charIndex:t};t-=r[n].length+1}return{lineIndex:n-1,charIndex:r[n-1].length<t?r[n-1].length:t}},_getCursorBoundaries:function(t){void 0===t&&(t=this.selectionStart);var e=this._getLeftOffset(),r=this._getTopOffset(),i=this._getCursorBoundariesOffsets(t);return{left:e,top:r,leftOffset:i.left,topOffset:i.top}},_getCursorBoundariesOffsets:function(t){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;for(var e,r=0,i=0,n=0,o=0,a,s=this.get2DCursorLocation(t),c=0;c<s.lineIndex;c++)n+=this.getHeightOfLine(c);e=this._getLineLeftOffset(s.lineIndex);var l=this.__charBounds[s.lineIndex][s.charIndex];return l&&(o=l.left),0!==this.charSpacing&&0===this._textLines[0].length&&(o-=this._getWidthOfCharSpacing()),a={top:n,left:e+(o>0?o:0)},this.cursorOffsetCache=a,this.cursorOffsetCache},renderCursor:function(t,e){var r=this.get2DCursorLocation(),i=r.lineIndex,n=r.charIndex>0?r.charIndex-1:0,o=this.getValueOfPropertyAt(i,n,"fontSize"),a=this.scaleX*this.canvas.getZoom(),s=this.cursorWidth/a,c=t.topOffset;c+=(1-this._fontSizeFraction)*this.getHeightOfLine(i)/this.lineHeight-o*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(t,e),e.fillStyle=this.getValueOfPropertyAt(i,n,"fill"),e.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,e.fillRect(t.left+t.leftOffset-s/2,c+t.top,s,o)},renderSelection:function(t,e){for(var r=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,i=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,n=this.get2DCursorLocation(r),o=this.get2DCursorLocation(i),a=n.lineIndex,s=o.lineIndex,c=n.charIndex<0?0:n.charIndex,l=o.charIndex<0?0:o.charIndex,h=a;h<=s;h++){var u=this._getLineLeftOffset(h)||0,f=this.getHeightOfLine(h),d=0,p=0,g=0;h===a&&(p=this.__charBounds[a][c].left),h>=a&&h<s?g=this.getLineWidth(h)||5:h===s&&(g=0===l?this.__charBounds[s][l].left:this.__charBounds[s][l-1].left+this.__charBounds[s][l-1].width),d=f,(this.lineHeight<1||h===s&&this.lineHeight>1)&&(f/=this.lineHeight),this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",e.fillRect(t.left+u+p,t.top+t.topOffset+f,g-p,1)):(e.fillStyle=this.selectionColor,e.fillRect(t.left+u+p,t.top+t.topOffset,g-p,f)),t.topOffset+=d}},getCurrentCharFontSize:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")},getCurrentCharColor:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fill")},_getCurrentCharIndex:function(){var t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}}),fabric.IText.fromObject=function(e,r){if(t(e),e.styles)for(var i in e.styles)for(var n in e.styles[i])t(e.styles[i][n]);fabric.Object._fromObject("IText",e,r,"text")}}(),function(){var t=fabric.util.object.clone;fabric.util.object.extend(fabric.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1,this.callSuper("onDeselect")},initAddedHandler:function(){var t=this;this.on("added",function(){var e=t.canvas;e&&(e._hasITextHandlers||(e._hasITextHandlers=!0,t._initCanvasHandlers(e)),e._iTextInstances=e._iTextInstances||[],e._iTextInstances.push(t))})},initRemovedHandler:function(){var t=this;this.on("removed",function(){var e=t.canvas;e&&(e._iTextInstances=e._iTextInstances||[],fabric.util.removeFromArray(e._iTextInstances,t),0===e._iTextInstances.length&&(e._hasITextHandlers=!1,t._removeCanvasHandlers(e)))})},_initCanvasHandlers:function(t){t._mouseUpITextHandler=function(){t._iTextInstances&&t._iTextInstances.forEach(function(t){t.__isMousedown=!1})}.bind(this),t.on("mouse:up",t._mouseUpITextHandler)},_removeCanvasHandlers:function(t){t.off("mouse:up",t._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(t,e,r,i){var n;return n={isAborted:!1,abort:function(){this.isAborted=!0}},t.animate("_currentCursorOpacity",e,{duration:r,onComplete:function(){n.isAborted||t[i]()},onChange:function(){t.canvas&&t.selectionStart===t.selectionEnd&&t.renderCursorOrSelection()},abort:function(){return n.isAborted}}),n},_onTickComplete:function(){var t=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout(function(){t._currentTickCompleteState=t._animateCursor(t,0,this.cursorDuration/2,"_tick")},100)},initDelayedCursor:function(t){var e=this,r=t?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout(function(){e._tick()},r)},abortCursorAnimation:function(){var t=this._currentTickState||this._currentTickCompleteState;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,t&&this.canvas&&this.canvas.clearContext(this.canvas.contextTop||this.ctx)},selectAll:function(){this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea()},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(t){var e=0,r=t-1;if(this._reSpace.test(this._text[r]))for(;this._reSpace.test(this._text[r]);)e++,r--;for(;/\S/.test(this._text[r])&&r>-1;)e++,r--;return t-e},findWordBoundaryRight:function(t){var e=0,r=t;if(this._reSpace.test(this._text[r]))for(;this._reSpace.test(this._text[r]);)e++,r++;for(;/\S/.test(this._text[r])&&r<this.text.length;)e++,r++;return t+e},findLineBoundaryLeft:function(t){for(var e=0,r=t-1;!/\n/.test(this._text[r])&&r>-1;)e++,r--;return t-e},findLineBoundaryRight:function(t){for(var e=0,r=t;!/\n/.test(this._text[r])&&r<this.text.length;)e++,r++;return t+e},searchWordBoundary:function(t,e){for(var r=this._reSpace.test(this.text.charAt(t))?t-1:t,i=this.text.charAt(r),n=/[ \n\.,;!\?\-]/;!n.test(i)&&r>0&&r<this.text.length;)r+=e,i=this.text.charAt(r);return n.test(i)&&"\n"!==i&&(r+=1===e?0:1),r},selectWord:function(t){t=t||this.selectionStart;var e=this.searchWordBoundary(t,-1),r=this.searchWordBoundary(t,1);this.selectionStart=e,this.selectionEnd=r,this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()},selectLine:function(t){t=t||this.selectionStart;var e=this.findLineBoundaryLeft(t),r=this.findLineBoundaryRight(t);this.selectionStart=e,this.selectionEnd=r,this._fireSelectionChanged(),this._updateTextarea()},enterEditing:function(t){if(!this.isEditing&&this.editable)return this.canvas&&this.exitEditingOnOthers(this.canvas),this.isEditing=!0,this.initHiddenTextarea(t),this.hiddenTextarea.focus(),this.hiddenTextarea.value=this.text,this._updateTextarea(),this._saveEditingProps(),this._setEditingProps(),this._textBeforeEdit=this.text,this._tick(),this.fire("editing:entered"),this._fireSelectionChanged(),this.canvas?(this.canvas.fire("text:editing:entered",{target:this}),this.initMouseMoveHandler(),this.canvas.requestRenderAll(),this):this},exitEditingOnOthers:function(t){t._iTextInstances&&t._iTextInstances.forEach(function(t){t.selected=!1,t.isEditing&&t.exitEditing()})},initMouseMoveHandler:function(){this.canvas.on("mouse:move",this.mouseMoveHandler)},mouseMoveHandler:function(t){if(this.__isMousedown&&this.isEditing){var e=this.getSelectionStartFromPointer(t.e),r=this.selectionStart,i=this.selectionEnd;(e===this.__selectionStartOnMouseDown&&r!==i||r!==e&&i!==e)&&(e>this.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=e):(this.selectionStart=e,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===r&&this.selectionEnd===i||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(t,e,r){var i=r.slice(0,t),n=fabric.util.string.graphemeSplit(i).length;if(t===e)return{selectionStart:n,selectionEnd:n};var o=r.slice(t,e);return{selectionStart:n,selectionEnd:n+fabric.util.string.graphemeSplit(o).length}},fromGraphemeToStringSelection:function(t,e,r){var i=r.slice(0,t),n=i.join("").length;return t===e?{selectionStart:n,selectionEnd:n}:{selectionStart:n,selectionEnd:n+r.slice(t,e).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value;var t=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=t.selectionEnd,this.inCompositionMode||(this.selectionStart=t.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),r=this.get2DCursorLocation(t),i=r.lineIndex,n=r.charIndex,o=this.getValueOfPropertyAt(i,n,"fontSize")*this.lineHeight,a=e.leftOffset,s=this.calcTransformMatrix(),c={x:e.left+a,y:e.top+e.topOffset+o},l=this.canvas.upperCanvasEl,h=l.width-o,u=l.height-o;return c=fabric.util.transformPoint(c,s),c=fabric.util.transformPoint(c,this.canvas.viewportTransform),c.x<0&&(c.x=0),c.x>h&&(c.x=h),c.y<0&&(c.y=0),c.y>u&&(c.y=u),c.x+=this.canvas._offset.left,c.y+=this.canvas._offset.top,{left:c.x+"px",top:c.y+"px",fontSize:o+"px",charHeight:o}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.overCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var t=this._textBeforeEdit!==this.text;return this.selected=!1,this.isEditing=!1,this.selectable=!0,this.selectionEnd=this.selectionStart,this.hiddenTextarea&&(this.hiddenTextarea.blur&&this.hiddenTextarea.blur(),this.canvas&&this.hiddenTextarea.parentNode.removeChild(this.hiddenTextarea),this.hiddenTextarea=null),this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this.fire("editing:exited"),t&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var t in this.styles)this._textLines[t]||delete this.styles[t]},removeStyleFromTo:function(t,e){var r=this.get2DCursorLocation(t,!0),i=this.get2DCursorLocation(e,!0),n=r.lineIndex,o=r.charIndex,a=i.lineIndex,s=i.charIndex,c,l;if(n!==a){if(this.styles[n])for(c=o;c<this._textLines[n].length;c++)delete this.styles[n][c];if(this.styles[a])for(c=s;c<this._textLines[a].length;c++)(l=this.styles[a][c])&&(this.styles[n]||(this.styles[n]={}),this.styles[n][o+c-s]=l);for(c=n+1;c<=a;c++)delete this.styles[c];this.shiftLineStyles(a,n-a)}else if(this.styles[n]){l=this.styles[n];var h=s-o;for(c=o;c<s;c++)delete l[c];for(c=s;c<this._textLines[n].length;c++)l[c]&&(l[c-h]=l[c],delete l[c])}},shiftLineStyles:function(e,r){var i=t(this.styles);for(var n in this.styles){var o=parseInt(n,10);o>e&&(this.styles[o+r]=i[o],i[o-r]||delete this.styles[o])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(e,r,i,n){var o,a={},s=!1;i||(i=1),this.shiftLineStyles(e,i),this.styles[e]&&this.styles[e][r-1]&&(o=this.styles[e][r-1]);for(var c in this.styles[e]){var l=parseInt(c,10);l>=r&&(s=!0,a[l-r]=this.styles[e][c],delete this.styles[e][c])}for(s?this.styles[e+i]=a:delete this.styles[e+i];i>1;)i--,n[i]?this.styles[e+i]={0:t(n[i])}:o?this.styles[e+i]={0:t(o)}:delete this.styles[e+i];this._forceClearCache=!0},insertCharStyleObject:function(e,r,i,n){var o=this.styles[e],a=t(o);i||(i=1);for(var s in a){var c=parseInt(s,10);c>=r&&(o[c+i]=a[c],a[c-i]||delete o[c])}if(this._forceClearCache=!0,o)if(n)for(;i--;)this.styles[e][r+i]=t(n[i]);else for(var l=o[r?r-1:1];l&&i--;)this.styles[e][r+i]=t(l)},insertNewStyleBlock:function(t,e,r){for(var i=this.get2DCursorLocation(e,!0),n=0,o=0,a=0;a<t.length;a++)"\n"===t[a]?(o&&(this.insertCharStyleObject(i.lineIndex,i.charIndex,o,r),r=r&&r.slice(o),o=0),n++):(n&&(this.insertNewlineStyleObject(i.lineIndex,i.charIndex,n,r),r=r&&r.slice(n),n=0),o++);o&&this.insertCharStyleObject(i.lineIndex,i.charIndex,o,r),n&&this.insertNewlineStyleObject(i.lineIndex,i.charIndex,n,r)},setSelectionStartEndWithShift:function(t,e,r){r<=t?(e===t?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=t),this.selectionStart=r):r>t&&r<e?"right"===this._selectionDirection?this.selectionEnd=r:this.selectionStart=r:(e===t?this._selectionDirection="right":"left"===this._selectionDirection&&(this._selectionDirection="right",this.selectionStart=e),this.selectionEnd=r)},setSelectionInBoundaries:function(){var t=this.text.length;this.selectionStart>t?this.selectionStart=t:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>t?this.selectionEnd=t:this.selectionEnd<0&&(this.selectionEnd=0)}})}(),fabric.util.object.extend(fabric.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown.bind(this))},onMouseDown:function(t){this.__newClickTime=+new Date;var e=this.canvas.getPointer(t.e);this.isTripleClick(e,t.e)&&(this.fire("tripleclick",t),this._stopEvent(t.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=e,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected},isTripleClick:function(t){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===t.x&&this.__lastPointer.y===t.y},_stopEvent:function(t){t.preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},initClicks:function(){this.on("mousedblclick",function(t){this.selectWord(this.getSelectionStartFromPointer(t.e))}),this.on("tripleclick",function(t){this.selectLine(this.getSelectionStartFromPointer(t.e))})},initMousedownHandler:function(){this.on("mousedown",function(t){if(this.editable&&(!t.e.button||1===t.e.button)){var e=this.canvas.getPointer(t.e);this.__mousedownX=e.x,this.__mousedownY=e.y,this.__isMousedown=!0,this.selected&&this.setCursorByClick(t.e),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection())}})},_isObjectMoved:function(t){var e=this.canvas.getPointer(t);return this.__mousedownX!==e.x||this.__mousedownY!==e.y},initMouseupHandler:function(){this.on("mouseup",function(t){this.__isMousedown=!1,!this.editable||this._isObjectMoved(t.e)||t.e.button&&1!==t.e.button||(this.__lastSelected&&!this.__corner&&(this.enterEditing(t.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()),this.selected=!0)})},setCursorByClick:function(t){var e=this.getSelectionStartFromPointer(t),r=this.selectionStart,i=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(r,i,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(t){for(var e=this.getLocalPointer(t),r=0,i=0,n=0,o=0,a=0,s,c,l=0,h=this._textLines.length;l<h&&n<=e.y;l++)n+=this.getHeightOfLine(l)*this.scaleY,a=l,l>0&&(o+=this._textLines[l-1].length+1);s=this._getLineLeftOffset(a),i=s*this.scaleX,c=this._textLines[a];for(var u=0,f=c.length;u<f&&(r=i,(i+=this.__charBounds[a][u].kernedWidth*this.scaleX)<=e.x);u++)o++;return this._getNewSelectionStartFromOffset(e,r,i,o,f)},_getNewSelectionStartFromOffset:function(t,e,r,i,n){var o=t.x-e,a=r-t.x,s=a>o?0:1,c=i+s;return this.flipX&&(c=n-c),c>this._text.length&&(c=this._text.length),c}}),fabric.util.object.extend(fabric.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=fabric.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var t=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+t.top+"; left: "+t.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; line-height: 1px; paddingーtop: "+t.fontSize+";",fabric.document.body.appendChild(this.hiddenTextarea),fabric.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),fabric.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),fabric.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),fabric.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),fabric.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),fabric.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),fabric.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),fabric.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),fabric.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(fabric.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(t){if(this.isEditing&&!this.inCompositionMode){if(t.keyCode in this.keysMap)this[this.keysMap[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown&&(t.ctrlKey||t.metaKey)))return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(t){if(!this.isEditing||this._copyDone||this.inCompositionMode)return void(this._copyDone=!1);t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(t){var e=this.fromPaste;if(this.fromPaste=!1,t&&t.stopPropagation(),this.isEditing){var r=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,i=this._text.length,n=r.length,o,a,s=n-i;""===this.hiddenTextarea.value&&(this.styles={},this.updateFromTextArea(),this.fire("changed"),this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll())),this.selectionStart!==this.selectionEnd?(o=this._text.slice(this.selectionStart,this.selectionEnd),s+=this.selectionEnd-this.selectionStart):n<i&&(o=this._text.slice(this.selectionEnd+s,this.selectionEnd));var c=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);a=r.slice(c.selectionEnd-s,c.selectionEnd),o&&o.length&&(this.selectionStart!==this.selectionEnd?this.removeStyleFromTo(this.selectionStart,this.selectionEnd):this.selectionStart>c.selectionStart?this.removeStyleFromTo(this.selectionEnd-o.length,this.selectionEnd):this.removeStyleFromTo(this.selectionEnd,this.selectionEnd+o.length)),a.length&&(e&&a.join("")===fabric.copiedText?this.insertNewStyleBlock(a,this.selectionStart,fabric.copiedTextStyle):this.insertNewStyleBlock(a,this.selectionStart)),this.updateFromTextArea(),this.fire("changed"),this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll())}},onCompositionStart:function(){this.inCompositionMode=!0},onCompositionEnd:function(){this.inCompositionMode=!1},onCompositionUpdate:function(t){this.compositionStart=t.target.selectionStart,this.compositionEnd=t.target.selectionEnd,this.updateTextareaPosition()},copy:function(){if(this.selectionStart!==this.selectionEnd){var t=this.getSelectedText();fabric.copiedText=t,fabric.copiedTextStyle=this.getSelectionStyles(this.selectionStart,this.selectionEnd),this._copyDone=!0}},paste:function(){this.fromPaste=!0},_getClipboardData:function(t){return t&&t.clipboardData||fabric.window.clipboardData},_getWidthBeforeCursor:function(t,e){var r=this._getLineLeftOffset(t),i;return e>0&&(i=this.__charBounds[t][e-1],r+=i.left+i.width),r},getDownCursorOffset:function(t,e){var r=this._getSelectionForOffset(t,e),i=this.get2DCursorLocation(r),n=i.lineIndex;if(n===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-r;var o=i.charIndex,a=this._getWidthBeforeCursor(n,o),s=this._getIndexOnLine(n+1,a);return this._textLines[n].slice(o).length+s+2},_getSelectionForOffset:function(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(t,e){var r=this._getSelectionForOffset(t,e),i=this.get2DCursorLocation(r),n=i.lineIndex;if(0===n||t.metaKey||33===t.keyCode)return-r;var o=i.charIndex,a=this._getWidthBeforeCursor(n,o),s=this._getIndexOnLine(n-1,a),c=this._textLines[n].slice(0,o);return-this._textLines[n-1].length+s-c.length},_getIndexOnLine:function(t,e){for(var r=this._textLines[t],i=this._getLineLeftOffset(t),n=i,o=0,a,s,c=0,l=r.length;c<l;c++)if(a=this.__charBounds[t][c].width,(n+=a)>e){s=!0;var h=n-a,u=n,f=Math.abs(h-e),d=Math.abs(u-e);o=d<f?c:c-1;break}return s||(o=r.length-1),o},moveCursorDown:function(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)},moveCursorUp:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorUpOrDown("Up",t)},_moveCursorUpOrDown:function(t,e){var r="get"+t+"CursorOffset",i=this[r](e,"right"===this._selectionDirection);e.shiftKey?this.moveCursorWithShift(i):this.moveCursorWithoutShift(i),0!==i&&(this.setSelectionInBoundaries(),this.abortCursorAnimation(),this._currentCursorOpacity=1,this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorWithShift:function(t){var e="left"===this._selectionDirection?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),0!==t},moveCursorWithoutShift:function(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),0!==t},moveCursorLeft:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorLeftOrRight("Left",t)},_move:function(t,e,r){var i;if(t.altKey)i=this["findWordBoundary"+r](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===r?-1:1,!0;i=this["findLineBoundary"+r](this[e])}if(void 0!==typeof i&&this[e]!==i)return this[e]=i,!0},_moveLeft:function(t,e){return this._move(t,e,"Left")},_moveRight:function(t,e){return this._move(t,e,"Right")},moveCursorLeftWithoutShift:function(t){var e=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e},moveCursorLeftWithShift:function(t){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(t,"selectionStart")):void 0},moveCursorRight:function(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)},_moveCursorLeftOrRight:function(t,e){var r="moveCursor"+t+"With";this._currentCursorOpacity=1,e.shiftKey?r+="Shift":r+="outShift",this[r](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(t){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(t,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(t){var e=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e},removeChars:function(t){this.selectionStart===this.selectionEnd?this._removeCharsNearCursor(t):this._removeCharsFromTo(this.selectionStart,this.selectionEnd),this.set("dirty",!0),this.setSelectionEnd(this.selectionStart),this._removeExtraneousStyles(),this.canvas&&this.canvas.requestRenderAll(),this.setCoords(),this.fire("changed"),this.canvas&&this.canvas.fire("text:changed",{target:this})},_removeCharsNearCursor:function(t){if(0!==this.selectionStart)if(t.metaKey){var e=this.findLineBoundaryLeft(this.selectionStart);this._removeCharsFromTo(e,this.selectionStart),this.setSelectionStart(e)}else if(t.altKey){var r=this.findWordBoundaryLeft(this.selectionStart);this._removeCharsFromTo(r,this.selectionStart),this.setSelectionStart(r)}else this._removeSingleCharAndStyle(this.selectionStart),this.setSelectionStart(this.selectionStart-1)}}),function(){var t=fabric.util.toFixed,e=fabric.Object.NUM_FRACTION_DIGITS;fabric.util.object.extend(fabric.Text.prototype,{toSVG:function(t){var e=this._createBaseSVGMarkup(),r=this._getSVGLeftTopOffsets(),i=this._getSVGTextAndBg(r.textTop,r.textLeft);return this._wrapSVGTextAndBg(e,i),t?t(e.join("")):e.join("")},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(t,e){var r=!0,i=this.getSvgFilter(),n=""===i?"":' style="'+i+'"';t.push("\t<g ",this.getSvgId(),'transform="',this.getSvgTransform(),this.getSvgTransformMatrix(),'"',n,">\n",e.textBgRects.join(""),'\t\t<text xml:space="preserve" ',this.fontFamily?'font-family="'+this.fontFamily.replace(/"/g,"'")+'" ':"",this.fontSize?'font-size="'+this.fontSize+'" ':"",this.fontStyle?'font-style="'+this.fontStyle+'" ':"",this.fontWeight?'font-weight="'+this.fontWeight+'" ':"",this.textDecoration?'text-decoration="'+this.textDecoration+'" ':"",'style="',this.getSvgStyles(!0),'" >\n',e.textSpans.join(""),"\t\t</text>\n","\t</g>\n")},_getSVGTextAndBg:function(t,e){var r=[],i=[],n=t,o;this._setSVGBg(i);for(var a=0,s=this._textLines.length;a<s;a++)o=this._getLineLeftOffset(a),(this.textBackgroundColor||this.styleHas("textBackgroundColor",a))&&this._setSVGTextLineBg(i,a,e+o,n),this._setSVGTextLineText(r,a,e+o,n),n+=this.getHeightOfLine(a);return{textSpans:r,textBgRects:i}},_createTextCharSpan:function(r,i,n,o){var a=this.getSvgSpanStyles(i,!1),s=a?'style="'+a+'"':"";return['\t\t\t<tspan x="',t(n,e),'" y="',t(o,e),'" ',s,">",fabric.util.string.escapeXml(r),"</tspan>\n"].join("")},_setSVGTextLineText:function(t,e,r,i){var n=this.getHeightOfLine(e),o,a,s="",c,l,h=0,u=this._textLines[e],f;i+=n*(1-this._fontSizeFraction)/this.lineHeight;for(var d=0,p=u.length-1;d<=p;d++)f=d===p||this.charSpacing,s+=u[d],c=this.__charBounds[e][d],0===h&&(r+=c.kernedWidth-c.width),h+=c.kernedWidth,"justify"!==this.textAlign||f||this._reSpaceAndTab.test(u[d])&&(f=!0),f||(o=o||this.getCompleteStyleDeclaration(e,d),a=this.getCompleteStyleDeclaration(e,d+1),f=this._hasStyleChanged(o,a)),f&&(l=this._getStyleDeclaration(e,d)||{},t.push(this._createTextCharSpan(s,l,r,i)),s="",o=a,r+=h,h=0)},_pushTextBgRect:function(r,i,n,o,a,s){r.push("\t\t<rect ",this._getFillAttributes(i),' x="',t(n,e),'" y="',t(o,e),'" width="',t(a,e),'" height="',t(s,e),'"></rect>\n')},_setSVGTextLineBg:function(t,e,r,i){for(var n=this._textLines[e],o=this.getHeightOfLine(e)/this.lineHeight,a=0,s=0,c,l,h=this.getValueOfPropertyAt(e,0,"textBackgroundColor"),u=0,f=n.length;u<f;u++)c=this.__charBounds[e][u],l=this.getValueOfPropertyAt(e,u,"textBackgroundColor"),l!==h?(h&&this._pushTextBgRect(t,h,r+s,i,a,o),s=c.left,a=c.width,h=l):a+=c.kernedWidth;l&&this._pushTextBgRect(t,l,r+s,i,a,o)},_getFillAttributes:function(t){var e=t&&"string"==typeof t?new fabric.Color(t):"";return e&&e.getSource()&&1!==e.getAlpha()?'opacity="'+e.getAlpha()+'" fill="'+e.setAlpha(1).toRgb()+'"':'fill="'+t+'"'},_getSVGLineTopOffset:function(t){for(var e=0,r=0,i=0;i<t;i++)e+=this.getHeightOfLine(i);return r=this.getHeightOfLine(i),{lineTop:e,offset:(this._fontSizeMult-this._fontSizeFraction)*r/(this.lineHeight*this._fontSizeMult)}},getSvgStyles:function(t){return fabric.Object.prototype.getSvgStyles.call(this,t)+" white-space: pre;"}})}(),function(t){"use strict";var e=t.fabric||(t.fabric={});e.Textbox=e.util.createClass(e.IText,e.Observable,{type:"textbox",minWidth:20,dynamicMinWidth:2,__cachedLines:null,lockScalingFlip:!0,noScaleCache:!1,initialize:function(t,r){this.callSuper("initialize",t,r),this.ctx=this.objectCaching?this._cacheContext:e.util.createCanvasElement().getContext("2d"),this._dimensionAffectingProps.push("width")},initDimensions:function(){if(!this.__skipDimension){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this._clearCache(),this.dynamicMinWidth=0;var t=this._splitTextIntoLines(this.text);this.textLines=t.lines,this._textLines=t.graphemeLines,this._unwrappedTextLines=t._unwrappedLines,this._text=t.graphemeText,this._styleMap=this._generateStyleMap(t),this.dynamicMinWidth>this.width&&this._set("width",this.dynamicMinWidth),"justify"===this.textAlign&&this.enlargeSpaces(),this.height=this.calcTextHeight()}},_generateStyleMap:function(t){for(var e=0,r=0,i=0,n={},o=0;o<t.graphemeLines.length;o++)"\n"===t.graphemeText[i]&&o>0?(r=0,i++,e++):this._reSpaceAndTab.test(t.graphemeText[i])&&o>0&&(r++,i++),n[o]={line:e,offset:r},i+=t.graphemeLines[o].length,r+=t.graphemeLines[o].length;return n},styleHas:function(t,r){if(this._styleMap&&!this.isWrapping){var i=this._styleMap[r];i&&(r=i.line)}return e.Text.prototype.styleHas.call(this,t,r)},_getStyleDeclaration:function(t,e){if(this._styleMap&&!this.isWrapping){var r=this._styleMap[t];if(!r)return null;t=r.line,e=r.offset+e}return this.callSuper("_getStyleDeclaration",t,e)},_setStyleDeclaration:function(t,e,r){var i=this._styleMap[t];t=i.line,e=i.offset+e,this.styles[t][e]=r},_deleteStyleDeclaration:function(t,e){var r=this._styleMap[t];t=r.line,e=r.offset+e,delete this.styles[t][e]},_getLineStyle:function(t){var e=this._styleMap[t];return this.styles[e.line]},_setLineStyle:function(t,e){var r=this._styleMap[t];this.styles[r.line]=e},_deleteLineStyle:function(t){var e=this._styleMap[t];delete this.styles[e.line]},_wrapText:function(t,e){var r=[],i;for(this.isWrapping=!0,i=0;i<t.length;i++)r=r.concat(this._wrapLine(t[i],i,e));return this.isWrapping=!1,r},_measureWord:function(t,e,r){var i=0,n,o=!0;r=r||0;for(var a=0,s=t.length;a<s;a++){i+=this._getGraphemeBox(t[a],e,a+r,n,!0).kernedWidth,n=t[a]}return i},_wrapLine:function(t,r,i){for(var n=0,o=[],a=[],s=t.split(this._reSpaceAndTab),c="",l=0,h=" ",u=0,f=0,d=0,p=!0,g=this._getWidthOfCharSpacing(),v=0;v<s.length;v++)c=e.util.string.graphemeSplit(s[v]),u=this._measureWord(c,r,l),l+=c.length,n+=f+u-g,n>=i&&!p&&(o.push(a),a=[],n=u,p=!0),p||a.push(" "),a=a.concat(c),f=this._measureWord([" "],r,l),l++,p=!1,u>d&&(d=u);return v&&o.push(a),d>this.dynamicMinWidth&&(this.dynamicMinWidth=d-g),o},_splitTextIntoLines:function(t){for(var r=e.Text.prototype._splitTextIntoLines.call(this,t),i=this._wrapText(r.lines,this.width),n=new Array(i.length),o=0;o<i.length;o++)n[o]=i[o].join("");return r.lines=n,r.graphemeLines=i,r},getMinWidth:function(){return Math.max(this.minWidth,this.dynamicMinWidth)},toObject:function(t){return this.callSuper("toObject",["minWidth"].concat(t))}}),e.Textbox.fromObject=function(t,r){return e.Object._fromObject("Textbox",t,r,"text")}}(exports),function(){var t=fabric.Canvas.prototype._setObjectScale;fabric.Canvas.prototype._setObjectScale=function(e,r,i,n,o,a,s){var c=r.target;if(!("x"===o&&c instanceof fabric.Textbox))return t.call(fabric.Canvas.prototype,e,r,i,n,o,a,s);var l=c._getTransformedDimensions().x,h=c.width*(e.x/l);return h>=c.getMinWidth()?(c.set("width",h),!0):void 0},fabric.util.object.extend(fabric.Textbox.prototype,{_removeExtraneousStyles:function(){for(var t in this._styleMap)this._textLines[t]||delete this.styles[this._styleMap[t].line]}})}(),function(){function request(t,e,r){var i=URL.parse(t);i.port||(i.port=0===i.protocol.indexOf("https:")?443:80);var n=0===i.protocol.indexOf("https:")?HTTPS:HTTP,o=n.request({hostname:i.hostname,port:i.port,path:i.path,method:"GET"},function(t){var i="";e&&t.setEncoding(e),t.on("end",function(){r(i)}),t.on("data",function(e){200===t.statusCode&&(i+=e)})});o.on("error",function(t){t.errno===process.ECONNREFUSED?fabric.log("ECONNREFUSED: connection refused to "+i.hostname+":"+i.port):fabric.log(t.message),r(null)}),o.end()}function requestFs(t,e){__webpack_require__(78).readFile(t,function(t,r){if(t)throw fabric.log(t),t;e(r)})}if("undefined"==typeof document||"undefined"==typeof window){var DOMParser=__webpack_require__(65).DOMParser,URL=__webpack_require__(25),HTTP=__webpack_require__(26),HTTPS=__webpack_require__(77),Canvas=!function t(){var e=new Error('Cannot find module "."');throw e.code="MODULE_NOT_FOUND",e}(),Image=!function t(){var e=new Error('Cannot find module "."');throw e.code="MODULE_NOT_FOUND",e}().Image;fabric.util.loadImage=function(t,e,r){function i(i){i?(n.src=new Buffer(i,"binary"),n._src=t,e&&e.call(r,n)):(n=null,e&&e.call(r,null,!0))}var n=new Image;t&&(t instanceof Buffer||0===t.indexOf("data"))?(n.src=n._src=t,e&&e.call(r,n)):t&&0!==t.indexOf("http")?requestFs(t,i):t?request(t,"binary",i):e&&e.call(r,t)},fabric.loadSVGFromURL=function(t,e,r){t=t.replace(/^\n\s*/,"").replace(/\?.*$/,"").trim(),0!==t.indexOf("http")?requestFs(t,function(t){fabric.loadSVGFromString(t.toString(),e,r)}):request(t,"",function(t){fabric.loadSVGFromString(t,e,r)})},fabric.loadSVGFromString=function(t,e,r){var i=(new DOMParser).parseFromString(t);fabric.parseSVGDocument(i.documentElement,function(t,r){e&&e(t,r)},r)},fabric.util.getScript=function(url,callback){request(url,"",function(body){eval(body),callback&&callback()})},fabric.createCanvasForNode=function(t,e,r,i){i=i||r;var n=fabric.document.createElement("canvas"),o=new Canvas(t||600,e||600,i),a=new Canvas(t||600,e||600,i);n.width=o.width,n.height=o.height,r=r||{},r.nodeCanvas=o,r.nodeCacheCanvas=a;var s=fabric.Canvas||fabric.StaticCanvas,c=new s(n,r);return c.nodeCanvas=o,c.nodeCacheCanvas=a,c.contextContainer=o.getContext("2d"),c.contextCache=a.getContext("2d"),c.Font=Canvas.Font,c};var originaInitStatic=fabric.StaticCanvas.prototype._initStatic;fabric.StaticCanvas.prototype._initStatic=function(t,e){t=t||fabric.document.createElement("canvas"),this.nodeCanvas=new Canvas(t.width,t.height),this.nodeCacheCanvas=new Canvas(t.width,t.height),originaInitStatic.call(this,t,e),this.contextContainer=this.nodeCanvas.getContext("2d"),this.contextCache=this.nodeCacheCanvas.getContext("2d"),this.Font=Canvas.Font},fabric.StaticCanvas.prototype.createPNGStream=function(){return this.nodeCanvas.createPNGStream()},fabric.StaticCanvas.prototype.createJPEGStream=function(t){return this.nodeCanvas.createJPEGStream(t)},fabric.StaticCanvas.prototype._initRetinaScaling=function(){if(this._isRetinaScaling())return this.lowerCanvasEl.setAttribute("width",this.width*fabric.devicePixelRatio),this.lowerCanvasEl.setAttribute("height",this.height*fabric.devicePixelRatio),this.nodeCanvas.width=this.width*fabric.devicePixelRatio,this.nodeCanvas.height=this.height*fabric.devicePixelRatio,this.contextContainer.scale(fabric.devicePixelRatio,fabric.devicePixelRatio),this},fabric.Canvas&&(fabric.Canvas.prototype._initRetinaScaling=fabric.StaticCanvas.prototype._initRetinaScaling);var origSetBackstoreDimension=fabric.StaticCanvas.prototype._setBackstoreDimension;fabric.StaticCanvas.prototype._setBackstoreDimension=function(t,e){return origSetBackstoreDimension.call(this,t,e),this.nodeCanvas[t]=e,this},fabric.Canvas&&(fabric.Canvas.prototype._setBackstoreDimension=fabric.StaticCanvas.prototype._setBackstoreDimension)}}()}).call(exports,__webpack_require__(2).Buffer,__webpack_require__(1))},function(t,e){},function(t,e){},function(t,e,r){(function(t,i){var n;!function(o){function a(t){throw new RangeError(I[t])}function s(t,e){for(var r=t.length,i=[];r--;)i[r]=e(t[r]);return i}function c(t,e){var r=t.split("@"),i="";return r.length>1&&(i=r[0]+"@",t=r[1]),t=t.replace(D,"."),i+s(t.split("."),e).join(".")}function l(t){for(var e=[],r=0,i=t.length,n,o;r<i;)n=t.charCodeAt(r++),n>=55296&&n<=56319&&r<i?(o=t.charCodeAt(r++),56320==(64512&o)?e.push(((1023&n)<<10)+(1023&o)+65536):(e.push(n),r--)):e.push(n);return e}function h(t){return s(t,function(t){var e="";return t>65535&&(t-=65536,e+=F(t>>>10&1023|55296),t=56320|1023&t),e+=F(t)}).join("")}function u(t){return t-48<10?t-22:t-65<26?t-65:t-97<26?t-97:x}function f(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function d(t,e,r){var i=0;for(t=r?M(t/k):t>>1,t+=M(t/e);t>j*A>>1;i+=x)t=M(t/j);return M(i+(j+1)*t/(t+T))}function p(t){var e=[],r=t.length,i,n=0,o=E,s=P,c,l,f,p,g,v,m,b,y;for(c=t.lastIndexOf(O),c<0&&(c=0),l=0;l<c;++l)t.charCodeAt(l)>=128&&a("not-basic"),e.push(t.charCodeAt(l));for(f=c>0?c+1:0;f<r;){for(p=n,g=1,v=x;f>=r&&a("invalid-input"),m=u(t.charCodeAt(f++)),(m>=x||m>M((S-n)/g))&&a("overflow"),n+=m*g,b=v<=s?C:v>=s+A?A:v-s,!(m<b);v+=x)y=x-b,g>M(S/y)&&a("overflow"),g*=y;i=e.length+1,s=d(n-p,i,0==p),M(n/i)>S-o&&a("overflow"),o+=M(n/i),n%=i,e.splice(n++,0,o)}return h(e)}function g(t){var e,r,i,n,o,s,c,h,u,p,g,v=[],m,b,y,_;for(t=l(t),m=t.length,e=E,r=0,o=P,s=0;s<m;++s)(g=t[s])<128&&v.push(F(g));for(i=n=v.length,n&&v.push(O);i<m;){for(c=S,s=0;s<m;++s)(g=t[s])>=e&&g<c&&(c=g);for(b=i+1,c-e>M((S-r)/b)&&a("overflow"),r+=(c-e)*b,e=c,s=0;s<m;++s)if(g=t[s],g<e&&++r>S&&a("overflow"),g==e){for(h=r,u=x;p=u<=o?C:u>=o+A?A:u-o,!(h<p);u+=x)_=h-p,y=x-p,v.push(F(f(p+_%y,0))),h=M(_/y);v.push(F(f(h,0))),o=d(r,b,i==n),r=0,++i}++r,++e}return v.join("")}function v(t){return c(t,function(t){return R.test(t)?p(t.slice(4).toLowerCase()):t})}function m(t){return c(t,function(t){return L.test(t)?"xn--"+g(t):t})}var b="object"==typeof e&&e&&!e.nodeType&&e,y="object"==typeof t&&t&&!t.nodeType&&t,_="object"==typeof i&&i;_.global!==_&&_.window!==_&&_.self!==_||(o=_);var w,S=2147483647,x=36,C=1,A=26,T=38,k=700,P=72,E=128,O="-",R=/^xn--/,L=/[^\x20-\x7E]/,D=/[\x2E\u3002\uFF0E\uFF61]/g,I={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},j=x-C,M=Math.floor,F=String.fromCharCode,N;w={version:"1.4.1",ucs2:{decode:l,encode:h},decode:p,encode:g,toASCII:m,toUnicode:v},void 0!==(n=function(){return w}.call(e,r,e,t))&&(t.exports=n)}(this)}).call(e,r(67)(t),r(0))},function(t,e){t.exports=function(t){return t.webpackPolyfill||(t.deprecate=function(){},t.paths=[],t.children||(t.children=[]),Object.defineProperty(t,"loaded",{enumerable:!0,get:function(){return t.l}}),Object.defineProperty(t,"id",{enumerable:!0,get:function(){return t.i}}),t.webpackPolyfill=1),t}},function(t,e,r){"use strict";t.exports={isString:function(t){return"string"==typeof t},isObject:function(t){return"object"==typeof t&&null!==t},isNull:function(t){return null===t},isNullOrUndefined:function(t){return null==t}}},function(t,e,r){"use strict";e.decode=e.parse=r(70),e.encode=e.stringify=r(71)},function(t,e,r){"use strict";function i(t,e){return Object.prototype.hasOwnProperty.call(t,e)}t.exports=function(t,e,r,o){e=e||"&",r=r||"=";var a={};if("string"!=typeof t||0===t.length)return a;var s=/\+/g;t=t.split(e);var c=1e3;o&&"number"==typeof o.maxKeys&&(c=o.maxKeys);var l=t.length;c>0&&l>c&&(l=c);for(var h=0;h<l;++h){var u=t[h].replace(s,"%20"),f=u.indexOf(r),d,p,g,v;f>=0?(d=u.substr(0,f),p=u.substr(f+1)):(d=u,p=""),g=decodeURIComponent(d),v=decodeURIComponent(p),i(a,g)?n(a[g])?a[g].push(v):a[g]=[a[g],v]:a[g]=v}return a};var n=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},function(t,e,r){"use strict";function i(t,e){if(t.map)return t.map(e);for(var r=[],i=0;i<t.length;i++)r.push(e(t[i],i));return r}var n=function(t){switch(typeof t){case"string":return t;case"boolean":return t?"true":"false";case"number":return isFinite(t)?t:"";default:return""}};t.exports=function(t,e,r,s){return e=e||"&",r=r||"=",null===t&&(t=void 0),"object"==typeof t?i(a(t),function(a){var s=encodeURIComponent(n(a))+r;return o(t[a])?i(t[a],function(t){return s+encodeURIComponent(n(t))}).join(e):s+encodeURIComponent(n(t[a]))}).join(e):s?encodeURIComponent(n(s))+r+encodeURIComponent(n(t)):""};var o=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)},a=Object.keys||function(t){var e=[];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.push(r);return e}},function(t,e,r){(function(e,i,n){function o(t,e){return s.fetch&&e?"fetch":s.mozchunkedarraybuffer?"moz-chunked-arraybuffer":s.msstream?"ms-stream":s.arraybuffer&&t?"arraybuffer":s.vbArray&&t?"text:vbarray":"text"}function a(t){try{var e=t.status;return null!==e&&0!==e}catch(t){return!1}}var s=r(27),c=r(3),l=r(73),h=r(9),u=r(74),f=l.IncomingMessage,d=l.readyStates,p=t.exports=function(t){var r=this;h.Writable.call(r),r._opts=t,r._body=[],r._headers={},t.auth&&r.setHeader("Authorization","Basic "+new e(t.auth).toString("base64")),Object.keys(t.headers).forEach(function(e){r.setHeader(e,t.headers[e])});var i,n=!0;if("disable-fetch"===t.mode||"timeout"in t)n=!1,i=!0;else if("prefer-streaming"===t.mode)i=!1;else if("allow-wrong-content-type"===t.mode)i=!s.overrideMimeType;else{if(t.mode&&"default"!==t.mode&&"prefer-fast"!==t.mode)throw new Error("Invalid value for opts.mode");i=!0}r._mode=o(i,n),r.on("finish",function(){r._onFinish()})};c(p,h.Writable),p.prototype.setHeader=function(t,e){var r=this,i=t.toLowerCase();-1===g.indexOf(i)&&(r._headers[i]={name:t,value:e})},p.prototype.getHeader=function(t){var e=this._headers[t.toLowerCase()];return e?e.value:null},p.prototype.removeHeader=function(t){delete this._headers[t.toLowerCase()]},p.prototype._onFinish=function(){var t=this;if(!t._destroyed){var r=t._opts,o=t._headers,a=null;"GET"!==r.method&&"HEAD"!==r.method&&(a=s.blobConstructor?new i.Blob(t._body.map(function(t){return u(t)}),{type:(o["content-type"]||{}).value||""}):e.concat(t._body).toString());var c=[];if(Object.keys(o).forEach(function(t){var e=o[t].name,r=o[t].value;Array.isArray(r)?r.forEach(function(t){c.push([e,t])}):c.push([e,r])}),"fetch"===t._mode)i.fetch(t._opts.url,{method:t._opts.method,headers:c,body:a||void 0,mode:"cors",credentials:r.withCredentials?"include":"same-origin"}).then(function(e){t._fetchResponse=e,t._connect()},function(e){t.emit("error",e)});else{var l=t._xhr=new i.XMLHttpRequest;try{l.open(t._opts.method,t._opts.url,!0)}catch(e){return void n.nextTick(function(){t.emit("error",e)})}"responseType"in l&&(l.responseType=t._mode.split(":")[0]),"withCredentials"in l&&(l.withCredentials=!!r.withCredentials),"text"===t._mode&&"overrideMimeType"in l&&l.overrideMimeType("text/plain; charset=x-user-defined"),"timeout"in r&&(l.timeout=r.timeout,l.ontimeout=function(){t.emit("timeout")}),c.forEach(function(t){l.setRequestHeader(t[0],t[1])}),t._response=null,l.onreadystatechange=function(){switch(l.readyState){case d.LOADING:case d.DONE:t._onXHRProgress()}},"moz-chunked-arraybuffer"===t._mode&&(l.onprogress=function(){t._onXHRProgress()}),l.onerror=function(){t._destroyed||t.emit("error",new Error("XHR error"))};try{l.send(a)}catch(e){return void n.nextTick(function(){t.emit("error",e)})}}}},p.prototype._onXHRProgress=function(){var t=this;a(t._xhr)&&!t._destroyed&&(t._response||t._connect(),t._response._onXHRProgress())},p.prototype._connect=function(){var t=this;t._destroyed||(t._response=new f(t._xhr,t._fetchResponse,t._mode),t._response.on("error",function(e){t.emit("error",e)}),t.emit("response",t._response))},p.prototype._write=function(t,e,r){this._body.push(t),r()},p.prototype.abort=p.prototype.destroy=function(){var t=this;t._destroyed=!0,t._response&&(t._response._destroyed=!0),t._xhr&&t._xhr.abort()},p.prototype.end=function(t,e,r){var i=this;"function"==typeof t&&(r=t,t=void 0),h.Writable.prototype.end.call(i,t,e,r)},p.prototype.flushHeaders=function(){},p.prototype.setTimeout=function(){},p.prototype.setNoDelay=function(){},p.prototype.setSocketKeepAlive=function(){};var g=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","user-agent","via"]}).call(e,r(2).Buffer,r(0),r(1))},function(t,e,r){(function(t,i,n){var o=r(27),a=r(3),s=r(9),c=e.readyStates={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4},l=e.IncomingMessage=function(e,r,n){function a(){l.read().then(function(t){if(!c._destroyed){if(t.done)return void c.push(null);c.push(new i(t.value)),a()}}).catch(function(t){c.emit("error",t)})}var c=this;if(s.Readable.call(c),c._mode=n,c.headers={},c.rawHeaders=[],c.trailers={},c.rawTrailers=[],c.on("end",function(){t.nextTick(function(){c.emit("close")})}),"fetch"===n){c._fetchResponse=r,c.url=r.url,c.statusCode=r.status,c.statusMessage=r.statusText,r.headers.forEach(function(t,e){c.headers[e.toLowerCase()]=t,c.rawHeaders.push(e,t)});var l=r.body.getReader();a()}else{c._xhr=e,c._pos=0,c.url=e.responseURL,c.statusCode=e.status,c.statusMessage=e.statusText;if(e.getAllResponseHeaders().split(/\r?\n/).forEach(function(t){var e=t.match(/^([^:]+):\s*(.*)/);if(e){var r=e[1].toLowerCase();"set-cookie"===r?(void 0===c.headers[r]&&(c.headers[r]=[]),c.headers[r].push(e[2])):void 0!==c.headers[r]?c.headers[r]+=", "+e[2]:c.headers[r]=e[2],c.rawHeaders.push(e[1],e[2])}}),c._charset="x-user-defined",!o.overrideMimeType){var h=c.rawHeaders["mime-type"];if(h){var u=h.match(/;\s*charset=([^;])(;|$)/);u&&(c._charset=u[1].toLowerCase())}c._charset||(c._charset="utf-8")}}};a(l,s.Readable),l.prototype._read=function(){},l.prototype._onXHRProgress=function(){var t=this,e=t._xhr,r=null;switch(t._mode){case"text:vbarray":if(e.readyState!==c.DONE)break;try{r=new n.VBArray(e.responseBody).toArray()}catch(t){}if(null!==r){t.push(new i(r));break}case"text":try{r=e.responseText}catch(e){t._mode="text:vbarray";break}if(r.length>t._pos){var o=r.substr(t._pos);if("x-user-defined"===t._charset){for(var a=new i(o.length),s=0;s<o.length;s++)a[s]=255&o.charCodeAt(s);t.push(a)}else t.push(o,t._charset);t._pos=r.length}break;case"arraybuffer":if(e.readyState!==c.DONE||!e.response)break;r=e.response,t.push(new i(new Uint8Array(r)));break;case"moz-chunked-arraybuffer":if(r=e.response,e.readyState!==c.LOADING||!r)break;t.push(new i(new Uint8Array(r)));break;case"ms-stream":if(r=e.response,e.readyState!==c.LOADING)break;var l=new n.MSStreamReader;l.onprogress=function(){l.result.byteLength>t._pos&&(t.push(new i(new Uint8Array(l.result.slice(t._pos)))),t._pos=l.result.byteLength)},l.onload=function(){t.push(null)},l.readAsArrayBuffer(r)}t._xhr.readyState===c.DONE&&"ms-stream"!==t._mode&&t.push(null)}}).call(e,r(1),r(2).Buffer,r(0))},function(t,e,r){var i=r(2).Buffer;t.exports=function(t){if(t instanceof Uint8Array){if(0===t.byteOffset&&t.byteLength===t.buffer.byteLength)return t.buffer;if("function"==typeof t.buffer.slice)return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}if(i.isBuffer(t)){for(var e=new Uint8Array(t.length),r=t.length,n=0;n<r;n++)e[n]=t[n];return e.buffer}throw new Error("Argument must be a Buffer")}},function(t,e){function r(){for(var t={},e=0;e<arguments.length;e++){var r=arguments[e];for(var n in r)i.call(r,n)&&(t[n]=r[n])}return t}t.exports=r;var i=Object.prototype.hasOwnProperty},function(t,e){t.exports={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"}},function(t,e,r){var i=r(26),n=t.exports;for(var o in i)i.hasOwnProperty(o)&&(n[o]=i[o]);n.request=function(t,e){return t||(t={}),t.scheme="https",t.protocol="https:",i.request.call(this,t,e)}},function(t,e){},function(t,e,r){"use strict";function i(){}function n(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function o(){this._events=new i,this._eventsCount=0}var a=Object.prototype.hasOwnProperty,s="~";Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(s=!1)),o.prototype.eventNames=function t(){var e=[],r,i;if(0===this._eventsCount)return e;for(i in r=this._events)a.call(r,i)&&e.push(s?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e},o.prototype.listeners=function t(e,r){var i=s?s+e:e,n=this._events[i];if(r)return!!n;if(!n)return[];if(n.fn)return[n.fn];for(var o=0,a=n.length,c=new Array(a);o<a;o++)c[o]=n[o].fn;return c},o.prototype.emit=function t(e,r,i,n,o,a){var c=s?s+e:e;if(!this._events[c])return!1;var l=this._events[c],h=arguments.length,u,f;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),h){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,r),!0;case 3:return l.fn.call(l.context,r,i),!0;case 4:return l.fn.call(l.context,r,i,n),!0;case 5:return l.fn.call(l.context,r,i,n,o),!0;case 6:return l.fn.call(l.context,r,i,n,o,a),!0}for(f=1,u=new Array(h-1);f<h;f++)u[f-1]=arguments[f];l.fn.apply(l.context,u)}else{var d=l.length,p;for(f=0;f<d;f++)switch(l[f].once&&this.removeListener(e,l[f].fn,void 0,!0),h){case 1:l[f].fn.call(l[f].context);break;case 2:l[f].fn.call(l[f].context,r);break;case 3:l[f].fn.call(l[f].context,r,i);break;case 4:l[f].fn.call(l[f].context,r,i,n);break;default:if(!u)for(p=1,u=new Array(h-1);p<h;p++)u[p-1]=arguments[p];l[f].fn.apply(l[f].context,u)}}return!0},o.prototype.on=function t(e,r,i){var o=new n(r,i||this),a=s?s+e:e;return this._events[a]?this._events[a].fn?this._events[a]=[this._events[a],o]:this._events[a].push(o):(this._events[a]=o,this._eventsCount++),this},o.prototype.once=function t(e,r,i){var o=new n(r,i||this,!0),a=s?s+e:e;return this._events[a]?this._events[a].fn?this._events[a]=[this._events[a],o]:this._events[a].push(o):(this._events[a]=o,this._eventsCount++),this},o.prototype.removeListener=function t(e,r,n,o){var a=s?s+e:e;if(!this._events[a])return this;if(!r)return 0==--this._eventsCount?this._events=new i:delete this._events[a],this;var c=this._events[a];if(c.fn)c.fn!==r||o&&!c.once||n&&c.context!==n||(0==--this._eventsCount?this._events=new i:delete this._events[a]);else{for(var l=0,h=[],u=c.length;l<u;l++)(c[l].fn!==r||o&&!c[l].once||n&&c[l].context!==n)&&h.push(c[l]);h.length?this._events[a]=1===h.length?h[0]:h:0==--this._eventsCount?this._events=new i:delete this._events[a]}return this},o.prototype.removeAllListeners=function t(e){var r;return e?(r=s?s+e:e,this._events[r]&&(0==--this._eventsCount?this._events=new i:delete this._events[r])):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prototype.setMaxListeners=function t(){return this},o.prefixed=s,o.EventEmitter=o,t.exports=o},function(t,e,r){"use strict";function i(t){var e=0,r=0,i=0,s=0;return"detail"in t&&(r=t.detail),"wheelDelta"in t&&(r=-t.wheelDelta/120),"wheelDeltaY"in t&&(r=-t.wheelDeltaY/120),"wheelDeltaX"in t&&(e=-t.wheelDeltaX/120),"axis"in t&&t.axis===t.HORIZONTAL_AXIS&&(e=r,r=0),i=e*n,s=r*n,"deltaY"in t&&(s=t.deltaY),"deltaX"in t&&(i=t.deltaX),(i||s)&&t.deltaMode&&(1==t.deltaMode?(i*=o,s*=o):(i*=a,s*=a)),i&&!e&&(e=i<1?-1:1),s&&!r&&(r=s<1?-1:1),{spinX:e,spinY:r,pixelX:i,pixelY:s}}var n=10,o=40,a=800;t.exports=i}])});
dist/bundle.min.js
!function t(e,r){"object"==typeof exports&&"object"==typeof module?module.exports=r():"function"==typeof define&&define.amd?define("bundle",[],r):"object"==typeof exports?exports.bundle=r():e.bundle=r()}(this,function(){return function(t){function e(r){if(i[r])return i[r].exports;var n=i[r]={i:r,l:!1,exports:{}};return t[r].call(n.exports,n,n.exports,e),n.l=!0,n.exports}var r=window.webpackJsonpbundle;window.webpackJsonpbundle=function e(i,o,a){for(var s,c,l=0,h=[],u;l<i.length;l++)c=i[l],n[c]&&h.push(n[c][0]),n[c]=0;for(s in o)Object.prototype.hasOwnProperty.call(o,s)&&(t[s]=o[s]);for(r&&r(i,o,a);h.length;)h.shift()()};var i={},n={1:0};return e.e=function t(r){function i(){c.onerror=c.onload=null,clearTimeout(l);var t=n[r];0!==t&&(t&&t[1](new Error("Loading chunk "+r+" failed.")),n[r]=void 0)}var o=n[r];if(0===o)return new Promise(function(t){t()});if(o)return o[2];var a=new Promise(function(t,e){o=n[r]=[t,e]});o[2]=a;var s=document.getElementsByTagName("head")[0],c=document.createElement("script");c.type="text/javascript",c.charset="utf-8",c.async=!0,c.timeout=12e4,e.nc&&c.setAttribute("nonce",e.nc),c.src=e.p+""+r+".bundle.min.js";var l=setTimeout(i,12e4);return c.onerror=c.onload=i,s.appendChild(c),a},e.m=t,e.c=i,e.d=function(t,r,i){e.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var r=t&&t.__esModule?function e(){return t.default}:function e(){return t};return e.d(r,"a",r),r},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e.oe=function(t){throw console.error(t),t},e(e.s=29)}([function(t,e){var r;r=function(){return this}();try{r=r||Function("return this")()||(0,eval)("this")}catch(t){"object"==typeof window&&(r=window)}t.exports=r},function(t,e){function r(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}function n(t){if(u===setTimeout)return setTimeout(t,0);if((u===r||!u)&&setTimeout)return u=setTimeout,setTimeout(t,0);try{return u(t,0)}catch(e){try{return u.call(null,t,0)}catch(e){return u.call(this,t,0)}}}function o(t){if(f===clearTimeout)return clearTimeout(t);if((f===i||!f)&&clearTimeout)return f=clearTimeout,clearTimeout(t);try{return f(t)}catch(e){try{return f.call(null,t)}catch(e){return f.call(this,t)}}}function a(){p&&g&&(p=!1,g.length?d=g.concat(d):v=-1,d.length&&s())}function s(){if(!p){var t=n(a);p=!0;for(var e=d.length;e;){for(g=d,d=[];++v<e;)g&&g[v].run();v=-1,e=d.length}g=null,p=!1,o(t)}}function c(t,e){this.fun=t,this.array=e}function l(){}var h=t.exports={},u,f;!function(){try{u="function"==typeof setTimeout?setTimeout:r}catch(t){u=r}try{f="function"==typeof clearTimeout?clearTimeout:i}catch(t){f=i}}();var d=[],p=!1,g,v=-1;h.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)e[r-1]=arguments[r];d.push(new c(t,e)),1!==d.length||p||n(s)},c.prototype.run=function(){this.fun.apply(null,this.array)},h.title="browser",h.browser=!0,h.env={},h.argv=[],h.version="",h.versions={},h.on=l,h.addListener=l,h.once=l,h.off=l,h.removeListener=l,h.removeAllListeners=l,h.emit=l,h.prependListener=l,h.prependOnceListener=l,h.listeners=function(t){return[]},h.binding=function(t){throw new Error("process.binding is not supported")},h.cwd=function(){return"/"},h.chdir=function(t){throw new Error("process.chdir is not supported")},h.umask=function(){return 0}},function(t,e,r){"use strict";(function(t){function i(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===t.foo()&&"function"==typeof t.subarray&&0===t.subarray(1,1).byteLength}catch(t){return!1}}function n(){return a.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function o(t,e){if(n()<e)throw new RangeError("Invalid typed array length");return a.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e),t.__proto__=a.prototype):(null===t&&(t=new a(e)),t.length=e),t}function a(t,e,r){if(!(a.TYPED_ARRAY_SUPPORT||this instanceof a))return new a(t,e,r);if("number"==typeof t){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a string");return h(this,t)}return s(this,t,e,r)}function s(t,e,r,i){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer?d(t,e,r,i):"string"==typeof e?u(t,e,r):p(t,e)}function c(t){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative')}function l(t,e,r,i){return c(e),e<=0?o(t,e):void 0!==r?"string"==typeof i?o(t,e).fill(r,i):o(t,e).fill(r):o(t,e)}function h(t,e){if(c(e),t=o(t,e<0?0:0|g(e)),!a.TYPED_ARRAY_SUPPORT)for(var r=0;r<e;++r)t[r]=0;return t}function u(t,e,r){if("string"==typeof r&&""!==r||(r="utf8"),!a.isEncoding(r))throw new TypeError('"encoding" must be a valid string encoding');var i=0|m(e,r);t=o(t,i);var n=t.write(e,r);return n!==i&&(t=t.slice(0,n)),t}function f(t,e){var r=e.length<0?0:0|g(e.length);t=o(t,r);for(var i=0;i<r;i+=1)t[i]=255&e[i];return t}function d(t,e,r,i){if(e.byteLength,r<0||e.byteLength<r)throw new RangeError("'offset' is out of bounds");if(e.byteLength<r+(i||0))throw new RangeError("'length' is out of bounds");return e=void 0===r&&void 0===i?new Uint8Array(e):void 0===i?new Uint8Array(e,r):new Uint8Array(e,r,i),a.TYPED_ARRAY_SUPPORT?(t=e,t.__proto__=a.prototype):t=f(t,e),t}function p(t,e){if(a.isBuffer(e)){var r=0|g(e.length);return t=o(t,r),0===t.length?t:(e.copy(t,0,0,r),t)}if(e){if("undefined"!=typeof ArrayBuffer&&e.buffer instanceof ArrayBuffer||"length"in e)return"number"!=typeof e.length||J(e.length)?o(t,0):f(t,e);if("Buffer"===e.type&&$(e.data))return f(t,e.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function g(t){if(t>=n())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+n().toString(16)+" bytes");return 0|t}function v(t){return+t!=t&&(t=0),a.alloc(+t)}function m(t,e){if(a.isBuffer(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var i=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return G(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return V(t).length;default:if(i)return G(t).length;e=(""+e).toLowerCase(),i=!0}}function b(t,e,r){var i=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if(r>>>=0,e>>>=0,r<=e)return"";for(t||(t="utf8");;)switch(t){case"hex":return D(this,e,r);case"utf8":case"utf-8":return E(this,e,r);case"ascii":return R(this,e,r);case"latin1":case"binary":return L(this,e,r);case"base64":return P(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,e,r);default:if(i)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),i=!0}}function y(t,e,r){var i=t[e];t[e]=t[r],t[r]=i}function _(t,e,r,i,n){if(0===t.length)return-1;if("string"==typeof r?(i=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=n?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(n)return-1;r=t.length-1}else if(r<0){if(!n)return-1;r=0}if("string"==typeof e&&(e=a.from(e,i)),a.isBuffer(e))return 0===e.length?-1:w(t,e,r,i,n);if("number"==typeof e)return e&=255,a.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?n?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):w(t,[e],r,i,n);throw new TypeError("val must be string, number or Buffer")}function w(t,e,r,i,n){function o(t,e){return 1===a?t[e]:t.readUInt16BE(e*a)}var a=1,s=t.length,c=e.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(t.length<2||e.length<2)return-1;a=2,s/=2,c/=2,r/=2}var l;if(n){var h=-1;for(l=r;l<s;l++)if(o(t,l)===o(e,-1===h?0:l-h)){if(-1===h&&(h=l),l-h+1===c)return h*a}else-1!==h&&(l-=l-h),h=-1}else for(r+c>s&&(r=s-c),l=r;l>=0;l--){for(var u=!0,f=0;f<c;f++)if(o(t,l+f)!==o(e,f)){u=!1;break}if(u)return l}return-1}function S(t,e,r,i){r=Number(r)||0;var n=t.length-r;i?(i=Number(i))>n&&(i=n):i=n;var o=e.length;if(o%2!=0)throw new TypeError("Invalid hex string");i>o/2&&(i=o/2);for(var a=0;a<i;++a){var s=parseInt(e.substr(2*a,2),16);if(isNaN(s))return a;t[r+a]=s}return a}function x(t,e,r,i){return Z(G(e,t.length-r),t,r,i)}function C(t,e,r,i){return Z(H(e),t,r,i)}function A(t,e,r,i){return C(t,e,r,i)}function T(t,e,r,i){return Z(V(e),t,r,i)}function k(t,e,r,i){return Z(Y(e,t.length-r),t,r,i)}function P(t,e,r){return 0===e&&r===t.length?K.fromByteArray(t):K.fromByteArray(t.slice(e,r))}function E(t,e,r){r=Math.min(t.length,r);for(var i=[],n=e;n<r;){var o=t[n],a=null,s=o>239?4:o>223?3:o>191?2:1;if(n+s<=r){var c,l,h,u;switch(s){case 1:o<128&&(a=o);break;case 2:c=t[n+1],128==(192&c)&&(u=(31&o)<<6|63&c)>127&&(a=u);break;case 3:c=t[n+1],l=t[n+2],128==(192&c)&&128==(192&l)&&(u=(15&o)<<12|(63&c)<<6|63&l)>2047&&(u<55296||u>57343)&&(a=u);break;case 4:c=t[n+1],l=t[n+2],h=t[n+3],128==(192&c)&&128==(192&l)&&128==(192&h)&&(u=(15&o)<<18|(63&c)<<12|(63&l)<<6|63&h)>65535&&u<1114112&&(a=u)}}null===a?(a=65533,s=1):a>65535&&(a-=65536,i.push(a>>>10&1023|55296),a=56320|1023&a),i.push(a),n+=s}return O(i)}function O(t){var e=t.length;if(e<=tt)return String.fromCharCode.apply(String,t);for(var r="",i=0;i<e;)r+=String.fromCharCode.apply(String,t.slice(i,i+=tt));return r}function R(t,e,r){var i="";r=Math.min(t.length,r);for(var n=e;n<r;++n)i+=String.fromCharCode(127&t[n]);return i}function L(t,e,r){var i="";r=Math.min(t.length,r);for(var n=e;n<r;++n)i+=String.fromCharCode(t[n]);return i}function D(t,e,r){var i=t.length;(!e||e<0)&&(e=0),(!r||r<0||r>i)&&(r=i);for(var n="",o=e;o<r;++o)n+=X(t[o]);return n}function I(t,e,r){for(var i=t.slice(e,r),n="",o=0;o<i.length;o+=2)n+=String.fromCharCode(i[o]+256*i[o+1]);return n}function j(t,e,r){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}function M(t,e,r,i,n,o){if(!a.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>n||e<o)throw new RangeError('"value" argument is out of bounds');if(r+i>t.length)throw new RangeError("Index out of range")}function F(t,e,r,i){e<0&&(e=65535+e+1);for(var n=0,o=Math.min(t.length-r,2);n<o;++n)t[r+n]=(e&255<<8*(i?n:1-n))>>>8*(i?n:1-n)}function N(t,e,r,i){e<0&&(e=4294967295+e+1);for(var n=0,o=Math.min(t.length-r,4);n<o;++n)t[r+n]=e>>>8*(i?n:3-n)&255}function B(t,e,r,i,n,o){if(r+i>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function U(t,e,r,i,n){return n||B(t,e,r,4,3.4028234663852886e38,-3.4028234663852886e38),Q.write(t,e,r,i,23,4),r+4}function z(t,e,r,i,n){return n||B(t,e,r,8,1.7976931348623157e308,-1.7976931348623157e308),Q.write(t,e,r,i,52,8),r+8}function W(t){if(t=q(t).replace(et,""),t.length<2)return"";for(;t.length%4!=0;)t+="=";return t}function q(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function X(t){return t<16?"0"+t.toString(16):t.toString(16)}function G(t,e){e=e||1/0;for(var r,i=t.length,n=null,o=[],a=0;a<i;++a){if((r=t.charCodeAt(a))>55295&&r<57344){if(!n){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(a+1===i){(e-=3)>-1&&o.push(239,191,189);continue}n=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),n=r;continue}r=65536+(n-55296<<10|r-56320)}else n&&(e-=3)>-1&&o.push(239,191,189);if(n=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function H(t){for(var e=[],r=0;r<t.length;++r)e.push(255&t.charCodeAt(r));return e}function Y(t,e){for(var r,i,n,o=[],a=0;a<t.length&&!((e-=2)<0);++a)r=t.charCodeAt(a),i=r>>8,n=r%256,o.push(n),o.push(i);return o}function V(t){return K.toByteArray(W(t))}function Z(t,e,r,i){for(var n=0;n<i&&!(n+r>=e.length||n>=t.length);++n)e[n+r]=t[n];return n}function J(t){return t!==t}/*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <[email protected]> <http://feross.org> * @license MIT */ var K=r(40),Q=r(41),$=r(13);e.Buffer=a,e.SlowBuffer=v,e.INSPECT_MAX_BYTES=50,a.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:i(),e.kMaxLength=n(),a.poolSize=8192,a._augment=function(t){return t.__proto__=a.prototype,t},a.from=function(t,e,r){return s(null,t,e,r)},a.TYPED_ARRAY_SUPPORT&&(a.prototype.__proto__=Uint8Array.prototype,a.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&a[Symbol.species]===a&&Object.defineProperty(a,Symbol.species,{value:null,configurable:!0})),a.alloc=function(t,e,r){return l(null,t,e,r)},a.allocUnsafe=function(t){return h(null,t)},a.allocUnsafeSlow=function(t){return h(null,t)},a.isBuffer=function t(e){return!(null==e||!e._isBuffer)},a.compare=function t(e,r){if(!a.isBuffer(e)||!a.isBuffer(r))throw new TypeError("Arguments must be Buffers");if(e===r)return 0;for(var i=e.length,n=r.length,o=0,s=Math.min(i,n);o<s;++o)if(e[o]!==r[o]){i=e[o],n=r[o];break}return i<n?-1:n<i?1:0},a.isEncoding=function t(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function t(e,r){if(!$(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return a.alloc(0);var i;if(void 0===r)for(r=0,i=0;i<e.length;++i)r+=e[i].length;var n=a.allocUnsafe(r),o=0;for(i=0;i<e.length;++i){var s=e[i];if(!a.isBuffer(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(n,o),o+=s.length}return n},a.byteLength=m,a.prototype._isBuffer=!0,a.prototype.swap16=function t(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var r=0;r<e;r+=2)y(this,r,r+1);return this},a.prototype.swap32=function t(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var r=0;r<e;r+=4)y(this,r,r+3),y(this,r+1,r+2);return this},a.prototype.swap64=function t(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var r=0;r<e;r+=8)y(this,r,r+7),y(this,r+1,r+6),y(this,r+2,r+5),y(this,r+3,r+4);return this},a.prototype.toString=function t(){var e=0|this.length;return 0===e?"":0===arguments.length?E(this,0,e):b.apply(this,arguments)},a.prototype.equals=function t(e){if(!a.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===a.compare(this,e)},a.prototype.inspect=function t(){var r="",i=e.INSPECT_MAX_BYTES;return this.length>0&&(r=this.toString("hex",0,i).match(/.{2}/g).join(" "),this.length>i&&(r+=" ... ")),"<Buffer "+r+">"},a.prototype.compare=function t(e,r,i,n,o){if(!a.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===r&&(r=0),void 0===i&&(i=e?e.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),r<0||i>e.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&r>=i)return 0;if(n>=o)return-1;if(r>=i)return 1;if(r>>>=0,i>>>=0,n>>>=0,o>>>=0,this===e)return 0;for(var s=o-n,c=i-r,l=Math.min(s,c),h=this.slice(n,o),u=e.slice(r,i),f=0;f<l;++f)if(h[f]!==u[f]){s=h[f],c=u[f];break}return s<c?-1:c<s?1:0},a.prototype.includes=function t(e,r,i){return-1!==this.indexOf(e,r,i)},a.prototype.indexOf=function t(e,r,i){return _(this,e,r,i,!0)},a.prototype.lastIndexOf=function t(e,r,i){return _(this,e,r,i,!1)},a.prototype.write=function t(e,r,i,n){if(void 0===r)n="utf8",i=this.length,r=0;else if(void 0===i&&"string"==typeof r)n=r,i=this.length,r=0;else{if(!isFinite(r))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");r|=0,isFinite(i)?(i|=0,void 0===n&&(n="utf8")):(n=i,i=void 0)}var o=this.length-r;if((void 0===i||i>o)&&(i=o),e.length>0&&(i<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var a=!1;;)switch(n){case"hex":return S(this,e,r,i);case"utf8":case"utf-8":return x(this,e,r,i);case"ascii":return C(this,e,r,i);case"latin1":case"binary":return A(this,e,r,i);case"base64":return T(this,e,r,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,e,r,i);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},a.prototype.toJSON=function t(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var tt=4096;a.prototype.slice=function t(e,r){var i=this.length;e=~~e,r=void 0===r?i:~~r,e<0?(e+=i)<0&&(e=0):e>i&&(e=i),r<0?(r+=i)<0&&(r=0):r>i&&(r=i),r<e&&(r=e);var n;if(a.TYPED_ARRAY_SUPPORT)n=this.subarray(e,r),n.__proto__=a.prototype;else{var o=r-e;n=new a(o,void 0);for(var s=0;s<o;++s)n[s]=this[s+e]}return n},a.prototype.readUIntLE=function t(e,r,i){e|=0,r|=0,i||j(e,r,this.length);for(var n=this[e],o=1,a=0;++a<r&&(o*=256);)n+=this[e+a]*o;return n},a.prototype.readUIntBE=function t(e,r,i){e|=0,r|=0,i||j(e,r,this.length);for(var n=this[e+--r],o=1;r>0&&(o*=256);)n+=this[e+--r]*o;return n},a.prototype.readUInt8=function t(e,r){return r||j(e,1,this.length),this[e]},a.prototype.readUInt16LE=function t(e,r){return r||j(e,2,this.length),this[e]|this[e+1]<<8},a.prototype.readUInt16BE=function t(e,r){return r||j(e,2,this.length),this[e]<<8|this[e+1]},a.prototype.readUInt32LE=function t(e,r){return r||j(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},a.prototype.readUInt32BE=function t(e,r){return r||j(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},a.prototype.readIntLE=function t(e,r,i){e|=0,r|=0,i||j(e,r,this.length);for(var n=this[e],o=1,a=0;++a<r&&(o*=256);)n+=this[e+a]*o;return o*=128,n>=o&&(n-=Math.pow(2,8*r)),n},a.prototype.readIntBE=function t(e,r,i){e|=0,r|=0,i||j(e,r,this.length);for(var n=r,o=1,a=this[e+--n];n>0&&(o*=256);)a+=this[e+--n]*o;return o*=128,a>=o&&(a-=Math.pow(2,8*r)),a},a.prototype.readInt8=function t(e,r){return r||j(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},a.prototype.readInt16LE=function t(e,r){r||j(e,2,this.length);var i=this[e]|this[e+1]<<8;return 32768&i?4294901760|i:i},a.prototype.readInt16BE=function t(e,r){r||j(e,2,this.length);var i=this[e+1]|this[e]<<8;return 32768&i?4294901760|i:i},a.prototype.readInt32LE=function t(e,r){return r||j(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},a.prototype.readInt32BE=function t(e,r){return r||j(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},a.prototype.readFloatLE=function t(e,r){return r||j(e,4,this.length),Q.read(this,e,!0,23,4)},a.prototype.readFloatBE=function t(e,r){return r||j(e,4,this.length),Q.read(this,e,!1,23,4)},a.prototype.readDoubleLE=function t(e,r){return r||j(e,8,this.length),Q.read(this,e,!0,52,8)},a.prototype.readDoubleBE=function t(e,r){return r||j(e,8,this.length),Q.read(this,e,!1,52,8)},a.prototype.writeUIntLE=function t(e,r,i,n){if(e=+e,r|=0,i|=0,!n){M(this,e,r,i,Math.pow(2,8*i)-1,0)}var o=1,a=0;for(this[r]=255&e;++a<i&&(o*=256);)this[r+a]=e/o&255;return r+i},a.prototype.writeUIntBE=function t(e,r,i,n){if(e=+e,r|=0,i|=0,!n){M(this,e,r,i,Math.pow(2,8*i)-1,0)}var o=i-1,a=1;for(this[r+o]=255&e;--o>=0&&(a*=256);)this[r+o]=e/a&255;return r+i},a.prototype.writeUInt8=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,1,255,0),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[r]=255&e,r+1},a.prototype.writeUInt16LE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[r]=255&e,this[r+1]=e>>>8):F(this,e,r,!0),r+2},a.prototype.writeUInt16BE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[r]=e>>>8,this[r+1]=255&e):F(this,e,r,!1),r+2},a.prototype.writeUInt32LE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=255&e):N(this,e,r,!0),r+4},a.prototype.writeUInt32BE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=255&e):N(this,e,r,!1),r+4},a.prototype.writeIntLE=function t(e,r,i,n){if(e=+e,r|=0,!n){var o=Math.pow(2,8*i-1);M(this,e,r,i,o-1,-o)}var a=0,s=1,c=0;for(this[r]=255&e;++a<i&&(s*=256);)e<0&&0===c&&0!==this[r+a-1]&&(c=1),this[r+a]=(e/s>>0)-c&255;return r+i},a.prototype.writeIntBE=function t(e,r,i,n){if(e=+e,r|=0,!n){var o=Math.pow(2,8*i-1);M(this,e,r,i,o-1,-o)}var a=i-1,s=1,c=0;for(this[r+a]=255&e;--a>=0&&(s*=256);)e<0&&0===c&&0!==this[r+a+1]&&(c=1),this[r+a]=(e/s>>0)-c&255;return r+i},a.prototype.writeInt8=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,1,127,-128),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[r]=255&e,r+1},a.prototype.writeInt16LE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[r]=255&e,this[r+1]=e>>>8):F(this,e,r,!0),r+2},a.prototype.writeInt16BE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[r]=e>>>8,this[r+1]=255&e):F(this,e,r,!1),r+2},a.prototype.writeInt32LE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,4,2147483647,-2147483648),a.TYPED_ARRAY_SUPPORT?(this[r]=255&e,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24):N(this,e,r,!0),r+4},a.prototype.writeInt32BE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),a.TYPED_ARRAY_SUPPORT?(this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=255&e):N(this,e,r,!1),r+4},a.prototype.writeFloatLE=function t(e,r,i){return U(this,e,r,!0,i)},a.prototype.writeFloatBE=function t(e,r,i){return U(this,e,r,!1,i)},a.prototype.writeDoubleLE=function t(e,r,i){return z(this,e,r,!0,i)},a.prototype.writeDoubleBE=function t(e,r,i){return z(this,e,r,!1,i)},a.prototype.copy=function t(e,r,i,n){if(i||(i=0),n||0===n||(n=this.length),r>=e.length&&(r=e.length),r||(r=0),n>0&&n<i&&(n=i),n===i)return 0;if(0===e.length||0===this.length)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(i<0||i>=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-r<n-i&&(n=e.length-r+i);var o=n-i,s;if(this===e&&i<r&&r<n)for(s=o-1;s>=0;--s)e[s+r]=this[s+i];else if(o<1e3||!a.TYPED_ARRAY_SUPPORT)for(s=0;s<o;++s)e[s+r]=this[s+i];else Uint8Array.prototype.set.call(e,this.subarray(i,i+o),r);return o},a.prototype.fill=function t(e,r,i,n){if("string"==typeof e){if("string"==typeof r?(n=r,r=0,i=this.length):"string"==typeof i&&(n=i,i=this.length),1===e.length){var o=e.charCodeAt(0);o<256&&(e=o)}if(void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!a.isEncoding(n))throw new TypeError("Unknown encoding: "+n)}else"number"==typeof e&&(e&=255);if(r<0||this.length<r||this.length<i)throw new RangeError("Out of range index");if(i<=r)return this;r>>>=0,i=void 0===i?this.length:i>>>0,e||(e=0);var s;if("number"==typeof e)for(s=r;s<i;++s)this[s]=e;else{var c=a.isBuffer(e)?e:G(new a(e,n).toString()),l=c.length;for(s=0;s<i-r;++s)this[s+r]=c[s%l]}return this};var et=/[^+\/0-9A-Za-z-_]/g}).call(e,r(0))},function(t,e){"function"==typeof Object.create?t.exports=function t(e,r){e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function t(e,r){e.super_=r;var i=function(){};i.prototype=r.prototype,e.prototype=new i,e.prototype.constructor=e}},function(t,e,r){"use strict";function i(t){if(!(this instanceof i))return new i(t);h.call(this,t),u.call(this,t),t&&!1===t.readable&&(this.readable=!1),t&&!1===t.writable&&(this.writable=!1),this.allowHalfOpen=!0,t&&!1===t.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",n)}function n(){this.allowHalfOpen||this._writableState.ended||s(o,this)}function o(t){t.end()}function a(t,e){for(var r=0,i=t.length;r<i;r++)e(t[r],r)}var s=r(7),c=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e};t.exports=i;var l=r(5);l.inherits=r(3);var h=r(14),u=r(18);l.inherits(i,h);for(var f=c(u.prototype),d=0;d<f.length;d++){var p=f[d];i.prototype[p]||(i.prototype[p]=u.prototype[p])}Object.defineProperty(i.prototype,"destroyed",{get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed&&this._writableState.destroyed)},set:function(t){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=t,this._writableState.destroyed=t)}}),i.prototype._destroy=function(t,e){this.push(null),this.end(),s(e,t)}},function(t,e,r){(function(t){function r(t){return Array.isArray?Array.isArray(t):"[object Array]"===v(t)}function i(t){return"boolean"==typeof t}function n(t){return null===t}function o(t){return null==t}function a(t){return"number"==typeof t}function s(t){return"string"==typeof t}function c(t){return"symbol"==typeof t}function l(t){return void 0===t}function h(t){return"[object RegExp]"===v(t)}function u(t){return"object"==typeof t&&null!==t}function f(t){return"[object Date]"===v(t)}function d(t){return"[object Error]"===v(t)||t instanceof Error}function p(t){return"function"==typeof t}function g(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t}function v(t){return Object.prototype.toString.call(t)}e.isArray=r,e.isBoolean=i,e.isNull=n,e.isNullOrUndefined=o,e.isNumber=a,e.isString=s,e.isSymbol=c,e.isUndefined=l,e.isRegExp=h,e.isObject=u,e.isDate=f,e.isError=d,e.isFunction=p,e.isPrimitive=g,e.isBuffer=t.isBuffer}).call(e,r(2).Buffer)},function(t,e,r){"use strict";function i(){p=!1}function n(t){if(!t)return void(f!==u&&(f=u,i()));if(t!==f){if(t.length!==u.length)throw new Error("Custom alphabet for shortid must be "+u.length+" unique characters. You submitted "+t.length+" characters: "+t);var e=t.split("").filter(function(t,e,r){return e!==r.lastIndexOf(t)});if(e.length)throw new Error("Custom alphabet for shortid must be "+u.length+" unique characters. These characters were not unique: "+e.join(", "));f=t,i()}}function o(t){return n(t),f}function a(t){h.seed(t),d!==t&&(i(),d=t)}function s(){f||n(u);for(var t=f.split(""),e=[],r=h.nextValue(),i;t.length>0;)r=h.nextValue(),i=Math.floor(r*t.length),e.push(t.splice(i,1)[0]);return e.join("")}function c(){return p||(p=s())}function l(t){return c()[t]}var h=r(32),u="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-",f,d,p;t.exports={characters:o,seed:a,lookup:l,shuffled:c}},function(t,e,r){"use strict";(function(e){function r(t,r,i,n){if("function"!=typeof t)throw new TypeError('"callback" argument must be a function');var o=arguments.length,a,s;switch(o){case 0:case 1:return e.nextTick(t);case 2:return e.nextTick(function e(){t.call(null,r)});case 3:return e.nextTick(function e(){t.call(null,r,i)});case 4:return e.nextTick(function e(){t.call(null,r,i,n)});default:for(a=new Array(o-1),s=0;s<a.length;)a[s++]=arguments[s];return e.nextTick(function e(){t.apply(null,a)})}}!e.version||0===e.version.indexOf("v0.")||0===e.version.indexOf("v1.")&&0!==e.version.indexOf("v1.8.")?t.exports=r:t.exports=e.nextTick}).call(e,r(1))},function(t,e,r){"use strict";var i="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;e.assign=function(t){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var r=e.shift();if(r){if("object"!=typeof r)throw new TypeError(r+"must be non-object");for(var i in r)r.hasOwnProperty(i)&&(t[i]=r[i])}}return t},e.shrinkBuf=function(t,e){return t.length===e?t:t.subarray?t.subarray(0,e):(t.length=e,t)};var n={arraySet:function(t,e,r,i,n){if(e.subarray&&t.subarray)return void t.set(e.subarray(r,r+i),n);for(var o=0;o<i;o++)t[n+o]=e[r+o]},flattenChunks:function(t){var e,r,i,n,o,a;for(i=0,e=0,r=t.length;e<r;e++)i+=t[e].length;for(a=new Uint8Array(i),n=0,e=0,r=t.length;e<r;e++)o=t[e],a.set(o,n),n+=o.length;return a}},o={arraySet:function(t,e,r,i,n){for(var o=0;o<i;o++)t[n+o]=e[r+o]},flattenChunks:function(t){return[].concat.apply([],t)}};e.setTyped=function(t){t?(e.Buf8=Uint8Array,e.Buf16=Uint16Array,e.Buf32=Int32Array,e.assign(e,n)):(e.Buf8=Array,e.Buf16=Array,e.Buf32=Array,e.assign(e,o))},e.setTyped(i)},function(t,e,r){e=t.exports=r(14),e.Stream=e,e.Readable=e,e.Writable=r(18),e.Duplex=r(4),e.Transform=r(20),e.PassThrough=r(49)},function(t,e,r){function i(t,e){for(var r in t)e[r]=t[r]}function n(t,e,r){return a(t,e,r)}var o=r(2),a=o.Buffer;a.from&&a.alloc&&a.allocUnsafe&&a.allocUnsafeSlow?t.exports=o:(i(o,e),e.Buffer=n),i(a,n),n.from=function(t,e,r){if("number"==typeof t)throw new TypeError("Argument must not be a number");return a(t,e,r)},n.alloc=function(t,e,r){if("number"!=typeof t)throw new TypeError("Argument must be a number");var i=a(t);return void 0!==e?"string"==typeof r?i.fill(e,r):i.fill(e):i.fill(0),i},n.allocUnsafe=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return a(t)},n.allocUnsafeSlow=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return o.SlowBuffer(t)}},function(t,e,r){"use strict";function i(t,e){for(var r=0,i,o="";!i;)o+=t(e>>4*r&15|n()),i=e<Math.pow(16,r+1),r++;return o}var n=r(33);t.exports=i},function(t,e,r){(function(e,i,n){!function e(r,i){t.exports=i()}(this,function(){return function(t){function e(i){if(r[i])return r[i].exports;var n=r[i]={i:i,l:!1,exports:{}};return t[i].call(n.exports,n,n.exports,e),n.l=!0,n.exports}var r={};return e.m=t,e.c=r,e.i=function(t){return t},e.d=function(t,r,i){e.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var r=t&&t.__esModule?function e(){return t.default}:function e(){return t};return e.d(r,"a",r),r},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=13)}([function(t,r,n){"use strict";function o(t){lt=t}function a(){return lt}function s(t){lt>=at.infos&&console.log("Info: "+t)}function c(t){lt>=at.warnings&&console.log("Warning: "+t)}function l(t){console.log("Deprecated API usage: "+t)}function h(t){throw new Error(t)}function u(t,e){t||h(e)}function f(t,e){try{var r=new URL(t);if(!r.origin||"null"===r.origin)return!1}catch(t){return!1}var i=new URL(e,r);return r.origin===i.origin}function d(t){if(!t)return!1;switch(t.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function p(t,e){if(!t)return null;try{var r=e?new URL(t,e):new URL(t);if(d(r))return r}catch(t){}return null}function g(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!1}),r}function v(t){var e;return function(){return t&&(e=Object.create(null),t(e),t=null),e}}function m(t){return"string"!=typeof t?(c("The argument for removeNullCharacters must be a string."),t):t.replace(wt,"")}function b(t){u(null!==t&&"object"===(void 0===t?"undefined":Y(t))&&void 0!==t.length,"Invalid argument for bytesToString");var e=t.length,r=8192;if(e<8192)return String.fromCharCode.apply(null,t);for(var i=[],n=0;n<e;n+=8192){var o=Math.min(n+8192,e),a=t.subarray(n,o);i.push(String.fromCharCode.apply(null,a))}return i.join("")}function y(t){u("string"==typeof t,"Invalid argument for stringToBytes");for(var e=t.length,r=new Uint8Array(e),i=0;i<e;++i)r[i]=255&t.charCodeAt(i);return r}function _(t){return void 0!==t.length?t.length:(u(void 0!==t.byteLength),t.byteLength)}function w(t){if(1===t.length&&t[0]instanceof Uint8Array)return t[0];var e=0,r,i=t.length,n,o;for(r=0;r<i;r++)n=t[r],o=_(n),e+=o;var a=0,s=new Uint8Array(e);for(r=0;r<i;r++)n=t[r],n instanceof Uint8Array||(n="string"==typeof n?y(n):new Uint8Array(n)),o=n.byteLength,s.set(n,a),a+=o;return s}function S(t){return String.fromCharCode(t>>24&255,t>>16&255,t>>8&255,255&t)}function x(t){for(var e=1,r=0;t>e;)e<<=1,r++;return r}function C(t,e){return t[e]<<24>>24}function A(t,e){return t[e]<<8|t[e+1]}function T(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}function k(){var t=new Uint8Array(4);return t[0]=1,1===new Uint32Array(t.buffer,0,1)[0]}function P(){try{return new Function(""),!0}catch(t){return!1}}function E(t){var e,r=t.length,i=[];if("þ"===t[0]&&"ÿ"===t[1])for(e=2;e<r;e+=2)i.push(String.fromCharCode(t.charCodeAt(e)<<8|t.charCodeAt(e+1)));else for(e=0;e<r;++e){var n=At[t.charCodeAt(e)];i.push(n?String.fromCharCode(n):t.charAt(e))}return i.join("")}function O(t){return decodeURIComponent(escape(t))}function R(t){return unescape(encodeURIComponent(t))}function L(t){for(var e in t)return!1;return!0}function D(t){return"boolean"==typeof t}function I(t){return"number"==typeof t&&(0|t)===t}function j(t){return"number"==typeof t}function M(t){return"string"==typeof t}function F(t){return t instanceof Array}function N(t){return"object"===(void 0===t?"undefined":Y(t))&&null!==t&&void 0!==t.byteLength}function B(t){return 32===t||9===t||13===t||10===t}function U(){return"object"===(void 0===i?"undefined":Y(i))&&i+""=="[object process]"}function z(){var t={};return t.promise=new Promise(function(e,r){t.resolve=e,t.reject=r}),t}function W(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;return t?new Promise(function(i,n){i(t.apply(r,e))}):Promise.resolve(void 0)}function q(t,e,r){e?t.resolve():t.reject(r)}function X(t){return Promise.resolve(t).catch(function(){})}function G(t,e,r){var i=this;this.sourceName=t,this.targetName=e,this.comObj=r,this.callbackId=1,this.streamId=1,this.postMessageTransfers=!0,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null);var n=this.callbacksCapabilities=Object.create(null),o=this.actionHandler=Object.create(null);this._onComObjOnMessage=function(t){var e=t.data;if(e.targetName===i.sourceName)if(e.stream)i._processStreamMessage(e);else if(e.isReply){var a=e.callbackId;if(!(e.callbackId in n))throw new Error("Cannot resolve callback "+a);var s=n[a];delete n[a],"error"in e?s.reject(e.error):s.resolve(e.data)}else{if(!(e.action in o))throw new Error("Unknown action from worker: "+e.action);var c=o[e.action];if(e.callbackId){var l=i.sourceName,h=e.sourceName;Promise.resolve().then(function(){return c[0].call(c[1],e.data)}).then(function(t){r.postMessage({sourceName:l,targetName:h,isReply:!0,callbackId:e.callbackId,data:t})},function(t){t instanceof Error&&(t+=""),r.postMessage({sourceName:l,targetName:h,isReply:!0,callbackId:e.callbackId,error:t})})}else e.streamId?i._createStreamSink(e):c[0].call(c[1],e.data)}},r.addEventListener("message",this._onComObjOnMessage)}function H(t,e,r){var i=new Image;i.onload=function e(){r.resolve(t,i)},i.onerror=function e(){r.resolve(t,null),c("Error during JPEG image loading")},i.src=e}Object.defineProperty(r,"__esModule",{value:!0}),r.unreachable=r.warn=r.utf8StringToString=r.stringToUTF8String=r.stringToPDFString=r.stringToBytes=r.string32=r.shadow=r.setVerbosityLevel=r.ReadableStream=r.removeNullCharacters=r.readUint32=r.readUint16=r.readInt8=r.log2=r.loadJpegStream=r.isEvalSupported=r.isLittleEndian=r.createValidAbsoluteUrl=r.isSameOrigin=r.isNodeJS=r.isSpace=r.isString=r.isNum=r.isInt=r.isEmptyObj=r.isBool=r.isArrayBuffer=r.isArray=r.info=r.globalScope=r.getVerbosityLevel=r.getLookupTableFactory=r.deprecated=r.createObjectURL=r.createPromiseCapability=r.createBlob=r.bytesToString=r.assert=r.arraysToBytes=r.arrayByteLength=r.FormatError=r.XRefParseException=r.Util=r.UnknownErrorException=r.UnexpectedResponseException=r.TextRenderingMode=r.StreamType=r.StatTimer=r.PasswordResponses=r.PasswordException=r.PageViewport=r.NotImplementedException=r.NativeImageDecoding=r.MissingPDFException=r.MissingDataException=r.MessageHandler=r.InvalidPDFException=r.CMapCompressionType=r.ImageKind=r.FontType=r.AnnotationType=r.AnnotationFlag=r.AnnotationFieldFlag=r.AnnotationBorderStyleType=r.UNSUPPORTED_FEATURES=r.VERBOSITY_LEVELS=r.OPS=r.IDENTITY_MATRIX=r.FONT_IDENTITY_MATRIX=void 0;var Y="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};n(14);var V=n(9),Z="undefined"!=typeof window&&window.Math===Math?window:void 0!==e&&e.Math===Math?e:"undefined"!=typeof self&&self.Math===Math?self:void 0,J=[.001,0,0,.001,0,0],K={NONE:"none",DECODE:"decode",DISPLAY:"display"},Q={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},$={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},tt={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},et={INVISIBLE:1,HIDDEN:2,PRINT:4,NOZOOM:8,NOROTATE:16,NOVIEW:32,READONLY:64,LOCKED:128,TOGGLENOVIEW:256,LOCKEDCONTENTS:512},rt={READONLY:1,REQUIRED:2,NOEXPORT:4,MULTILINE:4096,PASSWORD:8192,NOTOGGLETOOFF:16384,RADIO:32768,PUSHBUTTON:65536,COMBO:131072,EDIT:262144,SORT:524288,FILESELECT:1048576,MULTISELECT:2097152,DONOTSPELLCHECK:4194304,DONOTSCROLL:8388608,COMB:16777216,RICHTEXT:33554432,RADIOSINUNISON:33554432,COMMITONSELCHANGE:67108864},it={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},nt={UNKNOWN:0,FLATE:1,LZW:2,DCT:3,JPX:4,JBIG:5,A85:6,AHX:7,CCF:8,RL:9},ot={UNKNOWN:0,TYPE1:1,TYPE1C:2,CIDFONTTYPE0:3,CIDFONTTYPE0C:4,TRUETYPE:5,CIDFONTTYPE2:6,TYPE3:7,OPENTYPE:8,TYPE0:9,MMTYPE1:10},at={errors:0,warnings:1,infos:5},st={NONE:0,BINARY:1,STREAM:2},ct={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotations:78,endAnnotations:79,beginAnnotation:80,endAnnotation:81,paintJpegXObject:82,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91},lt=at.warnings,ht={unknown:"unknown",forms:"forms",javaScript:"javaScript",smask:"smask",shadingPattern:"shadingPattern",font:"font"},ut={NEED_PASSWORD:1,INCORRECT_PASSWORD:2},ft=function t(){function e(t,e){this.name="PasswordException",this.message=t,this.code=e}return e.prototype=new Error,e.constructor=e,e}(),dt=function t(){function e(t,e){this.name="UnknownErrorException",this.message=t,this.details=e}return e.prototype=new Error,e.constructor=e,e}(),pt=function t(){function e(t){this.name="InvalidPDFException",this.message=t}return e.prototype=new Error,e.constructor=e,e}(),gt=function t(){function e(t){this.name="MissingPDFException",this.message=t}return e.prototype=new Error,e.constructor=e,e}(),vt=function t(){function e(t,e){this.name="UnexpectedResponseException",this.message=t,this.status=e}return e.prototype=new Error,e.constructor=e,e}(),mt=function t(){function e(t){this.message=t}return e.prototype=new Error,e.prototype.name="NotImplementedException",e.constructor=e,e}(),bt=function t(){function e(t,e){this.begin=t,this.end=e,this.message="Missing data ["+t+", "+e+")"}return e.prototype=new Error,e.prototype.name="MissingDataException",e.constructor=e,e}(),yt=function t(){function e(t){this.message=t}return e.prototype=new Error,e.prototype.name="XRefParseException",e.constructor=e,e}(),_t=function t(){function e(t){this.message=t}return e.prototype=new Error,e.prototype.name="FormatError",e.constructor=e,e}(),wt=/\x00/g,St=[1,0,0,1,0,0],xt=function t(){function e(){}var r=["rgb(",0,",",0,",",0,")"];e.makeCssRgb=function t(e,i,n){return r[1]=e,r[3]=i,r[5]=n,r.join("")},e.transform=function t(e,r){return[e[0]*r[0]+e[2]*r[1],e[1]*r[0]+e[3]*r[1],e[0]*r[2]+e[2]*r[3],e[1]*r[2]+e[3]*r[3],e[0]*r[4]+e[2]*r[5]+e[4],e[1]*r[4]+e[3]*r[5]+e[5]]},e.applyTransform=function t(e,r){return[e[0]*r[0]+e[1]*r[2]+r[4],e[0]*r[1]+e[1]*r[3]+r[5]]},e.applyInverseTransform=function t(e,r){var i=r[0]*r[3]-r[1]*r[2];return[(e[0]*r[3]-e[1]*r[2]+r[2]*r[5]-r[4]*r[3])/i,(-e[0]*r[1]+e[1]*r[0]+r[4]*r[1]-r[5]*r[0])/i]},e.getAxialAlignedBoundingBox=function t(r,i){var n=e.applyTransform(r,i),o=e.applyTransform(r.slice(2,4),i),a=e.applyTransform([r[0],r[3]],i),s=e.applyTransform([r[2],r[1]],i);return[Math.min(n[0],o[0],a[0],s[0]),Math.min(n[1],o[1],a[1],s[1]),Math.max(n[0],o[0],a[0],s[0]),Math.max(n[1],o[1],a[1],s[1])]},e.inverseTransform=function t(e){var r=e[0]*e[3]-e[1]*e[2];return[e[3]/r,-e[1]/r,-e[2]/r,e[0]/r,(e[2]*e[5]-e[4]*e[3])/r,(e[4]*e[1]-e[5]*e[0])/r]},e.apply3dTransform=function t(e,r){return[e[0]*r[0]+e[1]*r[1]+e[2]*r[2],e[3]*r[0]+e[4]*r[1]+e[5]*r[2],e[6]*r[0]+e[7]*r[1]+e[8]*r[2]]},e.singularValueDecompose2dScale=function t(e){var r=[e[0],e[2],e[1],e[3]],i=e[0]*r[0]+e[1]*r[2],n=e[0]*r[1]+e[1]*r[3],o=e[2]*r[0]+e[3]*r[2],a=e[2]*r[1]+e[3]*r[3],s=(i+a)/2,c=Math.sqrt((i+a)*(i+a)-4*(i*a-o*n))/2,l=s+c||1,h=s-c||1;return[Math.sqrt(l),Math.sqrt(h)]},e.normalizeRect=function t(e){var r=e.slice(0);return e[0]>e[2]&&(r[0]=e[2],r[2]=e[0]),e[1]>e[3]&&(r[1]=e[3],r[3]=e[1]),r},e.intersect=function t(r,i){function n(t,e){return t-e}var o=[r[0],r[2],i[0],i[2]].sort(n),a=[r[1],r[3],i[1],i[3]].sort(n),s=[];return r=e.normalizeRect(r),i=e.normalizeRect(i),(o[0]===r[0]&&o[1]===i[0]||o[0]===i[0]&&o[1]===r[0])&&(s[0]=o[1],s[2]=o[2],(a[0]===r[1]&&a[1]===i[1]||a[0]===i[1]&&a[1]===r[1])&&(s[1]=a[1],s[3]=a[2],s))},e.sign=function t(e){return e<0?-1:1};var i=["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM","","X","XX","XXX","XL","L","LX","LXX","LXXX","XC","","I","II","III","IV","V","VI","VII","VIII","IX"];return e.toRoman=function t(e,r){u(I(e)&&e>0,"The number should be a positive integer.");for(var n,o=[];e>=1e3;)e-=1e3,o.push("M");n=e/100|0,e%=100,o.push(i[n]),n=e/10|0,e%=10,o.push(i[10+n]),o.push(i[20+e]);var a=o.join("");return r?a.toLowerCase():a},e.appendToArray=function t(e,r){Array.prototype.push.apply(e,r)},e.prependToArray=function t(e,r){Array.prototype.unshift.apply(e,r)},e.extendObj=function t(e,r){for(var i in r)e[i]=r[i]},e.getInheritableProperty=function t(e,r,i){for(;e&&!e.has(r);)e=e.get("Parent");return e?i?e.getArray(r):e.get(r):null},e.inherit=function t(e,r,i){e.prototype=Object.create(r.prototype),e.prototype.constructor=e;for(var n in i)e.prototype[n]=i[n]},e.loadScript=function t(e,r){var i=document.createElement("script"),n=!1;i.setAttribute("src",e),r&&(i.onload=function(){n||r(),n=!0}),document.getElementsByTagName("head")[0].appendChild(i)},e}(),Ct=function t(){function e(t,e,r,i,n,o){this.viewBox=t,this.scale=e,this.rotation=r,this.offsetX=i,this.offsetY=n;var a=(t[2]+t[0])/2,s=(t[3]+t[1])/2,c,l,h,u;switch(r%=360,r=r<0?r+360:r){case 180:c=-1,l=0,h=0,u=1;break;case 90:c=0,l=1,h=1,u=0;break;case 270:c=0,l=-1,h=-1,u=0;break;default:c=1,l=0,h=0,u=-1}o&&(h=-h,u=-u);var f,d,p,g;0===c?(f=Math.abs(s-t[1])*e+i,d=Math.abs(a-t[0])*e+n,p=Math.abs(t[3]-t[1])*e,g=Math.abs(t[2]-t[0])*e):(f=Math.abs(a-t[0])*e+i,d=Math.abs(s-t[1])*e+n,p=Math.abs(t[2]-t[0])*e,g=Math.abs(t[3]-t[1])*e),this.transform=[c*e,l*e,h*e,u*e,f-c*e*a-h*e*s,d-l*e*a-u*e*s],this.width=p,this.height=g,this.fontScale=e}return e.prototype={clone:function t(r){r=r||{};var i="scale"in r?r.scale:this.scale,n="rotation"in r?r.rotation:this.rotation;return new e(this.viewBox.slice(),i,n,this.offsetX,this.offsetY,r.dontFlip)},convertToViewportPoint:function t(e,r){return xt.applyTransform([e,r],this.transform)},convertToViewportRectangle:function t(e){var r=xt.applyTransform([e[0],e[1]],this.transform),i=xt.applyTransform([e[2],e[3]],this.transform);return[r[0],r[1],i[0],i[1]]},convertToPdfPoint:function t(e,r){return xt.applyInverseTransform([e,r],this.transform)}},e}(),At=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,728,711,710,729,733,731,730,732,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8226,8224,8225,8230,8212,8211,402,8260,8249,8250,8722,8240,8222,8220,8221,8216,8217,8218,8482,64257,64258,321,338,352,376,381,305,322,339,353,382,0,8364],Tt=function t(){function e(t,e,r){for(;t.length<r;)t+=e;return t}function r(){this.started=Object.create(null),this.times=[],this.enabled=!0}return r.prototype={time:function t(e){this.enabled&&(e in this.started&&c("Timer is already running for "+e),this.started[e]=Date.now())},timeEnd:function t(e){this.enabled&&(e in this.started||c("Timer has not been started for "+e),this.times.push({name:e,start:this.started[e],end:Date.now()}),delete this.started[e])},toString:function t(){var r,i,n=this.times,o="",a=0;for(r=0,i=n.length;r<i;++r){var s=n[r].name;s.length>a&&(a=s.length)}for(r=0,i=n.length;r<i;++r){var c=n[r],l=c.end-c.start;o+=e(c.name," ",a)+" "+l+"ms\n"}return o}},r}(),kt=function t(e,r){if("undefined"!=typeof Blob)return new Blob([e],{type:r});throw new Error('The "Blob" constructor is not supported.')},Pt=function t(){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";return function t(r,i){if(!(arguments.length>2&&void 0!==arguments[2]&&arguments[2])&&URL.createObjectURL){var n=kt(r,i);return URL.createObjectURL(n)}for(var o="data:"+i+";base64,",a=0,s=r.length;a<s;a+=3){var c=255&r[a],l=255&r[a+1],h=255&r[a+2];o+=e[c>>2]+e[(3&c)<<4|l>>4]+e[a+1<s?(15&l)<<2|h>>6:64]+e[a+2<s?63&h:64]}return o}}();G.prototype={on:function t(e,r,i){var n=this.actionHandler;if(n[e])throw new Error('There is already an actionName called "'+e+'"');n[e]=[r,i]},send:function t(e,r,i){var n={sourceName:this.sourceName,targetName:this.targetName,action:e,data:r};this.postMessage(n,i)},sendWithPromise:function t(e,r,i){var n=this.callbackId++,o={sourceName:this.sourceName,targetName:this.targetName,action:e,data:r,callbackId:n},a=z();this.callbacksCapabilities[n]=a;try{this.postMessage(o,i)}catch(t){a.reject(t)}return a.promise},sendWithStream:function t(e,r,i,n){var o=this,a=this.streamId++,s=this.sourceName,c=this.targetName;return new V.ReadableStream({start:function t(i){var n=z();return o.streamControllers[a]={controller:i,startCall:n,isClosed:!1},o.postMessage({sourceName:s,targetName:c,action:e,streamId:a,data:r,desiredSize:i.desiredSize}),n.promise},pull:function t(e){var r=z();return o.streamControllers[a].pullCall=r,o.postMessage({sourceName:s,targetName:c,stream:"pull",streamId:a,desiredSize:e.desiredSize}),r.promise},cancel:function t(e){var r=z();return o.streamControllers[a].cancelCall=r,o.streamControllers[a].isClosed=!0,o.postMessage({sourceName:s,targetName:c,stream:"cancel",reason:e,streamId:a}),r.promise}},i)},_createStreamSink:function t(e){var r=this,i=this,n=this.actionHandler[e.action],o=e.streamId,a=e.desiredSize,s=this.sourceName,c=e.sourceName,l=z(),h=function t(e){var i=e.stream,n=e.chunk,a=e.success,l=e.reason;r.comObj.postMessage({sourceName:s,targetName:c,stream:i,streamId:o,chunk:n,success:a,reason:l})},u={enqueue:function t(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;if(!this.isCancelled){var i=this.desiredSize;this.desiredSize-=r,i>0&&this.desiredSize<=0&&(this.sinkCapability=z(),this.ready=this.sinkCapability.promise),h({stream:"enqueue",chunk:e})}},close:function t(){this.isCancelled||(h({stream:"close"}),delete i.streamSinks[o])},error:function t(e){h({stream:"error",reason:e})},sinkCapability:l,onPull:null,onCancel:null,isCancelled:!1,desiredSize:a,ready:null};u.sinkCapability.resolve(),u.ready=u.sinkCapability.promise,this.streamSinks[o]=u,W(n[0],[e.data,u],n[1]).then(function(){h({stream:"start_complete",success:!0})},function(t){h({stream:"start_complete",success:!1,reason:t})})},_processStreamMessage:function t(e){var r=this,i=this.sourceName,n=e.sourceName,o=e.streamId,a=function t(e){var a=e.stream,s=e.success,c=e.reason;r.comObj.postMessage({sourceName:i,targetName:n,stream:a,success:s,streamId:o,reason:c})},s=function t(){Promise.all([r.streamControllers[e.streamId].startCall,r.streamControllers[e.streamId].pullCall,r.streamControllers[e.streamId].cancelCall].map(function(t){return t&&X(t.promise)})).then(function(){delete r.streamControllers[e.streamId]})};switch(e.stream){case"start_complete":q(this.streamControllers[e.streamId].startCall,e.success,e.reason);break;case"pull_complete":q(this.streamControllers[e.streamId].pullCall,e.success,e.reason);break;case"pull":if(!this.streamSinks[e.streamId]){a({stream:"pull_complete",success:!0});break}this.streamSinks[e.streamId].desiredSize<=0&&e.desiredSize>0&&this.streamSinks[e.streamId].sinkCapability.resolve(),this.streamSinks[e.streamId].desiredSize=e.desiredSize,W(this.streamSinks[e.streamId].onPull).then(function(){a({stream:"pull_complete",success:!0})},function(t){a({stream:"pull_complete",success:!1,reason:t})});break;case"enqueue":this.streamControllers[e.streamId].isClosed||this.streamControllers[e.streamId].controller.enqueue(e.chunk);break;case"close":if(this.streamControllers[e.streamId].isClosed)break;this.streamControllers[e.streamId].isClosed=!0,this.streamControllers[e.streamId].controller.close(),s();break;case"error":this.streamControllers[e.streamId].controller.error(e.reason),s();break;case"cancel_complete":q(this.streamControllers[e.streamId].cancelCall,e.success,e.reason),s();break;case"cancel":if(!this.streamSinks[e.streamId])break;W(this.streamSinks[e.streamId].onCancel,[e.reason]).then(function(){a({stream:"cancel_complete",success:!0})},function(t){a({stream:"cancel_complete",success:!1,reason:t})}),this.streamSinks[e.streamId].sinkCapability.reject(e.reason),this.streamSinks[e.streamId].isCancelled=!0,delete this.streamSinks[e.streamId];break;default:throw new Error("Unexpected stream case")}},postMessage:function t(e,r){r&&this.postMessageTransfers?this.comObj.postMessage(e,r):this.comObj.postMessage(e)},destroy:function t(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}},r.FONT_IDENTITY_MATRIX=J,r.IDENTITY_MATRIX=St,r.OPS=ct,r.VERBOSITY_LEVELS=at,r.UNSUPPORTED_FEATURES=ht,r.AnnotationBorderStyleType=it,r.AnnotationFieldFlag=rt,r.AnnotationFlag=et,r.AnnotationType=tt,r.FontType=ot,r.ImageKind=$,r.CMapCompressionType=st,r.InvalidPDFException=pt,r.MessageHandler=G,r.MissingDataException=bt,r.MissingPDFException=gt,r.NativeImageDecoding=K,r.NotImplementedException=mt,r.PageViewport=Ct,r.PasswordException=ft,r.PasswordResponses=ut,r.StatTimer=Tt,r.StreamType=nt,r.TextRenderingMode=Q,r.UnexpectedResponseException=vt,r.UnknownErrorException=dt,r.Util=xt,r.XRefParseException=yt,r.FormatError=_t,r.arrayByteLength=_,r.arraysToBytes=w,r.assert=u,r.bytesToString=b,r.createBlob=kt,r.createPromiseCapability=z,r.createObjectURL=Pt,r.deprecated=l,r.getLookupTableFactory=v,r.getVerbosityLevel=a,r.globalScope=Z,r.info=s,r.isArray=F,r.isArrayBuffer=N,r.isBool=D,r.isEmptyObj=L,r.isInt=I,r.isNum=j,r.isString=M,r.isSpace=B,r.isNodeJS=U,r.isSameOrigin=f,r.createValidAbsoluteUrl=p,r.isLittleEndian=k,r.isEvalSupported=P,r.loadJpegStream=H,r.log2=x,r.readInt8=C,r.readUint16=A,r.readUint32=T,r.removeNullCharacters=m,r.ReadableStream=V.ReadableStream,r.setVerbosityLevel=o,r.shadow=g,r.string32=S,r.stringToBytes=y,r.stringToPDFString=E,r.stringToUTF8String=O,r.utf8StringToString=R,r.warn=c,r.unreachable=h},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){var r=e&&e.url;if(t.href=t.title=r?(0,h.removeNullCharacters)(r):"",r){var i=e.target;void 0===i&&(i=a("externalLinkTarget")),t.target=m[i];var n=e.rel;void 0===n&&(n=a("externalLinkRel")),t.rel=n}}function o(t){var e=t.indexOf("#"),r=t.indexOf("?"),i=Math.min(e>0?e:t.length,r>0?r:t.length);return t.substring(t.lastIndexOf("/",i)+1,i)}function a(t){var e=h.globalScope.PDFJS;switch(t){case"pdfBug":return!!e&&e.pdfBug;case"disableAutoFetch":return!!e&&e.disableAutoFetch;case"disableStream":return!!e&&e.disableStream;case"disableRange":return!!e&&e.disableRange;case"disableFontFace":return!!e&&e.disableFontFace;case"disableCreateObjectURL":return!!e&&e.disableCreateObjectURL;case"disableWebGL":return!e||e.disableWebGL;case"cMapUrl":return e?e.cMapUrl:null;case"cMapPacked":return!!e&&e.cMapPacked;case"postMessageTransfers":return!e||e.postMessageTransfers;case"workerPort":return e?e.workerPort:null;case"workerSrc":return e?e.workerSrc:null;case"disableWorker":return!!e&&e.disableWorker;case"maxImageSize":return e?e.maxImageSize:-1;case"imageResourcesPath":return e?e.imageResourcesPath:"";case"isEvalSupported":return!e||e.isEvalSupported;case"externalLinkTarget":if(!e)return v.NONE;switch(e.externalLinkTarget){case v.NONE:case v.SELF:case v.BLANK:case v.PARENT:case v.TOP:return e.externalLinkTarget}return(0,h.warn)("PDFJS.externalLinkTarget is invalid: "+e.externalLinkTarget),e.externalLinkTarget=v.NONE,v.NONE;case"externalLinkRel":return e?e.externalLinkRel:u;case"enableStats":return!(!e||!e.enableStats);case"pdfjsNext":return!(!e||!e.pdfjsNext);default:throw new Error("Unknown default setting: "+t)}}function s(){switch(a("externalLinkTarget")){case v.NONE:return!1;case v.SELF:case v.BLANK:case v.PARENT:case v.TOP:return!0}}function c(t,e){(0,h.deprecated)("isValidUrl(), please use createValidAbsoluteUrl() instead.");var r=e?"http://example.com":null;return null!==(0,h.createValidAbsoluteUrl)(t,r)}Object.defineProperty(e,"__esModule",{value:!0}),e.DOMCMapReaderFactory=e.DOMCanvasFactory=e.DEFAULT_LINK_REL=e.getDefaultSetting=e.LinkTarget=e.getFilenameFromUrl=e.isValidUrl=e.isExternalLinkTargetSet=e.addLinkAttributes=e.RenderingCancelledException=e.CustomStyle=void 0;var l=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),h=r(0),u="noopener noreferrer nofollow",f=function(){function t(){i(this,t)}return l(t,[{key:"create",value:function t(e,r){if(e<=0||r<=0)throw new Error("invalid canvas size");var i=document.createElement("canvas"),n=i.getContext("2d");return i.width=e,i.height=r,{canvas:i,context:n}}},{key:"reset",value:function t(e,r,i){if(!e.canvas)throw new Error("canvas is not specified");if(r<=0||i<=0)throw new Error("invalid canvas size");e.canvas.width=r,e.canvas.height=i}},{key:"destroy",value:function t(e){if(!e.canvas)throw new Error("canvas is not specified");e.canvas.width=0,e.canvas.height=0,e.canvas=null,e.context=null}}]),t}(),d=function(){function t(e){var r=e.baseUrl,n=void 0===r?null:r,o=e.isCompressed,a=void 0!==o&&o;i(this,t),this.baseUrl=n,this.isCompressed=a}return l(t,[{key:"fetch",value:function t(e){var r=this,i=e.name;return i?new Promise(function(t,e){var n=r.baseUrl+i+(r.isCompressed?".bcmap":""),o=new XMLHttpRequest;o.open("GET",n,!0),r.isCompressed&&(o.responseType="arraybuffer"),o.onreadystatechange=function(){if(o.readyState===XMLHttpRequest.DONE){if(200===o.status||0===o.status){var i=void 0;if(r.isCompressed&&o.response?i=new Uint8Array(o.response):!r.isCompressed&&o.responseText&&(i=(0,h.stringToBytes)(o.responseText)),i)return void t({cMapData:i,compressionType:r.isCompressed?h.CMapCompressionType.BINARY:h.CMapCompressionType.NONE})}e(new Error("Unable to load "+(r.isCompressed?"binary ":"")+"CMap at: "+n))}},o.send(null)}):Promise.reject(new Error("CMap name must be specified."))}}]),t}(),p=function t(){function e(){}var r=["ms","Moz","Webkit","O"],i=Object.create(null);return e.getProp=function t(e,n){if(1===arguments.length&&"string"==typeof i[e])return i[e];n=n||document.documentElement;var o=n.style,a,s;if("string"==typeof o[e])return i[e]=e;s=e.charAt(0).toUpperCase()+e.slice(1);for(var c=0,l=r.length;c<l;c++)if(a=r[c]+s,"string"==typeof o[a])return i[e]=a;return i[e]="undefined"},e.setProp=function t(e,r,i){var n=this.getProp(e);"undefined"!==n&&(r.style[n]=i)},e}(),g=function t(){function t(t,e){this.message=t,this.type=e}return t.prototype=new Error,t.prototype.name="RenderingCancelledException",t.constructor=t,t}(),v={NONE:0,SELF:1,BLANK:2,PARENT:3,TOP:4},m=["","_self","_blank","_parent","_top"];e.CustomStyle=p,e.RenderingCancelledException=g,e.addLinkAttributes=n,e.isExternalLinkTargetSet=s,e.isValidUrl=c,e.getFilenameFromUrl=o,e.LinkTarget=v,e.getDefaultSetting=a,e.DEFAULT_LINK_REL=u,e.DOMCanvasFactory=f,e.DOMCMapReaderFactory=d},function(t,e,r){"use strict";function i(){}Object.defineProperty(e,"__esModule",{value:!0}),e.AnnotationLayer=void 0;var n=r(1),o=r(0);i.prototype={create:function t(e){switch(e.data.annotationType){case o.AnnotationType.LINK:return new s(e);case o.AnnotationType.TEXT:return new c(e);case o.AnnotationType.WIDGET:switch(e.data.fieldType){case"Tx":return new h(e);case"Btn":if(e.data.radioButton)return new f(e);if(e.data.checkBox)return new u(e);(0,o.warn)("Unimplemented button widget annotation: pushbutton");break;case"Ch":return new d(e)}return new l(e);case o.AnnotationType.POPUP:return new p(e);case o.AnnotationType.LINE:return new v(e);case o.AnnotationType.HIGHLIGHT:return new m(e);case o.AnnotationType.UNDERLINE:return new b(e);case o.AnnotationType.SQUIGGLY:return new y(e);case o.AnnotationType.STRIKEOUT:return new _(e);case o.AnnotationType.FILEATTACHMENT:return new w(e);default:return new a(e)}}};var a=function t(){function e(t,e,r){this.isRenderable=e||!1,this.data=t.data,this.layer=t.layer,this.page=t.page,this.viewport=t.viewport,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderInteractiveForms=t.renderInteractiveForms,e&&(this.container=this._createContainer(r))}return e.prototype={_createContainer:function t(e){var r=this.data,i=this.page,a=this.viewport,s=document.createElement("section"),c=r.rect[2]-r.rect[0],l=r.rect[3]-r.rect[1];s.setAttribute("data-annotation-id",r.id);var h=o.Util.normalizeRect([r.rect[0],i.view[3]-r.rect[1]+i.view[1],r.rect[2],i.view[3]-r.rect[3]+i.view[1]]);if(n.CustomStyle.setProp("transform",s,"matrix("+a.transform.join(",")+")"),n.CustomStyle.setProp("transformOrigin",s,-h[0]+"px "+-h[1]+"px"),!e&&r.borderStyle.width>0){s.style.borderWidth=r.borderStyle.width+"px",r.borderStyle.style!==o.AnnotationBorderStyleType.UNDERLINE&&(c-=2*r.borderStyle.width,l-=2*r.borderStyle.width);var u=r.borderStyle.horizontalCornerRadius,f=r.borderStyle.verticalCornerRadius;if(u>0||f>0){var d=u+"px / "+f+"px";n.CustomStyle.setProp("borderRadius",s,d)}switch(r.borderStyle.style){case o.AnnotationBorderStyleType.SOLID:s.style.borderStyle="solid";break;case o.AnnotationBorderStyleType.DASHED:s.style.borderStyle="dashed";break;case o.AnnotationBorderStyleType.BEVELED:(0,o.warn)("Unimplemented border style: beveled");break;case o.AnnotationBorderStyleType.INSET:(0,o.warn)("Unimplemented border style: inset");break;case o.AnnotationBorderStyleType.UNDERLINE:s.style.borderBottomStyle="solid"}r.color?s.style.borderColor=o.Util.makeCssRgb(0|r.color[0],0|r.color[1],0|r.color[2]):s.style.borderWidth=0}return s.style.left=h[0]+"px",s.style.top=h[1]+"px",s.style.width=c+"px",s.style.height=l+"px",s},_createPopup:function t(e,r,i){r||(r=document.createElement("div"),r.style.height=e.style.height,r.style.width=e.style.width,e.appendChild(r));var n=new g({container:e,trigger:r,color:i.color,title:i.title,contents:i.contents,hideWrapper:!0}),o=n.render();o.style.left=e.style.width,e.appendChild(o)},render:function t(){throw new Error("Abstract method AnnotationElement.render called")}},e}(),s=function t(){function e(t){a.call(this,t,!0)}return o.Util.inherit(e,a,{render:function t(){this.container.className="linkAnnotation";var e=document.createElement("a");return(0,n.addLinkAttributes)(e,{url:this.data.url,target:this.data.newWindow?n.LinkTarget.BLANK:void 0}),this.data.url||(this.data.action?this._bindNamedAction(e,this.data.action):this._bindLink(e,this.data.dest)),this.container.appendChild(e),this.container},_bindLink:function t(e,r){var i=this;e.href=this.linkService.getDestinationHash(r),e.onclick=function(){return r&&i.linkService.navigateTo(r),!1},r&&(e.className="internalLink")},_bindNamedAction:function t(e,r){var i=this;e.href=this.linkService.getAnchorUrl(""),e.onclick=function(){return i.linkService.executeNamedAction(r),!1},e.className="internalLink"}}),e}(),c=function t(){function e(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);a.call(this,t,e)}return o.Util.inherit(e,a,{render:function t(){this.container.className="textAnnotation";var e=document.createElement("img");return e.style.height=this.container.style.height,e.style.width=this.container.style.width,e.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",e.alt="[{{type}} Annotation]",e.dataset.l10nId="text_annotation_type",e.dataset.l10nArgs=JSON.stringify({type:this.data.name}),this.data.hasPopup||this._createPopup(this.container,e,this.data),this.container.appendChild(e),this.container}}),e}(),l=function t(){function e(t,e){a.call(this,t,e)}return o.Util.inherit(e,a,{render:function t(){return this.container}}),e}(),h=function t(){function e(t){var e=t.renderInteractiveForms||!t.data.hasAppearance&&!!t.data.fieldValue;l.call(this,t,e)}var r=["left","center","right"];return o.Util.inherit(e,l,{render:function t(){this.container.className="textWidgetAnnotation";var e=null;if(this.renderInteractiveForms){if(this.data.multiLine?(e=document.createElement("textarea"),e.textContent=this.data.fieldValue):(e=document.createElement("input"),e.type="text",e.setAttribute("value",this.data.fieldValue)),e.disabled=this.data.readOnly,null!==this.data.maxLen&&(e.maxLength=this.data.maxLen),this.data.comb){var i=this.data.rect[2]-this.data.rect[0],n=i/this.data.maxLen;e.classList.add("comb"),e.style.letterSpacing="calc("+n+"px - 1ch)"}}else{e=document.createElement("div"),e.textContent=this.data.fieldValue,e.style.verticalAlign="middle",e.style.display="table-cell";var o=null;this.data.fontRefName&&(o=this.page.commonObjs.getData(this.data.fontRefName)),this._setTextStyle(e,o)}return null!==this.data.textAlignment&&(e.style.textAlign=r[this.data.textAlignment]),this.container.appendChild(e),this.container},_setTextStyle:function t(e,r){var i=e.style;if(i.fontSize=this.data.fontSize+"px",i.direction=this.data.fontDirection<0?"rtl":"ltr",r){i.fontWeight=r.black?r.bold?"900":"bold":r.bold?"bold":"normal",i.fontStyle=r.italic?"italic":"normal";var n=r.loadedName?'"'+r.loadedName+'", ':"",o=r.fallbackName||"Helvetica, sans-serif";i.fontFamily=n+o}}}),e}(),u=function t(){function e(t){l.call(this,t,t.renderInteractiveForms)}return o.Util.inherit(e,l,{render:function t(){this.container.className="buttonWidgetAnnotation checkBox";var e=document.createElement("input");return e.disabled=this.data.readOnly,e.type="checkbox",this.data.fieldValue&&"Off"!==this.data.fieldValue&&e.setAttribute("checked",!0),this.container.appendChild(e),this.container}}),e}(),f=function t(){function e(t){l.call(this,t,t.renderInteractiveForms)}return o.Util.inherit(e,l,{render:function t(){this.container.className="buttonWidgetAnnotation radioButton";var e=document.createElement("input");return e.disabled=this.data.readOnly,e.type="radio",e.name=this.data.fieldName,this.data.fieldValue===this.data.buttonValue&&e.setAttribute("checked",!0),this.container.appendChild(e),this.container}}),e}(),d=function t(){function e(t){l.call(this,t,t.renderInteractiveForms)}return o.Util.inherit(e,l,{render:function t(){this.container.className="choiceWidgetAnnotation";var e=document.createElement("select");e.disabled=this.data.readOnly,this.data.combo||(e.size=this.data.options.length,this.data.multiSelect&&(e.multiple=!0));for(var r=0,i=this.data.options.length;r<i;r++){var n=this.data.options[r],o=document.createElement("option");o.textContent=n.displayValue,o.value=n.exportValue,this.data.fieldValue.indexOf(n.displayValue)>=0&&o.setAttribute("selected",!0),e.appendChild(o)}return this.container.appendChild(e),this.container}}),e}(),p=function t(){function e(t){var e=!(!t.data.title&&!t.data.contents);a.call(this,t,e)}var r=["Line"];return o.Util.inherit(e,a,{render:function t(){if(this.container.className="popupAnnotation",r.indexOf(this.data.parentType)>=0)return this.container;var e='[data-annotation-id="'+this.data.parentId+'"]',i=this.layer.querySelector(e);if(!i)return this.container;var o=new g({container:this.container,trigger:i,color:this.data.color,title:this.data.title,contents:this.data.contents}),a=parseFloat(i.style.left),s=parseFloat(i.style.width);return n.CustomStyle.setProp("transformOrigin",this.container,-(a+s)+"px -"+i.style.top),this.container.style.left=a+s+"px",this.container.appendChild(o.render()),this.container}}),e}(),g=function t(){function e(t){this.container=t.container,this.trigger=t.trigger,this.color=t.color,this.title=t.title,this.contents=t.contents,this.hideWrapper=t.hideWrapper||!1,this.pinned=!1}var r=.7;return e.prototype={render:function t(){var e=document.createElement("div");e.className="popupWrapper",this.hideElement=this.hideWrapper?e:this.container,this.hideElement.setAttribute("hidden",!0);var r=document.createElement("div");r.className="popup";var i=this.color;if(i){var n=.7*(255-i[0])+i[0],a=.7*(255-i[1])+i[1],s=.7*(255-i[2])+i[2];r.style.backgroundColor=o.Util.makeCssRgb(0|n,0|a,0|s)}var c=this._formatContents(this.contents),l=document.createElement("h1");return l.textContent=this.title,this.trigger.addEventListener("click",this._toggle.bind(this)),this.trigger.addEventListener("mouseover",this._show.bind(this,!1)),this.trigger.addEventListener("mouseout",this._hide.bind(this,!1)),r.addEventListener("click",this._hide.bind(this,!0)),r.appendChild(l),r.appendChild(c),e.appendChild(r),e},_formatContents:function t(e){for(var r=document.createElement("p"),i=e.split(/(?:\r\n?|\n)/),n=0,o=i.length;n<o;++n){var a=i[n];r.appendChild(document.createTextNode(a)),n<o-1&&r.appendChild(document.createElement("br"))}return r},_toggle:function t(){this.pinned?this._hide(!0):this._show(!0)},_show:function t(e){e&&(this.pinned=!0),this.hideElement.hasAttribute("hidden")&&(this.hideElement.removeAttribute("hidden"),this.container.style.zIndex+=1)},_hide:function t(e){e&&(this.pinned=!1),this.hideElement.hasAttribute("hidden")||this.pinned||(this.hideElement.setAttribute("hidden",!0),this.container.style.zIndex-=1)}},e}(),v=function t(){function e(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);a.call(this,t,e,!0)}var r="http://www.w3.org/2000/svg";return o.Util.inherit(e,a,{render:function t(){this.container.className="lineAnnotation";var e=this.data,i=e.rect[2]-e.rect[0],n=e.rect[3]-e.rect[1],o=document.createElementNS(r,"svg:svg");o.setAttributeNS(null,"version","1.1"),o.setAttributeNS(null,"width",i+"px"),o.setAttributeNS(null,"height",n+"px"),o.setAttributeNS(null,"preserveAspectRatio","none"),o.setAttributeNS(null,"viewBox","0 0 "+i+" "+n);var a=document.createElementNS(r,"svg:line");return a.setAttributeNS(null,"x1",e.rect[2]-e.lineCoordinates[0]),a.setAttributeNS(null,"y1",e.rect[3]-e.lineCoordinates[1]),a.setAttributeNS(null,"x2",e.rect[2]-e.lineCoordinates[2]),a.setAttributeNS(null,"y2",e.rect[3]-e.lineCoordinates[3]),a.setAttributeNS(null,"stroke-width",e.borderStyle.width),a.setAttributeNS(null,"stroke","transparent"),o.appendChild(a),this.container.append(o),this._createPopup(this.container,a,this.data),this.container}}),e}(),m=function t(){function e(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);a.call(this,t,e,!0)}return o.Util.inherit(e,a,{render:function t(){return this.container.className="highlightAnnotation",this.data.hasPopup||this._createPopup(this.container,null,this.data),this.container}}),e}(),b=function t(){function e(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);a.call(this,t,e,!0)}return o.Util.inherit(e,a,{render:function t(){return this.container.className="underlineAnnotation",this.data.hasPopup||this._createPopup(this.container,null,this.data),this.container}}),e}(),y=function t(){function e(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);a.call(this,t,e,!0)}return o.Util.inherit(e,a,{render:function t(){return this.container.className="squigglyAnnotation",this.data.hasPopup||this._createPopup(this.container,null,this.data),this.container}}),e}(),_=function t(){function e(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);a.call(this,t,e,!0)}return o.Util.inherit(e,a,{render:function t(){return this.container.className="strikeoutAnnotation",this.data.hasPopup||this._createPopup(this.container,null,this.data),this.container}}),e}(),w=function t(){function e(t){a.call(this,t,!0);var e=this.data.file;this.filename=(0,n.getFilenameFromUrl)(e.filename),this.content=e.content,this.linkService.onFileAttachmentAnnotation({id:(0,o.stringToPDFString)(e.filename),filename:e.filename,content:e.content})}return o.Util.inherit(e,a,{render:function t(){this.container.className="fileAttachmentAnnotation";var e=document.createElement("div");return e.style.height=this.container.style.height,e.style.width=this.container.style.width,e.addEventListener("dblclick",this._download.bind(this)),this.data.hasPopup||!this.data.title&&!this.data.contents||this._createPopup(this.container,e,this.data),this.container.appendChild(e),this.container},_download:function t(){if(!this.downloadManager)return void(0,o.warn)("Download cannot be started due to unavailable download manager");this.downloadManager.downloadData(this.content,this.filename,"")}}),e}(),S=function t(){return{render:function t(e){for(var r=new i,o=0,a=e.annotations.length;o<a;o++){var s=e.annotations[o];if(s){var c=r.create({data:s,layer:e.div,page:e.page,viewport:e.viewport,linkService:e.linkService,downloadManager:e.downloadManager,imageResourcesPath:e.imageResourcesPath||(0,n.getDefaultSetting)("imageResourcesPath"),renderInteractiveForms:e.renderInteractiveForms||!1});c.isRenderable&&e.div.appendChild(c.render())}}},update:function t(e){for(var r=0,i=e.annotations.length;r<i;r++){var o=e.annotations[r],a=e.div.querySelector('[data-annotation-id="'+o.id+'"]');a&&n.CustomStyle.setProp("transform",a,"matrix("+e.viewport.transform.join(",")+")")}e.div.removeAttribute("hidden")}}}();e.AnnotationLayer=S},function(t,e,i){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e,r,i){var n=new S;arguments.length>1&&(0,l.deprecated)("getDocument is called with pdfDataRangeTransport, passwordCallback or progressCallback argument"),e&&(e instanceof x||(e=Object.create(e),e.length=t.length,e.initialData=t.initialData,e.abort||(e.abort=function(){})),t=Object.create(t),t.range=e),n.onPassword=r||null,n.onProgress=i||null;var o;if("string"==typeof t)o={url:t};else if((0,l.isArrayBuffer)(t))o={data:t};else if(t instanceof x)o={range:t};else{if("object"!==(void 0===t?"undefined":c(t)))throw new Error("Invalid parameter in getDocument, need either Uint8Array, string or a parameter object");if(!t.url&&!t.data&&!t.range)throw new Error("Invalid parameter object: need either .data, .range or .url");o=t}var s={},u=null,f=null,d=h.DOMCMapReaderFactory;for(var g in o)if("url"!==g||"undefined"==typeof window)if("range"!==g)if("worker"!==g)if("data"!==g||o[g]instanceof Uint8Array)"CMapReaderFactory"!==g?s[g]=o[g]:d=o[g];else{var v=o[g];if("string"==typeof v)s[g]=(0,l.stringToBytes)(v);else if("object"!==(void 0===v?"undefined":c(v))||null===v||isNaN(v.length)){if(!(0,l.isArrayBuffer)(v))throw new Error("Invalid PDF binary data: either typed array, string or array-like object is expected in the data property.");s[g]=new Uint8Array(v)}else s[g]=new Uint8Array(v)}else f=o[g];else u=o[g];else s[g]=new URL(o[g],window.location).href;if(s.rangeChunkSize=s.rangeChunkSize||p,s.ignoreErrors=!0!==s.stopAtErrors,void 0!==s.disableNativeImageDecoder&&(0,l.deprecated)("parameter disableNativeImageDecoder, use nativeImageDecoderSupport instead"),s.nativeImageDecoderSupport=s.nativeImageDecoderSupport||(!0===s.disableNativeImageDecoder?l.NativeImageDecoding.NONE:l.NativeImageDecoding.DECODE),s.nativeImageDecoderSupport!==l.NativeImageDecoding.DECODE&&s.nativeImageDecoderSupport!==l.NativeImageDecoding.NONE&&s.nativeImageDecoderSupport!==l.NativeImageDecoding.DISPLAY&&((0,l.warn)("Invalid parameter nativeImageDecoderSupport: need a state of enum {NativeImageDecoding}"),s.nativeImageDecoderSupport=l.NativeImageDecoding.DECODE),!f){var m=(0,h.getDefaultSetting)("workerPort");f=m?k.fromPort(m):new k,n._worker=f}var b=n.docId;return f.promise.then(function(){if(n.destroyed)throw new Error("Loading aborted");return a(f,s,u,b).then(function(t){if(n.destroyed)throw new Error("Loading aborted");var e=new l.MessageHandler(b,t,f.port),r=new P(e,n,u,d);n._transport=r,e.send("Ready",null)})}).catch(n._capability.reject),n}function a(t,e,r,i){return t.destroyed?Promise.reject(new Error("Worker was destroyed")):(e.disableAutoFetch=(0,h.getDefaultSetting)("disableAutoFetch"),e.disableStream=(0,h.getDefaultSetting)("disableStream"),e.chunkedViewerLoading=!!r,r&&(e.length=r.length,e.initialData=r.initialData),t.messageHandler.sendWithPromise("GetDocRequest",{docId:i,source:e,disableRange:(0,h.getDefaultSetting)("disableRange"),maxImageSize:(0,h.getDefaultSetting)("maxImageSize"),disableFontFace:(0,h.getDefaultSetting)("disableFontFace"),disableCreateObjectURL:(0,h.getDefaultSetting)("disableCreateObjectURL"),postMessageTransfers:(0,h.getDefaultSetting)("postMessageTransfers")&&!m,docBaseUrl:e.docBaseUrl,nativeImageDecoderSupport:e.nativeImageDecoderSupport,ignoreErrors:e.ignoreErrors}).then(function(e){if(t.destroyed)throw new Error("Worker was destroyed");return e}))}Object.defineProperty(e,"__esModule",{value:!0}),e.build=e.version=e._UnsupportedManager=e.PDFPageProxy=e.PDFDocumentProxy=e.PDFWorker=e.PDFDataRangeTransport=e.LoopbackPort=e.getDocument=void 0;var s=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},l=i(0),h=i(1),u=i(11),f=i(10),d=i(6),p=65536,g=!1,v,m=!1,b="undefined"!=typeof document&&document.currentScript?document.currentScript.src:null,y=null,_=!1;"undefined"==typeof window?(g=!0,_=!0):_=!0,"undefined"!=typeof requirejs&&requirejs.toUrl&&(v=requirejs.toUrl("pdfjs-dist/build/pdf.worker.js"));var w="undefined"!=typeof requirejs&&requirejs.load;y=_?function(t){r.e(0).then(function(){var e;e=r(81),t(e.WorkerMessageHandler)}.bind(null,r)).catch(r.oe)}:w?function(t){requirejs(["pdfjs-dist/build/pdf.worker"],function(e){t(e.WorkerMessageHandler)})}:null;var S=function t(){function e(){this._capability=(0,l.createPromiseCapability)(),this._transport=null,this._worker=null,this.docId="d"+r++,this.destroyed=!1,this.onPassword=null,this.onProgress=null,this.onUnsupportedFeature=null}var r=0;return e.prototype={get promise(){return this._capability.promise},destroy:function t(){var e=this;return this.destroyed=!0,(this._transport?this._transport.destroy():Promise.resolve()).then(function(){e._transport=null,e._worker&&(e._worker.destroy(),e._worker=null)})},then:function t(e,r){return this.promise.then.apply(this.promise,arguments)}},e}(),x=function t(){function e(t,e){this.length=t,this.initialData=e,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._readyCapability=(0,l.createPromiseCapability)()}return e.prototype={addRangeListener:function t(e){this._rangeListeners.push(e)},addProgressListener:function t(e){this._progressListeners.push(e)},addProgressiveReadListener:function t(e){this._progressiveReadListeners.push(e)},onDataRange:function t(e,r){for(var i=this._rangeListeners,n=0,o=i.length;n<o;++n)i[n](e,r)},onDataProgress:function t(e){var r=this;this._readyCapability.promise.then(function(){for(var t=r._progressListeners,i=0,n=t.length;i<n;++i)t[i](e)})},onDataProgressiveRead:function t(e){var r=this;this._readyCapability.promise.then(function(){for(var t=r._progressiveReadListeners,i=0,n=t.length;i<n;++i)t[i](e)})},transportReady:function t(){this._readyCapability.resolve()},requestDataRange:function t(e,r){throw new Error("Abstract method PDFDataRangeTransport.requestDataRange")},abort:function t(){}},e}(),C=function t(){function e(t,e,r){this.pdfInfo=t,this.transport=e,this.loadingTask=r}return e.prototype={get numPages(){return this.pdfInfo.numPages},get fingerprint(){return this.pdfInfo.fingerprint},getPage:function t(e){return this.transport.getPage(e)},getPageIndex:function t(e){return this.transport.getPageIndex(e)},getDestinations:function t(){return this.transport.getDestinations()},getDestination:function t(e){return this.transport.getDestination(e)},getPageLabels:function t(){return this.transport.getPageLabels()},getPageMode:function t(){return this.transport.getPageMode()},getAttachments:function t(){return this.transport.getAttachments()},getJavaScript:function t(){return this.transport.getJavaScript()},getOutline:function t(){return this.transport.getOutline()},getMetadata:function t(){return this.transport.getMetadata()},getData:function t(){return this.transport.getData()},getDownloadInfo:function t(){return this.transport.downloadInfoCapability.promise},getStats:function t(){return this.transport.getStats()},cleanup:function t(){this.transport.startCleanup()},destroy:function t(){return this.loadingTask.destroy()}},e}(),A=function t(){function e(t,e,r){this.pageIndex=t,this.pageInfo=e,this.transport=r,this.stats=new l.StatTimer,this.stats.enabled=(0,h.getDefaultSetting)("enableStats"),this.commonObjs=r.commonObjs,this.objs=new E,this.cleanupAfterRender=!1,this.pendingCleanup=!1,this.intentStates=Object.create(null),this.destroyed=!1}return e.prototype={get pageNumber(){return this.pageIndex+1},get rotate(){return this.pageInfo.rotate},get ref(){return this.pageInfo.ref},get userUnit(){return this.pageInfo.userUnit},get view(){return this.pageInfo.view},getViewport:function t(e,r){return arguments.length<2&&(r=this.rotate),new l.PageViewport(this.view,e,r,0,0)},getAnnotations:function t(e){var r=e&&e.intent||null;return this.annotationsPromise&&this.annotationsIntent===r||(this.annotationsPromise=this.transport.getAnnotations(this.pageIndex,r),this.annotationsIntent=r),this.annotationsPromise},render:function t(e){var r=this,i=this.stats;i.time("Overall"),this.pendingCleanup=!1;var n="print"===e.intent?"print":"display",o=e.canvasFactory||new h.DOMCanvasFactory;this.intentStates[n]||(this.intentStates[n]=Object.create(null));var a=this.intentStates[n];a.displayReadyCapability||(a.receivingOperatorList=!0,a.displayReadyCapability=(0,l.createPromiseCapability)(),a.operatorList={fnArray:[],argsArray:[],lastChunk:!1},this.stats.time("Page Request"),this.transport.messageHandler.send("RenderPageRequest",{pageIndex:this.pageNumber-1,intent:n,renderInteractiveForms:!0===e.renderInteractiveForms}));var s=function t(e){var n=a.renderTasks.indexOf(c);n>=0&&a.renderTasks.splice(n,1),r.cleanupAfterRender&&(r.pendingCleanup=!0),r._tryCleanup(),e?c.capability.reject(e):c.capability.resolve(),i.timeEnd("Rendering"),i.timeEnd("Overall")},c=new R(s,e,this.objs,this.commonObjs,a.operatorList,this.pageNumber,o);c.useRequestAnimationFrame="print"!==n,a.renderTasks||(a.renderTasks=[]),a.renderTasks.push(c);var u=c.task;return e.continueCallback&&((0,l.deprecated)("render is used with continueCallback parameter"),u.onContinue=e.continueCallback),a.displayReadyCapability.promise.then(function(t){if(r.pendingCleanup)return void s();i.time("Rendering"),c.initializeGraphics(t),c.operatorListChanged()}).catch(s),u},getOperatorList:function t(){function e(){if(i.operatorList.lastChunk){i.opListReadCapability.resolve(i.operatorList);var t=i.renderTasks.indexOf(n);t>=0&&i.renderTasks.splice(t,1)}}var r="oplist";this.intentStates.oplist||(this.intentStates.oplist=Object.create(null));var i=this.intentStates.oplist,n;return i.opListReadCapability||(n={},n.operatorListChanged=e,i.receivingOperatorList=!0,i.opListReadCapability=(0,l.createPromiseCapability)(),i.renderTasks=[],i.renderTasks.push(n),i.operatorList={fnArray:[],argsArray:[],lastChunk:!1},this.transport.messageHandler.send("RenderPageRequest",{pageIndex:this.pageIndex,intent:"oplist"})),i.opListReadCapability.promise},streamTextContent:function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=100;return this.transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this.pageNumber-1,normalizeWhitespace:!0===e.normalizeWhitespace,combineTextItems:!0!==e.disableCombineTextItems},{highWaterMark:100,size:function t(e){return e.items.length}})},getTextContent:function t(e){e=e||{};var r=this.streamTextContent(e);return new Promise(function(t,e){function i(){n.read().then(function(e){var r=e.value;if(e.done)return void t(o);l.Util.extendObj(o.styles,r.styles),l.Util.appendToArray(o.items,r.items),i()},e)}var n=r.getReader(),o={items:[],styles:Object.create(null)};i()})},_destroy:function t(){this.destroyed=!0,this.transport.pageCache[this.pageIndex]=null;var e=[];return Object.keys(this.intentStates).forEach(function(t){if("oplist"!==t){this.intentStates[t].renderTasks.forEach(function(t){var r=t.capability.promise.catch(function(){});e.push(r),t.cancel()})}},this),this.objs.clear(),this.annotationsPromise=null,this.pendingCleanup=!1,Promise.all(e)},destroy:function t(){(0,l.deprecated)("page destroy method, use cleanup() instead"),this.cleanup()},cleanup:function t(){this.pendingCleanup=!0,this._tryCleanup()},_tryCleanup:function t(){this.pendingCleanup&&!Object.keys(this.intentStates).some(function(t){var e=this.intentStates[t];return 0!==e.renderTasks.length||e.receivingOperatorList},this)&&(Object.keys(this.intentStates).forEach(function(t){delete this.intentStates[t]},this),this.objs.clear(),this.annotationsPromise=null,this.pendingCleanup=!1)},_startRenderPage:function t(e,r){var i=this.intentStates[r];i.displayReadyCapability&&i.displayReadyCapability.resolve(e)},_renderPageChunk:function t(e,r){var i=this.intentStates[r],n,o;for(n=0,o=e.length;n<o;n++)i.operatorList.fnArray.push(e.fnArray[n]),i.operatorList.argsArray.push(e.argsArray[n]);for(i.operatorList.lastChunk=e.lastChunk,n=0;n<i.renderTasks.length;n++)i.renderTasks[n].operatorListChanged();e.lastChunk&&(i.receivingOperatorList=!1,this._tryCleanup())}},e}(),T=function(){function t(e){n(this,t),this._listeners=[],this._defer=e,this._deferred=Promise.resolve(void 0)}return s(t,[{key:"postMessage",value:function t(e,r){function i(t){if("object"!==(void 0===t?"undefined":c(t))||null===t)return t;if(o.has(t))return o.get(t);var e,n;if((n=t.buffer)&&(0,l.isArrayBuffer)(n)){var a=r&&r.indexOf(n)>=0;return e=t===n?t:a?new t.constructor(n,t.byteOffset,t.byteLength):new t.constructor(t),o.set(t,e),e}e=(0,l.isArray)(t)?[]:{},o.set(t,e);for(var s in t){for(var h,u=t;!(h=Object.getOwnPropertyDescriptor(u,s));)u=Object.getPrototypeOf(u);void 0!==h.value&&"function"!=typeof h.value&&(e[s]=i(h.value))}return e}var n=this;if(!this._defer)return void this._listeners.forEach(function(t){t.call(this,{data:e})},this);var o=new WeakMap,a={data:i(e)};this._deferred.then(function(){n._listeners.forEach(function(t){t.call(this,a)},n)})}},{key:"addEventListener",value:function t(e,r){this._listeners.push(r)}},{key:"removeEventListener",value:function t(e,r){var i=this._listeners.indexOf(r);this._listeners.splice(i,1)}},{key:"terminate",value:function t(){this._listeners=[]}}]),t}(),k=function t(){function e(){if(void 0!==v)return v;if((0,h.getDefaultSetting)("workerSrc"))return(0,h.getDefaultSetting)("workerSrc");if(b)return b.replace(/(\.(?:min\.)?js)(\?.*)?$/i,".worker$1$2");throw new Error("No PDFJS.workerSrc specified")}function r(){var t;return a?a.promise:(a=(0,l.createPromiseCapability)(),(y||function(t){l.Util.loadScript(e(),function(){t(window.pdfjsDistBuildPdfWorker.WorkerMessageHandler)})})(a.resolve),a.promise)}function i(t){var e="importScripts('"+t+"');";return URL.createObjectURL(new Blob([e]))}function n(t,e){if(e&&s.has(e))throw new Error("Cannot use more than one PDFWorker per port");if(this.name=t,this.destroyed=!1,this._readyCapability=(0,l.createPromiseCapability)(),this._port=null,this._webWorker=null,this._messageHandler=null,e)return s.set(e,this),void this._initializeFromPort(e);this._initialize()}var o=0,a=void 0,s=new WeakMap;return n.prototype={get promise(){return this._readyCapability.promise},get port(){return this._port},get messageHandler(){return this._messageHandler},_initializeFromPort:function t(e){this._port=e,this._messageHandler=new l.MessageHandler("main","worker",e),this._messageHandler.on("ready",function(){}),this._readyCapability.resolve()},_initialize:function t(){var r=this;if(!g&&!(0,h.getDefaultSetting)("disableWorker")&&"undefined"!=typeof Worker){var n=e();try{(0,l.isSameOrigin)(window.location.href,n)||(n=i(new URL(n,window.location).href));var o=new Worker(n),a=new l.MessageHandler("main","worker",o),s=function t(){o.removeEventListener("error",c),a.destroy(),o.terminate(),r.destroyed?r._readyCapability.reject(new Error("Worker was destroyed")):r._setupFakeWorker()},c=function t(){r._webWorker||s()};o.addEventListener("error",c),a.on("test",function(t){if(o.removeEventListener("error",c),r.destroyed)return void s();t&&t.supportTypedArray?(r._messageHandler=a,r._port=o,r._webWorker=o,t.supportTransfers||(m=!0),r._readyCapability.resolve(),a.send("configure",{verbosity:(0,l.getVerbosityLevel)()})):(r._setupFakeWorker(),a.destroy(),o.terminate())}),a.on("console_log",function(t){console.log.apply(console,t)}),a.on("console_error",function(t){console.error.apply(console,t)}),a.on("ready",function(t){if(o.removeEventListener("error",c),r.destroyed)return void s();try{u()}catch(t){r._setupFakeWorker()}});var u=function t(){var e=(0,h.getDefaultSetting)("postMessageTransfers")&&!m,r=new Uint8Array([e?255:0]);try{a.send("test",r,[r.buffer])}catch(t){(0,l.info)("Cannot use postMessage transfers"),r[0]=0,a.send("test",r)}};return void u()}catch(t){(0,l.info)("The worker has been disabled.")}}this._setupFakeWorker()},_setupFakeWorker:function t(){var e=this;g||(0,h.getDefaultSetting)("disableWorker")||((0,l.warn)("Setting up fake worker."),g=!0),r().then(function(t){if(e.destroyed)return void e._readyCapability.reject(new Error("Worker was destroyed"));var r=Uint8Array!==Float32Array,i=new T(r);e._port=i;var n="fake"+o++,a=new l.MessageHandler(n+"_worker",n,i);t.setup(a,i);var s=new l.MessageHandler(n,n+"_worker",i);e._messageHandler=s,e._readyCapability.resolve()})},destroy:function t(){this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}},n.fromPort=function(t){return s.has(t)?s.get(t):new n(null,t)},n}(),P=function t(){function e(t,e,r,i){this.messageHandler=t,this.loadingTask=e,this.pdfDataRangeTransport=r,this.commonObjs=new E,this.fontLoader=new u.FontLoader(e.docId),this.CMapReaderFactory=new i({baseUrl:(0,h.getDefaultSetting)("cMapUrl"),isCompressed:(0,h.getDefaultSetting)("cMapPacked")}),this.destroyed=!1,this.destroyCapability=null,this._passwordCapability=null,this.pageCache=[],this.pagePromises=[],this.downloadInfoCapability=(0,l.createPromiseCapability)(),this.setupMessageHandler()}return e.prototype={destroy:function t(){var e=this;if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=(0,l.createPromiseCapability)(),this._passwordCapability&&this._passwordCapability.reject(new Error("Worker was destroyed during onPassword callback"));var r=[];this.pageCache.forEach(function(t){t&&r.push(t._destroy())}),this.pageCache=[],this.pagePromises=[];var i=this.messageHandler.sendWithPromise("Terminate",null);return r.push(i),Promise.all(r).then(function(){e.fontLoader.clear(),e.pdfDataRangeTransport&&(e.pdfDataRangeTransport.abort(),e.pdfDataRangeTransport=null),e.messageHandler&&(e.messageHandler.destroy(),e.messageHandler=null),e.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise},setupMessageHandler:function t(){var e=this.messageHandler,r=this.loadingTask,i=this.pdfDataRangeTransport;i&&(i.addRangeListener(function(t,r){e.send("OnDataRange",{begin:t,chunk:r})}),i.addProgressListener(function(t){e.send("OnDataProgress",{loaded:t})}),i.addProgressiveReadListener(function(t){e.send("OnDataRange",{chunk:t})}),e.on("RequestDataRange",function t(e){i.requestDataRange(e.begin,e.end)},this)),e.on("GetDoc",function t(e){var r=e.pdfInfo;this.numPages=e.pdfInfo.numPages;var i=this.loadingTask,n=new C(r,this,i);this.pdfDocument=n,i._capability.resolve(n)},this),e.on("PasswordRequest",function t(e){var i=this;if(this._passwordCapability=(0,l.createPromiseCapability)(),r.onPassword){var n=function t(e){i._passwordCapability.resolve({password:e})};r.onPassword(n,e.code)}else this._passwordCapability.reject(new l.PasswordException(e.message,e.code));return this._passwordCapability.promise},this),e.on("PasswordException",function t(e){r._capability.reject(new l.PasswordException(e.message,e.code))},this),e.on("InvalidPDF",function t(e){this.loadingTask._capability.reject(new l.InvalidPDFException(e.message))},this),e.on("MissingPDF",function t(e){this.loadingTask._capability.reject(new l.MissingPDFException(e.message))},this),e.on("UnexpectedResponse",function t(e){this.loadingTask._capability.reject(new l.UnexpectedResponseException(e.message,e.status))},this),e.on("UnknownError",function t(e){this.loadingTask._capability.reject(new l.UnknownErrorException(e.message,e.details))},this),e.on("DataLoaded",function t(e){this.downloadInfoCapability.resolve(e)},this),e.on("PDFManagerReady",function t(e){this.pdfDataRangeTransport&&this.pdfDataRangeTransport.transportReady()},this),e.on("StartRenderPage",function t(e){if(!this.destroyed){var r=this.pageCache[e.pageIndex];r.stats.timeEnd("Page Request"),r._startRenderPage(e.transparency,e.intent)}},this),e.on("RenderPageChunk",function t(e){if(!this.destroyed){this.pageCache[e.pageIndex]._renderPageChunk(e.operatorList,e.intent)}},this),e.on("commonobj",function t(e){var r=this;if(!this.destroyed){var i=e[0],n=e[1];if(!this.commonObjs.hasData(i))switch(n){case"Font":var o=e[2];if("error"in o){var a=o.error;(0,l.warn)("Error during font loading: "+a),this.commonObjs.resolve(i,a);break}var s=null;(0,h.getDefaultSetting)("pdfBug")&&l.globalScope.FontInspector&&l.globalScope.FontInspector.enabled&&(s={registerFont:function t(e,r){l.globalScope.FontInspector.fontAdded(e,r)}});var c=new u.FontFaceObject(o,{isEvalSuported:(0,h.getDefaultSetting)("isEvalSupported"),disableFontFace:(0,h.getDefaultSetting)("disableFontFace"),fontRegistry:s}),f=function t(e){r.commonObjs.resolve(i,c)};this.fontLoader.bind([c],f);break;case"FontPath":this.commonObjs.resolve(i,e[2]);break;default:throw new Error("Got unknown common object type "+n)}}},this),e.on("obj",function t(e){if(!this.destroyed){var r=e[0],i=e[1],n=e[2],o=this.pageCache[i],a;if(!o.objs.hasData(r))switch(n){case"JpegStream":a=e[3],(0,l.loadJpegStream)(r,a,o.objs);break;case"Image":a=e[3],o.objs.resolve(r,a);var s=8e6;a&&"data"in a&&a.data.length>8e6&&(o.cleanupAfterRender=!0);break;default:throw new Error("Got unknown object type "+n)}}},this),e.on("DocProgress",function t(e){if(!this.destroyed){var r=this.loadingTask;r.onProgress&&r.onProgress({loaded:e.loaded,total:e.total})}},this),e.on("PageError",function t(e){if(!this.destroyed){var r=this.pageCache[e.pageNum-1],i=r.intentStates[e.intent];if(!i.displayReadyCapability)throw new Error(e.error);if(i.displayReadyCapability.reject(e.error),i.operatorList){i.operatorList.lastChunk=!0;for(var n=0;n<i.renderTasks.length;n++)i.renderTasks[n].operatorListChanged()}}},this),e.on("UnsupportedFeature",function t(e){if(!this.destroyed){var r=e.featureId,i=this.loadingTask;i.onUnsupportedFeature&&i.onUnsupportedFeature(r),L.notify(r)}},this),e.on("JpegDecode",function(t){if(this.destroyed)return Promise.reject(new Error("Worker was destroyed"));if("undefined"==typeof document)return Promise.reject(new Error('"document" is not defined.'));var e=t[0],r=t[1];return 3!==r&&1!==r?Promise.reject(new Error("Only 3 components or 1 component can be returned")):new Promise(function(t,i){var n=new Image;n.onload=function(){var e=n.width,i=n.height,o=e*i,a=4*o,s=new Uint8Array(o*r),c=document.createElement("canvas");c.width=e,c.height=i;var l=c.getContext("2d");l.drawImage(n,0,0);var h=l.getImageData(0,0,e,i).data,u,f;if(3===r)for(u=0,f=0;u<a;u+=4,f+=3)s[f]=h[u],s[f+1]=h[u+1],s[f+2]=h[u+2];else if(1===r)for(u=0,f=0;u<a;u+=4,f++)s[f]=h[u];t({data:s,width:e,height:i})},n.onerror=function(){i(new Error("JpegDecode failed to load image"))},n.src=e})},this),e.on("FetchBuiltInCMap",function(t){return this.destroyed?Promise.reject(new Error("Worker was destroyed")):this.CMapReaderFactory.fetch({name:t.name})},this)},getData:function t(){return this.messageHandler.sendWithPromise("GetData",null)},getPage:function t(e,r){var i=this;if(!(0,l.isInt)(e)||e<=0||e>this.numPages)return Promise.reject(new Error("Invalid page request"));var n=e-1;if(n in this.pagePromises)return this.pagePromises[n];var o=this.messageHandler.sendWithPromise("GetPage",{pageIndex:n}).then(function(t){if(i.destroyed)throw new Error("Transport destroyed");var e=new A(n,t,i);return i.pageCache[n]=e,e});return this.pagePromises[n]=o,o},getPageIndex:function t(e){return this.messageHandler.sendWithPromise("GetPageIndex",{ref:e}).catch(function(t){return Promise.reject(new Error(t))})},getAnnotations:function t(e,r){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:e,intent:r})},getDestinations:function t(){return this.messageHandler.sendWithPromise("GetDestinations",null)},getDestination:function t(e){return this.messageHandler.sendWithPromise("GetDestination",{id:e})},getPageLabels:function t(){return this.messageHandler.sendWithPromise("GetPageLabels",null)},getPageMode:function t(){return this.messageHandler.sendWithPromise("GetPageMode",null)},getAttachments:function t(){return this.messageHandler.sendWithPromise("GetAttachments",null)},getJavaScript:function t(){return this.messageHandler.sendWithPromise("GetJavaScript",null)},getOutline:function t(){return this.messageHandler.sendWithPromise("GetOutline",null)},getMetadata:function t(){return this.messageHandler.sendWithPromise("GetMetadata",null).then(function t(e){return{info:e[0],metadata:e[1]?new d.Metadata(e[1]):null}})},getStats:function t(){return this.messageHandler.sendWithPromise("GetStats",null)},startCleanup:function t(){var e=this;this.messageHandler.sendWithPromise("Cleanup",null).then(function(){for(var t=0,r=e.pageCache.length;t<r;t++){var i=e.pageCache[t];i&&i.cleanup()}e.commonObjs.clear(),e.fontLoader.clear()})}},e}(),E=function t(){function e(){this.objs=Object.create(null)}return e.prototype={ensureObj:function t(e){if(this.objs[e])return this.objs[e];var r={capability:(0,l.createPromiseCapability)(),data:null,resolved:!1};return this.objs[e]=r,r},get:function t(e,r){if(r)return this.ensureObj(e).capability.promise.then(r),null;var i=this.objs[e];if(!i||!i.resolved)throw new Error("Requesting object that isn't resolved yet "+e);return i.data},resolve:function t(e,r){var i=this.ensureObj(e);i.resolved=!0,i.data=r,i.capability.resolve(r)},isResolved:function t(e){var r=this.objs;return!!r[e]&&r[e].resolved},hasData:function t(e){return this.isResolved(e)},getData:function t(e){var r=this.objs;return r[e]&&r[e].resolved?r[e].data:null},clear:function t(){this.objs=Object.create(null)}},e}(),O=function t(){function e(t){this._internalRenderTask=t,this.onContinue=null}return e.prototype={get promise(){return this._internalRenderTask.capability.promise},cancel:function t(){this._internalRenderTask.cancel()},then:function t(e,r){return this.promise.then.apply(this.promise,arguments)}},e}(),R=function t(){function e(t,e,r,i,n,o,a){this.callback=t,this.params=e,this.objs=r,this.commonObjs=i,this.operatorListIdx=null,this.operatorList=n,this.pageNumber=o,this.canvasFactory=a,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this.useRequestAnimationFrame=!1,this.cancelled=!1,this.capability=(0,l.createPromiseCapability)(),this.task=new O(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=e.canvasContext.canvas}var r=new WeakMap;return e.prototype={initializeGraphics:function t(e){if(this._canvas){if(r.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");r.set(this._canvas,this)}if(!this.cancelled){(0,h.getDefaultSetting)("pdfBug")&&l.globalScope.StepperManager&&l.globalScope.StepperManager.enabled&&(this.stepper=l.globalScope.StepperManager.create(this.pageNumber-1),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());var i=this.params;this.gfx=new f.CanvasGraphics(i.canvasContext,this.commonObjs,this.objs,this.canvasFactory,i.imageLayer),this.gfx.beginDrawing({transform:i.transform,viewport:i.viewport,transparency:e,background:i.background}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback&&this.graphicsReadyCallback()}},cancel:function t(){this.running=!1,this.cancelled=!0,this._canvas&&r.delete(this._canvas),(0,h.getDefaultSetting)("pdfjsNext")?this.callback(new h.RenderingCancelledException("Rendering cancelled, page "+this.pageNumber,"canvas")):this.callback("cancelled")},operatorListChanged:function t(){if(!this.graphicsReady)return void(this.graphicsReadyCallback||(this.graphicsReadyCallback=this._continueBound));this.stepper&&this.stepper.updateOperatorList(this.operatorList),this.running||this._continue()},_continue:function t(){this.running=!0,this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())},_scheduleNext:function t(){this.useRequestAnimationFrame&&"undefined"!=typeof window?window.requestAnimationFrame(this._nextBound):Promise.resolve(void 0).then(this._nextBound)},_next:function t(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),this._canvas&&r.delete(this._canvas),this.callback())))}},e}(),L=function t(){var e=[];return{listen:function t(r){(0,l.deprecated)("Global UnsupportedManager.listen is used: use PDFDocumentLoadingTask.onUnsupportedFeature instead"),e.push(r)},notify:function t(r){for(var i=0,n=e.length;i<n;i++)e[i](r)}}}(),D,I;e.version=D="1.8.575",e.build=I="bd8c1211",e.getDocument=o,e.LoopbackPort=T,e.PDFDataRangeTransport=x,e.PDFWorker=k,e.PDFDocumentProxy=C,e.PDFPageProxy=A,e._UnsupportedManager=L,e.version=D,e.build=I},function(t,e,o){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.SVGGraphics=void 0;var a=o(0),s=function t(){throw new Error("Not implemented: SVGGraphics")},c={fontStyle:"normal",fontWeight:"normal",fillColor:"#000000"},l=function t(){function e(t,e,r){for(var i=-1,n=e;n<r;n++){var o=255&(i^t[n]);i=i>>>8^d[o]}return-1^i}function o(t,r,i,n){var o=n,a=r.length;i[o]=a>>24&255,i[o+1]=a>>16&255,i[o+2]=a>>8&255,i[o+3]=255&a,o+=4,i[o]=255&t.charCodeAt(0),i[o+1]=255&t.charCodeAt(1),i[o+2]=255&t.charCodeAt(2),i[o+3]=255&t.charCodeAt(3),o+=4,i.set(r,o),o+=r.length;var s=e(i,n+4,o);i[o]=s>>24&255,i[o+1]=s>>16&255,i[o+2]=s>>8&255,i[o+3]=255&s}function s(t,e,r){for(var i=1,n=0,o=e;o<r;++o)i=(i+(255&t[o]))%65521,n=(n+i)%65521;return n<<16|i}function c(t){if(!(0,a.isNodeJS)())return l(t);try{var e;e=parseInt(i.versions.node)>=8?t:new n(t);var o=r(42).deflateSync(e,{level:9});return o instanceof Uint8Array?o:new Uint8Array(o)}catch(t){(0,a.warn)("Not compressing PNG because zlib.deflateSync is unavailable: "+t)}return l(t)}function l(t){var e=t.length,r=65535,i=Math.ceil(e/65535),n=new Uint8Array(2+e+5*i+4),o=0;n[o++]=120,n[o++]=156;for(var a=0;e>65535;)n[o++]=0,n[o++]=255,n[o++]=255,n[o++]=0,n[o++]=0,n.set(t.subarray(a,a+65535),o),o+=65535,a+=65535,e-=65535;n[o++]=1,n[o++]=255&e,n[o++]=e>>8&255,n[o++]=255&~e,n[o++]=(65535&~e)>>8&255,n.set(t.subarray(a),o),o+=t.length-a;var c=s(t,0,t.length);return n[o++]=c>>24&255,n[o++]=c>>16&255,n[o++]=c>>8&255,n[o++]=255&c,n}function h(t,e,r){var i=t.width,n=t.height,s,l,h,d=t.data;switch(e){case a.ImageKind.GRAYSCALE_1BPP:l=0,s=1,h=i+7>>3;break;case a.ImageKind.RGB_24BPP:l=2,s=8,h=3*i;break;case a.ImageKind.RGBA_32BPP:l=6,s=8,h=4*i;break;default:throw new Error("invalid format")}var p=new Uint8Array((1+h)*n),g=0,v=0,m,b;for(m=0;m<n;++m)p[g++]=0,p.set(d.subarray(v,v+h),g),v+=h,g+=h;if(e===a.ImageKind.GRAYSCALE_1BPP)for(g=0,m=0;m<n;m++)for(g++,b=0;b<h;b++)p[g++]^=255;var y=new Uint8Array([i>>24&255,i>>16&255,i>>8&255,255&i,n>>24&255,n>>16&255,n>>8&255,255&n,s,l,0,0,0]),_=c(p),w=u.length+3*f+y.length+_.length,S=new Uint8Array(w),x=0;return S.set(u,x),x+=u.length,o("IHDR",y,S,x),x+=f+y.length,o("IDATA",_,S,x),x+=f+_.length,o("IEND",new Uint8Array(0),S,x),(0,a.createObjectURL)(S,"image/png",r)}for(var u=new Uint8Array([137,80,78,71,13,10,26,10]),f=12,d=new Int32Array(256),p=0;p<256;p++){for(var g=p,v=0;v<8;v++)g=1&g?3988292384^g>>1&2147483647:g>>1&2147483647;d[p]=g}return function t(e,r){return h(e,void 0===e.kind?a.ImageKind.GRAYSCALE_1BPP:e.kind,r)}}(),h=function t(){function e(){this.fontSizeScale=1,this.fontWeight=c.fontWeight,this.fontSize=0,this.textMatrix=a.IDENTITY_MATRIX,this.fontMatrix=a.FONT_IDENTITY_MATRIX,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRise=0,this.fillColor=c.fillColor,this.strokeColor="#000000",this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.lineJoin="",this.lineCap="",this.miterLimit=0,this.dashArray=[],this.dashPhase=0,this.dependencies=[],this.activeClipUrl=null,this.clipGroup=null,this.maskId=""}return e.prototype={clone:function t(){return Object.create(this)},setCurrentPoint:function t(e,r){this.x=e,this.y=r}},e}();e.SVGGraphics=s=function t(){function e(t){for(var e=[],r=[],i=t.length,n=0;n<i;n++)"save"!==t[n].fn?"restore"===t[n].fn?e=r.pop():e.push(t[n]):(e.push({fnId:92,fn:"group",items:[]}),r.push(e),e=e[e.length-1].items);return e}function r(t){if(t===(0|t))return t.toString();var e=t.toFixed(10),r=e.length-1;if("0"!==e[r])return e;do{r--}while("0"===e[r]);return e.substr(0,"."===e[r]?r:r+1)}function i(t){if(0===t[4]&&0===t[5]){if(0===t[1]&&0===t[2])return 1===t[0]&&1===t[3]?"":"scale("+r(t[0])+" "+r(t[3])+")";if(t[0]===t[3]&&t[1]===-t[2]){return"rotate("+r(180*Math.acos(t[0])/Math.PI)+")"}}else if(1===t[0]&&0===t[1]&&0===t[2]&&1===t[3])return"translate("+r(t[4])+" "+r(t[5])+")";return"matrix("+r(t[0])+" "+r(t[1])+" "+r(t[2])+" "+r(t[3])+" "+r(t[4])+" "+r(t[5])+")"}function n(t,e,r){this.current=new h,this.transformMatrix=a.IDENTITY_MATRIX,this.transformStack=[],this.extraStack=[],this.commonObjs=t,this.objs=e,this.pendingClip=null,this.pendingEOFill=!1,this.embedFonts=!1,this.embeddedFonts=Object.create(null),this.cssStyle=null,this.forceDataSchema=!!r}var o="http://www.w3.org/2000/svg",s="http://www.w3.org/1999/xlink",u=["butt","round","square"],f=["miter","round","bevel"],d=0,p=0;return n.prototype={save:function t(){this.transformStack.push(this.transformMatrix);var e=this.current;this.extraStack.push(e),this.current=e.clone()},restore:function t(){this.transformMatrix=this.transformStack.pop(),this.current=this.extraStack.pop(),this.pendingClip=null,this.tgrp=null},group:function t(e){this.save(),this.executeOpTree(e),this.restore()},loadDependencies:function t(e){for(var r=this,i=e.fnArray,n=i.length,o=e.argsArray,s=0;s<n;s++)if(a.OPS.dependency===i[s])for(var c=o[s],l=0,h=c.length;l<h;l++){var u=c[l],f="g_"===u.substring(0,2),d;d=f?new Promise(function(t){r.commonObjs.get(u,t)}):new Promise(function(t){r.objs.get(u,t)}),this.current.dependencies.push(d)}return Promise.all(this.current.dependencies)},transform:function t(e,r,i,n,o,s){var c=[e,r,i,n,o,s];this.transformMatrix=a.Util.transform(this.transformMatrix,c),this.tgrp=null},getSVG:function t(e,r){var i=this;this.viewport=r;var n=this._initialize(r);return this.loadDependencies(e).then(function(){i.transformMatrix=a.IDENTITY_MATRIX;var t=i.convertOpList(e);return i.executeOpTree(t),n})},convertOpList:function t(r){var i=r.argsArray,n=r.fnArray,o=n.length,s=[],c=[];for(var l in a.OPS)s[a.OPS[l]]=l;for(var h=0;h<o;h++){var u=n[h];c.push({fnId:u,fn:s[u],args:i[h]})}return e(c)},executeOpTree:function t(e){for(var r=e.length,i=0;i<r;i++){var n=e[i].fn,o=e[i].fnId,s=e[i].args;switch(0|o){case a.OPS.beginText:this.beginText();break;case a.OPS.setLeading:this.setLeading(s);break;case a.OPS.setLeadingMoveText:this.setLeadingMoveText(s[0],s[1]);break;case a.OPS.setFont:this.setFont(s);break;case a.OPS.showText:case a.OPS.showSpacedText:this.showText(s[0]);break;case a.OPS.endText:this.endText();break;case a.OPS.moveText:this.moveText(s[0],s[1]);break;case a.OPS.setCharSpacing:this.setCharSpacing(s[0]);break;case a.OPS.setWordSpacing:this.setWordSpacing(s[0]);break;case a.OPS.setHScale:this.setHScale(s[0]);break;case a.OPS.setTextMatrix:this.setTextMatrix(s[0],s[1],s[2],s[3],s[4],s[5]);break;case a.OPS.setLineWidth:this.setLineWidth(s[0]);break;case a.OPS.setLineJoin:this.setLineJoin(s[0]);break;case a.OPS.setLineCap:this.setLineCap(s[0]);break;case a.OPS.setMiterLimit:this.setMiterLimit(s[0]);break;case a.OPS.setFillRGBColor:this.setFillRGBColor(s[0],s[1],s[2]);break;case a.OPS.setStrokeRGBColor:this.setStrokeRGBColor(s[0],s[1],s[2]);break;case a.OPS.setDash:this.setDash(s[0],s[1]);break;case a.OPS.setGState:this.setGState(s[0]);break;case a.OPS.fill:this.fill();break;case a.OPS.eoFill:this.eoFill();break;case a.OPS.stroke:this.stroke();break;case a.OPS.fillStroke:this.fillStroke();break;case a.OPS.eoFillStroke:this.eoFillStroke();break;case a.OPS.clip:this.clip("nonzero");break;case a.OPS.eoClip:this.clip("evenodd");break;case a.OPS.paintSolidColorImageMask:this.paintSolidColorImageMask();break;case a.OPS.paintJpegXObject:this.paintJpegXObject(s[0],s[1],s[2]);break;case a.OPS.paintImageXObject:this.paintImageXObject(s[0]);break;case a.OPS.paintInlineImageXObject:this.paintInlineImageXObject(s[0]);break;case a.OPS.paintImageMaskXObject:this.paintImageMaskXObject(s[0]);break;case a.OPS.paintFormXObjectBegin:this.paintFormXObjectBegin(s[0],s[1]);break;case a.OPS.paintFormXObjectEnd:this.paintFormXObjectEnd();break;case a.OPS.closePath:this.closePath();break;case a.OPS.closeStroke:this.closeStroke();break;case a.OPS.closeFillStroke:this.closeFillStroke();break;case a.OPS.nextLine:this.nextLine();break;case a.OPS.transform:this.transform(s[0],s[1],s[2],s[3],s[4],s[5]);break;case a.OPS.constructPath:this.constructPath(s[0],s[1]);break;case a.OPS.endPath:this.endPath();break;case 92:this.group(e[i].items);break;default:(0,a.warn)("Unimplemented operator "+n)}}},setWordSpacing:function t(e){this.current.wordSpacing=e},setCharSpacing:function t(e){this.current.charSpacing=e},nextLine:function t(){this.moveText(0,this.current.leading)},setTextMatrix:function t(e,i,n,a,s,c){var l=this.current;this.current.textMatrix=this.current.lineMatrix=[e,i,n,a,s,c],this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0,l.xcoords=[],l.tspan=document.createElementNS(o,"svg:tspan"),l.tspan.setAttributeNS(null,"font-family",l.fontFamily),l.tspan.setAttributeNS(null,"font-size",r(l.fontSize)+"px"),l.tspan.setAttributeNS(null,"y",r(-l.y)),l.txtElement=document.createElementNS(o,"svg:text"),l.txtElement.appendChild(l.tspan)},beginText:function t(){this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0,this.current.textMatrix=a.IDENTITY_MATRIX,this.current.lineMatrix=a.IDENTITY_MATRIX,this.current.tspan=document.createElementNS(o,"svg:tspan"),this.current.txtElement=document.createElementNS(o,"svg:text"),this.current.txtgrp=document.createElementNS(o,"svg:g"),this.current.xcoords=[]},moveText:function t(e,i){var n=this.current;this.current.x=this.current.lineX+=e,this.current.y=this.current.lineY+=i,n.xcoords=[],n.tspan=document.createElementNS(o,"svg:tspan"),n.tspan.setAttributeNS(null,"font-family",n.fontFamily),n.tspan.setAttributeNS(null,"font-size",r(n.fontSize)+"px"),n.tspan.setAttributeNS(null,"y",r(-n.y))},showText:function t(e){var n=this.current,o=n.font,s=n.fontSize;if(0!==s){var l=n.charSpacing,h=n.wordSpacing,u=n.fontDirection,f=n.textHScale*u,d=e.length,p=o.vertical,g=s*n.fontMatrix[0],v=0,m;for(m=0;m<d;++m){var b=e[m];if(null!==b)if((0,a.isNum)(b))v+=-b*s*.001;else{n.xcoords.push(n.x+v*f);var y=b.width,_=b.fontChar,w=(b.isSpace?h:0)+l,S=y*g+w*u;v+=S,n.tspan.textContent+=_}else v+=u*h}p?n.y-=v*f:n.x+=v*f,n.tspan.setAttributeNS(null,"x",n.xcoords.map(r).join(" ")),n.tspan.setAttributeNS(null,"y",r(-n.y)),n.tspan.setAttributeNS(null,"font-family",n.fontFamily),n.tspan.setAttributeNS(null,"font-size",r(n.fontSize)+"px"),n.fontStyle!==c.fontStyle&&n.tspan.setAttributeNS(null,"font-style",n.fontStyle),n.fontWeight!==c.fontWeight&&n.tspan.setAttributeNS(null,"font-weight",n.fontWeight),n.fillColor!==c.fillColor&&n.tspan.setAttributeNS(null,"fill",n.fillColor),n.txtElement.setAttributeNS(null,"transform",i(n.textMatrix)+" scale(1, -1)"),n.txtElement.setAttributeNS("http://www.w3.org/XML/1998/namespace","xml:space","preserve"),n.txtElement.appendChild(n.tspan),n.txtgrp.appendChild(n.txtElement),this._ensureTransformGroup().appendChild(n.txtElement)}},setLeadingMoveText:function t(e,r){this.setLeading(-r),this.moveText(e,r)},addFontStyle:function t(e){this.cssStyle||(this.cssStyle=document.createElementNS(o,"svg:style"),this.cssStyle.setAttributeNS(null,"type","text/css"),this.defs.appendChild(this.cssStyle));var r=(0,a.createObjectURL)(e.data,e.mimetype,this.forceDataSchema);this.cssStyle.textContent+='@font-face { font-family: "'+e.loadedName+'"; src: url('+r+"); }\n"},setFont:function t(e){var i=this.current,n=this.commonObjs.get(e[0]),s=e[1];this.current.font=n,this.embedFonts&&n.data&&!this.embeddedFonts[n.loadedName]&&(this.addFontStyle(n),this.embeddedFonts[n.loadedName]=n),i.fontMatrix=n.fontMatrix?n.fontMatrix:a.FONT_IDENTITY_MATRIX;var c=n.black?n.bold?"bolder":"bold":n.bold?"bold":"normal",l=n.italic?"italic":"normal";s<0?(s=-s,i.fontDirection=-1):i.fontDirection=1,i.fontSize=s,i.fontFamily=n.loadedName,i.fontWeight=c,i.fontStyle=l,i.tspan=document.createElementNS(o,"svg:tspan"),i.tspan.setAttributeNS(null,"y",r(-i.y)),i.xcoords=[]},endText:function t(){},setLineWidth:function t(e){this.current.lineWidth=e},setLineCap:function t(e){this.current.lineCap=u[e]},setLineJoin:function t(e){this.current.lineJoin=f[e]},setMiterLimit:function t(e){this.current.miterLimit=e},setStrokeAlpha:function t(e){this.current.strokeAlpha=e},setStrokeRGBColor:function t(e,r,i){var n=a.Util.makeCssRgb(e,r,i);this.current.strokeColor=n},setFillAlpha:function t(e){this.current.fillAlpha=e},setFillRGBColor:function t(e,r,i){var n=a.Util.makeCssRgb(e,r,i);this.current.fillColor=n,this.current.tspan=document.createElementNS(o,"svg:tspan"),this.current.xcoords=[]},setDash:function t(e,r){this.current.dashArray=e,this.current.dashPhase=r},constructPath:function t(e,i){var n=this.current,s=n.x,c=n.y;n.path=document.createElementNS(o,"svg:path");for(var l=[],h=e.length,u=0,f=0;u<h;u++)switch(0|e[u]){case a.OPS.rectangle:s=i[f++],c=i[f++];var d=i[f++],p=i[f++],g=s+d,v=c+p;l.push("M",r(s),r(c),"L",r(g),r(c),"L",r(g),r(v),"L",r(s),r(v),"Z");break;case a.OPS.moveTo:s=i[f++],c=i[f++],l.push("M",r(s),r(c));break;case a.OPS.lineTo:s=i[f++],c=i[f++],l.push("L",r(s),r(c));break;case a.OPS.curveTo:s=i[f+4],c=i[f+5],l.push("C",r(i[f]),r(i[f+1]),r(i[f+2]),r(i[f+3]),r(s),r(c)),f+=6;break;case a.OPS.curveTo2:s=i[f+2],c=i[f+3],l.push("C",r(s),r(c),r(i[f]),r(i[f+1]),r(i[f+2]),r(i[f+3])),f+=4;break;case a.OPS.curveTo3:s=i[f+2],c=i[f+3],l.push("C",r(i[f]),r(i[f+1]),r(s),r(c),r(s),r(c)),f+=4;break;case a.OPS.closePath:l.push("Z")}n.path.setAttributeNS(null,"d",l.join(" ")),n.path.setAttributeNS(null,"fill","none"),this._ensureTransformGroup().appendChild(n.path),n.element=n.path,n.setCurrentPoint(s,c)},endPath:function t(){if(this.pendingClip){var e=this.current,r="clippath"+d;d++;var n=document.createElementNS(o,"svg:clipPath");n.setAttributeNS(null,"id",r),n.setAttributeNS(null,"transform",i(this.transformMatrix));var a=e.element.cloneNode();"evenodd"===this.pendingClip?a.setAttributeNS(null,"clip-rule","evenodd"):a.setAttributeNS(null,"clip-rule","nonzero"),this.pendingClip=null,n.appendChild(a),this.defs.appendChild(n),e.activeClipUrl&&(e.clipGroup=null,this.extraStack.forEach(function(t){t.clipGroup=null})),e.activeClipUrl="url(#"+r+")",this.tgrp=null}},clip:function t(e){this.pendingClip=e},closePath:function t(){var e=this.current,r=e.path.getAttributeNS(null,"d");r+="Z",e.path.setAttributeNS(null,"d",r)},setLeading:function t(e){this.current.leading=-e},setTextRise:function t(e){this.current.textRise=e},setHScale:function t(e){this.current.textHScale=e/100},setGState:function t(e){for(var r=0,i=e.length;r<i;r++){var n=e[r],o=n[0],s=n[1];switch(o){case"LW":this.setLineWidth(s);break;case"LC":this.setLineCap(s);break;case"LJ":this.setLineJoin(s);break;case"ML":this.setMiterLimit(s);break;case"D":this.setDash(s[0],s[1]);break;case"Font":this.setFont(s);break;case"CA":this.setStrokeAlpha(s);break;case"ca":this.setFillAlpha(s);break;default:(0,a.warn)("Unimplemented graphic state "+o)}}},fill:function t(){var e=this.current;e.element.setAttributeNS(null,"fill",e.fillColor),e.element.setAttributeNS(null,"fill-opacity",e.fillAlpha)},stroke:function t(){var e=this.current;e.element.setAttributeNS(null,"stroke",e.strokeColor),e.element.setAttributeNS(null,"stroke-opacity",e.strokeAlpha),e.element.setAttributeNS(null,"stroke-miterlimit",r(e.miterLimit)),e.element.setAttributeNS(null,"stroke-linecap",e.lineCap),e.element.setAttributeNS(null,"stroke-linejoin",e.lineJoin),e.element.setAttributeNS(null,"stroke-width",r(e.lineWidth)+"px"),e.element.setAttributeNS(null,"stroke-dasharray",e.dashArray.map(r).join(" ")),e.element.setAttributeNS(null,"stroke-dashoffset",r(e.dashPhase)+"px"),e.element.setAttributeNS(null,"fill","none")},eoFill:function t(){this.current.element.setAttributeNS(null,"fill-rule","evenodd"),this.fill()},fillStroke:function t(){this.stroke(),this.fill()},eoFillStroke:function t(){this.current.element.setAttributeNS(null,"fill-rule","evenodd"),this.fillStroke()},closeStroke:function t(){this.closePath(),this.stroke()},closeFillStroke:function t(){this.closePath(),this.fillStroke()},paintSolidColorImageMask:function t(){var e=this.current,r=document.createElementNS(o,"svg:rect");r.setAttributeNS(null,"x","0"),r.setAttributeNS(null,"y","0"),r.setAttributeNS(null,"width","1px"),r.setAttributeNS(null,"height","1px"),r.setAttributeNS(null,"fill",e.fillColor),this._ensureTransformGroup().appendChild(r)},paintJpegXObject:function t(e,i,n){var a=this.objs.get(e),c=document.createElementNS(o,"svg:image");c.setAttributeNS(s,"xlink:href",a.src),c.setAttributeNS(null,"width",r(i)),c.setAttributeNS(null,"height",r(n)),c.setAttributeNS(null,"x","0"),c.setAttributeNS(null,"y",r(-n)),c.setAttributeNS(null,"transform","scale("+r(1/i)+" "+r(-1/n)+")"),this._ensureTransformGroup().appendChild(c)},paintImageXObject:function t(e){var r=this.objs.get(e);if(!r)return void(0,a.warn)("Dependent image isn't ready yet");this.paintInlineImageXObject(r)},paintInlineImageXObject:function t(e,i){var n=e.width,a=e.height,c=l(e,this.forceDataSchema),h=document.createElementNS(o,"svg:rect");h.setAttributeNS(null,"x","0"),h.setAttributeNS(null,"y","0"),h.setAttributeNS(null,"width",r(n)),h.setAttributeNS(null,"height",r(a)),this.current.element=h,this.clip("nonzero");var u=document.createElementNS(o,"svg:image");u.setAttributeNS(s,"xlink:href",c),u.setAttributeNS(null,"x","0"),u.setAttributeNS(null,"y",r(-a)),u.setAttributeNS(null,"width",r(n)+"px"),u.setAttributeNS(null,"height",r(a)+"px"),u.setAttributeNS(null,"transform","scale("+r(1/n)+" "+r(-1/a)+")"),i?i.appendChild(u):this._ensureTransformGroup().appendChild(u)},paintImageMaskXObject:function t(e){var i=this.current,n=e.width,a=e.height,s=i.fillColor;i.maskId="mask"+p++;var c=document.createElementNS(o,"svg:mask");c.setAttributeNS(null,"id",i.maskId);var l=document.createElementNS(o,"svg:rect");l.setAttributeNS(null,"x","0"),l.setAttributeNS(null,"y","0"),l.setAttributeNS(null,"width",r(n)),l.setAttributeNS(null,"height",r(a)),l.setAttributeNS(null,"fill",s),l.setAttributeNS(null,"mask","url(#"+i.maskId+")"),this.defs.appendChild(c),this._ensureTransformGroup().appendChild(l),this.paintInlineImageXObject(e,c)},paintFormXObjectBegin:function t(e,i){if((0,a.isArray)(e)&&6===e.length&&this.transform(e[0],e[1],e[2],e[3],e[4],e[5]),(0,a.isArray)(i)&&4===i.length){var n=i[2]-i[0],s=i[3]-i[1],c=document.createElementNS(o,"svg:rect");c.setAttributeNS(null,"x",i[0]),c.setAttributeNS(null,"y",i[1]),c.setAttributeNS(null,"width",r(n)),c.setAttributeNS(null,"height",r(s)),this.current.element=c,this.clip("nonzero"),this.endPath()}},paintFormXObjectEnd:function t(){},_initialize:function t(e){var r=document.createElementNS(o,"svg:svg");r.setAttributeNS(null,"version","1.1"),r.setAttributeNS(null,"width",e.width+"px"),r.setAttributeNS(null,"height",e.height+"px"),r.setAttributeNS(null,"preserveAspectRatio","none"),r.setAttributeNS(null,"viewBox","0 0 "+e.width+" "+e.height);var n=document.createElementNS(o,"svg:defs");r.appendChild(n),this.defs=n;var a=document.createElementNS(o,"svg:g");return a.setAttributeNS(null,"transform",i(e.transform)),r.appendChild(a),this.svg=a,r},_ensureClipGroup:function t(){if(!this.current.clipGroup){var e=document.createElementNS(o,"svg:g");e.setAttributeNS(null,"clip-path",this.current.activeClipUrl),this.svg.appendChild(e),this.current.clipGroup=e}return this.current.clipGroup},_ensureTransformGroup:function t(){return this.tgrp||(this.tgrp=document.createElementNS(o,"svg:g"),this.tgrp.setAttributeNS(null,"transform",i(this.transformMatrix)),this.current.activeClipUrl?this._ensureClipGroup().appendChild(this.tgrp):this.svg.appendChild(this.tgrp)),this.tgrp}},n}(),e.SVGGraphics=s},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.renderTextLayer=void 0;var i=r(0),n=r(1),o=function t(){function e(t){return!f.test(t)}function r(t,r,o){var a=document.createElement("div"),s={style:null,angle:0,canvasWidth:0,isWhitespace:!1,originalTransform:null,paddingBottom:0,paddingLeft:0,paddingRight:0,paddingTop:0,scale:1};if(t._textDivs.push(a),e(r.str))return s.isWhitespace=!0,void t._textDivProperties.set(a,s);var c=i.Util.transform(t._viewport.transform,r.transform),l=Math.atan2(c[1],c[0]),h=o[r.fontName];h.vertical&&(l+=Math.PI/2);var u=Math.sqrt(c[2]*c[2]+c[3]*c[3]),f=u;h.ascent?f=h.ascent*f:h.descent&&(f=(1+h.descent)*f);var p,g;if(0===l?(p=c[4],g=c[5]-f):(p=c[4]+f*Math.sin(l),g=c[5]-f*Math.cos(l)),d[1]=p,d[3]=g,d[5]=u,d[7]=h.fontFamily,s.style=d.join(""),a.setAttribute("style",s.style),a.textContent=r.str,(0,n.getDefaultSetting)("pdfBug")&&(a.dataset.fontName=r.fontName),0!==l&&(s.angle=l*(180/Math.PI)),r.str.length>1&&(h.vertical?s.canvasWidth=r.height*t._viewport.scale:s.canvasWidth=r.width*t._viewport.scale),t._textDivProperties.set(a,s),t._textContentStream&&t._layoutText(a),t._enhanceTextSelection){var v=1,m=0;0!==l&&(v=Math.cos(l),m=Math.sin(l));var b=(h.vertical?r.height:r.width)*t._viewport.scale,y=u,_,w;0!==l?(_=[v,m,-m,v,p,g],w=i.Util.getAxialAlignedBoundingBox([0,0,b,y],_)):w=[p,g,p+b,g+y],t._bounds.push({left:w[0],top:w[1],right:w[2],bottom:w[3],div:a,size:[b,y],m:_})}}function o(t){if(!t._canceled){var e=t._textDivs,r=t._capability,i=e.length;if(i>u)return t._renderingDone=!0,void r.resolve();if(!t._textContentStream)for(var n=0;n<i;n++)t._layoutText(e[n]);t._renderingDone=!0,r.resolve()}}function a(t){for(var e=t._bounds,r=t._viewport,n=s(r.width,r.height,e),o=0;o<n.length;o++){var a=e[o].div,c=t._textDivProperties.get(a);if(0!==c.angle){var l=n[o],h=e[o],u=h.m,f=u[0],d=u[1],p=[[0,0],[0,h.size[1]],[h.size[0],0],h.size],g=new Float64Array(64);p.forEach(function(t,e){var r=i.Util.applyTransform(t,u);g[e+0]=f&&(l.left-r[0])/f,g[e+4]=d&&(l.top-r[1])/d,g[e+8]=f&&(l.right-r[0])/f,g[e+12]=d&&(l.bottom-r[1])/d,g[e+16]=d&&(l.left-r[0])/-d,g[e+20]=f&&(l.top-r[1])/f,g[e+24]=d&&(l.right-r[0])/-d,g[e+28]=f&&(l.bottom-r[1])/f,g[e+32]=f&&(l.left-r[0])/-f,g[e+36]=d&&(l.top-r[1])/-d,g[e+40]=f&&(l.right-r[0])/-f,g[e+44]=d&&(l.bottom-r[1])/-d,g[e+48]=d&&(l.left-r[0])/d,g[e+52]=f&&(l.top-r[1])/-f,g[e+56]=d&&(l.right-r[0])/d,g[e+60]=f&&(l.bottom-r[1])/-f});var v=function t(e,r,i){for(var n=0,o=0;o<i;o++){var a=e[r++];a>0&&(n=n?Math.min(a,n):a)}return n},m=1+Math.min(Math.abs(f),Math.abs(d));c.paddingLeft=v(g,32,16)/m,c.paddingTop=v(g,48,16)/m,c.paddingRight=v(g,0,16)/m,c.paddingBottom=v(g,16,16)/m,t._textDivProperties.set(a,c)}else c.paddingLeft=e[o].left-n[o].left,c.paddingTop=e[o].top-n[o].top,c.paddingRight=n[o].right-e[o].right,c.paddingBottom=n[o].bottom-e[o].bottom,t._textDivProperties.set(a,c)}}function s(t,e,r){var i=r.map(function(t,e){return{x1:t.left,y1:t.top,x2:t.right,y2:t.bottom,index:e,x1New:void 0,x2New:void 0}});c(t,i);var n=new Array(r.length);return i.forEach(function(t){var e=t.index;n[e]={left:t.x1New,top:0,right:t.x2New,bottom:0}}),r.map(function(e,r){var o=n[r],a=i[r];a.x1=e.top,a.y1=t-o.right,a.x2=e.bottom,a.y2=t-o.left,a.index=r,a.x1New=void 0,a.x2New=void 0}),c(e,i),i.forEach(function(t){var e=t.index;n[e].top=t.x1New,n[e].bottom=t.x2New}),n}function c(t,e){e.sort(function(t,e){return t.x1-e.x1||t.index-e.index});var r={x1:-1/0,y1:-1/0,x2:0,y2:1/0,index:-1,x1New:0,x2New:0},i=[{start:-1/0,end:1/0,boundary:r}];e.forEach(function(t){for(var e=0;e<i.length&&i[e].end<=t.y1;)e++;for(var r=i.length-1;r>=0&&i[r].start>=t.y2;)r--;var n,o,a,s,c=-1/0;for(a=e;a<=r;a++){n=i[a],o=n.boundary;var l;l=o.x2>t.x1?o.index>t.index?o.x1New:t.x1:void 0===o.x2New?(o.x2+t.x1)/2:o.x2New,l>c&&(c=l)}for(t.x1New=c,a=e;a<=r;a++)n=i[a],o=n.boundary,void 0===o.x2New?o.x2>t.x1?o.index>t.index&&(o.x2New=o.x2):o.x2New=c:o.x2New>c&&(o.x2New=Math.max(c,o.x2));var h=[],u=null;for(a=e;a<=r;a++){n=i[a],o=n.boundary;var f=o.x2>t.x2?o:t;u===f?h[h.length-1].end=n.end:(h.push({start:n.start,end:n.end,boundary:f}),u=f)}for(i[e].start<t.y1&&(h[0].start=t.y1,h.unshift({start:i[e].start,end:t.y1,boundary:i[e].boundary})),t.y2<i[r].end&&(h[h.length-1].end=t.y2,h.push({start:t.y2,end:i[r].end,boundary:i[r].boundary})),a=e;a<=r;a++)if(n=i[a],o=n.boundary,void 0===o.x2New){var d=!1;for(s=e-1;!d&&s>=0&&i[s].start>=o.y1;s--)d=i[s].boundary===o;for(s=r+1;!d&&s<i.length&&i[s].end<=o.y2;s++)d=i[s].boundary===o;for(s=0;!d&&s<h.length;s++)d=h[s].boundary===o;d||(o.x2New=c)}Array.prototype.splice.apply(i,[e,r-e+1].concat(h))}),i.forEach(function(e){var r=e.boundary;void 0===r.x2New&&(r.x2New=Math.max(t,r.x2))})}function l(t){var e=t.textContent,r=t.textContentStream,n=t.container,o=t.viewport,a=t.textDivs,s=t.textContentItemsStr,c=t.enhanceTextSelection;this._textContent=e,this._textContentStream=r,this._container=n,this._viewport=o,this._textDivs=a||[],this._textContentItemsStr=s||[],this._enhanceTextSelection=!!c,this._reader=null,this._layoutTextLastFontSize=null,this._layoutTextLastFontFamily=null,this._layoutTextCtx=null,this._textDivProperties=new WeakMap,this._renderingDone=!1,this._canceled=!1,this._capability=(0,i.createPromiseCapability)(),this._renderTimer=null,this._bounds=[]}function h(t){var e=new l({textContent:t.textContent,textContentStream:t.textContentStream,container:t.container,viewport:t.viewport,textDivs:t.textDivs,textContentItemsStr:t.textContentItemsStr,enhanceTextSelection:t.enhanceTextSelection});return e._render(t.timeout),e}var u=1e5,f=/\S/,d=["left: ",0,"px; top: ",0,"px; font-size: ",0,"px; font-family: ","",";"];return l.prototype={get promise(){return this._capability.promise},cancel:function t(){this._reader&&(this._reader.cancel(),this._reader=null),this._canceled=!0,null!==this._renderTimer&&(clearTimeout(this._renderTimer),this._renderTimer=null),this._capability.reject("canceled")},_processItems:function t(e,i){for(var n=0,o=e.length;n<o;n++)this._textContentItemsStr.push(e[n].str),r(this,e[n],i)},_layoutText:function t(e){var r=this._container,i=this._textDivProperties.get(e);if(!i.isWhitespace){var o=e.style.fontSize,a=e.style.fontFamily;o===this._layoutTextLastFontSize&&a===this._layoutTextLastFontFamily||(this._layoutTextCtx.font=o+" "+a,this._lastFontSize=o,this._lastFontFamily=a);var s=this._layoutTextCtx.measureText(e.textContent).width,c="";0!==i.canvasWidth&&s>0&&(i.scale=i.canvasWidth/s,c="scaleX("+i.scale+")"),0!==i.angle&&(c="rotate("+i.angle+"deg) "+c),""!==c&&(i.originalTransform=c,n.CustomStyle.setProp("transform",e,c)),this._textDivProperties.set(e,i),r.appendChild(e)}},_render:function t(e){var r=this,n=(0,i.createPromiseCapability)(),a=Object.create(null),s=document.createElement("canvas");if(s.mozOpaque=!0,this._layoutTextCtx=s.getContext("2d",{alpha:!1}),this._textContent){var c=this._textContent.items,l=this._textContent.styles;this._processItems(c,l),n.resolve()}else{if(!this._textContentStream)throw new Error('Neither "textContent" nor "textContentStream" parameters specified.');var h=function t(){r._reader.read().then(function(e){var o=e.value;if(e.done)return void n.resolve();i.Util.extendObj(a,o.styles),r._processItems(o.items,a),t()},n.reject)};this._reader=this._textContentStream.getReader(),h()}n.promise.then(function(){a=null,e?r._renderTimer=setTimeout(function(){o(r),r._renderTimer=null},e):o(r)},this._capability.reject)},expandTextDivs:function t(e){if(this._enhanceTextSelection&&this._renderingDone){null!==this._bounds&&(a(this),this._bounds=null);for(var r=0,i=this._textDivs.length;r<i;r++){var o=this._textDivs[r],s=this._textDivProperties.get(o);if(!s.isWhitespace)if(e){var c="",l="";1!==s.scale&&(c="scaleX("+s.scale+")"),0!==s.angle&&(c="rotate("+s.angle+"deg) "+c),0!==s.paddingLeft&&(l+=" padding-left: "+s.paddingLeft/s.scale+"px;",c+=" translateX("+-s.paddingLeft/s.scale+"px)"),0!==s.paddingTop&&(l+=" padding-top: "+s.paddingTop+"px;",c+=" translateY("+-s.paddingTop+"px)"),0!==s.paddingRight&&(l+=" padding-right: "+s.paddingRight/s.scale+"px;"),0!==s.paddingBottom&&(l+=" padding-bottom: "+s.paddingBottom+"px;"),""!==l&&o.setAttribute("style",s.style+l),""!==c&&n.CustomStyle.setProp("transform",o,c)}else o.style.padding=0,n.CustomStyle.setProp("transform",o,s.originalTransform||"")}}}},h}();e.renderTextLayer=o},function(t,e,r){"use strict";function i(t){return t.replace(/>\\376\\377([^<]+)/g,function(t,e){for(var r=e.replace(/\\([0-3])([0-7])([0-7])/g,function(t,e,r,i){return String.fromCharCode(64*e+8*r+1*i)}),i="",n=0;n<r.length;n+=2){var o=256*r.charCodeAt(n)+r.charCodeAt(n+1);i+=o>=32&&o<127&&60!==o&&62!==o&&38!==o?String.fromCharCode(o):"&#x"+(65536+o).toString(16).substring(1)+";"}return">"+i})}function n(t){if("string"==typeof t){t=i(t);t=(new DOMParser).parseFromString(t,"application/xml")}else if(!(t instanceof Document))throw new Error("Metadata: Invalid metadata object");this.metaDocument=t,this.metadata=Object.create(null),this.parse()}Object.defineProperty(e,"__esModule",{value:!0}),n.prototype={parse:function t(){var e=this.metaDocument,r=e.documentElement;if("rdf:rdf"!==r.nodeName.toLowerCase())for(r=r.firstChild;r&&"rdf:rdf"!==r.nodeName.toLowerCase();)r=r.nextSibling;var i=r?r.nodeName.toLowerCase():null;if(r&&"rdf:rdf"===i&&r.hasChildNodes()){var n=r.childNodes,o,a,s,c,l,h,u;for(c=0,h=n.length;c<h;c++)if(o=n[c],"rdf:description"===o.nodeName.toLowerCase())for(l=0,u=o.childNodes.length;l<u;l++)"#text"!==o.childNodes[l].nodeName.toLowerCase()&&(a=o.childNodes[l],s=a.nodeName.toLowerCase(),this.metadata[s]=a.textContent.trim())}},get:function t(e){return this.metadata[e]||null},has:function t(e){return void 0!==this.metadata[e]}},e.Metadata=n},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.WebGLUtils=void 0;var i=r(1),n=r(0),o=function t(){function e(t,e,r){var i=t.createShader(r);if(t.shaderSource(i,e),t.compileShader(i),!t.getShaderParameter(i,t.COMPILE_STATUS)){var n=t.getShaderInfoLog(i);throw new Error("Error during shader compilation: "+n)}return i}function r(t,r){return e(t,r,t.VERTEX_SHADER)}function o(t,r){return e(t,r,t.FRAGMENT_SHADER)}function a(t,e){for(var r=t.createProgram(),i=0,n=e.length;i<n;++i)t.attachShader(r,e[i]);if(t.linkProgram(r),!t.getProgramParameter(r,t.LINK_STATUS)){var o=t.getProgramInfoLog(r);throw new Error("Error during program linking: "+o)}return r}function s(t,e,r){t.activeTexture(r);var i=t.createTexture();return t.bindTexture(t.TEXTURE_2D,i),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),i}function c(){p||(g=document.createElement("canvas"),p=g.getContext("webgl",{premultipliedalpha:!1}))}function l(){var t,e;c(),t=g,g=null,e=p,p=null;var i=r(e,v),n=o(e,m),s=a(e,[i,n]);e.useProgram(s);var l={};l.gl=e,l.canvas=t,l.resolutionLocation=e.getUniformLocation(s,"u_resolution"),l.positionLocation=e.getAttribLocation(s,"a_position"),l.backdropLocation=e.getUniformLocation(s,"u_backdrop"),l.subtypeLocation=e.getUniformLocation(s,"u_subtype");var h=e.getAttribLocation(s,"a_texCoord"),u=e.getUniformLocation(s,"u_image"),f=e.getUniformLocation(s,"u_mask"),d=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,d),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),e.STATIC_DRAW),e.enableVertexAttribArray(h),e.vertexAttribPointer(h,2,e.FLOAT,!1,0,0),e.uniform1i(u,0),e.uniform1i(f,1),b=l}function h(t,e,r){var i=t.width,n=t.height;b||l();var o=b,a=o.canvas,c=o.gl;a.width=i,a.height=n,c.viewport(0,0,c.drawingBufferWidth,c.drawingBufferHeight),c.uniform2f(o.resolutionLocation,i,n),r.backdrop?c.uniform4f(o.resolutionLocation,r.backdrop[0],r.backdrop[1],r.backdrop[2],1):c.uniform4f(o.resolutionLocation,0,0,0,0),c.uniform1i(o.subtypeLocation,"Luminosity"===r.subtype?1:0);var h=s(c,t,c.TEXTURE0),u=s(c,e,c.TEXTURE1),f=c.createBuffer();return c.bindBuffer(c.ARRAY_BUFFER,f),c.bufferData(c.ARRAY_BUFFER,new Float32Array([0,0,i,0,0,n,0,n,i,0,i,n]),c.STATIC_DRAW),c.enableVertexAttribArray(o.positionLocation),c.vertexAttribPointer(o.positionLocation,2,c.FLOAT,!1,0,0),c.clearColor(0,0,0,0),c.enable(c.BLEND),c.blendFunc(c.ONE,c.ONE_MINUS_SRC_ALPHA),c.clear(c.COLOR_BUFFER_BIT),c.drawArrays(c.TRIANGLES,0,6),c.flush(),c.deleteTexture(h),c.deleteTexture(u),c.deleteBuffer(f),a}function u(){var t,e;c(),t=g,g=null,e=p,p=null;var i=r(e,y),n=o(e,_),s=a(e,[i,n]);e.useProgram(s);var l={};l.gl=e,l.canvas=t,l.resolutionLocation=e.getUniformLocation(s,"u_resolution"),l.scaleLocation=e.getUniformLocation(s,"u_scale"),l.offsetLocation=e.getUniformLocation(s,"u_offset"),l.positionLocation=e.getAttribLocation(s,"a_position"),l.colorLocation=e.getAttribLocation(s,"a_color"),w=l}function f(t,e,r,i,n){w||u();var o=w,a=o.canvas,s=o.gl;a.width=t,a.height=e,s.viewport(0,0,s.drawingBufferWidth,s.drawingBufferHeight),s.uniform2f(o.resolutionLocation,t,e);var c=0,l,h,f;for(l=0,h=i.length;l<h;l++)switch(i[l].type){case"lattice":f=i[l].coords.length/i[l].verticesPerRow|0,c+=(f-1)*(i[l].verticesPerRow-1)*6;break;case"triangles":c+=i[l].coords.length}var d=new Float32Array(2*c),p=new Uint8Array(3*c),g=n.coords,v=n.colors,m=0,b=0;for(l=0,h=i.length;l<h;l++){var y=i[l],_=y.coords,S=y.colors;switch(y.type){case"lattice":var x=y.verticesPerRow;f=_.length/x|0;for(var C=1;C<f;C++)for(var A=C*x+1,T=1;T<x;T++,A++)d[m]=g[_[A-x-1]],d[m+1]=g[_[A-x-1]+1],d[m+2]=g[_[A-x]],d[m+3]=g[_[A-x]+1],d[m+4]=g[_[A-1]],d[m+5]=g[_[A-1]+1],p[b]=v[S[A-x-1]],p[b+1]=v[S[A-x-1]+1],p[b+2]=v[S[A-x-1]+2],p[b+3]=v[S[A-x]],p[b+4]=v[S[A-x]+1],p[b+5]=v[S[A-x]+2],p[b+6]=v[S[A-1]],p[b+7]=v[S[A-1]+1],p[b+8]=v[S[A-1]+2],d[m+6]=d[m+2],d[m+7]=d[m+3],d[m+8]=d[m+4],d[m+9]=d[m+5],d[m+10]=g[_[A]],d[m+11]=g[_[A]+1],p[b+9]=p[b+3],p[b+10]=p[b+4],p[b+11]=p[b+5],p[b+12]=p[b+6],p[b+13]=p[b+7],p[b+14]=p[b+8],p[b+15]=v[S[A]],p[b+16]=v[S[A]+1],p[b+17]=v[S[A]+2],m+=12,b+=18;break;case"triangles":for(var k=0,P=_.length;k<P;k++)d[m]=g[_[k]],d[m+1]=g[_[k]+1],p[b]=v[S[k]],p[b+1]=v[S[k]+1],p[b+2]=v[S[k]+2],m+=2,b+=3}}r?s.clearColor(r[0]/255,r[1]/255,r[2]/255,1):s.clearColor(0,0,0,0),s.clear(s.COLOR_BUFFER_BIT);var E=s.createBuffer();s.bindBuffer(s.ARRAY_BUFFER,E),s.bufferData(s.ARRAY_BUFFER,d,s.STATIC_DRAW),s.enableVertexAttribArray(o.positionLocation),s.vertexAttribPointer(o.positionLocation,2,s.FLOAT,!1,0,0);var O=s.createBuffer();return s.bindBuffer(s.ARRAY_BUFFER,O),s.bufferData(s.ARRAY_BUFFER,p,s.STATIC_DRAW),s.enableVertexAttribArray(o.colorLocation),s.vertexAttribPointer(o.colorLocation,3,s.UNSIGNED_BYTE,!1,0,0),s.uniform2f(o.scaleLocation,n.scaleX,n.scaleY),s.uniform2f(o.offsetLocation,n.offsetX,n.offsetY),s.drawArrays(s.TRIANGLES,0,c),s.flush(),s.deleteBuffer(E),s.deleteBuffer(O),a}function d(){b&&b.canvas&&(b.canvas.width=0,b.canvas.height=0),w&&w.canvas&&(w.canvas.width=0,w.canvas.height=0),b=null,w=null}var p,g,v=" attribute vec2 a_position; attribute vec2 a_texCoord; uniform vec2 u_resolution; varying vec2 v_texCoord; void main() { vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); v_texCoord = a_texCoord; } ",m=" precision mediump float; uniform vec4 u_backdrop; uniform int u_subtype; uniform sampler2D u_image; uniform sampler2D u_mask; varying vec2 v_texCoord; void main() { vec4 imageColor = texture2D(u_image, v_texCoord); vec4 maskColor = texture2D(u_mask, v_texCoord); if (u_backdrop.a > 0.0) { maskColor.rgb = maskColor.rgb * maskColor.a + u_backdrop.rgb * (1.0 - maskColor.a); } float lum; if (u_subtype == 0) { lum = maskColor.a; } else { lum = maskColor.r * 0.3 + maskColor.g * 0.59 + maskColor.b * 0.11; } imageColor.a *= lum; imageColor.rgb *= imageColor.a; gl_FragColor = imageColor; } ",b=null,y=" attribute vec2 a_position; attribute vec3 a_color; uniform vec2 u_resolution; uniform vec2 u_scale; uniform vec2 u_offset; varying vec4 v_color; void main() { vec2 position = (a_position + u_offset) * u_scale; vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); v_color = vec4(a_color / 255.0, 1.0); } ",_=" precision mediump float; varying vec4 v_color; void main() { gl_FragColor = v_color; } ",w=null;return{get isEnabled(){if((0,i.getDefaultSetting)("disableWebGL"))return!1;var t=!1;try{c(),t=!!p}catch(t){}return(0,n.shadow)(this,"isEnabled",t)},composeSMask:h,drawFigures:f,clear:d}}();e.WebGLUtils=o},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.PDFJS=e.isWorker=e.globalScope=void 0;var i=r(3),n=r(1),o=r(0),a=r(2),s=r(6),c=r(5),l=r(4),h="undefined"==typeof window;o.globalScope.PDFJS||(o.globalScope.PDFJS={});var u=o.globalScope.PDFJS;u.version="1.8.575",u.build="bd8c1211",u.pdfBug=!1,void 0!==u.verbosity&&(0,o.setVerbosityLevel)(u.verbosity),delete u.verbosity,Object.defineProperty(u,"verbosity",{get:function t(){return(0,o.getVerbosityLevel)()},set:function t(e){(0,o.setVerbosityLevel)(e)},enumerable:!0,configurable:!0}),u.VERBOSITY_LEVELS=o.VERBOSITY_LEVELS,u.OPS=o.OPS,u.UNSUPPORTED_FEATURES=o.UNSUPPORTED_FEATURES,u.isValidUrl=n.isValidUrl,u.shadow=o.shadow,u.createBlob=o.createBlob,u.createObjectURL=function t(e,r){return(0,o.createObjectURL)(e,r,u.disableCreateObjectURL)},Object.defineProperty(u,"isLittleEndian",{configurable:!0,get:function t(){return(0,o.shadow)(u,"isLittleEndian",(0,o.isLittleEndian)())}}),u.removeNullCharacters=o.removeNullCharacters,u.PasswordResponses=o.PasswordResponses,u.PasswordException=o.PasswordException,u.UnknownErrorException=o.UnknownErrorException,u.InvalidPDFException=o.InvalidPDFException,u.MissingPDFException=o.MissingPDFException,u.UnexpectedResponseException=o.UnexpectedResponseException,u.Util=o.Util,u.PageViewport=o.PageViewport,u.createPromiseCapability=o.createPromiseCapability,u.maxImageSize=void 0===u.maxImageSize?-1:u.maxImageSize,u.cMapUrl=void 0===u.cMapUrl?null:u.cMapUrl,u.cMapPacked=void 0!==u.cMapPacked&&u.cMapPacked,u.disableFontFace=void 0!==u.disableFontFace&&u.disableFontFace,u.imageResourcesPath=void 0===u.imageResourcesPath?"":u.imageResourcesPath,u.disableWorker=void 0!==u.disableWorker&&u.disableWorker,u.workerSrc=void 0===u.workerSrc?null:u.workerSrc,u.workerPort=void 0===u.workerPort?null:u.workerPort,u.disableRange=void 0!==u.disableRange&&u.disableRange,u.disableStream=void 0!==u.disableStream&&u.disableStream,u.disableAutoFetch=void 0!==u.disableAutoFetch&&u.disableAutoFetch,u.pdfBug=void 0!==u.pdfBug&&u.pdfBug,u.postMessageTransfers=void 0===u.postMessageTransfers||u.postMessageTransfers,u.disableCreateObjectURL=void 0!==u.disableCreateObjectURL&&u.disableCreateObjectURL,u.disableWebGL=void 0===u.disableWebGL||u.disableWebGL,u.externalLinkTarget=void 0===u.externalLinkTarget?n.LinkTarget.NONE:u.externalLinkTarget,u.externalLinkRel=void 0===u.externalLinkRel?n.DEFAULT_LINK_REL:u.externalLinkRel,u.isEvalSupported=void 0===u.isEvalSupported||u.isEvalSupported,u.pdfjsNext=void 0!==u.pdfjsNext&&u.pdfjsNext;var f=u.openExternalLinksInNewWindow;delete u.openExternalLinksInNewWindow,Object.defineProperty(u,"openExternalLinksInNewWindow",{get:function t(){return u.externalLinkTarget===n.LinkTarget.BLANK},set:function t(e){if(e&&(0,o.deprecated)('PDFJS.openExternalLinksInNewWindow, please use "PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK" instead.'),u.externalLinkTarget!==n.LinkTarget.NONE)return void(0,o.warn)("PDFJS.externalLinkTarget is already initialized");u.externalLinkTarget=e?n.LinkTarget.BLANK:n.LinkTarget.NONE},enumerable:!0,configurable:!0}),f&&(u.openExternalLinksInNewWindow=f),u.getDocument=i.getDocument,u.LoopbackPort=i.LoopbackPort,u.PDFDataRangeTransport=i.PDFDataRangeTransport,u.PDFWorker=i.PDFWorker,u.hasCanvasTypedArrays=!0,u.CustomStyle=n.CustomStyle,u.LinkTarget=n.LinkTarget,u.addLinkAttributes=n.addLinkAttributes,u.getFilenameFromUrl=n.getFilenameFromUrl,u.isExternalLinkTargetSet=n.isExternalLinkTargetSet,u.AnnotationLayer=a.AnnotationLayer,u.renderTextLayer=c.renderTextLayer,u.Metadata=s.Metadata,u.SVGGraphics=l.SVGGraphics,u.UnsupportedManager=i._UnsupportedManager,e.globalScope=o.globalScope,e.isWorker=h,e.PDFJS=u},function(t,e,r){"use strict";var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};!function(t,e){for(var r in e)t[r]=e[r]}(e,function(t){function e(i){if(r[i])return r[i].exports;var n=r[i]={i:i,l:!1,exports:{}};return t[i].call(n.exports,n,n.exports,e),n.l=!0,n.exports}var r={};return e.m=t,e.c=r,e.i=function(t){return t},e.d=function(t,r,i){e.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var r=t&&t.__esModule?function e(){return t.default}:function e(){return t};return e.d(r,"a",r),r},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=7)}([function(t,e,r){function n(t){return"string"==typeof t||"symbol"===(void 0===t?"undefined":a(t))}function o(t,e,r){if("function"!=typeof t)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(t,e,r)}var a="function"==typeof Symbol&&"symbol"===i(Symbol.iterator)?function(t){return void 0===t?"undefined":i(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":void 0===t?"undefined":i(t)},s=r(1),c=s.assert;e.typeIsObject=function(t){return"object"===(void 0===t?"undefined":a(t))&&null!==t||"function"==typeof t},e.createDataProperty=function(t,r,i){c(e.typeIsObject(t)),Object.defineProperty(t,r,{value:i,writable:!0,enumerable:!0,configurable:!0})},e.createArrayFromList=function(t){return t.slice()},e.ArrayBufferCopy=function(t,e,r,i,n){new Uint8Array(t).set(new Uint8Array(r,i,n),e)},e.CreateIterResultObject=function(t,e){c("boolean"==typeof e);var r={};return Object.defineProperty(r,"value",{value:t,enumerable:!0,writable:!0,configurable:!0}),Object.defineProperty(r,"done",{value:e,enumerable:!0,writable:!0,configurable:!0}),r},e.IsFiniteNonNegativeNumber=function(t){return!Number.isNaN(t)&&(t!==1/0&&!(t<0))},e.InvokeOrNoop=function(t,e,r){c(void 0!==t),c(n(e)),c(Array.isArray(r));var i=t[e];if(void 0!==i)return o(i,t,r)},e.PromiseInvokeOrNoop=function(t,r,i){c(void 0!==t),c(n(r)),c(Array.isArray(i));try{return Promise.resolve(e.InvokeOrNoop(t,r,i))}catch(t){return Promise.reject(t)}},e.PromiseInvokeOrPerformFallback=function(t,e,r,i,a){c(void 0!==t),c(n(e)),c(Array.isArray(r)),c(Array.isArray(a));var s=void 0;try{s=t[e]}catch(t){return Promise.reject(t)}if(void 0===s)return i.apply(null,a);try{return Promise.resolve(o(s,t,r))}catch(t){return Promise.reject(t)}},e.TransferArrayBuffer=function(t){return t.slice()},e.ValidateAndNormalizeHighWaterMark=function(t){if(t=Number(t),Number.isNaN(t)||t<0)throw new RangeError("highWaterMark property of a queuing strategy must be non-negative and non-NaN");return t},e.ValidateAndNormalizeQueuingStrategy=function(t,r){if(void 0!==t&&"function"!=typeof t)throw new TypeError("size property of a queuing strategy must be a function");return r=e.ValidateAndNormalizeHighWaterMark(r),{size:t,highWaterMark:r}}},function(t,e,r){function i(t){t&&t.constructor===n&&setTimeout(function(){throw t},0)}function n(t){this.name="AssertionError",this.message=t||"",this.stack=(new Error).stack}function o(t,e){if(!t)throw new n(e)}n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,t.exports={rethrowAssertionErrorRejection:i,AssertionError:n,assert:o}},function(t,e,r){function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t){return new yt(t)}function o(t){return!!lt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_writableStreamController")}function a(t){return ut(!0===o(t),"IsWritableStreamLocked should only be used on known writable streams"),void 0!==t._writer}function s(t,e){var r=t._state;if("closed"===r)return Promise.resolve(void 0);if("errored"===r)return Promise.reject(t._storedError);var i=new TypeError("Requested to abort");if(void 0!==t._pendingAbortRequest)return Promise.reject(i);ut("writable"===r||"erroring"===r,"state must be writable or erroring");var n=!1;"erroring"===r&&(n=!0,e=void 0);var o=new Promise(function(r,i){t._pendingAbortRequest={_resolve:r,_reject:i,_reason:e,_wasAlreadyErroring:n}});return!1===n&&h(t,i),o}function c(t){return ut(!0===a(t)),ut("writable"===t._state),new Promise(function(e,r){var i={_resolve:e,_reject:r};t._writeRequests.push(i)})}function l(t,e){var r=t._state;if("writable"===r)return void h(t,e);ut("erroring"===r),u(t)}function h(t,e){ut(void 0===t._storedError,"stream._storedError === undefined"),ut("writable"===t._state,"state must be writable");var r=t._writableStreamController;ut(void 0!==r,"controller must not be undefined"),t._state="erroring",t._storedError=e;var i=t._writer;void 0!==i&&k(i,e),!1===m(t)&&!0===r._started&&u(t)}function u(t){ut("erroring"===t._state,"stream._state === erroring"),ut(!1===m(t),"WritableStreamHasOperationMarkedInFlight(stream) === false"),t._state="errored",t._writableStreamController.__errorSteps();for(var e=t._storedError,r=0;r<t._writeRequests.length;r++){t._writeRequests[r]._reject(e)}if(t._writeRequests=[],void 0===t._pendingAbortRequest)return void _(t);var i=t._pendingAbortRequest;if(t._pendingAbortRequest=void 0,!0===i._wasAlreadyErroring)return i._reject(e),void _(t);t._writableStreamController.__abortSteps(i._reason).then(function(){i._resolve(),_(t)},function(e){i._reject(e),_(t)})}function f(t){ut(void 0!==t._inFlightWriteRequest),t._inFlightWriteRequest._resolve(void 0),t._inFlightWriteRequest=void 0}function d(t,e){ut(void 0!==t._inFlightWriteRequest),t._inFlightWriteRequest._reject(e),t._inFlightWriteRequest=void 0,ut("writable"===t._state||"erroring"===t._state),l(t,e)}function p(t){ut(void 0!==t._inFlightCloseRequest),t._inFlightCloseRequest._resolve(void 0),t._inFlightCloseRequest=void 0;var e=t._state;ut("writable"===e||"erroring"===e),"erroring"===e&&(t._storedError=void 0,void 0!==t._pendingAbortRequest&&(t._pendingAbortRequest._resolve(),t._pendingAbortRequest=void 0)),t._state="closed";var r=t._writer;void 0!==r&&J(r),ut(void 0===t._pendingAbortRequest,"stream._pendingAbortRequest === undefined"),ut(void 0===t._storedError,"stream._storedError === undefined")}function g(t,e){ut(void 0!==t._inFlightCloseRequest),t._inFlightCloseRequest._reject(e),t._inFlightCloseRequest=void 0,ut("writable"===t._state||"erroring"===t._state),void 0!==t._pendingAbortRequest&&(t._pendingAbortRequest._reject(e),t._pendingAbortRequest=void 0),l(t,e)}function v(t){return void 0!==t._closeRequest||void 0!==t._inFlightCloseRequest}function m(t){return void 0!==t._inFlightWriteRequest||void 0!==t._inFlightCloseRequest}function b(t){ut(void 0===t._inFlightCloseRequest),ut(void 0!==t._closeRequest),t._inFlightCloseRequest=t._closeRequest,t._closeRequest=void 0}function y(t){ut(void 0===t._inFlightWriteRequest,"there must be no pending write request"),ut(0!==t._writeRequests.length,"writeRequests must not be empty"),t._inFlightWriteRequest=t._writeRequests.shift()}function _(t){ut("errored"===t._state,'_stream_.[[state]] is `"errored"`'),void 0!==t._closeRequest&&(ut(void 0===t._inFlightCloseRequest),t._closeRequest._reject(t._storedError),t._closeRequest=void 0);var e=t._writer;void 0!==e&&(V(e,t._storedError),e._closedPromise.catch(function(){}))}function w(t,e){ut("writable"===t._state),ut(!1===v(t));var r=t._writer;void 0!==r&&e!==t._backpressure&&(!0===e?et(r):(ut(!1===e),it(r))),t._backpressure=e}function S(t){return!!lt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_ownerWritableStream")}function x(t,e){var r=t._ownerWritableStream;return ut(void 0!==r),s(r,e)}function C(t){var e=t._ownerWritableStream;ut(void 0!==e);var r=e._state;if("closed"===r||"errored"===r)return Promise.reject(new TypeError("The stream (in "+r+" state) is not in the writable state and cannot be closed"));ut("writable"===r||"erroring"===r),ut(!1===v(e));var i=new Promise(function(t,r){var i={_resolve:t,_reject:r};e._closeRequest=i});return!0===e._backpressure&&"writable"===r&&it(t),R(e._writableStreamController),i}function A(t){var e=t._ownerWritableStream;ut(void 0!==e);var r=e._state;return!0===v(e)||"closed"===r?Promise.resolve():"errored"===r?Promise.reject(e._storedError):(ut("writable"===r||"erroring"===r),C(t))}function T(t,e){"pending"===t._closedPromiseState?V(t,e):Z(t,e),t._closedPromise.catch(function(){})}function k(t,e){"pending"===t._readyPromiseState?tt(t,e):rt(t,e),t._readyPromise.catch(function(){})}function P(t){var e=t._ownerWritableStream,r=e._state;return"errored"===r||"erroring"===r?null:"closed"===r?0:D(e._writableStreamController)}function E(t){var e=t._ownerWritableStream;ut(void 0!==e),ut(e._writer===t);var r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");k(t,r),T(t,r),e._writer=void 0,t._ownerWritableStream=void 0}function O(t,e){var r=t._ownerWritableStream;ut(void 0!==r);var i=r._writableStreamController,n=L(i,e);if(r!==t._ownerWritableStream)return Promise.reject(X("write to"));var o=r._state;if("errored"===o)return Promise.reject(r._storedError);if(!0===v(r)||"closed"===o)return Promise.reject(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===o)return Promise.reject(r._storedError);ut("writable"===o);var a=c(r);return I(i,e,n),a}function R(t){gt(t,"close",0),M(t)}function L(t,e){var r=t._strategySize;if(void 0===r)return 1;try{return r(e)}catch(e){return F(t,e),1}}function D(t){return t._strategyHWM-t._queueTotalSize}function I(t,e,r){var i={chunk:e};try{gt(t,i,r)}catch(e){return void F(t,e)}var n=t._controlledWritableStream;if(!1===v(n)&&"writable"===n._state){w(n,U(t))}M(t)}function j(t){return!!lt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_underlyingSink")}function M(t){var e=t._controlledWritableStream;if(!1!==t._started&&void 0===e._inFlightWriteRequest){var r=e._state;if("closed"!==r&&"errored"!==r){if("erroring"===r)return void u(e);if(0!==t._queue.length){var i=vt(t);"close"===i?N(t):B(t,i.chunk)}}}}function F(t,e){"writable"===t._controlledWritableStream._state&&z(t,e)}function N(t){var e=t._controlledWritableStream;b(e),pt(t),ut(0===t._queue.length,"queue must be empty once the final write record is dequeued"),st(t._underlyingSink,"close",[]).then(function(){p(e)},function(t){g(e,t)}).catch(ft)}function B(t,e){var r=t._controlledWritableStream;y(r),st(t._underlyingSink,"write",[e,t]).then(function(){f(r);var e=r._state;if(ut("writable"===e||"erroring"===e),pt(t),!1===v(r)&&"writable"===e){var i=U(t);w(r,i)}M(t)},function(t){d(r,t)}).catch(ft)}function U(t){return D(t)<=0}function z(t,e){var r=t._controlledWritableStream;ut("writable"===r._state),h(r,e)}function W(t){return new TypeError("WritableStream.prototype."+t+" can only be used on a WritableStream")}function q(t){return new TypeError("WritableStreamDefaultWriter.prototype."+t+" can only be used on a WritableStreamDefaultWriter")}function X(t){return new TypeError("Cannot "+t+" a stream using a released writer")}function G(t){t._closedPromise=new Promise(function(e,r){t._closedPromise_resolve=e,t._closedPromise_reject=r,t._closedPromiseState="pending"})}function H(t,e){t._closedPromise=Promise.reject(e),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0,t._closedPromiseState="rejected"}function Y(t){t._closedPromise=Promise.resolve(void 0),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0,t._closedPromiseState="resolved"}function V(t,e){ut(void 0!==t._closedPromise_resolve,"writer._closedPromise_resolve !== undefined"),ut(void 0!==t._closedPromise_reject,"writer._closedPromise_reject !== undefined"),ut("pending"===t._closedPromiseState,"writer._closedPromiseState is pending"),t._closedPromise_reject(e),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0,t._closedPromiseState="rejected"}function Z(t,e){ut(void 0===t._closedPromise_resolve,"writer._closedPromise_resolve === undefined"),ut(void 0===t._closedPromise_reject,"writer._closedPromise_reject === undefined"),ut("pending"!==t._closedPromiseState,"writer._closedPromiseState is not pending"),t._closedPromise=Promise.reject(e),t._closedPromiseState="rejected"}function J(t){ut(void 0!==t._closedPromise_resolve,"writer._closedPromise_resolve !== undefined"),ut(void 0!==t._closedPromise_reject,"writer._closedPromise_reject !== undefined"),ut("pending"===t._closedPromiseState,"writer._closedPromiseState is pending"),t._closedPromise_resolve(void 0),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0,t._closedPromiseState="resolved"}function K(t){t._readyPromise=new Promise(function(e,r){t._readyPromise_resolve=e,t._readyPromise_reject=r}),t._readyPromiseState="pending"}function Q(t,e){t._readyPromise=Promise.reject(e),t._readyPromise_resolve=void 0,t._readyPromise_reject=void 0,t._readyPromiseState="rejected"}function $(t){t._readyPromise=Promise.resolve(void 0),t._readyPromise_resolve=void 0,t._readyPromise_reject=void 0,t._readyPromiseState="fulfilled"}function tt(t,e){ut(void 0!==t._readyPromise_resolve,"writer._readyPromise_resolve !== undefined"),ut(void 0!==t._readyPromise_reject,"writer._readyPromise_reject !== undefined"),t._readyPromise_reject(e),t._readyPromise_resolve=void 0,t._readyPromise_reject=void 0,t._readyPromiseState="rejected"}function et(t){ut(void 0===t._readyPromise_resolve,"writer._readyPromise_resolve === undefined"),ut(void 0===t._readyPromise_reject,"writer._readyPromise_reject === undefined"),t._readyPromise=new Promise(function(e,r){t._readyPromise_resolve=e,t._readyPromise_reject=r}),t._readyPromiseState="pending"}function rt(t,e){ut(void 0===t._readyPromise_resolve,"writer._readyPromise_resolve === undefined"),ut(void 0===t._readyPromise_reject,"writer._readyPromise_reject === undefined"),t._readyPromise=Promise.reject(e),t._readyPromiseState="rejected"}function it(t){ut(void 0!==t._readyPromise_resolve,"writer._readyPromise_resolve !== undefined"),ut(void 0!==t._readyPromise_reject,"writer._readyPromise_reject !== undefined"),t._readyPromise_resolve(void 0),t._readyPromise_resolve=void 0,t._readyPromise_reject=void 0,t._readyPromiseState="fulfilled"}var nt=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),ot=r(0),at=ot.InvokeOrNoop,st=ot.PromiseInvokeOrNoop,ct=ot.ValidateAndNormalizeQueuingStrategy,lt=ot.typeIsObject,ht=r(1),ut=ht.assert,ft=ht.rethrowAssertionErrorRejection,dt=r(3),pt=dt.DequeueValue,gt=dt.EnqueueValueWithSize,vt=dt.PeekQueueValue,mt=dt.ResetQueue,bt=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=r.size,o=r.highWaterMark,a=void 0===o?1:o;if(i(this,t),this._state="writable",this._storedError=void 0,this._writer=void 0,this._writableStreamController=void 0,this._writeRequests=[],this._inFlightWriteRequest=void 0,this._closeRequest=void 0,this._inFlightCloseRequest=void 0,this._pendingAbortRequest=void 0,this._backpressure=!1,void 0!==e.type)throw new RangeError("Invalid type is specified");this._writableStreamController=new _t(this,e,n,a),this._writableStreamController.__startSteps()}return nt(t,[{key:"abort",value:function t(e){return!1===o(this)?Promise.reject(W("abort")):!0===a(this)?Promise.reject(new TypeError("Cannot abort a stream that already has a writer")):s(this,e)}},{key:"getWriter",value:function t(){if(!1===o(this))throw W("getWriter");return n(this)}},{key:"locked",get:function t(){if(!1===o(this))throw W("locked");return a(this)}}]),t}();t.exports={AcquireWritableStreamDefaultWriter:n,IsWritableStream:o,IsWritableStreamLocked:a,WritableStream:bt,WritableStreamAbort:s,WritableStreamDefaultControllerError:z,WritableStreamDefaultWriterCloseWithErrorPropagation:A,WritableStreamDefaultWriterRelease:E,WritableStreamDefaultWriterWrite:O,WritableStreamCloseQueuedOrInFlight:v};var yt=function(){function t(e){if(i(this,t),!1===o(e))throw new TypeError("WritableStreamDefaultWriter can only be constructed with a WritableStream instance");if(!0===a(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;var r=e._state;if("writable"===r)!1===v(e)&&!0===e._backpressure?K(this):$(this),G(this);else if("erroring"===r)Q(this,e._storedError),this._readyPromise.catch(function(){}),G(this);else if("closed"===r)$(this),Y(this);else{ut("errored"===r,"state must be errored");var n=e._storedError;Q(this,n),this._readyPromise.catch(function(){}),H(this,n),this._closedPromise.catch(function(){})}}return nt(t,[{key:"abort",value:function t(e){return!1===S(this)?Promise.reject(q("abort")):void 0===this._ownerWritableStream?Promise.reject(X("abort")):x(this,e)}},{key:"close",value:function t(){if(!1===S(this))return Promise.reject(q("close"));var e=this._ownerWritableStream;return void 0===e?Promise.reject(X("close")):!0===v(e)?Promise.reject(new TypeError("cannot close an already-closing stream")):C(this)}},{key:"releaseLock",value:function t(){if(!1===S(this))throw q("releaseLock");var e=this._ownerWritableStream;void 0!==e&&(ut(void 0!==e._writer),E(this))}},{key:"write",value:function t(e){return!1===S(this)?Promise.reject(q("write")):void 0===this._ownerWritableStream?Promise.reject(X("write to")):O(this,e)}},{key:"closed",get:function t(){return!1===S(this)?Promise.reject(q("closed")):this._closedPromise}},{key:"desiredSize",get:function t(){if(!1===S(this))throw q("desiredSize");if(void 0===this._ownerWritableStream)throw X("desiredSize");return P(this)}},{key:"ready",get:function t(){return!1===S(this)?Promise.reject(q("ready")):this._readyPromise}}]),t}(),_t=function(){function t(e,r,n,a){if(i(this,t),!1===o(e))throw new TypeError("WritableStreamDefaultController can only be constructed with a WritableStream instance");if(void 0!==e._writableStreamController)throw new TypeError("WritableStreamDefaultController instances can only be created by the WritableStream constructor");this._controlledWritableStream=e,this._underlyingSink=r,this._queue=void 0,this._queueTotalSize=void 0,mt(this),this._started=!1;var s=ct(n,a);this._strategySize=s.size,this._strategyHWM=s.highWaterMark,w(e,U(this))}return nt(t,[{key:"error",value:function t(e){if(!1===j(this))throw new TypeError("WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController");"writable"===this._controlledWritableStream._state&&z(this,e)}},{key:"__abortSteps",value:function t(e){return st(this._underlyingSink,"abort",[e])}},{key:"__errorSteps",value:function t(){mt(this)}},{key:"__startSteps",value:function t(){var e=this,r=at(this._underlyingSink,"start",[this]),i=this._controlledWritableStream;Promise.resolve(r).then(function(){ut("writable"===i._state||"erroring"===i._state),e._started=!0,M(e)},function(t){ut("writable"===i._state||"erroring"===i._state),e._started=!0,l(i,t)}).catch(ft)}}]),t}()},function(t,e,r){var i=r(0),n=i.IsFiniteNonNegativeNumber,o=r(1),a=o.assert;e.DequeueValue=function(t){a("_queue"in t&&"_queueTotalSize"in t,"Spec-level failure: DequeueValue should only be used on containers with [[queue]] and [[queueTotalSize]]."),a(t._queue.length>0,"Spec-level failure: should never dequeue from an empty queue.");var e=t._queue.shift();return t._queueTotalSize-=e.size,t._queueTotalSize<0&&(t._queueTotalSize=0),e.value},e.EnqueueValueWithSize=function(t,e,r){if(a("_queue"in t&&"_queueTotalSize"in t,"Spec-level failure: EnqueueValueWithSize should only be used on containers with [[queue]] and [[queueTotalSize]]."),r=Number(r),!n(r))throw new RangeError("Size must be a finite, non-NaN, non-negative number.");t._queue.push({value:e,size:r}),t._queueTotalSize+=r},e.PeekQueueValue=function(t){return a("_queue"in t&&"_queueTotalSize"in t,"Spec-level failure: PeekQueueValue should only be used on containers with [[queue]] and [[queueTotalSize]]."),a(t._queue.length>0,"Spec-level failure: should never peek at an empty queue."),t._queue[0].value},e.ResetQueue=function(t){a("_queue"in t&&"_queueTotalSize"in t,"Spec-level failure: ResetQueue should only be used on containers with [[queue]] and [[queueTotalSize]]."),t._queue=[],t._queueTotalSize=0}},function(t,e,r){function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t){return new ee(t)}function o(t){return new te(t)}function a(t){return!!Mt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_readableStreamController")}function s(t){return Nt(!0===a(t),"IsReadableStreamDisturbed should only be used on known readable streams"),t._disturbed}function c(t){return Nt(!0===a(t),"IsReadableStreamLocked should only be used on known readable streams"),void 0!==t._reader}function l(t,e){Nt(!0===a(t)),Nt("boolean"==typeof e);var r=o(t),i={closedOrErrored:!1,canceled1:!1,canceled2:!1,reason1:void 0,reason2:void 0};i.promise=new Promise(function(t){i._resolve=t});var n=h();n._reader=r,n._teeState=i,n._cloneForBranch2=e;var s=u();s._stream=t,s._teeState=i;var c=f();c._stream=t,c._teeState=i;var l=Object.create(Object.prototype);jt(l,"pull",n),jt(l,"cancel",s);var d=new $t(l),p=Object.create(Object.prototype);jt(p,"pull",n),jt(p,"cancel",c);var g=new $t(p);return n._branch1=d._readableStreamController,n._branch2=g._readableStreamController,r._closedPromise.catch(function(t){!0!==i.closedOrErrored&&(M(n._branch1,t),M(n._branch2,t),i.closedOrErrored=!0)}),[d,g]}function h(){function t(){var e=t._reader,r=t._branch1,i=t._branch2,n=t._teeState;return O(e).then(function(t){Nt(Mt(t));var e=t.value,o=t.done;if(Nt("boolean"==typeof o),!0===o&&!1===n.closedOrErrored&&(!1===n.canceled1&&I(r),!1===n.canceled2&&I(i),n.closedOrErrored=!0),!0!==n.closedOrErrored){var a=e,s=e;!1===n.canceled1&&j(r,a),!1===n.canceled2&&j(i,s)}})}return t}function u(){function t(e){var r=t._stream,i=t._teeState;if(i.canceled1=!0,i.reason1=e,!0===i.canceled2){var n=It([i.reason1,i.reason2]),o=g(r,n);i._resolve(o)}return i.promise}return t}function f(){function t(e){var r=t._stream,i=t._teeState;if(i.canceled2=!0,i.reason2=e,!0===i.canceled1){var n=It([i.reason1,i.reason2]),o=g(r,n);i._resolve(o)}return i.promise}return t}function d(t){return Nt(!0===C(t._reader)),Nt("readable"===t._state||"closed"===t._state),new Promise(function(e,r){var i={_resolve:e,_reject:r};t._reader._readIntoRequests.push(i)})}function p(t){return Nt(!0===A(t._reader)),Nt("readable"===t._state),new Promise(function(e,r){var i={_resolve:e,_reject:r};t._reader._readRequests.push(i)})}function g(t,e){return t._disturbed=!0,"closed"===t._state?Promise.resolve(void 0):"errored"===t._state?Promise.reject(t._storedError):(v(t),t._readableStreamController.__cancelSteps(e).then(function(){}))}function v(t){Nt("readable"===t._state),t._state="closed";var e=t._reader;if(void 0!==e){if(!0===A(e)){for(var r=0;r<e._readRequests.length;r++){(0,e._readRequests[r]._resolve)(Tt(void 0,!0))}e._readRequests=[]}mt(e)}}function m(t,e){Nt(!0===a(t),"stream must be ReadableStream"),Nt("readable"===t._state,"state must be readable"),t._state="errored",t._storedError=e;var r=t._reader;if(void 0!==r){if(!0===A(r)){for(var i=0;i<r._readRequests.length;i++){r._readRequests[i]._reject(e)}r._readRequests=[]}else{Nt(C(r),"reader must be ReadableStreamBYOBReader");for(var n=0;n<r._readIntoRequests.length;n++){r._readIntoRequests[n]._reject(e)}r._readIntoRequests=[]}gt(r,e),r._closedPromise.catch(function(){})}}function b(t,e,r){var i=t._reader;Nt(i._readIntoRequests.length>0),i._readIntoRequests.shift()._resolve(Tt(e,r))}function y(t,e,r){var i=t._reader;Nt(i._readRequests.length>0),i._readRequests.shift()._resolve(Tt(e,r))}function _(t){return t._reader._readIntoRequests.length}function w(t){return t._reader._readRequests.length}function S(t){var e=t._reader;return void 0!==e&&!1!==C(e)}function x(t){var e=t._reader;return void 0!==e&&!1!==A(e)}function C(t){return!!Mt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_readIntoRequests")}function A(t){return!!Mt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_readRequests")}function T(t,e){t._ownerReadableStream=e,e._reader=t,"readable"===e._state?ft(t):"closed"===e._state?pt(t):(Nt("errored"===e._state,"state must be errored"),dt(t,e._storedError),t._closedPromise.catch(function(){}))}function k(t,e){var r=t._ownerReadableStream;return Nt(void 0!==r),g(r,e)}function P(t){Nt(void 0!==t._ownerReadableStream),Nt(t._ownerReadableStream._reader===t),"readable"===t._ownerReadableStream._state?gt(t,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):vt(t,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),t._closedPromise.catch(function(){}),t._ownerReadableStream._reader=void 0,t._ownerReadableStream=void 0}function E(t,e){var r=t._ownerReadableStream;return Nt(void 0!==r),r._disturbed=!0,"errored"===r._state?Promise.reject(r._storedError):K(r._readableStreamController,e)}function O(t){var e=t._ownerReadableStream;return Nt(void 0!==e),e._disturbed=!0,"closed"===e._state?Promise.resolve(Tt(void 0,!0)):"errored"===e._state?Promise.reject(e._storedError):(Nt("readable"===e._state),e._readableStreamController.__pullSteps())}function R(t){return!!Mt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_underlyingSource")}function L(t){if(!1!==D(t)){if(!0===t._pulling)return void(t._pullAgain=!0);Nt(!1===t._pullAgain),t._pulling=!0,Et(t._underlyingSource,"pull",[t]).then(function(){if(t._pulling=!1,!0===t._pullAgain)return t._pullAgain=!1,L(t)},function(e){F(t,e)}).catch(Bt)}}function D(t){var e=t._controlledReadableStream;return"closed"!==e._state&&"errored"!==e._state&&(!0!==t._closeRequested&&(!1!==t._started&&(!0===c(e)&&w(e)>0||N(t)>0)))}function I(t){var e=t._controlledReadableStream;Nt(!1===t._closeRequested),Nt("readable"===e._state),t._closeRequested=!0,0===t._queue.length&&v(e)}function j(t,e){var r=t._controlledReadableStream;if(Nt(!1===t._closeRequested),Nt("readable"===r._state),!0===c(r)&&w(r)>0)y(r,e,!1);else{var i=1;if(void 0!==t._strategySize){var n=t._strategySize;try{i=n(e)}catch(e){throw F(t,e),e}}try{Wt(t,e,i)}catch(e){throw F(t,e),e}}L(t)}function M(t,e){var r=t._controlledReadableStream;Nt("readable"===r._state),qt(t),m(r,e)}function F(t,e){"readable"===t._controlledReadableStream._state&&M(t,e)}function N(t){var e=t._controlledReadableStream,r=e._state;return"errored"===r?null:"closed"===r?0:t._strategyHWM-t._queueTotalSize}function B(t){return!!Mt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_underlyingByteSource")}function U(t){return!!Mt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_associatedReadableByteStreamController")}function z(t){if(!1!==rt(t)){if(!0===t._pulling)return void(t._pullAgain=!0);Nt(!1===t._pullAgain),t._pulling=!0,Et(t._underlyingByteSource,"pull",[t]).then(function(){t._pulling=!1,!0===t._pullAgain&&(t._pullAgain=!1,z(t))},function(e){"readable"===t._controlledReadableStream._state&&ot(t,e)}).catch(Bt)}}function W(t){Z(t),t._pendingPullIntos=[]}function q(t,e){Nt("errored"!==t._state,"state must not be errored");var r=!1;"closed"===t._state&&(Nt(0===e.bytesFilled),r=!0);var i=X(e);"default"===e.readerType?y(t,i,r):(Nt("byob"===e.readerType),b(t,i,r))}function X(t){var e=t.bytesFilled,r=t.elementSize;return Nt(e<=t.byteLength),Nt(e%r==0),new t.ctor(t.buffer,t.byteOffset,e/r)}function G(t,e,r,i){t._queue.push({buffer:e,byteOffset:r,byteLength:i}),t._queueTotalSize+=i}function H(t,e){var r=e.elementSize,i=e.bytesFilled-e.bytesFilled%r,n=Math.min(t._queueTotalSize,e.byteLength-e.bytesFilled),o=e.bytesFilled+n,a=o-o%r,s=n,c=!1;a>i&&(s=a-e.bytesFilled,c=!0);for(var l=t._queue;s>0;){var h=l[0],u=Math.min(s,h.byteLength),f=e.byteOffset+e.bytesFilled;At(e.buffer,f,h.buffer,h.byteOffset,u),h.byteLength===u?l.shift():(h.byteOffset+=u,h.byteLength-=u),t._queueTotalSize-=u,Y(t,u,e),s-=u}return!1===c&&(Nt(0===t._queueTotalSize,"queue must be empty"),Nt(e.bytesFilled>0),Nt(e.bytesFilled<e.elementSize)),c}function Y(t,e,r){Nt(0===t._pendingPullIntos.length||t._pendingPullIntos[0]===r),Z(t),r.bytesFilled+=e}function V(t){Nt("readable"===t._controlledReadableStream._state),0===t._queueTotalSize&&!0===t._closeRequested?v(t._controlledReadableStream):z(t)}function Z(t){void 0!==t._byobRequest&&(t._byobRequest._associatedReadableByteStreamController=void 0,t._byobRequest._view=void 0,t._byobRequest=void 0)}function J(t){for(Nt(!1===t._closeRequested);t._pendingPullIntos.length>0;){if(0===t._queueTotalSize)return;var e=t._pendingPullIntos[0];!0===H(t,e)&&(et(t),q(t._controlledReadableStream,e))}}function K(t,e){var r=t._controlledReadableStream,i=1;e.constructor!==DataView&&(i=e.constructor.BYTES_PER_ELEMENT);var n=e.constructor,o={buffer:e.buffer,byteOffset:e.byteOffset,byteLength:e.byteLength,bytesFilled:0,elementSize:i,ctor:n,readerType:"byob"};if(t._pendingPullIntos.length>0)return o.buffer=Ot(o.buffer),t._pendingPullIntos.push(o),d(r);if("closed"===r._state){var a=new e.constructor(o.buffer,o.byteOffset,0);return Promise.resolve(Tt(a,!0))}if(t._queueTotalSize>0){if(!0===H(t,o)){var s=X(o);return V(t),Promise.resolve(Tt(s,!1))}if(!0===t._closeRequested){var c=new TypeError("Insufficient bytes to fill elements in the given buffer");return ot(t,c),Promise.reject(c)}}o.buffer=Ot(o.buffer),t._pendingPullIntos.push(o);var l=d(r);return z(t),l}function Q(t,e){e.buffer=Ot(e.buffer),Nt(0===e.bytesFilled,"bytesFilled must be 0");var r=t._controlledReadableStream;if(!0===S(r))for(;_(r)>0;){var i=et(t);q(r,i)}}function $(t,e,r){if(r.bytesFilled+e>r.byteLength)throw new RangeError("bytesWritten out of range");if(Y(t,e,r),!(r.bytesFilled<r.elementSize)){et(t);var i=r.bytesFilled%r.elementSize;if(i>0){var n=r.byteOffset+r.bytesFilled,o=r.buffer.slice(n-i,n);G(t,o,0,o.byteLength)}r.buffer=Ot(r.buffer),r.bytesFilled-=i,q(t._controlledReadableStream,r),J(t)}}function tt(t,e){var r=t._pendingPullIntos[0],i=t._controlledReadableStream;if("closed"===i._state){if(0!==e)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream");Q(t,r)}else Nt("readable"===i._state),$(t,e,r)}function et(t){var e=t._pendingPullIntos.shift();return Z(t),e}function rt(t){var e=t._controlledReadableStream;return"readable"===e._state&&(!0!==t._closeRequested&&(!1!==t._started&&(!0===x(e)&&w(e)>0||(!0===S(e)&&_(e)>0||at(t)>0))))}function it(t){var e=t._controlledReadableStream;if(Nt(!1===t._closeRequested),Nt("readable"===e._state),t._queueTotalSize>0)return void(t._closeRequested=!0);if(t._pendingPullIntos.length>0){if(t._pendingPullIntos[0].bytesFilled>0){var r=new TypeError("Insufficient bytes to fill elements in the given buffer");throw ot(t,r),r}}v(e)}function nt(t,e){var r=t._controlledReadableStream;Nt(!1===t._closeRequested),Nt("readable"===r._state);var i=e.buffer,n=e.byteOffset,o=e.byteLength,a=Ot(i);if(!0===x(r))if(0===w(r))G(t,a,n,o);else{Nt(0===t._queue.length);var s=new Uint8Array(a,n,o);y(r,s,!1)}else!0===S(r)?(G(t,a,n,o),J(t)):(Nt(!1===c(r),"stream must not be locked"),G(t,a,n,o))}function ot(t,e){var r=t._controlledReadableStream;Nt("readable"===r._state),W(t),qt(t),m(r,e)}function at(t){var e=t._controlledReadableStream,r=e._state;return"errored"===r?null:"closed"===r?0:t._strategyHWM-t._queueTotalSize}function st(t,e){if(e=Number(e),!1===kt(e))throw new RangeError("bytesWritten must be a finite");Nt(t._pendingPullIntos.length>0),tt(t,e)}function ct(t,e){Nt(t._pendingPullIntos.length>0);var r=t._pendingPullIntos[0];if(r.byteOffset+r.bytesFilled!==e.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.byteLength!==e.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");r.buffer=e.buffer,tt(t,e.byteLength)}function lt(t){return new TypeError("ReadableStream.prototype."+t+" can only be used on a ReadableStream")}function ht(t){return new TypeError("Cannot "+t+" a stream using a released reader")}function ut(t){return new TypeError("ReadableStreamDefaultReader.prototype."+t+" can only be used on a ReadableStreamDefaultReader")}function ft(t){t._closedPromise=new Promise(function(e,r){t._closedPromise_resolve=e,t._closedPromise_reject=r})}function dt(t,e){t._closedPromise=Promise.reject(e),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0}function pt(t){t._closedPromise=Promise.resolve(void 0),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0}function gt(t,e){Nt(void 0!==t._closedPromise_resolve),Nt(void 0!==t._closedPromise_reject),t._closedPromise_reject(e),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0}function vt(t,e){Nt(void 0===t._closedPromise_resolve),Nt(void 0===t._closedPromise_reject),t._closedPromise=Promise.reject(e)}function mt(t){Nt(void 0!==t._closedPromise_resolve),Nt(void 0!==t._closedPromise_reject),t._closedPromise_resolve(void 0),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0}function bt(t){return new TypeError("ReadableStreamBYOBReader.prototype."+t+" can only be used on a ReadableStreamBYOBReader")}function yt(t){return new TypeError("ReadableStreamDefaultController.prototype."+t+" can only be used on a ReadableStreamDefaultController")}function _t(t){return new TypeError("ReadableStreamBYOBRequest.prototype."+t+" can only be used on a ReadableStreamBYOBRequest")}function wt(t){return new TypeError("ReadableByteStreamController.prototype."+t+" can only be used on a ReadableByteStreamController")}function St(t){try{Promise.prototype.then.call(t,void 0,function(){})}catch(t){}}var xt=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),Ct=r(0),At=Ct.ArrayBufferCopy,Tt=Ct.CreateIterResultObject,kt=Ct.IsFiniteNonNegativeNumber,Pt=Ct.InvokeOrNoop,Et=Ct.PromiseInvokeOrNoop,Ot=Ct.TransferArrayBuffer,Rt=Ct.ValidateAndNormalizeQueuingStrategy,Lt=Ct.ValidateAndNormalizeHighWaterMark,Dt=r(0),It=Dt.createArrayFromList,jt=Dt.createDataProperty,Mt=Dt.typeIsObject,Ft=r(1),Nt=Ft.assert,Bt=Ft.rethrowAssertionErrorRejection,Ut=r(3),zt=Ut.DequeueValue,Wt=Ut.EnqueueValueWithSize,qt=Ut.ResetQueue,Xt=r(2),Gt=Xt.AcquireWritableStreamDefaultWriter,Ht=Xt.IsWritableStream,Yt=Xt.IsWritableStreamLocked,Vt=Xt.WritableStreamAbort,Zt=Xt.WritableStreamDefaultWriterCloseWithErrorPropagation,Jt=Xt.WritableStreamDefaultWriterRelease,Kt=Xt.WritableStreamDefaultWriterWrite,Qt=Xt.WritableStreamCloseQueuedOrInFlight,$t=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=r.size,o=r.highWaterMark;i(this,t),this._state="readable",this._reader=void 0,this._storedError=void 0,this._disturbed=!1,this._readableStreamController=void 0;var a=e.type;if("bytes"===String(a))void 0===o&&(o=0),this._readableStreamController=new ne(this,e,o);else{if(void 0!==a)throw new RangeError("Invalid type is specified");void 0===o&&(o=1),this._readableStreamController=new re(this,e,n,o)}}return xt(t,[{key:"cancel",value:function t(e){return!1===a(this)?Promise.reject(lt("cancel")):!0===c(this)?Promise.reject(new TypeError("Cannot cancel a stream that already has a reader")):g(this,e)}},{key:"getReader",value:function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=e.mode;if(!1===a(this))throw lt("getReader");if(void 0===r)return o(this);if("byob"===(r=String(r)))return n(this);throw new RangeError("Invalid mode is specified")}},{key:"pipeThrough",value:function t(e,r){var i=e.writable,n=e.readable;return St(this.pipeTo(i,r)),n}},{key:"pipeTo",value:function t(e){var r=this,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=i.preventClose,s=i.preventAbort,l=i.preventCancel;if(!1===a(this))return Promise.reject(lt("pipeTo"));if(!1===Ht(e))return Promise.reject(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));if(n=Boolean(n),s=Boolean(s),l=Boolean(l),!0===c(this))return Promise.reject(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream"));if(!0===Yt(e))return Promise.reject(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream"));var h=o(this),u=Gt(e),f=!1,d=Promise.resolve();return new Promise(function(t,i){function o(){return d=Promise.resolve(),!0===f?Promise.resolve():u._readyPromise.then(function(){return O(h).then(function(t){var e=t.value;!0!==t.done&&(d=Kt(u,e).catch(function(){}))})}).then(o)}function a(){var t=d;return d.then(function(){return t!==d?a():void 0})}function c(t,e,r){"errored"===t._state?r(t._storedError):e.catch(r).catch(Bt)}function p(t,e,r){"closed"===t._state?r():e.then(r).catch(Bt)}function v(t,r,i){function n(){t().then(function(){return b(r,i)},function(t){return b(!0,t)}).catch(Bt)}!0!==f&&(f=!0,"writable"===e._state&&!1===Qt(e)?a().then(n):n())}function m(t,r){!0!==f&&(f=!0,"writable"===e._state&&!1===Qt(e)?a().then(function(){return b(t,r)}).catch(Bt):b(t,r))}function b(e,r){Jt(u),P(h),e?i(r):t(void 0)}if(c(r,h._closedPromise,function(t){!1===s?v(function(){return Vt(e,t)},!0,t):m(!0,t)}),c(e,u._closedPromise,function(t){!1===l?v(function(){return g(r,t)},!0,t):m(!0,t)}),p(r,h._closedPromise,function(){!1===n?v(function(){return Zt(u)}):m()}),!0===Qt(e)||"closed"===e._state){var y=new TypeError("the destination writable stream closed before all data could be piped to it");!1===l?v(function(){return g(r,y)},!0,y):m(!0,y)}o().catch(function(t){d=Promise.resolve(),Bt(t)})})}},{key:"tee",value:function t(){if(!1===a(this))throw lt("tee");var e=l(this,!1);return It(e)}},{key:"locked",get:function t(){if(!1===a(this))throw lt("locked");return c(this)}}]),t}();t.exports={ReadableStream:$t,IsReadableStreamDisturbed:s,ReadableStreamDefaultControllerClose:I,ReadableStreamDefaultControllerEnqueue:j,ReadableStreamDefaultControllerError:M,ReadableStreamDefaultControllerGetDesiredSize:N};var te=function(){function t(e){if(i(this,t),!1===a(e))throw new TypeError("ReadableStreamDefaultReader can only be constructed with a ReadableStream instance");if(!0===c(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");T(this,e),this._readRequests=[]}return xt(t,[{key:"cancel",value:function t(e){return!1===A(this)?Promise.reject(ut("cancel")):void 0===this._ownerReadableStream?Promise.reject(ht("cancel")):k(this,e)}},{key:"read",value:function t(){return!1===A(this)?Promise.reject(ut("read")):void 0===this._ownerReadableStream?Promise.reject(ht("read from")):O(this)}},{key:"releaseLock",value:function t(){if(!1===A(this))throw ut("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");P(this)}}},{key:"closed",get:function t(){return!1===A(this)?Promise.reject(ut("closed")):this._closedPromise}}]),t}(),ee=function(){function t(e){if(i(this,t),!a(e))throw new TypeError("ReadableStreamBYOBReader can only be constructed with a ReadableStream instance given a byte source");if(!1===B(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");if(c(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");T(this,e),this._readIntoRequests=[]}return xt(t,[{key:"cancel",value:function t(e){return C(this)?void 0===this._ownerReadableStream?Promise.reject(ht("cancel")):k(this,e):Promise.reject(bt("cancel"))}},{key:"read",value:function t(e){return C(this)?void 0===this._ownerReadableStream?Promise.reject(ht("read from")):ArrayBuffer.isView(e)?0===e.byteLength?Promise.reject(new TypeError("view must have non-zero byteLength")):E(this,e):Promise.reject(new TypeError("view must be an array buffer view")):Promise.reject(bt("read"))}},{key:"releaseLock",value:function t(){if(!C(this))throw bt("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readIntoRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");P(this)}}},{key:"closed",get:function t(){return C(this)?this._closedPromise:Promise.reject(bt("closed"))}}]),t}(),re=function(){function t(e,r,n,o){if(i(this,t),!1===a(e))throw new TypeError("ReadableStreamDefaultController can only be constructed with a ReadableStream instance");if(void 0!==e._readableStreamController)throw new TypeError("ReadableStreamDefaultController instances can only be created by the ReadableStream constructor");this._controlledReadableStream=e,this._underlyingSource=r,this._queue=void 0,this._queueTotalSize=void 0,qt(this),this._started=!1,this._closeRequested=!1,this._pullAgain=!1,this._pulling=!1;var s=Rt(n,o);this._strategySize=s.size,this._strategyHWM=s.highWaterMark;var c=this,l=Pt(r,"start",[this]);Promise.resolve(l).then(function(){c._started=!0,Nt(!1===c._pulling),Nt(!1===c._pullAgain),L(c)},function(t){F(c,t)}).catch(Bt)}return xt(t,[{key:"close",value:function t(){if(!1===R(this))throw yt("close");if(!0===this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");var e=this._controlledReadableStream._state;if("readable"!==e)throw new TypeError("The stream (in "+e+" state) is not in the readable state and cannot be closed");I(this)}},{key:"enqueue",value:function t(e){if(!1===R(this))throw yt("enqueue");if(!0===this._closeRequested)throw new TypeError("stream is closed or draining");var r=this._controlledReadableStream._state;if("readable"!==r)throw new TypeError("The stream (in "+r+" state) is not in the readable state and cannot be enqueued to");return j(this,e)}},{key:"error",value:function t(e){if(!1===R(this))throw yt("error");var r=this._controlledReadableStream;if("readable"!==r._state)throw new TypeError("The stream is "+r._state+" and so cannot be errored");M(this,e)}},{key:"__cancelSteps",value:function t(e){return qt(this),Et(this._underlyingSource,"cancel",[e])}},{key:"__pullSteps",value:function t(){var e=this._controlledReadableStream;if(this._queue.length>0){var r=zt(this);return!0===this._closeRequested&&0===this._queue.length?v(e):L(this),Promise.resolve(Tt(r,!1))}var i=p(e);return L(this),i}},{key:"desiredSize",get:function t(){if(!1===R(this))throw yt("desiredSize");return N(this)}}]),t}(),ie=function(){function t(e,r){i(this,t),this._associatedReadableByteStreamController=e,this._view=r}return xt(t,[{key:"respond",value:function t(e){if(!1===U(this))throw _t("respond");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");st(this._associatedReadableByteStreamController,e)}},{key:"respondWithNewView",value:function t(e){if(!1===U(this))throw _t("respond");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");ct(this._associatedReadableByteStreamController,e)}},{key:"view",get:function t(){return this._view}}]),t}(),ne=function(){function t(e,r,n){if(i(this,t),!1===a(e))throw new TypeError("ReadableByteStreamController can only be constructed with a ReadableStream instance given a byte source");if(void 0!==e._readableStreamController)throw new TypeError("ReadableByteStreamController instances can only be created by the ReadableStream constructor given a byte source");this._controlledReadableStream=e,this._underlyingByteSource=r,this._pullAgain=!1,this._pulling=!1,W(this),this._queue=this._queueTotalSize=void 0,qt(this),this._closeRequested=!1,this._started=!1,this._strategyHWM=Lt(n);var o=r.autoAllocateChunkSize;if(void 0!==o&&(!1===Number.isInteger(o)||o<=0))throw new RangeError("autoAllocateChunkSize must be a positive integer");this._autoAllocateChunkSize=o,this._pendingPullIntos=[];var s=this,c=Pt(r,"start",[this]);Promise.resolve(c).then(function(){s._started=!0,Nt(!1===s._pulling),Nt(!1===s._pullAgain),z(s)},function(t){"readable"===e._state&&ot(s,t)}).catch(Bt)}return xt(t,[{key:"close",value:function t(){if(!1===B(this))throw wt("close");if(!0===this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");var e=this._controlledReadableStream._state;if("readable"!==e)throw new TypeError("The stream (in "+e+" state) is not in the readable state and cannot be closed");it(this)}},{key:"enqueue",value:function t(e){if(!1===B(this))throw wt("enqueue");if(!0===this._closeRequested)throw new TypeError("stream is closed or draining");var r=this._controlledReadableStream._state;if("readable"!==r)throw new TypeError("The stream (in "+r+" state) is not in the readable state and cannot be enqueued to");if(!ArrayBuffer.isView(e))throw new TypeError("You can only enqueue array buffer views when using a ReadableByteStreamController");nt(this,e)}},{key:"error",value:function t(e){if(!1===B(this))throw wt("error");var r=this._controlledReadableStream;if("readable"!==r._state)throw new TypeError("The stream is "+r._state+" and so cannot be errored");ot(this,e)}},{key:"__cancelSteps",value:function t(e){if(this._pendingPullIntos.length>0){this._pendingPullIntos[0].bytesFilled=0}return qt(this),Et(this._underlyingByteSource,"cancel",[e])}},{key:"__pullSteps",value:function t(){var e=this._controlledReadableStream;if(Nt(!0===x(e)),this._queueTotalSize>0){Nt(0===w(e));var r=this._queue.shift();this._queueTotalSize-=r.byteLength,V(this);var i=void 0;try{i=new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}catch(t){return Promise.reject(t)}return Promise.resolve(Tt(i,!1))}var n=this._autoAllocateChunkSize;if(void 0!==n){var o=void 0;try{o=new ArrayBuffer(n)}catch(t){return Promise.reject(t)}var a={buffer:o,byteOffset:0,byteLength:n,bytesFilled:0,elementSize:1,ctor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(a)}var s=p(e);return z(this),s}},{key:"byobRequest",get:function t(){if(!1===B(this))throw wt("byobRequest");if(void 0===this._byobRequest&&this._pendingPullIntos.length>0){var e=this._pendingPullIntos[0],r=new Uint8Array(e.buffer,e.byteOffset+e.bytesFilled,e.byteLength-e.bytesFilled);this._byobRequest=new ie(this,r)}return this._byobRequest}},{key:"desiredSize",get:function t(){if(!1===B(this))throw wt("desiredSize");return at(this)}}]),t}()},function(t,e,r){var i=r(6),n=r(4),o=r(2);e.TransformStream=i.TransformStream,e.ReadableStream=n.ReadableStream,e.IsReadableStreamDisturbed=n.IsReadableStreamDisturbed,e.ReadableStreamDefaultControllerClose=n.ReadableStreamDefaultControllerClose,e.ReadableStreamDefaultControllerEnqueue=n.ReadableStreamDefaultControllerEnqueue,e.ReadableStreamDefaultControllerError=n.ReadableStreamDefaultControllerError,e.ReadableStreamDefaultControllerGetDesiredSize=n.ReadableStreamDefaultControllerGetDesiredSize,e.AcquireWritableStreamDefaultWriter=o.AcquireWritableStreamDefaultWriter,e.IsWritableStream=o.IsWritableStream,e.IsWritableStreamLocked=o.IsWritableStreamLocked,e.WritableStream=o.WritableStream,e.WritableStreamAbort=o.WritableStreamAbort,e.WritableStreamDefaultControllerError=o.WritableStreamDefaultControllerError,e.WritableStreamDefaultWriterCloseWithErrorPropagation=o.WritableStreamDefaultWriterCloseWithErrorPropagation,e.WritableStreamDefaultWriterRelease=o.WritableStreamDefaultWriterRelease,e.WritableStreamDefaultWriterWrite=o.WritableStreamDefaultWriterWrite},function(t,e,r){function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t){if(!0===t._errored)throw new TypeError("TransformStream is already errored");if(!0===t._readableClosed)throw new TypeError("Readable side is already closed");s(t)}function o(t,e){if(!0===t._errored)throw new TypeError("TransformStream is already errored");if(!0===t._readableClosed)throw new TypeError("Readable side is already closed");var r=t._readableController;try{E(r,e)}catch(e){throw t._readableClosed=!0,c(t,e),t._storedError}!0==R(r)<=0&&!1===t._backpressure&&u(t,!0)}function a(t,e){if(!0===t._errored)throw new TypeError("TransformStream is already errored");l(t,e)}function s(t){_(!1===t._errored),_(!1===t._readableClosed);try{P(t._readableController)}catch(t){_(!1)}t._readableClosed=!0}function c(t,e){!1===t._errored&&l(t,e)}function l(t,e){_(!1===t._errored),t._errored=!0,t._storedError=e,!1===t._writableDone&&I(t._writableController,e),!1===t._readableClosed&&O(t._readableController,e)}function h(t){return _(void 0!==t._backpressureChangePromise,"_backpressureChangePromise should have been initialized"),!1===t._backpressure?Promise.resolve():(_(!0===t._backpressure,"_backpressure should have been initialized"),t._backpressureChangePromise)}function u(t,e){_(t._backpressure!==e,"TransformStreamSetBackpressure() should be called only when backpressure is changed"),void 0!==t._backpressureChangePromise&&t._backpressureChangePromise_resolve(e),t._backpressureChangePromise=new Promise(function(e){t._backpressureChangePromise_resolve=e}),t._backpressureChangePromise.then(function(t){_(t!==e,"_backpressureChangePromise should be fulfilled only when backpressure is changed")}),t._backpressure=e}function f(t,e){return o(e._controlledTransformStream,t),Promise.resolve()}function d(t,e){_(!1===t._errored),_(!1===t._transforming),_(!1===t._backpressure),t._transforming=!0;var r=t._transformer,i=t._transformStreamController;return x(r,"transform",[e,i],f,[e,i]).then(function(){return t._transforming=!1,h(t)},function(e){return c(t,e),Promise.reject(e)})}function p(t){return!!A(t)&&!!Object.prototype.hasOwnProperty.call(t,"_controlledTransformStream")}function g(t){return!!A(t)&&!!Object.prototype.hasOwnProperty.call(t,"_transformStreamController")}function v(t){return new TypeError("TransformStreamDefaultController.prototype."+t+" can only be used on a TransformStreamDefaultController")}function m(t){return new TypeError("TransformStream.prototype."+t+" can only be used on a TransformStream")}var b=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),y=r(1),_=y.assert,w=r(0),S=w.InvokeOrNoop,x=w.PromiseInvokeOrPerformFallback,C=w.PromiseInvokeOrNoop,A=w.typeIsObject,T=r(4),k=T.ReadableStream,P=T.ReadableStreamDefaultControllerClose,E=T.ReadableStreamDefaultControllerEnqueue,O=T.ReadableStreamDefaultControllerError,R=T.ReadableStreamDefaultControllerGetDesiredSize,L=r(2),D=L.WritableStream,I=L.WritableStreamDefaultControllerError,j=function(){function t(e,r){i(this,t),this._transformStream=e,this._startPromise=r}return b(t,[{key:"start",value:function t(e){var r=this._transformStream;return r._writableController=e,this._startPromise.then(function(){return h(r)})}},{key:"write",value:function t(e){return d(this._transformStream,e)}},{key:"abort",value:function t(){var e=this._transformStream;e._writableDone=!0,l(e,new TypeError("Writable side aborted"))}},{key:"close",value:function t(){var e=this._transformStream;return _(!1===e._transforming),e._writableDone=!0,C(e._transformer,"flush",[e._transformStreamController]).then(function(){return!0===e._errored?Promise.reject(e._storedError):(!1===e._readableClosed&&s(e),Promise.resolve())}).catch(function(t){return c(e,t),Promise.reject(e._storedError)})}}]),t}(),M=function(){function t(e,r){i(this,t),this._transformStream=e,this._startPromise=r}return b(t,[{key:"start",value:function t(e){var r=this._transformStream;return r._readableController=e,this._startPromise.then(function(){return _(void 0!==r._backpressureChangePromise,"_backpressureChangePromise should have been initialized"),!0===r._backpressure?Promise.resolve():(_(!1===r._backpressure,"_backpressure should have been initialized"),r._backpressureChangePromise)})}},{key:"pull",value:function t(){var e=this._transformStream;return _(!0===e._backpressure,"pull() should be never called while _backpressure is false"),_(void 0!==e._backpressureChangePromise,"_backpressureChangePromise should have been initialized"),u(e,!1),e._backpressureChangePromise}},{key:"cancel",value:function t(){var e=this._transformStream;e._readableClosed=!0,l(e,new TypeError("Readable side canceled"))}}]),t}(),F=function(){function t(e){if(i(this,t),!1===g(e))throw new TypeError("TransformStreamDefaultController can only be constructed with a TransformStream instance");if(void 0!==e._transformStreamController)throw new TypeError("TransformStreamDefaultController instances can only be created by the TransformStream constructor");this._controlledTransformStream=e}return b(t,[{key:"enqueue",value:function t(e){if(!1===p(this))throw v("enqueue");o(this._controlledTransformStream,e)}},{key:"close",value:function t(){if(!1===p(this))throw v("close");n(this._controlledTransformStream)}},{key:"error",value:function t(e){if(!1===p(this))throw v("error");a(this._controlledTransformStream,e)}},{key:"desiredSize",get:function t(){if(!1===p(this))throw v("desiredSize");var e=this._controlledTransformStream,r=e._readableController;return R(r)}}]),t}(),N=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};i(this,t),this._transformer=e;var r=e.readableStrategy,n=e.writableStrategy;this._transforming=!1,this._errored=!1,this._storedError=void 0,this._writableController=void 0,this._readableController=void 0,this._transformStreamController=void 0,this._writableDone=!1,this._readableClosed=!1,this._backpressure=void 0,this._backpressureChangePromise=void 0,this._backpressureChangePromise_resolve=void 0,this._transformStreamController=new F(this);var o=void 0,a=new Promise(function(t){o=t}),s=new M(this,a);this._readable=new k(s,r);var c=new j(this,a);this._writable=new D(c,n),_(void 0!==this._writableController),_(void 0!==this._readableController),u(this,R(this._readableController)<=0);var l=this,h=S(e,"start",[l._transformStreamController]);o(h),a.catch(function(t){!1===l._errored&&(l._errored=!0,l._storedError=t)})}return b(t,[{key:"readable",get:function t(){if(!1===g(this))throw m("readable");return this._readable}},{key:"writable",get:function t(){if(!1===g(this))throw m("writable");return this._writable}}]),t}();t.exports={TransformStream:N}},function(t,e,r){t.exports=r(5)}]))},function(t,e,r){"use strict";function i(t){t.mozCurrentTransform||(t._originalSave=t.save,t._originalRestore=t.restore,t._originalRotate=t.rotate,t._originalScale=t.scale,t._originalTranslate=t.translate,t._originalTransform=t.transform,t._originalSetTransform=t.setTransform,t._transformMatrix=t._transformMatrix||[1,0,0,1,0,0],t._transformStack=[],Object.defineProperty(t,"mozCurrentTransform",{get:function t(){return this._transformMatrix}}),Object.defineProperty(t,"mozCurrentTransformInverse",{get:function t(){var e=this._transformMatrix,r=e[0],i=e[1],n=e[2],o=e[3],a=e[4],s=e[5],c=r*o-i*n,l=i*n-r*o;return[o/c,i/l,n/l,r/c,(o*a-n*s)/l,(i*a-r*s)/c]}}),t.save=function t(){var e=this._transformMatrix;this._transformStack.push(e),this._transformMatrix=e.slice(0,6),this._originalSave()},t.restore=function t(){var e=this._transformStack.pop();e&&(this._transformMatrix=e,this._originalRestore())},t.translate=function t(e,r){var i=this._transformMatrix;i[4]=i[0]*e+i[2]*r+i[4],i[5]=i[1]*e+i[3]*r+i[5],this._originalTranslate(e,r)},t.scale=function t(e,r){var i=this._transformMatrix;i[0]=i[0]*e,i[1]=i[1]*e,i[2]=i[2]*r,i[3]=i[3]*r,this._originalScale(e,r)},t.transform=function e(r,i,n,o,a,s){var c=this._transformMatrix;this._transformMatrix=[c[0]*r+c[2]*i,c[1]*r+c[3]*i,c[0]*n+c[2]*o,c[1]*n+c[3]*o,c[0]*a+c[2]*s+c[4],c[1]*a+c[3]*s+c[5]],t._originalTransform(r,i,n,o,a,s)},t.setTransform=function e(r,i,n,o,a,s){this._transformMatrix=[r,i,n,o,a,s],t._originalSetTransform(r,i,n,o,a,s)},t.rotate=function t(e){var r=Math.cos(e),i=Math.sin(e),n=this._transformMatrix;this._transformMatrix=[n[0]*r+n[2]*i,n[1]*r+n[3]*i,n[0]*-i+n[2]*r,n[1]*-i+n[3]*r,n[4],n[5]],this._originalRotate(e)})}function n(t){var e=1e3,r=t.width,i=t.height,n,o,a,s=r+1,c=new Uint8Array(s*(i+1)),l=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),h=r+7&-8,u=t.data,f=new Uint8Array(h*i),d=0,p;for(n=0,p=u.length;n<p;n++)for(var g=128,v=u[n];g>0;)f[d++]=v&g?0:255,g>>=1;var m=0;for(d=0,0!==f[d]&&(c[0]=1,++m),o=1;o<r;o++)f[d]!==f[d+1]&&(c[o]=f[d]?2:1,++m),d++;for(0!==f[d]&&(c[o]=2,++m),n=1;n<i;n++){d=n*h,a=n*s,f[d-h]!==f[d]&&(c[a]=f[d]?1:8,++m);var b=(f[d]?4:0)+(f[d-h]?8:0);for(o=1;o<r;o++)b=(b>>2)+(f[d+1]?4:0)+(f[d-h+1]?8:0),l[b]&&(c[a+o]=l[b],++m),d++;if(f[d-h]!==f[d]&&(c[a+o]=f[d]?2:4,++m),m>1e3)return null}for(d=h*(i-1),a=n*s,0!==f[d]&&(c[a]=8,++m),o=1;o<r;o++)f[d]!==f[d+1]&&(c[a+o]=f[d]?4:8,++m),d++;if(0!==f[d]&&(c[a+o]=4,++m),m>1e3)return null;var y=new Int32Array([0,s,-1,0,-s,0,0,0,1]),_=[];for(n=0;m&&n<=i;n++){for(var w=n*s,S=w+r;w<S&&!c[w];)w++;if(w!==S){var x=[w%s,n],C=c[w],A=w,T;do{var k=y[C];do{w+=k}while(!c[w]);T=c[w],5!==T&&10!==T?(C=T,c[w]=0):(C=T&51*C>>4,c[w]&=C>>2|C<<2),x.push(w%s),x.push(w/s|0),--m}while(A!==w);_.push(x),--n}}return function t(e){e.save(),e.scale(1/r,-1/i),e.translate(0,-i),e.beginPath();for(var n=0,o=_.length;n<o;n++){var a=_[n];e.moveTo(a[0],a[1]);for(var s=2,c=a.length;s<c;s+=2)e.lineTo(a[s],a[s+1])}e.fill(),e.beginPath(),e.restore()}}Object.defineProperty(e,"__esModule",{value:!0}),e.CanvasGraphics=void 0;var o=r(0),a=r(12),s=r(7),c=16,l=100,h=4096,u=.65,f=!0,d=1e3,p=16,g={get value(){return(0,o.shadow)(g,"value",(0,o.isLittleEndian)())}},v=function t(){function e(t){this.canvasFactory=t,this.cache=Object.create(null)}return e.prototype={getCanvas:function t(e,r,n,o){var a;return void 0!==this.cache[e]?(a=this.cache[e],this.canvasFactory.reset(a,r,n),a.context.setTransform(1,0,0,1,0,0)):(a=this.canvasFactory.create(r,n),this.cache[e]=a),o&&i(a.context),a},clear:function t(){for(var e in this.cache){var r=this.cache[e];this.canvasFactory.destroy(r),delete this.cache[e]}}},e}(),m=function t(){function e(){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=o.IDENTITY_MATRIX,this.textMatrixScale=1,this.fontMatrix=o.FONT_IDENTITY_MATRIX,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=o.TextRenderingMode.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.resumeSMaskCtx=null}return e.prototype={clone:function t(){return Object.create(this)},setCurrentPoint:function t(e,r){this.x=e,this.y=r}},e}(),b=function t(){function e(t,e,r,n,o){this.ctx=t,this.current=new m,this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=e,this.objs=r,this.canvasFactory=n,this.imageLayer=o,this.groupStack=[],this.processingType3=null,this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.smaskCounter=0,this.tempSMask=null,this.cachedCanvases=new v(this.canvasFactory),t&&i(t),this.cachedGetSinglePixelWidth=null}function r(t,e){if("undefined"!=typeof ImageData&&e instanceof ImageData)return void t.putImageData(e,0,0);var r=e.height,i=e.width,n=r%p,a=(r-n)/p,s=0===n?a:a+1,c=t.createImageData(i,p),l=0,h,u=e.data,f=c.data,d,v,m,b;if(e.kind===o.ImageKind.GRAYSCALE_1BPP){var y=u.byteLength,_=new Uint32Array(f.buffer,0,f.byteLength>>2),w=_.length,S=i+7>>3,x=4294967295,C=g.value?4278190080:255;for(d=0;d<s;d++){for(m=d<a?p:n,h=0,v=0;v<m;v++){for(var A=y-l,T=0,k=A>S?i:8*A-7,P=-8&k,E=0,O=0;T<P;T+=8)O=u[l++],_[h++]=128&O?x:C,_[h++]=64&O?x:C,_[h++]=32&O?x:C,_[h++]=16&O?x:C,_[h++]=8&O?x:C,_[h++]=4&O?x:C,_[h++]=2&O?x:C,_[h++]=1&O?x:C;for(;T<k;T++)0===E&&(O=u[l++],E=128),_[h++]=O&E?x:C,E>>=1}for(;h<w;)_[h++]=0;t.putImageData(c,0,d*p)}}else if(e.kind===o.ImageKind.RGBA_32BPP){for(v=0,b=i*p*4,d=0;d<a;d++)f.set(u.subarray(l,l+b)),l+=b,t.putImageData(c,0,v),v+=p;d<s&&(b=i*n*4,f.set(u.subarray(l,l+b)),t.putImageData(c,0,v))}else{if(e.kind!==o.ImageKind.RGB_24BPP)throw new Error("bad image kind: "+e.kind);for(m=p,b=i*m,d=0;d<s;d++){for(d>=a&&(m=n,b=i*m),h=0,v=b;v--;)f[h++]=u[l++],f[h++]=u[l++],f[h++]=u[l++],f[h++]=255;t.putImageData(c,0,d*p)}}}function c(t,e){for(var r=e.height,i=e.width,n=r%p,o=(r-n)/p,a=0===n?o:o+1,s=t.createImageData(i,p),c=0,l=e.data,h=s.data,u=0;u<a;u++){for(var f=u<o?p:n,d=3,g=0;g<f;g++)for(var v=0,m=0;m<i;m++){if(!v){var b=l[c++];v=128}h[d]=b&v?0:255,d+=4,v>>=1}t.putImageData(s,0,u*p)}}function l(t,e){for(var r=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font"],i=0,n=r.length;i<n;i++){var o=r[i];void 0!==t[o]&&(e[o]=t[o])}void 0!==t.setLineDash&&(e.setLineDash(t.getLineDash()),e.lineDashOffset=t.lineDashOffset)}function h(t){t.strokeStyle="#000000",t.fillStyle="#000000",t.fillRule="nonzero",t.globalAlpha=1,t.lineWidth=1,t.lineCap="butt",t.lineJoin="miter",t.miterLimit=10,t.globalCompositeOperation="source-over",t.font="10px sans-serif",void 0!==t.setLineDash&&(t.setLineDash([]),t.lineDashOffset=0)}function u(t,e,r,i){for(var n=t.length,o=3;o<n;o+=4){var a=t[o];if(0===a)t[o-3]=e,t[o-2]=r,t[o-1]=i;else if(a<255){var s=255-a;t[o-3]=t[o-3]*a+e*s>>8,t[o-2]=t[o-2]*a+r*s>>8,t[o-1]=t[o-1]*a+i*s>>8}}}function f(t,e,r){for(var i=t.length,n=1/255,o=3;o<i;o+=4){var a=r?r[t[o]]:t[o];e[o]=e[o]*a*(1/255)|0}}function d(t,e,r){for(var i=t.length,n=3;n<i;n+=4){var o=77*t[n-3]+152*t[n-2]+28*t[n-1];e[n]=r?e[n]*r[o>>8]>>8:e[n]*o>>16}}function b(t,e,r,i,n,o,a){var s=!!o,c=s?o[0]:0,l=s?o[1]:0,h=s?o[2]:0,p;p="Luminosity"===n?d:f;for(var g=1048576,v=Math.min(i,Math.ceil(1048576/r)),m=0;m<i;m+=v){var b=Math.min(v,i-m),y=t.getImageData(0,m,r,b),_=e.getImageData(0,m,r,b);s&&u(y.data,c,l,h),p(y.data,_.data,a),t.putImageData(_,0,m)}}function y(t,e,r){var i=e.canvas,n=e.context;t.setTransform(e.scaleX,0,0,e.scaleY,e.offsetX,e.offsetY);var o=e.backdrop||null;if(!e.transferMap&&s.WebGLUtils.isEnabled){var a=s.WebGLUtils.composeSMask(r.canvas,i,{subtype:e.subtype,backdrop:o});return t.setTransform(1,0,0,1,0,0),void t.drawImage(a,e.offsetX,e.offsetY)}b(n,r,i.width,i.height,e.subtype,o,e.transferMap),t.drawImage(i,0,0)}var _=15,w=10,S=["butt","round","square"],x=["miter","round","bevel"],C={},A={};e.prototype={beginDrawing:function t(e){var r=e.transform,i=e.viewport,n=e.transparency,o=e.background,a=void 0===o?null:o,s=this.ctx.canvas.width,c=this.ctx.canvas.height;if(this.ctx.save(),this.ctx.fillStyle=a||"rgb(255, 255, 255)",this.ctx.fillRect(0,0,s,c),this.ctx.restore(),n){var l=this.cachedCanvases.getCanvas("transparent",s,c,!0);this.compositeCtx=this.ctx,this.transparentCanvas=l.canvas,this.ctx=l.context,this.ctx.save(),this.ctx.transform.apply(this.ctx,this.compositeCtx.mozCurrentTransform)}this.ctx.save(),h(this.ctx),r&&this.ctx.transform.apply(this.ctx,r),this.ctx.transform.apply(this.ctx,i.transform),this.baseTransform=this.ctx.mozCurrentTransform.slice(),this.imageLayer&&this.imageLayer.beginLayout()},executeOperatorList:function t(e,r,i,n){var a=e.argsArray,s=e.fnArray,c=r||0,l=a.length;if(l===c)return c;for(var h=l-c>10&&"function"==typeof i,u=h?Date.now()+15:0,f=0,d=this.commonObjs,p=this.objs,g;;){if(void 0!==n&&c===n.nextBreakPoint)return n.breakIt(c,i),c;if((g=s[c])!==o.OPS.dependency)this[g].apply(this,a[c]);else for(var v=a[c],m=0,b=v.length;m<b;m++){var y=v[m],_="g"===y[0]&&"_"===y[1],w=_?d:p;if(!w.isResolved(y))return w.get(y,i),c}if(++c===l)return c;if(h&&++f>10){if(Date.now()>u)return i(),c;f=0}}},endDrawing:function t(){null!==this.current.activeSMask&&this.endSMaskGroup(),this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null),this.cachedCanvases.clear(),s.WebGLUtils.clear(),this.imageLayer&&this.imageLayer.endLayout()},setLineWidth:function t(e){this.current.lineWidth=e,this.ctx.lineWidth=e},setLineCap:function t(e){this.ctx.lineCap=S[e]},setLineJoin:function t(e){this.ctx.lineJoin=x[e]},setMiterLimit:function t(e){this.ctx.miterLimit=e},setDash:function t(e,r){var i=this.ctx;void 0!==i.setLineDash&&(i.setLineDash(e),i.lineDashOffset=r)},setRenderingIntent:function t(e){},setFlatness:function t(e){},setGState:function t(e){for(var r=0,i=e.length;r<i;r++){var n=e[r],o=n[0],a=n[1];switch(o){case"LW":this.setLineWidth(a);break;case"LC":this.setLineCap(a);break;case"LJ":this.setLineJoin(a);break;case"ML":this.setMiterLimit(a);break;case"D":this.setDash(a[0],a[1]);break;case"RI":this.setRenderingIntent(a);break;case"FL":this.setFlatness(a);break;case"Font":this.setFont(a[0],a[1]);break;case"CA":this.current.strokeAlpha=n[1];break;case"ca":this.current.fillAlpha=n[1],this.ctx.globalAlpha=n[1];break;case"BM":this.ctx.globalCompositeOperation=a;break;case"SMask":this.current.activeSMask&&(this.stateStack.length>0&&this.stateStack[this.stateStack.length-1].activeSMask===this.current.activeSMask?this.suspendSMaskGroup():this.endSMaskGroup()),this.current.activeSMask=a?this.tempSMask:null,this.current.activeSMask&&this.beginSMaskGroup(),this.tempSMask=null}}},beginSMaskGroup:function t(){var e=this.current.activeSMask,r=e.canvas.width,i=e.canvas.height,n="smaskGroupAt"+this.groupLevel,o=this.cachedCanvases.getCanvas(n,r,i,!0),a=this.ctx,s=a.mozCurrentTransform;this.ctx.save();var c=o.context;c.scale(1/e.scaleX,1/e.scaleY),c.translate(-e.offsetX,-e.offsetY),c.transform.apply(c,s),e.startTransformInverse=c.mozCurrentTransformInverse,l(a,c),this.ctx=c,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(a),this.groupLevel++},suspendSMaskGroup:function t(){var e=this.ctx;this.groupLevel--,this.ctx=this.groupStack.pop(),y(this.ctx,this.current.activeSMask,e),this.ctx.restore(),this.ctx.save(),l(e,this.ctx),this.current.resumeSMaskCtx=e;var r=o.Util.transform(this.current.activeSMask.startTransformInverse,e.mozCurrentTransform);this.ctx.transform.apply(this.ctx,r),e.save(),e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,e.canvas.width,e.canvas.height),e.restore()},resumeSMaskGroup:function t(){var e=this.current.resumeSMaskCtx,r=this.ctx;this.ctx=e,this.groupStack.push(r),this.groupLevel++},endSMaskGroup:function t(){var e=this.ctx;this.groupLevel--,this.ctx=this.groupStack.pop(),y(this.ctx,this.current.activeSMask,e),this.ctx.restore(),l(e,this.ctx);var r=o.Util.transform(this.current.activeSMask.startTransformInverse,e.mozCurrentTransform);this.ctx.transform.apply(this.ctx,r)},save:function t(){this.ctx.save();var e=this.current;this.stateStack.push(e),this.current=e.clone(),this.current.resumeSMaskCtx=null},restore:function t(){this.current.resumeSMaskCtx&&this.resumeSMaskGroup(),null===this.current.activeSMask||0!==this.stateStack.length&&this.stateStack[this.stateStack.length-1].activeSMask===this.current.activeSMask||this.endSMaskGroup(),0!==this.stateStack.length&&(this.current=this.stateStack.pop(),this.ctx.restore(),this.pendingClip=null,this.cachedGetSinglePixelWidth=null)},transform:function t(e,r,i,n,o,a){this.ctx.transform(e,r,i,n,o,a),this.cachedGetSinglePixelWidth=null},constructPath:function t(e,r){for(var i=this.ctx,n=this.current,a=n.x,s=n.y,c=0,l=0,h=e.length;c<h;c++)switch(0|e[c]){case o.OPS.rectangle:a=r[l++],s=r[l++];var u=r[l++],f=r[l++];0===u&&(u=this.getSinglePixelWidth()),0===f&&(f=this.getSinglePixelWidth());var d=a+u,p=s+f;this.ctx.moveTo(a,s),this.ctx.lineTo(d,s),this.ctx.lineTo(d,p),this.ctx.lineTo(a,p),this.ctx.lineTo(a,s),this.ctx.closePath();break;case o.OPS.moveTo:a=r[l++],s=r[l++],i.moveTo(a,s);break;case o.OPS.lineTo:a=r[l++],s=r[l++],i.lineTo(a,s);break;case o.OPS.curveTo:a=r[l+4],s=r[l+5],i.bezierCurveTo(r[l],r[l+1],r[l+2],r[l+3],a,s),l+=6;break;case o.OPS.curveTo2:i.bezierCurveTo(a,s,r[l],r[l+1],r[l+2],r[l+3]),a=r[l+2],s=r[l+3],l+=4;break;case o.OPS.curveTo3:a=r[l+2],s=r[l+3],i.bezierCurveTo(r[l],r[l+1],a,s,a,s),l+=4;break;case o.OPS.closePath:i.closePath()}n.setCurrentPoint(a,s)},closePath:function t(){this.ctx.closePath()},stroke:function t(e){e=void 0===e||e;var r=this.ctx,i=this.current.strokeColor;r.lineWidth=Math.max(.65*this.getSinglePixelWidth(),this.current.lineWidth),r.globalAlpha=this.current.strokeAlpha,i&&i.hasOwnProperty("type")&&"Pattern"===i.type?(r.save(),r.strokeStyle=i.getPattern(r,this),r.stroke(),r.restore()):r.stroke(),e&&this.consumePath(),r.globalAlpha=this.current.fillAlpha},closeStroke:function t(){this.closePath(),this.stroke()},fill:function t(e){e=void 0===e||e;var r=this.ctx,i=this.current.fillColor,n=this.current.patternFill,o=!1;n&&(r.save(),this.baseTransform&&r.setTransform.apply(r,this.baseTransform),r.fillStyle=i.getPattern(r,this),o=!0),this.pendingEOFill?(r.fill("evenodd"),this.pendingEOFill=!1):r.fill(),o&&r.restore(),e&&this.consumePath()},eoFill:function t(){this.pendingEOFill=!0,this.fill()},fillStroke:function t(){this.fill(!1),this.stroke(!1),this.consumePath()},eoFillStroke:function t(){this.pendingEOFill=!0,this.fillStroke()},closeFillStroke:function t(){this.closePath(),this.fillStroke()},closeEOFillStroke:function t(){this.pendingEOFill=!0,this.closePath(),this.fillStroke()},endPath:function t(){this.consumePath()},clip:function t(){this.pendingClip=C},eoClip:function t(){this.pendingClip=A},beginText:function t(){this.current.textMatrix=o.IDENTITY_MATRIX,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0},endText:function t(){var e=this.pendingTextPaths,r=this.ctx;if(void 0===e)return void r.beginPath();r.save(),r.beginPath();for(var i=0;i<e.length;i++){var n=e[i];r.setTransform.apply(r,n.transform),r.translate(n.x,n.y),n.addToPath(r,n.fontSize)}r.restore(),r.clip(),r.beginPath(),delete this.pendingTextPaths},setCharSpacing:function t(e){this.current.charSpacing=e},setWordSpacing:function t(e){this.current.wordSpacing=e},setHScale:function t(e){this.current.textHScale=e/100},setLeading:function t(e){this.current.leading=-e},setFont:function t(e,r){var i=this.commonObjs.get(e),n=this.current;if(!i)throw new Error("Can't find font for "+e);if(n.fontMatrix=i.fontMatrix?i.fontMatrix:o.FONT_IDENTITY_MATRIX,0!==n.fontMatrix[0]&&0!==n.fontMatrix[3]||(0,o.warn)("Invalid font matrix for font "+e),r<0?(r=-r,n.fontDirection=-1):n.fontDirection=1,this.current.font=i,this.current.fontSize=r,!i.isType3Font){var a=i.loadedName||"sans-serif",s=i.black?"900":i.bold?"bold":"normal",c=i.italic?"italic":"normal",l='"'+a+'", '+i.fallbackName,h=r<16?16:r>100?100:r;this.current.fontSizeScale=r/h;var u=c+" "+s+" "+h+"px "+l;this.ctx.font=u}},setTextRenderingMode:function t(e){this.current.textRenderingMode=e},setTextRise:function t(e){this.current.textRise=e},moveText:function t(e,r){this.current.x=this.current.lineX+=e,this.current.y=this.current.lineY+=r},setLeadingMoveText:function t(e,r){this.setLeading(-r),this.moveText(e,r)},setTextMatrix:function t(e,r,i,n,o,a){this.current.textMatrix=[e,r,i,n,o,a],this.current.textMatrixScale=Math.sqrt(e*e+r*r),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0},nextLine:function t(){this.moveText(0,this.current.leading)},paintChar:function t(e,r,i){var n=this.ctx,a=this.current,s=a.font,c=a.textRenderingMode,l=a.fontSize/a.fontSizeScale,h=c&o.TextRenderingMode.FILL_STROKE_MASK,u=!!(c&o.TextRenderingMode.ADD_TO_PATH_FLAG),f;if((s.disableFontFace||u)&&(f=s.getPathGenerator(this.commonObjs,e)),s.disableFontFace?(n.save(),n.translate(r,i),n.beginPath(),f(n,l),h!==o.TextRenderingMode.FILL&&h!==o.TextRenderingMode.FILL_STROKE||n.fill(),h!==o.TextRenderingMode.STROKE&&h!==o.TextRenderingMode.FILL_STROKE||n.stroke(),n.restore()):(h!==o.TextRenderingMode.FILL&&h!==o.TextRenderingMode.FILL_STROKE||n.fillText(e,r,i),h!==o.TextRenderingMode.STROKE&&h!==o.TextRenderingMode.FILL_STROKE||n.strokeText(e,r,i)),u){(this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:n.mozCurrentTransform,x:r,y:i,fontSize:l,addToPath:f})}},get isFontSubpixelAAEnabled(){var t=this.canvasFactory.create(10,10).context;t.scale(1.5,1),t.fillText("I",0,10);for(var e=t.getImageData(0,0,10,10).data,r=!1,i=3;i<e.length;i+=4)if(e[i]>0&&e[i]<255){r=!0;break}return(0,o.shadow)(this,"isFontSubpixelAAEnabled",r)},showText:function t(e){var r=this.current,i=r.font;if(i.isType3Font)return this.showType3Text(e);var n=r.fontSize;if(0!==n){var a=this.ctx,s=r.fontSizeScale,c=r.charSpacing,l=r.wordSpacing,h=r.fontDirection,u=r.textHScale*h,f=e.length,d=i.vertical,p=d?1:-1,g=i.defaultVMetrics,v=n*r.fontMatrix[0],m=r.textRenderingMode===o.TextRenderingMode.FILL&&!i.disableFontFace;a.save(),a.transform.apply(a,r.textMatrix),a.translate(r.x,r.y+r.textRise),r.patternFill&&(a.fillStyle=r.fillColor.getPattern(a,this)),h>0?a.scale(u,-1):a.scale(u,1);var b=r.lineWidth,y=r.textMatrixScale;if(0===y||0===b){var _=r.textRenderingMode&o.TextRenderingMode.FILL_STROKE_MASK;_!==o.TextRenderingMode.STROKE&&_!==o.TextRenderingMode.FILL_STROKE||(this.cachedGetSinglePixelWidth=null,b=.65*this.getSinglePixelWidth())}else b/=y;1!==s&&(a.scale(s,s),b/=s),a.lineWidth=b;var w=0,S;for(S=0;S<f;++S){var x=e[S];if((0,o.isNum)(x))w+=p*x*n/1e3;else{var C=!1,A=(x.isSpace?l:0)+c,T=x.fontChar,k=x.accent,P,E,O,R,L=x.width;if(d){var D,I,j;D=x.vmetric||g,I=x.vmetric?D[1]:.5*L,I=-I*v,j=D[2]*v,L=D?-D[0]:L,P=I/s,E=(w+j)/s}else P=w/s,E=0;if(i.remeasure&&L>0){var M=1e3*a.measureText(T).width/n*s;if(L<M&&this.isFontSubpixelAAEnabled){var F=L/M;C=!0,a.save(),a.scale(F,1),P/=F}else L!==M&&(P+=(L-M)/2e3*n/s)}(x.isInFont||i.missingFile)&&(m&&!k?a.fillText(T,P,E):(this.paintChar(T,P,E),k&&(O=P+k.offset.x/s,R=E-k.offset.y/s,this.paintChar(k.fontChar,O,R))));w+=L*v+A*h,C&&a.restore()}}d?r.y-=w*u:r.x+=w*u,a.restore()}},showType3Text:function t(e){var r=this.ctx,i=this.current,n=i.font,a=i.fontSize,s=i.fontDirection,c=n.vertical?1:-1,l=i.charSpacing,h=i.wordSpacing,u=i.textHScale*s,f=i.fontMatrix||o.FONT_IDENTITY_MATRIX,d=e.length,p=i.textRenderingMode===o.TextRenderingMode.INVISIBLE,g,v,m,b;if(!p&&0!==a){for(this.cachedGetSinglePixelWidth=null,r.save(),r.transform.apply(r,i.textMatrix),r.translate(i.x,i.y),r.scale(u,s),g=0;g<d;++g)if(v=e[g],(0,o.isNum)(v))b=c*v*a/1e3,this.ctx.translate(b,0),i.x+=b*u;else{var y=(v.isSpace?h:0)+l,_=n.charProcOperatorList[v.operatorListId];if(_){this.processingType3=v,this.save(),r.scale(a,a),r.transform.apply(r,f),this.executeOperatorList(_),this.restore();var w=o.Util.applyTransform([v.width,0],f);m=w[0]*a+y,r.translate(m,0),i.x+=m*u}else(0,o.warn)('Type3 character "'+v.operatorListId+'" is not available.')}r.restore(),this.processingType3=null}},setCharWidth:function t(e,r){},setCharWidthAndBounds:function t(e,r,i,n,o,a){this.ctx.rect(i,n,o-i,a-n),this.clip(),this.endPath()},getColorN_Pattern:function t(r){var i=this,n;if("TilingPattern"===r[0]){var o=r[1],s=this.baseTransform||this.ctx.mozCurrentTransform.slice(),c={createCanvasGraphics:function t(r){return new e(r,i.commonObjs,i.objs,i.canvasFactory)}};n=new a.TilingPattern(r,o,this.ctx,c,s)}else n=(0,a.getShadingPatternFromIR)(r);return n},setStrokeColorN:function t(){this.current.strokeColor=this.getColorN_Pattern(arguments)},setFillColorN:function t(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0},setStrokeRGBColor:function t(e,r,i){var n=o.Util.makeCssRgb(e,r,i);this.ctx.strokeStyle=n,this.current.strokeColor=n},setFillRGBColor:function t(e,r,i){var n=o.Util.makeCssRgb(e,r,i);this.ctx.fillStyle=n,this.current.fillColor=n,this.current.patternFill=!1},shadingFill:function t(e){var r=this.ctx;this.save();var i=(0,a.getShadingPatternFromIR)(e);r.fillStyle=i.getPattern(r,this,!0);var n=r.mozCurrentTransformInverse;if(n){var s=r.canvas,c=s.width,l=s.height,h=o.Util.applyTransform([0,0],n),u=o.Util.applyTransform([0,l],n),f=o.Util.applyTransform([c,0],n),d=o.Util.applyTransform([c,l],n),p=Math.min(h[0],u[0],f[0],d[0]),g=Math.min(h[1],u[1],f[1],d[1]),v=Math.max(h[0],u[0],f[0],d[0]),m=Math.max(h[1],u[1],f[1],d[1]);this.ctx.fillRect(p,g,v-p,m-g)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.restore()},beginInlineImage:function t(){throw new Error("Should not call beginInlineImage")},beginImageData:function t(){throw new Error("Should not call beginImageData")},paintFormXObjectBegin:function t(e,r){if(this.save(),this.baseTransformStack.push(this.baseTransform),(0,o.isArray)(e)&&6===e.length&&this.transform.apply(this,e),this.baseTransform=this.ctx.mozCurrentTransform,(0,o.isArray)(r)&&4===r.length){var i=r[2]-r[0],n=r[3]-r[1];this.ctx.rect(r[0],r[1],i,n),this.clip(),this.endPath()}},paintFormXObjectEnd:function t(){this.restore(),this.baseTransform=this.baseTransformStack.pop()},beginGroup:function t(e){this.save();var r=this.ctx;e.isolated||(0,o.info)("TODO: Support non-isolated groups."),e.knockout&&(0,o.warn)("Knockout groups not supported.");var i=r.mozCurrentTransform;if(e.matrix&&r.transform.apply(r,e.matrix),!e.bbox)throw new Error("Bounding box is required.");var n=o.Util.getAxialAlignedBoundingBox(e.bbox,r.mozCurrentTransform),a=[0,0,r.canvas.width,r.canvas.height];n=o.Util.intersect(n,a)||[0,0,0,0];var s=Math.floor(n[0]),c=Math.floor(n[1]),h=Math.max(Math.ceil(n[2])-s,1),u=Math.max(Math.ceil(n[3])-c,1),f=1,d=1;h>4096&&(f=h/4096,h=4096),u>4096&&(d=u/4096,u=4096);var p="groupAt"+this.groupLevel;e.smask&&(p+="_smask_"+this.smaskCounter++%2);var g=this.cachedCanvases.getCanvas(p,h,u,!0),v=g.context;v.scale(1/f,1/d),v.translate(-s,-c),v.transform.apply(v,i),e.smask?this.smaskStack.push({canvas:g.canvas,context:v,offsetX:s,offsetY:c,scaleX:f,scaleY:d,subtype:e.smask.subtype,backdrop:e.smask.backdrop,transferMap:e.smask.transferMap||null,startTransformInverse:null}):(r.setTransform(1,0,0,1,0,0),r.translate(s,c),r.scale(f,d)),l(r,v),this.ctx=v,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(r),this.groupLevel++,this.current.activeSMask=null},endGroup:function t(e){this.groupLevel--;var r=this.ctx;this.ctx=this.groupStack.pop(),void 0!==this.ctx.imageSmoothingEnabled?this.ctx.imageSmoothingEnabled=!1:this.ctx.mozImageSmoothingEnabled=!1,e.smask?this.tempSMask=this.smaskStack.pop():this.ctx.drawImage(r.canvas,0,0),this.restore()},beginAnnotations:function t(){this.save(),this.baseTransform&&this.ctx.setTransform.apply(this.ctx,this.baseTransform)},endAnnotations:function t(){this.restore()},beginAnnotation:function t(e,r,i){if(this.save(),h(this.ctx),this.current=new m,(0,o.isArray)(e)&&4===e.length){var n=e[2]-e[0],a=e[3]-e[1];this.ctx.rect(e[0],e[1],n,a),this.clip(),this.endPath()}this.transform.apply(this,r),this.transform.apply(this,i)},endAnnotation:function t(){this.restore()},paintJpegXObject:function t(e,r,i){var n=this.objs.get(e);if(!n)return void(0,o.warn)("Dependent image isn't ready yet");this.save();var a=this.ctx;if(a.scale(1/r,-1/i),a.drawImage(n,0,0,n.width,n.height,0,-i,r,i),this.imageLayer){var s=a.mozCurrentTransformInverse,c=this.getCanvasPosition(0,0);this.imageLayer.appendImage({objId:e,left:c[0],top:c[1],width:r/s[0],height:i/s[3]})}this.restore()},paintImageMaskXObject:function t(e){var r=this.ctx,i=e.width,o=e.height,a=this.current.fillColor,s=this.current.patternFill,l=this.processingType3;if(l&&void 0===l.compiled&&(l.compiled=i<=1e3&&o<=1e3?n({data:e.data,width:i,height:o}):null),l&&l.compiled)return void l.compiled(r);var h=this.cachedCanvases.getCanvas("maskCanvas",i,o),u=h.context;u.save(),c(u,e),u.globalCompositeOperation="source-in",u.fillStyle=s?a.getPattern(u,this):a,u.fillRect(0,0,i,o),u.restore(),this.paintInlineImageXObject(h.canvas)},paintImageMaskXObjectRepeat:function t(e,r,i,n){var o=e.width,a=e.height,s=this.current.fillColor,l=this.current.patternFill,h=this.cachedCanvases.getCanvas("maskCanvas",o,a),u=h.context;u.save(),c(u,e),u.globalCompositeOperation="source-in",u.fillStyle=l?s.getPattern(u,this):s,u.fillRect(0,0,o,a),u.restore();for(var f=this.ctx,d=0,p=n.length;d<p;d+=2)f.save(),f.transform(r,0,0,i,n[d],n[d+1]),f.scale(1,-1),f.drawImage(h.canvas,0,0,o,a,0,-1,1,1),f.restore()},paintImageMaskXObjectGroup:function t(e){for(var r=this.ctx,i=this.current.fillColor,n=this.current.patternFill,o=0,a=e.length;o<a;o++){var s=e[o],l=s.width,h=s.height,u=this.cachedCanvases.getCanvas("maskCanvas",l,h),f=u.context;f.save(),c(f,s),f.globalCompositeOperation="source-in",f.fillStyle=n?i.getPattern(f,this):i,f.fillRect(0,0,l,h),f.restore(),r.save(),r.transform.apply(r,s.transform),r.scale(1,-1),r.drawImage(u.canvas,0,0,l,h,0,-1,1,1),r.restore()}},paintImageXObject:function t(e){var r=this.objs.get(e);if(!r)return void(0,o.warn)("Dependent image isn't ready yet");this.paintInlineImageXObject(r)},paintImageXObjectRepeat:function t(e,r,i,n){var a=this.objs.get(e);if(!a)return void(0,o.warn)("Dependent image isn't ready yet");for(var s=a.width,c=a.height,l=[],h=0,u=n.length;h<u;h+=2)l.push({transform:[r,0,0,i,n[h],n[h+1]],x:0,y:0,w:s,h:c});this.paintInlineImageXObjectGroup(a,l)},paintInlineImageXObject:function t(e){var i=e.width,n=e.height,o=this.ctx;this.save(),o.scale(1/i,-1/n);var a=o.mozCurrentTransformInverse,s=a[0],c=a[1],l=Math.max(Math.sqrt(s*s+c*c),1),h=a[2],u=a[3],f=Math.max(Math.sqrt(h*h+u*u),1),d,p;if(e instanceof HTMLElement||!e.data)d=e;else{p=this.cachedCanvases.getCanvas("inlineImage",i,n);var g=p.context;r(g,e),d=p.canvas}for(var v=i,m=n,b="prescale1";l>2&&v>1||f>2&&m>1;){var y=v,_=m;l>2&&v>1&&(y=Math.ceil(v/2),l/=v/y),f>2&&m>1&&(_=Math.ceil(m/2),f/=m/_),p=this.cachedCanvases.getCanvas(b,y,_),g=p.context,g.clearRect(0,0,y,_),g.drawImage(d,0,0,v,m,0,0,y,_),d=p.canvas,v=y,m=_,b="prescale1"===b?"prescale2":"prescale1"}if(o.drawImage(d,0,0,v,m,0,-n,i,n),this.imageLayer){var w=this.getCanvasPosition(0,-n);this.imageLayer.appendImage({imgData:e,left:w[0],top:w[1],width:i/a[0],height:n/a[3]})}this.restore()},paintInlineImageXObjectGroup:function t(e,i){var n=this.ctx,o=e.width,a=e.height,s=this.cachedCanvases.getCanvas("inlineImage",o,a);r(s.context,e);for(var c=0,l=i.length;c<l;c++){var h=i[c];if(n.save(),n.transform.apply(n,h.transform),n.scale(1,-1),n.drawImage(s.canvas,h.x,h.y,h.w,h.h,0,-1,1,1),this.imageLayer){var u=this.getCanvasPosition(h.x,h.y);this.imageLayer.appendImage({imgData:e,left:u[0],top:u[1],width:o,height:a})}n.restore()}},paintSolidColorImageMask:function t(){this.ctx.fillRect(0,0,1,1)},paintXObject:function t(){(0,o.warn)("Unsupported 'paintXObject' command.")},markPoint:function t(e){},markPointProps:function t(e,r){},beginMarkedContent:function t(e){},beginMarkedContentProps:function t(e,r){},endMarkedContent:function t(){},beginCompat:function t(){},endCompat:function t(){},consumePath:function t(){var e=this.ctx;this.pendingClip&&(this.pendingClip===A?e.clip("evenodd"):e.clip(),this.pendingClip=null),e.beginPath()},getSinglePixelWidth:function t(e){if(null===this.cachedGetSinglePixelWidth){this.ctx.save();var r=this.ctx.mozCurrentTransformInverse;this.ctx.restore(),this.cachedGetSinglePixelWidth=Math.sqrt(Math.max(r[0]*r[0]+r[1]*r[1],r[2]*r[2]+r[3]*r[3]))}return this.cachedGetSinglePixelWidth},getCanvasPosition:function t(e,r){var i=this.ctx.mozCurrentTransform;return[i[0]*e+i[2]*r+i[4],i[1]*e+i[3]*r+i[5]]}};for(var T in o.OPS)e.prototype[o.OPS[T]]=e.prototype[T];return e}();e.CanvasGraphics=b},function(t,e,r){"use strict";function i(t){this.docId=t,this.styleElement=null,this.nativeFontFaces=[],this.loadTestFontId=0,this.loadingContext={requests:[],nextRequestId:0}}Object.defineProperty(e,"__esModule",{value:!0}),e.FontLoader=e.FontFaceObject=void 0;var n=r(0);i.prototype={insertRule:function t(e){var r=this.styleElement;r||(r=this.styleElement=document.createElement("style"),r.id="PDFJS_FONT_STYLE_TAG_"+this.docId,document.documentElement.getElementsByTagName("head")[0].appendChild(r));var i=r.sheet;i.insertRule(e,i.cssRules.length)},clear:function t(){this.styleElement&&(this.styleElement.remove(),this.styleElement=null),this.nativeFontFaces.forEach(function(t){document.fonts.delete(t)}),this.nativeFontFaces.length=0}};var o=function t(){return atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==")};Object.defineProperty(i.prototype,"loadTestFont",{get:function t(){return(0,n.shadow)(this,"loadTestFont",o())},configurable:!0}),i.prototype.addNativeFontFace=function t(e){this.nativeFontFaces.push(e),document.fonts.add(e)},i.prototype.bind=function t(e,r){for(var o=[],a=[],s=[],c=function t(e){return e.loaded.catch(function(t){(0,n.warn)('Failed to load font "'+e.family+'": '+t)})},l=i.isFontLoadingAPISupported&&!i.isSyncFontLoadingSupported,h=0,u=e.length;h<u;h++){var f=e[h];if(!f.attached&&!1!==f.loading)if(f.attached=!0,l){var d=f.createNativeFontFace();d&&(this.addNativeFontFace(d),s.push(c(d)))}else{var p=f.createFontFaceRule();p&&(this.insertRule(p),o.push(p),a.push(f))}}var g=this.queueLoadingCallback(r);l?Promise.all(s).then(function(){g.complete()}):o.length>0&&!i.isSyncFontLoadingSupported?this.prepareFontLoadEvent(o,a,g):g.complete()},i.prototype.queueLoadingCallback=function t(e){function r(){for((0,n.assert)(!a.end,"completeRequest() cannot be called twice"),a.end=Date.now();i.requests.length>0&&i.requests[0].end;){var t=i.requests.shift();setTimeout(t.callback,0)}}var i=this.loadingContext,o="pdfjs-font-loading-"+i.nextRequestId++,a={id:o,complete:r,callback:e,started:Date.now()};return i.requests.push(a),a},i.prototype.prepareFontLoadEvent=function t(e,r,i){function o(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function a(t,e,r,i){return t.substr(0,e)+i+t.substr(e+r)}function s(t,e){return++f>30?((0,n.warn)("Load test font never loaded."),void e()):(u.font="30px "+t,u.fillText(".",0,20),u.getImageData(0,0,1,1).data[3]>0?void e():void setTimeout(s.bind(null,t,e)))}var c,l,h=document.createElement("canvas");h.width=1,h.height=1;var u=h.getContext("2d"),f=0,d="lt"+Date.now()+this.loadTestFontId++,p=this.loadTestFont,g=976;p=a(p,976,d.length,d);var v=16,m=1482184792,b=o(p,16);for(c=0,l=d.length-3;c<l;c+=4)b=b-1482184792+o(d,c)|0;c<d.length&&(b=b-1482184792+o(d+"XXX",c)|0),p=a(p,16,4,(0,n.string32)(b));var y="url(data:font/opentype;base64,"+btoa(p)+");",_='@font-face { font-family:"'+d+'";src:'+y+"}";this.insertRule(_);var w=[];for(c=0,l=r.length;c<l;c++)w.push(r[c].loadedName);w.push(d);var S=document.createElement("div");for(S.setAttribute("style","visibility: hidden;width: 10px; height: 10px;position: absolute; top: 0px; left: 0px;"),c=0,l=w.length;c<l;++c){var x=document.createElement("span");x.textContent="Hi",x.style.fontFamily=w[c],S.appendChild(x)}document.body.appendChild(S),s(d,function(){document.body.removeChild(S),i.complete()})},i.isFontLoadingAPISupported="undefined"!=typeof document&&!!document.fonts;var a=function t(){if("undefined"==typeof navigator)return!0;var e=!1,r=/Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);return r&&r[1]>=14&&(e=!0),e};Object.defineProperty(i,"isSyncFontLoadingSupported",{get:function t(){return(0,n.shadow)(i,"isSyncFontLoadingSupported",a())},enumerable:!0,configurable:!0});var s={get value(){return(0,n.shadow)(this,"value",(0,n.isEvalSupported)())}},c=function t(){function e(t,e){this.compiledGlyphs=Object.create(null);for(var r in t)this[r]=t[r];this.options=e}return e.prototype={createNativeFontFace:function t(){if(!this.data)return null;if(this.options.disableFontFace)return this.disableFontFace=!0,null;var e=new FontFace(this.loadedName,this.data,{});return this.options.fontRegistry&&this.options.fontRegistry.registerFont(this),e},createFontFaceRule:function t(){if(!this.data)return null;if(this.options.disableFontFace)return this.disableFontFace=!0,null;var e=(0,n.bytesToString)(new Uint8Array(this.data)),r=this.loadedName,i="url(data:"+this.mimetype+";base64,"+btoa(e)+");",o='@font-face { font-family:"'+r+'";src:'+i+"}";return this.options.fontRegistry&&this.options.fontRegistry.registerFont(this,i),o},getPathGenerator:function t(e,r){if(!(r in this.compiledGlyphs)){var i=e.get(this.loadedName+"_path_"+r),n,o,a;if(this.options.isEvalSupported&&s.value){var c,l="";for(o=0,a=i.length;o<a;o++)n=i[o],c=void 0!==n.args?n.args.join(","):"",l+="c."+n.cmd+"("+c+");\n";this.compiledGlyphs[r]=new Function("c","size",l)}else this.compiledGlyphs[r]=function(t,e){for(o=0,a=i.length;o<a;o++)n=i[o],"scale"===n.cmd&&(n.args=[e,-e]),t[n.cmd].apply(t,n.args)}}return this.compiledGlyphs[r]}},e}();e.FontFaceObject=c,e.FontLoader=i},function(t,e,r){"use strict";function i(t){var e=a[t[0]];if(!e)throw new Error("Unknown IR type: "+t[0]);return e.fromIR(t)}Object.defineProperty(e,"__esModule",{value:!0}),e.TilingPattern=e.getShadingPatternFromIR=void 0;var n=r(0),o=r(7),a={};a.RadialAxial={fromIR:function t(e){var r=e[1],i=e[2],n=e[3],o=e[4],a=e[5],s=e[6];return{type:"Pattern",getPattern:function t(e){var c;"axial"===r?c=e.createLinearGradient(n[0],n[1],o[0],o[1]):"radial"===r&&(c=e.createRadialGradient(n[0],n[1],a,o[0],o[1],s));for(var l=0,h=i.length;l<h;++l){var u=i[l];c.addColorStop(u[0],u[1])}return c}}}};var s=function t(){function e(t,e,r,i,n,o,a,s){var c=e.coords,l=e.colors,h=t.data,u=4*t.width,f;c[r+1]>c[i+1]&&(f=r,r=i,i=f,f=o,o=a,a=f),c[i+1]>c[n+1]&&(f=i,i=n,n=f,f=a,a=s,s=f),c[r+1]>c[i+1]&&(f=r,r=i,i=f,f=o,o=a,a=f);var d=(c[r]+e.offsetX)*e.scaleX,p=(c[r+1]+e.offsetY)*e.scaleY,g=(c[i]+e.offsetX)*e.scaleX,v=(c[i+1]+e.offsetY)*e.scaleY,m=(c[n]+e.offsetX)*e.scaleX,b=(c[n+1]+e.offsetY)*e.scaleY;if(!(p>=b))for(var y=l[o],_=l[o+1],w=l[o+2],S=l[a],x=l[a+1],C=l[a+2],A=l[s],T=l[s+1],k=l[s+2],P=Math.round(p),E=Math.round(b),O,R,L,D,I,j,M,F,N,B=P;B<=E;B++){B<v?(N=B<p?0:p===v?1:(p-B)/(p-v),O=d-(d-g)*N,R=y-(y-S)*N,L=_-(_-x)*N,D=w-(w-C)*N):(N=B>b?1:v===b?0:(v-B)/(v-b),O=g-(g-m)*N,R=S-(S-A)*N,L=x-(x-T)*N,D=C-(C-k)*N),N=B<p?0:B>b?1:(p-B)/(p-b),I=d-(d-m)*N,j=y-(y-A)*N,M=_-(_-T)*N,F=w-(w-k)*N;for(var U=Math.round(Math.min(O,I)),z=Math.round(Math.max(O,I)),W=u*B+4*U,q=U;q<=z;q++)N=(O-q)/(O-I),N=N<0?0:N>1?1:N,h[W++]=R-(R-j)*N|0,h[W++]=L-(L-M)*N|0,h[W++]=D-(D-F)*N|0,h[W++]=255}}function r(t,r,i){var n=r.coords,o=r.colors,a,s;switch(r.type){case"lattice":var c=r.verticesPerRow,l=Math.floor(n.length/c)-1,h=c-1;for(a=0;a<l;a++)for(var u=a*c,f=0;f<h;f++,u++)e(t,i,n[u],n[u+1],n[u+c],o[u],o[u+1],o[u+c]),e(t,i,n[u+c+1],n[u+1],n[u+c],o[u+c+1],o[u+1],o[u+c]);break;case"triangles":for(a=0,s=n.length;a<s;a+=3)e(t,i,n[a],n[a+1],n[a+2],o[a],o[a+1],o[a+2]);break;default:throw new Error("illegal figure")}}function i(t,e,i,n,a,s,c){var l=1.1,h=3e3,u=2,f=Math.floor(t[0]),d=Math.floor(t[1]),p=Math.ceil(t[2])-f,g=Math.ceil(t[3])-d,v=Math.min(Math.ceil(Math.abs(p*e[0]*1.1)),3e3),m=Math.min(Math.ceil(Math.abs(g*e[1]*1.1)),3e3),b=p/v,y=g/m,_={coords:i,colors:n,offsetX:-f,offsetY:-d,scaleX:1/b,scaleY:1/y},w=v+4,S=m+4,x,C,A,T;if(o.WebGLUtils.isEnabled)x=o.WebGLUtils.drawFigures(v,m,s,a,_),C=c.getCanvas("mesh",w,S,!1),C.context.drawImage(x,2,2),x=C.canvas;else{C=c.getCanvas("mesh",w,S,!1);var k=C.context,P=k.createImageData(v,m);if(s){var E=P.data;for(A=0,T=E.length;A<T;A+=4)E[A]=s[0],E[A+1]=s[1],E[A+2]=s[2],E[A+3]=255}for(A=0;A<a.length;A++)r(P,a[A],_);k.putImageData(P,2,2),x=C.canvas}return{canvas:x,offsetX:f-2*b,offsetY:d-2*y,scaleX:b,scaleY:y}}return i}();a.Mesh={fromIR:function t(e){var r=e[2],i=e[3],o=e[4],a=e[5],c=e[6],l=e[8];return{type:"Pattern",getPattern:function t(e,h,u){var f;if(u)f=n.Util.singularValueDecompose2dScale(e.mozCurrentTransform);else if(f=n.Util.singularValueDecompose2dScale(h.baseTransform),c){var d=n.Util.singularValueDecompose2dScale(c);f=[f[0]*d[0],f[1]*d[1]]}var p=s(a,f,r,i,o,u?null:l,h.cachedCanvases);return u||(e.setTransform.apply(e,h.baseTransform),c&&e.transform.apply(e,c)),e.translate(p.offsetX,p.offsetY),e.scale(p.scaleX,p.scaleY),e.createPattern(p.canvas,"no-repeat")}}}},a.Dummy={fromIR:function t(){return{type:"Pattern",getPattern:function t(){return"hotpink"}}}};var c=function t(){function e(t,e,r,i,n){this.operatorList=t[2],this.matrix=t[3]||[1,0,0,1,0,0],this.bbox=t[4],this.xstep=t[5],this.ystep=t[6],this.paintType=t[7],this.tilingType=t[8],this.color=e,this.canvasGraphicsFactory=i,this.baseTransform=n,this.type="Pattern",this.ctx=r}var r={COLORED:1,UNCOLORED:2},i=3e3;return e.prototype={createPatternCanvas:function t(e){var r=this.operatorList,i=this.bbox,o=this.xstep,a=this.ystep,s=this.paintType,c=this.tilingType,l=this.color,h=this.canvasGraphicsFactory;(0,n.info)("TilingType: "+c);var u=i[0],f=i[1],d=i[2],p=i[3],g=[u,f],v=[u+o,f+a],m=v[0]-g[0],b=v[1]-g[1],y=n.Util.singularValueDecompose2dScale(this.matrix),_=n.Util.singularValueDecompose2dScale(this.baseTransform),w=[y[0]*_[0],y[1]*_[1]];m=Math.min(Math.ceil(Math.abs(m*w[0])),3e3),b=Math.min(Math.ceil(Math.abs(b*w[1])),3e3);var S=e.cachedCanvases.getCanvas("pattern",m,b,!0),x=S.context,C=h.createCanvasGraphics(x);C.groupLevel=e.groupLevel,this.setFillAndStrokeStyleToContext(x,s,l),this.setScale(m,b,o,a),this.transformToScale(C);var A=[1,0,0,1,-g[0],-g[1]];return C.transform.apply(C,A),this.clipBbox(C,i,u,f,d,p),C.executeOperatorList(r),S.canvas},setScale:function t(e,r,i,n){this.scale=[e/i,r/n]},transformToScale:function t(e){var r=this.scale,i=[r[0],0,0,r[1],0,0];e.transform.apply(e,i)},scaleToContext:function t(){var e=this.scale;this.ctx.scale(1/e[0],1/e[1])},clipBbox:function t(e,r,i,o,a,s){if((0,n.isArray)(r)&&4===r.length){var c=a-i,l=s-o;e.ctx.rect(i,o,c,l),e.clip(),e.endPath()}},setFillAndStrokeStyleToContext:function t(e,i,o){switch(i){case r.COLORED:var a=this.ctx;e.fillStyle=a.fillStyle,e.strokeStyle=a.strokeStyle;break;case r.UNCOLORED:var s=n.Util.makeCssRgb(o[0],o[1],o[2]);e.fillStyle=s,e.strokeStyle=s;break;default:throw new n.FormatError("Unsupported paint type: "+i)}},getPattern:function t(e,r){var i=this.createPatternCanvas(r);return e=this.ctx,e.setTransform.apply(e,this.baseTransform),e.transform.apply(e,this.matrix),this.scaleToContext(),e.createPattern(i,"repeat")}},e}();e.getShadingPatternFromIR=i,e.TilingPattern=c},function(t,e,r){"use strict";var i="1.8.575",n="bd8c1211",o=r(0),a=r(8),s=r(3),c=r(5),l=r(2),h=r(1),u=r(4);e.PDFJS=a.PDFJS,e.build=s.build,e.version=s.version,e.getDocument=s.getDocument,e.LoopbackPort=s.LoopbackPort,e.PDFDataRangeTransport=s.PDFDataRangeTransport,e.PDFWorker=s.PDFWorker,e.renderTextLayer=c.renderTextLayer,e.AnnotationLayer=l.AnnotationLayer,e.CustomStyle=h.CustomStyle,e.createPromiseCapability=o.createPromiseCapability,e.PasswordResponses=o.PasswordResponses,e.InvalidPDFException=o.InvalidPDFException,e.MissingPDFException=o.MissingPDFException,e.SVGGraphics=u.SVGGraphics,e.NativeImageDecoding=o.NativeImageDecoding,e.UnexpectedResponseException=o.UnexpectedResponseException,e.OPS=o.OPS,e.UNSUPPORTED_FEATURES=o.UNSUPPORTED_FEATURES,e.isValidUrl=h.isValidUrl,e.createValidAbsoluteUrl=o.createValidAbsoluteUrl,e.createObjectURL=o.createObjectURL,e.removeNullCharacters=o.removeNullCharacters,e.shadow=o.shadow,e.createBlob=o.createBlob,e.RenderingCancelledException=h.RenderingCancelledException,e.getFilenameFromUrl=h.getFilenameFromUrl,e.addLinkAttributes=h.addLinkAttributes,e.StatTimer=o.StatTimer},function(t,r,i){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};if("undefined"==typeof PDFJS||!PDFJS.compatibilityChecked){var o="undefined"!=typeof window&&window.Math===Math?window:void 0!==e&&e.Math===Math?e:"undefined"!=typeof self&&self.Math===Math?self:void 0,a="undefined"!=typeof navigator&&navigator.userAgent||"",s=/Android/.test(a),c=/Android\s[0-2][^\d]/.test(a),l=/Android\s[0-4][^\d]/.test(a),h=a.indexOf("Chrom")>=0,u=/Chrome\/(39|40)\./.test(a),f=a.indexOf("CriOS")>=0,d=a.indexOf("Trident")>=0,p=/\b(iPad|iPhone|iPod)(?=;)/.test(a),g=a.indexOf("Opera")>=0,v=/Safari\//.test(a)&&!/(Chrome\/|Android\s)/.test(a),m="object"===("undefined"==typeof window?"undefined":n(window))&&"object"===("undefined"==typeof document?"undefined":n(document));"undefined"==typeof PDFJS&&(o.PDFJS={}),PDFJS.compatibilityChecked=!0,function t(){function e(t,e){return new c(this.slice(t,e))}function r(t,e){arguments.length<2&&(e=0);for(var r=0,i=t.length;r<i;++r,++e)this[e]=255&t[r]}function i(t,e){this.buffer=t,this.byteLength=t.length,this.length=e,s(this.length)}function a(t){return{get:function e(){var r=this.buffer,i=t<<2;return(r[i]|r[i+1]<<8|r[i+2]<<16|r[i+3]<<24)>>>0},set:function e(r){var i=this.buffer,n=t<<2;i[n]=255&r,i[n+1]=r>>8&255,i[n+2]=r>>16&255,i[n+3]=r>>>24&255}}}function s(t){for(;l<t;)Object.defineProperty(i.prototype,l,a(l)),l++}function c(t){var i,o,a;if("number"==typeof t)for(i=[],o=0;o<t;++o)i[o]=0;else if("slice"in t)i=t.slice(0);else for(i=[],o=0,a=t.length;o<a;++o)i[o]=t[o];return i.subarray=e,i.buffer=i,i.byteLength=i.length,i.set=r,"object"===(void 0===t?"undefined":n(t))&&t.buffer&&(i.buffer=t.buffer),i}if("undefined"!=typeof Uint8Array)return void 0===Uint8Array.prototype.subarray&&(Uint8Array.prototype.subarray=function t(e,r){return new Uint8Array(this.slice(e,r))},Float32Array.prototype.subarray=function t(e,r){return new Float32Array(this.slice(e,r))}),void("undefined"==typeof Float64Array&&(o.Float64Array=Float32Array));i.prototype=Object.create(null);var l=0;o.Uint8Array=c,o.Int8Array=c,o.Int32Array=c,o.Uint16Array=c,o.Float32Array=c,o.Float64Array=c,o.Uint32Array=function(){if(3===arguments.length){if(0!==arguments[1])throw new Error("offset !== 0 is not supported");return new i(arguments[0],arguments[2])}return c.apply(this,arguments)}}(),function t(){if(m&&window.CanvasPixelArray){var e=window.CanvasPixelArray.prototype;"buffer"in e||(Object.defineProperty(e,"buffer",{get:function t(){return this},enumerable:!1,configurable:!0}),Object.defineProperty(e,"byteLength",{get:function t(){return this.length},enumerable:!1,configurable:!0}))}}(),function t(){o.URL||(o.URL=o.webkitURL)}(),function t(){if(void 0!==Object.defineProperty){var e=!0;try{m&&Object.defineProperty(new Image,"id",{value:"test"});var r=function t(){};r.prototype={get id(){}},Object.defineProperty(new r,"id",{value:"",configurable:!0,enumerable:!0,writable:!1})}catch(t){e=!1}if(e)return}Object.defineProperty=function t(e,r,i){delete e[r],"get"in i&&e.__defineGetter__(r,i.get),"set"in i&&e.__defineSetter__(r,i.set),"value"in i&&(e.__defineSetter__(r,function t(e){return this.__defineGetter__(r,function t(){return e}),e}),e[r]=i.value)}}(),function t(){if("undefined"!=typeof XMLHttpRequest){var e=XMLHttpRequest.prototype,r=new XMLHttpRequest;if("overrideMimeType"in r||Object.defineProperty(e,"overrideMimeType",{value:function t(e){}}),!("responseType"in r)){if(Object.defineProperty(e,"responseType",{get:function t(){return this._responseType||"text"},set:function t(e){"text"!==e&&"arraybuffer"!==e||(this._responseType=e,"arraybuffer"===e&&"function"==typeof this.overrideMimeType&&this.overrideMimeType("text/plain; charset=x-user-defined"))}}),"undefined"!=typeof VBArray)return void Object.defineProperty(e,"response",{get:function t(){return"arraybuffer"===this.responseType?new Uint8Array(new VBArray(this.responseBody).toArray()):this.responseText}});Object.defineProperty(e,"response",{get:function t(){if("arraybuffer"!==this.responseType)return this.responseText;var e=this.responseText,r,i=e.length,n=new Uint8Array(i);for(r=0;r<i;++r)n[r]=255&e.charCodeAt(r);return n.buffer}})}}}(),function t(){if(!("btoa"in o)){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";o.btoa=function(t){var r="",i,n;for(i=0,n=t.length;i<n;i+=3){var o=255&t.charCodeAt(i),a=255&t.charCodeAt(i+1),s=255&t.charCodeAt(i+2),c=o>>2,l=(3&o)<<4|a>>4,h=i+1<n?(15&a)<<2|s>>6:64,u=i+2<n?63&s:64;r+=e.charAt(c)+e.charAt(l)+e.charAt(h)+e.charAt(u)}return r}}}(),function t(){if(!("atob"in o)){o.atob=function(t){if(t=t.replace(/=+$/,""),t.length%4==1)throw new Error("bad atob input");for(var e=0,r,i,n=0,o="";i=t.charAt(n++);~i&&(r=e%4?64*r+i:i,e++%4)?o+=String.fromCharCode(255&r>>(-2*e&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return o}}}(),function t(){void 0===Function.prototype.bind&&(Function.prototype.bind=function t(e){var r=this,i=Array.prototype.slice.call(arguments,1);return function t(){var n=i.concat(Array.prototype.slice.call(arguments));return r.apply(e,n)}})}(),function t(){if(m){"dataset"in document.createElement("div")||Object.defineProperty(HTMLElement.prototype,"dataset",{get:function t(){if(this._dataset)return this._dataset;for(var e={},r=0,i=this.attributes.length;r<i;r++){var n=this.attributes[r];if("data-"===n.name.substring(0,5)){e[n.name.substring(5).replace(/\-([a-z])/g,function(t,e){return e.toUpperCase()})]=n.value}}return Object.defineProperty(this,"_dataset",{value:e,writable:!1,enumerable:!1}),e},enumerable:!0})}}(),function t(){function e(t,e,r,i){var n=t.className||"",o=n.split(/\s+/g);""===o[0]&&o.shift();var a=o.indexOf(e);return a<0&&r&&o.push(e),a>=0&&i&&o.splice(a,1),t.className=o.join(" "),a>=0}if(m){if(!("classList"in document.createElement("div"))){var r={add:function t(r){e(this.element,r,!0,!1)},contains:function t(r){return e(this.element,r,!1,!1)},remove:function t(r){e(this.element,r,!1,!0)},toggle:function t(r){e(this.element,r,!0,!0)}};Object.defineProperty(HTMLElement.prototype,"classList",{get:function t(){if(this._classList)return this._classList;var e=Object.create(r,{element:{value:this,writable:!1,enumerable:!0}});return Object.defineProperty(this,"_classList",{value:e,writable:!1,enumerable:!1}),e},enumerable:!0})}}}(),function t(){if(!("undefined"==typeof importScripts||"console"in o)){var e={},r={log:function t(){var e=Array.prototype.slice.call(arguments);o.postMessage({targetName:"main",action:"console_log",data:e})},error:function t(){var e=Array.prototype.slice.call(arguments);o.postMessage({targetName:"main",action:"console_error",data:e})},time:function t(r){e[r]=Date.now()},timeEnd:function t(r){var i=e[r];if(!i)throw new Error("Unknown timer name "+r);this.log("Timer:",r,Date.now()-i)}};o.console=r}}(),function t(){if(m)"console"in window?"bind"in console.log||(console.log=function(t){return function(e){return t(e)}}(console.log),console.error=function(t){return function(e){return t(e)}}(console.error),console.warn=function(t){return function(e){return t(e)}}(console.warn)):window.console={log:function t(){},error:function t(){},warn:function t(){}}}(),function t(){function e(t){r(t.target)&&t.stopPropagation()}function r(t){return t.disabled||t.parentNode&&r(t.parentNode)}g&&document.addEventListener("click",e,!0)}(),function t(){(d||f)&&(PDFJS.disableCreateObjectURL=!0)}(),function t(){"undefined"!=typeof navigator&&("language"in navigator||(PDFJS.locale=navigator.userLanguage||"en-US"))}(),function t(){(v||c||u||p)&&(PDFJS.disableRange=!0,PDFJS.disableStream=!0)}(),function t(){m&&(history.pushState&&!c||(PDFJS.disableHistory=!0))}(),function t(){if(m)if(window.CanvasPixelArray)"function"!=typeof window.CanvasPixelArray.prototype.set&&(window.CanvasPixelArray.prototype.set=function(t){for(var e=0,r=this.length;e<r;e++)this[e]=t[e]});else{var e=!1,r;if(h?(r=a.match(/Chrom(e|ium)\/([0-9]+)\./),e=r&&parseInt(r[2])<21):s?e=l:v&&(r=a.match(/Version\/([0-9]+)\.([0-9]+)\.([0-9]+) Safari\//),e=r&&parseInt(r[1])<6),e){var i=window.CanvasRenderingContext2D.prototype,n=i.createImageData;i.createImageData=function(t,e){var r=n.call(this,t,e);return r.data.set=function(t){for(var e=0,r=this.length;e<r;e++)this[e]=t[e]},r},i=null}}}(),function t(){function e(){window.requestAnimationFrame=function(t){return window.setTimeout(t,20)},window.cancelAnimationFrame=function(t){window.clearTimeout(t)}}if(m)p?e():"requestAnimationFrame"in window||(window.requestAnimationFrame=window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame,window.requestAnimationFrame||e())}(),function t(){(p||s)&&(PDFJS.maxCanvasPixels=5242880)}(),function t(){m&&d&&window.parent!==window&&(PDFJS.disableFullscreen=!0)}(),function t(){m&&("currentScript"in document||Object.defineProperty(document,"currentScript",{get:function t(){var e=document.getElementsByTagName("script");return e[e.length-1]},enumerable:!0,configurable:!0}))}(),function t(){if(m){var e=document.createElement("input");try{e.type="number"}catch(t){var r=e.constructor.prototype,i=Object.getOwnPropertyDescriptor(r,"type");Object.defineProperty(r,"type",{get:function t(){return i.get.call(this)},set:function t(e){i.set.call(this,"number"===e?"text":e)},enumerable:!0,configurable:!0})}}}(),function t(){if(m&&document.attachEvent){var e=document.constructor.prototype,r=Object.getOwnPropertyDescriptor(e,"readyState");Object.defineProperty(e,"readyState",{get:function t(){var e=r.get.call(this);return"interactive"===e?"loading":e},set:function t(e){r.set.call(this,e)},enumerable:!0,configurable:!0})}}(),function t(){m&&void 0===Element.prototype.remove&&(Element.prototype.remove=function(){this.parentNode&&this.parentNode.removeChild(this)})}(),function t(){Number.isNaN||(Number.isNaN=function(t){return"number"==typeof t&&isNaN(t)})}(),function t(){Number.isInteger||(Number.isInteger=function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t})}(),function t(){if(o.Promise)return"function"!=typeof o.Promise.all&&(o.Promise.all=function(t){var e=0,r=[],i,n,a=new o.Promise(function(t,e){i=t,n=e});return t.forEach(function(t,o){e++,t.then(function(t){r[o]=t,0===--e&&i(r)},n)}),0===e&&i(r),a}),"function"!=typeof o.Promise.resolve&&(o.Promise.resolve=function(t){return new o.Promise(function(e){e(t)})}),"function"!=typeof o.Promise.reject&&(o.Promise.reject=function(t){return new o.Promise(function(e,r){r(t)})}),void("function"!=typeof o.Promise.prototype.catch&&(o.Promise.prototype.catch=function(t){return o.Promise.prototype.then(void 0,t)}));var e=0,r=1,i=2,n=500,a={handlers:[],running:!1,unhandledRejections:[],pendingRejectionCheck:!1,scheduleHandlers:function t(e){0!==e._status&&(this.handlers=this.handlers.concat(e._handlers),e._handlers=[],this.running||(this.running=!0,setTimeout(this.runHandlers.bind(this),0)))},runHandlers:function t(){for(var e=1,r=Date.now()+1;this.handlers.length>0;){var n=this.handlers.shift(),o=n.thisPromise._status,a=n.thisPromise._value;try{1===o?"function"==typeof n.onResolve&&(a=n.onResolve(a)):"function"==typeof n.onReject&&(a=n.onReject(a),o=1,n.thisPromise._unhandledRejection&&this.removeUnhandeledRejection(n.thisPromise))}catch(t){o=i,a=t}if(n.nextPromise._updateStatus(o,a),Date.now()>=r)break}if(this.handlers.length>0)return void setTimeout(this.runHandlers.bind(this),0);this.running=!1},addUnhandledRejection:function t(e){this.unhandledRejections.push({promise:e,time:Date.now()}),this.scheduleRejectionCheck()},removeUnhandeledRejection:function t(e){e._unhandledRejection=!1;for(var r=0;r<this.unhandledRejections.length;r++)this.unhandledRejections[r].promise===e&&(this.unhandledRejections.splice(r),r--)},scheduleRejectionCheck:function t(){var e=this;this.pendingRejectionCheck||(this.pendingRejectionCheck=!0,setTimeout(function(){e.pendingRejectionCheck=!1;for(var t=Date.now(),r=0;r<e.unhandledRejections.length;r++)if(t-e.unhandledRejections[r].time>500){var i=e.unhandledRejections[r].promise._value,n="Unhandled rejection: "+i;i.stack&&(n+="\n"+i.stack);try{throw new Error(n)}catch(t){console.warn(n)}e.unhandledRejections.splice(r),r--}e.unhandledRejections.length&&e.scheduleRejectionCheck()},500))}},s=function t(e){this._status=0,this._handlers=[];try{e.call(this,this._resolve.bind(this),this._reject.bind(this))}catch(t){this._reject(t)}};s.all=function t(e){function r(t){a._status!==i&&(l=[],o(t))}var n,o,a=new s(function(t,e){n=t,o=e}),c=e.length,l=[];if(0===c)return n(l),a;for(var h=0,u=e.length;h<u;++h){var f=e[h],d=function(t){return function(e){a._status!==i&&(l[t]=e,0===--c&&n(l))}}(h);s.isPromise(f)?f.then(d,r):d(f)}return a},s.isPromise=function t(e){return e&&"function"==typeof e.then},s.resolve=function t(e){return new s(function(t){t(e)})},s.reject=function t(e){return new s(function(t,r){r(e)})},s.prototype={_status:null,_value:null,_handlers:null,_unhandledRejection:null,_updateStatus:function t(e,r){if(1!==this._status&&this._status!==i){if(1===e&&s.isPromise(r))return void r.then(this._updateStatus.bind(this,1),this._updateStatus.bind(this,i));this._status=e,this._value=r,e===i&&0===this._handlers.length&&(this._unhandledRejection=!0,a.addUnhandledRejection(this)),a.scheduleHandlers(this)}},_resolve:function t(e){this._updateStatus(1,e)},_reject:function t(e){this._updateStatus(i,e)},then:function t(e,r){var i=new s(function(t,e){this.resolve=t,this.reject=e});return this._handlers.push({thisPromise:this,onResolve:e,onReject:r,nextPromise:i}),a.scheduleHandlers(this),i},catch:function t(e){return this.then(void 0,e)}},o.Promise=s}(),function t(){function e(){this.id="$weakmap"+r++}if(!o.WeakMap){var r=0;e.prototype={has:function t(e){return("object"===(void 0===e?"undefined":n(e))||"function"==typeof e)&&null!==e&&!!Object.getOwnPropertyDescriptor(e,this.id)},get:function t(e){return this.has(e)?e[this.id]:void 0},set:function t(e,r){Object.defineProperty(e,this.id,{value:r,enumerable:!1,configurable:!0})},delete:function t(e){delete e[this.id]}},o.WeakMap=e}}(),function t(){function e(t){return void 0!==d[t]}function r(){l.call(this),this._isInvalid=!0}function i(t){return""===t&&r.call(this),t.toLowerCase()}function a(t){var e=t.charCodeAt(0);return e>32&&e<127&&-1===[34,35,60,62,63,96].indexOf(e)?t:encodeURIComponent(t)}function s(t){var e=t.charCodeAt(0);return e>32&&e<127&&-1===[34,35,60,62,96].indexOf(e)?t:encodeURIComponent(t)}function c(t,n,o){function c(t){y.push(t)}var l=n||"scheme start",h=0,u="",f=!1,b=!1,y=[];t:for(;(t[h-1]!==g||0===h)&&!this._isInvalid;){var _=t[h];switch(l){case"scheme start":if(!_||!v.test(_)){if(n){c("Invalid scheme.");break t}u="",l="no scheme";continue}u+=_.toLowerCase(),l="scheme";break;case"scheme":if(_&&m.test(_))u+=_.toLowerCase();else{if(":"!==_){if(n){if(_===g)break t;c("Code point not allowed in scheme: "+_);break t}u="",h=0,l="no scheme";continue}if(this._scheme=u,u="",n)break t;e(this._scheme)&&(this._isRelative=!0),l="file"===this._scheme?"relative":this._isRelative&&o&&o._scheme===this._scheme?"relative or authority":this._isRelative?"authority first slash":"scheme data"}break;case"scheme data":"?"===_?(this._query="?",l="query"):"#"===_?(this._fragment="#",l="fragment"):_!==g&&"\t"!==_&&"\n"!==_&&"\r"!==_&&(this._schemeData+=a(_));break;case"no scheme":if(o&&e(o._scheme)){l="relative";continue}c("Missing scheme."),r.call(this);break;case"relative or authority":if("/"!==_||"/"!==t[h+1]){c("Expected /, got: "+_),l="relative";continue}l="authority ignore slashes";break;case"relative":if(this._isRelative=!0,"file"!==this._scheme&&(this._scheme=o._scheme),_===g){this._host=o._host,this._port=o._port,this._path=o._path.slice(),this._query=o._query,this._username=o._username,this._password=o._password;break t}if("/"===_||"\\"===_)"\\"===_&&c("\\ is an invalid code point."),l="relative slash";else if("?"===_)this._host=o._host,this._port=o._port,this._path=o._path.slice(),this._query="?",this._username=o._username,this._password=o._password,l="query";else{if("#"!==_){var w=t[h+1],S=t[h+2];("file"!==this._scheme||!v.test(_)||":"!==w&&"|"!==w||S!==g&&"/"!==S&&"\\"!==S&&"?"!==S&&"#"!==S)&&(this._host=o._host,this._port=o._port,this._username=o._username,this._password=o._password,this._path=o._path.slice(),this._path.pop()),l="relative path";continue}this._host=o._host,this._port=o._port,this._path=o._path.slice(),this._query=o._query,this._fragment="#",this._username=o._username,this._password=o._password,l="fragment"}break;case"relative slash":if("/"!==_&&"\\"!==_){"file"!==this._scheme&&(this._host=o._host,this._port=o._port,this._username=o._username,this._password=o._password),l="relative path";continue}"\\"===_&&c("\\ is an invalid code point."),l="file"===this._scheme?"file host":"authority ignore slashes";break;case"authority first slash":if("/"!==_){c("Expected '/', got: "+_),l="authority ignore slashes";continue}l="authority second slash";break;case"authority second slash":if(l="authority ignore slashes","/"!==_){c("Expected '/', got: "+_);continue}break;case"authority ignore slashes":if("/"!==_&&"\\"!==_){l="authority";continue}c("Expected authority, got: "+_);break;case"authority":if("@"===_){f&&(c("@ already seen."),u+="%40"),f=!0;for(var x=0;x<u.length;x++){var C=u[x];if("\t"!==C&&"\n"!==C&&"\r"!==C)if(":"!==C||null!==this._password){var A=a(C);null!==this._password?this._password+=A:this._username+=A}else this._password="";else c("Invalid whitespace in authority.")}u=""}else{if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_){h-=u.length,u="",l="host";continue}u+=_}break;case"file host":if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_){2!==u.length||!v.test(u[0])||":"!==u[1]&&"|"!==u[1]?0===u.length?l="relative path start":(this._host=i.call(this,u),u="",l="relative path start"):l="relative path";continue}"\t"===_||"\n"===_||"\r"===_?c("Invalid whitespace in file host."):u+=_;break;case"host":case"hostname":if(":"!==_||b){if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_){if(this._host=i.call(this,u),u="",l="relative path start",n)break t;continue}"\t"!==_&&"\n"!==_&&"\r"!==_?("["===_?b=!0:"]"===_&&(b=!1),u+=_):c("Invalid code point in host/hostname: "+_)}else if(this._host=i.call(this,u),u="",l="port","hostname"===n)break t;break;case"port":if(/[0-9]/.test(_))u+=_;else{if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_||n){if(""!==u){var T=parseInt(u,10);T!==d[this._scheme]&&(this._port=T+""),u=""}if(n)break t;l="relative path start";continue}"\t"===_||"\n"===_||"\r"===_?c("Invalid code point in port: "+_):r.call(this)}break;case"relative path start":if("\\"===_&&c("'\\' not allowed in path."),l="relative path","/"!==_&&"\\"!==_)continue;break;case"relative path":if(_!==g&&"/"!==_&&"\\"!==_&&(n||"?"!==_&&"#"!==_))"\t"!==_&&"\n"!==_&&"\r"!==_&&(u+=a(_));else{"\\"===_&&c("\\ not allowed in relative path.");var k;(k=p[u.toLowerCase()])&&(u=k),".."===u?(this._path.pop(),"/"!==_&&"\\"!==_&&this._path.push("")):"."===u&&"/"!==_&&"\\"!==_?this._path.push(""):"."!==u&&("file"===this._scheme&&0===this._path.length&&2===u.length&&v.test(u[0])&&"|"===u[1]&&(u=u[0]+":"),this._path.push(u)),u="","?"===_?(this._query="?",l="query"):"#"===_&&(this._fragment="#",l="fragment")}break;case"query":n||"#"!==_?_!==g&&"\t"!==_&&"\n"!==_&&"\r"!==_&&(this._query+=s(_)):(this._fragment="#",l="fragment");break;case"fragment":_!==g&&"\t"!==_&&"\n"!==_&&"\r"!==_&&(this._fragment+=_)}h++}}function l(){this._scheme="",this._schemeData="",this._username="",this._password=null,this._host="",this._port="",this._path=[],this._query="",this._fragment="",this._isInvalid=!1,this._isRelative=!1}function h(t,e){void 0===e||e instanceof h||(e=new h(String(e))),this._url=t,l.call(this);var r=t.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g,"");c.call(this,r,null,e)}var u=!1;try{if("function"==typeof URL&&"object"===n(URL.prototype)&&"origin"in URL.prototype){var f=new URL("b","http://a");f.pathname="c%20d",u="http://a/c%20d"===f.href}}catch(t){}if(!u){var d=Object.create(null);d.ftp=21,d.file=0,d.gopher=70,d.http=80,d.https=443,d.ws=80,d.wss=443;var p=Object.create(null);p["%2e"]=".",p[".%2e"]="..",p["%2e."]="..",p["%2e%2e"]="..";var g,v=/[a-zA-Z]/,m=/[a-zA-Z0-9\+\-\.]/;h.prototype={toString:function t(){return this.href},get href(){if(this._isInvalid)return this._url;var t="";return""===this._username&&null===this._password||(t=this._username+(null!==this._password?":"+this._password:"")+"@"),this.protocol+(this._isRelative?"//"+t+this.host:"")+this.pathname+this._query+this._fragment},set href(t){l.call(this),c.call(this,t)},get protocol(){return this._scheme+":"},set protocol(t){this._isInvalid||c.call(this,t+":","scheme start")},get host(){return this._isInvalid?"":this._port?this._host+":"+this._port:this._host},set host(t){!this._isInvalid&&this._isRelative&&c.call(this,t,"host")},get hostname(){return this._host},set hostname(t){!this._isInvalid&&this._isRelative&&c.call(this,t,"hostname")},get port(){return this._port},set port(t){!this._isInvalid&&this._isRelative&&c.call(this,t,"port")},get pathname(){return this._isInvalid?"":this._isRelative?"/"+this._path.join("/"):this._schemeData},set pathname(t){!this._isInvalid&&this._isRelative&&(this._path=[],c.call(this,t,"relative path start"))},get search(){return this._isInvalid||!this._query||"?"===this._query?"":this._query},set search(t){!this._isInvalid&&this._isRelative&&(this._query="?","?"===t[0]&&(t=t.slice(1)),c.call(this,t,"query"))},get hash(){return this._isInvalid||!this._fragment||"#"===this._fragment?"":this._fragment},set hash(t){this._isInvalid||(this._fragment="#","#"===t[0]&&(t=t.slice(1)),c.call(this,t,"fragment"))},get origin(){var t;if(this._isInvalid||!this._scheme)return"";switch(this._scheme){case"data":case"file":case"javascript":case"mailto":return"null";case"blob":try{return new h(this._schemeData).origin||"null"}catch(t){}return"null"}return t=this.host,t?this._scheme+"://"+t:""}};var b=o.URL;b&&(h.createObjectURL=function(t){return b.createObjectURL.apply(b,arguments)},h.revokeObjectURL=function(t){b.revokeObjectURL(t)}),o.URL=h}}()}}])})}).call(e,r(0),r(1),r(2).Buffer)},function(t,e){var r={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==r.call(t)}},function(t,e,r){"use strict";(function(e,i){function n(t){return B.from(t)}function o(t){return B.isBuffer(t)||t instanceof U}function a(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?I(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}function s(t,e){j=j||r(4),t=t||{},this.objectMode=!!t.objectMode,e instanceof j&&(this.objectMode=this.objectMode||!!t.readableObjectMode);var i=t.highWaterMark,n=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:n,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new X,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(H||(H=r(19).StringDecoder),this.decoder=new H(t.encoding),this.encoding=t.encoding)}function c(t){if(j=j||r(4),!(this instanceof c))return new c(t);this._readableState=new s(t,this),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),N.call(this)}function l(t,e,r,i,o){var a=t._readableState;if(null===e)a.reading=!1,g(t,a);else{var s;o||(s=u(a,e)),s?t.emit("error",s):a.objectMode||e&&e.length>0?("string"==typeof e||a.objectMode||Object.getPrototypeOf(e)===B.prototype||(e=n(e)),i?a.endEmitted?t.emit("error",new Error("stream.unshift() after end event")):h(t,a,e,!0):a.ended?t.emit("error",new Error("stream.push() after EOF")):(a.reading=!1,a.decoder&&!r?(e=a.decoder.write(e),a.objectMode||0!==e.length?h(t,a,e,!1):b(t,a)):h(t,a,e,!1))):i||(a.reading=!1)}return f(a)}function h(t,e,r,i){e.flowing&&0===e.length&&!e.sync?(t.emit("data",r),t.read(0)):(e.length+=e.objectMode?1:r.length,i?e.buffer.unshift(r):e.buffer.push(r),e.needReadable&&v(t)),b(t,e)}function u(t,e){var r;return o(e)||"string"==typeof e||void 0===e||t.objectMode||(r=new TypeError("Invalid non-string/buffer chunk")),r}function f(t){return!t.ended&&(t.needReadable||t.length<t.highWaterMark||0===t.length)}function d(t){return t>=V?t=V:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}function p(t,e){return t<=0||0===e.length&&e.ended?0:e.objectMode?1:t!==t?e.flowing&&e.length?e.buffer.head.data.length:e.length:(t>e.highWaterMark&&(e.highWaterMark=d(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function g(t,e){if(!e.ended){if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,v(t)}}function v(t){var e=t._readableState;e.needReadable=!1,e.emittedReadable||(q("emitReadable",e.flowing),e.emittedReadable=!0,e.sync?D(m,t):m(t))}function m(t){q("emit readable"),t.emit("readable"),C(t)}function b(t,e){e.readingMore||(e.readingMore=!0,D(y,t,e))}function y(t,e){for(var r=e.length;!e.reading&&!e.flowing&&!e.ended&&e.length<e.highWaterMark&&(q("maybeReadMore read 0"),t.read(0),r!==e.length);)r=e.length;e.readingMore=!1}function _(t){return function(){var e=t._readableState;q("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&F(t,"data")&&(e.flowing=!0,C(t))}}function w(t){q("readable nexttick read 0"),t.read(0)}function S(t,e){e.resumeScheduled||(e.resumeScheduled=!0,D(x,t,e))}function x(t,e){e.reading||(q("resume read 0"),t.read(0)),e.resumeScheduled=!1,e.awaitDrain=0,t.emit("resume"),C(t),e.flowing&&!e.reading&&t.read(0)}function C(t){var e=t._readableState;for(q("flow",e.flowing);e.flowing&&null!==t.read(););}function A(t,e){if(0===e.length)return null;var r;return e.objectMode?r=e.buffer.shift():!t||t>=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.head.data:e.buffer.concat(e.length),e.buffer.clear()):r=T(t,e.buffer,e.decoder),r}function T(t,e,r){var i;return t<e.head.data.length?(i=e.head.data.slice(0,t),e.head.data=e.head.data.slice(t)):i=t===e.head.data.length?e.shift():r?k(t,e):P(t,e),i}function k(t,e){var r=e.head,i=1,n=r.data;for(t-=n.length;r=r.next;){var o=r.data,a=t>o.length?o.length:t;if(a===o.length?n+=o:n+=o.slice(0,t),0===(t-=a)){a===o.length?(++i,r.next?e.head=r.next:e.head=e.tail=null):(e.head=r,r.data=o.slice(a));break}++i}return e.length-=i,n}function P(t,e){var r=B.allocUnsafe(t),i=e.head,n=1;for(i.data.copy(r),t-=i.data.length;i=i.next;){var o=i.data,a=t>o.length?o.length:t;if(o.copy(r,r.length-t,0,a),0===(t-=a)){a===o.length?(++n,i.next?e.head=i.next:e.head=e.tail=null):(e.head=i,i.data=o.slice(a));break}++n}return e.length-=n,r}function E(t){var e=t._readableState;if(e.length>0)throw new Error('"endReadable()" called on non-empty stream');e.endEmitted||(e.ended=!0,D(O,e,t))}function O(t,e){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}function R(t,e){for(var r=0,i=t.length;r<i;r++)e(t[r],r)}function L(t,e){for(var r=0,i=t.length;r<i;r++)if(t[r]===e)return r;return-1}var D=r(7);t.exports=c;var I=r(13),j;c.ReadableState=s;var M=r(15).EventEmitter,F=function(t,e){return t.listeners(e).length},N=r(16),B=r(10).Buffer,U=e.Uint8Array||function(){},z=r(5);z.inherits=r(3);var W=r(44),q=void 0;q=W&&W.debuglog?W.debuglog("stream"):function(){};var X=r(45),G=r(17),H;z.inherits(c,N);var Y=["error","close","destroy","pause","resume"];Object.defineProperty(c.prototype,"destroyed",{get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(t){this._readableState&&(this._readableState.destroyed=t)}}),c.prototype.destroy=G.destroy,c.prototype._undestroy=G.undestroy,c.prototype._destroy=function(t,e){this.push(null),e(t)},c.prototype.push=function(t,e){var r=this._readableState,i;return r.objectMode?i=!0:"string"==typeof t&&(e=e||r.defaultEncoding,e!==r.encoding&&(t=B.from(t,e),e=""),i=!0),l(this,t,e,!1,i)},c.prototype.unshift=function(t){return l(this,t,null,!0,!1)},c.prototype.isPaused=function(){return!1===this._readableState.flowing},c.prototype.setEncoding=function(t){return H||(H=r(19).StringDecoder),this._readableState.decoder=new H(t),this._readableState.encoding=t,this};var V=8388608;c.prototype.read=function(t){q("read",t),t=parseInt(t,10);var e=this._readableState,r=t;if(0!==t&&(e.emittedReadable=!1),0===t&&e.needReadable&&(e.length>=e.highWaterMark||e.ended))return q("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?E(this):v(this),null;if(0===(t=p(t,e))&&e.ended)return 0===e.length&&E(this),null;var i=e.needReadable;q("need readable",i),(0===e.length||e.length-t<e.highWaterMark)&&(i=!0,q("length less than watermark",i)),e.ended||e.reading?(i=!1,q("reading or ended",i)):i&&(q("do read"),e.reading=!0,e.sync=!0,0===e.length&&(e.needReadable=!0),this._read(e.highWaterMark),e.sync=!1,e.reading||(t=p(r,e)));var n;return n=t>0?A(t,e):null,null===n?(e.needReadable=!0,t=0):e.length-=t,0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&E(this)),null!==n&&this.emit("data",n),n},c.prototype._read=function(t){this.emit("error",new Error("_read() is not implemented"))},c.prototype.pipe=function(t,e){function r(t,e){q("onunpipe"),t===f&&e&&!1===e.hasUnpiped&&(e.hasUnpiped=!0,o())}function n(){q("onend"),t.end()}function o(){q("cleanup"),t.removeListener("close",l),t.removeListener("finish",h),t.removeListener("drain",v),t.removeListener("error",c),t.removeListener("unpipe",r),f.removeListener("end",n),f.removeListener("end",u),f.removeListener("data",s),m=!0,!d.awaitDrain||t._writableState&&!t._writableState.needDrain||v()}function s(e){q("ondata"),b=!1,!1!==t.write(e)||b||((1===d.pipesCount&&d.pipes===t||d.pipesCount>1&&-1!==L(d.pipes,t))&&!m&&(q("false write response, pause",f._readableState.awaitDrain),f._readableState.awaitDrain++,b=!0),f.pause())}function c(e){q("onerror",e),u(),t.removeListener("error",c),0===F(t,"error")&&t.emit("error",e)}function l(){t.removeListener("finish",h),u()}function h(){q("onfinish"),t.removeListener("close",l),u()}function u(){q("unpipe"),f.unpipe(t)}var f=this,d=this._readableState;switch(d.pipesCount){case 0:d.pipes=t;break;case 1:d.pipes=[d.pipes,t];break;default:d.pipes.push(t)}d.pipesCount+=1,q("pipe count=%d opts=%j",d.pipesCount,e);var p=(!e||!1!==e.end)&&t!==i.stdout&&t!==i.stderr,g=p?n:u;d.endEmitted?D(g):f.once("end",g),t.on("unpipe",r);var v=_(f);t.on("drain",v);var m=!1,b=!1;return f.on("data",s),a(t,"error",c),t.once("close",l),t.once("finish",h),t.emit("pipe",f),d.flowing||(q("pipe resume"),f.resume()),t},c.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes?this:(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r),this);if(!t){var i=e.pipes,n=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var o=0;o<n;o++)i[o].emit("unpipe",this,r);return this}var a=L(e.pipes,t);return-1===a?this:(e.pipes.splice(a,1),e.pipesCount-=1,1===e.pipesCount&&(e.pipes=e.pipes[0]),t.emit("unpipe",this,r),this)},c.prototype.on=function(t,e){var r=N.prototype.on.call(this,t,e);if("data"===t)!1!==this._readableState.flowing&&this.resume();else if("readable"===t){var i=this._readableState;i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.emittedReadable=!1,i.reading?i.length&&v(this):D(w,this))}return r},c.prototype.addListener=c.prototype.on,c.prototype.resume=function(){var t=this._readableState;return t.flowing||(q("resume"),t.flowing=!0,S(this,t)),this},c.prototype.pause=function(){return q("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(q("pause"),this._readableState.flowing=!1,this.emit("pause")),this},c.prototype.wrap=function(t){var e=this._readableState,r=!1,i=this;t.on("end",function(){if(q("wrapped end"),e.decoder&&!e.ended){var t=e.decoder.end();t&&t.length&&i.push(t)}i.push(null)}),t.on("data",function(n){if(q("wrapped data"),e.decoder&&(n=e.decoder.write(n)),(!e.objectMode||null!==n&&void 0!==n)&&(e.objectMode||n&&n.length)){i.push(n)||(r=!0,t.pause())}});for(var n in t)void 0===this[n]&&"function"==typeof t[n]&&(this[n]=function(e){return function(){return t[e].apply(t,arguments)}}(n));for(var o=0;o<Y.length;o++)t.on(Y[o],i.emit.bind(i,Y[o]));return i._read=function(e){q("wrapped _read",e),r&&(r=!1,t.resume())},i},c._fromList=A}).call(e,r(0),r(1))},function(t,e){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(t){return"function"==typeof t}function n(t){return"number"==typeof t}function o(t){return"object"==typeof t&&null!==t}function a(t){return void 0===t}t.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(t){if(!n(t)||t<0||isNaN(t))throw TypeError("n must be a positive number");return this._maxListeners=t,this},r.prototype.emit=function(t){var e,r,n,s,c,l;if(this._events||(this._events={}),"error"===t&&(!this._events.error||o(this._events.error)&&!this._events.error.length)){if((e=arguments[1])instanceof Error)throw e;var h=new Error('Uncaught, unspecified "error" event. ('+e+")");throw h.context=e,h}if(r=this._events[t],a(r))return!1;if(i(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:s=Array.prototype.slice.call(arguments,1),r.apply(this,s)}else if(o(r))for(s=Array.prototype.slice.call(arguments,1),l=r.slice(),n=l.length,c=0;c<n;c++)l[c].apply(this,s);return!0},r.prototype.addListener=function(t,e){var n;if(!i(e))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",t,i(e.listener)?e.listener:e),this._events[t]?o(this._events[t])?this._events[t].push(e):this._events[t]=[this._events[t],e]:this._events[t]=e,o(this._events[t])&&!this._events[t].warned&&(n=a(this._maxListeners)?r.defaultMaxListeners:this._maxListeners)&&n>0&&this._events[t].length>n&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace()),this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(t,e){function r(){this.removeListener(t,r),n||(n=!0,e.apply(this,arguments))}if(!i(e))throw TypeError("listener must be a function");var n=!1;return r.listener=e,this.on(t,r),this},r.prototype.removeListener=function(t,e){var r,n,a,s;if(!i(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(r=this._events[t],a=r.length,n=-1,r===e||i(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(o(r)){for(s=a;s-- >0;)if(r[s]===e||r[s].listener&&r[s].listener===e){n=s;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},r.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[t],i(r))this.removeListener(t,r);else if(r)for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},r.prototype.listeners=function(t){var e;return e=this._events&&this._events[t]?i(this._events[t])?[this._events[t]]:this._events[t].slice():[]},r.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(i(e))return 1;if(e)return e.length}return 0},r.listenerCount=function(t,e){return t.listenerCount(e)}},function(t,e,r){t.exports=r(15).EventEmitter},function(t,e,r){"use strict";function i(t,e){var r=this,i=this._readableState&&this._readableState.destroyed,n=this._writableState&&this._writableState.destroyed;if(i||n)return void(e?e(t):!t||this._writableState&&this._writableState.errorEmitted||a(o,this,t));this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,function(t){!e&&t?(a(o,r,t),r._writableState&&(r._writableState.errorEmitted=!0)):e&&e(t)})}function n(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function o(t,e){t.emit("error",e)}var a=r(7);t.exports={destroy:i,undestroy:n}},function(t,e,r){"use strict";(function(e,i,n){function o(t,e,r){this.chunk=t,this.encoding=e,this.callback=r,this.next=null}function a(t){var e=this;this.next=null,this.entry=null,this.finish=function(){P(e,t)}}function s(t){return j.from(t)}function c(t){return j.isBuffer(t)||t instanceof M}function l(){}function h(t,e){R=R||r(4),t=t||{},this.objectMode=!!t.objectMode,e instanceof R&&(this.objectMode=this.objectMode||!!t.writableObjectMode);var i=t.highWaterMark,n=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:n,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var o=!1===t.decodeStrings;this.decodeStrings=!o,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(t){y(e,t)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new a(this)}function u(t){if(R=R||r(4),!(N.call(u,this)||this instanceof R))return new u(t);this._writableState=new h(t,this),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),I.call(this)}function f(t,e){var r=new Error("write after end");t.emit("error",r),E(e,r)}function d(t,e,r,i){var n=!0,o=!1;return null===r?o=new TypeError("May not write null values to stream"):"string"==typeof r||void 0===r||e.objectMode||(o=new TypeError("Invalid non-string/buffer chunk")),o&&(t.emit("error",o),E(i,o),n=!1),n}function p(t,e,r){return t.objectMode||!1===t.decodeStrings||"string"!=typeof e||(e=j.from(e,r)),e}function g(t,e,r,i,n,o){if(!r){var a=p(e,i,n);i!==a&&(r=!0,n="buffer",i=a)}var s=e.objectMode?1:i.length;e.length+=s;var c=e.length<e.highWaterMark;if(c||(e.needDrain=!0),e.writing||e.corked){var l=e.lastBufferedRequest;e.lastBufferedRequest={chunk:i,encoding:n,isBuf:r,callback:o,next:null},l?l.next=e.lastBufferedRequest:e.bufferedRequest=e.lastBufferedRequest,e.bufferedRequestCount+=1}else v(t,e,!1,s,i,n,o);return c}function v(t,e,r,i,n,o,a){e.writelen=i,e.writecb=a,e.writing=!0,e.sync=!0,r?t._writev(n,e.onwrite):t._write(n,o,e.onwrite),e.sync=!1}function m(t,e,r,i,n){--e.pendingcb,r?(E(n,i),E(T,t,e),t._writableState.errorEmitted=!0,t.emit("error",i)):(n(i),t._writableState.errorEmitted=!0,t.emit("error",i),T(t,e))}function b(t){t.writing=!1,t.writecb=null,t.length-=t.writelen,t.writelen=0}function y(t,e){var r=t._writableState,i=r.sync,n=r.writecb;if(b(r),e)m(t,r,i,e,n);else{var o=x(r);o||r.corked||r.bufferProcessing||!r.bufferedRequest||S(t,r),i?O(_,t,r,o,n):_(t,r,o,n)}}function _(t,e,r,i){r||w(t,e),e.pendingcb--,i(),T(t,e)}function w(t,e){0===e.length&&e.needDrain&&(e.needDrain=!1,t.emit("drain"))}function S(t,e){e.bufferProcessing=!0;var r=e.bufferedRequest;if(t._writev&&r&&r.next){var i=e.bufferedRequestCount,n=new Array(i),o=e.corkedRequestsFree;o.entry=r;for(var s=0,c=!0;r;)n[s]=r,r.isBuf||(c=!1),r=r.next,s+=1;n.allBuffers=c,v(t,e,!0,e.length,n,"",o.finish),e.pendingcb++,e.lastBufferedRequest=null,o.next?(e.corkedRequestsFree=o.next,o.next=null):e.corkedRequestsFree=new a(e)}else{for(;r;){var l=r.chunk,h=r.encoding,u=r.callback;if(v(t,e,!1,e.objectMode?1:l.length,l,h,u),r=r.next,e.writing)break}null===r&&(e.lastBufferedRequest=null)}e.bufferedRequestCount=0,e.bufferedRequest=r,e.bufferProcessing=!1}function x(t){return t.ending&&0===t.length&&null===t.bufferedRequest&&!t.finished&&!t.writing}function C(t,e){t._final(function(r){e.pendingcb--,r&&t.emit("error",r),e.prefinished=!0,t.emit("prefinish"),T(t,e)})}function A(t,e){e.prefinished||e.finalCalled||("function"==typeof t._final?(e.pendingcb++,e.finalCalled=!0,E(C,t,e)):(e.prefinished=!0,t.emit("prefinish")))}function T(t,e){var r=x(e);return r&&(A(t,e),0===e.pendingcb&&(e.finished=!0,t.emit("finish"))),r}function k(t,e,r){e.ending=!0,T(t,e),r&&(e.finished?E(r):t.once("finish",r)),e.ended=!0,t.writable=!1}function P(t,e,r){var i=t.entry;for(t.entry=null;i;){var n=i.callback;e.pendingcb--,n(r),i=i.next}e.corkedRequestsFree?e.corkedRequestsFree.next=t:e.corkedRequestsFree=t}var E=r(7);t.exports=u;var O=!e.browser&&["v0.10","v0.9."].indexOf(e.version.slice(0,5))>-1?i:E,R;u.WritableState=h;var L=r(5);L.inherits=r(3);var D={deprecate:r(48)},I=r(16),j=r(10).Buffer,M=n.Uint8Array||function(){},F=r(17);L.inherits(u,I),h.prototype.getBuffer=function t(){for(var e=this.bufferedRequest,r=[];e;)r.push(e),e=e.next;return r},function(){try{Object.defineProperty(h.prototype,"buffer",{get:D.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(t){}}();var N;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(N=Function.prototype[Symbol.hasInstance],Object.defineProperty(u,Symbol.hasInstance,{value:function(t){return!!N.call(this,t)||t&&t._writableState instanceof h}})):N=function(t){return t instanceof this},u.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},u.prototype.write=function(t,e,r){var i=this._writableState,n=!1,o=c(t)&&!i.objectMode;return o&&!j.isBuffer(t)&&(t=s(t)),"function"==typeof e&&(r=e,e=null),o?e="buffer":e||(e=i.defaultEncoding),"function"!=typeof r&&(r=l),i.ended?f(this,r):(o||d(this,i,t,r))&&(i.pendingcb++,n=g(this,i,o,t,e,r)),n},u.prototype.cork=function(){this._writableState.corked++},u.prototype.uncork=function(){var t=this._writableState;t.corked&&(t.corked--,t.writing||t.corked||t.finished||t.bufferProcessing||!t.bufferedRequest||S(this,t))},u.prototype.setDefaultEncoding=function t(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},u.prototype._write=function(t,e,r){r(new Error("_write() is not implemented"))},u.prototype._writev=null,u.prototype.end=function(t,e,r){var i=this._writableState;"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!==t&&void 0!==t&&this.write(t,e),i.corked&&(i.corked=1,this.uncork()),i.ending||i.finished||k(this,i,r)},Object.defineProperty(u.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t)}}),u.prototype.destroy=F.destroy,u.prototype._undestroy=F.undestroy,u.prototype._destroy=function(t,e){this.end(),e(t)}}).call(e,r(1),r(46).setImmediate,r(0))},function(t,e,r){function i(t){if(t&&!c(t))throw new Error("Unknown encoding: "+t)}function n(t){return t.toString(this.encoding)}function o(t){this.charReceived=t.length%2,this.charLength=this.charReceived?2:0}function a(t){this.charReceived=t.length%3,this.charLength=this.charReceived?3:0}var s=r(2).Buffer,c=s.isEncoding||function(t){switch(t&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}},l=e.StringDecoder=function(t){switch(this.encoding=(t||"utf8").toLowerCase().replace(/[-_]/,""),i(t),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=o;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=a;break;default:return void(this.write=n)}this.charBuffer=new s(6),this.charReceived=0,this.charLength=0};l.prototype.write=function(t){for(var e="";this.charLength;){var r=t.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:t.length;if(t.copy(this.charBuffer,this.charReceived,0,r),this.charReceived+=r,this.charReceived<this.charLength)return"";t=t.slice(r,t.length),e=this.charBuffer.slice(0,this.charLength).toString(this.encoding);var i=e.charCodeAt(e.length-1);if(!(i>=55296&&i<=56319)){if(this.charReceived=this.charLength=0,0===t.length)return e;break}this.charLength+=this.surrogateSize,e=""}this.detectIncompleteChar(t);var n=t.length;this.charLength&&(t.copy(this.charBuffer,0,t.length-this.charReceived,n),n-=this.charReceived),e+=t.toString(this.encoding,0,n);var n=e.length-1,i=e.charCodeAt(n);if(i>=55296&&i<=56319){var o=this.surrogateSize;return this.charLength+=o,this.charReceived+=o,this.charBuffer.copy(this.charBuffer,o,0,o),t.copy(this.charBuffer,0,0,o),e.substring(0,n)}return e},l.prototype.detectIncompleteChar=function(t){for(var e=t.length>=3?3:t.length;e>0;e--){var r=t[t.length-e];if(1==e&&r>>5==6){this.charLength=2;break}if(e<=2&&r>>4==14){this.charLength=3;break}if(e<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=e},l.prototype.end=function(t){var e="";if(t&&t.length&&(e=this.write(t)),this.charReceived){var r=this.charReceived,i=this.charBuffer,n=this.encoding;e+=i.slice(0,r).toString(n)}return e}},function(t,e,r){"use strict";function i(t){this.afterTransform=function(e,r){return n(t,e,r)},this.needTransform=!1,this.transforming=!1,this.writecb=null,this.writechunk=null,this.writeencoding=null}function n(t,e,r){var i=t._transformState;i.transforming=!1;var n=i.writecb;if(!n)return t.emit("error",new Error("write callback called multiple times"));i.writechunk=null,i.writecb=null,null!==r&&void 0!==r&&t.push(r),n(e);var o=t._readableState;o.reading=!1,(o.needReadable||o.length<o.highWaterMark)&&t._read(o.highWaterMark)}function o(t){if(!(this instanceof o))return new o(t);s.call(this,t),this._transformState=new i(this);var e=this;this._readableState.needReadable=!0,this._readableState.sync=!1,t&&("function"==typeof t.transform&&(this._transform=t.transform),"function"==typeof t.flush&&(this._flush=t.flush)),this.once("prefinish",function(){"function"==typeof this._flush?this._flush(function(t,r){a(e,t,r)}):a(e)})}function a(t,e,r){if(e)return t.emit("error",e);null!==r&&void 0!==r&&t.push(r);var i=t._writableState,n=t._transformState;if(i.length)throw new Error("Calling transform done when ws.length != 0");if(n.transforming)throw new Error("Calling transform done when still transforming");return t.push(null)}t.exports=o;var s=r(4),c=r(5);c.inherits=r(3),c.inherits(o,s),o.prototype.push=function(t,e){return this._transformState.needTransform=!1,s.prototype.push.call(this,t,e)},o.prototype._transform=function(t,e,r){throw new Error("_transform() is not implemented")},o.prototype._write=function(t,e,r){var i=this._transformState;if(i.writecb=r,i.writechunk=t,i.writeencoding=e,!i.transforming){var n=this._readableState;(i.needTransform||n.needReadable||n.length<n.highWaterMark)&&this._read(n.highWaterMark)}},o.prototype._read=function(t){var e=this._transformState;null!==e.writechunk&&e.writecb&&!e.transforming?(e.transforming=!0,this._transform(e.writechunk,e.writeencoding,e.afterTransform)):e.needTransform=!0},o.prototype._destroy=function(t,e){var r=this;s.prototype._destroy.call(this,t,function(t){e(t),r.emit("close")})}},function(t,e,r){"use strict";t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},function(t,e,r){"use strict";function i(t,e,r,i){for(var n=65535&t|0,o=t>>>16&65535|0,a=0;0!==r;){a=r>2e3?2e3:r,r-=a;do{n=n+e[i++]|0,o=o+n|0}while(--a);n%=65521,o%=65521}return n|o<<16|0}t.exports=i},function(t,e,r){"use strict";function i(){for(var t,e=[],r=0;r<256;r++){t=r;for(var i=0;i<8;i++)t=1&t?3988292384^t>>>1:t>>>1;e[r]=t}return e}function n(t,e,r,i){var n=o,a=i+r;t^=-1;for(var s=i;s<a;s++)t=t>>>8^n[255&(t^e[s])];return-1^t}var o=i();t.exports=n},function(t,e,r){(function(t,i){function n(t,r){var i={seen:[],stylize:a};return arguments.length>=3&&(i.depth=arguments[2]),arguments.length>=4&&(i.colors=arguments[3]),g(r)?i.showHidden=r:r&&e._extend(i,r),w(i.showHidden)&&(i.showHidden=!1),w(i.depth)&&(i.depth=2),w(i.colors)&&(i.colors=!1),w(i.customInspect)&&(i.customInspect=!0),i.colors&&(i.stylize=o),c(i,t,i.depth)}function o(t,e){var r=n.styles[e];return r?"["+n.colors[r][0]+"m"+t+"["+n.colors[r][1]+"m":t}function a(t,e){return t}function s(t){var e={};return t.forEach(function(t,r){e[t]=!0}),e}function c(t,r,i){if(t.customInspect&&r&&T(r.inspect)&&r.inspect!==e.inspect&&(!r.constructor||r.constructor.prototype!==r)){var n=r.inspect(i,t);return y(n)||(n=c(t,n,i)),n}var o=l(t,r);if(o)return o;var a=Object.keys(r),g=s(a);if(t.showHidden&&(a=Object.getOwnPropertyNames(r)),A(r)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return h(r);if(0===a.length){if(T(r)){var v=r.name?": "+r.name:"";return t.stylize("[Function"+v+"]","special")}if(S(r))return t.stylize(RegExp.prototype.toString.call(r),"regexp");if(C(r))return t.stylize(Date.prototype.toString.call(r),"date");if(A(r))return h(r)}var m="",b=!1,_=["{","}"];if(p(r)&&(b=!0,_=["[","]"]),T(r)){m=" [Function"+(r.name?": "+r.name:"")+"]"}if(S(r)&&(m=" "+RegExp.prototype.toString.call(r)),C(r)&&(m=" "+Date.prototype.toUTCString.call(r)),A(r)&&(m=" "+h(r)),0===a.length&&(!b||0==r.length))return _[0]+m+_[1];if(i<0)return S(r)?t.stylize(RegExp.prototype.toString.call(r),"regexp"):t.stylize("[Object]","special");t.seen.push(r);var w;return w=b?u(t,r,i,g,a):a.map(function(e){return f(t,r,i,g,e,b)}),t.seen.pop(),d(w,m,_)}function l(t,e){if(w(e))return t.stylize("undefined","undefined");if(y(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}return b(e)?t.stylize(""+e,"number"):g(e)?t.stylize(""+e,"boolean"):v(e)?t.stylize("null","null"):void 0}function h(t){return"["+Error.prototype.toString.call(t)+"]"}function u(t,e,r,i,n){for(var o=[],a=0,s=e.length;a<s;++a)R(e,String(a))?o.push(f(t,e,r,i,String(a),!0)):o.push("");return n.forEach(function(n){n.match(/^\d+$/)||o.push(f(t,e,r,i,n,!0))}),o}function f(t,e,r,i,n,o){var a,s,l;if(l=Object.getOwnPropertyDescriptor(e,n)||{value:e[n]},l.get?s=l.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):l.set&&(s=t.stylize("[Setter]","special")),R(i,n)||(a="["+n+"]"),s||(t.seen.indexOf(l.value)<0?(s=v(r)?c(t,l.value,null):c(t,l.value,r-1),s.indexOf("\n")>-1&&(s=o?s.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+s.split("\n").map(function(t){return" "+t}).join("\n"))):s=t.stylize("[Circular]","special")),w(a)){if(o&&n.match(/^\d+$/))return s;a=JSON.stringify(""+n),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=t.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=t.stylize(a,"string"))}return a+": "+s}function d(t,e,r){var i=0;return t.reduce(function(t,e){return i++,e.indexOf("\n")>=0&&i++,t+e.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1]:r[0]+e+" "+t.join(", ")+" "+r[1]}function p(t){return Array.isArray(t)}function g(t){return"boolean"==typeof t}function v(t){return null===t}function m(t){return null==t}function b(t){return"number"==typeof t}function y(t){return"string"==typeof t}function _(t){return"symbol"==typeof t}function w(t){return void 0===t}function S(t){return x(t)&&"[object RegExp]"===P(t)}function x(t){return"object"==typeof t&&null!==t}function C(t){return x(t)&&"[object Date]"===P(t)}function A(t){return x(t)&&("[object Error]"===P(t)||t instanceof Error)}function T(t){return"function"==typeof t}function k(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t}function P(t){return Object.prototype.toString.call(t)}function E(t){return t<10?"0"+t.toString(10):t.toString(10)}function O(){var t=new Date,e=[E(t.getHours()),E(t.getMinutes()),E(t.getSeconds())].join(":");return[t.getDate(),j[t.getMonth()],e].join(" ")}function R(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var L=/%[sdj%]/g;e.format=function(t){if(!y(t)){for(var e=[],r=0;r<arguments.length;r++)e.push(n(arguments[r]));return e.join(" ")}for(var r=1,i=arguments,o=i.length,a=String(t).replace(L,function(t){if("%%"===t)return"%";if(r>=o)return t;switch(t){case"%s":return String(i[r++]);case"%d":return Number(i[r++]);case"%j":try{return JSON.stringify(i[r++])}catch(t){return"[Circular]"}default:return t}}),s=i[r];r<o;s=i[++r])v(s)||!x(s)?a+=" "+s:a+=" "+n(s);return a},e.deprecate=function(r,n){function o(){if(!a){if(i.throwDeprecation)throw new Error(n);i.traceDeprecation?console.trace(n):console.error(n),a=!0}return r.apply(this,arguments)}if(w(t.process))return function(){return e.deprecate(r,n).apply(this,arguments)};if(!0===i.noDeprecation)return r;var a=!1;return o};var D={},I;e.debuglog=function(t){if(w(I)&&(I=i.env.NODE_DEBUG||""),t=t.toUpperCase(),!D[t])if(new RegExp("\\b"+t+"\\b","i").test(I)){var r=i.pid;D[t]=function(){var i=e.format.apply(e,arguments);console.error("%s %d: %s",t,r,i)}}else D[t]=function(){};return D[t]},e.inspect=n,n.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},n.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},e.isArray=p,e.isBoolean=g,e.isNull=v,e.isNullOrUndefined=m,e.isNumber=b,e.isString=y,e.isSymbol=_,e.isUndefined=w,e.isRegExp=S,e.isObject=x,e.isDate=C,e.isError=A,e.isFunction=T,e.isPrimitive=k,e.isBuffer=r(58);var j=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];e.log=function(){console.log("%s - %s",O(),e.format.apply(e,arguments))},e.inherits=r(59),e._extend=function(t,e){if(!e||!x(e))return t;for(var r=Object.keys(e),i=r.length;i--;)t[r[i]]=e[r[i]];return t}}).call(e,r(0),r(1))},function(t,e,r){"use strict";function i(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}function n(t,e,r){if(t&&l.isObject(t)&&t instanceof i)return t;var n=new i;return n.parse(t,e,r),n}function o(t){return l.isString(t)&&(t=n(t)),t instanceof i?t.format():i.prototype.format.call(t)}function a(t,e){return n(t,!1,!0).resolve(e)}function s(t,e){return t?n(t,!1,!0).resolveObject(e):e}var c=r(66),l=r(68);e.parse=n,e.resolve=a,e.resolveObject=s,e.format=o,e.Url=i;var h=/^([a-z0-9.+-]+:)/i,u=/:[0-9]*$/,f=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,d=["<",">",'"',"`"," ","\r","\n","\t"],p=["{","}","|","\\","^","`"].concat(d),g=["'"].concat(p),v=["%","/","?",";","#"].concat(g),m=["/","?","#"],b=255,y=/^[+a-z0-9A-Z_-]{0,63}$/,_=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,w={javascript:!0,"javascript:":!0},S={javascript:!0,"javascript:":!0},x={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},C=r(69);i.prototype.parse=function(t,e,r){if(!l.isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var i=t.indexOf("?"),n=-1!==i&&i<t.indexOf("#")?"?":"#",o=t.split(n),a=/\\/g;o[0]=o[0].replace(a,"/"),t=o.join(n);var s=t;if(s=s.trim(),!r&&1===t.split("#").length){var u=f.exec(s);if(u)return this.path=s,this.href=s,this.pathname=u[1],u[2]?(this.search=u[2],this.query=e?C.parse(this.search.substr(1)):this.search.substr(1)):e&&(this.search="",this.query={}),this}var d=h.exec(s);if(d){d=d[0];var p=d.toLowerCase();this.protocol=p,s=s.substr(d.length)}if(r||d||s.match(/^\/\/[^@\/]+@[^@\/]+/)){var b="//"===s.substr(0,2);!b||d&&S[d]||(s=s.substr(2),this.slashes=!0)}if(!S[d]&&(b||d&&!x[d])){for(var A=-1,T=0;T<m.length;T++){var k=s.indexOf(m[T]);-1!==k&&(-1===A||k<A)&&(A=k)}var P,E;E=-1===A?s.lastIndexOf("@"):s.lastIndexOf("@",A),-1!==E&&(P=s.slice(0,E),s=s.slice(E+1),this.auth=decodeURIComponent(P)),A=-1;for(var T=0;T<v.length;T++){var k=s.indexOf(v[T]);-1!==k&&(-1===A||k<A)&&(A=k)}-1===A&&(A=s.length),this.host=s.slice(0,A),s=s.slice(A),this.parseHost(),this.hostname=this.hostname||"";var O="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!O)for(var R=this.hostname.split(/\./),T=0,L=R.length;T<L;T++){var D=R[T];if(D&&!D.match(y)){for(var I="",j=0,M=D.length;j<M;j++)D.charCodeAt(j)>127?I+="x":I+=D[j];if(!I.match(y)){var F=R.slice(0,T),N=R.slice(T+1),B=D.match(_);B&&(F.push(B[1]),N.unshift(B[2])),N.length&&(s="/"+N.join(".")+s),this.hostname=F.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),O||(this.hostname=c.toASCII(this.hostname));var U=this.port?":"+this.port:"",z=this.hostname||"";this.host=z+U,this.href+=this.host,O&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==s[0]&&(s="/"+s))}if(!w[p])for(var T=0,L=g.length;T<L;T++){var W=g[T];if(-1!==s.indexOf(W)){var q=encodeURIComponent(W);q===W&&(q=escape(W)),s=s.split(W).join(q)}}var X=s.indexOf("#");-1!==X&&(this.hash=s.substr(X),s=s.slice(0,X));var G=s.indexOf("?");if(-1!==G?(this.search=s.substr(G),this.query=s.substr(G+1),e&&(this.query=C.parse(this.query)),s=s.slice(0,G)):e&&(this.search="",this.query={}),s&&(this.pathname=s),x[p]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var U=this.pathname||"",H=this.search||"";this.path=U+H}return this.href=this.format(),this},i.prototype.format=function(){var t=this.auth||"";t&&(t=encodeURIComponent(t),t=t.replace(/%3A/i,":"),t+="@");var e=this.protocol||"",r=this.pathname||"",i=this.hash||"",n=!1,o="";this.host?n=t+this.host:this.hostname&&(n=t+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(n+=":"+this.port)),this.query&&l.isObject(this.query)&&Object.keys(this.query).length&&(o=C.stringify(this.query));var a=this.search||o&&"?"+o||"";return e&&":"!==e.substr(-1)&&(e+=":"),this.slashes||(!e||x[e])&&!1!==n?(n="//"+(n||""),r&&"/"!==r.charAt(0)&&(r="/"+r)):n||(n=""),i&&"#"!==i.charAt(0)&&(i="#"+i),a&&"?"!==a.charAt(0)&&(a="?"+a),r=r.replace(/[?#]/g,function(t){return encodeURIComponent(t)}),a=a.replace("#","%23"),e+n+r+a+i},i.prototype.resolve=function(t){return this.resolveObject(n(t,!1,!0)).format()},i.prototype.resolveObject=function(t){if(l.isString(t)){var e=new i;e.parse(t,!1,!0),t=e}for(var r=new i,n=Object.keys(this),o=0;o<n.length;o++){var a=n[o];r[a]=this[a]}if(r.hash=t.hash,""===t.href)return r.href=r.format(),r;if(t.slashes&&!t.protocol){for(var s=Object.keys(t),c=0;c<s.length;c++){var h=s[c];"protocol"!==h&&(r[h]=t[h])}return x[r.protocol]&&r.hostname&&!r.pathname&&(r.path=r.pathname="/"),r.href=r.format(),r}if(t.protocol&&t.protocol!==r.protocol){if(!x[t.protocol]){for(var u=Object.keys(t),f=0;f<u.length;f++){var d=u[f];r[d]=t[d]}return r.href=r.format(),r}if(r.protocol=t.protocol,t.host||S[t.protocol])r.pathname=t.pathname;else{for(var p=(t.pathname||"").split("/");p.length&&!(t.host=p.shift()););t.host||(t.host=""),t.hostname||(t.hostname=""),""!==p[0]&&p.unshift(""),p.length<2&&p.unshift(""),r.pathname=p.join("/")}if(r.search=t.search,r.query=t.query,r.host=t.host||"",r.auth=t.auth,r.hostname=t.hostname||t.host,r.port=t.port,r.pathname||r.search){var g=r.pathname||"",v=r.search||"";r.path=g+v}return r.slashes=r.slashes||t.slashes,r.href=r.format(),r}var m=r.pathname&&"/"===r.pathname.charAt(0),b=t.host||t.pathname&&"/"===t.pathname.charAt(0),y=b||m||r.host&&t.pathname,_=y,w=r.pathname&&r.pathname.split("/")||[],p=t.pathname&&t.pathname.split("/")||[],C=r.protocol&&!x[r.protocol];if(C&&(r.hostname="",r.port=null,r.host&&(""===w[0]?w[0]=r.host:w.unshift(r.host)),r.host="",t.protocol&&(t.hostname=null,t.port=null,t.host&&(""===p[0]?p[0]=t.host:p.unshift(t.host)),t.host=null),y=y&&(""===p[0]||""===w[0])),b)r.host=t.host||""===t.host?t.host:r.host,r.hostname=t.hostname||""===t.hostname?t.hostname:r.hostname,r.search=t.search,r.query=t.query,w=p;else if(p.length)w||(w=[]),w.pop(),w=w.concat(p),r.search=t.search,r.query=t.query;else if(!l.isNullOrUndefined(t.search)){if(C){r.hostname=r.host=w.shift();var A=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@");A&&(r.auth=A.shift(),r.host=r.hostname=A.shift())}return r.search=t.search,r.query=t.query,l.isNull(r.pathname)&&l.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!w.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var T=w.slice(-1)[0],k=(r.host||t.host||w.length>1)&&("."===T||".."===T)||""===T,P=0,E=w.length;E>=0;E--)T=w[E],"."===T?w.splice(E,1):".."===T?(w.splice(E,1),P++):P&&(w.splice(E,1),P--);if(!y&&!_)for(;P--;P)w.unshift("..");!y||""===w[0]||w[0]&&"/"===w[0].charAt(0)||w.unshift(""),k&&"/"!==w.join("/").substr(-1)&&w.push("");var O=""===w[0]||w[0]&&"/"===w[0].charAt(0);if(C){r.hostname=r.host=O?"":w.length?w.shift():"";var A=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@");A&&(r.auth=A.shift(),r.host=r.hostname=A.shift())}return y=y||r.host&&w.length,y&&!O&&w.unshift(""),w.length?r.pathname=w.join("/"):(r.pathname=null,r.path=null),l.isNull(r.pathname)&&l.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=t.auth||r.auth,r.slashes=r.slashes||t.slashes,r.href=r.format(),r},i.prototype.parseHost=function(){var t=this.host,e=u.exec(t);e&&(e=e[0],":"!==e&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)}},function(t,e,r){(function(t){var i=r(72),n=r(75),o=r(76),a=r(25),s=e;s.request=function(e,r){e="string"==typeof e?a.parse(e):n(e);var o=-1===t.location.protocol.search(/^https?:$/)?"http:":"",s=e.protocol||o,c=e.hostname||e.host,l=e.port,h=e.path||"/";c&&-1!==c.indexOf(":")&&(c="["+c+"]"),e.url=(c?s+"//"+c:"")+(l?":"+l:"")+h,e.method=(e.method||"GET").toUpperCase(),e.headers=e.headers||{};var u=new i(e);return r&&u.on("response",r),u},s.get=function t(e,r){var i=s.request(e,r);return i.end(),i},s.Agent=function(){},s.Agent.defaultMaxSockets=4,s.STATUS_CODES=o,s.METHODS=["CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REPORT","SEARCH","SUBSCRIBE","TRACE","UNLOCK","UNSUBSCRIBE"]}).call(e,r(0))},function(t,e,r){(function(t){function r(){if(void 0!==o)return o;if(t.XMLHttpRequest){o=new t.XMLHttpRequest;try{o.open("GET",t.XDomainRequest?"/":"https://example.com")}catch(t){o=null}}else o=null;return o}function i(t){var e=r();if(!e)return!1;try{return e.responseType=t,e.responseType===t}catch(t){}return!1}function n(t){return"function"==typeof t}e.fetch=n(t.fetch)&&n(t.ReadableStream),e.blobConstructor=!1;try{new Blob([new ArrayBuffer(1)]),e.blobConstructor=!0}catch(t){}var o,a=void 0!==t.ArrayBuffer,s=a&&n(t.ArrayBuffer.prototype.slice);e.arraybuffer=e.fetch||a&&i("arraybuffer"),e.msstream=!e.fetch&&s&&i("ms-stream"),e.mozchunkedarraybuffer=!e.fetch&&a&&i("moz-chunked-arraybuffer"),e.overrideMimeType=e.fetch||!!r()&&n(r().overrideMimeType),e.vbArray=n(t.VBArray),o=null}).call(e,r(0))},function(t,e){function r(t){throw new Error("Cannot find module '"+t+"'.")}r.keys=function(){return[]},r.resolve=r,t.exports=r,r.id=28},function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t){function e(e){return(0,l.getDocument)(e).then(function(e){return e.getPage(1).then(function(i){A=i,x=A.getViewport(1);var n=t.clientWidth/x.width/v;return x=A.getViewport(n),T.setDocument(e).then(function(){T.currentScale=n,r(x.width*v,x.height*v)})})})}function r(e,r){var i=document.createElement("canvas");i.id=s.default.generate(),i.width=e,i.height=r,t.appendChild(i),C=new h.fabric.Canvas(i.id),C.selection=!1,h.fabric.util.addListener(document.getElementsByClassName("upper-canvas")[0],"contextmenu",function(t){var e=C.getPointer(t),r=C.findTarget(t);w.emit("contextmenu",t,e,r),t.preventDefault()}),C.on("mouse:dblclick",function(t){var e=C.getPointer(t.e);w.emit("mouse:dblclick",t.e,e),t.e.preventDefault()}),C.on("mouse:up",function(t){var e=C.getPointer(t.e),r=C.findTarget(t.e);w.emit("mouse:up",t.e,e,r),t.e.preventDefault()}),C.on("mouse:down",function(t){var e=C.getPointer(t.e),r=C.findTarget(t.e);w.emit("mouse:down",t.e,e,r),t.e.preventDefault()}),C.on("mouse:wheel",function(t){var e=(0,p.default)(t.e).pixelY/3600;w.emit("mouse:wheel",t.e,e),t.e.preventDefault()}),C.on("object:selected",function(t){var e=t.target;w.emit("object:selected",e)})}function i(t,e){function r(e){return new Promise(function(r){h.fabric.Image.fromURL(e,function(e){e.top=t.y-e.height,e.left=t.x-e.width/2,e.topRate=t.y/x.height,e.leftRate=t.x/x.width,e.opacity=.85,e.hasControls=!1,e.hasRotatingPoint=!1;var i=b(t),n=o(i,2),s=n[0],c=n[1];e.pdfPoint={x:s,y:c},e.index=C.size(),e.on("moving",function(t){return y(t,e)}),Object.assign(e,a),C.add(e),r(e)})})}var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return e&&(w.pinImgURL=e),i.text?n(w.pinImgURL,i).then(r):r(w.pinImgURL)}function n(e,r){return new Promise(function(i){h.fabric.Image.fromURL(e,function(e){var n=document.createElement("canvas");n.id=s.default.generate(),n.width=e.width,n.height=e.height,n.style.display="none",t.appendChild(n);var o=new h.fabric.Canvas(n.id);e.left=0,e.top=0,o.add(e);var a=new h.fabric.Text(r.text,{fontSize:r.fontSize||20,fill:r.color||"red",fontFamily:r.fontFamily||"Comic Sans",fontWeight:r.fontWeight||"normal"});a.left=e.left+(e.width-a.width)/2,a.top=e.top+(e.height-a.height)/2.5,o.add(a),i(o.toDataURL()),o.dispose(),t.removeChild(n)})})}function a(t,e,r,n){var a=x.convertToViewportPoint(t.x,t.y),s=o(a,2);return i({x:s[0],y:s[1]},e,r,n)}function c(t,e,r,n,o){return i({x:t*x.width,y:e*x.height},r,n,o)}function u(t){var e=C.item(t);e&&(C.remove(e),e.text&&C.remove(e.text))}function d(t){}function m(t){var e=T.currentScale,r=e+t,i=r/e;T.currentScale=r,x=A.getViewport(r);var n=C.getHeight(),o=C.getWidth();C.setHeight(n*i),C.setWidth(o*i),C.getObjects().forEach(function(t){t.set("top",x.height*t.topRate-t.height),t.set("left",x.width*t.leftRate-t.width/2),t.setCoords()}),C.renderAll(),C.calcOffset()}function b(t){return x.convertToPdfPoint(t.x,t.y)}function y(t,e){e.topRate=(e.top+e.height)/x.height,e.leftRate=(e.left+e.width/2)/x.width;var r=b({x:e.left+e.width/2,y:e.top+e.height}),i=o(r,2),n=i[0],a=i[1];e.pdfPoint={x:n,y:a},e.setCoords(),w.emit("object:moving",e)}var _=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};f.default.call(this);var w=this;w.load=e,w.addPin=i,w.addPinWithRate=c,w.addPinWithPdfPoint=a,w.removePin=u,w.zoomIn=m,w.zoomOut=d,w.pinImgURL=_.pinImgURL||"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACEAAAAvCAYAAABt7qMfAAAJKklEQVRYR61YfXBU1RX/nfdYEoyQooKY7AappaWDBUuKu+8ljKGVFMpQsQOCfLT8g6NQC1ItVSvy0TLaGaso2kFrrJXWqSgWYaCIpZnKvrcJRGescawoluwGUygfgkCy+947nfNyN25eNiSLPX8l+84593fPPR+/ewn9lLZx40oyJSW1xHyjRzSeiCrAfBmASwCcB3ACzCkA/yTgjY5MZvc1TU2f9sc99aXUZprDM0AtmOcCqAZQ2pcNgM8AWABeYk3bVRGPH7mQTa8gmseOHThkyJBZRLSCmccDGBBw5IFIdp8GEAIwNK8O0Axgg55Ov1jW1HQuH5i8ID6qrCwdGArdC6IfAyjJMTzhh5v5gEf0HjE3a7p+ymUeogFjGLiWmScQIKCH5diliehZraNjVVlT03+DQHqAaJ04MeLp+noQzQeQ/d4C5hcBvBo6d+7dEe+8c7a38CYNY5DO/HWX6CYA4uOarC4RvaYxryyz7fdz7buB+Lim5ksDOjqeAzCzS4n576Tr94Xj8UQ/cqGbSso0r2Pm9QCm5myoPkQ0Z4RlHe0Cl/3j4LRpRcWnTq0GsFIZuGCuC2naL3INCgVyuLp6qOY4q0F0h8odcfFk6OzZldmIdkUiaZoLwPw0gEGixcCmQZp2z7B4/EyhCwf15YiIeR0TrVAbdBhYXmHbT4quD+JQNHplSNO2A5ioHOwNEd3aWwQYoLZJk65wHGeE53mleih0Jp3JtI1qaDhGgJcPtESEXPd5Amao78060fQyyzrsg2iJxRZJ9gLQAJz2PG/WyIaGPfmc/XvSpKt0x7kdwM0ARqhm1U7AUSbarmUyG8v370/ms02ZpsHMfwEw3P/O/JNIIvEEHauqGtzBvJmZv6+O4dGj6fTKbzU1ZYKOUqY53WNeS8A3cxItqNYM5lWRRGJr8INEMBWLrQKR5J5Ifcbz5lLSMGRHzwMYDOC4zlxblki8ledcJcMlWmU5304DkJy5NNBJjzGwrMK2pay7yRHDGOMCbwAoByCNbgmlTPMRZpaEEflHUVHR9OH19dJ2uyQVjYY9TdtGwAT1YyuYn9GI9njAUdK0K9jzagDcBmCUr0P0AZinR2z7w1xffhWePLkVRN/z1Zifo2QsthdEk5XihohtLw+ibzHNJcTsZ7LkDAM/qrBtOdtu0hqLyXD7U7ZbEvP94URC+kQ3SZrmajA/qH58W47jAwCjFfplEct6PNeCZ8/WW5PJzUwkA0yS6fFwcfFPqb7eCTr3z9wwHgAgZ05g3tk+dOgPRu/a1ZGrqwqhTuXVEQEhE+4qdJbWwohty0665GA0OqSYaDeIYgDOep43dWRDw74ggOz/qerq8ey6fwNwOYD3QkSTg6WejMWmgUgiORBAhyBvY+BKAC4xzwsnEi/lLiD1rXveHmauBHBSZ74xX+JmbZLR6GhoWr1K4EPkeTeEGxqEZ3RJi2kKL3kNQJG/btIwDgL4igq1X7e5BtLtAOwA8G0AGQLmh217S2+ROByNTtE0TXYpZKcxnU7XBslNyjQXMrNUJBHwH6mO15l5ijgl5qfCicTSHolkGAJMxjqIaA8c59ZwY+PxoJ7qOc8w8xz17YWwbS8KdtEW0/wVMd+ndA7IcaxlQJJJpNHT9akj9+07mSd80nyEWzCYf8e6vjqXMX0yadIwx3HuV2B1vwcQzYtY1iu5vhRNlKOQyIpspFRV1WT2vD+rsvqUNG1qcGwfqay8xA2FNoFoQY5Dm5lf1oAUE0liy/i/IdtJGdieSacXBo8iaRjfQGezktb9GYgWkU/jSkvrwCwERErw4XAicS/5g/Rz8bkm86MA5gWOwQUgO+8SATCA6E4ZTj2O1jRXgvkh9fuOds+b7w8wlSi/VwOs1dO0746Mx4UbdpPU9ddfzpomvV96RucQ6i4nQLTVyWQeGLV/f1vw4+Hq6i9rnrcLzF/190u0tMKynvJBHKmurnBd93UAX1OGD0Zse22eRcA1NQM+aW8f5wA1BIwB0aUgErr3ITyv/vSZM2+PbW6WmdBDkoaxDMBj6kOLpmm15fH4v7pITYth/IaAu5TCu47jTMm3m6BnBrTeOESurqKOOwEY6ve6sG0vFtvPQZjmRGJ+GUAFAGnJt0dsW6bm/0VShjGbgT8AKAZwjIjmhi1rrzjvRnQD5fo+ue5N4cZGmS1fSJKGIWP71SxzY+CxiG2vyCZ/dxCdfX+XmiWycK+5UQgqlQtSWbLecSKaEbYsO+ujGwg1BUVZEkjkI0/Xa0fu23eokEVzdVuqqsrI8/4KQPqDzx/KI5HFtGWLlLYvPS4/agBJd7y2U4PWhMvL1+UaFQIoZRjLGXhElf8hnXl2cADmvQYqErNRgTzFwNwK295dyOKi2xqLVXlEkuxCiGVDP49Y1sNBP/lBSAhddyeI5E4pXfQVp7h4waj6+vb+ApF+0ppOyzBbpGwOqrnU42h7vZW3xGJziGiTIrDnifmOcCIh47df0mIYM6mzJIVAnyei5WHLkstVD+kVhOwk2dHxLAE/zO4Enjc90tAg/OOCIsSYOy9T1ynFrU5R0fzeInnBR5IjsdgEl0icddJ8oifC5eV39ZWkKdP8JTPLWBc5zpp2c0U8/mZvyC8Iwi9Z03wIzD9TDo5pwMxy25ZXmLySjEbHQdd3gDmiFJ4Oh8NLLgS8z+cif3Lq+mZ1vRe/luY4c/Nd9dS4l2k8TQF4kzxvXpBjBtH3CUIMFDEVhiQ3LamW1ZFEYk3QWUsstoKIpCeIdMhDS5BZ5Qtfv0AI8SkdPHg9E8nFSAhMijRtdi4DU4xJ5kP2ZaZOT6fv7O2dKhdMv0CIQdIwLiOibcwsL3hCu+Ku48ySce8/hLjuH7PHwMBb0LQZfb3aZYH0G4R/LN1r32/pEctarY7h1ypK7SBaHLEsyaN+SUEg/C7Y3r6BiZaId7kzeMA6DbibgavVii84RUW3FdJdCwIhi6hHErnyC7MWEWonFx3xdcB13Vuubmz8uF8hUEoFgxC7lGF8hwGpltzX3XNMNK/CsrYVAkBFtFAT4EBlZWj4wIFrCLhHveLKZfq3TlHR3YUcw0UlZi5cuUmlS0rqCLhFngC8AQMWBG9u/d3eRR1H1nkyFqsBkbzILQ3btlyaL0r+B7tw5ax4J5d3AAAAAElFTkSuQmCC";var S=document.createElement("div");S.id=s.default.generate(),S.style.position="absolute",t.appendChild(S);var x=null,C=null,A=null,T=new g({container:t,viewer:S})}Object.defineProperty(e,"__esModule",{value:!0});var o=function(){function t(t,e){var r=[],i=!0,n=!1,o=void 0;try{for(var a=t[Symbol.iterator](),s;!(i=(s=a.next()).done)&&(r.push(s.value),!e||r.length!==e);i=!0);}catch(t){n=!0,o=t}finally{try{!i&&a.return&&a.return()}finally{if(n)throw o}}return r}return function(e,r){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return t(e,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),a=r(30),s=i(a);r(38);var c=r(39),l=r(61),h=r(63),u=r(79),f=i(u),d=r(80),p=i(d);h.fabric.devicePixelRatio=1,c.PDFJS.disableTextLayer=!0;var g=c.PDFJS.PDFViewer,v=96/72;n.prototype=Object.create(f.default.prototype),n.prototype.constructor=n,e.default=n},function(t,e,r){"use strict";t.exports=r(31)},function(t,e,r){"use strict";function i(e){return s.seed(e),t.exports}function n(e){return f=e,t.exports}function o(t){return void 0!==t&&s.characters(t),s.shuffled()}function a(){return h(f)}var s=r(6),c=r(11),l=r(34),h=r(35),u=r(36),f=r(37)||0;t.exports=a,t.exports.generate=a,t.exports.seed=i,t.exports.worker=n,t.exports.characters=o,t.exports.decode=l,t.exports.isValid=u},function(t,e,r){"use strict";function i(){return(o=(9301*o+49297)%233280)/233280}function n(t){o=t}var o=1;t.exports={nextValue:i,seed:n}},function(t,e,r){"use strict";function i(){if(!n||!n.getRandomValues)return 48&Math.floor(256*Math.random());var t=new Uint8Array(1);return n.getRandomValues(t),48&t[0]}var n="object"==typeof window&&(window.crypto||window.msCrypto);t.exports=i},function(t,e,r){"use strict";function i(t){var e=n.shuffled();return{version:15&e.indexOf(t.substr(0,1)),worker:15&e.indexOf(t.substr(1,1))}}var n=r(6);t.exports=i},function(t,e,r){"use strict";function i(t){var e="",r=Math.floor(.001*(Date.now()-a));return r===l?c++:(c=0,l=r),e+=n(o.lookup,s),e+=n(o.lookup,t),c>0&&(e+=n(o.lookup,c)),e+=n(o.lookup,r)}var n=r(11),o=r(6),a=1459707606518,s=6,c,l;t.exports=i},function(t,e,r){"use strict";function i(t){if(!t||"string"!=typeof t||t.length<6)return!1;for(var e=n.characters(),r=t.length,i=0;i<r;i++)if(-1===e.indexOf(t[i]))return!1;return!0}var n=r(6);t.exports=i},function(t,e,r){"use strict";t.exports=0},function(t,e,r){(function(e){!function e(r,i){t.exports=i()}(this,function(){return function(t){function e(i){if(r[i])return r[i].exports;var n=r[i]={i:i,l:!1,exports:{}};return t[i].call(n.exports,n,n.exports,e),n.l=!0,n.exports}var r={};return e.m=t,e.c=r,e.i=function(t){return t},e.d=function(t,r,i){e.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var r=t&&t.__esModule?function e(){return t.default}:function e(){return t};return e.d(r,"a",r),r},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=1)}([function(t,r,i){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};if("undefined"==typeof PDFJS||!PDFJS.compatibilityChecked){var o="undefined"!=typeof window&&window.Math===Math?window:void 0!==e&&e.Math===Math?e:"undefined"!=typeof self&&self.Math===Math?self:void 0,a="undefined"!=typeof navigator&&navigator.userAgent||"",s=/Android/.test(a),c=/Android\s[0-2][^\d]/.test(a),l=/Android\s[0-4][^\d]/.test(a),h=a.indexOf("Chrom")>=0,u=/Chrome\/(39|40)\./.test(a),f=a.indexOf("CriOS")>=0,d=a.indexOf("Trident")>=0,p=/\b(iPad|iPhone|iPod)(?=;)/.test(a),g=a.indexOf("Opera")>=0,v=/Safari\//.test(a)&&!/(Chrome\/|Android\s)/.test(a),m="object"===("undefined"==typeof window?"undefined":n(window))&&"object"===("undefined"==typeof document?"undefined":n(document));"undefined"==typeof PDFJS&&(o.PDFJS={}),PDFJS.compatibilityChecked=!0,function t(){function e(t,e){return new c(this.slice(t,e))}function r(t,e){arguments.length<2&&(e=0);for(var r=0,i=t.length;r<i;++r,++e)this[e]=255&t[r]}function i(t,e){this.buffer=t,this.byteLength=t.length,this.length=e,s(this.length)}function a(t){return{get:function e(){var r=this.buffer,i=t<<2;return(r[i]|r[i+1]<<8|r[i+2]<<16|r[i+3]<<24)>>>0},set:function e(r){var i=this.buffer,n=t<<2;i[n]=255&r,i[n+1]=r>>8&255,i[n+2]=r>>16&255,i[n+3]=r>>>24&255}}}function s(t){for(;l<t;)Object.defineProperty(i.prototype,l,a(l)),l++}function c(t){var i,o,a;if("number"==typeof t)for(i=[],o=0;o<t;++o)i[o]=0;else if("slice"in t)i=t.slice(0);else for(i=[],o=0,a=t.length;o<a;++o)i[o]=t[o];return i.subarray=e,i.buffer=i,i.byteLength=i.length,i.set=r,"object"===(void 0===t?"undefined":n(t))&&t.buffer&&(i.buffer=t.buffer),i}if("undefined"!=typeof Uint8Array)return void 0===Uint8Array.prototype.subarray&&(Uint8Array.prototype.subarray=function t(e,r){return new Uint8Array(this.slice(e,r))},Float32Array.prototype.subarray=function t(e,r){return new Float32Array(this.slice(e,r))}),void("undefined"==typeof Float64Array&&(o.Float64Array=Float32Array));i.prototype=Object.create(null);var l=0;o.Uint8Array=c,o.Int8Array=c,o.Int32Array=c,o.Uint16Array=c,o.Float32Array=c,o.Float64Array=c,o.Uint32Array=function(){if(3===arguments.length){if(0!==arguments[1])throw new Error("offset !== 0 is not supported");return new i(arguments[0],arguments[2])}return c.apply(this,arguments)}}(),function t(){if(m&&window.CanvasPixelArray){var e=window.CanvasPixelArray.prototype;"buffer"in e||(Object.defineProperty(e,"buffer",{get:function t(){return this},enumerable:!1,configurable:!0}),Object.defineProperty(e,"byteLength",{get:function t(){return this.length},enumerable:!1,configurable:!0}))}}(),function t(){o.URL||(o.URL=o.webkitURL)}(),function t(){if(void 0!==Object.defineProperty){var e=!0;try{m&&Object.defineProperty(new Image,"id",{value:"test"});var r=function t(){};r.prototype={get id(){}},Object.defineProperty(new r,"id",{value:"",configurable:!0,enumerable:!0,writable:!1})}catch(t){e=!1}if(e)return}Object.defineProperty=function t(e,r,i){delete e[r],"get"in i&&e.__defineGetter__(r,i.get),"set"in i&&e.__defineSetter__(r,i.set),"value"in i&&(e.__defineSetter__(r,function t(e){return this.__defineGetter__(r,function t(){return e}),e}),e[r]=i.value)}}(),function t(){if("undefined"!=typeof XMLHttpRequest){var e=XMLHttpRequest.prototype,r=new XMLHttpRequest;if("overrideMimeType"in r||Object.defineProperty(e,"overrideMimeType",{value:function t(e){}}),!("responseType"in r)){if(Object.defineProperty(e,"responseType",{get:function t(){return this._responseType||"text"},set:function t(e){"text"!==e&&"arraybuffer"!==e||(this._responseType=e,"arraybuffer"===e&&"function"==typeof this.overrideMimeType&&this.overrideMimeType("text/plain; charset=x-user-defined"))}}),"undefined"!=typeof VBArray)return void Object.defineProperty(e,"response",{get:function t(){return"arraybuffer"===this.responseType?new Uint8Array(new VBArray(this.responseBody).toArray()):this.responseText}});Object.defineProperty(e,"response",{get:function t(){if("arraybuffer"!==this.responseType)return this.responseText;var e=this.responseText,r,i=e.length,n=new Uint8Array(i);for(r=0;r<i;++r)n[r]=255&e.charCodeAt(r);return n.buffer}})}}}(),function t(){if(!("btoa"in o)){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";o.btoa=function(t){var r="",i,n;for(i=0,n=t.length;i<n;i+=3){var o=255&t.charCodeAt(i),a=255&t.charCodeAt(i+1),s=255&t.charCodeAt(i+2),c=o>>2,l=(3&o)<<4|a>>4,h=i+1<n?(15&a)<<2|s>>6:64,u=i+2<n?63&s:64;r+=e.charAt(c)+e.charAt(l)+e.charAt(h)+e.charAt(u)}return r}}}(),function t(){if(!("atob"in o)){o.atob=function(t){if(t=t.replace(/=+$/,""),t.length%4==1)throw new Error("bad atob input");for(var e=0,r,i,n=0,o="";i=t.charAt(n++);~i&&(r=e%4?64*r+i:i,e++%4)?o+=String.fromCharCode(255&r>>(-2*e&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return o}}}(),function t(){void 0===Function.prototype.bind&&(Function.prototype.bind=function t(e){var r=this,i=Array.prototype.slice.call(arguments,1);return function t(){var n=i.concat(Array.prototype.slice.call(arguments));return r.apply(e,n)}})}(),function t(){if(m){"dataset"in document.createElement("div")||Object.defineProperty(HTMLElement.prototype,"dataset",{get:function t(){if(this._dataset)return this._dataset;for(var e={},r=0,i=this.attributes.length;r<i;r++){var n=this.attributes[r];if("data-"===n.name.substring(0,5)){e[n.name.substring(5).replace(/\-([a-z])/g,function(t,e){return e.toUpperCase()})]=n.value}}return Object.defineProperty(this,"_dataset",{value:e,writable:!1,enumerable:!1}),e},enumerable:!0})}}(),function t(){function e(t,e,r,i){var n=t.className||"",o=n.split(/\s+/g);""===o[0]&&o.shift();var a=o.indexOf(e);return a<0&&r&&o.push(e),a>=0&&i&&o.splice(a,1),t.className=o.join(" "),a>=0}if(m){if(!("classList"in document.createElement("div"))){var r={add:function t(r){e(this.element,r,!0,!1)},contains:function t(r){return e(this.element,r,!1,!1)},remove:function t(r){e(this.element,r,!1,!0)},toggle:function t(r){e(this.element,r,!0,!0)}};Object.defineProperty(HTMLElement.prototype,"classList",{get:function t(){if(this._classList)return this._classList;var e=Object.create(r,{element:{value:this,writable:!1,enumerable:!0}});return Object.defineProperty(this,"_classList",{value:e,writable:!1,enumerable:!1}),e},enumerable:!0})}}}(),function t(){if(!("undefined"==typeof importScripts||"console"in o)){var e={},r={log:function t(){var e=Array.prototype.slice.call(arguments);o.postMessage({targetName:"main",action:"console_log",data:e})},error:function t(){var e=Array.prototype.slice.call(arguments);o.postMessage({targetName:"main",action:"console_error",data:e})},time:function t(r){e[r]=Date.now()},timeEnd:function t(r){var i=e[r];if(!i)throw new Error("Unknown timer name "+r);this.log("Timer:",r,Date.now()-i)}};o.console=r}}(),function t(){if(m)"console"in window?"bind"in console.log||(console.log=function(t){return function(e){return t(e)}}(console.log),console.error=function(t){return function(e){return t(e)}}(console.error),console.warn=function(t){return function(e){return t(e)}}(console.warn)):window.console={log:function t(){},error:function t(){},warn:function t(){}}}(),function t(){function e(t){r(t.target)&&t.stopPropagation()}function r(t){return t.disabled||t.parentNode&&r(t.parentNode)}g&&document.addEventListener("click",e,!0)}(),function t(){(d||f)&&(PDFJS.disableCreateObjectURL=!0)}(),function t(){"undefined"!=typeof navigator&&("language"in navigator||(PDFJS.locale=navigator.userLanguage||"en-US"))}(),function t(){(v||c||u||p)&&(PDFJS.disableRange=!0,PDFJS.disableStream=!0)}(),function t(){m&&(history.pushState&&!c||(PDFJS.disableHistory=!0))}(),function t(){if(m)if(window.CanvasPixelArray)"function"!=typeof window.CanvasPixelArray.prototype.set&&(window.CanvasPixelArray.prototype.set=function(t){for(var e=0,r=this.length;e<r;e++)this[e]=t[e]});else{var e=!1,r;if(h?(r=a.match(/Chrom(e|ium)\/([0-9]+)\./),e=r&&parseInt(r[2])<21):s?e=l:v&&(r=a.match(/Version\/([0-9]+)\.([0-9]+)\.([0-9]+) Safari\//),e=r&&parseInt(r[1])<6),e){var i=window.CanvasRenderingContext2D.prototype,n=i.createImageData;i.createImageData=function(t,e){var r=n.call(this,t,e);return r.data.set=function(t){for(var e=0,r=this.length;e<r;e++)this[e]=t[e]},r},i=null}}}(),function t(){function e(){window.requestAnimationFrame=function(t){return window.setTimeout(t,20)},window.cancelAnimationFrame=function(t){window.clearTimeout(t)}}if(m)p?e():"requestAnimationFrame"in window||(window.requestAnimationFrame=window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame,window.requestAnimationFrame||e())}(),function t(){(p||s)&&(PDFJS.maxCanvasPixels=5242880)}(),function t(){m&&d&&window.parent!==window&&(PDFJS.disableFullscreen=!0)}(),function t(){m&&("currentScript"in document||Object.defineProperty(document,"currentScript",{get:function t(){var e=document.getElementsByTagName("script");return e[e.length-1]},enumerable:!0,configurable:!0}))}(),function t(){if(m){var e=document.createElement("input");try{e.type="number"}catch(t){var r=e.constructor.prototype,i=Object.getOwnPropertyDescriptor(r,"type");Object.defineProperty(r,"type",{get:function t(){return i.get.call(this)},set:function t(e){i.set.call(this,"number"===e?"text":e)},enumerable:!0,configurable:!0})}}}(),function t(){if(m&&document.attachEvent){var e=document.constructor.prototype,r=Object.getOwnPropertyDescriptor(e,"readyState");Object.defineProperty(e,"readyState",{get:function t(){var e=r.get.call(this);return"interactive"===e?"loading":e},set:function t(e){r.set.call(this,e)},enumerable:!0,configurable:!0})}}(),function t(){m&&void 0===Element.prototype.remove&&(Element.prototype.remove=function(){this.parentNode&&this.parentNode.removeChild(this)})}(),function t(){Number.isNaN||(Number.isNaN=function(t){return"number"==typeof t&&isNaN(t)})}(),function t(){Number.isInteger||(Number.isInteger=function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t})}(),function t(){if(o.Promise)return"function"!=typeof o.Promise.all&&(o.Promise.all=function(t){var e=0,r=[],i,n,a=new o.Promise(function(t,e){i=t,n=e});return t.forEach(function(t,o){e++,t.then(function(t){r[o]=t,0===--e&&i(r)},n)}),0===e&&i(r),a}),"function"!=typeof o.Promise.resolve&&(o.Promise.resolve=function(t){return new o.Promise(function(e){e(t)})}),"function"!=typeof o.Promise.reject&&(o.Promise.reject=function(t){return new o.Promise(function(e,r){r(t)})}),void("function"!=typeof o.Promise.prototype.catch&&(o.Promise.prototype.catch=function(t){return o.Promise.prototype.then(void 0,t)}));var e=0,r=1,i=2,n=500,a={handlers:[],running:!1,unhandledRejections:[],pendingRejectionCheck:!1,scheduleHandlers:function t(e){0!==e._status&&(this.handlers=this.handlers.concat(e._handlers),e._handlers=[],this.running||(this.running=!0,setTimeout(this.runHandlers.bind(this),0)))},runHandlers:function t(){for(var e=1,r=Date.now()+1;this.handlers.length>0;){var n=this.handlers.shift(),o=n.thisPromise._status,a=n.thisPromise._value;try{1===o?"function"==typeof n.onResolve&&(a=n.onResolve(a)):"function"==typeof n.onReject&&(a=n.onReject(a),o=1,n.thisPromise._unhandledRejection&&this.removeUnhandeledRejection(n.thisPromise))}catch(t){o=i,a=t}if(n.nextPromise._updateStatus(o,a),Date.now()>=r)break}if(this.handlers.length>0)return void setTimeout(this.runHandlers.bind(this),0);this.running=!1},addUnhandledRejection:function t(e){this.unhandledRejections.push({promise:e,time:Date.now()}),this.scheduleRejectionCheck()},removeUnhandeledRejection:function t(e){e._unhandledRejection=!1;for(var r=0;r<this.unhandledRejections.length;r++)this.unhandledRejections[r].promise===e&&(this.unhandledRejections.splice(r),r--)},scheduleRejectionCheck:function t(){var e=this;this.pendingRejectionCheck||(this.pendingRejectionCheck=!0,setTimeout(function(){e.pendingRejectionCheck=!1;for(var t=Date.now(),r=0;r<e.unhandledRejections.length;r++)if(t-e.unhandledRejections[r].time>500){var i=e.unhandledRejections[r].promise._value,n="Unhandled rejection: "+i;i.stack&&(n+="\n"+i.stack);try{throw new Error(n)}catch(t){console.warn(n)}e.unhandledRejections.splice(r),r--}e.unhandledRejections.length&&e.scheduleRejectionCheck()},500))}},s=function t(e){this._status=0,this._handlers=[];try{e.call(this,this._resolve.bind(this),this._reject.bind(this))}catch(t){this._reject(t)}};s.all=function t(e){function r(t){a._status!==i&&(l=[],o(t))}var n,o,a=new s(function(t,e){n=t,o=e}),c=e.length,l=[];if(0===c)return n(l),a;for(var h=0,u=e.length;h<u;++h){var f=e[h],d=function(t){return function(e){a._status!==i&&(l[t]=e,0===--c&&n(l))}}(h);s.isPromise(f)?f.then(d,r):d(f)}return a},s.isPromise=function t(e){return e&&"function"==typeof e.then},s.resolve=function t(e){return new s(function(t){t(e)})},s.reject=function t(e){return new s(function(t,r){r(e)})},s.prototype={_status:null,_value:null,_handlers:null,_unhandledRejection:null,_updateStatus:function t(e,r){if(1!==this._status&&this._status!==i){if(1===e&&s.isPromise(r))return void r.then(this._updateStatus.bind(this,1),this._updateStatus.bind(this,i));this._status=e,this._value=r,e===i&&0===this._handlers.length&&(this._unhandledRejection=!0,a.addUnhandledRejection(this)),a.scheduleHandlers(this)}},_resolve:function t(e){this._updateStatus(1,e)},_reject:function t(e){this._updateStatus(i,e)},then:function t(e,r){var i=new s(function(t,e){this.resolve=t,this.reject=e});return this._handlers.push({thisPromise:this,onResolve:e,onReject:r,nextPromise:i}),a.scheduleHandlers(this),i},catch:function t(e){return this.then(void 0,e)}},o.Promise=s}(),function t(){function e(){this.id="$weakmap"+r++}if(!o.WeakMap){var r=0;e.prototype={has:function t(e){return("object"===(void 0===e?"undefined":n(e))||"function"==typeof e)&&null!==e&&!!Object.getOwnPropertyDescriptor(e,this.id)},get:function t(e){return this.has(e)?e[this.id]:void 0},set:function t(e,r){Object.defineProperty(e,this.id,{value:r,enumerable:!1,configurable:!0})},delete:function t(e){delete e[this.id]}},o.WeakMap=e}}(),function t(){function e(t){return void 0!==d[t]}function r(){l.call(this),this._isInvalid=!0}function i(t){return""===t&&r.call(this),t.toLowerCase()}function a(t){var e=t.charCodeAt(0);return e>32&&e<127&&-1===[34,35,60,62,63,96].indexOf(e)?t:encodeURIComponent(t)}function s(t){var e=t.charCodeAt(0);return e>32&&e<127&&-1===[34,35,60,62,96].indexOf(e)?t:encodeURIComponent(t)}function c(t,n,o){function c(t){y.push(t)}var l=n||"scheme start",h=0,u="",f=!1,b=!1,y=[];t:for(;(t[h-1]!==g||0===h)&&!this._isInvalid;){var _=t[h];switch(l){case"scheme start":if(!_||!v.test(_)){if(n){c("Invalid scheme.");break t}u="",l="no scheme";continue}u+=_.toLowerCase(),l="scheme";break;case"scheme":if(_&&m.test(_))u+=_.toLowerCase();else{if(":"!==_){if(n){if(_===g)break t;c("Code point not allowed in scheme: "+_);break t}u="",h=0,l="no scheme";continue}if(this._scheme=u,u="",n)break t;e(this._scheme)&&(this._isRelative=!0),l="file"===this._scheme?"relative":this._isRelative&&o&&o._scheme===this._scheme?"relative or authority":this._isRelative?"authority first slash":"scheme data"}break;case"scheme data":"?"===_?(this._query="?",l="query"):"#"===_?(this._fragment="#",l="fragment"):_!==g&&"\t"!==_&&"\n"!==_&&"\r"!==_&&(this._schemeData+=a(_));break;case"no scheme":if(o&&e(o._scheme)){l="relative";continue}c("Missing scheme."),r.call(this);break;case"relative or authority":if("/"!==_||"/"!==t[h+1]){c("Expected /, got: "+_),l="relative";continue}l="authority ignore slashes";break;case"relative":if(this._isRelative=!0,"file"!==this._scheme&&(this._scheme=o._scheme),_===g){this._host=o._host,this._port=o._port,this._path=o._path.slice(),this._query=o._query,this._username=o._username,this._password=o._password;break t}if("/"===_||"\\"===_)"\\"===_&&c("\\ is an invalid code point."),l="relative slash";else if("?"===_)this._host=o._host,this._port=o._port,this._path=o._path.slice(),this._query="?",this._username=o._username,this._password=o._password,l="query";else{if("#"!==_){var w=t[h+1],S=t[h+2];("file"!==this._scheme||!v.test(_)||":"!==w&&"|"!==w||S!==g&&"/"!==S&&"\\"!==S&&"?"!==S&&"#"!==S)&&(this._host=o._host,this._port=o._port,this._username=o._username,this._password=o._password,this._path=o._path.slice(),this._path.pop()),l="relative path";continue}this._host=o._host,this._port=o._port,this._path=o._path.slice(),this._query=o._query,this._fragment="#",this._username=o._username,this._password=o._password,l="fragment"}break;case"relative slash":if("/"!==_&&"\\"!==_){"file"!==this._scheme&&(this._host=o._host,this._port=o._port,this._username=o._username,this._password=o._password),l="relative path";continue}"\\"===_&&c("\\ is an invalid code point."),l="file"===this._scheme?"file host":"authority ignore slashes";break;case"authority first slash":if("/"!==_){c("Expected '/', got: "+_),l="authority ignore slashes";continue}l="authority second slash";break;case"authority second slash":if(l="authority ignore slashes","/"!==_){c("Expected '/', got: "+_);continue}break;case"authority ignore slashes":if("/"!==_&&"\\"!==_){l="authority";continue}c("Expected authority, got: "+_);break;case"authority":if("@"===_){f&&(c("@ already seen."),u+="%40"),f=!0;for(var x=0;x<u.length;x++){var C=u[x];if("\t"!==C&&"\n"!==C&&"\r"!==C)if(":"!==C||null!==this._password){var A=a(C);null!==this._password?this._password+=A:this._username+=A}else this._password="";else c("Invalid whitespace in authority.")}u=""}else{if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_){h-=u.length,u="",l="host";continue}u+=_}break;case"file host":if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_){2!==u.length||!v.test(u[0])||":"!==u[1]&&"|"!==u[1]?0===u.length?l="relative path start":(this._host=i.call(this,u),u="",l="relative path start"):l="relative path";continue}"\t"===_||"\n"===_||"\r"===_?c("Invalid whitespace in file host."):u+=_;break;case"host":case"hostname":if(":"!==_||b){if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_){if(this._host=i.call(this,u),u="",l="relative path start",n)break t;continue}"\t"!==_&&"\n"!==_&&"\r"!==_?("["===_?b=!0:"]"===_&&(b=!1),u+=_):c("Invalid code point in host/hostname: "+_)}else if(this._host=i.call(this,u),u="",l="port","hostname"===n)break t;break;case"port":if(/[0-9]/.test(_))u+=_;else{if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_||n){if(""!==u){var T=parseInt(u,10);T!==d[this._scheme]&&(this._port=T+""),u=""}if(n)break t;l="relative path start";continue}"\t"===_||"\n"===_||"\r"===_?c("Invalid code point in port: "+_):r.call(this)}break;case"relative path start":if("\\"===_&&c("'\\' not allowed in path."),l="relative path","/"!==_&&"\\"!==_)continue;break;case"relative path":if(_!==g&&"/"!==_&&"\\"!==_&&(n||"?"!==_&&"#"!==_))"\t"!==_&&"\n"!==_&&"\r"!==_&&(u+=a(_));else{"\\"===_&&c("\\ not allowed in relative path.");var k;(k=p[u.toLowerCase()])&&(u=k),".."===u?(this._path.pop(),"/"!==_&&"\\"!==_&&this._path.push("")):"."===u&&"/"!==_&&"\\"!==_?this._path.push(""):"."!==u&&("file"===this._scheme&&0===this._path.length&&2===u.length&&v.test(u[0])&&"|"===u[1]&&(u=u[0]+":"),this._path.push(u)),u="","?"===_?(this._query="?",l="query"):"#"===_&&(this._fragment="#",l="fragment")}break;case"query":n||"#"!==_?_!==g&&"\t"!==_&&"\n"!==_&&"\r"!==_&&(this._query+=s(_)):(this._fragment="#",l="fragment");break;case"fragment":_!==g&&"\t"!==_&&"\n"!==_&&"\r"!==_&&(this._fragment+=_)}h++}}function l(){this._scheme="",this._schemeData="",this._username="",this._password=null,this._host="",this._port="",this._path=[],this._query="",this._fragment="",this._isInvalid=!1,this._isRelative=!1}function h(t,e){void 0===e||e instanceof h||(e=new h(String(e))),this._url=t,l.call(this);var r=t.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g,"");c.call(this,r,null,e)}var u=!1;try{if("function"==typeof URL&&"object"===n(URL.prototype)&&"origin"in URL.prototype){var f=new URL("b","http://a");f.pathname="c%20d",u="http://a/c%20d"===f.href}}catch(t){}if(!u){var d=Object.create(null);d.ftp=21,d.file=0,d.gopher=70,d.http=80,d.https=443,d.ws=80,d.wss=443;var p=Object.create(null);p["%2e"]=".",p[".%2e"]="..",p["%2e."]="..",p["%2e%2e"]="..";var g,v=/[a-zA-Z]/,m=/[a-zA-Z0-9\+\-\.]/;h.prototype={toString:function t(){return this.href},get href(){if(this._isInvalid)return this._url;var t="";return""===this._username&&null===this._password||(t=this._username+(null!==this._password?":"+this._password:"")+"@"),this.protocol+(this._isRelative?"//"+t+this.host:"")+this.pathname+this._query+this._fragment},set href(t){l.call(this),c.call(this,t)},get protocol(){return this._scheme+":"},set protocol(t){this._isInvalid||c.call(this,t+":","scheme start")},get host(){return this._isInvalid?"":this._port?this._host+":"+this._port:this._host},set host(t){!this._isInvalid&&this._isRelative&&c.call(this,t,"host")},get hostname(){return this._host},set hostname(t){!this._isInvalid&&this._isRelative&&c.call(this,t,"hostname")},get port(){return this._port},set port(t){!this._isInvalid&&this._isRelative&&c.call(this,t,"port")},get pathname(){return this._isInvalid?"":this._isRelative?"/"+this._path.join("/"):this._schemeData},set pathname(t){!this._isInvalid&&this._isRelative&&(this._path=[],c.call(this,t,"relative path start"))},get search(){return this._isInvalid||!this._query||"?"===this._query?"":this._query},set search(t){!this._isInvalid&&this._isRelative&&(this._query="?","?"===t[0]&&(t=t.slice(1)),c.call(this,t,"query"))},get hash(){return this._isInvalid||!this._fragment||"#"===this._fragment?"":this._fragment},set hash(t){this._isInvalid||(this._fragment="#","#"===t[0]&&(t=t.slice(1)),c.call(this,t,"fragment"))},get origin(){var t;if(this._isInvalid||!this._scheme)return"";switch(this._scheme){case"data":case"file":case"javascript":case"mailto":return"null";case"blob":try{return new h(this._schemeData).origin||"null"}catch(t){}return"null"}return t=this.host,t?this._scheme+"://"+t:""}};var b=o.URL;b&&(h.createObjectURL=function(t){return b.createObjectURL.apply(b,arguments)},h.revokeObjectURL=function(t){b.revokeObjectURL(t)}),o.URL=h}}()}},function(t,e,r){"use strict";r(0)}])})}).call(e,r(0))},function(t,e,r){!function e(r,i){t.exports=i()}(this,function(){return function(t){function e(i){if(r[i])return r[i].exports;var n=r[i]={i:i,l:!1,exports:{}};return t[i].call(n.exports,n,n.exports,e),n.l=!0,n.exports}var r={};return e.m=t,e.c=r,e.i=function(t){return t},e.d=function(t,r,i){e.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var r=t&&t.__esModule?function e(){return t.default}:function e(){return t};return e.d(r,"a",r),r},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=14)}([function(t,e,i){"use strict";var n;n="undefined"!=typeof window&&window["pdfjs-dist/build/pdf"]?window["pdfjs-dist/build/pdf"]:r(12),t.exports=n},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){return e?t.replace(/\{\{\s*(\w+)\s*\}\}/g,function(t,r){return r in e?e[r]:"{{"+r+"}}"}):t}function o(t){var e=window.devicePixelRatio||1,r=t.webkitBackingStorePixelRatio||t.mozBackingStorePixelRatio||t.msBackingStorePixelRatio||t.oBackingStorePixelRatio||t.backingStorePixelRatio||1,i=e/r;return{sx:i,sy:i,scaled:1!==i}}function a(t,e){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=t.offsetParent;if(!i)return void console.error("offsetParent is not set -- cannot scroll");for(var n=t.offsetTop+t.clientTop,o=t.offsetLeft+t.clientLeft;i.clientHeight===i.scrollHeight||r&&"hidden"===getComputedStyle(i).overflow;)if(i.dataset._scaleY&&(n/=i.dataset._scaleY,o/=i.dataset._scaleX),n+=i.offsetTop,o+=i.offsetLeft,!(i=i.offsetParent))return;e&&(void 0!==e.top&&(n+=e.top),void 0!==e.left&&(o+=e.left,i.scrollLeft=o)),i.scrollTop=n}function s(t,e){var r=function r(o){n||(n=window.requestAnimationFrame(function r(){n=null;var o=t.scrollTop,a=i.lastY;o!==a&&(i.down=o>a),i.lastY=o,e(i)}))},i={down:!0,lastY:t.scrollTop,_eventHandler:r},n=null;return t.addEventListener("scroll",r,!0),i}function c(t){for(var e=t.split("&"),r=Object.create(null),i=0,n=e.length;i<n;++i){var o=e[i].split("="),a=o[0].toLowerCase(),s=o.length>1?o[1]:null;r[decodeURIComponent(a)]=decodeURIComponent(s)}return r}function l(t,e){var r=0,i=t.length-1;if(0===t.length||!e(t[i]))return t.length;if(e(t[r]))return r;for(;r<i;){var n=r+i>>1;e(t[n])?i=n:r=n+1}return r}function h(t){if(Math.floor(t)===t)return[t,1];var e=1/t,r=8;if(e>8)return[1,8];if(Math.floor(e)===e)return[1,e];for(var i=t>1?e:t,n=0,o=1,a=1,s=1;;){var c=n+a,l=o+s;if(l>8)break;i<=c/l?(a=c,s=l):(n=c,o=l)}var h=void 0;return h=i-n/o<a/s-i?i===t?[n,o]:[o,n]:i===t?[a,s]:[s,a]}function u(t,e){var r=t%e;return 0===r?t:Math.round(t-r+e)}function f(t,e){function r(t){var e=t.div;return e.offsetTop+e.clientTop+e.clientHeight>n}for(var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=t.scrollTop,o=n+t.clientHeight,a=t.scrollLeft,s=a+t.clientWidth,c=[],h=void 0,u=void 0,f=void 0,d=void 0,p=void 0,g=void 0,v=void 0,m=void 0,b=0===e.length?0:l(e,r),y=b,_=e.length;y<_&&(h=e[y],u=h.div,f=u.offsetTop+u.clientTop,d=u.clientHeight,!(f>o));y++)v=u.offsetLeft+u.clientLeft,m=u.clientWidth,v+m<a||v>s||(p=Math.max(0,n-f)+Math.max(0,f+d-o),g=100*(d-p)/d|0,c.push({id:h.id,x:v,y:f,view:h,percent:g}));var w=c[0],S=c[c.length-1];return i&&c.sort(function(t,e){var r=t.percent-e.percent;return Math.abs(r)>.001?-r:t.id-e.id}),{first:w,last:S,views:c}}function d(t){t.preventDefault()}function p(t){for(var e=0,r=t.length;e<r&&""===t[e].trim();)e++;return"data:"===t.substr(e,5).toLowerCase()}function g(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"document.pdf";if(p(t))return console.warn('getPDFFileNameFromURL: ignoring "data:" URL for performance reasons.'),e;var r=/^(?:(?:[^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/,i=/[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i,n=r.exec(t),o=i.exec(n[1])||i.exec(n[2])||i.exec(n[3]);if(o&&(o=o[0],-1!==o.indexOf("%")))try{o=i.exec(decodeURIComponent(o))[0]}catch(t){}return o||e}function v(t){var e=Math.sqrt(t.deltaX*t.deltaX+t.deltaY*t.deltaY),r=Math.atan2(t.deltaY,t.deltaX);-.25*Math.PI<r&&r<.75*Math.PI&&(e=-e);var i=0,n=1,o=30,a=30;return 0===t.deltaMode?e/=900:1===t.deltaMode&&(e/=30),e}function m(t){var e=Object.create(null);for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e}function b(t,e,r){return Math.min(Math.max(t,e),r)}Object.defineProperty(e,"__esModule",{value:!0}),e.localized=e.animationStarted=e.normalizeWheelEventDelta=e.binarySearchFirstItem=e.watchScroll=e.scrollIntoView=e.getOutputScale=e.approximateFraction=e.roundToDivide=e.getVisibleElements=e.parseQueryString=e.noContextMenuHandler=e.getPDFFileNameFromURL=e.ProgressBar=e.EventBus=e.NullL10n=e.mozL10n=e.RendererType=e.cloneObj=e.VERTICAL_PADDING=e.SCROLLBAR_PADDING=e.MAX_AUTO_SCALE=e.UNKNOWN_SCALE=e.MAX_SCALE=e.MIN_SCALE=e.DEFAULT_SCALE=e.DEFAULT_SCALE_VALUE=e.CSS_UNITS=void 0;var y=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),_=r(0),w=96/72,S="auto",x=1,C=.25,A=10,T=0,k=1.25,P=40,E=5,O={CANVAS:"canvas",SVG:"svg"},R={get:function t(e,r,i){return Promise.resolve(n(i,r))},translate:function t(e){return Promise.resolve()}};_.PDFJS.disableFullscreen=void 0!==_.PDFJS.disableFullscreen&&_.PDFJS.disableFullscreen,_.PDFJS.useOnlyCssZoom=void 0!==_.PDFJS.useOnlyCssZoom&&_.PDFJS.useOnlyCssZoom,_.PDFJS.maxCanvasPixels=void 0===_.PDFJS.maxCanvasPixels?16777216:_.PDFJS.maxCanvasPixels,_.PDFJS.disableHistory=void 0!==_.PDFJS.disableHistory&&_.PDFJS.disableHistory,_.PDFJS.disableTextLayer=void 0!==_.PDFJS.disableTextLayer&&_.PDFJS.disableTextLayer,_.PDFJS.ignoreCurrentPositionOnZoom=void 0!==_.PDFJS.ignoreCurrentPositionOnZoom&&_.PDFJS.ignoreCurrentPositionOnZoom,_.PDFJS.locale=void 0===_.PDFJS.locale&&"undefined"!=typeof navigator?navigator.language:_.PDFJS.locale;var L=new Promise(function(t){window.requestAnimationFrame(t)}),D=void 0,I=Promise.resolve(),j=function(){function t(){i(this,t),this._listeners=Object.create(null)}return y(t,[{key:"on",value:function t(e,r){var i=this._listeners[e];i||(i=[],this._listeners[e]=i),i.push(r)}},{key:"off",value:function t(e,r){var i=this._listeners[e],n=void 0;!i||(n=i.indexOf(r))<0||i.splice(n,1)}},{key:"dispatch",value:function t(e){var r=this._listeners[e];if(r&&0!==r.length){var i=Array.prototype.slice.call(arguments,1);r.slice(0).forEach(function(t){t.apply(null,i)})}}}]),t}(),M=function(){function t(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=r.height,o=r.width,a=r.units;i(this,t),this.visible=!0,this.div=document.querySelector(e+" .progress"),this.bar=this.div.parentNode,this.height=n||100,this.width=o||100,this.units=a||"%",this.div.style.height=this.height+this.units,this.percent=0}return y(t,[{key:"_updateBar",value:function t(){if(this._indeterminate)return this.div.classList.add("indeterminate"),void(this.div.style.width=this.width+this.units);this.div.classList.remove("indeterminate");var e=this.width*this._percent/100;this.div.style.width=e+this.units}},{key:"setWidth",value:function t(e){if(e){var r=e.parentNode,i=r.offsetWidth-e.offsetWidth;i>0&&this.bar.setAttribute("style","width: calc(100% - "+i+"px);")}}},{key:"hide",value:function t(){this.visible&&(this.visible=!1,this.bar.classList.add("hidden"),document.body.classList.remove("loadingInProgress"))}},{key:"show",value:function t(){this.visible||(this.visible=!0,document.body.classList.add("loadingInProgress"),this.bar.classList.remove("hidden"))}},{key:"percent",get:function t(){return this._percent},set:function t(e){this._indeterminate=isNaN(e),this._percent=b(e,0,100),this._updateBar()}}]),t}();e.CSS_UNITS=96/72,e.DEFAULT_SCALE_VALUE="auto",e.DEFAULT_SCALE=1,e.MIN_SCALE=.25,e.MAX_SCALE=10,e.UNKNOWN_SCALE=0,e.MAX_AUTO_SCALE=1.25,e.SCROLLBAR_PADDING=40,e.VERTICAL_PADDING=5,e.cloneObj=m,e.RendererType=O,e.mozL10n=void 0,e.NullL10n=R,e.EventBus=j,e.ProgressBar=M,e.getPDFFileNameFromURL=g,e.noContextMenuHandler=d,e.parseQueryString=c,e.getVisibleElements=f,e.roundToDivide=u,e.approximateFraction=h,e.getOutputScale=o,e.scrollIntoView=a,e.watchScroll=s,e.binarySearchFirstItem=l,e.normalizeWheelEventDelta=v,e.animationStarted=L,e.localized=I},function(t,e,r){"use strict";function i(t){t.on("documentload",function(){var t=document.createEvent("CustomEvent");t.initCustomEvent("documentload",!0,!0,{}),window.dispatchEvent(t)}),t.on("pagerendered",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("pagerendered",!0,!0,{pageNumber:t.pageNumber,cssTransform:t.cssTransform}),t.source.div.dispatchEvent(e)}),t.on("textlayerrendered",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("textlayerrendered",!0,!0,{pageNumber:t.pageNumber}),t.source.textLayerDiv.dispatchEvent(e)}),t.on("pagechange",function(t){var e=document.createEvent("UIEvents");e.initUIEvent("pagechange",!0,!0,window,0),e.pageNumber=t.pageNumber,t.source.container.dispatchEvent(e)}),t.on("pagesinit",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("pagesinit",!0,!0,null),t.source.container.dispatchEvent(e)}),t.on("pagesloaded",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("pagesloaded",!0,!0,{pagesCount:t.pagesCount}),t.source.container.dispatchEvent(e)}),t.on("scalechange",function(t){var e=document.createEvent("UIEvents");e.initUIEvent("scalechange",!0,!0,window,0),e.scale=t.scale,e.presetValue=t.presetValue,t.source.container.dispatchEvent(e)}),t.on("updateviewarea",function(t){var e=document.createEvent("UIEvents");e.initUIEvent("updateviewarea",!0,!0,window,0),e.location=t.location,t.source.container.dispatchEvent(e)}),t.on("find",function(t){if(t.source!==window){var e=document.createEvent("CustomEvent");e.initCustomEvent("find"+t.type,!0,!0,{query:t.query,phraseSearch:t.phraseSearch,caseSensitive:t.caseSensitive,highlightAll:t.highlightAll,findPrevious:t.findPrevious}),window.dispatchEvent(e)}}),t.on("attachmentsloaded",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("attachmentsloaded",!0,!0,{attachmentsCount:t.attachmentsCount}),t.source.container.dispatchEvent(e)}),t.on("sidebarviewchanged",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("sidebarviewchanged",!0,!0,{view:t.view}),t.source.outerContainer.dispatchEvent(e)}),t.on("pagemode",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("pagemode",!0,!0,{mode:t.mode}),t.source.pdfViewer.container.dispatchEvent(e)}),t.on("namedaction",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("namedaction",!0,!0,{action:t.action}),t.source.pdfViewer.container.dispatchEvent(e)}),t.on("presentationmodechanged",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("presentationmodechanged",!0,!0,{active:t.active,switchInProgress:t.switchInProgress}),window.dispatchEvent(e)}),t.on("outlineloaded",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("outlineloaded",!0,!0,{outlineCount:t.outlineCount}),t.source.container.dispatchEvent(e)})}function n(){return a||(a=new o.EventBus,i(a),a)}Object.defineProperty(e,"__esModule",{value:!0}),e.getGlobalEventBus=e.attachDOMEventsToEventBus=void 0;var o=r(1),a=null;e.attachDOMEventsToEventBus=i,e.getGlobalEventBus=n},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t){if(!(t instanceof Array))return!1;var e=t.length,r=!0;if(e<2)return!1;var i=t[0];if(!("object"===(void 0===i?"undefined":o(i))&&"number"==typeof i.num&&(0|i.num)===i.num&&"number"==typeof i.gen&&(0|i.gen)===i.gen||"number"==typeof i&&(0|i)===i&&i>=0))return!1;var n=t[1];if("object"!==(void 0===n?"undefined":o(n))||"string"!=typeof n.name)return!1;switch(n.name){case"XYZ":if(5!==e)return!1;break;case"Fit":case"FitB":return 2===e;case"FitH":case"FitBH":case"FitV":case"FitBV":if(3!==e)return!1;break;case"FitR":if(6!==e)return!1;r=!1;break;default:return!1}for(var a=2;a<e;a++){var s=t[a];if(!("number"==typeof s||r&&null===s))return!1}return!0}Object.defineProperty(e,"__esModule",{value:!0}),e.SimpleLinkService=e.PDFLinkService=void 0;var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},a=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),s=r(2),c=r(1),l=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=e.eventBus;i(this,t),this.eventBus=r||(0,s.getGlobalEventBus)(),this.baseUrl=null,this.pdfDocument=null,this.pdfViewer=null,this.pdfHistory=null,this._pagesRefCache=null}return a(t,[{key:"setDocument",value:function t(e,r){this.baseUrl=r,this.pdfDocument=e,this._pagesRefCache=Object.create(null)}},{key:"setViewer",value:function t(e){this.pdfViewer=e}},{key:"setHistory",value:function t(e){this.pdfHistory=e}},{key:"navigateTo",value:function t(e){var r=this,i=function t(i){var n=i.namedDest,o=i.explicitDest,a=o[0],s=void 0;if(a instanceof Object){if(null===(s=r._cachedPageNumber(a)))return void r.pdfDocument.getPageIndex(a).then(function(e){r.cachePageRef(e+1,a),t({namedDest:n,explicitDest:o})}).catch(function(){console.error('PDFLinkService.navigateTo: "'+a+'" is not a valid page reference, for dest="'+e+'".')})}else{if((0|a)!==a)return void console.error('PDFLinkService.navigateTo: "'+a+'" is not a valid destination reference, for dest="'+e+'".');s=a+1}if(!s||s<1||s>r.pagesCount)return void console.error('PDFLinkService.navigateTo: "'+s+'" is not a valid page number, for dest="'+e+'".');r.pdfViewer.scrollPageIntoView({pageNumber:s,destArray:o}),r.pdfHistory&&r.pdfHistory.push({dest:o,hash:n,page:s})};new Promise(function(t,i){if("string"==typeof e)return void r.pdfDocument.getDestination(e).then(function(r){t({namedDest:e,explicitDest:r})});t({namedDest:"",explicitDest:e})}).then(function(t){if(!(t.explicitDest instanceof Array))return void console.error('PDFLinkService.navigateTo: "'+t.explicitDest+'" is not a valid destination array, for dest="'+e+'".');i(t)})}},{key:"getDestinationHash",value:function t(e){if("string"==typeof e)return this.getAnchorUrl("#"+escape(e));if(e instanceof Array){var r=JSON.stringify(e);return this.getAnchorUrl("#"+escape(r))}return this.getAnchorUrl("")}},{key:"getAnchorUrl",value:function t(e){return(this.baseUrl||"")+e}},{key:"setHash",value:function t(e){var r=void 0,i=void 0;if(e.indexOf("=")>=0){var o=(0,c.parseQueryString)(e);if("search"in o&&this.eventBus.dispatch("findfromurlhash",{source:this,query:o.search.replace(/"/g,""),phraseSearch:"true"===o.phrase}),"nameddest"in o)return this.pdfHistory&&this.pdfHistory.updateNextHashParam(o.nameddest),void this.navigateTo(o.nameddest);if("page"in o&&(r=0|o.page||1),"zoom"in o){var a=o.zoom.split(","),s=a[0],l=parseFloat(s);-1===s.indexOf("Fit")?i=[null,{name:"XYZ"},a.length>1?0|a[1]:null,a.length>2?0|a[2]:null,l?l/100:s]:"Fit"===s||"FitB"===s?i=[null,{name:s}]:"FitH"===s||"FitBH"===s||"FitV"===s||"FitBV"===s?i=[null,{name:s},a.length>1?0|a[1]:null]:"FitR"===s?5!==a.length?console.error('PDFLinkService.setHash: Not enough parameters for "FitR".'):i=[null,{name:s},0|a[1],0|a[2],0|a[3],0|a[4]]:console.error('PDFLinkService.setHash: "'+s+'" is not a valid zoom value.')}i?this.pdfViewer.scrollPageIntoView({pageNumber:r||this.page,destArray:i,allowNegativeOffset:!0}):r&&(this.page=r),"pagemode"in o&&this.eventBus.dispatch("pagemode",{source:this,mode:o.pagemode})}else{/^\d+$/.test(e)&&e<=this.pagesCount&&(console.warn('PDFLinkService_setHash: specifying a page number directly after the hash symbol (#) is deprecated, please use the "#page='+e+'" form instead.'),this.page=0|e),i=unescape(e);try{i=JSON.parse(i),i instanceof Array||(i=i.toString())}catch(t){}if("string"==typeof i||n(i))return this.pdfHistory&&this.pdfHistory.updateNextHashParam(i),void this.navigateTo(i);console.error('PDFLinkService.setHash: "'+unescape(e)+'" is not a valid destination.')}}},{key:"executeNamedAction",value:function t(e){switch(e){case"GoBack":this.pdfHistory&&this.pdfHistory.back();break;case"GoForward":this.pdfHistory&&this.pdfHistory.forward();break;case"NextPage":this.page<this.pagesCount&&this.page++;break;case"PrevPage":this.page>1&&this.page--;break;case"LastPage":this.page=this.pagesCount;break;case"FirstPage":this.page=1}this.eventBus.dispatch("namedaction",{source:this,action:e})}},{key:"onFileAttachmentAnnotation",value:function t(e){var r=e.id,i=e.filename,n=e.content;this.eventBus.dispatch("fileattachmentannotation",{source:this,id:r,filename:i,content:n})}},{key:"cachePageRef",value:function t(e,r){var i=r.num+" "+r.gen+" R";this._pagesRefCache[i]=e}},{key:"_cachedPageNumber",value:function t(e){var r=e.num+" "+e.gen+" R";return this._pagesRefCache&&this._pagesRefCache[r]||null}},{key:"pagesCount",get:function t(){return this.pdfDocument?this.pdfDocument.numPages:0}},{key:"page",get:function t(){return this.pdfViewer.currentPageNumber},set:function t(e){this.pdfViewer.currentPageNumber=e}}]),t}(),h=function(){function t(){i(this,t)}return a(t,[{key:"navigateTo",value:function t(e){}},{key:"getDestinationHash",value:function t(e){return"#"}},{key:"getAnchorUrl",value:function t(e){return"#"}},{key:"setHash",value:function t(e){}},{key:"executeNamedAction",value:function t(e){}},{key:"onFileAttachmentAnnotation",value:function t(e){var r=e.id,i=e.filename,n=e.content}},{key:"cachePageRef",value:function t(e,r){}},{key:"page",get:function t(){return 0},set:function t(e){}}]),t}();e.PDFLinkService=l,e.SimpleLinkService=h},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.DefaultAnnotationLayerFactory=e.AnnotationLayerBuilder=void 0;var n=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),o=r(0),a=r(1),s=r(3),c=function(){function t(e){var r=e.pageDiv,n=e.pdfPage,o=e.linkService,s=e.downloadManager,c=e.renderInteractiveForms,l=void 0!==c&&c,h=e.l10n,u=void 0===h?a.NullL10n:h;i(this,t),this.pageDiv=r,this.pdfPage=n,this.linkService=o,this.downloadManager=s,this.renderInteractiveForms=l,this.l10n=u,this.div=null}return n(t,[{key:"render",value:function t(e){var r=this,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"display";this.pdfPage.getAnnotations({intent:i}).then(function(t){var i={viewport:e.clone({dontFlip:!0}),div:r.div,annotations:t,page:r.pdfPage,renderInteractiveForms:r.renderInteractiveForms,linkService:r.linkService,downloadManager:r.downloadManager};if(r.div)o.AnnotationLayer.update(i);else{if(0===t.length)return;r.div=document.createElement("div"),r.div.className="annotationLayer",r.pageDiv.appendChild(r.div),i.div=r.div,o.AnnotationLayer.render(i),r.l10n.translate(r.div)}})}},{key:"hide",value:function t(){this.div&&this.div.setAttribute("hidden","true")}}]),t}(),l=function(){function t(){i(this,t)}return n(t,[{key:"createAnnotationLayerBuilder",value:function t(e,r){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:a.NullL10n;return new c({pageDiv:e,pdfPage:r,renderInteractiveForms:i,linkService:new s.SimpleLinkService,l10n:n})}}]),t}();e.AnnotationLayerBuilder=c,e.DefaultAnnotationLayerFactory=l},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.PDFPageView=void 0;var n=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),o=r(1),a=r(0),s=r(2),c=r(7),l=function(){function t(e){i(this,t);var r=e.container,n=e.defaultViewport;this.id=e.id,this.renderingId="page"+this.id,this.pageLabel=null,this.rotation=0,this.scale=e.scale||o.DEFAULT_SCALE,this.viewport=n,this.pdfPageRotate=n.rotation,this.hasRestrictedScaling=!1,this.enhanceTextSelection=e.enhanceTextSelection||!1,this.renderInteractiveForms=e.renderInteractiveForms||!1,this.eventBus=e.eventBus||(0,s.getGlobalEventBus)(),this.renderingQueue=e.renderingQueue,this.textLayerFactory=e.textLayerFactory,this.annotationLayerFactory=e.annotationLayerFactory,this.renderer=e.renderer||o.RendererType.CANVAS,this.l10n=e.l10n||o.NullL10n,this.paintTask=null,this.paintedViewportMap=new WeakMap,this.renderingState=c.RenderingStates.INITIAL,this.resume=null,this.error=null,this.onBeforeDraw=null,this.onAfterDraw=null,this.annotationLayer=null,this.textLayer=null,this.zoomLayer=null;var a=document.createElement("div");a.className="page",a.style.width=Math.floor(this.viewport.width)+"px",a.style.height=Math.floor(this.viewport.height)+"px",a.setAttribute("data-page-number",this.id),this.div=a,r.appendChild(a)}return n(t,[{key:"setPdfPage",value:function t(e){this.pdfPage=e,this.pdfPageRotate=e.rotate;var r=(this.rotation+this.pdfPageRotate)%360;this.viewport=e.getViewport(this.scale*o.CSS_UNITS,r),this.stats=e.stats,this.reset()}},{key:"destroy",value:function t(){this.reset(),this.pdfPage&&this.pdfPage.cleanup()}},{key:"_resetZoomLayer",value:function t(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(this.zoomLayer){var r=this.zoomLayer.firstChild;this.paintedViewportMap.delete(r),r.width=0,r.height=0,e&&this.zoomLayer.remove(),this.zoomLayer=null}}},{key:"reset",value:function t(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.cancelRendering();var i=this.div;i.style.width=Math.floor(this.viewport.width)+"px",i.style.height=Math.floor(this.viewport.height)+"px";for(var n=i.childNodes,o=e&&this.zoomLayer||null,a=r&&this.annotationLayer&&this.annotationLayer.div||null,s=n.length-1;s>=0;s--){var c=n[s];o!==c&&a!==c&&i.removeChild(c)}i.removeAttribute("data-loaded"),a?this.annotationLayer.hide():this.annotationLayer=null,o||(this.canvas&&(this.paintedViewportMap.delete(this.canvas),this.canvas.width=0,this.canvas.height=0,delete this.canvas),this._resetZoomLayer()),this.svg&&(this.paintedViewportMap.delete(this.svg),delete this.svg),this.loadingIconDiv=document.createElement("div"),this.loadingIconDiv.className="loadingIcon",i.appendChild(this.loadingIconDiv)}},{key:"update",value:function t(e,r){this.scale=e||this.scale,void 0!==r&&(this.rotation=r);var i=(this.rotation+this.pdfPageRotate)%360;if(this.viewport=this.viewport.clone({scale:this.scale*o.CSS_UNITS,rotation:i}),this.svg)return this.cssTransform(this.svg,!0),void this.eventBus.dispatch("pagerendered",{source:this,pageNumber:this.id,cssTransform:!0});var n=!1;if(this.canvas&&a.PDFJS.maxCanvasPixels>0){var s=this.outputScale;(Math.floor(this.viewport.width)*s.sx|0)*(Math.floor(this.viewport.height)*s.sy|0)>a.PDFJS.maxCanvasPixels&&(n=!0)}if(this.canvas){if(a.PDFJS.useOnlyCssZoom||this.hasRestrictedScaling&&n)return this.cssTransform(this.canvas,!0),void this.eventBus.dispatch("pagerendered",{source:this,pageNumber:this.id,cssTransform:!0});this.zoomLayer||this.canvas.hasAttribute("hidden")||(this.zoomLayer=this.canvas.parentNode,this.zoomLayer.style.position="absolute")}this.zoomLayer&&this.cssTransform(this.zoomLayer.firstChild),this.reset(!0,!0)}},{key:"cancelRendering",value:function t(){this.paintTask&&(this.paintTask.cancel(),this.paintTask=null),this.renderingState=c.RenderingStates.INITIAL,this.resume=null,this.textLayer&&(this.textLayer.cancel(),this.textLayer=null)}},{key:"cssTransform",value:function t(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=this.viewport.width,n=this.viewport.height,o=this.div;e.style.width=e.parentNode.style.width=o.style.width=Math.floor(i)+"px",e.style.height=e.parentNode.style.height=o.style.height=Math.floor(n)+"px";var s=this.viewport.rotation-this.paintedViewportMap.get(e).rotation,c=Math.abs(s),l=1,h=1;90!==c&&270!==c||(l=n/i,h=i/n);var t="rotate("+s+"deg) scale("+l+","+h+")";if(a.CustomStyle.setProp("transform",e,t),this.textLayer){var u=this.textLayer.viewport,f=this.viewport.rotation-u.rotation,d=Math.abs(f),p=i/u.width;90!==d&&270!==d||(p=i/u.height);var g=this.textLayer.textLayerDiv,v=void 0,m=void 0;switch(d){case 0:v=m=0;break;case 90:v=0,m="-"+g.style.height;break;case 180:v="-"+g.style.width,m="-"+g.style.height;break;case 270:v="-"+g.style.width,m=0;break;default:console.error("Bad rotation value.")}a.CustomStyle.setProp("transform",g,"rotate("+d+"deg) scale("+p+", "+p+") translate("+v+", "+m+")"),a.CustomStyle.setProp("transformOrigin",g,"0% 0%")}r&&this.annotationLayer&&this.annotationLayer.render(this.viewport,"display")}},{key:"getPagePoint",value:function t(e,r){return this.viewport.convertToPdfPoint(e,r)}},{key:"draw",value:function t(){var e=this;this.renderingState!==c.RenderingStates.INITIAL&&(console.error("Must be in new state before drawing"),this.reset()),this.renderingState=c.RenderingStates.RUNNING;var r=this.pdfPage,i=this.div,n=document.createElement("div");n.style.width=i.style.width,n.style.height=i.style.height,n.classList.add("canvasWrapper"),this.annotationLayer&&this.annotationLayer.div?i.insertBefore(n,this.annotationLayer.div):i.appendChild(n);var s=null;if(this.textLayerFactory){var l=document.createElement("div");l.className="textLayer",l.style.width=n.style.width,l.style.height=n.style.height,this.annotationLayer&&this.annotationLayer.div?i.insertBefore(l,this.annotationLayer.div):i.appendChild(l),s=this.textLayerFactory.createTextLayerBuilder(l,this.id-1,this.viewport,this.enhanceTextSelection)}this.textLayer=s;var h=null;this.renderingQueue&&(h=function t(r){if(!e.renderingQueue.isHighestPriority(e))return e.renderingState=c.RenderingStates.PAUSED,void(e.resume=function(){e.renderingState=c.RenderingStates.RUNNING,r()});r()});var u=function t(n){return f===e.paintTask&&(e.paintTask=null),"cancelled"===n||n instanceof a.RenderingCancelledException?(e.error=null,Promise.resolve(void 0)):(e.renderingState=c.RenderingStates.FINISHED,e.loadingIconDiv&&(i.removeChild(e.loadingIconDiv),delete e.loadingIconDiv),e._resetZoomLayer(!0),e.error=n,e.stats=r.stats,e.onAfterDraw&&e.onAfterDraw(),e.eventBus.dispatch("pagerendered",{source:e,pageNumber:e.id,cssTransform:!1}),n?Promise.reject(n):Promise.resolve(void 0))},f=this.renderer===o.RendererType.SVG?this.paintOnSvg(n):this.paintOnCanvas(n);f.onRenderContinue=h,this.paintTask=f;var d=f.promise.then(function(){return u(null).then(function(){if(s){var t=r.streamTextContent({normalizeWhitespace:!0});s.setTextContentStream(t),s.render()}})},function(t){return u(t)});return this.annotationLayerFactory&&(this.annotationLayer||(this.annotationLayer=this.annotationLayerFactory.createAnnotationLayerBuilder(i,r,this.renderInteractiveForms,this.l10n)),this.annotationLayer.render(this.viewport,"display")),i.setAttribute("data-loaded",!0),this.onBeforeDraw&&this.onBeforeDraw(),d}},{key:"paintOnCanvas",value:function t(e){var r=(0,a.createPromiseCapability)(),i={promise:r.promise,onRenderContinue:function t(e){e()},cancel:function t(){y.cancel()}},n=this.viewport,s=document.createElement("canvas");s.id=this.renderingId,s.setAttribute("hidden","hidden");var c=!0,l=function t(){c&&(s.removeAttribute("hidden"),c=!1)};e.appendChild(s),this.canvas=s,s.mozOpaque=!0;var h=s.getContext("2d",{alpha:!1}),u=(0,o.getOutputScale)(h);if(this.outputScale=u,a.PDFJS.useOnlyCssZoom){var f=n.clone({scale:o.CSS_UNITS});u.sx*=f.width/n.width,u.sy*=f.height/n.height,u.scaled=!0}if(a.PDFJS.maxCanvasPixels>0){var d=n.width*n.height,p=Math.sqrt(a.PDFJS.maxCanvasPixels/d);u.sx>p||u.sy>p?(u.sx=p,u.sy=p,u.scaled=!0,this.hasRestrictedScaling=!0):this.hasRestrictedScaling=!1}var g=(0,o.approximateFraction)(u.sx),v=(0,o.approximateFraction)(u.sy);s.width=(0,o.roundToDivide)(n.width*u.sx,g[0]),s.height=(0,o.roundToDivide)(n.height*u.sy,v[0]),s.style.width=(0,o.roundToDivide)(n.width,g[1])+"px",s.style.height=(0,o.roundToDivide)(n.height,v[1])+"px",this.paintedViewportMap.set(s,n);var m=u.scaled?[u.sx,0,0,u.sy,0,0]:null,b={canvasContext:h,transform:m,viewport:this.viewport,renderInteractiveForms:this.renderInteractiveForms},y=this.pdfPage.render(b);return y.onContinue=function(t){l(),i.onRenderContinue?i.onRenderContinue(t):t()},y.promise.then(function(){l(),r.resolve(void 0)},function(t){l(),r.reject(t)}),i}},{key:"paintOnSvg",value:function t(e){var r=this,i=!1,n=function t(){if(i)throw a.PDFJS.pdfjsNext?new a.RenderingCancelledException("Rendering cancelled, page "+r.id,"svg"):"cancelled"},s=this.pdfPage,l=this.viewport.clone({scale:o.CSS_UNITS});return{promise:s.getOperatorList().then(function(t){return n(),new a.SVGGraphics(s.commonObjs,s.objs).getSVG(t,l).then(function(t){n(),r.svg=t,r.paintedViewportMap.set(t,l),t.style.width=e.style.width,t.style.height=e.style.height,r.renderingState=c.RenderingStates.FINISHED,e.appendChild(t)})}),onRenderContinue:function t(e){e()},cancel:function t(){i=!0}}}},{key:"setPageLabel",value:function t(e){this.pageLabel="string"==typeof e?e:null,null!==this.pageLabel?this.div.setAttribute("data-page-label",this.pageLabel):this.div.removeAttribute("data-page-label")}},{key:"width",get:function t(){return this.viewport.width}},{key:"height",get:function t(){return this.viewport.height}}]),t}();e.PDFPageView=l},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.DefaultTextLayerFactory=e.TextLayerBuilder=void 0;var n=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),o=r(2),a=r(0),s=300,c=function(){function t(e){var r=e.textLayerDiv,n=e.eventBus,a=e.pageIndex,s=e.viewport,c=e.findController,l=void 0===c?null:c,h=e.enhanceTextSelection,u=void 0!==h&&h;i(this,t),this.textLayerDiv=r,this.eventBus=n||(0,o.getGlobalEventBus)(),this.textContent=null,this.textContentItemsStr=[],this.textContentStream=null,this.renderingDone=!1,this.pageIdx=a,this.pageNumber=this.pageIdx+1,this.matches=[],this.viewport=s,this.textDivs=[],this.findController=l,this.textLayerRenderTask=null,this.enhanceTextSelection=u,this._bindMouse()}return n(t,[{key:"_finishRendering",value:function t(){if(this.renderingDone=!0,!this.enhanceTextSelection){var e=document.createElement("div");e.className="endOfContent",this.textLayerDiv.appendChild(e)}this.eventBus.dispatch("textlayerrendered",{source:this,pageNumber:this.pageNumber,numTextDivs:this.textDivs.length})}},{key:"render",value:function t(){var e=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;if((this.textContent||this.textContentStream)&&!this.renderingDone){this.cancel(),this.textDivs=[];var i=document.createDocumentFragment();this.textLayerRenderTask=(0,a.renderTextLayer)({textContent:this.textContent,textContentStream:this.textContentStream,container:i,viewport:this.viewport,textDivs:this.textDivs,textContentItemsStr:this.textContentItemsStr,timeout:r,enhanceTextSelection:this.enhanceTextSelection}),this.textLayerRenderTask.promise.then(function(){e.textLayerDiv.appendChild(i),e._finishRendering(),e.updateMatches()},function(t){})}}},{key:"cancel",value:function t(){this.textLayerRenderTask&&(this.textLayerRenderTask.cancel(),this.textLayerRenderTask=null)}},{key:"setTextContentStream",value:function t(e){this.cancel(),this.textContentStream=e}},{key:"setTextContent",value:function t(e){this.cancel(),this.textContent=e}},{key:"convertMatches",value:function t(e,r){var i=0,n=0,o=this.textContentItemsStr,a=o.length-1,s=null===this.findController?0:this.findController.state.query.length,c=[];if(!e)return c;for(var l=0,h=e.length;l<h;l++){for(var u=e[l];i!==a&&u>=n+o[i].length;)n+=o[i].length,i++;i===o.length&&console.error("Could not find a matching mapping");var f={begin:{divIdx:i,offset:u-n}};for(u+=r?r[l]:s;i!==a&&u>n+o[i].length;)n+=o[i].length,i++;f.end={divIdx:i,offset:u-n},c.push(f)}return c}},{key:"renderMatches",value:function t(e){function r(t,e){var r=t.divIdx;o[r].textContent="",i(r,0,t.offset,e)}function i(t,e,r,i){var a=o[t],s=n[t].substring(e,r),c=document.createTextNode(s);if(i){var l=document.createElement("span");return l.className=i,l.appendChild(c),void a.appendChild(l)}a.appendChild(c)}if(0!==e.length){var n=this.textContentItemsStr,o=this.textDivs,a=null,s=this.pageIdx,c=null!==this.findController&&s===this.findController.selected.pageIdx,l=null===this.findController?-1:this.findController.selected.matchIdx,h=null!==this.findController&&this.findController.state.highlightAll,u={divIdx:-1,offset:void 0},f=l,d=f+1;if(h)f=0,d=e.length;else if(!c)return;for(var p=f;p<d;p++){var g=e[p],v=g.begin,m=g.end,b=c&&p===l,y=b?" selected":"";if(this.findController&&this.findController.updateMatchPosition(s,p,o,v.divIdx),a&&v.divIdx===a.divIdx?i(a.divIdx,a.offset,v.offset):(null!==a&&i(a.divIdx,a.offset,u.offset),r(v)),v.divIdx===m.divIdx)i(v.divIdx,v.offset,m.offset,"highlight"+y);else{i(v.divIdx,v.offset,u.offset,"highlight begin"+y);for(var _=v.divIdx+1,w=m.divIdx;_<w;_++)o[_].className="highlight middle"+y;r(m,"highlight end"+y)}a=m}a&&i(a.divIdx,a.offset,u.offset)}}},{key:"updateMatches",value:function t(){if(this.renderingDone){for(var e=this.matches,r=this.textDivs,i=this.textContentItemsStr,n=-1,o=0,a=e.length;o<a;o++){for(var s=e[o],c=Math.max(n,s.begin.divIdx),l=c,h=s.end.divIdx;l<=h;l++){var u=r[l];u.textContent=i[l],u.className=""}n=s.end.divIdx+1}if(null!==this.findController&&this.findController.active){var f=void 0,d=void 0;null!==this.findController&&(f=this.findController.pageMatches[this.pageIdx]||null,d=this.findController.pageMatchesLength?this.findController.pageMatchesLength[this.pageIdx]||null:null),this.matches=this.convertMatches(f,d),this.renderMatches(this.matches)}}}},{key:"_bindMouse",value:function t(){var e=this,r=this.textLayerDiv,i=null;r.addEventListener("mousedown",function(t){if(e.enhanceTextSelection&&e.textLayerRenderTask)return e.textLayerRenderTask.expandTextDivs(!0),void(i&&(clearTimeout(i),i=null));var n=r.querySelector(".endOfContent");if(n){var o=t.target!==r;if(o=o&&"none"!==window.getComputedStyle(n).getPropertyValue("-moz-user-select")){var a=r.getBoundingClientRect(),s=Math.max(0,(t.pageY-a.top)/a.height);n.style.top=(100*s).toFixed(2)+"%"}n.classList.add("active")}}),r.addEventListener("mouseup",function(){if(e.enhanceTextSelection&&e.textLayerRenderTask)return void(i=setTimeout(function(){e.textLayerRenderTask&&e.textLayerRenderTask.expandTextDivs(!1),i=null},300));var t=r.querySelector(".endOfContent");t&&(t.style.top="",t.classList.remove("active"))})}}]),t}(),l=function(){function t(){i(this,t)}return n(t,[{key:"createTextLayerBuilder",value:function t(e,r,i){var n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return new c({textLayerDiv:e,pageIndex:r,viewport:i,enhanceTextSelection:n})}}]),t}();e.TextLayerBuilder=c,e.DefaultTextLayerFactory=l},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),o=3e4,a={INITIAL:0,RUNNING:1,PAUSED:2,FINISHED:3},s=function(){function t(){i(this,t),this.pdfViewer=null,this.pdfThumbnailViewer=null,this.onIdle=null,this.highestPriorityPage=null,this.idleTimeout=null,this.printing=!1,this.isThumbnailViewEnabled=!1}return n(t,[{key:"setViewer",value:function t(e){this.pdfViewer=e}},{key:"setThumbnailViewer",value:function t(e){this.pdfThumbnailViewer=e}},{key:"isHighestPriority",value:function t(e){return this.highestPriorityPage===e.renderingId}},{key:"renderHighestPriority",value:function t(e){this.idleTimeout&&(clearTimeout(this.idleTimeout),this.idleTimeout=null),this.pdfViewer.forceRendering(e)||this.pdfThumbnailViewer&&this.isThumbnailViewEnabled&&this.pdfThumbnailViewer.forceRendering()||this.printing||this.onIdle&&(this.idleTimeout=setTimeout(this.onIdle.bind(this),3e4))}},{key:"getHighestPriority",value:function t(e,r,i){var n=e.views,o=n.length;if(0===o)return!1;for(var a=0;a<o;++a){var s=n[a].view;if(!this.isViewFinished(s))return s}if(i){var c=e.last.id;if(r[c]&&!this.isViewFinished(r[c]))return r[c]}else{var l=e.first.id-2;if(r[l]&&!this.isViewFinished(r[l]))return r[l]}return null}},{key:"isViewFinished",value:function t(e){return e.renderingState===a.FINISHED}},{key:"renderView",value:function t(e){var r=this;switch(e.renderingState){case a.FINISHED:return!1;case a.PAUSED:this.highestPriorityPage=e.renderingId,e.resume();break;case a.RUNNING:this.highestPriorityPage=e.renderingId;break;case a.INITIAL:this.highestPriorityPage=e.renderingId;var i=function t(){r.renderHighestPriority()};e.draw().then(i,i)}return!0}}]),t}();e.RenderingStates=a,e.PDFRenderingQueue=s},function(t,e,r){"use strict";function i(t,e){var r=document.createElement("a");if(r.click)r.href=t,r.target="_parent","download"in r&&(r.download=e),(document.body||document.documentElement).appendChild(r),r.click(),r.parentNode.removeChild(r);else{if(window.top===window&&t.split("#")[0]===window.location.href.split("#")[0]){var i=-1===t.indexOf("?")?"?":"&";t=t.replace(/#|$/,i+"$&")}window.open(t,"_parent")}}function n(){}Object.defineProperty(e,"__esModule",{value:!0}),e.DownloadManager=void 0;var o=r(0);n.prototype={downloadUrl:function t(e,r){(0,o.createValidAbsoluteUrl)(e,"http://example.com")&&i(e+"#pdfjs.action=download",r)},downloadData:function t(e,r,n){if(navigator.msSaveBlob)return navigator.msSaveBlob(new Blob([e],{type:n}),r);i((0,o.createObjectURL)(e,n,o.PDFJS.disableCreateObjectURL),r)},download:function t(e,r,n){return navigator.msSaveBlob?void(navigator.msSaveBlob(e,n)||this.downloadUrl(r,n)):o.PDFJS.disableCreateObjectURL?void this.downloadUrl(r,n):void i(URL.createObjectURL(e),n)}},e.DownloadManager=n},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.GenericL10n=void 0;var n=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}();r(13);var o=document.webL10n,a=function(){function t(e){i(this,t),this._lang=e,this._ready=new Promise(function(t,r){o.setLanguage(e,function(){t(o)})})}return n(t,[{key:"getDirection",value:function t(){return this._ready.then(function(t){return t.getDirection()})}},{key:"get",value:function t(e,r,i){return this._ready.then(function(t){return t.get(e,r,i)})}},{key:"translate",value:function t(e){return this._ready.then(function(t){return t.translate(e)})}}]),t}();e.GenericL10n=a},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.PDFFindController=e.FindState=void 0;var n=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),o=r(0),a=r(1),s={FOUND:0,NOT_FOUND:1,WRAPPED:2,PENDING:3},c=-50,l=-400,h=250,u={"‘":"'","’":"'","‚":"'","‛":"'","“":'"',"”":'"',"„":'"',"‟":'"',"¼":"1/4","½":"1/2","¾":"3/4"},f=function(){function t(e){var r=e.pdfViewer;i(this,t),this.pdfViewer=r,this.onUpdateResultsCount=null,this.onUpdateState=null,this.reset();var n=Object.keys(u).join("");this.normalizationRegex=new RegExp("["+n+"]","g")}return n(t,[{key:"reset",value:function t(){var e=this;this.startedTextExtraction=!1,this.extractTextPromises=[],this.pendingFindMatches=Object.create(null),this.active=!1,this.pageContents=[],this.pageMatches=[],this.pageMatchesLength=null,this.matchCount=0,this.selected={pageIdx:-1,matchIdx:-1},this.offset={pageIdx:null,matchIdx:null},this.pagesToSearch=null,this.resumePageIdx=null,this.state=null,this.dirtyMatch=!1,this.findTimeout=null,this._firstPagePromise=new Promise(function(t){e.resolveFirstPage=t})}},{key:"normalize",value:function t(e){return e.replace(this.normalizationRegex,function(t){return u[t]})}},{key:"_prepareMatches",value:function t(e,r,i){function n(t,e){var r=t[e],i=t[e+1];if(e<t.length-1&&r.match===i.match)return r.skipped=!0,!0;for(var n=e-1;n>=0;n--){var o=t[n];if(!o.skipped){if(o.match+o.matchLength<r.match)break;if(o.match+o.matchLength>=r.match+r.matchLength)return r.skipped=!0,!0}}return!1}e.sort(function(t,e){return t.match===e.match?t.matchLength-e.matchLength:t.match-e.match});for(var o=0,a=e.length;o<a;o++)n(e,o)||(r.push(e[o].match),i.push(e[o].matchLength))}},{key:"calcFindPhraseMatch",value:function t(e,r,i){for(var n=[],o=e.length,a=-o;;){if(-1===(a=i.indexOf(e,a+o)))break;n.push(a)}this.pageMatches[r]=n}},{key:"calcFindWordMatch",value:function t(e,r,i){for(var n=[],o=e.match(/\S+/g),a=0,s=o.length;a<s;a++)for(var c=o[a],l=c.length,h=-l;;){if(-1===(h=i.indexOf(c,h+l)))break;n.push({match:h,matchLength:l,skipped:!1})}this.pageMatchesLength||(this.pageMatchesLength=[]),this.pageMatchesLength[r]=[],this.pageMatches[r]=[],this._prepareMatches(n,this.pageMatches[r],this.pageMatchesLength[r])}},{key:"calcFindMatch",value:function t(e){var r=this.normalize(this.pageContents[e]),i=this.normalize(this.state.query),n=this.state.caseSensitive,o=this.state.phraseSearch;0!==i.length&&(n||(r=r.toLowerCase(),i=i.toLowerCase()),o?this.calcFindPhraseMatch(i,e,r):this.calcFindWordMatch(i,e,r),this.updatePage(e),this.resumePageIdx===e&&(this.resumePageIdx=null,this.nextPageMatch()),this.pageMatches[e].length>0&&(this.matchCount+=this.pageMatches[e].length,this.updateUIResultsCount()))}},{key:"extractText",value:function t(){var e=this;if(!this.startedTextExtraction){this.startedTextExtraction=!0,this.pageContents.length=0;for(var r=Promise.resolve(),i=function t(i,n){var a=(0,o.createPromiseCapability)();e.extractTextPromises[i]=a.promise,r=r.then(function(){return e.pdfViewer.getPageTextContent(i).then(function(t){for(var r=t.items,n=[],o=0,s=r.length;o<s;o++)n.push(r[o].str);e.pageContents[i]=n.join(""),a.resolve(i)})})},n=0,a=this.pdfViewer.pagesCount;n<a;n++)i(n,a)}}},{key:"executeCommand",value:function t(e,r){var i=this;null!==this.state&&"findagain"===e||(this.dirtyMatch=!0),this.state=r,this.updateUIState(s.PENDING),this._firstPagePromise.then(function(){i.extractText(),clearTimeout(i.findTimeout),"find"===e?i.findTimeout=setTimeout(i.nextMatch.bind(i),250):i.nextMatch()})}},{key:"updatePage",value:function t(e){this.selected.pageIdx===e&&(this.pdfViewer.currentPageNumber=e+1);var r=this.pdfViewer.getPageView(e);r.textLayer&&r.textLayer.updateMatches()}},{key:"nextMatch",value:function t(){var e=this,r=this.state.findPrevious,i=this.pdfViewer.currentPageNumber-1,n=this.pdfViewer.pagesCount;if(this.active=!0,this.dirtyMatch){this.dirtyMatch=!1,this.selected.pageIdx=this.selected.matchIdx=-1,this.offset.pageIdx=i,this.offset.matchIdx=null,this.hadMatch=!1,this.resumePageIdx=null,this.pageMatches=[],this.matchCount=0,this.pageMatchesLength=null;for(var o=0;o<n;o++)this.updatePage(o),o in this.pendingFindMatches||(this.pendingFindMatches[o]=!0,this.extractTextPromises[o].then(function(t){delete e.pendingFindMatches[t],e.calcFindMatch(t)}))}if(""===this.state.query)return void this.updateUIState(s.FOUND);if(!this.resumePageIdx){var a=this.offset;if(this.pagesToSearch=n,null!==a.matchIdx){var c=this.pageMatches[a.pageIdx].length;if(!r&&a.matchIdx+1<c||r&&a.matchIdx>0)return this.hadMatch=!0,a.matchIdx=r?a.matchIdx-1:a.matchIdx+1,void this.updateMatch(!0);this.advanceOffsetPage(r)}this.nextPageMatch()}}},{key:"matchesReady",value:function t(e){var r=this.offset,i=e.length,n=this.state.findPrevious;return i?(this.hadMatch=!0,r.matchIdx=n?i-1:0,this.updateMatch(!0),!0):(this.advanceOffsetPage(n),!!(r.wrapped&&(r.matchIdx=null,this.pagesToSearch<0))&&(this.updateMatch(!1),!0))}},{key:"updateMatchPosition",value:function t(e,r,i,n){if(this.selected.matchIdx===r&&this.selected.pageIdx===e){var o={top:-50,left:-400};(0,a.scrollIntoView)(i[n],o,!0)}}},{key:"nextPageMatch",value:function t(){null!==this.resumePageIdx&&console.error("There can only be one pending page.");var e=null;do{var r=this.offset.pageIdx;if(!(e=this.pageMatches[r])){this.resumePageIdx=r;break}}while(!this.matchesReady(e))}},{key:"advanceOffsetPage",value:function t(e){var r=this.offset,i=this.extractTextPromises.length;r.pageIdx=e?r.pageIdx-1:r.pageIdx+1,r.matchIdx=null,this.pagesToSearch--,(r.pageIdx>=i||r.pageIdx<0)&&(r.pageIdx=e?i-1:0,r.wrapped=!0)}},{key:"updateMatch",value:function t(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],r=s.NOT_FOUND,i=this.offset.wrapped;if(this.offset.wrapped=!1,e){var n=this.selected.pageIdx;this.selected.pageIdx=this.offset.pageIdx,this.selected.matchIdx=this.offset.matchIdx,r=i?s.WRAPPED:s.FOUND,-1!==n&&n!==this.selected.pageIdx&&this.updatePage(n)}this.updateUIState(r,this.state.findPrevious),-1!==this.selected.pageIdx&&this.updatePage(this.selected.pageIdx)}},{key:"updateUIResultsCount",value:function t(){this.onUpdateResultsCount&&this.onUpdateResultsCount(this.matchCount)}},{key:"updateUIState",value:function t(e,r){this.onUpdateState&&this.onUpdateState(e,r,this.matchCount)}}]),t}();e.FindState=s,e.PDFFindController=f},function(t,e,r){"use strict";function i(t){this.linkService=t.linkService,this.eventBus=t.eventBus||(0,n.getGlobalEventBus)(),this.initialized=!1,this.initialDestination=null,this.initialBookmark=null}Object.defineProperty(e,"__esModule",{value:!0}),e.PDFHistory=void 0;var n=r(2);i.prototype={initialize:function t(e){function r(){a.previousHash=window.location.hash.slice(1),a._pushToHistory({hash:a.previousHash},!1,!0),a._updatePreviousBookmark()}function i(t,e){function r(){window.removeEventListener("popstate",r),window.addEventListener("popstate",i),a._pushToHistory(t,!1,!0),history.forward()}function i(){window.removeEventListener("popstate",i),a.allowHashChange=!0,a.historyUnlocked=!0,e()}a.historyUnlocked=!1,a.allowHashChange=!1,window.addEventListener("popstate",r),history.back()}function n(){var t=a._getPreviousParams(null,!0);if(t){var e=!a.current.dest&&a.current.hash!==a.previousHash;a._pushToHistory(t,!1,e),a._updatePreviousBookmark()}window.removeEventListener("beforeunload",n)}this.initialized=!0,this.reInitialized=!1,this.allowHashChange=!0,this.historyUnlocked=!0,this.isViewerInPresentationMode=!1,this.previousHash=window.location.hash.substring(1),this.currentBookmark="",this.currentPage=0,this.updatePreviousBookmark=!1,this.previousBookmark="",this.previousPage=0,this.nextHashParam="",this.fingerprint=e,this.currentUid=this.uid=0,this.current={};var o=window.history.state;this._isStateObjectDefined(o)?(o.target.dest?this.initialDestination=o.target.dest:this.initialBookmark=o.target.hash,this.currentUid=o.uid,this.uid=o.uid+1,this.current=o.target):(o&&o.fingerprint&&this.fingerprint!==o.fingerprint&&(this.reInitialized=!0),this._pushOrReplaceState({fingerprint:this.fingerprint},!0));var a=this;window.addEventListener("popstate",function t(e){if(a.historyUnlocked){if(e.state)return void a._goTo(e.state);if(0===a.uid){i(a.previousHash&&a.currentBookmark&&a.previousHash!==a.currentBookmark?{hash:a.currentBookmark,page:a.currentPage}:{page:1},function(){r()})}else r()}}),window.addEventListener("beforeunload",n),window.addEventListener("pageshow",function t(e){window.addEventListener("beforeunload",n)}),a.eventBus.on("presentationmodechanged",function(t){a.isViewerInPresentationMode=t.active})},clearHistoryState:function t(){this._pushOrReplaceState(null,!0)},_isStateObjectDefined:function t(e){return!!(e&&e.uid>=0&&e.fingerprint&&this.fingerprint===e.fingerprint&&e.target&&e.target.hash)},_pushOrReplaceState:function t(e,r){r?window.history.replaceState(e,"",document.URL):window.history.pushState(e,"",document.URL)},get isHashChangeUnlocked(){return!this.initialized||this.allowHashChange},_updatePreviousBookmark:function t(){this.updatePreviousBookmark&&this.currentBookmark&&this.currentPage&&(this.previousBookmark=this.currentBookmark,this.previousPage=this.currentPage,this.updatePreviousBookmark=!1)},updateCurrentBookmark:function t(e,r){this.initialized&&(this.currentBookmark=e.substring(1),this.currentPage=0|r,this._updatePreviousBookmark())},updateNextHashParam:function t(e){this.initialized&&(this.nextHashParam=e)},push:function t(e,r){if(this.initialized&&this.historyUnlocked){if(e.dest&&!e.hash&&(e.hash=this.current.hash&&this.current.dest&&this.current.dest===e.dest?this.current.hash:this.linkService.getDestinationHash(e.dest).split("#")[1]),e.page&&(e.page|=0),r){var i=window.history.state.target;return i||(this._pushToHistory(e,!1),this.previousHash=window.location.hash.substring(1)),this.updatePreviousBookmark=!this.nextHashParam,void(i&&this._updatePreviousBookmark())}if(this.nextHashParam){if(this.nextHashParam===e.hash)return this.nextHashParam=null,void(this.updatePreviousBookmark=!0);this.nextHashParam=null}e.hash?this.current.hash?this.current.hash!==e.hash?this._pushToHistory(e,!0):(!this.current.page&&e.page&&this._pushToHistory(e,!1,!0),this.updatePreviousBookmark=!0):this._pushToHistory(e,!0):this.current.page&&e.page&&this.current.page!==e.page&&this._pushToHistory(e,!0)}},_getPreviousParams:function t(e,r){if(!this.currentBookmark||!this.currentPage)return null;if(this.updatePreviousBookmark&&(this.updatePreviousBookmark=!1),this.uid>0&&(!this.previousBookmark||!this.previousPage))return null;if(!this.current.dest&&!e||r){if(this.previousBookmark===this.currentBookmark)return null}else{if(!this.current.page&&!e)return null;if(this.previousPage===this.currentPage)return null}var i={hash:this.currentBookmark,page:this.currentPage};return this.isViewerInPresentationMode&&(i.hash=null),i},_stateObj:function t(e){return{fingerprint:this.fingerprint,uid:this.uid,target:e}},_pushToHistory:function t(e,r,i){if(this.initialized){if(!e.hash&&e.page&&(e.hash="page="+e.page),r&&!i){var n=this._getPreviousParams();if(n){var o=!this.current.dest&&this.current.hash!==this.previousHash;this._pushToHistory(n,!1,o)}}this._pushOrReplaceState(this._stateObj(e),i||0===this.uid),this.currentUid=this.uid++,this.current=e,this.updatePreviousBookmark=!0}},_goTo:function t(e){if(this.initialized&&this.historyUnlocked&&this._isStateObjectDefined(e)){if(!this.reInitialized&&e.uid<this.currentUid){var r=this._getPreviousParams(!0);if(r)return this._pushToHistory(this.current,!1),this._pushToHistory(r,!1),this.currentUid=e.uid,void window.history.back()}this.historyUnlocked=!1,e.target.dest?this.linkService.navigateTo(e.target.dest):this.linkService.setHash(e.target.hash),this.currentUid=e.uid,e.uid>this.uid&&(this.uid=e.uid),this.current=e.target,this.updatePreviousBookmark=!0;var i=window.location.hash.substring(1);this.previousHash!==i&&(this.allowHashChange=!1),this.previousHash=i,this.historyUnlocked=!0}},back:function t(){this.go(-1)},forward:function t(){this.go(1)},go:function t(e){if(this.initialized&&this.historyUnlocked){var r=window.history.state;-1===e&&r&&r.uid>0?window.history.back():1===e&&r&&r.uid<this.uid-1&&window.history.forward()}}},e.PDFHistory=i},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t){var e=[];this.push=function r(i){var n=e.indexOf(i);n>=0&&e.splice(n,1),e.push(i),e.length>t&&e.shift().destroy()},this.resize=function(r){for(t=r;e.length>t;)e.shift().destroy()}}function o(t,e){return e===t||Math.abs(e-t)<1e-15}function a(t){return t.width<=t.height}Object.defineProperty(e,"__esModule",{value:!0}),e.PDFViewer=e.PresentationModeState=void 0;var s=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),c=r(0),l=r(1),h=r(7),u=r(4),f=r(2),d=r(5),p=r(3),g=r(6),v={UNKNOWN:0,NORMAL:1,CHANGING:2,FULLSCREEN:3},m=10,b=function(){function t(e){i(this,t),this.container=e.container,this.viewer=e.viewer||e.container.firstElementChild,this.eventBus=e.eventBus||(0,f.getGlobalEventBus)(),this.linkService=e.linkService||new p.SimpleLinkService,this.downloadManager=e.downloadManager||null,this.removePageBorders=e.removePageBorders||!1,this.enhanceTextSelection=e.enhanceTextSelection||!1,this.renderInteractiveForms=e.renderInteractiveForms||!1,this.enablePrintAutoRotate=e.enablePrintAutoRotate||!1,this.renderer=e.renderer||l.RendererType.CANVAS,this.l10n=e.l10n||l.NullL10n,this.defaultRenderingQueue=!e.renderingQueue,this.defaultRenderingQueue?(this.renderingQueue=new h.PDFRenderingQueue,this.renderingQueue.setViewer(this)):this.renderingQueue=e.renderingQueue,this.scroll=(0,l.watchScroll)(this.container,this._scrollUpdate.bind(this)),this.presentationModeState=v.UNKNOWN,this._resetView(),this.removePageBorders&&this.viewer.classList.add("removePageBorders")}return s(t,[{key:"getPageView",value:function t(e){return this._pages[e]}},{key:"_setCurrentPageNumber",value:function t(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(this._currentPageNumber===e)return void(r&&this._resetCurrentPageView());if(!(0<e&&e<=this.pagesCount))return void console.error('PDFViewer._setCurrentPageNumber: "'+e+'" is out of bounds.');var i={source:this,pageNumber:e,pageLabel:this._pageLabels&&this._pageLabels[e-1]};this._currentPageNumber=e,this.eventBus.dispatch("pagechanging",i),this.eventBus.dispatch("pagechange",i),r&&this._resetCurrentPageView()}},{key:"setDocument",value:function t(e){var r=this;if(this.pdfDocument&&(this._cancelRendering(),this._resetView()),this.pdfDocument=e,e){var i=e.numPages,n=(0,c.createPromiseCapability)();this.pagesPromise=n.promise,n.promise.then(function(){r._pageViewsReady=!0,r.eventBus.dispatch("pagesloaded",{source:r,pagesCount:i})});var o=!1,a=(0,c.createPromiseCapability)();this.onePageRendered=a.promise;var s=function t(e){e.onBeforeDraw=function(){r._buffer.push(e)},e.onAfterDraw=function(){o||(o=!0,a.resolve())}},h=e.getPage(1);return this.firstPagePromise=h,h.then(function(t){for(var o=r.currentScale,h=t.getViewport(o*l.CSS_UNITS),u=1;u<=i;++u){var f=null;c.PDFJS.disableTextLayer||(f=r);var p=new d.PDFPageView({container:r.viewer,eventBus:r.eventBus,id:u,scale:o,defaultViewport:h.clone(),renderingQueue:r.renderingQueue,textLayerFactory:f,annotationLayerFactory:r,enhanceTextSelection:r.enhanceTextSelection,renderInteractiveForms:r.renderInteractiveForms,renderer:r.renderer,l10n:r.l10n});s(p),r._pages.push(p)}a.promise.then(function(){if(c.PDFJS.disableAutoFetch)return void n.resolve();for(var t=i,o=function i(o){e.getPage(o).then(function(e){var i=r._pages[o-1];i.pdfPage||i.setPdfPage(e),r.linkService.cachePageRef(o,e.ref),0==--t&&n.resolve()})},a=1;a<=i;++a)o(a)}),r.eventBus.dispatch("pagesinit",{source:r}),r.defaultRenderingQueue&&r.update(),r.findController&&r.findController.resolveFirstPage()})}}},{key:"setPageLabels",value:function t(e){if(this.pdfDocument){e?e instanceof Array&&this.pdfDocument.numPages===e.length?this._pageLabels=e:(this._pageLabels=null,console.error("PDFViewer.setPageLabels: Invalid page labels.")):this._pageLabels=null;for(var r=0,i=this._pages.length;r<i;r++){var n=this._pages[r],o=this._pageLabels&&this._pageLabels[r];n.setPageLabel(o)}}}},{key:"_resetView",value:function t(){this._pages=[],this._currentPageNumber=1,this._currentScale=l.UNKNOWN_SCALE,this._currentScaleValue=null,this._pageLabels=null,this._buffer=new n(10),this._location=null,this._pagesRotation=0,this._pagesRequests=[],this._pageViewsReady=!1,this.viewer.textContent=""}},{key:"_scrollUpdate",value:function t(){0!==this.pagesCount&&this.update()}},{key:"_setScaleDispatchEvent",value:function t(e,r){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n={source:this,scale:e,presetValue:i?r:void 0};this.eventBus.dispatch("scalechanging",n),this.eventBus.dispatch("scalechange",n)}},{key:"_setScaleUpdatePages",value:function t(e,r){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(this._currentScaleValue=r.toString(),o(this._currentScale,e))return void(n&&this._setScaleDispatchEvent(e,r,!0));for(var a=0,s=this._pages.length;a<s;a++)this._pages[a].update(e);if(this._currentScale=e,!i){var l=this._currentPageNumber,h=void 0;!this._location||c.PDFJS.ignoreCurrentPositionOnZoom||this.isInPresentationMode||this.isChangingPresentationMode||(l=this._location.pageNumber,h=[null,{name:"XYZ"},this._location.left,this._location.top,null]),this.scrollPageIntoView({pageNumber:l,destArray:h,allowNegativeOffset:!0})}this._setScaleDispatchEvent(e,r,n),this.defaultRenderingQueue&&this.update()}},{key:"_setScale",value:function t(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=parseFloat(e);if(i>0)this._setScaleUpdatePages(i,e,r,!1);else{var n=this._pages[this._currentPageNumber-1];if(!n)return;var o=this.isInPresentationMode||this.removePageBorders?0:l.SCROLLBAR_PADDING,a=this.isInPresentationMode||this.removePageBorders?0:l.VERTICAL_PADDING,s=(this.container.clientWidth-o)/n.width*n.scale,c=(this.container.clientHeight-a)/n.height*n.scale;switch(e){case"page-actual":i=1;break;case"page-width":i=s;break;case"page-height":i=c;break;case"page-fit":i=Math.min(s,c);break;case"auto":var h=n.width>n.height,u=h?Math.min(c,s):s;i=Math.min(l.MAX_AUTO_SCALE,u);break;default:return void console.error('PDFViewer._setScale: "'+e+'" is an unknown zoom value.')}this._setScaleUpdatePages(i,e,r,!0)}}},{key:"_resetCurrentPageView",value:function t(){this.isInPresentationMode&&this._setScale(this._currentScaleValue,!0);var e=this._pages[this._currentPageNumber-1];(0,l.scrollIntoView)(e.div)}},{key:"scrollPageIntoView",value:function t(e){if(this.pdfDocument){if(arguments.length>1||"number"==typeof e){console.warn("Call of scrollPageIntoView() with obsolete signature.");var r={};"number"==typeof e&&(r.pageNumber=e),arguments[1]instanceof Array&&(r.destArray=arguments[1]),e=r}var i=e.pageNumber||0,n=e.destArray||null,o=e.allowNegativeOffset||!1;if(this.isInPresentationMode||!n)return void this._setCurrentPageNumber(i,!0);var a=this._pages[i-1];if(!a)return void console.error('PDFViewer.scrollPageIntoView: Invalid "pageNumber" parameter.');var s=0,c=0,h=0,u=0,f=void 0,d=void 0,p=a.rotation%180!=0,g=(p?a.height:a.width)/a.scale/l.CSS_UNITS,v=(p?a.width:a.height)/a.scale/l.CSS_UNITS,m=0;switch(n[1].name){case"XYZ":s=n[2],c=n[3],m=n[4],s=null!==s?s:0,c=null!==c?c:v;break;case"Fit":case"FitB":m="page-fit";break;case"FitH":case"FitBH":c=n[2],m="page-width",null===c&&this._location&&(s=this._location.left,c=this._location.top);break;case"FitV":case"FitBV":s=n[2],h=g,u=v,m="page-height";break;case"FitR":s=n[2],c=n[3],h=n[4]-s,u=n[5]-c;var b=this.removePageBorders?0:l.SCROLLBAR_PADDING,y=this.removePageBorders?0:l.VERTICAL_PADDING;f=(this.container.clientWidth-b)/h/l.CSS_UNITS,d=(this.container.clientHeight-y)/u/l.CSS_UNITS,m=Math.min(Math.abs(f),Math.abs(d));break;default:return void console.error('PDFViewer.scrollPageIntoView: "'+n[1].name+'" is not a valid destination type.')}if(m&&m!==this._currentScale?this.currentScaleValue=m:this._currentScale===l.UNKNOWN_SCALE&&(this.currentScaleValue=l.DEFAULT_SCALE_VALUE),"page-fit"===m&&!n[4])return void(0,l.scrollIntoView)(a.div);var _=[a.viewport.convertToViewportPoint(s,c),a.viewport.convertToViewportPoint(s+h,c+u)],w=Math.min(_[0][0],_[1][0]),S=Math.min(_[0][1],_[1][1]);o||(w=Math.max(w,0),S=Math.max(S,0)),(0,l.scrollIntoView)(a.div,{left:w,top:S})}}},{key:"_updateLocation",value:function t(e){var r=this._currentScale,i=this._currentScaleValue,n=parseFloat(i)===r?Math.round(1e4*r)/100:i,o=e.id,a="#page="+o;a+="&zoom="+n;var s=this._pages[o-1],c=this.container,l=s.getPagePoint(c.scrollLeft-e.x,c.scrollTop-e.y),h=Math.round(l[0]),u=Math.round(l[1]);a+=","+h+","+u,this._location={pageNumber:o,scale:n,top:u,left:h,pdfOpenParams:a}}},{key:"update",value:function t(){var e=this._getVisiblePages(),r=e.views;if(0!==r.length){var i=Math.max(10,2*r.length+1);this._buffer.resize(i),this.renderingQueue.renderHighestPriority(e);for(var n=this._currentPageNumber,o=e.first,a=!1,s=0,c=r.length;s<c;++s){var l=r[s];if(l.percent<100)break;if(l.id===n){a=!0;break}}a||(n=r[0].id),this.isInPresentationMode||this._setCurrentPageNumber(n),this._updateLocation(o),this.eventBus.dispatch("updateviewarea",{source:this,location:this._location})}}},{key:"containsElement",value:function t(e){return this.container.contains(e)}},{key:"focus",value:function t(){this.container.focus()}},{key:"_getVisiblePages",value:function t(){if(!this.isInPresentationMode)return(0,l.getVisibleElements)(this.container,this._pages,!0);var e=[],r=this._pages[this._currentPageNumber-1];return e.push({id:r.id,view:r}),{first:r,last:r,views:e}}},{key:"cleanup",value:function t(){for(var e=0,r=this._pages.length;e<r;e++)this._pages[e]&&this._pages[e].renderingState!==h.RenderingStates.FINISHED&&this._pages[e].reset()}},{key:"_cancelRendering",value:function t(){for(var e=0,r=this._pages.length;e<r;e++)this._pages[e]&&this._pages[e].cancelRendering()}},{key:"_ensurePdfPageLoaded",value:function t(e){var r=this;if(e.pdfPage)return Promise.resolve(e.pdfPage);var i=e.id;if(this._pagesRequests[i])return this._pagesRequests[i];var n=this.pdfDocument.getPage(i).then(function(t){return e.pdfPage||e.setPdfPage(t),r._pagesRequests[i]=null,t});return this._pagesRequests[i]=n,n}},{key:"forceRendering",value:function t(e){var r=this,i=e||this._getVisiblePages(),n=this.renderingQueue.getHighestPriority(i,this._pages,this.scroll.down);return!!n&&(this._ensurePdfPageLoaded(n).then(function(){r.renderingQueue.renderView(n)}),!0)}},{key:"getPageTextContent",value:function t(e){return this.pdfDocument.getPage(e+1).then(function(t){return t.getTextContent({normalizeWhitespace:!0})})}},{key:"createTextLayerBuilder",value:function t(e,r,i){var n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return new g.TextLayerBuilder({textLayerDiv:e,eventBus:this.eventBus,pageIndex:r,viewport:i,findController:this.isInPresentationMode?null:this.findController,enhanceTextSelection:!this.isInPresentationMode&&n})}},{key:"createAnnotationLayerBuilder",value:function t(e,r){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:l.NullL10n;return new u.AnnotationLayerBuilder({pageDiv:e,pdfPage:r,renderInteractiveForms:i,linkService:this.linkService,downloadManager:this.downloadManager,l10n:n})}},{key:"setFindController",value:function t(e){this.findController=e}},{key:"getPagesOverview",value:function t(){var e=this._pages.map(function(t){var e=t.pdfPage.getViewport(1);return{width:e.width,height:e.height,rotation:e.rotation}});if(!this.enablePrintAutoRotate)return e;var r=a(e[0]);return e.map(function(t){return r===a(t)?t:{width:t.height,height:t.width,rotation:(t.rotation+90)%360}})}},{key:"pagesCount",get:function t(){return this._pages.length}},{key:"pageViewsReady",get:function t(){return this._pageViewsReady}},{key:"currentPageNumber",get:function t(){return this._currentPageNumber},set:function t(e){if((0|e)!==e)throw new Error("Invalid page number.");this.pdfDocument&&this._setCurrentPageNumber(e,!0)}},{key:"currentPageLabel",get:function t(){return this._pageLabels&&this._pageLabels[this._currentPageNumber-1]},set:function t(e){var r=0|e;if(this._pageLabels){var i=this._pageLabels.indexOf(e);i>=0&&(r=i+1)}this.currentPageNumber=r}},{key:"currentScale",get:function t(){return this._currentScale!==l.UNKNOWN_SCALE?this._currentScale:l.DEFAULT_SCALE},set:function t(e){if(isNaN(e))throw new Error("Invalid numeric scale");this.pdfDocument&&this._setScale(e,!1)}},{key:"currentScaleValue",get:function t(){return this._currentScaleValue},set:function t(e){this.pdfDocument&&this._setScale(e,!1)}},{key:"pagesRotation",get:function t(){return this._pagesRotation},set:function t(e){if("number"!=typeof e||e%90!=0)throw new Error("Invalid pages rotation angle.");if(this.pdfDocument){this._pagesRotation=e;for(var r=0,i=this._pages.length;r<i;r++){var n=this._pages[r];n.update(n.scale,e)}this._setScale(this._currentScaleValue,!0),this.defaultRenderingQueue&&this.update()}}},{key:"isInPresentationMode",get:function t(){return this.presentationModeState===v.FULLSCREEN}},{key:"isChangingPresentationMode",get:function t(){return this.presentationModeState===v.CHANGING}},{key:"isHorizontalScrollbarEnabled",get:function t(){return!this.isInPresentationMode&&this.container.scrollWidth>this.container.clientWidth}},{key:"hasEqualPageSizes",get:function t(){for(var e=this._pages[0],r=1,i=this._pages.length;r<i;++r){var n=this._pages[r];if(n.width!==e.width||n.height!==e.height)return!1}return!0}}]),t}();e.PresentationModeState=v,e.PDFViewer=b},function(t,e,r){"use strict";document.webL10n=function(t,e,r){function i(){return e.querySelectorAll('link[type="application/l10n"]')}function n(){var t=e.querySelector('script[type="application/l10n"]');return t?JSON.parse(t.innerHTML):null}function o(t){return t?t.querySelectorAll("*[data-l10n-id]"):[]}function a(t){if(!t)return{};var e=t.getAttribute("data-l10n-id"),r=t.getAttribute("data-l10n-args"),i={};if(r)try{i=JSON.parse(r)}catch(t){console.warn("could not parse arguments for #"+e)}return{id:e,args:i}}function s(t){var r=e.createEvent("Event");r.initEvent("localized",!0,!1),r.language=t,e.dispatchEvent(r)}function c(t,e,r){e=e||function t(e){},r=r||function t(){};var i=new XMLHttpRequest;i.open("GET",t,A),i.overrideMimeType&&i.overrideMimeType("text/plain; charset=utf-8"),i.onreadystatechange=function(){4==i.readyState&&(200==i.status||0===i.status?e(i.responseText):r())},i.onerror=r,i.ontimeout=r;try{i.send(null)}catch(t){r()}}function l(t,e,r,i){function n(t){return t.lastIndexOf("\\")<0?t:t.replace(/\\\\/g,"\\").replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\b/g,"\b").replace(/\\f/g,"\f").replace(/\\{/g,"{").replace(/\\}/g,"}").replace(/\\"/g,'"').replace(/\\'/g,"'")}function o(t,r){function i(t,r,i){function c(){for(;;){if(!p.length)return void i();var t=p.shift();if(!h.test(t)){if(r){if(b=u.exec(t)){g=b[1].toLowerCase(),m="*"!==g&&g!==e&&g!==v;continue}if(m)continue;if(b=f.exec(t))return void o(a+b[1],c)}var l=t.match(d);l&&3==l.length&&(s[l[1]]=n(l[2]))}}}var p=t.replace(l,"").split(/[\r\n]+/),g="*",v=e.split("-",1)[0],m=!1,b="";c()}function o(t,e){c(t,function(t){i(t,!1,e)},function(){console.warn(t+" not found."),e()})}var s={},l=/^\s*|\s*$/,h=/^\s*#|^\s*$/,u=/^\s*\[(.*)\]\s*$/,f=/^\s*@import\s+url\((.*)\)\s*$/i,d=/^([^=\s]*)\s*=\s*(.+)$/;i(t,!0,function(){r(s)})}var a=t.replace(/[^\/]*$/,"")||"./";c(t,function(t){_+=t,o(t,function(t){for(var e in t){var i,n,o=e.lastIndexOf(".");o>0?(i=e.substring(0,o),n=e.substr(o+1)):(i=e,n=w),y[i]||(y[i]={}),y[i][n]=t[e]}r&&r()})},i)}function h(t,e){function r(t){var e=t.href;this.load=function(t,r){l(e,t,r,function(){console.warn(e+" not found."),console.warn('"'+t+'" resource not found'),S="",r()})}}t&&(t=t.toLowerCase()),e=e||function t(){},u(),S=t;var o=i(),a=o.length;if(0===a){var c=n();if(c&&c.locales&&c.default_locale){if(console.log("using the embedded JSON directory, early way out"),!(y=c.locales[t])){var h=c.default_locale.toLowerCase();for(var f in c.locales){if((f=f.toLowerCase())===t){y=c.locales[t];break}f===h&&(y=c.locales[h])}}e()}else console.log("no resource to load, early way out");return s(t),void(C="complete")}var d=null,p=0;d=function r(){++p>=a&&(e(),s(t),C="complete")};for(var g=0;g<a;g++){new r(o[g]).load(t,d)}}function u(){y={},_="",S=""}function f(t){function e(t,e){return-1!==e.indexOf(t)}function r(t,e,r){return e<=t&&t<=r}var i={af:3,ak:4,am:4,ar:1,asa:3,az:0,be:11,bem:3,bez:3,bg:3,bh:4,bm:0,bn:3,bo:0,br:20,brx:3,bs:11,ca:3,cgg:3,chr:3,cs:12,cy:17,da:3,de:3,dv:3,dz:0,ee:3,el:3,en:3,eo:3,es:3,et:3,eu:3,fa:0,ff:5,fi:3,fil:4,fo:3,fr:5,fur:3,fy:3,ga:8,gd:24,gl:3,gsw:3,gu:3,guw:4,gv:23,ha:3,haw:3,he:2,hi:4,hr:11,hu:0,id:0,ig:0,ii:0,is:3,it:3,iu:7,ja:0,jmc:3,jv:0,ka:0,kab:5,kaj:3,kcg:3,kde:0,kea:0,kk:3,kl:3,km:0,kn:0,ko:0,ksb:3,ksh:21,ku:3,kw:7,lag:18,lb:3,lg:3,ln:4,lo:0,lt:10,lv:6,mas:3,mg:4,mk:16,ml:3,mn:3,mo:9,mr:3,ms:0,mt:15,my:0,nah:3,naq:7,nb:3,nd:3,ne:3,nl:3,nn:3,no:3,nr:3,nso:4,ny:3,nyn:3,om:3,or:3,pa:3,pap:3,pl:13,ps:3,pt:3,rm:3,ro:9,rof:3,ru:11,rwk:3,sah:0,saq:3,se:7,seh:3,ses:0,sg:0,sh:11,shi:19,sk:12,sl:14,sma:7,smi:7,smj:7,smn:7,sms:7,sn:3,so:3,sq:3,sr:11,ss:3,ssy:3,st:3,sv:3,sw:3,syr:3,ta:3,te:3,teo:3,th:0,ti:4,tig:3,tk:3,tl:4,tn:3,to:0,tr:0,ts:3,tzm:22,uk:11,ur:3,ve:3,vi:0,vun:3,wa:4,wae:3,wo:0,xh:3,xog:3,yo:0,zh:0,zu:3},n={0:function t(e){return"other"},1:function t(e){return r(e%100,3,10)?"few":0===e?"zero":r(e%100,11,99)?"many":2==e?"two":1==e?"one":"other"},2:function t(e){return 0!==e&&e%10==0?"many":2==e?"two":1==e?"one":"other"},3:function t(e){return 1==e?"one":"other"},4:function t(e){return r(e,0,1)?"one":"other"},5:function t(e){return r(e,0,2)&&2!=e?"one":"other"},6:function t(e){return 0===e?"zero":e%10==1&&e%100!=11?"one":"other"},7:function t(e){return 2==e?"two":1==e?"one":"other"},8:function t(e){return r(e,3,6)?"few":r(e,7,10)?"many":2==e?"two":1==e?"one":"other"},9:function t(e){return 0===e||1!=e&&r(e%100,1,19)?"few":1==e?"one":"other"},10:function t(e){return r(e%10,2,9)&&!r(e%100,11,19)?"few":e%10!=1||r(e%100,11,19)?"other":"one"},11:function t(e){return r(e%10,2,4)&&!r(e%100,12,14)?"few":e%10==0||r(e%10,5,9)||r(e%100,11,14)?"many":e%10==1&&e%100!=11?"one":"other"},12:function t(e){return r(e,2,4)?"few":1==e?"one":"other"},13:function t(e){return r(e%10,2,4)&&!r(e%100,12,14)?"few":1!=e&&r(e%10,0,1)||r(e%10,5,9)||r(e%100,12,14)?"many":1==e?"one":"other"},14:function t(e){return r(e%100,3,4)?"few":e%100==2?"two":e%100==1?"one":"other"},15:function t(e){return 0===e||r(e%100,2,10)?"few":r(e%100,11,19)?"many":1==e?"one":"other"},16:function t(e){return e%10==1&&11!=e?"one":"other"},17:function t(e){return 3==e?"few":0===e?"zero":6==e?"many":2==e?"two":1==e?"one":"other"},18:function t(e){return 0===e?"zero":r(e,0,2)&&0!==e&&2!=e?"one":"other"},19:function t(e){return r(e,2,10)?"few":r(e,0,1)?"one":"other"},20:function t(i){return!r(i%10,3,4)&&i%10!=9||r(i%100,10,19)||r(i%100,70,79)||r(i%100,90,99)?i%1e6==0&&0!==i?"many":i%10!=2||e(i%100,[12,72,92])?i%10!=1||e(i%100,[11,71,91])?"other":"one":"two":"few"},21:function t(e){return 0===e?"zero":1==e?"one":"other"},22:function t(e){return r(e,0,1)||r(e,11,99)?"one":"other"},23:function t(e){return r(e%10,1,2)||e%20==0?"one":"other"},24:function t(i){return r(i,3,10)||r(i,13,19)?"few":e(i,[2,12])?"two":e(i,[1,11])?"one":"other"}},o=i[t.replace(/-.*$/,"")];return o in n?n[o]:(console.warn("plural form unknown for ["+t+"]"),function(){return"other"})}function d(t,e,r){var i=y[t];if(!i){if(console.warn("#"+t+" is undefined."),!r)return null;i=r}var n={};for(var o in i){var a=i[o];a=p(a,e,t,o),a=g(a,e,t),n[o]=a}return n}function p(t,e,r,i){var n=/\{\[\s*([a-zA-Z]+)\(([a-zA-Z]+)\)\s*\]\}/,o=n.exec(t);if(!o||!o.length)return t;var a=o[1],s=o[2],c;if(e&&s in e?c=e[s]:s in y&&(c=y[s]),a in x){t=(0,x[a])(t,c,r,i)}return t}function g(t,e,r){var i=/\{\{\s*(.+?)\s*\}\}/g;return t.replace(i,function(t,i){return e&&i in e?e[i]:i in y?y[i]:(console.log("argument {{"+i+"}} for #"+r+" is undefined."),t)})}function v(t){var r=a(t);if(r.id){var i=d(r.id,r.args);if(!i)return void console.warn("#"+r.id+" is undefined.");if(i[w]){if(0===m(t))t[w]=i[w];else{for(var n=t.childNodes,o=!1,s=0,c=n.length;s<c;s++)3===n[s].nodeType&&/\S/.test(n[s].nodeValue)&&(o?n[s].nodeValue="":(n[s].nodeValue=i[w],o=!0));if(!o){var l=e.createTextNode(i[w]);t.insertBefore(l,t.firstChild)}}delete i[w]}for(var h in i)t[h]=i[h]}}function m(t){if(t.children)return t.children.length;if(void 0!==t.childElementCount)return t.childElementCount;for(var e=0,r=0;r<t.childNodes.length;r++)e+=1===t.nodeType?1:0;return e}function b(t){t=t||e.documentElement;for(var r=o(t),i=r.length,n=0;n<i;n++)v(r[n]);v(t)}var y={},_="",w="textContent",S="",x={},C="loading",A=!0;return x.plural=function(t,e,r,i){var n=parseFloat(e);if(isNaN(n))return t;if(i!=w)return t;x._pluralRules||(x._pluralRules=f(S));var o="["+x._pluralRules(n)+"]";return 0===n&&r+"[zero]"in y?t=y[r+"[zero]"][i]:1==n&&r+"[one]"in y?t=y[r+"[one]"][i]:2==n&&r+"[two]"in y?t=y[r+"[two]"][i]:r+o in y?t=y[r+o][i]:r+"[other]"in y&&(t=y[r+"[other]"][i]),t},{get:function t(e,r,i){var n=e.lastIndexOf("."),o=w;n>0&&(o=e.substr(n+1),e=e.substring(0,n));var a;i&&(a={},a[o]=i);var s=d(e,r,a);return s&&o in s?s[o]:"{{"+e+"}}"},getData:function t(){return y},getText:function t(){return _},getLanguage:function t(){return S},setLanguage:function t(e,r){h(e,function(){r&&r()})},getDirection:function t(){var e=["ar","he","fa","ps","ur"],r=S.split("-",1)[0];return e.indexOf(r)>=0?"rtl":"ltr"},translate:b,getReadyState:function t(){return C},ready:function r(i){i&&("complete"==C||"interactive"==C?t.setTimeout(function(){i()}):e.addEventListener&&e.addEventListener("localized",function t(){e.removeEventListener("localized",t),i()}))}}}(window,document)},function(t,e,r){"use strict";var i=r(0),n=r(12),o=r(5),a=r(3),s=r(6),c=r(4),l=r(11),h=r(10),u=r(1),f=r(8),d=r(9),p=i.PDFJS;p.PDFViewer=n.PDFViewer,p.PDFPageView=o.PDFPageView,p.PDFLinkService=a.PDFLinkService,p.TextLayerBuilder=s.TextLayerBuilder,p.DefaultTextLayerFactory=s.DefaultTextLayerFactory,p.AnnotationLayerBuilder=c.AnnotationLayerBuilder,p.DefaultAnnotationLayerFactory=c.DefaultAnnotationLayerFactory,p.PDFHistory=l.PDFHistory,p.PDFFindController=h.PDFFindController,p.EventBus=u.EventBus,p.DownloadManager=f.DownloadManager,p.ProgressBar=u.ProgressBar,p.GenericL10n=d.GenericL10n,p.NullL10n=u.NullL10n,e.PDFJS=p}])})},function(t,e,r){"use strict";function i(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===t[e-2]?2:"="===t[e-1]?1:0}function n(t){return 3*t.length/4-i(t)}function o(t){var e,r,n,o,a,s=t.length;o=i(t),a=new u(3*s/4-o),r=o>0?s-4:s;var c=0;for(e=0;e<r;e+=4)n=h[t.charCodeAt(e)]<<18|h[t.charCodeAt(e+1)]<<12|h[t.charCodeAt(e+2)]<<6|h[t.charCodeAt(e+3)],a[c++]=n>>16&255,a[c++]=n>>8&255,a[c++]=255&n;return 2===o?(n=h[t.charCodeAt(e)]<<2|h[t.charCodeAt(e+1)]>>4,a[c++]=255&n):1===o&&(n=h[t.charCodeAt(e)]<<10|h[t.charCodeAt(e+1)]<<4|h[t.charCodeAt(e+2)]>>2,a[c++]=n>>8&255,a[c++]=255&n),a}function a(t){return l[t>>18&63]+l[t>>12&63]+l[t>>6&63]+l[63&t]}function s(t,e,r){for(var i,n=[],o=e;o<r;o+=3)i=(t[o]<<16)+(t[o+1]<<8)+t[o+2],n.push(a(i));return n.join("")}function c(t){for(var e,r=t.length,i=r%3,n="",o=[],a=16383,c=0,h=r-i;c<h;c+=16383)o.push(s(t,c,c+16383>h?h:c+16383));return 1===i?(e=t[r-1],n+=l[e>>2],n+=l[e<<4&63],n+="=="):2===i&&(e=(t[r-2]<<8)+t[r-1],n+=l[e>>10],n+=l[e>>4&63],n+=l[e<<2&63],n+="="),o.push(n),o.join("")}e.byteLength=n,e.toByteArray=o,e.fromByteArray=c;for(var l=[],h=[],u="undefined"!=typeof Uint8Array?Uint8Array:Array,f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",d=0,p=f.length;d<p;++d)l[d]=f[d],h[f.charCodeAt(d)]=d;h["-".charCodeAt(0)]=62,h["_".charCodeAt(0)]=63},function(t,e){e.read=function(t,e,r,i,n){var o,a,s=8*n-i-1,c=(1<<s)-1,l=c>>1,h=-7,u=r?n-1:0,f=r?-1:1,d=t[e+u];for(u+=f,o=d&(1<<-h)-1,d>>=-h,h+=s;h>0;o=256*o+t[e+u],u+=f,h-=8);for(a=o&(1<<-h)-1,o>>=-h,h+=i;h>0;a=256*a+t[e+u],u+=f,h-=8);if(0===o)o=1-l;else{if(o===c)return a?NaN:1/0*(d?-1:1);a+=Math.pow(2,i),o-=l}return(d?-1:1)*a*Math.pow(2,o-i)},e.write=function(t,e,r,i,n,o){var a,s,c,l=8*o-n-1,h=(1<<l)-1,u=h>>1,f=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,d=i?0:o-1,p=i?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,a=h):(a=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-a))<1&&(a--,c*=2),e+=a+u>=1?f/c:f*Math.pow(2,1-u),e*c>=2&&(a++,c/=2),a+u>=h?(s=0,a=h):a+u>=1?(s=(e*c-1)*Math.pow(2,n),a+=u):(s=e*Math.pow(2,u-1)*Math.pow(2,n),a=0));n>=8;t[r+d]=255&s,d+=p,s/=256,n-=8);for(a=a<<n|s,l+=n;l>0;t[r+d]=255&a,d+=p,a/=256,l-=8);t[r+d-p]|=128*g}},function(t,e,r){(function(t,i){function n(e,r,i){function n(){for(var t;null!==(t=e.read());)s.push(t),c+=t.length;e.once("readable",n)}function o(t){e.removeListener("end",a),e.removeListener("readable",n),i(t)}function a(){var r=t.concat(s,c);s=[],i(null,r),e.close()}var s=[],c=0;e.on("error",o),e.on("end",a),e.end(r),n()}function o(e,r){if("string"==typeof r&&(r=new t(r)),!t.isBuffer(r))throw new TypeError("Not a string or buffer");var i=g.Z_FINISH;return e._processChunk(r,i)}function a(t){if(!(this instanceof a))return new a(t);d.call(this,t,g.DEFLATE)}function s(t){if(!(this instanceof s))return new s(t);d.call(this,t,g.INFLATE)}function c(t){if(!(this instanceof c))return new c(t);d.call(this,t,g.GZIP)}function l(t){if(!(this instanceof l))return new l(t);d.call(this,t,g.GUNZIP)}function h(t){if(!(this instanceof h))return new h(t);d.call(this,t,g.DEFLATERAW)}function u(t){if(!(this instanceof u))return new u(t);d.call(this,t,g.INFLATERAW)}function f(t){if(!(this instanceof f))return new f(t);d.call(this,t,g.UNZIP)}function d(r,i){if(this._opts=r=r||{},this._chunkSize=r.chunkSize||e.Z_DEFAULT_CHUNK,p.call(this,r),r.flush&&r.flush!==g.Z_NO_FLUSH&&r.flush!==g.Z_PARTIAL_FLUSH&&r.flush!==g.Z_SYNC_FLUSH&&r.flush!==g.Z_FULL_FLUSH&&r.flush!==g.Z_FINISH&&r.flush!==g.Z_BLOCK)throw new Error("Invalid flush flag: "+r.flush);if(this._flushFlag=r.flush||g.Z_NO_FLUSH,r.chunkSize&&(r.chunkSize<e.Z_MIN_CHUNK||r.chunkSize>e.Z_MAX_CHUNK))throw new Error("Invalid chunk size: "+r.chunkSize);if(r.windowBits&&(r.windowBits<e.Z_MIN_WINDOWBITS||r.windowBits>e.Z_MAX_WINDOWBITS))throw new Error("Invalid windowBits: "+r.windowBits);if(r.level&&(r.level<e.Z_MIN_LEVEL||r.level>e.Z_MAX_LEVEL))throw new Error("Invalid compression level: "+r.level);if(r.memLevel&&(r.memLevel<e.Z_MIN_MEMLEVEL||r.memLevel>e.Z_MAX_MEMLEVEL))throw new Error("Invalid memLevel: "+r.memLevel);if(r.strategy&&r.strategy!=e.Z_FILTERED&&r.strategy!=e.Z_HUFFMAN_ONLY&&r.strategy!=e.Z_RLE&&r.strategy!=e.Z_FIXED&&r.strategy!=e.Z_DEFAULT_STRATEGY)throw new Error("Invalid strategy: "+r.strategy);if(r.dictionary&&!t.isBuffer(r.dictionary))throw new Error("Invalid dictionary: it should be a Buffer instance");this._binding=new g.Zlib(i);var n=this;this._hadError=!1,this._binding.onerror=function(t,r){n._binding=null,n._hadError=!0;var i=new Error(t);i.errno=r,i.code=e.codes[r],n.emit("error",i)};var o=e.Z_DEFAULT_COMPRESSION;"number"==typeof r.level&&(o=r.level);var a=e.Z_DEFAULT_STRATEGY;"number"==typeof r.strategy&&(a=r.strategy),this._binding.init(r.windowBits||e.Z_DEFAULT_WINDOWBITS,o,r.memLevel||e.Z_DEFAULT_MEMLEVEL,a,r.dictionary),this._buffer=new t(this._chunkSize),this._offset=0,this._closed=!1,this._level=o,this._strategy=a,this.once("end",this.close)}var p=r(43),g=r(50),v=r(24),m=r(60).ok;g.Z_MIN_WINDOWBITS=8,g.Z_MAX_WINDOWBITS=15,g.Z_DEFAULT_WINDOWBITS=15,g.Z_MIN_CHUNK=64,g.Z_MAX_CHUNK=1/0,g.Z_DEFAULT_CHUNK=16384,g.Z_MIN_MEMLEVEL=1,g.Z_MAX_MEMLEVEL=9,g.Z_DEFAULT_MEMLEVEL=8,g.Z_MIN_LEVEL=-1,g.Z_MAX_LEVEL=9,g.Z_DEFAULT_LEVEL=g.Z_DEFAULT_COMPRESSION,Object.keys(g).forEach(function(t){t.match(/^Z/)&&(e[t]=g[t])}),e.codes={Z_OK:g.Z_OK,Z_STREAM_END:g.Z_STREAM_END,Z_NEED_DICT:g.Z_NEED_DICT,Z_ERRNO:g.Z_ERRNO,Z_STREAM_ERROR:g.Z_STREAM_ERROR,Z_DATA_ERROR:g.Z_DATA_ERROR,Z_MEM_ERROR:g.Z_MEM_ERROR,Z_BUF_ERROR:g.Z_BUF_ERROR,Z_VERSION_ERROR:g.Z_VERSION_ERROR},Object.keys(e.codes).forEach(function(t){e.codes[e.codes[t]]=t}),e.Deflate=a,e.Inflate=s,e.Gzip=c,e.Gunzip=l,e.DeflateRaw=h,e.InflateRaw=u,e.Unzip=f,e.createDeflate=function(t){return new a(t)},e.createInflate=function(t){return new s(t)},e.createDeflateRaw=function(t){return new h(t)},e.createInflateRaw=function(t){return new u(t)},e.createGzip=function(t){return new c(t)},e.createGunzip=function(t){return new l(t)},e.createUnzip=function(t){return new f(t)},e.deflate=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new a(e),t,r)},e.deflateSync=function(t,e){return o(new a(e),t)},e.gzip=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new c(e),t,r)},e.gzipSync=function(t,e){return o(new c(e),t)},e.deflateRaw=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new h(e),t,r)},e.deflateRawSync=function(t,e){return o(new h(e),t)},e.unzip=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new f(e),t,r)},e.unzipSync=function(t,e){return o(new f(e),t)},e.inflate=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new s(e),t,r)},e.inflateSync=function(t,e){return o(new s(e),t)},e.gunzip=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new l(e),t,r)},e.gunzipSync=function(t,e){return o(new l(e),t)},e.inflateRaw=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new u(e),t,r)},e.inflateRawSync=function(t,e){return o(new u(e),t)},v.inherits(d,p),d.prototype.params=function(t,r,n){if(t<e.Z_MIN_LEVEL||t>e.Z_MAX_LEVEL)throw new RangeError("Invalid compression level: "+t);if(r!=e.Z_FILTERED&&r!=e.Z_HUFFMAN_ONLY&&r!=e.Z_RLE&&r!=e.Z_FIXED&&r!=e.Z_DEFAULT_STRATEGY)throw new TypeError("Invalid strategy: "+r);if(this._level!==t||this._strategy!==r){var o=this;this.flush(g.Z_SYNC_FLUSH,function(){o._binding.params(t,r),o._hadError||(o._level=t,o._strategy=r,n&&n())})}else i.nextTick(n)},d.prototype.reset=function(){return this._binding.reset()},d.prototype._flush=function(e){this._transform(new t(0),"",e)},d.prototype.flush=function(e,r){var n=this._writableState;if(("function"==typeof e||void 0===e&&!r)&&(r=e,e=g.Z_FULL_FLUSH),n.ended)r&&i.nextTick(r);else if(n.ending)r&&this.once("end",r);else if(n.needDrain){var o=this;this.once("drain",function(){o.flush(r)})}else this._flushFlag=e,this.write(new t(0),"",r)},d.prototype.close=function(t){if(t&&i.nextTick(t),!this._closed){this._closed=!0,this._binding.close();var e=this;i.nextTick(function(){e.emit("close")})}},d.prototype._transform=function(e,r,i){var n,o=this._writableState,a=o.ending||o.ended,s=a&&(!e||o.length===e.length);if(null===!e&&!t.isBuffer(e))return i(new Error("invalid input"));s?n=g.Z_FINISH:(n=this._flushFlag,e.length>=o.length&&(this._flushFlag=this._opts.flush||g.Z_NO_FLUSH));var c=this;this._processChunk(e,n,i)},d.prototype._processChunk=function(e,r,i){function n(f,d){if(!c._hadError){var p=a-d;if(m(p>=0,"have should not go down"),p>0){var g=c._buffer.slice(c._offset,c._offset+p);c._offset+=p,l?c.push(g):(h.push(g),u+=g.length)}if((0===d||c._offset>=c._chunkSize)&&(a=c._chunkSize,c._offset=0,c._buffer=new t(c._chunkSize)),0===d){if(s+=o-f,o=f,!l)return!0;var v=c._binding.write(r,e,s,o,c._buffer,c._offset,c._chunkSize);return v.callback=n,void(v.buffer=e)}if(!l)return!1;i()}}var o=e&&e.length,a=this._chunkSize-this._offset,s=0,c=this,l="function"==typeof i;if(!l){var h=[],u=0,f;this.on("error",function(t){f=t});do{var d=this._binding.writeSync(r,e,s,o,this._buffer,this._offset,a)}while(!this._hadError&&n(d[0],d[1]));if(this._hadError)throw f;var p=t.concat(h,u);return this.close(),p}var g=this._binding.write(r,e,s,o,this._buffer,this._offset,a);g.buffer=e,g.callback=n},v.inherits(a,d),v.inherits(s,d),v.inherits(c,d),v.inherits(l,d),v.inherits(h,d),v.inherits(u,d),v.inherits(f,d)}).call(e,r(2).Buffer,r(1))},function(t,e,r){t.exports=r(9).Transform},function(t,e){},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e,r){t.copy(e,r)}var o=r(10).Buffer;t.exports=function(){function t(){i(this,t),this.head=null,this.tail=null,this.length=0}return t.prototype.push=function t(e){var r={data:e,next:null};this.length>0?this.tail.next=r:this.head=r,this.tail=r,++this.length},t.prototype.unshift=function t(e){var r={data:e,next:this.head};0===this.length&&(this.tail=r),this.head=r,++this.length},t.prototype.shift=function t(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},t.prototype.clear=function t(){this.head=this.tail=null,this.length=0},t.prototype.join=function t(e){if(0===this.length)return"";for(var r=this.head,i=""+r.data;r=r.next;)i+=e+r.data;return i},t.prototype.concat=function t(e){if(0===this.length)return o.alloc(0);if(1===this.length)return this.head.data;for(var r=o.allocUnsafe(e>>>0),i=this.head,a=0;i;)n(i.data,r,a),a+=i.data.length,i=i.next;return r},t}()},function(t,e,r){function i(t,e){this._id=t,this._clearFn=e}var n=Function.prototype.apply;e.setTimeout=function(){return new i(n.call(setTimeout,window,arguments),clearTimeout)},e.setInterval=function(){return new i(n.call(setInterval,window,arguments),clearInterval)},e.clearTimeout=e.clearInterval=function(t){t&&t.close()},i.prototype.unref=i.prototype.ref=function(){},i.prototype.close=function(){this._clearFn.call(window,this._id)},e.enroll=function(t,e){clearTimeout(t._idleTimeoutId),t._idleTimeout=e},e.unenroll=function(t){clearTimeout(t._idleTimeoutId),t._idleTimeout=-1},e._unrefActive=e.active=function(t){clearTimeout(t._idleTimeoutId);var e=t._idleTimeout;e>=0&&(t._idleTimeoutId=setTimeout(function e(){t._onTimeout&&t._onTimeout()},e))},r(47),e.setImmediate=setImmediate,e.clearImmediate=clearImmediate},function(t,e,r){(function(t,e){!function(t,r){"use strict";function i(t){"function"!=typeof t&&(t=new Function(""+t));for(var e=new Array(arguments.length-1),r=0;r<e.length;r++)e[r]=arguments[r+1];var i={callback:t,args:e};return p[d]=i,m(d),d++}function n(t){delete p[t]}function o(t){var e=t.callback,i=t.args;switch(i.length){case 0:e();break;case 1:e(i[0]);break;case 2:e(i[0],i[1]);break;case 3:e(i[0],i[1],i[2]);break;default:e.apply(r,i)}}function a(t){if(g)setTimeout(a,0,t);else{var e=p[t];if(e){g=!0;try{o(e)}finally{n(t),g=!1}}}}function s(){m=function(t){e.nextTick(function(){a(t)})}}function c(){if(t.postMessage&&!t.importScripts){var e=!0,r=t.onmessage;return t.onmessage=function(){e=!1},t.postMessage("","*"),t.onmessage=r,e}}function l(){var e="setImmediate$"+Math.random()+"$",r=function(r){r.source===t&&"string"==typeof r.data&&0===r.data.indexOf(e)&&a(+r.data.slice(e.length))};t.addEventListener?t.addEventListener("message",r,!1):t.attachEvent("onmessage",r),m=function(r){t.postMessage(e+r,"*")}}function h(){var t=new MessageChannel;t.port1.onmessage=function(t){a(t.data)},m=function(e){t.port2.postMessage(e)}}function u(){var t=v.documentElement;m=function(e){var r=v.createElement("script");r.onreadystatechange=function(){a(e),r.onreadystatechange=null,t.removeChild(r),r=null},t.appendChild(r)}}function f(){m=function(t){setTimeout(a,0,t)}}if(!t.setImmediate){var d=1,p={},g=!1,v=t.document,m,b=Object.getPrototypeOf&&Object.getPrototypeOf(t);b=b&&b.setTimeout?b:t,"[object process]"==={}.toString.call(t.process)?s():c()?l():t.MessageChannel?h():v&&"onreadystatechange"in v.createElement("script")?u():f(),b.setImmediate=i,b.clearImmediate=n}}("undefined"==typeof self?void 0===t?this:t:self)}).call(e,r(0),r(1))},function(t,e,r){(function(e){function r(t,e){function r(){if(!n){if(i("throwDeprecation"))throw new Error(e);i("traceDeprecation")?console.trace(e):console.warn(e),n=!0}return t.apply(this,arguments)}if(i("noDeprecation"))return t;var n=!1;return r}function i(t){try{if(!e.localStorage)return!1}catch(t){return!1}var r=e.localStorage[t];return null!=r&&"true"===String(r).toLowerCase()}t.exports=r}).call(e,r(0))},function(t,e,r){"use strict";function i(t){if(!(this instanceof i))return new i(t);n.call(this,t)}t.exports=i;var n=r(20),o=r(5);o.inherits=r(3),o.inherits(i,n),i.prototype._transform=function(t,e,r){r(null,t)}},function(t,e,r){(function(t,i){function n(t){if(t<e.DEFLATE||t>e.UNZIP)throw new TypeError("Bad argument");this.mode=t,this.init_done=!1,this.write_in_progress=!1,this.pending_close=!1,this.windowBits=0,this.level=0,this.memLevel=0,this.strategy=0,this.dictionary=null}function o(t,e){for(var r=0;r<t.length;r++)this[e+r]=t[r]}var a=r(21),s=r(51),c=r(52),l=r(54),h=r(57);for(var u in h)e[u]=h[u];e.NONE=0,e.DEFLATE=1,e.INFLATE=2,e.GZIP=3,e.GUNZIP=4,e.DEFLATERAW=5,e.INFLATERAW=6,e.UNZIP=7,n.prototype.init=function(t,r,i,n,o){switch(this.windowBits=t,this.level=r,this.memLevel=i,this.strategy=n,this.mode!==e.GZIP&&this.mode!==e.GUNZIP||(this.windowBits+=16),this.mode===e.UNZIP&&(this.windowBits+=32),this.mode!==e.DEFLATERAW&&this.mode!==e.INFLATERAW||(this.windowBits=-this.windowBits),this.strm=new s,this.mode){case e.DEFLATE:case e.GZIP:case e.DEFLATERAW:var a=c.deflateInit2(this.strm,this.level,e.Z_DEFLATED,this.windowBits,this.memLevel,this.strategy);break;case e.INFLATE:case e.GUNZIP:case e.INFLATERAW:case e.UNZIP:var a=l.inflateInit2(this.strm,this.windowBits);break;default:throw new Error("Unknown mode "+this.mode)}if(a!==e.Z_OK)return void this._error(a);this.write_in_progress=!1,this.init_done=!0},n.prototype.params=function(){throw new Error("deflateParams Not supported")},n.prototype._writeCheck=function(){if(!this.init_done)throw new Error("write before init");if(this.mode===e.NONE)throw new Error("already finalized");if(this.write_in_progress)throw new Error("write already in progress");if(this.pending_close)throw new Error("close is pending")},n.prototype.write=function(e,r,i,n,o,a,s){this._writeCheck(),this.write_in_progress=!0;var c=this;return t.nextTick(function(){c.write_in_progress=!1;var t=c._write(e,r,i,n,o,a,s);c.callback(t[0],t[1]),c.pending_close&&c.close()}),this},n.prototype.writeSync=function(t,e,r,i,n,o,a){return this._writeCheck(),this._write(t,e,r,i,n,o,a)},n.prototype._write=function(t,r,n,a,s,h,u){if(this.write_in_progress=!0,t!==e.Z_NO_FLUSH&&t!==e.Z_PARTIAL_FLUSH&&t!==e.Z_SYNC_FLUSH&&t!==e.Z_FULL_FLUSH&&t!==e.Z_FINISH&&t!==e.Z_BLOCK)throw new Error("Invalid flush value");null==r&&(r=new i(0),a=0,n=0),s._set?s.set=s._set:s.set=o;var f=this.strm;switch(f.avail_in=a,f.input=r,f.next_in=n,f.avail_out=u,f.output=s,f.next_out=h,this.mode){case e.DEFLATE:case e.GZIP:case e.DEFLATERAW:var d=c.deflate(f,t);break;case e.UNZIP:case e.INFLATE:case e.GUNZIP:case e.INFLATERAW:var d=l.inflate(f,t);break;default:throw new Error("Unknown mode "+this.mode)}return d!==e.Z_STREAM_END&&d!==e.Z_OK&&this._error(d),this.write_in_progress=!1,[f.avail_in,f.avail_out]},n.prototype.close=function(){if(this.write_in_progress)return void(this.pending_close=!0);this.pending_close=!1,this.mode===e.DEFLATE||this.mode===e.GZIP||this.mode===e.DEFLATERAW?c.deflateEnd(this.strm):l.inflateEnd(this.strm),this.mode=e.NONE},n.prototype.reset=function(){switch(this.mode){case e.DEFLATE:case e.DEFLATERAW:var t=c.deflateReset(this.strm);break;case e.INFLATE:case e.INFLATERAW:var t=l.inflateReset(this.strm)}t!==e.Z_OK&&this._error(t)},n.prototype._error=function(t){this.onerror(a[t]+": "+this.strm.msg,t),this.write_in_progress=!1,this.pending_close&&this.close()},e.Zlib=n}).call(e,r(1),r(2).Buffer)},function(t,e,r){"use strict";function i(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}t.exports=i},function(t,e,r){"use strict";function i(t,e){return t.msg=D[e],e}function n(t){return(t<<1)-(t>4?9:0)}function o(t){for(var e=t.length;--e>=0;)t[e]=0}function a(t){var e=t.state,r=e.pending;r>t.avail_out&&(r=t.avail_out),0!==r&&(E.arraySet(t.output,e.pending_buf,e.pending_out,r,t.next_out),t.next_out+=r,e.pending_out+=r,t.total_out+=r,t.avail_out-=r,e.pending-=r,0===e.pending&&(e.pending_out=0))}function s(t,e){O._tr_flush_block(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,a(t.strm)}function c(t,e){t.pending_buf[t.pending++]=e}function l(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e}function h(t,e,r,i){var n=t.avail_in;return n>i&&(n=i),0===n?0:(t.avail_in-=n,E.arraySet(e,t.input,t.next_in,n,r),1===t.state.wrap?t.adler=R(t.adler,e,n,r):2===t.state.wrap&&(t.adler=L(t.adler,e,n,r)),t.next_in+=n,t.total_in+=n,n)}function u(t,e){var r=t.max_chain_length,i=t.strstart,n,o,a=t.prev_length,s=t.nice_match,c=t.strstart>t.w_size-ht?t.strstart-(t.w_size-ht):0,l=t.window,h=t.w_mask,u=t.prev,f=t.strstart+lt,d=l[i+a-1],p=l[i+a];t.prev_length>=t.good_match&&(r>>=2),s>t.lookahead&&(s=t.lookahead);do{if(n=e,l[n+a]===p&&l[n+a-1]===d&&l[n]===l[i]&&l[++n]===l[i+1]){i+=2,n++;do{}while(l[++i]===l[++n]&&l[++i]===l[++n]&&l[++i]===l[++n]&&l[++i]===l[++n]&&l[++i]===l[++n]&&l[++i]===l[++n]&&l[++i]===l[++n]&&l[++i]===l[++n]&&i<f);if(o=lt-(f-i),i=f-lt,o>a){if(t.match_start=e,a=o,o>=s)break;d=l[i+a-1],p=l[i+a]}}}while((e=u[e&h])>c&&0!=--r);return a<=t.lookahead?a:t.lookahead}function f(t){var e=t.w_size,r,i,n,o,a;do{if(o=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-ht)){E.arraySet(t.window,t.window,e,e,0),t.match_start-=e,t.strstart-=e,t.block_start-=e,i=t.hash_size,r=i;do{n=t.head[--r],t.head[r]=n>=e?n-e:0}while(--i);i=e,r=i;do{n=t.prev[--r],t.prev[r]=n>=e?n-e:0}while(--i);o+=e}if(0===t.strm.avail_in)break;if(i=h(t.strm,t.window,t.strstart+t.lookahead,o),t.lookahead+=i,t.lookahead+t.insert>=ct)for(a=t.strstart-t.insert,t.ins_h=t.window[a],t.ins_h=(t.ins_h<<t.hash_shift^t.window[a+1])&t.hash_mask;t.insert&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[a+ct-1])&t.hash_mask,t.prev[a&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=a,a++,t.insert--,!(t.lookahead+t.insert<ct)););}while(t.lookahead<ht&&0!==t.strm.avail_in)}function d(t,e){var r=65535;for(r>t.pending_buf_size-5&&(r=t.pending_buf_size-5);;){if(t.lookahead<=1){if(f(t),0===t.lookahead&&e===I)return yt;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;var i=t.block_start+r;if((0===t.strstart||t.strstart>=i)&&(t.lookahead=t.strstart-i,t.strstart=i,s(t,!1),0===t.strm.avail_out))return yt;if(t.strstart-t.block_start>=t.w_size-ht&&(s(t,!1),0===t.strm.avail_out))return yt}return t.insert=0,e===F?(s(t,!0),0===t.strm.avail_out?wt:St):(t.strstart>t.block_start&&(s(t,!1),t.strm.avail_out),yt)}function p(t,e){for(var r,i;;){if(t.lookahead<ht){if(f(t),t.lookahead<ht&&e===I)return yt;if(0===t.lookahead)break}if(r=0,t.lookahead>=ct&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+ct-1])&t.hash_mask,r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==r&&t.strstart-r<=t.w_size-ht&&(t.match_length=u(t,r)),t.match_length>=ct)if(i=O._tr_tally(t,t.strstart-t.match_start,t.match_length-ct),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=ct){t.match_length--;do{t.strstart++,t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+ct-1])&t.hash_mask,r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!=--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+1])&t.hash_mask;else i=O._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(i&&(s(t,!1),0===t.strm.avail_out))return yt}return t.insert=t.strstart<ct-1?t.strstart:ct-1,e===F?(s(t,!0),0===t.strm.avail_out?wt:St):t.last_lit&&(s(t,!1),0===t.strm.avail_out)?yt:_t}function g(t,e){for(var r,i,n;;){if(t.lookahead<ht){if(f(t),t.lookahead<ht&&e===I)return yt;if(0===t.lookahead)break}if(r=0,t.lookahead>=ct&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+ct-1])&t.hash_mask,r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=ct-1,0!==r&&t.prev_length<t.max_lazy_match&&t.strstart-r<=t.w_size-ht&&(t.match_length=u(t,r),t.match_length<=5&&(t.strategy===G||t.match_length===ct&&t.strstart-t.match_start>4096)&&(t.match_length=ct-1)),t.prev_length>=ct&&t.match_length<=t.prev_length){n=t.strstart+t.lookahead-ct,i=O._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-ct),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=n&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+ct-1])&t.hash_mask,r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!=--t.prev_length);if(t.match_available=0,t.match_length=ct-1,t.strstart++,i&&(s(t,!1),0===t.strm.avail_out))return yt}else if(t.match_available){if(i=O._tr_tally(t,0,t.window[t.strstart-1]),i&&s(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return yt}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(i=O._tr_tally(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<ct-1?t.strstart:ct-1,e===F?(s(t,!0),0===t.strm.avail_out?wt:St):t.last_lit&&(s(t,!1),0===t.strm.avail_out)?yt:_t}function v(t,e){for(var r,i,n,o,a=t.window;;){if(t.lookahead<=lt){if(f(t),t.lookahead<=lt&&e===I)return yt;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=ct&&t.strstart>0&&(n=t.strstart-1,(i=a[n])===a[++n]&&i===a[++n]&&i===a[++n])){o=t.strstart+lt;do{}while(i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&n<o);t.match_length=lt-(o-n),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=ct?(r=O._tr_tally(t,1,t.match_length-ct),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(r=O._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),r&&(s(t,!1),0===t.strm.avail_out))return yt}return t.insert=0,e===F?(s(t,!0),0===t.strm.avail_out?wt:St):t.last_lit&&(s(t,!1),0===t.strm.avail_out)?yt:_t}function m(t,e){for(var r;;){if(0===t.lookahead&&(f(t),0===t.lookahead)){if(e===I)return yt;break}if(t.match_length=0,r=O._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,r&&(s(t,!1),0===t.strm.avail_out))return yt}return t.insert=0,e===F?(s(t,!0),0===t.strm.avail_out?wt:St):t.last_lit&&(s(t,!1),0===t.strm.avail_out)?yt:_t}function b(t,e,r,i,n){this.good_length=t,this.max_lazy=e,this.nice_length=r,this.max_chain=i,this.func=n}function y(t){t.window_size=2*t.w_size,o(t.head),t.max_lazy_match=Ct[t.level].max_lazy,t.good_match=Ct[t.level].good_length,t.nice_match=Ct[t.level].nice_length,t.max_chain_length=Ct[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=ct-1,t.match_available=0,t.ins_h=0}function _(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=K,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new E.Buf16(2*at),this.dyn_dtree=new E.Buf16(2*(2*nt+1)),this.bl_tree=new E.Buf16(2*(2*ot+1)),o(this.dyn_ltree),o(this.dyn_dtree),o(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new E.Buf16(st+1),this.heap=new E.Buf16(2*it+1),o(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new E.Buf16(2*it+1),o(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function w(t){var e;return t&&t.state?(t.total_in=t.total_out=0,t.data_type=J,e=t.state,e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?ft:mt,t.adler=2===e.wrap?0:1,e.last_flush=I,O._tr_init(e),B):i(t,z)}function S(t){var e=w(t);return e===B&&y(t.state),e}function x(t,e){return t&&t.state?2!==t.state.wrap?z:(t.state.gzhead=e,B):z}function C(t,e,r,n,o,a){if(!t)return z;var s=1;if(e===X&&(e=6),n<0?(s=0,n=-n):n>15&&(s=2,n-=16),o<1||o>Q||r!==K||n<8||n>15||e<0||e>9||a<0||a>V)return i(t,z);8===n&&(n=9);var c=new _;return t.state=c,c.strm=t,c.wrap=s,c.gzhead=null,c.w_bits=n,c.w_size=1<<c.w_bits,c.w_mask=c.w_size-1,c.hash_bits=o+7,c.hash_size=1<<c.hash_bits,c.hash_mask=c.hash_size-1,c.hash_shift=~~((c.hash_bits+ct-1)/ct),c.window=new E.Buf8(2*c.w_size),c.head=new E.Buf16(c.hash_size),c.prev=new E.Buf16(c.w_size),c.lit_bufsize=1<<o+6,c.pending_buf_size=4*c.lit_bufsize,c.pending_buf=new E.Buf8(c.pending_buf_size),c.d_buf=1*c.lit_bufsize,c.l_buf=3*c.lit_bufsize,c.level=e,c.strategy=a,c.method=r,S(t)}function A(t,e){return C(t,e,K,$,tt,Z)}function T(t,e){var r,s,h,u;if(!t||!t.state||e>N||e<0)return t?i(t,z):z;if(s=t.state,!t.output||!t.input&&0!==t.avail_in||s.status===bt&&e!==F)return i(t,0===t.avail_out?q:z);if(s.strm=t,r=s.last_flush,s.last_flush=e,s.status===ft)if(2===s.wrap)t.adler=0,c(s,31),c(s,139),c(s,8),s.gzhead?(c(s,(s.gzhead.text?1:0)+(s.gzhead.hcrc?2:0)+(s.gzhead.extra?4:0)+(s.gzhead.name?8:0)+(s.gzhead.comment?16:0)),c(s,255&s.gzhead.time),c(s,s.gzhead.time>>8&255),c(s,s.gzhead.time>>16&255),c(s,s.gzhead.time>>24&255),c(s,9===s.level?2:s.strategy>=H||s.level<2?4:0),c(s,255&s.gzhead.os),s.gzhead.extra&&s.gzhead.extra.length&&(c(s,255&s.gzhead.extra.length),c(s,s.gzhead.extra.length>>8&255)),s.gzhead.hcrc&&(t.adler=L(t.adler,s.pending_buf,s.pending,0)),s.gzindex=0,s.status=dt):(c(s,0),c(s,0),c(s,0),c(s,0),c(s,0),c(s,9===s.level?2:s.strategy>=H||s.level<2?4:0),c(s,xt),s.status=mt);else{var f=K+(s.w_bits-8<<4)<<8,d=-1;d=s.strategy>=H||s.level<2?0:s.level<6?1:6===s.level?2:3,f|=d<<6,0!==s.strstart&&(f|=ut),f+=31-f%31,s.status=mt,l(s,f),0!==s.strstart&&(l(s,t.adler>>>16),l(s,65535&t.adler)),t.adler=1}if(s.status===dt)if(s.gzhead.extra){for(h=s.pending;s.gzindex<(65535&s.gzhead.extra.length)&&(s.pending!==s.pending_buf_size||(s.gzhead.hcrc&&s.pending>h&&(t.adler=L(t.adler,s.pending_buf,s.pending-h,h)),a(t),h=s.pending,s.pending!==s.pending_buf_size));)c(s,255&s.gzhead.extra[s.gzindex]),s.gzindex++;s.gzhead.hcrc&&s.pending>h&&(t.adler=L(t.adler,s.pending_buf,s.pending-h,h)),s.gzindex===s.gzhead.extra.length&&(s.gzindex=0,s.status=pt)}else s.status=pt;if(s.status===pt)if(s.gzhead.name){h=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>h&&(t.adler=L(t.adler,s.pending_buf,s.pending-h,h)),a(t),h=s.pending,s.pending===s.pending_buf_size)){u=1;break}u=s.gzindex<s.gzhead.name.length?255&s.gzhead.name.charCodeAt(s.gzindex++):0,c(s,u)}while(0!==u);s.gzhead.hcrc&&s.pending>h&&(t.adler=L(t.adler,s.pending_buf,s.pending-h,h)),0===u&&(s.gzindex=0,s.status=gt)}else s.status=gt;if(s.status===gt)if(s.gzhead.comment){h=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>h&&(t.adler=L(t.adler,s.pending_buf,s.pending-h,h)),a(t),h=s.pending,s.pending===s.pending_buf_size)){u=1;break}u=s.gzindex<s.gzhead.comment.length?255&s.gzhead.comment.charCodeAt(s.gzindex++):0,c(s,u)}while(0!==u);s.gzhead.hcrc&&s.pending>h&&(t.adler=L(t.adler,s.pending_buf,s.pending-h,h)),0===u&&(s.status=vt)}else s.status=vt;if(s.status===vt&&(s.gzhead.hcrc?(s.pending+2>s.pending_buf_size&&a(t),s.pending+2<=s.pending_buf_size&&(c(s,255&t.adler),c(s,t.adler>>8&255),t.adler=0,s.status=mt)):s.status=mt),0!==s.pending){if(a(t),0===t.avail_out)return s.last_flush=-1,B}else if(0===t.avail_in&&n(e)<=n(r)&&e!==F)return i(t,q);if(s.status===bt&&0!==t.avail_in)return i(t,q);if(0!==t.avail_in||0!==s.lookahead||e!==I&&s.status!==bt){var p=s.strategy===H?m(s,e):s.strategy===Y?v(s,e):Ct[s.level].func(s,e);if(p!==wt&&p!==St||(s.status=bt),p===yt||p===wt)return 0===t.avail_out&&(s.last_flush=-1),B;if(p===_t&&(e===j?O._tr_align(s):e!==N&&(O._tr_stored_block(s,0,0,!1),e===M&&(o(s.head),0===s.lookahead&&(s.strstart=0,s.block_start=0,s.insert=0))),a(t),0===t.avail_out))return s.last_flush=-1,B}return e!==F?B:s.wrap<=0?U:(2===s.wrap?(c(s,255&t.adler),c(s,t.adler>>8&255),c(s,t.adler>>16&255),c(s,t.adler>>24&255),c(s,255&t.total_in),c(s,t.total_in>>8&255),c(s,t.total_in>>16&255),c(s,t.total_in>>24&255)):(l(s,t.adler>>>16),l(s,65535&t.adler)),a(t),s.wrap>0&&(s.wrap=-s.wrap),0!==s.pending?B:U)}function k(t){var e;return t&&t.state?(e=t.state.status)!==ft&&e!==dt&&e!==pt&&e!==gt&&e!==vt&&e!==mt&&e!==bt?i(t,z):(t.state=null,e===mt?i(t,W):B):z}function P(t,e){var r=e.length,i,n,a,s,c,l,h,u;if(!t||!t.state)return z;if(i=t.state,2===(s=i.wrap)||1===s&&i.status!==ft||i.lookahead)return z;for(1===s&&(t.adler=R(t.adler,e,r,0)),i.wrap=0,r>=i.w_size&&(0===s&&(o(i.head),i.strstart=0,i.block_start=0,i.insert=0),u=new E.Buf8(i.w_size),E.arraySet(u,e,r-i.w_size,i.w_size,0),e=u,r=i.w_size),c=t.avail_in,l=t.next_in,h=t.input,t.avail_in=r,t.next_in=0,t.input=e,f(i);i.lookahead>=ct;){n=i.strstart,a=i.lookahead-(ct-1);do{i.ins_h=(i.ins_h<<i.hash_shift^i.window[n+ct-1])&i.hash_mask,i.prev[n&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=n,n++}while(--a);i.strstart=n,i.lookahead=ct-1,f(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=ct-1,i.match_available=0,t.next_in=l,t.input=h,t.avail_in=c,i.wrap=s,B}var E=r(8),O=r(53),R=r(22),L=r(23),D=r(21),I=0,j=1,M=3,F=4,N=5,B=0,U=1,z=-2,W=-3,q=-5,X=-1,G=1,H=2,Y=3,V=4,Z=0,J=2,K=8,Q=9,$=15,tt=8,et=29,rt=256,it=286,nt=30,ot=19,at=2*it+1,st=15,ct=3,lt=258,ht=lt+ct+1,ut=32,ft=42,dt=69,pt=73,gt=91,vt=103,mt=113,bt=666,yt=1,_t=2,wt=3,St=4,xt=3,Ct;Ct=[new b(0,0,0,0,d),new b(4,4,8,4,p),new b(4,5,16,8,p),new b(4,6,32,32,p),new b(4,4,16,16,g),new b(8,16,32,32,g),new b(8,16,128,128,g),new b(8,32,128,256,g),new b(32,128,258,1024,g),new b(32,258,258,4096,g)],e.deflateInit=A,e.deflateInit2=C,e.deflateReset=S,e.deflateResetKeep=w,e.deflateSetHeader=x,e.deflate=T,e.deflateEnd=k,e.deflateSetDictionary=P,e.deflateInfo="pako deflate (from Nodeca project)"},function(t,e,r){"use strict";function i(t){for(var e=t.length;--e>=0;)t[e]=0}function n(t,e,r,i,n){this.static_tree=t,this.extra_bits=e,this.extra_base=r,this.elems=i,this.max_length=n,this.has_stree=t&&t.length}function o(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}function a(t){return t<256?ct[t]:ct[256+(t>>>7)]}function s(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255}function c(t,e,r){t.bi_valid>Z-r?(t.bi_buf|=e<<t.bi_valid&65535,s(t,t.bi_buf),t.bi_buf=e>>Z-t.bi_valid,t.bi_valid+=r-Z):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=r)}function l(t,e,r){c(t,r[2*e],r[2*e+1])}function h(t,e){var r=0;do{r|=1&t,t>>>=1,r<<=1}while(--e>0);return r>>>1}function u(t){16===t.bi_valid?(s(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)}function f(t,e){var r=e.dyn_tree,i=e.max_code,n=e.stat_desc.static_tree,o=e.stat_desc.has_stree,a=e.stat_desc.extra_bits,s=e.stat_desc.extra_base,c=e.stat_desc.max_length,l,h,u,f,d,p,g=0;for(f=0;f<=V;f++)t.bl_count[f]=0;for(r[2*t.heap[t.heap_max]+1]=0,l=t.heap_max+1;l<Y;l++)h=t.heap[l],f=r[2*r[2*h+1]+1]+1,f>c&&(f=c,g++),r[2*h+1]=f,h>i||(t.bl_count[f]++,d=0,h>=s&&(d=a[h-s]),p=r[2*h],t.opt_len+=p*(f+d),o&&(t.static_len+=p*(n[2*h+1]+d)));if(0!==g){do{for(f=c-1;0===t.bl_count[f];)f--;t.bl_count[f]--,t.bl_count[f+1]+=2,t.bl_count[c]--,g-=2}while(g>0);for(f=c;0!==f;f--)for(h=t.bl_count[f];0!==h;)(u=t.heap[--l])>i||(r[2*u+1]!==f&&(t.opt_len+=(f-r[2*u+1])*r[2*u],r[2*u+1]=f),h--)}}function d(t,e,r){var i=new Array(V+1),n=0,o,a;for(o=1;o<=V;o++)i[o]=n=n+r[o-1]<<1;for(a=0;a<=e;a++){var s=t[2*a+1];0!==s&&(t[2*a]=h(i[s]++,s))}}function p(){var t,e,r,i,o,a=new Array(V+1);for(r=0,i=0;i<W-1;i++)for(ht[i]=r,t=0;t<1<<et[i];t++)lt[r++]=i;for(lt[r-1]=i,o=0,i=0;i<16;i++)for(ut[i]=o,t=0;t<1<<rt[i];t++)ct[o++]=i;for(o>>=7;i<G;i++)for(ut[i]=o<<7,t=0;t<1<<rt[i]-7;t++)ct[256+o++]=i;for(e=0;e<=V;e++)a[e]=0;for(t=0;t<=143;)at[2*t+1]=8,t++,a[8]++;for(;t<=255;)at[2*t+1]=9,t++,a[9]++;for(;t<=279;)at[2*t+1]=7,t++,a[7]++;for(;t<=287;)at[2*t+1]=8,t++,a[8]++;for(d(at,X+1,a),t=0;t<G;t++)st[2*t+1]=5,st[2*t]=h(t,5);ft=new n(at,et,q+1,X,V),dt=new n(st,rt,0,G,V),pt=new n(new Array(0),it,0,H,J)}function g(t){var e;for(e=0;e<X;e++)t.dyn_ltree[2*e]=0;for(e=0;e<G;e++)t.dyn_dtree[2*e]=0;for(e=0;e<H;e++)t.bl_tree[2*e]=0;t.dyn_ltree[2*K]=1,t.opt_len=t.static_len=0,t.last_lit=t.matches=0}function v(t){t.bi_valid>8?s(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0}function m(t,e,r,i){v(t),i&&(s(t,r),s(t,~r)),L.arraySet(t.pending_buf,t.window,e,r,t.pending),t.pending+=r}function b(t,e,r,i){var n=2*e,o=2*r;return t[n]<t[o]||t[n]===t[o]&&i[e]<=i[r]}function y(t,e,r){for(var i=t.heap[r],n=r<<1;n<=t.heap_len&&(n<t.heap_len&&b(e,t.heap[n+1],t.heap[n],t.depth)&&n++,!b(e,i,t.heap[n],t.depth));)t.heap[r]=t.heap[n],r=n,n<<=1;t.heap[r]=i}function _(t,e,r){var i,n,o=0,s,h;if(0!==t.last_lit)do{i=t.pending_buf[t.d_buf+2*o]<<8|t.pending_buf[t.d_buf+2*o+1],n=t.pending_buf[t.l_buf+o],o++,0===i?l(t,n,e):(s=lt[n],l(t,s+q+1,e),h=et[s],0!==h&&(n-=ht[s],c(t,n,h)),i--,s=a(i),l(t,s,r),0!==(h=rt[s])&&(i-=ut[s],c(t,i,h)))}while(o<t.last_lit);l(t,K,e)}function w(t,e){var r=e.dyn_tree,i=e.stat_desc.static_tree,n=e.stat_desc.has_stree,o=e.stat_desc.elems,a,s,c=-1,l;for(t.heap_len=0,t.heap_max=Y,a=0;a<o;a++)0!==r[2*a]?(t.heap[++t.heap_len]=c=a,t.depth[a]=0):r[2*a+1]=0;for(;t.heap_len<2;)l=t.heap[++t.heap_len]=c<2?++c:0,r[2*l]=1,t.depth[l]=0,t.opt_len--,n&&(t.static_len-=i[2*l+1]);for(e.max_code=c,a=t.heap_len>>1;a>=1;a--)y(t,r,a);l=o;do{a=t.heap[1],t.heap[1]=t.heap[t.heap_len--],y(t,r,1),s=t.heap[1],t.heap[--t.heap_max]=a,t.heap[--t.heap_max]=s,r[2*l]=r[2*a]+r[2*s],t.depth[l]=(t.depth[a]>=t.depth[s]?t.depth[a]:t.depth[s])+1,r[2*a+1]=r[2*s+1]=l,t.heap[1]=l++,y(t,r,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],f(t,e),d(r,c,t.bl_count)}function S(t,e,r){var i,n=-1,o,a=e[1],s=0,c=7,l=4;for(0===a&&(c=138,l=3),e[2*(r+1)+1]=65535,i=0;i<=r;i++)o=a,a=e[2*(i+1)+1],++s<c&&o===a||(s<l?t.bl_tree[2*o]+=s:0!==o?(o!==n&&t.bl_tree[2*o]++,t.bl_tree[2*Q]++):s<=10?t.bl_tree[2*$]++:t.bl_tree[2*tt]++,s=0,n=o,0===a?(c=138,l=3):o===a?(c=6,l=3):(c=7,l=4))}function x(t,e,r){var i,n=-1,o,a=e[1],s=0,h=7,u=4;for(0===a&&(h=138,u=3),i=0;i<=r;i++)if(o=a,a=e[2*(i+1)+1],!(++s<h&&o===a)){if(s<u)do{l(t,o,t.bl_tree)}while(0!=--s);else 0!==o?(o!==n&&(l(t,o,t.bl_tree),s--),l(t,Q,t.bl_tree),c(t,s-3,2)):s<=10?(l(t,$,t.bl_tree),c(t,s-3,3)):(l(t,tt,t.bl_tree),c(t,s-11,7));s=0,n=o,0===a?(h=138,u=3):o===a?(h=6,u=3):(h=7,u=4)}}function C(t){var e;for(S(t,t.dyn_ltree,t.l_desc.max_code),S(t,t.dyn_dtree,t.d_desc.max_code),w(t,t.bl_desc),e=H-1;e>=3&&0===t.bl_tree[2*nt[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e}function A(t,e,r,i){var n;for(c(t,e-257,5),c(t,r-1,5),c(t,i-4,4),n=0;n<i;n++)c(t,t.bl_tree[2*nt[n]+1],3);x(t,t.dyn_ltree,e-1),x(t,t.dyn_dtree,r-1)}function T(t){var e=4093624447,r;for(r=0;r<=31;r++,e>>>=1)if(1&e&&0!==t.dyn_ltree[2*r])return I;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return j;for(r=32;r<q;r++)if(0!==t.dyn_ltree[2*r])return j;return I}function k(t){gt||(p(),gt=!0),t.l_desc=new o(t.dyn_ltree,ft),t.d_desc=new o(t.dyn_dtree,dt),t.bl_desc=new o(t.bl_tree,pt),t.bi_buf=0,t.bi_valid=0,g(t)}function P(t,e,r,i){c(t,(F<<1)+(i?1:0),3),m(t,e,r,!0)}function E(t){c(t,N<<1,3),l(t,K,at),u(t)}function O(t,e,r,i){var n,o,a=0;t.level>0?(t.strm.data_type===M&&(t.strm.data_type=T(t)),w(t,t.l_desc),w(t,t.d_desc),a=C(t),n=t.opt_len+3+7>>>3,(o=t.static_len+3+7>>>3)<=n&&(n=o)):n=o=r+5,r+4<=n&&-1!==e?P(t,e,r,i):t.strategy===D||o===n?(c(t,(N<<1)+(i?1:0),3),_(t,at,st)):(c(t,(B<<1)+(i?1:0),3),A(t,t.l_desc.max_code+1,t.d_desc.max_code+1,a+1),_(t,t.dyn_ltree,t.dyn_dtree)),g(t),i&&v(t)}function R(t,e,r){return t.pending_buf[t.d_buf+2*t.last_lit]=e>>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&r,t.last_lit++,0===e?t.dyn_ltree[2*r]++:(t.matches++,e--,t.dyn_ltree[2*(lt[r]+q+1)]++,t.dyn_dtree[2*a(e)]++),t.last_lit===t.lit_bufsize-1}var L=r(8),D=4,I=0,j=1,M=2,F=0,N=1,B=2,U=3,z=258,W=29,q=256,X=q+1+W,G=30,H=19,Y=2*X+1,V=15,Z=16,J=7,K=256,Q=16,$=17,tt=18,et=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],rt=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],it=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],nt=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],ot=512,at=new Array(2*(X+2));i(at);var st=new Array(2*G);i(st);var ct=new Array(512);i(ct);var lt=new Array(256);i(lt);var ht=new Array(W);i(ht);var ut=new Array(G);i(ut);var ft,dt,pt,gt=!1;e._tr_init=k,e._tr_stored_block=P,e._tr_flush_block=O,e._tr_tally=R,e._tr_align=E},function(t,e,r){"use strict";function i(t){return(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24)}function n(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new v.Buf16(320),this.work=new v.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function o(t){var e;return t&&t.state?(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=j,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new v.Buf32(dt),e.distcode=e.distdyn=new v.Buf32(pt),e.sane=1,e.back=-1,k):O}function a(t){var e;return t&&t.state?(e=t.state,e.wsize=0,e.whave=0,e.wnext=0,o(t)):O}function s(t,e){var r,i;return t&&t.state?(i=t.state,e<0?(r=0,e=-e):(r=1+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?O:(null!==i.window&&i.wbits!==e&&(i.window=null),i.wrap=r,i.wbits=e,a(t))):O}function c(t,e){var r,i;return t?(i=new n,t.state=i,i.window=null,r=s(t,e),r!==k&&(t.state=null),r):O}function l(t){return c(t,vt)}function h(t){if(mt){var e;for(bt=new v.Buf32(512),yt=new v.Buf32(32),e=0;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(_(S,t.lens,0,288,bt,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;_(x,t.lens,0,32,yt,0,t.work,{bits:5}),mt=!1}t.lencode=bt,t.lenbits=9,t.distcode=yt,t.distbits=5}function u(t,e,r,i){var n,o=t.state;return null===o.window&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new v.Buf8(o.wsize)),i>=o.wsize?(v.arraySet(o.window,e,r-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(n=o.wsize-o.wnext,n>i&&(n=i),v.arraySet(o.window,e,r-i,n,o.wnext),i-=n,i?(v.arraySet(o.window,e,r-i,i,0),o.wnext=i,o.whave=o.wsize):(o.wnext+=n,o.wnext===o.wsize&&(o.wnext=0),o.whave<o.wsize&&(o.whave+=n))),0}function f(t,e){var r,n,o,a,s,c,l,f,d,p,g,dt,pt,gt,vt=0,mt,bt,yt,_t,wt,St,xt,Ct,At=new v.Buf8(4),Tt,kt,Pt=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!t||!t.state||!t.output||!t.input&&0!==t.avail_in)return O;r=t.state,r.mode===H&&(r.mode=Y),s=t.next_out,o=t.output,l=t.avail_out,a=t.next_in,n=t.input,c=t.avail_in,f=r.hold,d=r.bits,p=c,g=l,Ct=k;t:for(;;)switch(r.mode){case j:if(0===r.wrap){r.mode=Y;break}for(;d<16;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(2&r.wrap&&35615===f){r.check=0,At[0]=255&f,At[1]=f>>>8&255,r.check=b(r.check,At,2,0),f=0,d=0,r.mode=M;break}if(r.flags=0,r.head&&(r.head.done=!1),!(1&r.wrap)||(((255&f)<<8)+(f>>8))%31){t.msg="incorrect header check",r.mode=ht;break}if((15&f)!==I){t.msg="unknown compression method",r.mode=ht;break}if(f>>>=4,d-=4,xt=8+(15&f),0===r.wbits)r.wbits=xt;else if(xt>r.wbits){t.msg="invalid window size",r.mode=ht;break}r.dmax=1<<xt,t.adler=r.check=1,r.mode=512&f?X:H,f=0,d=0;break;case M:for(;d<16;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(r.flags=f,(255&r.flags)!==I){t.msg="unknown compression method",r.mode=ht;break}if(57344&r.flags){t.msg="unknown header flags set",r.mode=ht;break}r.head&&(r.head.text=f>>8&1),512&r.flags&&(At[0]=255&f,At[1]=f>>>8&255,r.check=b(r.check,At,2,0)),f=0,d=0,r.mode=F;case F:for(;d<32;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}r.head&&(r.head.time=f),512&r.flags&&(At[0]=255&f,At[1]=f>>>8&255,At[2]=f>>>16&255,At[3]=f>>>24&255,r.check=b(r.check,At,4,0)),f=0,d=0,r.mode=N;case N:for(;d<16;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}r.head&&(r.head.xflags=255&f,r.head.os=f>>8),512&r.flags&&(At[0]=255&f,At[1]=f>>>8&255,r.check=b(r.check,At,2,0)),f=0,d=0,r.mode=B;case B:if(1024&r.flags){for(;d<16;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}r.length=f,r.head&&(r.head.extra_len=f),512&r.flags&&(At[0]=255&f,At[1]=f>>>8&255,r.check=b(r.check,At,2,0)),f=0,d=0}else r.head&&(r.head.extra=null);r.mode=U;case U:if(1024&r.flags&&(dt=r.length,dt>c&&(dt=c),dt&&(r.head&&(xt=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),v.arraySet(r.head.extra,n,a,dt,xt)),512&r.flags&&(r.check=b(r.check,n,dt,a)),c-=dt,a+=dt,r.length-=dt),r.length))break t;r.length=0,r.mode=z;case z:if(2048&r.flags){if(0===c)break t;dt=0;do{xt=n[a+dt++],r.head&&xt&&r.length<65536&&(r.head.name+=String.fromCharCode(xt))}while(xt&&dt<c);if(512&r.flags&&(r.check=b(r.check,n,dt,a)),c-=dt,a+=dt,xt)break t}else r.head&&(r.head.name=null);r.length=0,r.mode=W;case W:if(4096&r.flags){if(0===c)break t;dt=0;do{xt=n[a+dt++],r.head&&xt&&r.length<65536&&(r.head.comment+=String.fromCharCode(xt))}while(xt&&dt<c);if(512&r.flags&&(r.check=b(r.check,n,dt,a)),c-=dt,a+=dt,xt)break t}else r.head&&(r.head.comment=null);r.mode=q;case q:if(512&r.flags){for(;d<16;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(f!==(65535&r.check)){t.msg="header crc mismatch",r.mode=ht;break}f=0,d=0}r.head&&(r.head.hcrc=r.flags>>9&1,r.head.done=!0),t.adler=r.check=0,r.mode=H;break;case X:for(;d<32;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}t.adler=r.check=i(f),f=0,d=0,r.mode=G;case G:if(0===r.havedict)return t.next_out=s,t.avail_out=l,t.next_in=a,t.avail_in=c,r.hold=f,r.bits=d,E;t.adler=r.check=1,r.mode=H;case H:if(e===A||e===T)break t;case Y:if(r.last){f>>>=7&d,d-=7&d,r.mode=st;break}for(;d<3;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}switch(r.last=1&f,f>>>=1,d-=1,3&f){case 0:r.mode=V;break;case 1:if(h(r),r.mode=tt,e===T){f>>>=2,d-=2;break t}break;case 2:r.mode=K;break;case 3:t.msg="invalid block type",r.mode=ht}f>>>=2,d-=2;break;case V:for(f>>>=7&d,d-=7&d;d<32;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if((65535&f)!=(f>>>16^65535)){t.msg="invalid stored block lengths",r.mode=ht;break}if(r.length=65535&f,f=0,d=0,r.mode=Z,e===T)break t;case Z:r.mode=J;case J:if(dt=r.length){if(dt>c&&(dt=c),dt>l&&(dt=l),0===dt)break t;v.arraySet(o,n,a,dt,s),c-=dt,a+=dt,l-=dt,s+=dt,r.length-=dt;break}r.mode=H;break;case K:for(;d<14;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(r.nlen=257+(31&f),f>>>=5,d-=5,r.ndist=1+(31&f),f>>>=5,d-=5,r.ncode=4+(15&f),f>>>=4,d-=4,r.nlen>286||r.ndist>30){t.msg="too many length or distance symbols",r.mode=ht;break}r.have=0,r.mode=Q;case Q:for(;r.have<r.ncode;){for(;d<3;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}r.lens[Pt[r.have++]]=7&f,f>>>=3,d-=3}for(;r.have<19;)r.lens[Pt[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,Tt={bits:r.lenbits},Ct=_(w,r.lens,0,19,r.lencode,0,r.work,Tt),r.lenbits=Tt.bits,Ct){t.msg="invalid code lengths set",r.mode=ht;break}r.have=0,r.mode=$;case $:for(;r.have<r.nlen+r.ndist;){for(;vt=r.lencode[f&(1<<r.lenbits)-1],mt=vt>>>24,bt=vt>>>16&255,yt=65535&vt,!(mt<=d);){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(yt<16)f>>>=mt,d-=mt,r.lens[r.have++]=yt;else{if(16===yt){for(kt=mt+2;d<kt;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(f>>>=mt,d-=mt,0===r.have){t.msg="invalid bit length repeat",r.mode=ht;break}xt=r.lens[r.have-1],dt=3+(3&f),f>>>=2,d-=2}else if(17===yt){for(kt=mt+3;d<kt;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}f>>>=mt,d-=mt,xt=0,dt=3+(7&f),f>>>=3,d-=3}else{for(kt=mt+7;d<kt;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}f>>>=mt,d-=mt,xt=0,dt=11+(127&f),f>>>=7,d-=7}if(r.have+dt>r.nlen+r.ndist){t.msg="invalid bit length repeat",r.mode=ht;break}for(;dt--;)r.lens[r.have++]=xt}}if(r.mode===ht)break;if(0===r.lens[256]){t.msg="invalid code -- missing end-of-block",r.mode=ht;break}if(r.lenbits=9,Tt={bits:r.lenbits},Ct=_(S,r.lens,0,r.nlen,r.lencode,0,r.work,Tt),r.lenbits=Tt.bits,Ct){t.msg="invalid literal/lengths set",r.mode=ht;break}if(r.distbits=6,r.distcode=r.distdyn,Tt={bits:r.distbits},Ct=_(x,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,Tt),r.distbits=Tt.bits,Ct){t.msg="invalid distances set",r.mode=ht;break}if(r.mode=tt,e===T)break t;case tt:r.mode=et;case et:if(c>=6&&l>=258){t.next_out=s,t.avail_out=l,t.next_in=a,t.avail_in=c,r.hold=f,r.bits=d,y(t,g),s=t.next_out,o=t.output,l=t.avail_out,a=t.next_in,n=t.input,c=t.avail_in,f=r.hold,d=r.bits,r.mode===H&&(r.back=-1);break}for(r.back=0;vt=r.lencode[f&(1<<r.lenbits)-1],mt=vt>>>24,bt=vt>>>16&255,yt=65535&vt,!(mt<=d);){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(bt&&0==(240&bt)){for(_t=mt,wt=bt,St=yt;vt=r.lencode[St+((f&(1<<_t+wt)-1)>>_t)],mt=vt>>>24,bt=vt>>>16&255,yt=65535&vt,!(_t+mt<=d);){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}f>>>=_t,d-=_t,r.back+=_t}if(f>>>=mt,d-=mt,r.back+=mt,r.length=yt,0===bt){r.mode=at;break}if(32&bt){r.back=-1,r.mode=H;break}if(64&bt){t.msg="invalid literal/length code",r.mode=ht;break}r.extra=15&bt,r.mode=rt;case rt:if(r.extra){for(kt=r.extra;d<kt;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}r.length+=f&(1<<r.extra)-1,f>>>=r.extra,d-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=it;case it:for(;vt=r.distcode[f&(1<<r.distbits)-1],mt=vt>>>24,bt=vt>>>16&255,yt=65535&vt,!(mt<=d);){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(0==(240&bt)){for(_t=mt,wt=bt,St=yt;vt=r.distcode[St+((f&(1<<_t+wt)-1)>>_t)],mt=vt>>>24,bt=vt>>>16&255,yt=65535&vt,!(_t+mt<=d);){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}f>>>=_t,d-=_t,r.back+=_t}if(f>>>=mt,d-=mt,r.back+=mt,64&bt){t.msg="invalid distance code",r.mode=ht;break}r.offset=yt,r.extra=15&bt,r.mode=nt;case nt:if(r.extra){for(kt=r.extra;d<kt;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}r.offset+=f&(1<<r.extra)-1,f>>>=r.extra,d-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){t.msg="invalid distance too far back",r.mode=ht;break}r.mode=ot;case ot:if(0===l)break t;if(dt=g-l,r.offset>dt){if((dt=r.offset-dt)>r.whave&&r.sane){t.msg="invalid distance too far back",r.mode=ht;break}dt>r.wnext?(dt-=r.wnext,pt=r.wsize-dt):pt=r.wnext-dt,dt>r.length&&(dt=r.length),gt=r.window}else gt=o,pt=s-r.offset,dt=r.length;dt>l&&(dt=l),l-=dt,r.length-=dt;do{o[s++]=gt[pt++]}while(--dt);0===r.length&&(r.mode=et);break;case at:if(0===l)break t;o[s++]=r.length,l--,r.mode=et;break;case st:if(r.wrap){for(;d<32;){if(0===c)break t;c--,f|=n[a++]<<d,d+=8}if(g-=l,t.total_out+=g,r.total+=g,g&&(t.adler=r.check=r.flags?b(r.check,o,g,s-g):m(r.check,o,g,s-g)),g=l,(r.flags?f:i(f))!==r.check){t.msg="incorrect data check",r.mode=ht;break}f=0,d=0}r.mode=ct;case ct:if(r.wrap&&r.flags){for(;d<32;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(f!==(4294967295&r.total)){t.msg="incorrect length check",r.mode=ht;break}f=0,d=0}r.mode=lt;case lt:Ct=P;break t;case ht:Ct=R;break t;case ut:return L;case ft:default:return O}return t.next_out=s,t.avail_out=l,t.next_in=a,t.avail_in=c,r.hold=f,r.bits=d,(r.wsize||g!==t.avail_out&&r.mode<ht&&(r.mode<st||e!==C))&&u(t,t.output,t.next_out,g-t.avail_out)?(r.mode=ut,L):(p-=t.avail_in,g-=t.avail_out,t.total_in+=p,t.total_out+=g,r.total+=g,r.wrap&&g&&(t.adler=r.check=r.flags?b(r.check,o,g,t.next_out-g):m(r.check,o,g,t.next_out-g)),t.data_type=r.bits+(r.last?64:0)+(r.mode===H?128:0)+(r.mode===tt||r.mode===Z?256:0),(0===p&&0===g||e===C)&&Ct===k&&(Ct=D),Ct)}function d(t){if(!t||!t.state)return O;var e=t.state;return e.window&&(e.window=null),t.state=null,k}function p(t,e){var r;return t&&t.state?(r=t.state,0==(2&r.wrap)?O:(r.head=e,e.done=!1,k)):O}function g(t,e){var r=e.length,i,n,o;return t&&t.state?(i=t.state,0!==i.wrap&&i.mode!==G?O:i.mode===G&&(n=1,(n=m(n,e,r,0))!==i.check)?R:(o=u(t,e,r,r))?(i.mode=ut,L):(i.havedict=1,k)):O}var v=r(8),m=r(22),b=r(23),y=r(55),_=r(56),w=0,S=1,x=2,C=4,A=5,T=6,k=0,P=1,E=2,O=-2,R=-3,L=-4,D=-5,I=8,j=1,M=2,F=3,N=4,B=5,U=6,z=7,W=8,q=9,X=10,G=11,H=12,Y=13,V=14,Z=15,J=16,K=17,Q=18,$=19,tt=20,et=21,rt=22,it=23,nt=24,ot=25,at=26,st=27,ct=28,lt=29,ht=30,ut=31,ft=32,dt=852,pt=592,gt=15,vt=15,mt=!0,bt,yt;e.inflateReset=a,e.inflateReset2=s,e.inflateResetKeep=o,e.inflateInit=l,e.inflateInit2=c,e.inflate=f,e.inflateEnd=d,e.inflateGetHeader=p,e.inflateSetDictionary=g,e.inflateInfo="pako inflate (from Nodeca project)"},function(t,e,r){"use strict";var i=30,n=12;t.exports=function t(e,r){var i,n,o,a,s,c,l,h,u,f,d,p,g,v,m,b,y,_,w,S,x,C,A,T,k;i=e.state,n=e.next_in,T=e.input,o=n+(e.avail_in-5),a=e.next_out,k=e.output,s=a-(r-e.avail_out),c=a+(e.avail_out-257),l=i.dmax,h=i.wsize,u=i.whave,f=i.wnext,d=i.window,p=i.hold,g=i.bits,v=i.lencode,m=i.distcode,b=(1<<i.lenbits)-1,y=(1<<i.distbits)-1;t:do{g<15&&(p+=T[n++]<<g,g+=8,p+=T[n++]<<g,g+=8),_=v[p&b];e:for(;;){if(w=_>>>24,p>>>=w,g-=w,0===(w=_>>>16&255))k[a++]=65535&_;else{if(!(16&w)){if(0==(64&w)){_=v[(65535&_)+(p&(1<<w)-1)];continue e}if(32&w){i.mode=12;break t}e.msg="invalid literal/length code",i.mode=30;break t}S=65535&_,w&=15,w&&(g<w&&(p+=T[n++]<<g,g+=8),S+=p&(1<<w)-1,p>>>=w,g-=w),g<15&&(p+=T[n++]<<g,g+=8,p+=T[n++]<<g,g+=8),_=m[p&y];r:for(;;){if(w=_>>>24,p>>>=w,g-=w,!(16&(w=_>>>16&255))){if(0==(64&w)){_=m[(65535&_)+(p&(1<<w)-1)];continue r}e.msg="invalid distance code",i.mode=30;break t}if(x=65535&_,w&=15,g<w&&(p+=T[n++]<<g,(g+=8)<w&&(p+=T[n++]<<g,g+=8)),(x+=p&(1<<w)-1)>l){e.msg="invalid distance too far back",i.mode=30;break t}if(p>>>=w,g-=w,w=a-s,x>w){if((w=x-w)>u&&i.sane){e.msg="invalid distance too far back",i.mode=30;break t}if(C=0,A=d,0===f){if(C+=h-w,w<S){S-=w;do{k[a++]=d[C++]}while(--w);C=a-x,A=k}}else if(f<w){if(C+=h+f-w,(w-=f)<S){S-=w;do{k[a++]=d[C++]}while(--w);if(C=0,f<S){w=f,S-=w;do{k[a++]=d[C++]}while(--w);C=a-x,A=k}}}else if(C+=f-w,w<S){S-=w;do{k[a++]=d[C++]}while(--w);C=a-x,A=k}for(;S>2;)k[a++]=A[C++],k[a++]=A[C++],k[a++]=A[C++],S-=3;S&&(k[a++]=A[C++],S>1&&(k[a++]=A[C++]))}else{C=a-x;do{k[a++]=k[C++],k[a++]=k[C++],k[a++]=k[C++],S-=3}while(S>2);S&&(k[a++]=k[C++],S>1&&(k[a++]=k[C++]))}break}}break}}while(n<o&&a<c);S=g>>3,n-=S,g-=S<<3,p&=(1<<g)-1,e.next_in=n,e.next_out=a,e.avail_in=n<o?o-n+5:5-(n-o),e.avail_out=a<c?c-a+257:257-(a-c),i.hold=p,i.bits=g}},function(t,e,r){"use strict";var i=r(8),n=15,o=852,a=592,s=0,c=1,l=2,h=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],u=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],f=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],d=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function t(e,r,n,o,a,s,c,l){var p=l.bits,g=0,v=0,m=0,b=0,y=0,_=0,w=0,S=0,x=0,C=0,A,T,k,P,E,O=null,R=0,L,D=new i.Buf16(16),I=new i.Buf16(16),j=null,M=0,F,N,B;for(g=0;g<=15;g++)D[g]=0;for(v=0;v<o;v++)D[r[n+v]]++;for(y=p,b=15;b>=1&&0===D[b];b--);if(y>b&&(y=b),0===b)return a[s++]=20971520,a[s++]=20971520,l.bits=1,0;for(m=1;m<b&&0===D[m];m++);for(y<m&&(y=m),S=1,g=1;g<=15;g++)if(S<<=1,(S-=D[g])<0)return-1;if(S>0&&(0===e||1!==b))return-1;for(I[1]=0,g=1;g<15;g++)I[g+1]=I[g]+D[g];for(v=0;v<o;v++)0!==r[n+v]&&(c[I[r[n+v]]++]=v);if(0===e?(O=j=c,L=19):1===e?(O=h,R-=257,j=u,M-=257,L=256):(O=f,j=d,L=-1),C=0,v=0,g=m,E=s,_=y,w=0,k=-1,x=1<<y,P=x-1,1===e&&x>852||2===e&&x>592)return 1;for(var U=0;;){U++,F=g-w,c[v]<L?(N=0,B=c[v]):c[v]>L?(N=j[M+c[v]],B=O[R+c[v]]):(N=96,B=0),A=1<<g-w,T=1<<_,m=T;do{T-=A,a[E+(C>>w)+T]=F<<24|N<<16|B|0}while(0!==T);for(A=1<<g-1;C&A;)A>>=1;if(0!==A?(C&=A-1,C+=A):C=0,v++,0==--D[g]){if(g===b)break;g=r[n+c[v]]}if(g>y&&(C&P)!==k){for(0===w&&(w=y),E+=m,_=g-w,S=1<<_;_+w<b&&!((S-=D[_+w])<=0);)_++,S<<=1;if(x+=1<<_,1===e&&x>852||2===e&&x>592)return 1;k=C&P,a[k]=y<<24|_<<16|E-s|0}}return 0!==C&&(a[E+C]=g-w<<24|64<<16|0),l.bits=y,0}},function(t,e,r){"use strict";t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},function(t,e){t.exports=function t(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},function(t,e){"function"==typeof Object.create?t.exports=function t(e,r){e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function t(e,r){e.super_=r;var i=function(){};i.prototype=r.prototype,e.prototype=new i,e.prototype.constructor=e}},function(t,e,r){"use strict";(function(e){/*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <[email protected]> <http://feross.org> * @license MIT */ function i(t,e){if(t===e)return 0;for(var r=t.length,i=e.length,n=0,o=Math.min(r,i);n<o;++n)if(t[n]!==e[n]){r=t[n],i=e[n];break}return r<i?-1:i<r?1:0}function n(t){return e.Buffer&&"function"==typeof e.Buffer.isBuffer?e.Buffer.isBuffer(t):!(null==t||!t._isBuffer)}function o(t){return Object.prototype.toString.call(t)}function a(t){return!n(t)&&("function"==typeof e.ArrayBuffer&&("function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):!!t&&(t instanceof DataView||!!(t.buffer&&t.buffer instanceof ArrayBuffer))))}function s(t){if(_.isFunction(t)){if(x)return t.name;var e=t.toString(),r=e.match(A);return r&&r[1]}}function c(t,e){return"string"==typeof t?t.length<e?t:t.slice(0,e):t}function l(t){if(x||!_.isFunction(t))return _.inspect(t);var e=s(t);return"[Function"+(e?": "+e:"")+"]"}function h(t){return c(l(t.actual),128)+" "+t.operator+" "+c(l(t.expected),128)}function u(t,e,r,i,n){throw new C.AssertionError({message:r,actual:t,expected:e,operator:i,stackStartFunction:n})}function f(t,e){t||u(t,!0,e,"==",C.ok)}function d(t,e,r,s){if(t===e)return!0;if(n(t)&&n(e))return 0===i(t,e);if(_.isDate(t)&&_.isDate(e))return t.getTime()===e.getTime();if(_.isRegExp(t)&&_.isRegExp(e))return t.source===e.source&&t.global===e.global&&t.multiline===e.multiline&&t.lastIndex===e.lastIndex&&t.ignoreCase===e.ignoreCase;if(null!==t&&"object"==typeof t||null!==e&&"object"==typeof e){if(a(t)&&a(e)&&o(t)===o(e)&&!(t instanceof Float32Array||t instanceof Float64Array))return 0===i(new Uint8Array(t.buffer),new Uint8Array(e.buffer));if(n(t)!==n(e))return!1;s=s||{actual:[],expected:[]};var c=s.actual.indexOf(t);return-1!==c&&c===s.expected.indexOf(e)||(s.actual.push(t),s.expected.push(e),g(t,e,r,s))}return r?t===e:t==e}function p(t){return"[object Arguments]"==Object.prototype.toString.call(t)}function g(t,e,r,i){if(null===t||void 0===t||null===e||void 0===e)return!1;if(_.isPrimitive(t)||_.isPrimitive(e))return t===e;if(r&&Object.getPrototypeOf(t)!==Object.getPrototypeOf(e))return!1;var n=p(t),o=p(e);if(n&&!o||!n&&o)return!1;if(n)return t=S.call(t),e=S.call(e),d(t,e,r);var a=T(t),s=T(e),c,l;if(a.length!==s.length)return!1;for(a.sort(),s.sort(),l=a.length-1;l>=0;l--)if(a[l]!==s[l])return!1;for(l=a.length-1;l>=0;l--)if(c=a[l],!d(t[c],e[c],r,i))return!1;return!0}function v(t,e,r){d(t,e,!0)&&u(t,e,r,"notDeepStrictEqual",v)}function m(t,e){if(!t||!e)return!1;if("[object RegExp]"==Object.prototype.toString.call(e))return e.test(t);try{if(t instanceof e)return!0}catch(t){}return!Error.isPrototypeOf(e)&&!0===e.call({},t)}function b(t){var e;try{t()}catch(t){e=t}return e}function y(t,e,r,i){var n;if("function"!=typeof e)throw new TypeError('"block" argument must be a function');"string"==typeof r&&(i=r,r=null),n=b(e),i=(r&&r.name?" ("+r.name+").":".")+(i?" "+i:"."),t&&!n&&u(n,r,"Missing expected exception"+i);var o="string"==typeof i,a=!t&&_.isError(n),s=!t&&n&&!r;if((a&&o&&m(n,r)||s)&&u(n,r,"Got unwanted exception"+i),t&&n&&r&&!m(n,r)||!t&&n)throw n}var _=r(24),w=Object.prototype.hasOwnProperty,S=Array.prototype.slice,x=function(){return"foo"===function t(){}.name}(),C=t.exports=f,A=/\s*function\s+([^\(\s]*)\s*/;C.AssertionError=function t(e){this.name="AssertionError",this.actual=e.actual,this.expected=e.expected,this.operator=e.operator,e.message?(this.message=e.message,this.generatedMessage=!1):(this.message=h(this),this.generatedMessage=!0);var r=e.stackStartFunction||u;if(Error.captureStackTrace)Error.captureStackTrace(this,r);else{var i=new Error;if(i.stack){var n=i.stack,o=s(r),a=n.indexOf("\n"+o);if(a>=0){var c=n.indexOf("\n",a+1);n=n.substring(c+1)}this.stack=n}}},_.inherits(C.AssertionError,Error),C.fail=u,C.ok=f,C.equal=function t(e,r,i){e!=r&&u(e,r,i,"==",C.equal)},C.notEqual=function t(e,r,i){e==r&&u(e,r,i,"!=",C.notEqual)},C.deepEqual=function t(e,r,i){d(e,r,!1)||u(e,r,i,"deepEqual",C.deepEqual)},C.deepStrictEqual=function t(e,r,i){d(e,r,!0)||u(e,r,i,"deepStrictEqual",C.deepStrictEqual)},C.notDeepEqual=function t(e,r,i){d(e,r,!1)&&u(e,r,i,"notDeepEqual",C.notDeepEqual)},C.notDeepStrictEqual=v,C.strictEqual=function t(e,r,i){e!==r&&u(e,r,i,"===",C.strictEqual)},C.notStrictEqual=function t(e,r,i){e===r&&u(e,r,i,"!==",C.notStrictEqual)},C.throws=function(t,e,r){y(!0,t,e,r)},C.doesNotThrow=function(t,e,r){y(!1,t,e,r)},C.ifError=function(t){if(t)throw t};var T=Object.keys||function(t){var e=[];for(var r in t)w.call(t,r)&&e.push(r);return e}}).call(e,r(0))},function(t,e,r){"use strict";var i=r(12),n=r(62);"undefined"!=typeof window&&"Worker"in window?i.PDFJS.workerPort=new n:i.PDFJS.disableWorker=!0,t.exports=i},function(t,e,r){t.exports=function(){return new Worker(r.p+"cdd3fcf50f101cabb45a.worker.js")}},function(module,exports,__webpack_require__){(function(Buffer,process){function copyGLTo2DDrawImage(t,e){var r=t.canvas,i=e.getContext("2d");i.translate(0,e.height),i.scale(1,-1);var n=r.height-e.height;i.drawImage(r,0,n,e.width,e.height,0,0,e.width,e.height)}function copyGLTo2DPutImageData(t,e){var r=e.getContext("2d"),i=e.width,n=e.height,o=i*n*4,a=new Uint8Array(this.imageBuffer,0,o),s=new Uint8ClampedArray(this.imageBuffer,0,o);t.readPixels(0,0,i,n,t.RGBA,t.UNSIGNED_BYTE,a);var c=new ImageData(s,i);r.putImageData(c,0,0)}/*! Fabric.js Copyright 2008-2015, Printio (Juriy Zaytsev, Maxim Chernyak) */ var fabric=fabric||{version:"2.0.0-beta4"};exports.fabric=fabric,"undefined"!=typeof document&&"undefined"!=typeof window?(fabric.document=document,fabric.window=window,window.fabric=fabric):(fabric.document=__webpack_require__(64).jsdom(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]}}),fabric.window=fabric.document.defaultView),fabric.isTouchSupported="ontouchstart"in fabric.document.documentElement,fabric.isLikelyNode=void 0!==Buffer&&"undefined"==typeof window,fabric.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id"],fabric.DPI=96,fabric.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:e[-+]?\\d+)?)",fabric.fontPaths={},fabric.iMatrix=[1,0,0,1,0,0],fabric.canvasModule="canvas",fabric.perfLimitSizeTotal=2097152,fabric.maxCacheSideLimit=4096,fabric.minCacheSideLimit=256,fabric.charWidthsCache={},fabric.textureSize=2048,fabric.enableGLFiltering=!0,fabric.devicePixelRatio=fabric.window.devicePixelRatio||fabric.window.webkitDevicePixelRatio||fabric.window.mozDevicePixelRatio||1,fabric.initFilterBackend=function(){return fabric.isWebglSupported&&fabric.isWebglSupported(fabric.textureSize)&&fabric.enableGLFiltering?(console.log("max texture size: "+fabric.maxTextureSize),new fabric.WebglFilterBackend({tileSize:fabric.textureSize})):fabric.Canvas2dFilterBackend?new fabric.Canvas2dFilterBackend:void 0},function(){function t(t,e){if(this.__eventListeners[t]){var r=this.__eventListeners[t];e?r[r.indexOf(e)]=!1:fabric.util.array.fill(r,!1)}}function e(t,e){if(this.__eventListeners||(this.__eventListeners={}),1===arguments.length)for(var r in t)this.on(r,t[r]);else this.__eventListeners[t]||(this.__eventListeners[t]=[]),this.__eventListeners[t].push(e);return this}function r(e,r){if(this.__eventListeners){if(0===arguments.length)for(e in this.__eventListeners)t.call(this,e);else if(1===arguments.length&&"object"==typeof arguments[0])for(var i in e)t.call(this,i,e[i]);else t.call(this,e,r);return this}}function i(t,e){if(this.__eventListeners){var r=this.__eventListeners[t];if(r){for(var i=0,n=r.length;i<n;i++)r[i]&&r[i].call(this,e||{});return this.__eventListeners[t]=r.filter(function(t){return!1!==t}),this}}}fabric.Observable={observe:e,stopObserving:r,fire:i,on:e,off:r,trigger:i}}(),fabric.Collection={_objects:[],add:function(){if(this._objects.push.apply(this._objects,arguments),this._onObjectAdded)for(var t=0,e=arguments.length;t<e;t++)this._onObjectAdded(arguments[t]);return this.renderOnAddRemove&&this.requestRenderAll(),this},insertAt:function(t,e,r){var i=this.getObjects();return r?i[e]=t:i.splice(e,0,t),this._onObjectAdded&&this._onObjectAdded(t),this.renderOnAddRemove&&this.requestRenderAll(),this},remove:function(){for(var t=this.getObjects(),e,r=!1,i=0,n=arguments.length;i<n;i++)-1!==(e=t.indexOf(arguments[i]))&&(r=!0,t.splice(e,1),this._onObjectRemoved&&this._onObjectRemoved(arguments[i]));return this.renderOnAddRemove&&r&&this.requestRenderAll(),this},forEachObject:function(t,e){for(var r=this.getObjects(),i=0,n=r.length;i<n;i++)t.call(e,r[i],i,r);return this},getObjects:function(t){return void 0===t?this._objects:this._objects.filter(function(e){return e.type===t})},item:function(t){return this.getObjects()[t]},isEmpty:function(){return 0===this.getObjects().length},size:function(){return this.getObjects().length},contains:function(t){return this.getObjects().indexOf(t)>-1},complexity:function(){return this.getObjects().reduce(function(t,e){return t+=e.complexity?e.complexity():0},0)}},fabric.CommonMethods={_setOptions:function(t){for(var e in t)this.set(e,t[e])},_initGradient:function(t,e){!t||!t.colorStops||t instanceof fabric.Gradient||this.set(e,new fabric.Gradient(t))},_initPattern:function(t,e,r){!t||!t.source||t instanceof fabric.Pattern?r&&r():this.set(e,new fabric.Pattern(t,r))},_initClipping:function(t){if(t.clipTo&&"string"==typeof t.clipTo){var e=fabric.util.getFunctionBody(t.clipTo);void 0!==e&&(this.clipTo=new Function("ctx",e))}},_setObject:function(t){for(var e in t)this._set(e,t[e])},set:function(t,e){return"object"==typeof t?this._setObject(t):"function"==typeof e&&"clipTo"!==t?this._set(t,e(this.get(t))):this._set(t,e),this},_set:function(t,e){this[t]=e},toggle:function(t){var e=this.get(t);return"boolean"==typeof e&&this.set(t,!e),this},get:function(t){return this[t]}},function(t){var e=Math.sqrt,r=Math.atan2,i=Math.pow,n=Math.abs,o=Math.PI/180;fabric.util={removeFromArray:function(t,e){var r=t.indexOf(e);return-1!==r&&t.splice(r,1),t},getRandomInt:function(t,e){return Math.floor(Math.random()*(e-t+1))+t},degreesToRadians:function(t){return t*o},radiansToDegrees:function(t){return t/o},rotatePoint:function(t,e,r){t.subtractEquals(e);var i=fabric.util.rotateVector(t,r);return new fabric.Point(i.x,i.y).addEquals(e)},rotateVector:function(t,e){var r=Math.sin(e),i=Math.cos(e);return{x:t.x*i-t.y*r,y:t.x*r+t.y*i}},transformPoint:function(t,e,r){return r?new fabric.Point(e[0]*t.x+e[2]*t.y,e[1]*t.x+e[3]*t.y):new fabric.Point(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])},makeBoundingBoxFromPoints:function(t){var e=[t[0].x,t[1].x,t[2].x,t[3].x],r=fabric.util.array.min(e),i=fabric.util.array.max(e),n=Math.abs(r-i),o=[t[0].y,t[1].y,t[2].y,t[3].y],a=fabric.util.array.min(o),s=fabric.util.array.max(o);return{left:r,top:a,width:n,height:Math.abs(a-s)}},invertTransform:function(t){var e=1/(t[0]*t[3]-t[1]*t[2]),r=[e*t[3],-e*t[1],-e*t[2],e*t[0]],i=fabric.util.transformPoint({x:t[4],y:t[5]},r,!0);return r[4]=-i.x,r[5]=-i.y,r},toFixed:function(t,e){return parseFloat(Number(t).toFixed(e))},parseUnit:function(t,e){var r=/\D{0,2}$/.exec(t),i=parseFloat(t);switch(e||(e=fabric.Text.DEFAULT_SVG_FONT_SIZE),r[0]){case"mm":return i*fabric.DPI/25.4;case"cm":return i*fabric.DPI/2.54;case"in":return i*fabric.DPI;case"pt":return i*fabric.DPI/72;case"pc":return i*fabric.DPI/72*12;case"em":return i*e;default:return i}},falseFunction:function(){return!1},getKlass:function(t,e){return t=fabric.util.string.camelize(t.charAt(0).toUpperCase()+t.slice(1)),fabric.util.resolveNamespace(e)[t]},resolveNamespace:function(e){if(!e)return fabric;var r=e.split("."),i=r.length,n,o=t||fabric.window;for(n=0;n<i;++n)o=o[r[n]];return o},loadImage:function(t,e,r,i){if(!t)return void(e&&e.call(r,t));var n=fabric.util.createImage();n.onload=function(){e&&e.call(r,n),n=n.onload=n.onerror=null},n.onerror=function(){fabric.log("Error loading "+n.src),e&&e.call(r,null,!0),n=n.onload=n.onerror=null},0!==t.indexOf("data")&&i&&(n.crossOrigin=i),n.src=t},enlivenObjects:function(t,e,r,i){function n(){++a===s&&e&&e(o)}t=t||[];var o=[],a=0,s=t.length;if(!s)return void(e&&e(o));t.forEach(function(t,e){if(!t||!t.type)return void n();fabric.util.getKlass(t.type,r).fromObject(t,function(r,a){a||(o[e]=r),i&&i(t,r,a),n()})})},enlivenPatterns:function(t,e){function r(){++n===o&&e&&e(i)}t=t||[];var i=[],n=0,o=t.length;if(!o)return void(e&&e(i));t.forEach(function(t,e){t&&t.source?new fabric.Pattern(t,function(t){i[e]=t,r()}):(i[e]=t,r())})},groupSVGElements:function(t,e,r){var i;return 1===t.length?t[0]:(e&&(e.width&&e.height?e.centerPoint={x:e.width/2,y:e.height/2}:(delete e.width,delete e.height)),i=new fabric.Group(t,e),void 0!==r&&(i.sourcePath=r),i)},populateWithProperties:function(t,e,r){if(r&&"[object Array]"===Object.prototype.toString.call(r))for(var i=0,n=r.length;i<n;i++)r[i]in t&&(e[r[i]]=t[r[i]])},drawDashedLine:function(t,i,n,o,a,s){var c=o-i,l=a-n,h=e(c*c+l*l),u=r(l,c),f=s.length,d=0,p=!0;for(t.save(),t.translate(i,n),t.moveTo(0,0),t.rotate(u),i=0;h>i;)i+=s[d++%f],i>h&&(i=h),t[p?"lineTo":"moveTo"](i,0),p=!p;t.restore()},createCanvasElement:function(t){return t||(t=fabric.document.createElement("canvas")),t},createImage:function(){return fabric.document.createElement("img")},clipContext:function(t,e){e.save(),e.beginPath(),t.clipTo(e),e.clip()},multiplyTransformMatrices:function(t,e,r){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],r?0:t[0]*e[4]+t[2]*e[5]+t[4],r?0:t[1]*e[4]+t[3]*e[5]+t[5]]},qrDecompose:function(t){var n=r(t[1],t[0]),a=i(t[0],2)+i(t[1],2),s=e(a),c=(t[0]*t[3]-t[2]*t[1])/s,l=r(t[0]*t[2]+t[1]*t[3],a);return{angle:n/o,scaleX:s,scaleY:c,skewX:l/o,skewY:0,translateX:t[4],translateY:t[5]}},customTransformMatrix:function(t,e,r){var i=[1,0,n(Math.tan(r*o)),1],a=[n(t),0,0,n(e)];return fabric.util.multiplyTransformMatrices(a,i,!0)},resetObjectTransform:function(t){t.scaleX=1,t.scaleY=1,t.skewX=0,t.skewY=0,t.flipX=!1,t.flipY=!1,t.setAngle(0)},getFunctionBody:function(t){return(String(t).match(/function[^{]*\{([\s\S]*)\}/)||{})[1]},isTransparent:function(t,e,r,i){i>0&&(e>i?e-=i:e=0,r>i?r-=i:r=0);var n=!0,o,a,s=t.getImageData(e,r,2*i||1,2*i||1),c=s.data.length;for(o=3;o<c&&(a=s.data[o],!1!==(n=a<=0));o+=4);return s=null,n},parsePreserveAspectRatioAttribute:function(t){var e="meet",r="Mid",i="Mid",n=t.split(" "),o;return n&&n.length&&(e=n.pop(),"meet"!==e&&"slice"!==e?(o=e,e="meet"):n.length&&(o=n.pop())),r="none"!==o?o.slice(1,4):"none",i="none"!==o?o.slice(5,8):"none",{meetOrSlice:e,alignX:r,alignY:i}},clearFabricFontCache:function(t){t?fabric.charWidthsCache[t]&&delete fabric.charWidthsCache[t]:fabric.charWidthsCache={}},limitDimsByArea:function(t,e){var r=Math.sqrt(e*t),i=Math.floor(e/r);return{x:Math.floor(r),y:i}},capValue:function(t,e,r){return Math.max(t,Math.min(e,r))},findScaleToFit:function(t,e){return Math.min(e.width/t.width,e.height/t.height)},findScaleToCover:function(t,e){return Math.max(e.width/t.width,e.height/t.height)}}}(exports),function(){function t(t,i,o,a,c,l,h){var u=s.call(arguments);if(n[u])return n[u];var f=Math.PI,d=h*f/180,p=Math.sin(d),g=Math.cos(d),v=0,m=0;o=Math.abs(o),a=Math.abs(a);var b=-g*t*.5-p*i*.5,y=-g*i*.5+p*t*.5,_=o*o,w=a*a,S=y*y,x=b*b,C=_*w-_*S-w*x,A=0;if(C<0){var T=Math.sqrt(1-C/(_*w));o*=T,a*=T}else A=(c===l?-1:1)*Math.sqrt(C/(_*S+w*x));var k=A*o*y/a,P=-A*a*b/o,E=g*k-p*P+.5*t,O=p*k+g*P+.5*i,R=r(1,0,(b-k)/o,(y-P)/a),L=r((b-k)/o,(y-P)/a,(-b-k)/o,(-y-P)/a);0===l&&L>0?L-=2*f:1===l&&L<0&&(L+=2*f);for(var D=Math.ceil(Math.abs(L/f*2)),I=[],j=L/D,M=8/3*Math.sin(j/4)*Math.sin(j/4)/Math.sin(j/2),F=R+j,N=0;N<D;N++)I[N]=e(R,F,g,p,o,a,E,O,M,v,m),v=I[N][4],m=I[N][5],R=F,F+=j;return n[u]=I,I}function e(t,e,r,i,n,a,c,l,h,u,f){var d=s.call(arguments);if(o[d])return o[d];var p=Math.cos(t),g=Math.sin(t),v=Math.cos(e),m=Math.sin(e),b=r*n*v-i*a*m+c,y=i*n*v+r*a*m+l,_=u+h*(-r*n*g-i*a*p),w=f+h*(-i*n*g+r*a*p),S=b+h*(r*n*m+i*a*v),x=y+h*(i*n*m-r*a*v);return o[d]=[_,w,S,x,b,y],o[d]}function r(t,e,r,i){var n=Math.atan2(e,t),o=Math.atan2(i,r);return o>=n?o-n:2*Math.PI-(n-o)}function i(t,e,r,i,n,o,c,l){var h=s.call(arguments);if(a[h])return a[h];var u=Math.sqrt,f=Math.min,d=Math.max,p=Math.abs,g=[],v=[[],[]],m,b,y,_,w,S,x,C;b=6*t-12*r+6*n,m=-3*t+9*r-9*n+3*c,y=3*r-3*t;for(var A=0;A<2;++A)if(A>0&&(b=6*e-12*i+6*o,m=-3*e+9*i-9*o+3*l,y=3*i-3*e),p(m)<1e-12){if(p(b)<1e-12)continue;0<(_=-y/b)&&_<1&&g.push(_)}else(x=b*b-4*y*m)<0||(C=u(x),w=(-b+C)/(2*m),0<w&&w<1&&g.push(w),0<(S=(-b-C)/(2*m))&&S<1&&g.push(S));for(var T,k,P=g.length,E=P,O;P--;)_=g[P],O=1-_,T=O*O*O*t+3*O*O*_*r+3*O*_*_*n+_*_*_*c,v[0][P]=T,k=O*O*O*e+3*O*O*_*i+3*O*_*_*o+_*_*_*l,v[1][P]=k;v[0][E]=t,v[1][E]=e,v[0][E+1]=c,v[1][E+1]=l;var R=[{x:f.apply(null,v[0]),y:f.apply(null,v[1])},{x:d.apply(null,v[0]),y:d.apply(null,v[1])}];return a[h]=R,R}var n={},o={},a={},s=Array.prototype.join;fabric.util.drawArc=function(e,r,i,n){for(var o=n[0],a=n[1],s=n[2],c=n[3],l=n[4],h=n[5],u=n[6],f=[[],[],[],[]],d=t(h-r,u-i,o,a,c,l,s),p=0,g=d.length;p<g;p++)f[p][0]=d[p][0]+r,f[p][1]=d[p][1]+i,f[p][2]=d[p][2]+r,f[p][3]=d[p][3]+i,f[p][4]=d[p][4]+r,f[p][5]=d[p][5]+i,e.bezierCurveTo.apply(e,f[p])},fabric.util.getBoundsOfArc=function(e,r,n,o,a,s,c,l,h){for(var u=0,f=0,d,p=[],g=t(l-e,h-r,n,o,s,c,a),v=0,m=g.length;v<m;v++)d=i(u,f,g[v][0],g[v][1],g[v][2],g[v][3],g[v][4],g[v][5]),p.push({x:d[0].x+e,y:d[0].y+r}),p.push({x:d[1].x+e,y:d[1].y+r}),u=g[v][4],f=g[v][5];return p},fabric.util.getBoundsOfCurve=i}(),function(){function t(t,e){for(var r=o.call(arguments,2),i=[],n=0,a=t.length;n<a;n++)i[n]=r.length?t[n][e].apply(t[n],r):t[n][e].call(t[n]);return i}function e(t,e){return n(t,e,function(t,e){return t>=e})}function r(t,e){return n(t,e,function(t,e){return t<e})}function i(t,e){for(var r=t.length;r--;)t[r]=e;return t}function n(t,e,r){if(t&&0!==t.length){var i=t.length-1,n=e?t[i][e]:t[i];if(e)for(;i--;)r(t[i][e],n)&&(n=t[i][e]);else for(;i--;)r(t[i],n)&&(n=t[i]);return n}}var o=Array.prototype.slice;fabric.util.array={fill:i,invoke:t,min:r,max:e}}(),function(){function t(e,r,i){if(i)if(!fabric.isLikelyNode&&r instanceof Element)e=r;else if(r instanceof Array){e=[];for(var n=0,o=r.length;n<o;n++)e[n]=t({},r[n],i)}else if(r&&"object"==typeof r)for(var a in r)r.hasOwnProperty(a)&&(e[a]=t({},r[a],i));else e=r;else for(var a in r)e[a]=r[a];return e}function e(e,r){return t({},e,r)}fabric.util.object={extend:t,clone:e}}(),function(){function t(t){return t.replace(/-+(.)?/g,function(t,e){return e?e.toUpperCase():""})}function e(t,e){return t.charAt(0).toUpperCase()+(e?t.slice(1):t.slice(1).toLowerCase())}function r(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function i(t){for(var e=0,r=[],e=0,i;e<t.length;e++)!1!==(i=n(t,e))&&r.push(i);return r}function n(t,e){var r=t.charCodeAt(e);if(isNaN(r))return"";if(r<55296||r>57343)return t.charAt(e);if(55296<=r&&r<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";var i=t.charCodeAt(e+1);if(56320>i||i>57343)throw"High surrogate without following low surrogate";return t.charAt(e)+t.charAt(e+1)}if(0===e)throw"Low surrogate without preceding high surrogate";var n=t.charCodeAt(e-1);if(55296>n||n>56319)throw"Low surrogate without preceding high surrogate";return!1}fabric.util.string={camelize:t,capitalize:e,escapeXml:r,graphemeSplit:i}}(),function(){function t(){}function e(t){for(var e=null,r=this;r.constructor.superclass;){var n=r.constructor.superclass.prototype[t];if(r[t]!==n){e=n;break}r=r.constructor.superclass.prototype}return e?arguments.length>1?e.apply(this,i.call(arguments,1)):e.call(this):console.log("tried to callSuper "+t+", method not found in prototype chain",this)}function r(){function r(){this.initialize.apply(this,arguments)}var o=null,s=i.call(arguments,0);"function"==typeof s[0]&&(o=s.shift()),r.superclass=o,r.subclasses=[],o&&(t.prototype=o.prototype,r.prototype=new t,o.subclasses.push(r));for(var c=0,l=s.length;c<l;c++)a(r,s[c],o);return r.prototype.initialize||(r.prototype.initialize=n),r.prototype.constructor=r,r.prototype.callSuper=e,r}var i=Array.prototype.slice,n=function(){},o=function(){for(var t in{toString:1})if("toString"===t)return!1;return!0}(),a=function(t,e,r){for(var i in e)i in t.prototype&&"function"==typeof t.prototype[i]&&(e[i]+"").indexOf("callSuper")>-1?t.prototype[i]=function(t){return function(){var i=this.constructor.superclass;this.constructor.superclass=r;var n=e[t].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==t)return n}}(i):t.prototype[i]=e[i],o&&(e.toString!==Object.prototype.toString&&(t.prototype.toString=e.toString),e.valueOf!==Object.prototype.valueOf&&(t.prototype.valueOf=e.valueOf))};fabric.util.createClass=r}(),function(){function t(t){var e=Array.prototype.slice.call(arguments,1),r,i,n=e.length;for(i=0;i<n;i++)if(r=typeof t[e[i]],!/^(?:function|object|unknown)$/.test(r))return!1;return!0}function e(t,e){return{handler:e,wrappedHandler:r(t,e)}}function r(t,e){return function(r){e.call(s(t),r||fabric.window.event)}}function i(t,e){return function(r){if(d[t]&&d[t][e])for(var i=d[t][e],n=0,o=i.length;n<o;n++)i[n].call(this,r||fabric.window.event)}}function n(t){t||(t=fabric.window.event);var e=t.target||(typeof t.srcElement!==a?t.srcElement:null),r=fabric.util.getScrollLeftTop(e);return{x:v(t)+r.left,y:m(t)+r.top}}function o(t,e,r){var i="touchend"===t.type?"changedTouches":"touches";return t[i]&&t[i][0]?t[i][0][e]-(t[i][0][e]-t[i][0][r])||t[r]:t[r]}var a="unknown",s,c,l=function(){var t=0;return function(e){return e.__uniqueID||(e.__uniqueID="uniqueID__"+t++)}}();!function(){var t={};s=function(e){return t[e]},c=function(e,r){t[e]=r}}();var h=t(fabric.document.documentElement,"addEventListener","removeEventListener")&&t(fabric.window,"addEventListener","removeEventListener"),u=t(fabric.document.documentElement,"attachEvent","detachEvent")&&t(fabric.window,"attachEvent","detachEvent"),f={},d={},p,g;h?(p=function(t,e,r,i){t&&t.addEventListener(e,r,!u&&i)},g=function(t,e,r,i){t&&t.removeEventListener(e,r,!u&&i)}):u?(p=function(t,r,i){if(t){var n=l(t);c(n,t),f[n]||(f[n]={}),f[n][r]||(f[n][r]=[]);var o=e(n,i);f[n][r].push(o),t.attachEvent("on"+r,o.wrappedHandler)}},g=function(t,e,r){if(t){var i=l(t),n;if(f[i]&&f[i][e])for(var o=0,a=f[i][e].length;o<a;o++)(n=f[i][e][o])&&n.handler===r&&(t.detachEvent("on"+e,n.wrappedHandler),f[i][e][o]=null)}}):(p=function(t,e,r){if(t){var n=l(t);if(d[n]||(d[n]={}),!d[n][e]){d[n][e]=[];var o=t["on"+e];o&&d[n][e].push(o),t["on"+e]=i(n,e)}d[n][e].push(r)}},g=function(t,e,r){if(t){var i=l(t);if(d[i]&&d[i][e])for(var n=d[i][e],o=0,a=n.length;o<a;o++)n[o]===r&&n.splice(o,1)}}),fabric.util.addListener=p,fabric.util.removeListener=g;var v=function(t){return t.clientX},m=function(t){return t.clientY};fabric.isTouchSupported&&(v=function(t){return o(t,"pageX","clientX")},m=function(t){return o(t,"pageY","clientY")}),fabric.util.getPointer=n,fabric.util.object.extend(fabric.util,fabric.Observable)}(),function(){function t(t,e){var r=t.style;if(!r)return t;if("string"==typeof e)return t.style.cssText+=";"+e,e.indexOf("opacity")>-1?o(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var i in e)if("opacity"===i)o(t,e[i]);else{var n="float"===i||"cssFloat"===i?void 0===r.styleFloat?"cssFloat":"styleFloat":i;r[n]=e[i]}return t}var e=fabric.document.createElement("div"),r="string"==typeof e.style.opacity,i="string"==typeof e.style.filter,n=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,o=function(t){return t};r?o=function(t,e){return t.style.opacity=e,t}:i&&(o=function(t,e){var r=t.style;return t.currentStyle&&!t.currentStyle.hasLayout&&(r.zoom=1),n.test(r.filter)?(e=e>=.9999?"":"alpha(opacity="+100*e+")",r.filter=r.filter.replace(n,e)):r.filter+=" alpha(opacity="+100*e+")",t}),fabric.util.setStyle=t}(),function(){function t(t){return"string"==typeof t?fabric.document.getElementById(t):t}function e(t,e){var r=fabric.document.createElement(t);for(var i in e)"class"===i?r.className=e[i]:"for"===i?r.htmlFor=e[i]:r.setAttribute(i,e[i]);return r}function r(t,e){t&&-1===(" "+t.className+" ").indexOf(" "+e+" ")&&(t.className+=(t.className?" ":"")+e)}function i(t,r,i){return"string"==typeof r&&(r=e(r,i)),t.parentNode&&t.parentNode.replaceChild(r,t),r.appendChild(t),r}function n(t){for(var e=0,r=0,i=fabric.document.documentElement,n=fabric.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&(t=t.parentNode||t.host,t===fabric.document?(e=n.scrollLeft||i.scrollLeft||0,r=n.scrollTop||i.scrollTop||0):(e+=t.scrollLeft||0,r+=t.scrollTop||0),1!==t.nodeType||"fixed"!==fabric.util.getElementStyle(t,"position")););return{left:e,top:r}}function o(t){var e,r=t&&t.ownerDocument,i={left:0,top:0},o={left:0,top:0},a,s={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!r)return o;for(var c in s)o[s[c]]+=parseInt(l(t,c),10)||0;return e=r.documentElement,void 0!==t.getBoundingClientRect&&(i=t.getBoundingClientRect()),a=n(t),{left:i.left+a.left-(e.clientLeft||0)+o.left,top:i.top+a.top-(e.clientTop||0)+o.top}}var a=Array.prototype.slice,s,c=function(t){return a.call(t,0)};try{s=c(fabric.document.childNodes)instanceof Array}catch(t){}s||(c=function(t){for(var e=new Array(t.length),r=t.length;r--;)e[r]=t[r];return e});var l;l=fabric.document.defaultView&&fabric.document.defaultView.getComputedStyle?function(t,e){var r=fabric.document.defaultView.getComputedStyle(t,null);return r?r[e]:void 0}:function(t,e){var r=t.style[e];return!r&&t.currentStyle&&(r=t.currentStyle[e]),r},function(){function t(t){return void 0!==t.onselectstart&&(t.onselectstart=fabric.util.falseFunction),i?t.style[i]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t}function e(t){return void 0!==t.onselectstart&&(t.onselectstart=null),i?t.style[i]="":"string"==typeof t.unselectable&&(t.unselectable=""),t}var r=fabric.document.documentElement.style,i="userSelect"in r?"userSelect":"MozUserSelect"in r?"MozUserSelect":"WebkitUserSelect"in r?"WebkitUserSelect":"KhtmlUserSelect"in r?"KhtmlUserSelect":"";fabric.util.makeElementUnselectable=t,fabric.util.makeElementSelectable=e}(),function(){function t(t,e){var r=fabric.document.getElementsByTagName("head")[0],i=fabric.document.createElement("script"),n=!0;i.onload=i.onreadystatechange=function(t){if(n){if("string"==typeof this.readyState&&"loaded"!==this.readyState&&"complete"!==this.readyState)return;n=!1,e(t||fabric.window.event),i=i.onload=i.onreadystatechange=null}},i.src=t,r.appendChild(i)}fabric.util.getScript=t}(),fabric.util.getById=t,fabric.util.toArray=c,fabric.util.makeElement=e,fabric.util.addClass=r,fabric.util.wrapElement=i,fabric.util.getScrollLeftTop=n,fabric.util.getElementOffset=o,fabric.util.getElementStyle=l}(),function(){function t(t,e){return t+(/\?/.test(t)?"&":"?")+e}function e(){}function r(r,n){n||(n={});var o=n.method?n.method.toUpperCase():"GET",a=n.onComplete||function(){},s=i(),c=n.body||n.parameters;return s.onreadystatechange=function(){4===s.readyState&&(a(s),s.onreadystatechange=e)},"GET"===o&&(c=null,"string"==typeof n.parameters&&(r=t(r,n.parameters))),s.open(o,r,!0),"POST"!==o&&"PUT"!==o||s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.send(c),s}var i=function(){for(var t=[function(){return new ActiveXObject("Microsoft.XMLHTTP")},function(){return new ActiveXObject("Msxml2.XMLHTTP")},function(){return new ActiveXObject("Msxml2.XMLHTTP.3.0")},function(){return new XMLHttpRequest}],e=t.length;e--;)try{if(t[e]())return t[e]}catch(t){}}();fabric.util.request=r}(),fabric.log=function(){},fabric.warn=function(){},"undefined"!=typeof console&&["log","warn"].forEach(function(t){void 0!==console[t]&&"function"==typeof console[t].apply&&(fabric[t]=function(){return console[t].apply(console,arguments)})}),function(){function t(){return!1}function e(e){r(function(i){e||(e={});var n=i||+new Date,o=e.duration||500,a=n+o,s,c=e.onChange||t,l=e.abort||t,h=e.onComplete||t,u=e.easing||function(t,e,r,i){return-r*Math.cos(t/i*(Math.PI/2))+r+e},f="startValue"in e?e.startValue:0,d="endValue"in e?e.endValue:100,p=e.byValue||d-f;e.onStart&&e.onStart(),function t(i){if(l())return void h(d,1,1);s=i||+new Date;var g=s>a?o:s-n,v=g/o,m=u(g,f,p,o),b=Math.abs((m-f)/p);if(c(m,b,v),s>a)return void(e.onComplete&&e.onComplete());r(t)}(n)})}function r(){return i.apply(fabric.window,arguments)}var i=fabric.window.requestAnimationFrame||fabric.window.webkitRequestAnimationFrame||fabric.window.mozRequestAnimationFrame||fabric.window.oRequestAnimationFrame||fabric.window.msRequestAnimationFrame||function(t){fabric.window.setTimeout(t,1e3/60)};fabric.util.animate=e,fabric.util.requestAnimFrame=r}(),function(){function t(t,e,r){var i="rgba("+parseInt(t[0]+r*(e[0]-t[0]),10)+","+parseInt(t[1]+r*(e[1]-t[1]),10)+","+parseInt(t[2]+r*(e[2]-t[2]),10);return i+=","+(t&&e?parseFloat(t[3]+r*(e[3]-t[3])):1),i+=")"}function e(e,r,i,n){var o=new fabric.Color(e).getSource(),a=new fabric.Color(r).getSource();n=n||{},fabric.util.animate(fabric.util.object.extend(n,{duration:i||500,startValue:o,endValue:a,byValue:a,easing:function(e,r,i,o){return t(r,i,n.colorEasing?n.colorEasing(e,o):1-Math.cos(e/o*(Math.PI/2)))}}))}fabric.util.animateColor=e}(),function(){function t(t,e,r,i){return t<Math.abs(e)?(t=e,i=r/4):i=0===e&&0===t?r/(2*Math.PI)*Math.asin(1):r/(2*Math.PI)*Math.asin(e/t),{a:t,c:e,p:r,s:i}}function e(t,e,r){return t.a*Math.pow(2,10*(e-=1))*Math.sin((e*r-t.s)*(2*Math.PI)/t.p)}function r(t,e,r,i){return r*((t=t/i-1)*t*t+1)+e}function i(t,e,r,i){return t/=i/2,t<1?r/2*t*t*t+e:r/2*((t-=2)*t*t+2)+e}function n(t,e,r,i){return r*(t/=i)*t*t*t+e}function o(t,e,r,i){return-r*((t=t/i-1)*t*t*t-1)+e}function a(t,e,r,i){return t/=i/2,t<1?r/2*t*t*t*t+e:-r/2*((t-=2)*t*t*t-2)+e}function s(t,e,r,i){return r*(t/=i)*t*t*t*t+e}function c(t,e,r,i){return r*((t=t/i-1)*t*t*t*t+1)+e}function l(t,e,r,i){return t/=i/2,t<1?r/2*t*t*t*t*t+e:r/2*((t-=2)*t*t*t*t+2)+e}function h(t,e,r,i){return-r*Math.cos(t/i*(Math.PI/2))+r+e}function u(t,e,r,i){return r*Math.sin(t/i*(Math.PI/2))+e}function f(t,e,r,i){return-r/2*(Math.cos(Math.PI*t/i)-1)+e}function d(t,e,r,i){return 0===t?e:r*Math.pow(2,10*(t/i-1))+e}function p(t,e,r,i){return t===i?e+r:r*(1-Math.pow(2,-10*t/i))+e}function g(t,e,r,i){return 0===t?e:t===i?e+r:(t/=i/2,t<1?r/2*Math.pow(2,10*(t-1))+e:r/2*(2-Math.pow(2,-10*--t))+e)}function v(t,e,r,i){return-r*(Math.sqrt(1-(t/=i)*t)-1)+e}function m(t,e,r,i){return r*Math.sqrt(1-(t=t/i-1)*t)+e}function b(t,e,r,i){return t/=i/2,t<1?-r/2*(Math.sqrt(1-t*t)-1)+e:r/2*(Math.sqrt(1-(t-=2)*t)+1)+e}function y(r,i,n,o){var a=0,s=n;return 0===r?i:1==(r/=o)?i+n:(a||(a=.3*o),-e(t(s,n,a,1.70158),r,o)+i)}function _(e,r,i,n){var o=1.70158,a=0,s=i;if(0===e)return r;if(1===(e/=n))return r+i;a||(a=.3*n);var c=t(s,i,a,o);return c.a*Math.pow(2,-10*e)*Math.sin((e*n-c.s)*(2*Math.PI)/c.p)+c.c+r}function w(r,i,n,o){var a=1.70158,s=0,c=n;if(0===r)return i;if(2===(r/=o/2))return i+n;s||(s=o*(.3*1.5));var l=t(c,n,s,a);return r<1?-.5*e(l,r,o)+i:l.a*Math.pow(2,-10*(r-=1))*Math.sin((r*o-l.s)*(2*Math.PI)/l.p)*.5+l.c+i}function S(t,e,r,i,n){return void 0===n&&(n=1.70158),r*(t/=i)*t*((n+1)*t-n)+e}function x(t,e,r,i,n){return void 0===n&&(n=1.70158),r*((t=t/i-1)*t*((n+1)*t+n)+1)+e}function C(t,e,r,i,n){return void 0===n&&(n=1.70158),t/=i/2,t<1?r/2*(t*t*((1+(n*=1.525))*t-n))+e:r/2*((t-=2)*t*((1+(n*=1.525))*t+n)+2)+e}function A(t,e,r,i){return r-T(i-t,0,r,i)+e}function T(t,e,r,i){return(t/=i)<1/2.75?r*(7.5625*t*t)+e:t<2/2.75?r*(7.5625*(t-=1.5/2.75)*t+.75)+e:t<2.5/2.75?r*(7.5625*(t-=2.25/2.75)*t+.9375)+e:r*(7.5625*(t-=2.625/2.75)*t+.984375)+e}function k(t,e,r,i){return t<i/2?.5*A(2*t,0,r,i)+e:.5*T(2*t-i,0,r,i)+.5*r+e}fabric.util.ease={easeInQuad:function(t,e,r,i){return r*(t/=i)*t+e},easeOutQuad:function(t,e,r,i){return-r*(t/=i)*(t-2)+e},easeInOutQuad:function(t,e,r,i){return t/=i/2,t<1?r/2*t*t+e:-r/2*(--t*(t-2)-1)+e},easeInCubic:function(t,e,r,i){return r*(t/=i)*t*t+e},easeOutCubic:r,easeInOutCubic:i,easeInQuart:n,easeOutQuart:o,easeInOutQuart:a,easeInQuint:s,easeOutQuint:c,easeInOutQuint:l,easeInSine:h,easeOutSine:u,easeInOutSine:f,easeInExpo:d,easeOutExpo:p,easeInOutExpo:g,easeInCirc:v,easeOutCirc:m,easeInOutCirc:b,easeInElastic:y,easeOutElastic:_,easeInOutElastic:w,easeInBack:S,easeOutBack:x,easeInOutBack:C,easeInBounce:A,easeOutBounce:T,easeInOutBounce:k}}(),function(t){"use strict";function e(t){return t in A?A[t]:t}function r(t,e,r,i){var n="[object Array]"===Object.prototype.toString.call(e),o;return"fill"!==t&&"stroke"!==t||"none"!==e?"strokeDashArray"===t?e="none"===e?null:e.replace(/,/g," ").split(/\s+/).map(function(t){return parseFloat(t)}):"transformMatrix"===t?e=r&&r.transformMatrix?_(r.transformMatrix,g.parseTransformAttribute(e)):g.parseTransformAttribute(e):"visible"===t?(e="none"!==e&&"hidden"!==e,r&&!1===r.visible&&(e=!1)):"opacity"===t?(e=parseFloat(e),r&&void 0!==r.opacity&&(e*=r.opacity)):"originX"===t?e="start"===e?"left":"end"===e?"right":"center":o=n?e.map(y):y(e,i):e="",!n&&isNaN(o)?e:o}function i(t){for(var e in T)if(void 0!==t[T[e]]&&""!==t[e]){if(void 0===t[e]){if(!g.Object.prototype[e])continue;t[e]=g.Object.prototype[e]}if(0!==t[e].indexOf("url(")){var r=new g.Color(t[e]);t[e]=r.setAlpha(b(r.getAlpha()*t[T[e]],2)).toRgba()}}return t}function n(t,e){for(var r,i=[],n,o=0;o<e.length;o++)r=e[o],n=t.getElementsByTagName(r),i=i.concat(Array.prototype.slice.call(n));return i}function o(t,e){var r,i;t.replace(/;\s*$/,"").split(";").forEach(function(t){var n=t.split(":");r=n[0].trim().toLowerCase(),i=n[1].trim(),e[r]=i})}function a(t,e){var r,i;for(var n in t)void 0!==t[n]&&(r=n.toLowerCase(),i=t[n],e[r]=i)}function s(t,e){var r={};for(var i in g.cssRules[e])if(c(t,i.split(" ")))for(var n in g.cssRules[e][i])r[n]=g.cssRules[e][i][n];return r}function c(t,e){var r,i=!0;return r=h(t,e.pop()),r&&e.length&&(i=l(t,e)),r&&i&&0===e.length}function l(t,e){for(var r,i=!0;t.parentNode&&1===t.parentNode.nodeType&&e.length;)i&&(r=e.pop()),t=t.parentNode,i=h(t,r);return 0===e.length}function h(t,e){var r=t.nodeName,i=t.getAttribute("class"),n=t.getAttribute("id"),o;if(o=new RegExp("^"+r,"i"),e=e.replace(o,""),n&&e.length&&(o=new RegExp("#"+n+"(?![a-zA-Z\\-]+)","i"),e=e.replace(o,"")),i&&e.length){i=i.split(" ");for(var a=i.length;a--;)o=new RegExp("\\."+i[a]+"(?![a-zA-Z\\-]+)","i"),e=e.replace(o,"")}return 0===e.length}function u(t,e){var r;if(t.getElementById&&(r=t.getElementById(e)),r)return r;var i,n,o=t.getElementsByTagName("*");for(n=0;n<o.length;n++)if(i=o[n],e===i.getAttribute("id"))return i}function f(t){for(var e=n(t,["use","svg:use"]),r=0;e.length&&r<e.length;){var i=e[r],o=i.getAttribute("xlink:href").substr(1),a=i.getAttribute("x")||0,s=i.getAttribute("y")||0,c=u(t,o).cloneNode(!0),l=(c.getAttribute("transform")||"")+" translate("+a+", "+s+")",h,f=e.length,p,g,v,m;if(d(c),/^svg$/i.test(c.nodeName)){var b=c.ownerDocument.createElement("g");for(g=0,v=c.attributes,m=v.length;g<m;g++)p=v.item(g),b.setAttribute(p.nodeName,p.nodeValue);for(;c.firstChild;)b.appendChild(c.firstChild);c=b}for(g=0,v=i.attributes,m=v.length;g<m;g++)p=v.item(g),"x"!==p.nodeName&&"y"!==p.nodeName&&"xlink:href"!==p.nodeName&&("transform"===p.nodeName?l=p.nodeValue+" "+l:c.setAttribute(p.nodeName,p.nodeValue));c.setAttribute("transform",l),c.setAttribute("instantiated_by_use","1"),c.removeAttribute("id"),h=i.parentNode,h.replaceChild(c,i),e.length===f&&r++}}function d(t){var e=t.getAttribute("viewBox"),r=1,i=1,n=0,o=0,a,s,c,l,h=t.getAttribute("width"),u=t.getAttribute("height"),f=t.getAttribute("x")||0,d=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",v=!e||!S.test(t.nodeName)||!(e=e.match(k)),m=!h||!u||"100%"===h||"100%"===u,b=v&&m,_={},w="";if(_.width=0,_.height=0,_.toBeParsed=b,b)return _;if(v)return _.width=y(h),_.height=y(u),_;if(n=-parseFloat(e[1]),o=-parseFloat(e[2]),a=parseFloat(e[3]),s=parseFloat(e[4]),m?(_.width=a,_.height=s):(_.width=y(h),_.height=y(u),r=_.width/a,i=_.height/s),p=g.util.parsePreserveAspectRatioAttribute(p),"none"!==p.alignX&&(i=r=r>i?i:r),1===r&&1===i&&0===n&&0===o&&0===f&&0===d)return _;if((f||d)&&(w=" translate("+y(f)+" "+y(d)+") "),c=w+" matrix("+r+" 0 0 "+i+" "+n*r+" "+o*i+") ","svg"===t.nodeName){for(l=t.ownerDocument.createElement("g");t.firstChild;)l.appendChild(t.firstChild);t.appendChild(l)}else l=t,c=l.getAttribute("transform")+c;return l.setAttribute("transform",c),_}function p(t,e){for(;t&&(t=t.parentNode);)if(t.nodeName&&e.test(t.nodeName.replace("svg:",""))&&!t.getAttribute("instantiated_by_use"))return!0;return!1}var g=t.fabric||(t.fabric={}),v=g.util.object.extend,m=g.util.object.clone,b=g.util.toFixed,y=g.util.parseUnit,_=g.util.multiplyTransformMatrices,w=/^(path|circle|polygon|polyline|ellipse|rect|line|image|text)$/i,S=/^(symbol|image|marker|pattern|view|svg)$/i,x=/^(?:pattern|defs|symbol|metadata|clipPath|mask)$/i,C=/^(symbol|g|a|svg)$/i,A={cx:"left",x:"left",r:"radius",cy:"top",y:"top",display:"visible",visibility:"visible",transform:"transformMatrix","fill-opacity":"fillOpacity","fill-rule":"fillRule","font-family":"fontFamily","font-size":"fontSize","font-style":"fontStyle","font-weight":"fontWeight","stroke-dasharray":"strokeDashArray","stroke-linecap":"strokeLineCap","stroke-linejoin":"strokeLineJoin","stroke-miterlimit":"strokeMiterLimit","stroke-opacity":"strokeOpacity","stroke-width":"strokeWidth","text-decoration":"textDecoration","text-anchor":"originX",opacity:"opacity"},T={stroke:"strokeOpacity",fill:"fillOpacity"};g.cssRules={},g.gradientDefs={},g.parseTransformAttribute=function(){function t(t,e){var r=Math.cos(e[0]),i=Math.sin(e[0]),n=0,o=0;3===e.length&&(n=e[1],o=e[2]),t[0]=r,t[1]=i,t[2]=-i,t[3]=r,t[4]=n-(r*n-i*o),t[5]=o-(i*n+r*o)}function e(t,e){var r=e[0],i=2===e.length?e[1]:e[0];t[0]=r,t[3]=i}function r(t,e,r){t[r]=Math.tan(g.util.degreesToRadians(e[0]))}function i(t,e){t[4]=e[0],2===e.length&&(t[5]=e[1])}var n=[1,0,0,1,0,0],o=g.reNum,a="(?:\\s+,?\\s*|,\\s*)",s="(?:(skewX)\\s*\\(\\s*("+o+")\\s*\\))",c="(?:(skewY)\\s*\\(\\s*("+o+")\\s*\\))",l="(?:(rotate)\\s*\\(\\s*("+o+")(?:"+a+"("+o+")"+a+"("+o+"))?\\s*\\))",h="(?:(scale)\\s*\\(\\s*("+o+")(?:"+a+"("+o+"))?\\s*\\))",u="(?:(translate)\\s*\\(\\s*("+o+")(?:"+a+"("+o+"))?\\s*\\))",f="(?:(matrix)\\s*\\(\\s*("+o+")"+a+"("+o+")"+a+"("+o+")"+a+"("+o+")"+a+"("+o+")"+a+"("+o+")\\s*\\))",d="(?:"+f+"|"+u+"|"+h+"|"+l+"|"+s+"|"+c+")",p="(?:"+d+"(?:"+a+"*"+d+")*)",v="^\\s*(?:"+p+"?)\\s*$",m=new RegExp(v),b=new RegExp(d,"g");return function(o){var a=n.concat(),s=[];if(!o||o&&!m.test(o))return a;o.replace(b,function(o){var c=new RegExp(d).exec(o).filter(function(t){return!!t}),l=c[1],h=c.slice(2).map(parseFloat);switch(l){case"translate":i(a,h);break;case"rotate":h[0]=g.util.degreesToRadians(h[0]),t(a,h);break;case"scale":e(a,h);break;case"skewX":r(a,h,2);break;case"skewY":r(a,h,1);break;case"matrix":a=h}s.push(a.concat()),a=n.concat()});for(var c=s[0];s.length>1;)s.shift(),c=g.util.multiplyTransformMatrices(c,s[0]);return c}}();var k=new RegExp("^\\s*("+g.reNum+"+)\\s*,?\\s*("+g.reNum+"+)\\s*,?\\s*("+g.reNum+"+)\\s*,?\\s*("+g.reNum+"+)\\s*$");g.parseSVGDocument=function(t,e,r,i){if(t){f(t);var n=g.Object.__uid++,o=d(t),a=g.util.toArray(t.getElementsByTagName("*"));if(o.crossOrigin=i&&i.crossOrigin,o.svgUid=n,0===a.length&&g.isLikelyNode){a=t.selectNodes('//*[name(.)!="svg"]');for(var s=[],c=0,l=a.length;c<l;c++)s[c]=a[c];a=s}var h=a.filter(function(t){return d(t),w.test(t.nodeName.replace("svg:",""))&&!p(t,x)});if(!h||h&&!h.length)return void(e&&e([],{}));g.gradientDefs[n]=g.getGradientDefs(t),g.cssRules[n]=g.getCSSRules(t),g.parseElements(h,function(t,r){e&&e(t,o,r,a)},m(o),r,i)}};var P=new RegExp("(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*("+g.reNum+"(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|"+g.reNum+"))?\\s+(.*)");v(g,{parseFontDeclaration:function(t,e){var r=t.match(P);if(r){var i=r[1],n=r[3],o=r[4],a=r[5],s=r[6];i&&(e.fontStyle=i),n&&(e.fontWeight=isNaN(parseFloat(n))?n:parseFloat(n)),o&&(e.fontSize=y(o)),s&&(e.fontFamily=s),a&&(e.lineHeight="normal"===a?1:a)}},getGradientDefs:function(t){var e=["linearGradient","radialGradient","svg:linearGradient","svg:radialGradient"],r=n(t,e),i,o=0,a,s,c={},l={};for(o=r.length;o--;)i=r[o],s=i.getAttribute("xlink:href"),a=i.getAttribute("id"),s&&(l[a]=s.substr(1)),c[a]=i;for(a in l){var h=c[l[a]].cloneNode(!0);for(i=c[a];h.firstChild;)i.appendChild(h.firstChild)}return c},parseAttributes:function(t,n,o){if(t){var a,c={},l;void 0===o&&(o=t.getAttribute("svgUid")),t.parentNode&&C.test(t.parentNode.nodeName)&&(c=g.parseAttributes(t.parentNode,n,o)),l=c&&c.fontSize||t.getAttribute("font-size")||g.Text.DEFAULT_SVG_FONT_SIZE;var h=n.reduce(function(e,r){return a=t.getAttribute(r),a&&(e[r]=a),e},{});h=v(h,v(s(t,o),g.parseStyleAttribute(t)));var u,f,d={};for(var p in h)u=e(p),f=r(u,h[p],c,l),d[u]=f;d&&d.font&&g.parseFontDeclaration(d.font,d);var m=v(c,d);return C.test(t.nodeName)?m:i(m)}},parseElements:function(t,e,r,i,n){new g.ElementsParser(t,e,r,i,n).parse()},parseStyleAttribute:function(t){var e={},r=t.getAttribute("style");return r?("string"==typeof r?o(r,e):a(r,e),e):e},parsePointsAttribute:function(t){if(!t)return null;t=t.replace(/,/g," ").trim(),t=t.split(/\s+/);var e=[],r,i;for(r=0,i=t.length;r<i;r+=2)e.push({x:parseFloat(t[r]),y:parseFloat(t[r+1])});return e},getCSSRules:function(t){for(var e=t.getElementsByTagName("style"),r={},i,n=0,o=e.length;n<o;n++){var a=e[n].textContent||e[n].text;a=a.replace(/\/\*[\s\S]*?\*\//g,""),""!==a.trim()&&(i=a.match(/[^{]*\{[\s\S]*?\}/g),i=i.map(function(t){return t.trim()}),i.forEach(function(t){for(var e=t.match(/([\s\S]*?)\s*\{([^}]*)\}/),i={},n=e[2].trim(),o=n.replace(/;$/,"").split(/\s*;\s*/),a=0,s=o.length;a<s;a++){var c=o[a].split(/\s*:\s*/),l=c[0],h=c[1];i[l]=h}t=e[1],t.split(",").forEach(function(t){""!==(t=t.replace(/^svg/i,"").trim())&&(r[t]?g.util.object.extend(r[t],i):r[t]=g.util.object.clone(i))})}))}return r},loadSVGFromURL:function(t,e,r,i){function n(t){var n=t.responseXML;n&&!n.documentElement&&g.window.ActiveXObject&&t.responseText&&(n=new ActiveXObject("Microsoft.XMLDOM"),n.async="false",n.loadXML(t.responseText.replace(/<!DOCTYPE[\s\S]*?(\[[\s\S]*\])*?>/i,""))),n&&n.documentElement||e&&e(null),g.parseSVGDocument(n.documentElement,function(t,r,i,n){e&&e(t,r,i,n)},r,i)}t=t.replace(/^\n\s*/,"").trim(),new g.util.request(t,{method:"get",onComplete:n})},loadSVGFromString:function(t,e,r,i){t=t.trim();var n;if("undefined"!=typeof DOMParser){var o=new DOMParser;o&&o.parseFromString&&(n=o.parseFromString(t,"text/xml"))}else g.window.ActiveXObject&&(n=new ActiveXObject("Microsoft.XMLDOM"),n.async="false",n.loadXML(t.replace(/<!DOCTYPE[\s\S]*?(\[[\s\S]*\])*?>/i,"")));g.parseSVGDocument(n.documentElement,function(t,r,i,n){e(t,r,i,n)},r,i)}})}(exports),fabric.ElementsParser=function(t,e,r,i,n){this.elements=t,this.callback=e,this.options=r,this.reviver=i,this.svgUid=r&&r.svgUid||0,this.parsingOptions=n},fabric.ElementsParser.prototype.parse=function(){this.instances=new Array(this.elements.length),this.numElements=this.elements.length,this.createObjects()},fabric.ElementsParser.prototype.createObjects=function(){for(var t=0,e=this.elements.length;t<e;t++)this.elements[t].setAttribute("svgUid",this.svgUid),function(t,e){setTimeout(function(){t.createObject(t.elements[e],e)},0)}(this,t)},fabric.ElementsParser.prototype.createObject=function(t,e){var r=fabric[fabric.util.string.capitalize(t.tagName.replace("svg:",""))];if(r&&r.fromElement)try{this._createObject(r,t,e)}catch(t){fabric.log(t)}else this.checkIfDone()},fabric.ElementsParser.prototype._createObject=function(t,e,r){t.fromElement(e,this.createCallback(r,e),this.options)},fabric.ElementsParser.prototype.createCallback=function(t,e){var r=this;return function(i){r.resolveGradient(i,"fill"),r.resolveGradient(i,"stroke"),i._removeTransformMatrix(),i instanceof fabric.Image&&i.parsePreserveAspectRatioAttribute(e),r.reviver&&r.reviver(e,i),r.instances[t]=i,r.checkIfDone()}},fabric.ElementsParser.prototype.resolveGradient=function(t,e){var r=t.get(e);if(/^url\(/.test(r)){var i=r.slice(5,r.length-1);fabric.gradientDefs[this.svgUid][i]&&t.set(e,fabric.Gradient.fromElement(fabric.gradientDefs[this.svgUid][i],t))}},fabric.ElementsParser.prototype.checkIfDone=function(){0==--this.numElements&&(this.instances=this.instances.filter(function(t){return null!=t}),this.callback(this.instances,this.elements))},function(t){"use strict";function e(t,e){this.x=t,this.y=e}var r=t.fabric||(t.fabric={});if(r.Point)return void r.warn("fabric.Point is already defined");r.Point=e,e.prototype={type:"point",constructor:e,add:function(t){return new e(this.x+t.x,this.y+t.y)},addEquals:function(t){return this.x+=t.x,this.y+=t.y,this},scalarAdd:function(t){return new e(this.x+t,this.y+t)},scalarAddEquals:function(t){return this.x+=t,this.y+=t,this},subtract:function(t){return new e(this.x-t.x,this.y-t.y)},subtractEquals:function(t){return this.x-=t.x,this.y-=t.y,this},scalarSubtract:function(t){return new e(this.x-t,this.y-t)},scalarSubtractEquals:function(t){return this.x-=t,this.y-=t,this},multiply:function(t){return new e(this.x*t,this.y*t)},multiplyEquals:function(t){return this.x*=t,this.y*=t,this},divide:function(t){return new e(this.x/t,this.y/t)},divideEquals:function(t){return this.x/=t,this.y/=t,this},eq:function(t){return this.x===t.x&&this.y===t.y},lt:function(t){return this.x<t.x&&this.y<t.y},lte:function(t){return this.x<=t.x&&this.y<=t.y},gt:function(t){return this.x>t.x&&this.y>t.y},gte:function(t){return this.x>=t.x&&this.y>=t.y},lerp:function(t,r){return void 0===r&&(r=.5),r=Math.max(Math.min(1,r),0),new e(this.x+(t.x-this.x)*r,this.y+(t.y-this.y)*r)},distanceFrom:function(t){var e=this.x-t.x,r=this.y-t.y;return Math.sqrt(e*e+r*r)},midPointFrom:function(t){return this.lerp(t)},min:function(t){return new e(Math.min(this.x,t.x),Math.min(this.y,t.y))},max:function(t){return new e(Math.max(this.x,t.x),Math.max(this.y,t.y))},toString:function(){return this.x+","+this.y},setXY:function(t,e){return this.x=t,this.y=e,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setFromPoint:function(t){return this.x=t.x,this.y=t.y,this},swap:function(t){var e=this.x,r=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=r},clone:function(){return new e(this.x,this.y)}}}(exports),function(t){"use strict";function e(t){this.status=t,this.points=[]}var r=t.fabric||(t.fabric={});if(r.Intersection)return void r.warn("fabric.Intersection is already defined");r.Intersection=e,r.Intersection.prototype={constructor:e,appendPoint:function(t){return this.points.push(t),this},appendPoints:function(t){return this.points=this.points.concat(t),this}},r.Intersection.intersectLineLine=function(t,i,n,o){var a,s=(o.x-n.x)*(t.y-n.y)-(o.y-n.y)*(t.x-n.x),c=(i.x-t.x)*(t.y-n.y)-(i.y-t.y)*(t.x-n.x),l=(o.y-n.y)*(i.x-t.x)-(o.x-n.x)*(i.y-t.y);if(0!==l){var h=s/l,u=c/l;0<=h&&h<=1&&0<=u&&u<=1?(a=new e("Intersection"),a.appendPoint(new r.Point(t.x+h*(i.x-t.x),t.y+h*(i.y-t.y)))):a=new e}else a=new e(0===s||0===c?"Coincident":"Parallel");return a},r.Intersection.intersectLinePolygon=function(t,r,i){for(var n=new e,o=i.length,a,s,c,l=0;l<o;l++)a=i[l],s=i[(l+1)%o],c=e.intersectLineLine(t,r,a,s),n.appendPoints(c.points);return n.points.length>0&&(n.status="Intersection"),n},r.Intersection.intersectPolygonPolygon=function(t,r){for(var i=new e,n=t.length,o=0;o<n;o++){var a=t[o],s=t[(o+1)%n],c=e.intersectLinePolygon(a,s,r);i.appendPoints(c.points)}return i.points.length>0&&(i.status="Intersection"),i},r.Intersection.intersectPolygonRectangle=function(t,i,n){var o=i.min(n),a=i.max(n),s=new r.Point(a.x,o.y),c=new r.Point(o.x,a.y),l=e.intersectLinePolygon(o,s,t),h=e.intersectLinePolygon(s,a,t),u=e.intersectLinePolygon(a,c,t),f=e.intersectLinePolygon(c,o,t),d=new e;return d.appendPoints(l.points),d.appendPoints(h.points),d.appendPoints(u.points),d.appendPoints(f.points),d.points.length>0&&(d.status="Intersection"),d}}(exports),function(t){"use strict";function e(t){t?this._tryParsingColor(t):this.setSource([0,0,0,1])}function r(t,e,r){return r<0&&(r+=1),r>1&&(r-=1),r<1/6?t+6*(e-t)*r:r<.5?e:r<2/3?t+(e-t)*(2/3-r)*6:t}var i=t.fabric||(t.fabric={});if(i.Color)return void i.warn("fabric.Color is already defined.");i.Color=e,i.Color.prototype={_tryParsingColor:function(t){var r;t in e.colorNameMap&&(t=e.colorNameMap[t]),"transparent"===t&&(r=[255,255,255,0]),r||(r=e.sourceFromHex(t)),r||(r=e.sourceFromRgb(t)),r||(r=e.sourceFromHsl(t)),r||(r=[0,0,0,1]),r&&this.setSource(r)},_rgbToHsl:function(t,e,r){t/=255,e/=255,r/=255;var n,o,a,s=i.util.array.max([t,e,r]),c=i.util.array.min([t,e,r]);if(a=(s+c)/2,s===c)n=o=0;else{var l=s-c;switch(o=a>.5?l/(2-s-c):l/(s+c),s){case t:n=(e-r)/l+(e<r?6:0);break;case e:n=(r-t)/l+2;break;case r:n=(t-e)/l+4}n/=6}return[Math.round(360*n),Math.round(100*o),Math.round(100*a)]},getSource:function(){return this._source},setSource:function(t){this._source=t},toRgb:function(){var t=this.getSource();return"rgb("+t[0]+","+t[1]+","+t[2]+")"},toRgba:function(){var t=this.getSource();return"rgba("+t[0]+","+t[1]+","+t[2]+","+t[3]+")"},toHsl:function(){var t=this.getSource(),e=this._rgbToHsl(t[0],t[1],t[2]);return"hsl("+e[0]+","+e[1]+"%,"+e[2]+"%)"},toHsla:function(){var t=this.getSource(),e=this._rgbToHsl(t[0],t[1],t[2]);return"hsla("+e[0]+","+e[1]+"%,"+e[2]+"%,"+t[3]+")"},toHex:function(){var t=this.getSource(),e,r,i;return e=t[0].toString(16),e=1===e.length?"0"+e:e,r=t[1].toString(16),r=1===r.length?"0"+r:r,i=t[2].toString(16),i=1===i.length?"0"+i:i,e.toUpperCase()+r.toUpperCase()+i.toUpperCase()},toHexa:function(){var t=this.getSource(),e;return e=255*t[3],e=e.toString(16),e=1===e.length?"0"+e:e,this.toHex()+e.toUpperCase()},getAlpha:function(){return this.getSource()[3]},setAlpha:function(t){var e=this.getSource();return e[3]=t,this.setSource(e),this},toGrayscale:function(){var t=this.getSource(),e=parseInt((.3*t[0]+.59*t[1]+.11*t[2]).toFixed(0),10),r=t[3];return this.setSource([e,e,e,r]),this},toBlackWhite:function(t){var e=this.getSource(),r=(.3*e[0]+.59*e[1]+.11*e[2]).toFixed(0),i=e[3];return t=t||127,r=Number(r)<Number(t)?0:255,this.setSource([r,r,r,i]),this},overlayWith:function(t){t instanceof e||(t=new e(t));for(var r=[],i=this.getAlpha(),n=.5,o=this.getSource(),a=t.getSource(),s=0;s<3;s++)r.push(Math.round(.5*o[s]+.5*a[s]));return r[3]=i,this.setSource(r),this}},i.Color.reRGBa=/^rgba?\(\s*(\d{1,3}(?:\.\d+)?\%?)\s*,\s*(\d{1,3}(?:\.\d+)?\%?)\s*,\s*(\d{1,3}(?:\.\d+)?\%?)\s*(?:\s*,\s*((?:\d*\.?\d+)?)\s*)?\)$/,i.Color.reHSLa=/^hsla?\(\s*(\d{1,3})\s*,\s*(\d{1,3}\%)\s*,\s*(\d{1,3}\%)\s*(?:\s*,\s*(\d+(?:\.\d+)?)\s*)?\)$/,i.Color.reHex=/^#?([0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{4}|[0-9a-f]{3})$/i,i.Color.colorNameMap={aqua:"#00FFFF",black:"#000000",blue:"#0000FF",fuchsia:"#FF00FF",gray:"#808080",grey:"#808080",green:"#008000",lime:"#00FF00",maroon:"#800000",navy:"#000080",olive:"#808000",orange:"#FFA500",purple:"#800080",red:"#FF0000",silver:"#C0C0C0",teal:"#008080",white:"#FFFFFF",yellow:"#FFFF00"},i.Color.fromRgb=function(t){return e.fromSource(e.sourceFromRgb(t))},i.Color.sourceFromRgb=function(t){var r=t.match(e.reRGBa);if(r){var i=parseInt(r[1],10)/(/%$/.test(r[1])?100:1)*(/%$/.test(r[1])?255:1),n=parseInt(r[2],10)/(/%$/.test(r[2])?100:1)*(/%$/.test(r[2])?255:1),o=parseInt(r[3],10)/(/%$/.test(r[3])?100:1)*(/%$/.test(r[3])?255:1);return[parseInt(i,10),parseInt(n,10),parseInt(o,10),r[4]?parseFloat(r[4]):1]}},i.Color.fromRgba=e.fromRgb,i.Color.fromHsl=function(t){return e.fromSource(e.sourceFromHsl(t))},i.Color.sourceFromHsl=function(t){var i=t.match(e.reHSLa);if(i){var n=(parseFloat(i[1])%360+360)%360/360,o=parseFloat(i[2])/(/%$/.test(i[2])?100:1),a=parseFloat(i[3])/(/%$/.test(i[3])?100:1),s,c,l;if(0===o)s=c=l=a;else{var h=a<=.5?a*(o+1):a+o-a*o,u=2*a-h;s=r(u,h,n+1/3),c=r(u,h,n),l=r(u,h,n-1/3)}return[Math.round(255*s),Math.round(255*c),Math.round(255*l),i[4]?parseFloat(i[4]):1]}},i.Color.fromHsla=e.fromHsl,i.Color.fromHex=function(t){return e.fromSource(e.sourceFromHex(t))},i.Color.sourceFromHex=function(t){if(t.match(e.reHex)){var r=t.slice(t.indexOf("#")+1),i=3===r.length||4===r.length,n=8===r.length||4===r.length,o=i?r.charAt(0)+r.charAt(0):r.substring(0,2),a=i?r.charAt(1)+r.charAt(1):r.substring(2,4),s=i?r.charAt(2)+r.charAt(2):r.substring(4,6),c=n?i?r.charAt(3)+r.charAt(3):r.substring(6,8):"FF";return[parseInt(o,16),parseInt(a,16),parseInt(s,16),parseFloat((parseInt(c,16)/255).toFixed(2))]}},i.Color.fromSource=function(t){var r=new e;return r.setSource(t),r}}(exports),function(){function t(t){var e=t.getAttribute("style"),r=t.getAttribute("offset")||0,i,n,o;if(r=parseFloat(r)/(/%$/.test(r)?100:1),r=r<0?0:r>1?1:r,e){var a=e.split(/\s*;\s*/);""===a[a.length-1]&&a.pop();for(var s=a.length;s--;){var c=a[s].split(/\s*:\s*/),l=c[0].trim(),h=c[1].trim();"stop-color"===l?i=h:"stop-opacity"===l&&(o=h)}}return i||(i=t.getAttribute("stop-color")||"rgb(0,0,0)"),o||(o=t.getAttribute("stop-opacity")),i=new fabric.Color(i),n=i.getAlpha(),o=isNaN(parseFloat(o))?1:parseFloat(o),o*=n,{offset:r,color:i.toRgb(),opacity:o}}function e(t){return{x1:t.getAttribute("x1")||0,y1:t.getAttribute("y1")||0,x2:t.getAttribute("x2")||"100%",y2:t.getAttribute("y2")||0}}function r(t){return{x1:t.getAttribute("fx")||t.getAttribute("cx")||"50%",y1:t.getAttribute("fy")||t.getAttribute("cy")||"50%",r1:0,x2:t.getAttribute("cx")||"50%",y2:t.getAttribute("cy")||"50%",r2:t.getAttribute("r")||"50%"}}function i(t,e,r){var i,n=0,o=1,a="";for(var s in e)"Infinity"===e[s]?e[s]=1:"-Infinity"===e[s]&&(e[s]=0),i=parseFloat(e[s],10),o="string"==typeof e[s]&&/^\d+%$/.test(e[s])?.01:1,"x1"===s||"x2"===s||"r2"===s?(o*="objectBoundingBox"===r?t.width:1,n="objectBoundingBox"===r?t.left||0:0):"y1"!==s&&"y2"!==s||(o*="objectBoundingBox"===r?t.height:1,n="objectBoundingBox"===r?t.top||0:0),e[s]=i*o+n;if("ellipse"===t.type&&null!==e.r2&&"objectBoundingBox"===r&&t.rx!==t.ry){var c=t.ry/t.rx;a=" scale(1, "+c+")",e.y1&&(e.y1/=c),e.y2&&(e.y2/=c)}return a}var n=fabric.util.object.clone;fabric.Gradient=fabric.util.createClass({offsetX:0,offsetY:0,initialize:function(t){t||(t={});var e={};this.id=fabric.Object.__uid++,this.type=t.type||"linear",e={x1:t.coords.x1||0,y1:t.coords.y1||0,x2:t.coords.x2||0,y2:t.coords.y2||0},"radial"===this.type&&(e.r1=t.coords.r1||0,e.r2=t.coords.r2||0),this.coords=e,this.colorStops=t.colorStops.slice(),t.gradientTransform&&(this.gradientTransform=t.gradientTransform),this.offsetX=t.offsetX||this.offsetX,this.offsetY=t.offsetY||this.offsetY},addColorStop:function(t){for(var e in t){var r=new fabric.Color(t[e]);this.colorStops.push({offset:parseFloat(e),color:r.toRgb(),opacity:r.getAlpha()})}return this},toObject:function(t){var e={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return fabric.util.populateWithProperties(this,e,t),e},toSVG:function(t){var e=n(this.coords,!0),r,i,o=n(this.colorStops,!0),a=e.r1>e.r2;o.sort(function(t,e){return t.offset-e.offset});for(var s in e)"x1"===s||"x2"===s?e[s]+=this.offsetX-t.width/2:"y1"!==s&&"y2"!==s||(e[s]+=this.offsetY-t.height/2);if(i='id="SVGID_'+this.id+'" gradientUnits="userSpaceOnUse"',this.gradientTransform&&(i+=' gradientTransform="matrix('+this.gradientTransform.join(" ")+')" '),"linear"===this.type?r=["<linearGradient ",i,' x1="',e.x1,'" y1="',e.y1,'" x2="',e.x2,'" y2="',e.y2,'">\n']:"radial"===this.type&&(r=["<radialGradient ",i,' cx="',a?e.x1:e.x2,'" cy="',a?e.y1:e.y2,'" r="',a?e.r1:e.r2,'" fx="',a?e.x2:e.x1,'" fy="',a?e.y2:e.y1,'">\n']),"radial"===this.type){if(a){o=o.concat(),o.reverse();for(var c=0;c<o.length;c++)o[c].offset=1-o[c].offset}var l=Math.min(e.r1,e.r2);if(l>0)for(var h=Math.max(e.r1,e.r2),u=l/h,c=0;c<o.length;c++)o[c].offset+=u*(1-o[c].offset)}for(var c=0;c<o.length;c++){var f=o[c];r.push("<stop ",'offset="',100*f.offset+"%",'" style="stop-color:',f.color,null!==f.opacity?";stop-opacity: "+f.opacity:";",'"/>\n')}return r.push("linear"===this.type?"</linearGradient>\n":"</radialGradient>\n"),r.join("")},toLive:function(t){var e,r=fabric.util.object.clone(this.coords);if(this.type){"linear"===this.type?e=t.createLinearGradient(r.x1,r.y1,r.x2,r.y2):"radial"===this.type&&(e=t.createRadialGradient(r.x1,r.y1,r.r1,r.x2,r.y2,r.r2));for(var i=0,n=this.colorStops.length;i<n;i++){var o=this.colorStops[i].color,a=this.colorStops[i].opacity,s=this.colorStops[i].offset;void 0!==a&&(o=new fabric.Color(o).setAlpha(a).toRgba()),e.addColorStop(s,o)}return e}}}),fabric.util.object.extend(fabric.Gradient,{fromElement:function(n,o){var a=n.getElementsByTagName("stop"),s,c=n.getAttribute("gradientUnits")||"objectBoundingBox",l=n.getAttribute("gradientTransform"),h=[],u,f;s="linearGradient"===n.nodeName||"LINEARGRADIENT"===n.nodeName?"linear":"radial","linear"===s?u=e(n):"radial"===s&&(u=r(n));for(var d=a.length;d--;)h.push(t(a[d]));f=i(o,u,c);var p=new fabric.Gradient({type:s,coords:u,colorStops:h,offsetX:-o.left,offsetY:-o.top});return(l||""!==f)&&(p.gradientTransform=fabric.parseTransformAttribute((l||"")+f)),p},forObject:function(t,e){return e||(e={}),i(t,e.coords,"userSpaceOnUse"),new fabric.Gradient(e)}})}(),function(){"use strict";var t=fabric.util.toFixed;fabric.Pattern=fabric.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,initialize:function(t,e){if(t||(t={}),this.id=fabric.Object.__uid++,this.setOptions(t),!t.source||t.source&&"string"!=typeof t.source)return void(e&&e(this));if(void 0!==fabric.util.getFunctionBody(t.source))this.source=new Function(fabric.util.getFunctionBody(t.source)),e&&e(this);else{var r=this;this.source=fabric.util.createImage(),fabric.util.loadImage(t.source,function(t){r.source=t,e&&e(r)})}},toObject:function(e){var r=fabric.Object.NUM_FRACTION_DIGITS,i,n;return"function"==typeof this.source?i=String(this.source):"string"==typeof this.source.src?i=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(i=this.source.toDataURL()),n={type:"pattern",source:i,repeat:this.repeat,offsetX:t(this.offsetX,r),offsetY:t(this.offsetY,r)},fabric.util.populateWithProperties(this,n,e),n},toSVG:function(t){var e="function"==typeof this.source?this.source():this.source,r=e.width/t.width,i=e.height/t.height,n=this.offsetX/t.width,o=this.offsetY/t.height,a="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(i=1),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(r=1),e.src?a=e.src:e.toDataURL&&(a=e.toDataURL()),'<pattern id="SVGID_'+this.id+'" x="'+n+'" y="'+o+'" width="'+r+'" height="'+i+'">\n<image x="0" y="0" width="'+e.width+'" height="'+e.height+'" xlink:href="'+a+'"></image>\n</pattern>\n'},setOptions:function(t){for(var e in t)this[e]=t[e]},toLive:function(t){var e="function"==typeof this.source?this.source():this.source;if(!e)return"";if(void 0!==e.src){if(!e.complete)return"";if(0===e.naturalWidth||0===e.naturalHeight)return""}return t.createPattern(e,this.repeat)}})}(),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.util.toFixed;if(e.Shadow)return void e.warn("fabric.Shadow is already defined.");e.Shadow=e.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,initialize:function(t){"string"==typeof t&&(t=this._parseShadow(t));for(var r in t)this[r]=t[r];this.id=e.Object.__uid++},_parseShadow:function(t){var r=t.trim(),i=e.Shadow.reOffsetsAndBlur.exec(r)||[];return{color:(r.replace(e.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseInt(i[1],10)||0,offsetY:parseInt(i[2],10)||0,blur:parseInt(i[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(t){var i=40,n=40,o=e.Object.NUM_FRACTION_DIGITS,a=e.util.rotateVector({x:this.offsetX,y:this.offsetY},e.util.degreesToRadians(-t.angle)),s=20;return t.width&&t.height&&(i=100*r((Math.abs(a.x)+this.blur)/t.width,o)+20,n=100*r((Math.abs(a.y)+this.blur)/t.height,o)+20),t.flipX&&(a.x*=-1),t.flipY&&(a.y*=-1),'<filter id="SVGID_'+this.id+'" y="-'+n+'%" height="'+(100+2*n)+'%" x="-'+i+'%" width="'+(100+2*i)+'%" >\n\t<feGaussianBlur in="SourceAlpha" stdDeviation="'+r(this.blur?this.blur/2:0,o)+'"></feGaussianBlur>\n\t<feOffset dx="'+r(a.x,o)+'" dy="'+r(a.y,o)+'" result="oBlur" ></feOffset>\n\t<feFlood flood-color="'+this.color+'"/>\n\t<feComposite in2="oBlur" operator="in" />\n\t<feMerge>\n\t\t<feMergeNode></feMergeNode>\n\t\t<feMergeNode in="SourceGraphic"></feMergeNode>\n\t</feMerge>\n</filter>\n'},toObject:function(){if(this.includeDefaultValues)return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke};var t={},r=e.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke"].forEach(function(e){this[e]!==r[e]&&(t[e]=this[e])},this),t}}),e.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:px)?(?:\s?|$))?(-?\d+(?:px)?(?:\s?|$))?(\d+(?:px)?)?(?:\s?|$)(?:$|\s)/}(exports),function(){"use strict";if(fabric.StaticCanvas)return void fabric.warn("fabric.StaticCanvas is already defined.");var t=fabric.util.object.extend,e=fabric.util.getElementOffset,r=fabric.util.removeFromArray,i=fabric.util.toFixed,n=fabric.util.transformPoint,o=fabric.util.invertTransform,a=new Error("Could not initialize `canvas` element");fabric.StaticCanvas=fabric.util.createClass(fabric.CommonMethods,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(t,e)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,clipTo:null,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:fabric.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,onBeforeScaleRotate:function(){},enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,_initStatic:function(t,e){var r=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(t),this._initOptions(e),this._setImageSmoothing(),this.interactive||this._initRetinaScaling(),e.overlayImage&&this.setOverlayImage(e.overlayImage,r),e.backgroundImage&&this.setBackgroundImage(e.backgroundImage,r),e.backgroundColor&&this.setBackgroundColor(e.backgroundColor,r),e.overlayColor&&this.setOverlayColor(e.overlayColor,r),this.calcOffset()},_isRetinaScaling:function(){return 1!==fabric.devicePixelRatio&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?fabric.devicePixelRatio:1},_initRetinaScaling:function(){this._isRetinaScaling()&&(this.lowerCanvasEl.setAttribute("width",this.width*fabric.devicePixelRatio),this.lowerCanvasEl.setAttribute("height",this.height*fabric.devicePixelRatio),this.contextContainer.scale(fabric.devicePixelRatio,fabric.devicePixelRatio))},calcOffset:function(){return this._offset=e(this.lowerCanvasEl),this},setOverlayImage:function(t,e,r){return this.__setBgOverlayImage("overlayImage",t,e,r)},setBackgroundImage:function(t,e,r){return this.__setBgOverlayImage("backgroundImage",t,e,r)},setOverlayColor:function(t,e){return this.__setBgOverlayColor("overlayColor",t,e)},setBackgroundColor:function(t,e){return this.__setBgOverlayColor("backgroundColor",t,e)},_setImageSmoothing:function(){var t=this.getContext();t.imageSmoothingEnabled=t.imageSmoothingEnabled||t.webkitImageSmoothingEnabled||t.mozImageSmoothingEnabled||t.msImageSmoothingEnabled||t.oImageSmoothingEnabled,t.imageSmoothingEnabled=this.imageSmoothingEnabled},__setBgOverlayImage:function(t,e,r,i){return"string"==typeof e?fabric.util.loadImage(e,function(e){e&&(this[t]=new fabric.Image(e,i)),r&&r(e)},this,i&&i.crossOrigin):(i&&e.setOptions(i),this[t]=e,r&&r(e)),this},__setBgOverlayColor:function(t,e,r){return this[t]=e,this._initGradient(e,t),this._initPattern(e,t,r),this},_createCanvasElement:function(t){var e=fabric.util.createCanvasElement(t);if(e.style||(e.style={}),!e)throw a;if(void 0===e.getContext)throw a;return e},_initOptions:function(t){this._setOptions(t),this.width=this.width||parseInt(this.lowerCanvasEl.width,10)||0,this.height=this.height||parseInt(this.lowerCanvasEl.height,10)||0,this.lowerCanvasEl.style&&(this.lowerCanvasEl.width=this.width,this.lowerCanvasEl.height=this.height,this.lowerCanvasEl.style.width=this.width+"px",this.lowerCanvasEl.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(t){this.lowerCanvasEl=fabric.util.getById(t)||this._createCanvasElement(t),fabric.util.addClass(this.lowerCanvasEl,"lower-canvas"),this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(t,e){return this.setDimensions({width:t},e)},setHeight:function(t,e){return this.setDimensions({height:t},e)},setDimensions:function(t,e){var r;e=e||{};for(var i in t)r=t[i],e.cssOnly||(this._setBackstoreDimension(i,t[i]),r+="px"),e.backstoreOnly||this._setCssDimension(i,r);return this._initRetinaScaling(),this._setImageSmoothing(),this.calcOffset(),e.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(t,e){return this.lowerCanvasEl[t]=e,this.upperCanvasEl&&(this.upperCanvasEl[t]=e),this.cacheCanvasEl&&(this.cacheCanvasEl[t]=e),this[t]=e,this},_setCssDimension:function(t,e){return this.lowerCanvasEl.style[t]=e,this.upperCanvasEl&&(this.upperCanvasEl.style[t]=e),this.wrapperEl&&(this.wrapperEl.style[t]=e),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(t){var e=this._activeObject,r,i=!1,n=!0;this.viewportTransform=t;for(var o=0,a=this._objects.length;o<a;o++)r=this._objects[o],r.group||r.setCoords(!1,!0);return e&&"activeSelection"===e.type&&e.setCoords(!1,!0),this.calcViewportBoundaries(),this.renderOnAddRemove&&this.requestRenderAll(),this},zoomToPoint:function(t,e){var r=t,i=this.viewportTransform.slice(0);t=n(t,o(this.viewportTransform)),i[0]=e,i[3]=e;var a=n(t,i);return i[4]+=r.x-a.x,i[5]+=r.y-a.y,this.setViewportTransform(i)},setZoom:function(t){return this.zoomToPoint(new fabric.Point(0,0),t),this},absolutePan:function(t){var e=this.viewportTransform.slice(0);return e[4]=-t.x,e[5]=-t.y,this.setViewportTransform(e)},relativePan:function(t){return this.absolutePan(new fabric.Point(-t.x-this.viewportTransform[4],-t.y-this.viewportTransform[5]))},getElement:function(){return this.lowerCanvasEl},_onObjectAdded:function(t){this.stateful&&t.setupState(),t._set("canvas",this),t.setCoords(),this.fire("object:added",{target:t}),t.fire("added")},_onObjectRemoved:function(t){this.fire("object:removed",{target:t}),t.fire("removed"),delete t.canvas},clearContext:function(t){return t.clearRect(0,0,this.width,this.height),this},getContext:function(){return this.contextContainer},clear:function(){return this._objects.length=0,this.backgroundImage=null,this.overlayImage=null,this.backgroundColor="",this.overlayColor="",this._hasITextHandlers&&(this.off("mouse:up",this._mouseUpITextHandler),this._iTextInstances=null,this._hasITextHandlers=!1),this.clearContext(this.contextContainer),this.fire("canvas:cleared"),this.renderOnAddRemove&&this.requestRenderAll(),this},renderAll:function(){var t=this.contextContainer;return this.renderCanvas(t,this._objects),this},renderAndReset:function(){this.renderAll(),this.isRendering=!1},requestRenderAll:function(){return this.isRendering||(this.isRendering=!0,fabric.util.requestAnimFrame(this.renderAndResetBound)),this},calcViewportBoundaries:function(){var t={},e=this.width,r=this.height,i=o(this.viewportTransform);return t.tl=n({x:0,y:0},i),t.br=n({x:e,y:r},i),t.tr=new fabric.Point(t.br.x,t.tl.y),t.bl=new fabric.Point(t.tl.x,t.br.y),this.vptCoords=t,t},renderCanvas:function(t,e){this.calcViewportBoundaries(),this.clearContext(t),this.fire("before:render"),this.clipTo&&fabric.util.clipContext(this,t),this._renderBackground(t),t.save(),t.transform.apply(t,this.viewportTransform),this._renderObjects(t,e),t.restore(),!this.controlsAboveOverlay&&this.interactive&&this.drawControls(t),this.clipTo&&t.restore(),this._renderOverlay(t),this.controlsAboveOverlay&&this.interactive&&this.drawControls(t),this.fire("after:render")},_renderObjects:function(t,e){for(var r=0,i=e.length;r<i;++r)e[r]&&e[r].render(t)},_renderBackgroundOrOverlay:function(t,e){var r=this[e+"Color"];r&&(t.fillStyle=r.toLive?r.toLive(t,this):r,t.fillRect(r.offsetX||0,r.offsetY||0,this.width,this.height)),(r=this[e+"Image"])&&(this[e+"Vpt"]&&(t.save(),t.transform.apply(t,this.viewportTransform)),r.render(t),this[e+"Vpt"]&&t.restore())},_renderBackground:function(t){this._renderBackgroundOrOverlay(t,"background")},_renderOverlay:function(t){this._renderBackgroundOrOverlay(t,"overlay")},getCenter:function(){return{top:this.height/2,left:this.width/2}},centerObjectH:function(t){return this._centerObject(t,new fabric.Point(this.getCenter().left,t.getCenterPoint().y))},centerObjectV:function(t){return this._centerObject(t,new fabric.Point(t.getCenterPoint().x,this.getCenter().top))},centerObject:function(t){var e=this.getCenter();return this._centerObject(t,new fabric.Point(e.left,e.top))},viewportCenterObject:function(t){var e=this.getVpCenter();return this._centerObject(t,e)},viewportCenterObjectH:function(t){var e=this.getVpCenter();return this._centerObject(t,new fabric.Point(e.x,t.getCenterPoint().y)),this},viewportCenterObjectV:function(t){var e=this.getVpCenter();return this._centerObject(t,new fabric.Point(t.getCenterPoint().x,e.y))},getVpCenter:function(){var t=this.getCenter(),e=o(this.viewportTransform);return n({x:t.left,y:t.top},e)},_centerObject:function(t,e){return t.setPositionByOrigin(e,"center","center"),this.requestRenderAll(),this},toDatalessJSON:function(t){return this.toDatalessObject(t)},toObject:function(t){return this._toObjectMethod("toObject",t)},toDatalessObject:function(t){return this._toObjectMethod("toDatalessObject",t)},_toObjectMethod:function(e,r){var i={objects:this._toObjects(e,r)};return t(i,this.__serializeBgOverlay(e,r)),fabric.util.populateWithProperties(this,i,r),i},_toObjects:function(t,e){return this.getObjects().filter(function(t){return!t.excludeFromExport}).map(function(r){return this._toObject(r,t,e)},this)},_toObject:function(t,e,r){var i;this.includeDefaultValues||(i=t.includeDefaultValues,t.includeDefaultValues=!1);var n=t[e](r);return this.includeDefaultValues||(t.includeDefaultValues=i),n},__serializeBgOverlay:function(t,e){var r={},i=this.backgroundImage,n=this.overlayImage;return this.backgroundColor&&(r.background=this.backgroundColor.toObject?this.backgroundColor.toObject(e):this.backgroundColor),this.overlayColor&&(r.overlay=this.overlayColor.toObject?this.overlayColor.toObject(e):this.overlayColor),i&&!i.excludeFromExport&&(r.backgroundImage=this._toObject(i,t,e)),n&&!n.excludeFromExport&&(r.overlayImage=this._toObject(n,t,e)),r},svgViewportTransformation:!0,toSVG:function(t,e){t||(t={});var r=[];return this._setSVGPreamble(r,t),this._setSVGHeader(r,t),this._setSVGBgOverlayColor(r,"backgroundColor"),this._setSVGBgOverlayImage(r,"backgroundImage",e),this._setSVGObjects(r,e),this._setSVGBgOverlayColor(r,"overlayColor"),this._setSVGBgOverlayImage(r,"overlayImage",e),r.push("</svg>"),r.join("")},_setSVGPreamble:function(t,e){e.suppressPreamble||t.push('<?xml version="1.0" encoding="',e.encoding||"UTF-8",'" standalone="no" ?>\n','<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ','"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n')},_setSVGHeader:function(t,e){var r=e.width||this.width,n=e.height||this.height,o,a='viewBox="0 0 '+this.width+" "+this.height+'" ',s=fabric.Object.NUM_FRACTION_DIGITS;e.viewBox?a='viewBox="'+e.viewBox.x+" "+e.viewBox.y+" "+e.viewBox.width+" "+e.viewBox.height+'" ':this.svgViewportTransformation&&(o=this.viewportTransform,a='viewBox="'+i(-o[4]/o[0],s)+" "+i(-o[5]/o[3],s)+" "+i(this.width/o[0],s)+" "+i(this.height/o[3],s)+'" '),t.push("<svg ",'xmlns="http://www.w3.org/2000/svg" ','xmlns:xlink="http://www.w3.org/1999/xlink" ','version="1.1" ','width="',r,'" ','height="',n,'" ',a,'xml:space="preserve">\n',"<desc>Created with Fabric.js ",fabric.version,"</desc>\n","<defs>\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),"</defs>\n")},createSVGRefElementsMarkup:function(){var t=this;return["backgroundColor","overlayColor"].map(function(e){var r=t[e];if(r&&r.toLive)return r.toSVG(t,!1)}).join("")},createSVGFontFacesMarkup:function(){for(var t="",e={},r,i,n,o,a,s,c,l=fabric.fontPaths,h=this.getObjects(),u=0,f=h.length;u<f;u++)if(r=h[u],i=r.fontFamily,-1!==r.type.indexOf("text")&&!e[i]&&l[i]&&(e[i]=!0,r.styles)){n=r.styles;for(a in n){o=n[a];for(c in o)s=o[c],i=s.fontFamily,!e[i]&&l[i]&&(e[i]=!0)}}for(var d in e)t+=["\t\t@font-face {\n","\t\t\tfont-family: '",d,"';\n","\t\t\tsrc: url('",l[d],"');\n","\t\t}\n"].join("");return t&&(t=['\t<style type="text/css">',"<![CDATA[\n",t,"]]>","</style>\n"].join("")),t},_setSVGObjects:function(t,e){for(var r,i=0,n=this.getObjects(),o=n.length;i<o;i++)r=n[i],r.excludeFromExport||this._setSVGObject(t,r,e)},_setSVGObject:function(t,e,r){t.push(e.toSVG(r))},_setSVGBgOverlayImage:function(t,e,r){this[e]&&this[e].toSVG&&t.push(this[e].toSVG(r))},_setSVGBgOverlayColor:function(t,e){var r=this[e];if(r)if(r.toLive){var i=r.repeat;t.push('<rect transform="translate(',this.width/2,",",this.height/2,')"',' x="',r.offsetX-this.width/2,'" y="',r.offsetY-this.height/2,'" ','width="',"repeat-y"===i||"no-repeat"===i?r.source.width:this.width,'" height="',"repeat-x"===i||"no-repeat"===i?r.source.height:this.height,'" fill="url(#SVGID_'+r.id+')"',"></rect>\n")}else t.push('<rect x="0" y="0" ','width="',this.width,'" height="',this.height,'" fill="',this[e],'"',"></rect>\n")},sendToBack:function(t){if(!t)return this;var e=this._activeObject,i,n,o;if(t===e&&"activeSelection"===t.type)for(o=e._objects,i=o.length;i--;)n=o[i],r(this._objects,n),this._objects.unshift(n);else r(this._objects,t),this._objects.unshift(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(t){if(!t)return this;var e=this._activeObject,i,n,o;if(t===e&&"activeSelection"===t.type)for(o=e._objects,i=0;i<o.length;i++)n=o[i],r(this._objects,n),this._objects.push(n);else r(this._objects,t),this._objects.push(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},sendBackwards:function(t,e){if(!t)return this;var i=this._activeObject,n,o,a,s,c,l=0;if(t===i&&"activeSelection"===t.type)for(c=i._objects,n=0;n<c.length;n++)o=c[n],a=this._objects.indexOf(o),a>0+l&&(s=a-1,r(this._objects,o),this._objects.splice(s,0,o)),l++;else 0!==(a=this._objects.indexOf(t))&&(s=this._findNewLowerIndex(t,a,e),r(this._objects,t),this._objects.splice(s,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(t,e,r){var i;if(r){i=e;for(var n=e-1;n>=0;--n){if(t.intersectsWithObject(this._objects[n])||t.isContainedWithinObject(this._objects[n])||this._objects[n].isContainedWithinObject(t)){i=n;break}}}else i=e-1;return i},bringForward:function(t,e){if(!t)return this;var i=this._activeObject,n,o,a,s,c,l=0;if(t===i&&"activeSelection"===t.type)for(c=i._objects,n=c.length;n--;)o=c[n],a=this._objects.indexOf(o),a<this._objects.length-1-l&&(s=a+1,r(this._objects,o),this._objects.splice(s,0,o)),l++;else(a=this._objects.indexOf(t))!==this._objects.length-1&&(s=this._findNewUpperIndex(t,a,e),r(this._objects,t),this._objects.splice(s,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewUpperIndex:function(t,e,r){var i;if(r){i=e;for(var n=e+1;n<this._objects.length;++n){if(t.intersectsWithObject(this._objects[n])||t.isContainedWithinObject(this._objects[n])||this._objects[n].isContainedWithinObject(t)){i=n;break}}}else i=e+1;return i},moveTo:function(t,e){return r(this._objects,t),this._objects.splice(e,0,t),this.renderOnAddRemove&&this.requestRenderAll()},dispose:function(){return this.clear(),this},toString:function(){return"#<fabric.Canvas ("+this.complexity()+"): { objects: "+this.getObjects().length+" }>"}}),t(fabric.StaticCanvas.prototype,fabric.Observable),t(fabric.StaticCanvas.prototype,fabric.Collection),t(fabric.StaticCanvas.prototype,fabric.DataURLExporter),t(fabric.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(t){var e=fabric.util.createCanvasElement();if(!e||!e.getContext)return null;var r=e.getContext("2d");if(!r)return null;switch(t){case"getImageData":return void 0!==r.getImageData;case"setLineDash":return void 0!==r.setLineDash;case"toDataURL":return void 0!==e.toDataURL;case"toDataURLWithQuality":try{return e.toDataURL("image/jpeg",0),!0}catch(t){}return!1;default:return null}}}),fabric.StaticCanvas.prototype.toJSON=fabric.StaticCanvas.prototype.toObject}(),fabric.BaseBrush=fabric.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeDashArray:null,setShadow:function(t){return this.shadow=new fabric.Shadow(t),this},_setBrushStyles:function(){var t=this.canvas.contextTop;t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.lineJoin=this.strokeLineJoin,this.strokeDashArray&&fabric.StaticCanvas.supports("setLineDash")&&t.setLineDash(this.strokeDashArray)},_setShadow:function(){if(this.shadow){var t=this.canvas.contextTop,e=this.canvas.getZoom();t.shadowColor=this.shadow.color,t.shadowBlur=this.shadow.blur*e,t.shadowOffsetX=this.shadow.offsetX*e,t.shadowOffsetY=this.shadow.offsetY*e}},_resetShadow:function(){var t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0}}),function(){fabric.PencilBrush=fabric.util.createClass(fabric.BaseBrush,{initialize:function(t){this.canvas=t,this._points=[]},onMouseDown:function(t){this._prepareForDrawing(t),this._captureDrawingPath(t),this._render()},onMouseMove:function(t){this._captureDrawingPath(t),this.canvas.clearContext(this.canvas.contextTop),this._render()},onMouseUp:function(){this._finalizeAndAddPath()},_prepareForDrawing:function(t){var e=new fabric.Point(t.x,t.y);this._reset(),this._addPoint(e),this.canvas.contextTop.moveTo(e.x,e.y)},_addPoint:function(t){this._points.push(t)},_reset:function(){this._points.length=0,this._setBrushStyles(),this._setShadow()},_captureDrawingPath:function(t){var e=new fabric.Point(t.x,t.y);this._addPoint(e)},_render:function(){var t=this.canvas.contextTop,e=this.canvas.viewportTransform,r=this._points[0],i=this._points[1];t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5]),t.beginPath(),2===this._points.length&&r.x===i.x&&r.y===i.y&&(r.x-=.5,i.x+=.5),t.moveTo(r.x,r.y);for(var n=1,o=this._points.length;n<o;n++){var a=r.midPointFrom(i);t.quadraticCurveTo(r.x,r.y,a.x,a.y),r=this._points[n],i=this._points[n+1]}t.lineTo(r.x,r.y),t.stroke(),t.restore()},convertPointsToSVGPath:function(t){var e=[],r=new fabric.Point(t[0].x,t[0].y),i=new fabric.Point(t[1].x,t[1].y);e.push("M ",t[0].x," ",t[0].y," ");for(var n=1,o=t.length;n<o;n++){var a=r.midPointFrom(i);e.push("Q ",r.x," ",r.y," ",a.x," ",a.y," "),r=new fabric.Point(t[n].x,t[n].y),n+1<t.length&&(i=new fabric.Point(t[n+1].x,t[n+1].y))}return e.push("L ",r.x," ",r.y," "),e},createPath:function(t){var e=new fabric.Path(t,{fill:null,stroke:this.color,strokeWidth:this.width,strokeLineCap:this.strokeLineCap,strokeLineJoin:this.strokeLineJoin,strokeDashArray:this.strokeDashArray,originX:"center",originY:"center"});return this.shadow&&(this.shadow.affectStroke=!0,e.setShadow(this.shadow)),e},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath();var t=this.convertPointsToSVGPath(this._points).join("");if("M 0 0 Q 0 0 0 0 L 0 0"===t)return void this.canvas.requestRenderAll();var e=this.createPath(t);this.canvas.add(e),e.setCoords(),this.canvas.clearContext(this.canvas.contextTop),this._resetShadow(),this.canvas.requestRenderAll(),this.canvas.fire("path:created",{path:e})}})}(),fabric.CircleBrush=fabric.util.createClass(fabric.BaseBrush,{width:10,initialize:function(t){this.canvas=t,this.points=[]},drawDot:function(t){var e=this.addPoint(t),r=this.canvas.contextTop,i=this.canvas.viewportTransform;r.save(),r.transform(i[0],i[1],i[2],i[3],i[4],i[5]),r.fillStyle=e.fill,r.beginPath(),r.arc(e.x,e.y,e.radius,0,2*Math.PI,!1),r.closePath(),r.fill(),r.restore()},onMouseDown:function(t){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(t)},onMouseMove:function(t){this.drawDot(t)},onMouseUp:function(){var t=this.canvas.renderOnAddRemove;this.canvas.renderOnAddRemove=!1;for(var e=[],r=0,i=this.points.length;r<i;r++){var n=this.points[r],o=new fabric.Circle({radius:n.radius,left:n.x,top:n.y,originX:"center",originY:"center",fill:n.fill});this.shadow&&o.setShadow(this.shadow),e.push(o)}var a=new fabric.Group(e,{originX:"center",originY:"center"});a.canvas=this.canvas,this.canvas.add(a),this.canvas.fire("path:created",{path:a}),this.canvas.clearContext(this.canvas.contextTop),this._resetShadow(),this.canvas.renderOnAddRemove=t,this.canvas.requestRenderAll()},addPoint:function(t){var e=new fabric.Point(t.x,t.y),r=fabric.util.getRandomInt(Math.max(0,this.width-20),this.width+20)/2,i=new fabric.Color(this.color).setAlpha(fabric.util.getRandomInt(0,100)/100).toRgba();return e.radius=r,e.fill=i,this.points.push(e),e}}),fabric.SprayBrush=fabric.util.createClass(fabric.BaseBrush,{width:10,density:20,dotWidth:1,dotWidthVariance:1,randomOpacity:!1,optimizeOverlapping:!0,initialize:function(t){this.canvas=t,this.sprayChunks=[]},onMouseDown:function(t){this.sprayChunks.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.addSprayChunk(t),this.render()},onMouseMove:function(t){this.addSprayChunk(t),this.render()},onMouseUp:function(){var t=this.canvas.renderOnAddRemove;this.canvas.renderOnAddRemove=!1;for(var e=[],r=0,i=this.sprayChunks.length;r<i;r++)for(var n=this.sprayChunks[r],o=0,a=n.length;o<a;o++){var s=new fabric.Rect({width:n[o].width,height:n[o].width,left:n[o].x+1,top:n[o].y+1,originX:"center",originY:"center",fill:this.color});this.shadow&&s.setShadow(this.shadow),e.push(s)}this.optimizeOverlapping&&(e=this._getOptimizedRects(e));var c=new fabric.Group(e,{originX:"center",originY:"center"});c.canvas=this.canvas,this.canvas.add(c),this.canvas.fire("path:created",{path:c}),this.canvas.clearContext(this.canvas.contextTop),this._resetShadow(),this.canvas.renderOnAddRemove=t,this.canvas.requestRenderAll()},_getOptimizedRects:function(t){for(var e={},r,i=0,n=t.length;i<n;i++)r=t[i].left+""+t[i].top,e[r]||(e[r]=t[i]);var o=[];for(r in e)o.push(e[r]);return o},render:function(){var t=this.canvas.contextTop;t.fillStyle=this.color;var e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5]);for(var r=0,i=this.sprayChunkPoints.length;r<i;r++){var n=this.sprayChunkPoints[r];void 0!==n.opacity&&(t.globalAlpha=n.opacity),t.fillRect(n.x,n.y,n.width,n.width)}t.restore()},addSprayChunk:function(t){this.sprayChunkPoints=[];for(var e,r,i,n=this.width/2,o=0;o<this.density;o++){e=fabric.util.getRandomInt(t.x-n,t.x+n),r=fabric.util.getRandomInt(t.y-n,t.y+n),i=this.dotWidthVariance?fabric.util.getRandomInt(Math.max(1,this.dotWidth-this.dotWidthVariance),this.dotWidth+this.dotWidthVariance):this.dotWidth;var a=new fabric.Point(e,r);a.width=i,this.randomOpacity&&(a.opacity=fabric.util.getRandomInt(0,100)/100),this.sprayChunkPoints.push(a)}this.sprayChunks.push(this.sprayChunkPoints)}}),fabric.PatternBrush=fabric.util.createClass(fabric.PencilBrush,{getPatternSrc:function(){var t=20,e=5,r=fabric.document.createElement("canvas"),i=r.getContext("2d");return r.width=r.height=25,i.fillStyle=this.color,i.beginPath(),i.arc(10,10,10,0,2*Math.PI,!1),i.closePath(),i.fill(),r},getPatternSrcFunction:function(){return String(this.getPatternSrc).replace("this.color",'"'+this.color+'"')},getPattern:function(){return this.canvas.contextTop.createPattern(this.source||this.getPatternSrc(),"repeat")},_setBrushStyles:function(){this.callSuper("_setBrushStyles"),this.canvas.contextTop.strokeStyle=this.getPattern()},createPath:function(t){var e=this.callSuper("createPath",t),r=e._getLeftTopCoords().scalarAdd(e.strokeWidth/2);return e.stroke=new fabric.Pattern({source:this.source||this.getPatternSrcFunction(),offsetX:-r.x,offsetY:-r.y}),e}}),function(){var t=fabric.util.getPointer,e=fabric.util.degreesToRadians,r=fabric.util.radiansToDegrees,i=Math.atan2,n=Math.abs,o=fabric.StaticCanvas.supports("setLineDash"),a=.5;fabric.Canvas=fabric.util.createClass(fabric.StaticCanvas,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this._initStatic(t,e),this._initInteractive(),this._createCacheCanvas()},uniScaleTransform:!1,uniScaleKey:"shiftKey",centeredScaling:!1,centeredRotation:!1,centeredKey:"altKey",altActionKey:"shiftKey",interactive:!0,selection:!0,selectionKey:"shiftKey",altSelectionKey:null,selectionColor:"rgba(100, 100, 255, 0.3)",selectionDashArray:[],selectionBorderColor:"rgba(255, 255, 255, 0.3)",selectionLineWidth:1,hoverCursor:"move",moveCursor:"move",defaultCursor:"default",freeDrawingCursor:"crosshair",rotationCursor:"crosshair",notAllowedCursor:"not-allowed",containerClass:"canvas-container",perPixelTargetFind:!1,targetFindTolerance:0,skipTargetFind:!1,isDrawingMode:!1,preserveObjectStacking:!1,snapAngle:0,snapThreshold:null,stopContextMenu:!1,fireRightClick:!1,fireMiddleClick:!1,_initInteractive:function(){this._currentTransform=null,this._groupSelector=null,this._initWrapperElement(),this._createUpperCanvas(),this._initEventListeners(),this._initRetinaScaling(),this.freeDrawingBrush=fabric.PencilBrush&&new fabric.PencilBrush(this),this.calcOffset()},_chooseObjectsToRender:function(){var t=this.getActiveObjects(),e,r,i;if(t.length>0&&!this.preserveObjectStacking){r=[],i=[];for(var n=0,o=this._objects.length;n<o;n++)e=this._objects[n],-1===t.indexOf(e)?r.push(e):i.push(e);t.length>1&&(this._activeObject._objects=i),r.push.apply(r,i)}else r=this._objects;return r},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1);var t=this.contextContainer;return this.renderCanvas(t,this._chooseObjectsToRender()),this},renderTop:function(){var t=this.contextTop;return this.clearContext(t),this.selection&&this._groupSelector&&this._drawSelection(t),this.fire("after:render"),this.contextTopDirty=!0,this},_resetCurrentTransform:function(){var t=this._currentTransform;t.target.set({scaleX:t.original.scaleX,scaleY:t.original.scaleY,skewX:t.original.skewX,skewY:t.original.skewY,left:t.original.left,top:t.original.top}),this._shouldCenterTransform(t.target)?"rotate"===t.action?this._setOriginToCenter(t.target):("center"!==t.originX&&("right"===t.originX?t.mouseXSign=-1:t.mouseXSign=1),"center"!==t.originY&&("bottom"===t.originY?t.mouseYSign=-1:t.mouseYSign=1),t.originX="center",t.originY="center"):(t.originX=t.original.originX,t.originY=t.original.originY)},containsPoint:function(t,e,r){var i=!0,n=r||this.getPointer(t,!0),o;return o=e.group&&e.group===this._activeObject&&"activeSelection"===e.group.type?this._normalizePointer(e.group,n):{x:n.x,y:n.y},e.containsPoint(o)||e._findTargetCorner(n)},_normalizePointer:function(t,e){var r=t.calcTransformMatrix(),i=fabric.util.invertTransform(r),n=this.restorePointerVpt(e);return fabric.util.transformPoint(n,i)},isTargetTransparent:function(t,e,r){var i=t.hasBorders,n=t.transparentCorners,o=this.contextCache,a=t.selectionBackgroundColor;t.hasBorders=t.transparentCorners=!1,t.selectionBackgroundColor="",o.save(),o.transform.apply(o,this.viewportTransform),t.render(o),o.restore(),t.active&&t._renderControls(o),t.hasBorders=i,t.transparentCorners=n,t.selectionBackgroundColor=a;var s=fabric.util.isTransparent(o,e,r,this.targetFindTolerance);return this.clearContext(o),s},_shouldClearSelection:function(t,e){var r=this.getActiveObjects(),i=this._activeObject;return!e||e&&i&&r.length>1&&-1===r.indexOf(e)&&i!==e&&!t[this.selectionKey]||e&&!e.evented||e&&!e.selectable&&i&&i!==e},_shouldCenterTransform:function(t){if(t){var e=this._currentTransform,r;return"scale"===e.action||"scaleX"===e.action||"scaleY"===e.action?r=this.centeredScaling||t.centeredScaling:"rotate"===e.action&&(r=this.centeredRotation||t.centeredRotation),r?!e.altKey:e.altKey}},_getOriginFromCorner:function(t,e){var r={x:t.originX,y:t.originY};return"ml"===e||"tl"===e||"bl"===e?r.x="right":"mr"!==e&&"tr"!==e&&"br"!==e||(r.x="left"),"tl"===e||"mt"===e||"tr"===e?r.y="bottom":"bl"!==e&&"mb"!==e&&"br"!==e||(r.y="top"),r},_getActionFromCorner:function(t,e,r){if(!e)return"drag";switch(e){case"mtr":return"rotate";case"ml":case"mr":return r[this.altActionKey]?"skewY":"scaleX";case"mt":case"mb":return r[this.altActionKey]?"skewX":"scaleY";default:return"scale"}},_setupCurrentTransform:function(t,r){if(r){var i=this.getPointer(t),n=r._findTargetCorner(this.getPointer(t,!0)),o=this._getActionFromCorner(r,n,t),a=this._getOriginFromCorner(r,n);this._currentTransform={target:r,action:o,corner:n,scaleX:r.scaleX,scaleY:r.scaleY,skewX:r.skewX,skewY:r.skewY,offsetX:i.x-r.left,offsetY:i.y-r.top,originX:a.x,originY:a.y,ex:i.x,ey:i.y,lastX:i.x,lastY:i.y,left:r.left,top:r.top,theta:e(r.angle),width:r.width*r.scaleX,mouseXSign:1,mouseYSign:1,shiftKey:t.shiftKey,altKey:t[this.centeredKey]},this._currentTransform.original={left:r.left,top:r.top,scaleX:r.scaleX,scaleY:r.scaleY,skewX:r.skewX,skewY:r.skewY,originX:a.x,originY:a.y},this._resetCurrentTransform()}},_translateObject:function(t,e){var r=this._currentTransform,i=r.target,n=t-r.offsetX,o=e-r.offsetY,a=!i.get("lockMovementX")&&i.left!==n,s=!i.get("lockMovementY")&&i.top!==o;return a&&i.set("left",n),s&&i.set("top",o),a||s},_changeSkewTransformOrigin:function(t,e,r){var i="originX",n={0:"center"},o=e.target.skewX,a="left",s="right",c="mt"===e.corner||"ml"===e.corner?1:-1,l=1;t=t>0?1:-1,"y"===r&&(o=e.target.skewY,a="top",s="bottom",i="originY"),n[-1]=a,n[1]=s,e.target.flipX&&(l*=-1),e.target.flipY&&(l*=-1),0===o?(e.skewSign=-c*t*l,e[i]=n[-t]):(o=o>0?1:-1,e.skewSign=o,e[i]=n[o*c*l])},_skewObject:function(t,e,r){var i=this._currentTransform,n=i.target,o=!1,a=n.get("lockSkewingX"),s=n.get("lockSkewingY");if(a&&"x"===r||s&&"y"===r)return!1;var c=n.getCenterPoint(),l=n.toLocalPoint(new fabric.Point(t,e),"center","center")[r],h=n.toLocalPoint(new fabric.Point(i.lastX,i.lastY),"center","center")[r],u,f,d=n._getTransformedDimensions();return this._changeSkewTransformOrigin(l-h,i,r),u=n.toLocalPoint(new fabric.Point(t,e),i.originX,i.originY)[r],f=n.translateToOriginPoint(c,i.originX,i.originY),o=this._setObjectSkew(u,i,r,d),i.lastX=t,i.lastY=e,n.setPositionByOrigin(f,i.originX,i.originY),o},_setObjectSkew:function(t,e,r,i){var n=e.target,o,a=!1,s=e.skewSign,c,l,h,u,f,d,p,g;return"x"===r?(h="y",u="Y",f="X",p=0,g=n.skewY):(h="x",u="X",f="Y",p=n.skewX,g=0),l=n._getTransformedDimensions(p,g),d=2*Math.abs(t)-l[r],d<=2?o=0:(o=s*Math.atan(d/n["scale"+f]/(l[h]/n["scale"+u])),o=fabric.util.radiansToDegrees(o)),a=n["skew"+f]!==o,n.set("skew"+f,o),0!==n["skew"+u]&&(c=n._getTransformedDimensions(),o=i[h]/c[h]*n["scale"+u],n.set("scale"+u,o)),a},_scaleObject:function(t,e,r){var i=this._currentTransform,n=i.target,o=n.get("lockScalingX"),a=n.get("lockScalingY"),s=n.get("lockScalingFlip");if(o&&a)return!1;var c=n.translateToOriginPoint(n.getCenterPoint(),i.originX,i.originY),l=n.toLocalPoint(new fabric.Point(t,e),i.originX,i.originY),h=n._getTransformedDimensions(),u=!1;return this._setLocalMouse(l,i),u=this._setObjectScale(l,i,o,a,r,s,h),n.setPositionByOrigin(c,i.originX,i.originY),u},_setObjectScale:function(t,e,r,i,n,o,a){var s=e.target,c=!1,l=!1,h=!1,u,f,d,p;return d=t.x*s.scaleX/a.x,p=t.y*s.scaleY/a.y,u=s.scaleX!==d,f=s.scaleY!==p,o&&d<=0&&d<s.scaleX&&(c=!0),o&&p<=0&&p<s.scaleY&&(l=!0),"equally"!==n||r||i?n?"x"!==n||s.get("lockUniScaling")?"y"!==n||s.get("lockUniScaling")||l||i||s.set("scaleY",p)&&(h=h||f):c||r||s.set("scaleX",d)&&(h=h||u):(c||r||s.set("scaleX",d)&&(h=h||u),l||i||s.set("scaleY",p)&&(h=h||f)):c||l||(h=this._scaleObjectEqually(t,s,e,a)),e.newScaleX=d,e.newScaleY=p,c||l||this._flipObject(e,n),h},_scaleObjectEqually:function(t,e,r,i){var n=t.y+t.x,o=i.y*r.original.scaleY/e.scaleY+i.x*r.original.scaleX/e.scaleX,a;return r.newScaleX=r.original.scaleX*n/o,r.newScaleY=r.original.scaleY*n/o,a=r.newScaleX!==e.scaleX||r.newScaleY!==e.scaleY,e.set("scaleX",r.newScaleX),e.set("scaleY",r.newScaleY),a},_flipObject:function(t,e){t.newScaleX<0&&"y"!==e&&("left"===t.originX?t.originX="right":"right"===t.originX&&(t.originX="left")),t.newScaleY<0&&"x"!==e&&("top"===t.originY?t.originY="bottom":"bottom"===t.originY&&(t.originY="top"))},_setLocalMouse:function(t,e){var r=e.target,i=this.getZoom(),o=r.padding/i;"right"===e.originX?t.x*=-1:"center"===e.originX&&(t.x*=2*e.mouseXSign,t.x<0&&(e.mouseXSign=-e.mouseXSign)),"bottom"===e.originY?t.y*=-1:"center"===e.originY&&(t.y*=2*e.mouseYSign,t.y<0&&(e.mouseYSign=-e.mouseYSign)),n(t.x)>o?t.x<0?t.x+=o:t.x-=o:t.x=0,n(t.y)>o?t.y<0?t.y+=o:t.y-=o:t.y=0},_rotateObject:function(t,e){var n=this._currentTransform;if(n.target.get("lockRotation"))return!1;var o=i(n.ey-n.top,n.ex-n.left),a=i(e-n.top,t-n.left),s=r(a-o+n.theta),c=!0;if(n.target.snapAngle>0){var l=n.target.snapAngle,h=n.target.snapThreshold||l,u=Math.ceil(s/l)*l,f=Math.floor(s/l)*l;Math.abs(s-f)<h?s=f:Math.abs(s-u)<h&&(s=u)}return s<0&&(s=360+s),s%=360,n.target.angle===s?c=!1:n.target.angle=s,c},setCursor:function(t){this.upperCanvasEl.style.cursor=t},_resetObjectTransform:function(t){t.scaleX=1,t.scaleY=1,t.skewX=0,t.skewY=0,t.setAngle(0)},_drawSelection:function(t){var e=this._groupSelector,r=e.left,i=e.top,a=n(r),s=n(i);if(this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(e.ex-(r>0?0:-r),e.ey-(i>0?0:-i),a,s)),this.selectionLineWidth&&this.selectionBorderColor)if(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,this.selectionDashArray.length>1&&!o){var c=e.ex+.5-(r>0?0:a),l=e.ey+.5-(i>0?0:s);t.beginPath(),fabric.util.drawDashedLine(t,c,l,c+a,l,this.selectionDashArray),fabric.util.drawDashedLine(t,c,l+s-1,c+a,l+s-1,this.selectionDashArray),fabric.util.drawDashedLine(t,c,l,c,l+s,this.selectionDashArray),fabric.util.drawDashedLine(t,c+a-1,l,c+a-1,l+s,this.selectionDashArray),t.closePath(),t.stroke()}else fabric.Object.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(e.ex+.5-(r>0?0:a),e.ey+.5-(i>0?0:s),a,s)},findTarget:function(t,e){if(!this.skipTargetFind){var r=!0,i=this.getPointer(t,!0),n=this._activeObject,o=this.getActiveObjects(),a;if(this.targets=[],o.length>1&&!e&&n===this._searchPossibleTargets([n],i))return this._fireOverOutEvents(n,t),n;if(1===o.length&&n._findTargetCorner(i))return this._fireOverOutEvents(n,t),n;if(1===o.length&&n===this._searchPossibleTargets([n],i)){if(!this.preserveObjectStacking)return this._fireOverOutEvents(n,t),n;a=n}var s=this._searchPossibleTargets(this._objects,i);return t[this.altSelectionKey]&&s&&a&&s!==a&&(s=a),this._fireOverOutEvents(s,t),s}},_fireOverOutEvents:function(t,e){var r,i,n=this._hoveredTarget;n!==t&&(r={e:e,target:t,previousTarget:this._hoveredTarget},i={e:e,target:this._hoveredTarget,nextTarget:t},this._hoveredTarget=t),t?n!==t&&(n&&(this.fire("mouse:out",i),n.fire("mouseout",i)),this.fire("mouse:over",r),t.fire("mouseover",r)):n&&(this.fire("mouse:out",i),n.fire("mouseout",i))},_checkTarget:function(t,e){if(e&&e.visible&&e.evented&&this.containsPoint(null,e,t)){if(!this.perPixelTargetFind&&!e.perPixelTargetFind||e.isEditing)return!0;if(!this.isTargetTransparent(e,t.x,t.y))return!0}},_searchPossibleTargets:function(t,e){for(var r,i=t.length,n,o;i--;)if(this._checkTarget(e,t[i])){r=t[i],"group"===r.type&&r.subTargetCheck&&(n=this._normalizePointer(r,e),(o=this._searchPossibleTargets(r._objects,n))&&this.targets.push(o));break}return r},restorePointerVpt:function(t){return fabric.util.transformPoint(t,fabric.util.invertTransform(this.viewportTransform))},getPointer:function(e,r,i){i||(i=this.upperCanvasEl);var n=t(e),o=i.getBoundingClientRect(),a=o.width||0,s=o.height||0,c;return a&&s||("top"in o&&"bottom"in o&&(s=Math.abs(o.top-o.bottom)),"right"in o&&"left"in o&&(a=Math.abs(o.right-o.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,r||(n=this.restorePointerVpt(n)),c=0===a||0===s?{width:1,height:1}:{width:i.width/a,height:i.height/s},{x:n.x*c.width,y:n.y*c.height}},_createUpperCanvas:function(){var t=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,"");this.upperCanvasEl?this.upperCanvasEl.className="":this.upperCanvasEl=this._createCanvasElement(),fabric.util.addClass(this.upperCanvasEl,"upper-canvas "+t),this.wrapperEl.appendChild(this.upperCanvasEl),this._copyCanvasStyle(this.lowerCanvasEl,this.upperCanvasEl),this._applyCanvasStyle(this.upperCanvasEl),this.contextTop=this.upperCanvasEl.getContext("2d")},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=fabric.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),fabric.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),fabric.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(t){var e=this.width||t.width,r=this.height||t.height;fabric.util.setStyle(t,{position:"absolute",width:e+"px",height:r+"px",left:0,top:0,"touch-action":"none"}),t.width=e,t.height=r,fabric.util.makeElementUnselectable(t)},_copyCanvasStyle:function(t,e){e.style.cssText=t.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var t=this._activeObject;return t?"activeSelection"===t.type&&t._objects?t._objects:[t]:[]},_onObjectRemoved:function(t){t===this._activeObject&&(this.fire("before:selection:cleared",{target:t}),this._discardActiveObject(),this.fire("selection:cleared",{target:t}),t.fire("deselected")),this._hoveredTarget===t&&(this._hoveredTarget=null),this.callSuper("_onObjectRemoved",t)},setActiveObject:function(t,e){var r=this._activeObject;return t===r?this:(this._setActiveObject(t)&&(r&&r.fire("deselected",{e:e}),this.fire("object:selected",{target:t,e:e}),t.fire("selected",{e:e})),this)},_setActiveObject:function(t){return this._activeObject!==t&&!!this._discardActiveObject()&&(this._activeObject=t,t.set("active",!0),!0)},_discardActiveObject:function(){var t=this._activeObject;if(t&&t.onDeselect&&"function"==typeof t.onDeselect){if(t.onDeselect())return!1;t.set("active",!1),this._activeObject=null}return!0},discardActiveObject:function(t){var e=this._activeObject;return e&&(this.fire("before:selection:cleared",{target:e,e:t}),this._discardActiveObject()&&(this.fire("selection:cleared",{e:t}),e.fire("deselected",{e:t}))),this},dispose:function(){fabric.StaticCanvas.prototype.dispose.call(this);var t=this.wrapperEl;return this.removeListeners(),t.removeChild(this.upperCanvasEl),t.removeChild(this.lowerCanvasEl),delete this.upperCanvasEl,t.parentNode&&t.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(t){var e=this._activeObject;e&&e._renderControls(t)},_toObject:function(t,e,r){var i=this._realizeGroupTransformOnObject(t),n=this.callSuper("_toObject",t,e,r);return this._unwindGroupTransformOnObject(t,i),n},_realizeGroupTransformOnObject:function(t){if(t.group&&"activeSelection"===t.group.type&&this._activeObject===t.group){var e=["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"],r={};return e.forEach(function(e){r[e]=t[e]}),this._activeObject.realizeTransform(t),r}return null},_unwindGroupTransformOnObject:function(t,e){e&&t.set(e)},_setSVGObject:function(t,e,r){var i=this._realizeGroupTransformOnObject(e);this.callSuper("_setSVGObject",t,e,r),this._unwindGroupTransformOnObject(e,i)}});for(var s in fabric.StaticCanvas)"prototype"!==s&&(fabric.Canvas[s]=fabric.StaticCanvas[s]);fabric.isTouchSupported&&(fabric.Canvas.prototype._setCursorFromEvent=function(){})}(),function(){function t(t,e){return"which"in t?t.which===e:t.button===e-1}var e={mt:0,tr:1,mr:2,br:3,mb:4,bl:5,ml:6,tl:7},r=fabric.util.addListener,i=fabric.util.removeListener,n=3,o=2,a=1;fabric.util.object.extend(fabric.Canvas.prototype,{cursorMap:["n-resize","ne-resize","e-resize","se-resize","s-resize","sw-resize","w-resize","nw-resize"],_initEventListeners:function(){this.removeListeners(),this._bindEvents(),r(fabric.window,"resize",this._onResize),r(this.upperCanvasEl,"mousedown",this._onMouseDown),r(this.upperCanvasEl,"dblclick",this._onDoubleClick),r(this.upperCanvasEl,"mousemove",this._onMouseMove),r(this.upperCanvasEl,"mouseout",this._onMouseOut),r(this.upperCanvasEl,"mouseenter",this._onMouseEnter),r(this.upperCanvasEl,"wheel",this._onMouseWheel),r(this.upperCanvasEl,"contextmenu",this._onContextMenu),r(this.upperCanvasEl,"touchstart",this._onMouseDown,{passive:!1}),r(this.upperCanvasEl,"touchmove",this._onMouseMove,{passive:!1}),"undefined"!=typeof eventjs&&"add"in eventjs&&(eventjs.add(this.upperCanvasEl,"gesture",this._onGesture),eventjs.add(this.upperCanvasEl,"drag",this._onDrag),eventjs.add(this.upperCanvasEl,"orientation",this._onOrientationChange),eventjs.add(this.upperCanvasEl,"shake",this._onShake),eventjs.add(this.upperCanvasEl,"longpress",this._onLongPress))},_bindEvents:function(){this.eventsBinded||(this._onMouseDown=this._onMouseDown.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this.eventsBinded=!0)},removeListeners:function(){i(fabric.window,"resize",this._onResize),i(this.upperCanvasEl,"mousedown",this._onMouseDown),i(this.upperCanvasEl,"mousemove",this._onMouseMove),i(this.upperCanvasEl,"mouseout",this._onMouseOut),i(this.upperCanvasEl,"mouseenter",this._onMouseEnter),i(this.upperCanvasEl,"wheel",this._onMouseWheel),i(this.upperCanvasEl,"contextmenu",this._onContextMenu),i(this.upperCanvasEl,"doubleclick",this._onDoubleClick),i(this.upperCanvasEl,"touchstart",this._onMouseDown),i(this.upperCanvasEl,"touchmove",this._onMouseMove),"undefined"!=typeof eventjs&&"remove"in eventjs&&(eventjs.remove(this.upperCanvasEl,"gesture",this._onGesture),eventjs.remove(this.upperCanvasEl,"drag",this._onDrag),eventjs.remove(this.upperCanvasEl,"orientation",this._onOrientationChange),eventjs.remove(this.upperCanvasEl,"shake",this._onShake),eventjs.remove(this.upperCanvasEl,"longpress",this._onLongPress))},_onGesture:function(t,e){this.__onTransformGesture&&this.__onTransformGesture(t,e)},_onDrag:function(t,e){this.__onDrag&&this.__onDrag(t,e)},_onMouseWheel:function(t){this.__onMouseWheel(t)},_onMouseOut:function(t){var e=this._hoveredTarget;this.fire("mouse:out",{target:e,e:t}),this._hoveredTarget=null,e&&e.fire("mouseout",{e:t}),this._iTextInstances&&this._iTextInstances.forEach(function(t){t.isEditing&&t.hiddenTextarea.focus()})},_onMouseEnter:function(t){this.findTarget(t)||(this.fire("mouse:over",{target:null,e:t}),this._hoveredTarget=null)},_onOrientationChange:function(t,e){this.__onOrientationChange&&this.__onOrientationChange(t,e)},_onShake:function(t,e){this.__onShake&&this.__onShake(t,e)},_onLongPress:function(t,e){this.__onLongPress&&this.__onLongPress(t,e)},_onContextMenu:function(t){return this.stopContextMenu&&(t.stopPropagation(),t.preventDefault()),!1},_onDoubleClick:function(t){var e;this._handleEvent(t,"dblclick",void 0)},_onMouseDown:function(t){this.__onMouseDown(t),r(fabric.document,"touchend",this._onMouseUp,{passive:!1}),r(fabric.document,"touchmove",this._onMouseMove,{passive:!1}),i(this.upperCanvasEl,"mousemove",this._onMouseMove),i(this.upperCanvasEl,"touchmove",this._onMouseMove),"touchstart"===t.type?i(this.upperCanvasEl,"mousedown",this._onMouseDown):(r(fabric.document,"mouseup",this._onMouseUp),r(fabric.document,"mousemove",this._onMouseMove))},_onMouseUp:function(t){if(this.__onMouseUp(t),i(fabric.document,"mouseup",this._onMouseUp),i(fabric.document,"touchend",this._onMouseUp),i(fabric.document,"mousemove",this._onMouseMove),i(fabric.document,"touchmove",this._onMouseMove),r(this.upperCanvasEl,"mousemove",this._onMouseMove),r(this.upperCanvasEl,"touchmove",this._onMouseMove,{passive:!1}),"touchend"===t.type){var e=this;setTimeout(function(){r(e.upperCanvasEl,"mousedown",e._onMouseDown)},400)}},_onMouseMove:function(t){!this.allowTouchScrolling&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)},_onResize:function(){this.calcOffset()},_shouldRender:function(t,e){var r=this._activeObject;return(!r||!r.isEditing||t!==r)&&!!(t&&(t.isMoving||t!==r)||!t&&r||!t&&!r&&!this._groupSelector||e&&this._previousPointer&&this.selection&&(e.x!==this._previousPointer.x||e.y!==this._previousPointer.y))},__onMouseUp:function(e){var r;if(t(e,3))return void(this.fireRightClick&&this._handleEvent(e,"up",r,3));if(t(e,2))return void(this.fireMiddleClick&&this._handleEvent(e,"up",r,2));if(this.isDrawingMode&&this._isCurrentlyDrawing)return void this._onMouseUpInDrawingMode(e);var i=!0,n=this._currentTransform,o=this._groupSelector,a=!o||0===o.left&&0===o.top;n&&(this._finalizeCurrentTransform(e),i=!n.actionPerformed),r=i?this.findTarget(e,!0):n.target;var s=this._shouldRender(r,this.getPointer(e));r||!a?this._maybeGroupObjects(e):(this._groupSelector=null,this._currentTransform=null),r&&(r.isMoving=!1),this._setCursorFromEvent(e,r),this._handleEvent(e,"up",r||null,1,a),r&&(r.__corner=0),s&&this.requestRenderAll()},_handleEvent:function(t,e,r,i,n){var o=void 0===r?this.findTarget(t):r,a=this.targets||[],s={e:t,target:o,subTargets:a,button:i||1,isClick:n||!1};this.fire("mouse:"+e,s),o&&o.fire("mouse"+e,s);for(var c=0;c<a.length;c++)a[c].fire("mouse"+e,s)},_finalizeCurrentTransform:function(t){var e=this._currentTransform,r=e.target;r._scaling&&(r._scaling=!1),r.setCoords(),this._restoreOriginXY(r),(e.actionPerformed||this.stateful&&r.hasStateChanged())&&(this.fire("object:modified",{target:r,e:t}),r.fire("modified",{e:t}))},_restoreOriginXY:function(t){if(this._previousOriginX&&this._previousOriginY){var e=t.translateToOriginPoint(t.getCenterPoint(),this._previousOriginX,this._previousOriginY);t.originX=this._previousOriginX,t.originY=this._previousOriginY,t.left=e.x,t.top=e.y,this._previousOriginX=null,this._previousOriginY=null}},_onMouseDownInDrawingMode:function(t){this._isCurrentlyDrawing=!0,this.discardActiveObject(t).requestRenderAll(),this.clipTo&&fabric.util.clipContext(this,this.contextTop);var e=this.getPointer(t);this.freeDrawingBrush.onMouseDown(e),this._handleEvent(t,"down")},_onMouseMoveInDrawingMode:function(t){if(this._isCurrentlyDrawing){var e=this.getPointer(t);this.freeDrawingBrush.onMouseMove(e)}this.setCursor(this.freeDrawingCursor),this._handleEvent(t,"move")},_onMouseUpInDrawingMode:function(t){this._isCurrentlyDrawing=!1,this.clipTo&&this.contextTop.restore(),this.freeDrawingBrush.onMouseUp(),this._handleEvent(t,"up")},__onMouseDown:function(e){var r=this.findTarget(e);if(t(e,3))return void(this.fireRightClick&&this._handleEvent(e,"down",r||null,3));if(t(e,2))return void(this.fireMiddleClick&&this._handleEvent(e,"down",r||null,2));if(this.isDrawingMode)return void this._onMouseDownInDrawingMode(e);if(!this._currentTransform){var i=this.getPointer(e,!0);this._previousPointer=i;var n=this._shouldRender(r,i),o=this._shouldGroup(e,r);this._shouldClearSelection(e,r)?this.discardActiveObject(e):o&&(this._handleGrouping(e,r),r=this._activeObject),!this.selection||r&&(r.selectable||r.isEditing)||(this._groupSelector={ex:i.x,ey:i.y,top:0,left:0}),r&&(!r.selectable||!r.__corner&&o||(this._beforeTransform(e,r),this._setupCurrentTransform(e,r)),r.selectable?this.setActiveObject(r,e):this.discardActiveObject()),this._handleEvent(e,"down",r||null),n&&this.requestRenderAll()}},_beforeTransform:function(t,e){this.stateful&&e.saveState(),e._findTargetCorner(this.getPointer(t))&&this.onBeforeScaleRotate(e)},_setOriginToCenter:function(t){this._previousOriginX=this._currentTransform.target.originX,this._previousOriginY=this._currentTransform.target.originY;var e=t.getCenterPoint();t.originX="center",t.originY="center",t.left=e.x,t.top=e.y,this._currentTransform.left=t.left,this._currentTransform.top=t.top},_setCenterToOrigin:function(t){var e=t.translateToOriginPoint(t.getCenterPoint(),this._previousOriginX,this._previousOriginY);t.originX=this._previousOriginX,t.originY=this._previousOriginY,t.left=e.x,t.top=e.y,this._previousOriginX=null,this._previousOriginY=null},__onMouseMove:function(t){var e,r;if(this.isDrawingMode)return void this._onMouseMoveInDrawingMode(t);if(!(void 0!==t.touches&&t.touches.length>1)){var i=this._groupSelector;i?(r=this.getPointer(t,!0),i.left=r.x-i.ex,i.top=r.y-i.ey,this.renderTop()):this._currentTransform?this._transformObject(t):(e=this.findTarget(t),this._setCursorFromEvent(t,e)),this._handleEvent(t,"move",e||null)}},__onMouseWheel:function(t){this._handleEvent(t,"wheel")},_transformObject:function(t){var e=this.getPointer(t),r=this._currentTransform;r.reset=!1,r.target.isMoving=!0,r.shiftKey=t.shiftKey,r.altKey=t[this.centeredKey],this._beforeScaleTransform(t,r),this._performTransformAction(t,r,e),r.actionPerformed&&this.requestRenderAll()},_performTransformAction:function(t,e,r){var i=r.x,n=r.y,o=e.target,a=e.action,s=!1;"rotate"===a?(s=this._rotateObject(i,n))&&this._fire("rotating",o,t):"scale"===a?(s=this._onScale(t,e,i,n))&&this._fire("scaling",o,t):"scaleX"===a?(s=this._scaleObject(i,n,"x"))&&this._fire("scaling",o,t):"scaleY"===a?(s=this._scaleObject(i,n,"y"))&&this._fire("scaling",o,t):"skewX"===a?(s=this._skewObject(i,n,"x"))&&this._fire("skewing",o,t):"skewY"===a?(s=this._skewObject(i,n,"y"))&&this._fire("skewing",o,t):(s=this._translateObject(i,n))&&(this._fire("moving",o,t),this.setCursor(o.moveCursor||this.moveCursor)),e.actionPerformed=e.actionPerformed||s},_fire:function(t,e,r){this.fire("object:"+t,{target:e,e:r}),e.fire(t,{e:r})},_beforeScaleTransform:function(t,e){if("scale"===e.action||"scaleX"===e.action||"scaleY"===e.action){var r=this._shouldCenterTransform(e.target);(r&&("center"!==e.originX||"center"!==e.originY)||!r&&"center"===e.originX&&"center"===e.originY)&&(this._resetCurrentTransform(),e.reset=!0)}},_onScale:function(t,e,r,i){return this._isUniscalePossible(t,e.target)?(e.currentAction="scale",this._scaleObject(r,i)):(e.reset||"scale"!==e.currentAction||this._resetCurrentTransform(),e.currentAction="scaleEqually",this._scaleObject(r,i,"equally"))},_isUniscalePossible:function(t,e){return(t[this.uniScaleKey]||this.uniScaleTransform)&&!e.get("lockUniScaling")},_setCursorFromEvent:function(t,e){if(!e)return this.setCursor(this.defaultCursor),!1;var r=e.hoverCursor||this.hoverCursor,i=this._activeObject&&"activeSelection"===this._activeObject.type?this._activeObject:null,n=(!i||!i.contains(e))&&e._findTargetCorner(this.getPointer(t,!0));n?this.setCursor(this.getCornerCursor(n,e,t)):this.setCursor(r)},getCornerCursor:function(t,r,i){return this.actionIsDisabled(t,r,i)?this.notAllowedCursor:t in e?this._getRotatedCornerCursor(t,r,i):"mtr"===t&&r.hasRotatingPoint?this.rotationCursor:this.defaultCursor},actionIsDisabled:function(t,e,r){return"mt"===t||"mb"===t?r[this.altActionKey]?e.lockSkewingX:e.lockScalingY:"ml"===t||"mr"===t?r[this.altActionKey]?e.lockSkewingY:e.lockScalingX:"mtr"===t?e.lockRotation:this._isUniscalePossible(r,e)?e.lockScalingX&&e.lockScalingY:e.lockScalingX||e.lockScalingY},_getRotatedCornerCursor:function(t,r,i){var n=Math.round(r.angle%360/45);return n<0&&(n+=8),n+=e[t],i[this.altActionKey]&&e[t]%2==0&&(n+=2),n%=8,this.cursorMap[n]}})}(),function(){var t=Math.min,e=Math.max;fabric.util.object.extend(fabric.Canvas.prototype,{_shouldGroup:function(t,e){var r=this._activeObject;return t[this.selectionKey]&&e&&e.selectable&&this.selection&&(r!==e||"activeSelection"===r.type)},_handleGrouping:function(t,e){var r=this._activeObject;0===r.__corner&&(e!==r||(e=this.findTarget(t,!0)))&&(r&&"activeSelection"===r.type?this._updateActiveSelection(e,t):this._createActiveSelection(e,t))},_updateActiveSelection:function(t,e){var r=this._activeObject;if(r.contains(t)){if(r.removeWithUpdate(t),1===r.size())return void this.setActiveObject(r.item(0),e)}else r.addWithUpdate(t);this.fire("selection:created",{target:r,e:e})},_createActiveSelection:function(t,e){var r=this._createGroup(t);this.setActiveObject(r,e),this.fire("selection:created",{target:r,e:e})},_createGroup:function(t){var e=this.getObjects(),r=e.indexOf(this._activeObject)<e.indexOf(t),i=r?[this._activeObject,t]:[t,this._activeObject];return this._activeObject.isEditing&&this._activeObject.exitEditing(),new fabric.ActiveSelection(i,{canvas:this})},_groupSelectedObjects:function(t){var e=this._collectObjects();1===e.length?this.setActiveObject(e[0],t):e.length>1&&(e=new fabric.ActiveSelection(e.reverse(),{canvas:this}),this.setActiveObject(e,t),this.fire("selection:created",{target:e,e:t}),this.requestRenderAll())},_collectObjects:function(){for(var r=[],i,n=this._groupSelector.ex,o=this._groupSelector.ey,a=n+this._groupSelector.left,s=o+this._groupSelector.top,c=new fabric.Point(t(n,a),t(o,s)),l=new fabric.Point(e(n,a),e(o,s)),h=n===a&&o===s,u=this._objects.length;u--&&!((i=this._objects[u])&&i.selectable&&i.visible&&(i.intersectsWithRect(c,l)||i.isContainedWithinRect(c,l)||i.containsPoint(c)||i.containsPoint(l))&&(r.push(i),h)););return r},_maybeGroupObjects:function(t){this.selection&&this._groupSelector&&this._groupSelectedObjects(t),this.setCursor(this.defaultCursor),this._groupSelector=null,this._currentTransform=null}})}(),function(){var t=fabric.StaticCanvas.supports("toDataURLWithQuality");fabric.util.object.extend(fabric.StaticCanvas.prototype,{toDataURL:function(t){t||(t={});var e=t.format||"png",r=t.quality||1,i=t.multiplier||1,n={left:t.left||0,top:t.top||0,width:t.width||0,height:t.height||0};return this.__toDataURLWithMultiplier(e,r,n,i)},__toDataURLWithMultiplier:function(t,e,r,i){var n=this.width,o=this.height,a=(r.width||this.width)*i,s=(r.height||this.height)*i,c=this.getZoom(),l=c*i,h=this.viewportTransform,u=(h[4]-r.left)*i,f=(h[5]-r.top)*i,d=[l,0,0,l,u,f],p=this.interactive;this.viewportTransform=d,this.interactive&&(this.interactive=!1),n!==a||o!==s?this.setDimensions({width:a,height:s}):this.renderAll();var g=this.__toDataURL(t,e,r);return p&&(this.interactive=p),this.viewportTransform=h,this.setDimensions({width:n,height:o}),g},__toDataURL:function(e,r){var i=this.contextContainer.canvas;return"jpg"===e&&(e="jpeg"),t?i.toDataURL("image/"+e,r):i.toDataURL("image/"+e)},toDataURLWithMultiplier:function(t,e,r){return this.toDataURL({format:t,multiplier:e,quality:r})}})}(),fabric.util.object.extend(fabric.StaticCanvas.prototype,{loadFromDatalessJSON:function(t,e,r){return this.loadFromJSON(t,e,r)},loadFromJSON:function(t,e,r){if(t){var i="string"==typeof t?JSON.parse(t):fabric.util.object.clone(t),n=this,o=this.renderOnAddRemove;return this.renderOnAddRemove=!1,this._enlivenObjects(i.objects,function(t){n.clear(),n._setBgOverlay(i,function(){t.forEach(function(t,e){n.insertAt(t,e)}),n.renderOnAddRemove=o,delete i.objects,delete i.backgroundImage,delete i.overlayImage,delete i.background,delete i.overlay,n._setOptions(i),n.renderAll(),e&&e()})},r),this}},_setBgOverlay:function(t,e){var r={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(!(t.backgroundImage||t.overlayImage||t.background||t.overlay))return void(e&&e());var i=function(){r.backgroundImage&&r.overlayImage&&r.backgroundColor&&r.overlayColor&&e&&e()};this.__setBgOverlay("backgroundImage",t.backgroundImage,r,i),this.__setBgOverlay("overlayImage",t.overlayImage,r,i),this.__setBgOverlay("backgroundColor",t.background,r,i),this.__setBgOverlay("overlayColor",t.overlay,r,i)},__setBgOverlay:function(t,e,r,i){var n=this;if(!e)return r[t]=!0,void(i&&i());"backgroundImage"===t||"overlayImage"===t?fabric.util.enlivenObjects([e],function(e){n[t]=e[0],r[t]=!0,i&&i()}):this["set"+fabric.util.string.capitalize(t,!0)](e,function(){r[t]=!0,i&&i()})},_enlivenObjects:function(t,e,r){if(!t||0===t.length)return void(e&&e([]));fabric.util.enlivenObjects(t,function(t){e&&e(t)},null,r)},_toDataURL:function(t,e){this.clone(function(r){e(r.toDataURL(t))})},_toDataURLWithMultiplier:function(t,e,r){this.clone(function(i){r(i.toDataURLWithMultiplier(t,e))})},clone:function(t,e){var r=JSON.stringify(this.toJSON(e));this.cloneWithoutData(function(e){e.loadFromJSON(r,function(){t&&t(e)})})},cloneWithoutData:function(t){var e=fabric.document.createElement("canvas");e.width=this.width,e.height=this.height;var r=new fabric.Canvas(e);r.clipTo=this.clipTo,this.backgroundImage?(r.setBackgroundImage(this.backgroundImage.src,function(){r.renderAll(),t&&t(r)}),r.backgroundImageOpacity=this.backgroundImageOpacity,r.backgroundImageStretch=this.backgroundImageStretch):t&&t(r)}}),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.util.object.extend,i=e.util.object.clone,n=e.util.toFixed,o=e.util.string.capitalize,a=e.util.degreesToRadians,s=e.StaticCanvas.supports("setLineDash"),c=!e.isLikelyNode,l=2;e.Object||(e.Object=e.util.createClass(e.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgba(102,153,255,0.75)",borderDashArray:null,cornerColor:"rgba(102,153,255,0.5)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:10,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,transformMatrix:null,minScaleLimit:.01,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,hasRotatingPoint:!0,rotatingPointOffset:40,perPixelTargetFind:!1,includeDefaultValues:!0,clipTo:null,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockUniScaling:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:c,statefullCache:!1,noScaleCache:!0,dirty:!0,stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow clipTo visible backgroundColor skewX skewY fillRule".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height strokeLineCap strokeLineJoin strokeMiterLimit backgroundColor".split(" "),initialize:function(t){(t=t||{})&&this.setOptions(t)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=e.document.createElement("canvas"),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas()},_limitCacheSize:function(t){var r=e.perfLimitSizeTotal,i=e.cacheSideLimit,n=t.width,o=t.height,a=n/o,s=e.util.limitDimsByArea(a,r,i),c=e.util.capValue,l=e.maxCacheSideLimit,h=e.minCacheSideLimit,u=c(h,s.x,l),f=c(h,s.y,l);return n>u?(t.zoomX/=n/u,t.width=u):n<h&&(t.width=h),o>f?(t.zoomY/=o/f,t.height=f):o<h&&(t.height=h),t},_getCacheCanvasDimensions:function(){var t=this.canvas&&this.canvas.getZoom()||1,r=this.getObjectScaling(),i=this._getNonTransformedDimensions(),n=this.canvas&&this.canvas._isRetinaScaling()?e.devicePixelRatio:1,o=r.scaleX*t*n,a=r.scaleY*t*n;return{width:i.x*o+2,height:i.y*a+2,zoomX:o,zoomY:a}},_updateCacheCanvas:function(){if(this.noScaleCache&&this.canvas&&this.canvas._currentTransform){var t=this.canvas._currentTransform.action;if(t.slice&&"scale"===t.slice(0,5))return!1}var r=this._limitCacheSize(this._getCacheCanvasDimensions()),i=e.minCacheSideLimit,n=r.width,o=r.height,a=r.zoomX,s=r.zoomY,c=n!==this.cacheWidth||o!==this.cacheHeight,l=this.zoomX!==a||this.zoomY!==s,h=c||l,u=0,f=0,d=!1;if(c){var p=this._cacheCanvas.width,g=this._cacheCanvas.height,v=n>p||o>g,m=(n<.9*p||o<.9*g)&&p>i&&g>i;d=v||m,v&&(u=.1*n&-2,f=.1*o&-2)}return!!h&&(d?(this._cacheCanvas.width=Math.max(Math.ceil(n)+u,i),this._cacheCanvas.height=Math.max(Math.ceil(o)+f,i),this.cacheTranslationX=(n+u)/2,this.cacheTranslationY=(o+f)/2):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,this._cacheCanvas.width,this._cacheCanvas.height)),this.cacheWidth=n,this.cacheHeight=o,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(a,s),this.zoomX=a,this.zoomY=s,!0)},setOptions:function(t){this._setOptions(t),this._initGradient(t.fill,"fill"),this._initGradient(t.stroke,"stroke"),this._initClipping(t),this._initPattern(t.fill,"fill"),this._initPattern(t.stroke,"stroke")},transform:function(t,e){this.group&&!this.group._transformDone&&this.group.transform(t);var r=e?this._getLeftTopCoords():this.getCenterPoint();t.translate(r.x,r.y),this.angle&&t.rotate(a(this.angle)),t.scale(this.scaleX*(this.flipX?-1:1),this.scaleY*(this.flipY?-1:1)),this.skewX&&t.transform(1,0,Math.tan(a(this.skewX)),1,0,0),this.skewY&&t.transform(1,Math.tan(a(this.skewY)),0,1,0,0)},toObject:function(t){var r=e.Object.NUM_FRACTION_DIGITS,i={type:this.type,originX:this.originX,originY:this.originY,left:n(this.left,r),top:n(this.top,r),width:n(this.width,r),height:n(this.height,r),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:n(this.strokeWidth,r),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeLineJoin:this.strokeLineJoin,strokeMiterLimit:n(this.strokeMiterLimit,r),scaleX:n(this.scaleX,r),scaleY:n(this.scaleY,r),angle:n(this.angle,r),flipX:this.flipX,flipY:this.flipY,opacity:n(this.opacity,r),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,clipTo:this.clipTo&&String(this.clipTo),backgroundColor:this.backgroundColor,fillRule:this.fillRule,globalCompositeOperation:this.globalCompositeOperation,transformMatrix:this.transformMatrix?this.transformMatrix.concat():null,skewX:n(this.skewX,r),skewY:n(this.skewY,r)};return e.util.populateWithProperties(this,i,t),this.includeDefaultValues||(i=this._removeDefaultValues(i)),i},toDatalessObject:function(t){return this.toObject(t)},_removeDefaultValues:function(t){var r=e.util.getKlass(t.type).prototype;return r.stateProperties.forEach(function(e){t[e]===r[e]&&delete t[e],"[object Array]"===Object.prototype.toString.call(t[e])&&"[object Array]"===Object.prototype.toString.call(r[e])&&0===t[e].length&&0===r[e].length&&delete t[e]}),t},toString:function(){return"#<fabric."+o(this.type)+">"},getObjectScaling:function(){var t=this.scaleX,e=this.scaleY;if(this.group){var r=this.group.getObjectScaling();t*=r.scaleX,e*=r.scaleY}return{scaleX:t,scaleY:e}},getObjectOpacity:function(){var t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t},_set:function(t,r){return("scaleX"===t||"scaleY"===t)&&(r=this._constrainScale(r)),"scaleX"===t&&r<0?(this.flipX=!this.flipX,r*=-1):"scaleY"===t&&r<0?(this.flipY=!this.flipY,r*=-1):"shadow"!==t||!r||r instanceof e.Shadow?"dirty"===t&&this.group&&this.group.set("dirty",r):r=new e.Shadow(r),this[t]=r,this.cacheProperties.indexOf(t)>-1&&(this.group&&this.group.set("dirty",!0),this.dirty=!0),this.group&&this.stateProperties.indexOf(t)>-1&&this.group.isOnACache()&&this.group.set("dirty",!0),"width"!==t&&"height"!==t||(this.minScaleLimit=Math.min(.1,1/Math.max(this.width,this.height))),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:e.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||0===this.width&&0===this.height||!this.visible},render:function(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t,this),this.transformMatrix&&t.transform.apply(t,this.transformMatrix),this.clipTo&&e.util.clipContext(this,t),this.shouldCache()?(this._cacheCanvas||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext),this.dirty=!1),this.drawCacheOnCanvas(t)):(this.dirty=!1,this.drawObject(t),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),this.clipTo&&t.restore(),t.restore())},needsItsOwnCache:function(){return!1},shouldCache:function(){return this.ownCaching=this.objectCaching&&(!this.group||this.needsItsOwnCache()||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawObject:function(t){this._renderBackground(t),this._setStrokeStyles(t,this),this._setFillStyles(t,this),this._render(t)},drawCacheOnCanvas:function(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(t){if(this.isNotVisible())return!1;if(this._cacheCanvas&&!t&&this._updateCacheCanvas())return!0;if(this.dirty||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&!t){var e=this.cacheWidth/this.zoomX,r=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-e/2,-r/2,e,r)}return!0}return!1},_renderBackground:function(t){if(this.backgroundColor){var e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}},_setOpacity:function(t){this.group&&!this.group.transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity},_setStrokeStyles:function(t,e){e.stroke&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,t.strokeStyle=e.stroke.toLive?e.stroke.toLive(t,this):e.stroke)},_setFillStyles:function(t,e){e.fill&&(t.fillStyle=e.fill.toLive?e.fill.toLive(t,this):e.fill)},_setLineDash:function(t,e,r){e&&(1&e.length&&e.push.apply(e,e),s?t.setLineDash(e):r&&r(t))},_renderControls:function(t,r){var i=this.getViewportTransform(),n=this.calcTransformMatrix(),o,s,c;r=r||{},s=void 0!==r.hasBorders?r.hasBorders:this.hasBorders,c=void 0!==r.hasControls?r.hasControls:this.hasControls,n=e.util.multiplyTransformMatrices(i,n),o=e.util.qrDecompose(n),t.save(),t.translate(o.translateX,o.translateY),t.lineWidth=1*this.borderScaleFactor,this.group||(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),r.forActiveSelection?(t.rotate(a(o.angle)),s&&this.drawBordersInGroup(t,o,r)):(t.rotate(a(this.angle)),s&&this.drawBorders(t,r)),c&&this.drawControls(t,r),t.restore()},_setShadow:function(t){if(this.shadow){var r=this.canvas&&this.canvas.viewportTransform[0]||1,i=this.canvas&&this.canvas.viewportTransform[3]||1,n=this.getObjectScaling();this.canvas&&this.canvas._isRetinaScaling()&&(r*=e.devicePixelRatio,i*=e.devicePixelRatio),t.shadowColor=this.shadow.color,t.shadowBlur=this.shadow.blur*(r+i)*(n.scaleX+n.scaleY)/4,t.shadowOffsetX=this.shadow.offsetX*r*n.scaleX,t.shadowOffsetY=this.shadow.offsetY*i*n.scaleY}},_removeShadow:function(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)},_applyPatternGradientTransform:function(t,e){if(e.toLive){var r=e.gradientTransform||e.patternTransform,i=-this.width/2+e.offsetX||0,n=-this.height/2+e.offsetY||0;t.translate(i,n),r&&t.transform.apply(t,r)}},_renderFill:function(t){this.fill&&(t.save(),this._applyPatternGradientTransform(t,this.fill),"evenodd"===this.fillRule?t.fill("evenodd"):t.fill(),t.restore())},_renderStroke:function(t){this.stroke&&0!==this.strokeWidth&&(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this._setLineDash(t,this.strokeDashArray,this._renderDashedStroke),this._applyPatternGradientTransform(t,this.stroke),t.stroke(),t.restore())},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_removeTransformMatrix:function(){var t=this._findCenterFromElement();if(this.transformMatrix){var r=e.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",r.scaleX),this.set("scaleY",r.scaleY),this.angle=r.angle,this.skewX=r.skewX,this.skewY=0,t=e.util.transformPoint(t,this.transformMatrix)}this.transformMatrix=null,this.setPositionByOrigin(t,"center","center")},clone:function(t,r){var i=this.toObject(r);this.constructor.fromObject?this.constructor.fromObject(i,t):e.Object._fromObject("Object",i,t)},cloneAsImage:function(t,r){var i=this.toDataURL(r);return e.util.loadImage(i,function(r){t&&t(new e.Image(r))}),this},toDataURL:function(t){t||(t={});var r=e.util.createCanvasElement(),i=this.getBoundingRect();r.width=i.width,r.height=i.height,e.util.wrapElement(r,"div");var n=new e.StaticCanvas(r,{enableRetinaScaling:t.enableRetinaScaling});"jpg"===t.format&&(t.format="jpeg"),"jpeg"===t.format&&(n.backgroundColor="#fff");var o={active:this.active,left:this.left,top:this.top};this.set("active",!1),this.setPositionByOrigin(new e.Point(n.width/2,n.height/2),"center","center");var a=this.canvas;n.add(this);var s=n.toDataURL(t);return this.set(o).setCoords(),this.canvas=a,n.dispose(),n=null,s},isType:function(t){return this.type===t},complexity:function(){return 1},toJSON:function(t){return this.toObject(t)},setGradient:function(t,r){r||(r={});var i={colorStops:[]};return i.type=r.type||(r.r1||r.r2?"radial":"linear"),i.coords={x1:r.x1,y1:r.y1,x2:r.x2,y2:r.y2},(r.r1||r.r2)&&(i.coords.r1=r.r1,i.coords.r2=r.r2),i.gradientTransform=r.gradientTransform,e.Gradient.prototype.addColorStop.call(i,r.colorStops),this.set(t,e.Gradient.forObject(this,i))},setPatternFill:function(t){return this.set("fill",new e.Pattern(t))},setShadow:function(t){return this.set("shadow",t?new e.Shadow(t):null)},setColor:function(t){return this.set("fill",t),this},setAngle:function(t){var e=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return e&&this._setOriginToCenter(),this.set("angle",t),e&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},remove:function(){return this.canvas&&this.canvas.remove(this),this},getLocalPointer:function(t,r){r=r||this.canvas.getPointer(t);var i=new e.Point(r.x,r.y),n=this._getLeftTopCoords();return this.angle&&(i=e.util.rotatePoint(i,n,a(-this.angle))),{x:i.x-n.x,y:i.y-n.y}},_setupCompositeOperation:function(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)}}),e.util.createAccessors&&e.util.createAccessors(e.Object),e.Object.prototype.rotate=e.Object.prototype.setAngle,r(e.Object.prototype,e.Observable),e.Object.NUM_FRACTION_DIGITS=2,e.Object._fromObject=function(t,r,n,o){var a=e[t];r=i(r,!0),e.util.enlivenPatterns([r.fill,r.stroke],function(t){void 0!==t[0]&&(r.fill=t[0]),void 0!==t[1]&&(r.stroke=t[1]);var e=o?new a(r[o],r):new a(r);n&&n(e)})},e.Object.__uid=0)}(exports),function(){var t=fabric.util.degreesToRadians,e={left:-.5,center:0,right:.5},r={top:-.5,center:0,bottom:.5};fabric.util.object.extend(fabric.Object.prototype,{translateToGivenOrigin:function(t,i,n,o,a){var s=t.x,c=t.y,l,h,u;return"string"==typeof i?i=e[i]:i-=.5,"string"==typeof o?o=e[o]:o-=.5,l=o-i,"string"==typeof n?n=r[n]:n-=.5,"string"==typeof a?a=r[a]:a-=.5,h=a-n,(l||h)&&(u=this._getTransformedDimensions(),s=t.x+l*u.x,c=t.y+h*u.y),new fabric.Point(s,c)},translateToCenterPoint:function(e,r,i){var n=this.translateToGivenOrigin(e,r,i,"center","center");return this.angle?fabric.util.rotatePoint(n,e,t(this.angle)):n},translateToOriginPoint:function(e,r,i){var n=this.translateToGivenOrigin(e,"center","center",r,i);return this.angle?fabric.util.rotatePoint(n,e,t(this.angle)):n},getCenterPoint:function(){var t=new fabric.Point(this.left,this.top);return this.translateToCenterPoint(t,this.originX,this.originY)},getPointByOrigin:function(t,e){var r=this.getCenterPoint();return this.translateToOriginPoint(r,t,e)},toLocalPoint:function(e,r,i){var n=this.getCenterPoint(),o,a;return o=void 0!==r&&void 0!==i?this.translateToGivenOrigin(n,"center","center",r,i):new fabric.Point(this.left,this.top),a=new fabric.Point(e.x,e.y),this.angle&&(a=fabric.util.rotatePoint(a,n,-t(this.angle))),a.subtractEquals(o)},setPositionByOrigin:function(t,e,r){var i=this.translateToCenterPoint(t,e,r),n=this.translateToOriginPoint(i,this.originX,this.originY);this.set("left",n.x),this.set("top",n.y)},adjustPosition:function(r){var i=t(this.angle),n=this.getScaledWidth(),o=Math.cos(i)*n,a=Math.sin(i)*n,s,c;s="string"==typeof this.originX?e[this.originX]:this.originX-.5,c="string"==typeof r?e[r]:r-.5,this.left+=o*(c-s),this.top+=a*(c-s),this.setCoords(),this.originX=r},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var t=this.getCenterPoint();this.originX="center",this.originY="center",this.left=t.x,this.top=t.y},_resetOrigin:function(){var t=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=t.x,this.top=t.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")},onDeselect:function(){}})}(),function(){function t(t){return[new fabric.Point(t.tl.x,t.tl.y),new fabric.Point(t.tr.x,t.tr.y),new fabric.Point(t.br.x,t.br.y),new fabric.Point(t.bl.x,t.bl.y)]}var e=fabric.util.degreesToRadians,r=fabric.util.multiplyTransformMatrices;fabric.util.object.extend(fabric.Object.prototype,{oCoords:null,aCoords:null,getCoords:function(e,r){this.oCoords||this.setCoords();var i=e?this.aCoords:this.oCoords;return t(r?this.calcCoords(e):i)},intersectsWithRect:function(t,e,r,i){var n=this.getCoords(r,i);return"Intersection"===fabric.Intersection.intersectPolygonRectangle(n,t,e).status},intersectsWithObject:function(t,e,r){return"Intersection"===fabric.Intersection.intersectPolygonPolygon(this.getCoords(e,r),t.getCoords(e,r)).status||t.isContainedWithinObject(this,e,r)||this.isContainedWithinObject(t,e,r)},isContainedWithinObject:function(t,e,r){for(var i=this.getCoords(e,r),n=0,o=t._getImageLines(r?t.calcCoords(e):e?t.aCoords:t.oCoords);n<4;n++)if(!t.containsPoint(i[n],o))return!1;return!0},isContainedWithinRect:function(t,e,r,i){var n=this.getBoundingRect(r,i);return n.left>=t.x&&n.left+n.width<=e.x&&n.top>=t.y&&n.top+n.height<=e.y},containsPoint:function(t,e,r,i){var e=e||this._getImageLines(i?this.calcCoords(r):r?this.aCoords:this.oCoords),n=this._findCrossPoints(t,e);return 0!==n&&n%2==1},isOnScreen:function(t){if(!this.canvas)return!1;for(var e=this.canvas.vptCoords.tl,r=this.canvas.vptCoords.br,i=this.getCoords(!0,t),n,o=0;o<4;o++)if(n=i[o],n.x<=r.x&&n.x>=e.x&&n.y<=r.y&&n.y>=e.y)return!0;if(this.intersectsWithRect(e,r,!0))return!0;var a={x:(e.x+r.x)/2,y:(e.y+r.y)/2};return!!this.containsPoint(a,null,!0)},_getImageLines:function(t){return{topline:{o:t.tl,d:t.tr},rightline:{o:t.tr,d:t.br},bottomline:{o:t.br,d:t.bl},leftline:{o:t.bl,d:t.tl}}},_findCrossPoints:function(t,e){var r,i,n,o,a,s=0,c;for(var l in e)if(c=e[l],!(c.o.y<t.y&&c.d.y<t.y||c.o.y>=t.y&&c.d.y>=t.y||(c.o.x===c.d.x&&c.o.x>=t.x?a=c.o.x:(r=0,i=(c.d.y-c.o.y)/(c.d.x-c.o.x),n=t.y-r*t.x,o=c.o.y-i*c.o.x,a=-(n-o)/(r-i)),a>=t.x&&(s+=1),2!==s)))break;return s},getBoundingRectWidth:function(){return this.getBoundingRect().width},getBoundingRectHeight:function(){return this.getBoundingRect().height},getBoundingRect:function(t,e){var r=this.getCoords(t,e);return fabric.util.makeBoundingBoxFromPoints(r)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(t){return Math.abs(t)<this.minScaleLimit?t<0?-this.minScaleLimit:this.minScaleLimit:t},scale:function(t){return t=this._constrainScale(t),t<0&&(this.flipX=!this.flipX,this.flipY=!this.flipY,t*=-1),this.scaleX=t,this.scaleY=t,this.setCoords()},scaleToWidth:function(t){var e=this.getBoundingRect().width/this.getScaledWidth();return this.scale(t/this.width/e)},scaleToHeight:function(t){var e=this.getBoundingRect().height/this.getScaledHeight();return this.scale(t/this.height/e)},calcCoords:function(t){var r=e(this.angle),i=this.getViewportTransform(),n=t?this._getTransformedDimensions():this._calculateCurrentDimensions(),o=n.x,a=n.y,s=Math.sin(r),c=Math.cos(r),l=o>0?Math.atan(a/o):0,h=o/Math.cos(l)/2,u=Math.cos(l+r)*h,f=Math.sin(l+r)*h,d=this.getCenterPoint(),p=t?d:fabric.util.transformPoint(d,i),g=new fabric.Point(p.x-u,p.y-f),v=new fabric.Point(g.x+o*c,g.y+o*s),m=new fabric.Point(g.x-a*s,g.y+a*c),b=new fabric.Point(p.x+u,p.y+f);if(!t)var y=new fabric.Point((g.x+m.x)/2,(g.y+m.y)/2),_=new fabric.Point((v.x+g.x)/2,(v.y+g.y)/2),w=new fabric.Point((b.x+v.x)/2,(b.y+v.y)/2),S=new fabric.Point((b.x+m.x)/2,(b.y+m.y)/2),x=new fabric.Point(_.x+s*this.rotatingPointOffset,_.y-c*this.rotatingPointOffset);var p={tl:g,tr:v,br:b,bl:m};return t||(p.ml=y,p.mt=_,p.mr=w,p.mb=S,p.mtr=x),p},setCoords:function(t,e){return this.oCoords=this.calcCoords(t),e||(this.aCoords=this.calcCoords(!0)),t||this._setCornerCoords&&this._setCornerCoords(),this},_calcRotateMatrix:function(){if(this.angle){var t=e(this.angle),r=Math.cos(t),i=Math.sin(t);return 6.123233995736766e-17!==r&&-1.8369701987210297e-16!==r||(r=0),[r,i,-i,r,0,0]}return fabric.iMatrix.concat()},calcTransformMatrix:function(t){var e=this.getCenterPoint(),i=[1,0,0,1,e.x,e.y],n,o=this._calcDimensionsTransformMatrix(this.skewX,this.skewY,!0),a;return a=this.group&&!t?r(this.group.calcTransformMatrix(),i):i,this.angle&&(n=this._calcRotateMatrix(),a=r(a,n)),a=r(a,o)},_calcDimensionsTransformMatrix:function(t,i,n){var o,a=this.scaleX*(n&&this.flipX?-1:1),s=this.scaleY*(n&&this.flipY?-1:1),c=[a,0,0,s,0,0];return t&&(o=[1,0,Math.tan(e(t)),1],c=r(c,o,!0)),i&&(o=[1,Math.tan(e(i)),0,1],c=r(c,o,!0)),c},_getNonTransformedDimensions:function(){var t=this.strokeWidth;return{x:this.width+t,y:this.height+t}},_getTransformedDimensions:function(t,e){void 0===t&&(t=this.skewX),void 0===e&&(e=this.skewY);var r=this._getNonTransformedDimensions(),i=r.x/2,n=r.y/2,o=[{x:-i,y:-n},{x:i,y:-n},{x:-i,y:n},{x:i,y:n}],a,s=this._calcDimensionsTransformMatrix(t,e,!1),c;for(a=0;a<o.length;a++)o[a]=fabric.util.transformPoint(o[a],s);return c=fabric.util.makeBoundingBoxFromPoints(o),{x:c.width,y:c.height}},_calculateCurrentDimensions:function(){var t=this.getViewportTransform(),e=this._getTransformedDimensions();return fabric.util.transformPoint(e,t,!0).scalarAdd(2*this.padding)}})}(),fabric.util.object.extend(fabric.Object.prototype,{sendToBack:function(){return this.group?fabric.StaticCanvas.prototype.sendToBack.call(this.group,this):this.canvas.sendToBack(this),this},bringToFront:function(){return this.group?fabric.StaticCanvas.prototype.bringToFront.call(this.group,this):this.canvas.bringToFront(this),this},sendBackwards:function(t){return this.group?fabric.StaticCanvas.prototype.sendBackwards.call(this.group,this,t):this.canvas.sendBackwards(this,t),this},bringForward:function(t){return this.group?fabric.StaticCanvas.prototype.bringForward.call(this.group,this,t):this.canvas.bringForward(this,t),this},moveTo:function(t){return this.group?fabric.StaticCanvas.prototype.moveTo.call(this.group,this,t):this.canvas.moveTo(this,t),this}}),function(){function t(t,e){if(e){if(e.toLive)return t+": url(#SVGID_"+e.id+"); ";var r=new fabric.Color(e),i=t+": "+r.toRgb()+"; ",n=r.getAlpha();return 1!==n&&(i+=t+"-opacity: "+n.toString()+"; "),i}return t+": none; "}var e=fabric.Object.NUM_FRACTION_DIGITS,r=fabric.util.toFixed;fabric.util.object.extend(fabric.Object.prototype,{getSvgStyles:function(e){var r=this.fillRule,i=this.strokeWidth?this.strokeWidth:"0",n=this.strokeDashArray?this.strokeDashArray.join(" "):"none",o=this.strokeLineCap?this.strokeLineCap:"butt",a=this.strokeLineJoin?this.strokeLineJoin:"miter",s=this.strokeMiterLimit?this.strokeMiterLimit:"4",c=void 0!==this.opacity?this.opacity:"1",l=this.visible?"":" visibility: hidden;",h=e?"":this.getSvgFilter(),u=t("fill",this.fill);return[t("stroke",this.stroke),"stroke-width: ",i,"; ","stroke-dasharray: ",n,"; ","stroke-linecap: ",o,"; ","stroke-linejoin: ",a,"; ","stroke-miterlimit: ",s,"; ",u,"fill-rule: ",r,"; ","opacity: ",c,";",h,l].join("")},getSvgSpanStyles:function(e){var r=e.strokeWidth?"stroke-width: "+e.strokeWidth+"; ":"",i=e.fontFamily?"font-family: "+e.fontFamily.replace(/"/g,"'")+"; ":"",n=e.fontSize?"font-size: "+e.fontSize+"; ":"",o=e.fontStyle?"font-style: "+e.fontStyle+"; ":"",a=e.fontWeight?"font-weight: "+e.fontWeight+"; ":"",s=e.fill?t("fill",e.fill):"";return[e.stroke?t("stroke",e.stroke):"",r,i,n,o,a,this.getSvgTextDecoration(e),s].join("")},getSvgTextDecoration:function(t){return"overline"in t||"underline"in t||"linethrough"in t?"text-decoration: "+(t.overline?"overline ":"")+(t.underline?"underline ":"")+(t.linethrough?"line-through ":"")+";":""},getSvgFilter:function(){return this.shadow?"filter: url(#SVGID_"+this.shadow.id+");":""},getSvgId:function(){return this.id?'id="'+this.id+'" ':""},getSvgTransform:function(){var t=this.angle,e=this.skewX%360,i=this.skewY%360,n=this.getCenterPoint(),o=fabric.Object.NUM_FRACTION_DIGITS,a="translate("+r(n.x,o)+" "+r(n.y,o)+")",s=0!==t?" rotate("+r(t,o)+")":"",c=1===this.scaleX&&1===this.scaleY?"":" scale("+r(this.scaleX,o)+" "+r(this.scaleY,o)+")",l=0!==e?" skewX("+r(e,o)+")":"",h=0!==i?" skewY("+r(i,o)+")":"";return[a,s,c,this.flipX?" matrix(-1 0 0 1 0 0) ":"",this.flipY?" matrix(1 0 0 -1 0 0)":"",l,h].join("")},getSvgTransformMatrix:function(){return this.transformMatrix?" matrix("+this.transformMatrix.join(" ")+") ":""},_setSVGBg:function(t){this.backgroundColor&&t.push("\t\t<rect ",this._getFillAttributes(this.backgroundColor),' x="',r(-this.width/2,e),'" y="',r(-this.height/2,e),'" width="',r(this.width,e),'" height="',r(this.height,e),'"></rect>\n')},_createBaseSVGMarkup:function(){var t=[];return this.fill&&this.fill.toLive&&t.push(this.fill.toSVG(this,!1)),this.stroke&&this.stroke.toLive&&t.push(this.stroke.toSVG(this,!1)),this.shadow&&t.push(this.shadow.toSVG(this)),t}})}(),function(){function t(t,e,i){var n={},o=!0;i.forEach(function(e){n[e]=t[e]}),r(t[e],n,!0)}function e(t,r,i){if(t===r)return!0;if(Array.isArray(t)){if(t.length!==r.length)return!1;for(var n=0,o=t.length;n<o;n++)if(!e(t[n],r[n]))return!1;return!0}if(t&&"object"==typeof t){var a=Object.keys(t),s;if(!i&&a.length!==Object.keys(r).length)return!1;for(var n=0,o=a.length;n<o;n++)if(s=a[n],!e(t[s],r[s]))return!1;return!0}}var r=fabric.util.object.extend,i="stateProperties";fabric.util.object.extend(fabric.Object.prototype,{hasStateChanged:function(t){t=t||i;var r="_"+t;return Object.keys(this[r]).length<this[t].length||!e(this[r],this,!0)},saveState:function(e){var r=e&&e.propertySet||i,n="_"+r;return this[n]?(t(this,n,this[r]),e&&e.stateProperties&&t(this,n,e.stateProperties),this):this.setupState(e)},setupState:function(t){t=t||{};var e=t.propertySet||i;return t.propertySet=e,this["_"+e]={},this.saveState(t),this}})}(),function(){var t=fabric.util.degreesToRadians;fabric.util.object.extend(fabric.Object.prototype,{_controlsVisibility:null,_findTargetCorner:function(t){if(!this.hasControls||!this.active||this.group)return!1;var e=t.x,r=t.y,i,n;this.__corner=0;for(var o in this.oCoords)if(this.isControlVisible(o)&&("mtr"!==o||this.hasRotatingPoint)&&(!this.get("lockUniScaling")||"mt"!==o&&"mr"!==o&&"mb"!==o&&"ml"!==o)&&(n=this._getImageLines(this.oCoords[o].corner),0!==(i=this._findCrossPoints({x:e,y:r},n))&&i%2==1))return this.__corner=o,o;return!1},_setCornerCoords:function(){var e=this.oCoords,r=t(45-this.angle),i=.707106*this.cornerSize,n=i*Math.cos(r),o=i*Math.sin(r),a,s;for(var c in e)a=e[c].x,s=e[c].y,e[c].corner={tl:{x:a-o,y:s-n},tr:{x:a+n,y:s-o},bl:{x:a-n,y:s+o},br:{x:a+o,y:s+n}}},drawSelectionBackground:function(e){if(!this.selectionBackgroundColor||!this.active||this.canvas&&!this.canvas.interactive)return this;e.save();var r=this.getCenterPoint(),i=this._calculateCurrentDimensions(),n=this.canvas.viewportTransform;return e.translate(r.x,r.y),e.scale(1/n[0],1/n[3]),e.rotate(t(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-i.x/2,-i.y/2,i.x,i.y),e.restore(),this},drawBorders:function(t,e){e=e||{};var r=this._calculateCurrentDimensions(),i=1/this.borderScaleFactor,n=r.x+i,o=r.y+i,a=void 0!==e.hasRotatingPoint?e.hasRotatingPoint:this.hasRotatingPoint,s=void 0!==e.hasControls?e.hasControls:this.hasControls,c=void 0!==e.rotatingPointOffset?e.rotatingPointOffset:this.rotatingPointOffset;if(t.save(),t.strokeStyle=e.borderColor||this.borderColor,this._setLineDash(t,e.borderDashArray||this.borderDashArray,null),t.strokeRect(-n/2,-o/2,n,o),a&&this.isControlVisible("mtr")&&s){var l=-o/2;t.beginPath(),t.moveTo(0,l),t.lineTo(0,l-c),t.closePath(),t.stroke()}return t.restore(),this},drawBordersInGroup:function(t,e,r){r=r||{};var i=this._getNonTransformedDimensions(),n=fabric.util.customTransformMatrix(e.scaleX,e.scaleY,e.skewX),o=fabric.util.transformPoint(i,n),a=1/this.borderScaleFactor,s=o.x+a,c=o.y+a;return t.save(),this._setLineDash(t,r.borderDashArray||this.borderDashArray,null),t.strokeStyle=r.borderColor||this.borderColor,t.strokeRect(-s/2,-c/2,s,c),t.restore(),this},drawControls:function(t,e){e=e||{};var r=this._calculateCurrentDimensions(),i=r.x,n=r.y,o=e.cornerSize||this.cornerSize,a=-(i+o)/2,s=-(n+o)/2,c=void 0!==e.transparentCorners?e.transparentCorners:this.transparentCorners,l=void 0!==e.hasRotatingPoint?e.hasRotatingPoint:this.hasRotatingPoint,h=c?"stroke":"fill";return t.save(),t.strokeStyle=t.fillStyle=e.cornerColor||this.cornerColor,this.transparentCorners||(t.strokeStyle=e.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(t,e.cornerDashArray||this.cornerDashArray,null),this._drawControl("tl",t,h,a,s,e),this._drawControl("tr",t,h,a+i,s,e),this._drawControl("bl",t,h,a,s+n,e),this._drawControl("br",t,h,a+i,s+n,e),this.get("lockUniScaling")||(this._drawControl("mt",t,h,a+i/2,s,e),this._drawControl("mb",t,h,a+i/2,s+n,e),this._drawControl("mr",t,h,a+i,s+n/2,e),this._drawControl("ml",t,h,a,s+n/2,e)),l&&this._drawControl("mtr",t,h,a+i/2,s-this.rotatingPointOffset,e),t.restore(),this},_drawControl:function(t,e,r,i,n,o){if(o=o||{},this.isControlVisible(t)){var a=this.cornerSize,s=!this.transparentCorners&&this.cornerStrokeColor;switch(o.cornerStyle||this.cornerStyle){case"circle":e.beginPath(),e.arc(i+a/2,n+a/2,a/2,0,2*Math.PI,!1),e[r](),s&&e.stroke();break;default:this.transparentCorners||e.clearRect(i,n,a,a),e[r+"Rect"](i,n,a,a),s&&e.strokeRect(i,n,a,a)}}},isControlVisible:function(t){return this._getControlsVisibility()[t]},setControlVisible:function(t,e){return this._getControlsVisibility()[t]=e,this},setControlsVisibility:function(t){t||(t={});for(var e in t)this.setControlVisible(e,t[e]);return this},_getControlsVisibility:function(){return this._controlsVisibility||(this._controlsVisibility={tl:!0,tr:!0,br:!0,bl:!0,ml:!0,mt:!0,mr:!0,mb:!0,mtr:!0}),this._controlsVisibility}})}(),fabric.util.object.extend(fabric.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(t,e){e=e||{};var r=function(){},i=e.onComplete||r,n=e.onChange||r,o=this;return fabric.util.animate({startValue:t.left,endValue:this.getCenter().left,duration:this.FX_DURATION,onChange:function(e){t.set("left",e),o.requestRenderAll(),n()},onComplete:function(){t.setCoords(),i()}}),this},fxCenterObjectV:function(t,e){e=e||{};var r=function(){},i=e.onComplete||r,n=e.onChange||r,o=this;return fabric.util.animate({startValue:t.top,endValue:this.getCenter().top,duration:this.FX_DURATION,onChange:function(e){t.set("top",e),o.requestRenderAll(),n()},onComplete:function(){t.setCoords(),i()}}),this},fxRemove:function(t,e){e=e||{};var r=function(){},i=e.onComplete||r,n=e.onChange||r,o=this;return fabric.util.animate({startValue:t.opacity,endValue:0,duration:this.FX_DURATION,onStart:function(){t.set("active",!1)},onChange:function(e){t.set("opacity",e),o.requestRenderAll(),n()},onComplete:function(){o.remove(t),i()}}),this}}),fabric.util.object.extend(fabric.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var t=[],e,r;for(e in arguments[0])t.push(e);for(var i=0,n=t.length;i<n;i++)e=t[i],r=i!==n-1,this._animate(e,arguments[0][e],arguments[1],r)}else this._animate.apply(this,arguments);return this},_animate:function(t,e,r,i){var n=this,o;e=e.toString(),r=r?fabric.util.object.clone(r):{},~t.indexOf(".")&&(o=t.split("."));var a=o?this.get(o[0])[o[1]]:this.get(t);"from"in r||(r.from=a),e=~e.indexOf("=")?a+parseFloat(e.replace("=","")):parseFloat(e),fabric.util.animate({startValue:r.from,endValue:e,byValue:r.by,easing:r.easing,duration:r.duration,abort:r.abort&&function(){return r.abort.call(n)},onChange:function(e,a,s){o?n[o[0]][o[1]]=e:n.set(t,e),i||r.onChange&&r.onChange(e,a,s)},onComplete:function(t,e,o){i||(n.setCoords(),r.onComplete&&r.onComplete(t,e,o))}})}}),function(t){"use strict";function e(t,e){var r=t.origin,i=t.axis1,n=t.axis2,o=t.dimension,a=e.nearest,s=e.center,c=e.farthest;return function(){switch(this.get(r)){case a:return Math.min(this.get(i),this.get(n));case s:return Math.min(this.get(i),this.get(n))+.5*this.get(o);case c:return Math.max(this.get(i),this.get(n))}}}var r=t.fabric||(t.fabric={}),i=r.util.object.extend,n=r.util.object.clone,o={x1:1,x2:1,y1:1,y2:1},a=r.StaticCanvas.supports("setLineDash");if(r.Line)return void r.warn("fabric.Line is already defined");var s=r.Object.prototype.cacheProperties.concat();s.push("x1","x2","y1","y2"),r.Line=r.util.createClass(r.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:s,initialize:function(t,e){t||(t=[0,0,0,0]),this.callSuper("initialize",e),this.set("x1",t[0]),this.set("y1",t[1]),this.set("x2",t[2]),this.set("y2",t[3]),this._setWidthHeight(e)},_setWidthHeight:function(t){t||(t={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in t?t.left:this._getLeftToOriginX(),this.top="top"in t?t.top:this._getTopToOriginY()},_set:function(t,e){return this.callSuper("_set",t,e),void 0!==o[t]&&this._setWidthHeight(),this},_getLeftToOriginX:e({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:e({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(t){if(t.beginPath(),!this.strokeDashArray||this.strokeDashArray&&a){var e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2)}t.lineWidth=this.strokeWidth;var r=t.strokeStyle;t.strokeStyle=this.stroke||t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=r},_renderDashedStroke:function(t){var e=this.calcLinePoints();t.beginPath(),r.util.drawDashedLine(t,e.x1,e.y1,e.x2,e.y2,this.strokeDashArray),t.closePath()},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(t){return i(this.callSuper("toObject",t),this.calcLinePoints())},_getNonTransformedDimensions:function(){var t=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(t.y-=this.strokeWidth),0===this.height&&(t.x-=this.strokeWidth)),t},calcLinePoints:function(){var t=this.x1<=this.x2?-1:1,e=this.y1<=this.y2?-1:1,r=t*this.width*.5,i=e*this.height*.5;return{x1:r,x2:t*this.width*-.5,y1:i,y2:e*this.height*-.5}},toSVG:function(t){var e=this._createBaseSVGMarkup(),r=this.calcLinePoints();return e.push("<line ",this.getSvgId(),'x1="',r.x1,'" y1="',r.y1,'" x2="',r.x2,'" y2="',r.y2,'" style="',this.getSvgStyles(),'" transform="',this.getSvgTransform(),this.getSvgTransformMatrix(),'"/>\n'),t?t(e.join("")):e.join("")}}),r.Line.ATTRIBUTE_NAMES=r.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),r.Line.fromElement=function(t,e,n){n=n||{};var o=r.parseAttributes(t,r.Line.ATTRIBUTE_NAMES),a=[o.x1||0,o.y1||0,o.x2||0,o.y2||0];n.originX="left",n.originY="top",e(new r.Line(a,i(o,n)))},r.Line.fromObject=function(t,e){function i(t){delete t.points,e&&e(t)}var o=n(t,!0);o.points=[t.x1,t.y1,t.x2,t.y2],r.Object._fromObject("Line",o,i,"points")}}(exports),function(t){"use strict";function e(t){return"radius"in t&&t.radius>=0}var r=t.fabric||(t.fabric={}),i=Math.PI,n=r.util.object.extend;if(r.Circle)return void r.warn("fabric.Circle is already defined.");var o=r.Object.prototype.cacheProperties.concat();o.push("radius"),r.Circle=r.util.createClass(r.Object,{type:"circle",radius:0,startAngle:0,endAngle:2*i,cacheProperties:o,initialize:function(t){this.callSuper("initialize",t),this.set("radius",t&&t.radius||0)},_set:function(t,e){return this.callSuper("_set",t,e),"radius"===t&&this.setRadius(e),this},toObject:function(t){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(t))},toSVG:function(t){var e=this._createBaseSVGMarkup(),r=0,n=0,o=(this.endAngle-this.startAngle)%(2*i);if(0===o)e.push("<circle ",this.getSvgId(),'cx="0" cy="0" ','r="',this.radius,'" style="',this.getSvgStyles(),'" transform="',this.getSvgTransform()," ",this.getSvgTransformMatrix(),'"/>\n');else{var a=Math.cos(this.startAngle)*this.radius,s=Math.sin(this.startAngle)*this.radius,c=Math.cos(this.endAngle)*this.radius,l=Math.sin(this.endAngle)*this.radius,h=o>i?"1":"0";e.push('<path d="M '+a+" "+s," A "+this.radius+" "+this.radius," 0 ",+h+" 1"," "+c+" "+l,'" style="',this.getSvgStyles(),'" transform="',this.getSvgTransform()," ",this.getSvgTransformMatrix(),'"/>\n')}return t?t(e.join("")):e.join("")},_render:function(t){t.beginPath(),t.arc(0,0,this.radius,this.startAngle,this.endAngle,!1),this._renderFill(t),this._renderStroke(t)},getRadiusX:function(){return this.get("radius")*this.get("scaleX")},getRadiusY:function(){return this.get("radius")*this.get("scaleY")},setRadius:function(t){return this.radius=t,this.set("width",2*t).set("height",2*t)}}),r.Circle.ATTRIBUTE_NAMES=r.SHARED_ATTRIBUTES.concat("cx cy r".split(" ")),r.Circle.fromElement=function(t,i,o){o||(o={});var a=r.parseAttributes(t,r.Circle.ATTRIBUTE_NAMES);if(!e(a))throw new Error("value of `r` attribute is required and can not be negative");a.left=(a.left||0)-a.radius,a.top=(a.top||0)-a.radius,a.originX="left",a.originY="top",i(new r.Circle(n(a,o)))},r.Circle.fromObject=function(t,e){return r.Object._fromObject("Circle",t,e)}}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={});if(e.Triangle)return void e.warn("fabric.Triangle is already defined");e.Triangle=e.util.createClass(e.Object,{type:"triangle",initialize:function(t){this.callSuper("initialize",t),this.set("width",t&&t.width||100).set("height",t&&t.height||100)},_render:function(t){var e=this.width/2,r=this.height/2;t.beginPath(),t.moveTo(-e,r),t.lineTo(0,-r),t.lineTo(e,r),t.closePath(),this._renderFill(t),this._renderStroke(t)},_renderDashedStroke:function(t){var r=this.width/2,i=this.height/2;t.beginPath(),e.util.drawDashedLine(t,-r,i,0,-i,this.strokeDashArray),e.util.drawDashedLine(t,0,-i,r,i,this.strokeDashArray),e.util.drawDashedLine(t,r,i,-r,i,this.strokeDashArray),t.closePath()},toSVG:function(t){var e=this._createBaseSVGMarkup(),r=this.width/2,i=this.height/2,n=[-r+" "+i,"0 "+-i,r+" "+i].join(",");return e.push("<polygon ",this.getSvgId(),'points="',n,'" style="',this.getSvgStyles(),'" transform="',this.getSvgTransform(),'"/>'),t?t(e.join("")):e.join("")}}),e.Triangle.fromObject=function(t,r){return e.Object._fromObject("Triangle",t,r)}}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=2*Math.PI,i=e.util.object.extend;if(e.Ellipse)return void e.warn("fabric.Ellipse is already defined.");var n=e.Object.prototype.cacheProperties.concat();n.push("rx","ry"),e.Ellipse=e.util.createClass(e.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:n,initialize:function(t){this.callSuper("initialize",t),this.set("rx",t&&t.rx||0),this.set("ry",t&&t.ry||0)},_set:function(t,e){switch(this.callSuper("_set",t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},toSVG:function(t){var e=this._createBaseSVGMarkup(),r=0,i=0;return e.push("<ellipse ",this.getSvgId(),'cx="',0,'" cy="',0,'" ','rx="',this.rx,'" ry="',this.ry,'" style="',this.getSvgStyles(),'" transform="',this.getSvgTransform(),this.getSvgTransformMatrix(),'"/>\n'),t?t(e.join("")):e.join("")},_render:function(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,r,!1),t.restore(),this._renderFill(t),this._renderStroke(t)}}),e.Ellipse.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),e.Ellipse.fromElement=function(t,r,n){n||(n={});var o=e.parseAttributes(t,e.Ellipse.ATTRIBUTE_NAMES);o.left=(o.left||0)-o.rx,o.top=(o.top||0)-o.ry,o.originX="left",o.originY="top",r(new e.Ellipse(i(o,n)))},e.Ellipse.fromObject=function(t,r){return e.Object._fromObject("Ellipse",t,r)}}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.util.object.extend;if(e.Rect)return void e.warn("fabric.Rect is already defined");var i=e.Object.prototype.stateProperties.concat();i.push("rx","ry");var n=e.Object.prototype.cacheProperties.concat();n.push("rx","ry"),e.Rect=e.util.createClass(e.Object,{stateProperties:i,type:"rect",rx:0,ry:0,cacheProperties:n,initialize:function(t){this.callSuper("initialize",t),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(t){if(1===this.width&&1===this.height)return void t.fillRect(-.5,-.5,1,1);var e=this.rx?Math.min(this.rx,this.width/2):0,r=this.ry?Math.min(this.ry,this.height/2):0,i=this.width,n=this.height,o=-this.width/2,a=-this.height/2,s=0!==e||0!==r,c=.4477152502;t.beginPath(),t.moveTo(o+e,a),t.lineTo(o+i-e,a),s&&t.bezierCurveTo(o+i-c*e,a,o+i,a+c*r,o+i,a+r),t.lineTo(o+i,a+n-r),s&&t.bezierCurveTo(o+i,a+n-c*r,o+i-c*e,a+n,o+i-e,a+n),t.lineTo(o+e,a+n),s&&t.bezierCurveTo(o+c*e,a+n,o,a+n-c*r,o,a+n-r),t.lineTo(o,a+r),s&&t.bezierCurveTo(o,a+c*r,o+c*e,a,o+e,a),t.closePath(),this._renderFill(t),this._renderStroke(t)},_renderDashedStroke:function(t){var r=-this.width/2,i=-this.height/2,n=this.width,o=this.height;t.beginPath(),e.util.drawDashedLine(t,r,i,r+n,i,this.strokeDashArray),e.util.drawDashedLine(t,r+n,i,r+n,i+o,this.strokeDashArray),e.util.drawDashedLine(t,r+n,i+o,r,i+o,this.strokeDashArray),e.util.drawDashedLine(t,r,i+o,r,i,this.strokeDashArray),t.closePath()},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},toSVG:function(t){var e=this._createBaseSVGMarkup(),r=-this.width/2,i=-this.height/2;return e.push("<rect ",this.getSvgId(),'x="',r,'" y="',i,'" rx="',this.get("rx"),'" ry="',this.get("ry"),'" width="',this.width,'" height="',this.height,'" style="',this.getSvgStyles(),'" transform="',this.getSvgTransform(),this.getSvgTransformMatrix(),'"/>\n'),t?t(e.join("")):e.join("")}}),e.Rect.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),e.Rect.fromElement=function(t,i,n){if(!t)return i(null);n=n||{};var o=e.parseAttributes(t,e.Rect.ATTRIBUTE_NAMES);o.left=o.left||0,o.top=o.top||0,o.originX="left",o.originY="top";var a=new e.Rect(r(n?e.util.object.clone(n):{},o));a.visible=a.visible&&a.width>0&&a.height>0,i(a)},e.Rect.fromObject=function(t,r){return e.Object._fromObject("Rect",t,r)}}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.util.object.extend,i=e.util.array.min,n=e.util.array.max,o=e.util.toFixed,a=e.Object.NUM_FRACTION_DIGITS;if(e.Polyline)return void e.warn("fabric.Polyline is already defined");var s=e.Object.prototype.cacheProperties.concat();s.push("points"),e.Polyline=e.util.createClass(e.Object,{type:"polyline",points:null,minX:0,minY:0,cacheProperties:s,initialize:function(t,e){e=e||{},this.points=t||[],this.callSuper("initialize",e),this._calcDimensions(),"top"in e||(this.top=this.minY),"left"in e||(this.left=this.minX),this.pathOffset={x:this.minX+this.width/2,y:this.minY+this.height/2}},_calcDimensions:function(){var t=this.points,e=i(t,"x"),r=i(t,"y"),o=n(t,"x"),a=n(t,"y");this.width=o-e||0,this.height=a-r||0,this.minX=e||0,this.minY=r||0},toObject:function(t){return r(this.callSuper("toObject",t),{points:this.points.concat()})},toSVG:function(t){for(var e=[],r=this.pathOffset.x,i=this.pathOffset.y,n=this._createBaseSVGMarkup(),s=0,c=this.points.length;s<c;s++)e.push(o(this.points[s].x-r,a),",",o(this.points[s].y-i,a)," ");return n.push("<",this.type," ",this.getSvgId(),'points="',e.join(""),'" style="',this.getSvgStyles(),'" transform="',this.getSvgTransform()," ",this.getSvgTransformMatrix(),'"/>\n'),t?t(n.join("")):n.join("")},commonRender:function(t){var e,r=this.points.length,i=this.pathOffset.x,n=this.pathOffset.y;if(!r||isNaN(this.points[r-1].y))return!1;t.beginPath(),t.moveTo(this.points[0].x-i,this.points[0].y-n);for(var o=0;o<r;o++)e=this.points[o],t.lineTo(e.x-i,e.y-n);return!0},_render:function(t){this.commonRender(t)&&(this._renderFill(t),this._renderStroke(t))},_renderDashedStroke:function(t){var r,i;t.beginPath();for(var n=0,o=this.points.length;n<o;n++)r=this.points[n],i=this.points[n+1]||r,e.util.drawDashedLine(t,r.x,r.y,i.x,i.y,this.strokeDashArray)},complexity:function(){return this.get("points").length}}),e.Polyline.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat(),e.Polyline.fromElement=function(t,r,i){if(!t)return r(null);i||(i={});var n=e.parsePointsAttribute(t.getAttribute("points")),o=e.parseAttributes(t,e.Polyline.ATTRIBUTE_NAMES);r(new e.Polyline(n,e.util.object.extend(o,i)))},e.Polyline.fromObject=function(t,r){return e.Object._fromObject("Polyline",t,r,"points")}}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.util.object.extend;if(e.Polygon)return void e.warn("fabric.Polygon is already defined");e.Polygon=e.util.createClass(e.Polyline,{type:"polygon",_render:function(t){this.commonRender(t)&&(t.closePath(),this._renderFill(t),this._renderStroke(t))},_renderDashedStroke:function(t){this.callSuper("_renderDashedStroke",t),t.closePath()}}),e.Polygon.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat(),e.Polygon.fromElement=function(t,i,n){if(!t)return i(null);n||(n={});var o=e.parsePointsAttribute(t.getAttribute("points")),a=e.parseAttributes(t,e.Polygon.ATTRIBUTE_NAMES);i(new e.Polygon(o,r(a,n)))},e.Polygon.fromObject=function(t,r){return e.Object._fromObject("Polygon",t,r,"points")}}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.util.array.min,i=e.util.array.max,n=e.util.object.extend,o=Object.prototype.toString,a=e.util.drawArc,s={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},c={m:"l",M:"L"};if(e.Path)return void e.warn("fabric.Path is already defined");var l=e.Object.prototype.stateProperties.concat();l.push("path");var h=e.Object.prototype.cacheProperties.concat();h.push("path","fillRule"),e.Path=e.util.createClass(e.Object,{type:"path",path:null,minX:0,minY:0,cacheProperties:h,stateProperties:l,initialize:function(t,e){e=e||{},this.callSuper("initialize",e),t||(t=[]);var r="[object Array]"===o.call(t);this.path=r?t:t.match&&t.match(/[mzlhvcsqta][^mzlhvcsqta]*/gi),this.path&&(r||(this.path=this._parsePath()),this._setPositionDimensions(e))},_setPositionDimensions:function(t){var e=this._parseDimensions();this.minX=e.left,this.minY=e.top,this.width=e.width,this.height=e.height,void 0===t.left&&(this.left=e.left+("center"===this.originX?this.width/2:"right"===this.originX?this.width:0)),void 0===t.top&&(this.top=e.top+("center"===this.originY?this.height/2:"bottom"===this.originY?this.height:0)),this.pathOffset=this.pathOffset||{x:this.minX+this.width/2,y:this.minY+this.height/2}},_renderPathCommands:function(t){var e,r=null,i=0,n=0,o=0,s=0,c=0,l=0,h,u,f=-this.pathOffset.x,d=-this.pathOffset.y;t.beginPath();for(var p=0,g=this.path.length;p<g;++p){switch(e=this.path[p],e[0]){case"l":o+=e[1],s+=e[2],t.lineTo(o+f,s+d);break;case"L":o=e[1],s=e[2],t.lineTo(o+f,s+d);break;case"h":o+=e[1],t.lineTo(o+f,s+d);break;case"H":o=e[1],t.lineTo(o+f,s+d);break;case"v":s+=e[1],t.lineTo(o+f,s+d);break;case"V":s=e[1],t.lineTo(o+f,s+d);break;case"m":o+=e[1],s+=e[2],i=o,n=s,t.moveTo(o+f,s+d);break;case"M":o=e[1],s=e[2],i=o,n=s,t.moveTo(o+f,s+d);break;case"c":h=o+e[5],u=s+e[6],c=o+e[3],l=s+e[4],t.bezierCurveTo(o+e[1]+f,s+e[2]+d,c+f,l+d,h+f,u+d),o=h,s=u;break;case"C":o=e[5],s=e[6],c=e[3],l=e[4],t.bezierCurveTo(e[1]+f,e[2]+d,c+f,l+d,o+f,s+d);break;case"s":h=o+e[3],u=s+e[4],null===r[0].match(/[CcSs]/)?(c=o,l=s):(c=2*o-c,l=2*s-l),t.bezierCurveTo(c+f,l+d,o+e[1]+f,s+e[2]+d,h+f,u+d),c=o+e[1],l=s+e[2],o=h,s=u;break;case"S":h=e[3],u=e[4],null===r[0].match(/[CcSs]/)?(c=o,l=s):(c=2*o-c,l=2*s-l),t.bezierCurveTo(c+f,l+d,e[1]+f,e[2]+d,h+f,u+d),o=h,s=u,c=e[1],l=e[2];break;case"q":h=o+e[3],u=s+e[4],c=o+e[1],l=s+e[2],t.quadraticCurveTo(c+f,l+d,h+f,u+d),o=h,s=u;break;case"Q":h=e[3],u=e[4],t.quadraticCurveTo(e[1]+f,e[2]+d,h+f,u+d),o=h,s=u,c=e[1],l=e[2];break;case"t":h=o+e[1],u=s+e[2],null===r[0].match(/[QqTt]/)?(c=o,l=s):(c=2*o-c,l=2*s-l),t.quadraticCurveTo(c+f,l+d,h+f,u+d),o=h,s=u;break;case"T":h=e[1],u=e[2],null===r[0].match(/[QqTt]/)?(c=o,l=s):(c=2*o-c,l=2*s-l),t.quadraticCurveTo(c+f,l+d,h+f,u+d),o=h,s=u;break;case"a":a(t,o+f,s+d,[e[1],e[2],e[3],e[4],e[5],e[6]+o+f,e[7]+s+d]),o+=e[6],s+=e[7];break;case"A":a(t,o+f,s+d,[e[1],e[2],e[3],e[4],e[5],e[6]+f,e[7]+d]),o=e[6],s=e[7];break;case"z":case"Z":o=i,s=n,t.closePath()}r=e}},_render:function(t){this._renderPathCommands(t),this._renderFill(t),this._renderStroke(t)},toString:function(){return"#<fabric.Path ("+this.complexity()+'): { "top": '+this.top+', "left": '+this.left+" }>"},toObject:function(t){return n(this.callSuper("toObject",t),{path:this.path.map(function(t){return t.slice()}),top:this.top,left:this.left})},toDatalessObject:function(t){var e=this.toObject(["sourcePath"].concat(t));return e.sourcePath&&delete e.path,e},toSVG:function(t){for(var e=[],r=this._createBaseSVGMarkup(),i="",n=0,o=this.path.length;n<o;n++)e.push(this.path[n].join(" "));var a=e.join(" ");return i=" translate("+-this.pathOffset.x+", "+-this.pathOffset.y+") ",r.push("<path ",this.getSvgId(),'d="',a,'" style="',this.getSvgStyles(),'" transform="',this.getSvgTransform(),i,this.getSvgTransformMatrix(),'" stroke-linecap="round" ',"/>\n"),t?t(r.join("")):r.join("")},complexity:function(){return this.path.length},_parsePath:function(){for(var t=[],e=[],r,i,n=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:e[-+]?\d+)?)/gi,o,a,l=0,h,u=this.path.length;l<u;l++){for(r=this.path[l],a=r.slice(1).trim(),e.length=0;o=n.exec(a);)e.push(o[0]);h=[r.charAt(0)];for(var f=0,d=e.length;f<d;f++)i=parseFloat(e[f]),isNaN(i)||h.push(i);var p=h[0],g=s[p.toLowerCase()],v=c[p]||p;if(h.length-1>g)for(var m=1,b=h.length;m<b;m+=g)t.push([p].concat(h.slice(m,m+g))),p=v;else t.push(h)}return t},_parseDimensions:function(){for(var t=[],n=[],o,a=null,s=0,c=0,l=0,h=0,u=0,f=0,d,p,g,v=0,m=this.path.length;v<m;++v){switch(o=this.path[v],o[0]){case"l":l+=o[1],h+=o[2],g=[];break;case"L":l=o[1],h=o[2],g=[];break;case"h":l+=o[1],g=[];break;case"H":l=o[1],g=[];break;case"v":h+=o[1],g=[];break;case"V":h=o[1],g=[];break;case"m":l+=o[1],h+=o[2],s=l,c=h,g=[];break;case"M":l=o[1],h=o[2],s=l,c=h,g=[];break;case"c":d=l+o[5],p=h+o[6],u=l+o[3],f=h+o[4],g=e.util.getBoundsOfCurve(l,h,l+o[1],h+o[2],u,f,d,p),l=d,h=p;break;case"C":u=o[3],f=o[4],g=e.util.getBoundsOfCurve(l,h,o[1],o[2],u,f,o[5],o[6]),l=o[5],h=o[6];break;case"s":d=l+o[3],p=h+o[4],null===a[0].match(/[CcSs]/)?(u=l,f=h):(u=2*l-u,f=2*h-f),g=e.util.getBoundsOfCurve(l,h,u,f,l+o[1],h+o[2],d,p),u=l+o[1],f=h+o[2],l=d,h=p;break;case"S":d=o[3],p=o[4],null===a[0].match(/[CcSs]/)?(u=l,f=h):(u=2*l-u,f=2*h-f),g=e.util.getBoundsOfCurve(l,h,u,f,o[1],o[2],d,p),l=d,h=p,u=o[1],f=o[2];break;case"q":d=l+o[3],p=h+o[4],u=l+o[1],f=h+o[2],g=e.util.getBoundsOfCurve(l,h,u,f,u,f,d,p),l=d,h=p;break;case"Q":u=o[1],f=o[2],g=e.util.getBoundsOfCurve(l,h,u,f,u,f,o[3],o[4]),l=o[3],h=o[4];break;case"t":d=l+o[1],p=h+o[2],null===a[0].match(/[QqTt]/)?(u=l,f=h):(u=2*l-u,f=2*h-f),g=e.util.getBoundsOfCurve(l,h,u,f,u,f,d,p),l=d,h=p;break;case"T":d=o[1],p=o[2],null===a[0].match(/[QqTt]/)?(u=l,f=h):(u=2*l-u,f=2*h-f),g=e.util.getBoundsOfCurve(l,h,u,f,u,f,d,p),l=d,h=p;break;case"a":g=e.util.getBoundsOfArc(l,h,o[1],o[2],o[3],o[4],o[5],o[6]+l,o[7]+h),l+=o[6],h+=o[7];break;case"A":g=e.util.getBoundsOfArc(l,h,o[1],o[2],o[3],o[4],o[5],o[6],o[7]),l=o[6],h=o[7];break;case"z":case"Z":l=s,h=c}a=o,g.forEach(function(e){t.push(e.x),n.push(e.y)}),t.push(l),n.push(h)}var b=r(t)||0,y=r(n)||0;return{left:b,top:y,width:(i(t)||0)-b,height:(i(n)||0)-y}}}),e.Path.fromObject=function(t,r){if("string"==typeof t.sourcePath){var i=t.sourcePath;e.loadSVGFromURL(i,function(e){var i=e[0];i.setOptions(t),r&&r(i)})}else e.Object._fromObject("Path",t,r,"path")},e.Path.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat(["d"]),e.Path.fromElement=function(t,r,i){var o=e.parseAttributes(t,e.Path.ATTRIBUTE_NAMES);o.originX="left",o.originY="top",r(new e.Path(o.d,n(o,i)))}}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.util.object.extend,i=e.util.array.min,n=e.util.array.max;e.Group||(e.Group=e.util.createClass(e.Object,e.Collection,{type:"group",strokeWidth:0,subTargetCheck:!1,cacheProperties:[],useSetOnGroup:!1,initialize:function(t,e,r){e=e||{},this._objects=[],r&&this.callSuper("initialize",e),this._objects=t||[];for(var i=this._objects.length;i--;)this._objects[i].group=this;if(e.originX&&(this.originX=e.originX),e.originY&&(this.originY=e.originY),!r){var n=e&&e.centerPoint;n||this._calcBounds(),this._updateObjectsCoords(n),delete e.centerPont,this.callSuper("initialize",e)}this.setCoords()},_updateObjectsCoords:function(t){for(var t=t||this.getCenterPoint(),e=this._objects.length;e--;)this._updateObjectCoords(this._objects[e],t)},_updateObjectCoords:function(t,e){var r=t.left,i=t.top,n=!0,o=!0;t.set({left:r-e.x,top:i-e.y}),t.group=this,t.setCoords(!0,!0)},toString:function(){return"#<fabric.Group: ("+this.complexity()+")>"},addWithUpdate:function(t){return this._restoreObjectsState(),e.util.resetObjectTransform(this),t&&(this._objects.push(t),t.group=this,t._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},removeWithUpdate:function(t){return this._restoreObjectsState(),e.util.resetObjectTransform(this),this.remove(t),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(t){this.dirty=!0,t.group=this},_onObjectRemoved:function(t){this.dirty=!0,delete t.group},_set:function(t,e){var r=this._objects.length;if(this.useSetOnGroup)for(;r--;)this._objects[r].setOnGroup(t,e);this.callSuper("_set",t,e)},toObject:function(t){var e=this.getObjects().map(function(e){var r=e.includeDefaultValues;e.includeDefaultValues=e.group.includeDefaultValues;var i=e.toObject(t);return e.includeDefaultValues=r,i});return r(this.callSuper("toObject",t),{objects:e})},toDatalessObject:function(t){var e,i=this.sourcePath;return e=i||this.getObjects().map(function(e){var r=e.includeDefaultValues;e.includeDefaultValues=e.group.includeDefaultValues;var i=e.toDatalessObject(t);return e.includeDefaultValues=r,i}),r(this.callSuper("toDatalessObject",t),{objects:e})},render:function(t){this._transformDone=!0,this.callSuper("render",t),this._transformDone=!1},shouldCache:function(){var t=this.objectCaching&&(!this.group||this.needsItsOwnCache()||!this.group.isOnACache());if(this.ownCaching=t,t)for(var e=0,r=this._objects.length;e<r;e++)if(this._objects[e].willDrawShadow())return this.ownCaching=!1,!1;return t},willDrawShadow:function(){if(this.shadow)return this.callSuper("willDrawShadow");for(var t=0,e=this._objects.length;t<e;t++)if(this._objects[t].willDrawShadow())return!0;return!1},isOnACache:function(){return this.ownCaching||this.group&&this.group.isOnACache()},drawObject:function(t){for(var e=0,r=this._objects.length;e<r;e++)this._objects[e].render(t)},isCacheDirty:function(){if(this.callSuper("isCacheDirty"))return!0;if(!this.statefullCache)return!1;for(var t=0,e=this._objects.length;t<e;t++)if(this._objects[t].isCacheDirty(!0)){if(this._cacheCanvas){var r=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-r/2,-i/2,r,i)}return!0}return!1},_restoreObjectsState:function(){return this._objects.forEach(this._restoreObjectState,this),this},realizeTransform:function(t){var r=t.calcTransformMatrix(),i=e.util.qrDecompose(r),n=new e.Point(i.translateX,i.translateY);return t.flipX=!1,t.flipY=!1,t.set("scaleX",i.scaleX),t.set("scaleY",i.scaleY),t.skewX=i.skewX,t.skewY=i.skewY,t.angle=i.angle,t.setPositionByOrigin(n,"center","center"),t},_restoreObjectState:function(t){return this.realizeTransform(t),t.setCoords(),delete t.group,this},destroy:function(){return this._restoreObjectsState()},toActiveSelection:function(){if(this.canvas){var t=this._objects,r=this.canvas;this._objects=[];var i=this.toObject(),n=new e.ActiveSelection([]);return n.set(i),n.type="activeSelection",r.remove(this),t.forEach(function(t){t.group=n,t.dirty=!0,r.add(t)}),n._objects=t,r._activeObject=n,n.setCoords(),n}},ungroupOnCanvas:function(){return this._restoreObjectsState()},setObjectsCoords:function(){var t=!0,e=!0;return this.forEachObject(function(t){t.setCoords(!0,!0)}),this},_calcBounds:function(t){for(var e=[],r=[],i,n,o=["tr","br","bl","tl"],a=0,s=this._objects.length,c,l=o.length,h=!0;a<s;++a)for(i=this._objects[a],i.setCoords(!0),c=0;c<l;c++)n=o[c],e.push(i.oCoords[n].x),r.push(i.oCoords[n].y);this.set(this._getBounds(e,r,t))},_getBounds:function(t,r,o){var a=new e.Point(i(t),i(r)),s=new e.Point(n(t),n(r)),c={width:s.x-a.x||0,height:s.y-a.y||0};return o||(c.left=a.x||0,c.top=a.y||0,"center"===this.originX&&(c.left+=c.width/2),"right"===this.originX&&(c.left+=c.width),"center"===this.originY&&(c.top+=c.height/2),"bottom"===this.originY&&(c.top+=c.height)),c},toSVG:function(t){var e=this._createBaseSVGMarkup();e.push("<g ",this.getSvgId(),'transform="',this.getSvgTransform(),this.getSvgTransformMatrix(),'" style="',this.getSvgFilter(),'">\n');for(var r=0,i=this._objects.length;r<i;r++)e.push("\t",this._objects[r].toSVG(t));return e.push("</g>\n"),t?t(e.join("")):e.join("")}}),e.Group.fromObject=function(t,r){e.util.enlivenObjects(t.objects,function(i){var n=e.util.object.clone(t,!0);delete n.objects,r&&r(new e.Group(i,n,!0))})})}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={});e.ActiveSelection||(e.ActiveSelection=e.util.createClass(e.Group,{type:"activeSelection",initialize:function(t,r){r=r||{},this._objects=t||[];for(var i=this._objects.length;i--;)this._objects[i].group=this;r.originX&&(this.originX=r.originX),r.originY&&(this.originY=r.originY),this._calcBounds(),this._updateObjectsCoords(),e.Object.prototype.initialize.call(this,r),this.setCoords()},toGroup:function(){var t=this._objects;this._objects=[];var r=this.toObject(),i=new e.Group([]);if(i.set(r),i.type="group",t.forEach(function(t){t.group=i,t.canvas.remove(t)}),i._objects=t,!this.canvas)return i;var n=this.canvas;return n._activeObject=i,n.add(i),i.setCoords(),i},onDeselect:function(){return this.destroy(),!1},toString:function(){return"#<fabric.ActiveSelection: ("+this.complexity()+")>"},_set:function(t,r){var i=this._objects.length;if("canvas"===t)for(;i--;)this._objects[i].set(t,r);if(this.useSetOnGroup)for(;i--;)this._objects[i].setOnGroup(t,r);e.Object.prototype._set.call(this,t,r)},shouldCache:function(){return!1},willDrawShadow:function(){if(this.shadow)return this.callSuper("willDrawShadow");for(var t=0,e=this._objects.length;t<e;t++)if(this._objects[t].willDrawShadow())return!0;return!1},isOnACache:function(){return!1},_renderControls:function(t,e,r){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",t,e),r=r||{},void 0===r.hasControls&&(r.hasControls=!1),void 0===r.hasRotatingPoint&&(r.hasRotatingPoint=!1),r.forActiveSelection=!0;for(var i=0,n=this._objects.length;i<n;i++)this._objects[i]._renderControls(t,r);t.restore()}}),e.ActiveSelection.fromObject=function(t,r){e.util.enlivenObjects(t.objects,function(i){delete t.objects,r&&r(new e.ActiveSelection(i,t,!0))})})}(exports),function(t){"use strict";var e=fabric.util.object.extend;if(t.fabric||(t.fabric={}),t.fabric.Image)return void fabric.warn("fabric.Image is already defined.");var r=fabric.Object.prototype.stateProperties.concat();r.push("cropX","cropY"),fabric.Image=fabric.util.createClass(fabric.Object,{type:"image",crossOrigin:"",strokeWidth:0,_lastScaleX:1,_lastScaleY:1,_filterScalingX:1,_filterScalingY:1,minimumScaleTrigger:.5,stateProperties:r,objectCaching:!1,cacheKey:"",cropX:0,cropY:0,initialize:function(t,e){e||(e={}),this.filters=[],this.callSuper("initialize",e),this._initElement(t,e),this.cacheKey="texture"+fabric.Object.__uid++},getElement:function(){return this._element},setElement:function(t,e){return this._element=t,this._originalElement=t,this._initConfig(e),this.resizeFilter&&this.applyResizeFilters(),0!==this.filters.length&&this.applyFilters(),this},setCrossOrigin:function(t){return this.crossOrigin=t,this._element.crossOrigin=t,this},getOriginalSize:function(){var t=this.getElement();return{width:t.width,height:t.height}},_stroke:function(t){if(this.stroke&&0!==this.strokeWidth){var e=this.width/2,r=this.height/2;t.beginPath(),t.moveTo(-e,-r),t.lineTo(e,-r),t.lineTo(e,r),t.lineTo(-e,r),t.lineTo(-e,-r),t.closePath()}},_renderDashedStroke:function(t){var e=-this.width/2,r=-this.height/2,i=this.width,n=this.height;t.save(),this._setStrokeStyles(t,this),t.beginPath(),fabric.util.drawDashedLine(t,e,r,e+i,r,this.strokeDashArray),fabric.util.drawDashedLine(t,e+i,r,e+i,r+n,this.strokeDashArray),fabric.util.drawDashedLine(t,e+i,r+n,e,r+n,this.strokeDashArray),fabric.util.drawDashedLine(t,e,r+n,e,r,this.strokeDashArray),t.closePath(),t.restore()},toObject:function(t){var r=[];this.filters.forEach(function(t){t&&r.push(t.toObject())});var i=e(this.callSuper("toObject",["crossOrigin","cropX","cropY"].concat(t)),{src:this.getSrc(),filters:r});return this.resizeFilter&&(i.resizeFilter=this.resizeFilter.toObject()),i.width/=this._filterScalingX,i.height/=this._filterScalingY,i},toSVG:function(t){var e=this._createBaseSVGMarkup(),r=-this.width/2,i=-this.height/2,n=!0;if(e.push('<g transform="',this.getSvgTransform(),this.getSvgTransformMatrix(),'">\n',"\t<image ",this.getSvgId(),'xlink:href="',this.getSvgSrc(!0),'" x="',r,'" y="',i,'" style="',this.getSvgStyles(),'" width="',this.width,'" height="',this.height,'"></image>\n'),this.stroke||this.strokeDashArray){var o=this.fill;this.fill=null,e.push("<rect ",'x="',r,'" y="',i,'" width="',this.width,'" height="',this.height,'" style="',this.getSvgStyles(),'"/>\n'),this.fill=o}return e.push("</g>\n"),t?t(e.join("")):e.join("")},getSrc:function(t){var e=t?this._element:this._originalElement;return e?fabric.isLikelyNode?e._src:e.src:this.src||""},setSrc:function(t,e,r){return fabric.util.loadImage(t,function(t){this.setElement(t,r),e(this)},this,r&&r.crossOrigin),this},toString:function(){return'#<fabric.Image: { src: "'+this.getSrc()+'" }>'},applyResizeFilters:function(){var t=this.resizeFilter,e=this.canvas?this.canvas.getRetinaScaling():1,r=this.minimumScaleTrigger,i=this.scaleX<r?this.scaleX:1,n=this.scaleY<r?this.scaleY:1;if(i*e<1&&(i*=e),n*e<1&&(n*=e),!t||i>=1&&n>=1)return void(this._element=this._filteredEl);fabric.filterBackend||(fabric.filterBackend=fabric.initFilterBackend());var o=this._filteredEl||this._originalElement,a;if(this._element===this._originalElement){var s=fabric.util.createCanvasElement();s.width=o.width,s.height=o.height,this._element=s}var c=this._element.getContext("2d");o.getContext?a=o.getContext("2d").getImageData(0,0,o.width,o.height):(c.drawImage(o,0,0),a=c.getImageData(0,0,o.width,o.height));var l={imageData:a,scaleX:i,scaleY:n};t.applyTo2d(l),this.width=this._element.width=l.imageData.width,this.height=this._element.height=l.imageData.height,c.putImageData(l.imageData,0,0)},applyFilters:function(t){if(t=t||this.filters||[],t=t.filter(function(t){return t}),0===t.length)return this._element=this._originalElement,this._filterScalingX=1,this._filterScalingY=1,this;var e=this._originalElement,r=e.naturalWidth||e.width,i=e.naturalHeight||e.height;if(this._element===this._originalElement){var n=fabric.util.createCanvasElement();n.width=e.width,n.height=e.height,this._element=n}else this._element.getContext("2d").clearRect(0,0,r,i);return fabric.filterBackend||(fabric.filterBackend=fabric.initFilterBackend()),fabric.filterBackend.applyFilters(t,this._originalElement,r,i,this._element,this.cacheKey),this.width===this._element.width&&this.height===this._element.height||(this._filterScalingX=this._element.width/this.width,this._filterScalingY=this._element.height/this.height,this.width=this._element.width,this.height=this._element.height),this},_render:function(t){var e=-this.width/2,r=-this.height/2,i;!1===this.isMoving&&this.resizeFilter&&this._needsResize()&&(this._lastScaleX=this.scaleX,this._lastScaleY=this.scaleY,this.applyResizeFilters()),i=this._element,i&&t.drawImage(i,this.cropX,this.cropY,this.width,this.height,e,r,this.width,this.height),this._stroke(t),this._renderStroke(t)},_needsResize:function(){return this.scaleX!==this._lastScaleX||this.scaleY!==this._lastScaleY},_resetWidthHeight:function(){var t=this.getElement();this.set("width",t.width),this.set("height",t.height)},_initElement:function(t,e){this.setElement(fabric.util.getById(t),e),fabric.util.addClass(this.getElement(),fabric.Image.CSS_CANVAS)},_initConfig:function(t){t||(t={}),this.setOptions(t),this._setWidthHeight(t),this._element&&this.crossOrigin&&(this._element.crossOrigin=this.crossOrigin)},_initFilters:function(t,e){t&&t.length?fabric.util.enlivenObjects(t,function(t){e&&e(t)},"fabric.Image.filters"):e&&e()},_setWidthHeight:function(t){this.width="width"in t?t.width:this.getElement()?this.getElement().width||0:0,this.height="height"in t?t.height:this.getElement()?this.getElement().height||0:0},parsePreserveAspectRatioAttribute:function(){if(this.preserveAspectRatio){var t=fabric.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio),e=this._element.width,r=this._element.height,i,n=this.width,o=this.height,a={width:n,height:o};!t||"none"===t.alignX&&"none"===t.alignY?(this.scaleX=n/e,this.scaleY=o/r):("meet"===t.meetOrSlice&&(this.width=e,this.height=r,this.scaleX=this.scaleY=i=fabric.util.findScaleToFit(this._element,a),"Mid"===t.alignX&&(this.left+=(n-e*i)/2),"Max"===t.alignX&&(this.left+=n-e*i),"Mid"===t.alignY&&(this.top+=(o-r*i)/2),"Max"===t.alignY&&(this.top+=o-r*i)),"slice"===t.meetOrSlice&&(this.scaleX=this.scaleY=i=fabric.util.findScaleToCover(this._element,a),this.width=n/i,this.height=o/i,"Mid"===t.alignX&&(this.cropX=(e-this.width)/2),"Max"===t.alignX&&(this.cropX=e-this.width),"Mid"===t.alignY&&(this.cropY=(r-this.height)/2),"Max"===t.alignY&&(this.cropY=r-this.height)))}}}),fabric.Image.CSS_CANVAS="canvas-img",fabric.Image.prototype.getSvgSrc=fabric.Image.prototype.getSrc,fabric.Image.fromObject=function(t,e){fabric.util.loadImage(t.src,function(r,i){if(i)return void(e&&e(null,i));fabric.Image.prototype._initFilters.call(t,t.filters,function(i){t.filters=i||[],fabric.Image.prototype._initFilters.call(t,[t.resizeFilter],function(i){t.resizeFilter=i[0];var n=new fabric.Image(r,t);e(n)})})},null,t.crossOrigin)},fabric.Image.fromURL=function(t,e,r){fabric.util.loadImage(t,function(t){e&&e(new fabric.Image(t,r))},null,r&&r.crossOrigin)},fabric.Image.ATTRIBUTE_NAMES=fabric.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin".split(" ")),fabric.Image.fromElement=function(t,r,i){var n=fabric.parseAttributes(t,fabric.Image.ATTRIBUTE_NAMES);fabric.Image.fromURL(n["xlink:href"],r,e(i?fabric.util.object.clone(i):{},n))}}(exports),fabric.util.object.extend(fabric.Object.prototype,{_getAngleValueForStraighten:function(){var t=this.angle%360;return t>0?90*Math.round((t-1)/90):90*Math.round(t/90)},straighten:function(){return this.setAngle(this._getAngleValueForStraighten()),this},fxStraighten:function(t){t=t||{};var e=function(){},r=t.onComplete||e,i=t.onChange||e,n=this;return fabric.util.animate({startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(t){n.setAngle(t),i()},onComplete:function(){n.setCoords(),r()},onStart:function(){n.set("active",!1)}}),this}}),fabric.util.object.extend(fabric.StaticCanvas.prototype,{straightenObject:function(t){return t.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(t){return t.fxStraighten({onChange:this.requestRenderAllBound}),this}}),function(){"use strict";function t(t){t&&t.tileSize&&(this.tileSize=t.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}fabric.isWebglSupported=function(t){if(fabric.isLikelyNode)return!1;t=t||fabric.WebglFilterBackend.prototype.tileSize;var e=document.createElement("canvas"),r=e.getContext("webgl")||e.getContext("experimental-webgl"),i=!1;return r&&(fabric.maxTextureSize=r.getParameter(r.MAX_TEXTURE_SIZE),i=fabric.maxTextureSize>=t),this.isSupported=i,i},fabric.WebglFilterBackend=t,t.prototype={tileSize:2048,resources:{},setupGLContext:function(t,e){this.dispose(),this.createWebGLCanvas(t,e),this.squareVertices=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(t,e)},chooseFastestCopyGLTo2DMethod:function(t,e){var r=void 0!==window.performance,i;try{new ImageData(1,1),i=!0}catch(t){i=!1}var n="undefined"!=typeof ArrayBuffer,o="undefined"!=typeof Uint8ClampedArray;if(r&&i&&n&&o){var a=fabric.util.createCanvasElement(),s=new ArrayBuffer(t*e*4),c={imageBuffer:s},l,h,u;a.width=t,a.height=e,l=window.performance.now(),copyGLTo2DDrawImage.call(c,this.gl,a),h=window.performance.now()-l,l=window.performance.now(),copyGLTo2DPutImageData.call(c,this.gl,a),u=window.performance.now()-l,h>u?(this.imageBuffer=s,this.copyGLTo2D=copyGLTo2DPutImageData):this.copyGLTo2D=copyGLTo2DDrawImage}},createWebGLCanvas:function(t,e){var r=fabric.util.createCanvasElement();r.width=t,r.height=e;var i={premultipliedAlpha:!1},n=r.getContext("webgl",i);n||(n=r.getContext("experimental-webgl",i)),n&&(n.clearColor(0,0,0,0),this.canvas=r,this.gl=n)},applyFilters:function(t,e,r,i,n,o){var a=this.gl,s;o&&(s=this.getCachedTexture(o,e));var c={originalWidth:e.width||e.originalWidth,originalHeight:e.height||e.originalHeight,sourceWidth:r,sourceHeight:i,context:a,sourceTexture:this.createTexture(a,r,i,!s&&e),targetTexture:this.createTexture(a,r,i),originalTexture:s||this.createTexture(a,r,i,!s&&e),passes:t.length,webgl:!0,squareVertices:this.squareVertices,programCache:this.programCache,pass:0,filterBackend:this},l=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,l),t.forEach(function(t){t&&t.applyTo(c)}),this.copyGLTo2D(a,n),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(c.sourceTexture),a.deleteTexture(c.targetTexture),a.deleteFramebuffer(l),n.getContext("2d").setTransform(1,0,0,1,0,0),c},applyFiltersDebug:function(t,e,r,i,n,o){var a=this.gl,s=this.applyFilters(t,e,r,i,n,o),c=a.getError();if(c!==a.NO_ERROR){var l=this.glErrorToString(a,c),h=new Error("WebGL Error "+l);throw h.glErrorCode=c,h}return s},glErrorToString:function(t,e){if(!t)return"Context undefined for error code: "+e;if("number"!=typeof e)return"Error code is not a number";switch(e){case t.NO_ERROR:return"NO_ERROR";case t.INVALID_ENUM:return"INVALID_ENUM";case t.INVALID_VALUE:return"INVALID_VALUE";case t.INVALID_OPERATION:return"INVALID_OPERATION";case t.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case t.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case t.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return"UNKNOWN_ERROR"}},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(t,e,r,i){var n=t.createTexture();return t.bindTexture(t.TEXTURE_2D,n),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),i?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,i):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,r,0,t.RGBA,t.UNSIGNED_BYTE,null),n},getCachedTexture:function(t,e){if(this.textureCache[t])return this.textureCache[t];var r=this.createTexture(this.gl,e.width,e.height,e);return this.textureCache[t]=r,r},evictCachesForKey:function(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])},copyGLTo2D:copyGLTo2DDrawImage,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var t=this.gl,e=t.getExtension("WEBGL_debug_renderer_info"),r={renderer:"",vendor:""};if(e){var i=t.getParameter(e.UNMASKED_RENDERER_WEBGL),n=t.getParameter(e.UNMASKED_VENDOR_WEBGL);i&&(r.renderer=i.toLowerCase()),n&&(r.vendor=n.toLowerCase())}return this.gpuInfo=r,r}}}(),function(){"use strict";function t(){}var e=function(){};fabric.Canvas2dFilterBackend=t,t.prototype={evictCachesForKey:e,dispose:e,clearWebGLCaches:e,resources:{},applyFilters:function(t,e,r,i,n){var o=n.getContext("2d");o.drawImage(e,0,0,r,i);var a=o.getImageData(0,0,r,i),s=o.getImageData(0,0,r,i),c={sourceWidth:r,sourceHeight:i,imageData:a,originalEl:e,originalImageData:s,canvasEl:n,ctx:o,filterBackend:this};return t.forEach(function(t){t.applyTo(c)}),c.imageData.width===r&&c.imageData.height===i||(n.width=c.imageData.width,n.height=c.imageData.height),o.putImageData(c.imageData,0,0),c}}}(),fabric.Image.filters=fabric.Image.filters||{},fabric.Image.filters.BaseFilter=fabric.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nattribute vec2 aTexCoord;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aTexCoord;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2d uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(t){t&&this.setOptions(t)},setOptions:function(t){for(var e in t)this[e]=t[e]},createProgram:function(t,e,r){if(this.vertexSource&&this.fragmentSource){var i=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(i,r||this.vertexSource),t.compileShader(i),!t.getShaderParameter(i,t.COMPILE_STATUS))throw new Error('Vertex shader compile error for "${this.type}": '+t.getShaderInfoLog(i));var n=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(n,e||this.fragmentSource),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Error('Fragment shader compile error for "${this.type}": '+t.getShaderInfoLog(n));var o=t.createProgram();if(t.attachShader(o,i),t.attachShader(o,n),t.linkProgram(o),!t.getProgramParameter(o,t.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+t.getProgramInfoLog(o));var a=this.getAttributeLocations(t,o),s=this.getUniformLocations(t,o)||{};return s.uStepW=t.getUniformLocation(o,"uStepW"),s.uStepH=t.getUniformLocation(o,"uStepH"),{program:o,attributeLocations:a,uniformLocations:s}}},getAttributeLocations:function(t,e){return{aPosition:t.getAttribLocation(e,"aPosition"),aTexCoord:t.getAttribLocation(e,"aTexCoord")}},getUniformLocations:function(){},sendAttributeData:function(t,e,r){["aPosition","aTexCoord"].forEach(function(i){var n=e[i],o=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,o),t.enableVertexAttribArray(n),t.vertexAttribPointer(n,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,r,t.STATIC_DRAW)})},_setupFrameBuffer:function(t){var e=t.context;t.passes>1?e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t.targetTexture,0):(e.bindFramebuffer(e.FRAMEBUFFER,null),e.finish())},_swapTextures:function(t){t.passes--,t.pass++;var e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e},isNeutralState:function(){return!1},applyTo:function(t){if(t.webgl){if(t.passes>1&&this.isNeutralState(t))return;this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)}else this.applyTo2d(t)},retrieveShader:function(t){return t.programCache.hasOwnProperty(this.type)||(t.programCache[this.type]=this.createProgram(t.context)),t.programCache[this.type]},applyToWebGL:function(t){var e=t.context,r=this.retrieveShader(t);0===t.pass&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(r.program),this.sendAttributeData(e,r.attributeLocations,t.squareVertices),e.uniform1f(r.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(r.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,r.uniformLocations),e.viewport(0,0,t.sourceWidth,t.sourceHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(t,e,r){t.activeTexture(r),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)},unbindAdditionalTexture:function(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(t){this[this.mainParameter]=t},sendUniformData:function(){},createHelpLayer:function(t){if(!t.helpLayer){var e=document.createElement("canvas");e.width=t.sourceWidth,e.height=t.sourceHeight,t.helpLayer=e}},toObject:function(){var t={type:this.type},e=this.mainParameter;return e&&(t[e]=this[e]),t},toJSON:function(){return this.toObject()}}),fabric.Image.filters.BaseFilter.fromObject=function(t,e){var r=new fabric.Image.filters[t.type](t);return e&&e(r),r},function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.Image.filters,i=e.util.createClass;r.ColorMatrix=i(r.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(t){this.callSuper("initialize",t),this.matrix=this.matrix.slice(0)},applyTo2d:function(t){var e=t.imageData,r=e.data,i=r.length,n=this.matrix,o,a,s,c,l,h=this.colorsOnly;for(l=0;l<i;l+=4)o=r[l],a=r[l+1],s=r[l+2],h?(r[l]=o*n[0]+a*n[1]+s*n[2]+255*n[4],r[l+1]=o*n[5]+a*n[6]+s*n[7]+255*n[9],r[l+2]=o*n[10]+a*n[11]+s*n[12]+255*n[14]):(c=r[l+3],r[l]=o*n[0]+a*n[1]+s*n[2]+c*n[3]+255*n[4],r[l+1]=o*n[5]+a*n[6]+s*n[7]+c*n[8]+255*n[9],r[l+2]=o*n[10]+a*n[11]+s*n[12]+c*n[13]+255*n[14],r[l+3]=o*n[15]+a*n[16]+s*n[17]+c*n[18]+255*n[19])},getUniformLocations:function(t,e){return{uColorMatrix:t.getUniformLocation(e,"uColorMatrix"),uConstants:t.getUniformLocation(e,"uConstants")}},sendUniformData:function(t,e){var r=this.matrix,i=[r[0],r[1],r[2],r[3],r[5],r[6],r[7],r[8],r[10],r[11],r[12],r[13],r[15],r[16],r[17],r[18]],n=[r[4],r[9],r[14],r[19]];t.uniformMatrix4fv(e.uColorMatrix,!1,i),t.uniform4fv(e.uConstants,n)}}),e.Image.filters.ColorMatrix.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.Image.filters,i=e.util.createClass;r.Brightness=i(r.BaseFilter,{type:"Brightness",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uBrightness;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor.rgb += uBrightness;\ngl_FragColor = color;\n}",brightness:0,mainParameter:"brightness",applyTo2d:function(t){if(0!==this.brightness){var e=t.imageData,r=e.data,i,n=r.length,o=Math.round(255*this.brightness);for(i=0;i<n;i+=4)r[i]=r[i]+o,r[i+1]=r[i+1]+o,r[i+2]=r[i+2]+o}},getUniformLocations:function(t,e){return{uBrightness:t.getUniformLocation(e,"uBrightness")}},sendUniformData:function(t,e){t.uniform1f(e.uBrightness,this.brightness)}}),e.Image.filters.Brightness.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.util.object.extend,i=e.Image.filters,n=e.util.createClass;i.Convolute=n(i.BaseFilter,{type:"Convolute",opaque:!1,matrix:[0,0,0,0,1,0,0,0,0],fragmentSource:{Convolute_3_1:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[9];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 0);\nfor (float h = 0.0; h < 3.0; h+=1.0) {\nfor (float w = 0.0; w < 3.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 1), uStepH * (h - 1));\ncolor += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 3.0 + w)];\n}\n}\ngl_FragColor = color;\n}",Convolute_3_0:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[9];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 1);\nfor (float h = 0.0; h < 3.0; h+=1.0) {\nfor (float w = 0.0; w < 3.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 1.0), uStepH * (h - 1.0));\ncolor.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 3.0 + w)];\n}\n}\nfloat alpha = texture2D(uTexture, vTexCoord).a;\ngl_FragColor = color;\ngl_FragColor.a = alpha;\n}",Convolute_5_1:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[25];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 0);\nfor (float h = 0.0; h < 5.0; h+=1.0) {\nfor (float w = 0.0; w < 5.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));\ncolor += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 5.0 + w)];\n}\n}\ngl_FragColor = color;\n}",Convolute_5_0:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[25];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 1);\nfor (float h = 0.0; h < 5.0; h+=1.0) {\nfor (float w = 0.0; w < 5.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));\ncolor.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 5.0 + w)];\n}\n}\nfloat alpha = texture2D(uTexture, vTexCoord).a;\ngl_FragColor = color;\ngl_FragColor.a = alpha;\n}",Convolute_7_1:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[49];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 0);\nfor (float h = 0.0; h < 7.0; h+=1.0) {\nfor (float w = 0.0; w < 7.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));\ncolor += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 7.0 + w)];\n}\n}\ngl_FragColor = color;\n}",Convolute_7_0:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[49];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 1);\nfor (float h = 0.0; h < 7.0; h+=1.0) {\nfor (float w = 0.0; w < 7.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));\ncolor.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 7.0 + w)];\n}\n}\nfloat alpha = texture2D(uTexture, vTexCoord).a;\ngl_FragColor = color;\ngl_FragColor.a = alpha;\n}",Convolute_9_1:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[81];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 0);\nfor (float h = 0.0; h < 9.0; h+=1.0) {\nfor (float w = 0.0; w < 9.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));\ncolor += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 9.0 + w)];\n}\n}\ngl_FragColor = color;\n}",Convolute_9_0:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[81];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 1);\nfor (float h = 0.0; h < 9.0; h+=1.0) {\nfor (float w = 0.0; w < 9.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));\ncolor.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 9.0 + w)];\n}\n}\nfloat alpha = texture2D(uTexture, vTexCoord).a;\ngl_FragColor = color;\ngl_FragColor.a = alpha;\n}"},retrieveShader:function(t){var e=Math.sqrt(this.matrix.length),r=this.type+"_"+e+"_"+this.opaque?1:0,i=this.fragmentSource[r];return t.programCache.hasOwnProperty(r)||(t.programCache[r]=this.createProgram(t.context,i)),t.programCache[r]},applyTo2d:function(t){var e=t.imageData,r=e.data,i=this.matrix,n=Math.round(Math.sqrt(i.length)),o=Math.floor(n/2),a=e.width,s=e.height,c=t.ctx.createImageData(a,s),l=c.data,h=this.opaque?1:0,u,f,d,p,g,v,m,b,y,_,w,S,x;for(w=0;w<s;w++)for(_=0;_<a;_++){for(g=4*(w*a+_),u=0,f=0,d=0,p=0,x=0;x<n;x++)for(S=0;S<n;S++)m=w+x-o,v=_+S-o,m<0||m>s||v<0||v>a||(b=4*(m*a+v),y=i[x*n+S],u+=r[b]*y,f+=r[b+1]*y,d+=r[b+2]*y,h||(p+=r[b+3]*y));l[g]=u,l[g+1]=f,l[g+2]=d,l[g+3]=h?r[g+3]:p}t.imageData=c},getUniformLocations:function(t,e){return{uMatrix:t.getUniformLocation(e,"uMatrix"),uOpaque:t.getUniformLocation(e,"uOpaque"),uHalfSize:t.getUniformLocation(e,"uHalfSize"),uSize:t.getUniformLocation(e,"uSize")}},sendUniformData:function(t,e){t.uniform1fv(e.uMatrix,this.matrix)},toObject:function(){return r(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),e.Image.filters.Convolute.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.Image.filters,i=e.util.createClass;r.Grayscale=i(r.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(t){var e=t.imageData,r=e.data,i,n=r.length,o,a=this.mode;for(i=0;i<n;i+=4)"average"===a?o=(r[i]+r[i+1]+r[i+2])/3:"lightness"===a?o=(Math.min(r[i],r[i+1],r[i+2])+Math.max(r[i],r[i+1],r[i+2]))/2:"luminosity"===a&&(o=.21*r[i]+.72*r[i+1]+.07*r[i+2]),r[i]=o,r[i+1]=o,r[i+2]=o},retrieveShader:function(t){var e=this.type+"_"+this.mode,r=this.fragmentSource[this.mode];return t.programCache.hasOwnProperty(e)||(t.programCache[e]=this.createProgram(t.context,r)),t.programCache[e]},getUniformLocations:function(t,e){return{uMode:t.getUniformLocation(e,"uMode")}},sendUniformData:function(t,e){var r=1;t.uniform1i(e.uMode,1)}}),e.Image.filters.Grayscale.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.Image.filters,i=e.util.createClass;r.Invert=i(r.BaseFilter,{type:"Invert",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uInvert;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nif (uInvert == 1) {\ngl_FragColor = vec4(1.0 - color.r,1.0 -color.g,1.0 -color.b,color.a);\n} else {\ngl_FragColor = color;\n}\n}",invert:!0,mainParameter:"invert",applyTo2d:function(t){if(this.invert){var e=t.imageData,r=e.data,i,n=r.length;for(i=0;i<n;i+=4)r[i]=255-r[i],r[i+1]=255-r[i+1],r[i+2]=255-r[i+2]}},getUniformLocations:function(t,e){return{uInvert:t.getUniformLocation(e,"uInvert")}},sendUniformData:function(t,e){t.uniform1i(e.uInvert,this.invert)}}),e.Image.filters.Invert.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.util.object.extend,i=e.Image.filters,n=e.util.createClass;i.Noise=n(i.BaseFilter,{type:"Noise",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uStepH;\nuniform float uNoise;\nuniform float uSeed;\nvarying vec2 vTexCoord;\nfloat rand(vec2 co, float seed, float vScale) {\nreturn fract(sin(dot(co.xy * vScale ,vec2(12.9898 , 78.233))) * 43758.5453 * (seed + 0.01) / 2.0);\n}\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor.rgb += (0.5 - rand(vTexCoord, uSeed, 0.1 / uStepH)) * uNoise;\ngl_FragColor = color;\n}",mainParameter:"noise",noise:0,applyTo2d:function(t){if(0!==this.noise)for(var e=t.imageData,r=e.data,i,n=r.length,o=this.noise,a,i=0,n=r.length;i<n;i+=4)a=(.5-Math.random())*o,r[i]+=a,r[i+1]+=a,r[i+2]+=a},getUniformLocations:function(t,e){return{uNoise:t.getUniformLocation(e,"uNoise"),uSeed:t.getUniformLocation(e,"uSeed")}},sendUniformData:function(t,e){t.uniform1f(e.uNoise,this.noise/255),t.uniform1f(e.uSeed,Math.random())},toObject:function(){return r(this.callSuper("toObject"),{noise:this.noise})}}),e.Image.filters.Noise.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.Image.filters,i=e.util.createClass;r.Pixelate=i(r.BaseFilter,{type:"Pixelate",blocksize:4,mainParameter:"blocksize",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uBlocksize;\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nfloat blockW = uBlocksize * uStepW;\nfloat blockH = uBlocksize * uStepW;\nint posX = int(vTexCoord.x / blockW);\nint posY = int(vTexCoord.y / blockH);\nfloat fposX = float(posX);\nfloat fposY = float(posY);\nvec2 squareCoords = vec2(fposX * blockW, fposY * blockH);\nvec4 color = texture2D(uTexture, squareCoords);\ngl_FragColor = color;\n}",applyTo2d:function(t){if(1!==this.blocksize){var e=t.imageData,r=e.data,i=e.height,n=e.width,o,a,s,c,l,h,u,f,d,p,g;for(a=0;a<i;a+=this.blocksize)for(s=0;s<n;s+=this.blocksize)for(o=4*a*n+4*s,c=r[o],l=r[o+1],h=r[o+2],u=r[o+3],p=Math.min(a+this.blocksize,i),g=Math.min(s+this.blocksize,n),f=a;f<p;f++)for(d=s;d<g;d++)o=4*f*n+4*d,r[o]=c,r[o+1]=l,r[o+2]=h,r[o+3]=u}},getUniformLocations:function(t,e){return{uBlocksize:t.getUniformLocation(e,"uBlocksize"),uStepW:t.getUniformLocation(e,"uStepW"),uStepH:t.getUniformLocation(e,"uStepH")}},sendUniformData:function(t,e){t.uniform1f(e.uBlocksize,this.blocksize)}}),e.Image.filters.Pixelate.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.util.object.extend,i=e.Image.filters,n=e.util.createClass;i.RemoveColor=n(i.BaseFilter,{type:"RemoveColor",color:"#FFFFFF",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uLow;\nuniform vec4 uHigh;\nvarying vec2 vTexCoord;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\nif(all(greaterThan(gl_FragColor.rgb,uLow.rgb)) && all(greaterThan(uHigh.rgb,gl_FragColor.rgb))) {\ngl_FragColor.a = 0.0;\n}\n}",distance:.02,useAlpha:!1,applyTo2d:function(t){var r=t.imageData,i=r.data,n,o=255*this.distance,a,s,c,l=new e.Color(this.color).getSource(),h=[l[0]-o,l[1]-o,l[2]-o],u=[l[0]+o,l[1]+o,l[2]+o];for(n=0;n<i.length;n+=4)a=i[n],s=i[n+1],c=i[n+2],a>h[0]&&s>h[1]&&c>h[2]&&a<u[0]&&s<u[1]&&c<u[2]&&(i[n+3]=0)},getUniformLocations:function(t,e){return{uLow:t.getUniformLocation(e,"uLow"),uHigh:t.getUniformLocation(e,"uHigh")}},sendUniformData:function(t,r){var i=new e.Color(this.color).getSource(),n=parseFloat(this.distance),o=[0+i[0]/255-n,0+i[1]/255-n,0+i[2]/255-n,1],a=[i[0]/255+n,i[1]/255+n,i[2]/255+n,1];t.uniform4fv(r.uLow,o),t.uniform4fv(r.uHigh,a)},toObject:function(){return r(this.callSuper("toObject"),{color:this.color,distance:this.distance})}}),e.Image.filters.RemoveColor.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.Image.filters,i=e.util.createClass,n={Brownie:[.5997,.34553,-.27082,0,.186,-.0377,.86095,.15059,0,-.1449,.24113,-.07441,.44972,0,-.02965,0,0,0,1,0],Vintage:[.62793,.32021,-.03965,0,.03784,.02578,.64411,.03259,0,.02926,.0466,-.08512,.52416,0,.02023,0,0,0,1,0],Kodachrome:[1.12855,-.39673,-.03992,0,.24991,-.16404,1.08352,-.05498,0,.09698,-.16786,-.56034,1.60148,0,.13972,0,0,0,1,0],Technicolor:[1.91252,-.85453,-.09155,0,.04624,-.30878,1.76589,-.10601,0,-.27589,-.2311,-.75018,1.84759,0,.12137,0,0,0,1,0],Polaroid:[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0],Sepia:[.393,.769,.189,0,0,.349,.686,.168,0,0,.272,.534,.131,0,0,0,0,0,1,0],BlackWhite:[1.5,1.5,1.5,0,-1,1.5,1.5,1.5,0,-1,1.5,1.5,1.5,0,-1,0,0,0,1,0]};for(var o in n)r[o]=i(r.ColorMatrix,{type:o,matrix:n[o],mainParameter:!1,colorsOnly:!0}),e.Image.filters[o].fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric,r=e.Image.filters,i=e.util.createClass;r.BlendColor=i(r.BaseFilter,{type:"BlendColor",color:"#F95C63",mode:"multiply",alpha:1,fragmentSource:{multiply:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor.rgb *= uColor.rgb;\ngl_FragColor = color;\n}",screen:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor.rgb = 1.0 - (1.0 - color.rgb) * (1.0 - uColor.rgb);\ngl_FragColor = color;\n}",add:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\ngl_FragColor.rgb += uColor.rgb;\n}",diff:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\ngl_FragColor.rgb = abs(gl_FragColor.rgb - uColor.rgb);\n}",subtract:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\ngl_FragColor.rgb -= uColor.rgb;\n}",lighten:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\ngl_FragColor.rgb = max(gl_FragColor.rgb, uColor.rgb);\n}",darken:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\ngl_FragColor.rgb = min(gl_FragColor.rgb, uColor.rgb);\n}",exclusion:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\ngl_FragColor.rgb += uColor.rgb - 2.0 * (uColor.rgb * gl_FragColor.rgb);\n}",overlay:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\nif (uColor.r < 0.5) {\ngl_FragColor.r *= 2.0 * uColor.r;\n} else {\ngl_FragColor.r = 1.0 - 2.0 * (1.0 - gl_FragColor.r) * (1.0 - uColor.r);\n}\nif (uColor.g < 0.5) {\ngl_FragColor.g *= 2.0 * uColor.g;\n} else {\ngl_FragColor.g = 1.0 - 2.0 * (1.0 - gl_FragColor.g) * (1.0 - uColor.g);\n}\nif (uColor.b < 0.5) {\ngl_FragColor.b *= 2.0 * uColor.b;\n} else {\ngl_FragColor.b = 1.0 - 2.0 * (1.0 - gl_FragColor.b) * (1.0 - uColor.b);\n}\n}",tint:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\ngl_FragColor.rgb *= (1.0 - uColor.a);\ngl_FragColor.rgb += uColor.rgb;\n}"},retrieveShader:function(t){var e=this.type+"_"+this.mode,r=this.fragmentSource[this.mode];return t.programCache.hasOwnProperty(e)||(t.programCache[e]=this.createProgram(t.context,r)),t.programCache[e]},applyTo2d:function(t){var r=t.imageData,i=r.data,n=i.length,o,a,s,c,l,h,u,f=1-this.alpha;u=new e.Color(this.color).getSource(),o=u[0]*this.alpha,a=u[1]*this.alpha,s=u[2]*this.alpha;for(var d=0;d<n;d+=4)switch(c=i[d],l=i[d+1],h=i[d+2],this.mode){case"multiply":i[d]=c*o/255,i[d+1]=l*a/255,i[d+2]=h*s/255;break;case"screen":i[d]=255-(255-c)*(255-o)/255,i[d+1]=255-(255-l)*(255-a)/255,i[d+2]=255-(255-h)*(255-s)/255;break;case"add":i[d]=c+o,i[d+1]=l+a,i[d+2]=h+s;break;case"diff":case"difference":i[d]=Math.abs(c-o),i[d+1]=Math.abs(l-a),i[d+2]=Math.abs(h-s);break;case"subtract":i[d]=c-o,i[d+1]=l-a,i[d+2]=h-s;break;case"darken":i[d]=Math.min(c,o),i[d+1]=Math.min(l,a),i[d+2]=Math.min(h,s);break;case"lighten":i[d]=Math.max(c,o),i[d+1]=Math.max(l,a),i[d+2]=Math.max(h,s);break;case"overlay":i[d]=o<128?2*c*o/255:255-2*(255-c)*(255-o)/255,i[d+1]=a<128?2*l*a/255:255-2*(255-l)*(255-a)/255,i[d+2]=s<128?2*h*s/255:255-2*(255-h)*(255-s)/255;break;case"exclusion":i[d]=o+c-2*o*c/255,i[d+1]=a+l-2*a*l/255,i[d+2]=s+h-2*s*h/255;break;case"tint":i[d]=o+c*f,i[d+1]=a+l*f,i[d+2]=s+h*f}},getUniformLocations:function(t,e){return{uColor:t.getUniformLocation(e,"uColor")}},sendUniformData:function(t,r){var i=new e.Color(this.color).getSource();i[0]=this.alpha*i[0]/255,i[1]=this.alpha*i[1]/255,i[2]=this.alpha*i[2]/255,i[3]=this.alpha,t.uniform4fv(r.uColor,i)},toObject:function(){return{type:this.type,color:this.color,mode:this.mode,alpha:this.alpha}}}),e.Image.filters.BlendColor.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric,r=e.Image.filters,i=e.util.createClass;r.BlendImage=i(r.BaseFilter,{type:"BlendImage",image:null,mode:"multiply",alpha:1,vertexSource:"attribute vec2 aPosition;\nattribute vec2 aTexCoord;\nvarying vec2 vTexCoord;\nvarying vec2 vTexCoord2;\nuniform mat3 uTransformMatrix;\nvoid main() {\nvTexCoord = aTexCoord;\nvTexCoord2 = (uTransformMatrix * vec3(aTexCoord, 1.0)).xy;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:{multiply:"precision highp float;\nuniform sampler2D uTexture;\nuniform sampler2D uImage;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvarying vec2 vTexCoord2;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec4 color2 = texture2D(uImage, vTexCoord2);\ncolor.rgba *= color2.rgba;\ngl_FragColor = color;\n}",mask:"precision highp float;\nuniform sampler2D uTexture;\nuniform sampler2D uImage;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvarying vec2 vTexCoord2;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec4 color2 = texture2D(uImage, vTexCoord2);\ncolor.a = color2.a;\ngl_FragColor = color;\n}"},retrieveShader:function(t){var e=this.type+"_"+this.mode,r=this.fragmentSource[this.mode];return t.programCache.hasOwnProperty(e)||(t.programCache[e]=this.createProgram(t.context,r)),t.programCache[e]},applyToWebGL:function(t){var e=t.context,r=this.createTexture(t.filterBackend,this.image);this.bindAdditionalTexture(e,r,e.TEXTURE1),this.callSuper("applyToWebGL",t),this.unbindAdditionalTexture(e,e.TEXTURE1)},createTexture:function(t,e){return t.getCachedTexture(e.cacheKey,e._element)},calculateMatrix:function(){var t=this.image,e=t._element.width,r=t._element.height;return[1/t.scaleX,0,0,0,1/t.scaleY,0,-t.left/e,-t.top/r,1]},applyTo2d:function(t){var e=t.imageData,r=t.filterBackend.resources,i=e.data,n=i.length,o=t.imageData.width,a=t.imageData.height,s,c,l,h,u,f,d,p,g,v,m=this.image,b;r.blendImage||(r.blendImage=document.createElement("canvas")),g=r.blendImage,g.width===o&&g.height===a||(g.width=o,g.height=a),v=g.getContext("2d"),v.setTransform(m.scaleX,0,0,m.scaleY,m.left,m.top),v.drawImage(m._element,0,0,o,a),b=v.getImageData(0,0,o,a).data;for(var y=0;y<n;y+=4)switch(u=i[y],f=i[y+1],d=i[y+2],p=i[y+3],s=b[y],c=b[y+1],l=b[y+2],h=b[y+3],this.mode){case"multiply":i[y]=u*s/255,i[y+1]=f*c/255,i[y+2]=d*l/255,i[y+3]=p*h/255;break;case"mask":i[y+3]=h}},getUniformLocations:function(t,e){return{uTransformMatrix:t.getUniformLocation(e,"uTransformMatrix"),uImage:t.getUniformLocation(e,"uImage")}},sendUniformData:function(t,e){var r=this.calculateMatrix();t.uniform1i(e.uImage,1),t.uniformMatrix3fv(e.uTransformMatrix,!1,r)},toObject:function(){return{type:this.type,image:this.image&&this.image.toObject(),mode:this.mode,alpha:this.alpha}}}),e.Image.filters.BlendImage.fromObject=function(t,r){e.Image.fromObject(t.image,function(i){var n=e.util.object.clone(t);n.image=i,r(new e.Image.filters.BlendImage(n))})}}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=Math.pow,i=Math.floor,n=Math.sqrt,o=Math.abs,a=Math.round,s=Math.sin,c=Math.ceil,l=e.Image.filters,h=e.util.createClass;l.Resize=h(l.BaseFilter,{type:"Resize",resizeType:"hermite",scaleX:0,scaleY:0,lanczosLobes:3,applyTo2d:function(t){var e=t.imageData,r=t.scaleX||this.scaleX,i=t.scaleY||this.scaleY;if(1!==r||1!==i){this.rcpScaleX=1/r,this.rcpScaleY=1/i;var n=e.width,o=e.height,s=a(n*r),c=a(o*i),l;"sliceHack"===this.resizeType?l=this.sliceByTwo(t,n,o,s,c):"hermite"===this.resizeType?l=this.hermiteFastResize(t,n,o,s,c):"bilinear"===this.resizeType?l=this.bilinearFiltering(t,n,o,s,c):"lanczos"===this.resizeType&&(l=this.lanczosResize(t,n,o,s,c)),t.imageData=l}},sliceByTwo:function(t,r,n,o,a){var s=t.imageData,c=.5,l=!1,h=!1,u=.5*r,f=.5*n,d=e.filterBackend.resources,p,g,v=0,m=0,b=r,y=0;for(d.sliceByTwo||(d.sliceByTwo=document.createElement("canvas")),p=d.sliceByTwo,(p.width<1.5*r||p.height<n)&&(p.width=1.5*r,p.height=n),g=p.getContext("2d"),g.clearRect(0,0,1.5*r,n),g.putImageData(s,0,0),o=i(o),a=i(a);!l||!h;)r=u,n=f,o<i(.5*u)?u=i(.5*u):(u=o,l=!0),a<i(.5*f)?f=i(.5*f):(f=a,h=!0),g.drawImage(p,v,m,r,n,b,y,u,f),v=b,m=y,y+=f;return g.getImageData(v,m,o,a)},lanczosResize:function(t,e,a,l,h){function u(t){return function(e){if(e>t)return 0;if(e*=Math.PI,o(e)<1e-16)return 1;var r=e/t;return s(e)*s(r)/e/r}}function f(t){var s,c,u,T,k,P,E,O,R,L,D;for(C.x=(t+.5)*m,A.x=i(C.x),s=0;s<h;s++){for(C.y=(s+.5)*b,A.y=i(C.y),k=0,P=0,E=0,O=0,R=0,c=A.x-w;c<=A.x+w;c++)if(!(c<0||c>=e)){L=i(1e3*o(c-C.x)),x[L]||(x[L]={});for(var I=A.y-S;I<=A.y+S;I++)I<0||I>=a||(D=i(1e3*o(I-C.y)),x[L][D]||(x[L][D]=v(n(r(L*y,2)+r(D*_,2))/1e3)),(u=x[L][D])>0&&(T=4*(I*e+c),k+=u,P+=u*d[T],E+=u*d[T+1],O+=u*d[T+2],R+=u*d[T+3]))}T=4*(s*l+t),g[T]=P/k,g[T+1]=E/k,g[T+2]=O/k,g[T+3]=R/k}return++t<l?f(t):p}var d=t.imageData.data,p=t.ctx.creteImageData(l,h),g=p.data,v=u(this.lanczosLobes),m=this.rcpScaleX,b=this.rcpScaleY,y=2/this.rcpScaleX,_=2/this.rcpScaleY,w=c(m*this.lanczosLobes/2),S=c(b*this.lanczosLobes/2),x={},C={},A={};return f(0)},bilinearFiltering:function(t,e,r,n,o){var a,s,c,l,h,u,f,d,p,g,v,m,b=0,y,_=this.rcpScaleX,w=this.rcpScaleY,S=4*(e-1),x=t.imageData,C=x.data,A=t.ctx.createImageData(n,o),T=A.data;for(f=0;f<o;f++)for(d=0;d<n;d++)for(h=i(_*d),u=i(w*f),p=_*d-h,g=w*f-u,y=4*(u*e+h),v=0;v<4;v++)a=C[y+v],s=C[y+4+v],c=C[y+S+v],l=C[y+S+4+v],m=a*(1-p)*(1-g)+s*p*(1-g)+c*g*(1-p)+l*p*g,T[b++]=m;return A},hermiteFastResize:function(t,e,r,a,s){for(var l=this.rcpScaleX,h=this.rcpScaleY,u=c(l/2),f=c(h/2),d=t.imageData,p=d.data,g=t.ctx.createImageData(a,s),v=g.data,m=0;m<s;m++)for(var b=0;b<a;b++){for(var y=4*(b+m*a),_=0,w=0,S=0,x=0,C=0,A=0,T=0,k=(m+.5)*h,P=i(m*h);P<(m+1)*h;P++)for(var E=o(k-(P+.5))/f,O=(b+.5)*l,R=E*E,L=i(b*l);L<(b+1)*l;L++){var D=o(O-(L+.5))/u,I=n(R+D*D);I>1&&I<-1||(_=2*I*I*I-3*I*I+1)>0&&(D=4*(L+P*e),T+=_*p[D+3],S+=_,p[D+3]<255&&(_=_*p[D+3]/250),x+=_*p[D],C+=_*p[D+1],A+=_*p[D+2],w+=_)}v[y]=x/w,v[y+1]=C/w,v[y+2]=A/w,v[y+3]=T/S}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),e.Image.filters.Resize.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.Image.filters,i=e.util.createClass;r.Contrast=i(r.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(t){if(0!==this.contrast){var e=t.imageData,r,i,n=e.data,i=n.length,o=Math.floor(255*this.contrast),a=259*(o+255)/(255*(259-o));for(r=0;r<i;r+=4)n[r]=a*(n[r]-128)+128,n[r+1]=a*(n[r+1]-128)+128,n[r+2]=a*(n[r+2]-128)+128}},getUniformLocations:function(t,e){return{uContrast:t.getUniformLocation(e,"uContrast")}},sendUniformData:function(t,e){t.uniform1f(e.uContrast,this.contrast)}}),e.Image.filters.Contrast.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.Image.filters,i=e.util.createClass;r.Saturation=i(r.BaseFilter,{type:"Saturation",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uSaturation;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat rgMax = max(color.r, color.g);\nfloat rgbMax = max(rgMax, color.b);\ncolor.r += rgbMax != color.r ? (rgbMax - color.r) * uSaturation : 0.00;\ncolor.g += rgbMax != color.g ? (rgbMax - color.g) * uSaturation : 0.00;\ncolor.b += rgbMax != color.b ? (rgbMax - color.b) * uSaturation : 0.00;\ngl_FragColor = color;\n}",saturation:0,mainParameter:"saturation",applyTo2d:function(t){if(0!==this.saturation){var e=t.imageData,r=e.data,i=r.length,n=-this.saturation,o,a;for(o=0;o<i;o+=4)a=Math.max(r[o],r[o+1],r[o+2]),r[o]+=a!==r[o]?(a-r[o])*n:0,r[o+1]+=a!==r[o+1]?(a-r[o+1])*n:0,r[o+2]+=a!==r[o+2]?(a-r[o+2])*n:0}},getUniformLocations:function(t,e){return{uSaturation:t.getUniformLocation(e,"uSaturation")}},sendUniformData:function(t,e){t.uniform1f(e.uSaturation,-this.saturation)}}),e.Image.filters.Saturation.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.Image.filters,i=e.util.createClass;r.Blur=i(r.BaseFilter,{type:"Blur",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec2 uDelta;\nvarying vec2 vTexCoord;\nconst float nSamples = 15.0;\nvec3 v3offset = vec3(12.9898, 78.233, 151.7182);\nfloat random(vec3 scale) {\nreturn fract(sin(dot(gl_FragCoord.xyz, scale)) * 43758.5453);\n}\nvoid main() {\nvec4 color = vec4(0.0);\nfloat total = 0.0;\nfloat offset = random(v3offset);\nfor (float t = -nSamples; t <= nSamples; t++) {\nfloat percent = (t + offset - 0.5) / nSamples;\nfloat weight = 1.0 - abs(percent);\ncolor += texture2D(uTexture, vTexCoord + uDelta * percent) * weight;\ntotal += weight;\n}\ngl_FragColor = color / total;\n}",blur:0,mainParameter:"blur",applyTo:function(t){t.webgl?(this.aspectRatio=t.sourceWidth/t.sourceHeight,t.passes++,this._setupFrameBuffer(t),this.horizontal=!0,this.applyToWebGL(t),this._swapTextures(t),this._setupFrameBuffer(t),this.horizontal=!1,this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)},applyTo2d:function(t){t.imageData=this.simpleBlur(t)},simpleBlur:function(t){var e=t.filterBackend.resources,r,i,n=t.imageData.width,o=t.imageData.height;e.blurLayer1||(e.blurLayer1=document.createElement("canvas"),e.blurLayer2=document.createElement("canvas")),r=e.blurLayer1,i=e.blurLayer2,r.width===n&&r.height===o||(i.width=r.width=n,i.height=r.height=o);var a=r.getContext("2d"),s=i.getContext("2d"),c=15,l,h,u,f,d=.06*this.blur*.5;for(a.putImageData(t.imageData,0,0),s.clearRect(0,0,n,o),f=-15;f<=15;f++)l=(Math.random()-.5)/4,h=f/15,u=d*h*n+l,s.globalAlpha=1-Math.abs(h),s.drawImage(r,u,l),a.drawImage(i,0,0),s.globalAlpha=1,s.clearRect(0,0,i.width,i.height);for(f=-15;f<=15;f++)l=(Math.random()-.5)/4,h=f/15,u=d*h*o+l,s.globalAlpha=1-Math.abs(h),s.drawImage(r,l,u),a.drawImage(i,0,0),s.globalAlpha=1,s.clearRect(0,0,i.width,i.height);t.ctx.drawImage(r,0,0);var p=t.ctx.getImageData(0,0,r.width,r.height);return a.globalAlpha=1,a.clearRect(0,0,r.width,r.height),p},getUniformLocations:function(t,e){return{delta:t.getUniformLocation(e,"uDelta")}},sendUniformData:function(t,e){var r=this.chooseRightDelta();t.uniform2fv(e.delta,r)},chooseRightDelta:function(){var t=1,e=[0,0],r;return this.horizontal?this.aspectRatio>1&&(t=1/this.aspectRatio):this.aspectRatio<1&&(t=this.aspectRatio),r=t*this.blur*.12,this.horizontal?e[0]=r:e[1]=r,e}}),r.Blur.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.Image.filters,i=e.util.createClass;r.Gamma=i(r.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",applyTo2d:function(t){var e=t.imageData,r=e.data,i=this.gamma,n=r.length,o=1/i[0],a=1/i[1],s=1/i[2],c;for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),c=0,n=256;c<n;c++)this.rVals[c]=255*Math.pow(c/255,o),this.gVals[c]=255*Math.pow(c/255,a),this.bVals[c]=255*Math.pow(c/255,s);for(c=0,n=r.length;c<n;c+=4)r[c]=this.rVals[r[c]],r[c+1]=this.gVals[r[c+1]],r[c+2]=this.bVals[r[c+2]]},getUniformLocations:function(t,e){return{uGamma:t.getUniformLocation(e,"uGamma")}},sendUniformData:function(t,e){t.uniform3fv(e.uGamma,this.gamma)}}),e.Image.filters.Gamma.fromObject=e.Image.filters.BaseFilter.fromObject}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.Image.filters,i=e.util.createClass;r.Composed=i(r.BaseFilter,{type:"Composed",subFilters:[],initialize:function(t){this.callSuper("initialize",t),this.subFilters=this.subFilters.slice(0)},applyTo:function(t){t.passes+=this.subFilters.length-1,this.subFilters.forEach(function(e){e.applyTo(t)})},toObject:function(){return e.util.object.extend(this.callSuper("toObject"),{subFilters:this.subFilters.map(function(t){return t.toObject()})})}}),e.Image.filters.Composed.fromObject=function(t,r){var i=t.subFilters||[],n=i.map(function(t){return new e.Image.filters[t.type](t)}),o=new e.Image.filters.Composed({subFilters:n});return r&&r(o),o}}(exports),function(t){"use strict";var e=t.fabric||(t.fabric={}),r=e.util.object.clone,i=2,n=200;if(e.Text)return void e.warn("fabric.Text is already defined");var o=e.Object.prototype.stateProperties.concat();o.push("fontFamily","fontWeight","fontSize","text","underline","overline","linethrough","textAlign","fontStyle","lineHeight","textBackgroundColor","charSpacing","styles");var a=e.Object.prototype.cacheProperties.concat();a.push("fontFamily","fontWeight","fontSize","text","underline","overline","linethrough","textAlign","fontStyle","lineHeight","textBackgroundColor","charSpacing","styles"),e.Text=e.util.createClass(e.Object,{_dimensionAffectingProps:["fontSize","fontWeight","fontFamily","fontStyle","lineHeight","text","charSpacing","textAlign","styles"],_reNewline:/\r?\n/,_reSpacesAndTabs:/[ \t\r]/g,_reSpaceAndTab:/[ \t\r]/,_reWords:/\S+/g,type:"text",fontSize:40,fontWeight:"normal",fontFamily:"Times New Roman",underline:!1,overline:!1,linethrough:!1,textAlign:"left",fontStyle:"normal",lineHeight:1.16,textBackgroundColor:"",stateProperties:o,cacheProperties:a,stroke:null,shadow:null,_fontSizeFraction:.222,offsets:{underline:.1,linethrough:-.315,overline:-.88},_fontSizeMult:1.13,charSpacing:0,styles:null,_measuringContext:null,_styleProperties:["stroke","strokeWidth","fill","fontFamily","fontSize","fontWeight","fontStyle","underline","overline","linethrough"],__charBounds:[],initialize:function(t,e){e=e||{},this.text=t,this.__skipDimension=!0,this.callSuper("initialize",e),this.__skipDimension=!1,this.initDimensions(),this.setCoords(),this.setupState({propertySet:"_dimensionAffectingProps"})},getMeasuringContext:function(){return e._measuringContext||(e._measuringContext=this.canvas&&this.canvas.contextCache||e.util.createCanvasElement().getContext("2d")),e._measuringContext},isEmptyStyles:function(t){if(!this.styles)return!0;if(void 0!==t&&!this.styles[t])return!0;var e=void 0===t?this.styles:{line:this.styles[t]};for(var r in e)for(var i in e[r])for(var n in e[r][i])return!1;return!0},styleHas:function(t,e){if(!this.styles||!t||""===t)return!1;if(void 0!==e&&!this.styles[e])return!1;var r=void 0===e?this.styles:{line:this.styles[e]};for(var i in r)for(var n in r[i])if(void 0!==r[i][n][t])return!0;return!1},cleanStyle:function(t){if(!this.styles||!t||""===t)return!1;var e=this.styles,r=0,i,n=!1,o,a=!0,s=0;for(var c in e){i=0;for(var l in e[c])r++,n?e[c][l][t]!==o&&(a=!1):(o=e[c][l][t],n=!0),e[c][l][t]===this[t]&&delete e[c][l][t],0!==Object.keys(e[c][l]).length?i++:delete e[c][l];0===i&&delete e[c]}for(var h=0;h<this._textLines.length;h++)s+=this._textLines[h].length;a&&r===s&&(this[t]=o,this.removeStyle(t))},removeStyle:function(t){if(this.styles&&t&&""!==t){var e=this.styles,r,i,n;for(i in e){var r=e[i];for(n in r)delete r[n][t],0===Object.keys(r[n]).length&&delete r[n];0===Object.keys(r).length&&delete e[i]}}},_extendStyles:function(t,r){var i=this.get2DCursorLocation(t);this._getLineStyle(i.lineIndex)||this._setLineStyle(i.lineIndex,{}),this._getStyleDeclaration(i.lineIndex,i.charIndex)||this._setStyleDeclaration(i.lineIndex,i.charIndex,{}),e.util.object.extend(this._getStyleDeclaration(i.lineIndex,i.charIndex),r)},initDimensions:function(){if(!this.__skipDimension){var t=this._splitTextIntoLines(this.text);this.textLines=t.lines,this._unwrappedTextLines=t._unwrappedLines,this._textLines=t.graphemeLines,this._text=t.graphemeText,this._clearCache(),this.width=this.calcTextWidth()||this.cursorWidth||2,"justify"===this.textAlign&&this.enlargeSpaces(),this.height=this.calcTextHeight()}},enlargeSpaces:function(){for(var t,e,r,i,n,o,a,s=0,c=this._textLines.length;s<c;s++)if(i=0,n=this._textLines[s],(e=this.getLineWidth(s))<this.width&&(a=this.textLines[s].match(this._reSpacesAndTabs))){r=a.length,t=(this.width-e)/r;for(var l=0,h=n.length;l<=h;l++)o=this.__charBounds[s][l],this._reSpaceAndTab.test(n[l])?(o.width+=t,o.kernedWidth+=t,o.left+=i,i+=t):o.left+=i}},toString:function(){return"#<fabric.Text ("+this.complexity()+'): { "text": "'+this.text+'", "fontFamily": "'+this.fontFamily+'" }>'},_getCacheCanvasDimensions:function(){var t=this.callSuper("_getCacheCanvasDimensions"),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t},_render:function(t){this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")},_renderText:function(t){this._renderTextFill(t),this._renderTextStroke(t)},_setTextStyles:function(t,e,r){t.textBaseline="alphabetic",t.font=this._getFontDeclaration(e,r)},calcTextWidth:function(){for(var t=this.getLineWidth(0),e=1,r=this._textLines.length;e<r;e++){var i=this.getLineWidth(e);i>t&&(t=i)}return t},_renderTextLine:function(t,e,r,i,n,o){this._renderChars(t,e,r,i,n,o)},_renderTextLinesBackground:function(t){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var e=0,r,i,n=t.fillStyle,o,a,s=this._getLeftOffset(),c=this._getTopOffset(),l=0,h=0,u,f,d=0,p=this._textLines.length;d<p;d++)if(r=this.getHeightOfLine(d),this.textBackgroundColor||this.styleHas("textBackgroundColor",d)){o=this._textLines[d],i=this._getLineLeftOffset(d),h=0,l=0,a=this.getValueOfPropertyAt(d,0,"textBackgroundColor");for(var g=0,v=o.length;g<v;g++)u=this.__charBounds[d][g],f=this.getValueOfPropertyAt(d,g,"textBackgroundColor"),f!==a?(t.fillStyle=a,a&&t.fillRect(s+i+l,c+e,h,r/this.lineHeight),l=u.left,h=u.width,a=f):h+=u.kernedWidth;f&&(t.fillStyle=f,t.fillRect(s+i+l,c+e,h,r/this.lineHeight)),e+=r}else e+=r;t.fillStyle=n,this._removeShadow(t)}},getFontCache:function(t){var r=t.fontFamily.toLowerCase();e.charWidthsCache[r]||(e.charWidthsCache[r]={});var i=e.charWidthsCache[r],n=t.fontStyle.toLowerCase()+"_"+(t.fontWeight+"").toLowerCase();return i[n]||(i[n]={}),i[n]},_applyCharStyles:function(t,e,r,i,n){this._setFillStyles(e,n),this._setStrokeStyles(e,n),e.font=this._getFontDeclaration(n)},_getStyleDeclaration:function(t,e){var r=this.styles&&this.styles[t];return r?r[e]:null},getCompleteStyleDeclaration:function(t,e){for(var r=this._getStyleDeclaration(t,e)||{},i={},n,o=0;o<this._styleProperties.length;o++)n=this._styleProperties[o],i[n]=void 0===r[n]?this[n]:r[n];return i},_setStyleDeclaration:function(t,e,r){this.styles[t][e]=r},_deleteStyleDeclaration:function(t,e){delete this.styles[t][e]},_getLineStyle:function(t){return this.styles[t]},_setLineStyle:function(t,e){this.styles[t]=e},_deleteLineStyle:function(t){delete this.styles[t]},_measureChar:function(t,e,r,i){var n=this.getFontCache(e),o=this._getFontDeclaration(e),a=this._getFontDeclaration(i),s=r+t,c=o===a,l,h,u,f=e.fontSize/200,d;if(r&&n[r]&&(u=n[r]),n[t]&&(d=l=n[t]),c&&n[s]&&(h=n[s],d=h-u),!l||!u||!h){var p=this.getMeasuringContext();this._setTextStyles(p,e,!0)}if(l||(d=l=p.measureText(t).width,n[t]=l),!u&&c&&r&&(u=p.measureText(r).width,n[r]=u),c&&!h&&(h=p.measureText(s).width,n[s]=h,(d=h-u)>l)){var g=d-l;n[t]=d,n[s]+=g,l=d}return{width:l*f,kernedWidth:d*f}},getHeightOfChar:function(t,e){return this.getValueOfPropertyAt(t,e,"fontSize")},measureLine:function(t){var e=this._measureLine(t);return 0!==this.charSpacing&&(e.width-=this._getWidthOfCharSpacing()),e.width<0&&(e.width=0),e},_measureLine:function(t){var e=0,r,i,n=this._textLines[t],o,a,s=0,c=new Array(n.length);for(this.__charBounds[t]=c,r=0;r<n.length;r++)i=n[r],a=this._getGraphemeBox(i,t,r,o),c[r]=a,e+=a.kernedWidth,o=i;return c[r]={left:a?a.left+a.width:0,width:0,kernedWidth:0,height:this.fontSize},{width:e,numOfSpaces:0}},_getGraphemeBox:function(t,e,r,i,n){var o=this.getCompleteStyleDeclaration(e,r),a=i?this.getCompleteStyleDeclaration(e,r-1):{},s=this._measureChar(t,o,i,a),c=s.kernedWidth,l=s.width;0!==this.charSpacing&&(l+=this._getWidthOfCharSpacing(),c+=this._getWidthOfCharSpacing());var h={width:l,left:0,height:o.fontSize,kernedWidth:c};if(r>0&&!n){var u=this.__charBounds[e][r-1];h.left=u.left+u.width+s.kernedWidth-s.width}return h},getHeightOfLine:function(t){if(this.__lineHeights[t])return this.__lineHeights[t];for(var e=this._textLines[t],r=this.getHeightOfChar(t,0),i=1,n=e.length;i<n;i++){var o=this.getHeightOfChar(t,i);o>r&&(r=o)}return this.__lineHeights[t]=r*this.lineHeight*this._fontSizeMult,this.__lineHeights[t]},calcTextHeight:function(){for(var t,e=0,r=0,i=this._textLines.length;r<i;r++)t=this.getHeightOfLine(r),e+=r===i-1?t/this.lineHeight:t;return e},_getLeftOffset:function(){return-this.width/2},_getTopOffset:function(){return-this.height/2},_renderTextCommon:function(t,e){for(var r=0,i=this._getLeftOffset(),n=this._getTopOffset(),o=0,a=this._textLines.length;o<a;o++){var s=this.getHeightOfLine(o),c=s/this.lineHeight,l=this._getLineLeftOffset(o);this._renderTextLine(e,t,this._textLines[o],i+l,n+r+c,o),r+=s}},_renderTextFill:function(t){(this.fill||this.styleHas("fill"))&&this._renderTextCommon(t,"fillText")},_renderTextStroke:function(t){(this.stroke&&0!==this.strokeWidth||!this.isEmptyStyles())&&(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this._setLineDash(t,this.strokeDashArray),t.beginPath(),this._renderTextCommon(t,"strokeText"),t.closePath(),t.restore())},_renderChars:function(t,e,r,i,n,o){var a=this.getHeightOfLine(o),s,c,l="",h,u=0,f;e.save(),n-=a*this._fontSizeFraction/this.lineHeight;for(var d=0,p=r.length-1;d<=p;d++)f=d===p||this.charSpacing,l+=r[d],h=this.__charBounds[o][d],0===u&&(i+=h.kernedWidth-h.width),u+=h.kernedWidth,"justify"!==this.textAlign||f||this._reSpaceAndTab.test(r[d])&&(f=!0),f||(s=s||this.getCompleteStyleDeclaration(o,d),c=this.getCompleteStyleDeclaration(o,d+1),f=this._hasStyleChanged(s,c)),f&&(this._renderChar(t,e,o,d,l,i,n,a),l="",s=c,i+=u,u=0);e.restore()},_renderChar:function(t,e,r,i,n,o,a){var s=this._getStyleDeclaration(r,i),c=this.getCompleteStyleDeclaration(r,i),l="fillText"===t&&c.fill,h="strokeText"===t&&c.stroke&&c.strokeWidth;(h||l)&&(s&&e.save(),this._applyCharStyles(t,e,r,i,c),s&&s.textBackgroundColor&&this._removeShadow(e),l&&e.fillText(n,o,a),h&&e.strokeText(n,o,a),s&&e.restore())},_hasStyleChanged:function(t,e){return t.fill!==e.fill||t.stroke!==e.stroke||t.strokeWidth!==e.strokeWidth||t.fontSize!==e.fontSize||t.fontFamily!==e.fontFamily||t.fontWeight!==e.fontWeight||t.fontStyle!==e.fontStyle},_getLineLeftOffset:function(t){var e=this.getLineWidth(t);return"center"===this.textAlign?(this.width-e)/2:"right"===this.textAlign?this.width-e:0},_clearCache:function(){this.__lineWidths=[],this.__lineHeights=[],this.__numberOfSpaces=[],this.__charBounds=[]},_shouldClearDimensionCache:function(){var t=this._forceClearCache;return t||(t=this.hasStateChanged("_dimensionAffectingProps")),t&&(this.saveState({propertySet:"_dimensionAffectingProps"}),this.dirty=!0,this._forceClearCache=!1),t},getLineWidth:function(t){if(this.__lineWidths[t])return this.__lineWidths[t];var e,r=this._textLines[t],i;return""===r?e=0:(i=this.measureLine(t),e=i.width),this.__lineWidths[t]=e,this.__numberOfSpaces[t]=i.numberOfSpaces,e},_getWidthOfCharSpacing:function(){return 0!==this.charSpacing?this.fontSize*this.charSpacing/1e3:0},getValueOfPropertyAt:function(t,e,r){var i=this._getStyleDeclaration(t,e);return i&&void 0!==i[r]?i[r]:this[r]},_renderTextDecoration:function(t,e){if(this[e]||this.styleHas(e)){for(var r,i,n,o,a=this._getLeftOffset(),s=this._getTopOffset(),c,l,h,u,f,d,p,g=0,v=this._textLines.length;g<v;g++)if(r=this.getHeightOfLine(g),this[e]||this.styleHas(e,g)){n=this._textLines[g],f=r/this.lineHeight,i=this._getLineLeftOffset(g),c=0,l=0,o=this.getValueOfPropertyAt(g,0,e),p=this.getValueOfPropertyAt(g,0,"fill");for(var m=0,b=n.length;m<b;m++)h=this.__charBounds[g][m],u=this.getValueOfPropertyAt(g,m,e),d=this.getValueOfPropertyAt(g,m,"fill"),(u!==o||d!==p)&&l>0?(t.fillStyle=p,o&&p&&t.fillRect(a+i+c,s+f*(1-this._fontSizeFraction)+this.offsets[e]*this.fontSize,l,this.fontSize/15),c=h.left,l=h.width,o=u,p=d):l+=h.kernedWidth;t.fillStyle=d,u&&d&&t.fillRect(a+i+c,s+f*(1-this._fontSizeFraction)+this.offsets[e]*this.fontSize,l,this.fontSize/15),s+=r}else s+=r;this._removeShadow(t)}},_getFontDeclaration:function(t,r){var i=t||this;return[e.isLikelyNode?i.fontWeight:i.fontStyle,e.isLikelyNode?i.fontStyle:i.fontWeight,r?"200px":i.fontSize+"px",e.isLikelyNode?'"'+i.fontFamily+'"':i.fontFamily].join(" ")},render:function(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",t)))},_splitTextIntoLines:function(t){for(var r=t.split(this._reNewline),i=new Array(r.length),n=["\n"],o=[],a=0;a<r.length;a++)i[a]=e.util.string.graphemeSplit(r[a]),o=o.concat(i[a],n);return o.pop(),{_unwrappedLines:i,lines:r,graphemeText:o,graphemeLines:i}},toObject:function(t){var e=["text","fontSize","fontWeight","fontFamily","fontStyle","lineHeight","underline","overline","linethrough","textAlign","textBackgroundColor","charSpacing"].concat(t),i=this.callSuper("toObject",e);return i.styles=r(this.styles,!0),i},_set:function(t,e){this.callSuper("_set",t,e),this._dimensionAffectingProps.indexOf(t)>-1&&(this.initDimensions(),this.setCoords())},complexity:function(){return 1}}),e.Text.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y dx dy font-family font-style font-weight font-size text-decoration text-anchor".split(" ")),e.Text.DEFAULT_SVG_FONT_SIZE=16,e.Text.fromElement=function(t,i,n){if(!t)return i(null);var o=e.parseAttributes(t,e.Text.ATTRIBUTE_NAMES);if(n=e.util.object.extend(n?r(n):{},o),n.top=n.top||0,n.left=n.left||0,o.textDecoration){var a=o.textDecoration;-1!==a.indexOf("underline")&&(n.underline=!0),-1!==a.indexOf("overline")&&(n.overline=!0),-1!==a.indexOf("line-through")&&(n.linethrough=!0),delete n.textDecoration}"dx"in o&&(n.left+=o.dx),"dy"in o&&(n.top+=o.dy),"fontSize"in n||(n.fontSize=e.Text.DEFAULT_SVG_FONT_SIZE),n.originX||(n.originX="left");var s="";"textContent"in t?s=t.textContent:"firstChild"in t&&null!==t.firstChild&&"data"in t.firstChild&&null!==t.firstChild.data&&(s=t.firstChild.data),s=s.replace(/^\s+|\s+$|\n+/g,"").replace(/\s+/g," ");var c=new e.Text(s,n),l=c.getScaledHeight()/c.height,h=(c.height+c.strokeWidth)*c.lineHeight-c.height,u=h*l,f=c.getScaledHeight()+u,d=0;"center"===c.originX&&(d=c.getScaledWidth()/2),"right"===c.originX&&(d=c.getScaledWidth()),c.set({left:c.left-d,top:c.top-(f-c.fontSize*(.18+c._fontSizeFraction))/c.lineHeight}),c.originX="left",c.originY="top",i(c)},e.Text.fromObject=function(t,r){return e.Object._fromObject("Text",t,r,"text")},e.util.createAccessors&&e.util.createAccessors(e.Text)}(exports),function(){function t(t){t.textDecoration&&(t.textDecoration.indexOf("underline")>-1&&(t.underline=!0),t.textDecoration.indexOf("line-through")>-1&&(t.linethrough=!0),t.textDecoration.indexOf("overline")>-1&&(t.overline=!0),delete t.textDecoration)}fabric.IText=fabric.util.createClass(fabric.Text,fabric.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"#333",cursorDelay:1e3,cursorDuration:600,caching:!0,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(t,e){this.styles=e?e.styles||{}:{},this.callSuper("initialize",t,e),this.initBehavior()},setSelectionStart:function(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)},setSelectionEnd:function(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)},_updateAndFire:function(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},getSelectionStyles:function(t,e){if(2===arguments.length){for(var r=[],i=t;i<e;i++)r.push(this.getSelectionStyles(i));return r}var n=this.get2DCursorLocation(t);return this._getStyleDeclaration(n.lineIndex,n.charIndex)||{}},setSelectionStyles:function(t){if(this.selectionStart===this.selectionEnd)return this;for(var e=this.selectionStart;e<this.selectionEnd;e++)this._extendStyles(e,t);return this._forceClearCache=!0,this},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(t){this.clearContextTop(),this.callSuper("render",t),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(t){this.callSuper("_render",t),this.ctx=t},clearContextTop:function(t){if(this.active&&this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this.canvas.contextTop;e.save(),e.transform.apply(e,this.canvas.viewportTransform),this.transform(e),this.transformMatrix&&e.transform.apply(e,this.transformMatrix),this._clearTextArea(e),t||e.restore()}},renderCursorOrSelection:function(){if(this.active&&this.isEditing){var t=this._getCursorBoundaries(),e;this.canvas&&this.canvas.contextTop?(e=this.canvas.contextTop,this.clearContextTop(!0)):(e=this.ctx,e.save()),this.selectionStart===this.selectionEnd?this.renderCursor(t,e):this.renderSelection(t,e),e.restore()}},_clearTextArea:function(t){var e=this.width+4,r=this.height+4;t.clearRect(-e/2,-r/2,e,r)},get2DCursorLocation:function(t,e){void 0===t&&(t=this.selectionStart);for(var r=e?this._unwrappedTextLines:this._textLines,i=r.length,n=0;n<i;n++){if(t<=r[n].length)return{lineIndex:n,charIndex:t};t-=r[n].length+1}return{lineIndex:n-1,charIndex:r[n-1].length<t?r[n-1].length:t}},_getCursorBoundaries:function(t){void 0===t&&(t=this.selectionStart);var e=this._getLeftOffset(),r=this._getTopOffset(),i=this._getCursorBoundariesOffsets(t);return{left:e,top:r,leftOffset:i.left,topOffset:i.top}},_getCursorBoundariesOffsets:function(t){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;for(var e,r=0,i=0,n=0,o=0,a,s=this.get2DCursorLocation(t),c=0;c<s.lineIndex;c++)n+=this.getHeightOfLine(c);e=this._getLineLeftOffset(s.lineIndex);var l=this.__charBounds[s.lineIndex][s.charIndex];return l&&(o=l.left),0!==this.charSpacing&&0===this._textLines[0].length&&(o-=this._getWidthOfCharSpacing()),a={top:n,left:e+(o>0?o:0)},this.cursorOffsetCache=a,this.cursorOffsetCache},renderCursor:function(t,e){var r=this.get2DCursorLocation(),i=r.lineIndex,n=r.charIndex>0?r.charIndex-1:0,o=this.getValueOfPropertyAt(i,n,"fontSize"),a=this.scaleX*this.canvas.getZoom(),s=this.cursorWidth/a,c=t.topOffset;c+=(1-this._fontSizeFraction)*this.getHeightOfLine(i)/this.lineHeight-o*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(t,e),e.fillStyle=this.getValueOfPropertyAt(i,n,"fill"),e.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,e.fillRect(t.left+t.leftOffset-s/2,c+t.top,s,o)},renderSelection:function(t,e){for(var r=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,i=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,n=this.get2DCursorLocation(r),o=this.get2DCursorLocation(i),a=n.lineIndex,s=o.lineIndex,c=n.charIndex<0?0:n.charIndex,l=o.charIndex<0?0:o.charIndex,h=a;h<=s;h++){var u=this._getLineLeftOffset(h)||0,f=this.getHeightOfLine(h),d=0,p=0,g=0;h===a&&(p=this.__charBounds[a][c].left),h>=a&&h<s?g=this.getLineWidth(h)||5:h===s&&(g=0===l?this.__charBounds[s][l].left:this.__charBounds[s][l-1].left+this.__charBounds[s][l-1].width),d=f,(this.lineHeight<1||h===s&&this.lineHeight>1)&&(f/=this.lineHeight),this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",e.fillRect(t.left+u+p,t.top+t.topOffset+f,g-p,1)):(e.fillStyle=this.selectionColor,e.fillRect(t.left+u+p,t.top+t.topOffset,g-p,f)),t.topOffset+=d}},getCurrentCharFontSize:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")},getCurrentCharColor:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fill")},_getCurrentCharIndex:function(){var t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}}),fabric.IText.fromObject=function(e,r){if(t(e),e.styles)for(var i in e.styles)for(var n in e.styles[i])t(e.styles[i][n]);fabric.Object._fromObject("IText",e,r,"text")}}(),function(){var t=fabric.util.object.clone;fabric.util.object.extend(fabric.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1,this.callSuper("onDeselect")},initAddedHandler:function(){var t=this;this.on("added",function(){var e=t.canvas;e&&(e._hasITextHandlers||(e._hasITextHandlers=!0,t._initCanvasHandlers(e)),e._iTextInstances=e._iTextInstances||[],e._iTextInstances.push(t))})},initRemovedHandler:function(){var t=this;this.on("removed",function(){var e=t.canvas;e&&(e._iTextInstances=e._iTextInstances||[],fabric.util.removeFromArray(e._iTextInstances,t),0===e._iTextInstances.length&&(e._hasITextHandlers=!1,t._removeCanvasHandlers(e)))})},_initCanvasHandlers:function(t){t._mouseUpITextHandler=function(){t._iTextInstances&&t._iTextInstances.forEach(function(t){t.__isMousedown=!1})}.bind(this),t.on("mouse:up",t._mouseUpITextHandler)},_removeCanvasHandlers:function(t){t.off("mouse:up",t._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(t,e,r,i){var n;return n={isAborted:!1,abort:function(){this.isAborted=!0}},t.animate("_currentCursorOpacity",e,{duration:r,onComplete:function(){n.isAborted||t[i]()},onChange:function(){t.canvas&&t.selectionStart===t.selectionEnd&&t.renderCursorOrSelection()},abort:function(){return n.isAborted}}),n},_onTickComplete:function(){var t=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout(function(){t._currentTickCompleteState=t._animateCursor(t,0,this.cursorDuration/2,"_tick")},100)},initDelayedCursor:function(t){var e=this,r=t?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout(function(){e._tick()},r)},abortCursorAnimation:function(){var t=this._currentTickState||this._currentTickCompleteState;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,t&&this.canvas&&this.canvas.clearContext(this.canvas.contextTop||this.ctx)},selectAll:function(){this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea()},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(t){var e=0,r=t-1;if(this._reSpace.test(this._text[r]))for(;this._reSpace.test(this._text[r]);)e++,r--;for(;/\S/.test(this._text[r])&&r>-1;)e++,r--;return t-e},findWordBoundaryRight:function(t){var e=0,r=t;if(this._reSpace.test(this._text[r]))for(;this._reSpace.test(this._text[r]);)e++,r++;for(;/\S/.test(this._text[r])&&r<this.text.length;)e++,r++;return t+e},findLineBoundaryLeft:function(t){for(var e=0,r=t-1;!/\n/.test(this._text[r])&&r>-1;)e++,r--;return t-e},findLineBoundaryRight:function(t){for(var e=0,r=t;!/\n/.test(this._text[r])&&r<this.text.length;)e++,r++;return t+e},searchWordBoundary:function(t,e){for(var r=this._reSpace.test(this.text.charAt(t))?t-1:t,i=this.text.charAt(r),n=/[ \n\.,;!\?\-]/;!n.test(i)&&r>0&&r<this.text.length;)r+=e,i=this.text.charAt(r);return n.test(i)&&"\n"!==i&&(r+=1===e?0:1),r},selectWord:function(t){t=t||this.selectionStart;var e=this.searchWordBoundary(t,-1),r=this.searchWordBoundary(t,1);this.selectionStart=e,this.selectionEnd=r,this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()},selectLine:function(t){t=t||this.selectionStart;var e=this.findLineBoundaryLeft(t),r=this.findLineBoundaryRight(t);this.selectionStart=e,this.selectionEnd=r,this._fireSelectionChanged(),this._updateTextarea()},enterEditing:function(t){if(!this.isEditing&&this.editable)return this.canvas&&this.exitEditingOnOthers(this.canvas),this.isEditing=!0,this.initHiddenTextarea(t),this.hiddenTextarea.focus(),this.hiddenTextarea.value=this.text,this._updateTextarea(),this._saveEditingProps(),this._setEditingProps(),this._textBeforeEdit=this.text,this._tick(),this.fire("editing:entered"),this._fireSelectionChanged(),this.canvas?(this.canvas.fire("text:editing:entered",{target:this}),this.initMouseMoveHandler(),this.canvas.requestRenderAll(),this):this},exitEditingOnOthers:function(t){t._iTextInstances&&t._iTextInstances.forEach(function(t){t.selected=!1,t.isEditing&&t.exitEditing()})},initMouseMoveHandler:function(){this.canvas.on("mouse:move",this.mouseMoveHandler)},mouseMoveHandler:function(t){if(this.__isMousedown&&this.isEditing){var e=this.getSelectionStartFromPointer(t.e),r=this.selectionStart,i=this.selectionEnd;(e===this.__selectionStartOnMouseDown&&r!==i||r!==e&&i!==e)&&(e>this.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=e):(this.selectionStart=e,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===r&&this.selectionEnd===i||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(t,e,r){var i=r.slice(0,t),n=fabric.util.string.graphemeSplit(i).length;if(t===e)return{selectionStart:n,selectionEnd:n};var o=r.slice(t,e);return{selectionStart:n,selectionEnd:n+fabric.util.string.graphemeSplit(o).length}},fromGraphemeToStringSelection:function(t,e,r){var i=r.slice(0,t),n=i.join("").length;return t===e?{selectionStart:n,selectionEnd:n}:{selectionStart:n,selectionEnd:n+r.slice(t,e).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value;var t=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=t.selectionEnd,this.inCompositionMode||(this.selectionStart=t.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),r=this.get2DCursorLocation(t),i=r.lineIndex,n=r.charIndex,o=this.getValueOfPropertyAt(i,n,"fontSize")*this.lineHeight,a=e.leftOffset,s=this.calcTransformMatrix(),c={x:e.left+a,y:e.top+e.topOffset+o},l=this.canvas.upperCanvasEl,h=l.width-o,u=l.height-o;return c=fabric.util.transformPoint(c,s),c=fabric.util.transformPoint(c,this.canvas.viewportTransform),c.x<0&&(c.x=0),c.x>h&&(c.x=h),c.y<0&&(c.y=0),c.y>u&&(c.y=u),c.x+=this.canvas._offset.left,c.y+=this.canvas._offset.top,{left:c.x+"px",top:c.y+"px",fontSize:o+"px",charHeight:o}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.overCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var t=this._textBeforeEdit!==this.text;return this.selected=!1,this.isEditing=!1,this.selectable=!0,this.selectionEnd=this.selectionStart,this.hiddenTextarea&&(this.hiddenTextarea.blur&&this.hiddenTextarea.blur(),this.canvas&&this.hiddenTextarea.parentNode.removeChild(this.hiddenTextarea),this.hiddenTextarea=null),this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this.fire("editing:exited"),t&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var t in this.styles)this._textLines[t]||delete this.styles[t]},removeStyleFromTo:function(t,e){var r=this.get2DCursorLocation(t,!0),i=this.get2DCursorLocation(e,!0),n=r.lineIndex,o=r.charIndex,a=i.lineIndex,s=i.charIndex,c,l;if(n!==a){if(this.styles[n])for(c=o;c<this._textLines[n].length;c++)delete this.styles[n][c];if(this.styles[a])for(c=s;c<this._textLines[a].length;c++)(l=this.styles[a][c])&&(this.styles[n]||(this.styles[n]={}),this.styles[n][o+c-s]=l);for(c=n+1;c<=a;c++)delete this.styles[c];this.shiftLineStyles(a,n-a)}else if(this.styles[n]){l=this.styles[n];var h=s-o;for(c=o;c<s;c++)delete l[c];for(c=s;c<this._textLines[n].length;c++)l[c]&&(l[c-h]=l[c],delete l[c])}},shiftLineStyles:function(e,r){var i=t(this.styles);for(var n in this.styles){var o=parseInt(n,10);o>e&&(this.styles[o+r]=i[o],i[o-r]||delete this.styles[o])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(e,r,i,n){var o,a={},s=!1;i||(i=1),this.shiftLineStyles(e,i),this.styles[e]&&this.styles[e][r-1]&&(o=this.styles[e][r-1]);for(var c in this.styles[e]){var l=parseInt(c,10);l>=r&&(s=!0,a[l-r]=this.styles[e][c],delete this.styles[e][c])}for(s?this.styles[e+i]=a:delete this.styles[e+i];i>1;)i--,n[i]?this.styles[e+i]={0:t(n[i])}:o?this.styles[e+i]={0:t(o)}:delete this.styles[e+i];this._forceClearCache=!0},insertCharStyleObject:function(e,r,i,n){var o=this.styles[e],a=t(o);i||(i=1);for(var s in a){var c=parseInt(s,10);c>=r&&(o[c+i]=a[c],a[c-i]||delete o[c])}if(this._forceClearCache=!0,o)if(n)for(;i--;)this.styles[e][r+i]=t(n[i]);else for(var l=o[r?r-1:1];l&&i--;)this.styles[e][r+i]=t(l)},insertNewStyleBlock:function(t,e,r){for(var i=this.get2DCursorLocation(e,!0),n=0,o=0,a=0;a<t.length;a++)"\n"===t[a]?(o&&(this.insertCharStyleObject(i.lineIndex,i.charIndex,o,r),r=r&&r.slice(o),o=0),n++):(n&&(this.insertNewlineStyleObject(i.lineIndex,i.charIndex,n,r),r=r&&r.slice(n),n=0),o++);o&&this.insertCharStyleObject(i.lineIndex,i.charIndex,o,r),n&&this.insertNewlineStyleObject(i.lineIndex,i.charIndex,n,r)},setSelectionStartEndWithShift:function(t,e,r){r<=t?(e===t?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=t),this.selectionStart=r):r>t&&r<e?"right"===this._selectionDirection?this.selectionEnd=r:this.selectionStart=r:(e===t?this._selectionDirection="right":"left"===this._selectionDirection&&(this._selectionDirection="right",this.selectionStart=e),this.selectionEnd=r)},setSelectionInBoundaries:function(){var t=this.text.length;this.selectionStart>t?this.selectionStart=t:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>t?this.selectionEnd=t:this.selectionEnd<0&&(this.selectionEnd=0)}})}(),fabric.util.object.extend(fabric.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown.bind(this))},onMouseDown:function(t){this.__newClickTime=+new Date;var e=this.canvas.getPointer(t.e);this.isTripleClick(e,t.e)&&(this.fire("tripleclick",t),this._stopEvent(t.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=e,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected},isTripleClick:function(t){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===t.x&&this.__lastPointer.y===t.y},_stopEvent:function(t){t.preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},initClicks:function(){this.on("mousedblclick",function(t){this.selectWord(this.getSelectionStartFromPointer(t.e))}),this.on("tripleclick",function(t){this.selectLine(this.getSelectionStartFromPointer(t.e))})},initMousedownHandler:function(){this.on("mousedown",function(t){if(this.editable&&(!t.e.button||1===t.e.button)){var e=this.canvas.getPointer(t.e);this.__mousedownX=e.x,this.__mousedownY=e.y,this.__isMousedown=!0,this.selected&&this.setCursorByClick(t.e),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection())}})},_isObjectMoved:function(t){var e=this.canvas.getPointer(t);return this.__mousedownX!==e.x||this.__mousedownY!==e.y},initMouseupHandler:function(){this.on("mouseup",function(t){this.__isMousedown=!1,!this.editable||this._isObjectMoved(t.e)||t.e.button&&1!==t.e.button||(this.__lastSelected&&!this.__corner&&(this.enterEditing(t.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()),this.selected=!0)})},setCursorByClick:function(t){var e=this.getSelectionStartFromPointer(t),r=this.selectionStart,i=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(r,i,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(t){for(var e=this.getLocalPointer(t),r=0,i=0,n=0,o=0,a=0,s,c,l=0,h=this._textLines.length;l<h&&n<=e.y;l++)n+=this.getHeightOfLine(l)*this.scaleY,a=l,l>0&&(o+=this._textLines[l-1].length+1);s=this._getLineLeftOffset(a),i=s*this.scaleX,c=this._textLines[a];for(var u=0,f=c.length;u<f&&(r=i,(i+=this.__charBounds[a][u].kernedWidth*this.scaleX)<=e.x);u++)o++;return this._getNewSelectionStartFromOffset(e,r,i,o,f)},_getNewSelectionStartFromOffset:function(t,e,r,i,n){var o=t.x-e,a=r-t.x,s=a>o?0:1,c=i+s;return this.flipX&&(c=n-c),c>this._text.length&&(c=this._text.length),c}}),fabric.util.object.extend(fabric.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=fabric.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var t=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+t.top+"; left: "+t.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; line-height: 1px; paddingーtop: "+t.fontSize+";",fabric.document.body.appendChild(this.hiddenTextarea),fabric.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),fabric.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),fabric.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),fabric.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),fabric.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),fabric.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),fabric.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),fabric.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),fabric.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(fabric.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(t){if(this.isEditing&&!this.inCompositionMode){if(t.keyCode in this.keysMap)this[this.keysMap[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown&&(t.ctrlKey||t.metaKey)))return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(t){if(!this.isEditing||this._copyDone||this.inCompositionMode)return void(this._copyDone=!1);t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(t){var e=this.fromPaste;if(this.fromPaste=!1,t&&t.stopPropagation(),this.isEditing){var r=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,i=this._text.length,n=r.length,o,a,s=n-i;""===this.hiddenTextarea.value&&(this.styles={},this.updateFromTextArea(),this.fire("changed"),this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll())),this.selectionStart!==this.selectionEnd?(o=this._text.slice(this.selectionStart,this.selectionEnd),s+=this.selectionEnd-this.selectionStart):n<i&&(o=this._text.slice(this.selectionEnd+s,this.selectionEnd));var c=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);a=r.slice(c.selectionEnd-s,c.selectionEnd),o&&o.length&&(this.selectionStart!==this.selectionEnd?this.removeStyleFromTo(this.selectionStart,this.selectionEnd):this.selectionStart>c.selectionStart?this.removeStyleFromTo(this.selectionEnd-o.length,this.selectionEnd):this.removeStyleFromTo(this.selectionEnd,this.selectionEnd+o.length)),a.length&&(e&&a.join("")===fabric.copiedText?this.insertNewStyleBlock(a,this.selectionStart,fabric.copiedTextStyle):this.insertNewStyleBlock(a,this.selectionStart)),this.updateFromTextArea(),this.fire("changed"),this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll())}},onCompositionStart:function(){this.inCompositionMode=!0},onCompositionEnd:function(){this.inCompositionMode=!1},onCompositionUpdate:function(t){this.compositionStart=t.target.selectionStart,this.compositionEnd=t.target.selectionEnd,this.updateTextareaPosition()},copy:function(){if(this.selectionStart!==this.selectionEnd){var t=this.getSelectedText();fabric.copiedText=t,fabric.copiedTextStyle=this.getSelectionStyles(this.selectionStart,this.selectionEnd),this._copyDone=!0}},paste:function(){this.fromPaste=!0},_getClipboardData:function(t){return t&&t.clipboardData||fabric.window.clipboardData},_getWidthBeforeCursor:function(t,e){var r=this._getLineLeftOffset(t),i;return e>0&&(i=this.__charBounds[t][e-1],r+=i.left+i.width),r},getDownCursorOffset:function(t,e){var r=this._getSelectionForOffset(t,e),i=this.get2DCursorLocation(r),n=i.lineIndex;if(n===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-r;var o=i.charIndex,a=this._getWidthBeforeCursor(n,o),s=this._getIndexOnLine(n+1,a);return this._textLines[n].slice(o).length+s+2},_getSelectionForOffset:function(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(t,e){var r=this._getSelectionForOffset(t,e),i=this.get2DCursorLocation(r),n=i.lineIndex;if(0===n||t.metaKey||33===t.keyCode)return-r;var o=i.charIndex,a=this._getWidthBeforeCursor(n,o),s=this._getIndexOnLine(n-1,a),c=this._textLines[n].slice(0,o);return-this._textLines[n-1].length+s-c.length},_getIndexOnLine:function(t,e){for(var r=this._textLines[t],i=this._getLineLeftOffset(t),n=i,o=0,a,s,c=0,l=r.length;c<l;c++)if(a=this.__charBounds[t][c].width,(n+=a)>e){s=!0;var h=n-a,u=n,f=Math.abs(h-e),d=Math.abs(u-e);o=d<f?c:c-1;break}return s||(o=r.length-1),o},moveCursorDown:function(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)},moveCursorUp:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorUpOrDown("Up",t)},_moveCursorUpOrDown:function(t,e){var r="get"+t+"CursorOffset",i=this[r](e,"right"===this._selectionDirection);e.shiftKey?this.moveCursorWithShift(i):this.moveCursorWithoutShift(i),0!==i&&(this.setSelectionInBoundaries(),this.abortCursorAnimation(),this._currentCursorOpacity=1,this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorWithShift:function(t){var e="left"===this._selectionDirection?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),0!==t},moveCursorWithoutShift:function(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),0!==t},moveCursorLeft:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorLeftOrRight("Left",t)},_move:function(t,e,r){var i;if(t.altKey)i=this["findWordBoundary"+r](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===r?-1:1,!0;i=this["findLineBoundary"+r](this[e])}if(void 0!==typeof i&&this[e]!==i)return this[e]=i,!0},_moveLeft:function(t,e){return this._move(t,e,"Left")},_moveRight:function(t,e){return this._move(t,e,"Right")},moveCursorLeftWithoutShift:function(t){var e=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e},moveCursorLeftWithShift:function(t){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(t,"selectionStart")):void 0},moveCursorRight:function(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)},_moveCursorLeftOrRight:function(t,e){var r="moveCursor"+t+"With";this._currentCursorOpacity=1,e.shiftKey?r+="Shift":r+="outShift",this[r](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(t){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(t,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(t){var e=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e},removeChars:function(t){this.selectionStart===this.selectionEnd?this._removeCharsNearCursor(t):this._removeCharsFromTo(this.selectionStart,this.selectionEnd),this.set("dirty",!0),this.setSelectionEnd(this.selectionStart),this._removeExtraneousStyles(),this.canvas&&this.canvas.requestRenderAll(),this.setCoords(),this.fire("changed"),this.canvas&&this.canvas.fire("text:changed",{target:this})},_removeCharsNearCursor:function(t){if(0!==this.selectionStart)if(t.metaKey){var e=this.findLineBoundaryLeft(this.selectionStart);this._removeCharsFromTo(e,this.selectionStart),this.setSelectionStart(e)}else if(t.altKey){var r=this.findWordBoundaryLeft(this.selectionStart);this._removeCharsFromTo(r,this.selectionStart),this.setSelectionStart(r)}else this._removeSingleCharAndStyle(this.selectionStart),this.setSelectionStart(this.selectionStart-1)}}),function(){var t=fabric.util.toFixed,e=fabric.Object.NUM_FRACTION_DIGITS;fabric.util.object.extend(fabric.Text.prototype,{toSVG:function(t){var e=this._createBaseSVGMarkup(),r=this._getSVGLeftTopOffsets(),i=this._getSVGTextAndBg(r.textTop,r.textLeft);return this._wrapSVGTextAndBg(e,i),t?t(e.join("")):e.join("")},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(t,e){var r=!0,i=this.getSvgFilter(),n=""===i?"":' style="'+i+'"';t.push("\t<g ",this.getSvgId(),'transform="',this.getSvgTransform(),this.getSvgTransformMatrix(),'"',n,">\n",e.textBgRects.join(""),'\t\t<text xml:space="preserve" ',this.fontFamily?'font-family="'+this.fontFamily.replace(/"/g,"'")+'" ':"",this.fontSize?'font-size="'+this.fontSize+'" ':"",this.fontStyle?'font-style="'+this.fontStyle+'" ':"",this.fontWeight?'font-weight="'+this.fontWeight+'" ':"",this.textDecoration?'text-decoration="'+this.textDecoration+'" ':"",'style="',this.getSvgStyles(!0),'" >\n',e.textSpans.join(""),"\t\t</text>\n","\t</g>\n")},_getSVGTextAndBg:function(t,e){var r=[],i=[],n=t,o;this._setSVGBg(i);for(var a=0,s=this._textLines.length;a<s;a++)o=this._getLineLeftOffset(a),(this.textBackgroundColor||this.styleHas("textBackgroundColor",a))&&this._setSVGTextLineBg(i,a,e+o,n),this._setSVGTextLineText(r,a,e+o,n),n+=this.getHeightOfLine(a);return{textSpans:r,textBgRects:i}},_createTextCharSpan:function(r,i,n,o){var a=this.getSvgSpanStyles(i,!1),s=a?'style="'+a+'"':"";return['\t\t\t<tspan x="',t(n,e),'" y="',t(o,e),'" ',s,">",fabric.util.string.escapeXml(r),"</tspan>\n"].join("")},_setSVGTextLineText:function(t,e,r,i){var n=this.getHeightOfLine(e),o,a,s="",c,l,h=0,u=this._textLines[e],f;i+=n*(1-this._fontSizeFraction)/this.lineHeight;for(var d=0,p=u.length-1;d<=p;d++)f=d===p||this.charSpacing,s+=u[d],c=this.__charBounds[e][d],0===h&&(r+=c.kernedWidth-c.width),h+=c.kernedWidth,"justify"!==this.textAlign||f||this._reSpaceAndTab.test(u[d])&&(f=!0),f||(o=o||this.getCompleteStyleDeclaration(e,d),a=this.getCompleteStyleDeclaration(e,d+1),f=this._hasStyleChanged(o,a)),f&&(l=this._getStyleDeclaration(e,d)||{},t.push(this._createTextCharSpan(s,l,r,i)),s="",o=a,r+=h,h=0)},_pushTextBgRect:function(r,i,n,o,a,s){r.push("\t\t<rect ",this._getFillAttributes(i),' x="',t(n,e),'" y="',t(o,e),'" width="',t(a,e),'" height="',t(s,e),'"></rect>\n')},_setSVGTextLineBg:function(t,e,r,i){for(var n=this._textLines[e],o=this.getHeightOfLine(e)/this.lineHeight,a=0,s=0,c,l,h=this.getValueOfPropertyAt(e,0,"textBackgroundColor"),u=0,f=n.length;u<f;u++)c=this.__charBounds[e][u],l=this.getValueOfPropertyAt(e,u,"textBackgroundColor"),l!==h?(h&&this._pushTextBgRect(t,h,r+s,i,a,o),s=c.left,a=c.width,h=l):a+=c.kernedWidth;l&&this._pushTextBgRect(t,l,r+s,i,a,o)},_getFillAttributes:function(t){var e=t&&"string"==typeof t?new fabric.Color(t):"";return e&&e.getSource()&&1!==e.getAlpha()?'opacity="'+e.getAlpha()+'" fill="'+e.setAlpha(1).toRgb()+'"':'fill="'+t+'"'},_getSVGLineTopOffset:function(t){for(var e=0,r=0,i=0;i<t;i++)e+=this.getHeightOfLine(i);return r=this.getHeightOfLine(i),{lineTop:e,offset:(this._fontSizeMult-this._fontSizeFraction)*r/(this.lineHeight*this._fontSizeMult)}},getSvgStyles:function(t){return fabric.Object.prototype.getSvgStyles.call(this,t)+" white-space: pre;"}})}(),function(t){"use strict";var e=t.fabric||(t.fabric={});e.Textbox=e.util.createClass(e.IText,e.Observable,{type:"textbox",minWidth:20,dynamicMinWidth:2,__cachedLines:null,lockScalingFlip:!0,noScaleCache:!1,initialize:function(t,r){this.callSuper("initialize",t,r),this.ctx=this.objectCaching?this._cacheContext:e.util.createCanvasElement().getContext("2d"),this._dimensionAffectingProps.push("width")},initDimensions:function(){if(!this.__skipDimension){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this._clearCache(),this.dynamicMinWidth=0;var t=this._splitTextIntoLines(this.text);this.textLines=t.lines,this._textLines=t.graphemeLines,this._unwrappedTextLines=t._unwrappedLines,this._text=t.graphemeText,this._styleMap=this._generateStyleMap(t),this.dynamicMinWidth>this.width&&this._set("width",this.dynamicMinWidth),"justify"===this.textAlign&&this.enlargeSpaces(),this.height=this.calcTextHeight()}},_generateStyleMap:function(t){for(var e=0,r=0,i=0,n={},o=0;o<t.graphemeLines.length;o++)"\n"===t.graphemeText[i]&&o>0?(r=0,i++,e++):this._reSpaceAndTab.test(t.graphemeText[i])&&o>0&&(r++,i++),n[o]={line:e,offset:r},i+=t.graphemeLines[o].length,r+=t.graphemeLines[o].length;return n},styleHas:function(t,r){if(this._styleMap&&!this.isWrapping){var i=this._styleMap[r];i&&(r=i.line)}return e.Text.prototype.styleHas.call(this,t,r)},_getStyleDeclaration:function(t,e){if(this._styleMap&&!this.isWrapping){var r=this._styleMap[t];if(!r)return null;t=r.line,e=r.offset+e}return this.callSuper("_getStyleDeclaration",t,e)},_setStyleDeclaration:function(t,e,r){var i=this._styleMap[t];t=i.line,e=i.offset+e,this.styles[t][e]=r},_deleteStyleDeclaration:function(t,e){var r=this._styleMap[t];t=r.line,e=r.offset+e,delete this.styles[t][e]},_getLineStyle:function(t){var e=this._styleMap[t];return this.styles[e.line]},_setLineStyle:function(t,e){var r=this._styleMap[t];this.styles[r.line]=e},_deleteLineStyle:function(t){var e=this._styleMap[t];delete this.styles[e.line]},_wrapText:function(t,e){var r=[],i;for(this.isWrapping=!0,i=0;i<t.length;i++)r=r.concat(this._wrapLine(t[i],i,e));return this.isWrapping=!1,r},_measureWord:function(t,e,r){var i=0,n,o=!0;r=r||0;for(var a=0,s=t.length;a<s;a++){i+=this._getGraphemeBox(t[a],e,a+r,n,!0).kernedWidth,n=t[a]}return i},_wrapLine:function(t,r,i){for(var n=0,o=[],a=[],s=t.split(this._reSpaceAndTab),c="",l=0,h=" ",u=0,f=0,d=0,p=!0,g=this._getWidthOfCharSpacing(),v=0;v<s.length;v++)c=e.util.string.graphemeSplit(s[v]),u=this._measureWord(c,r,l),l+=c.length,n+=f+u-g,n>=i&&!p&&(o.push(a),a=[],n=u,p=!0),p||a.push(" "),a=a.concat(c),f=this._measureWord([" "],r,l),l++,p=!1,u>d&&(d=u);return v&&o.push(a),d>this.dynamicMinWidth&&(this.dynamicMinWidth=d-g),o},_splitTextIntoLines:function(t){for(var r=e.Text.prototype._splitTextIntoLines.call(this,t),i=this._wrapText(r.lines,this.width),n=new Array(i.length),o=0;o<i.length;o++)n[o]=i[o].join("");return r.lines=n,r.graphemeLines=i,r},getMinWidth:function(){return Math.max(this.minWidth,this.dynamicMinWidth)},toObject:function(t){return this.callSuper("toObject",["minWidth"].concat(t))}}),e.Textbox.fromObject=function(t,r){return e.Object._fromObject("Textbox",t,r,"text")}}(exports),function(){var t=fabric.Canvas.prototype._setObjectScale;fabric.Canvas.prototype._setObjectScale=function(e,r,i,n,o,a,s){var c=r.target;if(!("x"===o&&c instanceof fabric.Textbox))return t.call(fabric.Canvas.prototype,e,r,i,n,o,a,s);var l=c._getTransformedDimensions().x,h=c.width*(e.x/l);return h>=c.getMinWidth()?(c.set("width",h),!0):void 0},fabric.util.object.extend(fabric.Textbox.prototype,{_removeExtraneousStyles:function(){for(var t in this._styleMap)this._textLines[t]||delete this.styles[this._styleMap[t].line]}})}(),function(){function request(t,e,r){var i=URL.parse(t);i.port||(i.port=0===i.protocol.indexOf("https:")?443:80);var n=0===i.protocol.indexOf("https:")?HTTPS:HTTP,o=n.request({hostname:i.hostname,port:i.port,path:i.path,method:"GET"},function(t){var i="";e&&t.setEncoding(e),t.on("end",function(){r(i)}),t.on("data",function(e){200===t.statusCode&&(i+=e)})});o.on("error",function(t){t.errno===process.ECONNREFUSED?fabric.log("ECONNREFUSED: connection refused to "+i.hostname+":"+i.port):fabric.log(t.message),r(null)}),o.end()}function requestFs(t,e){__webpack_require__(78).readFile(t,function(t,r){if(t)throw fabric.log(t),t;e(r)})}if("undefined"==typeof document||"undefined"==typeof window){var DOMParser=__webpack_require__(65).DOMParser,URL=__webpack_require__(25),HTTP=__webpack_require__(26),HTTPS=__webpack_require__(77),Canvas=!function t(){var e=new Error('Cannot find module "."');throw e.code="MODULE_NOT_FOUND",e}(),Image=!function t(){var e=new Error('Cannot find module "."');throw e.code="MODULE_NOT_FOUND",e}().Image;fabric.util.loadImage=function(t,e,r){function i(i){i?(n.src=new Buffer(i,"binary"),n._src=t,e&&e.call(r,n)):(n=null,e&&e.call(r,null,!0))}var n=new Image;t&&(t instanceof Buffer||0===t.indexOf("data"))?(n.src=n._src=t,e&&e.call(r,n)):t&&0!==t.indexOf("http")?requestFs(t,i):t?request(t,"binary",i):e&&e.call(r,t)},fabric.loadSVGFromURL=function(t,e,r){t=t.replace(/^\n\s*/,"").replace(/\?.*$/,"").trim(),0!==t.indexOf("http")?requestFs(t,function(t){fabric.loadSVGFromString(t.toString(),e,r)}):request(t,"",function(t){fabric.loadSVGFromString(t,e,r)})},fabric.loadSVGFromString=function(t,e,r){var i=(new DOMParser).parseFromString(t);fabric.parseSVGDocument(i.documentElement,function(t,r){e&&e(t,r)},r)},fabric.util.getScript=function(url,callback){request(url,"",function(body){eval(body),callback&&callback()})},fabric.createCanvasForNode=function(t,e,r,i){i=i||r;var n=fabric.document.createElement("canvas"),o=new Canvas(t||600,e||600,i),a=new Canvas(t||600,e||600,i);n.width=o.width,n.height=o.height,r=r||{},r.nodeCanvas=o,r.nodeCacheCanvas=a;var s=fabric.Canvas||fabric.StaticCanvas,c=new s(n,r);return c.nodeCanvas=o,c.nodeCacheCanvas=a,c.contextContainer=o.getContext("2d"),c.contextCache=a.getContext("2d"),c.Font=Canvas.Font,c};var originaInitStatic=fabric.StaticCanvas.prototype._initStatic;fabric.StaticCanvas.prototype._initStatic=function(t,e){t=t||fabric.document.createElement("canvas"),this.nodeCanvas=new Canvas(t.width,t.height),this.nodeCacheCanvas=new Canvas(t.width,t.height),originaInitStatic.call(this,t,e),this.contextContainer=this.nodeCanvas.getContext("2d"),this.contextCache=this.nodeCacheCanvas.getContext("2d"),this.Font=Canvas.Font},fabric.StaticCanvas.prototype.createPNGStream=function(){return this.nodeCanvas.createPNGStream()},fabric.StaticCanvas.prototype.createJPEGStream=function(t){return this.nodeCanvas.createJPEGStream(t)},fabric.StaticCanvas.prototype._initRetinaScaling=function(){if(this._isRetinaScaling())return this.lowerCanvasEl.setAttribute("width",this.width*fabric.devicePixelRatio),this.lowerCanvasEl.setAttribute("height",this.height*fabric.devicePixelRatio),this.nodeCanvas.width=this.width*fabric.devicePixelRatio,this.nodeCanvas.height=this.height*fabric.devicePixelRatio,this.contextContainer.scale(fabric.devicePixelRatio,fabric.devicePixelRatio),this},fabric.Canvas&&(fabric.Canvas.prototype._initRetinaScaling=fabric.StaticCanvas.prototype._initRetinaScaling);var origSetBackstoreDimension=fabric.StaticCanvas.prototype._setBackstoreDimension;fabric.StaticCanvas.prototype._setBackstoreDimension=function(t,e){return origSetBackstoreDimension.call(this,t,e),this.nodeCanvas[t]=e,this},fabric.Canvas&&(fabric.Canvas.prototype._setBackstoreDimension=fabric.StaticCanvas.prototype._setBackstoreDimension)}}()}).call(exports,__webpack_require__(2).Buffer,__webpack_require__(1))},function(t,e){},function(t,e){},function(t,e,r){(function(t,i){var n;!function(o){function a(t){throw new RangeError(I[t])}function s(t,e){for(var r=t.length,i=[];r--;)i[r]=e(t[r]);return i}function c(t,e){var r=t.split("@"),i="";return r.length>1&&(i=r[0]+"@",t=r[1]),t=t.replace(D,"."),i+s(t.split("."),e).join(".")}function l(t){for(var e=[],r=0,i=t.length,n,o;r<i;)n=t.charCodeAt(r++),n>=55296&&n<=56319&&r<i?(o=t.charCodeAt(r++),56320==(64512&o)?e.push(((1023&n)<<10)+(1023&o)+65536):(e.push(n),r--)):e.push(n);return e}function h(t){return s(t,function(t){var e="";return t>65535&&(t-=65536,e+=F(t>>>10&1023|55296),t=56320|1023&t),e+=F(t)}).join("")}function u(t){return t-48<10?t-22:t-65<26?t-65:t-97<26?t-97:x}function f(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function d(t,e,r){var i=0;for(t=r?M(t/k):t>>1,t+=M(t/e);t>j*A>>1;i+=x)t=M(t/j);return M(i+(j+1)*t/(t+T))}function p(t){var e=[],r=t.length,i,n=0,o=E,s=P,c,l,f,p,g,v,m,b,y;for(c=t.lastIndexOf(O),c<0&&(c=0),l=0;l<c;++l)t.charCodeAt(l)>=128&&a("not-basic"),e.push(t.charCodeAt(l));for(f=c>0?c+1:0;f<r;){for(p=n,g=1,v=x;f>=r&&a("invalid-input"),m=u(t.charCodeAt(f++)),(m>=x||m>M((S-n)/g))&&a("overflow"),n+=m*g,b=v<=s?C:v>=s+A?A:v-s,!(m<b);v+=x)y=x-b,g>M(S/y)&&a("overflow"),g*=y;i=e.length+1,s=d(n-p,i,0==p),M(n/i)>S-o&&a("overflow"),o+=M(n/i),n%=i,e.splice(n++,0,o)}return h(e)}function g(t){var e,r,i,n,o,s,c,h,u,p,g,v=[],m,b,y,_;for(t=l(t),m=t.length,e=E,r=0,o=P,s=0;s<m;++s)(g=t[s])<128&&v.push(F(g));for(i=n=v.length,n&&v.push(O);i<m;){for(c=S,s=0;s<m;++s)(g=t[s])>=e&&g<c&&(c=g);for(b=i+1,c-e>M((S-r)/b)&&a("overflow"),r+=(c-e)*b,e=c,s=0;s<m;++s)if(g=t[s],g<e&&++r>S&&a("overflow"),g==e){for(h=r,u=x;p=u<=o?C:u>=o+A?A:u-o,!(h<p);u+=x)_=h-p,y=x-p,v.push(F(f(p+_%y,0))),h=M(_/y);v.push(F(f(h,0))),o=d(r,b,i==n),r=0,++i}++r,++e}return v.join("")}function v(t){return c(t,function(t){return R.test(t)?p(t.slice(4).toLowerCase()):t})}function m(t){return c(t,function(t){return L.test(t)?"xn--"+g(t):t})}var b="object"==typeof e&&e&&!e.nodeType&&e,y="object"==typeof t&&t&&!t.nodeType&&t,_="object"==typeof i&&i;_.global!==_&&_.window!==_&&_.self!==_||(o=_);var w,S=2147483647,x=36,C=1,A=26,T=38,k=700,P=72,E=128,O="-",R=/^xn--/,L=/[^\x20-\x7E]/,D=/[\x2E\u3002\uFF0E\uFF61]/g,I={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},j=x-C,M=Math.floor,F=String.fromCharCode,N;w={version:"1.4.1",ucs2:{decode:l,encode:h},decode:p,encode:g,toASCII:m,toUnicode:v},void 0!==(n=function(){return w}.call(e,r,e,t))&&(t.exports=n)}(this)}).call(e,r(67)(t),r(0))},function(t,e){t.exports=function(t){return t.webpackPolyfill||(t.deprecate=function(){},t.paths=[],t.children||(t.children=[]),Object.defineProperty(t,"loaded",{enumerable:!0,get:function(){return t.l}}),Object.defineProperty(t,"id",{enumerable:!0,get:function(){return t.i}}),t.webpackPolyfill=1),t}},function(t,e,r){"use strict";t.exports={isString:function(t){return"string"==typeof t},isObject:function(t){return"object"==typeof t&&null!==t},isNull:function(t){return null===t},isNullOrUndefined:function(t){return null==t}}},function(t,e,r){"use strict";e.decode=e.parse=r(70),e.encode=e.stringify=r(71)},function(t,e,r){"use strict";function i(t,e){return Object.prototype.hasOwnProperty.call(t,e)}t.exports=function(t,e,r,o){e=e||"&",r=r||"=";var a={};if("string"!=typeof t||0===t.length)return a;var s=/\+/g;t=t.split(e);var c=1e3;o&&"number"==typeof o.maxKeys&&(c=o.maxKeys);var l=t.length;c>0&&l>c&&(l=c);for(var h=0;h<l;++h){var u=t[h].replace(s,"%20"),f=u.indexOf(r),d,p,g,v;f>=0?(d=u.substr(0,f),p=u.substr(f+1)):(d=u,p=""),g=decodeURIComponent(d),v=decodeURIComponent(p),i(a,g)?n(a[g])?a[g].push(v):a[g]=[a[g],v]:a[g]=v}return a};var n=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},function(t,e,r){"use strict";function i(t,e){if(t.map)return t.map(e);for(var r=[],i=0;i<t.length;i++)r.push(e(t[i],i));return r}var n=function(t){switch(typeof t){case"string":return t;case"boolean":return t?"true":"false";case"number":return isFinite(t)?t:"";default:return""}};t.exports=function(t,e,r,s){return e=e||"&",r=r||"=",null===t&&(t=void 0),"object"==typeof t?i(a(t),function(a){var s=encodeURIComponent(n(a))+r;return o(t[a])?i(t[a],function(t){return s+encodeURIComponent(n(t))}).join(e):s+encodeURIComponent(n(t[a]))}).join(e):s?encodeURIComponent(n(s))+r+encodeURIComponent(n(t)):""};var o=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)},a=Object.keys||function(t){var e=[];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.push(r);return e}},function(t,e,r){(function(e,i,n){function o(t,e){return s.fetch&&e?"fetch":s.mozchunkedarraybuffer?"moz-chunked-arraybuffer":s.msstream?"ms-stream":s.arraybuffer&&t?"arraybuffer":s.vbArray&&t?"text:vbarray":"text"}function a(t){try{var e=t.status;return null!==e&&0!==e}catch(t){return!1}}var s=r(27),c=r(3),l=r(73),h=r(9),u=r(74),f=l.IncomingMessage,d=l.readyStates,p=t.exports=function(t){var r=this;h.Writable.call(r),r._opts=t,r._body=[],r._headers={},t.auth&&r.setHeader("Authorization","Basic "+new e(t.auth).toString("base64")),Object.keys(t.headers).forEach(function(e){r.setHeader(e,t.headers[e])});var i,n=!0;if("disable-fetch"===t.mode||"timeout"in t)n=!1,i=!0;else if("prefer-streaming"===t.mode)i=!1;else if("allow-wrong-content-type"===t.mode)i=!s.overrideMimeType;else{if(t.mode&&"default"!==t.mode&&"prefer-fast"!==t.mode)throw new Error("Invalid value for opts.mode");i=!0}r._mode=o(i,n),r.on("finish",function(){r._onFinish()})};c(p,h.Writable),p.prototype.setHeader=function(t,e){var r=this,i=t.toLowerCase();-1===g.indexOf(i)&&(r._headers[i]={name:t,value:e})},p.prototype.getHeader=function(t){var e=this._headers[t.toLowerCase()];return e?e.value:null},p.prototype.removeHeader=function(t){delete this._headers[t.toLowerCase()]},p.prototype._onFinish=function(){var t=this;if(!t._destroyed){var r=t._opts,o=t._headers,a=null;"GET"!==r.method&&"HEAD"!==r.method&&(a=s.blobConstructor?new i.Blob(t._body.map(function(t){return u(t)}),{type:(o["content-type"]||{}).value||""}):e.concat(t._body).toString());var c=[];if(Object.keys(o).forEach(function(t){var e=o[t].name,r=o[t].value;Array.isArray(r)?r.forEach(function(t){c.push([e,t])}):c.push([e,r])}),"fetch"===t._mode)i.fetch(t._opts.url,{method:t._opts.method,headers:c,body:a||void 0,mode:"cors",credentials:r.withCredentials?"include":"same-origin"}).then(function(e){t._fetchResponse=e,t._connect()},function(e){t.emit("error",e)});else{var l=t._xhr=new i.XMLHttpRequest;try{l.open(t._opts.method,t._opts.url,!0)}catch(e){return void n.nextTick(function(){t.emit("error",e)})}"responseType"in l&&(l.responseType=t._mode.split(":")[0]),"withCredentials"in l&&(l.withCredentials=!!r.withCredentials),"text"===t._mode&&"overrideMimeType"in l&&l.overrideMimeType("text/plain; charset=x-user-defined"),"timeout"in r&&(l.timeout=r.timeout,l.ontimeout=function(){t.emit("timeout")}),c.forEach(function(t){l.setRequestHeader(t[0],t[1])}),t._response=null,l.onreadystatechange=function(){switch(l.readyState){case d.LOADING:case d.DONE:t._onXHRProgress()}},"moz-chunked-arraybuffer"===t._mode&&(l.onprogress=function(){t._onXHRProgress()}),l.onerror=function(){t._destroyed||t.emit("error",new Error("XHR error"))};try{l.send(a)}catch(e){return void n.nextTick(function(){t.emit("error",e)})}}}},p.prototype._onXHRProgress=function(){var t=this;a(t._xhr)&&!t._destroyed&&(t._response||t._connect(),t._response._onXHRProgress())},p.prototype._connect=function(){var t=this;t._destroyed||(t._response=new f(t._xhr,t._fetchResponse,t._mode),t._response.on("error",function(e){t.emit("error",e)}),t.emit("response",t._response))},p.prototype._write=function(t,e,r){this._body.push(t),r()},p.prototype.abort=p.prototype.destroy=function(){var t=this;t._destroyed=!0,t._response&&(t._response._destroyed=!0),t._xhr&&t._xhr.abort()},p.prototype.end=function(t,e,r){var i=this;"function"==typeof t&&(r=t,t=void 0),h.Writable.prototype.end.call(i,t,e,r)},p.prototype.flushHeaders=function(){},p.prototype.setTimeout=function(){},p.prototype.setNoDelay=function(){},p.prototype.setSocketKeepAlive=function(){};var g=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","user-agent","via"]}).call(e,r(2).Buffer,r(0),r(1))},function(t,e,r){(function(t,i,n){var o=r(27),a=r(3),s=r(9),c=e.readyStates={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4},l=e.IncomingMessage=function(e,r,n){function a(){l.read().then(function(t){if(!c._destroyed){if(t.done)return void c.push(null);c.push(new i(t.value)),a()}}).catch(function(t){c.emit("error",t)})}var c=this;if(s.Readable.call(c),c._mode=n,c.headers={},c.rawHeaders=[],c.trailers={},c.rawTrailers=[],c.on("end",function(){t.nextTick(function(){c.emit("close")})}),"fetch"===n){c._fetchResponse=r,c.url=r.url,c.statusCode=r.status,c.statusMessage=r.statusText,r.headers.forEach(function(t,e){c.headers[e.toLowerCase()]=t,c.rawHeaders.push(e,t)});var l=r.body.getReader();a()}else{c._xhr=e,c._pos=0,c.url=e.responseURL,c.statusCode=e.status,c.statusMessage=e.statusText;if(e.getAllResponseHeaders().split(/\r?\n/).forEach(function(t){var e=t.match(/^([^:]+):\s*(.*)/);if(e){var r=e[1].toLowerCase();"set-cookie"===r?(void 0===c.headers[r]&&(c.headers[r]=[]),c.headers[r].push(e[2])):void 0!==c.headers[r]?c.headers[r]+=", "+e[2]:c.headers[r]=e[2],c.rawHeaders.push(e[1],e[2])}}),c._charset="x-user-defined",!o.overrideMimeType){var h=c.rawHeaders["mime-type"];if(h){var u=h.match(/;\s*charset=([^;])(;|$)/);u&&(c._charset=u[1].toLowerCase())}c._charset||(c._charset="utf-8")}}};a(l,s.Readable),l.prototype._read=function(){},l.prototype._onXHRProgress=function(){var t=this,e=t._xhr,r=null;switch(t._mode){case"text:vbarray":if(e.readyState!==c.DONE)break;try{r=new n.VBArray(e.responseBody).toArray()}catch(t){}if(null!==r){t.push(new i(r));break}case"text":try{r=e.responseText}catch(e){t._mode="text:vbarray";break}if(r.length>t._pos){var o=r.substr(t._pos);if("x-user-defined"===t._charset){for(var a=new i(o.length),s=0;s<o.length;s++)a[s]=255&o.charCodeAt(s);t.push(a)}else t.push(o,t._charset);t._pos=r.length}break;case"arraybuffer":if(e.readyState!==c.DONE||!e.response)break;r=e.response,t.push(new i(new Uint8Array(r)));break;case"moz-chunked-arraybuffer":if(r=e.response,e.readyState!==c.LOADING||!r)break;t.push(new i(new Uint8Array(r)));break;case"ms-stream":if(r=e.response,e.readyState!==c.LOADING)break;var l=new n.MSStreamReader;l.onprogress=function(){l.result.byteLength>t._pos&&(t.push(new i(new Uint8Array(l.result.slice(t._pos)))),t._pos=l.result.byteLength)},l.onload=function(){t.push(null)},l.readAsArrayBuffer(r)}t._xhr.readyState===c.DONE&&"ms-stream"!==t._mode&&t.push(null)}}).call(e,r(1),r(2).Buffer,r(0))},function(t,e,r){var i=r(2).Buffer;t.exports=function(t){if(t instanceof Uint8Array){if(0===t.byteOffset&&t.byteLength===t.buffer.byteLength)return t.buffer;if("function"==typeof t.buffer.slice)return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}if(i.isBuffer(t)){for(var e=new Uint8Array(t.length),r=t.length,n=0;n<r;n++)e[n]=t[n];return e.buffer}throw new Error("Argument must be a Buffer")}},function(t,e){function r(){for(var t={},e=0;e<arguments.length;e++){var r=arguments[e];for(var n in r)i.call(r,n)&&(t[n]=r[n])}return t}t.exports=r;var i=Object.prototype.hasOwnProperty},function(t,e){t.exports={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"}},function(t,e,r){var i=r(26),n=t.exports;for(var o in i)i.hasOwnProperty(o)&&(n[o]=i[o]);n.request=function(t,e){return t||(t={}),t.scheme="https",t.protocol="https:",i.request.call(this,t,e)}},function(t,e){},function(t,e,r){"use strict";function i(){}function n(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function o(){this._events=new i,this._eventsCount=0}var a=Object.prototype.hasOwnProperty,s="~";Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(s=!1)),o.prototype.eventNames=function t(){var e=[],r,i;if(0===this._eventsCount)return e;for(i in r=this._events)a.call(r,i)&&e.push(s?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e},o.prototype.listeners=function t(e,r){var i=s?s+e:e,n=this._events[i];if(r)return!!n;if(!n)return[];if(n.fn)return[n.fn];for(var o=0,a=n.length,c=new Array(a);o<a;o++)c[o]=n[o].fn;return c},o.prototype.emit=function t(e,r,i,n,o,a){var c=s?s+e:e;if(!this._events[c])return!1;var l=this._events[c],h=arguments.length,u,f;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),h){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,r),!0;case 3:return l.fn.call(l.context,r,i),!0;case 4:return l.fn.call(l.context,r,i,n),!0;case 5:return l.fn.call(l.context,r,i,n,o),!0;case 6:return l.fn.call(l.context,r,i,n,o,a),!0}for(f=1,u=new Array(h-1);f<h;f++)u[f-1]=arguments[f];l.fn.apply(l.context,u)}else{var d=l.length,p;for(f=0;f<d;f++)switch(l[f].once&&this.removeListener(e,l[f].fn,void 0,!0),h){case 1:l[f].fn.call(l[f].context);break;case 2:l[f].fn.call(l[f].context,r);break;case 3:l[f].fn.call(l[f].context,r,i);break;case 4:l[f].fn.call(l[f].context,r,i,n);break;default:if(!u)for(p=1,u=new Array(h-1);p<h;p++)u[p-1]=arguments[p];l[f].fn.apply(l[f].context,u)}}return!0},o.prototype.on=function t(e,r,i){var o=new n(r,i||this),a=s?s+e:e;return this._events[a]?this._events[a].fn?this._events[a]=[this._events[a],o]:this._events[a].push(o):(this._events[a]=o,this._eventsCount++),this},o.prototype.once=function t(e,r,i){var o=new n(r,i||this,!0),a=s?s+e:e;return this._events[a]?this._events[a].fn?this._events[a]=[this._events[a],o]:this._events[a].push(o):(this._events[a]=o,this._eventsCount++),this},o.prototype.removeListener=function t(e,r,n,o){var a=s?s+e:e;if(!this._events[a])return this;if(!r)return 0==--this._eventsCount?this._events=new i:delete this._events[a],this;var c=this._events[a];if(c.fn)c.fn!==r||o&&!c.once||n&&c.context!==n||(0==--this._eventsCount?this._events=new i:delete this._events[a]);else{for(var l=0,h=[],u=c.length;l<u;l++)(c[l].fn!==r||o&&!c[l].once||n&&c[l].context!==n)&&h.push(c[l]);h.length?this._events[a]=1===h.length?h[0]:h:0==--this._eventsCount?this._events=new i:delete this._events[a]}return this},o.prototype.removeAllListeners=function t(e){var r;return e?(r=s?s+e:e,this._events[r]&&(0==--this._eventsCount?this._events=new i:delete this._events[r])):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prototype.setMaxListeners=function t(){return this},o.prefixed=s,o.EventEmitter=o,t.exports=o},function(t,e,r){"use strict";function i(t){var e=0,r=0,i=0,s=0;return"detail"in t&&(r=t.detail),"wheelDelta"in t&&(r=-t.wheelDelta/120),"wheelDeltaY"in t&&(r=-t.wheelDeltaY/120),"wheelDeltaX"in t&&(e=-t.wheelDeltaX/120),"axis"in t&&t.axis===t.HORIZONTAL_AXIS&&(e=r,r=0),i=e*n,s=r*n,"deltaY"in t&&(s=t.deltaY),"deltaX"in t&&(i=t.deltaX),(i||s)&&t.deltaMode&&(1==t.deltaMode?(i*=o,s*=o):(i*=a,s*=a)),i&&!e&&(e=i<1?-1:1),s&&!r&&(r=s<1?-1:1),{spinX:e,spinY:r,pixelX:i,pixelY:s}}var n=10,o=40,a=800;t.exports=i}])});
update bundle
dist/bundle.min.js
update bundle
<ide><path>ist/bundle.min.js <ide> * @author Feross Aboukhadijeh <[email protected]> <http://feross.org> <ide> * @license MIT <ide> */ <del>var K=r(40),Q=r(41),$=r(13);e.Buffer=a,e.SlowBuffer=v,e.INSPECT_MAX_BYTES=50,a.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:i(),e.kMaxLength=n(),a.poolSize=8192,a._augment=function(t){return t.__proto__=a.prototype,t},a.from=function(t,e,r){return s(null,t,e,r)},a.TYPED_ARRAY_SUPPORT&&(a.prototype.__proto__=Uint8Array.prototype,a.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&a[Symbol.species]===a&&Object.defineProperty(a,Symbol.species,{value:null,configurable:!0})),a.alloc=function(t,e,r){return l(null,t,e,r)},a.allocUnsafe=function(t){return h(null,t)},a.allocUnsafeSlow=function(t){return h(null,t)},a.isBuffer=function t(e){return!(null==e||!e._isBuffer)},a.compare=function t(e,r){if(!a.isBuffer(e)||!a.isBuffer(r))throw new TypeError("Arguments must be Buffers");if(e===r)return 0;for(var i=e.length,n=r.length,o=0,s=Math.min(i,n);o<s;++o)if(e[o]!==r[o]){i=e[o],n=r[o];break}return i<n?-1:n<i?1:0},a.isEncoding=function t(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function t(e,r){if(!$(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return a.alloc(0);var i;if(void 0===r)for(r=0,i=0;i<e.length;++i)r+=e[i].length;var n=a.allocUnsafe(r),o=0;for(i=0;i<e.length;++i){var s=e[i];if(!a.isBuffer(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(n,o),o+=s.length}return n},a.byteLength=m,a.prototype._isBuffer=!0,a.prototype.swap16=function t(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var r=0;r<e;r+=2)y(this,r,r+1);return this},a.prototype.swap32=function t(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var r=0;r<e;r+=4)y(this,r,r+3),y(this,r+1,r+2);return this},a.prototype.swap64=function t(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var r=0;r<e;r+=8)y(this,r,r+7),y(this,r+1,r+6),y(this,r+2,r+5),y(this,r+3,r+4);return this},a.prototype.toString=function t(){var e=0|this.length;return 0===e?"":0===arguments.length?E(this,0,e):b.apply(this,arguments)},a.prototype.equals=function t(e){if(!a.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===a.compare(this,e)},a.prototype.inspect=function t(){var r="",i=e.INSPECT_MAX_BYTES;return this.length>0&&(r=this.toString("hex",0,i).match(/.{2}/g).join(" "),this.length>i&&(r+=" ... ")),"<Buffer "+r+">"},a.prototype.compare=function t(e,r,i,n,o){if(!a.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===r&&(r=0),void 0===i&&(i=e?e.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),r<0||i>e.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&r>=i)return 0;if(n>=o)return-1;if(r>=i)return 1;if(r>>>=0,i>>>=0,n>>>=0,o>>>=0,this===e)return 0;for(var s=o-n,c=i-r,l=Math.min(s,c),h=this.slice(n,o),u=e.slice(r,i),f=0;f<l;++f)if(h[f]!==u[f]){s=h[f],c=u[f];break}return s<c?-1:c<s?1:0},a.prototype.includes=function t(e,r,i){return-1!==this.indexOf(e,r,i)},a.prototype.indexOf=function t(e,r,i){return _(this,e,r,i,!0)},a.prototype.lastIndexOf=function t(e,r,i){return _(this,e,r,i,!1)},a.prototype.write=function t(e,r,i,n){if(void 0===r)n="utf8",i=this.length,r=0;else if(void 0===i&&"string"==typeof r)n=r,i=this.length,r=0;else{if(!isFinite(r))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");r|=0,isFinite(i)?(i|=0,void 0===n&&(n="utf8")):(n=i,i=void 0)}var o=this.length-r;if((void 0===i||i>o)&&(i=o),e.length>0&&(i<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var a=!1;;)switch(n){case"hex":return S(this,e,r,i);case"utf8":case"utf-8":return x(this,e,r,i);case"ascii":return C(this,e,r,i);case"latin1":case"binary":return A(this,e,r,i);case"base64":return T(this,e,r,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,e,r,i);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},a.prototype.toJSON=function t(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var tt=4096;a.prototype.slice=function t(e,r){var i=this.length;e=~~e,r=void 0===r?i:~~r,e<0?(e+=i)<0&&(e=0):e>i&&(e=i),r<0?(r+=i)<0&&(r=0):r>i&&(r=i),r<e&&(r=e);var n;if(a.TYPED_ARRAY_SUPPORT)n=this.subarray(e,r),n.__proto__=a.prototype;else{var o=r-e;n=new a(o,void 0);for(var s=0;s<o;++s)n[s]=this[s+e]}return n},a.prototype.readUIntLE=function t(e,r,i){e|=0,r|=0,i||j(e,r,this.length);for(var n=this[e],o=1,a=0;++a<r&&(o*=256);)n+=this[e+a]*o;return n},a.prototype.readUIntBE=function t(e,r,i){e|=0,r|=0,i||j(e,r,this.length);for(var n=this[e+--r],o=1;r>0&&(o*=256);)n+=this[e+--r]*o;return n},a.prototype.readUInt8=function t(e,r){return r||j(e,1,this.length),this[e]},a.prototype.readUInt16LE=function t(e,r){return r||j(e,2,this.length),this[e]|this[e+1]<<8},a.prototype.readUInt16BE=function t(e,r){return r||j(e,2,this.length),this[e]<<8|this[e+1]},a.prototype.readUInt32LE=function t(e,r){return r||j(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},a.prototype.readUInt32BE=function t(e,r){return r||j(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},a.prototype.readIntLE=function t(e,r,i){e|=0,r|=0,i||j(e,r,this.length);for(var n=this[e],o=1,a=0;++a<r&&(o*=256);)n+=this[e+a]*o;return o*=128,n>=o&&(n-=Math.pow(2,8*r)),n},a.prototype.readIntBE=function t(e,r,i){e|=0,r|=0,i||j(e,r,this.length);for(var n=r,o=1,a=this[e+--n];n>0&&(o*=256);)a+=this[e+--n]*o;return o*=128,a>=o&&(a-=Math.pow(2,8*r)),a},a.prototype.readInt8=function t(e,r){return r||j(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},a.prototype.readInt16LE=function t(e,r){r||j(e,2,this.length);var i=this[e]|this[e+1]<<8;return 32768&i?4294901760|i:i},a.prototype.readInt16BE=function t(e,r){r||j(e,2,this.length);var i=this[e+1]|this[e]<<8;return 32768&i?4294901760|i:i},a.prototype.readInt32LE=function t(e,r){return r||j(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},a.prototype.readInt32BE=function t(e,r){return r||j(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},a.prototype.readFloatLE=function t(e,r){return r||j(e,4,this.length),Q.read(this,e,!0,23,4)},a.prototype.readFloatBE=function t(e,r){return r||j(e,4,this.length),Q.read(this,e,!1,23,4)},a.prototype.readDoubleLE=function t(e,r){return r||j(e,8,this.length),Q.read(this,e,!0,52,8)},a.prototype.readDoubleBE=function t(e,r){return r||j(e,8,this.length),Q.read(this,e,!1,52,8)},a.prototype.writeUIntLE=function t(e,r,i,n){if(e=+e,r|=0,i|=0,!n){M(this,e,r,i,Math.pow(2,8*i)-1,0)}var o=1,a=0;for(this[r]=255&e;++a<i&&(o*=256);)this[r+a]=e/o&255;return r+i},a.prototype.writeUIntBE=function t(e,r,i,n){if(e=+e,r|=0,i|=0,!n){M(this,e,r,i,Math.pow(2,8*i)-1,0)}var o=i-1,a=1;for(this[r+o]=255&e;--o>=0&&(a*=256);)this[r+o]=e/a&255;return r+i},a.prototype.writeUInt8=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,1,255,0),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[r]=255&e,r+1},a.prototype.writeUInt16LE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[r]=255&e,this[r+1]=e>>>8):F(this,e,r,!0),r+2},a.prototype.writeUInt16BE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[r]=e>>>8,this[r+1]=255&e):F(this,e,r,!1),r+2},a.prototype.writeUInt32LE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=255&e):N(this,e,r,!0),r+4},a.prototype.writeUInt32BE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=255&e):N(this,e,r,!1),r+4},a.prototype.writeIntLE=function t(e,r,i,n){if(e=+e,r|=0,!n){var o=Math.pow(2,8*i-1);M(this,e,r,i,o-1,-o)}var a=0,s=1,c=0;for(this[r]=255&e;++a<i&&(s*=256);)e<0&&0===c&&0!==this[r+a-1]&&(c=1),this[r+a]=(e/s>>0)-c&255;return r+i},a.prototype.writeIntBE=function t(e,r,i,n){if(e=+e,r|=0,!n){var o=Math.pow(2,8*i-1);M(this,e,r,i,o-1,-o)}var a=i-1,s=1,c=0;for(this[r+a]=255&e;--a>=0&&(s*=256);)e<0&&0===c&&0!==this[r+a+1]&&(c=1),this[r+a]=(e/s>>0)-c&255;return r+i},a.prototype.writeInt8=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,1,127,-128),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[r]=255&e,r+1},a.prototype.writeInt16LE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[r]=255&e,this[r+1]=e>>>8):F(this,e,r,!0),r+2},a.prototype.writeInt16BE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[r]=e>>>8,this[r+1]=255&e):F(this,e,r,!1),r+2},a.prototype.writeInt32LE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,4,2147483647,-2147483648),a.TYPED_ARRAY_SUPPORT?(this[r]=255&e,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24):N(this,e,r,!0),r+4},a.prototype.writeInt32BE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),a.TYPED_ARRAY_SUPPORT?(this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=255&e):N(this,e,r,!1),r+4},a.prototype.writeFloatLE=function t(e,r,i){return U(this,e,r,!0,i)},a.prototype.writeFloatBE=function t(e,r,i){return U(this,e,r,!1,i)},a.prototype.writeDoubleLE=function t(e,r,i){return z(this,e,r,!0,i)},a.prototype.writeDoubleBE=function t(e,r,i){return z(this,e,r,!1,i)},a.prototype.copy=function t(e,r,i,n){if(i||(i=0),n||0===n||(n=this.length),r>=e.length&&(r=e.length),r||(r=0),n>0&&n<i&&(n=i),n===i)return 0;if(0===e.length||0===this.length)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(i<0||i>=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-r<n-i&&(n=e.length-r+i);var o=n-i,s;if(this===e&&i<r&&r<n)for(s=o-1;s>=0;--s)e[s+r]=this[s+i];else if(o<1e3||!a.TYPED_ARRAY_SUPPORT)for(s=0;s<o;++s)e[s+r]=this[s+i];else Uint8Array.prototype.set.call(e,this.subarray(i,i+o),r);return o},a.prototype.fill=function t(e,r,i,n){if("string"==typeof e){if("string"==typeof r?(n=r,r=0,i=this.length):"string"==typeof i&&(n=i,i=this.length),1===e.length){var o=e.charCodeAt(0);o<256&&(e=o)}if(void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!a.isEncoding(n))throw new TypeError("Unknown encoding: "+n)}else"number"==typeof e&&(e&=255);if(r<0||this.length<r||this.length<i)throw new RangeError("Out of range index");if(i<=r)return this;r>>>=0,i=void 0===i?this.length:i>>>0,e||(e=0);var s;if("number"==typeof e)for(s=r;s<i;++s)this[s]=e;else{var c=a.isBuffer(e)?e:G(new a(e,n).toString()),l=c.length;for(s=0;s<i-r;++s)this[s+r]=c[s%l]}return this};var et=/[^+\/0-9A-Za-z-_]/g}).call(e,r(0))},function(t,e){"function"==typeof Object.create?t.exports=function t(e,r){e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function t(e,r){e.super_=r;var i=function(){};i.prototype=r.prototype,e.prototype=new i,e.prototype.constructor=e}},function(t,e,r){"use strict";function i(t){if(!(this instanceof i))return new i(t);h.call(this,t),u.call(this,t),t&&!1===t.readable&&(this.readable=!1),t&&!1===t.writable&&(this.writable=!1),this.allowHalfOpen=!0,t&&!1===t.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",n)}function n(){this.allowHalfOpen||this._writableState.ended||s(o,this)}function o(t){t.end()}function a(t,e){for(var r=0,i=t.length;r<i;r++)e(t[r],r)}var s=r(7),c=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e};t.exports=i;var l=r(5);l.inherits=r(3);var h=r(14),u=r(18);l.inherits(i,h);for(var f=c(u.prototype),d=0;d<f.length;d++){var p=f[d];i.prototype[p]||(i.prototype[p]=u.prototype[p])}Object.defineProperty(i.prototype,"destroyed",{get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed&&this._writableState.destroyed)},set:function(t){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=t,this._writableState.destroyed=t)}}),i.prototype._destroy=function(t,e){this.push(null),this.end(),s(e,t)}},function(t,e,r){(function(t){function r(t){return Array.isArray?Array.isArray(t):"[object Array]"===v(t)}function i(t){return"boolean"==typeof t}function n(t){return null===t}function o(t){return null==t}function a(t){return"number"==typeof t}function s(t){return"string"==typeof t}function c(t){return"symbol"==typeof t}function l(t){return void 0===t}function h(t){return"[object RegExp]"===v(t)}function u(t){return"object"==typeof t&&null!==t}function f(t){return"[object Date]"===v(t)}function d(t){return"[object Error]"===v(t)||t instanceof Error}function p(t){return"function"==typeof t}function g(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t}function v(t){return Object.prototype.toString.call(t)}e.isArray=r,e.isBoolean=i,e.isNull=n,e.isNullOrUndefined=o,e.isNumber=a,e.isString=s,e.isSymbol=c,e.isUndefined=l,e.isRegExp=h,e.isObject=u,e.isDate=f,e.isError=d,e.isFunction=p,e.isPrimitive=g,e.isBuffer=t.isBuffer}).call(e,r(2).Buffer)},function(t,e,r){"use strict";function i(){p=!1}function n(t){if(!t)return void(f!==u&&(f=u,i()));if(t!==f){if(t.length!==u.length)throw new Error("Custom alphabet for shortid must be "+u.length+" unique characters. You submitted "+t.length+" characters: "+t);var e=t.split("").filter(function(t,e,r){return e!==r.lastIndexOf(t)});if(e.length)throw new Error("Custom alphabet for shortid must be "+u.length+" unique characters. These characters were not unique: "+e.join(", "));f=t,i()}}function o(t){return n(t),f}function a(t){h.seed(t),d!==t&&(i(),d=t)}function s(){f||n(u);for(var t=f.split(""),e=[],r=h.nextValue(),i;t.length>0;)r=h.nextValue(),i=Math.floor(r*t.length),e.push(t.splice(i,1)[0]);return e.join("")}function c(){return p||(p=s())}function l(t){return c()[t]}var h=r(32),u="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-",f,d,p;t.exports={characters:o,seed:a,lookup:l,shuffled:c}},function(t,e,r){"use strict";(function(e){function r(t,r,i,n){if("function"!=typeof t)throw new TypeError('"callback" argument must be a function');var o=arguments.length,a,s;switch(o){case 0:case 1:return e.nextTick(t);case 2:return e.nextTick(function e(){t.call(null,r)});case 3:return e.nextTick(function e(){t.call(null,r,i)});case 4:return e.nextTick(function e(){t.call(null,r,i,n)});default:for(a=new Array(o-1),s=0;s<a.length;)a[s++]=arguments[s];return e.nextTick(function e(){t.apply(null,a)})}}!e.version||0===e.version.indexOf("v0.")||0===e.version.indexOf("v1.")&&0!==e.version.indexOf("v1.8.")?t.exports=r:t.exports=e.nextTick}).call(e,r(1))},function(t,e,r){"use strict";var i="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;e.assign=function(t){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var r=e.shift();if(r){if("object"!=typeof r)throw new TypeError(r+"must be non-object");for(var i in r)r.hasOwnProperty(i)&&(t[i]=r[i])}}return t},e.shrinkBuf=function(t,e){return t.length===e?t:t.subarray?t.subarray(0,e):(t.length=e,t)};var n={arraySet:function(t,e,r,i,n){if(e.subarray&&t.subarray)return void t.set(e.subarray(r,r+i),n);for(var o=0;o<i;o++)t[n+o]=e[r+o]},flattenChunks:function(t){var e,r,i,n,o,a;for(i=0,e=0,r=t.length;e<r;e++)i+=t[e].length;for(a=new Uint8Array(i),n=0,e=0,r=t.length;e<r;e++)o=t[e],a.set(o,n),n+=o.length;return a}},o={arraySet:function(t,e,r,i,n){for(var o=0;o<i;o++)t[n+o]=e[r+o]},flattenChunks:function(t){return[].concat.apply([],t)}};e.setTyped=function(t){t?(e.Buf8=Uint8Array,e.Buf16=Uint16Array,e.Buf32=Int32Array,e.assign(e,n)):(e.Buf8=Array,e.Buf16=Array,e.Buf32=Array,e.assign(e,o))},e.setTyped(i)},function(t,e,r){e=t.exports=r(14),e.Stream=e,e.Readable=e,e.Writable=r(18),e.Duplex=r(4),e.Transform=r(20),e.PassThrough=r(49)},function(t,e,r){function i(t,e){for(var r in t)e[r]=t[r]}function n(t,e,r){return a(t,e,r)}var o=r(2),a=o.Buffer;a.from&&a.alloc&&a.allocUnsafe&&a.allocUnsafeSlow?t.exports=o:(i(o,e),e.Buffer=n),i(a,n),n.from=function(t,e,r){if("number"==typeof t)throw new TypeError("Argument must not be a number");return a(t,e,r)},n.alloc=function(t,e,r){if("number"!=typeof t)throw new TypeError("Argument must be a number");var i=a(t);return void 0!==e?"string"==typeof r?i.fill(e,r):i.fill(e):i.fill(0),i},n.allocUnsafe=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return a(t)},n.allocUnsafeSlow=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return o.SlowBuffer(t)}},function(t,e,r){"use strict";function i(t,e){for(var r=0,i,o="";!i;)o+=t(e>>4*r&15|n()),i=e<Math.pow(16,r+1),r++;return o}var n=r(33);t.exports=i},function(t,e,r){(function(e,i,n){!function e(r,i){t.exports=i()}(this,function(){return function(t){function e(i){if(r[i])return r[i].exports;var n=r[i]={i:i,l:!1,exports:{}};return t[i].call(n.exports,n,n.exports,e),n.l=!0,n.exports}var r={};return e.m=t,e.c=r,e.i=function(t){return t},e.d=function(t,r,i){e.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var r=t&&t.__esModule?function e(){return t.default}:function e(){return t};return e.d(r,"a",r),r},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=13)}([function(t,r,n){"use strict";function o(t){lt=t}function a(){return lt}function s(t){lt>=at.infos&&console.log("Info: "+t)}function c(t){lt>=at.warnings&&console.log("Warning: "+t)}function l(t){console.log("Deprecated API usage: "+t)}function h(t){throw new Error(t)}function u(t,e){t||h(e)}function f(t,e){try{var r=new URL(t);if(!r.origin||"null"===r.origin)return!1}catch(t){return!1}var i=new URL(e,r);return r.origin===i.origin}function d(t){if(!t)return!1;switch(t.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function p(t,e){if(!t)return null;try{var r=e?new URL(t,e):new URL(t);if(d(r))return r}catch(t){}return null}function g(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!1}),r}function v(t){var e;return function(){return t&&(e=Object.create(null),t(e),t=null),e}}function m(t){return"string"!=typeof t?(c("The argument for removeNullCharacters must be a string."),t):t.replace(wt,"")}function b(t){u(null!==t&&"object"===(void 0===t?"undefined":Y(t))&&void 0!==t.length,"Invalid argument for bytesToString");var e=t.length,r=8192;if(e<8192)return String.fromCharCode.apply(null,t);for(var i=[],n=0;n<e;n+=8192){var o=Math.min(n+8192,e),a=t.subarray(n,o);i.push(String.fromCharCode.apply(null,a))}return i.join("")}function y(t){u("string"==typeof t,"Invalid argument for stringToBytes");for(var e=t.length,r=new Uint8Array(e),i=0;i<e;++i)r[i]=255&t.charCodeAt(i);return r}function _(t){return void 0!==t.length?t.length:(u(void 0!==t.byteLength),t.byteLength)}function w(t){if(1===t.length&&t[0]instanceof Uint8Array)return t[0];var e=0,r,i=t.length,n,o;for(r=0;r<i;r++)n=t[r],o=_(n),e+=o;var a=0,s=new Uint8Array(e);for(r=0;r<i;r++)n=t[r],n instanceof Uint8Array||(n="string"==typeof n?y(n):new Uint8Array(n)),o=n.byteLength,s.set(n,a),a+=o;return s}function S(t){return String.fromCharCode(t>>24&255,t>>16&255,t>>8&255,255&t)}function x(t){for(var e=1,r=0;t>e;)e<<=1,r++;return r}function C(t,e){return t[e]<<24>>24}function A(t,e){return t[e]<<8|t[e+1]}function T(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}function k(){var t=new Uint8Array(4);return t[0]=1,1===new Uint32Array(t.buffer,0,1)[0]}function P(){try{return new Function(""),!0}catch(t){return!1}}function E(t){var e,r=t.length,i=[];if("þ"===t[0]&&"ÿ"===t[1])for(e=2;e<r;e+=2)i.push(String.fromCharCode(t.charCodeAt(e)<<8|t.charCodeAt(e+1)));else for(e=0;e<r;++e){var n=At[t.charCodeAt(e)];i.push(n?String.fromCharCode(n):t.charAt(e))}return i.join("")}function O(t){return decodeURIComponent(escape(t))}function R(t){return unescape(encodeURIComponent(t))}function L(t){for(var e in t)return!1;return!0}function D(t){return"boolean"==typeof t}function I(t){return"number"==typeof t&&(0|t)===t}function j(t){return"number"==typeof t}function M(t){return"string"==typeof t}function F(t){return t instanceof Array}function N(t){return"object"===(void 0===t?"undefined":Y(t))&&null!==t&&void 0!==t.byteLength}function B(t){return 32===t||9===t||13===t||10===t}function U(){return"object"===(void 0===i?"undefined":Y(i))&&i+""=="[object process]"}function z(){var t={};return t.promise=new Promise(function(e,r){t.resolve=e,t.reject=r}),t}function W(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;return t?new Promise(function(i,n){i(t.apply(r,e))}):Promise.resolve(void 0)}function q(t,e,r){e?t.resolve():t.reject(r)}function X(t){return Promise.resolve(t).catch(function(){})}function G(t,e,r){var i=this;this.sourceName=t,this.targetName=e,this.comObj=r,this.callbackId=1,this.streamId=1,this.postMessageTransfers=!0,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null);var n=this.callbacksCapabilities=Object.create(null),o=this.actionHandler=Object.create(null);this._onComObjOnMessage=function(t){var e=t.data;if(e.targetName===i.sourceName)if(e.stream)i._processStreamMessage(e);else if(e.isReply){var a=e.callbackId;if(!(e.callbackId in n))throw new Error("Cannot resolve callback "+a);var s=n[a];delete n[a],"error"in e?s.reject(e.error):s.resolve(e.data)}else{if(!(e.action in o))throw new Error("Unknown action from worker: "+e.action);var c=o[e.action];if(e.callbackId){var l=i.sourceName,h=e.sourceName;Promise.resolve().then(function(){return c[0].call(c[1],e.data)}).then(function(t){r.postMessage({sourceName:l,targetName:h,isReply:!0,callbackId:e.callbackId,data:t})},function(t){t instanceof Error&&(t+=""),r.postMessage({sourceName:l,targetName:h,isReply:!0,callbackId:e.callbackId,error:t})})}else e.streamId?i._createStreamSink(e):c[0].call(c[1],e.data)}},r.addEventListener("message",this._onComObjOnMessage)}function H(t,e,r){var i=new Image;i.onload=function e(){r.resolve(t,i)},i.onerror=function e(){r.resolve(t,null),c("Error during JPEG image loading")},i.src=e}Object.defineProperty(r,"__esModule",{value:!0}),r.unreachable=r.warn=r.utf8StringToString=r.stringToUTF8String=r.stringToPDFString=r.stringToBytes=r.string32=r.shadow=r.setVerbosityLevel=r.ReadableStream=r.removeNullCharacters=r.readUint32=r.readUint16=r.readInt8=r.log2=r.loadJpegStream=r.isEvalSupported=r.isLittleEndian=r.createValidAbsoluteUrl=r.isSameOrigin=r.isNodeJS=r.isSpace=r.isString=r.isNum=r.isInt=r.isEmptyObj=r.isBool=r.isArrayBuffer=r.isArray=r.info=r.globalScope=r.getVerbosityLevel=r.getLookupTableFactory=r.deprecated=r.createObjectURL=r.createPromiseCapability=r.createBlob=r.bytesToString=r.assert=r.arraysToBytes=r.arrayByteLength=r.FormatError=r.XRefParseException=r.Util=r.UnknownErrorException=r.UnexpectedResponseException=r.TextRenderingMode=r.StreamType=r.StatTimer=r.PasswordResponses=r.PasswordException=r.PageViewport=r.NotImplementedException=r.NativeImageDecoding=r.MissingPDFException=r.MissingDataException=r.MessageHandler=r.InvalidPDFException=r.CMapCompressionType=r.ImageKind=r.FontType=r.AnnotationType=r.AnnotationFlag=r.AnnotationFieldFlag=r.AnnotationBorderStyleType=r.UNSUPPORTED_FEATURES=r.VERBOSITY_LEVELS=r.OPS=r.IDENTITY_MATRIX=r.FONT_IDENTITY_MATRIX=void 0;var Y="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};n(14);var V=n(9),Z="undefined"!=typeof window&&window.Math===Math?window:void 0!==e&&e.Math===Math?e:"undefined"!=typeof self&&self.Math===Math?self:void 0,J=[.001,0,0,.001,0,0],K={NONE:"none",DECODE:"decode",DISPLAY:"display"},Q={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},$={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},tt={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},et={INVISIBLE:1,HIDDEN:2,PRINT:4,NOZOOM:8,NOROTATE:16,NOVIEW:32,READONLY:64,LOCKED:128,TOGGLENOVIEW:256,LOCKEDCONTENTS:512},rt={READONLY:1,REQUIRED:2,NOEXPORT:4,MULTILINE:4096,PASSWORD:8192,NOTOGGLETOOFF:16384,RADIO:32768,PUSHBUTTON:65536,COMBO:131072,EDIT:262144,SORT:524288,FILESELECT:1048576,MULTISELECT:2097152,DONOTSPELLCHECK:4194304,DONOTSCROLL:8388608,COMB:16777216,RICHTEXT:33554432,RADIOSINUNISON:33554432,COMMITONSELCHANGE:67108864},it={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},nt={UNKNOWN:0,FLATE:1,LZW:2,DCT:3,JPX:4,JBIG:5,A85:6,AHX:7,CCF:8,RL:9},ot={UNKNOWN:0,TYPE1:1,TYPE1C:2,CIDFONTTYPE0:3,CIDFONTTYPE0C:4,TRUETYPE:5,CIDFONTTYPE2:6,TYPE3:7,OPENTYPE:8,TYPE0:9,MMTYPE1:10},at={errors:0,warnings:1,infos:5},st={NONE:0,BINARY:1,STREAM:2},ct={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotations:78,endAnnotations:79,beginAnnotation:80,endAnnotation:81,paintJpegXObject:82,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91},lt=at.warnings,ht={unknown:"unknown",forms:"forms",javaScript:"javaScript",smask:"smask",shadingPattern:"shadingPattern",font:"font"},ut={NEED_PASSWORD:1,INCORRECT_PASSWORD:2},ft=function t(){function e(t,e){this.name="PasswordException",this.message=t,this.code=e}return e.prototype=new Error,e.constructor=e,e}(),dt=function t(){function e(t,e){this.name="UnknownErrorException",this.message=t,this.details=e}return e.prototype=new Error,e.constructor=e,e}(),pt=function t(){function e(t){this.name="InvalidPDFException",this.message=t}return e.prototype=new Error,e.constructor=e,e}(),gt=function t(){function e(t){this.name="MissingPDFException",this.message=t}return e.prototype=new Error,e.constructor=e,e}(),vt=function t(){function e(t,e){this.name="UnexpectedResponseException",this.message=t,this.status=e}return e.prototype=new Error,e.constructor=e,e}(),mt=function t(){function e(t){this.message=t}return e.prototype=new Error,e.prototype.name="NotImplementedException",e.constructor=e,e}(),bt=function t(){function e(t,e){this.begin=t,this.end=e,this.message="Missing data ["+t+", "+e+")"}return e.prototype=new Error,e.prototype.name="MissingDataException",e.constructor=e,e}(),yt=function t(){function e(t){this.message=t}return e.prototype=new Error,e.prototype.name="XRefParseException",e.constructor=e,e}(),_t=function t(){function e(t){this.message=t}return e.prototype=new Error,e.prototype.name="FormatError",e.constructor=e,e}(),wt=/\x00/g,St=[1,0,0,1,0,0],xt=function t(){function e(){}var r=["rgb(",0,",",0,",",0,")"];e.makeCssRgb=function t(e,i,n){return r[1]=e,r[3]=i,r[5]=n,r.join("")},e.transform=function t(e,r){return[e[0]*r[0]+e[2]*r[1],e[1]*r[0]+e[3]*r[1],e[0]*r[2]+e[2]*r[3],e[1]*r[2]+e[3]*r[3],e[0]*r[4]+e[2]*r[5]+e[4],e[1]*r[4]+e[3]*r[5]+e[5]]},e.applyTransform=function t(e,r){return[e[0]*r[0]+e[1]*r[2]+r[4],e[0]*r[1]+e[1]*r[3]+r[5]]},e.applyInverseTransform=function t(e,r){var i=r[0]*r[3]-r[1]*r[2];return[(e[0]*r[3]-e[1]*r[2]+r[2]*r[5]-r[4]*r[3])/i,(-e[0]*r[1]+e[1]*r[0]+r[4]*r[1]-r[5]*r[0])/i]},e.getAxialAlignedBoundingBox=function t(r,i){var n=e.applyTransform(r,i),o=e.applyTransform(r.slice(2,4),i),a=e.applyTransform([r[0],r[3]],i),s=e.applyTransform([r[2],r[1]],i);return[Math.min(n[0],o[0],a[0],s[0]),Math.min(n[1],o[1],a[1],s[1]),Math.max(n[0],o[0],a[0],s[0]),Math.max(n[1],o[1],a[1],s[1])]},e.inverseTransform=function t(e){var r=e[0]*e[3]-e[1]*e[2];return[e[3]/r,-e[1]/r,-e[2]/r,e[0]/r,(e[2]*e[5]-e[4]*e[3])/r,(e[4]*e[1]-e[5]*e[0])/r]},e.apply3dTransform=function t(e,r){return[e[0]*r[0]+e[1]*r[1]+e[2]*r[2],e[3]*r[0]+e[4]*r[1]+e[5]*r[2],e[6]*r[0]+e[7]*r[1]+e[8]*r[2]]},e.singularValueDecompose2dScale=function t(e){var r=[e[0],e[2],e[1],e[3]],i=e[0]*r[0]+e[1]*r[2],n=e[0]*r[1]+e[1]*r[3],o=e[2]*r[0]+e[3]*r[2],a=e[2]*r[1]+e[3]*r[3],s=(i+a)/2,c=Math.sqrt((i+a)*(i+a)-4*(i*a-o*n))/2,l=s+c||1,h=s-c||1;return[Math.sqrt(l),Math.sqrt(h)]},e.normalizeRect=function t(e){var r=e.slice(0);return e[0]>e[2]&&(r[0]=e[2],r[2]=e[0]),e[1]>e[3]&&(r[1]=e[3],r[3]=e[1]),r},e.intersect=function t(r,i){function n(t,e){return t-e}var o=[r[0],r[2],i[0],i[2]].sort(n),a=[r[1],r[3],i[1],i[3]].sort(n),s=[];return r=e.normalizeRect(r),i=e.normalizeRect(i),(o[0]===r[0]&&o[1]===i[0]||o[0]===i[0]&&o[1]===r[0])&&(s[0]=o[1],s[2]=o[2],(a[0]===r[1]&&a[1]===i[1]||a[0]===i[1]&&a[1]===r[1])&&(s[1]=a[1],s[3]=a[2],s))},e.sign=function t(e){return e<0?-1:1};var i=["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM","","X","XX","XXX","XL","L","LX","LXX","LXXX","XC","","I","II","III","IV","V","VI","VII","VIII","IX"];return e.toRoman=function t(e,r){u(I(e)&&e>0,"The number should be a positive integer.");for(var n,o=[];e>=1e3;)e-=1e3,o.push("M");n=e/100|0,e%=100,o.push(i[n]),n=e/10|0,e%=10,o.push(i[10+n]),o.push(i[20+e]);var a=o.join("");return r?a.toLowerCase():a},e.appendToArray=function t(e,r){Array.prototype.push.apply(e,r)},e.prependToArray=function t(e,r){Array.prototype.unshift.apply(e,r)},e.extendObj=function t(e,r){for(var i in r)e[i]=r[i]},e.getInheritableProperty=function t(e,r,i){for(;e&&!e.has(r);)e=e.get("Parent");return e?i?e.getArray(r):e.get(r):null},e.inherit=function t(e,r,i){e.prototype=Object.create(r.prototype),e.prototype.constructor=e;for(var n in i)e.prototype[n]=i[n]},e.loadScript=function t(e,r){var i=document.createElement("script"),n=!1;i.setAttribute("src",e),r&&(i.onload=function(){n||r(),n=!0}),document.getElementsByTagName("head")[0].appendChild(i)},e}(),Ct=function t(){function e(t,e,r,i,n,o){this.viewBox=t,this.scale=e,this.rotation=r,this.offsetX=i,this.offsetY=n;var a=(t[2]+t[0])/2,s=(t[3]+t[1])/2,c,l,h,u;switch(r%=360,r=r<0?r+360:r){case 180:c=-1,l=0,h=0,u=1;break;case 90:c=0,l=1,h=1,u=0;break;case 270:c=0,l=-1,h=-1,u=0;break;default:c=1,l=0,h=0,u=-1}o&&(h=-h,u=-u);var f,d,p,g;0===c?(f=Math.abs(s-t[1])*e+i,d=Math.abs(a-t[0])*e+n,p=Math.abs(t[3]-t[1])*e,g=Math.abs(t[2]-t[0])*e):(f=Math.abs(a-t[0])*e+i,d=Math.abs(s-t[1])*e+n,p=Math.abs(t[2]-t[0])*e,g=Math.abs(t[3]-t[1])*e),this.transform=[c*e,l*e,h*e,u*e,f-c*e*a-h*e*s,d-l*e*a-u*e*s],this.width=p,this.height=g,this.fontScale=e}return e.prototype={clone:function t(r){r=r||{};var i="scale"in r?r.scale:this.scale,n="rotation"in r?r.rotation:this.rotation;return new e(this.viewBox.slice(),i,n,this.offsetX,this.offsetY,r.dontFlip)},convertToViewportPoint:function t(e,r){return xt.applyTransform([e,r],this.transform)},convertToViewportRectangle:function t(e){var r=xt.applyTransform([e[0],e[1]],this.transform),i=xt.applyTransform([e[2],e[3]],this.transform);return[r[0],r[1],i[0],i[1]]},convertToPdfPoint:function t(e,r){return xt.applyInverseTransform([e,r],this.transform)}},e}(),At=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,728,711,710,729,733,731,730,732,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8226,8224,8225,8230,8212,8211,402,8260,8249,8250,8722,8240,8222,8220,8221,8216,8217,8218,8482,64257,64258,321,338,352,376,381,305,322,339,353,382,0,8364],Tt=function t(){function e(t,e,r){for(;t.length<r;)t+=e;return t}function r(){this.started=Object.create(null),this.times=[],this.enabled=!0}return r.prototype={time:function t(e){this.enabled&&(e in this.started&&c("Timer is already running for "+e),this.started[e]=Date.now())},timeEnd:function t(e){this.enabled&&(e in this.started||c("Timer has not been started for "+e),this.times.push({name:e,start:this.started[e],end:Date.now()}),delete this.started[e])},toString:function t(){var r,i,n=this.times,o="",a=0;for(r=0,i=n.length;r<i;++r){var s=n[r].name;s.length>a&&(a=s.length)}for(r=0,i=n.length;r<i;++r){var c=n[r],l=c.end-c.start;o+=e(c.name," ",a)+" "+l+"ms\n"}return o}},r}(),kt=function t(e,r){if("undefined"!=typeof Blob)return new Blob([e],{type:r});throw new Error('The "Blob" constructor is not supported.')},Pt=function t(){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";return function t(r,i){if(!(arguments.length>2&&void 0!==arguments[2]&&arguments[2])&&URL.createObjectURL){var n=kt(r,i);return URL.createObjectURL(n)}for(var o="data:"+i+";base64,",a=0,s=r.length;a<s;a+=3){var c=255&r[a],l=255&r[a+1],h=255&r[a+2];o+=e[c>>2]+e[(3&c)<<4|l>>4]+e[a+1<s?(15&l)<<2|h>>6:64]+e[a+2<s?63&h:64]}return o}}();G.prototype={on:function t(e,r,i){var n=this.actionHandler;if(n[e])throw new Error('There is already an actionName called "'+e+'"');n[e]=[r,i]},send:function t(e,r,i){var n={sourceName:this.sourceName,targetName:this.targetName,action:e,data:r};this.postMessage(n,i)},sendWithPromise:function t(e,r,i){var n=this.callbackId++,o={sourceName:this.sourceName,targetName:this.targetName,action:e,data:r,callbackId:n},a=z();this.callbacksCapabilities[n]=a;try{this.postMessage(o,i)}catch(t){a.reject(t)}return a.promise},sendWithStream:function t(e,r,i,n){var o=this,a=this.streamId++,s=this.sourceName,c=this.targetName;return new V.ReadableStream({start:function t(i){var n=z();return o.streamControllers[a]={controller:i,startCall:n,isClosed:!1},o.postMessage({sourceName:s,targetName:c,action:e,streamId:a,data:r,desiredSize:i.desiredSize}),n.promise},pull:function t(e){var r=z();return o.streamControllers[a].pullCall=r,o.postMessage({sourceName:s,targetName:c,stream:"pull",streamId:a,desiredSize:e.desiredSize}),r.promise},cancel:function t(e){var r=z();return o.streamControllers[a].cancelCall=r,o.streamControllers[a].isClosed=!0,o.postMessage({sourceName:s,targetName:c,stream:"cancel",reason:e,streamId:a}),r.promise}},i)},_createStreamSink:function t(e){var r=this,i=this,n=this.actionHandler[e.action],o=e.streamId,a=e.desiredSize,s=this.sourceName,c=e.sourceName,l=z(),h=function t(e){var i=e.stream,n=e.chunk,a=e.success,l=e.reason;r.comObj.postMessage({sourceName:s,targetName:c,stream:i,streamId:o,chunk:n,success:a,reason:l})},u={enqueue:function t(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;if(!this.isCancelled){var i=this.desiredSize;this.desiredSize-=r,i>0&&this.desiredSize<=0&&(this.sinkCapability=z(),this.ready=this.sinkCapability.promise),h({stream:"enqueue",chunk:e})}},close:function t(){this.isCancelled||(h({stream:"close"}),delete i.streamSinks[o])},error:function t(e){h({stream:"error",reason:e})},sinkCapability:l,onPull:null,onCancel:null,isCancelled:!1,desiredSize:a,ready:null};u.sinkCapability.resolve(),u.ready=u.sinkCapability.promise,this.streamSinks[o]=u,W(n[0],[e.data,u],n[1]).then(function(){h({stream:"start_complete",success:!0})},function(t){h({stream:"start_complete",success:!1,reason:t})})},_processStreamMessage:function t(e){var r=this,i=this.sourceName,n=e.sourceName,o=e.streamId,a=function t(e){var a=e.stream,s=e.success,c=e.reason;r.comObj.postMessage({sourceName:i,targetName:n,stream:a,success:s,streamId:o,reason:c})},s=function t(){Promise.all([r.streamControllers[e.streamId].startCall,r.streamControllers[e.streamId].pullCall,r.streamControllers[e.streamId].cancelCall].map(function(t){return t&&X(t.promise)})).then(function(){delete r.streamControllers[e.streamId]})};switch(e.stream){case"start_complete":q(this.streamControllers[e.streamId].startCall,e.success,e.reason);break;case"pull_complete":q(this.streamControllers[e.streamId].pullCall,e.success,e.reason);break;case"pull":if(!this.streamSinks[e.streamId]){a({stream:"pull_complete",success:!0});break}this.streamSinks[e.streamId].desiredSize<=0&&e.desiredSize>0&&this.streamSinks[e.streamId].sinkCapability.resolve(),this.streamSinks[e.streamId].desiredSize=e.desiredSize,W(this.streamSinks[e.streamId].onPull).then(function(){a({stream:"pull_complete",success:!0})},function(t){a({stream:"pull_complete",success:!1,reason:t})});break;case"enqueue":this.streamControllers[e.streamId].isClosed||this.streamControllers[e.streamId].controller.enqueue(e.chunk);break;case"close":if(this.streamControllers[e.streamId].isClosed)break;this.streamControllers[e.streamId].isClosed=!0,this.streamControllers[e.streamId].controller.close(),s();break;case"error":this.streamControllers[e.streamId].controller.error(e.reason),s();break;case"cancel_complete":q(this.streamControllers[e.streamId].cancelCall,e.success,e.reason),s();break;case"cancel":if(!this.streamSinks[e.streamId])break;W(this.streamSinks[e.streamId].onCancel,[e.reason]).then(function(){a({stream:"cancel_complete",success:!0})},function(t){a({stream:"cancel_complete",success:!1,reason:t})}),this.streamSinks[e.streamId].sinkCapability.reject(e.reason),this.streamSinks[e.streamId].isCancelled=!0,delete this.streamSinks[e.streamId];break;default:throw new Error("Unexpected stream case")}},postMessage:function t(e,r){r&&this.postMessageTransfers?this.comObj.postMessage(e,r):this.comObj.postMessage(e)},destroy:function t(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}},r.FONT_IDENTITY_MATRIX=J,r.IDENTITY_MATRIX=St,r.OPS=ct,r.VERBOSITY_LEVELS=at,r.UNSUPPORTED_FEATURES=ht,r.AnnotationBorderStyleType=it,r.AnnotationFieldFlag=rt,r.AnnotationFlag=et,r.AnnotationType=tt,r.FontType=ot,r.ImageKind=$,r.CMapCompressionType=st,r.InvalidPDFException=pt,r.MessageHandler=G,r.MissingDataException=bt,r.MissingPDFException=gt,r.NativeImageDecoding=K,r.NotImplementedException=mt,r.PageViewport=Ct,r.PasswordException=ft,r.PasswordResponses=ut,r.StatTimer=Tt,r.StreamType=nt,r.TextRenderingMode=Q,r.UnexpectedResponseException=vt,r.UnknownErrorException=dt,r.Util=xt,r.XRefParseException=yt,r.FormatError=_t,r.arrayByteLength=_,r.arraysToBytes=w,r.assert=u,r.bytesToString=b,r.createBlob=kt,r.createPromiseCapability=z,r.createObjectURL=Pt,r.deprecated=l,r.getLookupTableFactory=v,r.getVerbosityLevel=a,r.globalScope=Z,r.info=s,r.isArray=F,r.isArrayBuffer=N,r.isBool=D,r.isEmptyObj=L,r.isInt=I,r.isNum=j,r.isString=M,r.isSpace=B,r.isNodeJS=U,r.isSameOrigin=f,r.createValidAbsoluteUrl=p,r.isLittleEndian=k,r.isEvalSupported=P,r.loadJpegStream=H,r.log2=x,r.readInt8=C,r.readUint16=A,r.readUint32=T,r.removeNullCharacters=m,r.ReadableStream=V.ReadableStream,r.setVerbosityLevel=o,r.shadow=g,r.string32=S,r.stringToBytes=y,r.stringToPDFString=E,r.stringToUTF8String=O,r.utf8StringToString=R,r.warn=c,r.unreachable=h},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){var r=e&&e.url;if(t.href=t.title=r?(0,h.removeNullCharacters)(r):"",r){var i=e.target;void 0===i&&(i=a("externalLinkTarget")),t.target=m[i];var n=e.rel;void 0===n&&(n=a("externalLinkRel")),t.rel=n}}function o(t){var e=t.indexOf("#"),r=t.indexOf("?"),i=Math.min(e>0?e:t.length,r>0?r:t.length);return t.substring(t.lastIndexOf("/",i)+1,i)}function a(t){var e=h.globalScope.PDFJS;switch(t){case"pdfBug":return!!e&&e.pdfBug;case"disableAutoFetch":return!!e&&e.disableAutoFetch;case"disableStream":return!!e&&e.disableStream;case"disableRange":return!!e&&e.disableRange;case"disableFontFace":return!!e&&e.disableFontFace;case"disableCreateObjectURL":return!!e&&e.disableCreateObjectURL;case"disableWebGL":return!e||e.disableWebGL;case"cMapUrl":return e?e.cMapUrl:null;case"cMapPacked":return!!e&&e.cMapPacked;case"postMessageTransfers":return!e||e.postMessageTransfers;case"workerPort":return e?e.workerPort:null;case"workerSrc":return e?e.workerSrc:null;case"disableWorker":return!!e&&e.disableWorker;case"maxImageSize":return e?e.maxImageSize:-1;case"imageResourcesPath":return e?e.imageResourcesPath:"";case"isEvalSupported":return!e||e.isEvalSupported;case"externalLinkTarget":if(!e)return v.NONE;switch(e.externalLinkTarget){case v.NONE:case v.SELF:case v.BLANK:case v.PARENT:case v.TOP:return e.externalLinkTarget}return(0,h.warn)("PDFJS.externalLinkTarget is invalid: "+e.externalLinkTarget),e.externalLinkTarget=v.NONE,v.NONE;case"externalLinkRel":return e?e.externalLinkRel:u;case"enableStats":return!(!e||!e.enableStats);case"pdfjsNext":return!(!e||!e.pdfjsNext);default:throw new Error("Unknown default setting: "+t)}}function s(){switch(a("externalLinkTarget")){case v.NONE:return!1;case v.SELF:case v.BLANK:case v.PARENT:case v.TOP:return!0}}function c(t,e){(0,h.deprecated)("isValidUrl(), please use createValidAbsoluteUrl() instead.");var r=e?"http://example.com":null;return null!==(0,h.createValidAbsoluteUrl)(t,r)}Object.defineProperty(e,"__esModule",{value:!0}),e.DOMCMapReaderFactory=e.DOMCanvasFactory=e.DEFAULT_LINK_REL=e.getDefaultSetting=e.LinkTarget=e.getFilenameFromUrl=e.isValidUrl=e.isExternalLinkTargetSet=e.addLinkAttributes=e.RenderingCancelledException=e.CustomStyle=void 0;var l=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),h=r(0),u="noopener noreferrer nofollow",f=function(){function t(){i(this,t)}return l(t,[{key:"create",value:function t(e,r){if(e<=0||r<=0)throw new Error("invalid canvas size");var i=document.createElement("canvas"),n=i.getContext("2d");return i.width=e,i.height=r,{canvas:i,context:n}}},{key:"reset",value:function t(e,r,i){if(!e.canvas)throw new Error("canvas is not specified");if(r<=0||i<=0)throw new Error("invalid canvas size");e.canvas.width=r,e.canvas.height=i}},{key:"destroy",value:function t(e){if(!e.canvas)throw new Error("canvas is not specified");e.canvas.width=0,e.canvas.height=0,e.canvas=null,e.context=null}}]),t}(),d=function(){function t(e){var r=e.baseUrl,n=void 0===r?null:r,o=e.isCompressed,a=void 0!==o&&o;i(this,t),this.baseUrl=n,this.isCompressed=a}return l(t,[{key:"fetch",value:function t(e){var r=this,i=e.name;return i?new Promise(function(t,e){var n=r.baseUrl+i+(r.isCompressed?".bcmap":""),o=new XMLHttpRequest;o.open("GET",n,!0),r.isCompressed&&(o.responseType="arraybuffer"),o.onreadystatechange=function(){if(o.readyState===XMLHttpRequest.DONE){if(200===o.status||0===o.status){var i=void 0;if(r.isCompressed&&o.response?i=new Uint8Array(o.response):!r.isCompressed&&o.responseText&&(i=(0,h.stringToBytes)(o.responseText)),i)return void t({cMapData:i,compressionType:r.isCompressed?h.CMapCompressionType.BINARY:h.CMapCompressionType.NONE})}e(new Error("Unable to load "+(r.isCompressed?"binary ":"")+"CMap at: "+n))}},o.send(null)}):Promise.reject(new Error("CMap name must be specified."))}}]),t}(),p=function t(){function e(){}var r=["ms","Moz","Webkit","O"],i=Object.create(null);return e.getProp=function t(e,n){if(1===arguments.length&&"string"==typeof i[e])return i[e];n=n||document.documentElement;var o=n.style,a,s;if("string"==typeof o[e])return i[e]=e;s=e.charAt(0).toUpperCase()+e.slice(1);for(var c=0,l=r.length;c<l;c++)if(a=r[c]+s,"string"==typeof o[a])return i[e]=a;return i[e]="undefined"},e.setProp=function t(e,r,i){var n=this.getProp(e);"undefined"!==n&&(r.style[n]=i)},e}(),g=function t(){function t(t,e){this.message=t,this.type=e}return t.prototype=new Error,t.prototype.name="RenderingCancelledException",t.constructor=t,t}(),v={NONE:0,SELF:1,BLANK:2,PARENT:3,TOP:4},m=["","_self","_blank","_parent","_top"];e.CustomStyle=p,e.RenderingCancelledException=g,e.addLinkAttributes=n,e.isExternalLinkTargetSet=s,e.isValidUrl=c,e.getFilenameFromUrl=o,e.LinkTarget=v,e.getDefaultSetting=a,e.DEFAULT_LINK_REL=u,e.DOMCanvasFactory=f,e.DOMCMapReaderFactory=d},function(t,e,r){"use strict";function i(){}Object.defineProperty(e,"__esModule",{value:!0}),e.AnnotationLayer=void 0;var n=r(1),o=r(0);i.prototype={create:function t(e){switch(e.data.annotationType){case o.AnnotationType.LINK:return new s(e);case o.AnnotationType.TEXT:return new c(e);case o.AnnotationType.WIDGET:switch(e.data.fieldType){case"Tx":return new h(e);case"Btn":if(e.data.radioButton)return new f(e);if(e.data.checkBox)return new u(e);(0,o.warn)("Unimplemented button widget annotation: pushbutton");break;case"Ch":return new d(e)}return new l(e);case o.AnnotationType.POPUP:return new p(e);case o.AnnotationType.LINE:return new v(e);case o.AnnotationType.HIGHLIGHT:return new m(e);case o.AnnotationType.UNDERLINE:return new b(e);case o.AnnotationType.SQUIGGLY:return new y(e);case o.AnnotationType.STRIKEOUT:return new _(e);case o.AnnotationType.FILEATTACHMENT:return new w(e);default:return new a(e)}}};var a=function t(){function e(t,e,r){this.isRenderable=e||!1,this.data=t.data,this.layer=t.layer,this.page=t.page,this.viewport=t.viewport,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderInteractiveForms=t.renderInteractiveForms,e&&(this.container=this._createContainer(r))}return e.prototype={_createContainer:function t(e){var r=this.data,i=this.page,a=this.viewport,s=document.createElement("section"),c=r.rect[2]-r.rect[0],l=r.rect[3]-r.rect[1];s.setAttribute("data-annotation-id",r.id);var h=o.Util.normalizeRect([r.rect[0],i.view[3]-r.rect[1]+i.view[1],r.rect[2],i.view[3]-r.rect[3]+i.view[1]]);if(n.CustomStyle.setProp("transform",s,"matrix("+a.transform.join(",")+")"),n.CustomStyle.setProp("transformOrigin",s,-h[0]+"px "+-h[1]+"px"),!e&&r.borderStyle.width>0){s.style.borderWidth=r.borderStyle.width+"px",r.borderStyle.style!==o.AnnotationBorderStyleType.UNDERLINE&&(c-=2*r.borderStyle.width,l-=2*r.borderStyle.width);var u=r.borderStyle.horizontalCornerRadius,f=r.borderStyle.verticalCornerRadius;if(u>0||f>0){var d=u+"px / "+f+"px";n.CustomStyle.setProp("borderRadius",s,d)}switch(r.borderStyle.style){case o.AnnotationBorderStyleType.SOLID:s.style.borderStyle="solid";break;case o.AnnotationBorderStyleType.DASHED:s.style.borderStyle="dashed";break;case o.AnnotationBorderStyleType.BEVELED:(0,o.warn)("Unimplemented border style: beveled");break;case o.AnnotationBorderStyleType.INSET:(0,o.warn)("Unimplemented border style: inset");break;case o.AnnotationBorderStyleType.UNDERLINE:s.style.borderBottomStyle="solid"}r.color?s.style.borderColor=o.Util.makeCssRgb(0|r.color[0],0|r.color[1],0|r.color[2]):s.style.borderWidth=0}return s.style.left=h[0]+"px",s.style.top=h[1]+"px",s.style.width=c+"px",s.style.height=l+"px",s},_createPopup:function t(e,r,i){r||(r=document.createElement("div"),r.style.height=e.style.height,r.style.width=e.style.width,e.appendChild(r));var n=new g({container:e,trigger:r,color:i.color,title:i.title,contents:i.contents,hideWrapper:!0}),o=n.render();o.style.left=e.style.width,e.appendChild(o)},render:function t(){throw new Error("Abstract method AnnotationElement.render called")}},e}(),s=function t(){function e(t){a.call(this,t,!0)}return o.Util.inherit(e,a,{render:function t(){this.container.className="linkAnnotation";var e=document.createElement("a");return(0,n.addLinkAttributes)(e,{url:this.data.url,target:this.data.newWindow?n.LinkTarget.BLANK:void 0}),this.data.url||(this.data.action?this._bindNamedAction(e,this.data.action):this._bindLink(e,this.data.dest)),this.container.appendChild(e),this.container},_bindLink:function t(e,r){var i=this;e.href=this.linkService.getDestinationHash(r),e.onclick=function(){return r&&i.linkService.navigateTo(r),!1},r&&(e.className="internalLink")},_bindNamedAction:function t(e,r){var i=this;e.href=this.linkService.getAnchorUrl(""),e.onclick=function(){return i.linkService.executeNamedAction(r),!1},e.className="internalLink"}}),e}(),c=function t(){function e(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);a.call(this,t,e)}return o.Util.inherit(e,a,{render:function t(){this.container.className="textAnnotation";var e=document.createElement("img");return e.style.height=this.container.style.height,e.style.width=this.container.style.width,e.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",e.alt="[{{type}} Annotation]",e.dataset.l10nId="text_annotation_type",e.dataset.l10nArgs=JSON.stringify({type:this.data.name}),this.data.hasPopup||this._createPopup(this.container,e,this.data),this.container.appendChild(e),this.container}}),e}(),l=function t(){function e(t,e){a.call(this,t,e)}return o.Util.inherit(e,a,{render:function t(){return this.container}}),e}(),h=function t(){function e(t){var e=t.renderInteractiveForms||!t.data.hasAppearance&&!!t.data.fieldValue;l.call(this,t,e)}var r=["left","center","right"];return o.Util.inherit(e,l,{render:function t(){this.container.className="textWidgetAnnotation";var e=null;if(this.renderInteractiveForms){if(this.data.multiLine?(e=document.createElement("textarea"),e.textContent=this.data.fieldValue):(e=document.createElement("input"),e.type="text",e.setAttribute("value",this.data.fieldValue)),e.disabled=this.data.readOnly,null!==this.data.maxLen&&(e.maxLength=this.data.maxLen),this.data.comb){var i=this.data.rect[2]-this.data.rect[0],n=i/this.data.maxLen;e.classList.add("comb"),e.style.letterSpacing="calc("+n+"px - 1ch)"}}else{e=document.createElement("div"),e.textContent=this.data.fieldValue,e.style.verticalAlign="middle",e.style.display="table-cell";var o=null;this.data.fontRefName&&(o=this.page.commonObjs.getData(this.data.fontRefName)),this._setTextStyle(e,o)}return null!==this.data.textAlignment&&(e.style.textAlign=r[this.data.textAlignment]),this.container.appendChild(e),this.container},_setTextStyle:function t(e,r){var i=e.style;if(i.fontSize=this.data.fontSize+"px",i.direction=this.data.fontDirection<0?"rtl":"ltr",r){i.fontWeight=r.black?r.bold?"900":"bold":r.bold?"bold":"normal",i.fontStyle=r.italic?"italic":"normal";var n=r.loadedName?'"'+r.loadedName+'", ':"",o=r.fallbackName||"Helvetica, sans-serif";i.fontFamily=n+o}}}),e}(),u=function t(){function e(t){l.call(this,t,t.renderInteractiveForms)}return o.Util.inherit(e,l,{render:function t(){this.container.className="buttonWidgetAnnotation checkBox";var e=document.createElement("input");return e.disabled=this.data.readOnly,e.type="checkbox",this.data.fieldValue&&"Off"!==this.data.fieldValue&&e.setAttribute("checked",!0),this.container.appendChild(e),this.container}}),e}(),f=function t(){function e(t){l.call(this,t,t.renderInteractiveForms)}return o.Util.inherit(e,l,{render:function t(){this.container.className="buttonWidgetAnnotation radioButton";var e=document.createElement("input");return e.disabled=this.data.readOnly,e.type="radio",e.name=this.data.fieldName,this.data.fieldValue===this.data.buttonValue&&e.setAttribute("checked",!0),this.container.appendChild(e),this.container}}),e}(),d=function t(){function e(t){l.call(this,t,t.renderInteractiveForms)}return o.Util.inherit(e,l,{render:function t(){this.container.className="choiceWidgetAnnotation";var e=document.createElement("select");e.disabled=this.data.readOnly,this.data.combo||(e.size=this.data.options.length,this.data.multiSelect&&(e.multiple=!0));for(var r=0,i=this.data.options.length;r<i;r++){var n=this.data.options[r],o=document.createElement("option");o.textContent=n.displayValue,o.value=n.exportValue,this.data.fieldValue.indexOf(n.displayValue)>=0&&o.setAttribute("selected",!0),e.appendChild(o)}return this.container.appendChild(e),this.container}}),e}(),p=function t(){function e(t){var e=!(!t.data.title&&!t.data.contents);a.call(this,t,e)}var r=["Line"];return o.Util.inherit(e,a,{render:function t(){if(this.container.className="popupAnnotation",r.indexOf(this.data.parentType)>=0)return this.container;var e='[data-annotation-id="'+this.data.parentId+'"]',i=this.layer.querySelector(e);if(!i)return this.container;var o=new g({container:this.container,trigger:i,color:this.data.color,title:this.data.title,contents:this.data.contents}),a=parseFloat(i.style.left),s=parseFloat(i.style.width);return n.CustomStyle.setProp("transformOrigin",this.container,-(a+s)+"px -"+i.style.top),this.container.style.left=a+s+"px",this.container.appendChild(o.render()),this.container}}),e}(),g=function t(){function e(t){this.container=t.container,this.trigger=t.trigger,this.color=t.color,this.title=t.title,this.contents=t.contents,this.hideWrapper=t.hideWrapper||!1,this.pinned=!1}var r=.7;return e.prototype={render:function t(){var e=document.createElement("div");e.className="popupWrapper",this.hideElement=this.hideWrapper?e:this.container,this.hideElement.setAttribute("hidden",!0);var r=document.createElement("div");r.className="popup";var i=this.color;if(i){var n=.7*(255-i[0])+i[0],a=.7*(255-i[1])+i[1],s=.7*(255-i[2])+i[2];r.style.backgroundColor=o.Util.makeCssRgb(0|n,0|a,0|s)}var c=this._formatContents(this.contents),l=document.createElement("h1");return l.textContent=this.title,this.trigger.addEventListener("click",this._toggle.bind(this)),this.trigger.addEventListener("mouseover",this._show.bind(this,!1)),this.trigger.addEventListener("mouseout",this._hide.bind(this,!1)),r.addEventListener("click",this._hide.bind(this,!0)),r.appendChild(l),r.appendChild(c),e.appendChild(r),e},_formatContents:function t(e){for(var r=document.createElement("p"),i=e.split(/(?:\r\n?|\n)/),n=0,o=i.length;n<o;++n){var a=i[n];r.appendChild(document.createTextNode(a)),n<o-1&&r.appendChild(document.createElement("br"))}return r},_toggle:function t(){this.pinned?this._hide(!0):this._show(!0)},_show:function t(e){e&&(this.pinned=!0),this.hideElement.hasAttribute("hidden")&&(this.hideElement.removeAttribute("hidden"),this.container.style.zIndex+=1)},_hide:function t(e){e&&(this.pinned=!1),this.hideElement.hasAttribute("hidden")||this.pinned||(this.hideElement.setAttribute("hidden",!0),this.container.style.zIndex-=1)}},e}(),v=function t(){function e(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);a.call(this,t,e,!0)}var r="http://www.w3.org/2000/svg";return o.Util.inherit(e,a,{render:function t(){this.container.className="lineAnnotation";var e=this.data,i=e.rect[2]-e.rect[0],n=e.rect[3]-e.rect[1],o=document.createElementNS(r,"svg:svg");o.setAttributeNS(null,"version","1.1"),o.setAttributeNS(null,"width",i+"px"),o.setAttributeNS(null,"height",n+"px"),o.setAttributeNS(null,"preserveAspectRatio","none"),o.setAttributeNS(null,"viewBox","0 0 "+i+" "+n);var a=document.createElementNS(r,"svg:line");return a.setAttributeNS(null,"x1",e.rect[2]-e.lineCoordinates[0]),a.setAttributeNS(null,"y1",e.rect[3]-e.lineCoordinates[1]),a.setAttributeNS(null,"x2",e.rect[2]-e.lineCoordinates[2]),a.setAttributeNS(null,"y2",e.rect[3]-e.lineCoordinates[3]),a.setAttributeNS(null,"stroke-width",e.borderStyle.width),a.setAttributeNS(null,"stroke","transparent"),o.appendChild(a),this.container.append(o),this._createPopup(this.container,a,this.data),this.container}}),e}(),m=function t(){function e(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);a.call(this,t,e,!0)}return o.Util.inherit(e,a,{render:function t(){return this.container.className="highlightAnnotation",this.data.hasPopup||this._createPopup(this.container,null,this.data),this.container}}),e}(),b=function t(){function e(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);a.call(this,t,e,!0)}return o.Util.inherit(e,a,{render:function t(){return this.container.className="underlineAnnotation",this.data.hasPopup||this._createPopup(this.container,null,this.data),this.container}}),e}(),y=function t(){function e(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);a.call(this,t,e,!0)}return o.Util.inherit(e,a,{render:function t(){return this.container.className="squigglyAnnotation",this.data.hasPopup||this._createPopup(this.container,null,this.data),this.container}}),e}(),_=function t(){function e(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);a.call(this,t,e,!0)}return o.Util.inherit(e,a,{render:function t(){return this.container.className="strikeoutAnnotation",this.data.hasPopup||this._createPopup(this.container,null,this.data),this.container}}),e}(),w=function t(){function e(t){a.call(this,t,!0);var e=this.data.file;this.filename=(0,n.getFilenameFromUrl)(e.filename),this.content=e.content,this.linkService.onFileAttachmentAnnotation({id:(0,o.stringToPDFString)(e.filename),filename:e.filename,content:e.content})}return o.Util.inherit(e,a,{render:function t(){this.container.className="fileAttachmentAnnotation";var e=document.createElement("div");return e.style.height=this.container.style.height,e.style.width=this.container.style.width,e.addEventListener("dblclick",this._download.bind(this)),this.data.hasPopup||!this.data.title&&!this.data.contents||this._createPopup(this.container,e,this.data),this.container.appendChild(e),this.container},_download:function t(){if(!this.downloadManager)return void(0,o.warn)("Download cannot be started due to unavailable download manager");this.downloadManager.downloadData(this.content,this.filename,"")}}),e}(),S=function t(){return{render:function t(e){for(var r=new i,o=0,a=e.annotations.length;o<a;o++){var s=e.annotations[o];if(s){var c=r.create({data:s,layer:e.div,page:e.page,viewport:e.viewport,linkService:e.linkService,downloadManager:e.downloadManager,imageResourcesPath:e.imageResourcesPath||(0,n.getDefaultSetting)("imageResourcesPath"),renderInteractiveForms:e.renderInteractiveForms||!1});c.isRenderable&&e.div.appendChild(c.render())}}},update:function t(e){for(var r=0,i=e.annotations.length;r<i;r++){var o=e.annotations[r],a=e.div.querySelector('[data-annotation-id="'+o.id+'"]');a&&n.CustomStyle.setProp("transform",a,"matrix("+e.viewport.transform.join(",")+")")}e.div.removeAttribute("hidden")}}}();e.AnnotationLayer=S},function(t,e,i){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e,r,i){var n=new S;arguments.length>1&&(0,l.deprecated)("getDocument is called with pdfDataRangeTransport, passwordCallback or progressCallback argument"),e&&(e instanceof x||(e=Object.create(e),e.length=t.length,e.initialData=t.initialData,e.abort||(e.abort=function(){})),t=Object.create(t),t.range=e),n.onPassword=r||null,n.onProgress=i||null;var o;if("string"==typeof t)o={url:t};else if((0,l.isArrayBuffer)(t))o={data:t};else if(t instanceof x)o={range:t};else{if("object"!==(void 0===t?"undefined":c(t)))throw new Error("Invalid parameter in getDocument, need either Uint8Array, string or a parameter object");if(!t.url&&!t.data&&!t.range)throw new Error("Invalid parameter object: need either .data, .range or .url");o=t}var s={},u=null,f=null,d=h.DOMCMapReaderFactory;for(var g in o)if("url"!==g||"undefined"==typeof window)if("range"!==g)if("worker"!==g)if("data"!==g||o[g]instanceof Uint8Array)"CMapReaderFactory"!==g?s[g]=o[g]:d=o[g];else{var v=o[g];if("string"==typeof v)s[g]=(0,l.stringToBytes)(v);else if("object"!==(void 0===v?"undefined":c(v))||null===v||isNaN(v.length)){if(!(0,l.isArrayBuffer)(v))throw new Error("Invalid PDF binary data: either typed array, string or array-like object is expected in the data property.");s[g]=new Uint8Array(v)}else s[g]=new Uint8Array(v)}else f=o[g];else u=o[g];else s[g]=new URL(o[g],window.location).href;if(s.rangeChunkSize=s.rangeChunkSize||p,s.ignoreErrors=!0!==s.stopAtErrors,void 0!==s.disableNativeImageDecoder&&(0,l.deprecated)("parameter disableNativeImageDecoder, use nativeImageDecoderSupport instead"),s.nativeImageDecoderSupport=s.nativeImageDecoderSupport||(!0===s.disableNativeImageDecoder?l.NativeImageDecoding.NONE:l.NativeImageDecoding.DECODE),s.nativeImageDecoderSupport!==l.NativeImageDecoding.DECODE&&s.nativeImageDecoderSupport!==l.NativeImageDecoding.NONE&&s.nativeImageDecoderSupport!==l.NativeImageDecoding.DISPLAY&&((0,l.warn)("Invalid parameter nativeImageDecoderSupport: need a state of enum {NativeImageDecoding}"),s.nativeImageDecoderSupport=l.NativeImageDecoding.DECODE),!f){var m=(0,h.getDefaultSetting)("workerPort");f=m?k.fromPort(m):new k,n._worker=f}var b=n.docId;return f.promise.then(function(){if(n.destroyed)throw new Error("Loading aborted");return a(f,s,u,b).then(function(t){if(n.destroyed)throw new Error("Loading aborted");var e=new l.MessageHandler(b,t,f.port),r=new P(e,n,u,d);n._transport=r,e.send("Ready",null)})}).catch(n._capability.reject),n}function a(t,e,r,i){return t.destroyed?Promise.reject(new Error("Worker was destroyed")):(e.disableAutoFetch=(0,h.getDefaultSetting)("disableAutoFetch"),e.disableStream=(0,h.getDefaultSetting)("disableStream"),e.chunkedViewerLoading=!!r,r&&(e.length=r.length,e.initialData=r.initialData),t.messageHandler.sendWithPromise("GetDocRequest",{docId:i,source:e,disableRange:(0,h.getDefaultSetting)("disableRange"),maxImageSize:(0,h.getDefaultSetting)("maxImageSize"),disableFontFace:(0,h.getDefaultSetting)("disableFontFace"),disableCreateObjectURL:(0,h.getDefaultSetting)("disableCreateObjectURL"),postMessageTransfers:(0,h.getDefaultSetting)("postMessageTransfers")&&!m,docBaseUrl:e.docBaseUrl,nativeImageDecoderSupport:e.nativeImageDecoderSupport,ignoreErrors:e.ignoreErrors}).then(function(e){if(t.destroyed)throw new Error("Worker was destroyed");return e}))}Object.defineProperty(e,"__esModule",{value:!0}),e.build=e.version=e._UnsupportedManager=e.PDFPageProxy=e.PDFDocumentProxy=e.PDFWorker=e.PDFDataRangeTransport=e.LoopbackPort=e.getDocument=void 0;var s=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},l=i(0),h=i(1),u=i(11),f=i(10),d=i(6),p=65536,g=!1,v,m=!1,b="undefined"!=typeof document&&document.currentScript?document.currentScript.src:null,y=null,_=!1;"undefined"==typeof window?(g=!0,_=!0):_=!0,"undefined"!=typeof requirejs&&requirejs.toUrl&&(v=requirejs.toUrl("pdfjs-dist/build/pdf.worker.js"));var w="undefined"!=typeof requirejs&&requirejs.load;y=_?function(t){r.e(0).then(function(){var e;e=r(81),t(e.WorkerMessageHandler)}.bind(null,r)).catch(r.oe)}:w?function(t){requirejs(["pdfjs-dist/build/pdf.worker"],function(e){t(e.WorkerMessageHandler)})}:null;var S=function t(){function e(){this._capability=(0,l.createPromiseCapability)(),this._transport=null,this._worker=null,this.docId="d"+r++,this.destroyed=!1,this.onPassword=null,this.onProgress=null,this.onUnsupportedFeature=null}var r=0;return e.prototype={get promise(){return this._capability.promise},destroy:function t(){var e=this;return this.destroyed=!0,(this._transport?this._transport.destroy():Promise.resolve()).then(function(){e._transport=null,e._worker&&(e._worker.destroy(),e._worker=null)})},then:function t(e,r){return this.promise.then.apply(this.promise,arguments)}},e}(),x=function t(){function e(t,e){this.length=t,this.initialData=e,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._readyCapability=(0,l.createPromiseCapability)()}return e.prototype={addRangeListener:function t(e){this._rangeListeners.push(e)},addProgressListener:function t(e){this._progressListeners.push(e)},addProgressiveReadListener:function t(e){this._progressiveReadListeners.push(e)},onDataRange:function t(e,r){for(var i=this._rangeListeners,n=0,o=i.length;n<o;++n)i[n](e,r)},onDataProgress:function t(e){var r=this;this._readyCapability.promise.then(function(){for(var t=r._progressListeners,i=0,n=t.length;i<n;++i)t[i](e)})},onDataProgressiveRead:function t(e){var r=this;this._readyCapability.promise.then(function(){for(var t=r._progressiveReadListeners,i=0,n=t.length;i<n;++i)t[i](e)})},transportReady:function t(){this._readyCapability.resolve()},requestDataRange:function t(e,r){throw new Error("Abstract method PDFDataRangeTransport.requestDataRange")},abort:function t(){}},e}(),C=function t(){function e(t,e,r){this.pdfInfo=t,this.transport=e,this.loadingTask=r}return e.prototype={get numPages(){return this.pdfInfo.numPages},get fingerprint(){return this.pdfInfo.fingerprint},getPage:function t(e){return this.transport.getPage(e)},getPageIndex:function t(e){return this.transport.getPageIndex(e)},getDestinations:function t(){return this.transport.getDestinations()},getDestination:function t(e){return this.transport.getDestination(e)},getPageLabels:function t(){return this.transport.getPageLabels()},getPageMode:function t(){return this.transport.getPageMode()},getAttachments:function t(){return this.transport.getAttachments()},getJavaScript:function t(){return this.transport.getJavaScript()},getOutline:function t(){return this.transport.getOutline()},getMetadata:function t(){return this.transport.getMetadata()},getData:function t(){return this.transport.getData()},getDownloadInfo:function t(){return this.transport.downloadInfoCapability.promise},getStats:function t(){return this.transport.getStats()},cleanup:function t(){this.transport.startCleanup()},destroy:function t(){return this.loadingTask.destroy()}},e}(),A=function t(){function e(t,e,r){this.pageIndex=t,this.pageInfo=e,this.transport=r,this.stats=new l.StatTimer,this.stats.enabled=(0,h.getDefaultSetting)("enableStats"),this.commonObjs=r.commonObjs,this.objs=new E,this.cleanupAfterRender=!1,this.pendingCleanup=!1,this.intentStates=Object.create(null),this.destroyed=!1}return e.prototype={get pageNumber(){return this.pageIndex+1},get rotate(){return this.pageInfo.rotate},get ref(){return this.pageInfo.ref},get userUnit(){return this.pageInfo.userUnit},get view(){return this.pageInfo.view},getViewport:function t(e,r){return arguments.length<2&&(r=this.rotate),new l.PageViewport(this.view,e,r,0,0)},getAnnotations:function t(e){var r=e&&e.intent||null;return this.annotationsPromise&&this.annotationsIntent===r||(this.annotationsPromise=this.transport.getAnnotations(this.pageIndex,r),this.annotationsIntent=r),this.annotationsPromise},render:function t(e){var r=this,i=this.stats;i.time("Overall"),this.pendingCleanup=!1;var n="print"===e.intent?"print":"display",o=e.canvasFactory||new h.DOMCanvasFactory;this.intentStates[n]||(this.intentStates[n]=Object.create(null));var a=this.intentStates[n];a.displayReadyCapability||(a.receivingOperatorList=!0,a.displayReadyCapability=(0,l.createPromiseCapability)(),a.operatorList={fnArray:[],argsArray:[],lastChunk:!1},this.stats.time("Page Request"),this.transport.messageHandler.send("RenderPageRequest",{pageIndex:this.pageNumber-1,intent:n,renderInteractiveForms:!0===e.renderInteractiveForms}));var s=function t(e){var n=a.renderTasks.indexOf(c);n>=0&&a.renderTasks.splice(n,1),r.cleanupAfterRender&&(r.pendingCleanup=!0),r._tryCleanup(),e?c.capability.reject(e):c.capability.resolve(),i.timeEnd("Rendering"),i.timeEnd("Overall")},c=new R(s,e,this.objs,this.commonObjs,a.operatorList,this.pageNumber,o);c.useRequestAnimationFrame="print"!==n,a.renderTasks||(a.renderTasks=[]),a.renderTasks.push(c);var u=c.task;return e.continueCallback&&((0,l.deprecated)("render is used with continueCallback parameter"),u.onContinue=e.continueCallback),a.displayReadyCapability.promise.then(function(t){if(r.pendingCleanup)return void s();i.time("Rendering"),c.initializeGraphics(t),c.operatorListChanged()}).catch(s),u},getOperatorList:function t(){function e(){if(i.operatorList.lastChunk){i.opListReadCapability.resolve(i.operatorList);var t=i.renderTasks.indexOf(n);t>=0&&i.renderTasks.splice(t,1)}}var r="oplist";this.intentStates.oplist||(this.intentStates.oplist=Object.create(null));var i=this.intentStates.oplist,n;return i.opListReadCapability||(n={},n.operatorListChanged=e,i.receivingOperatorList=!0,i.opListReadCapability=(0,l.createPromiseCapability)(),i.renderTasks=[],i.renderTasks.push(n),i.operatorList={fnArray:[],argsArray:[],lastChunk:!1},this.transport.messageHandler.send("RenderPageRequest",{pageIndex:this.pageIndex,intent:"oplist"})),i.opListReadCapability.promise},streamTextContent:function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=100;return this.transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this.pageNumber-1,normalizeWhitespace:!0===e.normalizeWhitespace,combineTextItems:!0!==e.disableCombineTextItems},{highWaterMark:100,size:function t(e){return e.items.length}})},getTextContent:function t(e){e=e||{};var r=this.streamTextContent(e);return new Promise(function(t,e){function i(){n.read().then(function(e){var r=e.value;if(e.done)return void t(o);l.Util.extendObj(o.styles,r.styles),l.Util.appendToArray(o.items,r.items),i()},e)}var n=r.getReader(),o={items:[],styles:Object.create(null)};i()})},_destroy:function t(){this.destroyed=!0,this.transport.pageCache[this.pageIndex]=null;var e=[];return Object.keys(this.intentStates).forEach(function(t){if("oplist"!==t){this.intentStates[t].renderTasks.forEach(function(t){var r=t.capability.promise.catch(function(){});e.push(r),t.cancel()})}},this),this.objs.clear(),this.annotationsPromise=null,this.pendingCleanup=!1,Promise.all(e)},destroy:function t(){(0,l.deprecated)("page destroy method, use cleanup() instead"),this.cleanup()},cleanup:function t(){this.pendingCleanup=!0,this._tryCleanup()},_tryCleanup:function t(){this.pendingCleanup&&!Object.keys(this.intentStates).some(function(t){var e=this.intentStates[t];return 0!==e.renderTasks.length||e.receivingOperatorList},this)&&(Object.keys(this.intentStates).forEach(function(t){delete this.intentStates[t]},this),this.objs.clear(),this.annotationsPromise=null,this.pendingCleanup=!1)},_startRenderPage:function t(e,r){var i=this.intentStates[r];i.displayReadyCapability&&i.displayReadyCapability.resolve(e)},_renderPageChunk:function t(e,r){var i=this.intentStates[r],n,o;for(n=0,o=e.length;n<o;n++)i.operatorList.fnArray.push(e.fnArray[n]),i.operatorList.argsArray.push(e.argsArray[n]);for(i.operatorList.lastChunk=e.lastChunk,n=0;n<i.renderTasks.length;n++)i.renderTasks[n].operatorListChanged();e.lastChunk&&(i.receivingOperatorList=!1,this._tryCleanup())}},e}(),T=function(){function t(e){n(this,t),this._listeners=[],this._defer=e,this._deferred=Promise.resolve(void 0)}return s(t,[{key:"postMessage",value:function t(e,r){function i(t){if("object"!==(void 0===t?"undefined":c(t))||null===t)return t;if(o.has(t))return o.get(t);var e,n;if((n=t.buffer)&&(0,l.isArrayBuffer)(n)){var a=r&&r.indexOf(n)>=0;return e=t===n?t:a?new t.constructor(n,t.byteOffset,t.byteLength):new t.constructor(t),o.set(t,e),e}e=(0,l.isArray)(t)?[]:{},o.set(t,e);for(var s in t){for(var h,u=t;!(h=Object.getOwnPropertyDescriptor(u,s));)u=Object.getPrototypeOf(u);void 0!==h.value&&"function"!=typeof h.value&&(e[s]=i(h.value))}return e}var n=this;if(!this._defer)return void this._listeners.forEach(function(t){t.call(this,{data:e})},this);var o=new WeakMap,a={data:i(e)};this._deferred.then(function(){n._listeners.forEach(function(t){t.call(this,a)},n)})}},{key:"addEventListener",value:function t(e,r){this._listeners.push(r)}},{key:"removeEventListener",value:function t(e,r){var i=this._listeners.indexOf(r);this._listeners.splice(i,1)}},{key:"terminate",value:function t(){this._listeners=[]}}]),t}(),k=function t(){function e(){if(void 0!==v)return v;if((0,h.getDefaultSetting)("workerSrc"))return(0,h.getDefaultSetting)("workerSrc");if(b)return b.replace(/(\.(?:min\.)?js)(\?.*)?$/i,".worker$1$2");throw new Error("No PDFJS.workerSrc specified")}function r(){var t;return a?a.promise:(a=(0,l.createPromiseCapability)(),(y||function(t){l.Util.loadScript(e(),function(){t(window.pdfjsDistBuildPdfWorker.WorkerMessageHandler)})})(a.resolve),a.promise)}function i(t){var e="importScripts('"+t+"');";return URL.createObjectURL(new Blob([e]))}function n(t,e){if(e&&s.has(e))throw new Error("Cannot use more than one PDFWorker per port");if(this.name=t,this.destroyed=!1,this._readyCapability=(0,l.createPromiseCapability)(),this._port=null,this._webWorker=null,this._messageHandler=null,e)return s.set(e,this),void this._initializeFromPort(e);this._initialize()}var o=0,a=void 0,s=new WeakMap;return n.prototype={get promise(){return this._readyCapability.promise},get port(){return this._port},get messageHandler(){return this._messageHandler},_initializeFromPort:function t(e){this._port=e,this._messageHandler=new l.MessageHandler("main","worker",e),this._messageHandler.on("ready",function(){}),this._readyCapability.resolve()},_initialize:function t(){var r=this;if(!g&&!(0,h.getDefaultSetting)("disableWorker")&&"undefined"!=typeof Worker){var n=e();try{(0,l.isSameOrigin)(window.location.href,n)||(n=i(new URL(n,window.location).href));var o=new Worker(n),a=new l.MessageHandler("main","worker",o),s=function t(){o.removeEventListener("error",c),a.destroy(),o.terminate(),r.destroyed?r._readyCapability.reject(new Error("Worker was destroyed")):r._setupFakeWorker()},c=function t(){r._webWorker||s()};o.addEventListener("error",c),a.on("test",function(t){if(o.removeEventListener("error",c),r.destroyed)return void s();t&&t.supportTypedArray?(r._messageHandler=a,r._port=o,r._webWorker=o,t.supportTransfers||(m=!0),r._readyCapability.resolve(),a.send("configure",{verbosity:(0,l.getVerbosityLevel)()})):(r._setupFakeWorker(),a.destroy(),o.terminate())}),a.on("console_log",function(t){console.log.apply(console,t)}),a.on("console_error",function(t){console.error.apply(console,t)}),a.on("ready",function(t){if(o.removeEventListener("error",c),r.destroyed)return void s();try{u()}catch(t){r._setupFakeWorker()}});var u=function t(){var e=(0,h.getDefaultSetting)("postMessageTransfers")&&!m,r=new Uint8Array([e?255:0]);try{a.send("test",r,[r.buffer])}catch(t){(0,l.info)("Cannot use postMessage transfers"),r[0]=0,a.send("test",r)}};return void u()}catch(t){(0,l.info)("The worker has been disabled.")}}this._setupFakeWorker()},_setupFakeWorker:function t(){var e=this;g||(0,h.getDefaultSetting)("disableWorker")||((0,l.warn)("Setting up fake worker."),g=!0),r().then(function(t){if(e.destroyed)return void e._readyCapability.reject(new Error("Worker was destroyed"));var r=Uint8Array!==Float32Array,i=new T(r);e._port=i;var n="fake"+o++,a=new l.MessageHandler(n+"_worker",n,i);t.setup(a,i);var s=new l.MessageHandler(n,n+"_worker",i);e._messageHandler=s,e._readyCapability.resolve()})},destroy:function t(){this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}},n.fromPort=function(t){return s.has(t)?s.get(t):new n(null,t)},n}(),P=function t(){function e(t,e,r,i){this.messageHandler=t,this.loadingTask=e,this.pdfDataRangeTransport=r,this.commonObjs=new E,this.fontLoader=new u.FontLoader(e.docId),this.CMapReaderFactory=new i({baseUrl:(0,h.getDefaultSetting)("cMapUrl"),isCompressed:(0,h.getDefaultSetting)("cMapPacked")}),this.destroyed=!1,this.destroyCapability=null,this._passwordCapability=null,this.pageCache=[],this.pagePromises=[],this.downloadInfoCapability=(0,l.createPromiseCapability)(),this.setupMessageHandler()}return e.prototype={destroy:function t(){var e=this;if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=(0,l.createPromiseCapability)(),this._passwordCapability&&this._passwordCapability.reject(new Error("Worker was destroyed during onPassword callback"));var r=[];this.pageCache.forEach(function(t){t&&r.push(t._destroy())}),this.pageCache=[],this.pagePromises=[];var i=this.messageHandler.sendWithPromise("Terminate",null);return r.push(i),Promise.all(r).then(function(){e.fontLoader.clear(),e.pdfDataRangeTransport&&(e.pdfDataRangeTransport.abort(),e.pdfDataRangeTransport=null),e.messageHandler&&(e.messageHandler.destroy(),e.messageHandler=null),e.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise},setupMessageHandler:function t(){var e=this.messageHandler,r=this.loadingTask,i=this.pdfDataRangeTransport;i&&(i.addRangeListener(function(t,r){e.send("OnDataRange",{begin:t,chunk:r})}),i.addProgressListener(function(t){e.send("OnDataProgress",{loaded:t})}),i.addProgressiveReadListener(function(t){e.send("OnDataRange",{chunk:t})}),e.on("RequestDataRange",function t(e){i.requestDataRange(e.begin,e.end)},this)),e.on("GetDoc",function t(e){var r=e.pdfInfo;this.numPages=e.pdfInfo.numPages;var i=this.loadingTask,n=new C(r,this,i);this.pdfDocument=n,i._capability.resolve(n)},this),e.on("PasswordRequest",function t(e){var i=this;if(this._passwordCapability=(0,l.createPromiseCapability)(),r.onPassword){var n=function t(e){i._passwordCapability.resolve({password:e})};r.onPassword(n,e.code)}else this._passwordCapability.reject(new l.PasswordException(e.message,e.code));return this._passwordCapability.promise},this),e.on("PasswordException",function t(e){r._capability.reject(new l.PasswordException(e.message,e.code))},this),e.on("InvalidPDF",function t(e){this.loadingTask._capability.reject(new l.InvalidPDFException(e.message))},this),e.on("MissingPDF",function t(e){this.loadingTask._capability.reject(new l.MissingPDFException(e.message))},this),e.on("UnexpectedResponse",function t(e){this.loadingTask._capability.reject(new l.UnexpectedResponseException(e.message,e.status))},this),e.on("UnknownError",function t(e){this.loadingTask._capability.reject(new l.UnknownErrorException(e.message,e.details))},this),e.on("DataLoaded",function t(e){this.downloadInfoCapability.resolve(e)},this),e.on("PDFManagerReady",function t(e){this.pdfDataRangeTransport&&this.pdfDataRangeTransport.transportReady()},this),e.on("StartRenderPage",function t(e){if(!this.destroyed){var r=this.pageCache[e.pageIndex];r.stats.timeEnd("Page Request"),r._startRenderPage(e.transparency,e.intent)}},this),e.on("RenderPageChunk",function t(e){if(!this.destroyed){this.pageCache[e.pageIndex]._renderPageChunk(e.operatorList,e.intent)}},this),e.on("commonobj",function t(e){var r=this;if(!this.destroyed){var i=e[0],n=e[1];if(!this.commonObjs.hasData(i))switch(n){case"Font":var o=e[2];if("error"in o){var a=o.error;(0,l.warn)("Error during font loading: "+a),this.commonObjs.resolve(i,a);break}var s=null;(0,h.getDefaultSetting)("pdfBug")&&l.globalScope.FontInspector&&l.globalScope.FontInspector.enabled&&(s={registerFont:function t(e,r){l.globalScope.FontInspector.fontAdded(e,r)}});var c=new u.FontFaceObject(o,{isEvalSuported:(0,h.getDefaultSetting)("isEvalSupported"),disableFontFace:(0,h.getDefaultSetting)("disableFontFace"),fontRegistry:s}),f=function t(e){r.commonObjs.resolve(i,c)};this.fontLoader.bind([c],f);break;case"FontPath":this.commonObjs.resolve(i,e[2]);break;default:throw new Error("Got unknown common object type "+n)}}},this),e.on("obj",function t(e){if(!this.destroyed){var r=e[0],i=e[1],n=e[2],o=this.pageCache[i],a;if(!o.objs.hasData(r))switch(n){case"JpegStream":a=e[3],(0,l.loadJpegStream)(r,a,o.objs);break;case"Image":a=e[3],o.objs.resolve(r,a);var s=8e6;a&&"data"in a&&a.data.length>8e6&&(o.cleanupAfterRender=!0);break;default:throw new Error("Got unknown object type "+n)}}},this),e.on("DocProgress",function t(e){if(!this.destroyed){var r=this.loadingTask;r.onProgress&&r.onProgress({loaded:e.loaded,total:e.total})}},this),e.on("PageError",function t(e){if(!this.destroyed){var r=this.pageCache[e.pageNum-1],i=r.intentStates[e.intent];if(!i.displayReadyCapability)throw new Error(e.error);if(i.displayReadyCapability.reject(e.error),i.operatorList){i.operatorList.lastChunk=!0;for(var n=0;n<i.renderTasks.length;n++)i.renderTasks[n].operatorListChanged()}}},this),e.on("UnsupportedFeature",function t(e){if(!this.destroyed){var r=e.featureId,i=this.loadingTask;i.onUnsupportedFeature&&i.onUnsupportedFeature(r),L.notify(r)}},this),e.on("JpegDecode",function(t){if(this.destroyed)return Promise.reject(new Error("Worker was destroyed"));if("undefined"==typeof document)return Promise.reject(new Error('"document" is not defined.'));var e=t[0],r=t[1];return 3!==r&&1!==r?Promise.reject(new Error("Only 3 components or 1 component can be returned")):new Promise(function(t,i){var n=new Image;n.onload=function(){var e=n.width,i=n.height,o=e*i,a=4*o,s=new Uint8Array(o*r),c=document.createElement("canvas");c.width=e,c.height=i;var l=c.getContext("2d");l.drawImage(n,0,0);var h=l.getImageData(0,0,e,i).data,u,f;if(3===r)for(u=0,f=0;u<a;u+=4,f+=3)s[f]=h[u],s[f+1]=h[u+1],s[f+2]=h[u+2];else if(1===r)for(u=0,f=0;u<a;u+=4,f++)s[f]=h[u];t({data:s,width:e,height:i})},n.onerror=function(){i(new Error("JpegDecode failed to load image"))},n.src=e})},this),e.on("FetchBuiltInCMap",function(t){return this.destroyed?Promise.reject(new Error("Worker was destroyed")):this.CMapReaderFactory.fetch({name:t.name})},this)},getData:function t(){return this.messageHandler.sendWithPromise("GetData",null)},getPage:function t(e,r){var i=this;if(!(0,l.isInt)(e)||e<=0||e>this.numPages)return Promise.reject(new Error("Invalid page request"));var n=e-1;if(n in this.pagePromises)return this.pagePromises[n];var o=this.messageHandler.sendWithPromise("GetPage",{pageIndex:n}).then(function(t){if(i.destroyed)throw new Error("Transport destroyed");var e=new A(n,t,i);return i.pageCache[n]=e,e});return this.pagePromises[n]=o,o},getPageIndex:function t(e){return this.messageHandler.sendWithPromise("GetPageIndex",{ref:e}).catch(function(t){return Promise.reject(new Error(t))})},getAnnotations:function t(e,r){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:e,intent:r})},getDestinations:function t(){return this.messageHandler.sendWithPromise("GetDestinations",null)},getDestination:function t(e){return this.messageHandler.sendWithPromise("GetDestination",{id:e})},getPageLabels:function t(){return this.messageHandler.sendWithPromise("GetPageLabels",null)},getPageMode:function t(){return this.messageHandler.sendWithPromise("GetPageMode",null)},getAttachments:function t(){return this.messageHandler.sendWithPromise("GetAttachments",null)},getJavaScript:function t(){return this.messageHandler.sendWithPromise("GetJavaScript",null)},getOutline:function t(){return this.messageHandler.sendWithPromise("GetOutline",null)},getMetadata:function t(){return this.messageHandler.sendWithPromise("GetMetadata",null).then(function t(e){return{info:e[0],metadata:e[1]?new d.Metadata(e[1]):null}})},getStats:function t(){return this.messageHandler.sendWithPromise("GetStats",null)},startCleanup:function t(){var e=this;this.messageHandler.sendWithPromise("Cleanup",null).then(function(){for(var t=0,r=e.pageCache.length;t<r;t++){var i=e.pageCache[t];i&&i.cleanup()}e.commonObjs.clear(),e.fontLoader.clear()})}},e}(),E=function t(){function e(){this.objs=Object.create(null)}return e.prototype={ensureObj:function t(e){if(this.objs[e])return this.objs[e];var r={capability:(0,l.createPromiseCapability)(),data:null,resolved:!1};return this.objs[e]=r,r},get:function t(e,r){if(r)return this.ensureObj(e).capability.promise.then(r),null;var i=this.objs[e];if(!i||!i.resolved)throw new Error("Requesting object that isn't resolved yet "+e);return i.data},resolve:function t(e,r){var i=this.ensureObj(e);i.resolved=!0,i.data=r,i.capability.resolve(r)},isResolved:function t(e){var r=this.objs;return!!r[e]&&r[e].resolved},hasData:function t(e){return this.isResolved(e)},getData:function t(e){var r=this.objs;return r[e]&&r[e].resolved?r[e].data:null},clear:function t(){this.objs=Object.create(null)}},e}(),O=function t(){function e(t){this._internalRenderTask=t,this.onContinue=null}return e.prototype={get promise(){return this._internalRenderTask.capability.promise},cancel:function t(){this._internalRenderTask.cancel()},then:function t(e,r){return this.promise.then.apply(this.promise,arguments)}},e}(),R=function t(){function e(t,e,r,i,n,o,a){this.callback=t,this.params=e,this.objs=r,this.commonObjs=i,this.operatorListIdx=null,this.operatorList=n,this.pageNumber=o,this.canvasFactory=a,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this.useRequestAnimationFrame=!1,this.cancelled=!1,this.capability=(0,l.createPromiseCapability)(),this.task=new O(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=e.canvasContext.canvas}var r=new WeakMap;return e.prototype={initializeGraphics:function t(e){if(this._canvas){if(r.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");r.set(this._canvas,this)}if(!this.cancelled){(0,h.getDefaultSetting)("pdfBug")&&l.globalScope.StepperManager&&l.globalScope.StepperManager.enabled&&(this.stepper=l.globalScope.StepperManager.create(this.pageNumber-1),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());var i=this.params;this.gfx=new f.CanvasGraphics(i.canvasContext,this.commonObjs,this.objs,this.canvasFactory,i.imageLayer),this.gfx.beginDrawing({transform:i.transform,viewport:i.viewport,transparency:e,background:i.background}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback&&this.graphicsReadyCallback()}},cancel:function t(){this.running=!1,this.cancelled=!0,this._canvas&&r.delete(this._canvas),(0,h.getDefaultSetting)("pdfjsNext")?this.callback(new h.RenderingCancelledException("Rendering cancelled, page "+this.pageNumber,"canvas")):this.callback("cancelled")},operatorListChanged:function t(){if(!this.graphicsReady)return void(this.graphicsReadyCallback||(this.graphicsReadyCallback=this._continueBound));this.stepper&&this.stepper.updateOperatorList(this.operatorList),this.running||this._continue()},_continue:function t(){this.running=!0,this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())},_scheduleNext:function t(){this.useRequestAnimationFrame&&"undefined"!=typeof window?window.requestAnimationFrame(this._nextBound):Promise.resolve(void 0).then(this._nextBound)},_next:function t(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),this._canvas&&r.delete(this._canvas),this.callback())))}},e}(),L=function t(){var e=[];return{listen:function t(r){(0,l.deprecated)("Global UnsupportedManager.listen is used: use PDFDocumentLoadingTask.onUnsupportedFeature instead"),e.push(r)},notify:function t(r){for(var i=0,n=e.length;i<n;i++)e[i](r)}}}(),D,I;e.version=D="1.8.575",e.build=I="bd8c1211",e.getDocument=o,e.LoopbackPort=T,e.PDFDataRangeTransport=x,e.PDFWorker=k,e.PDFDocumentProxy=C,e.PDFPageProxy=A,e._UnsupportedManager=L,e.version=D,e.build=I},function(t,e,o){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.SVGGraphics=void 0;var a=o(0),s=function t(){throw new Error("Not implemented: SVGGraphics")},c={fontStyle:"normal",fontWeight:"normal",fillColor:"#000000"},l=function t(){function e(t,e,r){for(var i=-1,n=e;n<r;n++){var o=255&(i^t[n]);i=i>>>8^d[o]}return-1^i}function o(t,r,i,n){var o=n,a=r.length;i[o]=a>>24&255,i[o+1]=a>>16&255,i[o+2]=a>>8&255,i[o+3]=255&a,o+=4,i[o]=255&t.charCodeAt(0),i[o+1]=255&t.charCodeAt(1),i[o+2]=255&t.charCodeAt(2),i[o+3]=255&t.charCodeAt(3),o+=4,i.set(r,o),o+=r.length;var s=e(i,n+4,o);i[o]=s>>24&255,i[o+1]=s>>16&255,i[o+2]=s>>8&255,i[o+3]=255&s}function s(t,e,r){for(var i=1,n=0,o=e;o<r;++o)i=(i+(255&t[o]))%65521,n=(n+i)%65521;return n<<16|i}function c(t){if(!(0,a.isNodeJS)())return l(t);try{var e;e=parseInt(i.versions.node)>=8?t:new n(t);var o=r(42).deflateSync(e,{level:9});return o instanceof Uint8Array?o:new Uint8Array(o)}catch(t){(0,a.warn)("Not compressing PNG because zlib.deflateSync is unavailable: "+t)}return l(t)}function l(t){var e=t.length,r=65535,i=Math.ceil(e/65535),n=new Uint8Array(2+e+5*i+4),o=0;n[o++]=120,n[o++]=156;for(var a=0;e>65535;)n[o++]=0,n[o++]=255,n[o++]=255,n[o++]=0,n[o++]=0,n.set(t.subarray(a,a+65535),o),o+=65535,a+=65535,e-=65535;n[o++]=1,n[o++]=255&e,n[o++]=e>>8&255,n[o++]=255&~e,n[o++]=(65535&~e)>>8&255,n.set(t.subarray(a),o),o+=t.length-a;var c=s(t,0,t.length);return n[o++]=c>>24&255,n[o++]=c>>16&255,n[o++]=c>>8&255,n[o++]=255&c,n}function h(t,e,r){var i=t.width,n=t.height,s,l,h,d=t.data;switch(e){case a.ImageKind.GRAYSCALE_1BPP:l=0,s=1,h=i+7>>3;break;case a.ImageKind.RGB_24BPP:l=2,s=8,h=3*i;break;case a.ImageKind.RGBA_32BPP:l=6,s=8,h=4*i;break;default:throw new Error("invalid format")}var p=new Uint8Array((1+h)*n),g=0,v=0,m,b;for(m=0;m<n;++m)p[g++]=0,p.set(d.subarray(v,v+h),g),v+=h,g+=h;if(e===a.ImageKind.GRAYSCALE_1BPP)for(g=0,m=0;m<n;m++)for(g++,b=0;b<h;b++)p[g++]^=255;var y=new Uint8Array([i>>24&255,i>>16&255,i>>8&255,255&i,n>>24&255,n>>16&255,n>>8&255,255&n,s,l,0,0,0]),_=c(p),w=u.length+3*f+y.length+_.length,S=new Uint8Array(w),x=0;return S.set(u,x),x+=u.length,o("IHDR",y,S,x),x+=f+y.length,o("IDATA",_,S,x),x+=f+_.length,o("IEND",new Uint8Array(0),S,x),(0,a.createObjectURL)(S,"image/png",r)}for(var u=new Uint8Array([137,80,78,71,13,10,26,10]),f=12,d=new Int32Array(256),p=0;p<256;p++){for(var g=p,v=0;v<8;v++)g=1&g?3988292384^g>>1&2147483647:g>>1&2147483647;d[p]=g}return function t(e,r){return h(e,void 0===e.kind?a.ImageKind.GRAYSCALE_1BPP:e.kind,r)}}(),h=function t(){function e(){this.fontSizeScale=1,this.fontWeight=c.fontWeight,this.fontSize=0,this.textMatrix=a.IDENTITY_MATRIX,this.fontMatrix=a.FONT_IDENTITY_MATRIX,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRise=0,this.fillColor=c.fillColor,this.strokeColor="#000000",this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.lineJoin="",this.lineCap="",this.miterLimit=0,this.dashArray=[],this.dashPhase=0,this.dependencies=[],this.activeClipUrl=null,this.clipGroup=null,this.maskId=""}return e.prototype={clone:function t(){return Object.create(this)},setCurrentPoint:function t(e,r){this.x=e,this.y=r}},e}();e.SVGGraphics=s=function t(){function e(t){for(var e=[],r=[],i=t.length,n=0;n<i;n++)"save"!==t[n].fn?"restore"===t[n].fn?e=r.pop():e.push(t[n]):(e.push({fnId:92,fn:"group",items:[]}),r.push(e),e=e[e.length-1].items);return e}function r(t){if(t===(0|t))return t.toString();var e=t.toFixed(10),r=e.length-1;if("0"!==e[r])return e;do{r--}while("0"===e[r]);return e.substr(0,"."===e[r]?r:r+1)}function i(t){if(0===t[4]&&0===t[5]){if(0===t[1]&&0===t[2])return 1===t[0]&&1===t[3]?"":"scale("+r(t[0])+" "+r(t[3])+")";if(t[0]===t[3]&&t[1]===-t[2]){return"rotate("+r(180*Math.acos(t[0])/Math.PI)+")"}}else if(1===t[0]&&0===t[1]&&0===t[2]&&1===t[3])return"translate("+r(t[4])+" "+r(t[5])+")";return"matrix("+r(t[0])+" "+r(t[1])+" "+r(t[2])+" "+r(t[3])+" "+r(t[4])+" "+r(t[5])+")"}function n(t,e,r){this.current=new h,this.transformMatrix=a.IDENTITY_MATRIX,this.transformStack=[],this.extraStack=[],this.commonObjs=t,this.objs=e,this.pendingClip=null,this.pendingEOFill=!1,this.embedFonts=!1,this.embeddedFonts=Object.create(null),this.cssStyle=null,this.forceDataSchema=!!r}var o="http://www.w3.org/2000/svg",s="http://www.w3.org/1999/xlink",u=["butt","round","square"],f=["miter","round","bevel"],d=0,p=0;return n.prototype={save:function t(){this.transformStack.push(this.transformMatrix);var e=this.current;this.extraStack.push(e),this.current=e.clone()},restore:function t(){this.transformMatrix=this.transformStack.pop(),this.current=this.extraStack.pop(),this.pendingClip=null,this.tgrp=null},group:function t(e){this.save(),this.executeOpTree(e),this.restore()},loadDependencies:function t(e){for(var r=this,i=e.fnArray,n=i.length,o=e.argsArray,s=0;s<n;s++)if(a.OPS.dependency===i[s])for(var c=o[s],l=0,h=c.length;l<h;l++){var u=c[l],f="g_"===u.substring(0,2),d;d=f?new Promise(function(t){r.commonObjs.get(u,t)}):new Promise(function(t){r.objs.get(u,t)}),this.current.dependencies.push(d)}return Promise.all(this.current.dependencies)},transform:function t(e,r,i,n,o,s){var c=[e,r,i,n,o,s];this.transformMatrix=a.Util.transform(this.transformMatrix,c),this.tgrp=null},getSVG:function t(e,r){var i=this;this.viewport=r;var n=this._initialize(r);return this.loadDependencies(e).then(function(){i.transformMatrix=a.IDENTITY_MATRIX;var t=i.convertOpList(e);return i.executeOpTree(t),n})},convertOpList:function t(r){var i=r.argsArray,n=r.fnArray,o=n.length,s=[],c=[];for(var l in a.OPS)s[a.OPS[l]]=l;for(var h=0;h<o;h++){var u=n[h];c.push({fnId:u,fn:s[u],args:i[h]})}return e(c)},executeOpTree:function t(e){for(var r=e.length,i=0;i<r;i++){var n=e[i].fn,o=e[i].fnId,s=e[i].args;switch(0|o){case a.OPS.beginText:this.beginText();break;case a.OPS.setLeading:this.setLeading(s);break;case a.OPS.setLeadingMoveText:this.setLeadingMoveText(s[0],s[1]);break;case a.OPS.setFont:this.setFont(s);break;case a.OPS.showText:case a.OPS.showSpacedText:this.showText(s[0]);break;case a.OPS.endText:this.endText();break;case a.OPS.moveText:this.moveText(s[0],s[1]);break;case a.OPS.setCharSpacing:this.setCharSpacing(s[0]);break;case a.OPS.setWordSpacing:this.setWordSpacing(s[0]);break;case a.OPS.setHScale:this.setHScale(s[0]);break;case a.OPS.setTextMatrix:this.setTextMatrix(s[0],s[1],s[2],s[3],s[4],s[5]);break;case a.OPS.setLineWidth:this.setLineWidth(s[0]);break;case a.OPS.setLineJoin:this.setLineJoin(s[0]);break;case a.OPS.setLineCap:this.setLineCap(s[0]);break;case a.OPS.setMiterLimit:this.setMiterLimit(s[0]);break;case a.OPS.setFillRGBColor:this.setFillRGBColor(s[0],s[1],s[2]);break;case a.OPS.setStrokeRGBColor:this.setStrokeRGBColor(s[0],s[1],s[2]);break;case a.OPS.setDash:this.setDash(s[0],s[1]);break;case a.OPS.setGState:this.setGState(s[0]);break;case a.OPS.fill:this.fill();break;case a.OPS.eoFill:this.eoFill();break;case a.OPS.stroke:this.stroke();break;case a.OPS.fillStroke:this.fillStroke();break;case a.OPS.eoFillStroke:this.eoFillStroke();break;case a.OPS.clip:this.clip("nonzero");break;case a.OPS.eoClip:this.clip("evenodd");break;case a.OPS.paintSolidColorImageMask:this.paintSolidColorImageMask();break;case a.OPS.paintJpegXObject:this.paintJpegXObject(s[0],s[1],s[2]);break;case a.OPS.paintImageXObject:this.paintImageXObject(s[0]);break;case a.OPS.paintInlineImageXObject:this.paintInlineImageXObject(s[0]);break;case a.OPS.paintImageMaskXObject:this.paintImageMaskXObject(s[0]);break;case a.OPS.paintFormXObjectBegin:this.paintFormXObjectBegin(s[0],s[1]);break;case a.OPS.paintFormXObjectEnd:this.paintFormXObjectEnd();break;case a.OPS.closePath:this.closePath();break;case a.OPS.closeStroke:this.closeStroke();break;case a.OPS.closeFillStroke:this.closeFillStroke();break;case a.OPS.nextLine:this.nextLine();break;case a.OPS.transform:this.transform(s[0],s[1],s[2],s[3],s[4],s[5]);break;case a.OPS.constructPath:this.constructPath(s[0],s[1]);break;case a.OPS.endPath:this.endPath();break;case 92:this.group(e[i].items);break;default:(0,a.warn)("Unimplemented operator "+n)}}},setWordSpacing:function t(e){this.current.wordSpacing=e},setCharSpacing:function t(e){this.current.charSpacing=e},nextLine:function t(){this.moveText(0,this.current.leading)},setTextMatrix:function t(e,i,n,a,s,c){var l=this.current;this.current.textMatrix=this.current.lineMatrix=[e,i,n,a,s,c],this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0,l.xcoords=[],l.tspan=document.createElementNS(o,"svg:tspan"),l.tspan.setAttributeNS(null,"font-family",l.fontFamily),l.tspan.setAttributeNS(null,"font-size",r(l.fontSize)+"px"),l.tspan.setAttributeNS(null,"y",r(-l.y)),l.txtElement=document.createElementNS(o,"svg:text"),l.txtElement.appendChild(l.tspan)},beginText:function t(){this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0,this.current.textMatrix=a.IDENTITY_MATRIX,this.current.lineMatrix=a.IDENTITY_MATRIX,this.current.tspan=document.createElementNS(o,"svg:tspan"),this.current.txtElement=document.createElementNS(o,"svg:text"),this.current.txtgrp=document.createElementNS(o,"svg:g"),this.current.xcoords=[]},moveText:function t(e,i){var n=this.current;this.current.x=this.current.lineX+=e,this.current.y=this.current.lineY+=i,n.xcoords=[],n.tspan=document.createElementNS(o,"svg:tspan"),n.tspan.setAttributeNS(null,"font-family",n.fontFamily),n.tspan.setAttributeNS(null,"font-size",r(n.fontSize)+"px"),n.tspan.setAttributeNS(null,"y",r(-n.y))},showText:function t(e){var n=this.current,o=n.font,s=n.fontSize;if(0!==s){var l=n.charSpacing,h=n.wordSpacing,u=n.fontDirection,f=n.textHScale*u,d=e.length,p=o.vertical,g=s*n.fontMatrix[0],v=0,m;for(m=0;m<d;++m){var b=e[m];if(null!==b)if((0,a.isNum)(b))v+=-b*s*.001;else{n.xcoords.push(n.x+v*f);var y=b.width,_=b.fontChar,w=(b.isSpace?h:0)+l,S=y*g+w*u;v+=S,n.tspan.textContent+=_}else v+=u*h}p?n.y-=v*f:n.x+=v*f,n.tspan.setAttributeNS(null,"x",n.xcoords.map(r).join(" ")),n.tspan.setAttributeNS(null,"y",r(-n.y)),n.tspan.setAttributeNS(null,"font-family",n.fontFamily),n.tspan.setAttributeNS(null,"font-size",r(n.fontSize)+"px"),n.fontStyle!==c.fontStyle&&n.tspan.setAttributeNS(null,"font-style",n.fontStyle),n.fontWeight!==c.fontWeight&&n.tspan.setAttributeNS(null,"font-weight",n.fontWeight),n.fillColor!==c.fillColor&&n.tspan.setAttributeNS(null,"fill",n.fillColor),n.txtElement.setAttributeNS(null,"transform",i(n.textMatrix)+" scale(1, -1)"),n.txtElement.setAttributeNS("http://www.w3.org/XML/1998/namespace","xml:space","preserve"),n.txtElement.appendChild(n.tspan),n.txtgrp.appendChild(n.txtElement),this._ensureTransformGroup().appendChild(n.txtElement)}},setLeadingMoveText:function t(e,r){this.setLeading(-r),this.moveText(e,r)},addFontStyle:function t(e){this.cssStyle||(this.cssStyle=document.createElementNS(o,"svg:style"),this.cssStyle.setAttributeNS(null,"type","text/css"),this.defs.appendChild(this.cssStyle));var r=(0,a.createObjectURL)(e.data,e.mimetype,this.forceDataSchema);this.cssStyle.textContent+='@font-face { font-family: "'+e.loadedName+'"; src: url('+r+"); }\n"},setFont:function t(e){var i=this.current,n=this.commonObjs.get(e[0]),s=e[1];this.current.font=n,this.embedFonts&&n.data&&!this.embeddedFonts[n.loadedName]&&(this.addFontStyle(n),this.embeddedFonts[n.loadedName]=n),i.fontMatrix=n.fontMatrix?n.fontMatrix:a.FONT_IDENTITY_MATRIX;var c=n.black?n.bold?"bolder":"bold":n.bold?"bold":"normal",l=n.italic?"italic":"normal";s<0?(s=-s,i.fontDirection=-1):i.fontDirection=1,i.fontSize=s,i.fontFamily=n.loadedName,i.fontWeight=c,i.fontStyle=l,i.tspan=document.createElementNS(o,"svg:tspan"),i.tspan.setAttributeNS(null,"y",r(-i.y)),i.xcoords=[]},endText:function t(){},setLineWidth:function t(e){this.current.lineWidth=e},setLineCap:function t(e){this.current.lineCap=u[e]},setLineJoin:function t(e){this.current.lineJoin=f[e]},setMiterLimit:function t(e){this.current.miterLimit=e},setStrokeAlpha:function t(e){this.current.strokeAlpha=e},setStrokeRGBColor:function t(e,r,i){var n=a.Util.makeCssRgb(e,r,i);this.current.strokeColor=n},setFillAlpha:function t(e){this.current.fillAlpha=e},setFillRGBColor:function t(e,r,i){var n=a.Util.makeCssRgb(e,r,i);this.current.fillColor=n,this.current.tspan=document.createElementNS(o,"svg:tspan"),this.current.xcoords=[]},setDash:function t(e,r){this.current.dashArray=e,this.current.dashPhase=r},constructPath:function t(e,i){var n=this.current,s=n.x,c=n.y;n.path=document.createElementNS(o,"svg:path");for(var l=[],h=e.length,u=0,f=0;u<h;u++)switch(0|e[u]){case a.OPS.rectangle:s=i[f++],c=i[f++];var d=i[f++],p=i[f++],g=s+d,v=c+p;l.push("M",r(s),r(c),"L",r(g),r(c),"L",r(g),r(v),"L",r(s),r(v),"Z");break;case a.OPS.moveTo:s=i[f++],c=i[f++],l.push("M",r(s),r(c));break;case a.OPS.lineTo:s=i[f++],c=i[f++],l.push("L",r(s),r(c));break;case a.OPS.curveTo:s=i[f+4],c=i[f+5],l.push("C",r(i[f]),r(i[f+1]),r(i[f+2]),r(i[f+3]),r(s),r(c)),f+=6;break;case a.OPS.curveTo2:s=i[f+2],c=i[f+3],l.push("C",r(s),r(c),r(i[f]),r(i[f+1]),r(i[f+2]),r(i[f+3])),f+=4;break;case a.OPS.curveTo3:s=i[f+2],c=i[f+3],l.push("C",r(i[f]),r(i[f+1]),r(s),r(c),r(s),r(c)),f+=4;break;case a.OPS.closePath:l.push("Z")}n.path.setAttributeNS(null,"d",l.join(" ")),n.path.setAttributeNS(null,"fill","none"),this._ensureTransformGroup().appendChild(n.path),n.element=n.path,n.setCurrentPoint(s,c)},endPath:function t(){if(this.pendingClip){var e=this.current,r="clippath"+d;d++;var n=document.createElementNS(o,"svg:clipPath");n.setAttributeNS(null,"id",r),n.setAttributeNS(null,"transform",i(this.transformMatrix));var a=e.element.cloneNode();"evenodd"===this.pendingClip?a.setAttributeNS(null,"clip-rule","evenodd"):a.setAttributeNS(null,"clip-rule","nonzero"),this.pendingClip=null,n.appendChild(a),this.defs.appendChild(n),e.activeClipUrl&&(e.clipGroup=null,this.extraStack.forEach(function(t){t.clipGroup=null})),e.activeClipUrl="url(#"+r+")",this.tgrp=null}},clip:function t(e){this.pendingClip=e},closePath:function t(){var e=this.current,r=e.path.getAttributeNS(null,"d");r+="Z",e.path.setAttributeNS(null,"d",r)},setLeading:function t(e){this.current.leading=-e},setTextRise:function t(e){this.current.textRise=e},setHScale:function t(e){this.current.textHScale=e/100},setGState:function t(e){for(var r=0,i=e.length;r<i;r++){var n=e[r],o=n[0],s=n[1];switch(o){case"LW":this.setLineWidth(s);break;case"LC":this.setLineCap(s);break;case"LJ":this.setLineJoin(s);break;case"ML":this.setMiterLimit(s);break;case"D":this.setDash(s[0],s[1]);break;case"Font":this.setFont(s);break;case"CA":this.setStrokeAlpha(s);break;case"ca":this.setFillAlpha(s);break;default:(0,a.warn)("Unimplemented graphic state "+o)}}},fill:function t(){var e=this.current;e.element.setAttributeNS(null,"fill",e.fillColor),e.element.setAttributeNS(null,"fill-opacity",e.fillAlpha)},stroke:function t(){var e=this.current;e.element.setAttributeNS(null,"stroke",e.strokeColor),e.element.setAttributeNS(null,"stroke-opacity",e.strokeAlpha),e.element.setAttributeNS(null,"stroke-miterlimit",r(e.miterLimit)),e.element.setAttributeNS(null,"stroke-linecap",e.lineCap),e.element.setAttributeNS(null,"stroke-linejoin",e.lineJoin),e.element.setAttributeNS(null,"stroke-width",r(e.lineWidth)+"px"),e.element.setAttributeNS(null,"stroke-dasharray",e.dashArray.map(r).join(" ")),e.element.setAttributeNS(null,"stroke-dashoffset",r(e.dashPhase)+"px"),e.element.setAttributeNS(null,"fill","none")},eoFill:function t(){this.current.element.setAttributeNS(null,"fill-rule","evenodd"),this.fill()},fillStroke:function t(){this.stroke(),this.fill()},eoFillStroke:function t(){this.current.element.setAttributeNS(null,"fill-rule","evenodd"),this.fillStroke()},closeStroke:function t(){this.closePath(),this.stroke()},closeFillStroke:function t(){this.closePath(),this.fillStroke()},paintSolidColorImageMask:function t(){var e=this.current,r=document.createElementNS(o,"svg:rect");r.setAttributeNS(null,"x","0"),r.setAttributeNS(null,"y","0"),r.setAttributeNS(null,"width","1px"),r.setAttributeNS(null,"height","1px"),r.setAttributeNS(null,"fill",e.fillColor),this._ensureTransformGroup().appendChild(r)},paintJpegXObject:function t(e,i,n){var a=this.objs.get(e),c=document.createElementNS(o,"svg:image");c.setAttributeNS(s,"xlink:href",a.src),c.setAttributeNS(null,"width",r(i)),c.setAttributeNS(null,"height",r(n)),c.setAttributeNS(null,"x","0"),c.setAttributeNS(null,"y",r(-n)),c.setAttributeNS(null,"transform","scale("+r(1/i)+" "+r(-1/n)+")"),this._ensureTransformGroup().appendChild(c)},paintImageXObject:function t(e){var r=this.objs.get(e);if(!r)return void(0,a.warn)("Dependent image isn't ready yet");this.paintInlineImageXObject(r)},paintInlineImageXObject:function t(e,i){var n=e.width,a=e.height,c=l(e,this.forceDataSchema),h=document.createElementNS(o,"svg:rect");h.setAttributeNS(null,"x","0"),h.setAttributeNS(null,"y","0"),h.setAttributeNS(null,"width",r(n)),h.setAttributeNS(null,"height",r(a)),this.current.element=h,this.clip("nonzero");var u=document.createElementNS(o,"svg:image");u.setAttributeNS(s,"xlink:href",c),u.setAttributeNS(null,"x","0"),u.setAttributeNS(null,"y",r(-a)),u.setAttributeNS(null,"width",r(n)+"px"),u.setAttributeNS(null,"height",r(a)+"px"),u.setAttributeNS(null,"transform","scale("+r(1/n)+" "+r(-1/a)+")"),i?i.appendChild(u):this._ensureTransformGroup().appendChild(u)},paintImageMaskXObject:function t(e){var i=this.current,n=e.width,a=e.height,s=i.fillColor;i.maskId="mask"+p++;var c=document.createElementNS(o,"svg:mask");c.setAttributeNS(null,"id",i.maskId);var l=document.createElementNS(o,"svg:rect");l.setAttributeNS(null,"x","0"),l.setAttributeNS(null,"y","0"),l.setAttributeNS(null,"width",r(n)),l.setAttributeNS(null,"height",r(a)),l.setAttributeNS(null,"fill",s),l.setAttributeNS(null,"mask","url(#"+i.maskId+")"),this.defs.appendChild(c),this._ensureTransformGroup().appendChild(l),this.paintInlineImageXObject(e,c)},paintFormXObjectBegin:function t(e,i){if((0,a.isArray)(e)&&6===e.length&&this.transform(e[0],e[1],e[2],e[3],e[4],e[5]),(0,a.isArray)(i)&&4===i.length){var n=i[2]-i[0],s=i[3]-i[1],c=document.createElementNS(o,"svg:rect");c.setAttributeNS(null,"x",i[0]),c.setAttributeNS(null,"y",i[1]),c.setAttributeNS(null,"width",r(n)),c.setAttributeNS(null,"height",r(s)),this.current.element=c,this.clip("nonzero"),this.endPath()}},paintFormXObjectEnd:function t(){},_initialize:function t(e){var r=document.createElementNS(o,"svg:svg");r.setAttributeNS(null,"version","1.1"),r.setAttributeNS(null,"width",e.width+"px"),r.setAttributeNS(null,"height",e.height+"px"),r.setAttributeNS(null,"preserveAspectRatio","none"),r.setAttributeNS(null,"viewBox","0 0 "+e.width+" "+e.height);var n=document.createElementNS(o,"svg:defs");r.appendChild(n),this.defs=n;var a=document.createElementNS(o,"svg:g");return a.setAttributeNS(null,"transform",i(e.transform)),r.appendChild(a),this.svg=a,r},_ensureClipGroup:function t(){if(!this.current.clipGroup){var e=document.createElementNS(o,"svg:g");e.setAttributeNS(null,"clip-path",this.current.activeClipUrl),this.svg.appendChild(e),this.current.clipGroup=e}return this.current.clipGroup},_ensureTransformGroup:function t(){return this.tgrp||(this.tgrp=document.createElementNS(o,"svg:g"),this.tgrp.setAttributeNS(null,"transform",i(this.transformMatrix)),this.current.activeClipUrl?this._ensureClipGroup().appendChild(this.tgrp):this.svg.appendChild(this.tgrp)),this.tgrp}},n}(),e.SVGGraphics=s},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.renderTextLayer=void 0;var i=r(0),n=r(1),o=function t(){function e(t){return!f.test(t)}function r(t,r,o){var a=document.createElement("div"),s={style:null,angle:0,canvasWidth:0,isWhitespace:!1,originalTransform:null,paddingBottom:0,paddingLeft:0,paddingRight:0,paddingTop:0,scale:1};if(t._textDivs.push(a),e(r.str))return s.isWhitespace=!0,void t._textDivProperties.set(a,s);var c=i.Util.transform(t._viewport.transform,r.transform),l=Math.atan2(c[1],c[0]),h=o[r.fontName];h.vertical&&(l+=Math.PI/2);var u=Math.sqrt(c[2]*c[2]+c[3]*c[3]),f=u;h.ascent?f=h.ascent*f:h.descent&&(f=(1+h.descent)*f);var p,g;if(0===l?(p=c[4],g=c[5]-f):(p=c[4]+f*Math.sin(l),g=c[5]-f*Math.cos(l)),d[1]=p,d[3]=g,d[5]=u,d[7]=h.fontFamily,s.style=d.join(""),a.setAttribute("style",s.style),a.textContent=r.str,(0,n.getDefaultSetting)("pdfBug")&&(a.dataset.fontName=r.fontName),0!==l&&(s.angle=l*(180/Math.PI)),r.str.length>1&&(h.vertical?s.canvasWidth=r.height*t._viewport.scale:s.canvasWidth=r.width*t._viewport.scale),t._textDivProperties.set(a,s),t._textContentStream&&t._layoutText(a),t._enhanceTextSelection){var v=1,m=0;0!==l&&(v=Math.cos(l),m=Math.sin(l));var b=(h.vertical?r.height:r.width)*t._viewport.scale,y=u,_,w;0!==l?(_=[v,m,-m,v,p,g],w=i.Util.getAxialAlignedBoundingBox([0,0,b,y],_)):w=[p,g,p+b,g+y],t._bounds.push({left:w[0],top:w[1],right:w[2],bottom:w[3],div:a,size:[b,y],m:_})}}function o(t){if(!t._canceled){var e=t._textDivs,r=t._capability,i=e.length;if(i>u)return t._renderingDone=!0,void r.resolve();if(!t._textContentStream)for(var n=0;n<i;n++)t._layoutText(e[n]);t._renderingDone=!0,r.resolve()}}function a(t){for(var e=t._bounds,r=t._viewport,n=s(r.width,r.height,e),o=0;o<n.length;o++){var a=e[o].div,c=t._textDivProperties.get(a);if(0!==c.angle){var l=n[o],h=e[o],u=h.m,f=u[0],d=u[1],p=[[0,0],[0,h.size[1]],[h.size[0],0],h.size],g=new Float64Array(64);p.forEach(function(t,e){var r=i.Util.applyTransform(t,u);g[e+0]=f&&(l.left-r[0])/f,g[e+4]=d&&(l.top-r[1])/d,g[e+8]=f&&(l.right-r[0])/f,g[e+12]=d&&(l.bottom-r[1])/d,g[e+16]=d&&(l.left-r[0])/-d,g[e+20]=f&&(l.top-r[1])/f,g[e+24]=d&&(l.right-r[0])/-d,g[e+28]=f&&(l.bottom-r[1])/f,g[e+32]=f&&(l.left-r[0])/-f,g[e+36]=d&&(l.top-r[1])/-d,g[e+40]=f&&(l.right-r[0])/-f,g[e+44]=d&&(l.bottom-r[1])/-d,g[e+48]=d&&(l.left-r[0])/d,g[e+52]=f&&(l.top-r[1])/-f,g[e+56]=d&&(l.right-r[0])/d,g[e+60]=f&&(l.bottom-r[1])/-f});var v=function t(e,r,i){for(var n=0,o=0;o<i;o++){var a=e[r++];a>0&&(n=n?Math.min(a,n):a)}return n},m=1+Math.min(Math.abs(f),Math.abs(d));c.paddingLeft=v(g,32,16)/m,c.paddingTop=v(g,48,16)/m,c.paddingRight=v(g,0,16)/m,c.paddingBottom=v(g,16,16)/m,t._textDivProperties.set(a,c)}else c.paddingLeft=e[o].left-n[o].left,c.paddingTop=e[o].top-n[o].top,c.paddingRight=n[o].right-e[o].right,c.paddingBottom=n[o].bottom-e[o].bottom,t._textDivProperties.set(a,c)}}function s(t,e,r){var i=r.map(function(t,e){return{x1:t.left,y1:t.top,x2:t.right,y2:t.bottom,index:e,x1New:void 0,x2New:void 0}});c(t,i);var n=new Array(r.length);return i.forEach(function(t){var e=t.index;n[e]={left:t.x1New,top:0,right:t.x2New,bottom:0}}),r.map(function(e,r){var o=n[r],a=i[r];a.x1=e.top,a.y1=t-o.right,a.x2=e.bottom,a.y2=t-o.left,a.index=r,a.x1New=void 0,a.x2New=void 0}),c(e,i),i.forEach(function(t){var e=t.index;n[e].top=t.x1New,n[e].bottom=t.x2New}),n}function c(t,e){e.sort(function(t,e){return t.x1-e.x1||t.index-e.index});var r={x1:-1/0,y1:-1/0,x2:0,y2:1/0,index:-1,x1New:0,x2New:0},i=[{start:-1/0,end:1/0,boundary:r}];e.forEach(function(t){for(var e=0;e<i.length&&i[e].end<=t.y1;)e++;for(var r=i.length-1;r>=0&&i[r].start>=t.y2;)r--;var n,o,a,s,c=-1/0;for(a=e;a<=r;a++){n=i[a],o=n.boundary;var l;l=o.x2>t.x1?o.index>t.index?o.x1New:t.x1:void 0===o.x2New?(o.x2+t.x1)/2:o.x2New,l>c&&(c=l)}for(t.x1New=c,a=e;a<=r;a++)n=i[a],o=n.boundary,void 0===o.x2New?o.x2>t.x1?o.index>t.index&&(o.x2New=o.x2):o.x2New=c:o.x2New>c&&(o.x2New=Math.max(c,o.x2));var h=[],u=null;for(a=e;a<=r;a++){n=i[a],o=n.boundary;var f=o.x2>t.x2?o:t;u===f?h[h.length-1].end=n.end:(h.push({start:n.start,end:n.end,boundary:f}),u=f)}for(i[e].start<t.y1&&(h[0].start=t.y1,h.unshift({start:i[e].start,end:t.y1,boundary:i[e].boundary})),t.y2<i[r].end&&(h[h.length-1].end=t.y2,h.push({start:t.y2,end:i[r].end,boundary:i[r].boundary})),a=e;a<=r;a++)if(n=i[a],o=n.boundary,void 0===o.x2New){var d=!1;for(s=e-1;!d&&s>=0&&i[s].start>=o.y1;s--)d=i[s].boundary===o;for(s=r+1;!d&&s<i.length&&i[s].end<=o.y2;s++)d=i[s].boundary===o;for(s=0;!d&&s<h.length;s++)d=h[s].boundary===o;d||(o.x2New=c)}Array.prototype.splice.apply(i,[e,r-e+1].concat(h))}),i.forEach(function(e){var r=e.boundary;void 0===r.x2New&&(r.x2New=Math.max(t,r.x2))})}function l(t){var e=t.textContent,r=t.textContentStream,n=t.container,o=t.viewport,a=t.textDivs,s=t.textContentItemsStr,c=t.enhanceTextSelection;this._textContent=e,this._textContentStream=r,this._container=n,this._viewport=o,this._textDivs=a||[],this._textContentItemsStr=s||[],this._enhanceTextSelection=!!c,this._reader=null,this._layoutTextLastFontSize=null,this._layoutTextLastFontFamily=null,this._layoutTextCtx=null,this._textDivProperties=new WeakMap,this._renderingDone=!1,this._canceled=!1,this._capability=(0,i.createPromiseCapability)(),this._renderTimer=null,this._bounds=[]}function h(t){var e=new l({textContent:t.textContent,textContentStream:t.textContentStream,container:t.container,viewport:t.viewport,textDivs:t.textDivs,textContentItemsStr:t.textContentItemsStr,enhanceTextSelection:t.enhanceTextSelection});return e._render(t.timeout),e}var u=1e5,f=/\S/,d=["left: ",0,"px; top: ",0,"px; font-size: ",0,"px; font-family: ","",";"];return l.prototype={get promise(){return this._capability.promise},cancel:function t(){this._reader&&(this._reader.cancel(),this._reader=null),this._canceled=!0,null!==this._renderTimer&&(clearTimeout(this._renderTimer),this._renderTimer=null),this._capability.reject("canceled")},_processItems:function t(e,i){for(var n=0,o=e.length;n<o;n++)this._textContentItemsStr.push(e[n].str),r(this,e[n],i)},_layoutText:function t(e){var r=this._container,i=this._textDivProperties.get(e);if(!i.isWhitespace){var o=e.style.fontSize,a=e.style.fontFamily;o===this._layoutTextLastFontSize&&a===this._layoutTextLastFontFamily||(this._layoutTextCtx.font=o+" "+a,this._lastFontSize=o,this._lastFontFamily=a);var s=this._layoutTextCtx.measureText(e.textContent).width,c="";0!==i.canvasWidth&&s>0&&(i.scale=i.canvasWidth/s,c="scaleX("+i.scale+")"),0!==i.angle&&(c="rotate("+i.angle+"deg) "+c),""!==c&&(i.originalTransform=c,n.CustomStyle.setProp("transform",e,c)),this._textDivProperties.set(e,i),r.appendChild(e)}},_render:function t(e){var r=this,n=(0,i.createPromiseCapability)(),a=Object.create(null),s=document.createElement("canvas");if(s.mozOpaque=!0,this._layoutTextCtx=s.getContext("2d",{alpha:!1}),this._textContent){var c=this._textContent.items,l=this._textContent.styles;this._processItems(c,l),n.resolve()}else{if(!this._textContentStream)throw new Error('Neither "textContent" nor "textContentStream" parameters specified.');var h=function t(){r._reader.read().then(function(e){var o=e.value;if(e.done)return void n.resolve();i.Util.extendObj(a,o.styles),r._processItems(o.items,a),t()},n.reject)};this._reader=this._textContentStream.getReader(),h()}n.promise.then(function(){a=null,e?r._renderTimer=setTimeout(function(){o(r),r._renderTimer=null},e):o(r)},this._capability.reject)},expandTextDivs:function t(e){if(this._enhanceTextSelection&&this._renderingDone){null!==this._bounds&&(a(this),this._bounds=null);for(var r=0,i=this._textDivs.length;r<i;r++){var o=this._textDivs[r],s=this._textDivProperties.get(o);if(!s.isWhitespace)if(e){var c="",l="";1!==s.scale&&(c="scaleX("+s.scale+")"),0!==s.angle&&(c="rotate("+s.angle+"deg) "+c),0!==s.paddingLeft&&(l+=" padding-left: "+s.paddingLeft/s.scale+"px;",c+=" translateX("+-s.paddingLeft/s.scale+"px)"),0!==s.paddingTop&&(l+=" padding-top: "+s.paddingTop+"px;",c+=" translateY("+-s.paddingTop+"px)"),0!==s.paddingRight&&(l+=" padding-right: "+s.paddingRight/s.scale+"px;"),0!==s.paddingBottom&&(l+=" padding-bottom: "+s.paddingBottom+"px;"),""!==l&&o.setAttribute("style",s.style+l),""!==c&&n.CustomStyle.setProp("transform",o,c)}else o.style.padding=0,n.CustomStyle.setProp("transform",o,s.originalTransform||"")}}}},h}();e.renderTextLayer=o},function(t,e,r){"use strict";function i(t){return t.replace(/>\\376\\377([^<]+)/g,function(t,e){for(var r=e.replace(/\\([0-3])([0-7])([0-7])/g,function(t,e,r,i){return String.fromCharCode(64*e+8*r+1*i)}),i="",n=0;n<r.length;n+=2){var o=256*r.charCodeAt(n)+r.charCodeAt(n+1);i+=o>=32&&o<127&&60!==o&&62!==o&&38!==o?String.fromCharCode(o):"&#x"+(65536+o).toString(16).substring(1)+";"}return">"+i})}function n(t){if("string"==typeof t){t=i(t);t=(new DOMParser).parseFromString(t,"application/xml")}else if(!(t instanceof Document))throw new Error("Metadata: Invalid metadata object");this.metaDocument=t,this.metadata=Object.create(null),this.parse()}Object.defineProperty(e,"__esModule",{value:!0}),n.prototype={parse:function t(){var e=this.metaDocument,r=e.documentElement;if("rdf:rdf"!==r.nodeName.toLowerCase())for(r=r.firstChild;r&&"rdf:rdf"!==r.nodeName.toLowerCase();)r=r.nextSibling;var i=r?r.nodeName.toLowerCase():null;if(r&&"rdf:rdf"===i&&r.hasChildNodes()){var n=r.childNodes,o,a,s,c,l,h,u;for(c=0,h=n.length;c<h;c++)if(o=n[c],"rdf:description"===o.nodeName.toLowerCase())for(l=0,u=o.childNodes.length;l<u;l++)"#text"!==o.childNodes[l].nodeName.toLowerCase()&&(a=o.childNodes[l],s=a.nodeName.toLowerCase(),this.metadata[s]=a.textContent.trim())}},get:function t(e){return this.metadata[e]||null},has:function t(e){return void 0!==this.metadata[e]}},e.Metadata=n},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.WebGLUtils=void 0;var i=r(1),n=r(0),o=function t(){function e(t,e,r){var i=t.createShader(r);if(t.shaderSource(i,e),t.compileShader(i),!t.getShaderParameter(i,t.COMPILE_STATUS)){var n=t.getShaderInfoLog(i);throw new Error("Error during shader compilation: "+n)}return i}function r(t,r){return e(t,r,t.VERTEX_SHADER)}function o(t,r){return e(t,r,t.FRAGMENT_SHADER)}function a(t,e){for(var r=t.createProgram(),i=0,n=e.length;i<n;++i)t.attachShader(r,e[i]);if(t.linkProgram(r),!t.getProgramParameter(r,t.LINK_STATUS)){var o=t.getProgramInfoLog(r);throw new Error("Error during program linking: "+o)}return r}function s(t,e,r){t.activeTexture(r);var i=t.createTexture();return t.bindTexture(t.TEXTURE_2D,i),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),i}function c(){p||(g=document.createElement("canvas"),p=g.getContext("webgl",{premultipliedalpha:!1}))}function l(){var t,e;c(),t=g,g=null,e=p,p=null;var i=r(e,v),n=o(e,m),s=a(e,[i,n]);e.useProgram(s);var l={};l.gl=e,l.canvas=t,l.resolutionLocation=e.getUniformLocation(s,"u_resolution"),l.positionLocation=e.getAttribLocation(s,"a_position"),l.backdropLocation=e.getUniformLocation(s,"u_backdrop"),l.subtypeLocation=e.getUniformLocation(s,"u_subtype");var h=e.getAttribLocation(s,"a_texCoord"),u=e.getUniformLocation(s,"u_image"),f=e.getUniformLocation(s,"u_mask"),d=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,d),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),e.STATIC_DRAW),e.enableVertexAttribArray(h),e.vertexAttribPointer(h,2,e.FLOAT,!1,0,0),e.uniform1i(u,0),e.uniform1i(f,1),b=l}function h(t,e,r){var i=t.width,n=t.height;b||l();var o=b,a=o.canvas,c=o.gl;a.width=i,a.height=n,c.viewport(0,0,c.drawingBufferWidth,c.drawingBufferHeight),c.uniform2f(o.resolutionLocation,i,n),r.backdrop?c.uniform4f(o.resolutionLocation,r.backdrop[0],r.backdrop[1],r.backdrop[2],1):c.uniform4f(o.resolutionLocation,0,0,0,0),c.uniform1i(o.subtypeLocation,"Luminosity"===r.subtype?1:0);var h=s(c,t,c.TEXTURE0),u=s(c,e,c.TEXTURE1),f=c.createBuffer();return c.bindBuffer(c.ARRAY_BUFFER,f),c.bufferData(c.ARRAY_BUFFER,new Float32Array([0,0,i,0,0,n,0,n,i,0,i,n]),c.STATIC_DRAW),c.enableVertexAttribArray(o.positionLocation),c.vertexAttribPointer(o.positionLocation,2,c.FLOAT,!1,0,0),c.clearColor(0,0,0,0),c.enable(c.BLEND),c.blendFunc(c.ONE,c.ONE_MINUS_SRC_ALPHA),c.clear(c.COLOR_BUFFER_BIT),c.drawArrays(c.TRIANGLES,0,6),c.flush(),c.deleteTexture(h),c.deleteTexture(u),c.deleteBuffer(f),a}function u(){var t,e;c(),t=g,g=null,e=p,p=null;var i=r(e,y),n=o(e,_),s=a(e,[i,n]);e.useProgram(s);var l={};l.gl=e,l.canvas=t,l.resolutionLocation=e.getUniformLocation(s,"u_resolution"),l.scaleLocation=e.getUniformLocation(s,"u_scale"),l.offsetLocation=e.getUniformLocation(s,"u_offset"),l.positionLocation=e.getAttribLocation(s,"a_position"),l.colorLocation=e.getAttribLocation(s,"a_color"),w=l}function f(t,e,r,i,n){w||u();var o=w,a=o.canvas,s=o.gl;a.width=t,a.height=e,s.viewport(0,0,s.drawingBufferWidth,s.drawingBufferHeight),s.uniform2f(o.resolutionLocation,t,e);var c=0,l,h,f;for(l=0,h=i.length;l<h;l++)switch(i[l].type){case"lattice":f=i[l].coords.length/i[l].verticesPerRow|0,c+=(f-1)*(i[l].verticesPerRow-1)*6;break;case"triangles":c+=i[l].coords.length}var d=new Float32Array(2*c),p=new Uint8Array(3*c),g=n.coords,v=n.colors,m=0,b=0;for(l=0,h=i.length;l<h;l++){var y=i[l],_=y.coords,S=y.colors;switch(y.type){case"lattice":var x=y.verticesPerRow;f=_.length/x|0;for(var C=1;C<f;C++)for(var A=C*x+1,T=1;T<x;T++,A++)d[m]=g[_[A-x-1]],d[m+1]=g[_[A-x-1]+1],d[m+2]=g[_[A-x]],d[m+3]=g[_[A-x]+1],d[m+4]=g[_[A-1]],d[m+5]=g[_[A-1]+1],p[b]=v[S[A-x-1]],p[b+1]=v[S[A-x-1]+1],p[b+2]=v[S[A-x-1]+2],p[b+3]=v[S[A-x]],p[b+4]=v[S[A-x]+1],p[b+5]=v[S[A-x]+2],p[b+6]=v[S[A-1]],p[b+7]=v[S[A-1]+1],p[b+8]=v[S[A-1]+2],d[m+6]=d[m+2],d[m+7]=d[m+3],d[m+8]=d[m+4],d[m+9]=d[m+5],d[m+10]=g[_[A]],d[m+11]=g[_[A]+1],p[b+9]=p[b+3],p[b+10]=p[b+4],p[b+11]=p[b+5],p[b+12]=p[b+6],p[b+13]=p[b+7],p[b+14]=p[b+8],p[b+15]=v[S[A]],p[b+16]=v[S[A]+1],p[b+17]=v[S[A]+2],m+=12,b+=18;break;case"triangles":for(var k=0,P=_.length;k<P;k++)d[m]=g[_[k]],d[m+1]=g[_[k]+1],p[b]=v[S[k]],p[b+1]=v[S[k]+1],p[b+2]=v[S[k]+2],m+=2,b+=3}}r?s.clearColor(r[0]/255,r[1]/255,r[2]/255,1):s.clearColor(0,0,0,0),s.clear(s.COLOR_BUFFER_BIT);var E=s.createBuffer();s.bindBuffer(s.ARRAY_BUFFER,E),s.bufferData(s.ARRAY_BUFFER,d,s.STATIC_DRAW),s.enableVertexAttribArray(o.positionLocation),s.vertexAttribPointer(o.positionLocation,2,s.FLOAT,!1,0,0);var O=s.createBuffer();return s.bindBuffer(s.ARRAY_BUFFER,O),s.bufferData(s.ARRAY_BUFFER,p,s.STATIC_DRAW),s.enableVertexAttribArray(o.colorLocation),s.vertexAttribPointer(o.colorLocation,3,s.UNSIGNED_BYTE,!1,0,0),s.uniform2f(o.scaleLocation,n.scaleX,n.scaleY),s.uniform2f(o.offsetLocation,n.offsetX,n.offsetY),s.drawArrays(s.TRIANGLES,0,c),s.flush(),s.deleteBuffer(E),s.deleteBuffer(O),a}function d(){b&&b.canvas&&(b.canvas.width=0,b.canvas.height=0),w&&w.canvas&&(w.canvas.width=0,w.canvas.height=0),b=null,w=null}var p,g,v=" attribute vec2 a_position; attribute vec2 a_texCoord; uniform vec2 u_resolution; varying vec2 v_texCoord; void main() { vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); v_texCoord = a_texCoord; } ",m=" precision mediump float; uniform vec4 u_backdrop; uniform int u_subtype; uniform sampler2D u_image; uniform sampler2D u_mask; varying vec2 v_texCoord; void main() { vec4 imageColor = texture2D(u_image, v_texCoord); vec4 maskColor = texture2D(u_mask, v_texCoord); if (u_backdrop.a > 0.0) { maskColor.rgb = maskColor.rgb * maskColor.a + u_backdrop.rgb * (1.0 - maskColor.a); } float lum; if (u_subtype == 0) { lum = maskColor.a; } else { lum = maskColor.r * 0.3 + maskColor.g * 0.59 + maskColor.b * 0.11; } imageColor.a *= lum; imageColor.rgb *= imageColor.a; gl_FragColor = imageColor; } ",b=null,y=" attribute vec2 a_position; attribute vec3 a_color; uniform vec2 u_resolution; uniform vec2 u_scale; uniform vec2 u_offset; varying vec4 v_color; void main() { vec2 position = (a_position + u_offset) * u_scale; vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); v_color = vec4(a_color / 255.0, 1.0); } ",_=" precision mediump float; varying vec4 v_color; void main() { gl_FragColor = v_color; } ",w=null;return{get isEnabled(){if((0,i.getDefaultSetting)("disableWebGL"))return!1;var t=!1;try{c(),t=!!p}catch(t){}return(0,n.shadow)(this,"isEnabled",t)},composeSMask:h,drawFigures:f,clear:d}}();e.WebGLUtils=o},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.PDFJS=e.isWorker=e.globalScope=void 0;var i=r(3),n=r(1),o=r(0),a=r(2),s=r(6),c=r(5),l=r(4),h="undefined"==typeof window;o.globalScope.PDFJS||(o.globalScope.PDFJS={});var u=o.globalScope.PDFJS;u.version="1.8.575",u.build="bd8c1211",u.pdfBug=!1,void 0!==u.verbosity&&(0,o.setVerbosityLevel)(u.verbosity),delete u.verbosity,Object.defineProperty(u,"verbosity",{get:function t(){return(0,o.getVerbosityLevel)()},set:function t(e){(0,o.setVerbosityLevel)(e)},enumerable:!0,configurable:!0}),u.VERBOSITY_LEVELS=o.VERBOSITY_LEVELS,u.OPS=o.OPS,u.UNSUPPORTED_FEATURES=o.UNSUPPORTED_FEATURES,u.isValidUrl=n.isValidUrl,u.shadow=o.shadow,u.createBlob=o.createBlob,u.createObjectURL=function t(e,r){return(0,o.createObjectURL)(e,r,u.disableCreateObjectURL)},Object.defineProperty(u,"isLittleEndian",{configurable:!0,get:function t(){return(0,o.shadow)(u,"isLittleEndian",(0,o.isLittleEndian)())}}),u.removeNullCharacters=o.removeNullCharacters,u.PasswordResponses=o.PasswordResponses,u.PasswordException=o.PasswordException,u.UnknownErrorException=o.UnknownErrorException,u.InvalidPDFException=o.InvalidPDFException,u.MissingPDFException=o.MissingPDFException,u.UnexpectedResponseException=o.UnexpectedResponseException,u.Util=o.Util,u.PageViewport=o.PageViewport,u.createPromiseCapability=o.createPromiseCapability,u.maxImageSize=void 0===u.maxImageSize?-1:u.maxImageSize,u.cMapUrl=void 0===u.cMapUrl?null:u.cMapUrl,u.cMapPacked=void 0!==u.cMapPacked&&u.cMapPacked,u.disableFontFace=void 0!==u.disableFontFace&&u.disableFontFace,u.imageResourcesPath=void 0===u.imageResourcesPath?"":u.imageResourcesPath,u.disableWorker=void 0!==u.disableWorker&&u.disableWorker,u.workerSrc=void 0===u.workerSrc?null:u.workerSrc,u.workerPort=void 0===u.workerPort?null:u.workerPort,u.disableRange=void 0!==u.disableRange&&u.disableRange,u.disableStream=void 0!==u.disableStream&&u.disableStream,u.disableAutoFetch=void 0!==u.disableAutoFetch&&u.disableAutoFetch,u.pdfBug=void 0!==u.pdfBug&&u.pdfBug,u.postMessageTransfers=void 0===u.postMessageTransfers||u.postMessageTransfers,u.disableCreateObjectURL=void 0!==u.disableCreateObjectURL&&u.disableCreateObjectURL,u.disableWebGL=void 0===u.disableWebGL||u.disableWebGL,u.externalLinkTarget=void 0===u.externalLinkTarget?n.LinkTarget.NONE:u.externalLinkTarget,u.externalLinkRel=void 0===u.externalLinkRel?n.DEFAULT_LINK_REL:u.externalLinkRel,u.isEvalSupported=void 0===u.isEvalSupported||u.isEvalSupported,u.pdfjsNext=void 0!==u.pdfjsNext&&u.pdfjsNext;var f=u.openExternalLinksInNewWindow;delete u.openExternalLinksInNewWindow,Object.defineProperty(u,"openExternalLinksInNewWindow",{get:function t(){return u.externalLinkTarget===n.LinkTarget.BLANK},set:function t(e){if(e&&(0,o.deprecated)('PDFJS.openExternalLinksInNewWindow, please use "PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK" instead.'),u.externalLinkTarget!==n.LinkTarget.NONE)return void(0,o.warn)("PDFJS.externalLinkTarget is already initialized");u.externalLinkTarget=e?n.LinkTarget.BLANK:n.LinkTarget.NONE},enumerable:!0,configurable:!0}),f&&(u.openExternalLinksInNewWindow=f),u.getDocument=i.getDocument,u.LoopbackPort=i.LoopbackPort,u.PDFDataRangeTransport=i.PDFDataRangeTransport,u.PDFWorker=i.PDFWorker,u.hasCanvasTypedArrays=!0,u.CustomStyle=n.CustomStyle,u.LinkTarget=n.LinkTarget,u.addLinkAttributes=n.addLinkAttributes,u.getFilenameFromUrl=n.getFilenameFromUrl,u.isExternalLinkTargetSet=n.isExternalLinkTargetSet,u.AnnotationLayer=a.AnnotationLayer,u.renderTextLayer=c.renderTextLayer,u.Metadata=s.Metadata,u.SVGGraphics=l.SVGGraphics,u.UnsupportedManager=i._UnsupportedManager,e.globalScope=o.globalScope,e.isWorker=h,e.PDFJS=u},function(t,e,r){"use strict";var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};!function(t,e){for(var r in e)t[r]=e[r]}(e,function(t){function e(i){if(r[i])return r[i].exports;var n=r[i]={i:i,l:!1,exports:{}};return t[i].call(n.exports,n,n.exports,e),n.l=!0,n.exports}var r={};return e.m=t,e.c=r,e.i=function(t){return t},e.d=function(t,r,i){e.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var r=t&&t.__esModule?function e(){return t.default}:function e(){return t};return e.d(r,"a",r),r},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=7)}([function(t,e,r){function n(t){return"string"==typeof t||"symbol"===(void 0===t?"undefined":a(t))}function o(t,e,r){if("function"!=typeof t)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(t,e,r)}var a="function"==typeof Symbol&&"symbol"===i(Symbol.iterator)?function(t){return void 0===t?"undefined":i(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":void 0===t?"undefined":i(t)},s=r(1),c=s.assert;e.typeIsObject=function(t){return"object"===(void 0===t?"undefined":a(t))&&null!==t||"function"==typeof t},e.createDataProperty=function(t,r,i){c(e.typeIsObject(t)),Object.defineProperty(t,r,{value:i,writable:!0,enumerable:!0,configurable:!0})},e.createArrayFromList=function(t){return t.slice()},e.ArrayBufferCopy=function(t,e,r,i,n){new Uint8Array(t).set(new Uint8Array(r,i,n),e)},e.CreateIterResultObject=function(t,e){c("boolean"==typeof e);var r={};return Object.defineProperty(r,"value",{value:t,enumerable:!0,writable:!0,configurable:!0}),Object.defineProperty(r,"done",{value:e,enumerable:!0,writable:!0,configurable:!0}),r},e.IsFiniteNonNegativeNumber=function(t){return!Number.isNaN(t)&&(t!==1/0&&!(t<0))},e.InvokeOrNoop=function(t,e,r){c(void 0!==t),c(n(e)),c(Array.isArray(r));var i=t[e];if(void 0!==i)return o(i,t,r)},e.PromiseInvokeOrNoop=function(t,r,i){c(void 0!==t),c(n(r)),c(Array.isArray(i));try{return Promise.resolve(e.InvokeOrNoop(t,r,i))}catch(t){return Promise.reject(t)}},e.PromiseInvokeOrPerformFallback=function(t,e,r,i,a){c(void 0!==t),c(n(e)),c(Array.isArray(r)),c(Array.isArray(a));var s=void 0;try{s=t[e]}catch(t){return Promise.reject(t)}if(void 0===s)return i.apply(null,a);try{return Promise.resolve(o(s,t,r))}catch(t){return Promise.reject(t)}},e.TransferArrayBuffer=function(t){return t.slice()},e.ValidateAndNormalizeHighWaterMark=function(t){if(t=Number(t),Number.isNaN(t)||t<0)throw new RangeError("highWaterMark property of a queuing strategy must be non-negative and non-NaN");return t},e.ValidateAndNormalizeQueuingStrategy=function(t,r){if(void 0!==t&&"function"!=typeof t)throw new TypeError("size property of a queuing strategy must be a function");return r=e.ValidateAndNormalizeHighWaterMark(r),{size:t,highWaterMark:r}}},function(t,e,r){function i(t){t&&t.constructor===n&&setTimeout(function(){throw t},0)}function n(t){this.name="AssertionError",this.message=t||"",this.stack=(new Error).stack}function o(t,e){if(!t)throw new n(e)}n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,t.exports={rethrowAssertionErrorRejection:i,AssertionError:n,assert:o}},function(t,e,r){function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t){return new yt(t)}function o(t){return!!lt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_writableStreamController")}function a(t){return ut(!0===o(t),"IsWritableStreamLocked should only be used on known writable streams"),void 0!==t._writer}function s(t,e){var r=t._state;if("closed"===r)return Promise.resolve(void 0);if("errored"===r)return Promise.reject(t._storedError);var i=new TypeError("Requested to abort");if(void 0!==t._pendingAbortRequest)return Promise.reject(i);ut("writable"===r||"erroring"===r,"state must be writable or erroring");var n=!1;"erroring"===r&&(n=!0,e=void 0);var o=new Promise(function(r,i){t._pendingAbortRequest={_resolve:r,_reject:i,_reason:e,_wasAlreadyErroring:n}});return!1===n&&h(t,i),o}function c(t){return ut(!0===a(t)),ut("writable"===t._state),new Promise(function(e,r){var i={_resolve:e,_reject:r};t._writeRequests.push(i)})}function l(t,e){var r=t._state;if("writable"===r)return void h(t,e);ut("erroring"===r),u(t)}function h(t,e){ut(void 0===t._storedError,"stream._storedError === undefined"),ut("writable"===t._state,"state must be writable");var r=t._writableStreamController;ut(void 0!==r,"controller must not be undefined"),t._state="erroring",t._storedError=e;var i=t._writer;void 0!==i&&k(i,e),!1===m(t)&&!0===r._started&&u(t)}function u(t){ut("erroring"===t._state,"stream._state === erroring"),ut(!1===m(t),"WritableStreamHasOperationMarkedInFlight(stream) === false"),t._state="errored",t._writableStreamController.__errorSteps();for(var e=t._storedError,r=0;r<t._writeRequests.length;r++){t._writeRequests[r]._reject(e)}if(t._writeRequests=[],void 0===t._pendingAbortRequest)return void _(t);var i=t._pendingAbortRequest;if(t._pendingAbortRequest=void 0,!0===i._wasAlreadyErroring)return i._reject(e),void _(t);t._writableStreamController.__abortSteps(i._reason).then(function(){i._resolve(),_(t)},function(e){i._reject(e),_(t)})}function f(t){ut(void 0!==t._inFlightWriteRequest),t._inFlightWriteRequest._resolve(void 0),t._inFlightWriteRequest=void 0}function d(t,e){ut(void 0!==t._inFlightWriteRequest),t._inFlightWriteRequest._reject(e),t._inFlightWriteRequest=void 0,ut("writable"===t._state||"erroring"===t._state),l(t,e)}function p(t){ut(void 0!==t._inFlightCloseRequest),t._inFlightCloseRequest._resolve(void 0),t._inFlightCloseRequest=void 0;var e=t._state;ut("writable"===e||"erroring"===e),"erroring"===e&&(t._storedError=void 0,void 0!==t._pendingAbortRequest&&(t._pendingAbortRequest._resolve(),t._pendingAbortRequest=void 0)),t._state="closed";var r=t._writer;void 0!==r&&J(r),ut(void 0===t._pendingAbortRequest,"stream._pendingAbortRequest === undefined"),ut(void 0===t._storedError,"stream._storedError === undefined")}function g(t,e){ut(void 0!==t._inFlightCloseRequest),t._inFlightCloseRequest._reject(e),t._inFlightCloseRequest=void 0,ut("writable"===t._state||"erroring"===t._state),void 0!==t._pendingAbortRequest&&(t._pendingAbortRequest._reject(e),t._pendingAbortRequest=void 0),l(t,e)}function v(t){return void 0!==t._closeRequest||void 0!==t._inFlightCloseRequest}function m(t){return void 0!==t._inFlightWriteRequest||void 0!==t._inFlightCloseRequest}function b(t){ut(void 0===t._inFlightCloseRequest),ut(void 0!==t._closeRequest),t._inFlightCloseRequest=t._closeRequest,t._closeRequest=void 0}function y(t){ut(void 0===t._inFlightWriteRequest,"there must be no pending write request"),ut(0!==t._writeRequests.length,"writeRequests must not be empty"),t._inFlightWriteRequest=t._writeRequests.shift()}function _(t){ut("errored"===t._state,'_stream_.[[state]] is `"errored"`'),void 0!==t._closeRequest&&(ut(void 0===t._inFlightCloseRequest),t._closeRequest._reject(t._storedError),t._closeRequest=void 0);var e=t._writer;void 0!==e&&(V(e,t._storedError),e._closedPromise.catch(function(){}))}function w(t,e){ut("writable"===t._state),ut(!1===v(t));var r=t._writer;void 0!==r&&e!==t._backpressure&&(!0===e?et(r):(ut(!1===e),it(r))),t._backpressure=e}function S(t){return!!lt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_ownerWritableStream")}function x(t,e){var r=t._ownerWritableStream;return ut(void 0!==r),s(r,e)}function C(t){var e=t._ownerWritableStream;ut(void 0!==e);var r=e._state;if("closed"===r||"errored"===r)return Promise.reject(new TypeError("The stream (in "+r+" state) is not in the writable state and cannot be closed"));ut("writable"===r||"erroring"===r),ut(!1===v(e));var i=new Promise(function(t,r){var i={_resolve:t,_reject:r};e._closeRequest=i});return!0===e._backpressure&&"writable"===r&&it(t),R(e._writableStreamController),i}function A(t){var e=t._ownerWritableStream;ut(void 0!==e);var r=e._state;return!0===v(e)||"closed"===r?Promise.resolve():"errored"===r?Promise.reject(e._storedError):(ut("writable"===r||"erroring"===r),C(t))}function T(t,e){"pending"===t._closedPromiseState?V(t,e):Z(t,e),t._closedPromise.catch(function(){})}function k(t,e){"pending"===t._readyPromiseState?tt(t,e):rt(t,e),t._readyPromise.catch(function(){})}function P(t){var e=t._ownerWritableStream,r=e._state;return"errored"===r||"erroring"===r?null:"closed"===r?0:D(e._writableStreamController)}function E(t){var e=t._ownerWritableStream;ut(void 0!==e),ut(e._writer===t);var r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");k(t,r),T(t,r),e._writer=void 0,t._ownerWritableStream=void 0}function O(t,e){var r=t._ownerWritableStream;ut(void 0!==r);var i=r._writableStreamController,n=L(i,e);if(r!==t._ownerWritableStream)return Promise.reject(X("write to"));var o=r._state;if("errored"===o)return Promise.reject(r._storedError);if(!0===v(r)||"closed"===o)return Promise.reject(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===o)return Promise.reject(r._storedError);ut("writable"===o);var a=c(r);return I(i,e,n),a}function R(t){gt(t,"close",0),M(t)}function L(t,e){var r=t._strategySize;if(void 0===r)return 1;try{return r(e)}catch(e){return F(t,e),1}}function D(t){return t._strategyHWM-t._queueTotalSize}function I(t,e,r){var i={chunk:e};try{gt(t,i,r)}catch(e){return void F(t,e)}var n=t._controlledWritableStream;if(!1===v(n)&&"writable"===n._state){w(n,U(t))}M(t)}function j(t){return!!lt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_underlyingSink")}function M(t){var e=t._controlledWritableStream;if(!1!==t._started&&void 0===e._inFlightWriteRequest){var r=e._state;if("closed"!==r&&"errored"!==r){if("erroring"===r)return void u(e);if(0!==t._queue.length){var i=vt(t);"close"===i?N(t):B(t,i.chunk)}}}}function F(t,e){"writable"===t._controlledWritableStream._state&&z(t,e)}function N(t){var e=t._controlledWritableStream;b(e),pt(t),ut(0===t._queue.length,"queue must be empty once the final write record is dequeued"),st(t._underlyingSink,"close",[]).then(function(){p(e)},function(t){g(e,t)}).catch(ft)}function B(t,e){var r=t._controlledWritableStream;y(r),st(t._underlyingSink,"write",[e,t]).then(function(){f(r);var e=r._state;if(ut("writable"===e||"erroring"===e),pt(t),!1===v(r)&&"writable"===e){var i=U(t);w(r,i)}M(t)},function(t){d(r,t)}).catch(ft)}function U(t){return D(t)<=0}function z(t,e){var r=t._controlledWritableStream;ut("writable"===r._state),h(r,e)}function W(t){return new TypeError("WritableStream.prototype."+t+" can only be used on a WritableStream")}function q(t){return new TypeError("WritableStreamDefaultWriter.prototype."+t+" can only be used on a WritableStreamDefaultWriter")}function X(t){return new TypeError("Cannot "+t+" a stream using a released writer")}function G(t){t._closedPromise=new Promise(function(e,r){t._closedPromise_resolve=e,t._closedPromise_reject=r,t._closedPromiseState="pending"})}function H(t,e){t._closedPromise=Promise.reject(e),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0,t._closedPromiseState="rejected"}function Y(t){t._closedPromise=Promise.resolve(void 0),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0,t._closedPromiseState="resolved"}function V(t,e){ut(void 0!==t._closedPromise_resolve,"writer._closedPromise_resolve !== undefined"),ut(void 0!==t._closedPromise_reject,"writer._closedPromise_reject !== undefined"),ut("pending"===t._closedPromiseState,"writer._closedPromiseState is pending"),t._closedPromise_reject(e),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0,t._closedPromiseState="rejected"}function Z(t,e){ut(void 0===t._closedPromise_resolve,"writer._closedPromise_resolve === undefined"),ut(void 0===t._closedPromise_reject,"writer._closedPromise_reject === undefined"),ut("pending"!==t._closedPromiseState,"writer._closedPromiseState is not pending"),t._closedPromise=Promise.reject(e),t._closedPromiseState="rejected"}function J(t){ut(void 0!==t._closedPromise_resolve,"writer._closedPromise_resolve !== undefined"),ut(void 0!==t._closedPromise_reject,"writer._closedPromise_reject !== undefined"),ut("pending"===t._closedPromiseState,"writer._closedPromiseState is pending"),t._closedPromise_resolve(void 0),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0,t._closedPromiseState="resolved"}function K(t){t._readyPromise=new Promise(function(e,r){t._readyPromise_resolve=e,t._readyPromise_reject=r}),t._readyPromiseState="pending"}function Q(t,e){t._readyPromise=Promise.reject(e),t._readyPromise_resolve=void 0,t._readyPromise_reject=void 0,t._readyPromiseState="rejected"}function $(t){t._readyPromise=Promise.resolve(void 0),t._readyPromise_resolve=void 0,t._readyPromise_reject=void 0,t._readyPromiseState="fulfilled"}function tt(t,e){ut(void 0!==t._readyPromise_resolve,"writer._readyPromise_resolve !== undefined"),ut(void 0!==t._readyPromise_reject,"writer._readyPromise_reject !== undefined"),t._readyPromise_reject(e),t._readyPromise_resolve=void 0,t._readyPromise_reject=void 0,t._readyPromiseState="rejected"}function et(t){ut(void 0===t._readyPromise_resolve,"writer._readyPromise_resolve === undefined"),ut(void 0===t._readyPromise_reject,"writer._readyPromise_reject === undefined"),t._readyPromise=new Promise(function(e,r){t._readyPromise_resolve=e,t._readyPromise_reject=r}),t._readyPromiseState="pending"}function rt(t,e){ut(void 0===t._readyPromise_resolve,"writer._readyPromise_resolve === undefined"),ut(void 0===t._readyPromise_reject,"writer._readyPromise_reject === undefined"),t._readyPromise=Promise.reject(e),t._readyPromiseState="rejected"}function it(t){ut(void 0!==t._readyPromise_resolve,"writer._readyPromise_resolve !== undefined"),ut(void 0!==t._readyPromise_reject,"writer._readyPromise_reject !== undefined"),t._readyPromise_resolve(void 0),t._readyPromise_resolve=void 0,t._readyPromise_reject=void 0,t._readyPromiseState="fulfilled"}var nt=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),ot=r(0),at=ot.InvokeOrNoop,st=ot.PromiseInvokeOrNoop,ct=ot.ValidateAndNormalizeQueuingStrategy,lt=ot.typeIsObject,ht=r(1),ut=ht.assert,ft=ht.rethrowAssertionErrorRejection,dt=r(3),pt=dt.DequeueValue,gt=dt.EnqueueValueWithSize,vt=dt.PeekQueueValue,mt=dt.ResetQueue,bt=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=r.size,o=r.highWaterMark,a=void 0===o?1:o;if(i(this,t),this._state="writable",this._storedError=void 0,this._writer=void 0,this._writableStreamController=void 0,this._writeRequests=[],this._inFlightWriteRequest=void 0,this._closeRequest=void 0,this._inFlightCloseRequest=void 0,this._pendingAbortRequest=void 0,this._backpressure=!1,void 0!==e.type)throw new RangeError("Invalid type is specified");this._writableStreamController=new _t(this,e,n,a),this._writableStreamController.__startSteps()}return nt(t,[{key:"abort",value:function t(e){return!1===o(this)?Promise.reject(W("abort")):!0===a(this)?Promise.reject(new TypeError("Cannot abort a stream that already has a writer")):s(this,e)}},{key:"getWriter",value:function t(){if(!1===o(this))throw W("getWriter");return n(this)}},{key:"locked",get:function t(){if(!1===o(this))throw W("locked");return a(this)}}]),t}();t.exports={AcquireWritableStreamDefaultWriter:n,IsWritableStream:o,IsWritableStreamLocked:a,WritableStream:bt,WritableStreamAbort:s,WritableStreamDefaultControllerError:z,WritableStreamDefaultWriterCloseWithErrorPropagation:A,WritableStreamDefaultWriterRelease:E,WritableStreamDefaultWriterWrite:O,WritableStreamCloseQueuedOrInFlight:v};var yt=function(){function t(e){if(i(this,t),!1===o(e))throw new TypeError("WritableStreamDefaultWriter can only be constructed with a WritableStream instance");if(!0===a(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;var r=e._state;if("writable"===r)!1===v(e)&&!0===e._backpressure?K(this):$(this),G(this);else if("erroring"===r)Q(this,e._storedError),this._readyPromise.catch(function(){}),G(this);else if("closed"===r)$(this),Y(this);else{ut("errored"===r,"state must be errored");var n=e._storedError;Q(this,n),this._readyPromise.catch(function(){}),H(this,n),this._closedPromise.catch(function(){})}}return nt(t,[{key:"abort",value:function t(e){return!1===S(this)?Promise.reject(q("abort")):void 0===this._ownerWritableStream?Promise.reject(X("abort")):x(this,e)}},{key:"close",value:function t(){if(!1===S(this))return Promise.reject(q("close"));var e=this._ownerWritableStream;return void 0===e?Promise.reject(X("close")):!0===v(e)?Promise.reject(new TypeError("cannot close an already-closing stream")):C(this)}},{key:"releaseLock",value:function t(){if(!1===S(this))throw q("releaseLock");var e=this._ownerWritableStream;void 0!==e&&(ut(void 0!==e._writer),E(this))}},{key:"write",value:function t(e){return!1===S(this)?Promise.reject(q("write")):void 0===this._ownerWritableStream?Promise.reject(X("write to")):O(this,e)}},{key:"closed",get:function t(){return!1===S(this)?Promise.reject(q("closed")):this._closedPromise}},{key:"desiredSize",get:function t(){if(!1===S(this))throw q("desiredSize");if(void 0===this._ownerWritableStream)throw X("desiredSize");return P(this)}},{key:"ready",get:function t(){return!1===S(this)?Promise.reject(q("ready")):this._readyPromise}}]),t}(),_t=function(){function t(e,r,n,a){if(i(this,t),!1===o(e))throw new TypeError("WritableStreamDefaultController can only be constructed with a WritableStream instance");if(void 0!==e._writableStreamController)throw new TypeError("WritableStreamDefaultController instances can only be created by the WritableStream constructor");this._controlledWritableStream=e,this._underlyingSink=r,this._queue=void 0,this._queueTotalSize=void 0,mt(this),this._started=!1;var s=ct(n,a);this._strategySize=s.size,this._strategyHWM=s.highWaterMark,w(e,U(this))}return nt(t,[{key:"error",value:function t(e){if(!1===j(this))throw new TypeError("WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController");"writable"===this._controlledWritableStream._state&&z(this,e)}},{key:"__abortSteps",value:function t(e){return st(this._underlyingSink,"abort",[e])}},{key:"__errorSteps",value:function t(){mt(this)}},{key:"__startSteps",value:function t(){var e=this,r=at(this._underlyingSink,"start",[this]),i=this._controlledWritableStream;Promise.resolve(r).then(function(){ut("writable"===i._state||"erroring"===i._state),e._started=!0,M(e)},function(t){ut("writable"===i._state||"erroring"===i._state),e._started=!0,l(i,t)}).catch(ft)}}]),t}()},function(t,e,r){var i=r(0),n=i.IsFiniteNonNegativeNumber,o=r(1),a=o.assert;e.DequeueValue=function(t){a("_queue"in t&&"_queueTotalSize"in t,"Spec-level failure: DequeueValue should only be used on containers with [[queue]] and [[queueTotalSize]]."),a(t._queue.length>0,"Spec-level failure: should never dequeue from an empty queue.");var e=t._queue.shift();return t._queueTotalSize-=e.size,t._queueTotalSize<0&&(t._queueTotalSize=0),e.value},e.EnqueueValueWithSize=function(t,e,r){if(a("_queue"in t&&"_queueTotalSize"in t,"Spec-level failure: EnqueueValueWithSize should only be used on containers with [[queue]] and [[queueTotalSize]]."),r=Number(r),!n(r))throw new RangeError("Size must be a finite, non-NaN, non-negative number.");t._queue.push({value:e,size:r}),t._queueTotalSize+=r},e.PeekQueueValue=function(t){return a("_queue"in t&&"_queueTotalSize"in t,"Spec-level failure: PeekQueueValue should only be used on containers with [[queue]] and [[queueTotalSize]]."),a(t._queue.length>0,"Spec-level failure: should never peek at an empty queue."),t._queue[0].value},e.ResetQueue=function(t){a("_queue"in t&&"_queueTotalSize"in t,"Spec-level failure: ResetQueue should only be used on containers with [[queue]] and [[queueTotalSize]]."),t._queue=[],t._queueTotalSize=0}},function(t,e,r){function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t){return new ee(t)}function o(t){return new te(t)}function a(t){return!!Mt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_readableStreamController")}function s(t){return Nt(!0===a(t),"IsReadableStreamDisturbed should only be used on known readable streams"),t._disturbed}function c(t){return Nt(!0===a(t),"IsReadableStreamLocked should only be used on known readable streams"),void 0!==t._reader}function l(t,e){Nt(!0===a(t)),Nt("boolean"==typeof e);var r=o(t),i={closedOrErrored:!1,canceled1:!1,canceled2:!1,reason1:void 0,reason2:void 0};i.promise=new Promise(function(t){i._resolve=t});var n=h();n._reader=r,n._teeState=i,n._cloneForBranch2=e;var s=u();s._stream=t,s._teeState=i;var c=f();c._stream=t,c._teeState=i;var l=Object.create(Object.prototype);jt(l,"pull",n),jt(l,"cancel",s);var d=new $t(l),p=Object.create(Object.prototype);jt(p,"pull",n),jt(p,"cancel",c);var g=new $t(p);return n._branch1=d._readableStreamController,n._branch2=g._readableStreamController,r._closedPromise.catch(function(t){!0!==i.closedOrErrored&&(M(n._branch1,t),M(n._branch2,t),i.closedOrErrored=!0)}),[d,g]}function h(){function t(){var e=t._reader,r=t._branch1,i=t._branch2,n=t._teeState;return O(e).then(function(t){Nt(Mt(t));var e=t.value,o=t.done;if(Nt("boolean"==typeof o),!0===o&&!1===n.closedOrErrored&&(!1===n.canceled1&&I(r),!1===n.canceled2&&I(i),n.closedOrErrored=!0),!0!==n.closedOrErrored){var a=e,s=e;!1===n.canceled1&&j(r,a),!1===n.canceled2&&j(i,s)}})}return t}function u(){function t(e){var r=t._stream,i=t._teeState;if(i.canceled1=!0,i.reason1=e,!0===i.canceled2){var n=It([i.reason1,i.reason2]),o=g(r,n);i._resolve(o)}return i.promise}return t}function f(){function t(e){var r=t._stream,i=t._teeState;if(i.canceled2=!0,i.reason2=e,!0===i.canceled1){var n=It([i.reason1,i.reason2]),o=g(r,n);i._resolve(o)}return i.promise}return t}function d(t){return Nt(!0===C(t._reader)),Nt("readable"===t._state||"closed"===t._state),new Promise(function(e,r){var i={_resolve:e,_reject:r};t._reader._readIntoRequests.push(i)})}function p(t){return Nt(!0===A(t._reader)),Nt("readable"===t._state),new Promise(function(e,r){var i={_resolve:e,_reject:r};t._reader._readRequests.push(i)})}function g(t,e){return t._disturbed=!0,"closed"===t._state?Promise.resolve(void 0):"errored"===t._state?Promise.reject(t._storedError):(v(t),t._readableStreamController.__cancelSteps(e).then(function(){}))}function v(t){Nt("readable"===t._state),t._state="closed";var e=t._reader;if(void 0!==e){if(!0===A(e)){for(var r=0;r<e._readRequests.length;r++){(0,e._readRequests[r]._resolve)(Tt(void 0,!0))}e._readRequests=[]}mt(e)}}function m(t,e){Nt(!0===a(t),"stream must be ReadableStream"),Nt("readable"===t._state,"state must be readable"),t._state="errored",t._storedError=e;var r=t._reader;if(void 0!==r){if(!0===A(r)){for(var i=0;i<r._readRequests.length;i++){r._readRequests[i]._reject(e)}r._readRequests=[]}else{Nt(C(r),"reader must be ReadableStreamBYOBReader");for(var n=0;n<r._readIntoRequests.length;n++){r._readIntoRequests[n]._reject(e)}r._readIntoRequests=[]}gt(r,e),r._closedPromise.catch(function(){})}}function b(t,e,r){var i=t._reader;Nt(i._readIntoRequests.length>0),i._readIntoRequests.shift()._resolve(Tt(e,r))}function y(t,e,r){var i=t._reader;Nt(i._readRequests.length>0),i._readRequests.shift()._resolve(Tt(e,r))}function _(t){return t._reader._readIntoRequests.length}function w(t){return t._reader._readRequests.length}function S(t){var e=t._reader;return void 0!==e&&!1!==C(e)}function x(t){var e=t._reader;return void 0!==e&&!1!==A(e)}function C(t){return!!Mt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_readIntoRequests")}function A(t){return!!Mt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_readRequests")}function T(t,e){t._ownerReadableStream=e,e._reader=t,"readable"===e._state?ft(t):"closed"===e._state?pt(t):(Nt("errored"===e._state,"state must be errored"),dt(t,e._storedError),t._closedPromise.catch(function(){}))}function k(t,e){var r=t._ownerReadableStream;return Nt(void 0!==r),g(r,e)}function P(t){Nt(void 0!==t._ownerReadableStream),Nt(t._ownerReadableStream._reader===t),"readable"===t._ownerReadableStream._state?gt(t,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):vt(t,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),t._closedPromise.catch(function(){}),t._ownerReadableStream._reader=void 0,t._ownerReadableStream=void 0}function E(t,e){var r=t._ownerReadableStream;return Nt(void 0!==r),r._disturbed=!0,"errored"===r._state?Promise.reject(r._storedError):K(r._readableStreamController,e)}function O(t){var e=t._ownerReadableStream;return Nt(void 0!==e),e._disturbed=!0,"closed"===e._state?Promise.resolve(Tt(void 0,!0)):"errored"===e._state?Promise.reject(e._storedError):(Nt("readable"===e._state),e._readableStreamController.__pullSteps())}function R(t){return!!Mt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_underlyingSource")}function L(t){if(!1!==D(t)){if(!0===t._pulling)return void(t._pullAgain=!0);Nt(!1===t._pullAgain),t._pulling=!0,Et(t._underlyingSource,"pull",[t]).then(function(){if(t._pulling=!1,!0===t._pullAgain)return t._pullAgain=!1,L(t)},function(e){F(t,e)}).catch(Bt)}}function D(t){var e=t._controlledReadableStream;return"closed"!==e._state&&"errored"!==e._state&&(!0!==t._closeRequested&&(!1!==t._started&&(!0===c(e)&&w(e)>0||N(t)>0)))}function I(t){var e=t._controlledReadableStream;Nt(!1===t._closeRequested),Nt("readable"===e._state),t._closeRequested=!0,0===t._queue.length&&v(e)}function j(t,e){var r=t._controlledReadableStream;if(Nt(!1===t._closeRequested),Nt("readable"===r._state),!0===c(r)&&w(r)>0)y(r,e,!1);else{var i=1;if(void 0!==t._strategySize){var n=t._strategySize;try{i=n(e)}catch(e){throw F(t,e),e}}try{Wt(t,e,i)}catch(e){throw F(t,e),e}}L(t)}function M(t,e){var r=t._controlledReadableStream;Nt("readable"===r._state),qt(t),m(r,e)}function F(t,e){"readable"===t._controlledReadableStream._state&&M(t,e)}function N(t){var e=t._controlledReadableStream,r=e._state;return"errored"===r?null:"closed"===r?0:t._strategyHWM-t._queueTotalSize}function B(t){return!!Mt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_underlyingByteSource")}function U(t){return!!Mt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_associatedReadableByteStreamController")}function z(t){if(!1!==rt(t)){if(!0===t._pulling)return void(t._pullAgain=!0);Nt(!1===t._pullAgain),t._pulling=!0,Et(t._underlyingByteSource,"pull",[t]).then(function(){t._pulling=!1,!0===t._pullAgain&&(t._pullAgain=!1,z(t))},function(e){"readable"===t._controlledReadableStream._state&&ot(t,e)}).catch(Bt)}}function W(t){Z(t),t._pendingPullIntos=[]}function q(t,e){Nt("errored"!==t._state,"state must not be errored");var r=!1;"closed"===t._state&&(Nt(0===e.bytesFilled),r=!0);var i=X(e);"default"===e.readerType?y(t,i,r):(Nt("byob"===e.readerType),b(t,i,r))}function X(t){var e=t.bytesFilled,r=t.elementSize;return Nt(e<=t.byteLength),Nt(e%r==0),new t.ctor(t.buffer,t.byteOffset,e/r)}function G(t,e,r,i){t._queue.push({buffer:e,byteOffset:r,byteLength:i}),t._queueTotalSize+=i}function H(t,e){var r=e.elementSize,i=e.bytesFilled-e.bytesFilled%r,n=Math.min(t._queueTotalSize,e.byteLength-e.bytesFilled),o=e.bytesFilled+n,a=o-o%r,s=n,c=!1;a>i&&(s=a-e.bytesFilled,c=!0);for(var l=t._queue;s>0;){var h=l[0],u=Math.min(s,h.byteLength),f=e.byteOffset+e.bytesFilled;At(e.buffer,f,h.buffer,h.byteOffset,u),h.byteLength===u?l.shift():(h.byteOffset+=u,h.byteLength-=u),t._queueTotalSize-=u,Y(t,u,e),s-=u}return!1===c&&(Nt(0===t._queueTotalSize,"queue must be empty"),Nt(e.bytesFilled>0),Nt(e.bytesFilled<e.elementSize)),c}function Y(t,e,r){Nt(0===t._pendingPullIntos.length||t._pendingPullIntos[0]===r),Z(t),r.bytesFilled+=e}function V(t){Nt("readable"===t._controlledReadableStream._state),0===t._queueTotalSize&&!0===t._closeRequested?v(t._controlledReadableStream):z(t)}function Z(t){void 0!==t._byobRequest&&(t._byobRequest._associatedReadableByteStreamController=void 0,t._byobRequest._view=void 0,t._byobRequest=void 0)}function J(t){for(Nt(!1===t._closeRequested);t._pendingPullIntos.length>0;){if(0===t._queueTotalSize)return;var e=t._pendingPullIntos[0];!0===H(t,e)&&(et(t),q(t._controlledReadableStream,e))}}function K(t,e){var r=t._controlledReadableStream,i=1;e.constructor!==DataView&&(i=e.constructor.BYTES_PER_ELEMENT);var n=e.constructor,o={buffer:e.buffer,byteOffset:e.byteOffset,byteLength:e.byteLength,bytesFilled:0,elementSize:i,ctor:n,readerType:"byob"};if(t._pendingPullIntos.length>0)return o.buffer=Ot(o.buffer),t._pendingPullIntos.push(o),d(r);if("closed"===r._state){var a=new e.constructor(o.buffer,o.byteOffset,0);return Promise.resolve(Tt(a,!0))}if(t._queueTotalSize>0){if(!0===H(t,o)){var s=X(o);return V(t),Promise.resolve(Tt(s,!1))}if(!0===t._closeRequested){var c=new TypeError("Insufficient bytes to fill elements in the given buffer");return ot(t,c),Promise.reject(c)}}o.buffer=Ot(o.buffer),t._pendingPullIntos.push(o);var l=d(r);return z(t),l}function Q(t,e){e.buffer=Ot(e.buffer),Nt(0===e.bytesFilled,"bytesFilled must be 0");var r=t._controlledReadableStream;if(!0===S(r))for(;_(r)>0;){var i=et(t);q(r,i)}}function $(t,e,r){if(r.bytesFilled+e>r.byteLength)throw new RangeError("bytesWritten out of range");if(Y(t,e,r),!(r.bytesFilled<r.elementSize)){et(t);var i=r.bytesFilled%r.elementSize;if(i>0){var n=r.byteOffset+r.bytesFilled,o=r.buffer.slice(n-i,n);G(t,o,0,o.byteLength)}r.buffer=Ot(r.buffer),r.bytesFilled-=i,q(t._controlledReadableStream,r),J(t)}}function tt(t,e){var r=t._pendingPullIntos[0],i=t._controlledReadableStream;if("closed"===i._state){if(0!==e)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream");Q(t,r)}else Nt("readable"===i._state),$(t,e,r)}function et(t){var e=t._pendingPullIntos.shift();return Z(t),e}function rt(t){var e=t._controlledReadableStream;return"readable"===e._state&&(!0!==t._closeRequested&&(!1!==t._started&&(!0===x(e)&&w(e)>0||(!0===S(e)&&_(e)>0||at(t)>0))))}function it(t){var e=t._controlledReadableStream;if(Nt(!1===t._closeRequested),Nt("readable"===e._state),t._queueTotalSize>0)return void(t._closeRequested=!0);if(t._pendingPullIntos.length>0){if(t._pendingPullIntos[0].bytesFilled>0){var r=new TypeError("Insufficient bytes to fill elements in the given buffer");throw ot(t,r),r}}v(e)}function nt(t,e){var r=t._controlledReadableStream;Nt(!1===t._closeRequested),Nt("readable"===r._state);var i=e.buffer,n=e.byteOffset,o=e.byteLength,a=Ot(i);if(!0===x(r))if(0===w(r))G(t,a,n,o);else{Nt(0===t._queue.length);var s=new Uint8Array(a,n,o);y(r,s,!1)}else!0===S(r)?(G(t,a,n,o),J(t)):(Nt(!1===c(r),"stream must not be locked"),G(t,a,n,o))}function ot(t,e){var r=t._controlledReadableStream;Nt("readable"===r._state),W(t),qt(t),m(r,e)}function at(t){var e=t._controlledReadableStream,r=e._state;return"errored"===r?null:"closed"===r?0:t._strategyHWM-t._queueTotalSize}function st(t,e){if(e=Number(e),!1===kt(e))throw new RangeError("bytesWritten must be a finite");Nt(t._pendingPullIntos.length>0),tt(t,e)}function ct(t,e){Nt(t._pendingPullIntos.length>0);var r=t._pendingPullIntos[0];if(r.byteOffset+r.bytesFilled!==e.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.byteLength!==e.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");r.buffer=e.buffer,tt(t,e.byteLength)}function lt(t){return new TypeError("ReadableStream.prototype."+t+" can only be used on a ReadableStream")}function ht(t){return new TypeError("Cannot "+t+" a stream using a released reader")}function ut(t){return new TypeError("ReadableStreamDefaultReader.prototype."+t+" can only be used on a ReadableStreamDefaultReader")}function ft(t){t._closedPromise=new Promise(function(e,r){t._closedPromise_resolve=e,t._closedPromise_reject=r})}function dt(t,e){t._closedPromise=Promise.reject(e),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0}function pt(t){t._closedPromise=Promise.resolve(void 0),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0}function gt(t,e){Nt(void 0!==t._closedPromise_resolve),Nt(void 0!==t._closedPromise_reject),t._closedPromise_reject(e),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0}function vt(t,e){Nt(void 0===t._closedPromise_resolve),Nt(void 0===t._closedPromise_reject),t._closedPromise=Promise.reject(e)}function mt(t){Nt(void 0!==t._closedPromise_resolve),Nt(void 0!==t._closedPromise_reject),t._closedPromise_resolve(void 0),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0}function bt(t){return new TypeError("ReadableStreamBYOBReader.prototype."+t+" can only be used on a ReadableStreamBYOBReader")}function yt(t){return new TypeError("ReadableStreamDefaultController.prototype."+t+" can only be used on a ReadableStreamDefaultController")}function _t(t){return new TypeError("ReadableStreamBYOBRequest.prototype."+t+" can only be used on a ReadableStreamBYOBRequest")}function wt(t){return new TypeError("ReadableByteStreamController.prototype."+t+" can only be used on a ReadableByteStreamController")}function St(t){try{Promise.prototype.then.call(t,void 0,function(){})}catch(t){}}var xt=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),Ct=r(0),At=Ct.ArrayBufferCopy,Tt=Ct.CreateIterResultObject,kt=Ct.IsFiniteNonNegativeNumber,Pt=Ct.InvokeOrNoop,Et=Ct.PromiseInvokeOrNoop,Ot=Ct.TransferArrayBuffer,Rt=Ct.ValidateAndNormalizeQueuingStrategy,Lt=Ct.ValidateAndNormalizeHighWaterMark,Dt=r(0),It=Dt.createArrayFromList,jt=Dt.createDataProperty,Mt=Dt.typeIsObject,Ft=r(1),Nt=Ft.assert,Bt=Ft.rethrowAssertionErrorRejection,Ut=r(3),zt=Ut.DequeueValue,Wt=Ut.EnqueueValueWithSize,qt=Ut.ResetQueue,Xt=r(2),Gt=Xt.AcquireWritableStreamDefaultWriter,Ht=Xt.IsWritableStream,Yt=Xt.IsWritableStreamLocked,Vt=Xt.WritableStreamAbort,Zt=Xt.WritableStreamDefaultWriterCloseWithErrorPropagation,Jt=Xt.WritableStreamDefaultWriterRelease,Kt=Xt.WritableStreamDefaultWriterWrite,Qt=Xt.WritableStreamCloseQueuedOrInFlight,$t=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=r.size,o=r.highWaterMark;i(this,t),this._state="readable",this._reader=void 0,this._storedError=void 0,this._disturbed=!1,this._readableStreamController=void 0;var a=e.type;if("bytes"===String(a))void 0===o&&(o=0),this._readableStreamController=new ne(this,e,o);else{if(void 0!==a)throw new RangeError("Invalid type is specified");void 0===o&&(o=1),this._readableStreamController=new re(this,e,n,o)}}return xt(t,[{key:"cancel",value:function t(e){return!1===a(this)?Promise.reject(lt("cancel")):!0===c(this)?Promise.reject(new TypeError("Cannot cancel a stream that already has a reader")):g(this,e)}},{key:"getReader",value:function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=e.mode;if(!1===a(this))throw lt("getReader");if(void 0===r)return o(this);if("byob"===(r=String(r)))return n(this);throw new RangeError("Invalid mode is specified")}},{key:"pipeThrough",value:function t(e,r){var i=e.writable,n=e.readable;return St(this.pipeTo(i,r)),n}},{key:"pipeTo",value:function t(e){var r=this,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=i.preventClose,s=i.preventAbort,l=i.preventCancel;if(!1===a(this))return Promise.reject(lt("pipeTo"));if(!1===Ht(e))return Promise.reject(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));if(n=Boolean(n),s=Boolean(s),l=Boolean(l),!0===c(this))return Promise.reject(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream"));if(!0===Yt(e))return Promise.reject(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream"));var h=o(this),u=Gt(e),f=!1,d=Promise.resolve();return new Promise(function(t,i){function o(){return d=Promise.resolve(),!0===f?Promise.resolve():u._readyPromise.then(function(){return O(h).then(function(t){var e=t.value;!0!==t.done&&(d=Kt(u,e).catch(function(){}))})}).then(o)}function a(){var t=d;return d.then(function(){return t!==d?a():void 0})}function c(t,e,r){"errored"===t._state?r(t._storedError):e.catch(r).catch(Bt)}function p(t,e,r){"closed"===t._state?r():e.then(r).catch(Bt)}function v(t,r,i){function n(){t().then(function(){return b(r,i)},function(t){return b(!0,t)}).catch(Bt)}!0!==f&&(f=!0,"writable"===e._state&&!1===Qt(e)?a().then(n):n())}function m(t,r){!0!==f&&(f=!0,"writable"===e._state&&!1===Qt(e)?a().then(function(){return b(t,r)}).catch(Bt):b(t,r))}function b(e,r){Jt(u),P(h),e?i(r):t(void 0)}if(c(r,h._closedPromise,function(t){!1===s?v(function(){return Vt(e,t)},!0,t):m(!0,t)}),c(e,u._closedPromise,function(t){!1===l?v(function(){return g(r,t)},!0,t):m(!0,t)}),p(r,h._closedPromise,function(){!1===n?v(function(){return Zt(u)}):m()}),!0===Qt(e)||"closed"===e._state){var y=new TypeError("the destination writable stream closed before all data could be piped to it");!1===l?v(function(){return g(r,y)},!0,y):m(!0,y)}o().catch(function(t){d=Promise.resolve(),Bt(t)})})}},{key:"tee",value:function t(){if(!1===a(this))throw lt("tee");var e=l(this,!1);return It(e)}},{key:"locked",get:function t(){if(!1===a(this))throw lt("locked");return c(this)}}]),t}();t.exports={ReadableStream:$t,IsReadableStreamDisturbed:s,ReadableStreamDefaultControllerClose:I,ReadableStreamDefaultControllerEnqueue:j,ReadableStreamDefaultControllerError:M,ReadableStreamDefaultControllerGetDesiredSize:N};var te=function(){function t(e){if(i(this,t),!1===a(e))throw new TypeError("ReadableStreamDefaultReader can only be constructed with a ReadableStream instance");if(!0===c(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");T(this,e),this._readRequests=[]}return xt(t,[{key:"cancel",value:function t(e){return!1===A(this)?Promise.reject(ut("cancel")):void 0===this._ownerReadableStream?Promise.reject(ht("cancel")):k(this,e)}},{key:"read",value:function t(){return!1===A(this)?Promise.reject(ut("read")):void 0===this._ownerReadableStream?Promise.reject(ht("read from")):O(this)}},{key:"releaseLock",value:function t(){if(!1===A(this))throw ut("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");P(this)}}},{key:"closed",get:function t(){return!1===A(this)?Promise.reject(ut("closed")):this._closedPromise}}]),t}(),ee=function(){function t(e){if(i(this,t),!a(e))throw new TypeError("ReadableStreamBYOBReader can only be constructed with a ReadableStream instance given a byte source");if(!1===B(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");if(c(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");T(this,e),this._readIntoRequests=[]}return xt(t,[{key:"cancel",value:function t(e){return C(this)?void 0===this._ownerReadableStream?Promise.reject(ht("cancel")):k(this,e):Promise.reject(bt("cancel"))}},{key:"read",value:function t(e){return C(this)?void 0===this._ownerReadableStream?Promise.reject(ht("read from")):ArrayBuffer.isView(e)?0===e.byteLength?Promise.reject(new TypeError("view must have non-zero byteLength")):E(this,e):Promise.reject(new TypeError("view must be an array buffer view")):Promise.reject(bt("read"))}},{key:"releaseLock",value:function t(){if(!C(this))throw bt("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readIntoRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");P(this)}}},{key:"closed",get:function t(){return C(this)?this._closedPromise:Promise.reject(bt("closed"))}}]),t}(),re=function(){function t(e,r,n,o){if(i(this,t),!1===a(e))throw new TypeError("ReadableStreamDefaultController can only be constructed with a ReadableStream instance");if(void 0!==e._readableStreamController)throw new TypeError("ReadableStreamDefaultController instances can only be created by the ReadableStream constructor");this._controlledReadableStream=e,this._underlyingSource=r,this._queue=void 0,this._queueTotalSize=void 0,qt(this),this._started=!1,this._closeRequested=!1,this._pullAgain=!1,this._pulling=!1;var s=Rt(n,o);this._strategySize=s.size,this._strategyHWM=s.highWaterMark;var c=this,l=Pt(r,"start",[this]);Promise.resolve(l).then(function(){c._started=!0,Nt(!1===c._pulling),Nt(!1===c._pullAgain),L(c)},function(t){F(c,t)}).catch(Bt)}return xt(t,[{key:"close",value:function t(){if(!1===R(this))throw yt("close");if(!0===this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");var e=this._controlledReadableStream._state;if("readable"!==e)throw new TypeError("The stream (in "+e+" state) is not in the readable state and cannot be closed");I(this)}},{key:"enqueue",value:function t(e){if(!1===R(this))throw yt("enqueue");if(!0===this._closeRequested)throw new TypeError("stream is closed or draining");var r=this._controlledReadableStream._state;if("readable"!==r)throw new TypeError("The stream (in "+r+" state) is not in the readable state and cannot be enqueued to");return j(this,e)}},{key:"error",value:function t(e){if(!1===R(this))throw yt("error");var r=this._controlledReadableStream;if("readable"!==r._state)throw new TypeError("The stream is "+r._state+" and so cannot be errored");M(this,e)}},{key:"__cancelSteps",value:function t(e){return qt(this),Et(this._underlyingSource,"cancel",[e])}},{key:"__pullSteps",value:function t(){var e=this._controlledReadableStream;if(this._queue.length>0){var r=zt(this);return!0===this._closeRequested&&0===this._queue.length?v(e):L(this),Promise.resolve(Tt(r,!1))}var i=p(e);return L(this),i}},{key:"desiredSize",get:function t(){if(!1===R(this))throw yt("desiredSize");return N(this)}}]),t}(),ie=function(){function t(e,r){i(this,t),this._associatedReadableByteStreamController=e,this._view=r}return xt(t,[{key:"respond",value:function t(e){if(!1===U(this))throw _t("respond");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");st(this._associatedReadableByteStreamController,e)}},{key:"respondWithNewView",value:function t(e){if(!1===U(this))throw _t("respond");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");ct(this._associatedReadableByteStreamController,e)}},{key:"view",get:function t(){return this._view}}]),t}(),ne=function(){function t(e,r,n){if(i(this,t),!1===a(e))throw new TypeError("ReadableByteStreamController can only be constructed with a ReadableStream instance given a byte source");if(void 0!==e._readableStreamController)throw new TypeError("ReadableByteStreamController instances can only be created by the ReadableStream constructor given a byte source");this._controlledReadableStream=e,this._underlyingByteSource=r,this._pullAgain=!1,this._pulling=!1,W(this),this._queue=this._queueTotalSize=void 0,qt(this),this._closeRequested=!1,this._started=!1,this._strategyHWM=Lt(n);var o=r.autoAllocateChunkSize;if(void 0!==o&&(!1===Number.isInteger(o)||o<=0))throw new RangeError("autoAllocateChunkSize must be a positive integer");this._autoAllocateChunkSize=o,this._pendingPullIntos=[];var s=this,c=Pt(r,"start",[this]);Promise.resolve(c).then(function(){s._started=!0,Nt(!1===s._pulling),Nt(!1===s._pullAgain),z(s)},function(t){"readable"===e._state&&ot(s,t)}).catch(Bt)}return xt(t,[{key:"close",value:function t(){if(!1===B(this))throw wt("close");if(!0===this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");var e=this._controlledReadableStream._state;if("readable"!==e)throw new TypeError("The stream (in "+e+" state) is not in the readable state and cannot be closed");it(this)}},{key:"enqueue",value:function t(e){if(!1===B(this))throw wt("enqueue");if(!0===this._closeRequested)throw new TypeError("stream is closed or draining");var r=this._controlledReadableStream._state;if("readable"!==r)throw new TypeError("The stream (in "+r+" state) is not in the readable state and cannot be enqueued to");if(!ArrayBuffer.isView(e))throw new TypeError("You can only enqueue array buffer views when using a ReadableByteStreamController");nt(this,e)}},{key:"error",value:function t(e){if(!1===B(this))throw wt("error");var r=this._controlledReadableStream;if("readable"!==r._state)throw new TypeError("The stream is "+r._state+" and so cannot be errored");ot(this,e)}},{key:"__cancelSteps",value:function t(e){if(this._pendingPullIntos.length>0){this._pendingPullIntos[0].bytesFilled=0}return qt(this),Et(this._underlyingByteSource,"cancel",[e])}},{key:"__pullSteps",value:function t(){var e=this._controlledReadableStream;if(Nt(!0===x(e)),this._queueTotalSize>0){Nt(0===w(e));var r=this._queue.shift();this._queueTotalSize-=r.byteLength,V(this);var i=void 0;try{i=new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}catch(t){return Promise.reject(t)}return Promise.resolve(Tt(i,!1))}var n=this._autoAllocateChunkSize;if(void 0!==n){var o=void 0;try{o=new ArrayBuffer(n)}catch(t){return Promise.reject(t)}var a={buffer:o,byteOffset:0,byteLength:n,bytesFilled:0,elementSize:1,ctor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(a)}var s=p(e);return z(this),s}},{key:"byobRequest",get:function t(){if(!1===B(this))throw wt("byobRequest");if(void 0===this._byobRequest&&this._pendingPullIntos.length>0){var e=this._pendingPullIntos[0],r=new Uint8Array(e.buffer,e.byteOffset+e.bytesFilled,e.byteLength-e.bytesFilled);this._byobRequest=new ie(this,r)}return this._byobRequest}},{key:"desiredSize",get:function t(){if(!1===B(this))throw wt("desiredSize");return at(this)}}]),t}()},function(t,e,r){var i=r(6),n=r(4),o=r(2);e.TransformStream=i.TransformStream,e.ReadableStream=n.ReadableStream,e.IsReadableStreamDisturbed=n.IsReadableStreamDisturbed,e.ReadableStreamDefaultControllerClose=n.ReadableStreamDefaultControllerClose,e.ReadableStreamDefaultControllerEnqueue=n.ReadableStreamDefaultControllerEnqueue,e.ReadableStreamDefaultControllerError=n.ReadableStreamDefaultControllerError,e.ReadableStreamDefaultControllerGetDesiredSize=n.ReadableStreamDefaultControllerGetDesiredSize,e.AcquireWritableStreamDefaultWriter=o.AcquireWritableStreamDefaultWriter,e.IsWritableStream=o.IsWritableStream,e.IsWritableStreamLocked=o.IsWritableStreamLocked,e.WritableStream=o.WritableStream,e.WritableStreamAbort=o.WritableStreamAbort,e.WritableStreamDefaultControllerError=o.WritableStreamDefaultControllerError,e.WritableStreamDefaultWriterCloseWithErrorPropagation=o.WritableStreamDefaultWriterCloseWithErrorPropagation,e.WritableStreamDefaultWriterRelease=o.WritableStreamDefaultWriterRelease,e.WritableStreamDefaultWriterWrite=o.WritableStreamDefaultWriterWrite},function(t,e,r){function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t){if(!0===t._errored)throw new TypeError("TransformStream is already errored");if(!0===t._readableClosed)throw new TypeError("Readable side is already closed");s(t)}function o(t,e){if(!0===t._errored)throw new TypeError("TransformStream is already errored");if(!0===t._readableClosed)throw new TypeError("Readable side is already closed");var r=t._readableController;try{E(r,e)}catch(e){throw t._readableClosed=!0,c(t,e),t._storedError}!0==R(r)<=0&&!1===t._backpressure&&u(t,!0)}function a(t,e){if(!0===t._errored)throw new TypeError("TransformStream is already errored");l(t,e)}function s(t){_(!1===t._errored),_(!1===t._readableClosed);try{P(t._readableController)}catch(t){_(!1)}t._readableClosed=!0}function c(t,e){!1===t._errored&&l(t,e)}function l(t,e){_(!1===t._errored),t._errored=!0,t._storedError=e,!1===t._writableDone&&I(t._writableController,e),!1===t._readableClosed&&O(t._readableController,e)}function h(t){return _(void 0!==t._backpressureChangePromise,"_backpressureChangePromise should have been initialized"),!1===t._backpressure?Promise.resolve():(_(!0===t._backpressure,"_backpressure should have been initialized"),t._backpressureChangePromise)}function u(t,e){_(t._backpressure!==e,"TransformStreamSetBackpressure() should be called only when backpressure is changed"),void 0!==t._backpressureChangePromise&&t._backpressureChangePromise_resolve(e),t._backpressureChangePromise=new Promise(function(e){t._backpressureChangePromise_resolve=e}),t._backpressureChangePromise.then(function(t){_(t!==e,"_backpressureChangePromise should be fulfilled only when backpressure is changed")}),t._backpressure=e}function f(t,e){return o(e._controlledTransformStream,t),Promise.resolve()}function d(t,e){_(!1===t._errored),_(!1===t._transforming),_(!1===t._backpressure),t._transforming=!0;var r=t._transformer,i=t._transformStreamController;return x(r,"transform",[e,i],f,[e,i]).then(function(){return t._transforming=!1,h(t)},function(e){return c(t,e),Promise.reject(e)})}function p(t){return!!A(t)&&!!Object.prototype.hasOwnProperty.call(t,"_controlledTransformStream")}function g(t){return!!A(t)&&!!Object.prototype.hasOwnProperty.call(t,"_transformStreamController")}function v(t){return new TypeError("TransformStreamDefaultController.prototype."+t+" can only be used on a TransformStreamDefaultController")}function m(t){return new TypeError("TransformStream.prototype."+t+" can only be used on a TransformStream")}var b=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),y=r(1),_=y.assert,w=r(0),S=w.InvokeOrNoop,x=w.PromiseInvokeOrPerformFallback,C=w.PromiseInvokeOrNoop,A=w.typeIsObject,T=r(4),k=T.ReadableStream,P=T.ReadableStreamDefaultControllerClose,E=T.ReadableStreamDefaultControllerEnqueue,O=T.ReadableStreamDefaultControllerError,R=T.ReadableStreamDefaultControllerGetDesiredSize,L=r(2),D=L.WritableStream,I=L.WritableStreamDefaultControllerError,j=function(){function t(e,r){i(this,t),this._transformStream=e,this._startPromise=r}return b(t,[{key:"start",value:function t(e){var r=this._transformStream;return r._writableController=e,this._startPromise.then(function(){return h(r)})}},{key:"write",value:function t(e){return d(this._transformStream,e)}},{key:"abort",value:function t(){var e=this._transformStream;e._writableDone=!0,l(e,new TypeError("Writable side aborted"))}},{key:"close",value:function t(){var e=this._transformStream;return _(!1===e._transforming),e._writableDone=!0,C(e._transformer,"flush",[e._transformStreamController]).then(function(){return!0===e._errored?Promise.reject(e._storedError):(!1===e._readableClosed&&s(e),Promise.resolve())}).catch(function(t){return c(e,t),Promise.reject(e._storedError)})}}]),t}(),M=function(){function t(e,r){i(this,t),this._transformStream=e,this._startPromise=r}return b(t,[{key:"start",value:function t(e){var r=this._transformStream;return r._readableController=e,this._startPromise.then(function(){return _(void 0!==r._backpressureChangePromise,"_backpressureChangePromise should have been initialized"),!0===r._backpressure?Promise.resolve():(_(!1===r._backpressure,"_backpressure should have been initialized"),r._backpressureChangePromise)})}},{key:"pull",value:function t(){var e=this._transformStream;return _(!0===e._backpressure,"pull() should be never called while _backpressure is false"),_(void 0!==e._backpressureChangePromise,"_backpressureChangePromise should have been initialized"),u(e,!1),e._backpressureChangePromise}},{key:"cancel",value:function t(){var e=this._transformStream;e._readableClosed=!0,l(e,new TypeError("Readable side canceled"))}}]),t}(),F=function(){function t(e){if(i(this,t),!1===g(e))throw new TypeError("TransformStreamDefaultController can only be constructed with a TransformStream instance");if(void 0!==e._transformStreamController)throw new TypeError("TransformStreamDefaultController instances can only be created by the TransformStream constructor");this._controlledTransformStream=e}return b(t,[{key:"enqueue",value:function t(e){if(!1===p(this))throw v("enqueue");o(this._controlledTransformStream,e)}},{key:"close",value:function t(){if(!1===p(this))throw v("close");n(this._controlledTransformStream)}},{key:"error",value:function t(e){if(!1===p(this))throw v("error");a(this._controlledTransformStream,e)}},{key:"desiredSize",get:function t(){if(!1===p(this))throw v("desiredSize");var e=this._controlledTransformStream,r=e._readableController;return R(r)}}]),t}(),N=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};i(this,t),this._transformer=e;var r=e.readableStrategy,n=e.writableStrategy;this._transforming=!1,this._errored=!1,this._storedError=void 0,this._writableController=void 0,this._readableController=void 0,this._transformStreamController=void 0,this._writableDone=!1,this._readableClosed=!1,this._backpressure=void 0,this._backpressureChangePromise=void 0,this._backpressureChangePromise_resolve=void 0,this._transformStreamController=new F(this);var o=void 0,a=new Promise(function(t){o=t}),s=new M(this,a);this._readable=new k(s,r);var c=new j(this,a);this._writable=new D(c,n),_(void 0!==this._writableController),_(void 0!==this._readableController),u(this,R(this._readableController)<=0);var l=this,h=S(e,"start",[l._transformStreamController]);o(h),a.catch(function(t){!1===l._errored&&(l._errored=!0,l._storedError=t)})}return b(t,[{key:"readable",get:function t(){if(!1===g(this))throw m("readable");return this._readable}},{key:"writable",get:function t(){if(!1===g(this))throw m("writable");return this._writable}}]),t}();t.exports={TransformStream:N}},function(t,e,r){t.exports=r(5)}]))},function(t,e,r){"use strict";function i(t){t.mozCurrentTransform||(t._originalSave=t.save,t._originalRestore=t.restore,t._originalRotate=t.rotate,t._originalScale=t.scale,t._originalTranslate=t.translate,t._originalTransform=t.transform,t._originalSetTransform=t.setTransform,t._transformMatrix=t._transformMatrix||[1,0,0,1,0,0],t._transformStack=[],Object.defineProperty(t,"mozCurrentTransform",{get:function t(){return this._transformMatrix}}),Object.defineProperty(t,"mozCurrentTransformInverse",{get:function t(){var e=this._transformMatrix,r=e[0],i=e[1],n=e[2],o=e[3],a=e[4],s=e[5],c=r*o-i*n,l=i*n-r*o;return[o/c,i/l,n/l,r/c,(o*a-n*s)/l,(i*a-r*s)/c]}}),t.save=function t(){var e=this._transformMatrix;this._transformStack.push(e),this._transformMatrix=e.slice(0,6),this._originalSave()},t.restore=function t(){var e=this._transformStack.pop();e&&(this._transformMatrix=e,this._originalRestore())},t.translate=function t(e,r){var i=this._transformMatrix;i[4]=i[0]*e+i[2]*r+i[4],i[5]=i[1]*e+i[3]*r+i[5],this._originalTranslate(e,r)},t.scale=function t(e,r){var i=this._transformMatrix;i[0]=i[0]*e,i[1]=i[1]*e,i[2]=i[2]*r,i[3]=i[3]*r,this._originalScale(e,r)},t.transform=function e(r,i,n,o,a,s){var c=this._transformMatrix;this._transformMatrix=[c[0]*r+c[2]*i,c[1]*r+c[3]*i,c[0]*n+c[2]*o,c[1]*n+c[3]*o,c[0]*a+c[2]*s+c[4],c[1]*a+c[3]*s+c[5]],t._originalTransform(r,i,n,o,a,s)},t.setTransform=function e(r,i,n,o,a,s){this._transformMatrix=[r,i,n,o,a,s],t._originalSetTransform(r,i,n,o,a,s)},t.rotate=function t(e){var r=Math.cos(e),i=Math.sin(e),n=this._transformMatrix;this._transformMatrix=[n[0]*r+n[2]*i,n[1]*r+n[3]*i,n[0]*-i+n[2]*r,n[1]*-i+n[3]*r,n[4],n[5]],this._originalRotate(e)})}function n(t){var e=1e3,r=t.width,i=t.height,n,o,a,s=r+1,c=new Uint8Array(s*(i+1)),l=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),h=r+7&-8,u=t.data,f=new Uint8Array(h*i),d=0,p;for(n=0,p=u.length;n<p;n++)for(var g=128,v=u[n];g>0;)f[d++]=v&g?0:255,g>>=1;var m=0;for(d=0,0!==f[d]&&(c[0]=1,++m),o=1;o<r;o++)f[d]!==f[d+1]&&(c[o]=f[d]?2:1,++m),d++;for(0!==f[d]&&(c[o]=2,++m),n=1;n<i;n++){d=n*h,a=n*s,f[d-h]!==f[d]&&(c[a]=f[d]?1:8,++m);var b=(f[d]?4:0)+(f[d-h]?8:0);for(o=1;o<r;o++)b=(b>>2)+(f[d+1]?4:0)+(f[d-h+1]?8:0),l[b]&&(c[a+o]=l[b],++m),d++;if(f[d-h]!==f[d]&&(c[a+o]=f[d]?2:4,++m),m>1e3)return null}for(d=h*(i-1),a=n*s,0!==f[d]&&(c[a]=8,++m),o=1;o<r;o++)f[d]!==f[d+1]&&(c[a+o]=f[d]?4:8,++m),d++;if(0!==f[d]&&(c[a+o]=4,++m),m>1e3)return null;var y=new Int32Array([0,s,-1,0,-s,0,0,0,1]),_=[];for(n=0;m&&n<=i;n++){for(var w=n*s,S=w+r;w<S&&!c[w];)w++;if(w!==S){var x=[w%s,n],C=c[w],A=w,T;do{var k=y[C];do{w+=k}while(!c[w]);T=c[w],5!==T&&10!==T?(C=T,c[w]=0):(C=T&51*C>>4,c[w]&=C>>2|C<<2),x.push(w%s),x.push(w/s|0),--m}while(A!==w);_.push(x),--n}}return function t(e){e.save(),e.scale(1/r,-1/i),e.translate(0,-i),e.beginPath();for(var n=0,o=_.length;n<o;n++){var a=_[n];e.moveTo(a[0],a[1]);for(var s=2,c=a.length;s<c;s+=2)e.lineTo(a[s],a[s+1])}e.fill(),e.beginPath(),e.restore()}}Object.defineProperty(e,"__esModule",{value:!0}),e.CanvasGraphics=void 0;var o=r(0),a=r(12),s=r(7),c=16,l=100,h=4096,u=.65,f=!0,d=1e3,p=16,g={get value(){return(0,o.shadow)(g,"value",(0,o.isLittleEndian)())}},v=function t(){function e(t){this.canvasFactory=t,this.cache=Object.create(null)}return e.prototype={getCanvas:function t(e,r,n,o){var a;return void 0!==this.cache[e]?(a=this.cache[e],this.canvasFactory.reset(a,r,n),a.context.setTransform(1,0,0,1,0,0)):(a=this.canvasFactory.create(r,n),this.cache[e]=a),o&&i(a.context),a},clear:function t(){for(var e in this.cache){var r=this.cache[e];this.canvasFactory.destroy(r),delete this.cache[e]}}},e}(),m=function t(){function e(){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=o.IDENTITY_MATRIX,this.textMatrixScale=1,this.fontMatrix=o.FONT_IDENTITY_MATRIX,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=o.TextRenderingMode.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.resumeSMaskCtx=null}return e.prototype={clone:function t(){return Object.create(this)},setCurrentPoint:function t(e,r){this.x=e,this.y=r}},e}(),b=function t(){function e(t,e,r,n,o){this.ctx=t,this.current=new m,this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=e,this.objs=r,this.canvasFactory=n,this.imageLayer=o,this.groupStack=[],this.processingType3=null,this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.smaskCounter=0,this.tempSMask=null,this.cachedCanvases=new v(this.canvasFactory),t&&i(t),this.cachedGetSinglePixelWidth=null}function r(t,e){if("undefined"!=typeof ImageData&&e instanceof ImageData)return void t.putImageData(e,0,0);var r=e.height,i=e.width,n=r%p,a=(r-n)/p,s=0===n?a:a+1,c=t.createImageData(i,p),l=0,h,u=e.data,f=c.data,d,v,m,b;if(e.kind===o.ImageKind.GRAYSCALE_1BPP){var y=u.byteLength,_=new Uint32Array(f.buffer,0,f.byteLength>>2),w=_.length,S=i+7>>3,x=4294967295,C=g.value?4278190080:255;for(d=0;d<s;d++){for(m=d<a?p:n,h=0,v=0;v<m;v++){for(var A=y-l,T=0,k=A>S?i:8*A-7,P=-8&k,E=0,O=0;T<P;T+=8)O=u[l++],_[h++]=128&O?x:C,_[h++]=64&O?x:C,_[h++]=32&O?x:C,_[h++]=16&O?x:C,_[h++]=8&O?x:C,_[h++]=4&O?x:C,_[h++]=2&O?x:C,_[h++]=1&O?x:C;for(;T<k;T++)0===E&&(O=u[l++],E=128),_[h++]=O&E?x:C,E>>=1}for(;h<w;)_[h++]=0;t.putImageData(c,0,d*p)}}else if(e.kind===o.ImageKind.RGBA_32BPP){for(v=0,b=i*p*4,d=0;d<a;d++)f.set(u.subarray(l,l+b)),l+=b,t.putImageData(c,0,v),v+=p;d<s&&(b=i*n*4,f.set(u.subarray(l,l+b)),t.putImageData(c,0,v))}else{if(e.kind!==o.ImageKind.RGB_24BPP)throw new Error("bad image kind: "+e.kind);for(m=p,b=i*m,d=0;d<s;d++){for(d>=a&&(m=n,b=i*m),h=0,v=b;v--;)f[h++]=u[l++],f[h++]=u[l++],f[h++]=u[l++],f[h++]=255;t.putImageData(c,0,d*p)}}}function c(t,e){for(var r=e.height,i=e.width,n=r%p,o=(r-n)/p,a=0===n?o:o+1,s=t.createImageData(i,p),c=0,l=e.data,h=s.data,u=0;u<a;u++){for(var f=u<o?p:n,d=3,g=0;g<f;g++)for(var v=0,m=0;m<i;m++){if(!v){var b=l[c++];v=128}h[d]=b&v?0:255,d+=4,v>>=1}t.putImageData(s,0,u*p)}}function l(t,e){for(var r=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font"],i=0,n=r.length;i<n;i++){var o=r[i];void 0!==t[o]&&(e[o]=t[o])}void 0!==t.setLineDash&&(e.setLineDash(t.getLineDash()),e.lineDashOffset=t.lineDashOffset)}function h(t){t.strokeStyle="#000000",t.fillStyle="#000000",t.fillRule="nonzero",t.globalAlpha=1,t.lineWidth=1,t.lineCap="butt",t.lineJoin="miter",t.miterLimit=10,t.globalCompositeOperation="source-over",t.font="10px sans-serif",void 0!==t.setLineDash&&(t.setLineDash([]),t.lineDashOffset=0)}function u(t,e,r,i){for(var n=t.length,o=3;o<n;o+=4){var a=t[o];if(0===a)t[o-3]=e,t[o-2]=r,t[o-1]=i;else if(a<255){var s=255-a;t[o-3]=t[o-3]*a+e*s>>8,t[o-2]=t[o-2]*a+r*s>>8,t[o-1]=t[o-1]*a+i*s>>8}}}function f(t,e,r){for(var i=t.length,n=1/255,o=3;o<i;o+=4){var a=r?r[t[o]]:t[o];e[o]=e[o]*a*(1/255)|0}}function d(t,e,r){for(var i=t.length,n=3;n<i;n+=4){var o=77*t[n-3]+152*t[n-2]+28*t[n-1];e[n]=r?e[n]*r[o>>8]>>8:e[n]*o>>16}}function b(t,e,r,i,n,o,a){var s=!!o,c=s?o[0]:0,l=s?o[1]:0,h=s?o[2]:0,p;p="Luminosity"===n?d:f;for(var g=1048576,v=Math.min(i,Math.ceil(1048576/r)),m=0;m<i;m+=v){var b=Math.min(v,i-m),y=t.getImageData(0,m,r,b),_=e.getImageData(0,m,r,b);s&&u(y.data,c,l,h),p(y.data,_.data,a),t.putImageData(_,0,m)}}function y(t,e,r){var i=e.canvas,n=e.context;t.setTransform(e.scaleX,0,0,e.scaleY,e.offsetX,e.offsetY);var o=e.backdrop||null;if(!e.transferMap&&s.WebGLUtils.isEnabled){var a=s.WebGLUtils.composeSMask(r.canvas,i,{subtype:e.subtype,backdrop:o});return t.setTransform(1,0,0,1,0,0),void t.drawImage(a,e.offsetX,e.offsetY)}b(n,r,i.width,i.height,e.subtype,o,e.transferMap),t.drawImage(i,0,0)}var _=15,w=10,S=["butt","round","square"],x=["miter","round","bevel"],C={},A={};e.prototype={beginDrawing:function t(e){var r=e.transform,i=e.viewport,n=e.transparency,o=e.background,a=void 0===o?null:o,s=this.ctx.canvas.width,c=this.ctx.canvas.height;if(this.ctx.save(),this.ctx.fillStyle=a||"rgb(255, 255, 255)",this.ctx.fillRect(0,0,s,c),this.ctx.restore(),n){var l=this.cachedCanvases.getCanvas("transparent",s,c,!0);this.compositeCtx=this.ctx,this.transparentCanvas=l.canvas,this.ctx=l.context,this.ctx.save(),this.ctx.transform.apply(this.ctx,this.compositeCtx.mozCurrentTransform)}this.ctx.save(),h(this.ctx),r&&this.ctx.transform.apply(this.ctx,r),this.ctx.transform.apply(this.ctx,i.transform),this.baseTransform=this.ctx.mozCurrentTransform.slice(),this.imageLayer&&this.imageLayer.beginLayout()},executeOperatorList:function t(e,r,i,n){var a=e.argsArray,s=e.fnArray,c=r||0,l=a.length;if(l===c)return c;for(var h=l-c>10&&"function"==typeof i,u=h?Date.now()+15:0,f=0,d=this.commonObjs,p=this.objs,g;;){if(void 0!==n&&c===n.nextBreakPoint)return n.breakIt(c,i),c;if((g=s[c])!==o.OPS.dependency)this[g].apply(this,a[c]);else for(var v=a[c],m=0,b=v.length;m<b;m++){var y=v[m],_="g"===y[0]&&"_"===y[1],w=_?d:p;if(!w.isResolved(y))return w.get(y,i),c}if(++c===l)return c;if(h&&++f>10){if(Date.now()>u)return i(),c;f=0}}},endDrawing:function t(){null!==this.current.activeSMask&&this.endSMaskGroup(),this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null),this.cachedCanvases.clear(),s.WebGLUtils.clear(),this.imageLayer&&this.imageLayer.endLayout()},setLineWidth:function t(e){this.current.lineWidth=e,this.ctx.lineWidth=e},setLineCap:function t(e){this.ctx.lineCap=S[e]},setLineJoin:function t(e){this.ctx.lineJoin=x[e]},setMiterLimit:function t(e){this.ctx.miterLimit=e},setDash:function t(e,r){var i=this.ctx;void 0!==i.setLineDash&&(i.setLineDash(e),i.lineDashOffset=r)},setRenderingIntent:function t(e){},setFlatness:function t(e){},setGState:function t(e){for(var r=0,i=e.length;r<i;r++){var n=e[r],o=n[0],a=n[1];switch(o){case"LW":this.setLineWidth(a);break;case"LC":this.setLineCap(a);break;case"LJ":this.setLineJoin(a);break;case"ML":this.setMiterLimit(a);break;case"D":this.setDash(a[0],a[1]);break;case"RI":this.setRenderingIntent(a);break;case"FL":this.setFlatness(a);break;case"Font":this.setFont(a[0],a[1]);break;case"CA":this.current.strokeAlpha=n[1];break;case"ca":this.current.fillAlpha=n[1],this.ctx.globalAlpha=n[1];break;case"BM":this.ctx.globalCompositeOperation=a;break;case"SMask":this.current.activeSMask&&(this.stateStack.length>0&&this.stateStack[this.stateStack.length-1].activeSMask===this.current.activeSMask?this.suspendSMaskGroup():this.endSMaskGroup()),this.current.activeSMask=a?this.tempSMask:null,this.current.activeSMask&&this.beginSMaskGroup(),this.tempSMask=null}}},beginSMaskGroup:function t(){var e=this.current.activeSMask,r=e.canvas.width,i=e.canvas.height,n="smaskGroupAt"+this.groupLevel,o=this.cachedCanvases.getCanvas(n,r,i,!0),a=this.ctx,s=a.mozCurrentTransform;this.ctx.save();var c=o.context;c.scale(1/e.scaleX,1/e.scaleY),c.translate(-e.offsetX,-e.offsetY),c.transform.apply(c,s),e.startTransformInverse=c.mozCurrentTransformInverse,l(a,c),this.ctx=c,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(a),this.groupLevel++},suspendSMaskGroup:function t(){var e=this.ctx;this.groupLevel--,this.ctx=this.groupStack.pop(),y(this.ctx,this.current.activeSMask,e),this.ctx.restore(),this.ctx.save(),l(e,this.ctx),this.current.resumeSMaskCtx=e;var r=o.Util.transform(this.current.activeSMask.startTransformInverse,e.mozCurrentTransform);this.ctx.transform.apply(this.ctx,r),e.save(),e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,e.canvas.width,e.canvas.height),e.restore()},resumeSMaskGroup:function t(){var e=this.current.resumeSMaskCtx,r=this.ctx;this.ctx=e,this.groupStack.push(r),this.groupLevel++},endSMaskGroup:function t(){var e=this.ctx;this.groupLevel--,this.ctx=this.groupStack.pop(),y(this.ctx,this.current.activeSMask,e),this.ctx.restore(),l(e,this.ctx);var r=o.Util.transform(this.current.activeSMask.startTransformInverse,e.mozCurrentTransform);this.ctx.transform.apply(this.ctx,r)},save:function t(){this.ctx.save();var e=this.current;this.stateStack.push(e),this.current=e.clone(),this.current.resumeSMaskCtx=null},restore:function t(){this.current.resumeSMaskCtx&&this.resumeSMaskGroup(),null===this.current.activeSMask||0!==this.stateStack.length&&this.stateStack[this.stateStack.length-1].activeSMask===this.current.activeSMask||this.endSMaskGroup(),0!==this.stateStack.length&&(this.current=this.stateStack.pop(),this.ctx.restore(),this.pendingClip=null,this.cachedGetSinglePixelWidth=null)},transform:function t(e,r,i,n,o,a){this.ctx.transform(e,r,i,n,o,a),this.cachedGetSinglePixelWidth=null},constructPath:function t(e,r){for(var i=this.ctx,n=this.current,a=n.x,s=n.y,c=0,l=0,h=e.length;c<h;c++)switch(0|e[c]){case o.OPS.rectangle:a=r[l++],s=r[l++];var u=r[l++],f=r[l++];0===u&&(u=this.getSinglePixelWidth()),0===f&&(f=this.getSinglePixelWidth());var d=a+u,p=s+f;this.ctx.moveTo(a,s),this.ctx.lineTo(d,s),this.ctx.lineTo(d,p),this.ctx.lineTo(a,p),this.ctx.lineTo(a,s),this.ctx.closePath();break;case o.OPS.moveTo:a=r[l++],s=r[l++],i.moveTo(a,s);break;case o.OPS.lineTo:a=r[l++],s=r[l++],i.lineTo(a,s);break;case o.OPS.curveTo:a=r[l+4],s=r[l+5],i.bezierCurveTo(r[l],r[l+1],r[l+2],r[l+3],a,s),l+=6;break;case o.OPS.curveTo2:i.bezierCurveTo(a,s,r[l],r[l+1],r[l+2],r[l+3]),a=r[l+2],s=r[l+3],l+=4;break;case o.OPS.curveTo3:a=r[l+2],s=r[l+3],i.bezierCurveTo(r[l],r[l+1],a,s,a,s),l+=4;break;case o.OPS.closePath:i.closePath()}n.setCurrentPoint(a,s)},closePath:function t(){this.ctx.closePath()},stroke:function t(e){e=void 0===e||e;var r=this.ctx,i=this.current.strokeColor;r.lineWidth=Math.max(.65*this.getSinglePixelWidth(),this.current.lineWidth),r.globalAlpha=this.current.strokeAlpha,i&&i.hasOwnProperty("type")&&"Pattern"===i.type?(r.save(),r.strokeStyle=i.getPattern(r,this),r.stroke(),r.restore()):r.stroke(),e&&this.consumePath(),r.globalAlpha=this.current.fillAlpha},closeStroke:function t(){this.closePath(),this.stroke()},fill:function t(e){e=void 0===e||e;var r=this.ctx,i=this.current.fillColor,n=this.current.patternFill,o=!1;n&&(r.save(),this.baseTransform&&r.setTransform.apply(r,this.baseTransform),r.fillStyle=i.getPattern(r,this),o=!0),this.pendingEOFill?(r.fill("evenodd"),this.pendingEOFill=!1):r.fill(),o&&r.restore(),e&&this.consumePath()},eoFill:function t(){this.pendingEOFill=!0,this.fill()},fillStroke:function t(){this.fill(!1),this.stroke(!1),this.consumePath()},eoFillStroke:function t(){this.pendingEOFill=!0,this.fillStroke()},closeFillStroke:function t(){this.closePath(),this.fillStroke()},closeEOFillStroke:function t(){this.pendingEOFill=!0,this.closePath(),this.fillStroke()},endPath:function t(){this.consumePath()},clip:function t(){this.pendingClip=C},eoClip:function t(){this.pendingClip=A},beginText:function t(){this.current.textMatrix=o.IDENTITY_MATRIX,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0},endText:function t(){var e=this.pendingTextPaths,r=this.ctx;if(void 0===e)return void r.beginPath();r.save(),r.beginPath();for(var i=0;i<e.length;i++){var n=e[i];r.setTransform.apply(r,n.transform),r.translate(n.x,n.y),n.addToPath(r,n.fontSize)}r.restore(),r.clip(),r.beginPath(),delete this.pendingTextPaths},setCharSpacing:function t(e){this.current.charSpacing=e},setWordSpacing:function t(e){this.current.wordSpacing=e},setHScale:function t(e){this.current.textHScale=e/100},setLeading:function t(e){this.current.leading=-e},setFont:function t(e,r){var i=this.commonObjs.get(e),n=this.current;if(!i)throw new Error("Can't find font for "+e);if(n.fontMatrix=i.fontMatrix?i.fontMatrix:o.FONT_IDENTITY_MATRIX,0!==n.fontMatrix[0]&&0!==n.fontMatrix[3]||(0,o.warn)("Invalid font matrix for font "+e),r<0?(r=-r,n.fontDirection=-1):n.fontDirection=1,this.current.font=i,this.current.fontSize=r,!i.isType3Font){var a=i.loadedName||"sans-serif",s=i.black?"900":i.bold?"bold":"normal",c=i.italic?"italic":"normal",l='"'+a+'", '+i.fallbackName,h=r<16?16:r>100?100:r;this.current.fontSizeScale=r/h;var u=c+" "+s+" "+h+"px "+l;this.ctx.font=u}},setTextRenderingMode:function t(e){this.current.textRenderingMode=e},setTextRise:function t(e){this.current.textRise=e},moveText:function t(e,r){this.current.x=this.current.lineX+=e,this.current.y=this.current.lineY+=r},setLeadingMoveText:function t(e,r){this.setLeading(-r),this.moveText(e,r)},setTextMatrix:function t(e,r,i,n,o,a){this.current.textMatrix=[e,r,i,n,o,a],this.current.textMatrixScale=Math.sqrt(e*e+r*r),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0},nextLine:function t(){this.moveText(0,this.current.leading)},paintChar:function t(e,r,i){var n=this.ctx,a=this.current,s=a.font,c=a.textRenderingMode,l=a.fontSize/a.fontSizeScale,h=c&o.TextRenderingMode.FILL_STROKE_MASK,u=!!(c&o.TextRenderingMode.ADD_TO_PATH_FLAG),f;if((s.disableFontFace||u)&&(f=s.getPathGenerator(this.commonObjs,e)),s.disableFontFace?(n.save(),n.translate(r,i),n.beginPath(),f(n,l),h!==o.TextRenderingMode.FILL&&h!==o.TextRenderingMode.FILL_STROKE||n.fill(),h!==o.TextRenderingMode.STROKE&&h!==o.TextRenderingMode.FILL_STROKE||n.stroke(),n.restore()):(h!==o.TextRenderingMode.FILL&&h!==o.TextRenderingMode.FILL_STROKE||n.fillText(e,r,i),h!==o.TextRenderingMode.STROKE&&h!==o.TextRenderingMode.FILL_STROKE||n.strokeText(e,r,i)),u){(this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:n.mozCurrentTransform,x:r,y:i,fontSize:l,addToPath:f})}},get isFontSubpixelAAEnabled(){var t=this.canvasFactory.create(10,10).context;t.scale(1.5,1),t.fillText("I",0,10);for(var e=t.getImageData(0,0,10,10).data,r=!1,i=3;i<e.length;i+=4)if(e[i]>0&&e[i]<255){r=!0;break}return(0,o.shadow)(this,"isFontSubpixelAAEnabled",r)},showText:function t(e){var r=this.current,i=r.font;if(i.isType3Font)return this.showType3Text(e);var n=r.fontSize;if(0!==n){var a=this.ctx,s=r.fontSizeScale,c=r.charSpacing,l=r.wordSpacing,h=r.fontDirection,u=r.textHScale*h,f=e.length,d=i.vertical,p=d?1:-1,g=i.defaultVMetrics,v=n*r.fontMatrix[0],m=r.textRenderingMode===o.TextRenderingMode.FILL&&!i.disableFontFace;a.save(),a.transform.apply(a,r.textMatrix),a.translate(r.x,r.y+r.textRise),r.patternFill&&(a.fillStyle=r.fillColor.getPattern(a,this)),h>0?a.scale(u,-1):a.scale(u,1);var b=r.lineWidth,y=r.textMatrixScale;if(0===y||0===b){var _=r.textRenderingMode&o.TextRenderingMode.FILL_STROKE_MASK;_!==o.TextRenderingMode.STROKE&&_!==o.TextRenderingMode.FILL_STROKE||(this.cachedGetSinglePixelWidth=null,b=.65*this.getSinglePixelWidth())}else b/=y;1!==s&&(a.scale(s,s),b/=s),a.lineWidth=b;var w=0,S;for(S=0;S<f;++S){var x=e[S];if((0,o.isNum)(x))w+=p*x*n/1e3;else{var C=!1,A=(x.isSpace?l:0)+c,T=x.fontChar,k=x.accent,P,E,O,R,L=x.width;if(d){var D,I,j;D=x.vmetric||g,I=x.vmetric?D[1]:.5*L,I=-I*v,j=D[2]*v,L=D?-D[0]:L,P=I/s,E=(w+j)/s}else P=w/s,E=0;if(i.remeasure&&L>0){var M=1e3*a.measureText(T).width/n*s;if(L<M&&this.isFontSubpixelAAEnabled){var F=L/M;C=!0,a.save(),a.scale(F,1),P/=F}else L!==M&&(P+=(L-M)/2e3*n/s)}(x.isInFont||i.missingFile)&&(m&&!k?a.fillText(T,P,E):(this.paintChar(T,P,E),k&&(O=P+k.offset.x/s,R=E-k.offset.y/s,this.paintChar(k.fontChar,O,R))));w+=L*v+A*h,C&&a.restore()}}d?r.y-=w*u:r.x+=w*u,a.restore()}},showType3Text:function t(e){var r=this.ctx,i=this.current,n=i.font,a=i.fontSize,s=i.fontDirection,c=n.vertical?1:-1,l=i.charSpacing,h=i.wordSpacing,u=i.textHScale*s,f=i.fontMatrix||o.FONT_IDENTITY_MATRIX,d=e.length,p=i.textRenderingMode===o.TextRenderingMode.INVISIBLE,g,v,m,b;if(!p&&0!==a){for(this.cachedGetSinglePixelWidth=null,r.save(),r.transform.apply(r,i.textMatrix),r.translate(i.x,i.y),r.scale(u,s),g=0;g<d;++g)if(v=e[g],(0,o.isNum)(v))b=c*v*a/1e3,this.ctx.translate(b,0),i.x+=b*u;else{var y=(v.isSpace?h:0)+l,_=n.charProcOperatorList[v.operatorListId];if(_){this.processingType3=v,this.save(),r.scale(a,a),r.transform.apply(r,f),this.executeOperatorList(_),this.restore();var w=o.Util.applyTransform([v.width,0],f);m=w[0]*a+y,r.translate(m,0),i.x+=m*u}else(0,o.warn)('Type3 character "'+v.operatorListId+'" is not available.')}r.restore(),this.processingType3=null}},setCharWidth:function t(e,r){},setCharWidthAndBounds:function t(e,r,i,n,o,a){this.ctx.rect(i,n,o-i,a-n),this.clip(),this.endPath()},getColorN_Pattern:function t(r){var i=this,n;if("TilingPattern"===r[0]){var o=r[1],s=this.baseTransform||this.ctx.mozCurrentTransform.slice(),c={createCanvasGraphics:function t(r){return new e(r,i.commonObjs,i.objs,i.canvasFactory)}};n=new a.TilingPattern(r,o,this.ctx,c,s)}else n=(0,a.getShadingPatternFromIR)(r);return n},setStrokeColorN:function t(){this.current.strokeColor=this.getColorN_Pattern(arguments)},setFillColorN:function t(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0},setStrokeRGBColor:function t(e,r,i){var n=o.Util.makeCssRgb(e,r,i);this.ctx.strokeStyle=n,this.current.strokeColor=n},setFillRGBColor:function t(e,r,i){var n=o.Util.makeCssRgb(e,r,i);this.ctx.fillStyle=n,this.current.fillColor=n,this.current.patternFill=!1},shadingFill:function t(e){var r=this.ctx;this.save();var i=(0,a.getShadingPatternFromIR)(e);r.fillStyle=i.getPattern(r,this,!0);var n=r.mozCurrentTransformInverse;if(n){var s=r.canvas,c=s.width,l=s.height,h=o.Util.applyTransform([0,0],n),u=o.Util.applyTransform([0,l],n),f=o.Util.applyTransform([c,0],n),d=o.Util.applyTransform([c,l],n),p=Math.min(h[0],u[0],f[0],d[0]),g=Math.min(h[1],u[1],f[1],d[1]),v=Math.max(h[0],u[0],f[0],d[0]),m=Math.max(h[1],u[1],f[1],d[1]);this.ctx.fillRect(p,g,v-p,m-g)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.restore()},beginInlineImage:function t(){throw new Error("Should not call beginInlineImage")},beginImageData:function t(){throw new Error("Should not call beginImageData")},paintFormXObjectBegin:function t(e,r){if(this.save(),this.baseTransformStack.push(this.baseTransform),(0,o.isArray)(e)&&6===e.length&&this.transform.apply(this,e),this.baseTransform=this.ctx.mozCurrentTransform,(0,o.isArray)(r)&&4===r.length){var i=r[2]-r[0],n=r[3]-r[1];this.ctx.rect(r[0],r[1],i,n),this.clip(),this.endPath()}},paintFormXObjectEnd:function t(){this.restore(),this.baseTransform=this.baseTransformStack.pop()},beginGroup:function t(e){this.save();var r=this.ctx;e.isolated||(0,o.info)("TODO: Support non-isolated groups."),e.knockout&&(0,o.warn)("Knockout groups not supported.");var i=r.mozCurrentTransform;if(e.matrix&&r.transform.apply(r,e.matrix),!e.bbox)throw new Error("Bounding box is required.");var n=o.Util.getAxialAlignedBoundingBox(e.bbox,r.mozCurrentTransform),a=[0,0,r.canvas.width,r.canvas.height];n=o.Util.intersect(n,a)||[0,0,0,0];var s=Math.floor(n[0]),c=Math.floor(n[1]),h=Math.max(Math.ceil(n[2])-s,1),u=Math.max(Math.ceil(n[3])-c,1),f=1,d=1;h>4096&&(f=h/4096,h=4096),u>4096&&(d=u/4096,u=4096);var p="groupAt"+this.groupLevel;e.smask&&(p+="_smask_"+this.smaskCounter++%2);var g=this.cachedCanvases.getCanvas(p,h,u,!0),v=g.context;v.scale(1/f,1/d),v.translate(-s,-c),v.transform.apply(v,i),e.smask?this.smaskStack.push({canvas:g.canvas,context:v,offsetX:s,offsetY:c,scaleX:f,scaleY:d,subtype:e.smask.subtype,backdrop:e.smask.backdrop,transferMap:e.smask.transferMap||null,startTransformInverse:null}):(r.setTransform(1,0,0,1,0,0),r.translate(s,c),r.scale(f,d)),l(r,v),this.ctx=v,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(r),this.groupLevel++,this.current.activeSMask=null},endGroup:function t(e){this.groupLevel--;var r=this.ctx;this.ctx=this.groupStack.pop(),void 0!==this.ctx.imageSmoothingEnabled?this.ctx.imageSmoothingEnabled=!1:this.ctx.mozImageSmoothingEnabled=!1,e.smask?this.tempSMask=this.smaskStack.pop():this.ctx.drawImage(r.canvas,0,0),this.restore()},beginAnnotations:function t(){this.save(),this.baseTransform&&this.ctx.setTransform.apply(this.ctx,this.baseTransform)},endAnnotations:function t(){this.restore()},beginAnnotation:function t(e,r,i){if(this.save(),h(this.ctx),this.current=new m,(0,o.isArray)(e)&&4===e.length){var n=e[2]-e[0],a=e[3]-e[1];this.ctx.rect(e[0],e[1],n,a),this.clip(),this.endPath()}this.transform.apply(this,r),this.transform.apply(this,i)},endAnnotation:function t(){this.restore()},paintJpegXObject:function t(e,r,i){var n=this.objs.get(e);if(!n)return void(0,o.warn)("Dependent image isn't ready yet");this.save();var a=this.ctx;if(a.scale(1/r,-1/i),a.drawImage(n,0,0,n.width,n.height,0,-i,r,i),this.imageLayer){var s=a.mozCurrentTransformInverse,c=this.getCanvasPosition(0,0);this.imageLayer.appendImage({objId:e,left:c[0],top:c[1],width:r/s[0],height:i/s[3]})}this.restore()},paintImageMaskXObject:function t(e){var r=this.ctx,i=e.width,o=e.height,a=this.current.fillColor,s=this.current.patternFill,l=this.processingType3;if(l&&void 0===l.compiled&&(l.compiled=i<=1e3&&o<=1e3?n({data:e.data,width:i,height:o}):null),l&&l.compiled)return void l.compiled(r);var h=this.cachedCanvases.getCanvas("maskCanvas",i,o),u=h.context;u.save(),c(u,e),u.globalCompositeOperation="source-in",u.fillStyle=s?a.getPattern(u,this):a,u.fillRect(0,0,i,o),u.restore(),this.paintInlineImageXObject(h.canvas)},paintImageMaskXObjectRepeat:function t(e,r,i,n){var o=e.width,a=e.height,s=this.current.fillColor,l=this.current.patternFill,h=this.cachedCanvases.getCanvas("maskCanvas",o,a),u=h.context;u.save(),c(u,e),u.globalCompositeOperation="source-in",u.fillStyle=l?s.getPattern(u,this):s,u.fillRect(0,0,o,a),u.restore();for(var f=this.ctx,d=0,p=n.length;d<p;d+=2)f.save(),f.transform(r,0,0,i,n[d],n[d+1]),f.scale(1,-1),f.drawImage(h.canvas,0,0,o,a,0,-1,1,1),f.restore()},paintImageMaskXObjectGroup:function t(e){for(var r=this.ctx,i=this.current.fillColor,n=this.current.patternFill,o=0,a=e.length;o<a;o++){var s=e[o],l=s.width,h=s.height,u=this.cachedCanvases.getCanvas("maskCanvas",l,h),f=u.context;f.save(),c(f,s),f.globalCompositeOperation="source-in",f.fillStyle=n?i.getPattern(f,this):i,f.fillRect(0,0,l,h),f.restore(),r.save(),r.transform.apply(r,s.transform),r.scale(1,-1),r.drawImage(u.canvas,0,0,l,h,0,-1,1,1),r.restore()}},paintImageXObject:function t(e){var r=this.objs.get(e);if(!r)return void(0,o.warn)("Dependent image isn't ready yet");this.paintInlineImageXObject(r)},paintImageXObjectRepeat:function t(e,r,i,n){var a=this.objs.get(e);if(!a)return void(0,o.warn)("Dependent image isn't ready yet");for(var s=a.width,c=a.height,l=[],h=0,u=n.length;h<u;h+=2)l.push({transform:[r,0,0,i,n[h],n[h+1]],x:0,y:0,w:s,h:c});this.paintInlineImageXObjectGroup(a,l)},paintInlineImageXObject:function t(e){var i=e.width,n=e.height,o=this.ctx;this.save(),o.scale(1/i,-1/n);var a=o.mozCurrentTransformInverse,s=a[0],c=a[1],l=Math.max(Math.sqrt(s*s+c*c),1),h=a[2],u=a[3],f=Math.max(Math.sqrt(h*h+u*u),1),d,p;if(e instanceof HTMLElement||!e.data)d=e;else{p=this.cachedCanvases.getCanvas("inlineImage",i,n);var g=p.context;r(g,e),d=p.canvas}for(var v=i,m=n,b="prescale1";l>2&&v>1||f>2&&m>1;){var y=v,_=m;l>2&&v>1&&(y=Math.ceil(v/2),l/=v/y),f>2&&m>1&&(_=Math.ceil(m/2),f/=m/_),p=this.cachedCanvases.getCanvas(b,y,_),g=p.context,g.clearRect(0,0,y,_),g.drawImage(d,0,0,v,m,0,0,y,_),d=p.canvas,v=y,m=_,b="prescale1"===b?"prescale2":"prescale1"}if(o.drawImage(d,0,0,v,m,0,-n,i,n),this.imageLayer){var w=this.getCanvasPosition(0,-n);this.imageLayer.appendImage({imgData:e,left:w[0],top:w[1],width:i/a[0],height:n/a[3]})}this.restore()},paintInlineImageXObjectGroup:function t(e,i){var n=this.ctx,o=e.width,a=e.height,s=this.cachedCanvases.getCanvas("inlineImage",o,a);r(s.context,e);for(var c=0,l=i.length;c<l;c++){var h=i[c];if(n.save(),n.transform.apply(n,h.transform),n.scale(1,-1),n.drawImage(s.canvas,h.x,h.y,h.w,h.h,0,-1,1,1),this.imageLayer){var u=this.getCanvasPosition(h.x,h.y);this.imageLayer.appendImage({imgData:e,left:u[0],top:u[1],width:o,height:a})}n.restore()}},paintSolidColorImageMask:function t(){this.ctx.fillRect(0,0,1,1)},paintXObject:function t(){(0,o.warn)("Unsupported 'paintXObject' command.")},markPoint:function t(e){},markPointProps:function t(e,r){},beginMarkedContent:function t(e){},beginMarkedContentProps:function t(e,r){},endMarkedContent:function t(){},beginCompat:function t(){},endCompat:function t(){},consumePath:function t(){var e=this.ctx;this.pendingClip&&(this.pendingClip===A?e.clip("evenodd"):e.clip(),this.pendingClip=null),e.beginPath()},getSinglePixelWidth:function t(e){if(null===this.cachedGetSinglePixelWidth){this.ctx.save();var r=this.ctx.mozCurrentTransformInverse;this.ctx.restore(),this.cachedGetSinglePixelWidth=Math.sqrt(Math.max(r[0]*r[0]+r[1]*r[1],r[2]*r[2]+r[3]*r[3]))}return this.cachedGetSinglePixelWidth},getCanvasPosition:function t(e,r){var i=this.ctx.mozCurrentTransform;return[i[0]*e+i[2]*r+i[4],i[1]*e+i[3]*r+i[5]]}};for(var T in o.OPS)e.prototype[o.OPS[T]]=e.prototype[T];return e}();e.CanvasGraphics=b},function(t,e,r){"use strict";function i(t){this.docId=t,this.styleElement=null,this.nativeFontFaces=[],this.loadTestFontId=0,this.loadingContext={requests:[],nextRequestId:0}}Object.defineProperty(e,"__esModule",{value:!0}),e.FontLoader=e.FontFaceObject=void 0;var n=r(0);i.prototype={insertRule:function t(e){var r=this.styleElement;r||(r=this.styleElement=document.createElement("style"),r.id="PDFJS_FONT_STYLE_TAG_"+this.docId,document.documentElement.getElementsByTagName("head")[0].appendChild(r));var i=r.sheet;i.insertRule(e,i.cssRules.length)},clear:function t(){this.styleElement&&(this.styleElement.remove(),this.styleElement=null),this.nativeFontFaces.forEach(function(t){document.fonts.delete(t)}),this.nativeFontFaces.length=0}};var o=function t(){return atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==")};Object.defineProperty(i.prototype,"loadTestFont",{get:function t(){return(0,n.shadow)(this,"loadTestFont",o())},configurable:!0}),i.prototype.addNativeFontFace=function t(e){this.nativeFontFaces.push(e),document.fonts.add(e)},i.prototype.bind=function t(e,r){for(var o=[],a=[],s=[],c=function t(e){return e.loaded.catch(function(t){(0,n.warn)('Failed to load font "'+e.family+'": '+t)})},l=i.isFontLoadingAPISupported&&!i.isSyncFontLoadingSupported,h=0,u=e.length;h<u;h++){var f=e[h];if(!f.attached&&!1!==f.loading)if(f.attached=!0,l){var d=f.createNativeFontFace();d&&(this.addNativeFontFace(d),s.push(c(d)))}else{var p=f.createFontFaceRule();p&&(this.insertRule(p),o.push(p),a.push(f))}}var g=this.queueLoadingCallback(r);l?Promise.all(s).then(function(){g.complete()}):o.length>0&&!i.isSyncFontLoadingSupported?this.prepareFontLoadEvent(o,a,g):g.complete()},i.prototype.queueLoadingCallback=function t(e){function r(){for((0,n.assert)(!a.end,"completeRequest() cannot be called twice"),a.end=Date.now();i.requests.length>0&&i.requests[0].end;){var t=i.requests.shift();setTimeout(t.callback,0)}}var i=this.loadingContext,o="pdfjs-font-loading-"+i.nextRequestId++,a={id:o,complete:r,callback:e,started:Date.now()};return i.requests.push(a),a},i.prototype.prepareFontLoadEvent=function t(e,r,i){function o(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function a(t,e,r,i){return t.substr(0,e)+i+t.substr(e+r)}function s(t,e){return++f>30?((0,n.warn)("Load test font never loaded."),void e()):(u.font="30px "+t,u.fillText(".",0,20),u.getImageData(0,0,1,1).data[3]>0?void e():void setTimeout(s.bind(null,t,e)))}var c,l,h=document.createElement("canvas");h.width=1,h.height=1;var u=h.getContext("2d"),f=0,d="lt"+Date.now()+this.loadTestFontId++,p=this.loadTestFont,g=976;p=a(p,976,d.length,d);var v=16,m=1482184792,b=o(p,16);for(c=0,l=d.length-3;c<l;c+=4)b=b-1482184792+o(d,c)|0;c<d.length&&(b=b-1482184792+o(d+"XXX",c)|0),p=a(p,16,4,(0,n.string32)(b));var y="url(data:font/opentype;base64,"+btoa(p)+");",_='@font-face { font-family:"'+d+'";src:'+y+"}";this.insertRule(_);var w=[];for(c=0,l=r.length;c<l;c++)w.push(r[c].loadedName);w.push(d);var S=document.createElement("div");for(S.setAttribute("style","visibility: hidden;width: 10px; height: 10px;position: absolute; top: 0px; left: 0px;"),c=0,l=w.length;c<l;++c){var x=document.createElement("span");x.textContent="Hi",x.style.fontFamily=w[c],S.appendChild(x)}document.body.appendChild(S),s(d,function(){document.body.removeChild(S),i.complete()})},i.isFontLoadingAPISupported="undefined"!=typeof document&&!!document.fonts;var a=function t(){if("undefined"==typeof navigator)return!0;var e=!1,r=/Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);return r&&r[1]>=14&&(e=!0),e};Object.defineProperty(i,"isSyncFontLoadingSupported",{get:function t(){return(0,n.shadow)(i,"isSyncFontLoadingSupported",a())},enumerable:!0,configurable:!0});var s={get value(){return(0,n.shadow)(this,"value",(0,n.isEvalSupported)())}},c=function t(){function e(t,e){this.compiledGlyphs=Object.create(null);for(var r in t)this[r]=t[r];this.options=e}return e.prototype={createNativeFontFace:function t(){if(!this.data)return null;if(this.options.disableFontFace)return this.disableFontFace=!0,null;var e=new FontFace(this.loadedName,this.data,{});return this.options.fontRegistry&&this.options.fontRegistry.registerFont(this),e},createFontFaceRule:function t(){if(!this.data)return null;if(this.options.disableFontFace)return this.disableFontFace=!0,null;var e=(0,n.bytesToString)(new Uint8Array(this.data)),r=this.loadedName,i="url(data:"+this.mimetype+";base64,"+btoa(e)+");",o='@font-face { font-family:"'+r+'";src:'+i+"}";return this.options.fontRegistry&&this.options.fontRegistry.registerFont(this,i),o},getPathGenerator:function t(e,r){if(!(r in this.compiledGlyphs)){var i=e.get(this.loadedName+"_path_"+r),n,o,a;if(this.options.isEvalSupported&&s.value){var c,l="";for(o=0,a=i.length;o<a;o++)n=i[o],c=void 0!==n.args?n.args.join(","):"",l+="c."+n.cmd+"("+c+");\n";this.compiledGlyphs[r]=new Function("c","size",l)}else this.compiledGlyphs[r]=function(t,e){for(o=0,a=i.length;o<a;o++)n=i[o],"scale"===n.cmd&&(n.args=[e,-e]),t[n.cmd].apply(t,n.args)}}return this.compiledGlyphs[r]}},e}();e.FontFaceObject=c,e.FontLoader=i},function(t,e,r){"use strict";function i(t){var e=a[t[0]];if(!e)throw new Error("Unknown IR type: "+t[0]);return e.fromIR(t)}Object.defineProperty(e,"__esModule",{value:!0}),e.TilingPattern=e.getShadingPatternFromIR=void 0;var n=r(0),o=r(7),a={};a.RadialAxial={fromIR:function t(e){var r=e[1],i=e[2],n=e[3],o=e[4],a=e[5],s=e[6];return{type:"Pattern",getPattern:function t(e){var c;"axial"===r?c=e.createLinearGradient(n[0],n[1],o[0],o[1]):"radial"===r&&(c=e.createRadialGradient(n[0],n[1],a,o[0],o[1],s));for(var l=0,h=i.length;l<h;++l){var u=i[l];c.addColorStop(u[0],u[1])}return c}}}};var s=function t(){function e(t,e,r,i,n,o,a,s){var c=e.coords,l=e.colors,h=t.data,u=4*t.width,f;c[r+1]>c[i+1]&&(f=r,r=i,i=f,f=o,o=a,a=f),c[i+1]>c[n+1]&&(f=i,i=n,n=f,f=a,a=s,s=f),c[r+1]>c[i+1]&&(f=r,r=i,i=f,f=o,o=a,a=f);var d=(c[r]+e.offsetX)*e.scaleX,p=(c[r+1]+e.offsetY)*e.scaleY,g=(c[i]+e.offsetX)*e.scaleX,v=(c[i+1]+e.offsetY)*e.scaleY,m=(c[n]+e.offsetX)*e.scaleX,b=(c[n+1]+e.offsetY)*e.scaleY;if(!(p>=b))for(var y=l[o],_=l[o+1],w=l[o+2],S=l[a],x=l[a+1],C=l[a+2],A=l[s],T=l[s+1],k=l[s+2],P=Math.round(p),E=Math.round(b),O,R,L,D,I,j,M,F,N,B=P;B<=E;B++){B<v?(N=B<p?0:p===v?1:(p-B)/(p-v),O=d-(d-g)*N,R=y-(y-S)*N,L=_-(_-x)*N,D=w-(w-C)*N):(N=B>b?1:v===b?0:(v-B)/(v-b),O=g-(g-m)*N,R=S-(S-A)*N,L=x-(x-T)*N,D=C-(C-k)*N),N=B<p?0:B>b?1:(p-B)/(p-b),I=d-(d-m)*N,j=y-(y-A)*N,M=_-(_-T)*N,F=w-(w-k)*N;for(var U=Math.round(Math.min(O,I)),z=Math.round(Math.max(O,I)),W=u*B+4*U,q=U;q<=z;q++)N=(O-q)/(O-I),N=N<0?0:N>1?1:N,h[W++]=R-(R-j)*N|0,h[W++]=L-(L-M)*N|0,h[W++]=D-(D-F)*N|0,h[W++]=255}}function r(t,r,i){var n=r.coords,o=r.colors,a,s;switch(r.type){case"lattice":var c=r.verticesPerRow,l=Math.floor(n.length/c)-1,h=c-1;for(a=0;a<l;a++)for(var u=a*c,f=0;f<h;f++,u++)e(t,i,n[u],n[u+1],n[u+c],o[u],o[u+1],o[u+c]),e(t,i,n[u+c+1],n[u+1],n[u+c],o[u+c+1],o[u+1],o[u+c]);break;case"triangles":for(a=0,s=n.length;a<s;a+=3)e(t,i,n[a],n[a+1],n[a+2],o[a],o[a+1],o[a+2]);break;default:throw new Error("illegal figure")}}function i(t,e,i,n,a,s,c){var l=1.1,h=3e3,u=2,f=Math.floor(t[0]),d=Math.floor(t[1]),p=Math.ceil(t[2])-f,g=Math.ceil(t[3])-d,v=Math.min(Math.ceil(Math.abs(p*e[0]*1.1)),3e3),m=Math.min(Math.ceil(Math.abs(g*e[1]*1.1)),3e3),b=p/v,y=g/m,_={coords:i,colors:n,offsetX:-f,offsetY:-d,scaleX:1/b,scaleY:1/y},w=v+4,S=m+4,x,C,A,T;if(o.WebGLUtils.isEnabled)x=o.WebGLUtils.drawFigures(v,m,s,a,_),C=c.getCanvas("mesh",w,S,!1),C.context.drawImage(x,2,2),x=C.canvas;else{C=c.getCanvas("mesh",w,S,!1);var k=C.context,P=k.createImageData(v,m);if(s){var E=P.data;for(A=0,T=E.length;A<T;A+=4)E[A]=s[0],E[A+1]=s[1],E[A+2]=s[2],E[A+3]=255}for(A=0;A<a.length;A++)r(P,a[A],_);k.putImageData(P,2,2),x=C.canvas}return{canvas:x,offsetX:f-2*b,offsetY:d-2*y,scaleX:b,scaleY:y}}return i}();a.Mesh={fromIR:function t(e){var r=e[2],i=e[3],o=e[4],a=e[5],c=e[6],l=e[8];return{type:"Pattern",getPattern:function t(e,h,u){var f;if(u)f=n.Util.singularValueDecompose2dScale(e.mozCurrentTransform);else if(f=n.Util.singularValueDecompose2dScale(h.baseTransform),c){var d=n.Util.singularValueDecompose2dScale(c);f=[f[0]*d[0],f[1]*d[1]]}var p=s(a,f,r,i,o,u?null:l,h.cachedCanvases);return u||(e.setTransform.apply(e,h.baseTransform),c&&e.transform.apply(e,c)),e.translate(p.offsetX,p.offsetY),e.scale(p.scaleX,p.scaleY),e.createPattern(p.canvas,"no-repeat")}}}},a.Dummy={fromIR:function t(){return{type:"Pattern",getPattern:function t(){return"hotpink"}}}};var c=function t(){function e(t,e,r,i,n){this.operatorList=t[2],this.matrix=t[3]||[1,0,0,1,0,0],this.bbox=t[4],this.xstep=t[5],this.ystep=t[6],this.paintType=t[7],this.tilingType=t[8],this.color=e,this.canvasGraphicsFactory=i,this.baseTransform=n,this.type="Pattern",this.ctx=r}var r={COLORED:1,UNCOLORED:2},i=3e3;return e.prototype={createPatternCanvas:function t(e){var r=this.operatorList,i=this.bbox,o=this.xstep,a=this.ystep,s=this.paintType,c=this.tilingType,l=this.color,h=this.canvasGraphicsFactory;(0,n.info)("TilingType: "+c);var u=i[0],f=i[1],d=i[2],p=i[3],g=[u,f],v=[u+o,f+a],m=v[0]-g[0],b=v[1]-g[1],y=n.Util.singularValueDecompose2dScale(this.matrix),_=n.Util.singularValueDecompose2dScale(this.baseTransform),w=[y[0]*_[0],y[1]*_[1]];m=Math.min(Math.ceil(Math.abs(m*w[0])),3e3),b=Math.min(Math.ceil(Math.abs(b*w[1])),3e3);var S=e.cachedCanvases.getCanvas("pattern",m,b,!0),x=S.context,C=h.createCanvasGraphics(x);C.groupLevel=e.groupLevel,this.setFillAndStrokeStyleToContext(x,s,l),this.setScale(m,b,o,a),this.transformToScale(C);var A=[1,0,0,1,-g[0],-g[1]];return C.transform.apply(C,A),this.clipBbox(C,i,u,f,d,p),C.executeOperatorList(r),S.canvas},setScale:function t(e,r,i,n){this.scale=[e/i,r/n]},transformToScale:function t(e){var r=this.scale,i=[r[0],0,0,r[1],0,0];e.transform.apply(e,i)},scaleToContext:function t(){var e=this.scale;this.ctx.scale(1/e[0],1/e[1])},clipBbox:function t(e,r,i,o,a,s){if((0,n.isArray)(r)&&4===r.length){var c=a-i,l=s-o;e.ctx.rect(i,o,c,l),e.clip(),e.endPath()}},setFillAndStrokeStyleToContext:function t(e,i,o){switch(i){case r.COLORED:var a=this.ctx;e.fillStyle=a.fillStyle,e.strokeStyle=a.strokeStyle;break;case r.UNCOLORED:var s=n.Util.makeCssRgb(o[0],o[1],o[2]);e.fillStyle=s,e.strokeStyle=s;break;default:throw new n.FormatError("Unsupported paint type: "+i)}},getPattern:function t(e,r){var i=this.createPatternCanvas(r);return e=this.ctx,e.setTransform.apply(e,this.baseTransform),e.transform.apply(e,this.matrix),this.scaleToContext(),e.createPattern(i,"repeat")}},e}();e.getShadingPatternFromIR=i,e.TilingPattern=c},function(t,e,r){"use strict";var i="1.8.575",n="bd8c1211",o=r(0),a=r(8),s=r(3),c=r(5),l=r(2),h=r(1),u=r(4);e.PDFJS=a.PDFJS,e.build=s.build,e.version=s.version,e.getDocument=s.getDocument,e.LoopbackPort=s.LoopbackPort,e.PDFDataRangeTransport=s.PDFDataRangeTransport,e.PDFWorker=s.PDFWorker,e.renderTextLayer=c.renderTextLayer,e.AnnotationLayer=l.AnnotationLayer,e.CustomStyle=h.CustomStyle,e.createPromiseCapability=o.createPromiseCapability,e.PasswordResponses=o.PasswordResponses,e.InvalidPDFException=o.InvalidPDFException,e.MissingPDFException=o.MissingPDFException,e.SVGGraphics=u.SVGGraphics,e.NativeImageDecoding=o.NativeImageDecoding,e.UnexpectedResponseException=o.UnexpectedResponseException,e.OPS=o.OPS,e.UNSUPPORTED_FEATURES=o.UNSUPPORTED_FEATURES,e.isValidUrl=h.isValidUrl,e.createValidAbsoluteUrl=o.createValidAbsoluteUrl,e.createObjectURL=o.createObjectURL,e.removeNullCharacters=o.removeNullCharacters,e.shadow=o.shadow,e.createBlob=o.createBlob,e.RenderingCancelledException=h.RenderingCancelledException,e.getFilenameFromUrl=h.getFilenameFromUrl,e.addLinkAttributes=h.addLinkAttributes,e.StatTimer=o.StatTimer},function(t,r,i){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};if("undefined"==typeof PDFJS||!PDFJS.compatibilityChecked){var o="undefined"!=typeof window&&window.Math===Math?window:void 0!==e&&e.Math===Math?e:"undefined"!=typeof self&&self.Math===Math?self:void 0,a="undefined"!=typeof navigator&&navigator.userAgent||"",s=/Android/.test(a),c=/Android\s[0-2][^\d]/.test(a),l=/Android\s[0-4][^\d]/.test(a),h=a.indexOf("Chrom")>=0,u=/Chrome\/(39|40)\./.test(a),f=a.indexOf("CriOS")>=0,d=a.indexOf("Trident")>=0,p=/\b(iPad|iPhone|iPod)(?=;)/.test(a),g=a.indexOf("Opera")>=0,v=/Safari\//.test(a)&&!/(Chrome\/|Android\s)/.test(a),m="object"===("undefined"==typeof window?"undefined":n(window))&&"object"===("undefined"==typeof document?"undefined":n(document));"undefined"==typeof PDFJS&&(o.PDFJS={}),PDFJS.compatibilityChecked=!0,function t(){function e(t,e){return new c(this.slice(t,e))}function r(t,e){arguments.length<2&&(e=0);for(var r=0,i=t.length;r<i;++r,++e)this[e]=255&t[r]}function i(t,e){this.buffer=t,this.byteLength=t.length,this.length=e,s(this.length)}function a(t){return{get:function e(){var r=this.buffer,i=t<<2;return(r[i]|r[i+1]<<8|r[i+2]<<16|r[i+3]<<24)>>>0},set:function e(r){var i=this.buffer,n=t<<2;i[n]=255&r,i[n+1]=r>>8&255,i[n+2]=r>>16&255,i[n+3]=r>>>24&255}}}function s(t){for(;l<t;)Object.defineProperty(i.prototype,l,a(l)),l++}function c(t){var i,o,a;if("number"==typeof t)for(i=[],o=0;o<t;++o)i[o]=0;else if("slice"in t)i=t.slice(0);else for(i=[],o=0,a=t.length;o<a;++o)i[o]=t[o];return i.subarray=e,i.buffer=i,i.byteLength=i.length,i.set=r,"object"===(void 0===t?"undefined":n(t))&&t.buffer&&(i.buffer=t.buffer),i}if("undefined"!=typeof Uint8Array)return void 0===Uint8Array.prototype.subarray&&(Uint8Array.prototype.subarray=function t(e,r){return new Uint8Array(this.slice(e,r))},Float32Array.prototype.subarray=function t(e,r){return new Float32Array(this.slice(e,r))}),void("undefined"==typeof Float64Array&&(o.Float64Array=Float32Array));i.prototype=Object.create(null);var l=0;o.Uint8Array=c,o.Int8Array=c,o.Int32Array=c,o.Uint16Array=c,o.Float32Array=c,o.Float64Array=c,o.Uint32Array=function(){if(3===arguments.length){if(0!==arguments[1])throw new Error("offset !== 0 is not supported");return new i(arguments[0],arguments[2])}return c.apply(this,arguments)}}(),function t(){if(m&&window.CanvasPixelArray){var e=window.CanvasPixelArray.prototype;"buffer"in e||(Object.defineProperty(e,"buffer",{get:function t(){return this},enumerable:!1,configurable:!0}),Object.defineProperty(e,"byteLength",{get:function t(){return this.length},enumerable:!1,configurable:!0}))}}(),function t(){o.URL||(o.URL=o.webkitURL)}(),function t(){if(void 0!==Object.defineProperty){var e=!0;try{m&&Object.defineProperty(new Image,"id",{value:"test"});var r=function t(){};r.prototype={get id(){}},Object.defineProperty(new r,"id",{value:"",configurable:!0,enumerable:!0,writable:!1})}catch(t){e=!1}if(e)return}Object.defineProperty=function t(e,r,i){delete e[r],"get"in i&&e.__defineGetter__(r,i.get),"set"in i&&e.__defineSetter__(r,i.set),"value"in i&&(e.__defineSetter__(r,function t(e){return this.__defineGetter__(r,function t(){return e}),e}),e[r]=i.value)}}(),function t(){if("undefined"!=typeof XMLHttpRequest){var e=XMLHttpRequest.prototype,r=new XMLHttpRequest;if("overrideMimeType"in r||Object.defineProperty(e,"overrideMimeType",{value:function t(e){}}),!("responseType"in r)){if(Object.defineProperty(e,"responseType",{get:function t(){return this._responseType||"text"},set:function t(e){"text"!==e&&"arraybuffer"!==e||(this._responseType=e,"arraybuffer"===e&&"function"==typeof this.overrideMimeType&&this.overrideMimeType("text/plain; charset=x-user-defined"))}}),"undefined"!=typeof VBArray)return void Object.defineProperty(e,"response",{get:function t(){return"arraybuffer"===this.responseType?new Uint8Array(new VBArray(this.responseBody).toArray()):this.responseText}});Object.defineProperty(e,"response",{get:function t(){if("arraybuffer"!==this.responseType)return this.responseText;var e=this.responseText,r,i=e.length,n=new Uint8Array(i);for(r=0;r<i;++r)n[r]=255&e.charCodeAt(r);return n.buffer}})}}}(),function t(){if(!("btoa"in o)){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";o.btoa=function(t){var r="",i,n;for(i=0,n=t.length;i<n;i+=3){var o=255&t.charCodeAt(i),a=255&t.charCodeAt(i+1),s=255&t.charCodeAt(i+2),c=o>>2,l=(3&o)<<4|a>>4,h=i+1<n?(15&a)<<2|s>>6:64,u=i+2<n?63&s:64;r+=e.charAt(c)+e.charAt(l)+e.charAt(h)+e.charAt(u)}return r}}}(),function t(){if(!("atob"in o)){o.atob=function(t){if(t=t.replace(/=+$/,""),t.length%4==1)throw new Error("bad atob input");for(var e=0,r,i,n=0,o="";i=t.charAt(n++);~i&&(r=e%4?64*r+i:i,e++%4)?o+=String.fromCharCode(255&r>>(-2*e&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return o}}}(),function t(){void 0===Function.prototype.bind&&(Function.prototype.bind=function t(e){var r=this,i=Array.prototype.slice.call(arguments,1);return function t(){var n=i.concat(Array.prototype.slice.call(arguments));return r.apply(e,n)}})}(),function t(){if(m){"dataset"in document.createElement("div")||Object.defineProperty(HTMLElement.prototype,"dataset",{get:function t(){if(this._dataset)return this._dataset;for(var e={},r=0,i=this.attributes.length;r<i;r++){var n=this.attributes[r];if("data-"===n.name.substring(0,5)){e[n.name.substring(5).replace(/\-([a-z])/g,function(t,e){return e.toUpperCase()})]=n.value}}return Object.defineProperty(this,"_dataset",{value:e,writable:!1,enumerable:!1}),e},enumerable:!0})}}(),function t(){function e(t,e,r,i){var n=t.className||"",o=n.split(/\s+/g);""===o[0]&&o.shift();var a=o.indexOf(e);return a<0&&r&&o.push(e),a>=0&&i&&o.splice(a,1),t.className=o.join(" "),a>=0}if(m){if(!("classList"in document.createElement("div"))){var r={add:function t(r){e(this.element,r,!0,!1)},contains:function t(r){return e(this.element,r,!1,!1)},remove:function t(r){e(this.element,r,!1,!0)},toggle:function t(r){e(this.element,r,!0,!0)}};Object.defineProperty(HTMLElement.prototype,"classList",{get:function t(){if(this._classList)return this._classList;var e=Object.create(r,{element:{value:this,writable:!1,enumerable:!0}});return Object.defineProperty(this,"_classList",{value:e,writable:!1,enumerable:!1}),e},enumerable:!0})}}}(),function t(){if(!("undefined"==typeof importScripts||"console"in o)){var e={},r={log:function t(){var e=Array.prototype.slice.call(arguments);o.postMessage({targetName:"main",action:"console_log",data:e})},error:function t(){var e=Array.prototype.slice.call(arguments);o.postMessage({targetName:"main",action:"console_error",data:e})},time:function t(r){e[r]=Date.now()},timeEnd:function t(r){var i=e[r];if(!i)throw new Error("Unknown timer name "+r);this.log("Timer:",r,Date.now()-i)}};o.console=r}}(),function t(){if(m)"console"in window?"bind"in console.log||(console.log=function(t){return function(e){return t(e)}}(console.log),console.error=function(t){return function(e){return t(e)}}(console.error),console.warn=function(t){return function(e){return t(e)}}(console.warn)):window.console={log:function t(){},error:function t(){},warn:function t(){}}}(),function t(){function e(t){r(t.target)&&t.stopPropagation()}function r(t){return t.disabled||t.parentNode&&r(t.parentNode)}g&&document.addEventListener("click",e,!0)}(),function t(){(d||f)&&(PDFJS.disableCreateObjectURL=!0)}(),function t(){"undefined"!=typeof navigator&&("language"in navigator||(PDFJS.locale=navigator.userLanguage||"en-US"))}(),function t(){(v||c||u||p)&&(PDFJS.disableRange=!0,PDFJS.disableStream=!0)}(),function t(){m&&(history.pushState&&!c||(PDFJS.disableHistory=!0))}(),function t(){if(m)if(window.CanvasPixelArray)"function"!=typeof window.CanvasPixelArray.prototype.set&&(window.CanvasPixelArray.prototype.set=function(t){for(var e=0,r=this.length;e<r;e++)this[e]=t[e]});else{var e=!1,r;if(h?(r=a.match(/Chrom(e|ium)\/([0-9]+)\./),e=r&&parseInt(r[2])<21):s?e=l:v&&(r=a.match(/Version\/([0-9]+)\.([0-9]+)\.([0-9]+) Safari\//),e=r&&parseInt(r[1])<6),e){var i=window.CanvasRenderingContext2D.prototype,n=i.createImageData;i.createImageData=function(t,e){var r=n.call(this,t,e);return r.data.set=function(t){for(var e=0,r=this.length;e<r;e++)this[e]=t[e]},r},i=null}}}(),function t(){function e(){window.requestAnimationFrame=function(t){return window.setTimeout(t,20)},window.cancelAnimationFrame=function(t){window.clearTimeout(t)}}if(m)p?e():"requestAnimationFrame"in window||(window.requestAnimationFrame=window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame,window.requestAnimationFrame||e())}(),function t(){(p||s)&&(PDFJS.maxCanvasPixels=5242880)}(),function t(){m&&d&&window.parent!==window&&(PDFJS.disableFullscreen=!0)}(),function t(){m&&("currentScript"in document||Object.defineProperty(document,"currentScript",{get:function t(){var e=document.getElementsByTagName("script");return e[e.length-1]},enumerable:!0,configurable:!0}))}(),function t(){if(m){var e=document.createElement("input");try{e.type="number"}catch(t){var r=e.constructor.prototype,i=Object.getOwnPropertyDescriptor(r,"type");Object.defineProperty(r,"type",{get:function t(){return i.get.call(this)},set:function t(e){i.set.call(this,"number"===e?"text":e)},enumerable:!0,configurable:!0})}}}(),function t(){if(m&&document.attachEvent){var e=document.constructor.prototype,r=Object.getOwnPropertyDescriptor(e,"readyState");Object.defineProperty(e,"readyState",{get:function t(){var e=r.get.call(this);return"interactive"===e?"loading":e},set:function t(e){r.set.call(this,e)},enumerable:!0,configurable:!0})}}(),function t(){m&&void 0===Element.prototype.remove&&(Element.prototype.remove=function(){this.parentNode&&this.parentNode.removeChild(this)})}(),function t(){Number.isNaN||(Number.isNaN=function(t){return"number"==typeof t&&isNaN(t)})}(),function t(){Number.isInteger||(Number.isInteger=function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t})}(),function t(){if(o.Promise)return"function"!=typeof o.Promise.all&&(o.Promise.all=function(t){var e=0,r=[],i,n,a=new o.Promise(function(t,e){i=t,n=e});return t.forEach(function(t,o){e++,t.then(function(t){r[o]=t,0===--e&&i(r)},n)}),0===e&&i(r),a}),"function"!=typeof o.Promise.resolve&&(o.Promise.resolve=function(t){return new o.Promise(function(e){e(t)})}),"function"!=typeof o.Promise.reject&&(o.Promise.reject=function(t){return new o.Promise(function(e,r){r(t)})}),void("function"!=typeof o.Promise.prototype.catch&&(o.Promise.prototype.catch=function(t){return o.Promise.prototype.then(void 0,t)}));var e=0,r=1,i=2,n=500,a={handlers:[],running:!1,unhandledRejections:[],pendingRejectionCheck:!1,scheduleHandlers:function t(e){0!==e._status&&(this.handlers=this.handlers.concat(e._handlers),e._handlers=[],this.running||(this.running=!0,setTimeout(this.runHandlers.bind(this),0)))},runHandlers:function t(){for(var e=1,r=Date.now()+1;this.handlers.length>0;){var n=this.handlers.shift(),o=n.thisPromise._status,a=n.thisPromise._value;try{1===o?"function"==typeof n.onResolve&&(a=n.onResolve(a)):"function"==typeof n.onReject&&(a=n.onReject(a),o=1,n.thisPromise._unhandledRejection&&this.removeUnhandeledRejection(n.thisPromise))}catch(t){o=i,a=t}if(n.nextPromise._updateStatus(o,a),Date.now()>=r)break}if(this.handlers.length>0)return void setTimeout(this.runHandlers.bind(this),0);this.running=!1},addUnhandledRejection:function t(e){this.unhandledRejections.push({promise:e,time:Date.now()}),this.scheduleRejectionCheck()},removeUnhandeledRejection:function t(e){e._unhandledRejection=!1;for(var r=0;r<this.unhandledRejections.length;r++)this.unhandledRejections[r].promise===e&&(this.unhandledRejections.splice(r),r--)},scheduleRejectionCheck:function t(){var e=this;this.pendingRejectionCheck||(this.pendingRejectionCheck=!0,setTimeout(function(){e.pendingRejectionCheck=!1;for(var t=Date.now(),r=0;r<e.unhandledRejections.length;r++)if(t-e.unhandledRejections[r].time>500){var i=e.unhandledRejections[r].promise._value,n="Unhandled rejection: "+i;i.stack&&(n+="\n"+i.stack);try{throw new Error(n)}catch(t){console.warn(n)}e.unhandledRejections.splice(r),r--}e.unhandledRejections.length&&e.scheduleRejectionCheck()},500))}},s=function t(e){this._status=0,this._handlers=[];try{e.call(this,this._resolve.bind(this),this._reject.bind(this))}catch(t){this._reject(t)}};s.all=function t(e){function r(t){a._status!==i&&(l=[],o(t))}var n,o,a=new s(function(t,e){n=t,o=e}),c=e.length,l=[];if(0===c)return n(l),a;for(var h=0,u=e.length;h<u;++h){var f=e[h],d=function(t){return function(e){a._status!==i&&(l[t]=e,0===--c&&n(l))}}(h);s.isPromise(f)?f.then(d,r):d(f)}return a},s.isPromise=function t(e){return e&&"function"==typeof e.then},s.resolve=function t(e){return new s(function(t){t(e)})},s.reject=function t(e){return new s(function(t,r){r(e)})},s.prototype={_status:null,_value:null,_handlers:null,_unhandledRejection:null,_updateStatus:function t(e,r){if(1!==this._status&&this._status!==i){if(1===e&&s.isPromise(r))return void r.then(this._updateStatus.bind(this,1),this._updateStatus.bind(this,i));this._status=e,this._value=r,e===i&&0===this._handlers.length&&(this._unhandledRejection=!0,a.addUnhandledRejection(this)),a.scheduleHandlers(this)}},_resolve:function t(e){this._updateStatus(1,e)},_reject:function t(e){this._updateStatus(i,e)},then:function t(e,r){var i=new s(function(t,e){this.resolve=t,this.reject=e});return this._handlers.push({thisPromise:this,onResolve:e,onReject:r,nextPromise:i}),a.scheduleHandlers(this),i},catch:function t(e){return this.then(void 0,e)}},o.Promise=s}(),function t(){function e(){this.id="$weakmap"+r++}if(!o.WeakMap){var r=0;e.prototype={has:function t(e){return("object"===(void 0===e?"undefined":n(e))||"function"==typeof e)&&null!==e&&!!Object.getOwnPropertyDescriptor(e,this.id)},get:function t(e){return this.has(e)?e[this.id]:void 0},set:function t(e,r){Object.defineProperty(e,this.id,{value:r,enumerable:!1,configurable:!0})},delete:function t(e){delete e[this.id]}},o.WeakMap=e}}(),function t(){function e(t){return void 0!==d[t]}function r(){l.call(this),this._isInvalid=!0}function i(t){return""===t&&r.call(this),t.toLowerCase()}function a(t){var e=t.charCodeAt(0);return e>32&&e<127&&-1===[34,35,60,62,63,96].indexOf(e)?t:encodeURIComponent(t)}function s(t){var e=t.charCodeAt(0);return e>32&&e<127&&-1===[34,35,60,62,96].indexOf(e)?t:encodeURIComponent(t)}function c(t,n,o){function c(t){y.push(t)}var l=n||"scheme start",h=0,u="",f=!1,b=!1,y=[];t:for(;(t[h-1]!==g||0===h)&&!this._isInvalid;){var _=t[h];switch(l){case"scheme start":if(!_||!v.test(_)){if(n){c("Invalid scheme.");break t}u="",l="no scheme";continue}u+=_.toLowerCase(),l="scheme";break;case"scheme":if(_&&m.test(_))u+=_.toLowerCase();else{if(":"!==_){if(n){if(_===g)break t;c("Code point not allowed in scheme: "+_);break t}u="",h=0,l="no scheme";continue}if(this._scheme=u,u="",n)break t;e(this._scheme)&&(this._isRelative=!0),l="file"===this._scheme?"relative":this._isRelative&&o&&o._scheme===this._scheme?"relative or authority":this._isRelative?"authority first slash":"scheme data"}break;case"scheme data":"?"===_?(this._query="?",l="query"):"#"===_?(this._fragment="#",l="fragment"):_!==g&&"\t"!==_&&"\n"!==_&&"\r"!==_&&(this._schemeData+=a(_));break;case"no scheme":if(o&&e(o._scheme)){l="relative";continue}c("Missing scheme."),r.call(this);break;case"relative or authority":if("/"!==_||"/"!==t[h+1]){c("Expected /, got: "+_),l="relative";continue}l="authority ignore slashes";break;case"relative":if(this._isRelative=!0,"file"!==this._scheme&&(this._scheme=o._scheme),_===g){this._host=o._host,this._port=o._port,this._path=o._path.slice(),this._query=o._query,this._username=o._username,this._password=o._password;break t}if("/"===_||"\\"===_)"\\"===_&&c("\\ is an invalid code point."),l="relative slash";else if("?"===_)this._host=o._host,this._port=o._port,this._path=o._path.slice(),this._query="?",this._username=o._username,this._password=o._password,l="query";else{if("#"!==_){var w=t[h+1],S=t[h+2];("file"!==this._scheme||!v.test(_)||":"!==w&&"|"!==w||S!==g&&"/"!==S&&"\\"!==S&&"?"!==S&&"#"!==S)&&(this._host=o._host,this._port=o._port,this._username=o._username,this._password=o._password,this._path=o._path.slice(),this._path.pop()),l="relative path";continue}this._host=o._host,this._port=o._port,this._path=o._path.slice(),this._query=o._query,this._fragment="#",this._username=o._username,this._password=o._password,l="fragment"}break;case"relative slash":if("/"!==_&&"\\"!==_){"file"!==this._scheme&&(this._host=o._host,this._port=o._port,this._username=o._username,this._password=o._password),l="relative path";continue}"\\"===_&&c("\\ is an invalid code point."),l="file"===this._scheme?"file host":"authority ignore slashes";break;case"authority first slash":if("/"!==_){c("Expected '/', got: "+_),l="authority ignore slashes";continue}l="authority second slash";break;case"authority second slash":if(l="authority ignore slashes","/"!==_){c("Expected '/', got: "+_);continue}break;case"authority ignore slashes":if("/"!==_&&"\\"!==_){l="authority";continue}c("Expected authority, got: "+_);break;case"authority":if("@"===_){f&&(c("@ already seen."),u+="%40"),f=!0;for(var x=0;x<u.length;x++){var C=u[x];if("\t"!==C&&"\n"!==C&&"\r"!==C)if(":"!==C||null!==this._password){var A=a(C);null!==this._password?this._password+=A:this._username+=A}else this._password="";else c("Invalid whitespace in authority.")}u=""}else{if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_){h-=u.length,u="",l="host";continue}u+=_}break;case"file host":if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_){2!==u.length||!v.test(u[0])||":"!==u[1]&&"|"!==u[1]?0===u.length?l="relative path start":(this._host=i.call(this,u),u="",l="relative path start"):l="relative path";continue}"\t"===_||"\n"===_||"\r"===_?c("Invalid whitespace in file host."):u+=_;break;case"host":case"hostname":if(":"!==_||b){if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_){if(this._host=i.call(this,u),u="",l="relative path start",n)break t;continue}"\t"!==_&&"\n"!==_&&"\r"!==_?("["===_?b=!0:"]"===_&&(b=!1),u+=_):c("Invalid code point in host/hostname: "+_)}else if(this._host=i.call(this,u),u="",l="port","hostname"===n)break t;break;case"port":if(/[0-9]/.test(_))u+=_;else{if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_||n){if(""!==u){var T=parseInt(u,10);T!==d[this._scheme]&&(this._port=T+""),u=""}if(n)break t;l="relative path start";continue}"\t"===_||"\n"===_||"\r"===_?c("Invalid code point in port: "+_):r.call(this)}break;case"relative path start":if("\\"===_&&c("'\\' not allowed in path."),l="relative path","/"!==_&&"\\"!==_)continue;break;case"relative path":if(_!==g&&"/"!==_&&"\\"!==_&&(n||"?"!==_&&"#"!==_))"\t"!==_&&"\n"!==_&&"\r"!==_&&(u+=a(_));else{"\\"===_&&c("\\ not allowed in relative path.");var k;(k=p[u.toLowerCase()])&&(u=k),".."===u?(this._path.pop(),"/"!==_&&"\\"!==_&&this._path.push("")):"."===u&&"/"!==_&&"\\"!==_?this._path.push(""):"."!==u&&("file"===this._scheme&&0===this._path.length&&2===u.length&&v.test(u[0])&&"|"===u[1]&&(u=u[0]+":"),this._path.push(u)),u="","?"===_?(this._query="?",l="query"):"#"===_&&(this._fragment="#",l="fragment")}break;case"query":n||"#"!==_?_!==g&&"\t"!==_&&"\n"!==_&&"\r"!==_&&(this._query+=s(_)):(this._fragment="#",l="fragment");break;case"fragment":_!==g&&"\t"!==_&&"\n"!==_&&"\r"!==_&&(this._fragment+=_)}h++}}function l(){this._scheme="",this._schemeData="",this._username="",this._password=null,this._host="",this._port="",this._path=[],this._query="",this._fragment="",this._isInvalid=!1,this._isRelative=!1}function h(t,e){void 0===e||e instanceof h||(e=new h(String(e))),this._url=t,l.call(this);var r=t.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g,"");c.call(this,r,null,e)}var u=!1;try{if("function"==typeof URL&&"object"===n(URL.prototype)&&"origin"in URL.prototype){var f=new URL("b","http://a");f.pathname="c%20d",u="http://a/c%20d"===f.href}}catch(t){}if(!u){var d=Object.create(null);d.ftp=21,d.file=0,d.gopher=70,d.http=80,d.https=443,d.ws=80,d.wss=443;var p=Object.create(null);p["%2e"]=".",p[".%2e"]="..",p["%2e."]="..",p["%2e%2e"]="..";var g,v=/[a-zA-Z]/,m=/[a-zA-Z0-9\+\-\.]/;h.prototype={toString:function t(){return this.href},get href(){if(this._isInvalid)return this._url;var t="";return""===this._username&&null===this._password||(t=this._username+(null!==this._password?":"+this._password:"")+"@"),this.protocol+(this._isRelative?"//"+t+this.host:"")+this.pathname+this._query+this._fragment},set href(t){l.call(this),c.call(this,t)},get protocol(){return this._scheme+":"},set protocol(t){this._isInvalid||c.call(this,t+":","scheme start")},get host(){return this._isInvalid?"":this._port?this._host+":"+this._port:this._host},set host(t){!this._isInvalid&&this._isRelative&&c.call(this,t,"host")},get hostname(){return this._host},set hostname(t){!this._isInvalid&&this._isRelative&&c.call(this,t,"hostname")},get port(){return this._port},set port(t){!this._isInvalid&&this._isRelative&&c.call(this,t,"port")},get pathname(){return this._isInvalid?"":this._isRelative?"/"+this._path.join("/"):this._schemeData},set pathname(t){!this._isInvalid&&this._isRelative&&(this._path=[],c.call(this,t,"relative path start"))},get search(){return this._isInvalid||!this._query||"?"===this._query?"":this._query},set search(t){!this._isInvalid&&this._isRelative&&(this._query="?","?"===t[0]&&(t=t.slice(1)),c.call(this,t,"query"))},get hash(){return this._isInvalid||!this._fragment||"#"===this._fragment?"":this._fragment},set hash(t){this._isInvalid||(this._fragment="#","#"===t[0]&&(t=t.slice(1)),c.call(this,t,"fragment"))},get origin(){var t;if(this._isInvalid||!this._scheme)return"";switch(this._scheme){case"data":case"file":case"javascript":case"mailto":return"null";case"blob":try{return new h(this._schemeData).origin||"null"}catch(t){}return"null"}return t=this.host,t?this._scheme+"://"+t:""}};var b=o.URL;b&&(h.createObjectURL=function(t){return b.createObjectURL.apply(b,arguments)},h.revokeObjectURL=function(t){b.revokeObjectURL(t)}),o.URL=h}}()}}])})}).call(e,r(0),r(1),r(2).Buffer)},function(t,e){var r={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==r.call(t)}},function(t,e,r){"use strict";(function(e,i){function n(t){return B.from(t)}function o(t){return B.isBuffer(t)||t instanceof U}function a(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?I(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}function s(t,e){j=j||r(4),t=t||{},this.objectMode=!!t.objectMode,e instanceof j&&(this.objectMode=this.objectMode||!!t.readableObjectMode);var i=t.highWaterMark,n=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:n,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new X,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(H||(H=r(19).StringDecoder),this.decoder=new H(t.encoding),this.encoding=t.encoding)}function c(t){if(j=j||r(4),!(this instanceof c))return new c(t);this._readableState=new s(t,this),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),N.call(this)}function l(t,e,r,i,o){var a=t._readableState;if(null===e)a.reading=!1,g(t,a);else{var s;o||(s=u(a,e)),s?t.emit("error",s):a.objectMode||e&&e.length>0?("string"==typeof e||a.objectMode||Object.getPrototypeOf(e)===B.prototype||(e=n(e)),i?a.endEmitted?t.emit("error",new Error("stream.unshift() after end event")):h(t,a,e,!0):a.ended?t.emit("error",new Error("stream.push() after EOF")):(a.reading=!1,a.decoder&&!r?(e=a.decoder.write(e),a.objectMode||0!==e.length?h(t,a,e,!1):b(t,a)):h(t,a,e,!1))):i||(a.reading=!1)}return f(a)}function h(t,e,r,i){e.flowing&&0===e.length&&!e.sync?(t.emit("data",r),t.read(0)):(e.length+=e.objectMode?1:r.length,i?e.buffer.unshift(r):e.buffer.push(r),e.needReadable&&v(t)),b(t,e)}function u(t,e){var r;return o(e)||"string"==typeof e||void 0===e||t.objectMode||(r=new TypeError("Invalid non-string/buffer chunk")),r}function f(t){return!t.ended&&(t.needReadable||t.length<t.highWaterMark||0===t.length)}function d(t){return t>=V?t=V:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}function p(t,e){return t<=0||0===e.length&&e.ended?0:e.objectMode?1:t!==t?e.flowing&&e.length?e.buffer.head.data.length:e.length:(t>e.highWaterMark&&(e.highWaterMark=d(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function g(t,e){if(!e.ended){if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,v(t)}}function v(t){var e=t._readableState;e.needReadable=!1,e.emittedReadable||(q("emitReadable",e.flowing),e.emittedReadable=!0,e.sync?D(m,t):m(t))}function m(t){q("emit readable"),t.emit("readable"),C(t)}function b(t,e){e.readingMore||(e.readingMore=!0,D(y,t,e))}function y(t,e){for(var r=e.length;!e.reading&&!e.flowing&&!e.ended&&e.length<e.highWaterMark&&(q("maybeReadMore read 0"),t.read(0),r!==e.length);)r=e.length;e.readingMore=!1}function _(t){return function(){var e=t._readableState;q("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&F(t,"data")&&(e.flowing=!0,C(t))}}function w(t){q("readable nexttick read 0"),t.read(0)}function S(t,e){e.resumeScheduled||(e.resumeScheduled=!0,D(x,t,e))}function x(t,e){e.reading||(q("resume read 0"),t.read(0)),e.resumeScheduled=!1,e.awaitDrain=0,t.emit("resume"),C(t),e.flowing&&!e.reading&&t.read(0)}function C(t){var e=t._readableState;for(q("flow",e.flowing);e.flowing&&null!==t.read(););}function A(t,e){if(0===e.length)return null;var r;return e.objectMode?r=e.buffer.shift():!t||t>=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.head.data:e.buffer.concat(e.length),e.buffer.clear()):r=T(t,e.buffer,e.decoder),r}function T(t,e,r){var i;return t<e.head.data.length?(i=e.head.data.slice(0,t),e.head.data=e.head.data.slice(t)):i=t===e.head.data.length?e.shift():r?k(t,e):P(t,e),i}function k(t,e){var r=e.head,i=1,n=r.data;for(t-=n.length;r=r.next;){var o=r.data,a=t>o.length?o.length:t;if(a===o.length?n+=o:n+=o.slice(0,t),0===(t-=a)){a===o.length?(++i,r.next?e.head=r.next:e.head=e.tail=null):(e.head=r,r.data=o.slice(a));break}++i}return e.length-=i,n}function P(t,e){var r=B.allocUnsafe(t),i=e.head,n=1;for(i.data.copy(r),t-=i.data.length;i=i.next;){var o=i.data,a=t>o.length?o.length:t;if(o.copy(r,r.length-t,0,a),0===(t-=a)){a===o.length?(++n,i.next?e.head=i.next:e.head=e.tail=null):(e.head=i,i.data=o.slice(a));break}++n}return e.length-=n,r}function E(t){var e=t._readableState;if(e.length>0)throw new Error('"endReadable()" called on non-empty stream');e.endEmitted||(e.ended=!0,D(O,e,t))}function O(t,e){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}function R(t,e){for(var r=0,i=t.length;r<i;r++)e(t[r],r)}function L(t,e){for(var r=0,i=t.length;r<i;r++)if(t[r]===e)return r;return-1}var D=r(7);t.exports=c;var I=r(13),j;c.ReadableState=s;var M=r(15).EventEmitter,F=function(t,e){return t.listeners(e).length},N=r(16),B=r(10).Buffer,U=e.Uint8Array||function(){},z=r(5);z.inherits=r(3);var W=r(44),q=void 0;q=W&&W.debuglog?W.debuglog("stream"):function(){};var X=r(45),G=r(17),H;z.inherits(c,N);var Y=["error","close","destroy","pause","resume"];Object.defineProperty(c.prototype,"destroyed",{get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(t){this._readableState&&(this._readableState.destroyed=t)}}),c.prototype.destroy=G.destroy,c.prototype._undestroy=G.undestroy,c.prototype._destroy=function(t,e){this.push(null),e(t)},c.prototype.push=function(t,e){var r=this._readableState,i;return r.objectMode?i=!0:"string"==typeof t&&(e=e||r.defaultEncoding,e!==r.encoding&&(t=B.from(t,e),e=""),i=!0),l(this,t,e,!1,i)},c.prototype.unshift=function(t){return l(this,t,null,!0,!1)},c.prototype.isPaused=function(){return!1===this._readableState.flowing},c.prototype.setEncoding=function(t){return H||(H=r(19).StringDecoder),this._readableState.decoder=new H(t),this._readableState.encoding=t,this};var V=8388608;c.prototype.read=function(t){q("read",t),t=parseInt(t,10);var e=this._readableState,r=t;if(0!==t&&(e.emittedReadable=!1),0===t&&e.needReadable&&(e.length>=e.highWaterMark||e.ended))return q("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?E(this):v(this),null;if(0===(t=p(t,e))&&e.ended)return 0===e.length&&E(this),null;var i=e.needReadable;q("need readable",i),(0===e.length||e.length-t<e.highWaterMark)&&(i=!0,q("length less than watermark",i)),e.ended||e.reading?(i=!1,q("reading or ended",i)):i&&(q("do read"),e.reading=!0,e.sync=!0,0===e.length&&(e.needReadable=!0),this._read(e.highWaterMark),e.sync=!1,e.reading||(t=p(r,e)));var n;return n=t>0?A(t,e):null,null===n?(e.needReadable=!0,t=0):e.length-=t,0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&E(this)),null!==n&&this.emit("data",n),n},c.prototype._read=function(t){this.emit("error",new Error("_read() is not implemented"))},c.prototype.pipe=function(t,e){function r(t,e){q("onunpipe"),t===f&&e&&!1===e.hasUnpiped&&(e.hasUnpiped=!0,o())}function n(){q("onend"),t.end()}function o(){q("cleanup"),t.removeListener("close",l),t.removeListener("finish",h),t.removeListener("drain",v),t.removeListener("error",c),t.removeListener("unpipe",r),f.removeListener("end",n),f.removeListener("end",u),f.removeListener("data",s),m=!0,!d.awaitDrain||t._writableState&&!t._writableState.needDrain||v()}function s(e){q("ondata"),b=!1,!1!==t.write(e)||b||((1===d.pipesCount&&d.pipes===t||d.pipesCount>1&&-1!==L(d.pipes,t))&&!m&&(q("false write response, pause",f._readableState.awaitDrain),f._readableState.awaitDrain++,b=!0),f.pause())}function c(e){q("onerror",e),u(),t.removeListener("error",c),0===F(t,"error")&&t.emit("error",e)}function l(){t.removeListener("finish",h),u()}function h(){q("onfinish"),t.removeListener("close",l),u()}function u(){q("unpipe"),f.unpipe(t)}var f=this,d=this._readableState;switch(d.pipesCount){case 0:d.pipes=t;break;case 1:d.pipes=[d.pipes,t];break;default:d.pipes.push(t)}d.pipesCount+=1,q("pipe count=%d opts=%j",d.pipesCount,e);var p=(!e||!1!==e.end)&&t!==i.stdout&&t!==i.stderr,g=p?n:u;d.endEmitted?D(g):f.once("end",g),t.on("unpipe",r);var v=_(f);t.on("drain",v);var m=!1,b=!1;return f.on("data",s),a(t,"error",c),t.once("close",l),t.once("finish",h),t.emit("pipe",f),d.flowing||(q("pipe resume"),f.resume()),t},c.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes?this:(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r),this);if(!t){var i=e.pipes,n=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var o=0;o<n;o++)i[o].emit("unpipe",this,r);return this}var a=L(e.pipes,t);return-1===a?this:(e.pipes.splice(a,1),e.pipesCount-=1,1===e.pipesCount&&(e.pipes=e.pipes[0]),t.emit("unpipe",this,r),this)},c.prototype.on=function(t,e){var r=N.prototype.on.call(this,t,e);if("data"===t)!1!==this._readableState.flowing&&this.resume();else if("readable"===t){var i=this._readableState;i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.emittedReadable=!1,i.reading?i.length&&v(this):D(w,this))}return r},c.prototype.addListener=c.prototype.on,c.prototype.resume=function(){var t=this._readableState;return t.flowing||(q("resume"),t.flowing=!0,S(this,t)),this},c.prototype.pause=function(){return q("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(q("pause"),this._readableState.flowing=!1,this.emit("pause")),this},c.prototype.wrap=function(t){var e=this._readableState,r=!1,i=this;t.on("end",function(){if(q("wrapped end"),e.decoder&&!e.ended){var t=e.decoder.end();t&&t.length&&i.push(t)}i.push(null)}),t.on("data",function(n){if(q("wrapped data"),e.decoder&&(n=e.decoder.write(n)),(!e.objectMode||null!==n&&void 0!==n)&&(e.objectMode||n&&n.length)){i.push(n)||(r=!0,t.pause())}});for(var n in t)void 0===this[n]&&"function"==typeof t[n]&&(this[n]=function(e){return function(){return t[e].apply(t,arguments)}}(n));for(var o=0;o<Y.length;o++)t.on(Y[o],i.emit.bind(i,Y[o]));return i._read=function(e){q("wrapped _read",e),r&&(r=!1,t.resume())},i},c._fromList=A}).call(e,r(0),r(1))},function(t,e){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(t){return"function"==typeof t}function n(t){return"number"==typeof t}function o(t){return"object"==typeof t&&null!==t}function a(t){return void 0===t}t.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(t){if(!n(t)||t<0||isNaN(t))throw TypeError("n must be a positive number");return this._maxListeners=t,this},r.prototype.emit=function(t){var e,r,n,s,c,l;if(this._events||(this._events={}),"error"===t&&(!this._events.error||o(this._events.error)&&!this._events.error.length)){if((e=arguments[1])instanceof Error)throw e;var h=new Error('Uncaught, unspecified "error" event. ('+e+")");throw h.context=e,h}if(r=this._events[t],a(r))return!1;if(i(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:s=Array.prototype.slice.call(arguments,1),r.apply(this,s)}else if(o(r))for(s=Array.prototype.slice.call(arguments,1),l=r.slice(),n=l.length,c=0;c<n;c++)l[c].apply(this,s);return!0},r.prototype.addListener=function(t,e){var n;if(!i(e))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",t,i(e.listener)?e.listener:e),this._events[t]?o(this._events[t])?this._events[t].push(e):this._events[t]=[this._events[t],e]:this._events[t]=e,o(this._events[t])&&!this._events[t].warned&&(n=a(this._maxListeners)?r.defaultMaxListeners:this._maxListeners)&&n>0&&this._events[t].length>n&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace()),this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(t,e){function r(){this.removeListener(t,r),n||(n=!0,e.apply(this,arguments))}if(!i(e))throw TypeError("listener must be a function");var n=!1;return r.listener=e,this.on(t,r),this},r.prototype.removeListener=function(t,e){var r,n,a,s;if(!i(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(r=this._events[t],a=r.length,n=-1,r===e||i(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(o(r)){for(s=a;s-- >0;)if(r[s]===e||r[s].listener&&r[s].listener===e){n=s;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},r.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[t],i(r))this.removeListener(t,r);else if(r)for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},r.prototype.listeners=function(t){var e;return e=this._events&&this._events[t]?i(this._events[t])?[this._events[t]]:this._events[t].slice():[]},r.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(i(e))return 1;if(e)return e.length}return 0},r.listenerCount=function(t,e){return t.listenerCount(e)}},function(t,e,r){t.exports=r(15).EventEmitter},function(t,e,r){"use strict";function i(t,e){var r=this,i=this._readableState&&this._readableState.destroyed,n=this._writableState&&this._writableState.destroyed;if(i||n)return void(e?e(t):!t||this._writableState&&this._writableState.errorEmitted||a(o,this,t));this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,function(t){!e&&t?(a(o,r,t),r._writableState&&(r._writableState.errorEmitted=!0)):e&&e(t)})}function n(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function o(t,e){t.emit("error",e)}var a=r(7);t.exports={destroy:i,undestroy:n}},function(t,e,r){"use strict";(function(e,i,n){function o(t,e,r){this.chunk=t,this.encoding=e,this.callback=r,this.next=null}function a(t){var e=this;this.next=null,this.entry=null,this.finish=function(){P(e,t)}}function s(t){return j.from(t)}function c(t){return j.isBuffer(t)||t instanceof M}function l(){}function h(t,e){R=R||r(4),t=t||{},this.objectMode=!!t.objectMode,e instanceof R&&(this.objectMode=this.objectMode||!!t.writableObjectMode);var i=t.highWaterMark,n=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:n,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var o=!1===t.decodeStrings;this.decodeStrings=!o,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(t){y(e,t)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new a(this)}function u(t){if(R=R||r(4),!(N.call(u,this)||this instanceof R))return new u(t);this._writableState=new h(t,this),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),I.call(this)}function f(t,e){var r=new Error("write after end");t.emit("error",r),E(e,r)}function d(t,e,r,i){var n=!0,o=!1;return null===r?o=new TypeError("May not write null values to stream"):"string"==typeof r||void 0===r||e.objectMode||(o=new TypeError("Invalid non-string/buffer chunk")),o&&(t.emit("error",o),E(i,o),n=!1),n}function p(t,e,r){return t.objectMode||!1===t.decodeStrings||"string"!=typeof e||(e=j.from(e,r)),e}function g(t,e,r,i,n,o){if(!r){var a=p(e,i,n);i!==a&&(r=!0,n="buffer",i=a)}var s=e.objectMode?1:i.length;e.length+=s;var c=e.length<e.highWaterMark;if(c||(e.needDrain=!0),e.writing||e.corked){var l=e.lastBufferedRequest;e.lastBufferedRequest={chunk:i,encoding:n,isBuf:r,callback:o,next:null},l?l.next=e.lastBufferedRequest:e.bufferedRequest=e.lastBufferedRequest,e.bufferedRequestCount+=1}else v(t,e,!1,s,i,n,o);return c}function v(t,e,r,i,n,o,a){e.writelen=i,e.writecb=a,e.writing=!0,e.sync=!0,r?t._writev(n,e.onwrite):t._write(n,o,e.onwrite),e.sync=!1}function m(t,e,r,i,n){--e.pendingcb,r?(E(n,i),E(T,t,e),t._writableState.errorEmitted=!0,t.emit("error",i)):(n(i),t._writableState.errorEmitted=!0,t.emit("error",i),T(t,e))}function b(t){t.writing=!1,t.writecb=null,t.length-=t.writelen,t.writelen=0}function y(t,e){var r=t._writableState,i=r.sync,n=r.writecb;if(b(r),e)m(t,r,i,e,n);else{var o=x(r);o||r.corked||r.bufferProcessing||!r.bufferedRequest||S(t,r),i?O(_,t,r,o,n):_(t,r,o,n)}}function _(t,e,r,i){r||w(t,e),e.pendingcb--,i(),T(t,e)}function w(t,e){0===e.length&&e.needDrain&&(e.needDrain=!1,t.emit("drain"))}function S(t,e){e.bufferProcessing=!0;var r=e.bufferedRequest;if(t._writev&&r&&r.next){var i=e.bufferedRequestCount,n=new Array(i),o=e.corkedRequestsFree;o.entry=r;for(var s=0,c=!0;r;)n[s]=r,r.isBuf||(c=!1),r=r.next,s+=1;n.allBuffers=c,v(t,e,!0,e.length,n,"",o.finish),e.pendingcb++,e.lastBufferedRequest=null,o.next?(e.corkedRequestsFree=o.next,o.next=null):e.corkedRequestsFree=new a(e)}else{for(;r;){var l=r.chunk,h=r.encoding,u=r.callback;if(v(t,e,!1,e.objectMode?1:l.length,l,h,u),r=r.next,e.writing)break}null===r&&(e.lastBufferedRequest=null)}e.bufferedRequestCount=0,e.bufferedRequest=r,e.bufferProcessing=!1}function x(t){return t.ending&&0===t.length&&null===t.bufferedRequest&&!t.finished&&!t.writing}function C(t,e){t._final(function(r){e.pendingcb--,r&&t.emit("error",r),e.prefinished=!0,t.emit("prefinish"),T(t,e)})}function A(t,e){e.prefinished||e.finalCalled||("function"==typeof t._final?(e.pendingcb++,e.finalCalled=!0,E(C,t,e)):(e.prefinished=!0,t.emit("prefinish")))}function T(t,e){var r=x(e);return r&&(A(t,e),0===e.pendingcb&&(e.finished=!0,t.emit("finish"))),r}function k(t,e,r){e.ending=!0,T(t,e),r&&(e.finished?E(r):t.once("finish",r)),e.ended=!0,t.writable=!1}function P(t,e,r){var i=t.entry;for(t.entry=null;i;){var n=i.callback;e.pendingcb--,n(r),i=i.next}e.corkedRequestsFree?e.corkedRequestsFree.next=t:e.corkedRequestsFree=t}var E=r(7);t.exports=u;var O=!e.browser&&["v0.10","v0.9."].indexOf(e.version.slice(0,5))>-1?i:E,R;u.WritableState=h;var L=r(5);L.inherits=r(3);var D={deprecate:r(48)},I=r(16),j=r(10).Buffer,M=n.Uint8Array||function(){},F=r(17);L.inherits(u,I),h.prototype.getBuffer=function t(){for(var e=this.bufferedRequest,r=[];e;)r.push(e),e=e.next;return r},function(){try{Object.defineProperty(h.prototype,"buffer",{get:D.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(t){}}();var N;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(N=Function.prototype[Symbol.hasInstance],Object.defineProperty(u,Symbol.hasInstance,{value:function(t){return!!N.call(this,t)||t&&t._writableState instanceof h}})):N=function(t){return t instanceof this},u.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},u.prototype.write=function(t,e,r){var i=this._writableState,n=!1,o=c(t)&&!i.objectMode;return o&&!j.isBuffer(t)&&(t=s(t)),"function"==typeof e&&(r=e,e=null),o?e="buffer":e||(e=i.defaultEncoding),"function"!=typeof r&&(r=l),i.ended?f(this,r):(o||d(this,i,t,r))&&(i.pendingcb++,n=g(this,i,o,t,e,r)),n},u.prototype.cork=function(){this._writableState.corked++},u.prototype.uncork=function(){var t=this._writableState;t.corked&&(t.corked--,t.writing||t.corked||t.finished||t.bufferProcessing||!t.bufferedRequest||S(this,t))},u.prototype.setDefaultEncoding=function t(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},u.prototype._write=function(t,e,r){r(new Error("_write() is not implemented"))},u.prototype._writev=null,u.prototype.end=function(t,e,r){var i=this._writableState;"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!==t&&void 0!==t&&this.write(t,e),i.corked&&(i.corked=1,this.uncork()),i.ending||i.finished||k(this,i,r)},Object.defineProperty(u.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t)}}),u.prototype.destroy=F.destroy,u.prototype._undestroy=F.undestroy,u.prototype._destroy=function(t,e){this.end(),e(t)}}).call(e,r(1),r(46).setImmediate,r(0))},function(t,e,r){function i(t){if(t&&!c(t))throw new Error("Unknown encoding: "+t)}function n(t){return t.toString(this.encoding)}function o(t){this.charReceived=t.length%2,this.charLength=this.charReceived?2:0}function a(t){this.charReceived=t.length%3,this.charLength=this.charReceived?3:0}var s=r(2).Buffer,c=s.isEncoding||function(t){switch(t&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}},l=e.StringDecoder=function(t){switch(this.encoding=(t||"utf8").toLowerCase().replace(/[-_]/,""),i(t),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=o;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=a;break;default:return void(this.write=n)}this.charBuffer=new s(6),this.charReceived=0,this.charLength=0};l.prototype.write=function(t){for(var e="";this.charLength;){var r=t.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:t.length;if(t.copy(this.charBuffer,this.charReceived,0,r),this.charReceived+=r,this.charReceived<this.charLength)return"";t=t.slice(r,t.length),e=this.charBuffer.slice(0,this.charLength).toString(this.encoding);var i=e.charCodeAt(e.length-1);if(!(i>=55296&&i<=56319)){if(this.charReceived=this.charLength=0,0===t.length)return e;break}this.charLength+=this.surrogateSize,e=""}this.detectIncompleteChar(t);var n=t.length;this.charLength&&(t.copy(this.charBuffer,0,t.length-this.charReceived,n),n-=this.charReceived),e+=t.toString(this.encoding,0,n);var n=e.length-1,i=e.charCodeAt(n);if(i>=55296&&i<=56319){var o=this.surrogateSize;return this.charLength+=o,this.charReceived+=o,this.charBuffer.copy(this.charBuffer,o,0,o),t.copy(this.charBuffer,0,0,o),e.substring(0,n)}return e},l.prototype.detectIncompleteChar=function(t){for(var e=t.length>=3?3:t.length;e>0;e--){var r=t[t.length-e];if(1==e&&r>>5==6){this.charLength=2;break}if(e<=2&&r>>4==14){this.charLength=3;break}if(e<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=e},l.prototype.end=function(t){var e="";if(t&&t.length&&(e=this.write(t)),this.charReceived){var r=this.charReceived,i=this.charBuffer,n=this.encoding;e+=i.slice(0,r).toString(n)}return e}},function(t,e,r){"use strict";function i(t){this.afterTransform=function(e,r){return n(t,e,r)},this.needTransform=!1,this.transforming=!1,this.writecb=null,this.writechunk=null,this.writeencoding=null}function n(t,e,r){var i=t._transformState;i.transforming=!1;var n=i.writecb;if(!n)return t.emit("error",new Error("write callback called multiple times"));i.writechunk=null,i.writecb=null,null!==r&&void 0!==r&&t.push(r),n(e);var o=t._readableState;o.reading=!1,(o.needReadable||o.length<o.highWaterMark)&&t._read(o.highWaterMark)}function o(t){if(!(this instanceof o))return new o(t);s.call(this,t),this._transformState=new i(this);var e=this;this._readableState.needReadable=!0,this._readableState.sync=!1,t&&("function"==typeof t.transform&&(this._transform=t.transform),"function"==typeof t.flush&&(this._flush=t.flush)),this.once("prefinish",function(){"function"==typeof this._flush?this._flush(function(t,r){a(e,t,r)}):a(e)})}function a(t,e,r){if(e)return t.emit("error",e);null!==r&&void 0!==r&&t.push(r);var i=t._writableState,n=t._transformState;if(i.length)throw new Error("Calling transform done when ws.length != 0");if(n.transforming)throw new Error("Calling transform done when still transforming");return t.push(null)}t.exports=o;var s=r(4),c=r(5);c.inherits=r(3),c.inherits(o,s),o.prototype.push=function(t,e){return this._transformState.needTransform=!1,s.prototype.push.call(this,t,e)},o.prototype._transform=function(t,e,r){throw new Error("_transform() is not implemented")},o.prototype._write=function(t,e,r){var i=this._transformState;if(i.writecb=r,i.writechunk=t,i.writeencoding=e,!i.transforming){var n=this._readableState;(i.needTransform||n.needReadable||n.length<n.highWaterMark)&&this._read(n.highWaterMark)}},o.prototype._read=function(t){var e=this._transformState;null!==e.writechunk&&e.writecb&&!e.transforming?(e.transforming=!0,this._transform(e.writechunk,e.writeencoding,e.afterTransform)):e.needTransform=!0},o.prototype._destroy=function(t,e){var r=this;s.prototype._destroy.call(this,t,function(t){e(t),r.emit("close")})}},function(t,e,r){"use strict";t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},function(t,e,r){"use strict";function i(t,e,r,i){for(var n=65535&t|0,o=t>>>16&65535|0,a=0;0!==r;){a=r>2e3?2e3:r,r-=a;do{n=n+e[i++]|0,o=o+n|0}while(--a);n%=65521,o%=65521}return n|o<<16|0}t.exports=i},function(t,e,r){"use strict";function i(){for(var t,e=[],r=0;r<256;r++){t=r;for(var i=0;i<8;i++)t=1&t?3988292384^t>>>1:t>>>1;e[r]=t}return e}function n(t,e,r,i){var n=o,a=i+r;t^=-1;for(var s=i;s<a;s++)t=t>>>8^n[255&(t^e[s])];return-1^t}var o=i();t.exports=n},function(t,e,r){(function(t,i){function n(t,r){var i={seen:[],stylize:a};return arguments.length>=3&&(i.depth=arguments[2]),arguments.length>=4&&(i.colors=arguments[3]),g(r)?i.showHidden=r:r&&e._extend(i,r),w(i.showHidden)&&(i.showHidden=!1),w(i.depth)&&(i.depth=2),w(i.colors)&&(i.colors=!1),w(i.customInspect)&&(i.customInspect=!0),i.colors&&(i.stylize=o),c(i,t,i.depth)}function o(t,e){var r=n.styles[e];return r?"["+n.colors[r][0]+"m"+t+"["+n.colors[r][1]+"m":t}function a(t,e){return t}function s(t){var e={};return t.forEach(function(t,r){e[t]=!0}),e}function c(t,r,i){if(t.customInspect&&r&&T(r.inspect)&&r.inspect!==e.inspect&&(!r.constructor||r.constructor.prototype!==r)){var n=r.inspect(i,t);return y(n)||(n=c(t,n,i)),n}var o=l(t,r);if(o)return o;var a=Object.keys(r),g=s(a);if(t.showHidden&&(a=Object.getOwnPropertyNames(r)),A(r)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return h(r);if(0===a.length){if(T(r)){var v=r.name?": "+r.name:"";return t.stylize("[Function"+v+"]","special")}if(S(r))return t.stylize(RegExp.prototype.toString.call(r),"regexp");if(C(r))return t.stylize(Date.prototype.toString.call(r),"date");if(A(r))return h(r)}var m="",b=!1,_=["{","}"];if(p(r)&&(b=!0,_=["[","]"]),T(r)){m=" [Function"+(r.name?": "+r.name:"")+"]"}if(S(r)&&(m=" "+RegExp.prototype.toString.call(r)),C(r)&&(m=" "+Date.prototype.toUTCString.call(r)),A(r)&&(m=" "+h(r)),0===a.length&&(!b||0==r.length))return _[0]+m+_[1];if(i<0)return S(r)?t.stylize(RegExp.prototype.toString.call(r),"regexp"):t.stylize("[Object]","special");t.seen.push(r);var w;return w=b?u(t,r,i,g,a):a.map(function(e){return f(t,r,i,g,e,b)}),t.seen.pop(),d(w,m,_)}function l(t,e){if(w(e))return t.stylize("undefined","undefined");if(y(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}return b(e)?t.stylize(""+e,"number"):g(e)?t.stylize(""+e,"boolean"):v(e)?t.stylize("null","null"):void 0}function h(t){return"["+Error.prototype.toString.call(t)+"]"}function u(t,e,r,i,n){for(var o=[],a=0,s=e.length;a<s;++a)R(e,String(a))?o.push(f(t,e,r,i,String(a),!0)):o.push("");return n.forEach(function(n){n.match(/^\d+$/)||o.push(f(t,e,r,i,n,!0))}),o}function f(t,e,r,i,n,o){var a,s,l;if(l=Object.getOwnPropertyDescriptor(e,n)||{value:e[n]},l.get?s=l.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):l.set&&(s=t.stylize("[Setter]","special")),R(i,n)||(a="["+n+"]"),s||(t.seen.indexOf(l.value)<0?(s=v(r)?c(t,l.value,null):c(t,l.value,r-1),s.indexOf("\n")>-1&&(s=o?s.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+s.split("\n").map(function(t){return" "+t}).join("\n"))):s=t.stylize("[Circular]","special")),w(a)){if(o&&n.match(/^\d+$/))return s;a=JSON.stringify(""+n),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=t.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=t.stylize(a,"string"))}return a+": "+s}function d(t,e,r){var i=0;return t.reduce(function(t,e){return i++,e.indexOf("\n")>=0&&i++,t+e.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1]:r[0]+e+" "+t.join(", ")+" "+r[1]}function p(t){return Array.isArray(t)}function g(t){return"boolean"==typeof t}function v(t){return null===t}function m(t){return null==t}function b(t){return"number"==typeof t}function y(t){return"string"==typeof t}function _(t){return"symbol"==typeof t}function w(t){return void 0===t}function S(t){return x(t)&&"[object RegExp]"===P(t)}function x(t){return"object"==typeof t&&null!==t}function C(t){return x(t)&&"[object Date]"===P(t)}function A(t){return x(t)&&("[object Error]"===P(t)||t instanceof Error)}function T(t){return"function"==typeof t}function k(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t}function P(t){return Object.prototype.toString.call(t)}function E(t){return t<10?"0"+t.toString(10):t.toString(10)}function O(){var t=new Date,e=[E(t.getHours()),E(t.getMinutes()),E(t.getSeconds())].join(":");return[t.getDate(),j[t.getMonth()],e].join(" ")}function R(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var L=/%[sdj%]/g;e.format=function(t){if(!y(t)){for(var e=[],r=0;r<arguments.length;r++)e.push(n(arguments[r]));return e.join(" ")}for(var r=1,i=arguments,o=i.length,a=String(t).replace(L,function(t){if("%%"===t)return"%";if(r>=o)return t;switch(t){case"%s":return String(i[r++]);case"%d":return Number(i[r++]);case"%j":try{return JSON.stringify(i[r++])}catch(t){return"[Circular]"}default:return t}}),s=i[r];r<o;s=i[++r])v(s)||!x(s)?a+=" "+s:a+=" "+n(s);return a},e.deprecate=function(r,n){function o(){if(!a){if(i.throwDeprecation)throw new Error(n);i.traceDeprecation?console.trace(n):console.error(n),a=!0}return r.apply(this,arguments)}if(w(t.process))return function(){return e.deprecate(r,n).apply(this,arguments)};if(!0===i.noDeprecation)return r;var a=!1;return o};var D={},I;e.debuglog=function(t){if(w(I)&&(I=i.env.NODE_DEBUG||""),t=t.toUpperCase(),!D[t])if(new RegExp("\\b"+t+"\\b","i").test(I)){var r=i.pid;D[t]=function(){var i=e.format.apply(e,arguments);console.error("%s %d: %s",t,r,i)}}else D[t]=function(){};return D[t]},e.inspect=n,n.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},n.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},e.isArray=p,e.isBoolean=g,e.isNull=v,e.isNullOrUndefined=m,e.isNumber=b,e.isString=y,e.isSymbol=_,e.isUndefined=w,e.isRegExp=S,e.isObject=x,e.isDate=C,e.isError=A,e.isFunction=T,e.isPrimitive=k,e.isBuffer=r(58);var j=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];e.log=function(){console.log("%s - %s",O(),e.format.apply(e,arguments))},e.inherits=r(59),e._extend=function(t,e){if(!e||!x(e))return t;for(var r=Object.keys(e),i=r.length;i--;)t[r[i]]=e[r[i]];return t}}).call(e,r(0),r(1))},function(t,e,r){"use strict";function i(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}function n(t,e,r){if(t&&l.isObject(t)&&t instanceof i)return t;var n=new i;return n.parse(t,e,r),n}function o(t){return l.isString(t)&&(t=n(t)),t instanceof i?t.format():i.prototype.format.call(t)}function a(t,e){return n(t,!1,!0).resolve(e)}function s(t,e){return t?n(t,!1,!0).resolveObject(e):e}var c=r(66),l=r(68);e.parse=n,e.resolve=a,e.resolveObject=s,e.format=o,e.Url=i;var h=/^([a-z0-9.+-]+:)/i,u=/:[0-9]*$/,f=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,d=["<",">",'"',"`"," ","\r","\n","\t"],p=["{","}","|","\\","^","`"].concat(d),g=["'"].concat(p),v=["%","/","?",";","#"].concat(g),m=["/","?","#"],b=255,y=/^[+a-z0-9A-Z_-]{0,63}$/,_=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,w={javascript:!0,"javascript:":!0},S={javascript:!0,"javascript:":!0},x={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},C=r(69);i.prototype.parse=function(t,e,r){if(!l.isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var i=t.indexOf("?"),n=-1!==i&&i<t.indexOf("#")?"?":"#",o=t.split(n),a=/\\/g;o[0]=o[0].replace(a,"/"),t=o.join(n);var s=t;if(s=s.trim(),!r&&1===t.split("#").length){var u=f.exec(s);if(u)return this.path=s,this.href=s,this.pathname=u[1],u[2]?(this.search=u[2],this.query=e?C.parse(this.search.substr(1)):this.search.substr(1)):e&&(this.search="",this.query={}),this}var d=h.exec(s);if(d){d=d[0];var p=d.toLowerCase();this.protocol=p,s=s.substr(d.length)}if(r||d||s.match(/^\/\/[^@\/]+@[^@\/]+/)){var b="//"===s.substr(0,2);!b||d&&S[d]||(s=s.substr(2),this.slashes=!0)}if(!S[d]&&(b||d&&!x[d])){for(var A=-1,T=0;T<m.length;T++){var k=s.indexOf(m[T]);-1!==k&&(-1===A||k<A)&&(A=k)}var P,E;E=-1===A?s.lastIndexOf("@"):s.lastIndexOf("@",A),-1!==E&&(P=s.slice(0,E),s=s.slice(E+1),this.auth=decodeURIComponent(P)),A=-1;for(var T=0;T<v.length;T++){var k=s.indexOf(v[T]);-1!==k&&(-1===A||k<A)&&(A=k)}-1===A&&(A=s.length),this.host=s.slice(0,A),s=s.slice(A),this.parseHost(),this.hostname=this.hostname||"";var O="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!O)for(var R=this.hostname.split(/\./),T=0,L=R.length;T<L;T++){var D=R[T];if(D&&!D.match(y)){for(var I="",j=0,M=D.length;j<M;j++)D.charCodeAt(j)>127?I+="x":I+=D[j];if(!I.match(y)){var F=R.slice(0,T),N=R.slice(T+1),B=D.match(_);B&&(F.push(B[1]),N.unshift(B[2])),N.length&&(s="/"+N.join(".")+s),this.hostname=F.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),O||(this.hostname=c.toASCII(this.hostname));var U=this.port?":"+this.port:"",z=this.hostname||"";this.host=z+U,this.href+=this.host,O&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==s[0]&&(s="/"+s))}if(!w[p])for(var T=0,L=g.length;T<L;T++){var W=g[T];if(-1!==s.indexOf(W)){var q=encodeURIComponent(W);q===W&&(q=escape(W)),s=s.split(W).join(q)}}var X=s.indexOf("#");-1!==X&&(this.hash=s.substr(X),s=s.slice(0,X));var G=s.indexOf("?");if(-1!==G?(this.search=s.substr(G),this.query=s.substr(G+1),e&&(this.query=C.parse(this.query)),s=s.slice(0,G)):e&&(this.search="",this.query={}),s&&(this.pathname=s),x[p]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var U=this.pathname||"",H=this.search||"";this.path=U+H}return this.href=this.format(),this},i.prototype.format=function(){var t=this.auth||"";t&&(t=encodeURIComponent(t),t=t.replace(/%3A/i,":"),t+="@");var e=this.protocol||"",r=this.pathname||"",i=this.hash||"",n=!1,o="";this.host?n=t+this.host:this.hostname&&(n=t+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(n+=":"+this.port)),this.query&&l.isObject(this.query)&&Object.keys(this.query).length&&(o=C.stringify(this.query));var a=this.search||o&&"?"+o||"";return e&&":"!==e.substr(-1)&&(e+=":"),this.slashes||(!e||x[e])&&!1!==n?(n="//"+(n||""),r&&"/"!==r.charAt(0)&&(r="/"+r)):n||(n=""),i&&"#"!==i.charAt(0)&&(i="#"+i),a&&"?"!==a.charAt(0)&&(a="?"+a),r=r.replace(/[?#]/g,function(t){return encodeURIComponent(t)}),a=a.replace("#","%23"),e+n+r+a+i},i.prototype.resolve=function(t){return this.resolveObject(n(t,!1,!0)).format()},i.prototype.resolveObject=function(t){if(l.isString(t)){var e=new i;e.parse(t,!1,!0),t=e}for(var r=new i,n=Object.keys(this),o=0;o<n.length;o++){var a=n[o];r[a]=this[a]}if(r.hash=t.hash,""===t.href)return r.href=r.format(),r;if(t.slashes&&!t.protocol){for(var s=Object.keys(t),c=0;c<s.length;c++){var h=s[c];"protocol"!==h&&(r[h]=t[h])}return x[r.protocol]&&r.hostname&&!r.pathname&&(r.path=r.pathname="/"),r.href=r.format(),r}if(t.protocol&&t.protocol!==r.protocol){if(!x[t.protocol]){for(var u=Object.keys(t),f=0;f<u.length;f++){var d=u[f];r[d]=t[d]}return r.href=r.format(),r}if(r.protocol=t.protocol,t.host||S[t.protocol])r.pathname=t.pathname;else{for(var p=(t.pathname||"").split("/");p.length&&!(t.host=p.shift()););t.host||(t.host=""),t.hostname||(t.hostname=""),""!==p[0]&&p.unshift(""),p.length<2&&p.unshift(""),r.pathname=p.join("/")}if(r.search=t.search,r.query=t.query,r.host=t.host||"",r.auth=t.auth,r.hostname=t.hostname||t.host,r.port=t.port,r.pathname||r.search){var g=r.pathname||"",v=r.search||"";r.path=g+v}return r.slashes=r.slashes||t.slashes,r.href=r.format(),r}var m=r.pathname&&"/"===r.pathname.charAt(0),b=t.host||t.pathname&&"/"===t.pathname.charAt(0),y=b||m||r.host&&t.pathname,_=y,w=r.pathname&&r.pathname.split("/")||[],p=t.pathname&&t.pathname.split("/")||[],C=r.protocol&&!x[r.protocol];if(C&&(r.hostname="",r.port=null,r.host&&(""===w[0]?w[0]=r.host:w.unshift(r.host)),r.host="",t.protocol&&(t.hostname=null,t.port=null,t.host&&(""===p[0]?p[0]=t.host:p.unshift(t.host)),t.host=null),y=y&&(""===p[0]||""===w[0])),b)r.host=t.host||""===t.host?t.host:r.host,r.hostname=t.hostname||""===t.hostname?t.hostname:r.hostname,r.search=t.search,r.query=t.query,w=p;else if(p.length)w||(w=[]),w.pop(),w=w.concat(p),r.search=t.search,r.query=t.query;else if(!l.isNullOrUndefined(t.search)){if(C){r.hostname=r.host=w.shift();var A=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@");A&&(r.auth=A.shift(),r.host=r.hostname=A.shift())}return r.search=t.search,r.query=t.query,l.isNull(r.pathname)&&l.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!w.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var T=w.slice(-1)[0],k=(r.host||t.host||w.length>1)&&("."===T||".."===T)||""===T,P=0,E=w.length;E>=0;E--)T=w[E],"."===T?w.splice(E,1):".."===T?(w.splice(E,1),P++):P&&(w.splice(E,1),P--);if(!y&&!_)for(;P--;P)w.unshift("..");!y||""===w[0]||w[0]&&"/"===w[0].charAt(0)||w.unshift(""),k&&"/"!==w.join("/").substr(-1)&&w.push("");var O=""===w[0]||w[0]&&"/"===w[0].charAt(0);if(C){r.hostname=r.host=O?"":w.length?w.shift():"";var A=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@");A&&(r.auth=A.shift(),r.host=r.hostname=A.shift())}return y=y||r.host&&w.length,y&&!O&&w.unshift(""),w.length?r.pathname=w.join("/"):(r.pathname=null,r.path=null),l.isNull(r.pathname)&&l.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=t.auth||r.auth,r.slashes=r.slashes||t.slashes,r.href=r.format(),r},i.prototype.parseHost=function(){var t=this.host,e=u.exec(t);e&&(e=e[0],":"!==e&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)}},function(t,e,r){(function(t){var i=r(72),n=r(75),o=r(76),a=r(25),s=e;s.request=function(e,r){e="string"==typeof e?a.parse(e):n(e);var o=-1===t.location.protocol.search(/^https?:$/)?"http:":"",s=e.protocol||o,c=e.hostname||e.host,l=e.port,h=e.path||"/";c&&-1!==c.indexOf(":")&&(c="["+c+"]"),e.url=(c?s+"//"+c:"")+(l?":"+l:"")+h,e.method=(e.method||"GET").toUpperCase(),e.headers=e.headers||{};var u=new i(e);return r&&u.on("response",r),u},s.get=function t(e,r){var i=s.request(e,r);return i.end(),i},s.Agent=function(){},s.Agent.defaultMaxSockets=4,s.STATUS_CODES=o,s.METHODS=["CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REPORT","SEARCH","SUBSCRIBE","TRACE","UNLOCK","UNSUBSCRIBE"]}).call(e,r(0))},function(t,e,r){(function(t){function r(){if(void 0!==o)return o;if(t.XMLHttpRequest){o=new t.XMLHttpRequest;try{o.open("GET",t.XDomainRequest?"/":"https://example.com")}catch(t){o=null}}else o=null;return o}function i(t){var e=r();if(!e)return!1;try{return e.responseType=t,e.responseType===t}catch(t){}return!1}function n(t){return"function"==typeof t}e.fetch=n(t.fetch)&&n(t.ReadableStream),e.blobConstructor=!1;try{new Blob([new ArrayBuffer(1)]),e.blobConstructor=!0}catch(t){}var o,a=void 0!==t.ArrayBuffer,s=a&&n(t.ArrayBuffer.prototype.slice);e.arraybuffer=e.fetch||a&&i("arraybuffer"),e.msstream=!e.fetch&&s&&i("ms-stream"),e.mozchunkedarraybuffer=!e.fetch&&a&&i("moz-chunked-arraybuffer"),e.overrideMimeType=e.fetch||!!r()&&n(r().overrideMimeType),e.vbArray=n(t.VBArray),o=null}).call(e,r(0))},function(t,e){function r(t){throw new Error("Cannot find module '"+t+"'.")}r.keys=function(){return[]},r.resolve=r,t.exports=r,r.id=28},function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t){function e(e){return(0,l.getDocument)(e).then(function(e){return e.getPage(1).then(function(i){A=i,x=A.getViewport(1);var n=t.clientWidth/x.width/v;return x=A.getViewport(n),T.setDocument(e).then(function(){T.currentScale=n,r(x.width*v,x.height*v)})})})}function r(e,r){var i=document.createElement("canvas");i.id=s.default.generate(),i.width=e,i.height=r,t.appendChild(i),C=new h.fabric.Canvas(i.id),C.selection=!1,h.fabric.util.addListener(document.getElementsByClassName("upper-canvas")[0],"contextmenu",function(t){var e=C.getPointer(t),r=C.findTarget(t);w.emit("contextmenu",t,e,r),t.preventDefault()}),C.on("mouse:dblclick",function(t){var e=C.getPointer(t.e);w.emit("mouse:dblclick",t.e,e),t.e.preventDefault()}),C.on("mouse:up",function(t){var e=C.getPointer(t.e),r=C.findTarget(t.e);w.emit("mouse:up",t.e,e,r),t.e.preventDefault()}),C.on("mouse:down",function(t){var e=C.getPointer(t.e),r=C.findTarget(t.e);w.emit("mouse:down",t.e,e,r),t.e.preventDefault()}),C.on("mouse:wheel",function(t){var e=(0,p.default)(t.e).pixelY/3600;w.emit("mouse:wheel",t.e,e),t.e.preventDefault()}),C.on("object:selected",function(t){var e=t.target;w.emit("object:selected",e)})}function i(t,e){function r(e){return new Promise(function(r){h.fabric.Image.fromURL(e,function(e){e.top=t.y-e.height,e.left=t.x-e.width/2,e.topRate=t.y/x.height,e.leftRate=t.x/x.width,e.opacity=.85,e.hasControls=!1,e.hasRotatingPoint=!1;var i=b(t),n=o(i,2),s=n[0],c=n[1];e.pdfPoint={x:s,y:c},e.index=C.size(),e.on("moving",function(t){return y(t,e)}),Object.assign(e,a),C.add(e),r(e)})})}var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return e&&(w.pinImgURL=e),i.text?n(w.pinImgURL,i).then(r):r(w.pinImgURL)}function n(e,r){return new Promise(function(i){h.fabric.Image.fromURL(e,function(e){var n=document.createElement("canvas");n.id=s.default.generate(),n.width=e.width,n.height=e.height,n.style.display="none",t.appendChild(n);var o=new h.fabric.Canvas(n.id);e.left=0,e.top=0,o.add(e);var a=new h.fabric.Text(r.text,{fontSize:r.fontSize||20,fill:r.color||"red",fontFamily:r.fontFamily||"Comic Sans",fontWeight:r.fontWeight||"normal"});a.left=e.left+(e.width-a.width)/2,a.top=e.top+(e.height-a.height)/2.5,o.add(a),i(o.toDataURL()),o.dispose(),t.removeChild(n)})})}function a(t,e,r,n){var a=x.convertToViewportPoint(t.x,t.y),s=o(a,2);return i({x:s[0],y:s[1]},e,r,n)}function c(t,e,r,n,o){return i({x:t*x.width,y:e*x.height},r,n,o)}function u(t){var e=C.item(t);e&&(C.remove(e),e.text&&C.remove(e.text))}function d(t){}function m(t){var e=T.currentScale,r=e+t,i=r/e;T.currentScale=r,x=A.getViewport(r);var n=C.getHeight(),o=C.getWidth();C.setHeight(n*i),C.setWidth(o*i),C.getObjects().forEach(function(t){t.set("top",x.height*t.topRate-t.height),t.set("left",x.width*t.leftRate-t.width/2),t.setCoords()}),C.renderAll(),C.calcOffset()}function b(t){return x.convertToPdfPoint(t.x,t.y)}function y(t,e){e.topRate=(e.top+e.height)/x.height,e.leftRate=(e.left+e.width/2)/x.width;var r=b({x:e.left+e.width/2,y:e.top+e.height}),i=o(r,2),n=i[0],a=i[1];e.pdfPoint={x:n,y:a},e.setCoords(),w.emit("object:moving",e)}var _=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};f.default.call(this);var w=this;w.load=e,w.addPin=i,w.addPinWithRate=c,w.addPinWithPdfPoint=a,w.removePin=u,w.zoomIn=m,w.zoomOut=d,w.pinImgURL=_.pinImgURL||"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACEAAAAvCAYAAABt7qMfAAAJKklEQVRYR61YfXBU1RX/nfdYEoyQooKY7AappaWDBUuKu+8ljKGVFMpQsQOCfLT8g6NQC1ItVSvy0TLaGaso2kFrrJXWqSgWYaCIpZnKvrcJRGescawoluwGUygfgkCy+947nfNyN25eNiSLPX8l+84593fPPR+/ewn9lLZx40oyJSW1xHyjRzSeiCrAfBmASwCcB3ACzCkA/yTgjY5MZvc1TU2f9sc99aXUZprDM0AtmOcCqAZQ2pcNgM8AWABeYk3bVRGPH7mQTa8gmseOHThkyJBZRLSCmccDGBBw5IFIdp8GEAIwNK8O0Axgg55Ov1jW1HQuH5i8ID6qrCwdGArdC6IfAyjJMTzhh5v5gEf0HjE3a7p+ymUeogFjGLiWmScQIKCH5diliehZraNjVVlT03+DQHqAaJ04MeLp+noQzQeQ/d4C5hcBvBo6d+7dEe+8c7a38CYNY5DO/HWX6CYA4uOarC4RvaYxryyz7fdz7buB+Lim5ksDOjqeAzCzS4n576Tr94Xj8UQ/cqGbSso0r2Pm9QCm5myoPkQ0Z4RlHe0Cl/3j4LRpRcWnTq0GsFIZuGCuC2naL3INCgVyuLp6qOY4q0F0h8odcfFk6OzZldmIdkUiaZoLwPw0gEGixcCmQZp2z7B4/EyhCwf15YiIeR0TrVAbdBhYXmHbT4quD+JQNHplSNO2A5ioHOwNEd3aWwQYoLZJk65wHGeE53mleih0Jp3JtI1qaDhGgJcPtESEXPd5Amao78060fQyyzrsg2iJxRZJ9gLQAJz2PG/WyIaGPfmc/XvSpKt0x7kdwM0ARqhm1U7AUSbarmUyG8v370/ms02ZpsHMfwEw3P/O/JNIIvEEHauqGtzBvJmZv6+O4dGj6fTKbzU1ZYKOUqY53WNeS8A3cxItqNYM5lWRRGJr8INEMBWLrQKR5J5Ifcbz5lLSMGRHzwMYDOC4zlxblki8ledcJcMlWmU5304DkJy5NNBJjzGwrMK2pay7yRHDGOMCbwAoByCNbgmlTPMRZpaEEflHUVHR9OH19dJ2uyQVjYY9TdtGwAT1YyuYn9GI9njAUdK0K9jzagDcBmCUr0P0AZinR2z7w1xffhWePLkVRN/z1Zifo2QsthdEk5XihohtLw+ibzHNJcTsZ7LkDAM/qrBtOdtu0hqLyXD7U7ZbEvP94URC+kQ3SZrmajA/qH58W47jAwCjFfplEct6PNeCZ8/WW5PJzUwkA0yS6fFwcfFPqb7eCTr3z9wwHgAgZ05g3tk+dOgPRu/a1ZGrqwqhTuXVEQEhE+4qdJbWwohty0665GA0OqSYaDeIYgDOep43dWRDw74ggOz/qerq8ey6fwNwOYD3QkSTg6WejMWmgUgiORBAhyBvY+BKAC4xzwsnEi/lLiD1rXveHmauBHBSZ74xX+JmbZLR6GhoWr1K4EPkeTeEGxqEZ3RJi2kKL3kNQJG/btIwDgL4igq1X7e5BtLtAOwA8G0AGQLmh217S2+ROByNTtE0TXYpZKcxnU7XBslNyjQXMrNUJBHwH6mO15l5ijgl5qfCicTSHolkGAJMxjqIaA8c59ZwY+PxoJ7qOc8w8xz17YWwbS8KdtEW0/wVMd+ndA7IcaxlQJJJpNHT9akj9+07mSd80nyEWzCYf8e6vjqXMX0yadIwx3HuV2B1vwcQzYtY1iu5vhRNlKOQyIpspFRV1WT2vD+rsvqUNG1qcGwfqay8xA2FNoFoQY5Dm5lf1oAUE0liy/i/IdtJGdieSacXBo8iaRjfQGezktb9GYgWkU/jSkvrwCwERErw4XAicS/5g/Rz8bkm86MA5gWOwQUgO+8SATCA6E4ZTj2O1jRXgvkh9fuOds+b7w8wlSi/VwOs1dO0746Mx4UbdpPU9ddfzpomvV96RucQ6i4nQLTVyWQeGLV/f1vw4+Hq6i9rnrcLzF/190u0tMKynvJBHKmurnBd93UAX1OGD0Zse22eRcA1NQM+aW8f5wA1BIwB0aUgErr3ITyv/vSZM2+PbW6WmdBDkoaxDMBj6kOLpmm15fH4v7pITYth/IaAu5TCu47jTMm3m6BnBrTeOESurqKOOwEY6ve6sG0vFtvPQZjmRGJ+GUAFAGnJt0dsW6bm/0VShjGbgT8AKAZwjIjmhi1rrzjvRnQD5fo+ue5N4cZGmS1fSJKGIWP71SxzY+CxiG2vyCZ/dxCdfX+XmiWycK+5UQgqlQtSWbLecSKaEbYsO+ujGwg1BUVZEkjkI0/Xa0fu23eokEVzdVuqqsrI8/4KQPqDzx/KI5HFtGWLlLYvPS4/agBJd7y2U4PWhMvL1+UaFQIoZRjLGXhElf8hnXl2cADmvQYqErNRgTzFwNwK295dyOKi2xqLVXlEkuxCiGVDP49Y1sNBP/lBSAhddyeI5E4pXfQVp7h4waj6+vb+ApF+0ppOyzBbpGwOqrnU42h7vZW3xGJziGiTIrDnifmOcCIh47df0mIYM6mzJIVAnyei5WHLkstVD+kVhOwk2dHxLAE/zO4Enjc90tAg/OOCIsSYOy9T1ynFrU5R0fzeInnBR5IjsdgEl0icddJ8oifC5eV39ZWkKdP8JTPLWBc5zpp2c0U8/mZvyC8Iwi9Z03wIzD9TDo5pwMxy25ZXmLySjEbHQdd3gDmiFJ4Oh8NLLgS8z+cif3Lq+mZ1vRe/luY4c/Nd9dS4l2k8TQF4kzxvXpBjBtH3CUIMFDEVhiQ3LamW1ZFEYk3QWUsstoKIpCeIdMhDS5BZ5Qtfv0AI8SkdPHg9E8nFSAhMijRtdi4DU4xJ5kP2ZaZOT6fv7O2dKhdMv0CIQdIwLiOibcwsL3hCu+Ku48ySce8/hLjuH7PHwMBb0LQZfb3aZYH0G4R/LN1r32/pEctarY7h1ypK7SBaHLEsyaN+SUEg/C7Y3r6BiZaId7kzeMA6DbibgavVii84RUW3FdJdCwIhi6hHErnyC7MWEWonFx3xdcB13Vuubmz8uF8hUEoFgxC7lGF8hwGpltzX3XNMNK/CsrYVAkBFtFAT4EBlZWj4wIFrCLhHveLKZfq3TlHR3YUcw0UlZi5cuUmlS0rqCLhFngC8AQMWBG9u/d3eRR1H1nkyFqsBkbzILQ3btlyaL0r+B7tw5ax4J5d3AAAAAElFTkSuQmCC";var S=document.createElement("div");S.id=s.default.generate(),S.style.position="absolute",t.appendChild(S);var x=null,C=null,A=null,T=new g({container:t,viewer:S})}Object.defineProperty(e,"__esModule",{value:!0});var o=function(){function t(t,e){var r=[],i=!0,n=!1,o=void 0;try{for(var a=t[Symbol.iterator](),s;!(i=(s=a.next()).done)&&(r.push(s.value),!e||r.length!==e);i=!0);}catch(t){n=!0,o=t}finally{try{!i&&a.return&&a.return()}finally{if(n)throw o}}return r}return function(e,r){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return t(e,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),a=r(30),s=i(a);r(38);var c=r(39),l=r(61),h=r(63),u=r(79),f=i(u),d=r(80),p=i(d);h.fabric.devicePixelRatio=1,c.PDFJS.disableTextLayer=!0;var g=c.PDFJS.PDFViewer,v=96/72;n.prototype=Object.create(f.default.prototype),n.prototype.constructor=n,e.default=n},function(t,e,r){"use strict";t.exports=r(31)},function(t,e,r){"use strict";function i(e){return s.seed(e),t.exports}function n(e){return f=e,t.exports}function o(t){return void 0!==t&&s.characters(t),s.shuffled()}function a(){return h(f)}var s=r(6),c=r(11),l=r(34),h=r(35),u=r(36),f=r(37)||0;t.exports=a,t.exports.generate=a,t.exports.seed=i,t.exports.worker=n,t.exports.characters=o,t.exports.decode=l,t.exports.isValid=u},function(t,e,r){"use strict";function i(){return(o=(9301*o+49297)%233280)/233280}function n(t){o=t}var o=1;t.exports={nextValue:i,seed:n}},function(t,e,r){"use strict";function i(){if(!n||!n.getRandomValues)return 48&Math.floor(256*Math.random());var t=new Uint8Array(1);return n.getRandomValues(t),48&t[0]}var n="object"==typeof window&&(window.crypto||window.msCrypto);t.exports=i},function(t,e,r){"use strict";function i(t){var e=n.shuffled();return{version:15&e.indexOf(t.substr(0,1)),worker:15&e.indexOf(t.substr(1,1))}}var n=r(6);t.exports=i},function(t,e,r){"use strict";function i(t){var e="",r=Math.floor(.001*(Date.now()-a));return r===l?c++:(c=0,l=r),e+=n(o.lookup,s),e+=n(o.lookup,t),c>0&&(e+=n(o.lookup,c)),e+=n(o.lookup,r)}var n=r(11),o=r(6),a=1459707606518,s=6,c,l;t.exports=i},function(t,e,r){"use strict";function i(t){if(!t||"string"!=typeof t||t.length<6)return!1;for(var e=n.characters(),r=t.length,i=0;i<r;i++)if(-1===e.indexOf(t[i]))return!1;return!0}var n=r(6);t.exports=i},function(t,e,r){"use strict";t.exports=0},function(t,e,r){(function(e){!function e(r,i){t.exports=i()}(this,function(){return function(t){function e(i){if(r[i])return r[i].exports;var n=r[i]={i:i,l:!1,exports:{}};return t[i].call(n.exports,n,n.exports,e),n.l=!0,n.exports}var r={};return e.m=t,e.c=r,e.i=function(t){return t},e.d=function(t,r,i){e.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var r=t&&t.__esModule?function e(){return t.default}:function e(){return t};return e.d(r,"a",r),r},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=1)}([function(t,r,i){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};if("undefined"==typeof PDFJS||!PDFJS.compatibilityChecked){var o="undefined"!=typeof window&&window.Math===Math?window:void 0!==e&&e.Math===Math?e:"undefined"!=typeof self&&self.Math===Math?self:void 0,a="undefined"!=typeof navigator&&navigator.userAgent||"",s=/Android/.test(a),c=/Android\s[0-2][^\d]/.test(a),l=/Android\s[0-4][^\d]/.test(a),h=a.indexOf("Chrom")>=0,u=/Chrome\/(39|40)\./.test(a),f=a.indexOf("CriOS")>=0,d=a.indexOf("Trident")>=0,p=/\b(iPad|iPhone|iPod)(?=;)/.test(a),g=a.indexOf("Opera")>=0,v=/Safari\//.test(a)&&!/(Chrome\/|Android\s)/.test(a),m="object"===("undefined"==typeof window?"undefined":n(window))&&"object"===("undefined"==typeof document?"undefined":n(document));"undefined"==typeof PDFJS&&(o.PDFJS={}),PDFJS.compatibilityChecked=!0,function t(){function e(t,e){return new c(this.slice(t,e))}function r(t,e){arguments.length<2&&(e=0);for(var r=0,i=t.length;r<i;++r,++e)this[e]=255&t[r]}function i(t,e){this.buffer=t,this.byteLength=t.length,this.length=e,s(this.length)}function a(t){return{get:function e(){var r=this.buffer,i=t<<2;return(r[i]|r[i+1]<<8|r[i+2]<<16|r[i+3]<<24)>>>0},set:function e(r){var i=this.buffer,n=t<<2;i[n]=255&r,i[n+1]=r>>8&255,i[n+2]=r>>16&255,i[n+3]=r>>>24&255}}}function s(t){for(;l<t;)Object.defineProperty(i.prototype,l,a(l)),l++}function c(t){var i,o,a;if("number"==typeof t)for(i=[],o=0;o<t;++o)i[o]=0;else if("slice"in t)i=t.slice(0);else for(i=[],o=0,a=t.length;o<a;++o)i[o]=t[o];return i.subarray=e,i.buffer=i,i.byteLength=i.length,i.set=r,"object"===(void 0===t?"undefined":n(t))&&t.buffer&&(i.buffer=t.buffer),i}if("undefined"!=typeof Uint8Array)return void 0===Uint8Array.prototype.subarray&&(Uint8Array.prototype.subarray=function t(e,r){return new Uint8Array(this.slice(e,r))},Float32Array.prototype.subarray=function t(e,r){return new Float32Array(this.slice(e,r))}),void("undefined"==typeof Float64Array&&(o.Float64Array=Float32Array));i.prototype=Object.create(null);var l=0;o.Uint8Array=c,o.Int8Array=c,o.Int32Array=c,o.Uint16Array=c,o.Float32Array=c,o.Float64Array=c,o.Uint32Array=function(){if(3===arguments.length){if(0!==arguments[1])throw new Error("offset !== 0 is not supported");return new i(arguments[0],arguments[2])}return c.apply(this,arguments)}}(),function t(){if(m&&window.CanvasPixelArray){var e=window.CanvasPixelArray.prototype;"buffer"in e||(Object.defineProperty(e,"buffer",{get:function t(){return this},enumerable:!1,configurable:!0}),Object.defineProperty(e,"byteLength",{get:function t(){return this.length},enumerable:!1,configurable:!0}))}}(),function t(){o.URL||(o.URL=o.webkitURL)}(),function t(){if(void 0!==Object.defineProperty){var e=!0;try{m&&Object.defineProperty(new Image,"id",{value:"test"});var r=function t(){};r.prototype={get id(){}},Object.defineProperty(new r,"id",{value:"",configurable:!0,enumerable:!0,writable:!1})}catch(t){e=!1}if(e)return}Object.defineProperty=function t(e,r,i){delete e[r],"get"in i&&e.__defineGetter__(r,i.get),"set"in i&&e.__defineSetter__(r,i.set),"value"in i&&(e.__defineSetter__(r,function t(e){return this.__defineGetter__(r,function t(){return e}),e}),e[r]=i.value)}}(),function t(){if("undefined"!=typeof XMLHttpRequest){var e=XMLHttpRequest.prototype,r=new XMLHttpRequest;if("overrideMimeType"in r||Object.defineProperty(e,"overrideMimeType",{value:function t(e){}}),!("responseType"in r)){if(Object.defineProperty(e,"responseType",{get:function t(){return this._responseType||"text"},set:function t(e){"text"!==e&&"arraybuffer"!==e||(this._responseType=e,"arraybuffer"===e&&"function"==typeof this.overrideMimeType&&this.overrideMimeType("text/plain; charset=x-user-defined"))}}),"undefined"!=typeof VBArray)return void Object.defineProperty(e,"response",{get:function t(){return"arraybuffer"===this.responseType?new Uint8Array(new VBArray(this.responseBody).toArray()):this.responseText}});Object.defineProperty(e,"response",{get:function t(){if("arraybuffer"!==this.responseType)return this.responseText;var e=this.responseText,r,i=e.length,n=new Uint8Array(i);for(r=0;r<i;++r)n[r]=255&e.charCodeAt(r);return n.buffer}})}}}(),function t(){if(!("btoa"in o)){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";o.btoa=function(t){var r="",i,n;for(i=0,n=t.length;i<n;i+=3){var o=255&t.charCodeAt(i),a=255&t.charCodeAt(i+1),s=255&t.charCodeAt(i+2),c=o>>2,l=(3&o)<<4|a>>4,h=i+1<n?(15&a)<<2|s>>6:64,u=i+2<n?63&s:64;r+=e.charAt(c)+e.charAt(l)+e.charAt(h)+e.charAt(u)}return r}}}(),function t(){if(!("atob"in o)){o.atob=function(t){if(t=t.replace(/=+$/,""),t.length%4==1)throw new Error("bad atob input");for(var e=0,r,i,n=0,o="";i=t.charAt(n++);~i&&(r=e%4?64*r+i:i,e++%4)?o+=String.fromCharCode(255&r>>(-2*e&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return o}}}(),function t(){void 0===Function.prototype.bind&&(Function.prototype.bind=function t(e){var r=this,i=Array.prototype.slice.call(arguments,1);return function t(){var n=i.concat(Array.prototype.slice.call(arguments));return r.apply(e,n)}})}(),function t(){if(m){"dataset"in document.createElement("div")||Object.defineProperty(HTMLElement.prototype,"dataset",{get:function t(){if(this._dataset)return this._dataset;for(var e={},r=0,i=this.attributes.length;r<i;r++){var n=this.attributes[r];if("data-"===n.name.substring(0,5)){e[n.name.substring(5).replace(/\-([a-z])/g,function(t,e){return e.toUpperCase()})]=n.value}}return Object.defineProperty(this,"_dataset",{value:e,writable:!1,enumerable:!1}),e},enumerable:!0})}}(),function t(){function e(t,e,r,i){var n=t.className||"",o=n.split(/\s+/g);""===o[0]&&o.shift();var a=o.indexOf(e);return a<0&&r&&o.push(e),a>=0&&i&&o.splice(a,1),t.className=o.join(" "),a>=0}if(m){if(!("classList"in document.createElement("div"))){var r={add:function t(r){e(this.element,r,!0,!1)},contains:function t(r){return e(this.element,r,!1,!1)},remove:function t(r){e(this.element,r,!1,!0)},toggle:function t(r){e(this.element,r,!0,!0)}};Object.defineProperty(HTMLElement.prototype,"classList",{get:function t(){if(this._classList)return this._classList;var e=Object.create(r,{element:{value:this,writable:!1,enumerable:!0}});return Object.defineProperty(this,"_classList",{value:e,writable:!1,enumerable:!1}),e},enumerable:!0})}}}(),function t(){if(!("undefined"==typeof importScripts||"console"in o)){var e={},r={log:function t(){var e=Array.prototype.slice.call(arguments);o.postMessage({targetName:"main",action:"console_log",data:e})},error:function t(){var e=Array.prototype.slice.call(arguments);o.postMessage({targetName:"main",action:"console_error",data:e})},time:function t(r){e[r]=Date.now()},timeEnd:function t(r){var i=e[r];if(!i)throw new Error("Unknown timer name "+r);this.log("Timer:",r,Date.now()-i)}};o.console=r}}(),function t(){if(m)"console"in window?"bind"in console.log||(console.log=function(t){return function(e){return t(e)}}(console.log),console.error=function(t){return function(e){return t(e)}}(console.error),console.warn=function(t){return function(e){return t(e)}}(console.warn)):window.console={log:function t(){},error:function t(){},warn:function t(){}}}(),function t(){function e(t){r(t.target)&&t.stopPropagation()}function r(t){return t.disabled||t.parentNode&&r(t.parentNode)}g&&document.addEventListener("click",e,!0)}(),function t(){(d||f)&&(PDFJS.disableCreateObjectURL=!0)}(),function t(){"undefined"!=typeof navigator&&("language"in navigator||(PDFJS.locale=navigator.userLanguage||"en-US"))}(),function t(){(v||c||u||p)&&(PDFJS.disableRange=!0,PDFJS.disableStream=!0)}(),function t(){m&&(history.pushState&&!c||(PDFJS.disableHistory=!0))}(),function t(){if(m)if(window.CanvasPixelArray)"function"!=typeof window.CanvasPixelArray.prototype.set&&(window.CanvasPixelArray.prototype.set=function(t){for(var e=0,r=this.length;e<r;e++)this[e]=t[e]});else{var e=!1,r;if(h?(r=a.match(/Chrom(e|ium)\/([0-9]+)\./),e=r&&parseInt(r[2])<21):s?e=l:v&&(r=a.match(/Version\/([0-9]+)\.([0-9]+)\.([0-9]+) Safari\//),e=r&&parseInt(r[1])<6),e){var i=window.CanvasRenderingContext2D.prototype,n=i.createImageData;i.createImageData=function(t,e){var r=n.call(this,t,e);return r.data.set=function(t){for(var e=0,r=this.length;e<r;e++)this[e]=t[e]},r},i=null}}}(),function t(){function e(){window.requestAnimationFrame=function(t){return window.setTimeout(t,20)},window.cancelAnimationFrame=function(t){window.clearTimeout(t)}}if(m)p?e():"requestAnimationFrame"in window||(window.requestAnimationFrame=window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame,window.requestAnimationFrame||e())}(),function t(){(p||s)&&(PDFJS.maxCanvasPixels=5242880)}(),function t(){m&&d&&window.parent!==window&&(PDFJS.disableFullscreen=!0)}(),function t(){m&&("currentScript"in document||Object.defineProperty(document,"currentScript",{get:function t(){var e=document.getElementsByTagName("script");return e[e.length-1]},enumerable:!0,configurable:!0}))}(),function t(){if(m){var e=document.createElement("input");try{e.type="number"}catch(t){var r=e.constructor.prototype,i=Object.getOwnPropertyDescriptor(r,"type");Object.defineProperty(r,"type",{get:function t(){return i.get.call(this)},set:function t(e){i.set.call(this,"number"===e?"text":e)},enumerable:!0,configurable:!0})}}}(),function t(){if(m&&document.attachEvent){var e=document.constructor.prototype,r=Object.getOwnPropertyDescriptor(e,"readyState");Object.defineProperty(e,"readyState",{get:function t(){var e=r.get.call(this);return"interactive"===e?"loading":e},set:function t(e){r.set.call(this,e)},enumerable:!0,configurable:!0})}}(),function t(){m&&void 0===Element.prototype.remove&&(Element.prototype.remove=function(){this.parentNode&&this.parentNode.removeChild(this)})}(),function t(){Number.isNaN||(Number.isNaN=function(t){return"number"==typeof t&&isNaN(t)})}(),function t(){Number.isInteger||(Number.isInteger=function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t})}(),function t(){if(o.Promise)return"function"!=typeof o.Promise.all&&(o.Promise.all=function(t){var e=0,r=[],i,n,a=new o.Promise(function(t,e){i=t,n=e});return t.forEach(function(t,o){e++,t.then(function(t){r[o]=t,0===--e&&i(r)},n)}),0===e&&i(r),a}),"function"!=typeof o.Promise.resolve&&(o.Promise.resolve=function(t){return new o.Promise(function(e){e(t)})}),"function"!=typeof o.Promise.reject&&(o.Promise.reject=function(t){return new o.Promise(function(e,r){r(t)})}),void("function"!=typeof o.Promise.prototype.catch&&(o.Promise.prototype.catch=function(t){return o.Promise.prototype.then(void 0,t)}));var e=0,r=1,i=2,n=500,a={handlers:[],running:!1,unhandledRejections:[],pendingRejectionCheck:!1,scheduleHandlers:function t(e){0!==e._status&&(this.handlers=this.handlers.concat(e._handlers),e._handlers=[],this.running||(this.running=!0,setTimeout(this.runHandlers.bind(this),0)))},runHandlers:function t(){for(var e=1,r=Date.now()+1;this.handlers.length>0;){var n=this.handlers.shift(),o=n.thisPromise._status,a=n.thisPromise._value;try{1===o?"function"==typeof n.onResolve&&(a=n.onResolve(a)):"function"==typeof n.onReject&&(a=n.onReject(a),o=1,n.thisPromise._unhandledRejection&&this.removeUnhandeledRejection(n.thisPromise))}catch(t){o=i,a=t}if(n.nextPromise._updateStatus(o,a),Date.now()>=r)break}if(this.handlers.length>0)return void setTimeout(this.runHandlers.bind(this),0);this.running=!1},addUnhandledRejection:function t(e){this.unhandledRejections.push({promise:e,time:Date.now()}),this.scheduleRejectionCheck()},removeUnhandeledRejection:function t(e){e._unhandledRejection=!1;for(var r=0;r<this.unhandledRejections.length;r++)this.unhandledRejections[r].promise===e&&(this.unhandledRejections.splice(r),r--)},scheduleRejectionCheck:function t(){var e=this;this.pendingRejectionCheck||(this.pendingRejectionCheck=!0,setTimeout(function(){e.pendingRejectionCheck=!1;for(var t=Date.now(),r=0;r<e.unhandledRejections.length;r++)if(t-e.unhandledRejections[r].time>500){var i=e.unhandledRejections[r].promise._value,n="Unhandled rejection: "+i;i.stack&&(n+="\n"+i.stack);try{throw new Error(n)}catch(t){console.warn(n)}e.unhandledRejections.splice(r),r--}e.unhandledRejections.length&&e.scheduleRejectionCheck()},500))}},s=function t(e){this._status=0,this._handlers=[];try{e.call(this,this._resolve.bind(this),this._reject.bind(this))}catch(t){this._reject(t)}};s.all=function t(e){function r(t){a._status!==i&&(l=[],o(t))}var n,o,a=new s(function(t,e){n=t,o=e}),c=e.length,l=[];if(0===c)return n(l),a;for(var h=0,u=e.length;h<u;++h){var f=e[h],d=function(t){return function(e){a._status!==i&&(l[t]=e,0===--c&&n(l))}}(h);s.isPromise(f)?f.then(d,r):d(f)}return a},s.isPromise=function t(e){return e&&"function"==typeof e.then},s.resolve=function t(e){return new s(function(t){t(e)})},s.reject=function t(e){return new s(function(t,r){r(e)})},s.prototype={_status:null,_value:null,_handlers:null,_unhandledRejection:null,_updateStatus:function t(e,r){if(1!==this._status&&this._status!==i){if(1===e&&s.isPromise(r))return void r.then(this._updateStatus.bind(this,1),this._updateStatus.bind(this,i));this._status=e,this._value=r,e===i&&0===this._handlers.length&&(this._unhandledRejection=!0,a.addUnhandledRejection(this)),a.scheduleHandlers(this)}},_resolve:function t(e){this._updateStatus(1,e)},_reject:function t(e){this._updateStatus(i,e)},then:function t(e,r){var i=new s(function(t,e){this.resolve=t,this.reject=e});return this._handlers.push({thisPromise:this,onResolve:e,onReject:r,nextPromise:i}),a.scheduleHandlers(this),i},catch:function t(e){return this.then(void 0,e)}},o.Promise=s}(),function t(){function e(){this.id="$weakmap"+r++}if(!o.WeakMap){var r=0;e.prototype={has:function t(e){return("object"===(void 0===e?"undefined":n(e))||"function"==typeof e)&&null!==e&&!!Object.getOwnPropertyDescriptor(e,this.id)},get:function t(e){return this.has(e)?e[this.id]:void 0},set:function t(e,r){Object.defineProperty(e,this.id,{value:r,enumerable:!1,configurable:!0})},delete:function t(e){delete e[this.id]}},o.WeakMap=e}}(),function t(){function e(t){return void 0!==d[t]}function r(){l.call(this),this._isInvalid=!0}function i(t){return""===t&&r.call(this),t.toLowerCase()}function a(t){var e=t.charCodeAt(0);return e>32&&e<127&&-1===[34,35,60,62,63,96].indexOf(e)?t:encodeURIComponent(t)}function s(t){var e=t.charCodeAt(0);return e>32&&e<127&&-1===[34,35,60,62,96].indexOf(e)?t:encodeURIComponent(t)}function c(t,n,o){function c(t){y.push(t)}var l=n||"scheme start",h=0,u="",f=!1,b=!1,y=[];t:for(;(t[h-1]!==g||0===h)&&!this._isInvalid;){var _=t[h];switch(l){case"scheme start":if(!_||!v.test(_)){if(n){c("Invalid scheme.");break t}u="",l="no scheme";continue}u+=_.toLowerCase(),l="scheme";break;case"scheme":if(_&&m.test(_))u+=_.toLowerCase();else{if(":"!==_){if(n){if(_===g)break t;c("Code point not allowed in scheme: "+_);break t}u="",h=0,l="no scheme";continue}if(this._scheme=u,u="",n)break t;e(this._scheme)&&(this._isRelative=!0),l="file"===this._scheme?"relative":this._isRelative&&o&&o._scheme===this._scheme?"relative or authority":this._isRelative?"authority first slash":"scheme data"}break;case"scheme data":"?"===_?(this._query="?",l="query"):"#"===_?(this._fragment="#",l="fragment"):_!==g&&"\t"!==_&&"\n"!==_&&"\r"!==_&&(this._schemeData+=a(_));break;case"no scheme":if(o&&e(o._scheme)){l="relative";continue}c("Missing scheme."),r.call(this);break;case"relative or authority":if("/"!==_||"/"!==t[h+1]){c("Expected /, got: "+_),l="relative";continue}l="authority ignore slashes";break;case"relative":if(this._isRelative=!0,"file"!==this._scheme&&(this._scheme=o._scheme),_===g){this._host=o._host,this._port=o._port,this._path=o._path.slice(),this._query=o._query,this._username=o._username,this._password=o._password;break t}if("/"===_||"\\"===_)"\\"===_&&c("\\ is an invalid code point."),l="relative slash";else if("?"===_)this._host=o._host,this._port=o._port,this._path=o._path.slice(),this._query="?",this._username=o._username,this._password=o._password,l="query";else{if("#"!==_){var w=t[h+1],S=t[h+2];("file"!==this._scheme||!v.test(_)||":"!==w&&"|"!==w||S!==g&&"/"!==S&&"\\"!==S&&"?"!==S&&"#"!==S)&&(this._host=o._host,this._port=o._port,this._username=o._username,this._password=o._password,this._path=o._path.slice(),this._path.pop()),l="relative path";continue}this._host=o._host,this._port=o._port,this._path=o._path.slice(),this._query=o._query,this._fragment="#",this._username=o._username,this._password=o._password,l="fragment"}break;case"relative slash":if("/"!==_&&"\\"!==_){"file"!==this._scheme&&(this._host=o._host,this._port=o._port,this._username=o._username,this._password=o._password),l="relative path";continue}"\\"===_&&c("\\ is an invalid code point."),l="file"===this._scheme?"file host":"authority ignore slashes";break;case"authority first slash":if("/"!==_){c("Expected '/', got: "+_),l="authority ignore slashes";continue}l="authority second slash";break;case"authority second slash":if(l="authority ignore slashes","/"!==_){c("Expected '/', got: "+_);continue}break;case"authority ignore slashes":if("/"!==_&&"\\"!==_){l="authority";continue}c("Expected authority, got: "+_);break;case"authority":if("@"===_){f&&(c("@ already seen."),u+="%40"),f=!0;for(var x=0;x<u.length;x++){var C=u[x];if("\t"!==C&&"\n"!==C&&"\r"!==C)if(":"!==C||null!==this._password){var A=a(C);null!==this._password?this._password+=A:this._username+=A}else this._password="";else c("Invalid whitespace in authority.")}u=""}else{if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_){h-=u.length,u="",l="host";continue}u+=_}break;case"file host":if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_){2!==u.length||!v.test(u[0])||":"!==u[1]&&"|"!==u[1]?0===u.length?l="relative path start":(this._host=i.call(this,u),u="",l="relative path start"):l="relative path";continue}"\t"===_||"\n"===_||"\r"===_?c("Invalid whitespace in file host."):u+=_;break;case"host":case"hostname":if(":"!==_||b){if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_){if(this._host=i.call(this,u),u="",l="relative path start",n)break t;continue}"\t"!==_&&"\n"!==_&&"\r"!==_?("["===_?b=!0:"]"===_&&(b=!1),u+=_):c("Invalid code point in host/hostname: "+_)}else if(this._host=i.call(this,u),u="",l="port","hostname"===n)break t;break;case"port":if(/[0-9]/.test(_))u+=_;else{if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_||n){if(""!==u){var T=parseInt(u,10);T!==d[this._scheme]&&(this._port=T+""),u=""}if(n)break t;l="relative path start";continue}"\t"===_||"\n"===_||"\r"===_?c("Invalid code point in port: "+_):r.call(this)}break;case"relative path start":if("\\"===_&&c("'\\' not allowed in path."),l="relative path","/"!==_&&"\\"!==_)continue;break;case"relative path":if(_!==g&&"/"!==_&&"\\"!==_&&(n||"?"!==_&&"#"!==_))"\t"!==_&&"\n"!==_&&"\r"!==_&&(u+=a(_));else{"\\"===_&&c("\\ not allowed in relative path.");var k;(k=p[u.toLowerCase()])&&(u=k),".."===u?(this._path.pop(),"/"!==_&&"\\"!==_&&this._path.push("")):"."===u&&"/"!==_&&"\\"!==_?this._path.push(""):"."!==u&&("file"===this._scheme&&0===this._path.length&&2===u.length&&v.test(u[0])&&"|"===u[1]&&(u=u[0]+":"),this._path.push(u)),u="","?"===_?(this._query="?",l="query"):"#"===_&&(this._fragment="#",l="fragment")}break;case"query":n||"#"!==_?_!==g&&"\t"!==_&&"\n"!==_&&"\r"!==_&&(this._query+=s(_)):(this._fragment="#",l="fragment");break;case"fragment":_!==g&&"\t"!==_&&"\n"!==_&&"\r"!==_&&(this._fragment+=_)}h++}}function l(){this._scheme="",this._schemeData="",this._username="",this._password=null,this._host="",this._port="",this._path=[],this._query="",this._fragment="",this._isInvalid=!1,this._isRelative=!1}function h(t,e){void 0===e||e instanceof h||(e=new h(String(e))),this._url=t,l.call(this);var r=t.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g,"");c.call(this,r,null,e)}var u=!1;try{if("function"==typeof URL&&"object"===n(URL.prototype)&&"origin"in URL.prototype){var f=new URL("b","http://a");f.pathname="c%20d",u="http://a/c%20d"===f.href}}catch(t){}if(!u){var d=Object.create(null);d.ftp=21,d.file=0,d.gopher=70,d.http=80,d.https=443,d.ws=80,d.wss=443;var p=Object.create(null);p["%2e"]=".",p[".%2e"]="..",p["%2e."]="..",p["%2e%2e"]="..";var g,v=/[a-zA-Z]/,m=/[a-zA-Z0-9\+\-\.]/;h.prototype={toString:function t(){return this.href},get href(){if(this._isInvalid)return this._url;var t="";return""===this._username&&null===this._password||(t=this._username+(null!==this._password?":"+this._password:"")+"@"),this.protocol+(this._isRelative?"//"+t+this.host:"")+this.pathname+this._query+this._fragment},set href(t){l.call(this),c.call(this,t)},get protocol(){return this._scheme+":"},set protocol(t){this._isInvalid||c.call(this,t+":","scheme start")},get host(){return this._isInvalid?"":this._port?this._host+":"+this._port:this._host},set host(t){!this._isInvalid&&this._isRelative&&c.call(this,t,"host")},get hostname(){return this._host},set hostname(t){!this._isInvalid&&this._isRelative&&c.call(this,t,"hostname")},get port(){return this._port},set port(t){!this._isInvalid&&this._isRelative&&c.call(this,t,"port")},get pathname(){return this._isInvalid?"":this._isRelative?"/"+this._path.join("/"):this._schemeData},set pathname(t){!this._isInvalid&&this._isRelative&&(this._path=[],c.call(this,t,"relative path start"))},get search(){return this._isInvalid||!this._query||"?"===this._query?"":this._query},set search(t){!this._isInvalid&&this._isRelative&&(this._query="?","?"===t[0]&&(t=t.slice(1)),c.call(this,t,"query"))},get hash(){return this._isInvalid||!this._fragment||"#"===this._fragment?"":this._fragment},set hash(t){this._isInvalid||(this._fragment="#","#"===t[0]&&(t=t.slice(1)),c.call(this,t,"fragment"))},get origin(){var t;if(this._isInvalid||!this._scheme)return"";switch(this._scheme){case"data":case"file":case"javascript":case"mailto":return"null";case"blob":try{return new h(this._schemeData).origin||"null"}catch(t){}return"null"}return t=this.host,t?this._scheme+"://"+t:""}};var b=o.URL;b&&(h.createObjectURL=function(t){return b.createObjectURL.apply(b,arguments)},h.revokeObjectURL=function(t){b.revokeObjectURL(t)}),o.URL=h}}()}},function(t,e,r){"use strict";r(0)}])})}).call(e,r(0))},function(t,e,r){!function e(r,i){t.exports=i()}(this,function(){return function(t){function e(i){if(r[i])return r[i].exports;var n=r[i]={i:i,l:!1,exports:{}};return t[i].call(n.exports,n,n.exports,e),n.l=!0,n.exports}var r={};return e.m=t,e.c=r,e.i=function(t){return t},e.d=function(t,r,i){e.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var r=t&&t.__esModule?function e(){return t.default}:function e(){return t};return e.d(r,"a",r),r},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=14)}([function(t,e,i){"use strict";var n;n="undefined"!=typeof window&&window["pdfjs-dist/build/pdf"]?window["pdfjs-dist/build/pdf"]:r(12),t.exports=n},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){return e?t.replace(/\{\{\s*(\w+)\s*\}\}/g,function(t,r){return r in e?e[r]:"{{"+r+"}}"}):t}function o(t){var e=window.devicePixelRatio||1,r=t.webkitBackingStorePixelRatio||t.mozBackingStorePixelRatio||t.msBackingStorePixelRatio||t.oBackingStorePixelRatio||t.backingStorePixelRatio||1,i=e/r;return{sx:i,sy:i,scaled:1!==i}}function a(t,e){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=t.offsetParent;if(!i)return void console.error("offsetParent is not set -- cannot scroll");for(var n=t.offsetTop+t.clientTop,o=t.offsetLeft+t.clientLeft;i.clientHeight===i.scrollHeight||r&&"hidden"===getComputedStyle(i).overflow;)if(i.dataset._scaleY&&(n/=i.dataset._scaleY,o/=i.dataset._scaleX),n+=i.offsetTop,o+=i.offsetLeft,!(i=i.offsetParent))return;e&&(void 0!==e.top&&(n+=e.top),void 0!==e.left&&(o+=e.left,i.scrollLeft=o)),i.scrollTop=n}function s(t,e){var r=function r(o){n||(n=window.requestAnimationFrame(function r(){n=null;var o=t.scrollTop,a=i.lastY;o!==a&&(i.down=o>a),i.lastY=o,e(i)}))},i={down:!0,lastY:t.scrollTop,_eventHandler:r},n=null;return t.addEventListener("scroll",r,!0),i}function c(t){for(var e=t.split("&"),r=Object.create(null),i=0,n=e.length;i<n;++i){var o=e[i].split("="),a=o[0].toLowerCase(),s=o.length>1?o[1]:null;r[decodeURIComponent(a)]=decodeURIComponent(s)}return r}function l(t,e){var r=0,i=t.length-1;if(0===t.length||!e(t[i]))return t.length;if(e(t[r]))return r;for(;r<i;){var n=r+i>>1;e(t[n])?i=n:r=n+1}return r}function h(t){if(Math.floor(t)===t)return[t,1];var e=1/t,r=8;if(e>8)return[1,8];if(Math.floor(e)===e)return[1,e];for(var i=t>1?e:t,n=0,o=1,a=1,s=1;;){var c=n+a,l=o+s;if(l>8)break;i<=c/l?(a=c,s=l):(n=c,o=l)}var h=void 0;return h=i-n/o<a/s-i?i===t?[n,o]:[o,n]:i===t?[a,s]:[s,a]}function u(t,e){var r=t%e;return 0===r?t:Math.round(t-r+e)}function f(t,e){function r(t){var e=t.div;return e.offsetTop+e.clientTop+e.clientHeight>n}for(var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=t.scrollTop,o=n+t.clientHeight,a=t.scrollLeft,s=a+t.clientWidth,c=[],h=void 0,u=void 0,f=void 0,d=void 0,p=void 0,g=void 0,v=void 0,m=void 0,b=0===e.length?0:l(e,r),y=b,_=e.length;y<_&&(h=e[y],u=h.div,f=u.offsetTop+u.clientTop,d=u.clientHeight,!(f>o));y++)v=u.offsetLeft+u.clientLeft,m=u.clientWidth,v+m<a||v>s||(p=Math.max(0,n-f)+Math.max(0,f+d-o),g=100*(d-p)/d|0,c.push({id:h.id,x:v,y:f,view:h,percent:g}));var w=c[0],S=c[c.length-1];return i&&c.sort(function(t,e){var r=t.percent-e.percent;return Math.abs(r)>.001?-r:t.id-e.id}),{first:w,last:S,views:c}}function d(t){t.preventDefault()}function p(t){for(var e=0,r=t.length;e<r&&""===t[e].trim();)e++;return"data:"===t.substr(e,5).toLowerCase()}function g(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"document.pdf";if(p(t))return console.warn('getPDFFileNameFromURL: ignoring "data:" URL for performance reasons.'),e;var r=/^(?:(?:[^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/,i=/[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i,n=r.exec(t),o=i.exec(n[1])||i.exec(n[2])||i.exec(n[3]);if(o&&(o=o[0],-1!==o.indexOf("%")))try{o=i.exec(decodeURIComponent(o))[0]}catch(t){}return o||e}function v(t){var e=Math.sqrt(t.deltaX*t.deltaX+t.deltaY*t.deltaY),r=Math.atan2(t.deltaY,t.deltaX);-.25*Math.PI<r&&r<.75*Math.PI&&(e=-e);var i=0,n=1,o=30,a=30;return 0===t.deltaMode?e/=900:1===t.deltaMode&&(e/=30),e}function m(t){var e=Object.create(null);for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e}function b(t,e,r){return Math.min(Math.max(t,e),r)}Object.defineProperty(e,"__esModule",{value:!0}),e.localized=e.animationStarted=e.normalizeWheelEventDelta=e.binarySearchFirstItem=e.watchScroll=e.scrollIntoView=e.getOutputScale=e.approximateFraction=e.roundToDivide=e.getVisibleElements=e.parseQueryString=e.noContextMenuHandler=e.getPDFFileNameFromURL=e.ProgressBar=e.EventBus=e.NullL10n=e.mozL10n=e.RendererType=e.cloneObj=e.VERTICAL_PADDING=e.SCROLLBAR_PADDING=e.MAX_AUTO_SCALE=e.UNKNOWN_SCALE=e.MAX_SCALE=e.MIN_SCALE=e.DEFAULT_SCALE=e.DEFAULT_SCALE_VALUE=e.CSS_UNITS=void 0;var y=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),_=r(0),w=96/72,S="auto",x=1,C=.25,A=10,T=0,k=1.25,P=40,E=5,O={CANVAS:"canvas",SVG:"svg"},R={get:function t(e,r,i){return Promise.resolve(n(i,r))},translate:function t(e){return Promise.resolve()}};_.PDFJS.disableFullscreen=void 0!==_.PDFJS.disableFullscreen&&_.PDFJS.disableFullscreen,_.PDFJS.useOnlyCssZoom=void 0!==_.PDFJS.useOnlyCssZoom&&_.PDFJS.useOnlyCssZoom,_.PDFJS.maxCanvasPixels=void 0===_.PDFJS.maxCanvasPixels?16777216:_.PDFJS.maxCanvasPixels,_.PDFJS.disableHistory=void 0!==_.PDFJS.disableHistory&&_.PDFJS.disableHistory,_.PDFJS.disableTextLayer=void 0!==_.PDFJS.disableTextLayer&&_.PDFJS.disableTextLayer,_.PDFJS.ignoreCurrentPositionOnZoom=void 0!==_.PDFJS.ignoreCurrentPositionOnZoom&&_.PDFJS.ignoreCurrentPositionOnZoom,_.PDFJS.locale=void 0===_.PDFJS.locale&&"undefined"!=typeof navigator?navigator.language:_.PDFJS.locale;var L=new Promise(function(t){window.requestAnimationFrame(t)}),D=void 0,I=Promise.resolve(),j=function(){function t(){i(this,t),this._listeners=Object.create(null)}return y(t,[{key:"on",value:function t(e,r){var i=this._listeners[e];i||(i=[],this._listeners[e]=i),i.push(r)}},{key:"off",value:function t(e,r){var i=this._listeners[e],n=void 0;!i||(n=i.indexOf(r))<0||i.splice(n,1)}},{key:"dispatch",value:function t(e){var r=this._listeners[e];if(r&&0!==r.length){var i=Array.prototype.slice.call(arguments,1);r.slice(0).forEach(function(t){t.apply(null,i)})}}}]),t}(),M=function(){function t(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=r.height,o=r.width,a=r.units;i(this,t),this.visible=!0,this.div=document.querySelector(e+" .progress"),this.bar=this.div.parentNode,this.height=n||100,this.width=o||100,this.units=a||"%",this.div.style.height=this.height+this.units,this.percent=0}return y(t,[{key:"_updateBar",value:function t(){if(this._indeterminate)return this.div.classList.add("indeterminate"),void(this.div.style.width=this.width+this.units);this.div.classList.remove("indeterminate");var e=this.width*this._percent/100;this.div.style.width=e+this.units}},{key:"setWidth",value:function t(e){if(e){var r=e.parentNode,i=r.offsetWidth-e.offsetWidth;i>0&&this.bar.setAttribute("style","width: calc(100% - "+i+"px);")}}},{key:"hide",value:function t(){this.visible&&(this.visible=!1,this.bar.classList.add("hidden"),document.body.classList.remove("loadingInProgress"))}},{key:"show",value:function t(){this.visible||(this.visible=!0,document.body.classList.add("loadingInProgress"),this.bar.classList.remove("hidden"))}},{key:"percent",get:function t(){return this._percent},set:function t(e){this._indeterminate=isNaN(e),this._percent=b(e,0,100),this._updateBar()}}]),t}();e.CSS_UNITS=96/72,e.DEFAULT_SCALE_VALUE="auto",e.DEFAULT_SCALE=1,e.MIN_SCALE=.25,e.MAX_SCALE=10,e.UNKNOWN_SCALE=0,e.MAX_AUTO_SCALE=1.25,e.SCROLLBAR_PADDING=40,e.VERTICAL_PADDING=5,e.cloneObj=m,e.RendererType=O,e.mozL10n=void 0,e.NullL10n=R,e.EventBus=j,e.ProgressBar=M,e.getPDFFileNameFromURL=g,e.noContextMenuHandler=d,e.parseQueryString=c,e.getVisibleElements=f,e.roundToDivide=u,e.approximateFraction=h,e.getOutputScale=o,e.scrollIntoView=a,e.watchScroll=s,e.binarySearchFirstItem=l,e.normalizeWheelEventDelta=v,e.animationStarted=L,e.localized=I},function(t,e,r){"use strict";function i(t){t.on("documentload",function(){var t=document.createEvent("CustomEvent");t.initCustomEvent("documentload",!0,!0,{}),window.dispatchEvent(t)}),t.on("pagerendered",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("pagerendered",!0,!0,{pageNumber:t.pageNumber,cssTransform:t.cssTransform}),t.source.div.dispatchEvent(e)}),t.on("textlayerrendered",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("textlayerrendered",!0,!0,{pageNumber:t.pageNumber}),t.source.textLayerDiv.dispatchEvent(e)}),t.on("pagechange",function(t){var e=document.createEvent("UIEvents");e.initUIEvent("pagechange",!0,!0,window,0),e.pageNumber=t.pageNumber,t.source.container.dispatchEvent(e)}),t.on("pagesinit",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("pagesinit",!0,!0,null),t.source.container.dispatchEvent(e)}),t.on("pagesloaded",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("pagesloaded",!0,!0,{pagesCount:t.pagesCount}),t.source.container.dispatchEvent(e)}),t.on("scalechange",function(t){var e=document.createEvent("UIEvents");e.initUIEvent("scalechange",!0,!0,window,0),e.scale=t.scale,e.presetValue=t.presetValue,t.source.container.dispatchEvent(e)}),t.on("updateviewarea",function(t){var e=document.createEvent("UIEvents");e.initUIEvent("updateviewarea",!0,!0,window,0),e.location=t.location,t.source.container.dispatchEvent(e)}),t.on("find",function(t){if(t.source!==window){var e=document.createEvent("CustomEvent");e.initCustomEvent("find"+t.type,!0,!0,{query:t.query,phraseSearch:t.phraseSearch,caseSensitive:t.caseSensitive,highlightAll:t.highlightAll,findPrevious:t.findPrevious}),window.dispatchEvent(e)}}),t.on("attachmentsloaded",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("attachmentsloaded",!0,!0,{attachmentsCount:t.attachmentsCount}),t.source.container.dispatchEvent(e)}),t.on("sidebarviewchanged",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("sidebarviewchanged",!0,!0,{view:t.view}),t.source.outerContainer.dispatchEvent(e)}),t.on("pagemode",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("pagemode",!0,!0,{mode:t.mode}),t.source.pdfViewer.container.dispatchEvent(e)}),t.on("namedaction",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("namedaction",!0,!0,{action:t.action}),t.source.pdfViewer.container.dispatchEvent(e)}),t.on("presentationmodechanged",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("presentationmodechanged",!0,!0,{active:t.active,switchInProgress:t.switchInProgress}),window.dispatchEvent(e)}),t.on("outlineloaded",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("outlineloaded",!0,!0,{outlineCount:t.outlineCount}),t.source.container.dispatchEvent(e)})}function n(){return a||(a=new o.EventBus,i(a),a)}Object.defineProperty(e,"__esModule",{value:!0}),e.getGlobalEventBus=e.attachDOMEventsToEventBus=void 0;var o=r(1),a=null;e.attachDOMEventsToEventBus=i,e.getGlobalEventBus=n},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t){if(!(t instanceof Array))return!1;var e=t.length,r=!0;if(e<2)return!1;var i=t[0];if(!("object"===(void 0===i?"undefined":o(i))&&"number"==typeof i.num&&(0|i.num)===i.num&&"number"==typeof i.gen&&(0|i.gen)===i.gen||"number"==typeof i&&(0|i)===i&&i>=0))return!1;var n=t[1];if("object"!==(void 0===n?"undefined":o(n))||"string"!=typeof n.name)return!1;switch(n.name){case"XYZ":if(5!==e)return!1;break;case"Fit":case"FitB":return 2===e;case"FitH":case"FitBH":case"FitV":case"FitBV":if(3!==e)return!1;break;case"FitR":if(6!==e)return!1;r=!1;break;default:return!1}for(var a=2;a<e;a++){var s=t[a];if(!("number"==typeof s||r&&null===s))return!1}return!0}Object.defineProperty(e,"__esModule",{value:!0}),e.SimpleLinkService=e.PDFLinkService=void 0;var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},a=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),s=r(2),c=r(1),l=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=e.eventBus;i(this,t),this.eventBus=r||(0,s.getGlobalEventBus)(),this.baseUrl=null,this.pdfDocument=null,this.pdfViewer=null,this.pdfHistory=null,this._pagesRefCache=null}return a(t,[{key:"setDocument",value:function t(e,r){this.baseUrl=r,this.pdfDocument=e,this._pagesRefCache=Object.create(null)}},{key:"setViewer",value:function t(e){this.pdfViewer=e}},{key:"setHistory",value:function t(e){this.pdfHistory=e}},{key:"navigateTo",value:function t(e){var r=this,i=function t(i){var n=i.namedDest,o=i.explicitDest,a=o[0],s=void 0;if(a instanceof Object){if(null===(s=r._cachedPageNumber(a)))return void r.pdfDocument.getPageIndex(a).then(function(e){r.cachePageRef(e+1,a),t({namedDest:n,explicitDest:o})}).catch(function(){console.error('PDFLinkService.navigateTo: "'+a+'" is not a valid page reference, for dest="'+e+'".')})}else{if((0|a)!==a)return void console.error('PDFLinkService.navigateTo: "'+a+'" is not a valid destination reference, for dest="'+e+'".');s=a+1}if(!s||s<1||s>r.pagesCount)return void console.error('PDFLinkService.navigateTo: "'+s+'" is not a valid page number, for dest="'+e+'".');r.pdfViewer.scrollPageIntoView({pageNumber:s,destArray:o}),r.pdfHistory&&r.pdfHistory.push({dest:o,hash:n,page:s})};new Promise(function(t,i){if("string"==typeof e)return void r.pdfDocument.getDestination(e).then(function(r){t({namedDest:e,explicitDest:r})});t({namedDest:"",explicitDest:e})}).then(function(t){if(!(t.explicitDest instanceof Array))return void console.error('PDFLinkService.navigateTo: "'+t.explicitDest+'" is not a valid destination array, for dest="'+e+'".');i(t)})}},{key:"getDestinationHash",value:function t(e){if("string"==typeof e)return this.getAnchorUrl("#"+escape(e));if(e instanceof Array){var r=JSON.stringify(e);return this.getAnchorUrl("#"+escape(r))}return this.getAnchorUrl("")}},{key:"getAnchorUrl",value:function t(e){return(this.baseUrl||"")+e}},{key:"setHash",value:function t(e){var r=void 0,i=void 0;if(e.indexOf("=")>=0){var o=(0,c.parseQueryString)(e);if("search"in o&&this.eventBus.dispatch("findfromurlhash",{source:this,query:o.search.replace(/"/g,""),phraseSearch:"true"===o.phrase}),"nameddest"in o)return this.pdfHistory&&this.pdfHistory.updateNextHashParam(o.nameddest),void this.navigateTo(o.nameddest);if("page"in o&&(r=0|o.page||1),"zoom"in o){var a=o.zoom.split(","),s=a[0],l=parseFloat(s);-1===s.indexOf("Fit")?i=[null,{name:"XYZ"},a.length>1?0|a[1]:null,a.length>2?0|a[2]:null,l?l/100:s]:"Fit"===s||"FitB"===s?i=[null,{name:s}]:"FitH"===s||"FitBH"===s||"FitV"===s||"FitBV"===s?i=[null,{name:s},a.length>1?0|a[1]:null]:"FitR"===s?5!==a.length?console.error('PDFLinkService.setHash: Not enough parameters for "FitR".'):i=[null,{name:s},0|a[1],0|a[2],0|a[3],0|a[4]]:console.error('PDFLinkService.setHash: "'+s+'" is not a valid zoom value.')}i?this.pdfViewer.scrollPageIntoView({pageNumber:r||this.page,destArray:i,allowNegativeOffset:!0}):r&&(this.page=r),"pagemode"in o&&this.eventBus.dispatch("pagemode",{source:this,mode:o.pagemode})}else{/^\d+$/.test(e)&&e<=this.pagesCount&&(console.warn('PDFLinkService_setHash: specifying a page number directly after the hash symbol (#) is deprecated, please use the "#page='+e+'" form instead.'),this.page=0|e),i=unescape(e);try{i=JSON.parse(i),i instanceof Array||(i=i.toString())}catch(t){}if("string"==typeof i||n(i))return this.pdfHistory&&this.pdfHistory.updateNextHashParam(i),void this.navigateTo(i);console.error('PDFLinkService.setHash: "'+unescape(e)+'" is not a valid destination.')}}},{key:"executeNamedAction",value:function t(e){switch(e){case"GoBack":this.pdfHistory&&this.pdfHistory.back();break;case"GoForward":this.pdfHistory&&this.pdfHistory.forward();break;case"NextPage":this.page<this.pagesCount&&this.page++;break;case"PrevPage":this.page>1&&this.page--;break;case"LastPage":this.page=this.pagesCount;break;case"FirstPage":this.page=1}this.eventBus.dispatch("namedaction",{source:this,action:e})}},{key:"onFileAttachmentAnnotation",value:function t(e){var r=e.id,i=e.filename,n=e.content;this.eventBus.dispatch("fileattachmentannotation",{source:this,id:r,filename:i,content:n})}},{key:"cachePageRef",value:function t(e,r){var i=r.num+" "+r.gen+" R";this._pagesRefCache[i]=e}},{key:"_cachedPageNumber",value:function t(e){var r=e.num+" "+e.gen+" R";return this._pagesRefCache&&this._pagesRefCache[r]||null}},{key:"pagesCount",get:function t(){return this.pdfDocument?this.pdfDocument.numPages:0}},{key:"page",get:function t(){return this.pdfViewer.currentPageNumber},set:function t(e){this.pdfViewer.currentPageNumber=e}}]),t}(),h=function(){function t(){i(this,t)}return a(t,[{key:"navigateTo",value:function t(e){}},{key:"getDestinationHash",value:function t(e){return"#"}},{key:"getAnchorUrl",value:function t(e){return"#"}},{key:"setHash",value:function t(e){}},{key:"executeNamedAction",value:function t(e){}},{key:"onFileAttachmentAnnotation",value:function t(e){var r=e.id,i=e.filename,n=e.content}},{key:"cachePageRef",value:function t(e,r){}},{key:"page",get:function t(){return 0},set:function t(e){}}]),t}();e.PDFLinkService=l,e.SimpleLinkService=h},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.DefaultAnnotationLayerFactory=e.AnnotationLayerBuilder=void 0;var n=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),o=r(0),a=r(1),s=r(3),c=function(){function t(e){var r=e.pageDiv,n=e.pdfPage,o=e.linkService,s=e.downloadManager,c=e.renderInteractiveForms,l=void 0!==c&&c,h=e.l10n,u=void 0===h?a.NullL10n:h;i(this,t),this.pageDiv=r,this.pdfPage=n,this.linkService=o,this.downloadManager=s,this.renderInteractiveForms=l,this.l10n=u,this.div=null}return n(t,[{key:"render",value:function t(e){var r=this,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"display";this.pdfPage.getAnnotations({intent:i}).then(function(t){var i={viewport:e.clone({dontFlip:!0}),div:r.div,annotations:t,page:r.pdfPage,renderInteractiveForms:r.renderInteractiveForms,linkService:r.linkService,downloadManager:r.downloadManager};if(r.div)o.AnnotationLayer.update(i);else{if(0===t.length)return;r.div=document.createElement("div"),r.div.className="annotationLayer",r.pageDiv.appendChild(r.div),i.div=r.div,o.AnnotationLayer.render(i),r.l10n.translate(r.div)}})}},{key:"hide",value:function t(){this.div&&this.div.setAttribute("hidden","true")}}]),t}(),l=function(){function t(){i(this,t)}return n(t,[{key:"createAnnotationLayerBuilder",value:function t(e,r){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:a.NullL10n;return new c({pageDiv:e,pdfPage:r,renderInteractiveForms:i,linkService:new s.SimpleLinkService,l10n:n})}}]),t}();e.AnnotationLayerBuilder=c,e.DefaultAnnotationLayerFactory=l},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.PDFPageView=void 0;var n=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),o=r(1),a=r(0),s=r(2),c=r(7),l=function(){function t(e){i(this,t);var r=e.container,n=e.defaultViewport;this.id=e.id,this.renderingId="page"+this.id,this.pageLabel=null,this.rotation=0,this.scale=e.scale||o.DEFAULT_SCALE,this.viewport=n,this.pdfPageRotate=n.rotation,this.hasRestrictedScaling=!1,this.enhanceTextSelection=e.enhanceTextSelection||!1,this.renderInteractiveForms=e.renderInteractiveForms||!1,this.eventBus=e.eventBus||(0,s.getGlobalEventBus)(),this.renderingQueue=e.renderingQueue,this.textLayerFactory=e.textLayerFactory,this.annotationLayerFactory=e.annotationLayerFactory,this.renderer=e.renderer||o.RendererType.CANVAS,this.l10n=e.l10n||o.NullL10n,this.paintTask=null,this.paintedViewportMap=new WeakMap,this.renderingState=c.RenderingStates.INITIAL,this.resume=null,this.error=null,this.onBeforeDraw=null,this.onAfterDraw=null,this.annotationLayer=null,this.textLayer=null,this.zoomLayer=null;var a=document.createElement("div");a.className="page",a.style.width=Math.floor(this.viewport.width)+"px",a.style.height=Math.floor(this.viewport.height)+"px",a.setAttribute("data-page-number",this.id),this.div=a,r.appendChild(a)}return n(t,[{key:"setPdfPage",value:function t(e){this.pdfPage=e,this.pdfPageRotate=e.rotate;var r=(this.rotation+this.pdfPageRotate)%360;this.viewport=e.getViewport(this.scale*o.CSS_UNITS,r),this.stats=e.stats,this.reset()}},{key:"destroy",value:function t(){this.reset(),this.pdfPage&&this.pdfPage.cleanup()}},{key:"_resetZoomLayer",value:function t(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(this.zoomLayer){var r=this.zoomLayer.firstChild;this.paintedViewportMap.delete(r),r.width=0,r.height=0,e&&this.zoomLayer.remove(),this.zoomLayer=null}}},{key:"reset",value:function t(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.cancelRendering();var i=this.div;i.style.width=Math.floor(this.viewport.width)+"px",i.style.height=Math.floor(this.viewport.height)+"px";for(var n=i.childNodes,o=e&&this.zoomLayer||null,a=r&&this.annotationLayer&&this.annotationLayer.div||null,s=n.length-1;s>=0;s--){var c=n[s];o!==c&&a!==c&&i.removeChild(c)}i.removeAttribute("data-loaded"),a?this.annotationLayer.hide():this.annotationLayer=null,o||(this.canvas&&(this.paintedViewportMap.delete(this.canvas),this.canvas.width=0,this.canvas.height=0,delete this.canvas),this._resetZoomLayer()),this.svg&&(this.paintedViewportMap.delete(this.svg),delete this.svg),this.loadingIconDiv=document.createElement("div"),this.loadingIconDiv.className="loadingIcon",i.appendChild(this.loadingIconDiv)}},{key:"update",value:function t(e,r){this.scale=e||this.scale,void 0!==r&&(this.rotation=r);var i=(this.rotation+this.pdfPageRotate)%360;if(this.viewport=this.viewport.clone({scale:this.scale*o.CSS_UNITS,rotation:i}),this.svg)return this.cssTransform(this.svg,!0),void this.eventBus.dispatch("pagerendered",{source:this,pageNumber:this.id,cssTransform:!0});var n=!1;if(this.canvas&&a.PDFJS.maxCanvasPixels>0){var s=this.outputScale;(Math.floor(this.viewport.width)*s.sx|0)*(Math.floor(this.viewport.height)*s.sy|0)>a.PDFJS.maxCanvasPixels&&(n=!0)}if(this.canvas){if(a.PDFJS.useOnlyCssZoom||this.hasRestrictedScaling&&n)return this.cssTransform(this.canvas,!0),void this.eventBus.dispatch("pagerendered",{source:this,pageNumber:this.id,cssTransform:!0});this.zoomLayer||this.canvas.hasAttribute("hidden")||(this.zoomLayer=this.canvas.parentNode,this.zoomLayer.style.position="absolute")}this.zoomLayer&&this.cssTransform(this.zoomLayer.firstChild),this.reset(!0,!0)}},{key:"cancelRendering",value:function t(){this.paintTask&&(this.paintTask.cancel(),this.paintTask=null),this.renderingState=c.RenderingStates.INITIAL,this.resume=null,this.textLayer&&(this.textLayer.cancel(),this.textLayer=null)}},{key:"cssTransform",value:function t(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=this.viewport.width,n=this.viewport.height,o=this.div;e.style.width=e.parentNode.style.width=o.style.width=Math.floor(i)+"px",e.style.height=e.parentNode.style.height=o.style.height=Math.floor(n)+"px";var s=this.viewport.rotation-this.paintedViewportMap.get(e).rotation,c=Math.abs(s),l=1,h=1;90!==c&&270!==c||(l=n/i,h=i/n);var t="rotate("+s+"deg) scale("+l+","+h+")";if(a.CustomStyle.setProp("transform",e,t),this.textLayer){var u=this.textLayer.viewport,f=this.viewport.rotation-u.rotation,d=Math.abs(f),p=i/u.width;90!==d&&270!==d||(p=i/u.height);var g=this.textLayer.textLayerDiv,v=void 0,m=void 0;switch(d){case 0:v=m=0;break;case 90:v=0,m="-"+g.style.height;break;case 180:v="-"+g.style.width,m="-"+g.style.height;break;case 270:v="-"+g.style.width,m=0;break;default:console.error("Bad rotation value.")}a.CustomStyle.setProp("transform",g,"rotate("+d+"deg) scale("+p+", "+p+") translate("+v+", "+m+")"),a.CustomStyle.setProp("transformOrigin",g,"0% 0%")}r&&this.annotationLayer&&this.annotationLayer.render(this.viewport,"display")}},{key:"getPagePoint",value:function t(e,r){return this.viewport.convertToPdfPoint(e,r)}},{key:"draw",value:function t(){var e=this;this.renderingState!==c.RenderingStates.INITIAL&&(console.error("Must be in new state before drawing"),this.reset()),this.renderingState=c.RenderingStates.RUNNING;var r=this.pdfPage,i=this.div,n=document.createElement("div");n.style.width=i.style.width,n.style.height=i.style.height,n.classList.add("canvasWrapper"),this.annotationLayer&&this.annotationLayer.div?i.insertBefore(n,this.annotationLayer.div):i.appendChild(n);var s=null;if(this.textLayerFactory){var l=document.createElement("div");l.className="textLayer",l.style.width=n.style.width,l.style.height=n.style.height,this.annotationLayer&&this.annotationLayer.div?i.insertBefore(l,this.annotationLayer.div):i.appendChild(l),s=this.textLayerFactory.createTextLayerBuilder(l,this.id-1,this.viewport,this.enhanceTextSelection)}this.textLayer=s;var h=null;this.renderingQueue&&(h=function t(r){if(!e.renderingQueue.isHighestPriority(e))return e.renderingState=c.RenderingStates.PAUSED,void(e.resume=function(){e.renderingState=c.RenderingStates.RUNNING,r()});r()});var u=function t(n){return f===e.paintTask&&(e.paintTask=null),"cancelled"===n||n instanceof a.RenderingCancelledException?(e.error=null,Promise.resolve(void 0)):(e.renderingState=c.RenderingStates.FINISHED,e.loadingIconDiv&&(i.removeChild(e.loadingIconDiv),delete e.loadingIconDiv),e._resetZoomLayer(!0),e.error=n,e.stats=r.stats,e.onAfterDraw&&e.onAfterDraw(),e.eventBus.dispatch("pagerendered",{source:e,pageNumber:e.id,cssTransform:!1}),n?Promise.reject(n):Promise.resolve(void 0))},f=this.renderer===o.RendererType.SVG?this.paintOnSvg(n):this.paintOnCanvas(n);f.onRenderContinue=h,this.paintTask=f;var d=f.promise.then(function(){return u(null).then(function(){if(s){var t=r.streamTextContent({normalizeWhitespace:!0});s.setTextContentStream(t),s.render()}})},function(t){return u(t)});return this.annotationLayerFactory&&(this.annotationLayer||(this.annotationLayer=this.annotationLayerFactory.createAnnotationLayerBuilder(i,r,this.renderInteractiveForms,this.l10n)),this.annotationLayer.render(this.viewport,"display")),i.setAttribute("data-loaded",!0),this.onBeforeDraw&&this.onBeforeDraw(),d}},{key:"paintOnCanvas",value:function t(e){var r=(0,a.createPromiseCapability)(),i={promise:r.promise,onRenderContinue:function t(e){e()},cancel:function t(){y.cancel()}},n=this.viewport,s=document.createElement("canvas");s.id=this.renderingId,s.setAttribute("hidden","hidden");var c=!0,l=function t(){c&&(s.removeAttribute("hidden"),c=!1)};e.appendChild(s),this.canvas=s,s.mozOpaque=!0;var h=s.getContext("2d",{alpha:!1}),u=(0,o.getOutputScale)(h);if(this.outputScale=u,a.PDFJS.useOnlyCssZoom){var f=n.clone({scale:o.CSS_UNITS});u.sx*=f.width/n.width,u.sy*=f.height/n.height,u.scaled=!0}if(a.PDFJS.maxCanvasPixels>0){var d=n.width*n.height,p=Math.sqrt(a.PDFJS.maxCanvasPixels/d);u.sx>p||u.sy>p?(u.sx=p,u.sy=p,u.scaled=!0,this.hasRestrictedScaling=!0):this.hasRestrictedScaling=!1}var g=(0,o.approximateFraction)(u.sx),v=(0,o.approximateFraction)(u.sy);s.width=(0,o.roundToDivide)(n.width*u.sx,g[0]),s.height=(0,o.roundToDivide)(n.height*u.sy,v[0]),s.style.width=(0,o.roundToDivide)(n.width,g[1])+"px",s.style.height=(0,o.roundToDivide)(n.height,v[1])+"px",this.paintedViewportMap.set(s,n);var m=u.scaled?[u.sx,0,0,u.sy,0,0]:null,b={canvasContext:h,transform:m,viewport:this.viewport,renderInteractiveForms:this.renderInteractiveForms},y=this.pdfPage.render(b);return y.onContinue=function(t){l(),i.onRenderContinue?i.onRenderContinue(t):t()},y.promise.then(function(){l(),r.resolve(void 0)},function(t){l(),r.reject(t)}),i}},{key:"paintOnSvg",value:function t(e){var r=this,i=!1,n=function t(){if(i)throw a.PDFJS.pdfjsNext?new a.RenderingCancelledException("Rendering cancelled, page "+r.id,"svg"):"cancelled"},s=this.pdfPage,l=this.viewport.clone({scale:o.CSS_UNITS});return{promise:s.getOperatorList().then(function(t){return n(),new a.SVGGraphics(s.commonObjs,s.objs).getSVG(t,l).then(function(t){n(),r.svg=t,r.paintedViewportMap.set(t,l),t.style.width=e.style.width,t.style.height=e.style.height,r.renderingState=c.RenderingStates.FINISHED,e.appendChild(t)})}),onRenderContinue:function t(e){e()},cancel:function t(){i=!0}}}},{key:"setPageLabel",value:function t(e){this.pageLabel="string"==typeof e?e:null,null!==this.pageLabel?this.div.setAttribute("data-page-label",this.pageLabel):this.div.removeAttribute("data-page-label")}},{key:"width",get:function t(){return this.viewport.width}},{key:"height",get:function t(){return this.viewport.height}}]),t}();e.PDFPageView=l},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.DefaultTextLayerFactory=e.TextLayerBuilder=void 0;var n=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),o=r(2),a=r(0),s=300,c=function(){function t(e){var r=e.textLayerDiv,n=e.eventBus,a=e.pageIndex,s=e.viewport,c=e.findController,l=void 0===c?null:c,h=e.enhanceTextSelection,u=void 0!==h&&h;i(this,t),this.textLayerDiv=r,this.eventBus=n||(0,o.getGlobalEventBus)(),this.textContent=null,this.textContentItemsStr=[],this.textContentStream=null,this.renderingDone=!1,this.pageIdx=a,this.pageNumber=this.pageIdx+1,this.matches=[],this.viewport=s,this.textDivs=[],this.findController=l,this.textLayerRenderTask=null,this.enhanceTextSelection=u,this._bindMouse()}return n(t,[{key:"_finishRendering",value:function t(){if(this.renderingDone=!0,!this.enhanceTextSelection){var e=document.createElement("div");e.className="endOfContent",this.textLayerDiv.appendChild(e)}this.eventBus.dispatch("textlayerrendered",{source:this,pageNumber:this.pageNumber,numTextDivs:this.textDivs.length})}},{key:"render",value:function t(){var e=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;if((this.textContent||this.textContentStream)&&!this.renderingDone){this.cancel(),this.textDivs=[];var i=document.createDocumentFragment();this.textLayerRenderTask=(0,a.renderTextLayer)({textContent:this.textContent,textContentStream:this.textContentStream,container:i,viewport:this.viewport,textDivs:this.textDivs,textContentItemsStr:this.textContentItemsStr,timeout:r,enhanceTextSelection:this.enhanceTextSelection}),this.textLayerRenderTask.promise.then(function(){e.textLayerDiv.appendChild(i),e._finishRendering(),e.updateMatches()},function(t){})}}},{key:"cancel",value:function t(){this.textLayerRenderTask&&(this.textLayerRenderTask.cancel(),this.textLayerRenderTask=null)}},{key:"setTextContentStream",value:function t(e){this.cancel(),this.textContentStream=e}},{key:"setTextContent",value:function t(e){this.cancel(),this.textContent=e}},{key:"convertMatches",value:function t(e,r){var i=0,n=0,o=this.textContentItemsStr,a=o.length-1,s=null===this.findController?0:this.findController.state.query.length,c=[];if(!e)return c;for(var l=0,h=e.length;l<h;l++){for(var u=e[l];i!==a&&u>=n+o[i].length;)n+=o[i].length,i++;i===o.length&&console.error("Could not find a matching mapping");var f={begin:{divIdx:i,offset:u-n}};for(u+=r?r[l]:s;i!==a&&u>n+o[i].length;)n+=o[i].length,i++;f.end={divIdx:i,offset:u-n},c.push(f)}return c}},{key:"renderMatches",value:function t(e){function r(t,e){var r=t.divIdx;o[r].textContent="",i(r,0,t.offset,e)}function i(t,e,r,i){var a=o[t],s=n[t].substring(e,r),c=document.createTextNode(s);if(i){var l=document.createElement("span");return l.className=i,l.appendChild(c),void a.appendChild(l)}a.appendChild(c)}if(0!==e.length){var n=this.textContentItemsStr,o=this.textDivs,a=null,s=this.pageIdx,c=null!==this.findController&&s===this.findController.selected.pageIdx,l=null===this.findController?-1:this.findController.selected.matchIdx,h=null!==this.findController&&this.findController.state.highlightAll,u={divIdx:-1,offset:void 0},f=l,d=f+1;if(h)f=0,d=e.length;else if(!c)return;for(var p=f;p<d;p++){var g=e[p],v=g.begin,m=g.end,b=c&&p===l,y=b?" selected":"";if(this.findController&&this.findController.updateMatchPosition(s,p,o,v.divIdx),a&&v.divIdx===a.divIdx?i(a.divIdx,a.offset,v.offset):(null!==a&&i(a.divIdx,a.offset,u.offset),r(v)),v.divIdx===m.divIdx)i(v.divIdx,v.offset,m.offset,"highlight"+y);else{i(v.divIdx,v.offset,u.offset,"highlight begin"+y);for(var _=v.divIdx+1,w=m.divIdx;_<w;_++)o[_].className="highlight middle"+y;r(m,"highlight end"+y)}a=m}a&&i(a.divIdx,a.offset,u.offset)}}},{key:"updateMatches",value:function t(){if(this.renderingDone){for(var e=this.matches,r=this.textDivs,i=this.textContentItemsStr,n=-1,o=0,a=e.length;o<a;o++){for(var s=e[o],c=Math.max(n,s.begin.divIdx),l=c,h=s.end.divIdx;l<=h;l++){var u=r[l];u.textContent=i[l],u.className=""}n=s.end.divIdx+1}if(null!==this.findController&&this.findController.active){var f=void 0,d=void 0;null!==this.findController&&(f=this.findController.pageMatches[this.pageIdx]||null,d=this.findController.pageMatchesLength?this.findController.pageMatchesLength[this.pageIdx]||null:null),this.matches=this.convertMatches(f,d),this.renderMatches(this.matches)}}}},{key:"_bindMouse",value:function t(){var e=this,r=this.textLayerDiv,i=null;r.addEventListener("mousedown",function(t){if(e.enhanceTextSelection&&e.textLayerRenderTask)return e.textLayerRenderTask.expandTextDivs(!0),void(i&&(clearTimeout(i),i=null));var n=r.querySelector(".endOfContent");if(n){var o=t.target!==r;if(o=o&&"none"!==window.getComputedStyle(n).getPropertyValue("-moz-user-select")){var a=r.getBoundingClientRect(),s=Math.max(0,(t.pageY-a.top)/a.height);n.style.top=(100*s).toFixed(2)+"%"}n.classList.add("active")}}),r.addEventListener("mouseup",function(){if(e.enhanceTextSelection&&e.textLayerRenderTask)return void(i=setTimeout(function(){e.textLayerRenderTask&&e.textLayerRenderTask.expandTextDivs(!1),i=null},300));var t=r.querySelector(".endOfContent");t&&(t.style.top="",t.classList.remove("active"))})}}]),t}(),l=function(){function t(){i(this,t)}return n(t,[{key:"createTextLayerBuilder",value:function t(e,r,i){var n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return new c({textLayerDiv:e,pageIndex:r,viewport:i,enhanceTextSelection:n})}}]),t}();e.TextLayerBuilder=c,e.DefaultTextLayerFactory=l},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),o=3e4,a={INITIAL:0,RUNNING:1,PAUSED:2,FINISHED:3},s=function(){function t(){i(this,t),this.pdfViewer=null,this.pdfThumbnailViewer=null,this.onIdle=null,this.highestPriorityPage=null,this.idleTimeout=null,this.printing=!1,this.isThumbnailViewEnabled=!1}return n(t,[{key:"setViewer",value:function t(e){this.pdfViewer=e}},{key:"setThumbnailViewer",value:function t(e){this.pdfThumbnailViewer=e}},{key:"isHighestPriority",value:function t(e){return this.highestPriorityPage===e.renderingId}},{key:"renderHighestPriority",value:function t(e){this.idleTimeout&&(clearTimeout(this.idleTimeout),this.idleTimeout=null),this.pdfViewer.forceRendering(e)||this.pdfThumbnailViewer&&this.isThumbnailViewEnabled&&this.pdfThumbnailViewer.forceRendering()||this.printing||this.onIdle&&(this.idleTimeout=setTimeout(this.onIdle.bind(this),3e4))}},{key:"getHighestPriority",value:function t(e,r,i){var n=e.views,o=n.length;if(0===o)return!1;for(var a=0;a<o;++a){var s=n[a].view;if(!this.isViewFinished(s))return s}if(i){var c=e.last.id;if(r[c]&&!this.isViewFinished(r[c]))return r[c]}else{var l=e.first.id-2;if(r[l]&&!this.isViewFinished(r[l]))return r[l]}return null}},{key:"isViewFinished",value:function t(e){return e.renderingState===a.FINISHED}},{key:"renderView",value:function t(e){var r=this;switch(e.renderingState){case a.FINISHED:return!1;case a.PAUSED:this.highestPriorityPage=e.renderingId,e.resume();break;case a.RUNNING:this.highestPriorityPage=e.renderingId;break;case a.INITIAL:this.highestPriorityPage=e.renderingId;var i=function t(){r.renderHighestPriority()};e.draw().then(i,i)}return!0}}]),t}();e.RenderingStates=a,e.PDFRenderingQueue=s},function(t,e,r){"use strict";function i(t,e){var r=document.createElement("a");if(r.click)r.href=t,r.target="_parent","download"in r&&(r.download=e),(document.body||document.documentElement).appendChild(r),r.click(),r.parentNode.removeChild(r);else{if(window.top===window&&t.split("#")[0]===window.location.href.split("#")[0]){var i=-1===t.indexOf("?")?"?":"&";t=t.replace(/#|$/,i+"$&")}window.open(t,"_parent")}}function n(){}Object.defineProperty(e,"__esModule",{value:!0}),e.DownloadManager=void 0;var o=r(0);n.prototype={downloadUrl:function t(e,r){(0,o.createValidAbsoluteUrl)(e,"http://example.com")&&i(e+"#pdfjs.action=download",r)},downloadData:function t(e,r,n){if(navigator.msSaveBlob)return navigator.msSaveBlob(new Blob([e],{type:n}),r);i((0,o.createObjectURL)(e,n,o.PDFJS.disableCreateObjectURL),r)},download:function t(e,r,n){return navigator.msSaveBlob?void(navigator.msSaveBlob(e,n)||this.downloadUrl(r,n)):o.PDFJS.disableCreateObjectURL?void this.downloadUrl(r,n):void i(URL.createObjectURL(e),n)}},e.DownloadManager=n},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.GenericL10n=void 0;var n=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}();r(13);var o=document.webL10n,a=function(){function t(e){i(this,t),this._lang=e,this._ready=new Promise(function(t,r){o.setLanguage(e,function(){t(o)})})}return n(t,[{key:"getDirection",value:function t(){return this._ready.then(function(t){return t.getDirection()})}},{key:"get",value:function t(e,r,i){return this._ready.then(function(t){return t.get(e,r,i)})}},{key:"translate",value:function t(e){return this._ready.then(function(t){return t.translate(e)})}}]),t}();e.GenericL10n=a},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.PDFFindController=e.FindState=void 0;var n=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),o=r(0),a=r(1),s={FOUND:0,NOT_FOUND:1,WRAPPED:2,PENDING:3},c=-50,l=-400,h=250,u={"‘":"'","’":"'","‚":"'","‛":"'","“":'"',"”":'"',"„":'"',"‟":'"',"¼":"1/4","½":"1/2","¾":"3/4"},f=function(){function t(e){var r=e.pdfViewer;i(this,t),this.pdfViewer=r,this.onUpdateResultsCount=null,this.onUpdateState=null,this.reset();var n=Object.keys(u).join("");this.normalizationRegex=new RegExp("["+n+"]","g")}return n(t,[{key:"reset",value:function t(){var e=this;this.startedTextExtraction=!1,this.extractTextPromises=[],this.pendingFindMatches=Object.create(null),this.active=!1,this.pageContents=[],this.pageMatches=[],this.pageMatchesLength=null,this.matchCount=0,this.selected={pageIdx:-1,matchIdx:-1},this.offset={pageIdx:null,matchIdx:null},this.pagesToSearch=null,this.resumePageIdx=null,this.state=null,this.dirtyMatch=!1,this.findTimeout=null,this._firstPagePromise=new Promise(function(t){e.resolveFirstPage=t})}},{key:"normalize",value:function t(e){return e.replace(this.normalizationRegex,function(t){return u[t]})}},{key:"_prepareMatches",value:function t(e,r,i){function n(t,e){var r=t[e],i=t[e+1];if(e<t.length-1&&r.match===i.match)return r.skipped=!0,!0;for(var n=e-1;n>=0;n--){var o=t[n];if(!o.skipped){if(o.match+o.matchLength<r.match)break;if(o.match+o.matchLength>=r.match+r.matchLength)return r.skipped=!0,!0}}return!1}e.sort(function(t,e){return t.match===e.match?t.matchLength-e.matchLength:t.match-e.match});for(var o=0,a=e.length;o<a;o++)n(e,o)||(r.push(e[o].match),i.push(e[o].matchLength))}},{key:"calcFindPhraseMatch",value:function t(e,r,i){for(var n=[],o=e.length,a=-o;;){if(-1===(a=i.indexOf(e,a+o)))break;n.push(a)}this.pageMatches[r]=n}},{key:"calcFindWordMatch",value:function t(e,r,i){for(var n=[],o=e.match(/\S+/g),a=0,s=o.length;a<s;a++)for(var c=o[a],l=c.length,h=-l;;){if(-1===(h=i.indexOf(c,h+l)))break;n.push({match:h,matchLength:l,skipped:!1})}this.pageMatchesLength||(this.pageMatchesLength=[]),this.pageMatchesLength[r]=[],this.pageMatches[r]=[],this._prepareMatches(n,this.pageMatches[r],this.pageMatchesLength[r])}},{key:"calcFindMatch",value:function t(e){var r=this.normalize(this.pageContents[e]),i=this.normalize(this.state.query),n=this.state.caseSensitive,o=this.state.phraseSearch;0!==i.length&&(n||(r=r.toLowerCase(),i=i.toLowerCase()),o?this.calcFindPhraseMatch(i,e,r):this.calcFindWordMatch(i,e,r),this.updatePage(e),this.resumePageIdx===e&&(this.resumePageIdx=null,this.nextPageMatch()),this.pageMatches[e].length>0&&(this.matchCount+=this.pageMatches[e].length,this.updateUIResultsCount()))}},{key:"extractText",value:function t(){var e=this;if(!this.startedTextExtraction){this.startedTextExtraction=!0,this.pageContents.length=0;for(var r=Promise.resolve(),i=function t(i,n){var a=(0,o.createPromiseCapability)();e.extractTextPromises[i]=a.promise,r=r.then(function(){return e.pdfViewer.getPageTextContent(i).then(function(t){for(var r=t.items,n=[],o=0,s=r.length;o<s;o++)n.push(r[o].str);e.pageContents[i]=n.join(""),a.resolve(i)})})},n=0,a=this.pdfViewer.pagesCount;n<a;n++)i(n,a)}}},{key:"executeCommand",value:function t(e,r){var i=this;null!==this.state&&"findagain"===e||(this.dirtyMatch=!0),this.state=r,this.updateUIState(s.PENDING),this._firstPagePromise.then(function(){i.extractText(),clearTimeout(i.findTimeout),"find"===e?i.findTimeout=setTimeout(i.nextMatch.bind(i),250):i.nextMatch()})}},{key:"updatePage",value:function t(e){this.selected.pageIdx===e&&(this.pdfViewer.currentPageNumber=e+1);var r=this.pdfViewer.getPageView(e);r.textLayer&&r.textLayer.updateMatches()}},{key:"nextMatch",value:function t(){var e=this,r=this.state.findPrevious,i=this.pdfViewer.currentPageNumber-1,n=this.pdfViewer.pagesCount;if(this.active=!0,this.dirtyMatch){this.dirtyMatch=!1,this.selected.pageIdx=this.selected.matchIdx=-1,this.offset.pageIdx=i,this.offset.matchIdx=null,this.hadMatch=!1,this.resumePageIdx=null,this.pageMatches=[],this.matchCount=0,this.pageMatchesLength=null;for(var o=0;o<n;o++)this.updatePage(o),o in this.pendingFindMatches||(this.pendingFindMatches[o]=!0,this.extractTextPromises[o].then(function(t){delete e.pendingFindMatches[t],e.calcFindMatch(t)}))}if(""===this.state.query)return void this.updateUIState(s.FOUND);if(!this.resumePageIdx){var a=this.offset;if(this.pagesToSearch=n,null!==a.matchIdx){var c=this.pageMatches[a.pageIdx].length;if(!r&&a.matchIdx+1<c||r&&a.matchIdx>0)return this.hadMatch=!0,a.matchIdx=r?a.matchIdx-1:a.matchIdx+1,void this.updateMatch(!0);this.advanceOffsetPage(r)}this.nextPageMatch()}}},{key:"matchesReady",value:function t(e){var r=this.offset,i=e.length,n=this.state.findPrevious;return i?(this.hadMatch=!0,r.matchIdx=n?i-1:0,this.updateMatch(!0),!0):(this.advanceOffsetPage(n),!!(r.wrapped&&(r.matchIdx=null,this.pagesToSearch<0))&&(this.updateMatch(!1),!0))}},{key:"updateMatchPosition",value:function t(e,r,i,n){if(this.selected.matchIdx===r&&this.selected.pageIdx===e){var o={top:-50,left:-400};(0,a.scrollIntoView)(i[n],o,!0)}}},{key:"nextPageMatch",value:function t(){null!==this.resumePageIdx&&console.error("There can only be one pending page.");var e=null;do{var r=this.offset.pageIdx;if(!(e=this.pageMatches[r])){this.resumePageIdx=r;break}}while(!this.matchesReady(e))}},{key:"advanceOffsetPage",value:function t(e){var r=this.offset,i=this.extractTextPromises.length;r.pageIdx=e?r.pageIdx-1:r.pageIdx+1,r.matchIdx=null,this.pagesToSearch--,(r.pageIdx>=i||r.pageIdx<0)&&(r.pageIdx=e?i-1:0,r.wrapped=!0)}},{key:"updateMatch",value:function t(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],r=s.NOT_FOUND,i=this.offset.wrapped;if(this.offset.wrapped=!1,e){var n=this.selected.pageIdx;this.selected.pageIdx=this.offset.pageIdx,this.selected.matchIdx=this.offset.matchIdx,r=i?s.WRAPPED:s.FOUND,-1!==n&&n!==this.selected.pageIdx&&this.updatePage(n)}this.updateUIState(r,this.state.findPrevious),-1!==this.selected.pageIdx&&this.updatePage(this.selected.pageIdx)}},{key:"updateUIResultsCount",value:function t(){this.onUpdateResultsCount&&this.onUpdateResultsCount(this.matchCount)}},{key:"updateUIState",value:function t(e,r){this.onUpdateState&&this.onUpdateState(e,r,this.matchCount)}}]),t}();e.FindState=s,e.PDFFindController=f},function(t,e,r){"use strict";function i(t){this.linkService=t.linkService,this.eventBus=t.eventBus||(0,n.getGlobalEventBus)(),this.initialized=!1,this.initialDestination=null,this.initialBookmark=null}Object.defineProperty(e,"__esModule",{value:!0}),e.PDFHistory=void 0;var n=r(2);i.prototype={initialize:function t(e){function r(){a.previousHash=window.location.hash.slice(1),a._pushToHistory({hash:a.previousHash},!1,!0),a._updatePreviousBookmark()}function i(t,e){function r(){window.removeEventListener("popstate",r),window.addEventListener("popstate",i),a._pushToHistory(t,!1,!0),history.forward()}function i(){window.removeEventListener("popstate",i),a.allowHashChange=!0,a.historyUnlocked=!0,e()}a.historyUnlocked=!1,a.allowHashChange=!1,window.addEventListener("popstate",r),history.back()}function n(){var t=a._getPreviousParams(null,!0);if(t){var e=!a.current.dest&&a.current.hash!==a.previousHash;a._pushToHistory(t,!1,e),a._updatePreviousBookmark()}window.removeEventListener("beforeunload",n)}this.initialized=!0,this.reInitialized=!1,this.allowHashChange=!0,this.historyUnlocked=!0,this.isViewerInPresentationMode=!1,this.previousHash=window.location.hash.substring(1),this.currentBookmark="",this.currentPage=0,this.updatePreviousBookmark=!1,this.previousBookmark="",this.previousPage=0,this.nextHashParam="",this.fingerprint=e,this.currentUid=this.uid=0,this.current={};var o=window.history.state;this._isStateObjectDefined(o)?(o.target.dest?this.initialDestination=o.target.dest:this.initialBookmark=o.target.hash,this.currentUid=o.uid,this.uid=o.uid+1,this.current=o.target):(o&&o.fingerprint&&this.fingerprint!==o.fingerprint&&(this.reInitialized=!0),this._pushOrReplaceState({fingerprint:this.fingerprint},!0));var a=this;window.addEventListener("popstate",function t(e){if(a.historyUnlocked){if(e.state)return void a._goTo(e.state);if(0===a.uid){i(a.previousHash&&a.currentBookmark&&a.previousHash!==a.currentBookmark?{hash:a.currentBookmark,page:a.currentPage}:{page:1},function(){r()})}else r()}}),window.addEventListener("beforeunload",n),window.addEventListener("pageshow",function t(e){window.addEventListener("beforeunload",n)}),a.eventBus.on("presentationmodechanged",function(t){a.isViewerInPresentationMode=t.active})},clearHistoryState:function t(){this._pushOrReplaceState(null,!0)},_isStateObjectDefined:function t(e){return!!(e&&e.uid>=0&&e.fingerprint&&this.fingerprint===e.fingerprint&&e.target&&e.target.hash)},_pushOrReplaceState:function t(e,r){r?window.history.replaceState(e,"",document.URL):window.history.pushState(e,"",document.URL)},get isHashChangeUnlocked(){return!this.initialized||this.allowHashChange},_updatePreviousBookmark:function t(){this.updatePreviousBookmark&&this.currentBookmark&&this.currentPage&&(this.previousBookmark=this.currentBookmark,this.previousPage=this.currentPage,this.updatePreviousBookmark=!1)},updateCurrentBookmark:function t(e,r){this.initialized&&(this.currentBookmark=e.substring(1),this.currentPage=0|r,this._updatePreviousBookmark())},updateNextHashParam:function t(e){this.initialized&&(this.nextHashParam=e)},push:function t(e,r){if(this.initialized&&this.historyUnlocked){if(e.dest&&!e.hash&&(e.hash=this.current.hash&&this.current.dest&&this.current.dest===e.dest?this.current.hash:this.linkService.getDestinationHash(e.dest).split("#")[1]),e.page&&(e.page|=0),r){var i=window.history.state.target;return i||(this._pushToHistory(e,!1),this.previousHash=window.location.hash.substring(1)),this.updatePreviousBookmark=!this.nextHashParam,void(i&&this._updatePreviousBookmark())}if(this.nextHashParam){if(this.nextHashParam===e.hash)return this.nextHashParam=null,void(this.updatePreviousBookmark=!0);this.nextHashParam=null}e.hash?this.current.hash?this.current.hash!==e.hash?this._pushToHistory(e,!0):(!this.current.page&&e.page&&this._pushToHistory(e,!1,!0),this.updatePreviousBookmark=!0):this._pushToHistory(e,!0):this.current.page&&e.page&&this.current.page!==e.page&&this._pushToHistory(e,!0)}},_getPreviousParams:function t(e,r){if(!this.currentBookmark||!this.currentPage)return null;if(this.updatePreviousBookmark&&(this.updatePreviousBookmark=!1),this.uid>0&&(!this.previousBookmark||!this.previousPage))return null;if(!this.current.dest&&!e||r){if(this.previousBookmark===this.currentBookmark)return null}else{if(!this.current.page&&!e)return null;if(this.previousPage===this.currentPage)return null}var i={hash:this.currentBookmark,page:this.currentPage};return this.isViewerInPresentationMode&&(i.hash=null),i},_stateObj:function t(e){return{fingerprint:this.fingerprint,uid:this.uid,target:e}},_pushToHistory:function t(e,r,i){if(this.initialized){if(!e.hash&&e.page&&(e.hash="page="+e.page),r&&!i){var n=this._getPreviousParams();if(n){var o=!this.current.dest&&this.current.hash!==this.previousHash;this._pushToHistory(n,!1,o)}}this._pushOrReplaceState(this._stateObj(e),i||0===this.uid),this.currentUid=this.uid++,this.current=e,this.updatePreviousBookmark=!0}},_goTo:function t(e){if(this.initialized&&this.historyUnlocked&&this._isStateObjectDefined(e)){if(!this.reInitialized&&e.uid<this.currentUid){var r=this._getPreviousParams(!0);if(r)return this._pushToHistory(this.current,!1),this._pushToHistory(r,!1),this.currentUid=e.uid,void window.history.back()}this.historyUnlocked=!1,e.target.dest?this.linkService.navigateTo(e.target.dest):this.linkService.setHash(e.target.hash),this.currentUid=e.uid,e.uid>this.uid&&(this.uid=e.uid),this.current=e.target,this.updatePreviousBookmark=!0;var i=window.location.hash.substring(1);this.previousHash!==i&&(this.allowHashChange=!1),this.previousHash=i,this.historyUnlocked=!0}},back:function t(){this.go(-1)},forward:function t(){this.go(1)},go:function t(e){if(this.initialized&&this.historyUnlocked){var r=window.history.state;-1===e&&r&&r.uid>0?window.history.back():1===e&&r&&r.uid<this.uid-1&&window.history.forward()}}},e.PDFHistory=i},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t){var e=[];this.push=function r(i){var n=e.indexOf(i);n>=0&&e.splice(n,1),e.push(i),e.length>t&&e.shift().destroy()},this.resize=function(r){for(t=r;e.length>t;)e.shift().destroy()}}function o(t,e){return e===t||Math.abs(e-t)<1e-15}function a(t){return t.width<=t.height}Object.defineProperty(e,"__esModule",{value:!0}),e.PDFViewer=e.PresentationModeState=void 0;var s=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),c=r(0),l=r(1),h=r(7),u=r(4),f=r(2),d=r(5),p=r(3),g=r(6),v={UNKNOWN:0,NORMAL:1,CHANGING:2,FULLSCREEN:3},m=10,b=function(){function t(e){i(this,t),this.container=e.container,this.viewer=e.viewer||e.container.firstElementChild,this.eventBus=e.eventBus||(0,f.getGlobalEventBus)(),this.linkService=e.linkService||new p.SimpleLinkService,this.downloadManager=e.downloadManager||null,this.removePageBorders=e.removePageBorders||!1,this.enhanceTextSelection=e.enhanceTextSelection||!1,this.renderInteractiveForms=e.renderInteractiveForms||!1,this.enablePrintAutoRotate=e.enablePrintAutoRotate||!1,this.renderer=e.renderer||l.RendererType.CANVAS,this.l10n=e.l10n||l.NullL10n,this.defaultRenderingQueue=!e.renderingQueue,this.defaultRenderingQueue?(this.renderingQueue=new h.PDFRenderingQueue,this.renderingQueue.setViewer(this)):this.renderingQueue=e.renderingQueue,this.scroll=(0,l.watchScroll)(this.container,this._scrollUpdate.bind(this)),this.presentationModeState=v.UNKNOWN,this._resetView(),this.removePageBorders&&this.viewer.classList.add("removePageBorders")}return s(t,[{key:"getPageView",value:function t(e){return this._pages[e]}},{key:"_setCurrentPageNumber",value:function t(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(this._currentPageNumber===e)return void(r&&this._resetCurrentPageView());if(!(0<e&&e<=this.pagesCount))return void console.error('PDFViewer._setCurrentPageNumber: "'+e+'" is out of bounds.');var i={source:this,pageNumber:e,pageLabel:this._pageLabels&&this._pageLabels[e-1]};this._currentPageNumber=e,this.eventBus.dispatch("pagechanging",i),this.eventBus.dispatch("pagechange",i),r&&this._resetCurrentPageView()}},{key:"setDocument",value:function t(e){var r=this;if(this.pdfDocument&&(this._cancelRendering(),this._resetView()),this.pdfDocument=e,e){var i=e.numPages,n=(0,c.createPromiseCapability)();this.pagesPromise=n.promise,n.promise.then(function(){r._pageViewsReady=!0,r.eventBus.dispatch("pagesloaded",{source:r,pagesCount:i})});var o=!1,a=(0,c.createPromiseCapability)();this.onePageRendered=a.promise;var s=function t(e){e.onBeforeDraw=function(){r._buffer.push(e)},e.onAfterDraw=function(){o||(o=!0,a.resolve())}},h=e.getPage(1);return this.firstPagePromise=h,h.then(function(t){for(var o=r.currentScale,h=t.getViewport(o*l.CSS_UNITS),u=1;u<=i;++u){var f=null;c.PDFJS.disableTextLayer||(f=r);var p=new d.PDFPageView({container:r.viewer,eventBus:r.eventBus,id:u,scale:o,defaultViewport:h.clone(),renderingQueue:r.renderingQueue,textLayerFactory:f,annotationLayerFactory:r,enhanceTextSelection:r.enhanceTextSelection,renderInteractiveForms:r.renderInteractiveForms,renderer:r.renderer,l10n:r.l10n});s(p),r._pages.push(p)}a.promise.then(function(){if(c.PDFJS.disableAutoFetch)return void n.resolve();for(var t=i,o=function i(o){e.getPage(o).then(function(e){var i=r._pages[o-1];i.pdfPage||i.setPdfPage(e),r.linkService.cachePageRef(o,e.ref),0==--t&&n.resolve()})},a=1;a<=i;++a)o(a)}),r.eventBus.dispatch("pagesinit",{source:r}),r.defaultRenderingQueue&&r.update(),r.findController&&r.findController.resolveFirstPage()})}}},{key:"setPageLabels",value:function t(e){if(this.pdfDocument){e?e instanceof Array&&this.pdfDocument.numPages===e.length?this._pageLabels=e:(this._pageLabels=null,console.error("PDFViewer.setPageLabels: Invalid page labels.")):this._pageLabels=null;for(var r=0,i=this._pages.length;r<i;r++){var n=this._pages[r],o=this._pageLabels&&this._pageLabels[r];n.setPageLabel(o)}}}},{key:"_resetView",value:function t(){this._pages=[],this._currentPageNumber=1,this._currentScale=l.UNKNOWN_SCALE,this._currentScaleValue=null,this._pageLabels=null,this._buffer=new n(10),this._location=null,this._pagesRotation=0,this._pagesRequests=[],this._pageViewsReady=!1,this.viewer.textContent=""}},{key:"_scrollUpdate",value:function t(){0!==this.pagesCount&&this.update()}},{key:"_setScaleDispatchEvent",value:function t(e,r){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n={source:this,scale:e,presetValue:i?r:void 0};this.eventBus.dispatch("scalechanging",n),this.eventBus.dispatch("scalechange",n)}},{key:"_setScaleUpdatePages",value:function t(e,r){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(this._currentScaleValue=r.toString(),o(this._currentScale,e))return void(n&&this._setScaleDispatchEvent(e,r,!0));for(var a=0,s=this._pages.length;a<s;a++)this._pages[a].update(e);if(this._currentScale=e,!i){var l=this._currentPageNumber,h=void 0;!this._location||c.PDFJS.ignoreCurrentPositionOnZoom||this.isInPresentationMode||this.isChangingPresentationMode||(l=this._location.pageNumber,h=[null,{name:"XYZ"},this._location.left,this._location.top,null]),this.scrollPageIntoView({pageNumber:l,destArray:h,allowNegativeOffset:!0})}this._setScaleDispatchEvent(e,r,n),this.defaultRenderingQueue&&this.update()}},{key:"_setScale",value:function t(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=parseFloat(e);if(i>0)this._setScaleUpdatePages(i,e,r,!1);else{var n=this._pages[this._currentPageNumber-1];if(!n)return;var o=this.isInPresentationMode||this.removePageBorders?0:l.SCROLLBAR_PADDING,a=this.isInPresentationMode||this.removePageBorders?0:l.VERTICAL_PADDING,s=(this.container.clientWidth-o)/n.width*n.scale,c=(this.container.clientHeight-a)/n.height*n.scale;switch(e){case"page-actual":i=1;break;case"page-width":i=s;break;case"page-height":i=c;break;case"page-fit":i=Math.min(s,c);break;case"auto":var h=n.width>n.height,u=h?Math.min(c,s):s;i=Math.min(l.MAX_AUTO_SCALE,u);break;default:return void console.error('PDFViewer._setScale: "'+e+'" is an unknown zoom value.')}this._setScaleUpdatePages(i,e,r,!0)}}},{key:"_resetCurrentPageView",value:function t(){this.isInPresentationMode&&this._setScale(this._currentScaleValue,!0);var e=this._pages[this._currentPageNumber-1];(0,l.scrollIntoView)(e.div)}},{key:"scrollPageIntoView",value:function t(e){if(this.pdfDocument){if(arguments.length>1||"number"==typeof e){console.warn("Call of scrollPageIntoView() with obsolete signature.");var r={};"number"==typeof e&&(r.pageNumber=e),arguments[1]instanceof Array&&(r.destArray=arguments[1]),e=r}var i=e.pageNumber||0,n=e.destArray||null,o=e.allowNegativeOffset||!1;if(this.isInPresentationMode||!n)return void this._setCurrentPageNumber(i,!0);var a=this._pages[i-1];if(!a)return void console.error('PDFViewer.scrollPageIntoView: Invalid "pageNumber" parameter.');var s=0,c=0,h=0,u=0,f=void 0,d=void 0,p=a.rotation%180!=0,g=(p?a.height:a.width)/a.scale/l.CSS_UNITS,v=(p?a.width:a.height)/a.scale/l.CSS_UNITS,m=0;switch(n[1].name){case"XYZ":s=n[2],c=n[3],m=n[4],s=null!==s?s:0,c=null!==c?c:v;break;case"Fit":case"FitB":m="page-fit";break;case"FitH":case"FitBH":c=n[2],m="page-width",null===c&&this._location&&(s=this._location.left,c=this._location.top);break;case"FitV":case"FitBV":s=n[2],h=g,u=v,m="page-height";break;case"FitR":s=n[2],c=n[3],h=n[4]-s,u=n[5]-c;var b=this.removePageBorders?0:l.SCROLLBAR_PADDING,y=this.removePageBorders?0:l.VERTICAL_PADDING;f=(this.container.clientWidth-b)/h/l.CSS_UNITS,d=(this.container.clientHeight-y)/u/l.CSS_UNITS,m=Math.min(Math.abs(f),Math.abs(d));break;default:return void console.error('PDFViewer.scrollPageIntoView: "'+n[1].name+'" is not a valid destination type.')}if(m&&m!==this._currentScale?this.currentScaleValue=m:this._currentScale===l.UNKNOWN_SCALE&&(this.currentScaleValue=l.DEFAULT_SCALE_VALUE),"page-fit"===m&&!n[4])return void(0,l.scrollIntoView)(a.div);var _=[a.viewport.convertToViewportPoint(s,c),a.viewport.convertToViewportPoint(s+h,c+u)],w=Math.min(_[0][0],_[1][0]),S=Math.min(_[0][1],_[1][1]);o||(w=Math.max(w,0),S=Math.max(S,0)),(0,l.scrollIntoView)(a.div,{left:w,top:S})}}},{key:"_updateLocation",value:function t(e){var r=this._currentScale,i=this._currentScaleValue,n=parseFloat(i)===r?Math.round(1e4*r)/100:i,o=e.id,a="#page="+o;a+="&zoom="+n;var s=this._pages[o-1],c=this.container,l=s.getPagePoint(c.scrollLeft-e.x,c.scrollTop-e.y),h=Math.round(l[0]),u=Math.round(l[1]);a+=","+h+","+u,this._location={pageNumber:o,scale:n,top:u,left:h,pdfOpenParams:a}}},{key:"update",value:function t(){var e=this._getVisiblePages(),r=e.views;if(0!==r.length){var i=Math.max(10,2*r.length+1);this._buffer.resize(i),this.renderingQueue.renderHighestPriority(e);for(var n=this._currentPageNumber,o=e.first,a=!1,s=0,c=r.length;s<c;++s){var l=r[s];if(l.percent<100)break;if(l.id===n){a=!0;break}}a||(n=r[0].id),this.isInPresentationMode||this._setCurrentPageNumber(n),this._updateLocation(o),this.eventBus.dispatch("updateviewarea",{source:this,location:this._location})}}},{key:"containsElement",value:function t(e){return this.container.contains(e)}},{key:"focus",value:function t(){this.container.focus()}},{key:"_getVisiblePages",value:function t(){if(!this.isInPresentationMode)return(0,l.getVisibleElements)(this.container,this._pages,!0);var e=[],r=this._pages[this._currentPageNumber-1];return e.push({id:r.id,view:r}),{first:r,last:r,views:e}}},{key:"cleanup",value:function t(){for(var e=0,r=this._pages.length;e<r;e++)this._pages[e]&&this._pages[e].renderingState!==h.RenderingStates.FINISHED&&this._pages[e].reset()}},{key:"_cancelRendering",value:function t(){for(var e=0,r=this._pages.length;e<r;e++)this._pages[e]&&this._pages[e].cancelRendering()}},{key:"_ensurePdfPageLoaded",value:function t(e){var r=this;if(e.pdfPage)return Promise.resolve(e.pdfPage);var i=e.id;if(this._pagesRequests[i])return this._pagesRequests[i];var n=this.pdfDocument.getPage(i).then(function(t){return e.pdfPage||e.setPdfPage(t),r._pagesRequests[i]=null,t});return this._pagesRequests[i]=n,n}},{key:"forceRendering",value:function t(e){var r=this,i=e||this._getVisiblePages(),n=this.renderingQueue.getHighestPriority(i,this._pages,this.scroll.down);return!!n&&(this._ensurePdfPageLoaded(n).then(function(){r.renderingQueue.renderView(n)}),!0)}},{key:"getPageTextContent",value:function t(e){return this.pdfDocument.getPage(e+1).then(function(t){return t.getTextContent({normalizeWhitespace:!0})})}},{key:"createTextLayerBuilder",value:function t(e,r,i){var n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return new g.TextLayerBuilder({textLayerDiv:e,eventBus:this.eventBus,pageIndex:r,viewport:i,findController:this.isInPresentationMode?null:this.findController,enhanceTextSelection:!this.isInPresentationMode&&n})}},{key:"createAnnotationLayerBuilder",value:function t(e,r){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:l.NullL10n;return new u.AnnotationLayerBuilder({pageDiv:e,pdfPage:r,renderInteractiveForms:i,linkService:this.linkService,downloadManager:this.downloadManager,l10n:n})}},{key:"setFindController",value:function t(e){this.findController=e}},{key:"getPagesOverview",value:function t(){var e=this._pages.map(function(t){var e=t.pdfPage.getViewport(1);return{width:e.width,height:e.height,rotation:e.rotation}});if(!this.enablePrintAutoRotate)return e;var r=a(e[0]);return e.map(function(t){return r===a(t)?t:{width:t.height,height:t.width,rotation:(t.rotation+90)%360}})}},{key:"pagesCount",get:function t(){return this._pages.length}},{key:"pageViewsReady",get:function t(){return this._pageViewsReady}},{key:"currentPageNumber",get:function t(){return this._currentPageNumber},set:function t(e){if((0|e)!==e)throw new Error("Invalid page number.");this.pdfDocument&&this._setCurrentPageNumber(e,!0)}},{key:"currentPageLabel",get:function t(){return this._pageLabels&&this._pageLabels[this._currentPageNumber-1]},set:function t(e){var r=0|e;if(this._pageLabels){var i=this._pageLabels.indexOf(e);i>=0&&(r=i+1)}this.currentPageNumber=r}},{key:"currentScale",get:function t(){return this._currentScale!==l.UNKNOWN_SCALE?this._currentScale:l.DEFAULT_SCALE},set:function t(e){if(isNaN(e))throw new Error("Invalid numeric scale");this.pdfDocument&&this._setScale(e,!1)}},{key:"currentScaleValue",get:function t(){return this._currentScaleValue},set:function t(e){this.pdfDocument&&this._setScale(e,!1)}},{key:"pagesRotation",get:function t(){return this._pagesRotation},set:function t(e){if("number"!=typeof e||e%90!=0)throw new Error("Invalid pages rotation angle.");if(this.pdfDocument){this._pagesRotation=e;for(var r=0,i=this._pages.length;r<i;r++){var n=this._pages[r];n.update(n.scale,e)}this._setScale(this._currentScaleValue,!0),this.defaultRenderingQueue&&this.update()}}},{key:"isInPresentationMode",get:function t(){return this.presentationModeState===v.FULLSCREEN}},{key:"isChangingPresentationMode",get:function t(){return this.presentationModeState===v.CHANGING}},{key:"isHorizontalScrollbarEnabled",get:function t(){return!this.isInPresentationMode&&this.container.scrollWidth>this.container.clientWidth}},{key:"hasEqualPageSizes",get:function t(){for(var e=this._pages[0],r=1,i=this._pages.length;r<i;++r){var n=this._pages[r];if(n.width!==e.width||n.height!==e.height)return!1}return!0}}]),t}();e.PresentationModeState=v,e.PDFViewer=b},function(t,e,r){"use strict";document.webL10n=function(t,e,r){function i(){return e.querySelectorAll('link[type="application/l10n"]')}function n(){var t=e.querySelector('script[type="application/l10n"]');return t?JSON.parse(t.innerHTML):null}function o(t){return t?t.querySelectorAll("*[data-l10n-id]"):[]}function a(t){if(!t)return{};var e=t.getAttribute("data-l10n-id"),r=t.getAttribute("data-l10n-args"),i={};if(r)try{i=JSON.parse(r)}catch(t){console.warn("could not parse arguments for #"+e)}return{id:e,args:i}}function s(t){var r=e.createEvent("Event");r.initEvent("localized",!0,!1),r.language=t,e.dispatchEvent(r)}function c(t,e,r){e=e||function t(e){},r=r||function t(){};var i=new XMLHttpRequest;i.open("GET",t,A),i.overrideMimeType&&i.overrideMimeType("text/plain; charset=utf-8"),i.onreadystatechange=function(){4==i.readyState&&(200==i.status||0===i.status?e(i.responseText):r())},i.onerror=r,i.ontimeout=r;try{i.send(null)}catch(t){r()}}function l(t,e,r,i){function n(t){return t.lastIndexOf("\\")<0?t:t.replace(/\\\\/g,"\\").replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\b/g,"\b").replace(/\\f/g,"\f").replace(/\\{/g,"{").replace(/\\}/g,"}").replace(/\\"/g,'"').replace(/\\'/g,"'")}function o(t,r){function i(t,r,i){function c(){for(;;){if(!p.length)return void i();var t=p.shift();if(!h.test(t)){if(r){if(b=u.exec(t)){g=b[1].toLowerCase(),m="*"!==g&&g!==e&&g!==v;continue}if(m)continue;if(b=f.exec(t))return void o(a+b[1],c)}var l=t.match(d);l&&3==l.length&&(s[l[1]]=n(l[2]))}}}var p=t.replace(l,"").split(/[\r\n]+/),g="*",v=e.split("-",1)[0],m=!1,b="";c()}function o(t,e){c(t,function(t){i(t,!1,e)},function(){console.warn(t+" not found."),e()})}var s={},l=/^\s*|\s*$/,h=/^\s*#|^\s*$/,u=/^\s*\[(.*)\]\s*$/,f=/^\s*@import\s+url\((.*)\)\s*$/i,d=/^([^=\s]*)\s*=\s*(.+)$/;i(t,!0,function(){r(s)})}var a=t.replace(/[^\/]*$/,"")||"./";c(t,function(t){_+=t,o(t,function(t){for(var e in t){var i,n,o=e.lastIndexOf(".");o>0?(i=e.substring(0,o),n=e.substr(o+1)):(i=e,n=w),y[i]||(y[i]={}),y[i][n]=t[e]}r&&r()})},i)}function h(t,e){function r(t){var e=t.href;this.load=function(t,r){l(e,t,r,function(){console.warn(e+" not found."),console.warn('"'+t+'" resource not found'),S="",r()})}}t&&(t=t.toLowerCase()),e=e||function t(){},u(),S=t;var o=i(),a=o.length;if(0===a){var c=n();if(c&&c.locales&&c.default_locale){if(console.log("using the embedded JSON directory, early way out"),!(y=c.locales[t])){var h=c.default_locale.toLowerCase();for(var f in c.locales){if((f=f.toLowerCase())===t){y=c.locales[t];break}f===h&&(y=c.locales[h])}}e()}else console.log("no resource to load, early way out");return s(t),void(C="complete")}var d=null,p=0;d=function r(){++p>=a&&(e(),s(t),C="complete")};for(var g=0;g<a;g++){new r(o[g]).load(t,d)}}function u(){y={},_="",S=""}function f(t){function e(t,e){return-1!==e.indexOf(t)}function r(t,e,r){return e<=t&&t<=r}var i={af:3,ak:4,am:4,ar:1,asa:3,az:0,be:11,bem:3,bez:3,bg:3,bh:4,bm:0,bn:3,bo:0,br:20,brx:3,bs:11,ca:3,cgg:3,chr:3,cs:12,cy:17,da:3,de:3,dv:3,dz:0,ee:3,el:3,en:3,eo:3,es:3,et:3,eu:3,fa:0,ff:5,fi:3,fil:4,fo:3,fr:5,fur:3,fy:3,ga:8,gd:24,gl:3,gsw:3,gu:3,guw:4,gv:23,ha:3,haw:3,he:2,hi:4,hr:11,hu:0,id:0,ig:0,ii:0,is:3,it:3,iu:7,ja:0,jmc:3,jv:0,ka:0,kab:5,kaj:3,kcg:3,kde:0,kea:0,kk:3,kl:3,km:0,kn:0,ko:0,ksb:3,ksh:21,ku:3,kw:7,lag:18,lb:3,lg:3,ln:4,lo:0,lt:10,lv:6,mas:3,mg:4,mk:16,ml:3,mn:3,mo:9,mr:3,ms:0,mt:15,my:0,nah:3,naq:7,nb:3,nd:3,ne:3,nl:3,nn:3,no:3,nr:3,nso:4,ny:3,nyn:3,om:3,or:3,pa:3,pap:3,pl:13,ps:3,pt:3,rm:3,ro:9,rof:3,ru:11,rwk:3,sah:0,saq:3,se:7,seh:3,ses:0,sg:0,sh:11,shi:19,sk:12,sl:14,sma:7,smi:7,smj:7,smn:7,sms:7,sn:3,so:3,sq:3,sr:11,ss:3,ssy:3,st:3,sv:3,sw:3,syr:3,ta:3,te:3,teo:3,th:0,ti:4,tig:3,tk:3,tl:4,tn:3,to:0,tr:0,ts:3,tzm:22,uk:11,ur:3,ve:3,vi:0,vun:3,wa:4,wae:3,wo:0,xh:3,xog:3,yo:0,zh:0,zu:3},n={0:function t(e){return"other"},1:function t(e){return r(e%100,3,10)?"few":0===e?"zero":r(e%100,11,99)?"many":2==e?"two":1==e?"one":"other"},2:function t(e){return 0!==e&&e%10==0?"many":2==e?"two":1==e?"one":"other"},3:function t(e){return 1==e?"one":"other"},4:function t(e){return r(e,0,1)?"one":"other"},5:function t(e){return r(e,0,2)&&2!=e?"one":"other"},6:function t(e){return 0===e?"zero":e%10==1&&e%100!=11?"one":"other"},7:function t(e){return 2==e?"two":1==e?"one":"other"},8:function t(e){return r(e,3,6)?"few":r(e,7,10)?"many":2==e?"two":1==e?"one":"other"},9:function t(e){return 0===e||1!=e&&r(e%100,1,19)?"few":1==e?"one":"other"},10:function t(e){return r(e%10,2,9)&&!r(e%100,11,19)?"few":e%10!=1||r(e%100,11,19)?"other":"one"},11:function t(e){return r(e%10,2,4)&&!r(e%100,12,14)?"few":e%10==0||r(e%10,5,9)||r(e%100,11,14)?"many":e%10==1&&e%100!=11?"one":"other"},12:function t(e){return r(e,2,4)?"few":1==e?"one":"other"},13:function t(e){return r(e%10,2,4)&&!r(e%100,12,14)?"few":1!=e&&r(e%10,0,1)||r(e%10,5,9)||r(e%100,12,14)?"many":1==e?"one":"other"},14:function t(e){return r(e%100,3,4)?"few":e%100==2?"two":e%100==1?"one":"other"},15:function t(e){return 0===e||r(e%100,2,10)?"few":r(e%100,11,19)?"many":1==e?"one":"other"},16:function t(e){return e%10==1&&11!=e?"one":"other"},17:function t(e){return 3==e?"few":0===e?"zero":6==e?"many":2==e?"two":1==e?"one":"other"},18:function t(e){return 0===e?"zero":r(e,0,2)&&0!==e&&2!=e?"one":"other"},19:function t(e){return r(e,2,10)?"few":r(e,0,1)?"one":"other"},20:function t(i){return!r(i%10,3,4)&&i%10!=9||r(i%100,10,19)||r(i%100,70,79)||r(i%100,90,99)?i%1e6==0&&0!==i?"many":i%10!=2||e(i%100,[12,72,92])?i%10!=1||e(i%100,[11,71,91])?"other":"one":"two":"few"},21:function t(e){return 0===e?"zero":1==e?"one":"other"},22:function t(e){return r(e,0,1)||r(e,11,99)?"one":"other"},23:function t(e){return r(e%10,1,2)||e%20==0?"one":"other"},24:function t(i){return r(i,3,10)||r(i,13,19)?"few":e(i,[2,12])?"two":e(i,[1,11])?"one":"other"}},o=i[t.replace(/-.*$/,"")];return o in n?n[o]:(console.warn("plural form unknown for ["+t+"]"),function(){return"other"})}function d(t,e,r){var i=y[t];if(!i){if(console.warn("#"+t+" is undefined."),!r)return null;i=r}var n={};for(var o in i){var a=i[o];a=p(a,e,t,o),a=g(a,e,t),n[o]=a}return n}function p(t,e,r,i){var n=/\{\[\s*([a-zA-Z]+)\(([a-zA-Z]+)\)\s*\]\}/,o=n.exec(t);if(!o||!o.length)return t;var a=o[1],s=o[2],c;if(e&&s in e?c=e[s]:s in y&&(c=y[s]),a in x){t=(0,x[a])(t,c,r,i)}return t}function g(t,e,r){var i=/\{\{\s*(.+?)\s*\}\}/g;return t.replace(i,function(t,i){return e&&i in e?e[i]:i in y?y[i]:(console.log("argument {{"+i+"}} for #"+r+" is undefined."),t)})}function v(t){var r=a(t);if(r.id){var i=d(r.id,r.args);if(!i)return void console.warn("#"+r.id+" is undefined.");if(i[w]){if(0===m(t))t[w]=i[w];else{for(var n=t.childNodes,o=!1,s=0,c=n.length;s<c;s++)3===n[s].nodeType&&/\S/.test(n[s].nodeValue)&&(o?n[s].nodeValue="":(n[s].nodeValue=i[w],o=!0));if(!o){var l=e.createTextNode(i[w]);t.insertBefore(l,t.firstChild)}}delete i[w]}for(var h in i)t[h]=i[h]}}function m(t){if(t.children)return t.children.length;if(void 0!==t.childElementCount)return t.childElementCount;for(var e=0,r=0;r<t.childNodes.length;r++)e+=1===t.nodeType?1:0;return e}function b(t){t=t||e.documentElement;for(var r=o(t),i=r.length,n=0;n<i;n++)v(r[n]);v(t)}var y={},_="",w="textContent",S="",x={},C="loading",A=!0;return x.plural=function(t,e,r,i){var n=parseFloat(e);if(isNaN(n))return t;if(i!=w)return t;x._pluralRules||(x._pluralRules=f(S));var o="["+x._pluralRules(n)+"]";return 0===n&&r+"[zero]"in y?t=y[r+"[zero]"][i]:1==n&&r+"[one]"in y?t=y[r+"[one]"][i]:2==n&&r+"[two]"in y?t=y[r+"[two]"][i]:r+o in y?t=y[r+o][i]:r+"[other]"in y&&(t=y[r+"[other]"][i]),t},{get:function t(e,r,i){var n=e.lastIndexOf("."),o=w;n>0&&(o=e.substr(n+1),e=e.substring(0,n));var a;i&&(a={},a[o]=i);var s=d(e,r,a);return s&&o in s?s[o]:"{{"+e+"}}"},getData:function t(){return y},getText:function t(){return _},getLanguage:function t(){return S},setLanguage:function t(e,r){h(e,function(){r&&r()})},getDirection:function t(){var e=["ar","he","fa","ps","ur"],r=S.split("-",1)[0];return e.indexOf(r)>=0?"rtl":"ltr"},translate:b,getReadyState:function t(){return C},ready:function r(i){i&&("complete"==C||"interactive"==C?t.setTimeout(function(){i()}):e.addEventListener&&e.addEventListener("localized",function t(){e.removeEventListener("localized",t),i()}))}}}(window,document)},function(t,e,r){"use strict";var i=r(0),n=r(12),o=r(5),a=r(3),s=r(6),c=r(4),l=r(11),h=r(10),u=r(1),f=r(8),d=r(9),p=i.PDFJS;p.PDFViewer=n.PDFViewer,p.PDFPageView=o.PDFPageView,p.PDFLinkService=a.PDFLinkService,p.TextLayerBuilder=s.TextLayerBuilder,p.DefaultTextLayerFactory=s.DefaultTextLayerFactory,p.AnnotationLayerBuilder=c.AnnotationLayerBuilder,p.DefaultAnnotationLayerFactory=c.DefaultAnnotationLayerFactory,p.PDFHistory=l.PDFHistory,p.PDFFindController=h.PDFFindController,p.EventBus=u.EventBus,p.DownloadManager=f.DownloadManager,p.ProgressBar=u.ProgressBar,p.GenericL10n=d.GenericL10n,p.NullL10n=u.NullL10n,e.PDFJS=p}])})},function(t,e,r){"use strict";function i(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===t[e-2]?2:"="===t[e-1]?1:0}function n(t){return 3*t.length/4-i(t)}function o(t){var e,r,n,o,a,s=t.length;o=i(t),a=new u(3*s/4-o),r=o>0?s-4:s;var c=0;for(e=0;e<r;e+=4)n=h[t.charCodeAt(e)]<<18|h[t.charCodeAt(e+1)]<<12|h[t.charCodeAt(e+2)]<<6|h[t.charCodeAt(e+3)],a[c++]=n>>16&255,a[c++]=n>>8&255,a[c++]=255&n;return 2===o?(n=h[t.charCodeAt(e)]<<2|h[t.charCodeAt(e+1)]>>4,a[c++]=255&n):1===o&&(n=h[t.charCodeAt(e)]<<10|h[t.charCodeAt(e+1)]<<4|h[t.charCodeAt(e+2)]>>2,a[c++]=n>>8&255,a[c++]=255&n),a}function a(t){return l[t>>18&63]+l[t>>12&63]+l[t>>6&63]+l[63&t]}function s(t,e,r){for(var i,n=[],o=e;o<r;o+=3)i=(t[o]<<16)+(t[o+1]<<8)+t[o+2],n.push(a(i));return n.join("")}function c(t){for(var e,r=t.length,i=r%3,n="",o=[],a=16383,c=0,h=r-i;c<h;c+=16383)o.push(s(t,c,c+16383>h?h:c+16383));return 1===i?(e=t[r-1],n+=l[e>>2],n+=l[e<<4&63],n+="=="):2===i&&(e=(t[r-2]<<8)+t[r-1],n+=l[e>>10],n+=l[e>>4&63],n+=l[e<<2&63],n+="="),o.push(n),o.join("")}e.byteLength=n,e.toByteArray=o,e.fromByteArray=c;for(var l=[],h=[],u="undefined"!=typeof Uint8Array?Uint8Array:Array,f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",d=0,p=f.length;d<p;++d)l[d]=f[d],h[f.charCodeAt(d)]=d;h["-".charCodeAt(0)]=62,h["_".charCodeAt(0)]=63},function(t,e){e.read=function(t,e,r,i,n){var o,a,s=8*n-i-1,c=(1<<s)-1,l=c>>1,h=-7,u=r?n-1:0,f=r?-1:1,d=t[e+u];for(u+=f,o=d&(1<<-h)-1,d>>=-h,h+=s;h>0;o=256*o+t[e+u],u+=f,h-=8);for(a=o&(1<<-h)-1,o>>=-h,h+=i;h>0;a=256*a+t[e+u],u+=f,h-=8);if(0===o)o=1-l;else{if(o===c)return a?NaN:1/0*(d?-1:1);a+=Math.pow(2,i),o-=l}return(d?-1:1)*a*Math.pow(2,o-i)},e.write=function(t,e,r,i,n,o){var a,s,c,l=8*o-n-1,h=(1<<l)-1,u=h>>1,f=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,d=i?0:o-1,p=i?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,a=h):(a=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-a))<1&&(a--,c*=2),e+=a+u>=1?f/c:f*Math.pow(2,1-u),e*c>=2&&(a++,c/=2),a+u>=h?(s=0,a=h):a+u>=1?(s=(e*c-1)*Math.pow(2,n),a+=u):(s=e*Math.pow(2,u-1)*Math.pow(2,n),a=0));n>=8;t[r+d]=255&s,d+=p,s/=256,n-=8);for(a=a<<n|s,l+=n;l>0;t[r+d]=255&a,d+=p,a/=256,l-=8);t[r+d-p]|=128*g}},function(t,e,r){(function(t,i){function n(e,r,i){function n(){for(var t;null!==(t=e.read());)s.push(t),c+=t.length;e.once("readable",n)}function o(t){e.removeListener("end",a),e.removeListener("readable",n),i(t)}function a(){var r=t.concat(s,c);s=[],i(null,r),e.close()}var s=[],c=0;e.on("error",o),e.on("end",a),e.end(r),n()}function o(e,r){if("string"==typeof r&&(r=new t(r)),!t.isBuffer(r))throw new TypeError("Not a string or buffer");var i=g.Z_FINISH;return e._processChunk(r,i)}function a(t){if(!(this instanceof a))return new a(t);d.call(this,t,g.DEFLATE)}function s(t){if(!(this instanceof s))return new s(t);d.call(this,t,g.INFLATE)}function c(t){if(!(this instanceof c))return new c(t);d.call(this,t,g.GZIP)}function l(t){if(!(this instanceof l))return new l(t);d.call(this,t,g.GUNZIP)}function h(t){if(!(this instanceof h))return new h(t);d.call(this,t,g.DEFLATERAW)}function u(t){if(!(this instanceof u))return new u(t);d.call(this,t,g.INFLATERAW)}function f(t){if(!(this instanceof f))return new f(t);d.call(this,t,g.UNZIP)}function d(r,i){if(this._opts=r=r||{},this._chunkSize=r.chunkSize||e.Z_DEFAULT_CHUNK,p.call(this,r),r.flush&&r.flush!==g.Z_NO_FLUSH&&r.flush!==g.Z_PARTIAL_FLUSH&&r.flush!==g.Z_SYNC_FLUSH&&r.flush!==g.Z_FULL_FLUSH&&r.flush!==g.Z_FINISH&&r.flush!==g.Z_BLOCK)throw new Error("Invalid flush flag: "+r.flush);if(this._flushFlag=r.flush||g.Z_NO_FLUSH,r.chunkSize&&(r.chunkSize<e.Z_MIN_CHUNK||r.chunkSize>e.Z_MAX_CHUNK))throw new Error("Invalid chunk size: "+r.chunkSize);if(r.windowBits&&(r.windowBits<e.Z_MIN_WINDOWBITS||r.windowBits>e.Z_MAX_WINDOWBITS))throw new Error("Invalid windowBits: "+r.windowBits);if(r.level&&(r.level<e.Z_MIN_LEVEL||r.level>e.Z_MAX_LEVEL))throw new Error("Invalid compression level: "+r.level);if(r.memLevel&&(r.memLevel<e.Z_MIN_MEMLEVEL||r.memLevel>e.Z_MAX_MEMLEVEL))throw new Error("Invalid memLevel: "+r.memLevel);if(r.strategy&&r.strategy!=e.Z_FILTERED&&r.strategy!=e.Z_HUFFMAN_ONLY&&r.strategy!=e.Z_RLE&&r.strategy!=e.Z_FIXED&&r.strategy!=e.Z_DEFAULT_STRATEGY)throw new Error("Invalid strategy: "+r.strategy);if(r.dictionary&&!t.isBuffer(r.dictionary))throw new Error("Invalid dictionary: it should be a Buffer instance");this._binding=new g.Zlib(i);var n=this;this._hadError=!1,this._binding.onerror=function(t,r){n._binding=null,n._hadError=!0;var i=new Error(t);i.errno=r,i.code=e.codes[r],n.emit("error",i)};var o=e.Z_DEFAULT_COMPRESSION;"number"==typeof r.level&&(o=r.level);var a=e.Z_DEFAULT_STRATEGY;"number"==typeof r.strategy&&(a=r.strategy),this._binding.init(r.windowBits||e.Z_DEFAULT_WINDOWBITS,o,r.memLevel||e.Z_DEFAULT_MEMLEVEL,a,r.dictionary),this._buffer=new t(this._chunkSize),this._offset=0,this._closed=!1,this._level=o,this._strategy=a,this.once("end",this.close)}var p=r(43),g=r(50),v=r(24),m=r(60).ok;g.Z_MIN_WINDOWBITS=8,g.Z_MAX_WINDOWBITS=15,g.Z_DEFAULT_WINDOWBITS=15,g.Z_MIN_CHUNK=64,g.Z_MAX_CHUNK=1/0,g.Z_DEFAULT_CHUNK=16384,g.Z_MIN_MEMLEVEL=1,g.Z_MAX_MEMLEVEL=9,g.Z_DEFAULT_MEMLEVEL=8,g.Z_MIN_LEVEL=-1,g.Z_MAX_LEVEL=9,g.Z_DEFAULT_LEVEL=g.Z_DEFAULT_COMPRESSION,Object.keys(g).forEach(function(t){t.match(/^Z/)&&(e[t]=g[t])}),e.codes={Z_OK:g.Z_OK,Z_STREAM_END:g.Z_STREAM_END,Z_NEED_DICT:g.Z_NEED_DICT,Z_ERRNO:g.Z_ERRNO,Z_STREAM_ERROR:g.Z_STREAM_ERROR,Z_DATA_ERROR:g.Z_DATA_ERROR,Z_MEM_ERROR:g.Z_MEM_ERROR,Z_BUF_ERROR:g.Z_BUF_ERROR,Z_VERSION_ERROR:g.Z_VERSION_ERROR},Object.keys(e.codes).forEach(function(t){e.codes[e.codes[t]]=t}),e.Deflate=a,e.Inflate=s,e.Gzip=c,e.Gunzip=l,e.DeflateRaw=h,e.InflateRaw=u,e.Unzip=f,e.createDeflate=function(t){return new a(t)},e.createInflate=function(t){return new s(t)},e.createDeflateRaw=function(t){return new h(t)},e.createInflateRaw=function(t){return new u(t)},e.createGzip=function(t){return new c(t)},e.createGunzip=function(t){return new l(t)},e.createUnzip=function(t){return new f(t)},e.deflate=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new a(e),t,r)},e.deflateSync=function(t,e){return o(new a(e),t)},e.gzip=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new c(e),t,r)},e.gzipSync=function(t,e){return o(new c(e),t)},e.deflateRaw=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new h(e),t,r)},e.deflateRawSync=function(t,e){return o(new h(e),t)},e.unzip=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new f(e),t,r)},e.unzipSync=function(t,e){return o(new f(e),t)},e.inflate=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new s(e),t,r)},e.inflateSync=function(t,e){return o(new s(e),t)},e.gunzip=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new l(e),t,r)},e.gunzipSync=function(t,e){return o(new l(e),t)},e.inflateRaw=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new u(e),t,r)},e.inflateRawSync=function(t,e){return o(new u(e),t)},v.inherits(d,p),d.prototype.params=function(t,r,n){if(t<e.Z_MIN_LEVEL||t>e.Z_MAX_LEVEL)throw new RangeError("Invalid compression level: "+t);if(r!=e.Z_FILTERED&&r!=e.Z_HUFFMAN_ONLY&&r!=e.Z_RLE&&r!=e.Z_FIXED&&r!=e.Z_DEFAULT_STRATEGY)throw new TypeError("Invalid strategy: "+r);if(this._level!==t||this._strategy!==r){var o=this;this.flush(g.Z_SYNC_FLUSH,function(){o._binding.params(t,r),o._hadError||(o._level=t,o._strategy=r,n&&n())})}else i.nextTick(n)},d.prototype.reset=function(){return this._binding.reset()},d.prototype._flush=function(e){this._transform(new t(0),"",e)},d.prototype.flush=function(e,r){var n=this._writableState;if(("function"==typeof e||void 0===e&&!r)&&(r=e,e=g.Z_FULL_FLUSH),n.ended)r&&i.nextTick(r);else if(n.ending)r&&this.once("end",r);else if(n.needDrain){var o=this;this.once("drain",function(){o.flush(r)})}else this._flushFlag=e,this.write(new t(0),"",r)},d.prototype.close=function(t){if(t&&i.nextTick(t),!this._closed){this._closed=!0,this._binding.close();var e=this;i.nextTick(function(){e.emit("close")})}},d.prototype._transform=function(e,r,i){var n,o=this._writableState,a=o.ending||o.ended,s=a&&(!e||o.length===e.length);if(null===!e&&!t.isBuffer(e))return i(new Error("invalid input"));s?n=g.Z_FINISH:(n=this._flushFlag,e.length>=o.length&&(this._flushFlag=this._opts.flush||g.Z_NO_FLUSH));var c=this;this._processChunk(e,n,i)},d.prototype._processChunk=function(e,r,i){function n(f,d){if(!c._hadError){var p=a-d;if(m(p>=0,"have should not go down"),p>0){var g=c._buffer.slice(c._offset,c._offset+p);c._offset+=p,l?c.push(g):(h.push(g),u+=g.length)}if((0===d||c._offset>=c._chunkSize)&&(a=c._chunkSize,c._offset=0,c._buffer=new t(c._chunkSize)),0===d){if(s+=o-f,o=f,!l)return!0;var v=c._binding.write(r,e,s,o,c._buffer,c._offset,c._chunkSize);return v.callback=n,void(v.buffer=e)}if(!l)return!1;i()}}var o=e&&e.length,a=this._chunkSize-this._offset,s=0,c=this,l="function"==typeof i;if(!l){var h=[],u=0,f;this.on("error",function(t){f=t});do{var d=this._binding.writeSync(r,e,s,o,this._buffer,this._offset,a)}while(!this._hadError&&n(d[0],d[1]));if(this._hadError)throw f;var p=t.concat(h,u);return this.close(),p}var g=this._binding.write(r,e,s,o,this._buffer,this._offset,a);g.buffer=e,g.callback=n},v.inherits(a,d),v.inherits(s,d),v.inherits(c,d),v.inherits(l,d),v.inherits(h,d),v.inherits(u,d),v.inherits(f,d)}).call(e,r(2).Buffer,r(1))},function(t,e,r){t.exports=r(9).Transform},function(t,e){},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e,r){t.copy(e,r)}var o=r(10).Buffer;t.exports=function(){function t(){i(this,t),this.head=null,this.tail=null,this.length=0}return t.prototype.push=function t(e){var r={data:e,next:null};this.length>0?this.tail.next=r:this.head=r,this.tail=r,++this.length},t.prototype.unshift=function t(e){var r={data:e,next:this.head};0===this.length&&(this.tail=r),this.head=r,++this.length},t.prototype.shift=function t(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},t.prototype.clear=function t(){this.head=this.tail=null,this.length=0},t.prototype.join=function t(e){if(0===this.length)return"";for(var r=this.head,i=""+r.data;r=r.next;)i+=e+r.data;return i},t.prototype.concat=function t(e){if(0===this.length)return o.alloc(0);if(1===this.length)return this.head.data;for(var r=o.allocUnsafe(e>>>0),i=this.head,a=0;i;)n(i.data,r,a),a+=i.data.length,i=i.next;return r},t}()},function(t,e,r){function i(t,e){this._id=t,this._clearFn=e}var n=Function.prototype.apply;e.setTimeout=function(){return new i(n.call(setTimeout,window,arguments),clearTimeout)},e.setInterval=function(){return new i(n.call(setInterval,window,arguments),clearInterval)},e.clearTimeout=e.clearInterval=function(t){t&&t.close()},i.prototype.unref=i.prototype.ref=function(){},i.prototype.close=function(){this._clearFn.call(window,this._id)},e.enroll=function(t,e){clearTimeout(t._idleTimeoutId),t._idleTimeout=e},e.unenroll=function(t){clearTimeout(t._idleTimeoutId),t._idleTimeout=-1},e._unrefActive=e.active=function(t){clearTimeout(t._idleTimeoutId);var e=t._idleTimeout;e>=0&&(t._idleTimeoutId=setTimeout(function e(){t._onTimeout&&t._onTimeout()},e))},r(47),e.setImmediate=setImmediate,e.clearImmediate=clearImmediate},function(t,e,r){(function(t,e){!function(t,r){"use strict";function i(t){"function"!=typeof t&&(t=new Function(""+t));for(var e=new Array(arguments.length-1),r=0;r<e.length;r++)e[r]=arguments[r+1];var i={callback:t,args:e};return p[d]=i,m(d),d++}function n(t){delete p[t]}function o(t){var e=t.callback,i=t.args;switch(i.length){case 0:e();break;case 1:e(i[0]);break;case 2:e(i[0],i[1]);break;case 3:e(i[0],i[1],i[2]);break;default:e.apply(r,i)}}function a(t){if(g)setTimeout(a,0,t);else{var e=p[t];if(e){g=!0;try{o(e)}finally{n(t),g=!1}}}}function s(){m=function(t){e.nextTick(function(){a(t)})}}function c(){if(t.postMessage&&!t.importScripts){var e=!0,r=t.onmessage;return t.onmessage=function(){e=!1},t.postMessage("","*"),t.onmessage=r,e}}function l(){var e="setImmediate$"+Math.random()+"$",r=function(r){r.source===t&&"string"==typeof r.data&&0===r.data.indexOf(e)&&a(+r.data.slice(e.length))};t.addEventListener?t.addEventListener("message",r,!1):t.attachEvent("onmessage",r),m=function(r){t.postMessage(e+r,"*")}}function h(){var t=new MessageChannel;t.port1.onmessage=function(t){a(t.data)},m=function(e){t.port2.postMessage(e)}}function u(){var t=v.documentElement;m=function(e){var r=v.createElement("script");r.onreadystatechange=function(){a(e),r.onreadystatechange=null,t.removeChild(r),r=null},t.appendChild(r)}}function f(){m=function(t){setTimeout(a,0,t)}}if(!t.setImmediate){var d=1,p={},g=!1,v=t.document,m,b=Object.getPrototypeOf&&Object.getPrototypeOf(t);b=b&&b.setTimeout?b:t,"[object process]"==={}.toString.call(t.process)?s():c()?l():t.MessageChannel?h():v&&"onreadystatechange"in v.createElement("script")?u():f(),b.setImmediate=i,b.clearImmediate=n}}("undefined"==typeof self?void 0===t?this:t:self)}).call(e,r(0),r(1))},function(t,e,r){(function(e){function r(t,e){function r(){if(!n){if(i("throwDeprecation"))throw new Error(e);i("traceDeprecation")?console.trace(e):console.warn(e),n=!0}return t.apply(this,arguments)}if(i("noDeprecation"))return t;var n=!1;return r}function i(t){try{if(!e.localStorage)return!1}catch(t){return!1}var r=e.localStorage[t];return null!=r&&"true"===String(r).toLowerCase()}t.exports=r}).call(e,r(0))},function(t,e,r){"use strict";function i(t){if(!(this instanceof i))return new i(t);n.call(this,t)}t.exports=i;var n=r(20),o=r(5);o.inherits=r(3),o.inherits(i,n),i.prototype._transform=function(t,e,r){r(null,t)}},function(t,e,r){(function(t,i){function n(t){if(t<e.DEFLATE||t>e.UNZIP)throw new TypeError("Bad argument");this.mode=t,this.init_done=!1,this.write_in_progress=!1,this.pending_close=!1,this.windowBits=0,this.level=0,this.memLevel=0,this.strategy=0,this.dictionary=null}function o(t,e){for(var r=0;r<t.length;r++)this[e+r]=t[r]}var a=r(21),s=r(51),c=r(52),l=r(54),h=r(57);for(var u in h)e[u]=h[u];e.NONE=0,e.DEFLATE=1,e.INFLATE=2,e.GZIP=3,e.GUNZIP=4,e.DEFLATERAW=5,e.INFLATERAW=6,e.UNZIP=7,n.prototype.init=function(t,r,i,n,o){switch(this.windowBits=t,this.level=r,this.memLevel=i,this.strategy=n,this.mode!==e.GZIP&&this.mode!==e.GUNZIP||(this.windowBits+=16),this.mode===e.UNZIP&&(this.windowBits+=32),this.mode!==e.DEFLATERAW&&this.mode!==e.INFLATERAW||(this.windowBits=-this.windowBits),this.strm=new s,this.mode){case e.DEFLATE:case e.GZIP:case e.DEFLATERAW:var a=c.deflateInit2(this.strm,this.level,e.Z_DEFLATED,this.windowBits,this.memLevel,this.strategy);break;case e.INFLATE:case e.GUNZIP:case e.INFLATERAW:case e.UNZIP:var a=l.inflateInit2(this.strm,this.windowBits);break;default:throw new Error("Unknown mode "+this.mode)}if(a!==e.Z_OK)return void this._error(a);this.write_in_progress=!1,this.init_done=!0},n.prototype.params=function(){throw new Error("deflateParams Not supported")},n.prototype._writeCheck=function(){if(!this.init_done)throw new Error("write before init");if(this.mode===e.NONE)throw new Error("already finalized");if(this.write_in_progress)throw new Error("write already in progress");if(this.pending_close)throw new Error("close is pending")},n.prototype.write=function(e,r,i,n,o,a,s){this._writeCheck(),this.write_in_progress=!0;var c=this;return t.nextTick(function(){c.write_in_progress=!1;var t=c._write(e,r,i,n,o,a,s);c.callback(t[0],t[1]),c.pending_close&&c.close()}),this},n.prototype.writeSync=function(t,e,r,i,n,o,a){return this._writeCheck(),this._write(t,e,r,i,n,o,a)},n.prototype._write=function(t,r,n,a,s,h,u){if(this.write_in_progress=!0,t!==e.Z_NO_FLUSH&&t!==e.Z_PARTIAL_FLUSH&&t!==e.Z_SYNC_FLUSH&&t!==e.Z_FULL_FLUSH&&t!==e.Z_FINISH&&t!==e.Z_BLOCK)throw new Error("Invalid flush value");null==r&&(r=new i(0),a=0,n=0),s._set?s.set=s._set:s.set=o;var f=this.strm;switch(f.avail_in=a,f.input=r,f.next_in=n,f.avail_out=u,f.output=s,f.next_out=h,this.mode){case e.DEFLATE:case e.GZIP:case e.DEFLATERAW:var d=c.deflate(f,t);break;case e.UNZIP:case e.INFLATE:case e.GUNZIP:case e.INFLATERAW:var d=l.inflate(f,t);break;default:throw new Error("Unknown mode "+this.mode)}return d!==e.Z_STREAM_END&&d!==e.Z_OK&&this._error(d),this.write_in_progress=!1,[f.avail_in,f.avail_out]},n.prototype.close=function(){if(this.write_in_progress)return void(this.pending_close=!0);this.pending_close=!1,this.mode===e.DEFLATE||this.mode===e.GZIP||this.mode===e.DEFLATERAW?c.deflateEnd(this.strm):l.inflateEnd(this.strm),this.mode=e.NONE},n.prototype.reset=function(){switch(this.mode){case e.DEFLATE:case e.DEFLATERAW:var t=c.deflateReset(this.strm);break;case e.INFLATE:case e.INFLATERAW:var t=l.inflateReset(this.strm)}t!==e.Z_OK&&this._error(t)},n.prototype._error=function(t){this.onerror(a[t]+": "+this.strm.msg,t),this.write_in_progress=!1,this.pending_close&&this.close()},e.Zlib=n}).call(e,r(1),r(2).Buffer)},function(t,e,r){"use strict";function i(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}t.exports=i},function(t,e,r){"use strict";function i(t,e){return t.msg=D[e],e}function n(t){return(t<<1)-(t>4?9:0)}function o(t){for(var e=t.length;--e>=0;)t[e]=0}function a(t){var e=t.state,r=e.pending;r>t.avail_out&&(r=t.avail_out),0!==r&&(E.arraySet(t.output,e.pending_buf,e.pending_out,r,t.next_out),t.next_out+=r,e.pending_out+=r,t.total_out+=r,t.avail_out-=r,e.pending-=r,0===e.pending&&(e.pending_out=0))}function s(t,e){O._tr_flush_block(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,a(t.strm)}function c(t,e){t.pending_buf[t.pending++]=e}function l(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e}function h(t,e,r,i){var n=t.avail_in;return n>i&&(n=i),0===n?0:(t.avail_in-=n,E.arraySet(e,t.input,t.next_in,n,r),1===t.state.wrap?t.adler=R(t.adler,e,n,r):2===t.state.wrap&&(t.adler=L(t.adler,e,n,r)),t.next_in+=n,t.total_in+=n,n)}function u(t,e){var r=t.max_chain_length,i=t.strstart,n,o,a=t.prev_length,s=t.nice_match,c=t.strstart>t.w_size-ht?t.strstart-(t.w_size-ht):0,l=t.window,h=t.w_mask,u=t.prev,f=t.strstart+lt,d=l[i+a-1],p=l[i+a];t.prev_length>=t.good_match&&(r>>=2),s>t.lookahead&&(s=t.lookahead);do{if(n=e,l[n+a]===p&&l[n+a-1]===d&&l[n]===l[i]&&l[++n]===l[i+1]){i+=2,n++;do{}while(l[++i]===l[++n]&&l[++i]===l[++n]&&l[++i]===l[++n]&&l[++i]===l[++n]&&l[++i]===l[++n]&&l[++i]===l[++n]&&l[++i]===l[++n]&&l[++i]===l[++n]&&i<f);if(o=lt-(f-i),i=f-lt,o>a){if(t.match_start=e,a=o,o>=s)break;d=l[i+a-1],p=l[i+a]}}}while((e=u[e&h])>c&&0!=--r);return a<=t.lookahead?a:t.lookahead}function f(t){var e=t.w_size,r,i,n,o,a;do{if(o=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-ht)){E.arraySet(t.window,t.window,e,e,0),t.match_start-=e,t.strstart-=e,t.block_start-=e,i=t.hash_size,r=i;do{n=t.head[--r],t.head[r]=n>=e?n-e:0}while(--i);i=e,r=i;do{n=t.prev[--r],t.prev[r]=n>=e?n-e:0}while(--i);o+=e}if(0===t.strm.avail_in)break;if(i=h(t.strm,t.window,t.strstart+t.lookahead,o),t.lookahead+=i,t.lookahead+t.insert>=ct)for(a=t.strstart-t.insert,t.ins_h=t.window[a],t.ins_h=(t.ins_h<<t.hash_shift^t.window[a+1])&t.hash_mask;t.insert&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[a+ct-1])&t.hash_mask,t.prev[a&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=a,a++,t.insert--,!(t.lookahead+t.insert<ct)););}while(t.lookahead<ht&&0!==t.strm.avail_in)}function d(t,e){var r=65535;for(r>t.pending_buf_size-5&&(r=t.pending_buf_size-5);;){if(t.lookahead<=1){if(f(t),0===t.lookahead&&e===I)return yt;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;var i=t.block_start+r;if((0===t.strstart||t.strstart>=i)&&(t.lookahead=t.strstart-i,t.strstart=i,s(t,!1),0===t.strm.avail_out))return yt;if(t.strstart-t.block_start>=t.w_size-ht&&(s(t,!1),0===t.strm.avail_out))return yt}return t.insert=0,e===F?(s(t,!0),0===t.strm.avail_out?wt:St):(t.strstart>t.block_start&&(s(t,!1),t.strm.avail_out),yt)}function p(t,e){for(var r,i;;){if(t.lookahead<ht){if(f(t),t.lookahead<ht&&e===I)return yt;if(0===t.lookahead)break}if(r=0,t.lookahead>=ct&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+ct-1])&t.hash_mask,r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==r&&t.strstart-r<=t.w_size-ht&&(t.match_length=u(t,r)),t.match_length>=ct)if(i=O._tr_tally(t,t.strstart-t.match_start,t.match_length-ct),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=ct){t.match_length--;do{t.strstart++,t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+ct-1])&t.hash_mask,r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!=--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+1])&t.hash_mask;else i=O._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(i&&(s(t,!1),0===t.strm.avail_out))return yt}return t.insert=t.strstart<ct-1?t.strstart:ct-1,e===F?(s(t,!0),0===t.strm.avail_out?wt:St):t.last_lit&&(s(t,!1),0===t.strm.avail_out)?yt:_t}function g(t,e){for(var r,i,n;;){if(t.lookahead<ht){if(f(t),t.lookahead<ht&&e===I)return yt;if(0===t.lookahead)break}if(r=0,t.lookahead>=ct&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+ct-1])&t.hash_mask,r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=ct-1,0!==r&&t.prev_length<t.max_lazy_match&&t.strstart-r<=t.w_size-ht&&(t.match_length=u(t,r),t.match_length<=5&&(t.strategy===G||t.match_length===ct&&t.strstart-t.match_start>4096)&&(t.match_length=ct-1)),t.prev_length>=ct&&t.match_length<=t.prev_length){n=t.strstart+t.lookahead-ct,i=O._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-ct),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=n&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+ct-1])&t.hash_mask,r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!=--t.prev_length);if(t.match_available=0,t.match_length=ct-1,t.strstart++,i&&(s(t,!1),0===t.strm.avail_out))return yt}else if(t.match_available){if(i=O._tr_tally(t,0,t.window[t.strstart-1]),i&&s(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return yt}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(i=O._tr_tally(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<ct-1?t.strstart:ct-1,e===F?(s(t,!0),0===t.strm.avail_out?wt:St):t.last_lit&&(s(t,!1),0===t.strm.avail_out)?yt:_t}function v(t,e){for(var r,i,n,o,a=t.window;;){if(t.lookahead<=lt){if(f(t),t.lookahead<=lt&&e===I)return yt;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=ct&&t.strstart>0&&(n=t.strstart-1,(i=a[n])===a[++n]&&i===a[++n]&&i===a[++n])){o=t.strstart+lt;do{}while(i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&n<o);t.match_length=lt-(o-n),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=ct?(r=O._tr_tally(t,1,t.match_length-ct),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(r=O._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),r&&(s(t,!1),0===t.strm.avail_out))return yt}return t.insert=0,e===F?(s(t,!0),0===t.strm.avail_out?wt:St):t.last_lit&&(s(t,!1),0===t.strm.avail_out)?yt:_t}function m(t,e){for(var r;;){if(0===t.lookahead&&(f(t),0===t.lookahead)){if(e===I)return yt;break}if(t.match_length=0,r=O._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,r&&(s(t,!1),0===t.strm.avail_out))return yt}return t.insert=0,e===F?(s(t,!0),0===t.strm.avail_out?wt:St):t.last_lit&&(s(t,!1),0===t.strm.avail_out)?yt:_t}function b(t,e,r,i,n){this.good_length=t,this.max_lazy=e,this.nice_length=r,this.max_chain=i,this.func=n}function y(t){t.window_size=2*t.w_size,o(t.head),t.max_lazy_match=Ct[t.level].max_lazy,t.good_match=Ct[t.level].good_length,t.nice_match=Ct[t.level].nice_length,t.max_chain_length=Ct[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=ct-1,t.match_available=0,t.ins_h=0}function _(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=K,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new E.Buf16(2*at),this.dyn_dtree=new E.Buf16(2*(2*nt+1)),this.bl_tree=new E.Buf16(2*(2*ot+1)),o(this.dyn_ltree),o(this.dyn_dtree),o(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new E.Buf16(st+1),this.heap=new E.Buf16(2*it+1),o(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new E.Buf16(2*it+1),o(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function w(t){var e;return t&&t.state?(t.total_in=t.total_out=0,t.data_type=J,e=t.state,e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?ft:mt,t.adler=2===e.wrap?0:1,e.last_flush=I,O._tr_init(e),B):i(t,z)}function S(t){var e=w(t);return e===B&&y(t.state),e}function x(t,e){return t&&t.state?2!==t.state.wrap?z:(t.state.gzhead=e,B):z}function C(t,e,r,n,o,a){if(!t)return z;var s=1;if(e===X&&(e=6),n<0?(s=0,n=-n):n>15&&(s=2,n-=16),o<1||o>Q||r!==K||n<8||n>15||e<0||e>9||a<0||a>V)return i(t,z);8===n&&(n=9);var c=new _;return t.state=c,c.strm=t,c.wrap=s,c.gzhead=null,c.w_bits=n,c.w_size=1<<c.w_bits,c.w_mask=c.w_size-1,c.hash_bits=o+7,c.hash_size=1<<c.hash_bits,c.hash_mask=c.hash_size-1,c.hash_shift=~~((c.hash_bits+ct-1)/ct),c.window=new E.Buf8(2*c.w_size),c.head=new E.Buf16(c.hash_size),c.prev=new E.Buf16(c.w_size),c.lit_bufsize=1<<o+6,c.pending_buf_size=4*c.lit_bufsize,c.pending_buf=new E.Buf8(c.pending_buf_size),c.d_buf=1*c.lit_bufsize,c.l_buf=3*c.lit_bufsize,c.level=e,c.strategy=a,c.method=r,S(t)}function A(t,e){return C(t,e,K,$,tt,Z)}function T(t,e){var r,s,h,u;if(!t||!t.state||e>N||e<0)return t?i(t,z):z;if(s=t.state,!t.output||!t.input&&0!==t.avail_in||s.status===bt&&e!==F)return i(t,0===t.avail_out?q:z);if(s.strm=t,r=s.last_flush,s.last_flush=e,s.status===ft)if(2===s.wrap)t.adler=0,c(s,31),c(s,139),c(s,8),s.gzhead?(c(s,(s.gzhead.text?1:0)+(s.gzhead.hcrc?2:0)+(s.gzhead.extra?4:0)+(s.gzhead.name?8:0)+(s.gzhead.comment?16:0)),c(s,255&s.gzhead.time),c(s,s.gzhead.time>>8&255),c(s,s.gzhead.time>>16&255),c(s,s.gzhead.time>>24&255),c(s,9===s.level?2:s.strategy>=H||s.level<2?4:0),c(s,255&s.gzhead.os),s.gzhead.extra&&s.gzhead.extra.length&&(c(s,255&s.gzhead.extra.length),c(s,s.gzhead.extra.length>>8&255)),s.gzhead.hcrc&&(t.adler=L(t.adler,s.pending_buf,s.pending,0)),s.gzindex=0,s.status=dt):(c(s,0),c(s,0),c(s,0),c(s,0),c(s,0),c(s,9===s.level?2:s.strategy>=H||s.level<2?4:0),c(s,xt),s.status=mt);else{var f=K+(s.w_bits-8<<4)<<8,d=-1;d=s.strategy>=H||s.level<2?0:s.level<6?1:6===s.level?2:3,f|=d<<6,0!==s.strstart&&(f|=ut),f+=31-f%31,s.status=mt,l(s,f),0!==s.strstart&&(l(s,t.adler>>>16),l(s,65535&t.adler)),t.adler=1}if(s.status===dt)if(s.gzhead.extra){for(h=s.pending;s.gzindex<(65535&s.gzhead.extra.length)&&(s.pending!==s.pending_buf_size||(s.gzhead.hcrc&&s.pending>h&&(t.adler=L(t.adler,s.pending_buf,s.pending-h,h)),a(t),h=s.pending,s.pending!==s.pending_buf_size));)c(s,255&s.gzhead.extra[s.gzindex]),s.gzindex++;s.gzhead.hcrc&&s.pending>h&&(t.adler=L(t.adler,s.pending_buf,s.pending-h,h)),s.gzindex===s.gzhead.extra.length&&(s.gzindex=0,s.status=pt)}else s.status=pt;if(s.status===pt)if(s.gzhead.name){h=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>h&&(t.adler=L(t.adler,s.pending_buf,s.pending-h,h)),a(t),h=s.pending,s.pending===s.pending_buf_size)){u=1;break}u=s.gzindex<s.gzhead.name.length?255&s.gzhead.name.charCodeAt(s.gzindex++):0,c(s,u)}while(0!==u);s.gzhead.hcrc&&s.pending>h&&(t.adler=L(t.adler,s.pending_buf,s.pending-h,h)),0===u&&(s.gzindex=0,s.status=gt)}else s.status=gt;if(s.status===gt)if(s.gzhead.comment){h=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>h&&(t.adler=L(t.adler,s.pending_buf,s.pending-h,h)),a(t),h=s.pending,s.pending===s.pending_buf_size)){u=1;break}u=s.gzindex<s.gzhead.comment.length?255&s.gzhead.comment.charCodeAt(s.gzindex++):0,c(s,u)}while(0!==u);s.gzhead.hcrc&&s.pending>h&&(t.adler=L(t.adler,s.pending_buf,s.pending-h,h)),0===u&&(s.status=vt)}else s.status=vt;if(s.status===vt&&(s.gzhead.hcrc?(s.pending+2>s.pending_buf_size&&a(t),s.pending+2<=s.pending_buf_size&&(c(s,255&t.adler),c(s,t.adler>>8&255),t.adler=0,s.status=mt)):s.status=mt),0!==s.pending){if(a(t),0===t.avail_out)return s.last_flush=-1,B}else if(0===t.avail_in&&n(e)<=n(r)&&e!==F)return i(t,q);if(s.status===bt&&0!==t.avail_in)return i(t,q);if(0!==t.avail_in||0!==s.lookahead||e!==I&&s.status!==bt){var p=s.strategy===H?m(s,e):s.strategy===Y?v(s,e):Ct[s.level].func(s,e);if(p!==wt&&p!==St||(s.status=bt),p===yt||p===wt)return 0===t.avail_out&&(s.last_flush=-1),B;if(p===_t&&(e===j?O._tr_align(s):e!==N&&(O._tr_stored_block(s,0,0,!1),e===M&&(o(s.head),0===s.lookahead&&(s.strstart=0,s.block_start=0,s.insert=0))),a(t),0===t.avail_out))return s.last_flush=-1,B}return e!==F?B:s.wrap<=0?U:(2===s.wrap?(c(s,255&t.adler),c(s,t.adler>>8&255),c(s,t.adler>>16&255),c(s,t.adler>>24&255),c(s,255&t.total_in),c(s,t.total_in>>8&255),c(s,t.total_in>>16&255),c(s,t.total_in>>24&255)):(l(s,t.adler>>>16),l(s,65535&t.adler)),a(t),s.wrap>0&&(s.wrap=-s.wrap),0!==s.pending?B:U)}function k(t){var e;return t&&t.state?(e=t.state.status)!==ft&&e!==dt&&e!==pt&&e!==gt&&e!==vt&&e!==mt&&e!==bt?i(t,z):(t.state=null,e===mt?i(t,W):B):z}function P(t,e){var r=e.length,i,n,a,s,c,l,h,u;if(!t||!t.state)return z;if(i=t.state,2===(s=i.wrap)||1===s&&i.status!==ft||i.lookahead)return z;for(1===s&&(t.adler=R(t.adler,e,r,0)),i.wrap=0,r>=i.w_size&&(0===s&&(o(i.head),i.strstart=0,i.block_start=0,i.insert=0),u=new E.Buf8(i.w_size),E.arraySet(u,e,r-i.w_size,i.w_size,0),e=u,r=i.w_size),c=t.avail_in,l=t.next_in,h=t.input,t.avail_in=r,t.next_in=0,t.input=e,f(i);i.lookahead>=ct;){n=i.strstart,a=i.lookahead-(ct-1);do{i.ins_h=(i.ins_h<<i.hash_shift^i.window[n+ct-1])&i.hash_mask,i.prev[n&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=n,n++}while(--a);i.strstart=n,i.lookahead=ct-1,f(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=ct-1,i.match_available=0,t.next_in=l,t.input=h,t.avail_in=c,i.wrap=s,B}var E=r(8),O=r(53),R=r(22),L=r(23),D=r(21),I=0,j=1,M=3,F=4,N=5,B=0,U=1,z=-2,W=-3,q=-5,X=-1,G=1,H=2,Y=3,V=4,Z=0,J=2,K=8,Q=9,$=15,tt=8,et=29,rt=256,it=286,nt=30,ot=19,at=2*it+1,st=15,ct=3,lt=258,ht=lt+ct+1,ut=32,ft=42,dt=69,pt=73,gt=91,vt=103,mt=113,bt=666,yt=1,_t=2,wt=3,St=4,xt=3,Ct;Ct=[new b(0,0,0,0,d),new b(4,4,8,4,p),new b(4,5,16,8,p),new b(4,6,32,32,p),new b(4,4,16,16,g),new b(8,16,32,32,g),new b(8,16,128,128,g),new b(8,32,128,256,g),new b(32,128,258,1024,g),new b(32,258,258,4096,g)],e.deflateInit=A,e.deflateInit2=C,e.deflateReset=S,e.deflateResetKeep=w,e.deflateSetHeader=x,e.deflate=T,e.deflateEnd=k,e.deflateSetDictionary=P,e.deflateInfo="pako deflate (from Nodeca project)"},function(t,e,r){"use strict";function i(t){for(var e=t.length;--e>=0;)t[e]=0}function n(t,e,r,i,n){this.static_tree=t,this.extra_bits=e,this.extra_base=r,this.elems=i,this.max_length=n,this.has_stree=t&&t.length}function o(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}function a(t){return t<256?ct[t]:ct[256+(t>>>7)]}function s(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255}function c(t,e,r){t.bi_valid>Z-r?(t.bi_buf|=e<<t.bi_valid&65535,s(t,t.bi_buf),t.bi_buf=e>>Z-t.bi_valid,t.bi_valid+=r-Z):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=r)}function l(t,e,r){c(t,r[2*e],r[2*e+1])}function h(t,e){var r=0;do{r|=1&t,t>>>=1,r<<=1}while(--e>0);return r>>>1}function u(t){16===t.bi_valid?(s(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)}function f(t,e){var r=e.dyn_tree,i=e.max_code,n=e.stat_desc.static_tree,o=e.stat_desc.has_stree,a=e.stat_desc.extra_bits,s=e.stat_desc.extra_base,c=e.stat_desc.max_length,l,h,u,f,d,p,g=0;for(f=0;f<=V;f++)t.bl_count[f]=0;for(r[2*t.heap[t.heap_max]+1]=0,l=t.heap_max+1;l<Y;l++)h=t.heap[l],f=r[2*r[2*h+1]+1]+1,f>c&&(f=c,g++),r[2*h+1]=f,h>i||(t.bl_count[f]++,d=0,h>=s&&(d=a[h-s]),p=r[2*h],t.opt_len+=p*(f+d),o&&(t.static_len+=p*(n[2*h+1]+d)));if(0!==g){do{for(f=c-1;0===t.bl_count[f];)f--;t.bl_count[f]--,t.bl_count[f+1]+=2,t.bl_count[c]--,g-=2}while(g>0);for(f=c;0!==f;f--)for(h=t.bl_count[f];0!==h;)(u=t.heap[--l])>i||(r[2*u+1]!==f&&(t.opt_len+=(f-r[2*u+1])*r[2*u],r[2*u+1]=f),h--)}}function d(t,e,r){var i=new Array(V+1),n=0,o,a;for(o=1;o<=V;o++)i[o]=n=n+r[o-1]<<1;for(a=0;a<=e;a++){var s=t[2*a+1];0!==s&&(t[2*a]=h(i[s]++,s))}}function p(){var t,e,r,i,o,a=new Array(V+1);for(r=0,i=0;i<W-1;i++)for(ht[i]=r,t=0;t<1<<et[i];t++)lt[r++]=i;for(lt[r-1]=i,o=0,i=0;i<16;i++)for(ut[i]=o,t=0;t<1<<rt[i];t++)ct[o++]=i;for(o>>=7;i<G;i++)for(ut[i]=o<<7,t=0;t<1<<rt[i]-7;t++)ct[256+o++]=i;for(e=0;e<=V;e++)a[e]=0;for(t=0;t<=143;)at[2*t+1]=8,t++,a[8]++;for(;t<=255;)at[2*t+1]=9,t++,a[9]++;for(;t<=279;)at[2*t+1]=7,t++,a[7]++;for(;t<=287;)at[2*t+1]=8,t++,a[8]++;for(d(at,X+1,a),t=0;t<G;t++)st[2*t+1]=5,st[2*t]=h(t,5);ft=new n(at,et,q+1,X,V),dt=new n(st,rt,0,G,V),pt=new n(new Array(0),it,0,H,J)}function g(t){var e;for(e=0;e<X;e++)t.dyn_ltree[2*e]=0;for(e=0;e<G;e++)t.dyn_dtree[2*e]=0;for(e=0;e<H;e++)t.bl_tree[2*e]=0;t.dyn_ltree[2*K]=1,t.opt_len=t.static_len=0,t.last_lit=t.matches=0}function v(t){t.bi_valid>8?s(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0}function m(t,e,r,i){v(t),i&&(s(t,r),s(t,~r)),L.arraySet(t.pending_buf,t.window,e,r,t.pending),t.pending+=r}function b(t,e,r,i){var n=2*e,o=2*r;return t[n]<t[o]||t[n]===t[o]&&i[e]<=i[r]}function y(t,e,r){for(var i=t.heap[r],n=r<<1;n<=t.heap_len&&(n<t.heap_len&&b(e,t.heap[n+1],t.heap[n],t.depth)&&n++,!b(e,i,t.heap[n],t.depth));)t.heap[r]=t.heap[n],r=n,n<<=1;t.heap[r]=i}function _(t,e,r){var i,n,o=0,s,h;if(0!==t.last_lit)do{i=t.pending_buf[t.d_buf+2*o]<<8|t.pending_buf[t.d_buf+2*o+1],n=t.pending_buf[t.l_buf+o],o++,0===i?l(t,n,e):(s=lt[n],l(t,s+q+1,e),h=et[s],0!==h&&(n-=ht[s],c(t,n,h)),i--,s=a(i),l(t,s,r),0!==(h=rt[s])&&(i-=ut[s],c(t,i,h)))}while(o<t.last_lit);l(t,K,e)}function w(t,e){var r=e.dyn_tree,i=e.stat_desc.static_tree,n=e.stat_desc.has_stree,o=e.stat_desc.elems,a,s,c=-1,l;for(t.heap_len=0,t.heap_max=Y,a=0;a<o;a++)0!==r[2*a]?(t.heap[++t.heap_len]=c=a,t.depth[a]=0):r[2*a+1]=0;for(;t.heap_len<2;)l=t.heap[++t.heap_len]=c<2?++c:0,r[2*l]=1,t.depth[l]=0,t.opt_len--,n&&(t.static_len-=i[2*l+1]);for(e.max_code=c,a=t.heap_len>>1;a>=1;a--)y(t,r,a);l=o;do{a=t.heap[1],t.heap[1]=t.heap[t.heap_len--],y(t,r,1),s=t.heap[1],t.heap[--t.heap_max]=a,t.heap[--t.heap_max]=s,r[2*l]=r[2*a]+r[2*s],t.depth[l]=(t.depth[a]>=t.depth[s]?t.depth[a]:t.depth[s])+1,r[2*a+1]=r[2*s+1]=l,t.heap[1]=l++,y(t,r,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],f(t,e),d(r,c,t.bl_count)}function S(t,e,r){var i,n=-1,o,a=e[1],s=0,c=7,l=4;for(0===a&&(c=138,l=3),e[2*(r+1)+1]=65535,i=0;i<=r;i++)o=a,a=e[2*(i+1)+1],++s<c&&o===a||(s<l?t.bl_tree[2*o]+=s:0!==o?(o!==n&&t.bl_tree[2*o]++,t.bl_tree[2*Q]++):s<=10?t.bl_tree[2*$]++:t.bl_tree[2*tt]++,s=0,n=o,0===a?(c=138,l=3):o===a?(c=6,l=3):(c=7,l=4))}function x(t,e,r){var i,n=-1,o,a=e[1],s=0,h=7,u=4;for(0===a&&(h=138,u=3),i=0;i<=r;i++)if(o=a,a=e[2*(i+1)+1],!(++s<h&&o===a)){if(s<u)do{l(t,o,t.bl_tree)}while(0!=--s);else 0!==o?(o!==n&&(l(t,o,t.bl_tree),s--),l(t,Q,t.bl_tree),c(t,s-3,2)):s<=10?(l(t,$,t.bl_tree),c(t,s-3,3)):(l(t,tt,t.bl_tree),c(t,s-11,7));s=0,n=o,0===a?(h=138,u=3):o===a?(h=6,u=3):(h=7,u=4)}}function C(t){var e;for(S(t,t.dyn_ltree,t.l_desc.max_code),S(t,t.dyn_dtree,t.d_desc.max_code),w(t,t.bl_desc),e=H-1;e>=3&&0===t.bl_tree[2*nt[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e}function A(t,e,r,i){var n;for(c(t,e-257,5),c(t,r-1,5),c(t,i-4,4),n=0;n<i;n++)c(t,t.bl_tree[2*nt[n]+1],3);x(t,t.dyn_ltree,e-1),x(t,t.dyn_dtree,r-1)}function T(t){var e=4093624447,r;for(r=0;r<=31;r++,e>>>=1)if(1&e&&0!==t.dyn_ltree[2*r])return I;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return j;for(r=32;r<q;r++)if(0!==t.dyn_ltree[2*r])return j;return I}function k(t){gt||(p(),gt=!0),t.l_desc=new o(t.dyn_ltree,ft),t.d_desc=new o(t.dyn_dtree,dt),t.bl_desc=new o(t.bl_tree,pt),t.bi_buf=0,t.bi_valid=0,g(t)}function P(t,e,r,i){c(t,(F<<1)+(i?1:0),3),m(t,e,r,!0)}function E(t){c(t,N<<1,3),l(t,K,at),u(t)}function O(t,e,r,i){var n,o,a=0;t.level>0?(t.strm.data_type===M&&(t.strm.data_type=T(t)),w(t,t.l_desc),w(t,t.d_desc),a=C(t),n=t.opt_len+3+7>>>3,(o=t.static_len+3+7>>>3)<=n&&(n=o)):n=o=r+5,r+4<=n&&-1!==e?P(t,e,r,i):t.strategy===D||o===n?(c(t,(N<<1)+(i?1:0),3),_(t,at,st)):(c(t,(B<<1)+(i?1:0),3),A(t,t.l_desc.max_code+1,t.d_desc.max_code+1,a+1),_(t,t.dyn_ltree,t.dyn_dtree)),g(t),i&&v(t)}function R(t,e,r){return t.pending_buf[t.d_buf+2*t.last_lit]=e>>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&r,t.last_lit++,0===e?t.dyn_ltree[2*r]++:(t.matches++,e--,t.dyn_ltree[2*(lt[r]+q+1)]++,t.dyn_dtree[2*a(e)]++),t.last_lit===t.lit_bufsize-1}var L=r(8),D=4,I=0,j=1,M=2,F=0,N=1,B=2,U=3,z=258,W=29,q=256,X=q+1+W,G=30,H=19,Y=2*X+1,V=15,Z=16,J=7,K=256,Q=16,$=17,tt=18,et=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],rt=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],it=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],nt=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],ot=512,at=new Array(2*(X+2));i(at);var st=new Array(2*G);i(st);var ct=new Array(512);i(ct);var lt=new Array(256);i(lt);var ht=new Array(W);i(ht);var ut=new Array(G);i(ut);var ft,dt,pt,gt=!1;e._tr_init=k,e._tr_stored_block=P,e._tr_flush_block=O,e._tr_tally=R,e._tr_align=E},function(t,e,r){"use strict";function i(t){return(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24)}function n(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new v.Buf16(320),this.work=new v.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function o(t){var e;return t&&t.state?(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=j,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new v.Buf32(dt),e.distcode=e.distdyn=new v.Buf32(pt),e.sane=1,e.back=-1,k):O}function a(t){var e;return t&&t.state?(e=t.state,e.wsize=0,e.whave=0,e.wnext=0,o(t)):O}function s(t,e){var r,i;return t&&t.state?(i=t.state,e<0?(r=0,e=-e):(r=1+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?O:(null!==i.window&&i.wbits!==e&&(i.window=null),i.wrap=r,i.wbits=e,a(t))):O}function c(t,e){var r,i;return t?(i=new n,t.state=i,i.window=null,r=s(t,e),r!==k&&(t.state=null),r):O}function l(t){return c(t,vt)}function h(t){if(mt){var e;for(bt=new v.Buf32(512),yt=new v.Buf32(32),e=0;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(_(S,t.lens,0,288,bt,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;_(x,t.lens,0,32,yt,0,t.work,{bits:5}),mt=!1}t.lencode=bt,t.lenbits=9,t.distcode=yt,t.distbits=5}function u(t,e,r,i){var n,o=t.state;return null===o.window&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new v.Buf8(o.wsize)),i>=o.wsize?(v.arraySet(o.window,e,r-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(n=o.wsize-o.wnext,n>i&&(n=i),v.arraySet(o.window,e,r-i,n,o.wnext),i-=n,i?(v.arraySet(o.window,e,r-i,i,0),o.wnext=i,o.whave=o.wsize):(o.wnext+=n,o.wnext===o.wsize&&(o.wnext=0),o.whave<o.wsize&&(o.whave+=n))),0}function f(t,e){var r,n,o,a,s,c,l,f,d,p,g,dt,pt,gt,vt=0,mt,bt,yt,_t,wt,St,xt,Ct,At=new v.Buf8(4),Tt,kt,Pt=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!t||!t.state||!t.output||!t.input&&0!==t.avail_in)return O;r=t.state,r.mode===H&&(r.mode=Y),s=t.next_out,o=t.output,l=t.avail_out,a=t.next_in,n=t.input,c=t.avail_in,f=r.hold,d=r.bits,p=c,g=l,Ct=k;t:for(;;)switch(r.mode){case j:if(0===r.wrap){r.mode=Y;break}for(;d<16;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(2&r.wrap&&35615===f){r.check=0,At[0]=255&f,At[1]=f>>>8&255,r.check=b(r.check,At,2,0),f=0,d=0,r.mode=M;break}if(r.flags=0,r.head&&(r.head.done=!1),!(1&r.wrap)||(((255&f)<<8)+(f>>8))%31){t.msg="incorrect header check",r.mode=ht;break}if((15&f)!==I){t.msg="unknown compression method",r.mode=ht;break}if(f>>>=4,d-=4,xt=8+(15&f),0===r.wbits)r.wbits=xt;else if(xt>r.wbits){t.msg="invalid window size",r.mode=ht;break}r.dmax=1<<xt,t.adler=r.check=1,r.mode=512&f?X:H,f=0,d=0;break;case M:for(;d<16;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(r.flags=f,(255&r.flags)!==I){t.msg="unknown compression method",r.mode=ht;break}if(57344&r.flags){t.msg="unknown header flags set",r.mode=ht;break}r.head&&(r.head.text=f>>8&1),512&r.flags&&(At[0]=255&f,At[1]=f>>>8&255,r.check=b(r.check,At,2,0)),f=0,d=0,r.mode=F;case F:for(;d<32;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}r.head&&(r.head.time=f),512&r.flags&&(At[0]=255&f,At[1]=f>>>8&255,At[2]=f>>>16&255,At[3]=f>>>24&255,r.check=b(r.check,At,4,0)),f=0,d=0,r.mode=N;case N:for(;d<16;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}r.head&&(r.head.xflags=255&f,r.head.os=f>>8),512&r.flags&&(At[0]=255&f,At[1]=f>>>8&255,r.check=b(r.check,At,2,0)),f=0,d=0,r.mode=B;case B:if(1024&r.flags){for(;d<16;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}r.length=f,r.head&&(r.head.extra_len=f),512&r.flags&&(At[0]=255&f,At[1]=f>>>8&255,r.check=b(r.check,At,2,0)),f=0,d=0}else r.head&&(r.head.extra=null);r.mode=U;case U:if(1024&r.flags&&(dt=r.length,dt>c&&(dt=c),dt&&(r.head&&(xt=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),v.arraySet(r.head.extra,n,a,dt,xt)),512&r.flags&&(r.check=b(r.check,n,dt,a)),c-=dt,a+=dt,r.length-=dt),r.length))break t;r.length=0,r.mode=z;case z:if(2048&r.flags){if(0===c)break t;dt=0;do{xt=n[a+dt++],r.head&&xt&&r.length<65536&&(r.head.name+=String.fromCharCode(xt))}while(xt&&dt<c);if(512&r.flags&&(r.check=b(r.check,n,dt,a)),c-=dt,a+=dt,xt)break t}else r.head&&(r.head.name=null);r.length=0,r.mode=W;case W:if(4096&r.flags){if(0===c)break t;dt=0;do{xt=n[a+dt++],r.head&&xt&&r.length<65536&&(r.head.comment+=String.fromCharCode(xt))}while(xt&&dt<c);if(512&r.flags&&(r.check=b(r.check,n,dt,a)),c-=dt,a+=dt,xt)break t}else r.head&&(r.head.comment=null);r.mode=q;case q:if(512&r.flags){for(;d<16;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(f!==(65535&r.check)){t.msg="header crc mismatch",r.mode=ht;break}f=0,d=0}r.head&&(r.head.hcrc=r.flags>>9&1,r.head.done=!0),t.adler=r.check=0,r.mode=H;break;case X:for(;d<32;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}t.adler=r.check=i(f),f=0,d=0,r.mode=G;case G:if(0===r.havedict)return t.next_out=s,t.avail_out=l,t.next_in=a,t.avail_in=c,r.hold=f,r.bits=d,E;t.adler=r.check=1,r.mode=H;case H:if(e===A||e===T)break t;case Y:if(r.last){f>>>=7&d,d-=7&d,r.mode=st;break}for(;d<3;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}switch(r.last=1&f,f>>>=1,d-=1,3&f){case 0:r.mode=V;break;case 1:if(h(r),r.mode=tt,e===T){f>>>=2,d-=2;break t}break;case 2:r.mode=K;break;case 3:t.msg="invalid block type",r.mode=ht}f>>>=2,d-=2;break;case V:for(f>>>=7&d,d-=7&d;d<32;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if((65535&f)!=(f>>>16^65535)){t.msg="invalid stored block lengths",r.mode=ht;break}if(r.length=65535&f,f=0,d=0,r.mode=Z,e===T)break t;case Z:r.mode=J;case J:if(dt=r.length){if(dt>c&&(dt=c),dt>l&&(dt=l),0===dt)break t;v.arraySet(o,n,a,dt,s),c-=dt,a+=dt,l-=dt,s+=dt,r.length-=dt;break}r.mode=H;break;case K:for(;d<14;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(r.nlen=257+(31&f),f>>>=5,d-=5,r.ndist=1+(31&f),f>>>=5,d-=5,r.ncode=4+(15&f),f>>>=4,d-=4,r.nlen>286||r.ndist>30){t.msg="too many length or distance symbols",r.mode=ht;break}r.have=0,r.mode=Q;case Q:for(;r.have<r.ncode;){for(;d<3;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}r.lens[Pt[r.have++]]=7&f,f>>>=3,d-=3}for(;r.have<19;)r.lens[Pt[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,Tt={bits:r.lenbits},Ct=_(w,r.lens,0,19,r.lencode,0,r.work,Tt),r.lenbits=Tt.bits,Ct){t.msg="invalid code lengths set",r.mode=ht;break}r.have=0,r.mode=$;case $:for(;r.have<r.nlen+r.ndist;){for(;vt=r.lencode[f&(1<<r.lenbits)-1],mt=vt>>>24,bt=vt>>>16&255,yt=65535&vt,!(mt<=d);){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(yt<16)f>>>=mt,d-=mt,r.lens[r.have++]=yt;else{if(16===yt){for(kt=mt+2;d<kt;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(f>>>=mt,d-=mt,0===r.have){t.msg="invalid bit length repeat",r.mode=ht;break}xt=r.lens[r.have-1],dt=3+(3&f),f>>>=2,d-=2}else if(17===yt){for(kt=mt+3;d<kt;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}f>>>=mt,d-=mt,xt=0,dt=3+(7&f),f>>>=3,d-=3}else{for(kt=mt+7;d<kt;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}f>>>=mt,d-=mt,xt=0,dt=11+(127&f),f>>>=7,d-=7}if(r.have+dt>r.nlen+r.ndist){t.msg="invalid bit length repeat",r.mode=ht;break}for(;dt--;)r.lens[r.have++]=xt}}if(r.mode===ht)break;if(0===r.lens[256]){t.msg="invalid code -- missing end-of-block",r.mode=ht;break}if(r.lenbits=9,Tt={bits:r.lenbits},Ct=_(S,r.lens,0,r.nlen,r.lencode,0,r.work,Tt),r.lenbits=Tt.bits,Ct){t.msg="invalid literal/lengths set",r.mode=ht;break}if(r.distbits=6,r.distcode=r.distdyn,Tt={bits:r.distbits},Ct=_(x,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,Tt),r.distbits=Tt.bits,Ct){t.msg="invalid distances set",r.mode=ht;break}if(r.mode=tt,e===T)break t;case tt:r.mode=et;case et:if(c>=6&&l>=258){t.next_out=s,t.avail_out=l,t.next_in=a,t.avail_in=c,r.hold=f,r.bits=d,y(t,g),s=t.next_out,o=t.output,l=t.avail_out,a=t.next_in,n=t.input,c=t.avail_in,f=r.hold,d=r.bits,r.mode===H&&(r.back=-1);break}for(r.back=0;vt=r.lencode[f&(1<<r.lenbits)-1],mt=vt>>>24,bt=vt>>>16&255,yt=65535&vt,!(mt<=d);){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(bt&&0==(240&bt)){for(_t=mt,wt=bt,St=yt;vt=r.lencode[St+((f&(1<<_t+wt)-1)>>_t)],mt=vt>>>24,bt=vt>>>16&255,yt=65535&vt,!(_t+mt<=d);){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}f>>>=_t,d-=_t,r.back+=_t}if(f>>>=mt,d-=mt,r.back+=mt,r.length=yt,0===bt){r.mode=at;break}if(32&bt){r.back=-1,r.mode=H;break}if(64&bt){t.msg="invalid literal/length code",r.mode=ht;break}r.extra=15&bt,r.mode=rt;case rt:if(r.extra){for(kt=r.extra;d<kt;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}r.length+=f&(1<<r.extra)-1,f>>>=r.extra,d-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=it;case it:for(;vt=r.distcode[f&(1<<r.distbits)-1],mt=vt>>>24,bt=vt>>>16&255,yt=65535&vt,!(mt<=d);){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(0==(240&bt)){for(_t=mt,wt=bt,St=yt;vt=r.distcode[St+((f&(1<<_t+wt)-1)>>_t)],mt=vt>>>24,bt=vt>>>16&255,yt=65535&vt,!(_t+mt<=d);){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}f>>>=_t,d-=_t,r.back+=_t}if(f>>>=mt,d-=mt,r.back+=mt,64&bt){t.msg="invalid distance code",r.mode=ht;break}r.offset=yt,r.extra=15&bt,r.mode=nt;case nt:if(r.extra){for(kt=r.extra;d<kt;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}r.offset+=f&(1<<r.extra)-1,f>>>=r.extra,d-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){t.msg="invalid distance too far back",r.mode=ht;break}r.mode=ot;case ot:if(0===l)break t;if(dt=g-l,r.offset>dt){if((dt=r.offset-dt)>r.whave&&r.sane){t.msg="invalid distance too far back",r.mode=ht;break}dt>r.wnext?(dt-=r.wnext,pt=r.wsize-dt):pt=r.wnext-dt,dt>r.length&&(dt=r.length),gt=r.window}else gt=o,pt=s-r.offset,dt=r.length;dt>l&&(dt=l),l-=dt,r.length-=dt;do{o[s++]=gt[pt++]}while(--dt);0===r.length&&(r.mode=et);break;case at:if(0===l)break t;o[s++]=r.length,l--,r.mode=et;break;case st:if(r.wrap){for(;d<32;){if(0===c)break t;c--,f|=n[a++]<<d,d+=8}if(g-=l,t.total_out+=g,r.total+=g,g&&(t.adler=r.check=r.flags?b(r.check,o,g,s-g):m(r.check,o,g,s-g)),g=l,(r.flags?f:i(f))!==r.check){t.msg="incorrect data check",r.mode=ht;break}f=0,d=0}r.mode=ct;case ct:if(r.wrap&&r.flags){for(;d<32;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(f!==(4294967295&r.total)){t.msg="incorrect length check",r.mode=ht;break}f=0,d=0}r.mode=lt;case lt:Ct=P;break t;case ht:Ct=R;break t;case ut:return L;case ft:default:return O}return t.next_out=s,t.avail_out=l,t.next_in=a,t.avail_in=c,r.hold=f,r.bits=d,(r.wsize||g!==t.avail_out&&r.mode<ht&&(r.mode<st||e!==C))&&u(t,t.output,t.next_out,g-t.avail_out)?(r.mode=ut,L):(p-=t.avail_in,g-=t.avail_out,t.total_in+=p,t.total_out+=g,r.total+=g,r.wrap&&g&&(t.adler=r.check=r.flags?b(r.check,o,g,t.next_out-g):m(r.check,o,g,t.next_out-g)),t.data_type=r.bits+(r.last?64:0)+(r.mode===H?128:0)+(r.mode===tt||r.mode===Z?256:0),(0===p&&0===g||e===C)&&Ct===k&&(Ct=D),Ct)}function d(t){if(!t||!t.state)return O;var e=t.state;return e.window&&(e.window=null),t.state=null,k}function p(t,e){var r;return t&&t.state?(r=t.state,0==(2&r.wrap)?O:(r.head=e,e.done=!1,k)):O}function g(t,e){var r=e.length,i,n,o;return t&&t.state?(i=t.state,0!==i.wrap&&i.mode!==G?O:i.mode===G&&(n=1,(n=m(n,e,r,0))!==i.check)?R:(o=u(t,e,r,r))?(i.mode=ut,L):(i.havedict=1,k)):O}var v=r(8),m=r(22),b=r(23),y=r(55),_=r(56),w=0,S=1,x=2,C=4,A=5,T=6,k=0,P=1,E=2,O=-2,R=-3,L=-4,D=-5,I=8,j=1,M=2,F=3,N=4,B=5,U=6,z=7,W=8,q=9,X=10,G=11,H=12,Y=13,V=14,Z=15,J=16,K=17,Q=18,$=19,tt=20,et=21,rt=22,it=23,nt=24,ot=25,at=26,st=27,ct=28,lt=29,ht=30,ut=31,ft=32,dt=852,pt=592,gt=15,vt=15,mt=!0,bt,yt;e.inflateReset=a,e.inflateReset2=s,e.inflateResetKeep=o,e.inflateInit=l,e.inflateInit2=c,e.inflate=f,e.inflateEnd=d,e.inflateGetHeader=p,e.inflateSetDictionary=g,e.inflateInfo="pako inflate (from Nodeca project)"},function(t,e,r){"use strict";var i=30,n=12;t.exports=function t(e,r){var i,n,o,a,s,c,l,h,u,f,d,p,g,v,m,b,y,_,w,S,x,C,A,T,k;i=e.state,n=e.next_in,T=e.input,o=n+(e.avail_in-5),a=e.next_out,k=e.output,s=a-(r-e.avail_out),c=a+(e.avail_out-257),l=i.dmax,h=i.wsize,u=i.whave,f=i.wnext,d=i.window,p=i.hold,g=i.bits,v=i.lencode,m=i.distcode,b=(1<<i.lenbits)-1,y=(1<<i.distbits)-1;t:do{g<15&&(p+=T[n++]<<g,g+=8,p+=T[n++]<<g,g+=8),_=v[p&b];e:for(;;){if(w=_>>>24,p>>>=w,g-=w,0===(w=_>>>16&255))k[a++]=65535&_;else{if(!(16&w)){if(0==(64&w)){_=v[(65535&_)+(p&(1<<w)-1)];continue e}if(32&w){i.mode=12;break t}e.msg="invalid literal/length code",i.mode=30;break t}S=65535&_,w&=15,w&&(g<w&&(p+=T[n++]<<g,g+=8),S+=p&(1<<w)-1,p>>>=w,g-=w),g<15&&(p+=T[n++]<<g,g+=8,p+=T[n++]<<g,g+=8),_=m[p&y];r:for(;;){if(w=_>>>24,p>>>=w,g-=w,!(16&(w=_>>>16&255))){if(0==(64&w)){_=m[(65535&_)+(p&(1<<w)-1)];continue r}e.msg="invalid distance code",i.mode=30;break t}if(x=65535&_,w&=15,g<w&&(p+=T[n++]<<g,(g+=8)<w&&(p+=T[n++]<<g,g+=8)),(x+=p&(1<<w)-1)>l){e.msg="invalid distance too far back",i.mode=30;break t}if(p>>>=w,g-=w,w=a-s,x>w){if((w=x-w)>u&&i.sane){e.msg="invalid distance too far back",i.mode=30;break t}if(C=0,A=d,0===f){if(C+=h-w,w<S){S-=w;do{k[a++]=d[C++]}while(--w);C=a-x,A=k}}else if(f<w){if(C+=h+f-w,(w-=f)<S){S-=w;do{k[a++]=d[C++]}while(--w);if(C=0,f<S){w=f,S-=w;do{k[a++]=d[C++]}while(--w);C=a-x,A=k}}}else if(C+=f-w,w<S){S-=w;do{k[a++]=d[C++]}while(--w);C=a-x,A=k}for(;S>2;)k[a++]=A[C++],k[a++]=A[C++],k[a++]=A[C++],S-=3;S&&(k[a++]=A[C++],S>1&&(k[a++]=A[C++]))}else{C=a-x;do{k[a++]=k[C++],k[a++]=k[C++],k[a++]=k[C++],S-=3}while(S>2);S&&(k[a++]=k[C++],S>1&&(k[a++]=k[C++]))}break}}break}}while(n<o&&a<c);S=g>>3,n-=S,g-=S<<3,p&=(1<<g)-1,e.next_in=n,e.next_out=a,e.avail_in=n<o?o-n+5:5-(n-o),e.avail_out=a<c?c-a+257:257-(a-c),i.hold=p,i.bits=g}},function(t,e,r){"use strict";var i=r(8),n=15,o=852,a=592,s=0,c=1,l=2,h=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],u=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],f=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],d=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function t(e,r,n,o,a,s,c,l){var p=l.bits,g=0,v=0,m=0,b=0,y=0,_=0,w=0,S=0,x=0,C=0,A,T,k,P,E,O=null,R=0,L,D=new i.Buf16(16),I=new i.Buf16(16),j=null,M=0,F,N,B;for(g=0;g<=15;g++)D[g]=0;for(v=0;v<o;v++)D[r[n+v]]++;for(y=p,b=15;b>=1&&0===D[b];b--);if(y>b&&(y=b),0===b)return a[s++]=20971520,a[s++]=20971520,l.bits=1,0;for(m=1;m<b&&0===D[m];m++);for(y<m&&(y=m),S=1,g=1;g<=15;g++)if(S<<=1,(S-=D[g])<0)return-1;if(S>0&&(0===e||1!==b))return-1;for(I[1]=0,g=1;g<15;g++)I[g+1]=I[g]+D[g];for(v=0;v<o;v++)0!==r[n+v]&&(c[I[r[n+v]]++]=v);if(0===e?(O=j=c,L=19):1===e?(O=h,R-=257,j=u,M-=257,L=256):(O=f,j=d,L=-1),C=0,v=0,g=m,E=s,_=y,w=0,k=-1,x=1<<y,P=x-1,1===e&&x>852||2===e&&x>592)return 1;for(var U=0;;){U++,F=g-w,c[v]<L?(N=0,B=c[v]):c[v]>L?(N=j[M+c[v]],B=O[R+c[v]]):(N=96,B=0),A=1<<g-w,T=1<<_,m=T;do{T-=A,a[E+(C>>w)+T]=F<<24|N<<16|B|0}while(0!==T);for(A=1<<g-1;C&A;)A>>=1;if(0!==A?(C&=A-1,C+=A):C=0,v++,0==--D[g]){if(g===b)break;g=r[n+c[v]]}if(g>y&&(C&P)!==k){for(0===w&&(w=y),E+=m,_=g-w,S=1<<_;_+w<b&&!((S-=D[_+w])<=0);)_++,S<<=1;if(x+=1<<_,1===e&&x>852||2===e&&x>592)return 1;k=C&P,a[k]=y<<24|_<<16|E-s|0}}return 0!==C&&(a[E+C]=g-w<<24|64<<16|0),l.bits=y,0}},function(t,e,r){"use strict";t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},function(t,e){t.exports=function t(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},function(t,e){"function"==typeof Object.create?t.exports=function t(e,r){e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function t(e,r){e.super_=r;var i=function(){};i.prototype=r.prototype,e.prototype=new i,e.prototype.constructor=e}},function(t,e,r){"use strict";(function(e){/*! <add>var K=r(40),Q=r(41),$=r(13);e.Buffer=a,e.SlowBuffer=v,e.INSPECT_MAX_BYTES=50,a.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:i(),e.kMaxLength=n(),a.poolSize=8192,a._augment=function(t){return t.__proto__=a.prototype,t},a.from=function(t,e,r){return s(null,t,e,r)},a.TYPED_ARRAY_SUPPORT&&(a.prototype.__proto__=Uint8Array.prototype,a.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&a[Symbol.species]===a&&Object.defineProperty(a,Symbol.species,{value:null,configurable:!0})),a.alloc=function(t,e,r){return l(null,t,e,r)},a.allocUnsafe=function(t){return h(null,t)},a.allocUnsafeSlow=function(t){return h(null,t)},a.isBuffer=function t(e){return!(null==e||!e._isBuffer)},a.compare=function t(e,r){if(!a.isBuffer(e)||!a.isBuffer(r))throw new TypeError("Arguments must be Buffers");if(e===r)return 0;for(var i=e.length,n=r.length,o=0,s=Math.min(i,n);o<s;++o)if(e[o]!==r[o]){i=e[o],n=r[o];break}return i<n?-1:n<i?1:0},a.isEncoding=function t(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function t(e,r){if(!$(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return a.alloc(0);var i;if(void 0===r)for(r=0,i=0;i<e.length;++i)r+=e[i].length;var n=a.allocUnsafe(r),o=0;for(i=0;i<e.length;++i){var s=e[i];if(!a.isBuffer(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(n,o),o+=s.length}return n},a.byteLength=m,a.prototype._isBuffer=!0,a.prototype.swap16=function t(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var r=0;r<e;r+=2)y(this,r,r+1);return this},a.prototype.swap32=function t(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var r=0;r<e;r+=4)y(this,r,r+3),y(this,r+1,r+2);return this},a.prototype.swap64=function t(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var r=0;r<e;r+=8)y(this,r,r+7),y(this,r+1,r+6),y(this,r+2,r+5),y(this,r+3,r+4);return this},a.prototype.toString=function t(){var e=0|this.length;return 0===e?"":0===arguments.length?E(this,0,e):b.apply(this,arguments)},a.prototype.equals=function t(e){if(!a.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===a.compare(this,e)},a.prototype.inspect=function t(){var r="",i=e.INSPECT_MAX_BYTES;return this.length>0&&(r=this.toString("hex",0,i).match(/.{2}/g).join(" "),this.length>i&&(r+=" ... ")),"<Buffer "+r+">"},a.prototype.compare=function t(e,r,i,n,o){if(!a.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===r&&(r=0),void 0===i&&(i=e?e.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),r<0||i>e.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&r>=i)return 0;if(n>=o)return-1;if(r>=i)return 1;if(r>>>=0,i>>>=0,n>>>=0,o>>>=0,this===e)return 0;for(var s=o-n,c=i-r,l=Math.min(s,c),h=this.slice(n,o),u=e.slice(r,i),f=0;f<l;++f)if(h[f]!==u[f]){s=h[f],c=u[f];break}return s<c?-1:c<s?1:0},a.prototype.includes=function t(e,r,i){return-1!==this.indexOf(e,r,i)},a.prototype.indexOf=function t(e,r,i){return _(this,e,r,i,!0)},a.prototype.lastIndexOf=function t(e,r,i){return _(this,e,r,i,!1)},a.prototype.write=function t(e,r,i,n){if(void 0===r)n="utf8",i=this.length,r=0;else if(void 0===i&&"string"==typeof r)n=r,i=this.length,r=0;else{if(!isFinite(r))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");r|=0,isFinite(i)?(i|=0,void 0===n&&(n="utf8")):(n=i,i=void 0)}var o=this.length-r;if((void 0===i||i>o)&&(i=o),e.length>0&&(i<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var a=!1;;)switch(n){case"hex":return S(this,e,r,i);case"utf8":case"utf-8":return x(this,e,r,i);case"ascii":return C(this,e,r,i);case"latin1":case"binary":return A(this,e,r,i);case"base64":return T(this,e,r,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,e,r,i);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},a.prototype.toJSON=function t(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var tt=4096;a.prototype.slice=function t(e,r){var i=this.length;e=~~e,r=void 0===r?i:~~r,e<0?(e+=i)<0&&(e=0):e>i&&(e=i),r<0?(r+=i)<0&&(r=0):r>i&&(r=i),r<e&&(r=e);var n;if(a.TYPED_ARRAY_SUPPORT)n=this.subarray(e,r),n.__proto__=a.prototype;else{var o=r-e;n=new a(o,void 0);for(var s=0;s<o;++s)n[s]=this[s+e]}return n},a.prototype.readUIntLE=function t(e,r,i){e|=0,r|=0,i||j(e,r,this.length);for(var n=this[e],o=1,a=0;++a<r&&(o*=256);)n+=this[e+a]*o;return n},a.prototype.readUIntBE=function t(e,r,i){e|=0,r|=0,i||j(e,r,this.length);for(var n=this[e+--r],o=1;r>0&&(o*=256);)n+=this[e+--r]*o;return n},a.prototype.readUInt8=function t(e,r){return r||j(e,1,this.length),this[e]},a.prototype.readUInt16LE=function t(e,r){return r||j(e,2,this.length),this[e]|this[e+1]<<8},a.prototype.readUInt16BE=function t(e,r){return r||j(e,2,this.length),this[e]<<8|this[e+1]},a.prototype.readUInt32LE=function t(e,r){return r||j(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},a.prototype.readUInt32BE=function t(e,r){return r||j(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},a.prototype.readIntLE=function t(e,r,i){e|=0,r|=0,i||j(e,r,this.length);for(var n=this[e],o=1,a=0;++a<r&&(o*=256);)n+=this[e+a]*o;return o*=128,n>=o&&(n-=Math.pow(2,8*r)),n},a.prototype.readIntBE=function t(e,r,i){e|=0,r|=0,i||j(e,r,this.length);for(var n=r,o=1,a=this[e+--n];n>0&&(o*=256);)a+=this[e+--n]*o;return o*=128,a>=o&&(a-=Math.pow(2,8*r)),a},a.prototype.readInt8=function t(e,r){return r||j(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},a.prototype.readInt16LE=function t(e,r){r||j(e,2,this.length);var i=this[e]|this[e+1]<<8;return 32768&i?4294901760|i:i},a.prototype.readInt16BE=function t(e,r){r||j(e,2,this.length);var i=this[e+1]|this[e]<<8;return 32768&i?4294901760|i:i},a.prototype.readInt32LE=function t(e,r){return r||j(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},a.prototype.readInt32BE=function t(e,r){return r||j(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},a.prototype.readFloatLE=function t(e,r){return r||j(e,4,this.length),Q.read(this,e,!0,23,4)},a.prototype.readFloatBE=function t(e,r){return r||j(e,4,this.length),Q.read(this,e,!1,23,4)},a.prototype.readDoubleLE=function t(e,r){return r||j(e,8,this.length),Q.read(this,e,!0,52,8)},a.prototype.readDoubleBE=function t(e,r){return r||j(e,8,this.length),Q.read(this,e,!1,52,8)},a.prototype.writeUIntLE=function t(e,r,i,n){if(e=+e,r|=0,i|=0,!n){M(this,e,r,i,Math.pow(2,8*i)-1,0)}var o=1,a=0;for(this[r]=255&e;++a<i&&(o*=256);)this[r+a]=e/o&255;return r+i},a.prototype.writeUIntBE=function t(e,r,i,n){if(e=+e,r|=0,i|=0,!n){M(this,e,r,i,Math.pow(2,8*i)-1,0)}var o=i-1,a=1;for(this[r+o]=255&e;--o>=0&&(a*=256);)this[r+o]=e/a&255;return r+i},a.prototype.writeUInt8=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,1,255,0),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[r]=255&e,r+1},a.prototype.writeUInt16LE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[r]=255&e,this[r+1]=e>>>8):F(this,e,r,!0),r+2},a.prototype.writeUInt16BE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[r]=e>>>8,this[r+1]=255&e):F(this,e,r,!1),r+2},a.prototype.writeUInt32LE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=255&e):N(this,e,r,!0),r+4},a.prototype.writeUInt32BE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=255&e):N(this,e,r,!1),r+4},a.prototype.writeIntLE=function t(e,r,i,n){if(e=+e,r|=0,!n){var o=Math.pow(2,8*i-1);M(this,e,r,i,o-1,-o)}var a=0,s=1,c=0;for(this[r]=255&e;++a<i&&(s*=256);)e<0&&0===c&&0!==this[r+a-1]&&(c=1),this[r+a]=(e/s>>0)-c&255;return r+i},a.prototype.writeIntBE=function t(e,r,i,n){if(e=+e,r|=0,!n){var o=Math.pow(2,8*i-1);M(this,e,r,i,o-1,-o)}var a=i-1,s=1,c=0;for(this[r+a]=255&e;--a>=0&&(s*=256);)e<0&&0===c&&0!==this[r+a+1]&&(c=1),this[r+a]=(e/s>>0)-c&255;return r+i},a.prototype.writeInt8=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,1,127,-128),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[r]=255&e,r+1},a.prototype.writeInt16LE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[r]=255&e,this[r+1]=e>>>8):F(this,e,r,!0),r+2},a.prototype.writeInt16BE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[r]=e>>>8,this[r+1]=255&e):F(this,e,r,!1),r+2},a.prototype.writeInt32LE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,4,2147483647,-2147483648),a.TYPED_ARRAY_SUPPORT?(this[r]=255&e,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24):N(this,e,r,!0),r+4},a.prototype.writeInt32BE=function t(e,r,i){return e=+e,r|=0,i||M(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),a.TYPED_ARRAY_SUPPORT?(this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=255&e):N(this,e,r,!1),r+4},a.prototype.writeFloatLE=function t(e,r,i){return U(this,e,r,!0,i)},a.prototype.writeFloatBE=function t(e,r,i){return U(this,e,r,!1,i)},a.prototype.writeDoubleLE=function t(e,r,i){return z(this,e,r,!0,i)},a.prototype.writeDoubleBE=function t(e,r,i){return z(this,e,r,!1,i)},a.prototype.copy=function t(e,r,i,n){if(i||(i=0),n||0===n||(n=this.length),r>=e.length&&(r=e.length),r||(r=0),n>0&&n<i&&(n=i),n===i)return 0;if(0===e.length||0===this.length)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(i<0||i>=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-r<n-i&&(n=e.length-r+i);var o=n-i,s;if(this===e&&i<r&&r<n)for(s=o-1;s>=0;--s)e[s+r]=this[s+i];else if(o<1e3||!a.TYPED_ARRAY_SUPPORT)for(s=0;s<o;++s)e[s+r]=this[s+i];else Uint8Array.prototype.set.call(e,this.subarray(i,i+o),r);return o},a.prototype.fill=function t(e,r,i,n){if("string"==typeof e){if("string"==typeof r?(n=r,r=0,i=this.length):"string"==typeof i&&(n=i,i=this.length),1===e.length){var o=e.charCodeAt(0);o<256&&(e=o)}if(void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!a.isEncoding(n))throw new TypeError("Unknown encoding: "+n)}else"number"==typeof e&&(e&=255);if(r<0||this.length<r||this.length<i)throw new RangeError("Out of range index");if(i<=r)return this;r>>>=0,i=void 0===i?this.length:i>>>0,e||(e=0);var s;if("number"==typeof e)for(s=r;s<i;++s)this[s]=e;else{var c=a.isBuffer(e)?e:G(new a(e,n).toString()),l=c.length;for(s=0;s<i-r;++s)this[s+r]=c[s%l]}return this};var et=/[^+\/0-9A-Za-z-_]/g}).call(e,r(0))},function(t,e){"function"==typeof Object.create?t.exports=function t(e,r){e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function t(e,r){e.super_=r;var i=function(){};i.prototype=r.prototype,e.prototype=new i,e.prototype.constructor=e}},function(t,e,r){"use strict";function i(t){if(!(this instanceof i))return new i(t);h.call(this,t),u.call(this,t),t&&!1===t.readable&&(this.readable=!1),t&&!1===t.writable&&(this.writable=!1),this.allowHalfOpen=!0,t&&!1===t.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",n)}function n(){this.allowHalfOpen||this._writableState.ended||s(o,this)}function o(t){t.end()}function a(t,e){for(var r=0,i=t.length;r<i;r++)e(t[r],r)}var s=r(7),c=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e};t.exports=i;var l=r(5);l.inherits=r(3);var h=r(14),u=r(18);l.inherits(i,h);for(var f=c(u.prototype),d=0;d<f.length;d++){var p=f[d];i.prototype[p]||(i.prototype[p]=u.prototype[p])}Object.defineProperty(i.prototype,"destroyed",{get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed&&this._writableState.destroyed)},set:function(t){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=t,this._writableState.destroyed=t)}}),i.prototype._destroy=function(t,e){this.push(null),this.end(),s(e,t)}},function(t,e,r){(function(t){function r(t){return Array.isArray?Array.isArray(t):"[object Array]"===v(t)}function i(t){return"boolean"==typeof t}function n(t){return null===t}function o(t){return null==t}function a(t){return"number"==typeof t}function s(t){return"string"==typeof t}function c(t){return"symbol"==typeof t}function l(t){return void 0===t}function h(t){return"[object RegExp]"===v(t)}function u(t){return"object"==typeof t&&null!==t}function f(t){return"[object Date]"===v(t)}function d(t){return"[object Error]"===v(t)||t instanceof Error}function p(t){return"function"==typeof t}function g(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t}function v(t){return Object.prototype.toString.call(t)}e.isArray=r,e.isBoolean=i,e.isNull=n,e.isNullOrUndefined=o,e.isNumber=a,e.isString=s,e.isSymbol=c,e.isUndefined=l,e.isRegExp=h,e.isObject=u,e.isDate=f,e.isError=d,e.isFunction=p,e.isPrimitive=g,e.isBuffer=t.isBuffer}).call(e,r(2).Buffer)},function(t,e,r){"use strict";function i(){p=!1}function n(t){if(!t)return void(f!==u&&(f=u,i()));if(t!==f){if(t.length!==u.length)throw new Error("Custom alphabet for shortid must be "+u.length+" unique characters. You submitted "+t.length+" characters: "+t);var e=t.split("").filter(function(t,e,r){return e!==r.lastIndexOf(t)});if(e.length)throw new Error("Custom alphabet for shortid must be "+u.length+" unique characters. These characters were not unique: "+e.join(", "));f=t,i()}}function o(t){return n(t),f}function a(t){h.seed(t),d!==t&&(i(),d=t)}function s(){f||n(u);for(var t=f.split(""),e=[],r=h.nextValue(),i;t.length>0;)r=h.nextValue(),i=Math.floor(r*t.length),e.push(t.splice(i,1)[0]);return e.join("")}function c(){return p||(p=s())}function l(t){return c()[t]}var h=r(32),u="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-",f,d,p;t.exports={characters:o,seed:a,lookup:l,shuffled:c}},function(t,e,r){"use strict";(function(e){function r(t,r,i,n){if("function"!=typeof t)throw new TypeError('"callback" argument must be a function');var o=arguments.length,a,s;switch(o){case 0:case 1:return e.nextTick(t);case 2:return e.nextTick(function e(){t.call(null,r)});case 3:return e.nextTick(function e(){t.call(null,r,i)});case 4:return e.nextTick(function e(){t.call(null,r,i,n)});default:for(a=new Array(o-1),s=0;s<a.length;)a[s++]=arguments[s];return e.nextTick(function e(){t.apply(null,a)})}}!e.version||0===e.version.indexOf("v0.")||0===e.version.indexOf("v1.")&&0!==e.version.indexOf("v1.8.")?t.exports=r:t.exports=e.nextTick}).call(e,r(1))},function(t,e,r){"use strict";var i="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;e.assign=function(t){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var r=e.shift();if(r){if("object"!=typeof r)throw new TypeError(r+"must be non-object");for(var i in r)r.hasOwnProperty(i)&&(t[i]=r[i])}}return t},e.shrinkBuf=function(t,e){return t.length===e?t:t.subarray?t.subarray(0,e):(t.length=e,t)};var n={arraySet:function(t,e,r,i,n){if(e.subarray&&t.subarray)return void t.set(e.subarray(r,r+i),n);for(var o=0;o<i;o++)t[n+o]=e[r+o]},flattenChunks:function(t){var e,r,i,n,o,a;for(i=0,e=0,r=t.length;e<r;e++)i+=t[e].length;for(a=new Uint8Array(i),n=0,e=0,r=t.length;e<r;e++)o=t[e],a.set(o,n),n+=o.length;return a}},o={arraySet:function(t,e,r,i,n){for(var o=0;o<i;o++)t[n+o]=e[r+o]},flattenChunks:function(t){return[].concat.apply([],t)}};e.setTyped=function(t){t?(e.Buf8=Uint8Array,e.Buf16=Uint16Array,e.Buf32=Int32Array,e.assign(e,n)):(e.Buf8=Array,e.Buf16=Array,e.Buf32=Array,e.assign(e,o))},e.setTyped(i)},function(t,e,r){e=t.exports=r(14),e.Stream=e,e.Readable=e,e.Writable=r(18),e.Duplex=r(4),e.Transform=r(20),e.PassThrough=r(49)},function(t,e,r){function i(t,e){for(var r in t)e[r]=t[r]}function n(t,e,r){return a(t,e,r)}var o=r(2),a=o.Buffer;a.from&&a.alloc&&a.allocUnsafe&&a.allocUnsafeSlow?t.exports=o:(i(o,e),e.Buffer=n),i(a,n),n.from=function(t,e,r){if("number"==typeof t)throw new TypeError("Argument must not be a number");return a(t,e,r)},n.alloc=function(t,e,r){if("number"!=typeof t)throw new TypeError("Argument must be a number");var i=a(t);return void 0!==e?"string"==typeof r?i.fill(e,r):i.fill(e):i.fill(0),i},n.allocUnsafe=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return a(t)},n.allocUnsafeSlow=function(t){if("number"!=typeof t)throw new TypeError("Argument must be a number");return o.SlowBuffer(t)}},function(t,e,r){"use strict";function i(t,e){for(var r=0,i,o="";!i;)o+=t(e>>4*r&15|n()),i=e<Math.pow(16,r+1),r++;return o}var n=r(33);t.exports=i},function(t,e,r){(function(e,i,n){!function e(r,i){t.exports=i()}(this,function(){return function(t){function e(i){if(r[i])return r[i].exports;var n=r[i]={i:i,l:!1,exports:{}};return t[i].call(n.exports,n,n.exports,e),n.l=!0,n.exports}var r={};return e.m=t,e.c=r,e.i=function(t){return t},e.d=function(t,r,i){e.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var r=t&&t.__esModule?function e(){return t.default}:function e(){return t};return e.d(r,"a",r),r},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=13)}([function(t,r,n){"use strict";function o(t){lt=t}function a(){return lt}function s(t){lt>=at.infos&&console.log("Info: "+t)}function c(t){lt>=at.warnings&&console.log("Warning: "+t)}function l(t){console.log("Deprecated API usage: "+t)}function h(t){throw new Error(t)}function u(t,e){t||h(e)}function f(t,e){try{var r=new URL(t);if(!r.origin||"null"===r.origin)return!1}catch(t){return!1}var i=new URL(e,r);return r.origin===i.origin}function d(t){if(!t)return!1;switch(t.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function p(t,e){if(!t)return null;try{var r=e?new URL(t,e):new URL(t);if(d(r))return r}catch(t){}return null}function g(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!1}),r}function v(t){var e;return function(){return t&&(e=Object.create(null),t(e),t=null),e}}function m(t){return"string"!=typeof t?(c("The argument for removeNullCharacters must be a string."),t):t.replace(wt,"")}function b(t){u(null!==t&&"object"===(void 0===t?"undefined":Y(t))&&void 0!==t.length,"Invalid argument for bytesToString");var e=t.length,r=8192;if(e<8192)return String.fromCharCode.apply(null,t);for(var i=[],n=0;n<e;n+=8192){var o=Math.min(n+8192,e),a=t.subarray(n,o);i.push(String.fromCharCode.apply(null,a))}return i.join("")}function y(t){u("string"==typeof t,"Invalid argument for stringToBytes");for(var e=t.length,r=new Uint8Array(e),i=0;i<e;++i)r[i]=255&t.charCodeAt(i);return r}function _(t){return void 0!==t.length?t.length:(u(void 0!==t.byteLength),t.byteLength)}function w(t){if(1===t.length&&t[0]instanceof Uint8Array)return t[0];var e=0,r,i=t.length,n,o;for(r=0;r<i;r++)n=t[r],o=_(n),e+=o;var a=0,s=new Uint8Array(e);for(r=0;r<i;r++)n=t[r],n instanceof Uint8Array||(n="string"==typeof n?y(n):new Uint8Array(n)),o=n.byteLength,s.set(n,a),a+=o;return s}function S(t){return String.fromCharCode(t>>24&255,t>>16&255,t>>8&255,255&t)}function x(t){for(var e=1,r=0;t>e;)e<<=1,r++;return r}function C(t,e){return t[e]<<24>>24}function A(t,e){return t[e]<<8|t[e+1]}function T(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}function k(){var t=new Uint8Array(4);return t[0]=1,1===new Uint32Array(t.buffer,0,1)[0]}function P(){try{return new Function(""),!0}catch(t){return!1}}function E(t){var e,r=t.length,i=[];if("þ"===t[0]&&"ÿ"===t[1])for(e=2;e<r;e+=2)i.push(String.fromCharCode(t.charCodeAt(e)<<8|t.charCodeAt(e+1)));else for(e=0;e<r;++e){var n=At[t.charCodeAt(e)];i.push(n?String.fromCharCode(n):t.charAt(e))}return i.join("")}function O(t){return decodeURIComponent(escape(t))}function R(t){return unescape(encodeURIComponent(t))}function L(t){for(var e in t)return!1;return!0}function D(t){return"boolean"==typeof t}function I(t){return"number"==typeof t&&(0|t)===t}function j(t){return"number"==typeof t}function M(t){return"string"==typeof t}function F(t){return t instanceof Array}function N(t){return"object"===(void 0===t?"undefined":Y(t))&&null!==t&&void 0!==t.byteLength}function B(t){return 32===t||9===t||13===t||10===t}function U(){return"object"===(void 0===i?"undefined":Y(i))&&i+""=="[object process]"}function z(){var t={};return t.promise=new Promise(function(e,r){t.resolve=e,t.reject=r}),t}function W(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;return t?new Promise(function(i,n){i(t.apply(r,e))}):Promise.resolve(void 0)}function q(t,e,r){e?t.resolve():t.reject(r)}function X(t){return Promise.resolve(t).catch(function(){})}function G(t,e,r){var i=this;this.sourceName=t,this.targetName=e,this.comObj=r,this.callbackId=1,this.streamId=1,this.postMessageTransfers=!0,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null);var n=this.callbacksCapabilities=Object.create(null),o=this.actionHandler=Object.create(null);this._onComObjOnMessage=function(t){var e=t.data;if(e.targetName===i.sourceName)if(e.stream)i._processStreamMessage(e);else if(e.isReply){var a=e.callbackId;if(!(e.callbackId in n))throw new Error("Cannot resolve callback "+a);var s=n[a];delete n[a],"error"in e?s.reject(e.error):s.resolve(e.data)}else{if(!(e.action in o))throw new Error("Unknown action from worker: "+e.action);var c=o[e.action];if(e.callbackId){var l=i.sourceName,h=e.sourceName;Promise.resolve().then(function(){return c[0].call(c[1],e.data)}).then(function(t){r.postMessage({sourceName:l,targetName:h,isReply:!0,callbackId:e.callbackId,data:t})},function(t){t instanceof Error&&(t+=""),r.postMessage({sourceName:l,targetName:h,isReply:!0,callbackId:e.callbackId,error:t})})}else e.streamId?i._createStreamSink(e):c[0].call(c[1],e.data)}},r.addEventListener("message",this._onComObjOnMessage)}function H(t,e,r){var i=new Image;i.onload=function e(){r.resolve(t,i)},i.onerror=function e(){r.resolve(t,null),c("Error during JPEG image loading")},i.src=e}Object.defineProperty(r,"__esModule",{value:!0}),r.unreachable=r.warn=r.utf8StringToString=r.stringToUTF8String=r.stringToPDFString=r.stringToBytes=r.string32=r.shadow=r.setVerbosityLevel=r.ReadableStream=r.removeNullCharacters=r.readUint32=r.readUint16=r.readInt8=r.log2=r.loadJpegStream=r.isEvalSupported=r.isLittleEndian=r.createValidAbsoluteUrl=r.isSameOrigin=r.isNodeJS=r.isSpace=r.isString=r.isNum=r.isInt=r.isEmptyObj=r.isBool=r.isArrayBuffer=r.isArray=r.info=r.globalScope=r.getVerbosityLevel=r.getLookupTableFactory=r.deprecated=r.createObjectURL=r.createPromiseCapability=r.createBlob=r.bytesToString=r.assert=r.arraysToBytes=r.arrayByteLength=r.FormatError=r.XRefParseException=r.Util=r.UnknownErrorException=r.UnexpectedResponseException=r.TextRenderingMode=r.StreamType=r.StatTimer=r.PasswordResponses=r.PasswordException=r.PageViewport=r.NotImplementedException=r.NativeImageDecoding=r.MissingPDFException=r.MissingDataException=r.MessageHandler=r.InvalidPDFException=r.CMapCompressionType=r.ImageKind=r.FontType=r.AnnotationType=r.AnnotationFlag=r.AnnotationFieldFlag=r.AnnotationBorderStyleType=r.UNSUPPORTED_FEATURES=r.VERBOSITY_LEVELS=r.OPS=r.IDENTITY_MATRIX=r.FONT_IDENTITY_MATRIX=void 0;var Y="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};n(14);var V=n(9),Z="undefined"!=typeof window&&window.Math===Math?window:void 0!==e&&e.Math===Math?e:"undefined"!=typeof self&&self.Math===Math?self:void 0,J=[.001,0,0,.001,0,0],K={NONE:"none",DECODE:"decode",DISPLAY:"display"},Q={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},$={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},tt={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},et={INVISIBLE:1,HIDDEN:2,PRINT:4,NOZOOM:8,NOROTATE:16,NOVIEW:32,READONLY:64,LOCKED:128,TOGGLENOVIEW:256,LOCKEDCONTENTS:512},rt={READONLY:1,REQUIRED:2,NOEXPORT:4,MULTILINE:4096,PASSWORD:8192,NOTOGGLETOOFF:16384,RADIO:32768,PUSHBUTTON:65536,COMBO:131072,EDIT:262144,SORT:524288,FILESELECT:1048576,MULTISELECT:2097152,DONOTSPELLCHECK:4194304,DONOTSCROLL:8388608,COMB:16777216,RICHTEXT:33554432,RADIOSINUNISON:33554432,COMMITONSELCHANGE:67108864},it={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},nt={UNKNOWN:0,FLATE:1,LZW:2,DCT:3,JPX:4,JBIG:5,A85:6,AHX:7,CCF:8,RL:9},ot={UNKNOWN:0,TYPE1:1,TYPE1C:2,CIDFONTTYPE0:3,CIDFONTTYPE0C:4,TRUETYPE:5,CIDFONTTYPE2:6,TYPE3:7,OPENTYPE:8,TYPE0:9,MMTYPE1:10},at={errors:0,warnings:1,infos:5},st={NONE:0,BINARY:1,STREAM:2},ct={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotations:78,endAnnotations:79,beginAnnotation:80,endAnnotation:81,paintJpegXObject:82,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91},lt=at.warnings,ht={unknown:"unknown",forms:"forms",javaScript:"javaScript",smask:"smask",shadingPattern:"shadingPattern",font:"font"},ut={NEED_PASSWORD:1,INCORRECT_PASSWORD:2},ft=function t(){function e(t,e){this.name="PasswordException",this.message=t,this.code=e}return e.prototype=new Error,e.constructor=e,e}(),dt=function t(){function e(t,e){this.name="UnknownErrorException",this.message=t,this.details=e}return e.prototype=new Error,e.constructor=e,e}(),pt=function t(){function e(t){this.name="InvalidPDFException",this.message=t}return e.prototype=new Error,e.constructor=e,e}(),gt=function t(){function e(t){this.name="MissingPDFException",this.message=t}return e.prototype=new Error,e.constructor=e,e}(),vt=function t(){function e(t,e){this.name="UnexpectedResponseException",this.message=t,this.status=e}return e.prototype=new Error,e.constructor=e,e}(),mt=function t(){function e(t){this.message=t}return e.prototype=new Error,e.prototype.name="NotImplementedException",e.constructor=e,e}(),bt=function t(){function e(t,e){this.begin=t,this.end=e,this.message="Missing data ["+t+", "+e+")"}return e.prototype=new Error,e.prototype.name="MissingDataException",e.constructor=e,e}(),yt=function t(){function e(t){this.message=t}return e.prototype=new Error,e.prototype.name="XRefParseException",e.constructor=e,e}(),_t=function t(){function e(t){this.message=t}return e.prototype=new Error,e.prototype.name="FormatError",e.constructor=e,e}(),wt=/\x00/g,St=[1,0,0,1,0,0],xt=function t(){function e(){}var r=["rgb(",0,",",0,",",0,")"];e.makeCssRgb=function t(e,i,n){return r[1]=e,r[3]=i,r[5]=n,r.join("")},e.transform=function t(e,r){return[e[0]*r[0]+e[2]*r[1],e[1]*r[0]+e[3]*r[1],e[0]*r[2]+e[2]*r[3],e[1]*r[2]+e[3]*r[3],e[0]*r[4]+e[2]*r[5]+e[4],e[1]*r[4]+e[3]*r[5]+e[5]]},e.applyTransform=function t(e,r){return[e[0]*r[0]+e[1]*r[2]+r[4],e[0]*r[1]+e[1]*r[3]+r[5]]},e.applyInverseTransform=function t(e,r){var i=r[0]*r[3]-r[1]*r[2];return[(e[0]*r[3]-e[1]*r[2]+r[2]*r[5]-r[4]*r[3])/i,(-e[0]*r[1]+e[1]*r[0]+r[4]*r[1]-r[5]*r[0])/i]},e.getAxialAlignedBoundingBox=function t(r,i){var n=e.applyTransform(r,i),o=e.applyTransform(r.slice(2,4),i),a=e.applyTransform([r[0],r[3]],i),s=e.applyTransform([r[2],r[1]],i);return[Math.min(n[0],o[0],a[0],s[0]),Math.min(n[1],o[1],a[1],s[1]),Math.max(n[0],o[0],a[0],s[0]),Math.max(n[1],o[1],a[1],s[1])]},e.inverseTransform=function t(e){var r=e[0]*e[3]-e[1]*e[2];return[e[3]/r,-e[1]/r,-e[2]/r,e[0]/r,(e[2]*e[5]-e[4]*e[3])/r,(e[4]*e[1]-e[5]*e[0])/r]},e.apply3dTransform=function t(e,r){return[e[0]*r[0]+e[1]*r[1]+e[2]*r[2],e[3]*r[0]+e[4]*r[1]+e[5]*r[2],e[6]*r[0]+e[7]*r[1]+e[8]*r[2]]},e.singularValueDecompose2dScale=function t(e){var r=[e[0],e[2],e[1],e[3]],i=e[0]*r[0]+e[1]*r[2],n=e[0]*r[1]+e[1]*r[3],o=e[2]*r[0]+e[3]*r[2],a=e[2]*r[1]+e[3]*r[3],s=(i+a)/2,c=Math.sqrt((i+a)*(i+a)-4*(i*a-o*n))/2,l=s+c||1,h=s-c||1;return[Math.sqrt(l),Math.sqrt(h)]},e.normalizeRect=function t(e){var r=e.slice(0);return e[0]>e[2]&&(r[0]=e[2],r[2]=e[0]),e[1]>e[3]&&(r[1]=e[3],r[3]=e[1]),r},e.intersect=function t(r,i){function n(t,e){return t-e}var o=[r[0],r[2],i[0],i[2]].sort(n),a=[r[1],r[3],i[1],i[3]].sort(n),s=[];return r=e.normalizeRect(r),i=e.normalizeRect(i),(o[0]===r[0]&&o[1]===i[0]||o[0]===i[0]&&o[1]===r[0])&&(s[0]=o[1],s[2]=o[2],(a[0]===r[1]&&a[1]===i[1]||a[0]===i[1]&&a[1]===r[1])&&(s[1]=a[1],s[3]=a[2],s))},e.sign=function t(e){return e<0?-1:1};var i=["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM","","X","XX","XXX","XL","L","LX","LXX","LXXX","XC","","I","II","III","IV","V","VI","VII","VIII","IX"];return e.toRoman=function t(e,r){u(I(e)&&e>0,"The number should be a positive integer.");for(var n,o=[];e>=1e3;)e-=1e3,o.push("M");n=e/100|0,e%=100,o.push(i[n]),n=e/10|0,e%=10,o.push(i[10+n]),o.push(i[20+e]);var a=o.join("");return r?a.toLowerCase():a},e.appendToArray=function t(e,r){Array.prototype.push.apply(e,r)},e.prependToArray=function t(e,r){Array.prototype.unshift.apply(e,r)},e.extendObj=function t(e,r){for(var i in r)e[i]=r[i]},e.getInheritableProperty=function t(e,r,i){for(;e&&!e.has(r);)e=e.get("Parent");return e?i?e.getArray(r):e.get(r):null},e.inherit=function t(e,r,i){e.prototype=Object.create(r.prototype),e.prototype.constructor=e;for(var n in i)e.prototype[n]=i[n]},e.loadScript=function t(e,r){var i=document.createElement("script"),n=!1;i.setAttribute("src",e),r&&(i.onload=function(){n||r(),n=!0}),document.getElementsByTagName("head")[0].appendChild(i)},e}(),Ct=function t(){function e(t,e,r,i,n,o){this.viewBox=t,this.scale=e,this.rotation=r,this.offsetX=i,this.offsetY=n;var a=(t[2]+t[0])/2,s=(t[3]+t[1])/2,c,l,h,u;switch(r%=360,r=r<0?r+360:r){case 180:c=-1,l=0,h=0,u=1;break;case 90:c=0,l=1,h=1,u=0;break;case 270:c=0,l=-1,h=-1,u=0;break;default:c=1,l=0,h=0,u=-1}o&&(h=-h,u=-u);var f,d,p,g;0===c?(f=Math.abs(s-t[1])*e+i,d=Math.abs(a-t[0])*e+n,p=Math.abs(t[3]-t[1])*e,g=Math.abs(t[2]-t[0])*e):(f=Math.abs(a-t[0])*e+i,d=Math.abs(s-t[1])*e+n,p=Math.abs(t[2]-t[0])*e,g=Math.abs(t[3]-t[1])*e),this.transform=[c*e,l*e,h*e,u*e,f-c*e*a-h*e*s,d-l*e*a-u*e*s],this.width=p,this.height=g,this.fontScale=e}return e.prototype={clone:function t(r){r=r||{};var i="scale"in r?r.scale:this.scale,n="rotation"in r?r.rotation:this.rotation;return new e(this.viewBox.slice(),i,n,this.offsetX,this.offsetY,r.dontFlip)},convertToViewportPoint:function t(e,r){return xt.applyTransform([e,r],this.transform)},convertToViewportRectangle:function t(e){var r=xt.applyTransform([e[0],e[1]],this.transform),i=xt.applyTransform([e[2],e[3]],this.transform);return[r[0],r[1],i[0],i[1]]},convertToPdfPoint:function t(e,r){return xt.applyInverseTransform([e,r],this.transform)}},e}(),At=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,728,711,710,729,733,731,730,732,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8226,8224,8225,8230,8212,8211,402,8260,8249,8250,8722,8240,8222,8220,8221,8216,8217,8218,8482,64257,64258,321,338,352,376,381,305,322,339,353,382,0,8364],Tt=function t(){function e(t,e,r){for(;t.length<r;)t+=e;return t}function r(){this.started=Object.create(null),this.times=[],this.enabled=!0}return r.prototype={time:function t(e){this.enabled&&(e in this.started&&c("Timer is already running for "+e),this.started[e]=Date.now())},timeEnd:function t(e){this.enabled&&(e in this.started||c("Timer has not been started for "+e),this.times.push({name:e,start:this.started[e],end:Date.now()}),delete this.started[e])},toString:function t(){var r,i,n=this.times,o="",a=0;for(r=0,i=n.length;r<i;++r){var s=n[r].name;s.length>a&&(a=s.length)}for(r=0,i=n.length;r<i;++r){var c=n[r],l=c.end-c.start;o+=e(c.name," ",a)+" "+l+"ms\n"}return o}},r}(),kt=function t(e,r){if("undefined"!=typeof Blob)return new Blob([e],{type:r});throw new Error('The "Blob" constructor is not supported.')},Pt=function t(){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";return function t(r,i){if(!(arguments.length>2&&void 0!==arguments[2]&&arguments[2])&&URL.createObjectURL){var n=kt(r,i);return URL.createObjectURL(n)}for(var o="data:"+i+";base64,",a=0,s=r.length;a<s;a+=3){var c=255&r[a],l=255&r[a+1],h=255&r[a+2];o+=e[c>>2]+e[(3&c)<<4|l>>4]+e[a+1<s?(15&l)<<2|h>>6:64]+e[a+2<s?63&h:64]}return o}}();G.prototype={on:function t(e,r,i){var n=this.actionHandler;if(n[e])throw new Error('There is already an actionName called "'+e+'"');n[e]=[r,i]},send:function t(e,r,i){var n={sourceName:this.sourceName,targetName:this.targetName,action:e,data:r};this.postMessage(n,i)},sendWithPromise:function t(e,r,i){var n=this.callbackId++,o={sourceName:this.sourceName,targetName:this.targetName,action:e,data:r,callbackId:n},a=z();this.callbacksCapabilities[n]=a;try{this.postMessage(o,i)}catch(t){a.reject(t)}return a.promise},sendWithStream:function t(e,r,i,n){var o=this,a=this.streamId++,s=this.sourceName,c=this.targetName;return new V.ReadableStream({start:function t(i){var n=z();return o.streamControllers[a]={controller:i,startCall:n,isClosed:!1},o.postMessage({sourceName:s,targetName:c,action:e,streamId:a,data:r,desiredSize:i.desiredSize}),n.promise},pull:function t(e){var r=z();return o.streamControllers[a].pullCall=r,o.postMessage({sourceName:s,targetName:c,stream:"pull",streamId:a,desiredSize:e.desiredSize}),r.promise},cancel:function t(e){var r=z();return o.streamControllers[a].cancelCall=r,o.streamControllers[a].isClosed=!0,o.postMessage({sourceName:s,targetName:c,stream:"cancel",reason:e,streamId:a}),r.promise}},i)},_createStreamSink:function t(e){var r=this,i=this,n=this.actionHandler[e.action],o=e.streamId,a=e.desiredSize,s=this.sourceName,c=e.sourceName,l=z(),h=function t(e){var i=e.stream,n=e.chunk,a=e.success,l=e.reason;r.comObj.postMessage({sourceName:s,targetName:c,stream:i,streamId:o,chunk:n,success:a,reason:l})},u={enqueue:function t(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;if(!this.isCancelled){var i=this.desiredSize;this.desiredSize-=r,i>0&&this.desiredSize<=0&&(this.sinkCapability=z(),this.ready=this.sinkCapability.promise),h({stream:"enqueue",chunk:e})}},close:function t(){this.isCancelled||(h({stream:"close"}),delete i.streamSinks[o])},error:function t(e){h({stream:"error",reason:e})},sinkCapability:l,onPull:null,onCancel:null,isCancelled:!1,desiredSize:a,ready:null};u.sinkCapability.resolve(),u.ready=u.sinkCapability.promise,this.streamSinks[o]=u,W(n[0],[e.data,u],n[1]).then(function(){h({stream:"start_complete",success:!0})},function(t){h({stream:"start_complete",success:!1,reason:t})})},_processStreamMessage:function t(e){var r=this,i=this.sourceName,n=e.sourceName,o=e.streamId,a=function t(e){var a=e.stream,s=e.success,c=e.reason;r.comObj.postMessage({sourceName:i,targetName:n,stream:a,success:s,streamId:o,reason:c})},s=function t(){Promise.all([r.streamControllers[e.streamId].startCall,r.streamControllers[e.streamId].pullCall,r.streamControllers[e.streamId].cancelCall].map(function(t){return t&&X(t.promise)})).then(function(){delete r.streamControllers[e.streamId]})};switch(e.stream){case"start_complete":q(this.streamControllers[e.streamId].startCall,e.success,e.reason);break;case"pull_complete":q(this.streamControllers[e.streamId].pullCall,e.success,e.reason);break;case"pull":if(!this.streamSinks[e.streamId]){a({stream:"pull_complete",success:!0});break}this.streamSinks[e.streamId].desiredSize<=0&&e.desiredSize>0&&this.streamSinks[e.streamId].sinkCapability.resolve(),this.streamSinks[e.streamId].desiredSize=e.desiredSize,W(this.streamSinks[e.streamId].onPull).then(function(){a({stream:"pull_complete",success:!0})},function(t){a({stream:"pull_complete",success:!1,reason:t})});break;case"enqueue":this.streamControllers[e.streamId].isClosed||this.streamControllers[e.streamId].controller.enqueue(e.chunk);break;case"close":if(this.streamControllers[e.streamId].isClosed)break;this.streamControllers[e.streamId].isClosed=!0,this.streamControllers[e.streamId].controller.close(),s();break;case"error":this.streamControllers[e.streamId].controller.error(e.reason),s();break;case"cancel_complete":q(this.streamControllers[e.streamId].cancelCall,e.success,e.reason),s();break;case"cancel":if(!this.streamSinks[e.streamId])break;W(this.streamSinks[e.streamId].onCancel,[e.reason]).then(function(){a({stream:"cancel_complete",success:!0})},function(t){a({stream:"cancel_complete",success:!1,reason:t})}),this.streamSinks[e.streamId].sinkCapability.reject(e.reason),this.streamSinks[e.streamId].isCancelled=!0,delete this.streamSinks[e.streamId];break;default:throw new Error("Unexpected stream case")}},postMessage:function t(e,r){r&&this.postMessageTransfers?this.comObj.postMessage(e,r):this.comObj.postMessage(e)},destroy:function t(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}},r.FONT_IDENTITY_MATRIX=J,r.IDENTITY_MATRIX=St,r.OPS=ct,r.VERBOSITY_LEVELS=at,r.UNSUPPORTED_FEATURES=ht,r.AnnotationBorderStyleType=it,r.AnnotationFieldFlag=rt,r.AnnotationFlag=et,r.AnnotationType=tt,r.FontType=ot,r.ImageKind=$,r.CMapCompressionType=st,r.InvalidPDFException=pt,r.MessageHandler=G,r.MissingDataException=bt,r.MissingPDFException=gt,r.NativeImageDecoding=K,r.NotImplementedException=mt,r.PageViewport=Ct,r.PasswordException=ft,r.PasswordResponses=ut,r.StatTimer=Tt,r.StreamType=nt,r.TextRenderingMode=Q,r.UnexpectedResponseException=vt,r.UnknownErrorException=dt,r.Util=xt,r.XRefParseException=yt,r.FormatError=_t,r.arrayByteLength=_,r.arraysToBytes=w,r.assert=u,r.bytesToString=b,r.createBlob=kt,r.createPromiseCapability=z,r.createObjectURL=Pt,r.deprecated=l,r.getLookupTableFactory=v,r.getVerbosityLevel=a,r.globalScope=Z,r.info=s,r.isArray=F,r.isArrayBuffer=N,r.isBool=D,r.isEmptyObj=L,r.isInt=I,r.isNum=j,r.isString=M,r.isSpace=B,r.isNodeJS=U,r.isSameOrigin=f,r.createValidAbsoluteUrl=p,r.isLittleEndian=k,r.isEvalSupported=P,r.loadJpegStream=H,r.log2=x,r.readInt8=C,r.readUint16=A,r.readUint32=T,r.removeNullCharacters=m,r.ReadableStream=V.ReadableStream,r.setVerbosityLevel=o,r.shadow=g,r.string32=S,r.stringToBytes=y,r.stringToPDFString=E,r.stringToUTF8String=O,r.utf8StringToString=R,r.warn=c,r.unreachable=h},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){var r=e&&e.url;if(t.href=t.title=r?(0,h.removeNullCharacters)(r):"",r){var i=e.target;void 0===i&&(i=a("externalLinkTarget")),t.target=m[i];var n=e.rel;void 0===n&&(n=a("externalLinkRel")),t.rel=n}}function o(t){var e=t.indexOf("#"),r=t.indexOf("?"),i=Math.min(e>0?e:t.length,r>0?r:t.length);return t.substring(t.lastIndexOf("/",i)+1,i)}function a(t){var e=h.globalScope.PDFJS;switch(t){case"pdfBug":return!!e&&e.pdfBug;case"disableAutoFetch":return!!e&&e.disableAutoFetch;case"disableStream":return!!e&&e.disableStream;case"disableRange":return!!e&&e.disableRange;case"disableFontFace":return!!e&&e.disableFontFace;case"disableCreateObjectURL":return!!e&&e.disableCreateObjectURL;case"disableWebGL":return!e||e.disableWebGL;case"cMapUrl":return e?e.cMapUrl:null;case"cMapPacked":return!!e&&e.cMapPacked;case"postMessageTransfers":return!e||e.postMessageTransfers;case"workerPort":return e?e.workerPort:null;case"workerSrc":return e?e.workerSrc:null;case"disableWorker":return!!e&&e.disableWorker;case"maxImageSize":return e?e.maxImageSize:-1;case"imageResourcesPath":return e?e.imageResourcesPath:"";case"isEvalSupported":return!e||e.isEvalSupported;case"externalLinkTarget":if(!e)return v.NONE;switch(e.externalLinkTarget){case v.NONE:case v.SELF:case v.BLANK:case v.PARENT:case v.TOP:return e.externalLinkTarget}return(0,h.warn)("PDFJS.externalLinkTarget is invalid: "+e.externalLinkTarget),e.externalLinkTarget=v.NONE,v.NONE;case"externalLinkRel":return e?e.externalLinkRel:u;case"enableStats":return!(!e||!e.enableStats);case"pdfjsNext":return!(!e||!e.pdfjsNext);default:throw new Error("Unknown default setting: "+t)}}function s(){switch(a("externalLinkTarget")){case v.NONE:return!1;case v.SELF:case v.BLANK:case v.PARENT:case v.TOP:return!0}}function c(t,e){(0,h.deprecated)("isValidUrl(), please use createValidAbsoluteUrl() instead.");var r=e?"http://example.com":null;return null!==(0,h.createValidAbsoluteUrl)(t,r)}Object.defineProperty(e,"__esModule",{value:!0}),e.DOMCMapReaderFactory=e.DOMCanvasFactory=e.DEFAULT_LINK_REL=e.getDefaultSetting=e.LinkTarget=e.getFilenameFromUrl=e.isValidUrl=e.isExternalLinkTargetSet=e.addLinkAttributes=e.RenderingCancelledException=e.CustomStyle=void 0;var l=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),h=r(0),u="noopener noreferrer nofollow",f=function(){function t(){i(this,t)}return l(t,[{key:"create",value:function t(e,r){if(e<=0||r<=0)throw new Error("invalid canvas size");var i=document.createElement("canvas"),n=i.getContext("2d");return i.width=e,i.height=r,{canvas:i,context:n}}},{key:"reset",value:function t(e,r,i){if(!e.canvas)throw new Error("canvas is not specified");if(r<=0||i<=0)throw new Error("invalid canvas size");e.canvas.width=r,e.canvas.height=i}},{key:"destroy",value:function t(e){if(!e.canvas)throw new Error("canvas is not specified");e.canvas.width=0,e.canvas.height=0,e.canvas=null,e.context=null}}]),t}(),d=function(){function t(e){var r=e.baseUrl,n=void 0===r?null:r,o=e.isCompressed,a=void 0!==o&&o;i(this,t),this.baseUrl=n,this.isCompressed=a}return l(t,[{key:"fetch",value:function t(e){var r=this,i=e.name;return i?new Promise(function(t,e){var n=r.baseUrl+i+(r.isCompressed?".bcmap":""),o=new XMLHttpRequest;o.open("GET",n,!0),r.isCompressed&&(o.responseType="arraybuffer"),o.onreadystatechange=function(){if(o.readyState===XMLHttpRequest.DONE){if(200===o.status||0===o.status){var i=void 0;if(r.isCompressed&&o.response?i=new Uint8Array(o.response):!r.isCompressed&&o.responseText&&(i=(0,h.stringToBytes)(o.responseText)),i)return void t({cMapData:i,compressionType:r.isCompressed?h.CMapCompressionType.BINARY:h.CMapCompressionType.NONE})}e(new Error("Unable to load "+(r.isCompressed?"binary ":"")+"CMap at: "+n))}},o.send(null)}):Promise.reject(new Error("CMap name must be specified."))}}]),t}(),p=function t(){function e(){}var r=["ms","Moz","Webkit","O"],i=Object.create(null);return e.getProp=function t(e,n){if(1===arguments.length&&"string"==typeof i[e])return i[e];n=n||document.documentElement;var o=n.style,a,s;if("string"==typeof o[e])return i[e]=e;s=e.charAt(0).toUpperCase()+e.slice(1);for(var c=0,l=r.length;c<l;c++)if(a=r[c]+s,"string"==typeof o[a])return i[e]=a;return i[e]="undefined"},e.setProp=function t(e,r,i){var n=this.getProp(e);"undefined"!==n&&(r.style[n]=i)},e}(),g=function t(){function t(t,e){this.message=t,this.type=e}return t.prototype=new Error,t.prototype.name="RenderingCancelledException",t.constructor=t,t}(),v={NONE:0,SELF:1,BLANK:2,PARENT:3,TOP:4},m=["","_self","_blank","_parent","_top"];e.CustomStyle=p,e.RenderingCancelledException=g,e.addLinkAttributes=n,e.isExternalLinkTargetSet=s,e.isValidUrl=c,e.getFilenameFromUrl=o,e.LinkTarget=v,e.getDefaultSetting=a,e.DEFAULT_LINK_REL=u,e.DOMCanvasFactory=f,e.DOMCMapReaderFactory=d},function(t,e,r){"use strict";function i(){}Object.defineProperty(e,"__esModule",{value:!0}),e.AnnotationLayer=void 0;var n=r(1),o=r(0);i.prototype={create:function t(e){switch(e.data.annotationType){case o.AnnotationType.LINK:return new s(e);case o.AnnotationType.TEXT:return new c(e);case o.AnnotationType.WIDGET:switch(e.data.fieldType){case"Tx":return new h(e);case"Btn":if(e.data.radioButton)return new f(e);if(e.data.checkBox)return new u(e);(0,o.warn)("Unimplemented button widget annotation: pushbutton");break;case"Ch":return new d(e)}return new l(e);case o.AnnotationType.POPUP:return new p(e);case o.AnnotationType.LINE:return new v(e);case o.AnnotationType.HIGHLIGHT:return new m(e);case o.AnnotationType.UNDERLINE:return new b(e);case o.AnnotationType.SQUIGGLY:return new y(e);case o.AnnotationType.STRIKEOUT:return new _(e);case o.AnnotationType.FILEATTACHMENT:return new w(e);default:return new a(e)}}};var a=function t(){function e(t,e,r){this.isRenderable=e||!1,this.data=t.data,this.layer=t.layer,this.page=t.page,this.viewport=t.viewport,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderInteractiveForms=t.renderInteractiveForms,e&&(this.container=this._createContainer(r))}return e.prototype={_createContainer:function t(e){var r=this.data,i=this.page,a=this.viewport,s=document.createElement("section"),c=r.rect[2]-r.rect[0],l=r.rect[3]-r.rect[1];s.setAttribute("data-annotation-id",r.id);var h=o.Util.normalizeRect([r.rect[0],i.view[3]-r.rect[1]+i.view[1],r.rect[2],i.view[3]-r.rect[3]+i.view[1]]);if(n.CustomStyle.setProp("transform",s,"matrix("+a.transform.join(",")+")"),n.CustomStyle.setProp("transformOrigin",s,-h[0]+"px "+-h[1]+"px"),!e&&r.borderStyle.width>0){s.style.borderWidth=r.borderStyle.width+"px",r.borderStyle.style!==o.AnnotationBorderStyleType.UNDERLINE&&(c-=2*r.borderStyle.width,l-=2*r.borderStyle.width);var u=r.borderStyle.horizontalCornerRadius,f=r.borderStyle.verticalCornerRadius;if(u>0||f>0){var d=u+"px / "+f+"px";n.CustomStyle.setProp("borderRadius",s,d)}switch(r.borderStyle.style){case o.AnnotationBorderStyleType.SOLID:s.style.borderStyle="solid";break;case o.AnnotationBorderStyleType.DASHED:s.style.borderStyle="dashed";break;case o.AnnotationBorderStyleType.BEVELED:(0,o.warn)("Unimplemented border style: beveled");break;case o.AnnotationBorderStyleType.INSET:(0,o.warn)("Unimplemented border style: inset");break;case o.AnnotationBorderStyleType.UNDERLINE:s.style.borderBottomStyle="solid"}r.color?s.style.borderColor=o.Util.makeCssRgb(0|r.color[0],0|r.color[1],0|r.color[2]):s.style.borderWidth=0}return s.style.left=h[0]+"px",s.style.top=h[1]+"px",s.style.width=c+"px",s.style.height=l+"px",s},_createPopup:function t(e,r,i){r||(r=document.createElement("div"),r.style.height=e.style.height,r.style.width=e.style.width,e.appendChild(r));var n=new g({container:e,trigger:r,color:i.color,title:i.title,contents:i.contents,hideWrapper:!0}),o=n.render();o.style.left=e.style.width,e.appendChild(o)},render:function t(){throw new Error("Abstract method AnnotationElement.render called")}},e}(),s=function t(){function e(t){a.call(this,t,!0)}return o.Util.inherit(e,a,{render:function t(){this.container.className="linkAnnotation";var e=document.createElement("a");return(0,n.addLinkAttributes)(e,{url:this.data.url,target:this.data.newWindow?n.LinkTarget.BLANK:void 0}),this.data.url||(this.data.action?this._bindNamedAction(e,this.data.action):this._bindLink(e,this.data.dest)),this.container.appendChild(e),this.container},_bindLink:function t(e,r){var i=this;e.href=this.linkService.getDestinationHash(r),e.onclick=function(){return r&&i.linkService.navigateTo(r),!1},r&&(e.className="internalLink")},_bindNamedAction:function t(e,r){var i=this;e.href=this.linkService.getAnchorUrl(""),e.onclick=function(){return i.linkService.executeNamedAction(r),!1},e.className="internalLink"}}),e}(),c=function t(){function e(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);a.call(this,t,e)}return o.Util.inherit(e,a,{render:function t(){this.container.className="textAnnotation";var e=document.createElement("img");return e.style.height=this.container.style.height,e.style.width=this.container.style.width,e.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",e.alt="[{{type}} Annotation]",e.dataset.l10nId="text_annotation_type",e.dataset.l10nArgs=JSON.stringify({type:this.data.name}),this.data.hasPopup||this._createPopup(this.container,e,this.data),this.container.appendChild(e),this.container}}),e}(),l=function t(){function e(t,e){a.call(this,t,e)}return o.Util.inherit(e,a,{render:function t(){return this.container}}),e}(),h=function t(){function e(t){var e=t.renderInteractiveForms||!t.data.hasAppearance&&!!t.data.fieldValue;l.call(this,t,e)}var r=["left","center","right"];return o.Util.inherit(e,l,{render:function t(){this.container.className="textWidgetAnnotation";var e=null;if(this.renderInteractiveForms){if(this.data.multiLine?(e=document.createElement("textarea"),e.textContent=this.data.fieldValue):(e=document.createElement("input"),e.type="text",e.setAttribute("value",this.data.fieldValue)),e.disabled=this.data.readOnly,null!==this.data.maxLen&&(e.maxLength=this.data.maxLen),this.data.comb){var i=this.data.rect[2]-this.data.rect[0],n=i/this.data.maxLen;e.classList.add("comb"),e.style.letterSpacing="calc("+n+"px - 1ch)"}}else{e=document.createElement("div"),e.textContent=this.data.fieldValue,e.style.verticalAlign="middle",e.style.display="table-cell";var o=null;this.data.fontRefName&&(o=this.page.commonObjs.getData(this.data.fontRefName)),this._setTextStyle(e,o)}return null!==this.data.textAlignment&&(e.style.textAlign=r[this.data.textAlignment]),this.container.appendChild(e),this.container},_setTextStyle:function t(e,r){var i=e.style;if(i.fontSize=this.data.fontSize+"px",i.direction=this.data.fontDirection<0?"rtl":"ltr",r){i.fontWeight=r.black?r.bold?"900":"bold":r.bold?"bold":"normal",i.fontStyle=r.italic?"italic":"normal";var n=r.loadedName?'"'+r.loadedName+'", ':"",o=r.fallbackName||"Helvetica, sans-serif";i.fontFamily=n+o}}}),e}(),u=function t(){function e(t){l.call(this,t,t.renderInteractiveForms)}return o.Util.inherit(e,l,{render:function t(){this.container.className="buttonWidgetAnnotation checkBox";var e=document.createElement("input");return e.disabled=this.data.readOnly,e.type="checkbox",this.data.fieldValue&&"Off"!==this.data.fieldValue&&e.setAttribute("checked",!0),this.container.appendChild(e),this.container}}),e}(),f=function t(){function e(t){l.call(this,t,t.renderInteractiveForms)}return o.Util.inherit(e,l,{render:function t(){this.container.className="buttonWidgetAnnotation radioButton";var e=document.createElement("input");return e.disabled=this.data.readOnly,e.type="radio",e.name=this.data.fieldName,this.data.fieldValue===this.data.buttonValue&&e.setAttribute("checked",!0),this.container.appendChild(e),this.container}}),e}(),d=function t(){function e(t){l.call(this,t,t.renderInteractiveForms)}return o.Util.inherit(e,l,{render:function t(){this.container.className="choiceWidgetAnnotation";var e=document.createElement("select");e.disabled=this.data.readOnly,this.data.combo||(e.size=this.data.options.length,this.data.multiSelect&&(e.multiple=!0));for(var r=0,i=this.data.options.length;r<i;r++){var n=this.data.options[r],o=document.createElement("option");o.textContent=n.displayValue,o.value=n.exportValue,this.data.fieldValue.indexOf(n.displayValue)>=0&&o.setAttribute("selected",!0),e.appendChild(o)}return this.container.appendChild(e),this.container}}),e}(),p=function t(){function e(t){var e=!(!t.data.title&&!t.data.contents);a.call(this,t,e)}var r=["Line"];return o.Util.inherit(e,a,{render:function t(){if(this.container.className="popupAnnotation",r.indexOf(this.data.parentType)>=0)return this.container;var e='[data-annotation-id="'+this.data.parentId+'"]',i=this.layer.querySelector(e);if(!i)return this.container;var o=new g({container:this.container,trigger:i,color:this.data.color,title:this.data.title,contents:this.data.contents}),a=parseFloat(i.style.left),s=parseFloat(i.style.width);return n.CustomStyle.setProp("transformOrigin",this.container,-(a+s)+"px -"+i.style.top),this.container.style.left=a+s+"px",this.container.appendChild(o.render()),this.container}}),e}(),g=function t(){function e(t){this.container=t.container,this.trigger=t.trigger,this.color=t.color,this.title=t.title,this.contents=t.contents,this.hideWrapper=t.hideWrapper||!1,this.pinned=!1}var r=.7;return e.prototype={render:function t(){var e=document.createElement("div");e.className="popupWrapper",this.hideElement=this.hideWrapper?e:this.container,this.hideElement.setAttribute("hidden",!0);var r=document.createElement("div");r.className="popup";var i=this.color;if(i){var n=.7*(255-i[0])+i[0],a=.7*(255-i[1])+i[1],s=.7*(255-i[2])+i[2];r.style.backgroundColor=o.Util.makeCssRgb(0|n,0|a,0|s)}var c=this._formatContents(this.contents),l=document.createElement("h1");return l.textContent=this.title,this.trigger.addEventListener("click",this._toggle.bind(this)),this.trigger.addEventListener("mouseover",this._show.bind(this,!1)),this.trigger.addEventListener("mouseout",this._hide.bind(this,!1)),r.addEventListener("click",this._hide.bind(this,!0)),r.appendChild(l),r.appendChild(c),e.appendChild(r),e},_formatContents:function t(e){for(var r=document.createElement("p"),i=e.split(/(?:\r\n?|\n)/),n=0,o=i.length;n<o;++n){var a=i[n];r.appendChild(document.createTextNode(a)),n<o-1&&r.appendChild(document.createElement("br"))}return r},_toggle:function t(){this.pinned?this._hide(!0):this._show(!0)},_show:function t(e){e&&(this.pinned=!0),this.hideElement.hasAttribute("hidden")&&(this.hideElement.removeAttribute("hidden"),this.container.style.zIndex+=1)},_hide:function t(e){e&&(this.pinned=!1),this.hideElement.hasAttribute("hidden")||this.pinned||(this.hideElement.setAttribute("hidden",!0),this.container.style.zIndex-=1)}},e}(),v=function t(){function e(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);a.call(this,t,e,!0)}var r="http://www.w3.org/2000/svg";return o.Util.inherit(e,a,{render:function t(){this.container.className="lineAnnotation";var e=this.data,i=e.rect[2]-e.rect[0],n=e.rect[3]-e.rect[1],o=document.createElementNS(r,"svg:svg");o.setAttributeNS(null,"version","1.1"),o.setAttributeNS(null,"width",i+"px"),o.setAttributeNS(null,"height",n+"px"),o.setAttributeNS(null,"preserveAspectRatio","none"),o.setAttributeNS(null,"viewBox","0 0 "+i+" "+n);var a=document.createElementNS(r,"svg:line");return a.setAttributeNS(null,"x1",e.rect[2]-e.lineCoordinates[0]),a.setAttributeNS(null,"y1",e.rect[3]-e.lineCoordinates[1]),a.setAttributeNS(null,"x2",e.rect[2]-e.lineCoordinates[2]),a.setAttributeNS(null,"y2",e.rect[3]-e.lineCoordinates[3]),a.setAttributeNS(null,"stroke-width",e.borderStyle.width),a.setAttributeNS(null,"stroke","transparent"),o.appendChild(a),this.container.append(o),this._createPopup(this.container,a,this.data),this.container}}),e}(),m=function t(){function e(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);a.call(this,t,e,!0)}return o.Util.inherit(e,a,{render:function t(){return this.container.className="highlightAnnotation",this.data.hasPopup||this._createPopup(this.container,null,this.data),this.container}}),e}(),b=function t(){function e(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);a.call(this,t,e,!0)}return o.Util.inherit(e,a,{render:function t(){return this.container.className="underlineAnnotation",this.data.hasPopup||this._createPopup(this.container,null,this.data),this.container}}),e}(),y=function t(){function e(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);a.call(this,t,e,!0)}return o.Util.inherit(e,a,{render:function t(){return this.container.className="squigglyAnnotation",this.data.hasPopup||this._createPopup(this.container,null,this.data),this.container}}),e}(),_=function t(){function e(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);a.call(this,t,e,!0)}return o.Util.inherit(e,a,{render:function t(){return this.container.className="strikeoutAnnotation",this.data.hasPopup||this._createPopup(this.container,null,this.data),this.container}}),e}(),w=function t(){function e(t){a.call(this,t,!0);var e=this.data.file;this.filename=(0,n.getFilenameFromUrl)(e.filename),this.content=e.content,this.linkService.onFileAttachmentAnnotation({id:(0,o.stringToPDFString)(e.filename),filename:e.filename,content:e.content})}return o.Util.inherit(e,a,{render:function t(){this.container.className="fileAttachmentAnnotation";var e=document.createElement("div");return e.style.height=this.container.style.height,e.style.width=this.container.style.width,e.addEventListener("dblclick",this._download.bind(this)),this.data.hasPopup||!this.data.title&&!this.data.contents||this._createPopup(this.container,e,this.data),this.container.appendChild(e),this.container},_download:function t(){if(!this.downloadManager)return void(0,o.warn)("Download cannot be started due to unavailable download manager");this.downloadManager.downloadData(this.content,this.filename,"")}}),e}(),S=function t(){return{render:function t(e){for(var r=new i,o=0,a=e.annotations.length;o<a;o++){var s=e.annotations[o];if(s){var c=r.create({data:s,layer:e.div,page:e.page,viewport:e.viewport,linkService:e.linkService,downloadManager:e.downloadManager,imageResourcesPath:e.imageResourcesPath||(0,n.getDefaultSetting)("imageResourcesPath"),renderInteractiveForms:e.renderInteractiveForms||!1});c.isRenderable&&e.div.appendChild(c.render())}}},update:function t(e){for(var r=0,i=e.annotations.length;r<i;r++){var o=e.annotations[r],a=e.div.querySelector('[data-annotation-id="'+o.id+'"]');a&&n.CustomStyle.setProp("transform",a,"matrix("+e.viewport.transform.join(",")+")")}e.div.removeAttribute("hidden")}}}();e.AnnotationLayer=S},function(t,e,i){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e,r,i){var n=new S;arguments.length>1&&(0,l.deprecated)("getDocument is called with pdfDataRangeTransport, passwordCallback or progressCallback argument"),e&&(e instanceof x||(e=Object.create(e),e.length=t.length,e.initialData=t.initialData,e.abort||(e.abort=function(){})),t=Object.create(t),t.range=e),n.onPassword=r||null,n.onProgress=i||null;var o;if("string"==typeof t)o={url:t};else if((0,l.isArrayBuffer)(t))o={data:t};else if(t instanceof x)o={range:t};else{if("object"!==(void 0===t?"undefined":c(t)))throw new Error("Invalid parameter in getDocument, need either Uint8Array, string or a parameter object");if(!t.url&&!t.data&&!t.range)throw new Error("Invalid parameter object: need either .data, .range or .url");o=t}var s={},u=null,f=null,d=h.DOMCMapReaderFactory;for(var g in o)if("url"!==g||"undefined"==typeof window)if("range"!==g)if("worker"!==g)if("data"!==g||o[g]instanceof Uint8Array)"CMapReaderFactory"!==g?s[g]=o[g]:d=o[g];else{var v=o[g];if("string"==typeof v)s[g]=(0,l.stringToBytes)(v);else if("object"!==(void 0===v?"undefined":c(v))||null===v||isNaN(v.length)){if(!(0,l.isArrayBuffer)(v))throw new Error("Invalid PDF binary data: either typed array, string or array-like object is expected in the data property.");s[g]=new Uint8Array(v)}else s[g]=new Uint8Array(v)}else f=o[g];else u=o[g];else s[g]=new URL(o[g],window.location).href;if(s.rangeChunkSize=s.rangeChunkSize||p,s.ignoreErrors=!0!==s.stopAtErrors,void 0!==s.disableNativeImageDecoder&&(0,l.deprecated)("parameter disableNativeImageDecoder, use nativeImageDecoderSupport instead"),s.nativeImageDecoderSupport=s.nativeImageDecoderSupport||(!0===s.disableNativeImageDecoder?l.NativeImageDecoding.NONE:l.NativeImageDecoding.DECODE),s.nativeImageDecoderSupport!==l.NativeImageDecoding.DECODE&&s.nativeImageDecoderSupport!==l.NativeImageDecoding.NONE&&s.nativeImageDecoderSupport!==l.NativeImageDecoding.DISPLAY&&((0,l.warn)("Invalid parameter nativeImageDecoderSupport: need a state of enum {NativeImageDecoding}"),s.nativeImageDecoderSupport=l.NativeImageDecoding.DECODE),!f){var m=(0,h.getDefaultSetting)("workerPort");f=m?k.fromPort(m):new k,n._worker=f}var b=n.docId;return f.promise.then(function(){if(n.destroyed)throw new Error("Loading aborted");return a(f,s,u,b).then(function(t){if(n.destroyed)throw new Error("Loading aborted");var e=new l.MessageHandler(b,t,f.port),r=new P(e,n,u,d);n._transport=r,e.send("Ready",null)})}).catch(n._capability.reject),n}function a(t,e,r,i){return t.destroyed?Promise.reject(new Error("Worker was destroyed")):(e.disableAutoFetch=(0,h.getDefaultSetting)("disableAutoFetch"),e.disableStream=(0,h.getDefaultSetting)("disableStream"),e.chunkedViewerLoading=!!r,r&&(e.length=r.length,e.initialData=r.initialData),t.messageHandler.sendWithPromise("GetDocRequest",{docId:i,source:e,disableRange:(0,h.getDefaultSetting)("disableRange"),maxImageSize:(0,h.getDefaultSetting)("maxImageSize"),disableFontFace:(0,h.getDefaultSetting)("disableFontFace"),disableCreateObjectURL:(0,h.getDefaultSetting)("disableCreateObjectURL"),postMessageTransfers:(0,h.getDefaultSetting)("postMessageTransfers")&&!m,docBaseUrl:e.docBaseUrl,nativeImageDecoderSupport:e.nativeImageDecoderSupport,ignoreErrors:e.ignoreErrors}).then(function(e){if(t.destroyed)throw new Error("Worker was destroyed");return e}))}Object.defineProperty(e,"__esModule",{value:!0}),e.build=e.version=e._UnsupportedManager=e.PDFPageProxy=e.PDFDocumentProxy=e.PDFWorker=e.PDFDataRangeTransport=e.LoopbackPort=e.getDocument=void 0;var s=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},l=i(0),h=i(1),u=i(11),f=i(10),d=i(6),p=65536,g=!1,v,m=!1,b="undefined"!=typeof document&&document.currentScript?document.currentScript.src:null,y=null,_=!1;"undefined"==typeof window?(g=!0,_=!0):_=!0,"undefined"!=typeof requirejs&&requirejs.toUrl&&(v=requirejs.toUrl("pdfjs-dist/build/pdf.worker.js"));var w="undefined"!=typeof requirejs&&requirejs.load;y=_?function(t){r.e(0).then(function(){var e;e=r(81),t(e.WorkerMessageHandler)}.bind(null,r)).catch(r.oe)}:w?function(t){requirejs(["pdfjs-dist/build/pdf.worker"],function(e){t(e.WorkerMessageHandler)})}:null;var S=function t(){function e(){this._capability=(0,l.createPromiseCapability)(),this._transport=null,this._worker=null,this.docId="d"+r++,this.destroyed=!1,this.onPassword=null,this.onProgress=null,this.onUnsupportedFeature=null}var r=0;return e.prototype={get promise(){return this._capability.promise},destroy:function t(){var e=this;return this.destroyed=!0,(this._transport?this._transport.destroy():Promise.resolve()).then(function(){e._transport=null,e._worker&&(e._worker.destroy(),e._worker=null)})},then:function t(e,r){return this.promise.then.apply(this.promise,arguments)}},e}(),x=function t(){function e(t,e){this.length=t,this.initialData=e,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._readyCapability=(0,l.createPromiseCapability)()}return e.prototype={addRangeListener:function t(e){this._rangeListeners.push(e)},addProgressListener:function t(e){this._progressListeners.push(e)},addProgressiveReadListener:function t(e){this._progressiveReadListeners.push(e)},onDataRange:function t(e,r){for(var i=this._rangeListeners,n=0,o=i.length;n<o;++n)i[n](e,r)},onDataProgress:function t(e){var r=this;this._readyCapability.promise.then(function(){for(var t=r._progressListeners,i=0,n=t.length;i<n;++i)t[i](e)})},onDataProgressiveRead:function t(e){var r=this;this._readyCapability.promise.then(function(){for(var t=r._progressiveReadListeners,i=0,n=t.length;i<n;++i)t[i](e)})},transportReady:function t(){this._readyCapability.resolve()},requestDataRange:function t(e,r){throw new Error("Abstract method PDFDataRangeTransport.requestDataRange")},abort:function t(){}},e}(),C=function t(){function e(t,e,r){this.pdfInfo=t,this.transport=e,this.loadingTask=r}return e.prototype={get numPages(){return this.pdfInfo.numPages},get fingerprint(){return this.pdfInfo.fingerprint},getPage:function t(e){return this.transport.getPage(e)},getPageIndex:function t(e){return this.transport.getPageIndex(e)},getDestinations:function t(){return this.transport.getDestinations()},getDestination:function t(e){return this.transport.getDestination(e)},getPageLabels:function t(){return this.transport.getPageLabels()},getPageMode:function t(){return this.transport.getPageMode()},getAttachments:function t(){return this.transport.getAttachments()},getJavaScript:function t(){return this.transport.getJavaScript()},getOutline:function t(){return this.transport.getOutline()},getMetadata:function t(){return this.transport.getMetadata()},getData:function t(){return this.transport.getData()},getDownloadInfo:function t(){return this.transport.downloadInfoCapability.promise},getStats:function t(){return this.transport.getStats()},cleanup:function t(){this.transport.startCleanup()},destroy:function t(){return this.loadingTask.destroy()}},e}(),A=function t(){function e(t,e,r){this.pageIndex=t,this.pageInfo=e,this.transport=r,this.stats=new l.StatTimer,this.stats.enabled=(0,h.getDefaultSetting)("enableStats"),this.commonObjs=r.commonObjs,this.objs=new E,this.cleanupAfterRender=!1,this.pendingCleanup=!1,this.intentStates=Object.create(null),this.destroyed=!1}return e.prototype={get pageNumber(){return this.pageIndex+1},get rotate(){return this.pageInfo.rotate},get ref(){return this.pageInfo.ref},get userUnit(){return this.pageInfo.userUnit},get view(){return this.pageInfo.view},getViewport:function t(e,r){return arguments.length<2&&(r=this.rotate),new l.PageViewport(this.view,e,r,0,0)},getAnnotations:function t(e){var r=e&&e.intent||null;return this.annotationsPromise&&this.annotationsIntent===r||(this.annotationsPromise=this.transport.getAnnotations(this.pageIndex,r),this.annotationsIntent=r),this.annotationsPromise},render:function t(e){var r=this,i=this.stats;i.time("Overall"),this.pendingCleanup=!1;var n="print"===e.intent?"print":"display",o=e.canvasFactory||new h.DOMCanvasFactory;this.intentStates[n]||(this.intentStates[n]=Object.create(null));var a=this.intentStates[n];a.displayReadyCapability||(a.receivingOperatorList=!0,a.displayReadyCapability=(0,l.createPromiseCapability)(),a.operatorList={fnArray:[],argsArray:[],lastChunk:!1},this.stats.time("Page Request"),this.transport.messageHandler.send("RenderPageRequest",{pageIndex:this.pageNumber-1,intent:n,renderInteractiveForms:!0===e.renderInteractiveForms}));var s=function t(e){var n=a.renderTasks.indexOf(c);n>=0&&a.renderTasks.splice(n,1),r.cleanupAfterRender&&(r.pendingCleanup=!0),r._tryCleanup(),e?c.capability.reject(e):c.capability.resolve(),i.timeEnd("Rendering"),i.timeEnd("Overall")},c=new R(s,e,this.objs,this.commonObjs,a.operatorList,this.pageNumber,o);c.useRequestAnimationFrame="print"!==n,a.renderTasks||(a.renderTasks=[]),a.renderTasks.push(c);var u=c.task;return e.continueCallback&&((0,l.deprecated)("render is used with continueCallback parameter"),u.onContinue=e.continueCallback),a.displayReadyCapability.promise.then(function(t){if(r.pendingCleanup)return void s();i.time("Rendering"),c.initializeGraphics(t),c.operatorListChanged()}).catch(s),u},getOperatorList:function t(){function e(){if(i.operatorList.lastChunk){i.opListReadCapability.resolve(i.operatorList);var t=i.renderTasks.indexOf(n);t>=0&&i.renderTasks.splice(t,1)}}var r="oplist";this.intentStates.oplist||(this.intentStates.oplist=Object.create(null));var i=this.intentStates.oplist,n;return i.opListReadCapability||(n={},n.operatorListChanged=e,i.receivingOperatorList=!0,i.opListReadCapability=(0,l.createPromiseCapability)(),i.renderTasks=[],i.renderTasks.push(n),i.operatorList={fnArray:[],argsArray:[],lastChunk:!1},this.transport.messageHandler.send("RenderPageRequest",{pageIndex:this.pageIndex,intent:"oplist"})),i.opListReadCapability.promise},streamTextContent:function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=100;return this.transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this.pageNumber-1,normalizeWhitespace:!0===e.normalizeWhitespace,combineTextItems:!0!==e.disableCombineTextItems},{highWaterMark:100,size:function t(e){return e.items.length}})},getTextContent:function t(e){e=e||{};var r=this.streamTextContent(e);return new Promise(function(t,e){function i(){n.read().then(function(e){var r=e.value;if(e.done)return void t(o);l.Util.extendObj(o.styles,r.styles),l.Util.appendToArray(o.items,r.items),i()},e)}var n=r.getReader(),o={items:[],styles:Object.create(null)};i()})},_destroy:function t(){this.destroyed=!0,this.transport.pageCache[this.pageIndex]=null;var e=[];return Object.keys(this.intentStates).forEach(function(t){if("oplist"!==t){this.intentStates[t].renderTasks.forEach(function(t){var r=t.capability.promise.catch(function(){});e.push(r),t.cancel()})}},this),this.objs.clear(),this.annotationsPromise=null,this.pendingCleanup=!1,Promise.all(e)},destroy:function t(){(0,l.deprecated)("page destroy method, use cleanup() instead"),this.cleanup()},cleanup:function t(){this.pendingCleanup=!0,this._tryCleanup()},_tryCleanup:function t(){this.pendingCleanup&&!Object.keys(this.intentStates).some(function(t){var e=this.intentStates[t];return 0!==e.renderTasks.length||e.receivingOperatorList},this)&&(Object.keys(this.intentStates).forEach(function(t){delete this.intentStates[t]},this),this.objs.clear(),this.annotationsPromise=null,this.pendingCleanup=!1)},_startRenderPage:function t(e,r){var i=this.intentStates[r];i.displayReadyCapability&&i.displayReadyCapability.resolve(e)},_renderPageChunk:function t(e,r){var i=this.intentStates[r],n,o;for(n=0,o=e.length;n<o;n++)i.operatorList.fnArray.push(e.fnArray[n]),i.operatorList.argsArray.push(e.argsArray[n]);for(i.operatorList.lastChunk=e.lastChunk,n=0;n<i.renderTasks.length;n++)i.renderTasks[n].operatorListChanged();e.lastChunk&&(i.receivingOperatorList=!1,this._tryCleanup())}},e}(),T=function(){function t(e){n(this,t),this._listeners=[],this._defer=e,this._deferred=Promise.resolve(void 0)}return s(t,[{key:"postMessage",value:function t(e,r){function i(t){if("object"!==(void 0===t?"undefined":c(t))||null===t)return t;if(o.has(t))return o.get(t);var e,n;if((n=t.buffer)&&(0,l.isArrayBuffer)(n)){var a=r&&r.indexOf(n)>=0;return e=t===n?t:a?new t.constructor(n,t.byteOffset,t.byteLength):new t.constructor(t),o.set(t,e),e}e=(0,l.isArray)(t)?[]:{},o.set(t,e);for(var s in t){for(var h,u=t;!(h=Object.getOwnPropertyDescriptor(u,s));)u=Object.getPrototypeOf(u);void 0!==h.value&&"function"!=typeof h.value&&(e[s]=i(h.value))}return e}var n=this;if(!this._defer)return void this._listeners.forEach(function(t){t.call(this,{data:e})},this);var o=new WeakMap,a={data:i(e)};this._deferred.then(function(){n._listeners.forEach(function(t){t.call(this,a)},n)})}},{key:"addEventListener",value:function t(e,r){this._listeners.push(r)}},{key:"removeEventListener",value:function t(e,r){var i=this._listeners.indexOf(r);this._listeners.splice(i,1)}},{key:"terminate",value:function t(){this._listeners=[]}}]),t}(),k=function t(){function e(){if(void 0!==v)return v;if((0,h.getDefaultSetting)("workerSrc"))return(0,h.getDefaultSetting)("workerSrc");if(b)return b.replace(/(\.(?:min\.)?js)(\?.*)?$/i,".worker$1$2");throw new Error("No PDFJS.workerSrc specified")}function r(){var t;return a?a.promise:(a=(0,l.createPromiseCapability)(),(y||function(t){l.Util.loadScript(e(),function(){t(window.pdfjsDistBuildPdfWorker.WorkerMessageHandler)})})(a.resolve),a.promise)}function i(t){var e="importScripts('"+t+"');";return URL.createObjectURL(new Blob([e]))}function n(t,e){if(e&&s.has(e))throw new Error("Cannot use more than one PDFWorker per port");if(this.name=t,this.destroyed=!1,this._readyCapability=(0,l.createPromiseCapability)(),this._port=null,this._webWorker=null,this._messageHandler=null,e)return s.set(e,this),void this._initializeFromPort(e);this._initialize()}var o=0,a=void 0,s=new WeakMap;return n.prototype={get promise(){return this._readyCapability.promise},get port(){return this._port},get messageHandler(){return this._messageHandler},_initializeFromPort:function t(e){this._port=e,this._messageHandler=new l.MessageHandler("main","worker",e),this._messageHandler.on("ready",function(){}),this._readyCapability.resolve()},_initialize:function t(){var r=this;if(!g&&!(0,h.getDefaultSetting)("disableWorker")&&"undefined"!=typeof Worker){var n=e();try{(0,l.isSameOrigin)(window.location.href,n)||(n=i(new URL(n,window.location).href));var o=new Worker(n),a=new l.MessageHandler("main","worker",o),s=function t(){o.removeEventListener("error",c),a.destroy(),o.terminate(),r.destroyed?r._readyCapability.reject(new Error("Worker was destroyed")):r._setupFakeWorker()},c=function t(){r._webWorker||s()};o.addEventListener("error",c),a.on("test",function(t){if(o.removeEventListener("error",c),r.destroyed)return void s();t&&t.supportTypedArray?(r._messageHandler=a,r._port=o,r._webWorker=o,t.supportTransfers||(m=!0),r._readyCapability.resolve(),a.send("configure",{verbosity:(0,l.getVerbosityLevel)()})):(r._setupFakeWorker(),a.destroy(),o.terminate())}),a.on("console_log",function(t){console.log.apply(console,t)}),a.on("console_error",function(t){console.error.apply(console,t)}),a.on("ready",function(t){if(o.removeEventListener("error",c),r.destroyed)return void s();try{u()}catch(t){r._setupFakeWorker()}});var u=function t(){var e=(0,h.getDefaultSetting)("postMessageTransfers")&&!m,r=new Uint8Array([e?255:0]);try{a.send("test",r,[r.buffer])}catch(t){(0,l.info)("Cannot use postMessage transfers"),r[0]=0,a.send("test",r)}};return void u()}catch(t){(0,l.info)("The worker has been disabled.")}}this._setupFakeWorker()},_setupFakeWorker:function t(){var e=this;g||(0,h.getDefaultSetting)("disableWorker")||((0,l.warn)("Setting up fake worker."),g=!0),r().then(function(t){if(e.destroyed)return void e._readyCapability.reject(new Error("Worker was destroyed"));var r=Uint8Array!==Float32Array,i=new T(r);e._port=i;var n="fake"+o++,a=new l.MessageHandler(n+"_worker",n,i);t.setup(a,i);var s=new l.MessageHandler(n,n+"_worker",i);e._messageHandler=s,e._readyCapability.resolve()})},destroy:function t(){this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}},n.fromPort=function(t){return s.has(t)?s.get(t):new n(null,t)},n}(),P=function t(){function e(t,e,r,i){this.messageHandler=t,this.loadingTask=e,this.pdfDataRangeTransport=r,this.commonObjs=new E,this.fontLoader=new u.FontLoader(e.docId),this.CMapReaderFactory=new i({baseUrl:(0,h.getDefaultSetting)("cMapUrl"),isCompressed:(0,h.getDefaultSetting)("cMapPacked")}),this.destroyed=!1,this.destroyCapability=null,this._passwordCapability=null,this.pageCache=[],this.pagePromises=[],this.downloadInfoCapability=(0,l.createPromiseCapability)(),this.setupMessageHandler()}return e.prototype={destroy:function t(){var e=this;if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=(0,l.createPromiseCapability)(),this._passwordCapability&&this._passwordCapability.reject(new Error("Worker was destroyed during onPassword callback"));var r=[];this.pageCache.forEach(function(t){t&&r.push(t._destroy())}),this.pageCache=[],this.pagePromises=[];var i=this.messageHandler.sendWithPromise("Terminate",null);return r.push(i),Promise.all(r).then(function(){e.fontLoader.clear(),e.pdfDataRangeTransport&&(e.pdfDataRangeTransport.abort(),e.pdfDataRangeTransport=null),e.messageHandler&&(e.messageHandler.destroy(),e.messageHandler=null),e.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise},setupMessageHandler:function t(){var e=this.messageHandler,r=this.loadingTask,i=this.pdfDataRangeTransport;i&&(i.addRangeListener(function(t,r){e.send("OnDataRange",{begin:t,chunk:r})}),i.addProgressListener(function(t){e.send("OnDataProgress",{loaded:t})}),i.addProgressiveReadListener(function(t){e.send("OnDataRange",{chunk:t})}),e.on("RequestDataRange",function t(e){i.requestDataRange(e.begin,e.end)},this)),e.on("GetDoc",function t(e){var r=e.pdfInfo;this.numPages=e.pdfInfo.numPages;var i=this.loadingTask,n=new C(r,this,i);this.pdfDocument=n,i._capability.resolve(n)},this),e.on("PasswordRequest",function t(e){var i=this;if(this._passwordCapability=(0,l.createPromiseCapability)(),r.onPassword){var n=function t(e){i._passwordCapability.resolve({password:e})};r.onPassword(n,e.code)}else this._passwordCapability.reject(new l.PasswordException(e.message,e.code));return this._passwordCapability.promise},this),e.on("PasswordException",function t(e){r._capability.reject(new l.PasswordException(e.message,e.code))},this),e.on("InvalidPDF",function t(e){this.loadingTask._capability.reject(new l.InvalidPDFException(e.message))},this),e.on("MissingPDF",function t(e){this.loadingTask._capability.reject(new l.MissingPDFException(e.message))},this),e.on("UnexpectedResponse",function t(e){this.loadingTask._capability.reject(new l.UnexpectedResponseException(e.message,e.status))},this),e.on("UnknownError",function t(e){this.loadingTask._capability.reject(new l.UnknownErrorException(e.message,e.details))},this),e.on("DataLoaded",function t(e){this.downloadInfoCapability.resolve(e)},this),e.on("PDFManagerReady",function t(e){this.pdfDataRangeTransport&&this.pdfDataRangeTransport.transportReady()},this),e.on("StartRenderPage",function t(e){if(!this.destroyed){var r=this.pageCache[e.pageIndex];r.stats.timeEnd("Page Request"),r._startRenderPage(e.transparency,e.intent)}},this),e.on("RenderPageChunk",function t(e){if(!this.destroyed){this.pageCache[e.pageIndex]._renderPageChunk(e.operatorList,e.intent)}},this),e.on("commonobj",function t(e){var r=this;if(!this.destroyed){var i=e[0],n=e[1];if(!this.commonObjs.hasData(i))switch(n){case"Font":var o=e[2];if("error"in o){var a=o.error;(0,l.warn)("Error during font loading: "+a),this.commonObjs.resolve(i,a);break}var s=null;(0,h.getDefaultSetting)("pdfBug")&&l.globalScope.FontInspector&&l.globalScope.FontInspector.enabled&&(s={registerFont:function t(e,r){l.globalScope.FontInspector.fontAdded(e,r)}});var c=new u.FontFaceObject(o,{isEvalSuported:(0,h.getDefaultSetting)("isEvalSupported"),disableFontFace:(0,h.getDefaultSetting)("disableFontFace"),fontRegistry:s}),f=function t(e){r.commonObjs.resolve(i,c)};this.fontLoader.bind([c],f);break;case"FontPath":this.commonObjs.resolve(i,e[2]);break;default:throw new Error("Got unknown common object type "+n)}}},this),e.on("obj",function t(e){if(!this.destroyed){var r=e[0],i=e[1],n=e[2],o=this.pageCache[i],a;if(!o.objs.hasData(r))switch(n){case"JpegStream":a=e[3],(0,l.loadJpegStream)(r,a,o.objs);break;case"Image":a=e[3],o.objs.resolve(r,a);var s=8e6;a&&"data"in a&&a.data.length>8e6&&(o.cleanupAfterRender=!0);break;default:throw new Error("Got unknown object type "+n)}}},this),e.on("DocProgress",function t(e){if(!this.destroyed){var r=this.loadingTask;r.onProgress&&r.onProgress({loaded:e.loaded,total:e.total})}},this),e.on("PageError",function t(e){if(!this.destroyed){var r=this.pageCache[e.pageNum-1],i=r.intentStates[e.intent];if(!i.displayReadyCapability)throw new Error(e.error);if(i.displayReadyCapability.reject(e.error),i.operatorList){i.operatorList.lastChunk=!0;for(var n=0;n<i.renderTasks.length;n++)i.renderTasks[n].operatorListChanged()}}},this),e.on("UnsupportedFeature",function t(e){if(!this.destroyed){var r=e.featureId,i=this.loadingTask;i.onUnsupportedFeature&&i.onUnsupportedFeature(r),L.notify(r)}},this),e.on("JpegDecode",function(t){if(this.destroyed)return Promise.reject(new Error("Worker was destroyed"));if("undefined"==typeof document)return Promise.reject(new Error('"document" is not defined.'));var e=t[0],r=t[1];return 3!==r&&1!==r?Promise.reject(new Error("Only 3 components or 1 component can be returned")):new Promise(function(t,i){var n=new Image;n.onload=function(){var e=n.width,i=n.height,o=e*i,a=4*o,s=new Uint8Array(o*r),c=document.createElement("canvas");c.width=e,c.height=i;var l=c.getContext("2d");l.drawImage(n,0,0);var h=l.getImageData(0,0,e,i).data,u,f;if(3===r)for(u=0,f=0;u<a;u+=4,f+=3)s[f]=h[u],s[f+1]=h[u+1],s[f+2]=h[u+2];else if(1===r)for(u=0,f=0;u<a;u+=4,f++)s[f]=h[u];t({data:s,width:e,height:i})},n.onerror=function(){i(new Error("JpegDecode failed to load image"))},n.src=e})},this),e.on("FetchBuiltInCMap",function(t){return this.destroyed?Promise.reject(new Error("Worker was destroyed")):this.CMapReaderFactory.fetch({name:t.name})},this)},getData:function t(){return this.messageHandler.sendWithPromise("GetData",null)},getPage:function t(e,r){var i=this;if(!(0,l.isInt)(e)||e<=0||e>this.numPages)return Promise.reject(new Error("Invalid page request"));var n=e-1;if(n in this.pagePromises)return this.pagePromises[n];var o=this.messageHandler.sendWithPromise("GetPage",{pageIndex:n}).then(function(t){if(i.destroyed)throw new Error("Transport destroyed");var e=new A(n,t,i);return i.pageCache[n]=e,e});return this.pagePromises[n]=o,o},getPageIndex:function t(e){return this.messageHandler.sendWithPromise("GetPageIndex",{ref:e}).catch(function(t){return Promise.reject(new Error(t))})},getAnnotations:function t(e,r){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:e,intent:r})},getDestinations:function t(){return this.messageHandler.sendWithPromise("GetDestinations",null)},getDestination:function t(e){return this.messageHandler.sendWithPromise("GetDestination",{id:e})},getPageLabels:function t(){return this.messageHandler.sendWithPromise("GetPageLabels",null)},getPageMode:function t(){return this.messageHandler.sendWithPromise("GetPageMode",null)},getAttachments:function t(){return this.messageHandler.sendWithPromise("GetAttachments",null)},getJavaScript:function t(){return this.messageHandler.sendWithPromise("GetJavaScript",null)},getOutline:function t(){return this.messageHandler.sendWithPromise("GetOutline",null)},getMetadata:function t(){return this.messageHandler.sendWithPromise("GetMetadata",null).then(function t(e){return{info:e[0],metadata:e[1]?new d.Metadata(e[1]):null}})},getStats:function t(){return this.messageHandler.sendWithPromise("GetStats",null)},startCleanup:function t(){var e=this;this.messageHandler.sendWithPromise("Cleanup",null).then(function(){for(var t=0,r=e.pageCache.length;t<r;t++){var i=e.pageCache[t];i&&i.cleanup()}e.commonObjs.clear(),e.fontLoader.clear()})}},e}(),E=function t(){function e(){this.objs=Object.create(null)}return e.prototype={ensureObj:function t(e){if(this.objs[e])return this.objs[e];var r={capability:(0,l.createPromiseCapability)(),data:null,resolved:!1};return this.objs[e]=r,r},get:function t(e,r){if(r)return this.ensureObj(e).capability.promise.then(r),null;var i=this.objs[e];if(!i||!i.resolved)throw new Error("Requesting object that isn't resolved yet "+e);return i.data},resolve:function t(e,r){var i=this.ensureObj(e);i.resolved=!0,i.data=r,i.capability.resolve(r)},isResolved:function t(e){var r=this.objs;return!!r[e]&&r[e].resolved},hasData:function t(e){return this.isResolved(e)},getData:function t(e){var r=this.objs;return r[e]&&r[e].resolved?r[e].data:null},clear:function t(){this.objs=Object.create(null)}},e}(),O=function t(){function e(t){this._internalRenderTask=t,this.onContinue=null}return e.prototype={get promise(){return this._internalRenderTask.capability.promise},cancel:function t(){this._internalRenderTask.cancel()},then:function t(e,r){return this.promise.then.apply(this.promise,arguments)}},e}(),R=function t(){function e(t,e,r,i,n,o,a){this.callback=t,this.params=e,this.objs=r,this.commonObjs=i,this.operatorListIdx=null,this.operatorList=n,this.pageNumber=o,this.canvasFactory=a,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this.useRequestAnimationFrame=!1,this.cancelled=!1,this.capability=(0,l.createPromiseCapability)(),this.task=new O(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=e.canvasContext.canvas}var r=new WeakMap;return e.prototype={initializeGraphics:function t(e){if(this._canvas){if(r.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");r.set(this._canvas,this)}if(!this.cancelled){(0,h.getDefaultSetting)("pdfBug")&&l.globalScope.StepperManager&&l.globalScope.StepperManager.enabled&&(this.stepper=l.globalScope.StepperManager.create(this.pageNumber-1),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());var i=this.params;this.gfx=new f.CanvasGraphics(i.canvasContext,this.commonObjs,this.objs,this.canvasFactory,i.imageLayer),this.gfx.beginDrawing({transform:i.transform,viewport:i.viewport,transparency:e,background:i.background}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback&&this.graphicsReadyCallback()}},cancel:function t(){this.running=!1,this.cancelled=!0,this._canvas&&r.delete(this._canvas),(0,h.getDefaultSetting)("pdfjsNext")?this.callback(new h.RenderingCancelledException("Rendering cancelled, page "+this.pageNumber,"canvas")):this.callback("cancelled")},operatorListChanged:function t(){if(!this.graphicsReady)return void(this.graphicsReadyCallback||(this.graphicsReadyCallback=this._continueBound));this.stepper&&this.stepper.updateOperatorList(this.operatorList),this.running||this._continue()},_continue:function t(){this.running=!0,this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())},_scheduleNext:function t(){this.useRequestAnimationFrame&&"undefined"!=typeof window?window.requestAnimationFrame(this._nextBound):Promise.resolve(void 0).then(this._nextBound)},_next:function t(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),this._canvas&&r.delete(this._canvas),this.callback())))}},e}(),L=function t(){var e=[];return{listen:function t(r){(0,l.deprecated)("Global UnsupportedManager.listen is used: use PDFDocumentLoadingTask.onUnsupportedFeature instead"),e.push(r)},notify:function t(r){for(var i=0,n=e.length;i<n;i++)e[i](r)}}}(),D,I;e.version=D="1.8.575",e.build=I="bd8c1211",e.getDocument=o,e.LoopbackPort=T,e.PDFDataRangeTransport=x,e.PDFWorker=k,e.PDFDocumentProxy=C,e.PDFPageProxy=A,e._UnsupportedManager=L,e.version=D,e.build=I},function(t,e,o){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.SVGGraphics=void 0;var a=o(0),s=function t(){throw new Error("Not implemented: SVGGraphics")},c={fontStyle:"normal",fontWeight:"normal",fillColor:"#000000"},l=function t(){function e(t,e,r){for(var i=-1,n=e;n<r;n++){var o=255&(i^t[n]);i=i>>>8^d[o]}return-1^i}function o(t,r,i,n){var o=n,a=r.length;i[o]=a>>24&255,i[o+1]=a>>16&255,i[o+2]=a>>8&255,i[o+3]=255&a,o+=4,i[o]=255&t.charCodeAt(0),i[o+1]=255&t.charCodeAt(1),i[o+2]=255&t.charCodeAt(2),i[o+3]=255&t.charCodeAt(3),o+=4,i.set(r,o),o+=r.length;var s=e(i,n+4,o);i[o]=s>>24&255,i[o+1]=s>>16&255,i[o+2]=s>>8&255,i[o+3]=255&s}function s(t,e,r){for(var i=1,n=0,o=e;o<r;++o)i=(i+(255&t[o]))%65521,n=(n+i)%65521;return n<<16|i}function c(t){if(!(0,a.isNodeJS)())return l(t);try{var e;e=parseInt(i.versions.node)>=8?t:new n(t);var o=r(42).deflateSync(e,{level:9});return o instanceof Uint8Array?o:new Uint8Array(o)}catch(t){(0,a.warn)("Not compressing PNG because zlib.deflateSync is unavailable: "+t)}return l(t)}function l(t){var e=t.length,r=65535,i=Math.ceil(e/65535),n=new Uint8Array(2+e+5*i+4),o=0;n[o++]=120,n[o++]=156;for(var a=0;e>65535;)n[o++]=0,n[o++]=255,n[o++]=255,n[o++]=0,n[o++]=0,n.set(t.subarray(a,a+65535),o),o+=65535,a+=65535,e-=65535;n[o++]=1,n[o++]=255&e,n[o++]=e>>8&255,n[o++]=255&~e,n[o++]=(65535&~e)>>8&255,n.set(t.subarray(a),o),o+=t.length-a;var c=s(t,0,t.length);return n[o++]=c>>24&255,n[o++]=c>>16&255,n[o++]=c>>8&255,n[o++]=255&c,n}function h(t,e,r){var i=t.width,n=t.height,s,l,h,d=t.data;switch(e){case a.ImageKind.GRAYSCALE_1BPP:l=0,s=1,h=i+7>>3;break;case a.ImageKind.RGB_24BPP:l=2,s=8,h=3*i;break;case a.ImageKind.RGBA_32BPP:l=6,s=8,h=4*i;break;default:throw new Error("invalid format")}var p=new Uint8Array((1+h)*n),g=0,v=0,m,b;for(m=0;m<n;++m)p[g++]=0,p.set(d.subarray(v,v+h),g),v+=h,g+=h;if(e===a.ImageKind.GRAYSCALE_1BPP)for(g=0,m=0;m<n;m++)for(g++,b=0;b<h;b++)p[g++]^=255;var y=new Uint8Array([i>>24&255,i>>16&255,i>>8&255,255&i,n>>24&255,n>>16&255,n>>8&255,255&n,s,l,0,0,0]),_=c(p),w=u.length+3*f+y.length+_.length,S=new Uint8Array(w),x=0;return S.set(u,x),x+=u.length,o("IHDR",y,S,x),x+=f+y.length,o("IDATA",_,S,x),x+=f+_.length,o("IEND",new Uint8Array(0),S,x),(0,a.createObjectURL)(S,"image/png",r)}for(var u=new Uint8Array([137,80,78,71,13,10,26,10]),f=12,d=new Int32Array(256),p=0;p<256;p++){for(var g=p,v=0;v<8;v++)g=1&g?3988292384^g>>1&2147483647:g>>1&2147483647;d[p]=g}return function t(e,r){return h(e,void 0===e.kind?a.ImageKind.GRAYSCALE_1BPP:e.kind,r)}}(),h=function t(){function e(){this.fontSizeScale=1,this.fontWeight=c.fontWeight,this.fontSize=0,this.textMatrix=a.IDENTITY_MATRIX,this.fontMatrix=a.FONT_IDENTITY_MATRIX,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRise=0,this.fillColor=c.fillColor,this.strokeColor="#000000",this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.lineJoin="",this.lineCap="",this.miterLimit=0,this.dashArray=[],this.dashPhase=0,this.dependencies=[],this.activeClipUrl=null,this.clipGroup=null,this.maskId=""}return e.prototype={clone:function t(){return Object.create(this)},setCurrentPoint:function t(e,r){this.x=e,this.y=r}},e}();e.SVGGraphics=s=function t(){function e(t){for(var e=[],r=[],i=t.length,n=0;n<i;n++)"save"!==t[n].fn?"restore"===t[n].fn?e=r.pop():e.push(t[n]):(e.push({fnId:92,fn:"group",items:[]}),r.push(e),e=e[e.length-1].items);return e}function r(t){if(t===(0|t))return t.toString();var e=t.toFixed(10),r=e.length-1;if("0"!==e[r])return e;do{r--}while("0"===e[r]);return e.substr(0,"."===e[r]?r:r+1)}function i(t){if(0===t[4]&&0===t[5]){if(0===t[1]&&0===t[2])return 1===t[0]&&1===t[3]?"":"scale("+r(t[0])+" "+r(t[3])+")";if(t[0]===t[3]&&t[1]===-t[2]){return"rotate("+r(180*Math.acos(t[0])/Math.PI)+")"}}else if(1===t[0]&&0===t[1]&&0===t[2]&&1===t[3])return"translate("+r(t[4])+" "+r(t[5])+")";return"matrix("+r(t[0])+" "+r(t[1])+" "+r(t[2])+" "+r(t[3])+" "+r(t[4])+" "+r(t[5])+")"}function n(t,e,r){this.current=new h,this.transformMatrix=a.IDENTITY_MATRIX,this.transformStack=[],this.extraStack=[],this.commonObjs=t,this.objs=e,this.pendingClip=null,this.pendingEOFill=!1,this.embedFonts=!1,this.embeddedFonts=Object.create(null),this.cssStyle=null,this.forceDataSchema=!!r}var o="http://www.w3.org/2000/svg",s="http://www.w3.org/1999/xlink",u=["butt","round","square"],f=["miter","round","bevel"],d=0,p=0;return n.prototype={save:function t(){this.transformStack.push(this.transformMatrix);var e=this.current;this.extraStack.push(e),this.current=e.clone()},restore:function t(){this.transformMatrix=this.transformStack.pop(),this.current=this.extraStack.pop(),this.pendingClip=null,this.tgrp=null},group:function t(e){this.save(),this.executeOpTree(e),this.restore()},loadDependencies:function t(e){for(var r=this,i=e.fnArray,n=i.length,o=e.argsArray,s=0;s<n;s++)if(a.OPS.dependency===i[s])for(var c=o[s],l=0,h=c.length;l<h;l++){var u=c[l],f="g_"===u.substring(0,2),d;d=f?new Promise(function(t){r.commonObjs.get(u,t)}):new Promise(function(t){r.objs.get(u,t)}),this.current.dependencies.push(d)}return Promise.all(this.current.dependencies)},transform:function t(e,r,i,n,o,s){var c=[e,r,i,n,o,s];this.transformMatrix=a.Util.transform(this.transformMatrix,c),this.tgrp=null},getSVG:function t(e,r){var i=this;this.viewport=r;var n=this._initialize(r);return this.loadDependencies(e).then(function(){i.transformMatrix=a.IDENTITY_MATRIX;var t=i.convertOpList(e);return i.executeOpTree(t),n})},convertOpList:function t(r){var i=r.argsArray,n=r.fnArray,o=n.length,s=[],c=[];for(var l in a.OPS)s[a.OPS[l]]=l;for(var h=0;h<o;h++){var u=n[h];c.push({fnId:u,fn:s[u],args:i[h]})}return e(c)},executeOpTree:function t(e){for(var r=e.length,i=0;i<r;i++){var n=e[i].fn,o=e[i].fnId,s=e[i].args;switch(0|o){case a.OPS.beginText:this.beginText();break;case a.OPS.setLeading:this.setLeading(s);break;case a.OPS.setLeadingMoveText:this.setLeadingMoveText(s[0],s[1]);break;case a.OPS.setFont:this.setFont(s);break;case a.OPS.showText:case a.OPS.showSpacedText:this.showText(s[0]);break;case a.OPS.endText:this.endText();break;case a.OPS.moveText:this.moveText(s[0],s[1]);break;case a.OPS.setCharSpacing:this.setCharSpacing(s[0]);break;case a.OPS.setWordSpacing:this.setWordSpacing(s[0]);break;case a.OPS.setHScale:this.setHScale(s[0]);break;case a.OPS.setTextMatrix:this.setTextMatrix(s[0],s[1],s[2],s[3],s[4],s[5]);break;case a.OPS.setLineWidth:this.setLineWidth(s[0]);break;case a.OPS.setLineJoin:this.setLineJoin(s[0]);break;case a.OPS.setLineCap:this.setLineCap(s[0]);break;case a.OPS.setMiterLimit:this.setMiterLimit(s[0]);break;case a.OPS.setFillRGBColor:this.setFillRGBColor(s[0],s[1],s[2]);break;case a.OPS.setStrokeRGBColor:this.setStrokeRGBColor(s[0],s[1],s[2]);break;case a.OPS.setDash:this.setDash(s[0],s[1]);break;case a.OPS.setGState:this.setGState(s[0]);break;case a.OPS.fill:this.fill();break;case a.OPS.eoFill:this.eoFill();break;case a.OPS.stroke:this.stroke();break;case a.OPS.fillStroke:this.fillStroke();break;case a.OPS.eoFillStroke:this.eoFillStroke();break;case a.OPS.clip:this.clip("nonzero");break;case a.OPS.eoClip:this.clip("evenodd");break;case a.OPS.paintSolidColorImageMask:this.paintSolidColorImageMask();break;case a.OPS.paintJpegXObject:this.paintJpegXObject(s[0],s[1],s[2]);break;case a.OPS.paintImageXObject:this.paintImageXObject(s[0]);break;case a.OPS.paintInlineImageXObject:this.paintInlineImageXObject(s[0]);break;case a.OPS.paintImageMaskXObject:this.paintImageMaskXObject(s[0]);break;case a.OPS.paintFormXObjectBegin:this.paintFormXObjectBegin(s[0],s[1]);break;case a.OPS.paintFormXObjectEnd:this.paintFormXObjectEnd();break;case a.OPS.closePath:this.closePath();break;case a.OPS.closeStroke:this.closeStroke();break;case a.OPS.closeFillStroke:this.closeFillStroke();break;case a.OPS.nextLine:this.nextLine();break;case a.OPS.transform:this.transform(s[0],s[1],s[2],s[3],s[4],s[5]);break;case a.OPS.constructPath:this.constructPath(s[0],s[1]);break;case a.OPS.endPath:this.endPath();break;case 92:this.group(e[i].items);break;default:(0,a.warn)("Unimplemented operator "+n)}}},setWordSpacing:function t(e){this.current.wordSpacing=e},setCharSpacing:function t(e){this.current.charSpacing=e},nextLine:function t(){this.moveText(0,this.current.leading)},setTextMatrix:function t(e,i,n,a,s,c){var l=this.current;this.current.textMatrix=this.current.lineMatrix=[e,i,n,a,s,c],this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0,l.xcoords=[],l.tspan=document.createElementNS(o,"svg:tspan"),l.tspan.setAttributeNS(null,"font-family",l.fontFamily),l.tspan.setAttributeNS(null,"font-size",r(l.fontSize)+"px"),l.tspan.setAttributeNS(null,"y",r(-l.y)),l.txtElement=document.createElementNS(o,"svg:text"),l.txtElement.appendChild(l.tspan)},beginText:function t(){this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0,this.current.textMatrix=a.IDENTITY_MATRIX,this.current.lineMatrix=a.IDENTITY_MATRIX,this.current.tspan=document.createElementNS(o,"svg:tspan"),this.current.txtElement=document.createElementNS(o,"svg:text"),this.current.txtgrp=document.createElementNS(o,"svg:g"),this.current.xcoords=[]},moveText:function t(e,i){var n=this.current;this.current.x=this.current.lineX+=e,this.current.y=this.current.lineY+=i,n.xcoords=[],n.tspan=document.createElementNS(o,"svg:tspan"),n.tspan.setAttributeNS(null,"font-family",n.fontFamily),n.tspan.setAttributeNS(null,"font-size",r(n.fontSize)+"px"),n.tspan.setAttributeNS(null,"y",r(-n.y))},showText:function t(e){var n=this.current,o=n.font,s=n.fontSize;if(0!==s){var l=n.charSpacing,h=n.wordSpacing,u=n.fontDirection,f=n.textHScale*u,d=e.length,p=o.vertical,g=s*n.fontMatrix[0],v=0,m;for(m=0;m<d;++m){var b=e[m];if(null!==b)if((0,a.isNum)(b))v+=-b*s*.001;else{n.xcoords.push(n.x+v*f);var y=b.width,_=b.fontChar,w=(b.isSpace?h:0)+l,S=y*g+w*u;v+=S,n.tspan.textContent+=_}else v+=u*h}p?n.y-=v*f:n.x+=v*f,n.tspan.setAttributeNS(null,"x",n.xcoords.map(r).join(" ")),n.tspan.setAttributeNS(null,"y",r(-n.y)),n.tspan.setAttributeNS(null,"font-family",n.fontFamily),n.tspan.setAttributeNS(null,"font-size",r(n.fontSize)+"px"),n.fontStyle!==c.fontStyle&&n.tspan.setAttributeNS(null,"font-style",n.fontStyle),n.fontWeight!==c.fontWeight&&n.tspan.setAttributeNS(null,"font-weight",n.fontWeight),n.fillColor!==c.fillColor&&n.tspan.setAttributeNS(null,"fill",n.fillColor),n.txtElement.setAttributeNS(null,"transform",i(n.textMatrix)+" scale(1, -1)"),n.txtElement.setAttributeNS("http://www.w3.org/XML/1998/namespace","xml:space","preserve"),n.txtElement.appendChild(n.tspan),n.txtgrp.appendChild(n.txtElement),this._ensureTransformGroup().appendChild(n.txtElement)}},setLeadingMoveText:function t(e,r){this.setLeading(-r),this.moveText(e,r)},addFontStyle:function t(e){this.cssStyle||(this.cssStyle=document.createElementNS(o,"svg:style"),this.cssStyle.setAttributeNS(null,"type","text/css"),this.defs.appendChild(this.cssStyle));var r=(0,a.createObjectURL)(e.data,e.mimetype,this.forceDataSchema);this.cssStyle.textContent+='@font-face { font-family: "'+e.loadedName+'"; src: url('+r+"); }\n"},setFont:function t(e){var i=this.current,n=this.commonObjs.get(e[0]),s=e[1];this.current.font=n,this.embedFonts&&n.data&&!this.embeddedFonts[n.loadedName]&&(this.addFontStyle(n),this.embeddedFonts[n.loadedName]=n),i.fontMatrix=n.fontMatrix?n.fontMatrix:a.FONT_IDENTITY_MATRIX;var c=n.black?n.bold?"bolder":"bold":n.bold?"bold":"normal",l=n.italic?"italic":"normal";s<0?(s=-s,i.fontDirection=-1):i.fontDirection=1,i.fontSize=s,i.fontFamily=n.loadedName,i.fontWeight=c,i.fontStyle=l,i.tspan=document.createElementNS(o,"svg:tspan"),i.tspan.setAttributeNS(null,"y",r(-i.y)),i.xcoords=[]},endText:function t(){},setLineWidth:function t(e){this.current.lineWidth=e},setLineCap:function t(e){this.current.lineCap=u[e]},setLineJoin:function t(e){this.current.lineJoin=f[e]},setMiterLimit:function t(e){this.current.miterLimit=e},setStrokeAlpha:function t(e){this.current.strokeAlpha=e},setStrokeRGBColor:function t(e,r,i){var n=a.Util.makeCssRgb(e,r,i);this.current.strokeColor=n},setFillAlpha:function t(e){this.current.fillAlpha=e},setFillRGBColor:function t(e,r,i){var n=a.Util.makeCssRgb(e,r,i);this.current.fillColor=n,this.current.tspan=document.createElementNS(o,"svg:tspan"),this.current.xcoords=[]},setDash:function t(e,r){this.current.dashArray=e,this.current.dashPhase=r},constructPath:function t(e,i){var n=this.current,s=n.x,c=n.y;n.path=document.createElementNS(o,"svg:path");for(var l=[],h=e.length,u=0,f=0;u<h;u++)switch(0|e[u]){case a.OPS.rectangle:s=i[f++],c=i[f++];var d=i[f++],p=i[f++],g=s+d,v=c+p;l.push("M",r(s),r(c),"L",r(g),r(c),"L",r(g),r(v),"L",r(s),r(v),"Z");break;case a.OPS.moveTo:s=i[f++],c=i[f++],l.push("M",r(s),r(c));break;case a.OPS.lineTo:s=i[f++],c=i[f++],l.push("L",r(s),r(c));break;case a.OPS.curveTo:s=i[f+4],c=i[f+5],l.push("C",r(i[f]),r(i[f+1]),r(i[f+2]),r(i[f+3]),r(s),r(c)),f+=6;break;case a.OPS.curveTo2:s=i[f+2],c=i[f+3],l.push("C",r(s),r(c),r(i[f]),r(i[f+1]),r(i[f+2]),r(i[f+3])),f+=4;break;case a.OPS.curveTo3:s=i[f+2],c=i[f+3],l.push("C",r(i[f]),r(i[f+1]),r(s),r(c),r(s),r(c)),f+=4;break;case a.OPS.closePath:l.push("Z")}n.path.setAttributeNS(null,"d",l.join(" ")),n.path.setAttributeNS(null,"fill","none"),this._ensureTransformGroup().appendChild(n.path),n.element=n.path,n.setCurrentPoint(s,c)},endPath:function t(){if(this.pendingClip){var e=this.current,r="clippath"+d;d++;var n=document.createElementNS(o,"svg:clipPath");n.setAttributeNS(null,"id",r),n.setAttributeNS(null,"transform",i(this.transformMatrix));var a=e.element.cloneNode();"evenodd"===this.pendingClip?a.setAttributeNS(null,"clip-rule","evenodd"):a.setAttributeNS(null,"clip-rule","nonzero"),this.pendingClip=null,n.appendChild(a),this.defs.appendChild(n),e.activeClipUrl&&(e.clipGroup=null,this.extraStack.forEach(function(t){t.clipGroup=null})),e.activeClipUrl="url(#"+r+")",this.tgrp=null}},clip:function t(e){this.pendingClip=e},closePath:function t(){var e=this.current,r=e.path.getAttributeNS(null,"d");r+="Z",e.path.setAttributeNS(null,"d",r)},setLeading:function t(e){this.current.leading=-e},setTextRise:function t(e){this.current.textRise=e},setHScale:function t(e){this.current.textHScale=e/100},setGState:function t(e){for(var r=0,i=e.length;r<i;r++){var n=e[r],o=n[0],s=n[1];switch(o){case"LW":this.setLineWidth(s);break;case"LC":this.setLineCap(s);break;case"LJ":this.setLineJoin(s);break;case"ML":this.setMiterLimit(s);break;case"D":this.setDash(s[0],s[1]);break;case"Font":this.setFont(s);break;case"CA":this.setStrokeAlpha(s);break;case"ca":this.setFillAlpha(s);break;default:(0,a.warn)("Unimplemented graphic state "+o)}}},fill:function t(){var e=this.current;e.element.setAttributeNS(null,"fill",e.fillColor),e.element.setAttributeNS(null,"fill-opacity",e.fillAlpha)},stroke:function t(){var e=this.current;e.element.setAttributeNS(null,"stroke",e.strokeColor),e.element.setAttributeNS(null,"stroke-opacity",e.strokeAlpha),e.element.setAttributeNS(null,"stroke-miterlimit",r(e.miterLimit)),e.element.setAttributeNS(null,"stroke-linecap",e.lineCap),e.element.setAttributeNS(null,"stroke-linejoin",e.lineJoin),e.element.setAttributeNS(null,"stroke-width",r(e.lineWidth)+"px"),e.element.setAttributeNS(null,"stroke-dasharray",e.dashArray.map(r).join(" ")),e.element.setAttributeNS(null,"stroke-dashoffset",r(e.dashPhase)+"px"),e.element.setAttributeNS(null,"fill","none")},eoFill:function t(){this.current.element.setAttributeNS(null,"fill-rule","evenodd"),this.fill()},fillStroke:function t(){this.stroke(),this.fill()},eoFillStroke:function t(){this.current.element.setAttributeNS(null,"fill-rule","evenodd"),this.fillStroke()},closeStroke:function t(){this.closePath(),this.stroke()},closeFillStroke:function t(){this.closePath(),this.fillStroke()},paintSolidColorImageMask:function t(){var e=this.current,r=document.createElementNS(o,"svg:rect");r.setAttributeNS(null,"x","0"),r.setAttributeNS(null,"y","0"),r.setAttributeNS(null,"width","1px"),r.setAttributeNS(null,"height","1px"),r.setAttributeNS(null,"fill",e.fillColor),this._ensureTransformGroup().appendChild(r)},paintJpegXObject:function t(e,i,n){var a=this.objs.get(e),c=document.createElementNS(o,"svg:image");c.setAttributeNS(s,"xlink:href",a.src),c.setAttributeNS(null,"width",r(i)),c.setAttributeNS(null,"height",r(n)),c.setAttributeNS(null,"x","0"),c.setAttributeNS(null,"y",r(-n)),c.setAttributeNS(null,"transform","scale("+r(1/i)+" "+r(-1/n)+")"),this._ensureTransformGroup().appendChild(c)},paintImageXObject:function t(e){var r=this.objs.get(e);if(!r)return void(0,a.warn)("Dependent image isn't ready yet");this.paintInlineImageXObject(r)},paintInlineImageXObject:function t(e,i){var n=e.width,a=e.height,c=l(e,this.forceDataSchema),h=document.createElementNS(o,"svg:rect");h.setAttributeNS(null,"x","0"),h.setAttributeNS(null,"y","0"),h.setAttributeNS(null,"width",r(n)),h.setAttributeNS(null,"height",r(a)),this.current.element=h,this.clip("nonzero");var u=document.createElementNS(o,"svg:image");u.setAttributeNS(s,"xlink:href",c),u.setAttributeNS(null,"x","0"),u.setAttributeNS(null,"y",r(-a)),u.setAttributeNS(null,"width",r(n)+"px"),u.setAttributeNS(null,"height",r(a)+"px"),u.setAttributeNS(null,"transform","scale("+r(1/n)+" "+r(-1/a)+")"),i?i.appendChild(u):this._ensureTransformGroup().appendChild(u)},paintImageMaskXObject:function t(e){var i=this.current,n=e.width,a=e.height,s=i.fillColor;i.maskId="mask"+p++;var c=document.createElementNS(o,"svg:mask");c.setAttributeNS(null,"id",i.maskId);var l=document.createElementNS(o,"svg:rect");l.setAttributeNS(null,"x","0"),l.setAttributeNS(null,"y","0"),l.setAttributeNS(null,"width",r(n)),l.setAttributeNS(null,"height",r(a)),l.setAttributeNS(null,"fill",s),l.setAttributeNS(null,"mask","url(#"+i.maskId+")"),this.defs.appendChild(c),this._ensureTransformGroup().appendChild(l),this.paintInlineImageXObject(e,c)},paintFormXObjectBegin:function t(e,i){if((0,a.isArray)(e)&&6===e.length&&this.transform(e[0],e[1],e[2],e[3],e[4],e[5]),(0,a.isArray)(i)&&4===i.length){var n=i[2]-i[0],s=i[3]-i[1],c=document.createElementNS(o,"svg:rect");c.setAttributeNS(null,"x",i[0]),c.setAttributeNS(null,"y",i[1]),c.setAttributeNS(null,"width",r(n)),c.setAttributeNS(null,"height",r(s)),this.current.element=c,this.clip("nonzero"),this.endPath()}},paintFormXObjectEnd:function t(){},_initialize:function t(e){var r=document.createElementNS(o,"svg:svg");r.setAttributeNS(null,"version","1.1"),r.setAttributeNS(null,"width",e.width+"px"),r.setAttributeNS(null,"height",e.height+"px"),r.setAttributeNS(null,"preserveAspectRatio","none"),r.setAttributeNS(null,"viewBox","0 0 "+e.width+" "+e.height);var n=document.createElementNS(o,"svg:defs");r.appendChild(n),this.defs=n;var a=document.createElementNS(o,"svg:g");return a.setAttributeNS(null,"transform",i(e.transform)),r.appendChild(a),this.svg=a,r},_ensureClipGroup:function t(){if(!this.current.clipGroup){var e=document.createElementNS(o,"svg:g");e.setAttributeNS(null,"clip-path",this.current.activeClipUrl),this.svg.appendChild(e),this.current.clipGroup=e}return this.current.clipGroup},_ensureTransformGroup:function t(){return this.tgrp||(this.tgrp=document.createElementNS(o,"svg:g"),this.tgrp.setAttributeNS(null,"transform",i(this.transformMatrix)),this.current.activeClipUrl?this._ensureClipGroup().appendChild(this.tgrp):this.svg.appendChild(this.tgrp)),this.tgrp}},n}(),e.SVGGraphics=s},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.renderTextLayer=void 0;var i=r(0),n=r(1),o=function t(){function e(t){return!f.test(t)}function r(t,r,o){var a=document.createElement("div"),s={style:null,angle:0,canvasWidth:0,isWhitespace:!1,originalTransform:null,paddingBottom:0,paddingLeft:0,paddingRight:0,paddingTop:0,scale:1};if(t._textDivs.push(a),e(r.str))return s.isWhitespace=!0,void t._textDivProperties.set(a,s);var c=i.Util.transform(t._viewport.transform,r.transform),l=Math.atan2(c[1],c[0]),h=o[r.fontName];h.vertical&&(l+=Math.PI/2);var u=Math.sqrt(c[2]*c[2]+c[3]*c[3]),f=u;h.ascent?f=h.ascent*f:h.descent&&(f=(1+h.descent)*f);var p,g;if(0===l?(p=c[4],g=c[5]-f):(p=c[4]+f*Math.sin(l),g=c[5]-f*Math.cos(l)),d[1]=p,d[3]=g,d[5]=u,d[7]=h.fontFamily,s.style=d.join(""),a.setAttribute("style",s.style),a.textContent=r.str,(0,n.getDefaultSetting)("pdfBug")&&(a.dataset.fontName=r.fontName),0!==l&&(s.angle=l*(180/Math.PI)),r.str.length>1&&(h.vertical?s.canvasWidth=r.height*t._viewport.scale:s.canvasWidth=r.width*t._viewport.scale),t._textDivProperties.set(a,s),t._textContentStream&&t._layoutText(a),t._enhanceTextSelection){var v=1,m=0;0!==l&&(v=Math.cos(l),m=Math.sin(l));var b=(h.vertical?r.height:r.width)*t._viewport.scale,y=u,_,w;0!==l?(_=[v,m,-m,v,p,g],w=i.Util.getAxialAlignedBoundingBox([0,0,b,y],_)):w=[p,g,p+b,g+y],t._bounds.push({left:w[0],top:w[1],right:w[2],bottom:w[3],div:a,size:[b,y],m:_})}}function o(t){if(!t._canceled){var e=t._textDivs,r=t._capability,i=e.length;if(i>u)return t._renderingDone=!0,void r.resolve();if(!t._textContentStream)for(var n=0;n<i;n++)t._layoutText(e[n]);t._renderingDone=!0,r.resolve()}}function a(t){for(var e=t._bounds,r=t._viewport,n=s(r.width,r.height,e),o=0;o<n.length;o++){var a=e[o].div,c=t._textDivProperties.get(a);if(0!==c.angle){var l=n[o],h=e[o],u=h.m,f=u[0],d=u[1],p=[[0,0],[0,h.size[1]],[h.size[0],0],h.size],g=new Float64Array(64);p.forEach(function(t,e){var r=i.Util.applyTransform(t,u);g[e+0]=f&&(l.left-r[0])/f,g[e+4]=d&&(l.top-r[1])/d,g[e+8]=f&&(l.right-r[0])/f,g[e+12]=d&&(l.bottom-r[1])/d,g[e+16]=d&&(l.left-r[0])/-d,g[e+20]=f&&(l.top-r[1])/f,g[e+24]=d&&(l.right-r[0])/-d,g[e+28]=f&&(l.bottom-r[1])/f,g[e+32]=f&&(l.left-r[0])/-f,g[e+36]=d&&(l.top-r[1])/-d,g[e+40]=f&&(l.right-r[0])/-f,g[e+44]=d&&(l.bottom-r[1])/-d,g[e+48]=d&&(l.left-r[0])/d,g[e+52]=f&&(l.top-r[1])/-f,g[e+56]=d&&(l.right-r[0])/d,g[e+60]=f&&(l.bottom-r[1])/-f});var v=function t(e,r,i){for(var n=0,o=0;o<i;o++){var a=e[r++];a>0&&(n=n?Math.min(a,n):a)}return n},m=1+Math.min(Math.abs(f),Math.abs(d));c.paddingLeft=v(g,32,16)/m,c.paddingTop=v(g,48,16)/m,c.paddingRight=v(g,0,16)/m,c.paddingBottom=v(g,16,16)/m,t._textDivProperties.set(a,c)}else c.paddingLeft=e[o].left-n[o].left,c.paddingTop=e[o].top-n[o].top,c.paddingRight=n[o].right-e[o].right,c.paddingBottom=n[o].bottom-e[o].bottom,t._textDivProperties.set(a,c)}}function s(t,e,r){var i=r.map(function(t,e){return{x1:t.left,y1:t.top,x2:t.right,y2:t.bottom,index:e,x1New:void 0,x2New:void 0}});c(t,i);var n=new Array(r.length);return i.forEach(function(t){var e=t.index;n[e]={left:t.x1New,top:0,right:t.x2New,bottom:0}}),r.map(function(e,r){var o=n[r],a=i[r];a.x1=e.top,a.y1=t-o.right,a.x2=e.bottom,a.y2=t-o.left,a.index=r,a.x1New=void 0,a.x2New=void 0}),c(e,i),i.forEach(function(t){var e=t.index;n[e].top=t.x1New,n[e].bottom=t.x2New}),n}function c(t,e){e.sort(function(t,e){return t.x1-e.x1||t.index-e.index});var r={x1:-1/0,y1:-1/0,x2:0,y2:1/0,index:-1,x1New:0,x2New:0},i=[{start:-1/0,end:1/0,boundary:r}];e.forEach(function(t){for(var e=0;e<i.length&&i[e].end<=t.y1;)e++;for(var r=i.length-1;r>=0&&i[r].start>=t.y2;)r--;var n,o,a,s,c=-1/0;for(a=e;a<=r;a++){n=i[a],o=n.boundary;var l;l=o.x2>t.x1?o.index>t.index?o.x1New:t.x1:void 0===o.x2New?(o.x2+t.x1)/2:o.x2New,l>c&&(c=l)}for(t.x1New=c,a=e;a<=r;a++)n=i[a],o=n.boundary,void 0===o.x2New?o.x2>t.x1?o.index>t.index&&(o.x2New=o.x2):o.x2New=c:o.x2New>c&&(o.x2New=Math.max(c,o.x2));var h=[],u=null;for(a=e;a<=r;a++){n=i[a],o=n.boundary;var f=o.x2>t.x2?o:t;u===f?h[h.length-1].end=n.end:(h.push({start:n.start,end:n.end,boundary:f}),u=f)}for(i[e].start<t.y1&&(h[0].start=t.y1,h.unshift({start:i[e].start,end:t.y1,boundary:i[e].boundary})),t.y2<i[r].end&&(h[h.length-1].end=t.y2,h.push({start:t.y2,end:i[r].end,boundary:i[r].boundary})),a=e;a<=r;a++)if(n=i[a],o=n.boundary,void 0===o.x2New){var d=!1;for(s=e-1;!d&&s>=0&&i[s].start>=o.y1;s--)d=i[s].boundary===o;for(s=r+1;!d&&s<i.length&&i[s].end<=o.y2;s++)d=i[s].boundary===o;for(s=0;!d&&s<h.length;s++)d=h[s].boundary===o;d||(o.x2New=c)}Array.prototype.splice.apply(i,[e,r-e+1].concat(h))}),i.forEach(function(e){var r=e.boundary;void 0===r.x2New&&(r.x2New=Math.max(t,r.x2))})}function l(t){var e=t.textContent,r=t.textContentStream,n=t.container,o=t.viewport,a=t.textDivs,s=t.textContentItemsStr,c=t.enhanceTextSelection;this._textContent=e,this._textContentStream=r,this._container=n,this._viewport=o,this._textDivs=a||[],this._textContentItemsStr=s||[],this._enhanceTextSelection=!!c,this._reader=null,this._layoutTextLastFontSize=null,this._layoutTextLastFontFamily=null,this._layoutTextCtx=null,this._textDivProperties=new WeakMap,this._renderingDone=!1,this._canceled=!1,this._capability=(0,i.createPromiseCapability)(),this._renderTimer=null,this._bounds=[]}function h(t){var e=new l({textContent:t.textContent,textContentStream:t.textContentStream,container:t.container,viewport:t.viewport,textDivs:t.textDivs,textContentItemsStr:t.textContentItemsStr,enhanceTextSelection:t.enhanceTextSelection});return e._render(t.timeout),e}var u=1e5,f=/\S/,d=["left: ",0,"px; top: ",0,"px; font-size: ",0,"px; font-family: ","",";"];return l.prototype={get promise(){return this._capability.promise},cancel:function t(){this._reader&&(this._reader.cancel(),this._reader=null),this._canceled=!0,null!==this._renderTimer&&(clearTimeout(this._renderTimer),this._renderTimer=null),this._capability.reject("canceled")},_processItems:function t(e,i){for(var n=0,o=e.length;n<o;n++)this._textContentItemsStr.push(e[n].str),r(this,e[n],i)},_layoutText:function t(e){var r=this._container,i=this._textDivProperties.get(e);if(!i.isWhitespace){var o=e.style.fontSize,a=e.style.fontFamily;o===this._layoutTextLastFontSize&&a===this._layoutTextLastFontFamily||(this._layoutTextCtx.font=o+" "+a,this._lastFontSize=o,this._lastFontFamily=a);var s=this._layoutTextCtx.measureText(e.textContent).width,c="";0!==i.canvasWidth&&s>0&&(i.scale=i.canvasWidth/s,c="scaleX("+i.scale+")"),0!==i.angle&&(c="rotate("+i.angle+"deg) "+c),""!==c&&(i.originalTransform=c,n.CustomStyle.setProp("transform",e,c)),this._textDivProperties.set(e,i),r.appendChild(e)}},_render:function t(e){var r=this,n=(0,i.createPromiseCapability)(),a=Object.create(null),s=document.createElement("canvas");if(s.mozOpaque=!0,this._layoutTextCtx=s.getContext("2d",{alpha:!1}),this._textContent){var c=this._textContent.items,l=this._textContent.styles;this._processItems(c,l),n.resolve()}else{if(!this._textContentStream)throw new Error('Neither "textContent" nor "textContentStream" parameters specified.');var h=function t(){r._reader.read().then(function(e){var o=e.value;if(e.done)return void n.resolve();i.Util.extendObj(a,o.styles),r._processItems(o.items,a),t()},n.reject)};this._reader=this._textContentStream.getReader(),h()}n.promise.then(function(){a=null,e?r._renderTimer=setTimeout(function(){o(r),r._renderTimer=null},e):o(r)},this._capability.reject)},expandTextDivs:function t(e){if(this._enhanceTextSelection&&this._renderingDone){null!==this._bounds&&(a(this),this._bounds=null);for(var r=0,i=this._textDivs.length;r<i;r++){var o=this._textDivs[r],s=this._textDivProperties.get(o);if(!s.isWhitespace)if(e){var c="",l="";1!==s.scale&&(c="scaleX("+s.scale+")"),0!==s.angle&&(c="rotate("+s.angle+"deg) "+c),0!==s.paddingLeft&&(l+=" padding-left: "+s.paddingLeft/s.scale+"px;",c+=" translateX("+-s.paddingLeft/s.scale+"px)"),0!==s.paddingTop&&(l+=" padding-top: "+s.paddingTop+"px;",c+=" translateY("+-s.paddingTop+"px)"),0!==s.paddingRight&&(l+=" padding-right: "+s.paddingRight/s.scale+"px;"),0!==s.paddingBottom&&(l+=" padding-bottom: "+s.paddingBottom+"px;"),""!==l&&o.setAttribute("style",s.style+l),""!==c&&n.CustomStyle.setProp("transform",o,c)}else o.style.padding=0,n.CustomStyle.setProp("transform",o,s.originalTransform||"")}}}},h}();e.renderTextLayer=o},function(t,e,r){"use strict";function i(t){return t.replace(/>\\376\\377([^<]+)/g,function(t,e){for(var r=e.replace(/\\([0-3])([0-7])([0-7])/g,function(t,e,r,i){return String.fromCharCode(64*e+8*r+1*i)}),i="",n=0;n<r.length;n+=2){var o=256*r.charCodeAt(n)+r.charCodeAt(n+1);i+=o>=32&&o<127&&60!==o&&62!==o&&38!==o?String.fromCharCode(o):"&#x"+(65536+o).toString(16).substring(1)+";"}return">"+i})}function n(t){if("string"==typeof t){t=i(t);t=(new DOMParser).parseFromString(t,"application/xml")}else if(!(t instanceof Document))throw new Error("Metadata: Invalid metadata object");this.metaDocument=t,this.metadata=Object.create(null),this.parse()}Object.defineProperty(e,"__esModule",{value:!0}),n.prototype={parse:function t(){var e=this.metaDocument,r=e.documentElement;if("rdf:rdf"!==r.nodeName.toLowerCase())for(r=r.firstChild;r&&"rdf:rdf"!==r.nodeName.toLowerCase();)r=r.nextSibling;var i=r?r.nodeName.toLowerCase():null;if(r&&"rdf:rdf"===i&&r.hasChildNodes()){var n=r.childNodes,o,a,s,c,l,h,u;for(c=0,h=n.length;c<h;c++)if(o=n[c],"rdf:description"===o.nodeName.toLowerCase())for(l=0,u=o.childNodes.length;l<u;l++)"#text"!==o.childNodes[l].nodeName.toLowerCase()&&(a=o.childNodes[l],s=a.nodeName.toLowerCase(),this.metadata[s]=a.textContent.trim())}},get:function t(e){return this.metadata[e]||null},has:function t(e){return void 0!==this.metadata[e]}},e.Metadata=n},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.WebGLUtils=void 0;var i=r(1),n=r(0),o=function t(){function e(t,e,r){var i=t.createShader(r);if(t.shaderSource(i,e),t.compileShader(i),!t.getShaderParameter(i,t.COMPILE_STATUS)){var n=t.getShaderInfoLog(i);throw new Error("Error during shader compilation: "+n)}return i}function r(t,r){return e(t,r,t.VERTEX_SHADER)}function o(t,r){return e(t,r,t.FRAGMENT_SHADER)}function a(t,e){for(var r=t.createProgram(),i=0,n=e.length;i<n;++i)t.attachShader(r,e[i]);if(t.linkProgram(r),!t.getProgramParameter(r,t.LINK_STATUS)){var o=t.getProgramInfoLog(r);throw new Error("Error during program linking: "+o)}return r}function s(t,e,r){t.activeTexture(r);var i=t.createTexture();return t.bindTexture(t.TEXTURE_2D,i),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),i}function c(){p||(g=document.createElement("canvas"),p=g.getContext("webgl",{premultipliedalpha:!1}))}function l(){var t,e;c(),t=g,g=null,e=p,p=null;var i=r(e,v),n=o(e,m),s=a(e,[i,n]);e.useProgram(s);var l={};l.gl=e,l.canvas=t,l.resolutionLocation=e.getUniformLocation(s,"u_resolution"),l.positionLocation=e.getAttribLocation(s,"a_position"),l.backdropLocation=e.getUniformLocation(s,"u_backdrop"),l.subtypeLocation=e.getUniformLocation(s,"u_subtype");var h=e.getAttribLocation(s,"a_texCoord"),u=e.getUniformLocation(s,"u_image"),f=e.getUniformLocation(s,"u_mask"),d=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,d),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),e.STATIC_DRAW),e.enableVertexAttribArray(h),e.vertexAttribPointer(h,2,e.FLOAT,!1,0,0),e.uniform1i(u,0),e.uniform1i(f,1),b=l}function h(t,e,r){var i=t.width,n=t.height;b||l();var o=b,a=o.canvas,c=o.gl;a.width=i,a.height=n,c.viewport(0,0,c.drawingBufferWidth,c.drawingBufferHeight),c.uniform2f(o.resolutionLocation,i,n),r.backdrop?c.uniform4f(o.resolutionLocation,r.backdrop[0],r.backdrop[1],r.backdrop[2],1):c.uniform4f(o.resolutionLocation,0,0,0,0),c.uniform1i(o.subtypeLocation,"Luminosity"===r.subtype?1:0);var h=s(c,t,c.TEXTURE0),u=s(c,e,c.TEXTURE1),f=c.createBuffer();return c.bindBuffer(c.ARRAY_BUFFER,f),c.bufferData(c.ARRAY_BUFFER,new Float32Array([0,0,i,0,0,n,0,n,i,0,i,n]),c.STATIC_DRAW),c.enableVertexAttribArray(o.positionLocation),c.vertexAttribPointer(o.positionLocation,2,c.FLOAT,!1,0,0),c.clearColor(0,0,0,0),c.enable(c.BLEND),c.blendFunc(c.ONE,c.ONE_MINUS_SRC_ALPHA),c.clear(c.COLOR_BUFFER_BIT),c.drawArrays(c.TRIANGLES,0,6),c.flush(),c.deleteTexture(h),c.deleteTexture(u),c.deleteBuffer(f),a}function u(){var t,e;c(),t=g,g=null,e=p,p=null;var i=r(e,y),n=o(e,_),s=a(e,[i,n]);e.useProgram(s);var l={};l.gl=e,l.canvas=t,l.resolutionLocation=e.getUniformLocation(s,"u_resolution"),l.scaleLocation=e.getUniformLocation(s,"u_scale"),l.offsetLocation=e.getUniformLocation(s,"u_offset"),l.positionLocation=e.getAttribLocation(s,"a_position"),l.colorLocation=e.getAttribLocation(s,"a_color"),w=l}function f(t,e,r,i,n){w||u();var o=w,a=o.canvas,s=o.gl;a.width=t,a.height=e,s.viewport(0,0,s.drawingBufferWidth,s.drawingBufferHeight),s.uniform2f(o.resolutionLocation,t,e);var c=0,l,h,f;for(l=0,h=i.length;l<h;l++)switch(i[l].type){case"lattice":f=i[l].coords.length/i[l].verticesPerRow|0,c+=(f-1)*(i[l].verticesPerRow-1)*6;break;case"triangles":c+=i[l].coords.length}var d=new Float32Array(2*c),p=new Uint8Array(3*c),g=n.coords,v=n.colors,m=0,b=0;for(l=0,h=i.length;l<h;l++){var y=i[l],_=y.coords,S=y.colors;switch(y.type){case"lattice":var x=y.verticesPerRow;f=_.length/x|0;for(var C=1;C<f;C++)for(var A=C*x+1,T=1;T<x;T++,A++)d[m]=g[_[A-x-1]],d[m+1]=g[_[A-x-1]+1],d[m+2]=g[_[A-x]],d[m+3]=g[_[A-x]+1],d[m+4]=g[_[A-1]],d[m+5]=g[_[A-1]+1],p[b]=v[S[A-x-1]],p[b+1]=v[S[A-x-1]+1],p[b+2]=v[S[A-x-1]+2],p[b+3]=v[S[A-x]],p[b+4]=v[S[A-x]+1],p[b+5]=v[S[A-x]+2],p[b+6]=v[S[A-1]],p[b+7]=v[S[A-1]+1],p[b+8]=v[S[A-1]+2],d[m+6]=d[m+2],d[m+7]=d[m+3],d[m+8]=d[m+4],d[m+9]=d[m+5],d[m+10]=g[_[A]],d[m+11]=g[_[A]+1],p[b+9]=p[b+3],p[b+10]=p[b+4],p[b+11]=p[b+5],p[b+12]=p[b+6],p[b+13]=p[b+7],p[b+14]=p[b+8],p[b+15]=v[S[A]],p[b+16]=v[S[A]+1],p[b+17]=v[S[A]+2],m+=12,b+=18;break;case"triangles":for(var k=0,P=_.length;k<P;k++)d[m]=g[_[k]],d[m+1]=g[_[k]+1],p[b]=v[S[k]],p[b+1]=v[S[k]+1],p[b+2]=v[S[k]+2],m+=2,b+=3}}r?s.clearColor(r[0]/255,r[1]/255,r[2]/255,1):s.clearColor(0,0,0,0),s.clear(s.COLOR_BUFFER_BIT);var E=s.createBuffer();s.bindBuffer(s.ARRAY_BUFFER,E),s.bufferData(s.ARRAY_BUFFER,d,s.STATIC_DRAW),s.enableVertexAttribArray(o.positionLocation),s.vertexAttribPointer(o.positionLocation,2,s.FLOAT,!1,0,0);var O=s.createBuffer();return s.bindBuffer(s.ARRAY_BUFFER,O),s.bufferData(s.ARRAY_BUFFER,p,s.STATIC_DRAW),s.enableVertexAttribArray(o.colorLocation),s.vertexAttribPointer(o.colorLocation,3,s.UNSIGNED_BYTE,!1,0,0),s.uniform2f(o.scaleLocation,n.scaleX,n.scaleY),s.uniform2f(o.offsetLocation,n.offsetX,n.offsetY),s.drawArrays(s.TRIANGLES,0,c),s.flush(),s.deleteBuffer(E),s.deleteBuffer(O),a}function d(){b&&b.canvas&&(b.canvas.width=0,b.canvas.height=0),w&&w.canvas&&(w.canvas.width=0,w.canvas.height=0),b=null,w=null}var p,g,v=" attribute vec2 a_position; attribute vec2 a_texCoord; uniform vec2 u_resolution; varying vec2 v_texCoord; void main() { vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); v_texCoord = a_texCoord; } ",m=" precision mediump float; uniform vec4 u_backdrop; uniform int u_subtype; uniform sampler2D u_image; uniform sampler2D u_mask; varying vec2 v_texCoord; void main() { vec4 imageColor = texture2D(u_image, v_texCoord); vec4 maskColor = texture2D(u_mask, v_texCoord); if (u_backdrop.a > 0.0) { maskColor.rgb = maskColor.rgb * maskColor.a + u_backdrop.rgb * (1.0 - maskColor.a); } float lum; if (u_subtype == 0) { lum = maskColor.a; } else { lum = maskColor.r * 0.3 + maskColor.g * 0.59 + maskColor.b * 0.11; } imageColor.a *= lum; imageColor.rgb *= imageColor.a; gl_FragColor = imageColor; } ",b=null,y=" attribute vec2 a_position; attribute vec3 a_color; uniform vec2 u_resolution; uniform vec2 u_scale; uniform vec2 u_offset; varying vec4 v_color; void main() { vec2 position = (a_position + u_offset) * u_scale; vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); v_color = vec4(a_color / 255.0, 1.0); } ",_=" precision mediump float; varying vec4 v_color; void main() { gl_FragColor = v_color; } ",w=null;return{get isEnabled(){if((0,i.getDefaultSetting)("disableWebGL"))return!1;var t=!1;try{c(),t=!!p}catch(t){}return(0,n.shadow)(this,"isEnabled",t)},composeSMask:h,drawFigures:f,clear:d}}();e.WebGLUtils=o},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.PDFJS=e.isWorker=e.globalScope=void 0;var i=r(3),n=r(1),o=r(0),a=r(2),s=r(6),c=r(5),l=r(4),h="undefined"==typeof window;o.globalScope.PDFJS||(o.globalScope.PDFJS={});var u=o.globalScope.PDFJS;u.version="1.8.575",u.build="bd8c1211",u.pdfBug=!1,void 0!==u.verbosity&&(0,o.setVerbosityLevel)(u.verbosity),delete u.verbosity,Object.defineProperty(u,"verbosity",{get:function t(){return(0,o.getVerbosityLevel)()},set:function t(e){(0,o.setVerbosityLevel)(e)},enumerable:!0,configurable:!0}),u.VERBOSITY_LEVELS=o.VERBOSITY_LEVELS,u.OPS=o.OPS,u.UNSUPPORTED_FEATURES=o.UNSUPPORTED_FEATURES,u.isValidUrl=n.isValidUrl,u.shadow=o.shadow,u.createBlob=o.createBlob,u.createObjectURL=function t(e,r){return(0,o.createObjectURL)(e,r,u.disableCreateObjectURL)},Object.defineProperty(u,"isLittleEndian",{configurable:!0,get:function t(){return(0,o.shadow)(u,"isLittleEndian",(0,o.isLittleEndian)())}}),u.removeNullCharacters=o.removeNullCharacters,u.PasswordResponses=o.PasswordResponses,u.PasswordException=o.PasswordException,u.UnknownErrorException=o.UnknownErrorException,u.InvalidPDFException=o.InvalidPDFException,u.MissingPDFException=o.MissingPDFException,u.UnexpectedResponseException=o.UnexpectedResponseException,u.Util=o.Util,u.PageViewport=o.PageViewport,u.createPromiseCapability=o.createPromiseCapability,u.maxImageSize=void 0===u.maxImageSize?-1:u.maxImageSize,u.cMapUrl=void 0===u.cMapUrl?null:u.cMapUrl,u.cMapPacked=void 0!==u.cMapPacked&&u.cMapPacked,u.disableFontFace=void 0!==u.disableFontFace&&u.disableFontFace,u.imageResourcesPath=void 0===u.imageResourcesPath?"":u.imageResourcesPath,u.disableWorker=void 0!==u.disableWorker&&u.disableWorker,u.workerSrc=void 0===u.workerSrc?null:u.workerSrc,u.workerPort=void 0===u.workerPort?null:u.workerPort,u.disableRange=void 0!==u.disableRange&&u.disableRange,u.disableStream=void 0!==u.disableStream&&u.disableStream,u.disableAutoFetch=void 0!==u.disableAutoFetch&&u.disableAutoFetch,u.pdfBug=void 0!==u.pdfBug&&u.pdfBug,u.postMessageTransfers=void 0===u.postMessageTransfers||u.postMessageTransfers,u.disableCreateObjectURL=void 0!==u.disableCreateObjectURL&&u.disableCreateObjectURL,u.disableWebGL=void 0===u.disableWebGL||u.disableWebGL,u.externalLinkTarget=void 0===u.externalLinkTarget?n.LinkTarget.NONE:u.externalLinkTarget,u.externalLinkRel=void 0===u.externalLinkRel?n.DEFAULT_LINK_REL:u.externalLinkRel,u.isEvalSupported=void 0===u.isEvalSupported||u.isEvalSupported,u.pdfjsNext=void 0!==u.pdfjsNext&&u.pdfjsNext;var f=u.openExternalLinksInNewWindow;delete u.openExternalLinksInNewWindow,Object.defineProperty(u,"openExternalLinksInNewWindow",{get:function t(){return u.externalLinkTarget===n.LinkTarget.BLANK},set:function t(e){if(e&&(0,o.deprecated)('PDFJS.openExternalLinksInNewWindow, please use "PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK" instead.'),u.externalLinkTarget!==n.LinkTarget.NONE)return void(0,o.warn)("PDFJS.externalLinkTarget is already initialized");u.externalLinkTarget=e?n.LinkTarget.BLANK:n.LinkTarget.NONE},enumerable:!0,configurable:!0}),f&&(u.openExternalLinksInNewWindow=f),u.getDocument=i.getDocument,u.LoopbackPort=i.LoopbackPort,u.PDFDataRangeTransport=i.PDFDataRangeTransport,u.PDFWorker=i.PDFWorker,u.hasCanvasTypedArrays=!0,u.CustomStyle=n.CustomStyle,u.LinkTarget=n.LinkTarget,u.addLinkAttributes=n.addLinkAttributes,u.getFilenameFromUrl=n.getFilenameFromUrl,u.isExternalLinkTargetSet=n.isExternalLinkTargetSet,u.AnnotationLayer=a.AnnotationLayer,u.renderTextLayer=c.renderTextLayer,u.Metadata=s.Metadata,u.SVGGraphics=l.SVGGraphics,u.UnsupportedManager=i._UnsupportedManager,e.globalScope=o.globalScope,e.isWorker=h,e.PDFJS=u},function(t,e,r){"use strict";var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};!function(t,e){for(var r in e)t[r]=e[r]}(e,function(t){function e(i){if(r[i])return r[i].exports;var n=r[i]={i:i,l:!1,exports:{}};return t[i].call(n.exports,n,n.exports,e),n.l=!0,n.exports}var r={};return e.m=t,e.c=r,e.i=function(t){return t},e.d=function(t,r,i){e.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var r=t&&t.__esModule?function e(){return t.default}:function e(){return t};return e.d(r,"a",r),r},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=7)}([function(t,e,r){function n(t){return"string"==typeof t||"symbol"===(void 0===t?"undefined":a(t))}function o(t,e,r){if("function"!=typeof t)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(t,e,r)}var a="function"==typeof Symbol&&"symbol"===i(Symbol.iterator)?function(t){return void 0===t?"undefined":i(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":void 0===t?"undefined":i(t)},s=r(1),c=s.assert;e.typeIsObject=function(t){return"object"===(void 0===t?"undefined":a(t))&&null!==t||"function"==typeof t},e.createDataProperty=function(t,r,i){c(e.typeIsObject(t)),Object.defineProperty(t,r,{value:i,writable:!0,enumerable:!0,configurable:!0})},e.createArrayFromList=function(t){return t.slice()},e.ArrayBufferCopy=function(t,e,r,i,n){new Uint8Array(t).set(new Uint8Array(r,i,n),e)},e.CreateIterResultObject=function(t,e){c("boolean"==typeof e);var r={};return Object.defineProperty(r,"value",{value:t,enumerable:!0,writable:!0,configurable:!0}),Object.defineProperty(r,"done",{value:e,enumerable:!0,writable:!0,configurable:!0}),r},e.IsFiniteNonNegativeNumber=function(t){return!Number.isNaN(t)&&(t!==1/0&&!(t<0))},e.InvokeOrNoop=function(t,e,r){c(void 0!==t),c(n(e)),c(Array.isArray(r));var i=t[e];if(void 0!==i)return o(i,t,r)},e.PromiseInvokeOrNoop=function(t,r,i){c(void 0!==t),c(n(r)),c(Array.isArray(i));try{return Promise.resolve(e.InvokeOrNoop(t,r,i))}catch(t){return Promise.reject(t)}},e.PromiseInvokeOrPerformFallback=function(t,e,r,i,a){c(void 0!==t),c(n(e)),c(Array.isArray(r)),c(Array.isArray(a));var s=void 0;try{s=t[e]}catch(t){return Promise.reject(t)}if(void 0===s)return i.apply(null,a);try{return Promise.resolve(o(s,t,r))}catch(t){return Promise.reject(t)}},e.TransferArrayBuffer=function(t){return t.slice()},e.ValidateAndNormalizeHighWaterMark=function(t){if(t=Number(t),Number.isNaN(t)||t<0)throw new RangeError("highWaterMark property of a queuing strategy must be non-negative and non-NaN");return t},e.ValidateAndNormalizeQueuingStrategy=function(t,r){if(void 0!==t&&"function"!=typeof t)throw new TypeError("size property of a queuing strategy must be a function");return r=e.ValidateAndNormalizeHighWaterMark(r),{size:t,highWaterMark:r}}},function(t,e,r){function i(t){t&&t.constructor===n&&setTimeout(function(){throw t},0)}function n(t){this.name="AssertionError",this.message=t||"",this.stack=(new Error).stack}function o(t,e){if(!t)throw new n(e)}n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,t.exports={rethrowAssertionErrorRejection:i,AssertionError:n,assert:o}},function(t,e,r){function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t){return new yt(t)}function o(t){return!!lt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_writableStreamController")}function a(t){return ut(!0===o(t),"IsWritableStreamLocked should only be used on known writable streams"),void 0!==t._writer}function s(t,e){var r=t._state;if("closed"===r)return Promise.resolve(void 0);if("errored"===r)return Promise.reject(t._storedError);var i=new TypeError("Requested to abort");if(void 0!==t._pendingAbortRequest)return Promise.reject(i);ut("writable"===r||"erroring"===r,"state must be writable or erroring");var n=!1;"erroring"===r&&(n=!0,e=void 0);var o=new Promise(function(r,i){t._pendingAbortRequest={_resolve:r,_reject:i,_reason:e,_wasAlreadyErroring:n}});return!1===n&&h(t,i),o}function c(t){return ut(!0===a(t)),ut("writable"===t._state),new Promise(function(e,r){var i={_resolve:e,_reject:r};t._writeRequests.push(i)})}function l(t,e){var r=t._state;if("writable"===r)return void h(t,e);ut("erroring"===r),u(t)}function h(t,e){ut(void 0===t._storedError,"stream._storedError === undefined"),ut("writable"===t._state,"state must be writable");var r=t._writableStreamController;ut(void 0!==r,"controller must not be undefined"),t._state="erroring",t._storedError=e;var i=t._writer;void 0!==i&&k(i,e),!1===m(t)&&!0===r._started&&u(t)}function u(t){ut("erroring"===t._state,"stream._state === erroring"),ut(!1===m(t),"WritableStreamHasOperationMarkedInFlight(stream) === false"),t._state="errored",t._writableStreamController.__errorSteps();for(var e=t._storedError,r=0;r<t._writeRequests.length;r++){t._writeRequests[r]._reject(e)}if(t._writeRequests=[],void 0===t._pendingAbortRequest)return void _(t);var i=t._pendingAbortRequest;if(t._pendingAbortRequest=void 0,!0===i._wasAlreadyErroring)return i._reject(e),void _(t);t._writableStreamController.__abortSteps(i._reason).then(function(){i._resolve(),_(t)},function(e){i._reject(e),_(t)})}function f(t){ut(void 0!==t._inFlightWriteRequest),t._inFlightWriteRequest._resolve(void 0),t._inFlightWriteRequest=void 0}function d(t,e){ut(void 0!==t._inFlightWriteRequest),t._inFlightWriteRequest._reject(e),t._inFlightWriteRequest=void 0,ut("writable"===t._state||"erroring"===t._state),l(t,e)}function p(t){ut(void 0!==t._inFlightCloseRequest),t._inFlightCloseRequest._resolve(void 0),t._inFlightCloseRequest=void 0;var e=t._state;ut("writable"===e||"erroring"===e),"erroring"===e&&(t._storedError=void 0,void 0!==t._pendingAbortRequest&&(t._pendingAbortRequest._resolve(),t._pendingAbortRequest=void 0)),t._state="closed";var r=t._writer;void 0!==r&&J(r),ut(void 0===t._pendingAbortRequest,"stream._pendingAbortRequest === undefined"),ut(void 0===t._storedError,"stream._storedError === undefined")}function g(t,e){ut(void 0!==t._inFlightCloseRequest),t._inFlightCloseRequest._reject(e),t._inFlightCloseRequest=void 0,ut("writable"===t._state||"erroring"===t._state),void 0!==t._pendingAbortRequest&&(t._pendingAbortRequest._reject(e),t._pendingAbortRequest=void 0),l(t,e)}function v(t){return void 0!==t._closeRequest||void 0!==t._inFlightCloseRequest}function m(t){return void 0!==t._inFlightWriteRequest||void 0!==t._inFlightCloseRequest}function b(t){ut(void 0===t._inFlightCloseRequest),ut(void 0!==t._closeRequest),t._inFlightCloseRequest=t._closeRequest,t._closeRequest=void 0}function y(t){ut(void 0===t._inFlightWriteRequest,"there must be no pending write request"),ut(0!==t._writeRequests.length,"writeRequests must not be empty"),t._inFlightWriteRequest=t._writeRequests.shift()}function _(t){ut("errored"===t._state,'_stream_.[[state]] is `"errored"`'),void 0!==t._closeRequest&&(ut(void 0===t._inFlightCloseRequest),t._closeRequest._reject(t._storedError),t._closeRequest=void 0);var e=t._writer;void 0!==e&&(V(e,t._storedError),e._closedPromise.catch(function(){}))}function w(t,e){ut("writable"===t._state),ut(!1===v(t));var r=t._writer;void 0!==r&&e!==t._backpressure&&(!0===e?et(r):(ut(!1===e),it(r))),t._backpressure=e}function S(t){return!!lt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_ownerWritableStream")}function x(t,e){var r=t._ownerWritableStream;return ut(void 0!==r),s(r,e)}function C(t){var e=t._ownerWritableStream;ut(void 0!==e);var r=e._state;if("closed"===r||"errored"===r)return Promise.reject(new TypeError("The stream (in "+r+" state) is not in the writable state and cannot be closed"));ut("writable"===r||"erroring"===r),ut(!1===v(e));var i=new Promise(function(t,r){var i={_resolve:t,_reject:r};e._closeRequest=i});return!0===e._backpressure&&"writable"===r&&it(t),R(e._writableStreamController),i}function A(t){var e=t._ownerWritableStream;ut(void 0!==e);var r=e._state;return!0===v(e)||"closed"===r?Promise.resolve():"errored"===r?Promise.reject(e._storedError):(ut("writable"===r||"erroring"===r),C(t))}function T(t,e){"pending"===t._closedPromiseState?V(t,e):Z(t,e),t._closedPromise.catch(function(){})}function k(t,e){"pending"===t._readyPromiseState?tt(t,e):rt(t,e),t._readyPromise.catch(function(){})}function P(t){var e=t._ownerWritableStream,r=e._state;return"errored"===r||"erroring"===r?null:"closed"===r?0:D(e._writableStreamController)}function E(t){var e=t._ownerWritableStream;ut(void 0!==e),ut(e._writer===t);var r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");k(t,r),T(t,r),e._writer=void 0,t._ownerWritableStream=void 0}function O(t,e){var r=t._ownerWritableStream;ut(void 0!==r);var i=r._writableStreamController,n=L(i,e);if(r!==t._ownerWritableStream)return Promise.reject(X("write to"));var o=r._state;if("errored"===o)return Promise.reject(r._storedError);if(!0===v(r)||"closed"===o)return Promise.reject(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===o)return Promise.reject(r._storedError);ut("writable"===o);var a=c(r);return I(i,e,n),a}function R(t){gt(t,"close",0),M(t)}function L(t,e){var r=t._strategySize;if(void 0===r)return 1;try{return r(e)}catch(e){return F(t,e),1}}function D(t){return t._strategyHWM-t._queueTotalSize}function I(t,e,r){var i={chunk:e};try{gt(t,i,r)}catch(e){return void F(t,e)}var n=t._controlledWritableStream;if(!1===v(n)&&"writable"===n._state){w(n,U(t))}M(t)}function j(t){return!!lt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_underlyingSink")}function M(t){var e=t._controlledWritableStream;if(!1!==t._started&&void 0===e._inFlightWriteRequest){var r=e._state;if("closed"!==r&&"errored"!==r){if("erroring"===r)return void u(e);if(0!==t._queue.length){var i=vt(t);"close"===i?N(t):B(t,i.chunk)}}}}function F(t,e){"writable"===t._controlledWritableStream._state&&z(t,e)}function N(t){var e=t._controlledWritableStream;b(e),pt(t),ut(0===t._queue.length,"queue must be empty once the final write record is dequeued"),st(t._underlyingSink,"close",[]).then(function(){p(e)},function(t){g(e,t)}).catch(ft)}function B(t,e){var r=t._controlledWritableStream;y(r),st(t._underlyingSink,"write",[e,t]).then(function(){f(r);var e=r._state;if(ut("writable"===e||"erroring"===e),pt(t),!1===v(r)&&"writable"===e){var i=U(t);w(r,i)}M(t)},function(t){d(r,t)}).catch(ft)}function U(t){return D(t)<=0}function z(t,e){var r=t._controlledWritableStream;ut("writable"===r._state),h(r,e)}function W(t){return new TypeError("WritableStream.prototype."+t+" can only be used on a WritableStream")}function q(t){return new TypeError("WritableStreamDefaultWriter.prototype."+t+" can only be used on a WritableStreamDefaultWriter")}function X(t){return new TypeError("Cannot "+t+" a stream using a released writer")}function G(t){t._closedPromise=new Promise(function(e,r){t._closedPromise_resolve=e,t._closedPromise_reject=r,t._closedPromiseState="pending"})}function H(t,e){t._closedPromise=Promise.reject(e),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0,t._closedPromiseState="rejected"}function Y(t){t._closedPromise=Promise.resolve(void 0),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0,t._closedPromiseState="resolved"}function V(t,e){ut(void 0!==t._closedPromise_resolve,"writer._closedPromise_resolve !== undefined"),ut(void 0!==t._closedPromise_reject,"writer._closedPromise_reject !== undefined"),ut("pending"===t._closedPromiseState,"writer._closedPromiseState is pending"),t._closedPromise_reject(e),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0,t._closedPromiseState="rejected"}function Z(t,e){ut(void 0===t._closedPromise_resolve,"writer._closedPromise_resolve === undefined"),ut(void 0===t._closedPromise_reject,"writer._closedPromise_reject === undefined"),ut("pending"!==t._closedPromiseState,"writer._closedPromiseState is not pending"),t._closedPromise=Promise.reject(e),t._closedPromiseState="rejected"}function J(t){ut(void 0!==t._closedPromise_resolve,"writer._closedPromise_resolve !== undefined"),ut(void 0!==t._closedPromise_reject,"writer._closedPromise_reject !== undefined"),ut("pending"===t._closedPromiseState,"writer._closedPromiseState is pending"),t._closedPromise_resolve(void 0),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0,t._closedPromiseState="resolved"}function K(t){t._readyPromise=new Promise(function(e,r){t._readyPromise_resolve=e,t._readyPromise_reject=r}),t._readyPromiseState="pending"}function Q(t,e){t._readyPromise=Promise.reject(e),t._readyPromise_resolve=void 0,t._readyPromise_reject=void 0,t._readyPromiseState="rejected"}function $(t){t._readyPromise=Promise.resolve(void 0),t._readyPromise_resolve=void 0,t._readyPromise_reject=void 0,t._readyPromiseState="fulfilled"}function tt(t,e){ut(void 0!==t._readyPromise_resolve,"writer._readyPromise_resolve !== undefined"),ut(void 0!==t._readyPromise_reject,"writer._readyPromise_reject !== undefined"),t._readyPromise_reject(e),t._readyPromise_resolve=void 0,t._readyPromise_reject=void 0,t._readyPromiseState="rejected"}function et(t){ut(void 0===t._readyPromise_resolve,"writer._readyPromise_resolve === undefined"),ut(void 0===t._readyPromise_reject,"writer._readyPromise_reject === undefined"),t._readyPromise=new Promise(function(e,r){t._readyPromise_resolve=e,t._readyPromise_reject=r}),t._readyPromiseState="pending"}function rt(t,e){ut(void 0===t._readyPromise_resolve,"writer._readyPromise_resolve === undefined"),ut(void 0===t._readyPromise_reject,"writer._readyPromise_reject === undefined"),t._readyPromise=Promise.reject(e),t._readyPromiseState="rejected"}function it(t){ut(void 0!==t._readyPromise_resolve,"writer._readyPromise_resolve !== undefined"),ut(void 0!==t._readyPromise_reject,"writer._readyPromise_reject !== undefined"),t._readyPromise_resolve(void 0),t._readyPromise_resolve=void 0,t._readyPromise_reject=void 0,t._readyPromiseState="fulfilled"}var nt=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),ot=r(0),at=ot.InvokeOrNoop,st=ot.PromiseInvokeOrNoop,ct=ot.ValidateAndNormalizeQueuingStrategy,lt=ot.typeIsObject,ht=r(1),ut=ht.assert,ft=ht.rethrowAssertionErrorRejection,dt=r(3),pt=dt.DequeueValue,gt=dt.EnqueueValueWithSize,vt=dt.PeekQueueValue,mt=dt.ResetQueue,bt=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=r.size,o=r.highWaterMark,a=void 0===o?1:o;if(i(this,t),this._state="writable",this._storedError=void 0,this._writer=void 0,this._writableStreamController=void 0,this._writeRequests=[],this._inFlightWriteRequest=void 0,this._closeRequest=void 0,this._inFlightCloseRequest=void 0,this._pendingAbortRequest=void 0,this._backpressure=!1,void 0!==e.type)throw new RangeError("Invalid type is specified");this._writableStreamController=new _t(this,e,n,a),this._writableStreamController.__startSteps()}return nt(t,[{key:"abort",value:function t(e){return!1===o(this)?Promise.reject(W("abort")):!0===a(this)?Promise.reject(new TypeError("Cannot abort a stream that already has a writer")):s(this,e)}},{key:"getWriter",value:function t(){if(!1===o(this))throw W("getWriter");return n(this)}},{key:"locked",get:function t(){if(!1===o(this))throw W("locked");return a(this)}}]),t}();t.exports={AcquireWritableStreamDefaultWriter:n,IsWritableStream:o,IsWritableStreamLocked:a,WritableStream:bt,WritableStreamAbort:s,WritableStreamDefaultControllerError:z,WritableStreamDefaultWriterCloseWithErrorPropagation:A,WritableStreamDefaultWriterRelease:E,WritableStreamDefaultWriterWrite:O,WritableStreamCloseQueuedOrInFlight:v};var yt=function(){function t(e){if(i(this,t),!1===o(e))throw new TypeError("WritableStreamDefaultWriter can only be constructed with a WritableStream instance");if(!0===a(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;var r=e._state;if("writable"===r)!1===v(e)&&!0===e._backpressure?K(this):$(this),G(this);else if("erroring"===r)Q(this,e._storedError),this._readyPromise.catch(function(){}),G(this);else if("closed"===r)$(this),Y(this);else{ut("errored"===r,"state must be errored");var n=e._storedError;Q(this,n),this._readyPromise.catch(function(){}),H(this,n),this._closedPromise.catch(function(){})}}return nt(t,[{key:"abort",value:function t(e){return!1===S(this)?Promise.reject(q("abort")):void 0===this._ownerWritableStream?Promise.reject(X("abort")):x(this,e)}},{key:"close",value:function t(){if(!1===S(this))return Promise.reject(q("close"));var e=this._ownerWritableStream;return void 0===e?Promise.reject(X("close")):!0===v(e)?Promise.reject(new TypeError("cannot close an already-closing stream")):C(this)}},{key:"releaseLock",value:function t(){if(!1===S(this))throw q("releaseLock");var e=this._ownerWritableStream;void 0!==e&&(ut(void 0!==e._writer),E(this))}},{key:"write",value:function t(e){return!1===S(this)?Promise.reject(q("write")):void 0===this._ownerWritableStream?Promise.reject(X("write to")):O(this,e)}},{key:"closed",get:function t(){return!1===S(this)?Promise.reject(q("closed")):this._closedPromise}},{key:"desiredSize",get:function t(){if(!1===S(this))throw q("desiredSize");if(void 0===this._ownerWritableStream)throw X("desiredSize");return P(this)}},{key:"ready",get:function t(){return!1===S(this)?Promise.reject(q("ready")):this._readyPromise}}]),t}(),_t=function(){function t(e,r,n,a){if(i(this,t),!1===o(e))throw new TypeError("WritableStreamDefaultController can only be constructed with a WritableStream instance");if(void 0!==e._writableStreamController)throw new TypeError("WritableStreamDefaultController instances can only be created by the WritableStream constructor");this._controlledWritableStream=e,this._underlyingSink=r,this._queue=void 0,this._queueTotalSize=void 0,mt(this),this._started=!1;var s=ct(n,a);this._strategySize=s.size,this._strategyHWM=s.highWaterMark,w(e,U(this))}return nt(t,[{key:"error",value:function t(e){if(!1===j(this))throw new TypeError("WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController");"writable"===this._controlledWritableStream._state&&z(this,e)}},{key:"__abortSteps",value:function t(e){return st(this._underlyingSink,"abort",[e])}},{key:"__errorSteps",value:function t(){mt(this)}},{key:"__startSteps",value:function t(){var e=this,r=at(this._underlyingSink,"start",[this]),i=this._controlledWritableStream;Promise.resolve(r).then(function(){ut("writable"===i._state||"erroring"===i._state),e._started=!0,M(e)},function(t){ut("writable"===i._state||"erroring"===i._state),e._started=!0,l(i,t)}).catch(ft)}}]),t}()},function(t,e,r){var i=r(0),n=i.IsFiniteNonNegativeNumber,o=r(1),a=o.assert;e.DequeueValue=function(t){a("_queue"in t&&"_queueTotalSize"in t,"Spec-level failure: DequeueValue should only be used on containers with [[queue]] and [[queueTotalSize]]."),a(t._queue.length>0,"Spec-level failure: should never dequeue from an empty queue.");var e=t._queue.shift();return t._queueTotalSize-=e.size,t._queueTotalSize<0&&(t._queueTotalSize=0),e.value},e.EnqueueValueWithSize=function(t,e,r){if(a("_queue"in t&&"_queueTotalSize"in t,"Spec-level failure: EnqueueValueWithSize should only be used on containers with [[queue]] and [[queueTotalSize]]."),r=Number(r),!n(r))throw new RangeError("Size must be a finite, non-NaN, non-negative number.");t._queue.push({value:e,size:r}),t._queueTotalSize+=r},e.PeekQueueValue=function(t){return a("_queue"in t&&"_queueTotalSize"in t,"Spec-level failure: PeekQueueValue should only be used on containers with [[queue]] and [[queueTotalSize]]."),a(t._queue.length>0,"Spec-level failure: should never peek at an empty queue."),t._queue[0].value},e.ResetQueue=function(t){a("_queue"in t&&"_queueTotalSize"in t,"Spec-level failure: ResetQueue should only be used on containers with [[queue]] and [[queueTotalSize]]."),t._queue=[],t._queueTotalSize=0}},function(t,e,r){function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t){return new ee(t)}function o(t){return new te(t)}function a(t){return!!Mt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_readableStreamController")}function s(t){return Nt(!0===a(t),"IsReadableStreamDisturbed should only be used on known readable streams"),t._disturbed}function c(t){return Nt(!0===a(t),"IsReadableStreamLocked should only be used on known readable streams"),void 0!==t._reader}function l(t,e){Nt(!0===a(t)),Nt("boolean"==typeof e);var r=o(t),i={closedOrErrored:!1,canceled1:!1,canceled2:!1,reason1:void 0,reason2:void 0};i.promise=new Promise(function(t){i._resolve=t});var n=h();n._reader=r,n._teeState=i,n._cloneForBranch2=e;var s=u();s._stream=t,s._teeState=i;var c=f();c._stream=t,c._teeState=i;var l=Object.create(Object.prototype);jt(l,"pull",n),jt(l,"cancel",s);var d=new $t(l),p=Object.create(Object.prototype);jt(p,"pull",n),jt(p,"cancel",c);var g=new $t(p);return n._branch1=d._readableStreamController,n._branch2=g._readableStreamController,r._closedPromise.catch(function(t){!0!==i.closedOrErrored&&(M(n._branch1,t),M(n._branch2,t),i.closedOrErrored=!0)}),[d,g]}function h(){function t(){var e=t._reader,r=t._branch1,i=t._branch2,n=t._teeState;return O(e).then(function(t){Nt(Mt(t));var e=t.value,o=t.done;if(Nt("boolean"==typeof o),!0===o&&!1===n.closedOrErrored&&(!1===n.canceled1&&I(r),!1===n.canceled2&&I(i),n.closedOrErrored=!0),!0!==n.closedOrErrored){var a=e,s=e;!1===n.canceled1&&j(r,a),!1===n.canceled2&&j(i,s)}})}return t}function u(){function t(e){var r=t._stream,i=t._teeState;if(i.canceled1=!0,i.reason1=e,!0===i.canceled2){var n=It([i.reason1,i.reason2]),o=g(r,n);i._resolve(o)}return i.promise}return t}function f(){function t(e){var r=t._stream,i=t._teeState;if(i.canceled2=!0,i.reason2=e,!0===i.canceled1){var n=It([i.reason1,i.reason2]),o=g(r,n);i._resolve(o)}return i.promise}return t}function d(t){return Nt(!0===C(t._reader)),Nt("readable"===t._state||"closed"===t._state),new Promise(function(e,r){var i={_resolve:e,_reject:r};t._reader._readIntoRequests.push(i)})}function p(t){return Nt(!0===A(t._reader)),Nt("readable"===t._state),new Promise(function(e,r){var i={_resolve:e,_reject:r};t._reader._readRequests.push(i)})}function g(t,e){return t._disturbed=!0,"closed"===t._state?Promise.resolve(void 0):"errored"===t._state?Promise.reject(t._storedError):(v(t),t._readableStreamController.__cancelSteps(e).then(function(){}))}function v(t){Nt("readable"===t._state),t._state="closed";var e=t._reader;if(void 0!==e){if(!0===A(e)){for(var r=0;r<e._readRequests.length;r++){(0,e._readRequests[r]._resolve)(Tt(void 0,!0))}e._readRequests=[]}mt(e)}}function m(t,e){Nt(!0===a(t),"stream must be ReadableStream"),Nt("readable"===t._state,"state must be readable"),t._state="errored",t._storedError=e;var r=t._reader;if(void 0!==r){if(!0===A(r)){for(var i=0;i<r._readRequests.length;i++){r._readRequests[i]._reject(e)}r._readRequests=[]}else{Nt(C(r),"reader must be ReadableStreamBYOBReader");for(var n=0;n<r._readIntoRequests.length;n++){r._readIntoRequests[n]._reject(e)}r._readIntoRequests=[]}gt(r,e),r._closedPromise.catch(function(){})}}function b(t,e,r){var i=t._reader;Nt(i._readIntoRequests.length>0),i._readIntoRequests.shift()._resolve(Tt(e,r))}function y(t,e,r){var i=t._reader;Nt(i._readRequests.length>0),i._readRequests.shift()._resolve(Tt(e,r))}function _(t){return t._reader._readIntoRequests.length}function w(t){return t._reader._readRequests.length}function S(t){var e=t._reader;return void 0!==e&&!1!==C(e)}function x(t){var e=t._reader;return void 0!==e&&!1!==A(e)}function C(t){return!!Mt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_readIntoRequests")}function A(t){return!!Mt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_readRequests")}function T(t,e){t._ownerReadableStream=e,e._reader=t,"readable"===e._state?ft(t):"closed"===e._state?pt(t):(Nt("errored"===e._state,"state must be errored"),dt(t,e._storedError),t._closedPromise.catch(function(){}))}function k(t,e){var r=t._ownerReadableStream;return Nt(void 0!==r),g(r,e)}function P(t){Nt(void 0!==t._ownerReadableStream),Nt(t._ownerReadableStream._reader===t),"readable"===t._ownerReadableStream._state?gt(t,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):vt(t,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),t._closedPromise.catch(function(){}),t._ownerReadableStream._reader=void 0,t._ownerReadableStream=void 0}function E(t,e){var r=t._ownerReadableStream;return Nt(void 0!==r),r._disturbed=!0,"errored"===r._state?Promise.reject(r._storedError):K(r._readableStreamController,e)}function O(t){var e=t._ownerReadableStream;return Nt(void 0!==e),e._disturbed=!0,"closed"===e._state?Promise.resolve(Tt(void 0,!0)):"errored"===e._state?Promise.reject(e._storedError):(Nt("readable"===e._state),e._readableStreamController.__pullSteps())}function R(t){return!!Mt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_underlyingSource")}function L(t){if(!1!==D(t)){if(!0===t._pulling)return void(t._pullAgain=!0);Nt(!1===t._pullAgain),t._pulling=!0,Et(t._underlyingSource,"pull",[t]).then(function(){if(t._pulling=!1,!0===t._pullAgain)return t._pullAgain=!1,L(t)},function(e){F(t,e)}).catch(Bt)}}function D(t){var e=t._controlledReadableStream;return"closed"!==e._state&&"errored"!==e._state&&(!0!==t._closeRequested&&(!1!==t._started&&(!0===c(e)&&w(e)>0||N(t)>0)))}function I(t){var e=t._controlledReadableStream;Nt(!1===t._closeRequested),Nt("readable"===e._state),t._closeRequested=!0,0===t._queue.length&&v(e)}function j(t,e){var r=t._controlledReadableStream;if(Nt(!1===t._closeRequested),Nt("readable"===r._state),!0===c(r)&&w(r)>0)y(r,e,!1);else{var i=1;if(void 0!==t._strategySize){var n=t._strategySize;try{i=n(e)}catch(e){throw F(t,e),e}}try{Wt(t,e,i)}catch(e){throw F(t,e),e}}L(t)}function M(t,e){var r=t._controlledReadableStream;Nt("readable"===r._state),qt(t),m(r,e)}function F(t,e){"readable"===t._controlledReadableStream._state&&M(t,e)}function N(t){var e=t._controlledReadableStream,r=e._state;return"errored"===r?null:"closed"===r?0:t._strategyHWM-t._queueTotalSize}function B(t){return!!Mt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_underlyingByteSource")}function U(t){return!!Mt(t)&&!!Object.prototype.hasOwnProperty.call(t,"_associatedReadableByteStreamController")}function z(t){if(!1!==rt(t)){if(!0===t._pulling)return void(t._pullAgain=!0);Nt(!1===t._pullAgain),t._pulling=!0,Et(t._underlyingByteSource,"pull",[t]).then(function(){t._pulling=!1,!0===t._pullAgain&&(t._pullAgain=!1,z(t))},function(e){"readable"===t._controlledReadableStream._state&&ot(t,e)}).catch(Bt)}}function W(t){Z(t),t._pendingPullIntos=[]}function q(t,e){Nt("errored"!==t._state,"state must not be errored");var r=!1;"closed"===t._state&&(Nt(0===e.bytesFilled),r=!0);var i=X(e);"default"===e.readerType?y(t,i,r):(Nt("byob"===e.readerType),b(t,i,r))}function X(t){var e=t.bytesFilled,r=t.elementSize;return Nt(e<=t.byteLength),Nt(e%r==0),new t.ctor(t.buffer,t.byteOffset,e/r)}function G(t,e,r,i){t._queue.push({buffer:e,byteOffset:r,byteLength:i}),t._queueTotalSize+=i}function H(t,e){var r=e.elementSize,i=e.bytesFilled-e.bytesFilled%r,n=Math.min(t._queueTotalSize,e.byteLength-e.bytesFilled),o=e.bytesFilled+n,a=o-o%r,s=n,c=!1;a>i&&(s=a-e.bytesFilled,c=!0);for(var l=t._queue;s>0;){var h=l[0],u=Math.min(s,h.byteLength),f=e.byteOffset+e.bytesFilled;At(e.buffer,f,h.buffer,h.byteOffset,u),h.byteLength===u?l.shift():(h.byteOffset+=u,h.byteLength-=u),t._queueTotalSize-=u,Y(t,u,e),s-=u}return!1===c&&(Nt(0===t._queueTotalSize,"queue must be empty"),Nt(e.bytesFilled>0),Nt(e.bytesFilled<e.elementSize)),c}function Y(t,e,r){Nt(0===t._pendingPullIntos.length||t._pendingPullIntos[0]===r),Z(t),r.bytesFilled+=e}function V(t){Nt("readable"===t._controlledReadableStream._state),0===t._queueTotalSize&&!0===t._closeRequested?v(t._controlledReadableStream):z(t)}function Z(t){void 0!==t._byobRequest&&(t._byobRequest._associatedReadableByteStreamController=void 0,t._byobRequest._view=void 0,t._byobRequest=void 0)}function J(t){for(Nt(!1===t._closeRequested);t._pendingPullIntos.length>0;){if(0===t._queueTotalSize)return;var e=t._pendingPullIntos[0];!0===H(t,e)&&(et(t),q(t._controlledReadableStream,e))}}function K(t,e){var r=t._controlledReadableStream,i=1;e.constructor!==DataView&&(i=e.constructor.BYTES_PER_ELEMENT);var n=e.constructor,o={buffer:e.buffer,byteOffset:e.byteOffset,byteLength:e.byteLength,bytesFilled:0,elementSize:i,ctor:n,readerType:"byob"};if(t._pendingPullIntos.length>0)return o.buffer=Ot(o.buffer),t._pendingPullIntos.push(o),d(r);if("closed"===r._state){var a=new e.constructor(o.buffer,o.byteOffset,0);return Promise.resolve(Tt(a,!0))}if(t._queueTotalSize>0){if(!0===H(t,o)){var s=X(o);return V(t),Promise.resolve(Tt(s,!1))}if(!0===t._closeRequested){var c=new TypeError("Insufficient bytes to fill elements in the given buffer");return ot(t,c),Promise.reject(c)}}o.buffer=Ot(o.buffer),t._pendingPullIntos.push(o);var l=d(r);return z(t),l}function Q(t,e){e.buffer=Ot(e.buffer),Nt(0===e.bytesFilled,"bytesFilled must be 0");var r=t._controlledReadableStream;if(!0===S(r))for(;_(r)>0;){var i=et(t);q(r,i)}}function $(t,e,r){if(r.bytesFilled+e>r.byteLength)throw new RangeError("bytesWritten out of range");if(Y(t,e,r),!(r.bytesFilled<r.elementSize)){et(t);var i=r.bytesFilled%r.elementSize;if(i>0){var n=r.byteOffset+r.bytesFilled,o=r.buffer.slice(n-i,n);G(t,o,0,o.byteLength)}r.buffer=Ot(r.buffer),r.bytesFilled-=i,q(t._controlledReadableStream,r),J(t)}}function tt(t,e){var r=t._pendingPullIntos[0],i=t._controlledReadableStream;if("closed"===i._state){if(0!==e)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream");Q(t,r)}else Nt("readable"===i._state),$(t,e,r)}function et(t){var e=t._pendingPullIntos.shift();return Z(t),e}function rt(t){var e=t._controlledReadableStream;return"readable"===e._state&&(!0!==t._closeRequested&&(!1!==t._started&&(!0===x(e)&&w(e)>0||(!0===S(e)&&_(e)>0||at(t)>0))))}function it(t){var e=t._controlledReadableStream;if(Nt(!1===t._closeRequested),Nt("readable"===e._state),t._queueTotalSize>0)return void(t._closeRequested=!0);if(t._pendingPullIntos.length>0){if(t._pendingPullIntos[0].bytesFilled>0){var r=new TypeError("Insufficient bytes to fill elements in the given buffer");throw ot(t,r),r}}v(e)}function nt(t,e){var r=t._controlledReadableStream;Nt(!1===t._closeRequested),Nt("readable"===r._state);var i=e.buffer,n=e.byteOffset,o=e.byteLength,a=Ot(i);if(!0===x(r))if(0===w(r))G(t,a,n,o);else{Nt(0===t._queue.length);var s=new Uint8Array(a,n,o);y(r,s,!1)}else!0===S(r)?(G(t,a,n,o),J(t)):(Nt(!1===c(r),"stream must not be locked"),G(t,a,n,o))}function ot(t,e){var r=t._controlledReadableStream;Nt("readable"===r._state),W(t),qt(t),m(r,e)}function at(t){var e=t._controlledReadableStream,r=e._state;return"errored"===r?null:"closed"===r?0:t._strategyHWM-t._queueTotalSize}function st(t,e){if(e=Number(e),!1===kt(e))throw new RangeError("bytesWritten must be a finite");Nt(t._pendingPullIntos.length>0),tt(t,e)}function ct(t,e){Nt(t._pendingPullIntos.length>0);var r=t._pendingPullIntos[0];if(r.byteOffset+r.bytesFilled!==e.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.byteLength!==e.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");r.buffer=e.buffer,tt(t,e.byteLength)}function lt(t){return new TypeError("ReadableStream.prototype."+t+" can only be used on a ReadableStream")}function ht(t){return new TypeError("Cannot "+t+" a stream using a released reader")}function ut(t){return new TypeError("ReadableStreamDefaultReader.prototype."+t+" can only be used on a ReadableStreamDefaultReader")}function ft(t){t._closedPromise=new Promise(function(e,r){t._closedPromise_resolve=e,t._closedPromise_reject=r})}function dt(t,e){t._closedPromise=Promise.reject(e),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0}function pt(t){t._closedPromise=Promise.resolve(void 0),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0}function gt(t,e){Nt(void 0!==t._closedPromise_resolve),Nt(void 0!==t._closedPromise_reject),t._closedPromise_reject(e),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0}function vt(t,e){Nt(void 0===t._closedPromise_resolve),Nt(void 0===t._closedPromise_reject),t._closedPromise=Promise.reject(e)}function mt(t){Nt(void 0!==t._closedPromise_resolve),Nt(void 0!==t._closedPromise_reject),t._closedPromise_resolve(void 0),t._closedPromise_resolve=void 0,t._closedPromise_reject=void 0}function bt(t){return new TypeError("ReadableStreamBYOBReader.prototype."+t+" can only be used on a ReadableStreamBYOBReader")}function yt(t){return new TypeError("ReadableStreamDefaultController.prototype."+t+" can only be used on a ReadableStreamDefaultController")}function _t(t){return new TypeError("ReadableStreamBYOBRequest.prototype."+t+" can only be used on a ReadableStreamBYOBRequest")}function wt(t){return new TypeError("ReadableByteStreamController.prototype."+t+" can only be used on a ReadableByteStreamController")}function St(t){try{Promise.prototype.then.call(t,void 0,function(){})}catch(t){}}var xt=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),Ct=r(0),At=Ct.ArrayBufferCopy,Tt=Ct.CreateIterResultObject,kt=Ct.IsFiniteNonNegativeNumber,Pt=Ct.InvokeOrNoop,Et=Ct.PromiseInvokeOrNoop,Ot=Ct.TransferArrayBuffer,Rt=Ct.ValidateAndNormalizeQueuingStrategy,Lt=Ct.ValidateAndNormalizeHighWaterMark,Dt=r(0),It=Dt.createArrayFromList,jt=Dt.createDataProperty,Mt=Dt.typeIsObject,Ft=r(1),Nt=Ft.assert,Bt=Ft.rethrowAssertionErrorRejection,Ut=r(3),zt=Ut.DequeueValue,Wt=Ut.EnqueueValueWithSize,qt=Ut.ResetQueue,Xt=r(2),Gt=Xt.AcquireWritableStreamDefaultWriter,Ht=Xt.IsWritableStream,Yt=Xt.IsWritableStreamLocked,Vt=Xt.WritableStreamAbort,Zt=Xt.WritableStreamDefaultWriterCloseWithErrorPropagation,Jt=Xt.WritableStreamDefaultWriterRelease,Kt=Xt.WritableStreamDefaultWriterWrite,Qt=Xt.WritableStreamCloseQueuedOrInFlight,$t=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=r.size,o=r.highWaterMark;i(this,t),this._state="readable",this._reader=void 0,this._storedError=void 0,this._disturbed=!1,this._readableStreamController=void 0;var a=e.type;if("bytes"===String(a))void 0===o&&(o=0),this._readableStreamController=new ne(this,e,o);else{if(void 0!==a)throw new RangeError("Invalid type is specified");void 0===o&&(o=1),this._readableStreamController=new re(this,e,n,o)}}return xt(t,[{key:"cancel",value:function t(e){return!1===a(this)?Promise.reject(lt("cancel")):!0===c(this)?Promise.reject(new TypeError("Cannot cancel a stream that already has a reader")):g(this,e)}},{key:"getReader",value:function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=e.mode;if(!1===a(this))throw lt("getReader");if(void 0===r)return o(this);if("byob"===(r=String(r)))return n(this);throw new RangeError("Invalid mode is specified")}},{key:"pipeThrough",value:function t(e,r){var i=e.writable,n=e.readable;return St(this.pipeTo(i,r)),n}},{key:"pipeTo",value:function t(e){var r=this,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=i.preventClose,s=i.preventAbort,l=i.preventCancel;if(!1===a(this))return Promise.reject(lt("pipeTo"));if(!1===Ht(e))return Promise.reject(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));if(n=Boolean(n),s=Boolean(s),l=Boolean(l),!0===c(this))return Promise.reject(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream"));if(!0===Yt(e))return Promise.reject(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream"));var h=o(this),u=Gt(e),f=!1,d=Promise.resolve();return new Promise(function(t,i){function o(){return d=Promise.resolve(),!0===f?Promise.resolve():u._readyPromise.then(function(){return O(h).then(function(t){var e=t.value;!0!==t.done&&(d=Kt(u,e).catch(function(){}))})}).then(o)}function a(){var t=d;return d.then(function(){return t!==d?a():void 0})}function c(t,e,r){"errored"===t._state?r(t._storedError):e.catch(r).catch(Bt)}function p(t,e,r){"closed"===t._state?r():e.then(r).catch(Bt)}function v(t,r,i){function n(){t().then(function(){return b(r,i)},function(t){return b(!0,t)}).catch(Bt)}!0!==f&&(f=!0,"writable"===e._state&&!1===Qt(e)?a().then(n):n())}function m(t,r){!0!==f&&(f=!0,"writable"===e._state&&!1===Qt(e)?a().then(function(){return b(t,r)}).catch(Bt):b(t,r))}function b(e,r){Jt(u),P(h),e?i(r):t(void 0)}if(c(r,h._closedPromise,function(t){!1===s?v(function(){return Vt(e,t)},!0,t):m(!0,t)}),c(e,u._closedPromise,function(t){!1===l?v(function(){return g(r,t)},!0,t):m(!0,t)}),p(r,h._closedPromise,function(){!1===n?v(function(){return Zt(u)}):m()}),!0===Qt(e)||"closed"===e._state){var y=new TypeError("the destination writable stream closed before all data could be piped to it");!1===l?v(function(){return g(r,y)},!0,y):m(!0,y)}o().catch(function(t){d=Promise.resolve(),Bt(t)})})}},{key:"tee",value:function t(){if(!1===a(this))throw lt("tee");var e=l(this,!1);return It(e)}},{key:"locked",get:function t(){if(!1===a(this))throw lt("locked");return c(this)}}]),t}();t.exports={ReadableStream:$t,IsReadableStreamDisturbed:s,ReadableStreamDefaultControllerClose:I,ReadableStreamDefaultControllerEnqueue:j,ReadableStreamDefaultControllerError:M,ReadableStreamDefaultControllerGetDesiredSize:N};var te=function(){function t(e){if(i(this,t),!1===a(e))throw new TypeError("ReadableStreamDefaultReader can only be constructed with a ReadableStream instance");if(!0===c(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");T(this,e),this._readRequests=[]}return xt(t,[{key:"cancel",value:function t(e){return!1===A(this)?Promise.reject(ut("cancel")):void 0===this._ownerReadableStream?Promise.reject(ht("cancel")):k(this,e)}},{key:"read",value:function t(){return!1===A(this)?Promise.reject(ut("read")):void 0===this._ownerReadableStream?Promise.reject(ht("read from")):O(this)}},{key:"releaseLock",value:function t(){if(!1===A(this))throw ut("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");P(this)}}},{key:"closed",get:function t(){return!1===A(this)?Promise.reject(ut("closed")):this._closedPromise}}]),t}(),ee=function(){function t(e){if(i(this,t),!a(e))throw new TypeError("ReadableStreamBYOBReader can only be constructed with a ReadableStream instance given a byte source");if(!1===B(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");if(c(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");T(this,e),this._readIntoRequests=[]}return xt(t,[{key:"cancel",value:function t(e){return C(this)?void 0===this._ownerReadableStream?Promise.reject(ht("cancel")):k(this,e):Promise.reject(bt("cancel"))}},{key:"read",value:function t(e){return C(this)?void 0===this._ownerReadableStream?Promise.reject(ht("read from")):ArrayBuffer.isView(e)?0===e.byteLength?Promise.reject(new TypeError("view must have non-zero byteLength")):E(this,e):Promise.reject(new TypeError("view must be an array buffer view")):Promise.reject(bt("read"))}},{key:"releaseLock",value:function t(){if(!C(this))throw bt("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readIntoRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");P(this)}}},{key:"closed",get:function t(){return C(this)?this._closedPromise:Promise.reject(bt("closed"))}}]),t}(),re=function(){function t(e,r,n,o){if(i(this,t),!1===a(e))throw new TypeError("ReadableStreamDefaultController can only be constructed with a ReadableStream instance");if(void 0!==e._readableStreamController)throw new TypeError("ReadableStreamDefaultController instances can only be created by the ReadableStream constructor");this._controlledReadableStream=e,this._underlyingSource=r,this._queue=void 0,this._queueTotalSize=void 0,qt(this),this._started=!1,this._closeRequested=!1,this._pullAgain=!1,this._pulling=!1;var s=Rt(n,o);this._strategySize=s.size,this._strategyHWM=s.highWaterMark;var c=this,l=Pt(r,"start",[this]);Promise.resolve(l).then(function(){c._started=!0,Nt(!1===c._pulling),Nt(!1===c._pullAgain),L(c)},function(t){F(c,t)}).catch(Bt)}return xt(t,[{key:"close",value:function t(){if(!1===R(this))throw yt("close");if(!0===this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");var e=this._controlledReadableStream._state;if("readable"!==e)throw new TypeError("The stream (in "+e+" state) is not in the readable state and cannot be closed");I(this)}},{key:"enqueue",value:function t(e){if(!1===R(this))throw yt("enqueue");if(!0===this._closeRequested)throw new TypeError("stream is closed or draining");var r=this._controlledReadableStream._state;if("readable"!==r)throw new TypeError("The stream (in "+r+" state) is not in the readable state and cannot be enqueued to");return j(this,e)}},{key:"error",value:function t(e){if(!1===R(this))throw yt("error");var r=this._controlledReadableStream;if("readable"!==r._state)throw new TypeError("The stream is "+r._state+" and so cannot be errored");M(this,e)}},{key:"__cancelSteps",value:function t(e){return qt(this),Et(this._underlyingSource,"cancel",[e])}},{key:"__pullSteps",value:function t(){var e=this._controlledReadableStream;if(this._queue.length>0){var r=zt(this);return!0===this._closeRequested&&0===this._queue.length?v(e):L(this),Promise.resolve(Tt(r,!1))}var i=p(e);return L(this),i}},{key:"desiredSize",get:function t(){if(!1===R(this))throw yt("desiredSize");return N(this)}}]),t}(),ie=function(){function t(e,r){i(this,t),this._associatedReadableByteStreamController=e,this._view=r}return xt(t,[{key:"respond",value:function t(e){if(!1===U(this))throw _t("respond");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");st(this._associatedReadableByteStreamController,e)}},{key:"respondWithNewView",value:function t(e){if(!1===U(this))throw _t("respond");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");ct(this._associatedReadableByteStreamController,e)}},{key:"view",get:function t(){return this._view}}]),t}(),ne=function(){function t(e,r,n){if(i(this,t),!1===a(e))throw new TypeError("ReadableByteStreamController can only be constructed with a ReadableStream instance given a byte source");if(void 0!==e._readableStreamController)throw new TypeError("ReadableByteStreamController instances can only be created by the ReadableStream constructor given a byte source");this._controlledReadableStream=e,this._underlyingByteSource=r,this._pullAgain=!1,this._pulling=!1,W(this),this._queue=this._queueTotalSize=void 0,qt(this),this._closeRequested=!1,this._started=!1,this._strategyHWM=Lt(n);var o=r.autoAllocateChunkSize;if(void 0!==o&&(!1===Number.isInteger(o)||o<=0))throw new RangeError("autoAllocateChunkSize must be a positive integer");this._autoAllocateChunkSize=o,this._pendingPullIntos=[];var s=this,c=Pt(r,"start",[this]);Promise.resolve(c).then(function(){s._started=!0,Nt(!1===s._pulling),Nt(!1===s._pullAgain),z(s)},function(t){"readable"===e._state&&ot(s,t)}).catch(Bt)}return xt(t,[{key:"close",value:function t(){if(!1===B(this))throw wt("close");if(!0===this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");var e=this._controlledReadableStream._state;if("readable"!==e)throw new TypeError("The stream (in "+e+" state) is not in the readable state and cannot be closed");it(this)}},{key:"enqueue",value:function t(e){if(!1===B(this))throw wt("enqueue");if(!0===this._closeRequested)throw new TypeError("stream is closed or draining");var r=this._controlledReadableStream._state;if("readable"!==r)throw new TypeError("The stream (in "+r+" state) is not in the readable state and cannot be enqueued to");if(!ArrayBuffer.isView(e))throw new TypeError("You can only enqueue array buffer views when using a ReadableByteStreamController");nt(this,e)}},{key:"error",value:function t(e){if(!1===B(this))throw wt("error");var r=this._controlledReadableStream;if("readable"!==r._state)throw new TypeError("The stream is "+r._state+" and so cannot be errored");ot(this,e)}},{key:"__cancelSteps",value:function t(e){if(this._pendingPullIntos.length>0){this._pendingPullIntos[0].bytesFilled=0}return qt(this),Et(this._underlyingByteSource,"cancel",[e])}},{key:"__pullSteps",value:function t(){var e=this._controlledReadableStream;if(Nt(!0===x(e)),this._queueTotalSize>0){Nt(0===w(e));var r=this._queue.shift();this._queueTotalSize-=r.byteLength,V(this);var i=void 0;try{i=new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}catch(t){return Promise.reject(t)}return Promise.resolve(Tt(i,!1))}var n=this._autoAllocateChunkSize;if(void 0!==n){var o=void 0;try{o=new ArrayBuffer(n)}catch(t){return Promise.reject(t)}var a={buffer:o,byteOffset:0,byteLength:n,bytesFilled:0,elementSize:1,ctor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(a)}var s=p(e);return z(this),s}},{key:"byobRequest",get:function t(){if(!1===B(this))throw wt("byobRequest");if(void 0===this._byobRequest&&this._pendingPullIntos.length>0){var e=this._pendingPullIntos[0],r=new Uint8Array(e.buffer,e.byteOffset+e.bytesFilled,e.byteLength-e.bytesFilled);this._byobRequest=new ie(this,r)}return this._byobRequest}},{key:"desiredSize",get:function t(){if(!1===B(this))throw wt("desiredSize");return at(this)}}]),t}()},function(t,e,r){var i=r(6),n=r(4),o=r(2);e.TransformStream=i.TransformStream,e.ReadableStream=n.ReadableStream,e.IsReadableStreamDisturbed=n.IsReadableStreamDisturbed,e.ReadableStreamDefaultControllerClose=n.ReadableStreamDefaultControllerClose,e.ReadableStreamDefaultControllerEnqueue=n.ReadableStreamDefaultControllerEnqueue,e.ReadableStreamDefaultControllerError=n.ReadableStreamDefaultControllerError,e.ReadableStreamDefaultControllerGetDesiredSize=n.ReadableStreamDefaultControllerGetDesiredSize,e.AcquireWritableStreamDefaultWriter=o.AcquireWritableStreamDefaultWriter,e.IsWritableStream=o.IsWritableStream,e.IsWritableStreamLocked=o.IsWritableStreamLocked,e.WritableStream=o.WritableStream,e.WritableStreamAbort=o.WritableStreamAbort,e.WritableStreamDefaultControllerError=o.WritableStreamDefaultControllerError,e.WritableStreamDefaultWriterCloseWithErrorPropagation=o.WritableStreamDefaultWriterCloseWithErrorPropagation,e.WritableStreamDefaultWriterRelease=o.WritableStreamDefaultWriterRelease,e.WritableStreamDefaultWriterWrite=o.WritableStreamDefaultWriterWrite},function(t,e,r){function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t){if(!0===t._errored)throw new TypeError("TransformStream is already errored");if(!0===t._readableClosed)throw new TypeError("Readable side is already closed");s(t)}function o(t,e){if(!0===t._errored)throw new TypeError("TransformStream is already errored");if(!0===t._readableClosed)throw new TypeError("Readable side is already closed");var r=t._readableController;try{E(r,e)}catch(e){throw t._readableClosed=!0,c(t,e),t._storedError}!0==R(r)<=0&&!1===t._backpressure&&u(t,!0)}function a(t,e){if(!0===t._errored)throw new TypeError("TransformStream is already errored");l(t,e)}function s(t){_(!1===t._errored),_(!1===t._readableClosed);try{P(t._readableController)}catch(t){_(!1)}t._readableClosed=!0}function c(t,e){!1===t._errored&&l(t,e)}function l(t,e){_(!1===t._errored),t._errored=!0,t._storedError=e,!1===t._writableDone&&I(t._writableController,e),!1===t._readableClosed&&O(t._readableController,e)}function h(t){return _(void 0!==t._backpressureChangePromise,"_backpressureChangePromise should have been initialized"),!1===t._backpressure?Promise.resolve():(_(!0===t._backpressure,"_backpressure should have been initialized"),t._backpressureChangePromise)}function u(t,e){_(t._backpressure!==e,"TransformStreamSetBackpressure() should be called only when backpressure is changed"),void 0!==t._backpressureChangePromise&&t._backpressureChangePromise_resolve(e),t._backpressureChangePromise=new Promise(function(e){t._backpressureChangePromise_resolve=e}),t._backpressureChangePromise.then(function(t){_(t!==e,"_backpressureChangePromise should be fulfilled only when backpressure is changed")}),t._backpressure=e}function f(t,e){return o(e._controlledTransformStream,t),Promise.resolve()}function d(t,e){_(!1===t._errored),_(!1===t._transforming),_(!1===t._backpressure),t._transforming=!0;var r=t._transformer,i=t._transformStreamController;return x(r,"transform",[e,i],f,[e,i]).then(function(){return t._transforming=!1,h(t)},function(e){return c(t,e),Promise.reject(e)})}function p(t){return!!A(t)&&!!Object.prototype.hasOwnProperty.call(t,"_controlledTransformStream")}function g(t){return!!A(t)&&!!Object.prototype.hasOwnProperty.call(t,"_transformStreamController")}function v(t){return new TypeError("TransformStreamDefaultController.prototype."+t+" can only be used on a TransformStreamDefaultController")}function m(t){return new TypeError("TransformStream.prototype."+t+" can only be used on a TransformStream")}var b=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),y=r(1),_=y.assert,w=r(0),S=w.InvokeOrNoop,x=w.PromiseInvokeOrPerformFallback,C=w.PromiseInvokeOrNoop,A=w.typeIsObject,T=r(4),k=T.ReadableStream,P=T.ReadableStreamDefaultControllerClose,E=T.ReadableStreamDefaultControllerEnqueue,O=T.ReadableStreamDefaultControllerError,R=T.ReadableStreamDefaultControllerGetDesiredSize,L=r(2),D=L.WritableStream,I=L.WritableStreamDefaultControllerError,j=function(){function t(e,r){i(this,t),this._transformStream=e,this._startPromise=r}return b(t,[{key:"start",value:function t(e){var r=this._transformStream;return r._writableController=e,this._startPromise.then(function(){return h(r)})}},{key:"write",value:function t(e){return d(this._transformStream,e)}},{key:"abort",value:function t(){var e=this._transformStream;e._writableDone=!0,l(e,new TypeError("Writable side aborted"))}},{key:"close",value:function t(){var e=this._transformStream;return _(!1===e._transforming),e._writableDone=!0,C(e._transformer,"flush",[e._transformStreamController]).then(function(){return!0===e._errored?Promise.reject(e._storedError):(!1===e._readableClosed&&s(e),Promise.resolve())}).catch(function(t){return c(e,t),Promise.reject(e._storedError)})}}]),t}(),M=function(){function t(e,r){i(this,t),this._transformStream=e,this._startPromise=r}return b(t,[{key:"start",value:function t(e){var r=this._transformStream;return r._readableController=e,this._startPromise.then(function(){return _(void 0!==r._backpressureChangePromise,"_backpressureChangePromise should have been initialized"),!0===r._backpressure?Promise.resolve():(_(!1===r._backpressure,"_backpressure should have been initialized"),r._backpressureChangePromise)})}},{key:"pull",value:function t(){var e=this._transformStream;return _(!0===e._backpressure,"pull() should be never called while _backpressure is false"),_(void 0!==e._backpressureChangePromise,"_backpressureChangePromise should have been initialized"),u(e,!1),e._backpressureChangePromise}},{key:"cancel",value:function t(){var e=this._transformStream;e._readableClosed=!0,l(e,new TypeError("Readable side canceled"))}}]),t}(),F=function(){function t(e){if(i(this,t),!1===g(e))throw new TypeError("TransformStreamDefaultController can only be constructed with a TransformStream instance");if(void 0!==e._transformStreamController)throw new TypeError("TransformStreamDefaultController instances can only be created by the TransformStream constructor");this._controlledTransformStream=e}return b(t,[{key:"enqueue",value:function t(e){if(!1===p(this))throw v("enqueue");o(this._controlledTransformStream,e)}},{key:"close",value:function t(){if(!1===p(this))throw v("close");n(this._controlledTransformStream)}},{key:"error",value:function t(e){if(!1===p(this))throw v("error");a(this._controlledTransformStream,e)}},{key:"desiredSize",get:function t(){if(!1===p(this))throw v("desiredSize");var e=this._controlledTransformStream,r=e._readableController;return R(r)}}]),t}(),N=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};i(this,t),this._transformer=e;var r=e.readableStrategy,n=e.writableStrategy;this._transforming=!1,this._errored=!1,this._storedError=void 0,this._writableController=void 0,this._readableController=void 0,this._transformStreamController=void 0,this._writableDone=!1,this._readableClosed=!1,this._backpressure=void 0,this._backpressureChangePromise=void 0,this._backpressureChangePromise_resolve=void 0,this._transformStreamController=new F(this);var o=void 0,a=new Promise(function(t){o=t}),s=new M(this,a);this._readable=new k(s,r);var c=new j(this,a);this._writable=new D(c,n),_(void 0!==this._writableController),_(void 0!==this._readableController),u(this,R(this._readableController)<=0);var l=this,h=S(e,"start",[l._transformStreamController]);o(h),a.catch(function(t){!1===l._errored&&(l._errored=!0,l._storedError=t)})}return b(t,[{key:"readable",get:function t(){if(!1===g(this))throw m("readable");return this._readable}},{key:"writable",get:function t(){if(!1===g(this))throw m("writable");return this._writable}}]),t}();t.exports={TransformStream:N}},function(t,e,r){t.exports=r(5)}]))},function(t,e,r){"use strict";function i(t){t.mozCurrentTransform||(t._originalSave=t.save,t._originalRestore=t.restore,t._originalRotate=t.rotate,t._originalScale=t.scale,t._originalTranslate=t.translate,t._originalTransform=t.transform,t._originalSetTransform=t.setTransform,t._transformMatrix=t._transformMatrix||[1,0,0,1,0,0],t._transformStack=[],Object.defineProperty(t,"mozCurrentTransform",{get:function t(){return this._transformMatrix}}),Object.defineProperty(t,"mozCurrentTransformInverse",{get:function t(){var e=this._transformMatrix,r=e[0],i=e[1],n=e[2],o=e[3],a=e[4],s=e[5],c=r*o-i*n,l=i*n-r*o;return[o/c,i/l,n/l,r/c,(o*a-n*s)/l,(i*a-r*s)/c]}}),t.save=function t(){var e=this._transformMatrix;this._transformStack.push(e),this._transformMatrix=e.slice(0,6),this._originalSave()},t.restore=function t(){var e=this._transformStack.pop();e&&(this._transformMatrix=e,this._originalRestore())},t.translate=function t(e,r){var i=this._transformMatrix;i[4]=i[0]*e+i[2]*r+i[4],i[5]=i[1]*e+i[3]*r+i[5],this._originalTranslate(e,r)},t.scale=function t(e,r){var i=this._transformMatrix;i[0]=i[0]*e,i[1]=i[1]*e,i[2]=i[2]*r,i[3]=i[3]*r,this._originalScale(e,r)},t.transform=function e(r,i,n,o,a,s){var c=this._transformMatrix;this._transformMatrix=[c[0]*r+c[2]*i,c[1]*r+c[3]*i,c[0]*n+c[2]*o,c[1]*n+c[3]*o,c[0]*a+c[2]*s+c[4],c[1]*a+c[3]*s+c[5]],t._originalTransform(r,i,n,o,a,s)},t.setTransform=function e(r,i,n,o,a,s){this._transformMatrix=[r,i,n,o,a,s],t._originalSetTransform(r,i,n,o,a,s)},t.rotate=function t(e){var r=Math.cos(e),i=Math.sin(e),n=this._transformMatrix;this._transformMatrix=[n[0]*r+n[2]*i,n[1]*r+n[3]*i,n[0]*-i+n[2]*r,n[1]*-i+n[3]*r,n[4],n[5]],this._originalRotate(e)})}function n(t){var e=1e3,r=t.width,i=t.height,n,o,a,s=r+1,c=new Uint8Array(s*(i+1)),l=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),h=r+7&-8,u=t.data,f=new Uint8Array(h*i),d=0,p;for(n=0,p=u.length;n<p;n++)for(var g=128,v=u[n];g>0;)f[d++]=v&g?0:255,g>>=1;var m=0;for(d=0,0!==f[d]&&(c[0]=1,++m),o=1;o<r;o++)f[d]!==f[d+1]&&(c[o]=f[d]?2:1,++m),d++;for(0!==f[d]&&(c[o]=2,++m),n=1;n<i;n++){d=n*h,a=n*s,f[d-h]!==f[d]&&(c[a]=f[d]?1:8,++m);var b=(f[d]?4:0)+(f[d-h]?8:0);for(o=1;o<r;o++)b=(b>>2)+(f[d+1]?4:0)+(f[d-h+1]?8:0),l[b]&&(c[a+o]=l[b],++m),d++;if(f[d-h]!==f[d]&&(c[a+o]=f[d]?2:4,++m),m>1e3)return null}for(d=h*(i-1),a=n*s,0!==f[d]&&(c[a]=8,++m),o=1;o<r;o++)f[d]!==f[d+1]&&(c[a+o]=f[d]?4:8,++m),d++;if(0!==f[d]&&(c[a+o]=4,++m),m>1e3)return null;var y=new Int32Array([0,s,-1,0,-s,0,0,0,1]),_=[];for(n=0;m&&n<=i;n++){for(var w=n*s,S=w+r;w<S&&!c[w];)w++;if(w!==S){var x=[w%s,n],C=c[w],A=w,T;do{var k=y[C];do{w+=k}while(!c[w]);T=c[w],5!==T&&10!==T?(C=T,c[w]=0):(C=T&51*C>>4,c[w]&=C>>2|C<<2),x.push(w%s),x.push(w/s|0),--m}while(A!==w);_.push(x),--n}}return function t(e){e.save(),e.scale(1/r,-1/i),e.translate(0,-i),e.beginPath();for(var n=0,o=_.length;n<o;n++){var a=_[n];e.moveTo(a[0],a[1]);for(var s=2,c=a.length;s<c;s+=2)e.lineTo(a[s],a[s+1])}e.fill(),e.beginPath(),e.restore()}}Object.defineProperty(e,"__esModule",{value:!0}),e.CanvasGraphics=void 0;var o=r(0),a=r(12),s=r(7),c=16,l=100,h=4096,u=.65,f=!0,d=1e3,p=16,g={get value(){return(0,o.shadow)(g,"value",(0,o.isLittleEndian)())}},v=function t(){function e(t){this.canvasFactory=t,this.cache=Object.create(null)}return e.prototype={getCanvas:function t(e,r,n,o){var a;return void 0!==this.cache[e]?(a=this.cache[e],this.canvasFactory.reset(a,r,n),a.context.setTransform(1,0,0,1,0,0)):(a=this.canvasFactory.create(r,n),this.cache[e]=a),o&&i(a.context),a},clear:function t(){for(var e in this.cache){var r=this.cache[e];this.canvasFactory.destroy(r),delete this.cache[e]}}},e}(),m=function t(){function e(){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=o.IDENTITY_MATRIX,this.textMatrixScale=1,this.fontMatrix=o.FONT_IDENTITY_MATRIX,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=o.TextRenderingMode.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.resumeSMaskCtx=null}return e.prototype={clone:function t(){return Object.create(this)},setCurrentPoint:function t(e,r){this.x=e,this.y=r}},e}(),b=function t(){function e(t,e,r,n,o){this.ctx=t,this.current=new m,this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=e,this.objs=r,this.canvasFactory=n,this.imageLayer=o,this.groupStack=[],this.processingType3=null,this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.smaskCounter=0,this.tempSMask=null,this.cachedCanvases=new v(this.canvasFactory),t&&i(t),this.cachedGetSinglePixelWidth=null}function r(t,e){if("undefined"!=typeof ImageData&&e instanceof ImageData)return void t.putImageData(e,0,0);var r=e.height,i=e.width,n=r%p,a=(r-n)/p,s=0===n?a:a+1,c=t.createImageData(i,p),l=0,h,u=e.data,f=c.data,d,v,m,b;if(e.kind===o.ImageKind.GRAYSCALE_1BPP){var y=u.byteLength,_=new Uint32Array(f.buffer,0,f.byteLength>>2),w=_.length,S=i+7>>3,x=4294967295,C=g.value?4278190080:255;for(d=0;d<s;d++){for(m=d<a?p:n,h=0,v=0;v<m;v++){for(var A=y-l,T=0,k=A>S?i:8*A-7,P=-8&k,E=0,O=0;T<P;T+=8)O=u[l++],_[h++]=128&O?x:C,_[h++]=64&O?x:C,_[h++]=32&O?x:C,_[h++]=16&O?x:C,_[h++]=8&O?x:C,_[h++]=4&O?x:C,_[h++]=2&O?x:C,_[h++]=1&O?x:C;for(;T<k;T++)0===E&&(O=u[l++],E=128),_[h++]=O&E?x:C,E>>=1}for(;h<w;)_[h++]=0;t.putImageData(c,0,d*p)}}else if(e.kind===o.ImageKind.RGBA_32BPP){for(v=0,b=i*p*4,d=0;d<a;d++)f.set(u.subarray(l,l+b)),l+=b,t.putImageData(c,0,v),v+=p;d<s&&(b=i*n*4,f.set(u.subarray(l,l+b)),t.putImageData(c,0,v))}else{if(e.kind!==o.ImageKind.RGB_24BPP)throw new Error("bad image kind: "+e.kind);for(m=p,b=i*m,d=0;d<s;d++){for(d>=a&&(m=n,b=i*m),h=0,v=b;v--;)f[h++]=u[l++],f[h++]=u[l++],f[h++]=u[l++],f[h++]=255;t.putImageData(c,0,d*p)}}}function c(t,e){for(var r=e.height,i=e.width,n=r%p,o=(r-n)/p,a=0===n?o:o+1,s=t.createImageData(i,p),c=0,l=e.data,h=s.data,u=0;u<a;u++){for(var f=u<o?p:n,d=3,g=0;g<f;g++)for(var v=0,m=0;m<i;m++){if(!v){var b=l[c++];v=128}h[d]=b&v?0:255,d+=4,v>>=1}t.putImageData(s,0,u*p)}}function l(t,e){for(var r=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font"],i=0,n=r.length;i<n;i++){var o=r[i];void 0!==t[o]&&(e[o]=t[o])}void 0!==t.setLineDash&&(e.setLineDash(t.getLineDash()),e.lineDashOffset=t.lineDashOffset)}function h(t){t.strokeStyle="#000000",t.fillStyle="#000000",t.fillRule="nonzero",t.globalAlpha=1,t.lineWidth=1,t.lineCap="butt",t.lineJoin="miter",t.miterLimit=10,t.globalCompositeOperation="source-over",t.font="10px sans-serif",void 0!==t.setLineDash&&(t.setLineDash([]),t.lineDashOffset=0)}function u(t,e,r,i){for(var n=t.length,o=3;o<n;o+=4){var a=t[o];if(0===a)t[o-3]=e,t[o-2]=r,t[o-1]=i;else if(a<255){var s=255-a;t[o-3]=t[o-3]*a+e*s>>8,t[o-2]=t[o-2]*a+r*s>>8,t[o-1]=t[o-1]*a+i*s>>8}}}function f(t,e,r){for(var i=t.length,n=1/255,o=3;o<i;o+=4){var a=r?r[t[o]]:t[o];e[o]=e[o]*a*(1/255)|0}}function d(t,e,r){for(var i=t.length,n=3;n<i;n+=4){var o=77*t[n-3]+152*t[n-2]+28*t[n-1];e[n]=r?e[n]*r[o>>8]>>8:e[n]*o>>16}}function b(t,e,r,i,n,o,a){var s=!!o,c=s?o[0]:0,l=s?o[1]:0,h=s?o[2]:0,p;p="Luminosity"===n?d:f;for(var g=1048576,v=Math.min(i,Math.ceil(1048576/r)),m=0;m<i;m+=v){var b=Math.min(v,i-m),y=t.getImageData(0,m,r,b),_=e.getImageData(0,m,r,b);s&&u(y.data,c,l,h),p(y.data,_.data,a),t.putImageData(_,0,m)}}function y(t,e,r){var i=e.canvas,n=e.context;t.setTransform(e.scaleX,0,0,e.scaleY,e.offsetX,e.offsetY);var o=e.backdrop||null;if(!e.transferMap&&s.WebGLUtils.isEnabled){var a=s.WebGLUtils.composeSMask(r.canvas,i,{subtype:e.subtype,backdrop:o});return t.setTransform(1,0,0,1,0,0),void t.drawImage(a,e.offsetX,e.offsetY)}b(n,r,i.width,i.height,e.subtype,o,e.transferMap),t.drawImage(i,0,0)}var _=15,w=10,S=["butt","round","square"],x=["miter","round","bevel"],C={},A={};e.prototype={beginDrawing:function t(e){var r=e.transform,i=e.viewport,n=e.transparency,o=e.background,a=void 0===o?null:o,s=this.ctx.canvas.width,c=this.ctx.canvas.height;if(this.ctx.save(),this.ctx.fillStyle=a||"rgb(255, 255, 255)",this.ctx.fillRect(0,0,s,c),this.ctx.restore(),n){var l=this.cachedCanvases.getCanvas("transparent",s,c,!0);this.compositeCtx=this.ctx,this.transparentCanvas=l.canvas,this.ctx=l.context,this.ctx.save(),this.ctx.transform.apply(this.ctx,this.compositeCtx.mozCurrentTransform)}this.ctx.save(),h(this.ctx),r&&this.ctx.transform.apply(this.ctx,r),this.ctx.transform.apply(this.ctx,i.transform),this.baseTransform=this.ctx.mozCurrentTransform.slice(),this.imageLayer&&this.imageLayer.beginLayout()},executeOperatorList:function t(e,r,i,n){var a=e.argsArray,s=e.fnArray,c=r||0,l=a.length;if(l===c)return c;for(var h=l-c>10&&"function"==typeof i,u=h?Date.now()+15:0,f=0,d=this.commonObjs,p=this.objs,g;;){if(void 0!==n&&c===n.nextBreakPoint)return n.breakIt(c,i),c;if((g=s[c])!==o.OPS.dependency)this[g].apply(this,a[c]);else for(var v=a[c],m=0,b=v.length;m<b;m++){var y=v[m],_="g"===y[0]&&"_"===y[1],w=_?d:p;if(!w.isResolved(y))return w.get(y,i),c}if(++c===l)return c;if(h&&++f>10){if(Date.now()>u)return i(),c;f=0}}},endDrawing:function t(){null!==this.current.activeSMask&&this.endSMaskGroup(),this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null),this.cachedCanvases.clear(),s.WebGLUtils.clear(),this.imageLayer&&this.imageLayer.endLayout()},setLineWidth:function t(e){this.current.lineWidth=e,this.ctx.lineWidth=e},setLineCap:function t(e){this.ctx.lineCap=S[e]},setLineJoin:function t(e){this.ctx.lineJoin=x[e]},setMiterLimit:function t(e){this.ctx.miterLimit=e},setDash:function t(e,r){var i=this.ctx;void 0!==i.setLineDash&&(i.setLineDash(e),i.lineDashOffset=r)},setRenderingIntent:function t(e){},setFlatness:function t(e){},setGState:function t(e){for(var r=0,i=e.length;r<i;r++){var n=e[r],o=n[0],a=n[1];switch(o){case"LW":this.setLineWidth(a);break;case"LC":this.setLineCap(a);break;case"LJ":this.setLineJoin(a);break;case"ML":this.setMiterLimit(a);break;case"D":this.setDash(a[0],a[1]);break;case"RI":this.setRenderingIntent(a);break;case"FL":this.setFlatness(a);break;case"Font":this.setFont(a[0],a[1]);break;case"CA":this.current.strokeAlpha=n[1];break;case"ca":this.current.fillAlpha=n[1],this.ctx.globalAlpha=n[1];break;case"BM":this.ctx.globalCompositeOperation=a;break;case"SMask":this.current.activeSMask&&(this.stateStack.length>0&&this.stateStack[this.stateStack.length-1].activeSMask===this.current.activeSMask?this.suspendSMaskGroup():this.endSMaskGroup()),this.current.activeSMask=a?this.tempSMask:null,this.current.activeSMask&&this.beginSMaskGroup(),this.tempSMask=null}}},beginSMaskGroup:function t(){var e=this.current.activeSMask,r=e.canvas.width,i=e.canvas.height,n="smaskGroupAt"+this.groupLevel,o=this.cachedCanvases.getCanvas(n,r,i,!0),a=this.ctx,s=a.mozCurrentTransform;this.ctx.save();var c=o.context;c.scale(1/e.scaleX,1/e.scaleY),c.translate(-e.offsetX,-e.offsetY),c.transform.apply(c,s),e.startTransformInverse=c.mozCurrentTransformInverse,l(a,c),this.ctx=c,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(a),this.groupLevel++},suspendSMaskGroup:function t(){var e=this.ctx;this.groupLevel--,this.ctx=this.groupStack.pop(),y(this.ctx,this.current.activeSMask,e),this.ctx.restore(),this.ctx.save(),l(e,this.ctx),this.current.resumeSMaskCtx=e;var r=o.Util.transform(this.current.activeSMask.startTransformInverse,e.mozCurrentTransform);this.ctx.transform.apply(this.ctx,r),e.save(),e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,e.canvas.width,e.canvas.height),e.restore()},resumeSMaskGroup:function t(){var e=this.current.resumeSMaskCtx,r=this.ctx;this.ctx=e,this.groupStack.push(r),this.groupLevel++},endSMaskGroup:function t(){var e=this.ctx;this.groupLevel--,this.ctx=this.groupStack.pop(),y(this.ctx,this.current.activeSMask,e),this.ctx.restore(),l(e,this.ctx);var r=o.Util.transform(this.current.activeSMask.startTransformInverse,e.mozCurrentTransform);this.ctx.transform.apply(this.ctx,r)},save:function t(){this.ctx.save();var e=this.current;this.stateStack.push(e),this.current=e.clone(),this.current.resumeSMaskCtx=null},restore:function t(){this.current.resumeSMaskCtx&&this.resumeSMaskGroup(),null===this.current.activeSMask||0!==this.stateStack.length&&this.stateStack[this.stateStack.length-1].activeSMask===this.current.activeSMask||this.endSMaskGroup(),0!==this.stateStack.length&&(this.current=this.stateStack.pop(),this.ctx.restore(),this.pendingClip=null,this.cachedGetSinglePixelWidth=null)},transform:function t(e,r,i,n,o,a){this.ctx.transform(e,r,i,n,o,a),this.cachedGetSinglePixelWidth=null},constructPath:function t(e,r){for(var i=this.ctx,n=this.current,a=n.x,s=n.y,c=0,l=0,h=e.length;c<h;c++)switch(0|e[c]){case o.OPS.rectangle:a=r[l++],s=r[l++];var u=r[l++],f=r[l++];0===u&&(u=this.getSinglePixelWidth()),0===f&&(f=this.getSinglePixelWidth());var d=a+u,p=s+f;this.ctx.moveTo(a,s),this.ctx.lineTo(d,s),this.ctx.lineTo(d,p),this.ctx.lineTo(a,p),this.ctx.lineTo(a,s),this.ctx.closePath();break;case o.OPS.moveTo:a=r[l++],s=r[l++],i.moveTo(a,s);break;case o.OPS.lineTo:a=r[l++],s=r[l++],i.lineTo(a,s);break;case o.OPS.curveTo:a=r[l+4],s=r[l+5],i.bezierCurveTo(r[l],r[l+1],r[l+2],r[l+3],a,s),l+=6;break;case o.OPS.curveTo2:i.bezierCurveTo(a,s,r[l],r[l+1],r[l+2],r[l+3]),a=r[l+2],s=r[l+3],l+=4;break;case o.OPS.curveTo3:a=r[l+2],s=r[l+3],i.bezierCurveTo(r[l],r[l+1],a,s,a,s),l+=4;break;case o.OPS.closePath:i.closePath()}n.setCurrentPoint(a,s)},closePath:function t(){this.ctx.closePath()},stroke:function t(e){e=void 0===e||e;var r=this.ctx,i=this.current.strokeColor;r.lineWidth=Math.max(.65*this.getSinglePixelWidth(),this.current.lineWidth),r.globalAlpha=this.current.strokeAlpha,i&&i.hasOwnProperty("type")&&"Pattern"===i.type?(r.save(),r.strokeStyle=i.getPattern(r,this),r.stroke(),r.restore()):r.stroke(),e&&this.consumePath(),r.globalAlpha=this.current.fillAlpha},closeStroke:function t(){this.closePath(),this.stroke()},fill:function t(e){e=void 0===e||e;var r=this.ctx,i=this.current.fillColor,n=this.current.patternFill,o=!1;n&&(r.save(),this.baseTransform&&r.setTransform.apply(r,this.baseTransform),r.fillStyle=i.getPattern(r,this),o=!0),this.pendingEOFill?(r.fill("evenodd"),this.pendingEOFill=!1):r.fill(),o&&r.restore(),e&&this.consumePath()},eoFill:function t(){this.pendingEOFill=!0,this.fill()},fillStroke:function t(){this.fill(!1),this.stroke(!1),this.consumePath()},eoFillStroke:function t(){this.pendingEOFill=!0,this.fillStroke()},closeFillStroke:function t(){this.closePath(),this.fillStroke()},closeEOFillStroke:function t(){this.pendingEOFill=!0,this.closePath(),this.fillStroke()},endPath:function t(){this.consumePath()},clip:function t(){this.pendingClip=C},eoClip:function t(){this.pendingClip=A},beginText:function t(){this.current.textMatrix=o.IDENTITY_MATRIX,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0},endText:function t(){var e=this.pendingTextPaths,r=this.ctx;if(void 0===e)return void r.beginPath();r.save(),r.beginPath();for(var i=0;i<e.length;i++){var n=e[i];r.setTransform.apply(r,n.transform),r.translate(n.x,n.y),n.addToPath(r,n.fontSize)}r.restore(),r.clip(),r.beginPath(),delete this.pendingTextPaths},setCharSpacing:function t(e){this.current.charSpacing=e},setWordSpacing:function t(e){this.current.wordSpacing=e},setHScale:function t(e){this.current.textHScale=e/100},setLeading:function t(e){this.current.leading=-e},setFont:function t(e,r){var i=this.commonObjs.get(e),n=this.current;if(!i)throw new Error("Can't find font for "+e);if(n.fontMatrix=i.fontMatrix?i.fontMatrix:o.FONT_IDENTITY_MATRIX,0!==n.fontMatrix[0]&&0!==n.fontMatrix[3]||(0,o.warn)("Invalid font matrix for font "+e),r<0?(r=-r,n.fontDirection=-1):n.fontDirection=1,this.current.font=i,this.current.fontSize=r,!i.isType3Font){var a=i.loadedName||"sans-serif",s=i.black?"900":i.bold?"bold":"normal",c=i.italic?"italic":"normal",l='"'+a+'", '+i.fallbackName,h=r<16?16:r>100?100:r;this.current.fontSizeScale=r/h;var u=c+" "+s+" "+h+"px "+l;this.ctx.font=u}},setTextRenderingMode:function t(e){this.current.textRenderingMode=e},setTextRise:function t(e){this.current.textRise=e},moveText:function t(e,r){this.current.x=this.current.lineX+=e,this.current.y=this.current.lineY+=r},setLeadingMoveText:function t(e,r){this.setLeading(-r),this.moveText(e,r)},setTextMatrix:function t(e,r,i,n,o,a){this.current.textMatrix=[e,r,i,n,o,a],this.current.textMatrixScale=Math.sqrt(e*e+r*r),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0},nextLine:function t(){this.moveText(0,this.current.leading)},paintChar:function t(e,r,i){var n=this.ctx,a=this.current,s=a.font,c=a.textRenderingMode,l=a.fontSize/a.fontSizeScale,h=c&o.TextRenderingMode.FILL_STROKE_MASK,u=!!(c&o.TextRenderingMode.ADD_TO_PATH_FLAG),f;if((s.disableFontFace||u)&&(f=s.getPathGenerator(this.commonObjs,e)),s.disableFontFace?(n.save(),n.translate(r,i),n.beginPath(),f(n,l),h!==o.TextRenderingMode.FILL&&h!==o.TextRenderingMode.FILL_STROKE||n.fill(),h!==o.TextRenderingMode.STROKE&&h!==o.TextRenderingMode.FILL_STROKE||n.stroke(),n.restore()):(h!==o.TextRenderingMode.FILL&&h!==o.TextRenderingMode.FILL_STROKE||n.fillText(e,r,i),h!==o.TextRenderingMode.STROKE&&h!==o.TextRenderingMode.FILL_STROKE||n.strokeText(e,r,i)),u){(this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:n.mozCurrentTransform,x:r,y:i,fontSize:l,addToPath:f})}},get isFontSubpixelAAEnabled(){var t=this.canvasFactory.create(10,10).context;t.scale(1.5,1),t.fillText("I",0,10);for(var e=t.getImageData(0,0,10,10).data,r=!1,i=3;i<e.length;i+=4)if(e[i]>0&&e[i]<255){r=!0;break}return(0,o.shadow)(this,"isFontSubpixelAAEnabled",r)},showText:function t(e){var r=this.current,i=r.font;if(i.isType3Font)return this.showType3Text(e);var n=r.fontSize;if(0!==n){var a=this.ctx,s=r.fontSizeScale,c=r.charSpacing,l=r.wordSpacing,h=r.fontDirection,u=r.textHScale*h,f=e.length,d=i.vertical,p=d?1:-1,g=i.defaultVMetrics,v=n*r.fontMatrix[0],m=r.textRenderingMode===o.TextRenderingMode.FILL&&!i.disableFontFace;a.save(),a.transform.apply(a,r.textMatrix),a.translate(r.x,r.y+r.textRise),r.patternFill&&(a.fillStyle=r.fillColor.getPattern(a,this)),h>0?a.scale(u,-1):a.scale(u,1);var b=r.lineWidth,y=r.textMatrixScale;if(0===y||0===b){var _=r.textRenderingMode&o.TextRenderingMode.FILL_STROKE_MASK;_!==o.TextRenderingMode.STROKE&&_!==o.TextRenderingMode.FILL_STROKE||(this.cachedGetSinglePixelWidth=null,b=.65*this.getSinglePixelWidth())}else b/=y;1!==s&&(a.scale(s,s),b/=s),a.lineWidth=b;var w=0,S;for(S=0;S<f;++S){var x=e[S];if((0,o.isNum)(x))w+=p*x*n/1e3;else{var C=!1,A=(x.isSpace?l:0)+c,T=x.fontChar,k=x.accent,P,E,O,R,L=x.width;if(d){var D,I,j;D=x.vmetric||g,I=x.vmetric?D[1]:.5*L,I=-I*v,j=D[2]*v,L=D?-D[0]:L,P=I/s,E=(w+j)/s}else P=w/s,E=0;if(i.remeasure&&L>0){var M=1e3*a.measureText(T).width/n*s;if(L<M&&this.isFontSubpixelAAEnabled){var F=L/M;C=!0,a.save(),a.scale(F,1),P/=F}else L!==M&&(P+=(L-M)/2e3*n/s)}(x.isInFont||i.missingFile)&&(m&&!k?a.fillText(T,P,E):(this.paintChar(T,P,E),k&&(O=P+k.offset.x/s,R=E-k.offset.y/s,this.paintChar(k.fontChar,O,R))));w+=L*v+A*h,C&&a.restore()}}d?r.y-=w*u:r.x+=w*u,a.restore()}},showType3Text:function t(e){var r=this.ctx,i=this.current,n=i.font,a=i.fontSize,s=i.fontDirection,c=n.vertical?1:-1,l=i.charSpacing,h=i.wordSpacing,u=i.textHScale*s,f=i.fontMatrix||o.FONT_IDENTITY_MATRIX,d=e.length,p=i.textRenderingMode===o.TextRenderingMode.INVISIBLE,g,v,m,b;if(!p&&0!==a){for(this.cachedGetSinglePixelWidth=null,r.save(),r.transform.apply(r,i.textMatrix),r.translate(i.x,i.y),r.scale(u,s),g=0;g<d;++g)if(v=e[g],(0,o.isNum)(v))b=c*v*a/1e3,this.ctx.translate(b,0),i.x+=b*u;else{var y=(v.isSpace?h:0)+l,_=n.charProcOperatorList[v.operatorListId];if(_){this.processingType3=v,this.save(),r.scale(a,a),r.transform.apply(r,f),this.executeOperatorList(_),this.restore();var w=o.Util.applyTransform([v.width,0],f);m=w[0]*a+y,r.translate(m,0),i.x+=m*u}else(0,o.warn)('Type3 character "'+v.operatorListId+'" is not available.')}r.restore(),this.processingType3=null}},setCharWidth:function t(e,r){},setCharWidthAndBounds:function t(e,r,i,n,o,a){this.ctx.rect(i,n,o-i,a-n),this.clip(),this.endPath()},getColorN_Pattern:function t(r){var i=this,n;if("TilingPattern"===r[0]){var o=r[1],s=this.baseTransform||this.ctx.mozCurrentTransform.slice(),c={createCanvasGraphics:function t(r){return new e(r,i.commonObjs,i.objs,i.canvasFactory)}};n=new a.TilingPattern(r,o,this.ctx,c,s)}else n=(0,a.getShadingPatternFromIR)(r);return n},setStrokeColorN:function t(){this.current.strokeColor=this.getColorN_Pattern(arguments)},setFillColorN:function t(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0},setStrokeRGBColor:function t(e,r,i){var n=o.Util.makeCssRgb(e,r,i);this.ctx.strokeStyle=n,this.current.strokeColor=n},setFillRGBColor:function t(e,r,i){var n=o.Util.makeCssRgb(e,r,i);this.ctx.fillStyle=n,this.current.fillColor=n,this.current.patternFill=!1},shadingFill:function t(e){var r=this.ctx;this.save();var i=(0,a.getShadingPatternFromIR)(e);r.fillStyle=i.getPattern(r,this,!0);var n=r.mozCurrentTransformInverse;if(n){var s=r.canvas,c=s.width,l=s.height,h=o.Util.applyTransform([0,0],n),u=o.Util.applyTransform([0,l],n),f=o.Util.applyTransform([c,0],n),d=o.Util.applyTransform([c,l],n),p=Math.min(h[0],u[0],f[0],d[0]),g=Math.min(h[1],u[1],f[1],d[1]),v=Math.max(h[0],u[0],f[0],d[0]),m=Math.max(h[1],u[1],f[1],d[1]);this.ctx.fillRect(p,g,v-p,m-g)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.restore()},beginInlineImage:function t(){throw new Error("Should not call beginInlineImage")},beginImageData:function t(){throw new Error("Should not call beginImageData")},paintFormXObjectBegin:function t(e,r){if(this.save(),this.baseTransformStack.push(this.baseTransform),(0,o.isArray)(e)&&6===e.length&&this.transform.apply(this,e),this.baseTransform=this.ctx.mozCurrentTransform,(0,o.isArray)(r)&&4===r.length){var i=r[2]-r[0],n=r[3]-r[1];this.ctx.rect(r[0],r[1],i,n),this.clip(),this.endPath()}},paintFormXObjectEnd:function t(){this.restore(),this.baseTransform=this.baseTransformStack.pop()},beginGroup:function t(e){this.save();var r=this.ctx;e.isolated||(0,o.info)("TODO: Support non-isolated groups."),e.knockout&&(0,o.warn)("Knockout groups not supported.");var i=r.mozCurrentTransform;if(e.matrix&&r.transform.apply(r,e.matrix),!e.bbox)throw new Error("Bounding box is required.");var n=o.Util.getAxialAlignedBoundingBox(e.bbox,r.mozCurrentTransform),a=[0,0,r.canvas.width,r.canvas.height];n=o.Util.intersect(n,a)||[0,0,0,0];var s=Math.floor(n[0]),c=Math.floor(n[1]),h=Math.max(Math.ceil(n[2])-s,1),u=Math.max(Math.ceil(n[3])-c,1),f=1,d=1;h>4096&&(f=h/4096,h=4096),u>4096&&(d=u/4096,u=4096);var p="groupAt"+this.groupLevel;e.smask&&(p+="_smask_"+this.smaskCounter++%2);var g=this.cachedCanvases.getCanvas(p,h,u,!0),v=g.context;v.scale(1/f,1/d),v.translate(-s,-c),v.transform.apply(v,i),e.smask?this.smaskStack.push({canvas:g.canvas,context:v,offsetX:s,offsetY:c,scaleX:f,scaleY:d,subtype:e.smask.subtype,backdrop:e.smask.backdrop,transferMap:e.smask.transferMap||null,startTransformInverse:null}):(r.setTransform(1,0,0,1,0,0),r.translate(s,c),r.scale(f,d)),l(r,v),this.ctx=v,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(r),this.groupLevel++,this.current.activeSMask=null},endGroup:function t(e){this.groupLevel--;var r=this.ctx;this.ctx=this.groupStack.pop(),void 0!==this.ctx.imageSmoothingEnabled?this.ctx.imageSmoothingEnabled=!1:this.ctx.mozImageSmoothingEnabled=!1,e.smask?this.tempSMask=this.smaskStack.pop():this.ctx.drawImage(r.canvas,0,0),this.restore()},beginAnnotations:function t(){this.save(),this.baseTransform&&this.ctx.setTransform.apply(this.ctx,this.baseTransform)},endAnnotations:function t(){this.restore()},beginAnnotation:function t(e,r,i){if(this.save(),h(this.ctx),this.current=new m,(0,o.isArray)(e)&&4===e.length){var n=e[2]-e[0],a=e[3]-e[1];this.ctx.rect(e[0],e[1],n,a),this.clip(),this.endPath()}this.transform.apply(this,r),this.transform.apply(this,i)},endAnnotation:function t(){this.restore()},paintJpegXObject:function t(e,r,i){var n=this.objs.get(e);if(!n)return void(0,o.warn)("Dependent image isn't ready yet");this.save();var a=this.ctx;if(a.scale(1/r,-1/i),a.drawImage(n,0,0,n.width,n.height,0,-i,r,i),this.imageLayer){var s=a.mozCurrentTransformInverse,c=this.getCanvasPosition(0,0);this.imageLayer.appendImage({objId:e,left:c[0],top:c[1],width:r/s[0],height:i/s[3]})}this.restore()},paintImageMaskXObject:function t(e){var r=this.ctx,i=e.width,o=e.height,a=this.current.fillColor,s=this.current.patternFill,l=this.processingType3;if(l&&void 0===l.compiled&&(l.compiled=i<=1e3&&o<=1e3?n({data:e.data,width:i,height:o}):null),l&&l.compiled)return void l.compiled(r);var h=this.cachedCanvases.getCanvas("maskCanvas",i,o),u=h.context;u.save(),c(u,e),u.globalCompositeOperation="source-in",u.fillStyle=s?a.getPattern(u,this):a,u.fillRect(0,0,i,o),u.restore(),this.paintInlineImageXObject(h.canvas)},paintImageMaskXObjectRepeat:function t(e,r,i,n){var o=e.width,a=e.height,s=this.current.fillColor,l=this.current.patternFill,h=this.cachedCanvases.getCanvas("maskCanvas",o,a),u=h.context;u.save(),c(u,e),u.globalCompositeOperation="source-in",u.fillStyle=l?s.getPattern(u,this):s,u.fillRect(0,0,o,a),u.restore();for(var f=this.ctx,d=0,p=n.length;d<p;d+=2)f.save(),f.transform(r,0,0,i,n[d],n[d+1]),f.scale(1,-1),f.drawImage(h.canvas,0,0,o,a,0,-1,1,1),f.restore()},paintImageMaskXObjectGroup:function t(e){for(var r=this.ctx,i=this.current.fillColor,n=this.current.patternFill,o=0,a=e.length;o<a;o++){var s=e[o],l=s.width,h=s.height,u=this.cachedCanvases.getCanvas("maskCanvas",l,h),f=u.context;f.save(),c(f,s),f.globalCompositeOperation="source-in",f.fillStyle=n?i.getPattern(f,this):i,f.fillRect(0,0,l,h),f.restore(),r.save(),r.transform.apply(r,s.transform),r.scale(1,-1),r.drawImage(u.canvas,0,0,l,h,0,-1,1,1),r.restore()}},paintImageXObject:function t(e){var r=this.objs.get(e);if(!r)return void(0,o.warn)("Dependent image isn't ready yet");this.paintInlineImageXObject(r)},paintImageXObjectRepeat:function t(e,r,i,n){var a=this.objs.get(e);if(!a)return void(0,o.warn)("Dependent image isn't ready yet");for(var s=a.width,c=a.height,l=[],h=0,u=n.length;h<u;h+=2)l.push({transform:[r,0,0,i,n[h],n[h+1]],x:0,y:0,w:s,h:c});this.paintInlineImageXObjectGroup(a,l)},paintInlineImageXObject:function t(e){var i=e.width,n=e.height,o=this.ctx;this.save(),o.scale(1/i,-1/n);var a=o.mozCurrentTransformInverse,s=a[0],c=a[1],l=Math.max(Math.sqrt(s*s+c*c),1),h=a[2],u=a[3],f=Math.max(Math.sqrt(h*h+u*u),1),d,p;if(e instanceof HTMLElement||!e.data)d=e;else{p=this.cachedCanvases.getCanvas("inlineImage",i,n);var g=p.context;r(g,e),d=p.canvas}for(var v=i,m=n,b="prescale1";l>2&&v>1||f>2&&m>1;){var y=v,_=m;l>2&&v>1&&(y=Math.ceil(v/2),l/=v/y),f>2&&m>1&&(_=Math.ceil(m/2),f/=m/_),p=this.cachedCanvases.getCanvas(b,y,_),g=p.context,g.clearRect(0,0,y,_),g.drawImage(d,0,0,v,m,0,0,y,_),d=p.canvas,v=y,m=_,b="prescale1"===b?"prescale2":"prescale1"}if(o.drawImage(d,0,0,v,m,0,-n,i,n),this.imageLayer){var w=this.getCanvasPosition(0,-n);this.imageLayer.appendImage({imgData:e,left:w[0],top:w[1],width:i/a[0],height:n/a[3]})}this.restore()},paintInlineImageXObjectGroup:function t(e,i){var n=this.ctx,o=e.width,a=e.height,s=this.cachedCanvases.getCanvas("inlineImage",o,a);r(s.context,e);for(var c=0,l=i.length;c<l;c++){var h=i[c];if(n.save(),n.transform.apply(n,h.transform),n.scale(1,-1),n.drawImage(s.canvas,h.x,h.y,h.w,h.h,0,-1,1,1),this.imageLayer){var u=this.getCanvasPosition(h.x,h.y);this.imageLayer.appendImage({imgData:e,left:u[0],top:u[1],width:o,height:a})}n.restore()}},paintSolidColorImageMask:function t(){this.ctx.fillRect(0,0,1,1)},paintXObject:function t(){(0,o.warn)("Unsupported 'paintXObject' command.")},markPoint:function t(e){},markPointProps:function t(e,r){},beginMarkedContent:function t(e){},beginMarkedContentProps:function t(e,r){},endMarkedContent:function t(){},beginCompat:function t(){},endCompat:function t(){},consumePath:function t(){var e=this.ctx;this.pendingClip&&(this.pendingClip===A?e.clip("evenodd"):e.clip(),this.pendingClip=null),e.beginPath()},getSinglePixelWidth:function t(e){if(null===this.cachedGetSinglePixelWidth){this.ctx.save();var r=this.ctx.mozCurrentTransformInverse;this.ctx.restore(),this.cachedGetSinglePixelWidth=Math.sqrt(Math.max(r[0]*r[0]+r[1]*r[1],r[2]*r[2]+r[3]*r[3]))}return this.cachedGetSinglePixelWidth},getCanvasPosition:function t(e,r){var i=this.ctx.mozCurrentTransform;return[i[0]*e+i[2]*r+i[4],i[1]*e+i[3]*r+i[5]]}};for(var T in o.OPS)e.prototype[o.OPS[T]]=e.prototype[T];return e}();e.CanvasGraphics=b},function(t,e,r){"use strict";function i(t){this.docId=t,this.styleElement=null,this.nativeFontFaces=[],this.loadTestFontId=0,this.loadingContext={requests:[],nextRequestId:0}}Object.defineProperty(e,"__esModule",{value:!0}),e.FontLoader=e.FontFaceObject=void 0;var n=r(0);i.prototype={insertRule:function t(e){var r=this.styleElement;r||(r=this.styleElement=document.createElement("style"),r.id="PDFJS_FONT_STYLE_TAG_"+this.docId,document.documentElement.getElementsByTagName("head")[0].appendChild(r));var i=r.sheet;i.insertRule(e,i.cssRules.length)},clear:function t(){this.styleElement&&(this.styleElement.remove(),this.styleElement=null),this.nativeFontFaces.forEach(function(t){document.fonts.delete(t)}),this.nativeFontFaces.length=0}};var o=function t(){return atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==")};Object.defineProperty(i.prototype,"loadTestFont",{get:function t(){return(0,n.shadow)(this,"loadTestFont",o())},configurable:!0}),i.prototype.addNativeFontFace=function t(e){this.nativeFontFaces.push(e),document.fonts.add(e)},i.prototype.bind=function t(e,r){for(var o=[],a=[],s=[],c=function t(e){return e.loaded.catch(function(t){(0,n.warn)('Failed to load font "'+e.family+'": '+t)})},l=i.isFontLoadingAPISupported&&!i.isSyncFontLoadingSupported,h=0,u=e.length;h<u;h++){var f=e[h];if(!f.attached&&!1!==f.loading)if(f.attached=!0,l){var d=f.createNativeFontFace();d&&(this.addNativeFontFace(d),s.push(c(d)))}else{var p=f.createFontFaceRule();p&&(this.insertRule(p),o.push(p),a.push(f))}}var g=this.queueLoadingCallback(r);l?Promise.all(s).then(function(){g.complete()}):o.length>0&&!i.isSyncFontLoadingSupported?this.prepareFontLoadEvent(o,a,g):g.complete()},i.prototype.queueLoadingCallback=function t(e){function r(){for((0,n.assert)(!a.end,"completeRequest() cannot be called twice"),a.end=Date.now();i.requests.length>0&&i.requests[0].end;){var t=i.requests.shift();setTimeout(t.callback,0)}}var i=this.loadingContext,o="pdfjs-font-loading-"+i.nextRequestId++,a={id:o,complete:r,callback:e,started:Date.now()};return i.requests.push(a),a},i.prototype.prepareFontLoadEvent=function t(e,r,i){function o(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function a(t,e,r,i){return t.substr(0,e)+i+t.substr(e+r)}function s(t,e){return++f>30?((0,n.warn)("Load test font never loaded."),void e()):(u.font="30px "+t,u.fillText(".",0,20),u.getImageData(0,0,1,1).data[3]>0?void e():void setTimeout(s.bind(null,t,e)))}var c,l,h=document.createElement("canvas");h.width=1,h.height=1;var u=h.getContext("2d"),f=0,d="lt"+Date.now()+this.loadTestFontId++,p=this.loadTestFont,g=976;p=a(p,976,d.length,d);var v=16,m=1482184792,b=o(p,16);for(c=0,l=d.length-3;c<l;c+=4)b=b-1482184792+o(d,c)|0;c<d.length&&(b=b-1482184792+o(d+"XXX",c)|0),p=a(p,16,4,(0,n.string32)(b));var y="url(data:font/opentype;base64,"+btoa(p)+");",_='@font-face { font-family:"'+d+'";src:'+y+"}";this.insertRule(_);var w=[];for(c=0,l=r.length;c<l;c++)w.push(r[c].loadedName);w.push(d);var S=document.createElement("div");for(S.setAttribute("style","visibility: hidden;width: 10px; height: 10px;position: absolute; top: 0px; left: 0px;"),c=0,l=w.length;c<l;++c){var x=document.createElement("span");x.textContent="Hi",x.style.fontFamily=w[c],S.appendChild(x)}document.body.appendChild(S),s(d,function(){document.body.removeChild(S),i.complete()})},i.isFontLoadingAPISupported="undefined"!=typeof document&&!!document.fonts;var a=function t(){if("undefined"==typeof navigator)return!0;var e=!1,r=/Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);return r&&r[1]>=14&&(e=!0),e};Object.defineProperty(i,"isSyncFontLoadingSupported",{get:function t(){return(0,n.shadow)(i,"isSyncFontLoadingSupported",a())},enumerable:!0,configurable:!0});var s={get value(){return(0,n.shadow)(this,"value",(0,n.isEvalSupported)())}},c=function t(){function e(t,e){this.compiledGlyphs=Object.create(null);for(var r in t)this[r]=t[r];this.options=e}return e.prototype={createNativeFontFace:function t(){if(!this.data)return null;if(this.options.disableFontFace)return this.disableFontFace=!0,null;var e=new FontFace(this.loadedName,this.data,{});return this.options.fontRegistry&&this.options.fontRegistry.registerFont(this),e},createFontFaceRule:function t(){if(!this.data)return null;if(this.options.disableFontFace)return this.disableFontFace=!0,null;var e=(0,n.bytesToString)(new Uint8Array(this.data)),r=this.loadedName,i="url(data:"+this.mimetype+";base64,"+btoa(e)+");",o='@font-face { font-family:"'+r+'";src:'+i+"}";return this.options.fontRegistry&&this.options.fontRegistry.registerFont(this,i),o},getPathGenerator:function t(e,r){if(!(r in this.compiledGlyphs)){var i=e.get(this.loadedName+"_path_"+r),n,o,a;if(this.options.isEvalSupported&&s.value){var c,l="";for(o=0,a=i.length;o<a;o++)n=i[o],c=void 0!==n.args?n.args.join(","):"",l+="c."+n.cmd+"("+c+");\n";this.compiledGlyphs[r]=new Function("c","size",l)}else this.compiledGlyphs[r]=function(t,e){for(o=0,a=i.length;o<a;o++)n=i[o],"scale"===n.cmd&&(n.args=[e,-e]),t[n.cmd].apply(t,n.args)}}return this.compiledGlyphs[r]}},e}();e.FontFaceObject=c,e.FontLoader=i},function(t,e,r){"use strict";function i(t){var e=a[t[0]];if(!e)throw new Error("Unknown IR type: "+t[0]);return e.fromIR(t)}Object.defineProperty(e,"__esModule",{value:!0}),e.TilingPattern=e.getShadingPatternFromIR=void 0;var n=r(0),o=r(7),a={};a.RadialAxial={fromIR:function t(e){var r=e[1],i=e[2],n=e[3],o=e[4],a=e[5],s=e[6];return{type:"Pattern",getPattern:function t(e){var c;"axial"===r?c=e.createLinearGradient(n[0],n[1],o[0],o[1]):"radial"===r&&(c=e.createRadialGradient(n[0],n[1],a,o[0],o[1],s));for(var l=0,h=i.length;l<h;++l){var u=i[l];c.addColorStop(u[0],u[1])}return c}}}};var s=function t(){function e(t,e,r,i,n,o,a,s){var c=e.coords,l=e.colors,h=t.data,u=4*t.width,f;c[r+1]>c[i+1]&&(f=r,r=i,i=f,f=o,o=a,a=f),c[i+1]>c[n+1]&&(f=i,i=n,n=f,f=a,a=s,s=f),c[r+1]>c[i+1]&&(f=r,r=i,i=f,f=o,o=a,a=f);var d=(c[r]+e.offsetX)*e.scaleX,p=(c[r+1]+e.offsetY)*e.scaleY,g=(c[i]+e.offsetX)*e.scaleX,v=(c[i+1]+e.offsetY)*e.scaleY,m=(c[n]+e.offsetX)*e.scaleX,b=(c[n+1]+e.offsetY)*e.scaleY;if(!(p>=b))for(var y=l[o],_=l[o+1],w=l[o+2],S=l[a],x=l[a+1],C=l[a+2],A=l[s],T=l[s+1],k=l[s+2],P=Math.round(p),E=Math.round(b),O,R,L,D,I,j,M,F,N,B=P;B<=E;B++){B<v?(N=B<p?0:p===v?1:(p-B)/(p-v),O=d-(d-g)*N,R=y-(y-S)*N,L=_-(_-x)*N,D=w-(w-C)*N):(N=B>b?1:v===b?0:(v-B)/(v-b),O=g-(g-m)*N,R=S-(S-A)*N,L=x-(x-T)*N,D=C-(C-k)*N),N=B<p?0:B>b?1:(p-B)/(p-b),I=d-(d-m)*N,j=y-(y-A)*N,M=_-(_-T)*N,F=w-(w-k)*N;for(var U=Math.round(Math.min(O,I)),z=Math.round(Math.max(O,I)),W=u*B+4*U,q=U;q<=z;q++)N=(O-q)/(O-I),N=N<0?0:N>1?1:N,h[W++]=R-(R-j)*N|0,h[W++]=L-(L-M)*N|0,h[W++]=D-(D-F)*N|0,h[W++]=255}}function r(t,r,i){var n=r.coords,o=r.colors,a,s;switch(r.type){case"lattice":var c=r.verticesPerRow,l=Math.floor(n.length/c)-1,h=c-1;for(a=0;a<l;a++)for(var u=a*c,f=0;f<h;f++,u++)e(t,i,n[u],n[u+1],n[u+c],o[u],o[u+1],o[u+c]),e(t,i,n[u+c+1],n[u+1],n[u+c],o[u+c+1],o[u+1],o[u+c]);break;case"triangles":for(a=0,s=n.length;a<s;a+=3)e(t,i,n[a],n[a+1],n[a+2],o[a],o[a+1],o[a+2]);break;default:throw new Error("illegal figure")}}function i(t,e,i,n,a,s,c){var l=1.1,h=3e3,u=2,f=Math.floor(t[0]),d=Math.floor(t[1]),p=Math.ceil(t[2])-f,g=Math.ceil(t[3])-d,v=Math.min(Math.ceil(Math.abs(p*e[0]*1.1)),3e3),m=Math.min(Math.ceil(Math.abs(g*e[1]*1.1)),3e3),b=p/v,y=g/m,_={coords:i,colors:n,offsetX:-f,offsetY:-d,scaleX:1/b,scaleY:1/y},w=v+4,S=m+4,x,C,A,T;if(o.WebGLUtils.isEnabled)x=o.WebGLUtils.drawFigures(v,m,s,a,_),C=c.getCanvas("mesh",w,S,!1),C.context.drawImage(x,2,2),x=C.canvas;else{C=c.getCanvas("mesh",w,S,!1);var k=C.context,P=k.createImageData(v,m);if(s){var E=P.data;for(A=0,T=E.length;A<T;A+=4)E[A]=s[0],E[A+1]=s[1],E[A+2]=s[2],E[A+3]=255}for(A=0;A<a.length;A++)r(P,a[A],_);k.putImageData(P,2,2),x=C.canvas}return{canvas:x,offsetX:f-2*b,offsetY:d-2*y,scaleX:b,scaleY:y}}return i}();a.Mesh={fromIR:function t(e){var r=e[2],i=e[3],o=e[4],a=e[5],c=e[6],l=e[8];return{type:"Pattern",getPattern:function t(e,h,u){var f;if(u)f=n.Util.singularValueDecompose2dScale(e.mozCurrentTransform);else if(f=n.Util.singularValueDecompose2dScale(h.baseTransform),c){var d=n.Util.singularValueDecompose2dScale(c);f=[f[0]*d[0],f[1]*d[1]]}var p=s(a,f,r,i,o,u?null:l,h.cachedCanvases);return u||(e.setTransform.apply(e,h.baseTransform),c&&e.transform.apply(e,c)),e.translate(p.offsetX,p.offsetY),e.scale(p.scaleX,p.scaleY),e.createPattern(p.canvas,"no-repeat")}}}},a.Dummy={fromIR:function t(){return{type:"Pattern",getPattern:function t(){return"hotpink"}}}};var c=function t(){function e(t,e,r,i,n){this.operatorList=t[2],this.matrix=t[3]||[1,0,0,1,0,0],this.bbox=t[4],this.xstep=t[5],this.ystep=t[6],this.paintType=t[7],this.tilingType=t[8],this.color=e,this.canvasGraphicsFactory=i,this.baseTransform=n,this.type="Pattern",this.ctx=r}var r={COLORED:1,UNCOLORED:2},i=3e3;return e.prototype={createPatternCanvas:function t(e){var r=this.operatorList,i=this.bbox,o=this.xstep,a=this.ystep,s=this.paintType,c=this.tilingType,l=this.color,h=this.canvasGraphicsFactory;(0,n.info)("TilingType: "+c);var u=i[0],f=i[1],d=i[2],p=i[3],g=[u,f],v=[u+o,f+a],m=v[0]-g[0],b=v[1]-g[1],y=n.Util.singularValueDecompose2dScale(this.matrix),_=n.Util.singularValueDecompose2dScale(this.baseTransform),w=[y[0]*_[0],y[1]*_[1]];m=Math.min(Math.ceil(Math.abs(m*w[0])),3e3),b=Math.min(Math.ceil(Math.abs(b*w[1])),3e3);var S=e.cachedCanvases.getCanvas("pattern",m,b,!0),x=S.context,C=h.createCanvasGraphics(x);C.groupLevel=e.groupLevel,this.setFillAndStrokeStyleToContext(x,s,l),this.setScale(m,b,o,a),this.transformToScale(C);var A=[1,0,0,1,-g[0],-g[1]];return C.transform.apply(C,A),this.clipBbox(C,i,u,f,d,p),C.executeOperatorList(r),S.canvas},setScale:function t(e,r,i,n){this.scale=[e/i,r/n]},transformToScale:function t(e){var r=this.scale,i=[r[0],0,0,r[1],0,0];e.transform.apply(e,i)},scaleToContext:function t(){var e=this.scale;this.ctx.scale(1/e[0],1/e[1])},clipBbox:function t(e,r,i,o,a,s){if((0,n.isArray)(r)&&4===r.length){var c=a-i,l=s-o;e.ctx.rect(i,o,c,l),e.clip(),e.endPath()}},setFillAndStrokeStyleToContext:function t(e,i,o){switch(i){case r.COLORED:var a=this.ctx;e.fillStyle=a.fillStyle,e.strokeStyle=a.strokeStyle;break;case r.UNCOLORED:var s=n.Util.makeCssRgb(o[0],o[1],o[2]);e.fillStyle=s,e.strokeStyle=s;break;default:throw new n.FormatError("Unsupported paint type: "+i)}},getPattern:function t(e,r){var i=this.createPatternCanvas(r);return e=this.ctx,e.setTransform.apply(e,this.baseTransform),e.transform.apply(e,this.matrix),this.scaleToContext(),e.createPattern(i,"repeat")}},e}();e.getShadingPatternFromIR=i,e.TilingPattern=c},function(t,e,r){"use strict";var i="1.8.575",n="bd8c1211",o=r(0),a=r(8),s=r(3),c=r(5),l=r(2),h=r(1),u=r(4);e.PDFJS=a.PDFJS,e.build=s.build,e.version=s.version,e.getDocument=s.getDocument,e.LoopbackPort=s.LoopbackPort,e.PDFDataRangeTransport=s.PDFDataRangeTransport,e.PDFWorker=s.PDFWorker,e.renderTextLayer=c.renderTextLayer,e.AnnotationLayer=l.AnnotationLayer,e.CustomStyle=h.CustomStyle,e.createPromiseCapability=o.createPromiseCapability,e.PasswordResponses=o.PasswordResponses,e.InvalidPDFException=o.InvalidPDFException,e.MissingPDFException=o.MissingPDFException,e.SVGGraphics=u.SVGGraphics,e.NativeImageDecoding=o.NativeImageDecoding,e.UnexpectedResponseException=o.UnexpectedResponseException,e.OPS=o.OPS,e.UNSUPPORTED_FEATURES=o.UNSUPPORTED_FEATURES,e.isValidUrl=h.isValidUrl,e.createValidAbsoluteUrl=o.createValidAbsoluteUrl,e.createObjectURL=o.createObjectURL,e.removeNullCharacters=o.removeNullCharacters,e.shadow=o.shadow,e.createBlob=o.createBlob,e.RenderingCancelledException=h.RenderingCancelledException,e.getFilenameFromUrl=h.getFilenameFromUrl,e.addLinkAttributes=h.addLinkAttributes,e.StatTimer=o.StatTimer},function(t,r,i){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};if("undefined"==typeof PDFJS||!PDFJS.compatibilityChecked){var o="undefined"!=typeof window&&window.Math===Math?window:void 0!==e&&e.Math===Math?e:"undefined"!=typeof self&&self.Math===Math?self:void 0,a="undefined"!=typeof navigator&&navigator.userAgent||"",s=/Android/.test(a),c=/Android\s[0-2][^\d]/.test(a),l=/Android\s[0-4][^\d]/.test(a),h=a.indexOf("Chrom")>=0,u=/Chrome\/(39|40)\./.test(a),f=a.indexOf("CriOS")>=0,d=a.indexOf("Trident")>=0,p=/\b(iPad|iPhone|iPod)(?=;)/.test(a),g=a.indexOf("Opera")>=0,v=/Safari\//.test(a)&&!/(Chrome\/|Android\s)/.test(a),m="object"===("undefined"==typeof window?"undefined":n(window))&&"object"===("undefined"==typeof document?"undefined":n(document));"undefined"==typeof PDFJS&&(o.PDFJS={}),PDFJS.compatibilityChecked=!0,function t(){function e(t,e){return new c(this.slice(t,e))}function r(t,e){arguments.length<2&&(e=0);for(var r=0,i=t.length;r<i;++r,++e)this[e]=255&t[r]}function i(t,e){this.buffer=t,this.byteLength=t.length,this.length=e,s(this.length)}function a(t){return{get:function e(){var r=this.buffer,i=t<<2;return(r[i]|r[i+1]<<8|r[i+2]<<16|r[i+3]<<24)>>>0},set:function e(r){var i=this.buffer,n=t<<2;i[n]=255&r,i[n+1]=r>>8&255,i[n+2]=r>>16&255,i[n+3]=r>>>24&255}}}function s(t){for(;l<t;)Object.defineProperty(i.prototype,l,a(l)),l++}function c(t){var i,o,a;if("number"==typeof t)for(i=[],o=0;o<t;++o)i[o]=0;else if("slice"in t)i=t.slice(0);else for(i=[],o=0,a=t.length;o<a;++o)i[o]=t[o];return i.subarray=e,i.buffer=i,i.byteLength=i.length,i.set=r,"object"===(void 0===t?"undefined":n(t))&&t.buffer&&(i.buffer=t.buffer),i}if("undefined"!=typeof Uint8Array)return void 0===Uint8Array.prototype.subarray&&(Uint8Array.prototype.subarray=function t(e,r){return new Uint8Array(this.slice(e,r))},Float32Array.prototype.subarray=function t(e,r){return new Float32Array(this.slice(e,r))}),void("undefined"==typeof Float64Array&&(o.Float64Array=Float32Array));i.prototype=Object.create(null);var l=0;o.Uint8Array=c,o.Int8Array=c,o.Int32Array=c,o.Uint16Array=c,o.Float32Array=c,o.Float64Array=c,o.Uint32Array=function(){if(3===arguments.length){if(0!==arguments[1])throw new Error("offset !== 0 is not supported");return new i(arguments[0],arguments[2])}return c.apply(this,arguments)}}(),function t(){if(m&&window.CanvasPixelArray){var e=window.CanvasPixelArray.prototype;"buffer"in e||(Object.defineProperty(e,"buffer",{get:function t(){return this},enumerable:!1,configurable:!0}),Object.defineProperty(e,"byteLength",{get:function t(){return this.length},enumerable:!1,configurable:!0}))}}(),function t(){o.URL||(o.URL=o.webkitURL)}(),function t(){if(void 0!==Object.defineProperty){var e=!0;try{m&&Object.defineProperty(new Image,"id",{value:"test"});var r=function t(){};r.prototype={get id(){}},Object.defineProperty(new r,"id",{value:"",configurable:!0,enumerable:!0,writable:!1})}catch(t){e=!1}if(e)return}Object.defineProperty=function t(e,r,i){delete e[r],"get"in i&&e.__defineGetter__(r,i.get),"set"in i&&e.__defineSetter__(r,i.set),"value"in i&&(e.__defineSetter__(r,function t(e){return this.__defineGetter__(r,function t(){return e}),e}),e[r]=i.value)}}(),function t(){if("undefined"!=typeof XMLHttpRequest){var e=XMLHttpRequest.prototype,r=new XMLHttpRequest;if("overrideMimeType"in r||Object.defineProperty(e,"overrideMimeType",{value:function t(e){}}),!("responseType"in r)){if(Object.defineProperty(e,"responseType",{get:function t(){return this._responseType||"text"},set:function t(e){"text"!==e&&"arraybuffer"!==e||(this._responseType=e,"arraybuffer"===e&&"function"==typeof this.overrideMimeType&&this.overrideMimeType("text/plain; charset=x-user-defined"))}}),"undefined"!=typeof VBArray)return void Object.defineProperty(e,"response",{get:function t(){return"arraybuffer"===this.responseType?new Uint8Array(new VBArray(this.responseBody).toArray()):this.responseText}});Object.defineProperty(e,"response",{get:function t(){if("arraybuffer"!==this.responseType)return this.responseText;var e=this.responseText,r,i=e.length,n=new Uint8Array(i);for(r=0;r<i;++r)n[r]=255&e.charCodeAt(r);return n.buffer}})}}}(),function t(){if(!("btoa"in o)){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";o.btoa=function(t){var r="",i,n;for(i=0,n=t.length;i<n;i+=3){var o=255&t.charCodeAt(i),a=255&t.charCodeAt(i+1),s=255&t.charCodeAt(i+2),c=o>>2,l=(3&o)<<4|a>>4,h=i+1<n?(15&a)<<2|s>>6:64,u=i+2<n?63&s:64;r+=e.charAt(c)+e.charAt(l)+e.charAt(h)+e.charAt(u)}return r}}}(),function t(){if(!("atob"in o)){o.atob=function(t){if(t=t.replace(/=+$/,""),t.length%4==1)throw new Error("bad atob input");for(var e=0,r,i,n=0,o="";i=t.charAt(n++);~i&&(r=e%4?64*r+i:i,e++%4)?o+=String.fromCharCode(255&r>>(-2*e&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return o}}}(),function t(){void 0===Function.prototype.bind&&(Function.prototype.bind=function t(e){var r=this,i=Array.prototype.slice.call(arguments,1);return function t(){var n=i.concat(Array.prototype.slice.call(arguments));return r.apply(e,n)}})}(),function t(){if(m){"dataset"in document.createElement("div")||Object.defineProperty(HTMLElement.prototype,"dataset",{get:function t(){if(this._dataset)return this._dataset;for(var e={},r=0,i=this.attributes.length;r<i;r++){var n=this.attributes[r];if("data-"===n.name.substring(0,5)){e[n.name.substring(5).replace(/\-([a-z])/g,function(t,e){return e.toUpperCase()})]=n.value}}return Object.defineProperty(this,"_dataset",{value:e,writable:!1,enumerable:!1}),e},enumerable:!0})}}(),function t(){function e(t,e,r,i){var n=t.className||"",o=n.split(/\s+/g);""===o[0]&&o.shift();var a=o.indexOf(e);return a<0&&r&&o.push(e),a>=0&&i&&o.splice(a,1),t.className=o.join(" "),a>=0}if(m){if(!("classList"in document.createElement("div"))){var r={add:function t(r){e(this.element,r,!0,!1)},contains:function t(r){return e(this.element,r,!1,!1)},remove:function t(r){e(this.element,r,!1,!0)},toggle:function t(r){e(this.element,r,!0,!0)}};Object.defineProperty(HTMLElement.prototype,"classList",{get:function t(){if(this._classList)return this._classList;var e=Object.create(r,{element:{value:this,writable:!1,enumerable:!0}});return Object.defineProperty(this,"_classList",{value:e,writable:!1,enumerable:!1}),e},enumerable:!0})}}}(),function t(){if(!("undefined"==typeof importScripts||"console"in o)){var e={},r={log:function t(){var e=Array.prototype.slice.call(arguments);o.postMessage({targetName:"main",action:"console_log",data:e})},error:function t(){var e=Array.prototype.slice.call(arguments);o.postMessage({targetName:"main",action:"console_error",data:e})},time:function t(r){e[r]=Date.now()},timeEnd:function t(r){var i=e[r];if(!i)throw new Error("Unknown timer name "+r);this.log("Timer:",r,Date.now()-i)}};o.console=r}}(),function t(){if(m)"console"in window?"bind"in console.log||(console.log=function(t){return function(e){return t(e)}}(console.log),console.error=function(t){return function(e){return t(e)}}(console.error),console.warn=function(t){return function(e){return t(e)}}(console.warn)):window.console={log:function t(){},error:function t(){},warn:function t(){}}}(),function t(){function e(t){r(t.target)&&t.stopPropagation()}function r(t){return t.disabled||t.parentNode&&r(t.parentNode)}g&&document.addEventListener("click",e,!0)}(),function t(){(d||f)&&(PDFJS.disableCreateObjectURL=!0)}(),function t(){"undefined"!=typeof navigator&&("language"in navigator||(PDFJS.locale=navigator.userLanguage||"en-US"))}(),function t(){(v||c||u||p)&&(PDFJS.disableRange=!0,PDFJS.disableStream=!0)}(),function t(){m&&(history.pushState&&!c||(PDFJS.disableHistory=!0))}(),function t(){if(m)if(window.CanvasPixelArray)"function"!=typeof window.CanvasPixelArray.prototype.set&&(window.CanvasPixelArray.prototype.set=function(t){for(var e=0,r=this.length;e<r;e++)this[e]=t[e]});else{var e=!1,r;if(h?(r=a.match(/Chrom(e|ium)\/([0-9]+)\./),e=r&&parseInt(r[2])<21):s?e=l:v&&(r=a.match(/Version\/([0-9]+)\.([0-9]+)\.([0-9]+) Safari\//),e=r&&parseInt(r[1])<6),e){var i=window.CanvasRenderingContext2D.prototype,n=i.createImageData;i.createImageData=function(t,e){var r=n.call(this,t,e);return r.data.set=function(t){for(var e=0,r=this.length;e<r;e++)this[e]=t[e]},r},i=null}}}(),function t(){function e(){window.requestAnimationFrame=function(t){return window.setTimeout(t,20)},window.cancelAnimationFrame=function(t){window.clearTimeout(t)}}if(m)p?e():"requestAnimationFrame"in window||(window.requestAnimationFrame=window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame,window.requestAnimationFrame||e())}(),function t(){(p||s)&&(PDFJS.maxCanvasPixels=5242880)}(),function t(){m&&d&&window.parent!==window&&(PDFJS.disableFullscreen=!0)}(),function t(){m&&("currentScript"in document||Object.defineProperty(document,"currentScript",{get:function t(){var e=document.getElementsByTagName("script");return e[e.length-1]},enumerable:!0,configurable:!0}))}(),function t(){if(m){var e=document.createElement("input");try{e.type="number"}catch(t){var r=e.constructor.prototype,i=Object.getOwnPropertyDescriptor(r,"type");Object.defineProperty(r,"type",{get:function t(){return i.get.call(this)},set:function t(e){i.set.call(this,"number"===e?"text":e)},enumerable:!0,configurable:!0})}}}(),function t(){if(m&&document.attachEvent){var e=document.constructor.prototype,r=Object.getOwnPropertyDescriptor(e,"readyState");Object.defineProperty(e,"readyState",{get:function t(){var e=r.get.call(this);return"interactive"===e?"loading":e},set:function t(e){r.set.call(this,e)},enumerable:!0,configurable:!0})}}(),function t(){m&&void 0===Element.prototype.remove&&(Element.prototype.remove=function(){this.parentNode&&this.parentNode.removeChild(this)})}(),function t(){Number.isNaN||(Number.isNaN=function(t){return"number"==typeof t&&isNaN(t)})}(),function t(){Number.isInteger||(Number.isInteger=function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t})}(),function t(){if(o.Promise)return"function"!=typeof o.Promise.all&&(o.Promise.all=function(t){var e=0,r=[],i,n,a=new o.Promise(function(t,e){i=t,n=e});return t.forEach(function(t,o){e++,t.then(function(t){r[o]=t,0===--e&&i(r)},n)}),0===e&&i(r),a}),"function"!=typeof o.Promise.resolve&&(o.Promise.resolve=function(t){return new o.Promise(function(e){e(t)})}),"function"!=typeof o.Promise.reject&&(o.Promise.reject=function(t){return new o.Promise(function(e,r){r(t)})}),void("function"!=typeof o.Promise.prototype.catch&&(o.Promise.prototype.catch=function(t){return o.Promise.prototype.then(void 0,t)}));var e=0,r=1,i=2,n=500,a={handlers:[],running:!1,unhandledRejections:[],pendingRejectionCheck:!1,scheduleHandlers:function t(e){0!==e._status&&(this.handlers=this.handlers.concat(e._handlers),e._handlers=[],this.running||(this.running=!0,setTimeout(this.runHandlers.bind(this),0)))},runHandlers:function t(){for(var e=1,r=Date.now()+1;this.handlers.length>0;){var n=this.handlers.shift(),o=n.thisPromise._status,a=n.thisPromise._value;try{1===o?"function"==typeof n.onResolve&&(a=n.onResolve(a)):"function"==typeof n.onReject&&(a=n.onReject(a),o=1,n.thisPromise._unhandledRejection&&this.removeUnhandeledRejection(n.thisPromise))}catch(t){o=i,a=t}if(n.nextPromise._updateStatus(o,a),Date.now()>=r)break}if(this.handlers.length>0)return void setTimeout(this.runHandlers.bind(this),0);this.running=!1},addUnhandledRejection:function t(e){this.unhandledRejections.push({promise:e,time:Date.now()}),this.scheduleRejectionCheck()},removeUnhandeledRejection:function t(e){e._unhandledRejection=!1;for(var r=0;r<this.unhandledRejections.length;r++)this.unhandledRejections[r].promise===e&&(this.unhandledRejections.splice(r),r--)},scheduleRejectionCheck:function t(){var e=this;this.pendingRejectionCheck||(this.pendingRejectionCheck=!0,setTimeout(function(){e.pendingRejectionCheck=!1;for(var t=Date.now(),r=0;r<e.unhandledRejections.length;r++)if(t-e.unhandledRejections[r].time>500){var i=e.unhandledRejections[r].promise._value,n="Unhandled rejection: "+i;i.stack&&(n+="\n"+i.stack);try{throw new Error(n)}catch(t){console.warn(n)}e.unhandledRejections.splice(r),r--}e.unhandledRejections.length&&e.scheduleRejectionCheck()},500))}},s=function t(e){this._status=0,this._handlers=[];try{e.call(this,this._resolve.bind(this),this._reject.bind(this))}catch(t){this._reject(t)}};s.all=function t(e){function r(t){a._status!==i&&(l=[],o(t))}var n,o,a=new s(function(t,e){n=t,o=e}),c=e.length,l=[];if(0===c)return n(l),a;for(var h=0,u=e.length;h<u;++h){var f=e[h],d=function(t){return function(e){a._status!==i&&(l[t]=e,0===--c&&n(l))}}(h);s.isPromise(f)?f.then(d,r):d(f)}return a},s.isPromise=function t(e){return e&&"function"==typeof e.then},s.resolve=function t(e){return new s(function(t){t(e)})},s.reject=function t(e){return new s(function(t,r){r(e)})},s.prototype={_status:null,_value:null,_handlers:null,_unhandledRejection:null,_updateStatus:function t(e,r){if(1!==this._status&&this._status!==i){if(1===e&&s.isPromise(r))return void r.then(this._updateStatus.bind(this,1),this._updateStatus.bind(this,i));this._status=e,this._value=r,e===i&&0===this._handlers.length&&(this._unhandledRejection=!0,a.addUnhandledRejection(this)),a.scheduleHandlers(this)}},_resolve:function t(e){this._updateStatus(1,e)},_reject:function t(e){this._updateStatus(i,e)},then:function t(e,r){var i=new s(function(t,e){this.resolve=t,this.reject=e});return this._handlers.push({thisPromise:this,onResolve:e,onReject:r,nextPromise:i}),a.scheduleHandlers(this),i},catch:function t(e){return this.then(void 0,e)}},o.Promise=s}(),function t(){function e(){this.id="$weakmap"+r++}if(!o.WeakMap){var r=0;e.prototype={has:function t(e){return("object"===(void 0===e?"undefined":n(e))||"function"==typeof e)&&null!==e&&!!Object.getOwnPropertyDescriptor(e,this.id)},get:function t(e){return this.has(e)?e[this.id]:void 0},set:function t(e,r){Object.defineProperty(e,this.id,{value:r,enumerable:!1,configurable:!0})},delete:function t(e){delete e[this.id]}},o.WeakMap=e}}(),function t(){function e(t){return void 0!==d[t]}function r(){l.call(this),this._isInvalid=!0}function i(t){return""===t&&r.call(this),t.toLowerCase()}function a(t){var e=t.charCodeAt(0);return e>32&&e<127&&-1===[34,35,60,62,63,96].indexOf(e)?t:encodeURIComponent(t)}function s(t){var e=t.charCodeAt(0);return e>32&&e<127&&-1===[34,35,60,62,96].indexOf(e)?t:encodeURIComponent(t)}function c(t,n,o){function c(t){y.push(t)}var l=n||"scheme start",h=0,u="",f=!1,b=!1,y=[];t:for(;(t[h-1]!==g||0===h)&&!this._isInvalid;){var _=t[h];switch(l){case"scheme start":if(!_||!v.test(_)){if(n){c("Invalid scheme.");break t}u="",l="no scheme";continue}u+=_.toLowerCase(),l="scheme";break;case"scheme":if(_&&m.test(_))u+=_.toLowerCase();else{if(":"!==_){if(n){if(_===g)break t;c("Code point not allowed in scheme: "+_);break t}u="",h=0,l="no scheme";continue}if(this._scheme=u,u="",n)break t;e(this._scheme)&&(this._isRelative=!0),l="file"===this._scheme?"relative":this._isRelative&&o&&o._scheme===this._scheme?"relative or authority":this._isRelative?"authority first slash":"scheme data"}break;case"scheme data":"?"===_?(this._query="?",l="query"):"#"===_?(this._fragment="#",l="fragment"):_!==g&&"\t"!==_&&"\n"!==_&&"\r"!==_&&(this._schemeData+=a(_));break;case"no scheme":if(o&&e(o._scheme)){l="relative";continue}c("Missing scheme."),r.call(this);break;case"relative or authority":if("/"!==_||"/"!==t[h+1]){c("Expected /, got: "+_),l="relative";continue}l="authority ignore slashes";break;case"relative":if(this._isRelative=!0,"file"!==this._scheme&&(this._scheme=o._scheme),_===g){this._host=o._host,this._port=o._port,this._path=o._path.slice(),this._query=o._query,this._username=o._username,this._password=o._password;break t}if("/"===_||"\\"===_)"\\"===_&&c("\\ is an invalid code point."),l="relative slash";else if("?"===_)this._host=o._host,this._port=o._port,this._path=o._path.slice(),this._query="?",this._username=o._username,this._password=o._password,l="query";else{if("#"!==_){var w=t[h+1],S=t[h+2];("file"!==this._scheme||!v.test(_)||":"!==w&&"|"!==w||S!==g&&"/"!==S&&"\\"!==S&&"?"!==S&&"#"!==S)&&(this._host=o._host,this._port=o._port,this._username=o._username,this._password=o._password,this._path=o._path.slice(),this._path.pop()),l="relative path";continue}this._host=o._host,this._port=o._port,this._path=o._path.slice(),this._query=o._query,this._fragment="#",this._username=o._username,this._password=o._password,l="fragment"}break;case"relative slash":if("/"!==_&&"\\"!==_){"file"!==this._scheme&&(this._host=o._host,this._port=o._port,this._username=o._username,this._password=o._password),l="relative path";continue}"\\"===_&&c("\\ is an invalid code point."),l="file"===this._scheme?"file host":"authority ignore slashes";break;case"authority first slash":if("/"!==_){c("Expected '/', got: "+_),l="authority ignore slashes";continue}l="authority second slash";break;case"authority second slash":if(l="authority ignore slashes","/"!==_){c("Expected '/', got: "+_);continue}break;case"authority ignore slashes":if("/"!==_&&"\\"!==_){l="authority";continue}c("Expected authority, got: "+_);break;case"authority":if("@"===_){f&&(c("@ already seen."),u+="%40"),f=!0;for(var x=0;x<u.length;x++){var C=u[x];if("\t"!==C&&"\n"!==C&&"\r"!==C)if(":"!==C||null!==this._password){var A=a(C);null!==this._password?this._password+=A:this._username+=A}else this._password="";else c("Invalid whitespace in authority.")}u=""}else{if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_){h-=u.length,u="",l="host";continue}u+=_}break;case"file host":if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_){2!==u.length||!v.test(u[0])||":"!==u[1]&&"|"!==u[1]?0===u.length?l="relative path start":(this._host=i.call(this,u),u="",l="relative path start"):l="relative path";continue}"\t"===_||"\n"===_||"\r"===_?c("Invalid whitespace in file host."):u+=_;break;case"host":case"hostname":if(":"!==_||b){if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_){if(this._host=i.call(this,u),u="",l="relative path start",n)break t;continue}"\t"!==_&&"\n"!==_&&"\r"!==_?("["===_?b=!0:"]"===_&&(b=!1),u+=_):c("Invalid code point in host/hostname: "+_)}else if(this._host=i.call(this,u),u="",l="port","hostname"===n)break t;break;case"port":if(/[0-9]/.test(_))u+=_;else{if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_||n){if(""!==u){var T=parseInt(u,10);T!==d[this._scheme]&&(this._port=T+""),u=""}if(n)break t;l="relative path start";continue}"\t"===_||"\n"===_||"\r"===_?c("Invalid code point in port: "+_):r.call(this)}break;case"relative path start":if("\\"===_&&c("'\\' not allowed in path."),l="relative path","/"!==_&&"\\"!==_)continue;break;case"relative path":if(_!==g&&"/"!==_&&"\\"!==_&&(n||"?"!==_&&"#"!==_))"\t"!==_&&"\n"!==_&&"\r"!==_&&(u+=a(_));else{"\\"===_&&c("\\ not allowed in relative path.");var k;(k=p[u.toLowerCase()])&&(u=k),".."===u?(this._path.pop(),"/"!==_&&"\\"!==_&&this._path.push("")):"."===u&&"/"!==_&&"\\"!==_?this._path.push(""):"."!==u&&("file"===this._scheme&&0===this._path.length&&2===u.length&&v.test(u[0])&&"|"===u[1]&&(u=u[0]+":"),this._path.push(u)),u="","?"===_?(this._query="?",l="query"):"#"===_&&(this._fragment="#",l="fragment")}break;case"query":n||"#"!==_?_!==g&&"\t"!==_&&"\n"!==_&&"\r"!==_&&(this._query+=s(_)):(this._fragment="#",l="fragment");break;case"fragment":_!==g&&"\t"!==_&&"\n"!==_&&"\r"!==_&&(this._fragment+=_)}h++}}function l(){this._scheme="",this._schemeData="",this._username="",this._password=null,this._host="",this._port="",this._path=[],this._query="",this._fragment="",this._isInvalid=!1,this._isRelative=!1}function h(t,e){void 0===e||e instanceof h||(e=new h(String(e))),this._url=t,l.call(this);var r=t.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g,"");c.call(this,r,null,e)}var u=!1;try{if("function"==typeof URL&&"object"===n(URL.prototype)&&"origin"in URL.prototype){var f=new URL("b","http://a");f.pathname="c%20d",u="http://a/c%20d"===f.href}}catch(t){}if(!u){var d=Object.create(null);d.ftp=21,d.file=0,d.gopher=70,d.http=80,d.https=443,d.ws=80,d.wss=443;var p=Object.create(null);p["%2e"]=".",p[".%2e"]="..",p["%2e."]="..",p["%2e%2e"]="..";var g,v=/[a-zA-Z]/,m=/[a-zA-Z0-9\+\-\.]/;h.prototype={toString:function t(){return this.href},get href(){if(this._isInvalid)return this._url;var t="";return""===this._username&&null===this._password||(t=this._username+(null!==this._password?":"+this._password:"")+"@"),this.protocol+(this._isRelative?"//"+t+this.host:"")+this.pathname+this._query+this._fragment},set href(t){l.call(this),c.call(this,t)},get protocol(){return this._scheme+":"},set protocol(t){this._isInvalid||c.call(this,t+":","scheme start")},get host(){return this._isInvalid?"":this._port?this._host+":"+this._port:this._host},set host(t){!this._isInvalid&&this._isRelative&&c.call(this,t,"host")},get hostname(){return this._host},set hostname(t){!this._isInvalid&&this._isRelative&&c.call(this,t,"hostname")},get port(){return this._port},set port(t){!this._isInvalid&&this._isRelative&&c.call(this,t,"port")},get pathname(){return this._isInvalid?"":this._isRelative?"/"+this._path.join("/"):this._schemeData},set pathname(t){!this._isInvalid&&this._isRelative&&(this._path=[],c.call(this,t,"relative path start"))},get search(){return this._isInvalid||!this._query||"?"===this._query?"":this._query},set search(t){!this._isInvalid&&this._isRelative&&(this._query="?","?"===t[0]&&(t=t.slice(1)),c.call(this,t,"query"))},get hash(){return this._isInvalid||!this._fragment||"#"===this._fragment?"":this._fragment},set hash(t){this._isInvalid||(this._fragment="#","#"===t[0]&&(t=t.slice(1)),c.call(this,t,"fragment"))},get origin(){var t;if(this._isInvalid||!this._scheme)return"";switch(this._scheme){case"data":case"file":case"javascript":case"mailto":return"null";case"blob":try{return new h(this._schemeData).origin||"null"}catch(t){}return"null"}return t=this.host,t?this._scheme+"://"+t:""}};var b=o.URL;b&&(h.createObjectURL=function(t){return b.createObjectURL.apply(b,arguments)},h.revokeObjectURL=function(t){b.revokeObjectURL(t)}),o.URL=h}}()}}])})}).call(e,r(0),r(1),r(2).Buffer)},function(t,e){var r={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==r.call(t)}},function(t,e,r){"use strict";(function(e,i){function n(t){return B.from(t)}function o(t){return B.isBuffer(t)||t instanceof U}function a(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?I(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}function s(t,e){j=j||r(4),t=t||{},this.objectMode=!!t.objectMode,e instanceof j&&(this.objectMode=this.objectMode||!!t.readableObjectMode);var i=t.highWaterMark,n=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:n,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new X,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(H||(H=r(19).StringDecoder),this.decoder=new H(t.encoding),this.encoding=t.encoding)}function c(t){if(j=j||r(4),!(this instanceof c))return new c(t);this._readableState=new s(t,this),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),N.call(this)}function l(t,e,r,i,o){var a=t._readableState;if(null===e)a.reading=!1,g(t,a);else{var s;o||(s=u(a,e)),s?t.emit("error",s):a.objectMode||e&&e.length>0?("string"==typeof e||a.objectMode||Object.getPrototypeOf(e)===B.prototype||(e=n(e)),i?a.endEmitted?t.emit("error",new Error("stream.unshift() after end event")):h(t,a,e,!0):a.ended?t.emit("error",new Error("stream.push() after EOF")):(a.reading=!1,a.decoder&&!r?(e=a.decoder.write(e),a.objectMode||0!==e.length?h(t,a,e,!1):b(t,a)):h(t,a,e,!1))):i||(a.reading=!1)}return f(a)}function h(t,e,r,i){e.flowing&&0===e.length&&!e.sync?(t.emit("data",r),t.read(0)):(e.length+=e.objectMode?1:r.length,i?e.buffer.unshift(r):e.buffer.push(r),e.needReadable&&v(t)),b(t,e)}function u(t,e){var r;return o(e)||"string"==typeof e||void 0===e||t.objectMode||(r=new TypeError("Invalid non-string/buffer chunk")),r}function f(t){return!t.ended&&(t.needReadable||t.length<t.highWaterMark||0===t.length)}function d(t){return t>=V?t=V:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}function p(t,e){return t<=0||0===e.length&&e.ended?0:e.objectMode?1:t!==t?e.flowing&&e.length?e.buffer.head.data.length:e.length:(t>e.highWaterMark&&(e.highWaterMark=d(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function g(t,e){if(!e.ended){if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,v(t)}}function v(t){var e=t._readableState;e.needReadable=!1,e.emittedReadable||(q("emitReadable",e.flowing),e.emittedReadable=!0,e.sync?D(m,t):m(t))}function m(t){q("emit readable"),t.emit("readable"),C(t)}function b(t,e){e.readingMore||(e.readingMore=!0,D(y,t,e))}function y(t,e){for(var r=e.length;!e.reading&&!e.flowing&&!e.ended&&e.length<e.highWaterMark&&(q("maybeReadMore read 0"),t.read(0),r!==e.length);)r=e.length;e.readingMore=!1}function _(t){return function(){var e=t._readableState;q("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&F(t,"data")&&(e.flowing=!0,C(t))}}function w(t){q("readable nexttick read 0"),t.read(0)}function S(t,e){e.resumeScheduled||(e.resumeScheduled=!0,D(x,t,e))}function x(t,e){e.reading||(q("resume read 0"),t.read(0)),e.resumeScheduled=!1,e.awaitDrain=0,t.emit("resume"),C(t),e.flowing&&!e.reading&&t.read(0)}function C(t){var e=t._readableState;for(q("flow",e.flowing);e.flowing&&null!==t.read(););}function A(t,e){if(0===e.length)return null;var r;return e.objectMode?r=e.buffer.shift():!t||t>=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.head.data:e.buffer.concat(e.length),e.buffer.clear()):r=T(t,e.buffer,e.decoder),r}function T(t,e,r){var i;return t<e.head.data.length?(i=e.head.data.slice(0,t),e.head.data=e.head.data.slice(t)):i=t===e.head.data.length?e.shift():r?k(t,e):P(t,e),i}function k(t,e){var r=e.head,i=1,n=r.data;for(t-=n.length;r=r.next;){var o=r.data,a=t>o.length?o.length:t;if(a===o.length?n+=o:n+=o.slice(0,t),0===(t-=a)){a===o.length?(++i,r.next?e.head=r.next:e.head=e.tail=null):(e.head=r,r.data=o.slice(a));break}++i}return e.length-=i,n}function P(t,e){var r=B.allocUnsafe(t),i=e.head,n=1;for(i.data.copy(r),t-=i.data.length;i=i.next;){var o=i.data,a=t>o.length?o.length:t;if(o.copy(r,r.length-t,0,a),0===(t-=a)){a===o.length?(++n,i.next?e.head=i.next:e.head=e.tail=null):(e.head=i,i.data=o.slice(a));break}++n}return e.length-=n,r}function E(t){var e=t._readableState;if(e.length>0)throw new Error('"endReadable()" called on non-empty stream');e.endEmitted||(e.ended=!0,D(O,e,t))}function O(t,e){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}function R(t,e){for(var r=0,i=t.length;r<i;r++)e(t[r],r)}function L(t,e){for(var r=0,i=t.length;r<i;r++)if(t[r]===e)return r;return-1}var D=r(7);t.exports=c;var I=r(13),j;c.ReadableState=s;var M=r(15).EventEmitter,F=function(t,e){return t.listeners(e).length},N=r(16),B=r(10).Buffer,U=e.Uint8Array||function(){},z=r(5);z.inherits=r(3);var W=r(44),q=void 0;q=W&&W.debuglog?W.debuglog("stream"):function(){};var X=r(45),G=r(17),H;z.inherits(c,N);var Y=["error","close","destroy","pause","resume"];Object.defineProperty(c.prototype,"destroyed",{get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(t){this._readableState&&(this._readableState.destroyed=t)}}),c.prototype.destroy=G.destroy,c.prototype._undestroy=G.undestroy,c.prototype._destroy=function(t,e){this.push(null),e(t)},c.prototype.push=function(t,e){var r=this._readableState,i;return r.objectMode?i=!0:"string"==typeof t&&(e=e||r.defaultEncoding,e!==r.encoding&&(t=B.from(t,e),e=""),i=!0),l(this,t,e,!1,i)},c.prototype.unshift=function(t){return l(this,t,null,!0,!1)},c.prototype.isPaused=function(){return!1===this._readableState.flowing},c.prototype.setEncoding=function(t){return H||(H=r(19).StringDecoder),this._readableState.decoder=new H(t),this._readableState.encoding=t,this};var V=8388608;c.prototype.read=function(t){q("read",t),t=parseInt(t,10);var e=this._readableState,r=t;if(0!==t&&(e.emittedReadable=!1),0===t&&e.needReadable&&(e.length>=e.highWaterMark||e.ended))return q("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?E(this):v(this),null;if(0===(t=p(t,e))&&e.ended)return 0===e.length&&E(this),null;var i=e.needReadable;q("need readable",i),(0===e.length||e.length-t<e.highWaterMark)&&(i=!0,q("length less than watermark",i)),e.ended||e.reading?(i=!1,q("reading or ended",i)):i&&(q("do read"),e.reading=!0,e.sync=!0,0===e.length&&(e.needReadable=!0),this._read(e.highWaterMark),e.sync=!1,e.reading||(t=p(r,e)));var n;return n=t>0?A(t,e):null,null===n?(e.needReadable=!0,t=0):e.length-=t,0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&E(this)),null!==n&&this.emit("data",n),n},c.prototype._read=function(t){this.emit("error",new Error("_read() is not implemented"))},c.prototype.pipe=function(t,e){function r(t,e){q("onunpipe"),t===f&&e&&!1===e.hasUnpiped&&(e.hasUnpiped=!0,o())}function n(){q("onend"),t.end()}function o(){q("cleanup"),t.removeListener("close",l),t.removeListener("finish",h),t.removeListener("drain",v),t.removeListener("error",c),t.removeListener("unpipe",r),f.removeListener("end",n),f.removeListener("end",u),f.removeListener("data",s),m=!0,!d.awaitDrain||t._writableState&&!t._writableState.needDrain||v()}function s(e){q("ondata"),b=!1,!1!==t.write(e)||b||((1===d.pipesCount&&d.pipes===t||d.pipesCount>1&&-1!==L(d.pipes,t))&&!m&&(q("false write response, pause",f._readableState.awaitDrain),f._readableState.awaitDrain++,b=!0),f.pause())}function c(e){q("onerror",e),u(),t.removeListener("error",c),0===F(t,"error")&&t.emit("error",e)}function l(){t.removeListener("finish",h),u()}function h(){q("onfinish"),t.removeListener("close",l),u()}function u(){q("unpipe"),f.unpipe(t)}var f=this,d=this._readableState;switch(d.pipesCount){case 0:d.pipes=t;break;case 1:d.pipes=[d.pipes,t];break;default:d.pipes.push(t)}d.pipesCount+=1,q("pipe count=%d opts=%j",d.pipesCount,e);var p=(!e||!1!==e.end)&&t!==i.stdout&&t!==i.stderr,g=p?n:u;d.endEmitted?D(g):f.once("end",g),t.on("unpipe",r);var v=_(f);t.on("drain",v);var m=!1,b=!1;return f.on("data",s),a(t,"error",c),t.once("close",l),t.once("finish",h),t.emit("pipe",f),d.flowing||(q("pipe resume"),f.resume()),t},c.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes?this:(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this,r),this);if(!t){var i=e.pipes,n=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var o=0;o<n;o++)i[o].emit("unpipe",this,r);return this}var a=L(e.pipes,t);return-1===a?this:(e.pipes.splice(a,1),e.pipesCount-=1,1===e.pipesCount&&(e.pipes=e.pipes[0]),t.emit("unpipe",this,r),this)},c.prototype.on=function(t,e){var r=N.prototype.on.call(this,t,e);if("data"===t)!1!==this._readableState.flowing&&this.resume();else if("readable"===t){var i=this._readableState;i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.emittedReadable=!1,i.reading?i.length&&v(this):D(w,this))}return r},c.prototype.addListener=c.prototype.on,c.prototype.resume=function(){var t=this._readableState;return t.flowing||(q("resume"),t.flowing=!0,S(this,t)),this},c.prototype.pause=function(){return q("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(q("pause"),this._readableState.flowing=!1,this.emit("pause")),this},c.prototype.wrap=function(t){var e=this._readableState,r=!1,i=this;t.on("end",function(){if(q("wrapped end"),e.decoder&&!e.ended){var t=e.decoder.end();t&&t.length&&i.push(t)}i.push(null)}),t.on("data",function(n){if(q("wrapped data"),e.decoder&&(n=e.decoder.write(n)),(!e.objectMode||null!==n&&void 0!==n)&&(e.objectMode||n&&n.length)){i.push(n)||(r=!0,t.pause())}});for(var n in t)void 0===this[n]&&"function"==typeof t[n]&&(this[n]=function(e){return function(){return t[e].apply(t,arguments)}}(n));for(var o=0;o<Y.length;o++)t.on(Y[o],i.emit.bind(i,Y[o]));return i._read=function(e){q("wrapped _read",e),r&&(r=!1,t.resume())},i},c._fromList=A}).call(e,r(0),r(1))},function(t,e){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(t){return"function"==typeof t}function n(t){return"number"==typeof t}function o(t){return"object"==typeof t&&null!==t}function a(t){return void 0===t}t.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(t){if(!n(t)||t<0||isNaN(t))throw TypeError("n must be a positive number");return this._maxListeners=t,this},r.prototype.emit=function(t){var e,r,n,s,c,l;if(this._events||(this._events={}),"error"===t&&(!this._events.error||o(this._events.error)&&!this._events.error.length)){if((e=arguments[1])instanceof Error)throw e;var h=new Error('Uncaught, unspecified "error" event. ('+e+")");throw h.context=e,h}if(r=this._events[t],a(r))return!1;if(i(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:s=Array.prototype.slice.call(arguments,1),r.apply(this,s)}else if(o(r))for(s=Array.prototype.slice.call(arguments,1),l=r.slice(),n=l.length,c=0;c<n;c++)l[c].apply(this,s);return!0},r.prototype.addListener=function(t,e){var n;if(!i(e))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",t,i(e.listener)?e.listener:e),this._events[t]?o(this._events[t])?this._events[t].push(e):this._events[t]=[this._events[t],e]:this._events[t]=e,o(this._events[t])&&!this._events[t].warned&&(n=a(this._maxListeners)?r.defaultMaxListeners:this._maxListeners)&&n>0&&this._events[t].length>n&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace()),this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(t,e){function r(){this.removeListener(t,r),n||(n=!0,e.apply(this,arguments))}if(!i(e))throw TypeError("listener must be a function");var n=!1;return r.listener=e,this.on(t,r),this},r.prototype.removeListener=function(t,e){var r,n,a,s;if(!i(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(r=this._events[t],a=r.length,n=-1,r===e||i(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(o(r)){for(s=a;s-- >0;)if(r[s]===e||r[s].listener&&r[s].listener===e){n=s;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},r.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[t],i(r))this.removeListener(t,r);else if(r)for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},r.prototype.listeners=function(t){var e;return e=this._events&&this._events[t]?i(this._events[t])?[this._events[t]]:this._events[t].slice():[]},r.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(i(e))return 1;if(e)return e.length}return 0},r.listenerCount=function(t,e){return t.listenerCount(e)}},function(t,e,r){t.exports=r(15).EventEmitter},function(t,e,r){"use strict";function i(t,e){var r=this,i=this._readableState&&this._readableState.destroyed,n=this._writableState&&this._writableState.destroyed;if(i||n)return void(e?e(t):!t||this._writableState&&this._writableState.errorEmitted||a(o,this,t));this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,function(t){!e&&t?(a(o,r,t),r._writableState&&(r._writableState.errorEmitted=!0)):e&&e(t)})}function n(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function o(t,e){t.emit("error",e)}var a=r(7);t.exports={destroy:i,undestroy:n}},function(t,e,r){"use strict";(function(e,i,n){function o(t,e,r){this.chunk=t,this.encoding=e,this.callback=r,this.next=null}function a(t){var e=this;this.next=null,this.entry=null,this.finish=function(){P(e,t)}}function s(t){return j.from(t)}function c(t){return j.isBuffer(t)||t instanceof M}function l(){}function h(t,e){R=R||r(4),t=t||{},this.objectMode=!!t.objectMode,e instanceof R&&(this.objectMode=this.objectMode||!!t.writableObjectMode);var i=t.highWaterMark,n=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:n,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var o=!1===t.decodeStrings;this.decodeStrings=!o,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(t){y(e,t)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new a(this)}function u(t){if(R=R||r(4),!(N.call(u,this)||this instanceof R))return new u(t);this._writableState=new h(t,this),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),I.call(this)}function f(t,e){var r=new Error("write after end");t.emit("error",r),E(e,r)}function d(t,e,r,i){var n=!0,o=!1;return null===r?o=new TypeError("May not write null values to stream"):"string"==typeof r||void 0===r||e.objectMode||(o=new TypeError("Invalid non-string/buffer chunk")),o&&(t.emit("error",o),E(i,o),n=!1),n}function p(t,e,r){return t.objectMode||!1===t.decodeStrings||"string"!=typeof e||(e=j.from(e,r)),e}function g(t,e,r,i,n,o){if(!r){var a=p(e,i,n);i!==a&&(r=!0,n="buffer",i=a)}var s=e.objectMode?1:i.length;e.length+=s;var c=e.length<e.highWaterMark;if(c||(e.needDrain=!0),e.writing||e.corked){var l=e.lastBufferedRequest;e.lastBufferedRequest={chunk:i,encoding:n,isBuf:r,callback:o,next:null},l?l.next=e.lastBufferedRequest:e.bufferedRequest=e.lastBufferedRequest,e.bufferedRequestCount+=1}else v(t,e,!1,s,i,n,o);return c}function v(t,e,r,i,n,o,a){e.writelen=i,e.writecb=a,e.writing=!0,e.sync=!0,r?t._writev(n,e.onwrite):t._write(n,o,e.onwrite),e.sync=!1}function m(t,e,r,i,n){--e.pendingcb,r?(E(n,i),E(T,t,e),t._writableState.errorEmitted=!0,t.emit("error",i)):(n(i),t._writableState.errorEmitted=!0,t.emit("error",i),T(t,e))}function b(t){t.writing=!1,t.writecb=null,t.length-=t.writelen,t.writelen=0}function y(t,e){var r=t._writableState,i=r.sync,n=r.writecb;if(b(r),e)m(t,r,i,e,n);else{var o=x(r);o||r.corked||r.bufferProcessing||!r.bufferedRequest||S(t,r),i?O(_,t,r,o,n):_(t,r,o,n)}}function _(t,e,r,i){r||w(t,e),e.pendingcb--,i(),T(t,e)}function w(t,e){0===e.length&&e.needDrain&&(e.needDrain=!1,t.emit("drain"))}function S(t,e){e.bufferProcessing=!0;var r=e.bufferedRequest;if(t._writev&&r&&r.next){var i=e.bufferedRequestCount,n=new Array(i),o=e.corkedRequestsFree;o.entry=r;for(var s=0,c=!0;r;)n[s]=r,r.isBuf||(c=!1),r=r.next,s+=1;n.allBuffers=c,v(t,e,!0,e.length,n,"",o.finish),e.pendingcb++,e.lastBufferedRequest=null,o.next?(e.corkedRequestsFree=o.next,o.next=null):e.corkedRequestsFree=new a(e)}else{for(;r;){var l=r.chunk,h=r.encoding,u=r.callback;if(v(t,e,!1,e.objectMode?1:l.length,l,h,u),r=r.next,e.writing)break}null===r&&(e.lastBufferedRequest=null)}e.bufferedRequestCount=0,e.bufferedRequest=r,e.bufferProcessing=!1}function x(t){return t.ending&&0===t.length&&null===t.bufferedRequest&&!t.finished&&!t.writing}function C(t,e){t._final(function(r){e.pendingcb--,r&&t.emit("error",r),e.prefinished=!0,t.emit("prefinish"),T(t,e)})}function A(t,e){e.prefinished||e.finalCalled||("function"==typeof t._final?(e.pendingcb++,e.finalCalled=!0,E(C,t,e)):(e.prefinished=!0,t.emit("prefinish")))}function T(t,e){var r=x(e);return r&&(A(t,e),0===e.pendingcb&&(e.finished=!0,t.emit("finish"))),r}function k(t,e,r){e.ending=!0,T(t,e),r&&(e.finished?E(r):t.once("finish",r)),e.ended=!0,t.writable=!1}function P(t,e,r){var i=t.entry;for(t.entry=null;i;){var n=i.callback;e.pendingcb--,n(r),i=i.next}e.corkedRequestsFree?e.corkedRequestsFree.next=t:e.corkedRequestsFree=t}var E=r(7);t.exports=u;var O=!e.browser&&["v0.10","v0.9."].indexOf(e.version.slice(0,5))>-1?i:E,R;u.WritableState=h;var L=r(5);L.inherits=r(3);var D={deprecate:r(48)},I=r(16),j=r(10).Buffer,M=n.Uint8Array||function(){},F=r(17);L.inherits(u,I),h.prototype.getBuffer=function t(){for(var e=this.bufferedRequest,r=[];e;)r.push(e),e=e.next;return r},function(){try{Object.defineProperty(h.prototype,"buffer",{get:D.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(t){}}();var N;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(N=Function.prototype[Symbol.hasInstance],Object.defineProperty(u,Symbol.hasInstance,{value:function(t){return!!N.call(this,t)||t&&t._writableState instanceof h}})):N=function(t){return t instanceof this},u.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},u.prototype.write=function(t,e,r){var i=this._writableState,n=!1,o=c(t)&&!i.objectMode;return o&&!j.isBuffer(t)&&(t=s(t)),"function"==typeof e&&(r=e,e=null),o?e="buffer":e||(e=i.defaultEncoding),"function"!=typeof r&&(r=l),i.ended?f(this,r):(o||d(this,i,t,r))&&(i.pendingcb++,n=g(this,i,o,t,e,r)),n},u.prototype.cork=function(){this._writableState.corked++},u.prototype.uncork=function(){var t=this._writableState;t.corked&&(t.corked--,t.writing||t.corked||t.finished||t.bufferProcessing||!t.bufferedRequest||S(this,t))},u.prototype.setDefaultEncoding=function t(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},u.prototype._write=function(t,e,r){r(new Error("_write() is not implemented"))},u.prototype._writev=null,u.prototype.end=function(t,e,r){var i=this._writableState;"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!==t&&void 0!==t&&this.write(t,e),i.corked&&(i.corked=1,this.uncork()),i.ending||i.finished||k(this,i,r)},Object.defineProperty(u.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t)}}),u.prototype.destroy=F.destroy,u.prototype._undestroy=F.undestroy,u.prototype._destroy=function(t,e){this.end(),e(t)}}).call(e,r(1),r(46).setImmediate,r(0))},function(t,e,r){function i(t){if(t&&!c(t))throw new Error("Unknown encoding: "+t)}function n(t){return t.toString(this.encoding)}function o(t){this.charReceived=t.length%2,this.charLength=this.charReceived?2:0}function a(t){this.charReceived=t.length%3,this.charLength=this.charReceived?3:0}var s=r(2).Buffer,c=s.isEncoding||function(t){switch(t&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}},l=e.StringDecoder=function(t){switch(this.encoding=(t||"utf8").toLowerCase().replace(/[-_]/,""),i(t),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=o;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=a;break;default:return void(this.write=n)}this.charBuffer=new s(6),this.charReceived=0,this.charLength=0};l.prototype.write=function(t){for(var e="";this.charLength;){var r=t.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:t.length;if(t.copy(this.charBuffer,this.charReceived,0,r),this.charReceived+=r,this.charReceived<this.charLength)return"";t=t.slice(r,t.length),e=this.charBuffer.slice(0,this.charLength).toString(this.encoding);var i=e.charCodeAt(e.length-1);if(!(i>=55296&&i<=56319)){if(this.charReceived=this.charLength=0,0===t.length)return e;break}this.charLength+=this.surrogateSize,e=""}this.detectIncompleteChar(t);var n=t.length;this.charLength&&(t.copy(this.charBuffer,0,t.length-this.charReceived,n),n-=this.charReceived),e+=t.toString(this.encoding,0,n);var n=e.length-1,i=e.charCodeAt(n);if(i>=55296&&i<=56319){var o=this.surrogateSize;return this.charLength+=o,this.charReceived+=o,this.charBuffer.copy(this.charBuffer,o,0,o),t.copy(this.charBuffer,0,0,o),e.substring(0,n)}return e},l.prototype.detectIncompleteChar=function(t){for(var e=t.length>=3?3:t.length;e>0;e--){var r=t[t.length-e];if(1==e&&r>>5==6){this.charLength=2;break}if(e<=2&&r>>4==14){this.charLength=3;break}if(e<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=e},l.prototype.end=function(t){var e="";if(t&&t.length&&(e=this.write(t)),this.charReceived){var r=this.charReceived,i=this.charBuffer,n=this.encoding;e+=i.slice(0,r).toString(n)}return e}},function(t,e,r){"use strict";function i(t){this.afterTransform=function(e,r){return n(t,e,r)},this.needTransform=!1,this.transforming=!1,this.writecb=null,this.writechunk=null,this.writeencoding=null}function n(t,e,r){var i=t._transformState;i.transforming=!1;var n=i.writecb;if(!n)return t.emit("error",new Error("write callback called multiple times"));i.writechunk=null,i.writecb=null,null!==r&&void 0!==r&&t.push(r),n(e);var o=t._readableState;o.reading=!1,(o.needReadable||o.length<o.highWaterMark)&&t._read(o.highWaterMark)}function o(t){if(!(this instanceof o))return new o(t);s.call(this,t),this._transformState=new i(this);var e=this;this._readableState.needReadable=!0,this._readableState.sync=!1,t&&("function"==typeof t.transform&&(this._transform=t.transform),"function"==typeof t.flush&&(this._flush=t.flush)),this.once("prefinish",function(){"function"==typeof this._flush?this._flush(function(t,r){a(e,t,r)}):a(e)})}function a(t,e,r){if(e)return t.emit("error",e);null!==r&&void 0!==r&&t.push(r);var i=t._writableState,n=t._transformState;if(i.length)throw new Error("Calling transform done when ws.length != 0");if(n.transforming)throw new Error("Calling transform done when still transforming");return t.push(null)}t.exports=o;var s=r(4),c=r(5);c.inherits=r(3),c.inherits(o,s),o.prototype.push=function(t,e){return this._transformState.needTransform=!1,s.prototype.push.call(this,t,e)},o.prototype._transform=function(t,e,r){throw new Error("_transform() is not implemented")},o.prototype._write=function(t,e,r){var i=this._transformState;if(i.writecb=r,i.writechunk=t,i.writeencoding=e,!i.transforming){var n=this._readableState;(i.needTransform||n.needReadable||n.length<n.highWaterMark)&&this._read(n.highWaterMark)}},o.prototype._read=function(t){var e=this._transformState;null!==e.writechunk&&e.writecb&&!e.transforming?(e.transforming=!0,this._transform(e.writechunk,e.writeencoding,e.afterTransform)):e.needTransform=!0},o.prototype._destroy=function(t,e){var r=this;s.prototype._destroy.call(this,t,function(t){e(t),r.emit("close")})}},function(t,e,r){"use strict";t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},function(t,e,r){"use strict";function i(t,e,r,i){for(var n=65535&t|0,o=t>>>16&65535|0,a=0;0!==r;){a=r>2e3?2e3:r,r-=a;do{n=n+e[i++]|0,o=o+n|0}while(--a);n%=65521,o%=65521}return n|o<<16|0}t.exports=i},function(t,e,r){"use strict";function i(){for(var t,e=[],r=0;r<256;r++){t=r;for(var i=0;i<8;i++)t=1&t?3988292384^t>>>1:t>>>1;e[r]=t}return e}function n(t,e,r,i){var n=o,a=i+r;t^=-1;for(var s=i;s<a;s++)t=t>>>8^n[255&(t^e[s])];return-1^t}var o=i();t.exports=n},function(t,e,r){(function(t,i){function n(t,r){var i={seen:[],stylize:a};return arguments.length>=3&&(i.depth=arguments[2]),arguments.length>=4&&(i.colors=arguments[3]),g(r)?i.showHidden=r:r&&e._extend(i,r),w(i.showHidden)&&(i.showHidden=!1),w(i.depth)&&(i.depth=2),w(i.colors)&&(i.colors=!1),w(i.customInspect)&&(i.customInspect=!0),i.colors&&(i.stylize=o),c(i,t,i.depth)}function o(t,e){var r=n.styles[e];return r?"["+n.colors[r][0]+"m"+t+"["+n.colors[r][1]+"m":t}function a(t,e){return t}function s(t){var e={};return t.forEach(function(t,r){e[t]=!0}),e}function c(t,r,i){if(t.customInspect&&r&&T(r.inspect)&&r.inspect!==e.inspect&&(!r.constructor||r.constructor.prototype!==r)){var n=r.inspect(i,t);return y(n)||(n=c(t,n,i)),n}var o=l(t,r);if(o)return o;var a=Object.keys(r),g=s(a);if(t.showHidden&&(a=Object.getOwnPropertyNames(r)),A(r)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return h(r);if(0===a.length){if(T(r)){var v=r.name?": "+r.name:"";return t.stylize("[Function"+v+"]","special")}if(S(r))return t.stylize(RegExp.prototype.toString.call(r),"regexp");if(C(r))return t.stylize(Date.prototype.toString.call(r),"date");if(A(r))return h(r)}var m="",b=!1,_=["{","}"];if(p(r)&&(b=!0,_=["[","]"]),T(r)){m=" [Function"+(r.name?": "+r.name:"")+"]"}if(S(r)&&(m=" "+RegExp.prototype.toString.call(r)),C(r)&&(m=" "+Date.prototype.toUTCString.call(r)),A(r)&&(m=" "+h(r)),0===a.length&&(!b||0==r.length))return _[0]+m+_[1];if(i<0)return S(r)?t.stylize(RegExp.prototype.toString.call(r),"regexp"):t.stylize("[Object]","special");t.seen.push(r);var w;return w=b?u(t,r,i,g,a):a.map(function(e){return f(t,r,i,g,e,b)}),t.seen.pop(),d(w,m,_)}function l(t,e){if(w(e))return t.stylize("undefined","undefined");if(y(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}return b(e)?t.stylize(""+e,"number"):g(e)?t.stylize(""+e,"boolean"):v(e)?t.stylize("null","null"):void 0}function h(t){return"["+Error.prototype.toString.call(t)+"]"}function u(t,e,r,i,n){for(var o=[],a=0,s=e.length;a<s;++a)R(e,String(a))?o.push(f(t,e,r,i,String(a),!0)):o.push("");return n.forEach(function(n){n.match(/^\d+$/)||o.push(f(t,e,r,i,n,!0))}),o}function f(t,e,r,i,n,o){var a,s,l;if(l=Object.getOwnPropertyDescriptor(e,n)||{value:e[n]},l.get?s=l.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):l.set&&(s=t.stylize("[Setter]","special")),R(i,n)||(a="["+n+"]"),s||(t.seen.indexOf(l.value)<0?(s=v(r)?c(t,l.value,null):c(t,l.value,r-1),s.indexOf("\n")>-1&&(s=o?s.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+s.split("\n").map(function(t){return" "+t}).join("\n"))):s=t.stylize("[Circular]","special")),w(a)){if(o&&n.match(/^\d+$/))return s;a=JSON.stringify(""+n),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=t.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=t.stylize(a,"string"))}return a+": "+s}function d(t,e,r){var i=0;return t.reduce(function(t,e){return i++,e.indexOf("\n")>=0&&i++,t+e.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1]:r[0]+e+" "+t.join(", ")+" "+r[1]}function p(t){return Array.isArray(t)}function g(t){return"boolean"==typeof t}function v(t){return null===t}function m(t){return null==t}function b(t){return"number"==typeof t}function y(t){return"string"==typeof t}function _(t){return"symbol"==typeof t}function w(t){return void 0===t}function S(t){return x(t)&&"[object RegExp]"===P(t)}function x(t){return"object"==typeof t&&null!==t}function C(t){return x(t)&&"[object Date]"===P(t)}function A(t){return x(t)&&("[object Error]"===P(t)||t instanceof Error)}function T(t){return"function"==typeof t}function k(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t}function P(t){return Object.prototype.toString.call(t)}function E(t){return t<10?"0"+t.toString(10):t.toString(10)}function O(){var t=new Date,e=[E(t.getHours()),E(t.getMinutes()),E(t.getSeconds())].join(":");return[t.getDate(),j[t.getMonth()],e].join(" ")}function R(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var L=/%[sdj%]/g;e.format=function(t){if(!y(t)){for(var e=[],r=0;r<arguments.length;r++)e.push(n(arguments[r]));return e.join(" ")}for(var r=1,i=arguments,o=i.length,a=String(t).replace(L,function(t){if("%%"===t)return"%";if(r>=o)return t;switch(t){case"%s":return String(i[r++]);case"%d":return Number(i[r++]);case"%j":try{return JSON.stringify(i[r++])}catch(t){return"[Circular]"}default:return t}}),s=i[r];r<o;s=i[++r])v(s)||!x(s)?a+=" "+s:a+=" "+n(s);return a},e.deprecate=function(r,n){function o(){if(!a){if(i.throwDeprecation)throw new Error(n);i.traceDeprecation?console.trace(n):console.error(n),a=!0}return r.apply(this,arguments)}if(w(t.process))return function(){return e.deprecate(r,n).apply(this,arguments)};if(!0===i.noDeprecation)return r;var a=!1;return o};var D={},I;e.debuglog=function(t){if(w(I)&&(I=i.env.NODE_DEBUG||""),t=t.toUpperCase(),!D[t])if(new RegExp("\\b"+t+"\\b","i").test(I)){var r=i.pid;D[t]=function(){var i=e.format.apply(e,arguments);console.error("%s %d: %s",t,r,i)}}else D[t]=function(){};return D[t]},e.inspect=n,n.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},n.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},e.isArray=p,e.isBoolean=g,e.isNull=v,e.isNullOrUndefined=m,e.isNumber=b,e.isString=y,e.isSymbol=_,e.isUndefined=w,e.isRegExp=S,e.isObject=x,e.isDate=C,e.isError=A,e.isFunction=T,e.isPrimitive=k,e.isBuffer=r(58);var j=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];e.log=function(){console.log("%s - %s",O(),e.format.apply(e,arguments))},e.inherits=r(59),e._extend=function(t,e){if(!e||!x(e))return t;for(var r=Object.keys(e),i=r.length;i--;)t[r[i]]=e[r[i]];return t}}).call(e,r(0),r(1))},function(t,e,r){"use strict";function i(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}function n(t,e,r){if(t&&l.isObject(t)&&t instanceof i)return t;var n=new i;return n.parse(t,e,r),n}function o(t){return l.isString(t)&&(t=n(t)),t instanceof i?t.format():i.prototype.format.call(t)}function a(t,e){return n(t,!1,!0).resolve(e)}function s(t,e){return t?n(t,!1,!0).resolveObject(e):e}var c=r(66),l=r(68);e.parse=n,e.resolve=a,e.resolveObject=s,e.format=o,e.Url=i;var h=/^([a-z0-9.+-]+:)/i,u=/:[0-9]*$/,f=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,d=["<",">",'"',"`"," ","\r","\n","\t"],p=["{","}","|","\\","^","`"].concat(d),g=["'"].concat(p),v=["%","/","?",";","#"].concat(g),m=["/","?","#"],b=255,y=/^[+a-z0-9A-Z_-]{0,63}$/,_=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,w={javascript:!0,"javascript:":!0},S={javascript:!0,"javascript:":!0},x={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},C=r(69);i.prototype.parse=function(t,e,r){if(!l.isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var i=t.indexOf("?"),n=-1!==i&&i<t.indexOf("#")?"?":"#",o=t.split(n),a=/\\/g;o[0]=o[0].replace(a,"/"),t=o.join(n);var s=t;if(s=s.trim(),!r&&1===t.split("#").length){var u=f.exec(s);if(u)return this.path=s,this.href=s,this.pathname=u[1],u[2]?(this.search=u[2],this.query=e?C.parse(this.search.substr(1)):this.search.substr(1)):e&&(this.search="",this.query={}),this}var d=h.exec(s);if(d){d=d[0];var p=d.toLowerCase();this.protocol=p,s=s.substr(d.length)}if(r||d||s.match(/^\/\/[^@\/]+@[^@\/]+/)){var b="//"===s.substr(0,2);!b||d&&S[d]||(s=s.substr(2),this.slashes=!0)}if(!S[d]&&(b||d&&!x[d])){for(var A=-1,T=0;T<m.length;T++){var k=s.indexOf(m[T]);-1!==k&&(-1===A||k<A)&&(A=k)}var P,E;E=-1===A?s.lastIndexOf("@"):s.lastIndexOf("@",A),-1!==E&&(P=s.slice(0,E),s=s.slice(E+1),this.auth=decodeURIComponent(P)),A=-1;for(var T=0;T<v.length;T++){var k=s.indexOf(v[T]);-1!==k&&(-1===A||k<A)&&(A=k)}-1===A&&(A=s.length),this.host=s.slice(0,A),s=s.slice(A),this.parseHost(),this.hostname=this.hostname||"";var O="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!O)for(var R=this.hostname.split(/\./),T=0,L=R.length;T<L;T++){var D=R[T];if(D&&!D.match(y)){for(var I="",j=0,M=D.length;j<M;j++)D.charCodeAt(j)>127?I+="x":I+=D[j];if(!I.match(y)){var F=R.slice(0,T),N=R.slice(T+1),B=D.match(_);B&&(F.push(B[1]),N.unshift(B[2])),N.length&&(s="/"+N.join(".")+s),this.hostname=F.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),O||(this.hostname=c.toASCII(this.hostname));var U=this.port?":"+this.port:"",z=this.hostname||"";this.host=z+U,this.href+=this.host,O&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==s[0]&&(s="/"+s))}if(!w[p])for(var T=0,L=g.length;T<L;T++){var W=g[T];if(-1!==s.indexOf(W)){var q=encodeURIComponent(W);q===W&&(q=escape(W)),s=s.split(W).join(q)}}var X=s.indexOf("#");-1!==X&&(this.hash=s.substr(X),s=s.slice(0,X));var G=s.indexOf("?");if(-1!==G?(this.search=s.substr(G),this.query=s.substr(G+1),e&&(this.query=C.parse(this.query)),s=s.slice(0,G)):e&&(this.search="",this.query={}),s&&(this.pathname=s),x[p]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var U=this.pathname||"",H=this.search||"";this.path=U+H}return this.href=this.format(),this},i.prototype.format=function(){var t=this.auth||"";t&&(t=encodeURIComponent(t),t=t.replace(/%3A/i,":"),t+="@");var e=this.protocol||"",r=this.pathname||"",i=this.hash||"",n=!1,o="";this.host?n=t+this.host:this.hostname&&(n=t+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(n+=":"+this.port)),this.query&&l.isObject(this.query)&&Object.keys(this.query).length&&(o=C.stringify(this.query));var a=this.search||o&&"?"+o||"";return e&&":"!==e.substr(-1)&&(e+=":"),this.slashes||(!e||x[e])&&!1!==n?(n="//"+(n||""),r&&"/"!==r.charAt(0)&&(r="/"+r)):n||(n=""),i&&"#"!==i.charAt(0)&&(i="#"+i),a&&"?"!==a.charAt(0)&&(a="?"+a),r=r.replace(/[?#]/g,function(t){return encodeURIComponent(t)}),a=a.replace("#","%23"),e+n+r+a+i},i.prototype.resolve=function(t){return this.resolveObject(n(t,!1,!0)).format()},i.prototype.resolveObject=function(t){if(l.isString(t)){var e=new i;e.parse(t,!1,!0),t=e}for(var r=new i,n=Object.keys(this),o=0;o<n.length;o++){var a=n[o];r[a]=this[a]}if(r.hash=t.hash,""===t.href)return r.href=r.format(),r;if(t.slashes&&!t.protocol){for(var s=Object.keys(t),c=0;c<s.length;c++){var h=s[c];"protocol"!==h&&(r[h]=t[h])}return x[r.protocol]&&r.hostname&&!r.pathname&&(r.path=r.pathname="/"),r.href=r.format(),r}if(t.protocol&&t.protocol!==r.protocol){if(!x[t.protocol]){for(var u=Object.keys(t),f=0;f<u.length;f++){var d=u[f];r[d]=t[d]}return r.href=r.format(),r}if(r.protocol=t.protocol,t.host||S[t.protocol])r.pathname=t.pathname;else{for(var p=(t.pathname||"").split("/");p.length&&!(t.host=p.shift()););t.host||(t.host=""),t.hostname||(t.hostname=""),""!==p[0]&&p.unshift(""),p.length<2&&p.unshift(""),r.pathname=p.join("/")}if(r.search=t.search,r.query=t.query,r.host=t.host||"",r.auth=t.auth,r.hostname=t.hostname||t.host,r.port=t.port,r.pathname||r.search){var g=r.pathname||"",v=r.search||"";r.path=g+v}return r.slashes=r.slashes||t.slashes,r.href=r.format(),r}var m=r.pathname&&"/"===r.pathname.charAt(0),b=t.host||t.pathname&&"/"===t.pathname.charAt(0),y=b||m||r.host&&t.pathname,_=y,w=r.pathname&&r.pathname.split("/")||[],p=t.pathname&&t.pathname.split("/")||[],C=r.protocol&&!x[r.protocol];if(C&&(r.hostname="",r.port=null,r.host&&(""===w[0]?w[0]=r.host:w.unshift(r.host)),r.host="",t.protocol&&(t.hostname=null,t.port=null,t.host&&(""===p[0]?p[0]=t.host:p.unshift(t.host)),t.host=null),y=y&&(""===p[0]||""===w[0])),b)r.host=t.host||""===t.host?t.host:r.host,r.hostname=t.hostname||""===t.hostname?t.hostname:r.hostname,r.search=t.search,r.query=t.query,w=p;else if(p.length)w||(w=[]),w.pop(),w=w.concat(p),r.search=t.search,r.query=t.query;else if(!l.isNullOrUndefined(t.search)){if(C){r.hostname=r.host=w.shift();var A=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@");A&&(r.auth=A.shift(),r.host=r.hostname=A.shift())}return r.search=t.search,r.query=t.query,l.isNull(r.pathname)&&l.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!w.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var T=w.slice(-1)[0],k=(r.host||t.host||w.length>1)&&("."===T||".."===T)||""===T,P=0,E=w.length;E>=0;E--)T=w[E],"."===T?w.splice(E,1):".."===T?(w.splice(E,1),P++):P&&(w.splice(E,1),P--);if(!y&&!_)for(;P--;P)w.unshift("..");!y||""===w[0]||w[0]&&"/"===w[0].charAt(0)||w.unshift(""),k&&"/"!==w.join("/").substr(-1)&&w.push("");var O=""===w[0]||w[0]&&"/"===w[0].charAt(0);if(C){r.hostname=r.host=O?"":w.length?w.shift():"";var A=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@");A&&(r.auth=A.shift(),r.host=r.hostname=A.shift())}return y=y||r.host&&w.length,y&&!O&&w.unshift(""),w.length?r.pathname=w.join("/"):(r.pathname=null,r.path=null),l.isNull(r.pathname)&&l.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=t.auth||r.auth,r.slashes=r.slashes||t.slashes,r.href=r.format(),r},i.prototype.parseHost=function(){var t=this.host,e=u.exec(t);e&&(e=e[0],":"!==e&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)}},function(t,e,r){(function(t){var i=r(72),n=r(75),o=r(76),a=r(25),s=e;s.request=function(e,r){e="string"==typeof e?a.parse(e):n(e);var o=-1===t.location.protocol.search(/^https?:$/)?"http:":"",s=e.protocol||o,c=e.hostname||e.host,l=e.port,h=e.path||"/";c&&-1!==c.indexOf(":")&&(c="["+c+"]"),e.url=(c?s+"//"+c:"")+(l?":"+l:"")+h,e.method=(e.method||"GET").toUpperCase(),e.headers=e.headers||{};var u=new i(e);return r&&u.on("response",r),u},s.get=function t(e,r){var i=s.request(e,r);return i.end(),i},s.Agent=function(){},s.Agent.defaultMaxSockets=4,s.STATUS_CODES=o,s.METHODS=["CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REPORT","SEARCH","SUBSCRIBE","TRACE","UNLOCK","UNSUBSCRIBE"]}).call(e,r(0))},function(t,e,r){(function(t){function r(){if(void 0!==o)return o;if(t.XMLHttpRequest){o=new t.XMLHttpRequest;try{o.open("GET",t.XDomainRequest?"/":"https://example.com")}catch(t){o=null}}else o=null;return o}function i(t){var e=r();if(!e)return!1;try{return e.responseType=t,e.responseType===t}catch(t){}return!1}function n(t){return"function"==typeof t}e.fetch=n(t.fetch)&&n(t.ReadableStream),e.blobConstructor=!1;try{new Blob([new ArrayBuffer(1)]),e.blobConstructor=!0}catch(t){}var o,a=void 0!==t.ArrayBuffer,s=a&&n(t.ArrayBuffer.prototype.slice);e.arraybuffer=e.fetch||a&&i("arraybuffer"),e.msstream=!e.fetch&&s&&i("ms-stream"),e.mozchunkedarraybuffer=!e.fetch&&a&&i("moz-chunked-arraybuffer"),e.overrideMimeType=e.fetch||!!r()&&n(r().overrideMimeType),e.vbArray=n(t.VBArray),o=null}).call(e,r(0))},function(t,e){function r(t){throw new Error("Cannot find module '"+t+"'.")}r.keys=function(){return[]},r.resolve=r,t.exports=r,r.id=28},function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t){function e(e){function i(t,e){return e.getPage(1).then(function(e){return A=e,x=A.getViewport(1),t.clientWidth/(x.width*v)})}return(0,l.getDocument)(e).then(function(e){return Promise.all([i(t,e),T.setDocument(e)])}).then(function(t){var e=o(t,1),i=e[0];T.currentScale=i,x=A.getViewport(i),r(x.width*v,x.height*v)})}function r(e,r){var i=document.createElement("canvas");i.id=s.default.generate(),i.width=e,i.height=r,t.appendChild(i),C=new h.fabric.Canvas(i.id),C.selection=!1,h.fabric.util.addListener(document.getElementsByClassName("upper-canvas")[0],"contextmenu",function(t){var e=C.getPointer(t),r=C.findTarget(t);w.emit("contextmenu",t,e,r),t.preventDefault()}),C.on("mouse:dblclick",function(t){var e=C.getPointer(t.e);w.emit("mouse:dblclick",t.e,e),t.e.preventDefault()}),C.on("mouse:up",function(t){var e=C.getPointer(t.e),r=C.findTarget(t.e);w.emit("mouse:up",t.e,e,r),t.e.preventDefault()}),C.on("mouse:down",function(t){var e=C.getPointer(t.e),r=C.findTarget(t.e);w.emit("mouse:down",t.e,e,r),t.e.preventDefault()}),C.on("mouse:wheel",function(t){var e=(0,p.default)(t.e).pixelY/3600;w.emit("mouse:wheel",t.e,e),t.e.preventDefault()}),C.on("object:selected",function(t){var e=t.target;w.emit("object:selected",e)})}function i(t,e){function r(e){return new Promise(function(r){h.fabric.Image.fromURL(e,function(e){e.top=t.y-e.height,e.left=t.x-e.width/2,e.topRate=t.y/C.height,e.leftRate=t.x/C.width,e.opacity=w.pinOpacity,e.hasControls=!1,e.hasRotatingPoint=!1;var i=b(t),n=o(i,2),s=n[0],c=n[1];e.pdfPoint={x:s,y:c},e.index=C.size(),e.on("moving",function(t){return y(t,e)}),Object.assign(e,a),C.add(e),r(e)})})}var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return e&&(w.pinImgURL=e),i.text?n(w.pinImgURL,i).then(r):r(w.pinImgURL)}function n(e,r){return new Promise(function(i){h.fabric.Image.fromURL(e,function(e){var n=document.createElement("canvas");n.id=s.default.generate(),n.width=e.width,n.height=e.height,n.style.display="none",t.appendChild(n);var o=new h.fabric.Canvas(n.id);e.left=0,e.top=0,o.add(e);var a=new h.fabric.Text(r.text,{fontSize:r.fontSize||20,fill:r.color||"red",fontFamily:r.fontFamily||"Comic Sans",fontWeight:r.fontWeight||"normal"});a.left=e.left+(e.width-a.width)/2,a.top=e.top+(e.height-a.height)/2.5,o.add(a),i(o.toDataURL()),o.dispose(),t.removeChild(n)})})}function a(t,e,r,n){var a=x.convertToViewportPoint(t.x,t.y),s=o(a,2);return i({x:s[0],y:s[1]},e,r,n)}function c(t,e,r,n,o){return i({x:t*C.width,y:e*C.height},r,n,o)}function u(t){var e=C.item(t);e&&(C.remove(e),e.text&&C.remove(e.text))}function d(t){}function m(t){var e=T.currentScale,r=e+t,i=r/e;T.currentScale=r,x=A.getViewport(r);var n=C.getHeight(),o=C.getWidth();C.setHeight(n*i),C.setWidth(o*i),C.getObjects().forEach(function(t){t.set("top",C.height*t.topRate-t.height),t.set("left",C.width*t.leftRate-t.width/2),t.setCoords()}),C.renderAll(),C.calcOffset()}function b(t){return x.convertToPdfPoint(t.x,t.y)}function y(t,e){e.topRate=(e.top+e.height)/C.height,e.leftRate=(e.left+e.width/2)/C.width;var r=b({x:e.left+e.width/2,y:e.top+e.height}),i=o(r,2),n=i[0],a=i[1];e.pdfPoint={x:n,y:a},e.setCoords(),w.emit("object:moving",e)}var _=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};f.default.call(this);var w=this;w.load=e,w.addPin=i,w.addPinWithRate=c,w.addPinWithPdfPoint=a,w.removePin=u,w.zoomIn=m,w.zoomOut=d,w.pinImgURL=_.pinImgURL||"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACEAAAAvCAYAAABt7qMfAAAJKklEQVRYR61YfXBU1RX/nfdYEoyQooKY7AappaWDBUuKu+8ljKGVFMpQsQOCfLT8g6NQC1ItVSvy0TLaGaso2kFrrJXWqSgWYaCIpZnKvrcJRGescawoluwGUygfgkCy+947nfNyN25eNiSLPX8l+84593fPPR+/ewn9lLZx40oyJSW1xHyjRzSeiCrAfBmASwCcB3ACzCkA/yTgjY5MZvc1TU2f9sc99aXUZprDM0AtmOcCqAZQ2pcNgM8AWABeYk3bVRGPH7mQTa8gmseOHThkyJBZRLSCmccDGBBw5IFIdp8GEAIwNK8O0Axgg55Ov1jW1HQuH5i8ID6qrCwdGArdC6IfAyjJMTzhh5v5gEf0HjE3a7p+ymUeogFjGLiWmScQIKCH5diliehZraNjVVlT03+DQHqAaJ04MeLp+noQzQeQ/d4C5hcBvBo6d+7dEe+8c7a38CYNY5DO/HWX6CYA4uOarC4RvaYxryyz7fdz7buB+Lim5ksDOjqeAzCzS4n576Tr94Xj8UQ/cqGbSso0r2Pm9QCm5myoPkQ0Z4RlHe0Cl/3j4LRpRcWnTq0GsFIZuGCuC2naL3INCgVyuLp6qOY4q0F0h8odcfFk6OzZldmIdkUiaZoLwPw0gEGixcCmQZp2z7B4/EyhCwf15YiIeR0TrVAbdBhYXmHbT4quD+JQNHplSNO2A5ioHOwNEd3aWwQYoLZJk65wHGeE53mleih0Jp3JtI1qaDhGgJcPtESEXPd5Amao78060fQyyzrsg2iJxRZJ9gLQAJz2PG/WyIaGPfmc/XvSpKt0x7kdwM0ARqhm1U7AUSbarmUyG8v370/ms02ZpsHMfwEw3P/O/JNIIvEEHauqGtzBvJmZv6+O4dGj6fTKbzU1ZYKOUqY53WNeS8A3cxItqNYM5lWRRGJr8INEMBWLrQKR5J5Ifcbz5lLSMGRHzwMYDOC4zlxblki8ledcJcMlWmU5304DkJy5NNBJjzGwrMK2pay7yRHDGOMCbwAoByCNbgmlTPMRZpaEEflHUVHR9OH19dJ2uyQVjYY9TdtGwAT1YyuYn9GI9njAUdK0K9jzagDcBmCUr0P0AZinR2z7w1xffhWePLkVRN/z1Zifo2QsthdEk5XihohtLw+ibzHNJcTsZ7LkDAM/qrBtOdtu0hqLyXD7U7ZbEvP94URC+kQ3SZrmajA/qH58W47jAwCjFfplEct6PNeCZ8/WW5PJzUwkA0yS6fFwcfFPqb7eCTr3z9wwHgAgZ05g3tk+dOgPRu/a1ZGrqwqhTuXVEQEhE+4qdJbWwohty0665GA0OqSYaDeIYgDOep43dWRDw74ggOz/qerq8ey6fwNwOYD3QkSTg6WejMWmgUgiORBAhyBvY+BKAC4xzwsnEi/lLiD1rXveHmauBHBSZ74xX+JmbZLR6GhoWr1K4EPkeTeEGxqEZ3RJi2kKL3kNQJG/btIwDgL4igq1X7e5BtLtAOwA8G0AGQLmh217S2+ROByNTtE0TXYpZKcxnU7XBslNyjQXMrNUJBHwH6mO15l5ijgl5qfCicTSHolkGAJMxjqIaA8c59ZwY+PxoJ7qOc8w8xz17YWwbS8KdtEW0/wVMd+ndA7IcaxlQJJJpNHT9akj9+07mSd80nyEWzCYf8e6vjqXMX0yadIwx3HuV2B1vwcQzYtY1iu5vhRNlKOQyIpspFRV1WT2vD+rsvqUNG1qcGwfqay8xA2FNoFoQY5Dm5lf1oAUE0liy/i/IdtJGdieSacXBo8iaRjfQGezktb9GYgWkU/jSkvrwCwERErw4XAicS/5g/Rz8bkm86MA5gWOwQUgO+8SATCA6E4ZTj2O1jRXgvkh9fuOds+b7w8wlSi/VwOs1dO0746Mx4UbdpPU9ddfzpomvV96RucQ6i4nQLTVyWQeGLV/f1vw4+Hq6i9rnrcLzF/190u0tMKynvJBHKmurnBd93UAX1OGD0Zse22eRcA1NQM+aW8f5wA1BIwB0aUgErr3ITyv/vSZM2+PbW6WmdBDkoaxDMBj6kOLpmm15fH4v7pITYth/IaAu5TCu47jTMm3m6BnBrTeOESurqKOOwEY6ve6sG0vFtvPQZjmRGJ+GUAFAGnJt0dsW6bm/0VShjGbgT8AKAZwjIjmhi1rrzjvRnQD5fo+ue5N4cZGmS1fSJKGIWP71SxzY+CxiG2vyCZ/dxCdfX+XmiWycK+5UQgqlQtSWbLecSKaEbYsO+ujGwg1BUVZEkjkI0/Xa0fu23eokEVzdVuqqsrI8/4KQPqDzx/KI5HFtGWLlLYvPS4/agBJd7y2U4PWhMvL1+UaFQIoZRjLGXhElf8hnXl2cADmvQYqErNRgTzFwNwK295dyOKi2xqLVXlEkuxCiGVDP49Y1sNBP/lBSAhddyeI5E4pXfQVp7h4waj6+vb+ApF+0ppOyzBbpGwOqrnU42h7vZW3xGJziGiTIrDnifmOcCIh47df0mIYM6mzJIVAnyei5WHLkstVD+kVhOwk2dHxLAE/zO4Enjc90tAg/OOCIsSYOy9T1ynFrU5R0fzeInnBR5IjsdgEl0icddJ8oifC5eV39ZWkKdP8JTPLWBc5zpp2c0U8/mZvyC8Iwi9Z03wIzD9TDo5pwMxy25ZXmLySjEbHQdd3gDmiFJ4Oh8NLLgS8z+cif3Lq+mZ1vRe/luY4c/Nd9dS4l2k8TQF4kzxvXpBjBtH3CUIMFDEVhiQ3LamW1ZFEYk3QWUsstoKIpCeIdMhDS5BZ5Qtfv0AI8SkdPHg9E8nFSAhMijRtdi4DU4xJ5kP2ZaZOT6fv7O2dKhdMv0CIQdIwLiOibcwsL3hCu+Ku48ySce8/hLjuH7PHwMBb0LQZfb3aZYH0G4R/LN1r32/pEctarY7h1ypK7SBaHLEsyaN+SUEg/C7Y3r6BiZaId7kzeMA6DbibgavVii84RUW3FdJdCwIhi6hHErnyC7MWEWonFx3xdcB13Vuubmz8uF8hUEoFgxC7lGF8hwGpltzX3XNMNK/CsrYVAkBFtFAT4EBlZWj4wIFrCLhHveLKZfq3TlHR3YUcw0UlZi5cuUmlS0rqCLhFngC8AQMWBG9u/d3eRR1H1nkyFqsBkbzILQ3btlyaL0r+B7tw5ax4J5d3AAAAAElFTkSuQmCC",w.pinOpacity=_.pinOpacity||1;var S=document.createElement("div");S.id=s.default.generate(),S.style.position="absolute",t.appendChild(S);var x=null,C=null,A=null,T=new g({container:t,viewer:S})}Object.defineProperty(e,"__esModule",{value:!0});var o=function(){function t(t,e){var r=[],i=!0,n=!1,o=void 0;try{for(var a=t[Symbol.iterator](),s;!(i=(s=a.next()).done)&&(r.push(s.value),!e||r.length!==e);i=!0);}catch(t){n=!0,o=t}finally{try{!i&&a.return&&a.return()}finally{if(n)throw o}}return r}return function(e,r){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return t(e,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),a=r(30),s=i(a);r(38);var c=r(39),l=r(61),h=r(63),u=r(79),f=i(u),d=r(80),p=i(d),g=c.PDFJS.PDFViewer,v=96/72;c.PDFJS.disableTextLayer=!0,h.fabric.devicePixelRatio=1,n.prototype=Object.create(f.default.prototype),n.prototype.constructor=n,e.default=n},function(t,e,r){"use strict";t.exports=r(31)},function(t,e,r){"use strict";function i(e){return s.seed(e),t.exports}function n(e){return f=e,t.exports}function o(t){return void 0!==t&&s.characters(t),s.shuffled()}function a(){return h(f)}var s=r(6),c=r(11),l=r(34),h=r(35),u=r(36),f=r(37)||0;t.exports=a,t.exports.generate=a,t.exports.seed=i,t.exports.worker=n,t.exports.characters=o,t.exports.decode=l,t.exports.isValid=u},function(t,e,r){"use strict";function i(){return(o=(9301*o+49297)%233280)/233280}function n(t){o=t}var o=1;t.exports={nextValue:i,seed:n}},function(t,e,r){"use strict";function i(){if(!n||!n.getRandomValues)return 48&Math.floor(256*Math.random());var t=new Uint8Array(1);return n.getRandomValues(t),48&t[0]}var n="object"==typeof window&&(window.crypto||window.msCrypto);t.exports=i},function(t,e,r){"use strict";function i(t){var e=n.shuffled();return{version:15&e.indexOf(t.substr(0,1)),worker:15&e.indexOf(t.substr(1,1))}}var n=r(6);t.exports=i},function(t,e,r){"use strict";function i(t){var e="",r=Math.floor(.001*(Date.now()-a));return r===l?c++:(c=0,l=r),e+=n(o.lookup,s),e+=n(o.lookup,t),c>0&&(e+=n(o.lookup,c)),e+=n(o.lookup,r)}var n=r(11),o=r(6),a=1459707606518,s=6,c,l;t.exports=i},function(t,e,r){"use strict";function i(t){if(!t||"string"!=typeof t||t.length<6)return!1;for(var e=n.characters(),r=t.length,i=0;i<r;i++)if(-1===e.indexOf(t[i]))return!1;return!0}var n=r(6);t.exports=i},function(t,e,r){"use strict";t.exports=0},function(t,e,r){(function(e){!function e(r,i){t.exports=i()}(this,function(){return function(t){function e(i){if(r[i])return r[i].exports;var n=r[i]={i:i,l:!1,exports:{}};return t[i].call(n.exports,n,n.exports,e),n.l=!0,n.exports}var r={};return e.m=t,e.c=r,e.i=function(t){return t},e.d=function(t,r,i){e.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var r=t&&t.__esModule?function e(){return t.default}:function e(){return t};return e.d(r,"a",r),r},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=1)}([function(t,r,i){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};if("undefined"==typeof PDFJS||!PDFJS.compatibilityChecked){var o="undefined"!=typeof window&&window.Math===Math?window:void 0!==e&&e.Math===Math?e:"undefined"!=typeof self&&self.Math===Math?self:void 0,a="undefined"!=typeof navigator&&navigator.userAgent||"",s=/Android/.test(a),c=/Android\s[0-2][^\d]/.test(a),l=/Android\s[0-4][^\d]/.test(a),h=a.indexOf("Chrom")>=0,u=/Chrome\/(39|40)\./.test(a),f=a.indexOf("CriOS")>=0,d=a.indexOf("Trident")>=0,p=/\b(iPad|iPhone|iPod)(?=;)/.test(a),g=a.indexOf("Opera")>=0,v=/Safari\//.test(a)&&!/(Chrome\/|Android\s)/.test(a),m="object"===("undefined"==typeof window?"undefined":n(window))&&"object"===("undefined"==typeof document?"undefined":n(document));"undefined"==typeof PDFJS&&(o.PDFJS={}),PDFJS.compatibilityChecked=!0,function t(){function e(t,e){return new c(this.slice(t,e))}function r(t,e){arguments.length<2&&(e=0);for(var r=0,i=t.length;r<i;++r,++e)this[e]=255&t[r]}function i(t,e){this.buffer=t,this.byteLength=t.length,this.length=e,s(this.length)}function a(t){return{get:function e(){var r=this.buffer,i=t<<2;return(r[i]|r[i+1]<<8|r[i+2]<<16|r[i+3]<<24)>>>0},set:function e(r){var i=this.buffer,n=t<<2;i[n]=255&r,i[n+1]=r>>8&255,i[n+2]=r>>16&255,i[n+3]=r>>>24&255}}}function s(t){for(;l<t;)Object.defineProperty(i.prototype,l,a(l)),l++}function c(t){var i,o,a;if("number"==typeof t)for(i=[],o=0;o<t;++o)i[o]=0;else if("slice"in t)i=t.slice(0);else for(i=[],o=0,a=t.length;o<a;++o)i[o]=t[o];return i.subarray=e,i.buffer=i,i.byteLength=i.length,i.set=r,"object"===(void 0===t?"undefined":n(t))&&t.buffer&&(i.buffer=t.buffer),i}if("undefined"!=typeof Uint8Array)return void 0===Uint8Array.prototype.subarray&&(Uint8Array.prototype.subarray=function t(e,r){return new Uint8Array(this.slice(e,r))},Float32Array.prototype.subarray=function t(e,r){return new Float32Array(this.slice(e,r))}),void("undefined"==typeof Float64Array&&(o.Float64Array=Float32Array));i.prototype=Object.create(null);var l=0;o.Uint8Array=c,o.Int8Array=c,o.Int32Array=c,o.Uint16Array=c,o.Float32Array=c,o.Float64Array=c,o.Uint32Array=function(){if(3===arguments.length){if(0!==arguments[1])throw new Error("offset !== 0 is not supported");return new i(arguments[0],arguments[2])}return c.apply(this,arguments)}}(),function t(){if(m&&window.CanvasPixelArray){var e=window.CanvasPixelArray.prototype;"buffer"in e||(Object.defineProperty(e,"buffer",{get:function t(){return this},enumerable:!1,configurable:!0}),Object.defineProperty(e,"byteLength",{get:function t(){return this.length},enumerable:!1,configurable:!0}))}}(),function t(){o.URL||(o.URL=o.webkitURL)}(),function t(){if(void 0!==Object.defineProperty){var e=!0;try{m&&Object.defineProperty(new Image,"id",{value:"test"});var r=function t(){};r.prototype={get id(){}},Object.defineProperty(new r,"id",{value:"",configurable:!0,enumerable:!0,writable:!1})}catch(t){e=!1}if(e)return}Object.defineProperty=function t(e,r,i){delete e[r],"get"in i&&e.__defineGetter__(r,i.get),"set"in i&&e.__defineSetter__(r,i.set),"value"in i&&(e.__defineSetter__(r,function t(e){return this.__defineGetter__(r,function t(){return e}),e}),e[r]=i.value)}}(),function t(){if("undefined"!=typeof XMLHttpRequest){var e=XMLHttpRequest.prototype,r=new XMLHttpRequest;if("overrideMimeType"in r||Object.defineProperty(e,"overrideMimeType",{value:function t(e){}}),!("responseType"in r)){if(Object.defineProperty(e,"responseType",{get:function t(){return this._responseType||"text"},set:function t(e){"text"!==e&&"arraybuffer"!==e||(this._responseType=e,"arraybuffer"===e&&"function"==typeof this.overrideMimeType&&this.overrideMimeType("text/plain; charset=x-user-defined"))}}),"undefined"!=typeof VBArray)return void Object.defineProperty(e,"response",{get:function t(){return"arraybuffer"===this.responseType?new Uint8Array(new VBArray(this.responseBody).toArray()):this.responseText}});Object.defineProperty(e,"response",{get:function t(){if("arraybuffer"!==this.responseType)return this.responseText;var e=this.responseText,r,i=e.length,n=new Uint8Array(i);for(r=0;r<i;++r)n[r]=255&e.charCodeAt(r);return n.buffer}})}}}(),function t(){if(!("btoa"in o)){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";o.btoa=function(t){var r="",i,n;for(i=0,n=t.length;i<n;i+=3){var o=255&t.charCodeAt(i),a=255&t.charCodeAt(i+1),s=255&t.charCodeAt(i+2),c=o>>2,l=(3&o)<<4|a>>4,h=i+1<n?(15&a)<<2|s>>6:64,u=i+2<n?63&s:64;r+=e.charAt(c)+e.charAt(l)+e.charAt(h)+e.charAt(u)}return r}}}(),function t(){if(!("atob"in o)){o.atob=function(t){if(t=t.replace(/=+$/,""),t.length%4==1)throw new Error("bad atob input");for(var e=0,r,i,n=0,o="";i=t.charAt(n++);~i&&(r=e%4?64*r+i:i,e++%4)?o+=String.fromCharCode(255&r>>(-2*e&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return o}}}(),function t(){void 0===Function.prototype.bind&&(Function.prototype.bind=function t(e){var r=this,i=Array.prototype.slice.call(arguments,1);return function t(){var n=i.concat(Array.prototype.slice.call(arguments));return r.apply(e,n)}})}(),function t(){if(m){"dataset"in document.createElement("div")||Object.defineProperty(HTMLElement.prototype,"dataset",{get:function t(){if(this._dataset)return this._dataset;for(var e={},r=0,i=this.attributes.length;r<i;r++){var n=this.attributes[r];if("data-"===n.name.substring(0,5)){e[n.name.substring(5).replace(/\-([a-z])/g,function(t,e){return e.toUpperCase()})]=n.value}}return Object.defineProperty(this,"_dataset",{value:e,writable:!1,enumerable:!1}),e},enumerable:!0})}}(),function t(){function e(t,e,r,i){var n=t.className||"",o=n.split(/\s+/g);""===o[0]&&o.shift();var a=o.indexOf(e);return a<0&&r&&o.push(e),a>=0&&i&&o.splice(a,1),t.className=o.join(" "),a>=0}if(m){if(!("classList"in document.createElement("div"))){var r={add:function t(r){e(this.element,r,!0,!1)},contains:function t(r){return e(this.element,r,!1,!1)},remove:function t(r){e(this.element,r,!1,!0)},toggle:function t(r){e(this.element,r,!0,!0)}};Object.defineProperty(HTMLElement.prototype,"classList",{get:function t(){if(this._classList)return this._classList;var e=Object.create(r,{element:{value:this,writable:!1,enumerable:!0}});return Object.defineProperty(this,"_classList",{value:e,writable:!1,enumerable:!1}),e},enumerable:!0})}}}(),function t(){if(!("undefined"==typeof importScripts||"console"in o)){var e={},r={log:function t(){var e=Array.prototype.slice.call(arguments);o.postMessage({targetName:"main",action:"console_log",data:e})},error:function t(){var e=Array.prototype.slice.call(arguments);o.postMessage({targetName:"main",action:"console_error",data:e})},time:function t(r){e[r]=Date.now()},timeEnd:function t(r){var i=e[r];if(!i)throw new Error("Unknown timer name "+r);this.log("Timer:",r,Date.now()-i)}};o.console=r}}(),function t(){if(m)"console"in window?"bind"in console.log||(console.log=function(t){return function(e){return t(e)}}(console.log),console.error=function(t){return function(e){return t(e)}}(console.error),console.warn=function(t){return function(e){return t(e)}}(console.warn)):window.console={log:function t(){},error:function t(){},warn:function t(){}}}(),function t(){function e(t){r(t.target)&&t.stopPropagation()}function r(t){return t.disabled||t.parentNode&&r(t.parentNode)}g&&document.addEventListener("click",e,!0)}(),function t(){(d||f)&&(PDFJS.disableCreateObjectURL=!0)}(),function t(){"undefined"!=typeof navigator&&("language"in navigator||(PDFJS.locale=navigator.userLanguage||"en-US"))}(),function t(){(v||c||u||p)&&(PDFJS.disableRange=!0,PDFJS.disableStream=!0)}(),function t(){m&&(history.pushState&&!c||(PDFJS.disableHistory=!0))}(),function t(){if(m)if(window.CanvasPixelArray)"function"!=typeof window.CanvasPixelArray.prototype.set&&(window.CanvasPixelArray.prototype.set=function(t){for(var e=0,r=this.length;e<r;e++)this[e]=t[e]});else{var e=!1,r;if(h?(r=a.match(/Chrom(e|ium)\/([0-9]+)\./),e=r&&parseInt(r[2])<21):s?e=l:v&&(r=a.match(/Version\/([0-9]+)\.([0-9]+)\.([0-9]+) Safari\//),e=r&&parseInt(r[1])<6),e){var i=window.CanvasRenderingContext2D.prototype,n=i.createImageData;i.createImageData=function(t,e){var r=n.call(this,t,e);return r.data.set=function(t){for(var e=0,r=this.length;e<r;e++)this[e]=t[e]},r},i=null}}}(),function t(){function e(){window.requestAnimationFrame=function(t){return window.setTimeout(t,20)},window.cancelAnimationFrame=function(t){window.clearTimeout(t)}}if(m)p?e():"requestAnimationFrame"in window||(window.requestAnimationFrame=window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame,window.requestAnimationFrame||e())}(),function t(){(p||s)&&(PDFJS.maxCanvasPixels=5242880)}(),function t(){m&&d&&window.parent!==window&&(PDFJS.disableFullscreen=!0)}(),function t(){m&&("currentScript"in document||Object.defineProperty(document,"currentScript",{get:function t(){var e=document.getElementsByTagName("script");return e[e.length-1]},enumerable:!0,configurable:!0}))}(),function t(){if(m){var e=document.createElement("input");try{e.type="number"}catch(t){var r=e.constructor.prototype,i=Object.getOwnPropertyDescriptor(r,"type");Object.defineProperty(r,"type",{get:function t(){return i.get.call(this)},set:function t(e){i.set.call(this,"number"===e?"text":e)},enumerable:!0,configurable:!0})}}}(),function t(){if(m&&document.attachEvent){var e=document.constructor.prototype,r=Object.getOwnPropertyDescriptor(e,"readyState");Object.defineProperty(e,"readyState",{get:function t(){var e=r.get.call(this);return"interactive"===e?"loading":e},set:function t(e){r.set.call(this,e)},enumerable:!0,configurable:!0})}}(),function t(){m&&void 0===Element.prototype.remove&&(Element.prototype.remove=function(){this.parentNode&&this.parentNode.removeChild(this)})}(),function t(){Number.isNaN||(Number.isNaN=function(t){return"number"==typeof t&&isNaN(t)})}(),function t(){Number.isInteger||(Number.isInteger=function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t})}(),function t(){if(o.Promise)return"function"!=typeof o.Promise.all&&(o.Promise.all=function(t){var e=0,r=[],i,n,a=new o.Promise(function(t,e){i=t,n=e});return t.forEach(function(t,o){e++,t.then(function(t){r[o]=t,0===--e&&i(r)},n)}),0===e&&i(r),a}),"function"!=typeof o.Promise.resolve&&(o.Promise.resolve=function(t){return new o.Promise(function(e){e(t)})}),"function"!=typeof o.Promise.reject&&(o.Promise.reject=function(t){return new o.Promise(function(e,r){r(t)})}),void("function"!=typeof o.Promise.prototype.catch&&(o.Promise.prototype.catch=function(t){return o.Promise.prototype.then(void 0,t)}));var e=0,r=1,i=2,n=500,a={handlers:[],running:!1,unhandledRejections:[],pendingRejectionCheck:!1,scheduleHandlers:function t(e){0!==e._status&&(this.handlers=this.handlers.concat(e._handlers),e._handlers=[],this.running||(this.running=!0,setTimeout(this.runHandlers.bind(this),0)))},runHandlers:function t(){for(var e=1,r=Date.now()+1;this.handlers.length>0;){var n=this.handlers.shift(),o=n.thisPromise._status,a=n.thisPromise._value;try{1===o?"function"==typeof n.onResolve&&(a=n.onResolve(a)):"function"==typeof n.onReject&&(a=n.onReject(a),o=1,n.thisPromise._unhandledRejection&&this.removeUnhandeledRejection(n.thisPromise))}catch(t){o=i,a=t}if(n.nextPromise._updateStatus(o,a),Date.now()>=r)break}if(this.handlers.length>0)return void setTimeout(this.runHandlers.bind(this),0);this.running=!1},addUnhandledRejection:function t(e){this.unhandledRejections.push({promise:e,time:Date.now()}),this.scheduleRejectionCheck()},removeUnhandeledRejection:function t(e){e._unhandledRejection=!1;for(var r=0;r<this.unhandledRejections.length;r++)this.unhandledRejections[r].promise===e&&(this.unhandledRejections.splice(r),r--)},scheduleRejectionCheck:function t(){var e=this;this.pendingRejectionCheck||(this.pendingRejectionCheck=!0,setTimeout(function(){e.pendingRejectionCheck=!1;for(var t=Date.now(),r=0;r<e.unhandledRejections.length;r++)if(t-e.unhandledRejections[r].time>500){var i=e.unhandledRejections[r].promise._value,n="Unhandled rejection: "+i;i.stack&&(n+="\n"+i.stack);try{throw new Error(n)}catch(t){console.warn(n)}e.unhandledRejections.splice(r),r--}e.unhandledRejections.length&&e.scheduleRejectionCheck()},500))}},s=function t(e){this._status=0,this._handlers=[];try{e.call(this,this._resolve.bind(this),this._reject.bind(this))}catch(t){this._reject(t)}};s.all=function t(e){function r(t){a._status!==i&&(l=[],o(t))}var n,o,a=new s(function(t,e){n=t,o=e}),c=e.length,l=[];if(0===c)return n(l),a;for(var h=0,u=e.length;h<u;++h){var f=e[h],d=function(t){return function(e){a._status!==i&&(l[t]=e,0===--c&&n(l))}}(h);s.isPromise(f)?f.then(d,r):d(f)}return a},s.isPromise=function t(e){return e&&"function"==typeof e.then},s.resolve=function t(e){return new s(function(t){t(e)})},s.reject=function t(e){return new s(function(t,r){r(e)})},s.prototype={_status:null,_value:null,_handlers:null,_unhandledRejection:null,_updateStatus:function t(e,r){if(1!==this._status&&this._status!==i){if(1===e&&s.isPromise(r))return void r.then(this._updateStatus.bind(this,1),this._updateStatus.bind(this,i));this._status=e,this._value=r,e===i&&0===this._handlers.length&&(this._unhandledRejection=!0,a.addUnhandledRejection(this)),a.scheduleHandlers(this)}},_resolve:function t(e){this._updateStatus(1,e)},_reject:function t(e){this._updateStatus(i,e)},then:function t(e,r){var i=new s(function(t,e){this.resolve=t,this.reject=e});return this._handlers.push({thisPromise:this,onResolve:e,onReject:r,nextPromise:i}),a.scheduleHandlers(this),i},catch:function t(e){return this.then(void 0,e)}},o.Promise=s}(),function t(){function e(){this.id="$weakmap"+r++}if(!o.WeakMap){var r=0;e.prototype={has:function t(e){return("object"===(void 0===e?"undefined":n(e))||"function"==typeof e)&&null!==e&&!!Object.getOwnPropertyDescriptor(e,this.id)},get:function t(e){return this.has(e)?e[this.id]:void 0},set:function t(e,r){Object.defineProperty(e,this.id,{value:r,enumerable:!1,configurable:!0})},delete:function t(e){delete e[this.id]}},o.WeakMap=e}}(),function t(){function e(t){return void 0!==d[t]}function r(){l.call(this),this._isInvalid=!0}function i(t){return""===t&&r.call(this),t.toLowerCase()}function a(t){var e=t.charCodeAt(0);return e>32&&e<127&&-1===[34,35,60,62,63,96].indexOf(e)?t:encodeURIComponent(t)}function s(t){var e=t.charCodeAt(0);return e>32&&e<127&&-1===[34,35,60,62,96].indexOf(e)?t:encodeURIComponent(t)}function c(t,n,o){function c(t){y.push(t)}var l=n||"scheme start",h=0,u="",f=!1,b=!1,y=[];t:for(;(t[h-1]!==g||0===h)&&!this._isInvalid;){var _=t[h];switch(l){case"scheme start":if(!_||!v.test(_)){if(n){c("Invalid scheme.");break t}u="",l="no scheme";continue}u+=_.toLowerCase(),l="scheme";break;case"scheme":if(_&&m.test(_))u+=_.toLowerCase();else{if(":"!==_){if(n){if(_===g)break t;c("Code point not allowed in scheme: "+_);break t}u="",h=0,l="no scheme";continue}if(this._scheme=u,u="",n)break t;e(this._scheme)&&(this._isRelative=!0),l="file"===this._scheme?"relative":this._isRelative&&o&&o._scheme===this._scheme?"relative or authority":this._isRelative?"authority first slash":"scheme data"}break;case"scheme data":"?"===_?(this._query="?",l="query"):"#"===_?(this._fragment="#",l="fragment"):_!==g&&"\t"!==_&&"\n"!==_&&"\r"!==_&&(this._schemeData+=a(_));break;case"no scheme":if(o&&e(o._scheme)){l="relative";continue}c("Missing scheme."),r.call(this);break;case"relative or authority":if("/"!==_||"/"!==t[h+1]){c("Expected /, got: "+_),l="relative";continue}l="authority ignore slashes";break;case"relative":if(this._isRelative=!0,"file"!==this._scheme&&(this._scheme=o._scheme),_===g){this._host=o._host,this._port=o._port,this._path=o._path.slice(),this._query=o._query,this._username=o._username,this._password=o._password;break t}if("/"===_||"\\"===_)"\\"===_&&c("\\ is an invalid code point."),l="relative slash";else if("?"===_)this._host=o._host,this._port=o._port,this._path=o._path.slice(),this._query="?",this._username=o._username,this._password=o._password,l="query";else{if("#"!==_){var w=t[h+1],S=t[h+2];("file"!==this._scheme||!v.test(_)||":"!==w&&"|"!==w||S!==g&&"/"!==S&&"\\"!==S&&"?"!==S&&"#"!==S)&&(this._host=o._host,this._port=o._port,this._username=o._username,this._password=o._password,this._path=o._path.slice(),this._path.pop()),l="relative path";continue}this._host=o._host,this._port=o._port,this._path=o._path.slice(),this._query=o._query,this._fragment="#",this._username=o._username,this._password=o._password,l="fragment"}break;case"relative slash":if("/"!==_&&"\\"!==_){"file"!==this._scheme&&(this._host=o._host,this._port=o._port,this._username=o._username,this._password=o._password),l="relative path";continue}"\\"===_&&c("\\ is an invalid code point."),l="file"===this._scheme?"file host":"authority ignore slashes";break;case"authority first slash":if("/"!==_){c("Expected '/', got: "+_),l="authority ignore slashes";continue}l="authority second slash";break;case"authority second slash":if(l="authority ignore slashes","/"!==_){c("Expected '/', got: "+_);continue}break;case"authority ignore slashes":if("/"!==_&&"\\"!==_){l="authority";continue}c("Expected authority, got: "+_);break;case"authority":if("@"===_){f&&(c("@ already seen."),u+="%40"),f=!0;for(var x=0;x<u.length;x++){var C=u[x];if("\t"!==C&&"\n"!==C&&"\r"!==C)if(":"!==C||null!==this._password){var A=a(C);null!==this._password?this._password+=A:this._username+=A}else this._password="";else c("Invalid whitespace in authority.")}u=""}else{if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_){h-=u.length,u="",l="host";continue}u+=_}break;case"file host":if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_){2!==u.length||!v.test(u[0])||":"!==u[1]&&"|"!==u[1]?0===u.length?l="relative path start":(this._host=i.call(this,u),u="",l="relative path start"):l="relative path";continue}"\t"===_||"\n"===_||"\r"===_?c("Invalid whitespace in file host."):u+=_;break;case"host":case"hostname":if(":"!==_||b){if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_){if(this._host=i.call(this,u),u="",l="relative path start",n)break t;continue}"\t"!==_&&"\n"!==_&&"\r"!==_?("["===_?b=!0:"]"===_&&(b=!1),u+=_):c("Invalid code point in host/hostname: "+_)}else if(this._host=i.call(this,u),u="",l="port","hostname"===n)break t;break;case"port":if(/[0-9]/.test(_))u+=_;else{if(_===g||"/"===_||"\\"===_||"?"===_||"#"===_||n){if(""!==u){var T=parseInt(u,10);T!==d[this._scheme]&&(this._port=T+""),u=""}if(n)break t;l="relative path start";continue}"\t"===_||"\n"===_||"\r"===_?c("Invalid code point in port: "+_):r.call(this)}break;case"relative path start":if("\\"===_&&c("'\\' not allowed in path."),l="relative path","/"!==_&&"\\"!==_)continue;break;case"relative path":if(_!==g&&"/"!==_&&"\\"!==_&&(n||"?"!==_&&"#"!==_))"\t"!==_&&"\n"!==_&&"\r"!==_&&(u+=a(_));else{"\\"===_&&c("\\ not allowed in relative path.");var k;(k=p[u.toLowerCase()])&&(u=k),".."===u?(this._path.pop(),"/"!==_&&"\\"!==_&&this._path.push("")):"."===u&&"/"!==_&&"\\"!==_?this._path.push(""):"."!==u&&("file"===this._scheme&&0===this._path.length&&2===u.length&&v.test(u[0])&&"|"===u[1]&&(u=u[0]+":"),this._path.push(u)),u="","?"===_?(this._query="?",l="query"):"#"===_&&(this._fragment="#",l="fragment")}break;case"query":n||"#"!==_?_!==g&&"\t"!==_&&"\n"!==_&&"\r"!==_&&(this._query+=s(_)):(this._fragment="#",l="fragment");break;case"fragment":_!==g&&"\t"!==_&&"\n"!==_&&"\r"!==_&&(this._fragment+=_)}h++}}function l(){this._scheme="",this._schemeData="",this._username="",this._password=null,this._host="",this._port="",this._path=[],this._query="",this._fragment="",this._isInvalid=!1,this._isRelative=!1}function h(t,e){void 0===e||e instanceof h||(e=new h(String(e))),this._url=t,l.call(this);var r=t.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g,"");c.call(this,r,null,e)}var u=!1;try{if("function"==typeof URL&&"object"===n(URL.prototype)&&"origin"in URL.prototype){var f=new URL("b","http://a");f.pathname="c%20d",u="http://a/c%20d"===f.href}}catch(t){}if(!u){var d=Object.create(null);d.ftp=21,d.file=0,d.gopher=70,d.http=80,d.https=443,d.ws=80,d.wss=443;var p=Object.create(null);p["%2e"]=".",p[".%2e"]="..",p["%2e."]="..",p["%2e%2e"]="..";var g,v=/[a-zA-Z]/,m=/[a-zA-Z0-9\+\-\.]/;h.prototype={toString:function t(){return this.href},get href(){if(this._isInvalid)return this._url;var t="";return""===this._username&&null===this._password||(t=this._username+(null!==this._password?":"+this._password:"")+"@"),this.protocol+(this._isRelative?"//"+t+this.host:"")+this.pathname+this._query+this._fragment},set href(t){l.call(this),c.call(this,t)},get protocol(){return this._scheme+":"},set protocol(t){this._isInvalid||c.call(this,t+":","scheme start")},get host(){return this._isInvalid?"":this._port?this._host+":"+this._port:this._host},set host(t){!this._isInvalid&&this._isRelative&&c.call(this,t,"host")},get hostname(){return this._host},set hostname(t){!this._isInvalid&&this._isRelative&&c.call(this,t,"hostname")},get port(){return this._port},set port(t){!this._isInvalid&&this._isRelative&&c.call(this,t,"port")},get pathname(){return this._isInvalid?"":this._isRelative?"/"+this._path.join("/"):this._schemeData},set pathname(t){!this._isInvalid&&this._isRelative&&(this._path=[],c.call(this,t,"relative path start"))},get search(){return this._isInvalid||!this._query||"?"===this._query?"":this._query},set search(t){!this._isInvalid&&this._isRelative&&(this._query="?","?"===t[0]&&(t=t.slice(1)),c.call(this,t,"query"))},get hash(){return this._isInvalid||!this._fragment||"#"===this._fragment?"":this._fragment},set hash(t){this._isInvalid||(this._fragment="#","#"===t[0]&&(t=t.slice(1)),c.call(this,t,"fragment"))},get origin(){var t;if(this._isInvalid||!this._scheme)return"";switch(this._scheme){case"data":case"file":case"javascript":case"mailto":return"null";case"blob":try{return new h(this._schemeData).origin||"null"}catch(t){}return"null"}return t=this.host,t?this._scheme+"://"+t:""}};var b=o.URL;b&&(h.createObjectURL=function(t){return b.createObjectURL.apply(b,arguments)},h.revokeObjectURL=function(t){b.revokeObjectURL(t)}),o.URL=h}}()}},function(t,e,r){"use strict";r(0)}])})}).call(e,r(0))},function(t,e,r){!function e(r,i){t.exports=i()}(this,function(){return function(t){function e(i){if(r[i])return r[i].exports;var n=r[i]={i:i,l:!1,exports:{}};return t[i].call(n.exports,n,n.exports,e),n.l=!0,n.exports}var r={};return e.m=t,e.c=r,e.i=function(t){return t},e.d=function(t,r,i){e.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var r=t&&t.__esModule?function e(){return t.default}:function e(){return t};return e.d(r,"a",r),r},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=14)}([function(t,e,i){"use strict";var n;n="undefined"!=typeof window&&window["pdfjs-dist/build/pdf"]?window["pdfjs-dist/build/pdf"]:r(12),t.exports=n},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){return e?t.replace(/\{\{\s*(\w+)\s*\}\}/g,function(t,r){return r in e?e[r]:"{{"+r+"}}"}):t}function o(t){var e=window.devicePixelRatio||1,r=t.webkitBackingStorePixelRatio||t.mozBackingStorePixelRatio||t.msBackingStorePixelRatio||t.oBackingStorePixelRatio||t.backingStorePixelRatio||1,i=e/r;return{sx:i,sy:i,scaled:1!==i}}function a(t,e){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=t.offsetParent;if(!i)return void console.error("offsetParent is not set -- cannot scroll");for(var n=t.offsetTop+t.clientTop,o=t.offsetLeft+t.clientLeft;i.clientHeight===i.scrollHeight||r&&"hidden"===getComputedStyle(i).overflow;)if(i.dataset._scaleY&&(n/=i.dataset._scaleY,o/=i.dataset._scaleX),n+=i.offsetTop,o+=i.offsetLeft,!(i=i.offsetParent))return;e&&(void 0!==e.top&&(n+=e.top),void 0!==e.left&&(o+=e.left,i.scrollLeft=o)),i.scrollTop=n}function s(t,e){var r=function r(o){n||(n=window.requestAnimationFrame(function r(){n=null;var o=t.scrollTop,a=i.lastY;o!==a&&(i.down=o>a),i.lastY=o,e(i)}))},i={down:!0,lastY:t.scrollTop,_eventHandler:r},n=null;return t.addEventListener("scroll",r,!0),i}function c(t){for(var e=t.split("&"),r=Object.create(null),i=0,n=e.length;i<n;++i){var o=e[i].split("="),a=o[0].toLowerCase(),s=o.length>1?o[1]:null;r[decodeURIComponent(a)]=decodeURIComponent(s)}return r}function l(t,e){var r=0,i=t.length-1;if(0===t.length||!e(t[i]))return t.length;if(e(t[r]))return r;for(;r<i;){var n=r+i>>1;e(t[n])?i=n:r=n+1}return r}function h(t){if(Math.floor(t)===t)return[t,1];var e=1/t,r=8;if(e>8)return[1,8];if(Math.floor(e)===e)return[1,e];for(var i=t>1?e:t,n=0,o=1,a=1,s=1;;){var c=n+a,l=o+s;if(l>8)break;i<=c/l?(a=c,s=l):(n=c,o=l)}var h=void 0;return h=i-n/o<a/s-i?i===t?[n,o]:[o,n]:i===t?[a,s]:[s,a]}function u(t,e){var r=t%e;return 0===r?t:Math.round(t-r+e)}function f(t,e){function r(t){var e=t.div;return e.offsetTop+e.clientTop+e.clientHeight>n}for(var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=t.scrollTop,o=n+t.clientHeight,a=t.scrollLeft,s=a+t.clientWidth,c=[],h=void 0,u=void 0,f=void 0,d=void 0,p=void 0,g=void 0,v=void 0,m=void 0,b=0===e.length?0:l(e,r),y=b,_=e.length;y<_&&(h=e[y],u=h.div,f=u.offsetTop+u.clientTop,d=u.clientHeight,!(f>o));y++)v=u.offsetLeft+u.clientLeft,m=u.clientWidth,v+m<a||v>s||(p=Math.max(0,n-f)+Math.max(0,f+d-o),g=100*(d-p)/d|0,c.push({id:h.id,x:v,y:f,view:h,percent:g}));var w=c[0],S=c[c.length-1];return i&&c.sort(function(t,e){var r=t.percent-e.percent;return Math.abs(r)>.001?-r:t.id-e.id}),{first:w,last:S,views:c}}function d(t){t.preventDefault()}function p(t){for(var e=0,r=t.length;e<r&&""===t[e].trim();)e++;return"data:"===t.substr(e,5).toLowerCase()}function g(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"document.pdf";if(p(t))return console.warn('getPDFFileNameFromURL: ignoring "data:" URL for performance reasons.'),e;var r=/^(?:(?:[^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/,i=/[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i,n=r.exec(t),o=i.exec(n[1])||i.exec(n[2])||i.exec(n[3]);if(o&&(o=o[0],-1!==o.indexOf("%")))try{o=i.exec(decodeURIComponent(o))[0]}catch(t){}return o||e}function v(t){var e=Math.sqrt(t.deltaX*t.deltaX+t.deltaY*t.deltaY),r=Math.atan2(t.deltaY,t.deltaX);-.25*Math.PI<r&&r<.75*Math.PI&&(e=-e);var i=0,n=1,o=30,a=30;return 0===t.deltaMode?e/=900:1===t.deltaMode&&(e/=30),e}function m(t){var e=Object.create(null);for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e}function b(t,e,r){return Math.min(Math.max(t,e),r)}Object.defineProperty(e,"__esModule",{value:!0}),e.localized=e.animationStarted=e.normalizeWheelEventDelta=e.binarySearchFirstItem=e.watchScroll=e.scrollIntoView=e.getOutputScale=e.approximateFraction=e.roundToDivide=e.getVisibleElements=e.parseQueryString=e.noContextMenuHandler=e.getPDFFileNameFromURL=e.ProgressBar=e.EventBus=e.NullL10n=e.mozL10n=e.RendererType=e.cloneObj=e.VERTICAL_PADDING=e.SCROLLBAR_PADDING=e.MAX_AUTO_SCALE=e.UNKNOWN_SCALE=e.MAX_SCALE=e.MIN_SCALE=e.DEFAULT_SCALE=e.DEFAULT_SCALE_VALUE=e.CSS_UNITS=void 0;var y=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),_=r(0),w=96/72,S="auto",x=1,C=.25,A=10,T=0,k=1.25,P=40,E=5,O={CANVAS:"canvas",SVG:"svg"},R={get:function t(e,r,i){return Promise.resolve(n(i,r))},translate:function t(e){return Promise.resolve()}};_.PDFJS.disableFullscreen=void 0!==_.PDFJS.disableFullscreen&&_.PDFJS.disableFullscreen,_.PDFJS.useOnlyCssZoom=void 0!==_.PDFJS.useOnlyCssZoom&&_.PDFJS.useOnlyCssZoom,_.PDFJS.maxCanvasPixels=void 0===_.PDFJS.maxCanvasPixels?16777216:_.PDFJS.maxCanvasPixels,_.PDFJS.disableHistory=void 0!==_.PDFJS.disableHistory&&_.PDFJS.disableHistory,_.PDFJS.disableTextLayer=void 0!==_.PDFJS.disableTextLayer&&_.PDFJS.disableTextLayer,_.PDFJS.ignoreCurrentPositionOnZoom=void 0!==_.PDFJS.ignoreCurrentPositionOnZoom&&_.PDFJS.ignoreCurrentPositionOnZoom,_.PDFJS.locale=void 0===_.PDFJS.locale&&"undefined"!=typeof navigator?navigator.language:_.PDFJS.locale;var L=new Promise(function(t){window.requestAnimationFrame(t)}),D=void 0,I=Promise.resolve(),j=function(){function t(){i(this,t),this._listeners=Object.create(null)}return y(t,[{key:"on",value:function t(e,r){var i=this._listeners[e];i||(i=[],this._listeners[e]=i),i.push(r)}},{key:"off",value:function t(e,r){var i=this._listeners[e],n=void 0;!i||(n=i.indexOf(r))<0||i.splice(n,1)}},{key:"dispatch",value:function t(e){var r=this._listeners[e];if(r&&0!==r.length){var i=Array.prototype.slice.call(arguments,1);r.slice(0).forEach(function(t){t.apply(null,i)})}}}]),t}(),M=function(){function t(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=r.height,o=r.width,a=r.units;i(this,t),this.visible=!0,this.div=document.querySelector(e+" .progress"),this.bar=this.div.parentNode,this.height=n||100,this.width=o||100,this.units=a||"%",this.div.style.height=this.height+this.units,this.percent=0}return y(t,[{key:"_updateBar",value:function t(){if(this._indeterminate)return this.div.classList.add("indeterminate"),void(this.div.style.width=this.width+this.units);this.div.classList.remove("indeterminate");var e=this.width*this._percent/100;this.div.style.width=e+this.units}},{key:"setWidth",value:function t(e){if(e){var r=e.parentNode,i=r.offsetWidth-e.offsetWidth;i>0&&this.bar.setAttribute("style","width: calc(100% - "+i+"px);")}}},{key:"hide",value:function t(){this.visible&&(this.visible=!1,this.bar.classList.add("hidden"),document.body.classList.remove("loadingInProgress"))}},{key:"show",value:function t(){this.visible||(this.visible=!0,document.body.classList.add("loadingInProgress"),this.bar.classList.remove("hidden"))}},{key:"percent",get:function t(){return this._percent},set:function t(e){this._indeterminate=isNaN(e),this._percent=b(e,0,100),this._updateBar()}}]),t}();e.CSS_UNITS=96/72,e.DEFAULT_SCALE_VALUE="auto",e.DEFAULT_SCALE=1,e.MIN_SCALE=.25,e.MAX_SCALE=10,e.UNKNOWN_SCALE=0,e.MAX_AUTO_SCALE=1.25,e.SCROLLBAR_PADDING=40,e.VERTICAL_PADDING=5,e.cloneObj=m,e.RendererType=O,e.mozL10n=void 0,e.NullL10n=R,e.EventBus=j,e.ProgressBar=M,e.getPDFFileNameFromURL=g,e.noContextMenuHandler=d,e.parseQueryString=c,e.getVisibleElements=f,e.roundToDivide=u,e.approximateFraction=h,e.getOutputScale=o,e.scrollIntoView=a,e.watchScroll=s,e.binarySearchFirstItem=l,e.normalizeWheelEventDelta=v,e.animationStarted=L,e.localized=I},function(t,e,r){"use strict";function i(t){t.on("documentload",function(){var t=document.createEvent("CustomEvent");t.initCustomEvent("documentload",!0,!0,{}),window.dispatchEvent(t)}),t.on("pagerendered",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("pagerendered",!0,!0,{pageNumber:t.pageNumber,cssTransform:t.cssTransform}),t.source.div.dispatchEvent(e)}),t.on("textlayerrendered",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("textlayerrendered",!0,!0,{pageNumber:t.pageNumber}),t.source.textLayerDiv.dispatchEvent(e)}),t.on("pagechange",function(t){var e=document.createEvent("UIEvents");e.initUIEvent("pagechange",!0,!0,window,0),e.pageNumber=t.pageNumber,t.source.container.dispatchEvent(e)}),t.on("pagesinit",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("pagesinit",!0,!0,null),t.source.container.dispatchEvent(e)}),t.on("pagesloaded",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("pagesloaded",!0,!0,{pagesCount:t.pagesCount}),t.source.container.dispatchEvent(e)}),t.on("scalechange",function(t){var e=document.createEvent("UIEvents");e.initUIEvent("scalechange",!0,!0,window,0),e.scale=t.scale,e.presetValue=t.presetValue,t.source.container.dispatchEvent(e)}),t.on("updateviewarea",function(t){var e=document.createEvent("UIEvents");e.initUIEvent("updateviewarea",!0,!0,window,0),e.location=t.location,t.source.container.dispatchEvent(e)}),t.on("find",function(t){if(t.source!==window){var e=document.createEvent("CustomEvent");e.initCustomEvent("find"+t.type,!0,!0,{query:t.query,phraseSearch:t.phraseSearch,caseSensitive:t.caseSensitive,highlightAll:t.highlightAll,findPrevious:t.findPrevious}),window.dispatchEvent(e)}}),t.on("attachmentsloaded",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("attachmentsloaded",!0,!0,{attachmentsCount:t.attachmentsCount}),t.source.container.dispatchEvent(e)}),t.on("sidebarviewchanged",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("sidebarviewchanged",!0,!0,{view:t.view}),t.source.outerContainer.dispatchEvent(e)}),t.on("pagemode",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("pagemode",!0,!0,{mode:t.mode}),t.source.pdfViewer.container.dispatchEvent(e)}),t.on("namedaction",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("namedaction",!0,!0,{action:t.action}),t.source.pdfViewer.container.dispatchEvent(e)}),t.on("presentationmodechanged",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("presentationmodechanged",!0,!0,{active:t.active,switchInProgress:t.switchInProgress}),window.dispatchEvent(e)}),t.on("outlineloaded",function(t){var e=document.createEvent("CustomEvent");e.initCustomEvent("outlineloaded",!0,!0,{outlineCount:t.outlineCount}),t.source.container.dispatchEvent(e)})}function n(){return a||(a=new o.EventBus,i(a),a)}Object.defineProperty(e,"__esModule",{value:!0}),e.getGlobalEventBus=e.attachDOMEventsToEventBus=void 0;var o=r(1),a=null;e.attachDOMEventsToEventBus=i,e.getGlobalEventBus=n},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t){if(!(t instanceof Array))return!1;var e=t.length,r=!0;if(e<2)return!1;var i=t[0];if(!("object"===(void 0===i?"undefined":o(i))&&"number"==typeof i.num&&(0|i.num)===i.num&&"number"==typeof i.gen&&(0|i.gen)===i.gen||"number"==typeof i&&(0|i)===i&&i>=0))return!1;var n=t[1];if("object"!==(void 0===n?"undefined":o(n))||"string"!=typeof n.name)return!1;switch(n.name){case"XYZ":if(5!==e)return!1;break;case"Fit":case"FitB":return 2===e;case"FitH":case"FitBH":case"FitV":case"FitBV":if(3!==e)return!1;break;case"FitR":if(6!==e)return!1;r=!1;break;default:return!1}for(var a=2;a<e;a++){var s=t[a];if(!("number"==typeof s||r&&null===s))return!1}return!0}Object.defineProperty(e,"__esModule",{value:!0}),e.SimpleLinkService=e.PDFLinkService=void 0;var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},a=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),s=r(2),c=r(1),l=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=e.eventBus;i(this,t),this.eventBus=r||(0,s.getGlobalEventBus)(),this.baseUrl=null,this.pdfDocument=null,this.pdfViewer=null,this.pdfHistory=null,this._pagesRefCache=null}return a(t,[{key:"setDocument",value:function t(e,r){this.baseUrl=r,this.pdfDocument=e,this._pagesRefCache=Object.create(null)}},{key:"setViewer",value:function t(e){this.pdfViewer=e}},{key:"setHistory",value:function t(e){this.pdfHistory=e}},{key:"navigateTo",value:function t(e){var r=this,i=function t(i){var n=i.namedDest,o=i.explicitDest,a=o[0],s=void 0;if(a instanceof Object){if(null===(s=r._cachedPageNumber(a)))return void r.pdfDocument.getPageIndex(a).then(function(e){r.cachePageRef(e+1,a),t({namedDest:n,explicitDest:o})}).catch(function(){console.error('PDFLinkService.navigateTo: "'+a+'" is not a valid page reference, for dest="'+e+'".')})}else{if((0|a)!==a)return void console.error('PDFLinkService.navigateTo: "'+a+'" is not a valid destination reference, for dest="'+e+'".');s=a+1}if(!s||s<1||s>r.pagesCount)return void console.error('PDFLinkService.navigateTo: "'+s+'" is not a valid page number, for dest="'+e+'".');r.pdfViewer.scrollPageIntoView({pageNumber:s,destArray:o}),r.pdfHistory&&r.pdfHistory.push({dest:o,hash:n,page:s})};new Promise(function(t,i){if("string"==typeof e)return void r.pdfDocument.getDestination(e).then(function(r){t({namedDest:e,explicitDest:r})});t({namedDest:"",explicitDest:e})}).then(function(t){if(!(t.explicitDest instanceof Array))return void console.error('PDFLinkService.navigateTo: "'+t.explicitDest+'" is not a valid destination array, for dest="'+e+'".');i(t)})}},{key:"getDestinationHash",value:function t(e){if("string"==typeof e)return this.getAnchorUrl("#"+escape(e));if(e instanceof Array){var r=JSON.stringify(e);return this.getAnchorUrl("#"+escape(r))}return this.getAnchorUrl("")}},{key:"getAnchorUrl",value:function t(e){return(this.baseUrl||"")+e}},{key:"setHash",value:function t(e){var r=void 0,i=void 0;if(e.indexOf("=")>=0){var o=(0,c.parseQueryString)(e);if("search"in o&&this.eventBus.dispatch("findfromurlhash",{source:this,query:o.search.replace(/"/g,""),phraseSearch:"true"===o.phrase}),"nameddest"in o)return this.pdfHistory&&this.pdfHistory.updateNextHashParam(o.nameddest),void this.navigateTo(o.nameddest);if("page"in o&&(r=0|o.page||1),"zoom"in o){var a=o.zoom.split(","),s=a[0],l=parseFloat(s);-1===s.indexOf("Fit")?i=[null,{name:"XYZ"},a.length>1?0|a[1]:null,a.length>2?0|a[2]:null,l?l/100:s]:"Fit"===s||"FitB"===s?i=[null,{name:s}]:"FitH"===s||"FitBH"===s||"FitV"===s||"FitBV"===s?i=[null,{name:s},a.length>1?0|a[1]:null]:"FitR"===s?5!==a.length?console.error('PDFLinkService.setHash: Not enough parameters for "FitR".'):i=[null,{name:s},0|a[1],0|a[2],0|a[3],0|a[4]]:console.error('PDFLinkService.setHash: "'+s+'" is not a valid zoom value.')}i?this.pdfViewer.scrollPageIntoView({pageNumber:r||this.page,destArray:i,allowNegativeOffset:!0}):r&&(this.page=r),"pagemode"in o&&this.eventBus.dispatch("pagemode",{source:this,mode:o.pagemode})}else{/^\d+$/.test(e)&&e<=this.pagesCount&&(console.warn('PDFLinkService_setHash: specifying a page number directly after the hash symbol (#) is deprecated, please use the "#page='+e+'" form instead.'),this.page=0|e),i=unescape(e);try{i=JSON.parse(i),i instanceof Array||(i=i.toString())}catch(t){}if("string"==typeof i||n(i))return this.pdfHistory&&this.pdfHistory.updateNextHashParam(i),void this.navigateTo(i);console.error('PDFLinkService.setHash: "'+unescape(e)+'" is not a valid destination.')}}},{key:"executeNamedAction",value:function t(e){switch(e){case"GoBack":this.pdfHistory&&this.pdfHistory.back();break;case"GoForward":this.pdfHistory&&this.pdfHistory.forward();break;case"NextPage":this.page<this.pagesCount&&this.page++;break;case"PrevPage":this.page>1&&this.page--;break;case"LastPage":this.page=this.pagesCount;break;case"FirstPage":this.page=1}this.eventBus.dispatch("namedaction",{source:this,action:e})}},{key:"onFileAttachmentAnnotation",value:function t(e){var r=e.id,i=e.filename,n=e.content;this.eventBus.dispatch("fileattachmentannotation",{source:this,id:r,filename:i,content:n})}},{key:"cachePageRef",value:function t(e,r){var i=r.num+" "+r.gen+" R";this._pagesRefCache[i]=e}},{key:"_cachedPageNumber",value:function t(e){var r=e.num+" "+e.gen+" R";return this._pagesRefCache&&this._pagesRefCache[r]||null}},{key:"pagesCount",get:function t(){return this.pdfDocument?this.pdfDocument.numPages:0}},{key:"page",get:function t(){return this.pdfViewer.currentPageNumber},set:function t(e){this.pdfViewer.currentPageNumber=e}}]),t}(),h=function(){function t(){i(this,t)}return a(t,[{key:"navigateTo",value:function t(e){}},{key:"getDestinationHash",value:function t(e){return"#"}},{key:"getAnchorUrl",value:function t(e){return"#"}},{key:"setHash",value:function t(e){}},{key:"executeNamedAction",value:function t(e){}},{key:"onFileAttachmentAnnotation",value:function t(e){var r=e.id,i=e.filename,n=e.content}},{key:"cachePageRef",value:function t(e,r){}},{key:"page",get:function t(){return 0},set:function t(e){}}]),t}();e.PDFLinkService=l,e.SimpleLinkService=h},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.DefaultAnnotationLayerFactory=e.AnnotationLayerBuilder=void 0;var n=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),o=r(0),a=r(1),s=r(3),c=function(){function t(e){var r=e.pageDiv,n=e.pdfPage,o=e.linkService,s=e.downloadManager,c=e.renderInteractiveForms,l=void 0!==c&&c,h=e.l10n,u=void 0===h?a.NullL10n:h;i(this,t),this.pageDiv=r,this.pdfPage=n,this.linkService=o,this.downloadManager=s,this.renderInteractiveForms=l,this.l10n=u,this.div=null}return n(t,[{key:"render",value:function t(e){var r=this,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"display";this.pdfPage.getAnnotations({intent:i}).then(function(t){var i={viewport:e.clone({dontFlip:!0}),div:r.div,annotations:t,page:r.pdfPage,renderInteractiveForms:r.renderInteractiveForms,linkService:r.linkService,downloadManager:r.downloadManager};if(r.div)o.AnnotationLayer.update(i);else{if(0===t.length)return;r.div=document.createElement("div"),r.div.className="annotationLayer",r.pageDiv.appendChild(r.div),i.div=r.div,o.AnnotationLayer.render(i),r.l10n.translate(r.div)}})}},{key:"hide",value:function t(){this.div&&this.div.setAttribute("hidden","true")}}]),t}(),l=function(){function t(){i(this,t)}return n(t,[{key:"createAnnotationLayerBuilder",value:function t(e,r){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:a.NullL10n;return new c({pageDiv:e,pdfPage:r,renderInteractiveForms:i,linkService:new s.SimpleLinkService,l10n:n})}}]),t}();e.AnnotationLayerBuilder=c,e.DefaultAnnotationLayerFactory=l},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.PDFPageView=void 0;var n=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),o=r(1),a=r(0),s=r(2),c=r(7),l=function(){function t(e){i(this,t);var r=e.container,n=e.defaultViewport;this.id=e.id,this.renderingId="page"+this.id,this.pageLabel=null,this.rotation=0,this.scale=e.scale||o.DEFAULT_SCALE,this.viewport=n,this.pdfPageRotate=n.rotation,this.hasRestrictedScaling=!1,this.enhanceTextSelection=e.enhanceTextSelection||!1,this.renderInteractiveForms=e.renderInteractiveForms||!1,this.eventBus=e.eventBus||(0,s.getGlobalEventBus)(),this.renderingQueue=e.renderingQueue,this.textLayerFactory=e.textLayerFactory,this.annotationLayerFactory=e.annotationLayerFactory,this.renderer=e.renderer||o.RendererType.CANVAS,this.l10n=e.l10n||o.NullL10n,this.paintTask=null,this.paintedViewportMap=new WeakMap,this.renderingState=c.RenderingStates.INITIAL,this.resume=null,this.error=null,this.onBeforeDraw=null,this.onAfterDraw=null,this.annotationLayer=null,this.textLayer=null,this.zoomLayer=null;var a=document.createElement("div");a.className="page",a.style.width=Math.floor(this.viewport.width)+"px",a.style.height=Math.floor(this.viewport.height)+"px",a.setAttribute("data-page-number",this.id),this.div=a,r.appendChild(a)}return n(t,[{key:"setPdfPage",value:function t(e){this.pdfPage=e,this.pdfPageRotate=e.rotate;var r=(this.rotation+this.pdfPageRotate)%360;this.viewport=e.getViewport(this.scale*o.CSS_UNITS,r),this.stats=e.stats,this.reset()}},{key:"destroy",value:function t(){this.reset(),this.pdfPage&&this.pdfPage.cleanup()}},{key:"_resetZoomLayer",value:function t(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(this.zoomLayer){var r=this.zoomLayer.firstChild;this.paintedViewportMap.delete(r),r.width=0,r.height=0,e&&this.zoomLayer.remove(),this.zoomLayer=null}}},{key:"reset",value:function t(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.cancelRendering();var i=this.div;i.style.width=Math.floor(this.viewport.width)+"px",i.style.height=Math.floor(this.viewport.height)+"px";for(var n=i.childNodes,o=e&&this.zoomLayer||null,a=r&&this.annotationLayer&&this.annotationLayer.div||null,s=n.length-1;s>=0;s--){var c=n[s];o!==c&&a!==c&&i.removeChild(c)}i.removeAttribute("data-loaded"),a?this.annotationLayer.hide():this.annotationLayer=null,o||(this.canvas&&(this.paintedViewportMap.delete(this.canvas),this.canvas.width=0,this.canvas.height=0,delete this.canvas),this._resetZoomLayer()),this.svg&&(this.paintedViewportMap.delete(this.svg),delete this.svg),this.loadingIconDiv=document.createElement("div"),this.loadingIconDiv.className="loadingIcon",i.appendChild(this.loadingIconDiv)}},{key:"update",value:function t(e,r){this.scale=e||this.scale,void 0!==r&&(this.rotation=r);var i=(this.rotation+this.pdfPageRotate)%360;if(this.viewport=this.viewport.clone({scale:this.scale*o.CSS_UNITS,rotation:i}),this.svg)return this.cssTransform(this.svg,!0),void this.eventBus.dispatch("pagerendered",{source:this,pageNumber:this.id,cssTransform:!0});var n=!1;if(this.canvas&&a.PDFJS.maxCanvasPixels>0){var s=this.outputScale;(Math.floor(this.viewport.width)*s.sx|0)*(Math.floor(this.viewport.height)*s.sy|0)>a.PDFJS.maxCanvasPixels&&(n=!0)}if(this.canvas){if(a.PDFJS.useOnlyCssZoom||this.hasRestrictedScaling&&n)return this.cssTransform(this.canvas,!0),void this.eventBus.dispatch("pagerendered",{source:this,pageNumber:this.id,cssTransform:!0});this.zoomLayer||this.canvas.hasAttribute("hidden")||(this.zoomLayer=this.canvas.parentNode,this.zoomLayer.style.position="absolute")}this.zoomLayer&&this.cssTransform(this.zoomLayer.firstChild),this.reset(!0,!0)}},{key:"cancelRendering",value:function t(){this.paintTask&&(this.paintTask.cancel(),this.paintTask=null),this.renderingState=c.RenderingStates.INITIAL,this.resume=null,this.textLayer&&(this.textLayer.cancel(),this.textLayer=null)}},{key:"cssTransform",value:function t(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=this.viewport.width,n=this.viewport.height,o=this.div;e.style.width=e.parentNode.style.width=o.style.width=Math.floor(i)+"px",e.style.height=e.parentNode.style.height=o.style.height=Math.floor(n)+"px";var s=this.viewport.rotation-this.paintedViewportMap.get(e).rotation,c=Math.abs(s),l=1,h=1;90!==c&&270!==c||(l=n/i,h=i/n);var t="rotate("+s+"deg) scale("+l+","+h+")";if(a.CustomStyle.setProp("transform",e,t),this.textLayer){var u=this.textLayer.viewport,f=this.viewport.rotation-u.rotation,d=Math.abs(f),p=i/u.width;90!==d&&270!==d||(p=i/u.height);var g=this.textLayer.textLayerDiv,v=void 0,m=void 0;switch(d){case 0:v=m=0;break;case 90:v=0,m="-"+g.style.height;break;case 180:v="-"+g.style.width,m="-"+g.style.height;break;case 270:v="-"+g.style.width,m=0;break;default:console.error("Bad rotation value.")}a.CustomStyle.setProp("transform",g,"rotate("+d+"deg) scale("+p+", "+p+") translate("+v+", "+m+")"),a.CustomStyle.setProp("transformOrigin",g,"0% 0%")}r&&this.annotationLayer&&this.annotationLayer.render(this.viewport,"display")}},{key:"getPagePoint",value:function t(e,r){return this.viewport.convertToPdfPoint(e,r)}},{key:"draw",value:function t(){var e=this;this.renderingState!==c.RenderingStates.INITIAL&&(console.error("Must be in new state before drawing"),this.reset()),this.renderingState=c.RenderingStates.RUNNING;var r=this.pdfPage,i=this.div,n=document.createElement("div");n.style.width=i.style.width,n.style.height=i.style.height,n.classList.add("canvasWrapper"),this.annotationLayer&&this.annotationLayer.div?i.insertBefore(n,this.annotationLayer.div):i.appendChild(n);var s=null;if(this.textLayerFactory){var l=document.createElement("div");l.className="textLayer",l.style.width=n.style.width,l.style.height=n.style.height,this.annotationLayer&&this.annotationLayer.div?i.insertBefore(l,this.annotationLayer.div):i.appendChild(l),s=this.textLayerFactory.createTextLayerBuilder(l,this.id-1,this.viewport,this.enhanceTextSelection)}this.textLayer=s;var h=null;this.renderingQueue&&(h=function t(r){if(!e.renderingQueue.isHighestPriority(e))return e.renderingState=c.RenderingStates.PAUSED,void(e.resume=function(){e.renderingState=c.RenderingStates.RUNNING,r()});r()});var u=function t(n){return f===e.paintTask&&(e.paintTask=null),"cancelled"===n||n instanceof a.RenderingCancelledException?(e.error=null,Promise.resolve(void 0)):(e.renderingState=c.RenderingStates.FINISHED,e.loadingIconDiv&&(i.removeChild(e.loadingIconDiv),delete e.loadingIconDiv),e._resetZoomLayer(!0),e.error=n,e.stats=r.stats,e.onAfterDraw&&e.onAfterDraw(),e.eventBus.dispatch("pagerendered",{source:e,pageNumber:e.id,cssTransform:!1}),n?Promise.reject(n):Promise.resolve(void 0))},f=this.renderer===o.RendererType.SVG?this.paintOnSvg(n):this.paintOnCanvas(n);f.onRenderContinue=h,this.paintTask=f;var d=f.promise.then(function(){return u(null).then(function(){if(s){var t=r.streamTextContent({normalizeWhitespace:!0});s.setTextContentStream(t),s.render()}})},function(t){return u(t)});return this.annotationLayerFactory&&(this.annotationLayer||(this.annotationLayer=this.annotationLayerFactory.createAnnotationLayerBuilder(i,r,this.renderInteractiveForms,this.l10n)),this.annotationLayer.render(this.viewport,"display")),i.setAttribute("data-loaded",!0),this.onBeforeDraw&&this.onBeforeDraw(),d}},{key:"paintOnCanvas",value:function t(e){var r=(0,a.createPromiseCapability)(),i={promise:r.promise,onRenderContinue:function t(e){e()},cancel:function t(){y.cancel()}},n=this.viewport,s=document.createElement("canvas");s.id=this.renderingId,s.setAttribute("hidden","hidden");var c=!0,l=function t(){c&&(s.removeAttribute("hidden"),c=!1)};e.appendChild(s),this.canvas=s,s.mozOpaque=!0;var h=s.getContext("2d",{alpha:!1}),u=(0,o.getOutputScale)(h);if(this.outputScale=u,a.PDFJS.useOnlyCssZoom){var f=n.clone({scale:o.CSS_UNITS});u.sx*=f.width/n.width,u.sy*=f.height/n.height,u.scaled=!0}if(a.PDFJS.maxCanvasPixels>0){var d=n.width*n.height,p=Math.sqrt(a.PDFJS.maxCanvasPixels/d);u.sx>p||u.sy>p?(u.sx=p,u.sy=p,u.scaled=!0,this.hasRestrictedScaling=!0):this.hasRestrictedScaling=!1}var g=(0,o.approximateFraction)(u.sx),v=(0,o.approximateFraction)(u.sy);s.width=(0,o.roundToDivide)(n.width*u.sx,g[0]),s.height=(0,o.roundToDivide)(n.height*u.sy,v[0]),s.style.width=(0,o.roundToDivide)(n.width,g[1])+"px",s.style.height=(0,o.roundToDivide)(n.height,v[1])+"px",this.paintedViewportMap.set(s,n);var m=u.scaled?[u.sx,0,0,u.sy,0,0]:null,b={canvasContext:h,transform:m,viewport:this.viewport,renderInteractiveForms:this.renderInteractiveForms},y=this.pdfPage.render(b);return y.onContinue=function(t){l(),i.onRenderContinue?i.onRenderContinue(t):t()},y.promise.then(function(){l(),r.resolve(void 0)},function(t){l(),r.reject(t)}),i}},{key:"paintOnSvg",value:function t(e){var r=this,i=!1,n=function t(){if(i)throw a.PDFJS.pdfjsNext?new a.RenderingCancelledException("Rendering cancelled, page "+r.id,"svg"):"cancelled"},s=this.pdfPage,l=this.viewport.clone({scale:o.CSS_UNITS});return{promise:s.getOperatorList().then(function(t){return n(),new a.SVGGraphics(s.commonObjs,s.objs).getSVG(t,l).then(function(t){n(),r.svg=t,r.paintedViewportMap.set(t,l),t.style.width=e.style.width,t.style.height=e.style.height,r.renderingState=c.RenderingStates.FINISHED,e.appendChild(t)})}),onRenderContinue:function t(e){e()},cancel:function t(){i=!0}}}},{key:"setPageLabel",value:function t(e){this.pageLabel="string"==typeof e?e:null,null!==this.pageLabel?this.div.setAttribute("data-page-label",this.pageLabel):this.div.removeAttribute("data-page-label")}},{key:"width",get:function t(){return this.viewport.width}},{key:"height",get:function t(){return this.viewport.height}}]),t}();e.PDFPageView=l},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.DefaultTextLayerFactory=e.TextLayerBuilder=void 0;var n=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),o=r(2),a=r(0),s=300,c=function(){function t(e){var r=e.textLayerDiv,n=e.eventBus,a=e.pageIndex,s=e.viewport,c=e.findController,l=void 0===c?null:c,h=e.enhanceTextSelection,u=void 0!==h&&h;i(this,t),this.textLayerDiv=r,this.eventBus=n||(0,o.getGlobalEventBus)(),this.textContent=null,this.textContentItemsStr=[],this.textContentStream=null,this.renderingDone=!1,this.pageIdx=a,this.pageNumber=this.pageIdx+1,this.matches=[],this.viewport=s,this.textDivs=[],this.findController=l,this.textLayerRenderTask=null,this.enhanceTextSelection=u,this._bindMouse()}return n(t,[{key:"_finishRendering",value:function t(){if(this.renderingDone=!0,!this.enhanceTextSelection){var e=document.createElement("div");e.className="endOfContent",this.textLayerDiv.appendChild(e)}this.eventBus.dispatch("textlayerrendered",{source:this,pageNumber:this.pageNumber,numTextDivs:this.textDivs.length})}},{key:"render",value:function t(){var e=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;if((this.textContent||this.textContentStream)&&!this.renderingDone){this.cancel(),this.textDivs=[];var i=document.createDocumentFragment();this.textLayerRenderTask=(0,a.renderTextLayer)({textContent:this.textContent,textContentStream:this.textContentStream,container:i,viewport:this.viewport,textDivs:this.textDivs,textContentItemsStr:this.textContentItemsStr,timeout:r,enhanceTextSelection:this.enhanceTextSelection}),this.textLayerRenderTask.promise.then(function(){e.textLayerDiv.appendChild(i),e._finishRendering(),e.updateMatches()},function(t){})}}},{key:"cancel",value:function t(){this.textLayerRenderTask&&(this.textLayerRenderTask.cancel(),this.textLayerRenderTask=null)}},{key:"setTextContentStream",value:function t(e){this.cancel(),this.textContentStream=e}},{key:"setTextContent",value:function t(e){this.cancel(),this.textContent=e}},{key:"convertMatches",value:function t(e,r){var i=0,n=0,o=this.textContentItemsStr,a=o.length-1,s=null===this.findController?0:this.findController.state.query.length,c=[];if(!e)return c;for(var l=0,h=e.length;l<h;l++){for(var u=e[l];i!==a&&u>=n+o[i].length;)n+=o[i].length,i++;i===o.length&&console.error("Could not find a matching mapping");var f={begin:{divIdx:i,offset:u-n}};for(u+=r?r[l]:s;i!==a&&u>n+o[i].length;)n+=o[i].length,i++;f.end={divIdx:i,offset:u-n},c.push(f)}return c}},{key:"renderMatches",value:function t(e){function r(t,e){var r=t.divIdx;o[r].textContent="",i(r,0,t.offset,e)}function i(t,e,r,i){var a=o[t],s=n[t].substring(e,r),c=document.createTextNode(s);if(i){var l=document.createElement("span");return l.className=i,l.appendChild(c),void a.appendChild(l)}a.appendChild(c)}if(0!==e.length){var n=this.textContentItemsStr,o=this.textDivs,a=null,s=this.pageIdx,c=null!==this.findController&&s===this.findController.selected.pageIdx,l=null===this.findController?-1:this.findController.selected.matchIdx,h=null!==this.findController&&this.findController.state.highlightAll,u={divIdx:-1,offset:void 0},f=l,d=f+1;if(h)f=0,d=e.length;else if(!c)return;for(var p=f;p<d;p++){var g=e[p],v=g.begin,m=g.end,b=c&&p===l,y=b?" selected":"";if(this.findController&&this.findController.updateMatchPosition(s,p,o,v.divIdx),a&&v.divIdx===a.divIdx?i(a.divIdx,a.offset,v.offset):(null!==a&&i(a.divIdx,a.offset,u.offset),r(v)),v.divIdx===m.divIdx)i(v.divIdx,v.offset,m.offset,"highlight"+y);else{i(v.divIdx,v.offset,u.offset,"highlight begin"+y);for(var _=v.divIdx+1,w=m.divIdx;_<w;_++)o[_].className="highlight middle"+y;r(m,"highlight end"+y)}a=m}a&&i(a.divIdx,a.offset,u.offset)}}},{key:"updateMatches",value:function t(){if(this.renderingDone){for(var e=this.matches,r=this.textDivs,i=this.textContentItemsStr,n=-1,o=0,a=e.length;o<a;o++){for(var s=e[o],c=Math.max(n,s.begin.divIdx),l=c,h=s.end.divIdx;l<=h;l++){var u=r[l];u.textContent=i[l],u.className=""}n=s.end.divIdx+1}if(null!==this.findController&&this.findController.active){var f=void 0,d=void 0;null!==this.findController&&(f=this.findController.pageMatches[this.pageIdx]||null,d=this.findController.pageMatchesLength?this.findController.pageMatchesLength[this.pageIdx]||null:null),this.matches=this.convertMatches(f,d),this.renderMatches(this.matches)}}}},{key:"_bindMouse",value:function t(){var e=this,r=this.textLayerDiv,i=null;r.addEventListener("mousedown",function(t){if(e.enhanceTextSelection&&e.textLayerRenderTask)return e.textLayerRenderTask.expandTextDivs(!0),void(i&&(clearTimeout(i),i=null));var n=r.querySelector(".endOfContent");if(n){var o=t.target!==r;if(o=o&&"none"!==window.getComputedStyle(n).getPropertyValue("-moz-user-select")){var a=r.getBoundingClientRect(),s=Math.max(0,(t.pageY-a.top)/a.height);n.style.top=(100*s).toFixed(2)+"%"}n.classList.add("active")}}),r.addEventListener("mouseup",function(){if(e.enhanceTextSelection&&e.textLayerRenderTask)return void(i=setTimeout(function(){e.textLayerRenderTask&&e.textLayerRenderTask.expandTextDivs(!1),i=null},300));var t=r.querySelector(".endOfContent");t&&(t.style.top="",t.classList.remove("active"))})}}]),t}(),l=function(){function t(){i(this,t)}return n(t,[{key:"createTextLayerBuilder",value:function t(e,r,i){var n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return new c({textLayerDiv:e,pageIndex:r,viewport:i,enhanceTextSelection:n})}}]),t}();e.TextLayerBuilder=c,e.DefaultTextLayerFactory=l},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),o=3e4,a={INITIAL:0,RUNNING:1,PAUSED:2,FINISHED:3},s=function(){function t(){i(this,t),this.pdfViewer=null,this.pdfThumbnailViewer=null,this.onIdle=null,this.highestPriorityPage=null,this.idleTimeout=null,this.printing=!1,this.isThumbnailViewEnabled=!1}return n(t,[{key:"setViewer",value:function t(e){this.pdfViewer=e}},{key:"setThumbnailViewer",value:function t(e){this.pdfThumbnailViewer=e}},{key:"isHighestPriority",value:function t(e){return this.highestPriorityPage===e.renderingId}},{key:"renderHighestPriority",value:function t(e){this.idleTimeout&&(clearTimeout(this.idleTimeout),this.idleTimeout=null),this.pdfViewer.forceRendering(e)||this.pdfThumbnailViewer&&this.isThumbnailViewEnabled&&this.pdfThumbnailViewer.forceRendering()||this.printing||this.onIdle&&(this.idleTimeout=setTimeout(this.onIdle.bind(this),3e4))}},{key:"getHighestPriority",value:function t(e,r,i){var n=e.views,o=n.length;if(0===o)return!1;for(var a=0;a<o;++a){var s=n[a].view;if(!this.isViewFinished(s))return s}if(i){var c=e.last.id;if(r[c]&&!this.isViewFinished(r[c]))return r[c]}else{var l=e.first.id-2;if(r[l]&&!this.isViewFinished(r[l]))return r[l]}return null}},{key:"isViewFinished",value:function t(e){return e.renderingState===a.FINISHED}},{key:"renderView",value:function t(e){var r=this;switch(e.renderingState){case a.FINISHED:return!1;case a.PAUSED:this.highestPriorityPage=e.renderingId,e.resume();break;case a.RUNNING:this.highestPriorityPage=e.renderingId;break;case a.INITIAL:this.highestPriorityPage=e.renderingId;var i=function t(){r.renderHighestPriority()};e.draw().then(i,i)}return!0}}]),t}();e.RenderingStates=a,e.PDFRenderingQueue=s},function(t,e,r){"use strict";function i(t,e){var r=document.createElement("a");if(r.click)r.href=t,r.target="_parent","download"in r&&(r.download=e),(document.body||document.documentElement).appendChild(r),r.click(),r.parentNode.removeChild(r);else{if(window.top===window&&t.split("#")[0]===window.location.href.split("#")[0]){var i=-1===t.indexOf("?")?"?":"&";t=t.replace(/#|$/,i+"$&")}window.open(t,"_parent")}}function n(){}Object.defineProperty(e,"__esModule",{value:!0}),e.DownloadManager=void 0;var o=r(0);n.prototype={downloadUrl:function t(e,r){(0,o.createValidAbsoluteUrl)(e,"http://example.com")&&i(e+"#pdfjs.action=download",r)},downloadData:function t(e,r,n){if(navigator.msSaveBlob)return navigator.msSaveBlob(new Blob([e],{type:n}),r);i((0,o.createObjectURL)(e,n,o.PDFJS.disableCreateObjectURL),r)},download:function t(e,r,n){return navigator.msSaveBlob?void(navigator.msSaveBlob(e,n)||this.downloadUrl(r,n)):o.PDFJS.disableCreateObjectURL?void this.downloadUrl(r,n):void i(URL.createObjectURL(e),n)}},e.DownloadManager=n},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.GenericL10n=void 0;var n=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}();r(13);var o=document.webL10n,a=function(){function t(e){i(this,t),this._lang=e,this._ready=new Promise(function(t,r){o.setLanguage(e,function(){t(o)})})}return n(t,[{key:"getDirection",value:function t(){return this._ready.then(function(t){return t.getDirection()})}},{key:"get",value:function t(e,r,i){return this._ready.then(function(t){return t.get(e,r,i)})}},{key:"translate",value:function t(e){return this._ready.then(function(t){return t.translate(e)})}}]),t}();e.GenericL10n=a},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.PDFFindController=e.FindState=void 0;var n=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),o=r(0),a=r(1),s={FOUND:0,NOT_FOUND:1,WRAPPED:2,PENDING:3},c=-50,l=-400,h=250,u={"‘":"'","’":"'","‚":"'","‛":"'","“":'"',"”":'"',"„":'"',"‟":'"',"¼":"1/4","½":"1/2","¾":"3/4"},f=function(){function t(e){var r=e.pdfViewer;i(this,t),this.pdfViewer=r,this.onUpdateResultsCount=null,this.onUpdateState=null,this.reset();var n=Object.keys(u).join("");this.normalizationRegex=new RegExp("["+n+"]","g")}return n(t,[{key:"reset",value:function t(){var e=this;this.startedTextExtraction=!1,this.extractTextPromises=[],this.pendingFindMatches=Object.create(null),this.active=!1,this.pageContents=[],this.pageMatches=[],this.pageMatchesLength=null,this.matchCount=0,this.selected={pageIdx:-1,matchIdx:-1},this.offset={pageIdx:null,matchIdx:null},this.pagesToSearch=null,this.resumePageIdx=null,this.state=null,this.dirtyMatch=!1,this.findTimeout=null,this._firstPagePromise=new Promise(function(t){e.resolveFirstPage=t})}},{key:"normalize",value:function t(e){return e.replace(this.normalizationRegex,function(t){return u[t]})}},{key:"_prepareMatches",value:function t(e,r,i){function n(t,e){var r=t[e],i=t[e+1];if(e<t.length-1&&r.match===i.match)return r.skipped=!0,!0;for(var n=e-1;n>=0;n--){var o=t[n];if(!o.skipped){if(o.match+o.matchLength<r.match)break;if(o.match+o.matchLength>=r.match+r.matchLength)return r.skipped=!0,!0}}return!1}e.sort(function(t,e){return t.match===e.match?t.matchLength-e.matchLength:t.match-e.match});for(var o=0,a=e.length;o<a;o++)n(e,o)||(r.push(e[o].match),i.push(e[o].matchLength))}},{key:"calcFindPhraseMatch",value:function t(e,r,i){for(var n=[],o=e.length,a=-o;;){if(-1===(a=i.indexOf(e,a+o)))break;n.push(a)}this.pageMatches[r]=n}},{key:"calcFindWordMatch",value:function t(e,r,i){for(var n=[],o=e.match(/\S+/g),a=0,s=o.length;a<s;a++)for(var c=o[a],l=c.length,h=-l;;){if(-1===(h=i.indexOf(c,h+l)))break;n.push({match:h,matchLength:l,skipped:!1})}this.pageMatchesLength||(this.pageMatchesLength=[]),this.pageMatchesLength[r]=[],this.pageMatches[r]=[],this._prepareMatches(n,this.pageMatches[r],this.pageMatchesLength[r])}},{key:"calcFindMatch",value:function t(e){var r=this.normalize(this.pageContents[e]),i=this.normalize(this.state.query),n=this.state.caseSensitive,o=this.state.phraseSearch;0!==i.length&&(n||(r=r.toLowerCase(),i=i.toLowerCase()),o?this.calcFindPhraseMatch(i,e,r):this.calcFindWordMatch(i,e,r),this.updatePage(e),this.resumePageIdx===e&&(this.resumePageIdx=null,this.nextPageMatch()),this.pageMatches[e].length>0&&(this.matchCount+=this.pageMatches[e].length,this.updateUIResultsCount()))}},{key:"extractText",value:function t(){var e=this;if(!this.startedTextExtraction){this.startedTextExtraction=!0,this.pageContents.length=0;for(var r=Promise.resolve(),i=function t(i,n){var a=(0,o.createPromiseCapability)();e.extractTextPromises[i]=a.promise,r=r.then(function(){return e.pdfViewer.getPageTextContent(i).then(function(t){for(var r=t.items,n=[],o=0,s=r.length;o<s;o++)n.push(r[o].str);e.pageContents[i]=n.join(""),a.resolve(i)})})},n=0,a=this.pdfViewer.pagesCount;n<a;n++)i(n,a)}}},{key:"executeCommand",value:function t(e,r){var i=this;null!==this.state&&"findagain"===e||(this.dirtyMatch=!0),this.state=r,this.updateUIState(s.PENDING),this._firstPagePromise.then(function(){i.extractText(),clearTimeout(i.findTimeout),"find"===e?i.findTimeout=setTimeout(i.nextMatch.bind(i),250):i.nextMatch()})}},{key:"updatePage",value:function t(e){this.selected.pageIdx===e&&(this.pdfViewer.currentPageNumber=e+1);var r=this.pdfViewer.getPageView(e);r.textLayer&&r.textLayer.updateMatches()}},{key:"nextMatch",value:function t(){var e=this,r=this.state.findPrevious,i=this.pdfViewer.currentPageNumber-1,n=this.pdfViewer.pagesCount;if(this.active=!0,this.dirtyMatch){this.dirtyMatch=!1,this.selected.pageIdx=this.selected.matchIdx=-1,this.offset.pageIdx=i,this.offset.matchIdx=null,this.hadMatch=!1,this.resumePageIdx=null,this.pageMatches=[],this.matchCount=0,this.pageMatchesLength=null;for(var o=0;o<n;o++)this.updatePage(o),o in this.pendingFindMatches||(this.pendingFindMatches[o]=!0,this.extractTextPromises[o].then(function(t){delete e.pendingFindMatches[t],e.calcFindMatch(t)}))}if(""===this.state.query)return void this.updateUIState(s.FOUND);if(!this.resumePageIdx){var a=this.offset;if(this.pagesToSearch=n,null!==a.matchIdx){var c=this.pageMatches[a.pageIdx].length;if(!r&&a.matchIdx+1<c||r&&a.matchIdx>0)return this.hadMatch=!0,a.matchIdx=r?a.matchIdx-1:a.matchIdx+1,void this.updateMatch(!0);this.advanceOffsetPage(r)}this.nextPageMatch()}}},{key:"matchesReady",value:function t(e){var r=this.offset,i=e.length,n=this.state.findPrevious;return i?(this.hadMatch=!0,r.matchIdx=n?i-1:0,this.updateMatch(!0),!0):(this.advanceOffsetPage(n),!!(r.wrapped&&(r.matchIdx=null,this.pagesToSearch<0))&&(this.updateMatch(!1),!0))}},{key:"updateMatchPosition",value:function t(e,r,i,n){if(this.selected.matchIdx===r&&this.selected.pageIdx===e){var o={top:-50,left:-400};(0,a.scrollIntoView)(i[n],o,!0)}}},{key:"nextPageMatch",value:function t(){null!==this.resumePageIdx&&console.error("There can only be one pending page.");var e=null;do{var r=this.offset.pageIdx;if(!(e=this.pageMatches[r])){this.resumePageIdx=r;break}}while(!this.matchesReady(e))}},{key:"advanceOffsetPage",value:function t(e){var r=this.offset,i=this.extractTextPromises.length;r.pageIdx=e?r.pageIdx-1:r.pageIdx+1,r.matchIdx=null,this.pagesToSearch--,(r.pageIdx>=i||r.pageIdx<0)&&(r.pageIdx=e?i-1:0,r.wrapped=!0)}},{key:"updateMatch",value:function t(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],r=s.NOT_FOUND,i=this.offset.wrapped;if(this.offset.wrapped=!1,e){var n=this.selected.pageIdx;this.selected.pageIdx=this.offset.pageIdx,this.selected.matchIdx=this.offset.matchIdx,r=i?s.WRAPPED:s.FOUND,-1!==n&&n!==this.selected.pageIdx&&this.updatePage(n)}this.updateUIState(r,this.state.findPrevious),-1!==this.selected.pageIdx&&this.updatePage(this.selected.pageIdx)}},{key:"updateUIResultsCount",value:function t(){this.onUpdateResultsCount&&this.onUpdateResultsCount(this.matchCount)}},{key:"updateUIState",value:function t(e,r){this.onUpdateState&&this.onUpdateState(e,r,this.matchCount)}}]),t}();e.FindState=s,e.PDFFindController=f},function(t,e,r){"use strict";function i(t){this.linkService=t.linkService,this.eventBus=t.eventBus||(0,n.getGlobalEventBus)(),this.initialized=!1,this.initialDestination=null,this.initialBookmark=null}Object.defineProperty(e,"__esModule",{value:!0}),e.PDFHistory=void 0;var n=r(2);i.prototype={initialize:function t(e){function r(){a.previousHash=window.location.hash.slice(1),a._pushToHistory({hash:a.previousHash},!1,!0),a._updatePreviousBookmark()}function i(t,e){function r(){window.removeEventListener("popstate",r),window.addEventListener("popstate",i),a._pushToHistory(t,!1,!0),history.forward()}function i(){window.removeEventListener("popstate",i),a.allowHashChange=!0,a.historyUnlocked=!0,e()}a.historyUnlocked=!1,a.allowHashChange=!1,window.addEventListener("popstate",r),history.back()}function n(){var t=a._getPreviousParams(null,!0);if(t){var e=!a.current.dest&&a.current.hash!==a.previousHash;a._pushToHistory(t,!1,e),a._updatePreviousBookmark()}window.removeEventListener("beforeunload",n)}this.initialized=!0,this.reInitialized=!1,this.allowHashChange=!0,this.historyUnlocked=!0,this.isViewerInPresentationMode=!1,this.previousHash=window.location.hash.substring(1),this.currentBookmark="",this.currentPage=0,this.updatePreviousBookmark=!1,this.previousBookmark="",this.previousPage=0,this.nextHashParam="",this.fingerprint=e,this.currentUid=this.uid=0,this.current={};var o=window.history.state;this._isStateObjectDefined(o)?(o.target.dest?this.initialDestination=o.target.dest:this.initialBookmark=o.target.hash,this.currentUid=o.uid,this.uid=o.uid+1,this.current=o.target):(o&&o.fingerprint&&this.fingerprint!==o.fingerprint&&(this.reInitialized=!0),this._pushOrReplaceState({fingerprint:this.fingerprint},!0));var a=this;window.addEventListener("popstate",function t(e){if(a.historyUnlocked){if(e.state)return void a._goTo(e.state);if(0===a.uid){i(a.previousHash&&a.currentBookmark&&a.previousHash!==a.currentBookmark?{hash:a.currentBookmark,page:a.currentPage}:{page:1},function(){r()})}else r()}}),window.addEventListener("beforeunload",n),window.addEventListener("pageshow",function t(e){window.addEventListener("beforeunload",n)}),a.eventBus.on("presentationmodechanged",function(t){a.isViewerInPresentationMode=t.active})},clearHistoryState:function t(){this._pushOrReplaceState(null,!0)},_isStateObjectDefined:function t(e){return!!(e&&e.uid>=0&&e.fingerprint&&this.fingerprint===e.fingerprint&&e.target&&e.target.hash)},_pushOrReplaceState:function t(e,r){r?window.history.replaceState(e,"",document.URL):window.history.pushState(e,"",document.URL)},get isHashChangeUnlocked(){return!this.initialized||this.allowHashChange},_updatePreviousBookmark:function t(){this.updatePreviousBookmark&&this.currentBookmark&&this.currentPage&&(this.previousBookmark=this.currentBookmark,this.previousPage=this.currentPage,this.updatePreviousBookmark=!1)},updateCurrentBookmark:function t(e,r){this.initialized&&(this.currentBookmark=e.substring(1),this.currentPage=0|r,this._updatePreviousBookmark())},updateNextHashParam:function t(e){this.initialized&&(this.nextHashParam=e)},push:function t(e,r){if(this.initialized&&this.historyUnlocked){if(e.dest&&!e.hash&&(e.hash=this.current.hash&&this.current.dest&&this.current.dest===e.dest?this.current.hash:this.linkService.getDestinationHash(e.dest).split("#")[1]),e.page&&(e.page|=0),r){var i=window.history.state.target;return i||(this._pushToHistory(e,!1),this.previousHash=window.location.hash.substring(1)),this.updatePreviousBookmark=!this.nextHashParam,void(i&&this._updatePreviousBookmark())}if(this.nextHashParam){if(this.nextHashParam===e.hash)return this.nextHashParam=null,void(this.updatePreviousBookmark=!0);this.nextHashParam=null}e.hash?this.current.hash?this.current.hash!==e.hash?this._pushToHistory(e,!0):(!this.current.page&&e.page&&this._pushToHistory(e,!1,!0),this.updatePreviousBookmark=!0):this._pushToHistory(e,!0):this.current.page&&e.page&&this.current.page!==e.page&&this._pushToHistory(e,!0)}},_getPreviousParams:function t(e,r){if(!this.currentBookmark||!this.currentPage)return null;if(this.updatePreviousBookmark&&(this.updatePreviousBookmark=!1),this.uid>0&&(!this.previousBookmark||!this.previousPage))return null;if(!this.current.dest&&!e||r){if(this.previousBookmark===this.currentBookmark)return null}else{if(!this.current.page&&!e)return null;if(this.previousPage===this.currentPage)return null}var i={hash:this.currentBookmark,page:this.currentPage};return this.isViewerInPresentationMode&&(i.hash=null),i},_stateObj:function t(e){return{fingerprint:this.fingerprint,uid:this.uid,target:e}},_pushToHistory:function t(e,r,i){if(this.initialized){if(!e.hash&&e.page&&(e.hash="page="+e.page),r&&!i){var n=this._getPreviousParams();if(n){var o=!this.current.dest&&this.current.hash!==this.previousHash;this._pushToHistory(n,!1,o)}}this._pushOrReplaceState(this._stateObj(e),i||0===this.uid),this.currentUid=this.uid++,this.current=e,this.updatePreviousBookmark=!0}},_goTo:function t(e){if(this.initialized&&this.historyUnlocked&&this._isStateObjectDefined(e)){if(!this.reInitialized&&e.uid<this.currentUid){var r=this._getPreviousParams(!0);if(r)return this._pushToHistory(this.current,!1),this._pushToHistory(r,!1),this.currentUid=e.uid,void window.history.back()}this.historyUnlocked=!1,e.target.dest?this.linkService.navigateTo(e.target.dest):this.linkService.setHash(e.target.hash),this.currentUid=e.uid,e.uid>this.uid&&(this.uid=e.uid),this.current=e.target,this.updatePreviousBookmark=!0;var i=window.location.hash.substring(1);this.previousHash!==i&&(this.allowHashChange=!1),this.previousHash=i,this.historyUnlocked=!0}},back:function t(){this.go(-1)},forward:function t(){this.go(1)},go:function t(e){if(this.initialized&&this.historyUnlocked){var r=window.history.state;-1===e&&r&&r.uid>0?window.history.back():1===e&&r&&r.uid<this.uid-1&&window.history.forward()}}},e.PDFHistory=i},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t){var e=[];this.push=function r(i){var n=e.indexOf(i);n>=0&&e.splice(n,1),e.push(i),e.length>t&&e.shift().destroy()},this.resize=function(r){for(t=r;e.length>t;)e.shift().destroy()}}function o(t,e){return e===t||Math.abs(e-t)<1e-15}function a(t){return t.width<=t.height}Object.defineProperty(e,"__esModule",{value:!0}),e.PDFViewer=e.PresentationModeState=void 0;var s=function(){function t(t,e){for(var r=0;r<e.length;r++){var i=e[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,r,i){return r&&t(e.prototype,r),i&&t(e,i),e}}(),c=r(0),l=r(1),h=r(7),u=r(4),f=r(2),d=r(5),p=r(3),g=r(6),v={UNKNOWN:0,NORMAL:1,CHANGING:2,FULLSCREEN:3},m=10,b=function(){function t(e){i(this,t),this.container=e.container,this.viewer=e.viewer||e.container.firstElementChild,this.eventBus=e.eventBus||(0,f.getGlobalEventBus)(),this.linkService=e.linkService||new p.SimpleLinkService,this.downloadManager=e.downloadManager||null,this.removePageBorders=e.removePageBorders||!1,this.enhanceTextSelection=e.enhanceTextSelection||!1,this.renderInteractiveForms=e.renderInteractiveForms||!1,this.enablePrintAutoRotate=e.enablePrintAutoRotate||!1,this.renderer=e.renderer||l.RendererType.CANVAS,this.l10n=e.l10n||l.NullL10n,this.defaultRenderingQueue=!e.renderingQueue,this.defaultRenderingQueue?(this.renderingQueue=new h.PDFRenderingQueue,this.renderingQueue.setViewer(this)):this.renderingQueue=e.renderingQueue,this.scroll=(0,l.watchScroll)(this.container,this._scrollUpdate.bind(this)),this.presentationModeState=v.UNKNOWN,this._resetView(),this.removePageBorders&&this.viewer.classList.add("removePageBorders")}return s(t,[{key:"getPageView",value:function t(e){return this._pages[e]}},{key:"_setCurrentPageNumber",value:function t(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(this._currentPageNumber===e)return void(r&&this._resetCurrentPageView());if(!(0<e&&e<=this.pagesCount))return void console.error('PDFViewer._setCurrentPageNumber: "'+e+'" is out of bounds.');var i={source:this,pageNumber:e,pageLabel:this._pageLabels&&this._pageLabels[e-1]};this._currentPageNumber=e,this.eventBus.dispatch("pagechanging",i),this.eventBus.dispatch("pagechange",i),r&&this._resetCurrentPageView()}},{key:"setDocument",value:function t(e){var r=this;if(this.pdfDocument&&(this._cancelRendering(),this._resetView()),this.pdfDocument=e,e){var i=e.numPages,n=(0,c.createPromiseCapability)();this.pagesPromise=n.promise,n.promise.then(function(){r._pageViewsReady=!0,r.eventBus.dispatch("pagesloaded",{source:r,pagesCount:i})});var o=!1,a=(0,c.createPromiseCapability)();this.onePageRendered=a.promise;var s=function t(e){e.onBeforeDraw=function(){r._buffer.push(e)},e.onAfterDraw=function(){o||(o=!0,a.resolve())}},h=e.getPage(1);return this.firstPagePromise=h,h.then(function(t){for(var o=r.currentScale,h=t.getViewport(o*l.CSS_UNITS),u=1;u<=i;++u){var f=null;c.PDFJS.disableTextLayer||(f=r);var p=new d.PDFPageView({container:r.viewer,eventBus:r.eventBus,id:u,scale:o,defaultViewport:h.clone(),renderingQueue:r.renderingQueue,textLayerFactory:f,annotationLayerFactory:r,enhanceTextSelection:r.enhanceTextSelection,renderInteractiveForms:r.renderInteractiveForms,renderer:r.renderer,l10n:r.l10n});s(p),r._pages.push(p)}a.promise.then(function(){if(c.PDFJS.disableAutoFetch)return void n.resolve();for(var t=i,o=function i(o){e.getPage(o).then(function(e){var i=r._pages[o-1];i.pdfPage||i.setPdfPage(e),r.linkService.cachePageRef(o,e.ref),0==--t&&n.resolve()})},a=1;a<=i;++a)o(a)}),r.eventBus.dispatch("pagesinit",{source:r}),r.defaultRenderingQueue&&r.update(),r.findController&&r.findController.resolveFirstPage()})}}},{key:"setPageLabels",value:function t(e){if(this.pdfDocument){e?e instanceof Array&&this.pdfDocument.numPages===e.length?this._pageLabels=e:(this._pageLabels=null,console.error("PDFViewer.setPageLabels: Invalid page labels.")):this._pageLabels=null;for(var r=0,i=this._pages.length;r<i;r++){var n=this._pages[r],o=this._pageLabels&&this._pageLabels[r];n.setPageLabel(o)}}}},{key:"_resetView",value:function t(){this._pages=[],this._currentPageNumber=1,this._currentScale=l.UNKNOWN_SCALE,this._currentScaleValue=null,this._pageLabels=null,this._buffer=new n(10),this._location=null,this._pagesRotation=0,this._pagesRequests=[],this._pageViewsReady=!1,this.viewer.textContent=""}},{key:"_scrollUpdate",value:function t(){0!==this.pagesCount&&this.update()}},{key:"_setScaleDispatchEvent",value:function t(e,r){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n={source:this,scale:e,presetValue:i?r:void 0};this.eventBus.dispatch("scalechanging",n),this.eventBus.dispatch("scalechange",n)}},{key:"_setScaleUpdatePages",value:function t(e,r){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(this._currentScaleValue=r.toString(),o(this._currentScale,e))return void(n&&this._setScaleDispatchEvent(e,r,!0));for(var a=0,s=this._pages.length;a<s;a++)this._pages[a].update(e);if(this._currentScale=e,!i){var l=this._currentPageNumber,h=void 0;!this._location||c.PDFJS.ignoreCurrentPositionOnZoom||this.isInPresentationMode||this.isChangingPresentationMode||(l=this._location.pageNumber,h=[null,{name:"XYZ"},this._location.left,this._location.top,null]),this.scrollPageIntoView({pageNumber:l,destArray:h,allowNegativeOffset:!0})}this._setScaleDispatchEvent(e,r,n),this.defaultRenderingQueue&&this.update()}},{key:"_setScale",value:function t(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=parseFloat(e);if(i>0)this._setScaleUpdatePages(i,e,r,!1);else{var n=this._pages[this._currentPageNumber-1];if(!n)return;var o=this.isInPresentationMode||this.removePageBorders?0:l.SCROLLBAR_PADDING,a=this.isInPresentationMode||this.removePageBorders?0:l.VERTICAL_PADDING,s=(this.container.clientWidth-o)/n.width*n.scale,c=(this.container.clientHeight-a)/n.height*n.scale;switch(e){case"page-actual":i=1;break;case"page-width":i=s;break;case"page-height":i=c;break;case"page-fit":i=Math.min(s,c);break;case"auto":var h=n.width>n.height,u=h?Math.min(c,s):s;i=Math.min(l.MAX_AUTO_SCALE,u);break;default:return void console.error('PDFViewer._setScale: "'+e+'" is an unknown zoom value.')}this._setScaleUpdatePages(i,e,r,!0)}}},{key:"_resetCurrentPageView",value:function t(){this.isInPresentationMode&&this._setScale(this._currentScaleValue,!0);var e=this._pages[this._currentPageNumber-1];(0,l.scrollIntoView)(e.div)}},{key:"scrollPageIntoView",value:function t(e){if(this.pdfDocument){if(arguments.length>1||"number"==typeof e){console.warn("Call of scrollPageIntoView() with obsolete signature.");var r={};"number"==typeof e&&(r.pageNumber=e),arguments[1]instanceof Array&&(r.destArray=arguments[1]),e=r}var i=e.pageNumber||0,n=e.destArray||null,o=e.allowNegativeOffset||!1;if(this.isInPresentationMode||!n)return void this._setCurrentPageNumber(i,!0);var a=this._pages[i-1];if(!a)return void console.error('PDFViewer.scrollPageIntoView: Invalid "pageNumber" parameter.');var s=0,c=0,h=0,u=0,f=void 0,d=void 0,p=a.rotation%180!=0,g=(p?a.height:a.width)/a.scale/l.CSS_UNITS,v=(p?a.width:a.height)/a.scale/l.CSS_UNITS,m=0;switch(n[1].name){case"XYZ":s=n[2],c=n[3],m=n[4],s=null!==s?s:0,c=null!==c?c:v;break;case"Fit":case"FitB":m="page-fit";break;case"FitH":case"FitBH":c=n[2],m="page-width",null===c&&this._location&&(s=this._location.left,c=this._location.top);break;case"FitV":case"FitBV":s=n[2],h=g,u=v,m="page-height";break;case"FitR":s=n[2],c=n[3],h=n[4]-s,u=n[5]-c;var b=this.removePageBorders?0:l.SCROLLBAR_PADDING,y=this.removePageBorders?0:l.VERTICAL_PADDING;f=(this.container.clientWidth-b)/h/l.CSS_UNITS,d=(this.container.clientHeight-y)/u/l.CSS_UNITS,m=Math.min(Math.abs(f),Math.abs(d));break;default:return void console.error('PDFViewer.scrollPageIntoView: "'+n[1].name+'" is not a valid destination type.')}if(m&&m!==this._currentScale?this.currentScaleValue=m:this._currentScale===l.UNKNOWN_SCALE&&(this.currentScaleValue=l.DEFAULT_SCALE_VALUE),"page-fit"===m&&!n[4])return void(0,l.scrollIntoView)(a.div);var _=[a.viewport.convertToViewportPoint(s,c),a.viewport.convertToViewportPoint(s+h,c+u)],w=Math.min(_[0][0],_[1][0]),S=Math.min(_[0][1],_[1][1]);o||(w=Math.max(w,0),S=Math.max(S,0)),(0,l.scrollIntoView)(a.div,{left:w,top:S})}}},{key:"_updateLocation",value:function t(e){var r=this._currentScale,i=this._currentScaleValue,n=parseFloat(i)===r?Math.round(1e4*r)/100:i,o=e.id,a="#page="+o;a+="&zoom="+n;var s=this._pages[o-1],c=this.container,l=s.getPagePoint(c.scrollLeft-e.x,c.scrollTop-e.y),h=Math.round(l[0]),u=Math.round(l[1]);a+=","+h+","+u,this._location={pageNumber:o,scale:n,top:u,left:h,pdfOpenParams:a}}},{key:"update",value:function t(){var e=this._getVisiblePages(),r=e.views;if(0!==r.length){var i=Math.max(10,2*r.length+1);this._buffer.resize(i),this.renderingQueue.renderHighestPriority(e);for(var n=this._currentPageNumber,o=e.first,a=!1,s=0,c=r.length;s<c;++s){var l=r[s];if(l.percent<100)break;if(l.id===n){a=!0;break}}a||(n=r[0].id),this.isInPresentationMode||this._setCurrentPageNumber(n),this._updateLocation(o),this.eventBus.dispatch("updateviewarea",{source:this,location:this._location})}}},{key:"containsElement",value:function t(e){return this.container.contains(e)}},{key:"focus",value:function t(){this.container.focus()}},{key:"_getVisiblePages",value:function t(){if(!this.isInPresentationMode)return(0,l.getVisibleElements)(this.container,this._pages,!0);var e=[],r=this._pages[this._currentPageNumber-1];return e.push({id:r.id,view:r}),{first:r,last:r,views:e}}},{key:"cleanup",value:function t(){for(var e=0,r=this._pages.length;e<r;e++)this._pages[e]&&this._pages[e].renderingState!==h.RenderingStates.FINISHED&&this._pages[e].reset()}},{key:"_cancelRendering",value:function t(){for(var e=0,r=this._pages.length;e<r;e++)this._pages[e]&&this._pages[e].cancelRendering()}},{key:"_ensurePdfPageLoaded",value:function t(e){var r=this;if(e.pdfPage)return Promise.resolve(e.pdfPage);var i=e.id;if(this._pagesRequests[i])return this._pagesRequests[i];var n=this.pdfDocument.getPage(i).then(function(t){return e.pdfPage||e.setPdfPage(t),r._pagesRequests[i]=null,t});return this._pagesRequests[i]=n,n}},{key:"forceRendering",value:function t(e){var r=this,i=e||this._getVisiblePages(),n=this.renderingQueue.getHighestPriority(i,this._pages,this.scroll.down);return!!n&&(this._ensurePdfPageLoaded(n).then(function(){r.renderingQueue.renderView(n)}),!0)}},{key:"getPageTextContent",value:function t(e){return this.pdfDocument.getPage(e+1).then(function(t){return t.getTextContent({normalizeWhitespace:!0})})}},{key:"createTextLayerBuilder",value:function t(e,r,i){var n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return new g.TextLayerBuilder({textLayerDiv:e,eventBus:this.eventBus,pageIndex:r,viewport:i,findController:this.isInPresentationMode?null:this.findController,enhanceTextSelection:!this.isInPresentationMode&&n})}},{key:"createAnnotationLayerBuilder",value:function t(e,r){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:l.NullL10n;return new u.AnnotationLayerBuilder({pageDiv:e,pdfPage:r,renderInteractiveForms:i,linkService:this.linkService,downloadManager:this.downloadManager,l10n:n})}},{key:"setFindController",value:function t(e){this.findController=e}},{key:"getPagesOverview",value:function t(){var e=this._pages.map(function(t){var e=t.pdfPage.getViewport(1);return{width:e.width,height:e.height,rotation:e.rotation}});if(!this.enablePrintAutoRotate)return e;var r=a(e[0]);return e.map(function(t){return r===a(t)?t:{width:t.height,height:t.width,rotation:(t.rotation+90)%360}})}},{key:"pagesCount",get:function t(){return this._pages.length}},{key:"pageViewsReady",get:function t(){return this._pageViewsReady}},{key:"currentPageNumber",get:function t(){return this._currentPageNumber},set:function t(e){if((0|e)!==e)throw new Error("Invalid page number.");this.pdfDocument&&this._setCurrentPageNumber(e,!0)}},{key:"currentPageLabel",get:function t(){return this._pageLabels&&this._pageLabels[this._currentPageNumber-1]},set:function t(e){var r=0|e;if(this._pageLabels){var i=this._pageLabels.indexOf(e);i>=0&&(r=i+1)}this.currentPageNumber=r}},{key:"currentScale",get:function t(){return this._currentScale!==l.UNKNOWN_SCALE?this._currentScale:l.DEFAULT_SCALE},set:function t(e){if(isNaN(e))throw new Error("Invalid numeric scale");this.pdfDocument&&this._setScale(e,!1)}},{key:"currentScaleValue",get:function t(){return this._currentScaleValue},set:function t(e){this.pdfDocument&&this._setScale(e,!1)}},{key:"pagesRotation",get:function t(){return this._pagesRotation},set:function t(e){if("number"!=typeof e||e%90!=0)throw new Error("Invalid pages rotation angle.");if(this.pdfDocument){this._pagesRotation=e;for(var r=0,i=this._pages.length;r<i;r++){var n=this._pages[r];n.update(n.scale,e)}this._setScale(this._currentScaleValue,!0),this.defaultRenderingQueue&&this.update()}}},{key:"isInPresentationMode",get:function t(){return this.presentationModeState===v.FULLSCREEN}},{key:"isChangingPresentationMode",get:function t(){return this.presentationModeState===v.CHANGING}},{key:"isHorizontalScrollbarEnabled",get:function t(){return!this.isInPresentationMode&&this.container.scrollWidth>this.container.clientWidth}},{key:"hasEqualPageSizes",get:function t(){for(var e=this._pages[0],r=1,i=this._pages.length;r<i;++r){var n=this._pages[r];if(n.width!==e.width||n.height!==e.height)return!1}return!0}}]),t}();e.PresentationModeState=v,e.PDFViewer=b},function(t,e,r){"use strict";document.webL10n=function(t,e,r){function i(){return e.querySelectorAll('link[type="application/l10n"]')}function n(){var t=e.querySelector('script[type="application/l10n"]');return t?JSON.parse(t.innerHTML):null}function o(t){return t?t.querySelectorAll("*[data-l10n-id]"):[]}function a(t){if(!t)return{};var e=t.getAttribute("data-l10n-id"),r=t.getAttribute("data-l10n-args"),i={};if(r)try{i=JSON.parse(r)}catch(t){console.warn("could not parse arguments for #"+e)}return{id:e,args:i}}function s(t){var r=e.createEvent("Event");r.initEvent("localized",!0,!1),r.language=t,e.dispatchEvent(r)}function c(t,e,r){e=e||function t(e){},r=r||function t(){};var i=new XMLHttpRequest;i.open("GET",t,A),i.overrideMimeType&&i.overrideMimeType("text/plain; charset=utf-8"),i.onreadystatechange=function(){4==i.readyState&&(200==i.status||0===i.status?e(i.responseText):r())},i.onerror=r,i.ontimeout=r;try{i.send(null)}catch(t){r()}}function l(t,e,r,i){function n(t){return t.lastIndexOf("\\")<0?t:t.replace(/\\\\/g,"\\").replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\b/g,"\b").replace(/\\f/g,"\f").replace(/\\{/g,"{").replace(/\\}/g,"}").replace(/\\"/g,'"').replace(/\\'/g,"'")}function o(t,r){function i(t,r,i){function c(){for(;;){if(!p.length)return void i();var t=p.shift();if(!h.test(t)){if(r){if(b=u.exec(t)){g=b[1].toLowerCase(),m="*"!==g&&g!==e&&g!==v;continue}if(m)continue;if(b=f.exec(t))return void o(a+b[1],c)}var l=t.match(d);l&&3==l.length&&(s[l[1]]=n(l[2]))}}}var p=t.replace(l,"").split(/[\r\n]+/),g="*",v=e.split("-",1)[0],m=!1,b="";c()}function o(t,e){c(t,function(t){i(t,!1,e)},function(){console.warn(t+" not found."),e()})}var s={},l=/^\s*|\s*$/,h=/^\s*#|^\s*$/,u=/^\s*\[(.*)\]\s*$/,f=/^\s*@import\s+url\((.*)\)\s*$/i,d=/^([^=\s]*)\s*=\s*(.+)$/;i(t,!0,function(){r(s)})}var a=t.replace(/[^\/]*$/,"")||"./";c(t,function(t){_+=t,o(t,function(t){for(var e in t){var i,n,o=e.lastIndexOf(".");o>0?(i=e.substring(0,o),n=e.substr(o+1)):(i=e,n=w),y[i]||(y[i]={}),y[i][n]=t[e]}r&&r()})},i)}function h(t,e){function r(t){var e=t.href;this.load=function(t,r){l(e,t,r,function(){console.warn(e+" not found."),console.warn('"'+t+'" resource not found'),S="",r()})}}t&&(t=t.toLowerCase()),e=e||function t(){},u(),S=t;var o=i(),a=o.length;if(0===a){var c=n();if(c&&c.locales&&c.default_locale){if(console.log("using the embedded JSON directory, early way out"),!(y=c.locales[t])){var h=c.default_locale.toLowerCase();for(var f in c.locales){if((f=f.toLowerCase())===t){y=c.locales[t];break}f===h&&(y=c.locales[h])}}e()}else console.log("no resource to load, early way out");return s(t),void(C="complete")}var d=null,p=0;d=function r(){++p>=a&&(e(),s(t),C="complete")};for(var g=0;g<a;g++){new r(o[g]).load(t,d)}}function u(){y={},_="",S=""}function f(t){function e(t,e){return-1!==e.indexOf(t)}function r(t,e,r){return e<=t&&t<=r}var i={af:3,ak:4,am:4,ar:1,asa:3,az:0,be:11,bem:3,bez:3,bg:3,bh:4,bm:0,bn:3,bo:0,br:20,brx:3,bs:11,ca:3,cgg:3,chr:3,cs:12,cy:17,da:3,de:3,dv:3,dz:0,ee:3,el:3,en:3,eo:3,es:3,et:3,eu:3,fa:0,ff:5,fi:3,fil:4,fo:3,fr:5,fur:3,fy:3,ga:8,gd:24,gl:3,gsw:3,gu:3,guw:4,gv:23,ha:3,haw:3,he:2,hi:4,hr:11,hu:0,id:0,ig:0,ii:0,is:3,it:3,iu:7,ja:0,jmc:3,jv:0,ka:0,kab:5,kaj:3,kcg:3,kde:0,kea:0,kk:3,kl:3,km:0,kn:0,ko:0,ksb:3,ksh:21,ku:3,kw:7,lag:18,lb:3,lg:3,ln:4,lo:0,lt:10,lv:6,mas:3,mg:4,mk:16,ml:3,mn:3,mo:9,mr:3,ms:0,mt:15,my:0,nah:3,naq:7,nb:3,nd:3,ne:3,nl:3,nn:3,no:3,nr:3,nso:4,ny:3,nyn:3,om:3,or:3,pa:3,pap:3,pl:13,ps:3,pt:3,rm:3,ro:9,rof:3,ru:11,rwk:3,sah:0,saq:3,se:7,seh:3,ses:0,sg:0,sh:11,shi:19,sk:12,sl:14,sma:7,smi:7,smj:7,smn:7,sms:7,sn:3,so:3,sq:3,sr:11,ss:3,ssy:3,st:3,sv:3,sw:3,syr:3,ta:3,te:3,teo:3,th:0,ti:4,tig:3,tk:3,tl:4,tn:3,to:0,tr:0,ts:3,tzm:22,uk:11,ur:3,ve:3,vi:0,vun:3,wa:4,wae:3,wo:0,xh:3,xog:3,yo:0,zh:0,zu:3},n={0:function t(e){return"other"},1:function t(e){return r(e%100,3,10)?"few":0===e?"zero":r(e%100,11,99)?"many":2==e?"two":1==e?"one":"other"},2:function t(e){return 0!==e&&e%10==0?"many":2==e?"two":1==e?"one":"other"},3:function t(e){return 1==e?"one":"other"},4:function t(e){return r(e,0,1)?"one":"other"},5:function t(e){return r(e,0,2)&&2!=e?"one":"other"},6:function t(e){return 0===e?"zero":e%10==1&&e%100!=11?"one":"other"},7:function t(e){return 2==e?"two":1==e?"one":"other"},8:function t(e){return r(e,3,6)?"few":r(e,7,10)?"many":2==e?"two":1==e?"one":"other"},9:function t(e){return 0===e||1!=e&&r(e%100,1,19)?"few":1==e?"one":"other"},10:function t(e){return r(e%10,2,9)&&!r(e%100,11,19)?"few":e%10!=1||r(e%100,11,19)?"other":"one"},11:function t(e){return r(e%10,2,4)&&!r(e%100,12,14)?"few":e%10==0||r(e%10,5,9)||r(e%100,11,14)?"many":e%10==1&&e%100!=11?"one":"other"},12:function t(e){return r(e,2,4)?"few":1==e?"one":"other"},13:function t(e){return r(e%10,2,4)&&!r(e%100,12,14)?"few":1!=e&&r(e%10,0,1)||r(e%10,5,9)||r(e%100,12,14)?"many":1==e?"one":"other"},14:function t(e){return r(e%100,3,4)?"few":e%100==2?"two":e%100==1?"one":"other"},15:function t(e){return 0===e||r(e%100,2,10)?"few":r(e%100,11,19)?"many":1==e?"one":"other"},16:function t(e){return e%10==1&&11!=e?"one":"other"},17:function t(e){return 3==e?"few":0===e?"zero":6==e?"many":2==e?"two":1==e?"one":"other"},18:function t(e){return 0===e?"zero":r(e,0,2)&&0!==e&&2!=e?"one":"other"},19:function t(e){return r(e,2,10)?"few":r(e,0,1)?"one":"other"},20:function t(i){return!r(i%10,3,4)&&i%10!=9||r(i%100,10,19)||r(i%100,70,79)||r(i%100,90,99)?i%1e6==0&&0!==i?"many":i%10!=2||e(i%100,[12,72,92])?i%10!=1||e(i%100,[11,71,91])?"other":"one":"two":"few"},21:function t(e){return 0===e?"zero":1==e?"one":"other"},22:function t(e){return r(e,0,1)||r(e,11,99)?"one":"other"},23:function t(e){return r(e%10,1,2)||e%20==0?"one":"other"},24:function t(i){return r(i,3,10)||r(i,13,19)?"few":e(i,[2,12])?"two":e(i,[1,11])?"one":"other"}},o=i[t.replace(/-.*$/,"")];return o in n?n[o]:(console.warn("plural form unknown for ["+t+"]"),function(){return"other"})}function d(t,e,r){var i=y[t];if(!i){if(console.warn("#"+t+" is undefined."),!r)return null;i=r}var n={};for(var o in i){var a=i[o];a=p(a,e,t,o),a=g(a,e,t),n[o]=a}return n}function p(t,e,r,i){var n=/\{\[\s*([a-zA-Z]+)\(([a-zA-Z]+)\)\s*\]\}/,o=n.exec(t);if(!o||!o.length)return t;var a=o[1],s=o[2],c;if(e&&s in e?c=e[s]:s in y&&(c=y[s]),a in x){t=(0,x[a])(t,c,r,i)}return t}function g(t,e,r){var i=/\{\{\s*(.+?)\s*\}\}/g;return t.replace(i,function(t,i){return e&&i in e?e[i]:i in y?y[i]:(console.log("argument {{"+i+"}} for #"+r+" is undefined."),t)})}function v(t){var r=a(t);if(r.id){var i=d(r.id,r.args);if(!i)return void console.warn("#"+r.id+" is undefined.");if(i[w]){if(0===m(t))t[w]=i[w];else{for(var n=t.childNodes,o=!1,s=0,c=n.length;s<c;s++)3===n[s].nodeType&&/\S/.test(n[s].nodeValue)&&(o?n[s].nodeValue="":(n[s].nodeValue=i[w],o=!0));if(!o){var l=e.createTextNode(i[w]);t.insertBefore(l,t.firstChild)}}delete i[w]}for(var h in i)t[h]=i[h]}}function m(t){if(t.children)return t.children.length;if(void 0!==t.childElementCount)return t.childElementCount;for(var e=0,r=0;r<t.childNodes.length;r++)e+=1===t.nodeType?1:0;return e}function b(t){t=t||e.documentElement;for(var r=o(t),i=r.length,n=0;n<i;n++)v(r[n]);v(t)}var y={},_="",w="textContent",S="",x={},C="loading",A=!0;return x.plural=function(t,e,r,i){var n=parseFloat(e);if(isNaN(n))return t;if(i!=w)return t;x._pluralRules||(x._pluralRules=f(S));var o="["+x._pluralRules(n)+"]";return 0===n&&r+"[zero]"in y?t=y[r+"[zero]"][i]:1==n&&r+"[one]"in y?t=y[r+"[one]"][i]:2==n&&r+"[two]"in y?t=y[r+"[two]"][i]:r+o in y?t=y[r+o][i]:r+"[other]"in y&&(t=y[r+"[other]"][i]),t},{get:function t(e,r,i){var n=e.lastIndexOf("."),o=w;n>0&&(o=e.substr(n+1),e=e.substring(0,n));var a;i&&(a={},a[o]=i);var s=d(e,r,a);return s&&o in s?s[o]:"{{"+e+"}}"},getData:function t(){return y},getText:function t(){return _},getLanguage:function t(){return S},setLanguage:function t(e,r){h(e,function(){r&&r()})},getDirection:function t(){var e=["ar","he","fa","ps","ur"],r=S.split("-",1)[0];return e.indexOf(r)>=0?"rtl":"ltr"},translate:b,getReadyState:function t(){return C},ready:function r(i){i&&("complete"==C||"interactive"==C?t.setTimeout(function(){i()}):e.addEventListener&&e.addEventListener("localized",function t(){e.removeEventListener("localized",t),i()}))}}}(window,document)},function(t,e,r){"use strict";var i=r(0),n=r(12),o=r(5),a=r(3),s=r(6),c=r(4),l=r(11),h=r(10),u=r(1),f=r(8),d=r(9),p=i.PDFJS;p.PDFViewer=n.PDFViewer,p.PDFPageView=o.PDFPageView,p.PDFLinkService=a.PDFLinkService,p.TextLayerBuilder=s.TextLayerBuilder,p.DefaultTextLayerFactory=s.DefaultTextLayerFactory,p.AnnotationLayerBuilder=c.AnnotationLayerBuilder,p.DefaultAnnotationLayerFactory=c.DefaultAnnotationLayerFactory,p.PDFHistory=l.PDFHistory,p.PDFFindController=h.PDFFindController,p.EventBus=u.EventBus,p.DownloadManager=f.DownloadManager,p.ProgressBar=u.ProgressBar,p.GenericL10n=d.GenericL10n,p.NullL10n=u.NullL10n,e.PDFJS=p}])})},function(t,e,r){"use strict";function i(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===t[e-2]?2:"="===t[e-1]?1:0}function n(t){return 3*t.length/4-i(t)}function o(t){var e,r,n,o,a,s=t.length;o=i(t),a=new u(3*s/4-o),r=o>0?s-4:s;var c=0;for(e=0;e<r;e+=4)n=h[t.charCodeAt(e)]<<18|h[t.charCodeAt(e+1)]<<12|h[t.charCodeAt(e+2)]<<6|h[t.charCodeAt(e+3)],a[c++]=n>>16&255,a[c++]=n>>8&255,a[c++]=255&n;return 2===o?(n=h[t.charCodeAt(e)]<<2|h[t.charCodeAt(e+1)]>>4,a[c++]=255&n):1===o&&(n=h[t.charCodeAt(e)]<<10|h[t.charCodeAt(e+1)]<<4|h[t.charCodeAt(e+2)]>>2,a[c++]=n>>8&255,a[c++]=255&n),a}function a(t){return l[t>>18&63]+l[t>>12&63]+l[t>>6&63]+l[63&t]}function s(t,e,r){for(var i,n=[],o=e;o<r;o+=3)i=(t[o]<<16)+(t[o+1]<<8)+t[o+2],n.push(a(i));return n.join("")}function c(t){for(var e,r=t.length,i=r%3,n="",o=[],a=16383,c=0,h=r-i;c<h;c+=16383)o.push(s(t,c,c+16383>h?h:c+16383));return 1===i?(e=t[r-1],n+=l[e>>2],n+=l[e<<4&63],n+="=="):2===i&&(e=(t[r-2]<<8)+t[r-1],n+=l[e>>10],n+=l[e>>4&63],n+=l[e<<2&63],n+="="),o.push(n),o.join("")}e.byteLength=n,e.toByteArray=o,e.fromByteArray=c;for(var l=[],h=[],u="undefined"!=typeof Uint8Array?Uint8Array:Array,f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",d=0,p=f.length;d<p;++d)l[d]=f[d],h[f.charCodeAt(d)]=d;h["-".charCodeAt(0)]=62,h["_".charCodeAt(0)]=63},function(t,e){e.read=function(t,e,r,i,n){var o,a,s=8*n-i-1,c=(1<<s)-1,l=c>>1,h=-7,u=r?n-1:0,f=r?-1:1,d=t[e+u];for(u+=f,o=d&(1<<-h)-1,d>>=-h,h+=s;h>0;o=256*o+t[e+u],u+=f,h-=8);for(a=o&(1<<-h)-1,o>>=-h,h+=i;h>0;a=256*a+t[e+u],u+=f,h-=8);if(0===o)o=1-l;else{if(o===c)return a?NaN:1/0*(d?-1:1);a+=Math.pow(2,i),o-=l}return(d?-1:1)*a*Math.pow(2,o-i)},e.write=function(t,e,r,i,n,o){var a,s,c,l=8*o-n-1,h=(1<<l)-1,u=h>>1,f=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,d=i?0:o-1,p=i?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,a=h):(a=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-a))<1&&(a--,c*=2),e+=a+u>=1?f/c:f*Math.pow(2,1-u),e*c>=2&&(a++,c/=2),a+u>=h?(s=0,a=h):a+u>=1?(s=(e*c-1)*Math.pow(2,n),a+=u):(s=e*Math.pow(2,u-1)*Math.pow(2,n),a=0));n>=8;t[r+d]=255&s,d+=p,s/=256,n-=8);for(a=a<<n|s,l+=n;l>0;t[r+d]=255&a,d+=p,a/=256,l-=8);t[r+d-p]|=128*g}},function(t,e,r){(function(t,i){function n(e,r,i){function n(){for(var t;null!==(t=e.read());)s.push(t),c+=t.length;e.once("readable",n)}function o(t){e.removeListener("end",a),e.removeListener("readable",n),i(t)}function a(){var r=t.concat(s,c);s=[],i(null,r),e.close()}var s=[],c=0;e.on("error",o),e.on("end",a),e.end(r),n()}function o(e,r){if("string"==typeof r&&(r=new t(r)),!t.isBuffer(r))throw new TypeError("Not a string or buffer");var i=g.Z_FINISH;return e._processChunk(r,i)}function a(t){if(!(this instanceof a))return new a(t);d.call(this,t,g.DEFLATE)}function s(t){if(!(this instanceof s))return new s(t);d.call(this,t,g.INFLATE)}function c(t){if(!(this instanceof c))return new c(t);d.call(this,t,g.GZIP)}function l(t){if(!(this instanceof l))return new l(t);d.call(this,t,g.GUNZIP)}function h(t){if(!(this instanceof h))return new h(t);d.call(this,t,g.DEFLATERAW)}function u(t){if(!(this instanceof u))return new u(t);d.call(this,t,g.INFLATERAW)}function f(t){if(!(this instanceof f))return new f(t);d.call(this,t,g.UNZIP)}function d(r,i){if(this._opts=r=r||{},this._chunkSize=r.chunkSize||e.Z_DEFAULT_CHUNK,p.call(this,r),r.flush&&r.flush!==g.Z_NO_FLUSH&&r.flush!==g.Z_PARTIAL_FLUSH&&r.flush!==g.Z_SYNC_FLUSH&&r.flush!==g.Z_FULL_FLUSH&&r.flush!==g.Z_FINISH&&r.flush!==g.Z_BLOCK)throw new Error("Invalid flush flag: "+r.flush);if(this._flushFlag=r.flush||g.Z_NO_FLUSH,r.chunkSize&&(r.chunkSize<e.Z_MIN_CHUNK||r.chunkSize>e.Z_MAX_CHUNK))throw new Error("Invalid chunk size: "+r.chunkSize);if(r.windowBits&&(r.windowBits<e.Z_MIN_WINDOWBITS||r.windowBits>e.Z_MAX_WINDOWBITS))throw new Error("Invalid windowBits: "+r.windowBits);if(r.level&&(r.level<e.Z_MIN_LEVEL||r.level>e.Z_MAX_LEVEL))throw new Error("Invalid compression level: "+r.level);if(r.memLevel&&(r.memLevel<e.Z_MIN_MEMLEVEL||r.memLevel>e.Z_MAX_MEMLEVEL))throw new Error("Invalid memLevel: "+r.memLevel);if(r.strategy&&r.strategy!=e.Z_FILTERED&&r.strategy!=e.Z_HUFFMAN_ONLY&&r.strategy!=e.Z_RLE&&r.strategy!=e.Z_FIXED&&r.strategy!=e.Z_DEFAULT_STRATEGY)throw new Error("Invalid strategy: "+r.strategy);if(r.dictionary&&!t.isBuffer(r.dictionary))throw new Error("Invalid dictionary: it should be a Buffer instance");this._binding=new g.Zlib(i);var n=this;this._hadError=!1,this._binding.onerror=function(t,r){n._binding=null,n._hadError=!0;var i=new Error(t);i.errno=r,i.code=e.codes[r],n.emit("error",i)};var o=e.Z_DEFAULT_COMPRESSION;"number"==typeof r.level&&(o=r.level);var a=e.Z_DEFAULT_STRATEGY;"number"==typeof r.strategy&&(a=r.strategy),this._binding.init(r.windowBits||e.Z_DEFAULT_WINDOWBITS,o,r.memLevel||e.Z_DEFAULT_MEMLEVEL,a,r.dictionary),this._buffer=new t(this._chunkSize),this._offset=0,this._closed=!1,this._level=o,this._strategy=a,this.once("end",this.close)}var p=r(43),g=r(50),v=r(24),m=r(60).ok;g.Z_MIN_WINDOWBITS=8,g.Z_MAX_WINDOWBITS=15,g.Z_DEFAULT_WINDOWBITS=15,g.Z_MIN_CHUNK=64,g.Z_MAX_CHUNK=1/0,g.Z_DEFAULT_CHUNK=16384,g.Z_MIN_MEMLEVEL=1,g.Z_MAX_MEMLEVEL=9,g.Z_DEFAULT_MEMLEVEL=8,g.Z_MIN_LEVEL=-1,g.Z_MAX_LEVEL=9,g.Z_DEFAULT_LEVEL=g.Z_DEFAULT_COMPRESSION,Object.keys(g).forEach(function(t){t.match(/^Z/)&&(e[t]=g[t])}),e.codes={Z_OK:g.Z_OK,Z_STREAM_END:g.Z_STREAM_END,Z_NEED_DICT:g.Z_NEED_DICT,Z_ERRNO:g.Z_ERRNO,Z_STREAM_ERROR:g.Z_STREAM_ERROR,Z_DATA_ERROR:g.Z_DATA_ERROR,Z_MEM_ERROR:g.Z_MEM_ERROR,Z_BUF_ERROR:g.Z_BUF_ERROR,Z_VERSION_ERROR:g.Z_VERSION_ERROR},Object.keys(e.codes).forEach(function(t){e.codes[e.codes[t]]=t}),e.Deflate=a,e.Inflate=s,e.Gzip=c,e.Gunzip=l,e.DeflateRaw=h,e.InflateRaw=u,e.Unzip=f,e.createDeflate=function(t){return new a(t)},e.createInflate=function(t){return new s(t)},e.createDeflateRaw=function(t){return new h(t)},e.createInflateRaw=function(t){return new u(t)},e.createGzip=function(t){return new c(t)},e.createGunzip=function(t){return new l(t)},e.createUnzip=function(t){return new f(t)},e.deflate=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new a(e),t,r)},e.deflateSync=function(t,e){return o(new a(e),t)},e.gzip=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new c(e),t,r)},e.gzipSync=function(t,e){return o(new c(e),t)},e.deflateRaw=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new h(e),t,r)},e.deflateRawSync=function(t,e){return o(new h(e),t)},e.unzip=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new f(e),t,r)},e.unzipSync=function(t,e){return o(new f(e),t)},e.inflate=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new s(e),t,r)},e.inflateSync=function(t,e){return o(new s(e),t)},e.gunzip=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new l(e),t,r)},e.gunzipSync=function(t,e){return o(new l(e),t)},e.inflateRaw=function(t,e,r){return"function"==typeof e&&(r=e,e={}),n(new u(e),t,r)},e.inflateRawSync=function(t,e){return o(new u(e),t)},v.inherits(d,p),d.prototype.params=function(t,r,n){if(t<e.Z_MIN_LEVEL||t>e.Z_MAX_LEVEL)throw new RangeError("Invalid compression level: "+t);if(r!=e.Z_FILTERED&&r!=e.Z_HUFFMAN_ONLY&&r!=e.Z_RLE&&r!=e.Z_FIXED&&r!=e.Z_DEFAULT_STRATEGY)throw new TypeError("Invalid strategy: "+r);if(this._level!==t||this._strategy!==r){var o=this;this.flush(g.Z_SYNC_FLUSH,function(){o._binding.params(t,r),o._hadError||(o._level=t,o._strategy=r,n&&n())})}else i.nextTick(n)},d.prototype.reset=function(){return this._binding.reset()},d.prototype._flush=function(e){this._transform(new t(0),"",e)},d.prototype.flush=function(e,r){var n=this._writableState;if(("function"==typeof e||void 0===e&&!r)&&(r=e,e=g.Z_FULL_FLUSH),n.ended)r&&i.nextTick(r);else if(n.ending)r&&this.once("end",r);else if(n.needDrain){var o=this;this.once("drain",function(){o.flush(r)})}else this._flushFlag=e,this.write(new t(0),"",r)},d.prototype.close=function(t){if(t&&i.nextTick(t),!this._closed){this._closed=!0,this._binding.close();var e=this;i.nextTick(function(){e.emit("close")})}},d.prototype._transform=function(e,r,i){var n,o=this._writableState,a=o.ending||o.ended,s=a&&(!e||o.length===e.length);if(null===!e&&!t.isBuffer(e))return i(new Error("invalid input"));s?n=g.Z_FINISH:(n=this._flushFlag,e.length>=o.length&&(this._flushFlag=this._opts.flush||g.Z_NO_FLUSH));var c=this;this._processChunk(e,n,i)},d.prototype._processChunk=function(e,r,i){function n(f,d){if(!c._hadError){var p=a-d;if(m(p>=0,"have should not go down"),p>0){var g=c._buffer.slice(c._offset,c._offset+p);c._offset+=p,l?c.push(g):(h.push(g),u+=g.length)}if((0===d||c._offset>=c._chunkSize)&&(a=c._chunkSize,c._offset=0,c._buffer=new t(c._chunkSize)),0===d){if(s+=o-f,o=f,!l)return!0;var v=c._binding.write(r,e,s,o,c._buffer,c._offset,c._chunkSize);return v.callback=n,void(v.buffer=e)}if(!l)return!1;i()}}var o=e&&e.length,a=this._chunkSize-this._offset,s=0,c=this,l="function"==typeof i;if(!l){var h=[],u=0,f;this.on("error",function(t){f=t});do{var d=this._binding.writeSync(r,e,s,o,this._buffer,this._offset,a)}while(!this._hadError&&n(d[0],d[1]));if(this._hadError)throw f;var p=t.concat(h,u);return this.close(),p}var g=this._binding.write(r,e,s,o,this._buffer,this._offset,a);g.buffer=e,g.callback=n},v.inherits(a,d),v.inherits(s,d),v.inherits(c,d),v.inherits(l,d),v.inherits(h,d),v.inherits(u,d),v.inherits(f,d)}).call(e,r(2).Buffer,r(1))},function(t,e,r){t.exports=r(9).Transform},function(t,e){},function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e,r){t.copy(e,r)}var o=r(10).Buffer;t.exports=function(){function t(){i(this,t),this.head=null,this.tail=null,this.length=0}return t.prototype.push=function t(e){var r={data:e,next:null};this.length>0?this.tail.next=r:this.head=r,this.tail=r,++this.length},t.prototype.unshift=function t(e){var r={data:e,next:this.head};0===this.length&&(this.tail=r),this.head=r,++this.length},t.prototype.shift=function t(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},t.prototype.clear=function t(){this.head=this.tail=null,this.length=0},t.prototype.join=function t(e){if(0===this.length)return"";for(var r=this.head,i=""+r.data;r=r.next;)i+=e+r.data;return i},t.prototype.concat=function t(e){if(0===this.length)return o.alloc(0);if(1===this.length)return this.head.data;for(var r=o.allocUnsafe(e>>>0),i=this.head,a=0;i;)n(i.data,r,a),a+=i.data.length,i=i.next;return r},t}()},function(t,e,r){function i(t,e){this._id=t,this._clearFn=e}var n=Function.prototype.apply;e.setTimeout=function(){return new i(n.call(setTimeout,window,arguments),clearTimeout)},e.setInterval=function(){return new i(n.call(setInterval,window,arguments),clearInterval)},e.clearTimeout=e.clearInterval=function(t){t&&t.close()},i.prototype.unref=i.prototype.ref=function(){},i.prototype.close=function(){this._clearFn.call(window,this._id)},e.enroll=function(t,e){clearTimeout(t._idleTimeoutId),t._idleTimeout=e},e.unenroll=function(t){clearTimeout(t._idleTimeoutId),t._idleTimeout=-1},e._unrefActive=e.active=function(t){clearTimeout(t._idleTimeoutId);var e=t._idleTimeout;e>=0&&(t._idleTimeoutId=setTimeout(function e(){t._onTimeout&&t._onTimeout()},e))},r(47),e.setImmediate=setImmediate,e.clearImmediate=clearImmediate},function(t,e,r){(function(t,e){!function(t,r){"use strict";function i(t){"function"!=typeof t&&(t=new Function(""+t));for(var e=new Array(arguments.length-1),r=0;r<e.length;r++)e[r]=arguments[r+1];var i={callback:t,args:e};return p[d]=i,m(d),d++}function n(t){delete p[t]}function o(t){var e=t.callback,i=t.args;switch(i.length){case 0:e();break;case 1:e(i[0]);break;case 2:e(i[0],i[1]);break;case 3:e(i[0],i[1],i[2]);break;default:e.apply(r,i)}}function a(t){if(g)setTimeout(a,0,t);else{var e=p[t];if(e){g=!0;try{o(e)}finally{n(t),g=!1}}}}function s(){m=function(t){e.nextTick(function(){a(t)})}}function c(){if(t.postMessage&&!t.importScripts){var e=!0,r=t.onmessage;return t.onmessage=function(){e=!1},t.postMessage("","*"),t.onmessage=r,e}}function l(){var e="setImmediate$"+Math.random()+"$",r=function(r){r.source===t&&"string"==typeof r.data&&0===r.data.indexOf(e)&&a(+r.data.slice(e.length))};t.addEventListener?t.addEventListener("message",r,!1):t.attachEvent("onmessage",r),m=function(r){t.postMessage(e+r,"*")}}function h(){var t=new MessageChannel;t.port1.onmessage=function(t){a(t.data)},m=function(e){t.port2.postMessage(e)}}function u(){var t=v.documentElement;m=function(e){var r=v.createElement("script");r.onreadystatechange=function(){a(e),r.onreadystatechange=null,t.removeChild(r),r=null},t.appendChild(r)}}function f(){m=function(t){setTimeout(a,0,t)}}if(!t.setImmediate){var d=1,p={},g=!1,v=t.document,m,b=Object.getPrototypeOf&&Object.getPrototypeOf(t);b=b&&b.setTimeout?b:t,"[object process]"==={}.toString.call(t.process)?s():c()?l():t.MessageChannel?h():v&&"onreadystatechange"in v.createElement("script")?u():f(),b.setImmediate=i,b.clearImmediate=n}}("undefined"==typeof self?void 0===t?this:t:self)}).call(e,r(0),r(1))},function(t,e,r){(function(e){function r(t,e){function r(){if(!n){if(i("throwDeprecation"))throw new Error(e);i("traceDeprecation")?console.trace(e):console.warn(e),n=!0}return t.apply(this,arguments)}if(i("noDeprecation"))return t;var n=!1;return r}function i(t){try{if(!e.localStorage)return!1}catch(t){return!1}var r=e.localStorage[t];return null!=r&&"true"===String(r).toLowerCase()}t.exports=r}).call(e,r(0))},function(t,e,r){"use strict";function i(t){if(!(this instanceof i))return new i(t);n.call(this,t)}t.exports=i;var n=r(20),o=r(5);o.inherits=r(3),o.inherits(i,n),i.prototype._transform=function(t,e,r){r(null,t)}},function(t,e,r){(function(t,i){function n(t){if(t<e.DEFLATE||t>e.UNZIP)throw new TypeError("Bad argument");this.mode=t,this.init_done=!1,this.write_in_progress=!1,this.pending_close=!1,this.windowBits=0,this.level=0,this.memLevel=0,this.strategy=0,this.dictionary=null}function o(t,e){for(var r=0;r<t.length;r++)this[e+r]=t[r]}var a=r(21),s=r(51),c=r(52),l=r(54),h=r(57);for(var u in h)e[u]=h[u];e.NONE=0,e.DEFLATE=1,e.INFLATE=2,e.GZIP=3,e.GUNZIP=4,e.DEFLATERAW=5,e.INFLATERAW=6,e.UNZIP=7,n.prototype.init=function(t,r,i,n,o){switch(this.windowBits=t,this.level=r,this.memLevel=i,this.strategy=n,this.mode!==e.GZIP&&this.mode!==e.GUNZIP||(this.windowBits+=16),this.mode===e.UNZIP&&(this.windowBits+=32),this.mode!==e.DEFLATERAW&&this.mode!==e.INFLATERAW||(this.windowBits=-this.windowBits),this.strm=new s,this.mode){case e.DEFLATE:case e.GZIP:case e.DEFLATERAW:var a=c.deflateInit2(this.strm,this.level,e.Z_DEFLATED,this.windowBits,this.memLevel,this.strategy);break;case e.INFLATE:case e.GUNZIP:case e.INFLATERAW:case e.UNZIP:var a=l.inflateInit2(this.strm,this.windowBits);break;default:throw new Error("Unknown mode "+this.mode)}if(a!==e.Z_OK)return void this._error(a);this.write_in_progress=!1,this.init_done=!0},n.prototype.params=function(){throw new Error("deflateParams Not supported")},n.prototype._writeCheck=function(){if(!this.init_done)throw new Error("write before init");if(this.mode===e.NONE)throw new Error("already finalized");if(this.write_in_progress)throw new Error("write already in progress");if(this.pending_close)throw new Error("close is pending")},n.prototype.write=function(e,r,i,n,o,a,s){this._writeCheck(),this.write_in_progress=!0;var c=this;return t.nextTick(function(){c.write_in_progress=!1;var t=c._write(e,r,i,n,o,a,s);c.callback(t[0],t[1]),c.pending_close&&c.close()}),this},n.prototype.writeSync=function(t,e,r,i,n,o,a){return this._writeCheck(),this._write(t,e,r,i,n,o,a)},n.prototype._write=function(t,r,n,a,s,h,u){if(this.write_in_progress=!0,t!==e.Z_NO_FLUSH&&t!==e.Z_PARTIAL_FLUSH&&t!==e.Z_SYNC_FLUSH&&t!==e.Z_FULL_FLUSH&&t!==e.Z_FINISH&&t!==e.Z_BLOCK)throw new Error("Invalid flush value");null==r&&(r=new i(0),a=0,n=0),s._set?s.set=s._set:s.set=o;var f=this.strm;switch(f.avail_in=a,f.input=r,f.next_in=n,f.avail_out=u,f.output=s,f.next_out=h,this.mode){case e.DEFLATE:case e.GZIP:case e.DEFLATERAW:var d=c.deflate(f,t);break;case e.UNZIP:case e.INFLATE:case e.GUNZIP:case e.INFLATERAW:var d=l.inflate(f,t);break;default:throw new Error("Unknown mode "+this.mode)}return d!==e.Z_STREAM_END&&d!==e.Z_OK&&this._error(d),this.write_in_progress=!1,[f.avail_in,f.avail_out]},n.prototype.close=function(){if(this.write_in_progress)return void(this.pending_close=!0);this.pending_close=!1,this.mode===e.DEFLATE||this.mode===e.GZIP||this.mode===e.DEFLATERAW?c.deflateEnd(this.strm):l.inflateEnd(this.strm),this.mode=e.NONE},n.prototype.reset=function(){switch(this.mode){case e.DEFLATE:case e.DEFLATERAW:var t=c.deflateReset(this.strm);break;case e.INFLATE:case e.INFLATERAW:var t=l.inflateReset(this.strm)}t!==e.Z_OK&&this._error(t)},n.prototype._error=function(t){this.onerror(a[t]+": "+this.strm.msg,t),this.write_in_progress=!1,this.pending_close&&this.close()},e.Zlib=n}).call(e,r(1),r(2).Buffer)},function(t,e,r){"use strict";function i(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}t.exports=i},function(t,e,r){"use strict";function i(t,e){return t.msg=D[e],e}function n(t){return(t<<1)-(t>4?9:0)}function o(t){for(var e=t.length;--e>=0;)t[e]=0}function a(t){var e=t.state,r=e.pending;r>t.avail_out&&(r=t.avail_out),0!==r&&(E.arraySet(t.output,e.pending_buf,e.pending_out,r,t.next_out),t.next_out+=r,e.pending_out+=r,t.total_out+=r,t.avail_out-=r,e.pending-=r,0===e.pending&&(e.pending_out=0))}function s(t,e){O._tr_flush_block(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,a(t.strm)}function c(t,e){t.pending_buf[t.pending++]=e}function l(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e}function h(t,e,r,i){var n=t.avail_in;return n>i&&(n=i),0===n?0:(t.avail_in-=n,E.arraySet(e,t.input,t.next_in,n,r),1===t.state.wrap?t.adler=R(t.adler,e,n,r):2===t.state.wrap&&(t.adler=L(t.adler,e,n,r)),t.next_in+=n,t.total_in+=n,n)}function u(t,e){var r=t.max_chain_length,i=t.strstart,n,o,a=t.prev_length,s=t.nice_match,c=t.strstart>t.w_size-ht?t.strstart-(t.w_size-ht):0,l=t.window,h=t.w_mask,u=t.prev,f=t.strstart+lt,d=l[i+a-1],p=l[i+a];t.prev_length>=t.good_match&&(r>>=2),s>t.lookahead&&(s=t.lookahead);do{if(n=e,l[n+a]===p&&l[n+a-1]===d&&l[n]===l[i]&&l[++n]===l[i+1]){i+=2,n++;do{}while(l[++i]===l[++n]&&l[++i]===l[++n]&&l[++i]===l[++n]&&l[++i]===l[++n]&&l[++i]===l[++n]&&l[++i]===l[++n]&&l[++i]===l[++n]&&l[++i]===l[++n]&&i<f);if(o=lt-(f-i),i=f-lt,o>a){if(t.match_start=e,a=o,o>=s)break;d=l[i+a-1],p=l[i+a]}}}while((e=u[e&h])>c&&0!=--r);return a<=t.lookahead?a:t.lookahead}function f(t){var e=t.w_size,r,i,n,o,a;do{if(o=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-ht)){E.arraySet(t.window,t.window,e,e,0),t.match_start-=e,t.strstart-=e,t.block_start-=e,i=t.hash_size,r=i;do{n=t.head[--r],t.head[r]=n>=e?n-e:0}while(--i);i=e,r=i;do{n=t.prev[--r],t.prev[r]=n>=e?n-e:0}while(--i);o+=e}if(0===t.strm.avail_in)break;if(i=h(t.strm,t.window,t.strstart+t.lookahead,o),t.lookahead+=i,t.lookahead+t.insert>=ct)for(a=t.strstart-t.insert,t.ins_h=t.window[a],t.ins_h=(t.ins_h<<t.hash_shift^t.window[a+1])&t.hash_mask;t.insert&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[a+ct-1])&t.hash_mask,t.prev[a&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=a,a++,t.insert--,!(t.lookahead+t.insert<ct)););}while(t.lookahead<ht&&0!==t.strm.avail_in)}function d(t,e){var r=65535;for(r>t.pending_buf_size-5&&(r=t.pending_buf_size-5);;){if(t.lookahead<=1){if(f(t),0===t.lookahead&&e===I)return yt;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;var i=t.block_start+r;if((0===t.strstart||t.strstart>=i)&&(t.lookahead=t.strstart-i,t.strstart=i,s(t,!1),0===t.strm.avail_out))return yt;if(t.strstart-t.block_start>=t.w_size-ht&&(s(t,!1),0===t.strm.avail_out))return yt}return t.insert=0,e===F?(s(t,!0),0===t.strm.avail_out?wt:St):(t.strstart>t.block_start&&(s(t,!1),t.strm.avail_out),yt)}function p(t,e){for(var r,i;;){if(t.lookahead<ht){if(f(t),t.lookahead<ht&&e===I)return yt;if(0===t.lookahead)break}if(r=0,t.lookahead>=ct&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+ct-1])&t.hash_mask,r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==r&&t.strstart-r<=t.w_size-ht&&(t.match_length=u(t,r)),t.match_length>=ct)if(i=O._tr_tally(t,t.strstart-t.match_start,t.match_length-ct),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=ct){t.match_length--;do{t.strstart++,t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+ct-1])&t.hash_mask,r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!=--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+1])&t.hash_mask;else i=O._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(i&&(s(t,!1),0===t.strm.avail_out))return yt}return t.insert=t.strstart<ct-1?t.strstart:ct-1,e===F?(s(t,!0),0===t.strm.avail_out?wt:St):t.last_lit&&(s(t,!1),0===t.strm.avail_out)?yt:_t}function g(t,e){for(var r,i,n;;){if(t.lookahead<ht){if(f(t),t.lookahead<ht&&e===I)return yt;if(0===t.lookahead)break}if(r=0,t.lookahead>=ct&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+ct-1])&t.hash_mask,r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=ct-1,0!==r&&t.prev_length<t.max_lazy_match&&t.strstart-r<=t.w_size-ht&&(t.match_length=u(t,r),t.match_length<=5&&(t.strategy===G||t.match_length===ct&&t.strstart-t.match_start>4096)&&(t.match_length=ct-1)),t.prev_length>=ct&&t.match_length<=t.prev_length){n=t.strstart+t.lookahead-ct,i=O._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-ct),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=n&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+ct-1])&t.hash_mask,r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!=--t.prev_length);if(t.match_available=0,t.match_length=ct-1,t.strstart++,i&&(s(t,!1),0===t.strm.avail_out))return yt}else if(t.match_available){if(i=O._tr_tally(t,0,t.window[t.strstart-1]),i&&s(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return yt}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(i=O._tr_tally(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<ct-1?t.strstart:ct-1,e===F?(s(t,!0),0===t.strm.avail_out?wt:St):t.last_lit&&(s(t,!1),0===t.strm.avail_out)?yt:_t}function v(t,e){for(var r,i,n,o,a=t.window;;){if(t.lookahead<=lt){if(f(t),t.lookahead<=lt&&e===I)return yt;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=ct&&t.strstart>0&&(n=t.strstart-1,(i=a[n])===a[++n]&&i===a[++n]&&i===a[++n])){o=t.strstart+lt;do{}while(i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&n<o);t.match_length=lt-(o-n),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=ct?(r=O._tr_tally(t,1,t.match_length-ct),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(r=O._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),r&&(s(t,!1),0===t.strm.avail_out))return yt}return t.insert=0,e===F?(s(t,!0),0===t.strm.avail_out?wt:St):t.last_lit&&(s(t,!1),0===t.strm.avail_out)?yt:_t}function m(t,e){for(var r;;){if(0===t.lookahead&&(f(t),0===t.lookahead)){if(e===I)return yt;break}if(t.match_length=0,r=O._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,r&&(s(t,!1),0===t.strm.avail_out))return yt}return t.insert=0,e===F?(s(t,!0),0===t.strm.avail_out?wt:St):t.last_lit&&(s(t,!1),0===t.strm.avail_out)?yt:_t}function b(t,e,r,i,n){this.good_length=t,this.max_lazy=e,this.nice_length=r,this.max_chain=i,this.func=n}function y(t){t.window_size=2*t.w_size,o(t.head),t.max_lazy_match=Ct[t.level].max_lazy,t.good_match=Ct[t.level].good_length,t.nice_match=Ct[t.level].nice_length,t.max_chain_length=Ct[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=ct-1,t.match_available=0,t.ins_h=0}function _(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=K,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new E.Buf16(2*at),this.dyn_dtree=new E.Buf16(2*(2*nt+1)),this.bl_tree=new E.Buf16(2*(2*ot+1)),o(this.dyn_ltree),o(this.dyn_dtree),o(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new E.Buf16(st+1),this.heap=new E.Buf16(2*it+1),o(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new E.Buf16(2*it+1),o(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function w(t){var e;return t&&t.state?(t.total_in=t.total_out=0,t.data_type=J,e=t.state,e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?ft:mt,t.adler=2===e.wrap?0:1,e.last_flush=I,O._tr_init(e),B):i(t,z)}function S(t){var e=w(t);return e===B&&y(t.state),e}function x(t,e){return t&&t.state?2!==t.state.wrap?z:(t.state.gzhead=e,B):z}function C(t,e,r,n,o,a){if(!t)return z;var s=1;if(e===X&&(e=6),n<0?(s=0,n=-n):n>15&&(s=2,n-=16),o<1||o>Q||r!==K||n<8||n>15||e<0||e>9||a<0||a>V)return i(t,z);8===n&&(n=9);var c=new _;return t.state=c,c.strm=t,c.wrap=s,c.gzhead=null,c.w_bits=n,c.w_size=1<<c.w_bits,c.w_mask=c.w_size-1,c.hash_bits=o+7,c.hash_size=1<<c.hash_bits,c.hash_mask=c.hash_size-1,c.hash_shift=~~((c.hash_bits+ct-1)/ct),c.window=new E.Buf8(2*c.w_size),c.head=new E.Buf16(c.hash_size),c.prev=new E.Buf16(c.w_size),c.lit_bufsize=1<<o+6,c.pending_buf_size=4*c.lit_bufsize,c.pending_buf=new E.Buf8(c.pending_buf_size),c.d_buf=1*c.lit_bufsize,c.l_buf=3*c.lit_bufsize,c.level=e,c.strategy=a,c.method=r,S(t)}function A(t,e){return C(t,e,K,$,tt,Z)}function T(t,e){var r,s,h,u;if(!t||!t.state||e>N||e<0)return t?i(t,z):z;if(s=t.state,!t.output||!t.input&&0!==t.avail_in||s.status===bt&&e!==F)return i(t,0===t.avail_out?q:z);if(s.strm=t,r=s.last_flush,s.last_flush=e,s.status===ft)if(2===s.wrap)t.adler=0,c(s,31),c(s,139),c(s,8),s.gzhead?(c(s,(s.gzhead.text?1:0)+(s.gzhead.hcrc?2:0)+(s.gzhead.extra?4:0)+(s.gzhead.name?8:0)+(s.gzhead.comment?16:0)),c(s,255&s.gzhead.time),c(s,s.gzhead.time>>8&255),c(s,s.gzhead.time>>16&255),c(s,s.gzhead.time>>24&255),c(s,9===s.level?2:s.strategy>=H||s.level<2?4:0),c(s,255&s.gzhead.os),s.gzhead.extra&&s.gzhead.extra.length&&(c(s,255&s.gzhead.extra.length),c(s,s.gzhead.extra.length>>8&255)),s.gzhead.hcrc&&(t.adler=L(t.adler,s.pending_buf,s.pending,0)),s.gzindex=0,s.status=dt):(c(s,0),c(s,0),c(s,0),c(s,0),c(s,0),c(s,9===s.level?2:s.strategy>=H||s.level<2?4:0),c(s,xt),s.status=mt);else{var f=K+(s.w_bits-8<<4)<<8,d=-1;d=s.strategy>=H||s.level<2?0:s.level<6?1:6===s.level?2:3,f|=d<<6,0!==s.strstart&&(f|=ut),f+=31-f%31,s.status=mt,l(s,f),0!==s.strstart&&(l(s,t.adler>>>16),l(s,65535&t.adler)),t.adler=1}if(s.status===dt)if(s.gzhead.extra){for(h=s.pending;s.gzindex<(65535&s.gzhead.extra.length)&&(s.pending!==s.pending_buf_size||(s.gzhead.hcrc&&s.pending>h&&(t.adler=L(t.adler,s.pending_buf,s.pending-h,h)),a(t),h=s.pending,s.pending!==s.pending_buf_size));)c(s,255&s.gzhead.extra[s.gzindex]),s.gzindex++;s.gzhead.hcrc&&s.pending>h&&(t.adler=L(t.adler,s.pending_buf,s.pending-h,h)),s.gzindex===s.gzhead.extra.length&&(s.gzindex=0,s.status=pt)}else s.status=pt;if(s.status===pt)if(s.gzhead.name){h=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>h&&(t.adler=L(t.adler,s.pending_buf,s.pending-h,h)),a(t),h=s.pending,s.pending===s.pending_buf_size)){u=1;break}u=s.gzindex<s.gzhead.name.length?255&s.gzhead.name.charCodeAt(s.gzindex++):0,c(s,u)}while(0!==u);s.gzhead.hcrc&&s.pending>h&&(t.adler=L(t.adler,s.pending_buf,s.pending-h,h)),0===u&&(s.gzindex=0,s.status=gt)}else s.status=gt;if(s.status===gt)if(s.gzhead.comment){h=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>h&&(t.adler=L(t.adler,s.pending_buf,s.pending-h,h)),a(t),h=s.pending,s.pending===s.pending_buf_size)){u=1;break}u=s.gzindex<s.gzhead.comment.length?255&s.gzhead.comment.charCodeAt(s.gzindex++):0,c(s,u)}while(0!==u);s.gzhead.hcrc&&s.pending>h&&(t.adler=L(t.adler,s.pending_buf,s.pending-h,h)),0===u&&(s.status=vt)}else s.status=vt;if(s.status===vt&&(s.gzhead.hcrc?(s.pending+2>s.pending_buf_size&&a(t),s.pending+2<=s.pending_buf_size&&(c(s,255&t.adler),c(s,t.adler>>8&255),t.adler=0,s.status=mt)):s.status=mt),0!==s.pending){if(a(t),0===t.avail_out)return s.last_flush=-1,B}else if(0===t.avail_in&&n(e)<=n(r)&&e!==F)return i(t,q);if(s.status===bt&&0!==t.avail_in)return i(t,q);if(0!==t.avail_in||0!==s.lookahead||e!==I&&s.status!==bt){var p=s.strategy===H?m(s,e):s.strategy===Y?v(s,e):Ct[s.level].func(s,e);if(p!==wt&&p!==St||(s.status=bt),p===yt||p===wt)return 0===t.avail_out&&(s.last_flush=-1),B;if(p===_t&&(e===j?O._tr_align(s):e!==N&&(O._tr_stored_block(s,0,0,!1),e===M&&(o(s.head),0===s.lookahead&&(s.strstart=0,s.block_start=0,s.insert=0))),a(t),0===t.avail_out))return s.last_flush=-1,B}return e!==F?B:s.wrap<=0?U:(2===s.wrap?(c(s,255&t.adler),c(s,t.adler>>8&255),c(s,t.adler>>16&255),c(s,t.adler>>24&255),c(s,255&t.total_in),c(s,t.total_in>>8&255),c(s,t.total_in>>16&255),c(s,t.total_in>>24&255)):(l(s,t.adler>>>16),l(s,65535&t.adler)),a(t),s.wrap>0&&(s.wrap=-s.wrap),0!==s.pending?B:U)}function k(t){var e;return t&&t.state?(e=t.state.status)!==ft&&e!==dt&&e!==pt&&e!==gt&&e!==vt&&e!==mt&&e!==bt?i(t,z):(t.state=null,e===mt?i(t,W):B):z}function P(t,e){var r=e.length,i,n,a,s,c,l,h,u;if(!t||!t.state)return z;if(i=t.state,2===(s=i.wrap)||1===s&&i.status!==ft||i.lookahead)return z;for(1===s&&(t.adler=R(t.adler,e,r,0)),i.wrap=0,r>=i.w_size&&(0===s&&(o(i.head),i.strstart=0,i.block_start=0,i.insert=0),u=new E.Buf8(i.w_size),E.arraySet(u,e,r-i.w_size,i.w_size,0),e=u,r=i.w_size),c=t.avail_in,l=t.next_in,h=t.input,t.avail_in=r,t.next_in=0,t.input=e,f(i);i.lookahead>=ct;){n=i.strstart,a=i.lookahead-(ct-1);do{i.ins_h=(i.ins_h<<i.hash_shift^i.window[n+ct-1])&i.hash_mask,i.prev[n&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=n,n++}while(--a);i.strstart=n,i.lookahead=ct-1,f(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=ct-1,i.match_available=0,t.next_in=l,t.input=h,t.avail_in=c,i.wrap=s,B}var E=r(8),O=r(53),R=r(22),L=r(23),D=r(21),I=0,j=1,M=3,F=4,N=5,B=0,U=1,z=-2,W=-3,q=-5,X=-1,G=1,H=2,Y=3,V=4,Z=0,J=2,K=8,Q=9,$=15,tt=8,et=29,rt=256,it=286,nt=30,ot=19,at=2*it+1,st=15,ct=3,lt=258,ht=lt+ct+1,ut=32,ft=42,dt=69,pt=73,gt=91,vt=103,mt=113,bt=666,yt=1,_t=2,wt=3,St=4,xt=3,Ct;Ct=[new b(0,0,0,0,d),new b(4,4,8,4,p),new b(4,5,16,8,p),new b(4,6,32,32,p),new b(4,4,16,16,g),new b(8,16,32,32,g),new b(8,16,128,128,g),new b(8,32,128,256,g),new b(32,128,258,1024,g),new b(32,258,258,4096,g)],e.deflateInit=A,e.deflateInit2=C,e.deflateReset=S,e.deflateResetKeep=w,e.deflateSetHeader=x,e.deflate=T,e.deflateEnd=k,e.deflateSetDictionary=P,e.deflateInfo="pako deflate (from Nodeca project)"},function(t,e,r){"use strict";function i(t){for(var e=t.length;--e>=0;)t[e]=0}function n(t,e,r,i,n){this.static_tree=t,this.extra_bits=e,this.extra_base=r,this.elems=i,this.max_length=n,this.has_stree=t&&t.length}function o(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}function a(t){return t<256?ct[t]:ct[256+(t>>>7)]}function s(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255}function c(t,e,r){t.bi_valid>Z-r?(t.bi_buf|=e<<t.bi_valid&65535,s(t,t.bi_buf),t.bi_buf=e>>Z-t.bi_valid,t.bi_valid+=r-Z):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=r)}function l(t,e,r){c(t,r[2*e],r[2*e+1])}function h(t,e){var r=0;do{r|=1&t,t>>>=1,r<<=1}while(--e>0);return r>>>1}function u(t){16===t.bi_valid?(s(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)}function f(t,e){var r=e.dyn_tree,i=e.max_code,n=e.stat_desc.static_tree,o=e.stat_desc.has_stree,a=e.stat_desc.extra_bits,s=e.stat_desc.extra_base,c=e.stat_desc.max_length,l,h,u,f,d,p,g=0;for(f=0;f<=V;f++)t.bl_count[f]=0;for(r[2*t.heap[t.heap_max]+1]=0,l=t.heap_max+1;l<Y;l++)h=t.heap[l],f=r[2*r[2*h+1]+1]+1,f>c&&(f=c,g++),r[2*h+1]=f,h>i||(t.bl_count[f]++,d=0,h>=s&&(d=a[h-s]),p=r[2*h],t.opt_len+=p*(f+d),o&&(t.static_len+=p*(n[2*h+1]+d)));if(0!==g){do{for(f=c-1;0===t.bl_count[f];)f--;t.bl_count[f]--,t.bl_count[f+1]+=2,t.bl_count[c]--,g-=2}while(g>0);for(f=c;0!==f;f--)for(h=t.bl_count[f];0!==h;)(u=t.heap[--l])>i||(r[2*u+1]!==f&&(t.opt_len+=(f-r[2*u+1])*r[2*u],r[2*u+1]=f),h--)}}function d(t,e,r){var i=new Array(V+1),n=0,o,a;for(o=1;o<=V;o++)i[o]=n=n+r[o-1]<<1;for(a=0;a<=e;a++){var s=t[2*a+1];0!==s&&(t[2*a]=h(i[s]++,s))}}function p(){var t,e,r,i,o,a=new Array(V+1);for(r=0,i=0;i<W-1;i++)for(ht[i]=r,t=0;t<1<<et[i];t++)lt[r++]=i;for(lt[r-1]=i,o=0,i=0;i<16;i++)for(ut[i]=o,t=0;t<1<<rt[i];t++)ct[o++]=i;for(o>>=7;i<G;i++)for(ut[i]=o<<7,t=0;t<1<<rt[i]-7;t++)ct[256+o++]=i;for(e=0;e<=V;e++)a[e]=0;for(t=0;t<=143;)at[2*t+1]=8,t++,a[8]++;for(;t<=255;)at[2*t+1]=9,t++,a[9]++;for(;t<=279;)at[2*t+1]=7,t++,a[7]++;for(;t<=287;)at[2*t+1]=8,t++,a[8]++;for(d(at,X+1,a),t=0;t<G;t++)st[2*t+1]=5,st[2*t]=h(t,5);ft=new n(at,et,q+1,X,V),dt=new n(st,rt,0,G,V),pt=new n(new Array(0),it,0,H,J)}function g(t){var e;for(e=0;e<X;e++)t.dyn_ltree[2*e]=0;for(e=0;e<G;e++)t.dyn_dtree[2*e]=0;for(e=0;e<H;e++)t.bl_tree[2*e]=0;t.dyn_ltree[2*K]=1,t.opt_len=t.static_len=0,t.last_lit=t.matches=0}function v(t){t.bi_valid>8?s(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0}function m(t,e,r,i){v(t),i&&(s(t,r),s(t,~r)),L.arraySet(t.pending_buf,t.window,e,r,t.pending),t.pending+=r}function b(t,e,r,i){var n=2*e,o=2*r;return t[n]<t[o]||t[n]===t[o]&&i[e]<=i[r]}function y(t,e,r){for(var i=t.heap[r],n=r<<1;n<=t.heap_len&&(n<t.heap_len&&b(e,t.heap[n+1],t.heap[n],t.depth)&&n++,!b(e,i,t.heap[n],t.depth));)t.heap[r]=t.heap[n],r=n,n<<=1;t.heap[r]=i}function _(t,e,r){var i,n,o=0,s,h;if(0!==t.last_lit)do{i=t.pending_buf[t.d_buf+2*o]<<8|t.pending_buf[t.d_buf+2*o+1],n=t.pending_buf[t.l_buf+o],o++,0===i?l(t,n,e):(s=lt[n],l(t,s+q+1,e),h=et[s],0!==h&&(n-=ht[s],c(t,n,h)),i--,s=a(i),l(t,s,r),0!==(h=rt[s])&&(i-=ut[s],c(t,i,h)))}while(o<t.last_lit);l(t,K,e)}function w(t,e){var r=e.dyn_tree,i=e.stat_desc.static_tree,n=e.stat_desc.has_stree,o=e.stat_desc.elems,a,s,c=-1,l;for(t.heap_len=0,t.heap_max=Y,a=0;a<o;a++)0!==r[2*a]?(t.heap[++t.heap_len]=c=a,t.depth[a]=0):r[2*a+1]=0;for(;t.heap_len<2;)l=t.heap[++t.heap_len]=c<2?++c:0,r[2*l]=1,t.depth[l]=0,t.opt_len--,n&&(t.static_len-=i[2*l+1]);for(e.max_code=c,a=t.heap_len>>1;a>=1;a--)y(t,r,a);l=o;do{a=t.heap[1],t.heap[1]=t.heap[t.heap_len--],y(t,r,1),s=t.heap[1],t.heap[--t.heap_max]=a,t.heap[--t.heap_max]=s,r[2*l]=r[2*a]+r[2*s],t.depth[l]=(t.depth[a]>=t.depth[s]?t.depth[a]:t.depth[s])+1,r[2*a+1]=r[2*s+1]=l,t.heap[1]=l++,y(t,r,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],f(t,e),d(r,c,t.bl_count)}function S(t,e,r){var i,n=-1,o,a=e[1],s=0,c=7,l=4;for(0===a&&(c=138,l=3),e[2*(r+1)+1]=65535,i=0;i<=r;i++)o=a,a=e[2*(i+1)+1],++s<c&&o===a||(s<l?t.bl_tree[2*o]+=s:0!==o?(o!==n&&t.bl_tree[2*o]++,t.bl_tree[2*Q]++):s<=10?t.bl_tree[2*$]++:t.bl_tree[2*tt]++,s=0,n=o,0===a?(c=138,l=3):o===a?(c=6,l=3):(c=7,l=4))}function x(t,e,r){var i,n=-1,o,a=e[1],s=0,h=7,u=4;for(0===a&&(h=138,u=3),i=0;i<=r;i++)if(o=a,a=e[2*(i+1)+1],!(++s<h&&o===a)){if(s<u)do{l(t,o,t.bl_tree)}while(0!=--s);else 0!==o?(o!==n&&(l(t,o,t.bl_tree),s--),l(t,Q,t.bl_tree),c(t,s-3,2)):s<=10?(l(t,$,t.bl_tree),c(t,s-3,3)):(l(t,tt,t.bl_tree),c(t,s-11,7));s=0,n=o,0===a?(h=138,u=3):o===a?(h=6,u=3):(h=7,u=4)}}function C(t){var e;for(S(t,t.dyn_ltree,t.l_desc.max_code),S(t,t.dyn_dtree,t.d_desc.max_code),w(t,t.bl_desc),e=H-1;e>=3&&0===t.bl_tree[2*nt[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e}function A(t,e,r,i){var n;for(c(t,e-257,5),c(t,r-1,5),c(t,i-4,4),n=0;n<i;n++)c(t,t.bl_tree[2*nt[n]+1],3);x(t,t.dyn_ltree,e-1),x(t,t.dyn_dtree,r-1)}function T(t){var e=4093624447,r;for(r=0;r<=31;r++,e>>>=1)if(1&e&&0!==t.dyn_ltree[2*r])return I;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return j;for(r=32;r<q;r++)if(0!==t.dyn_ltree[2*r])return j;return I}function k(t){gt||(p(),gt=!0),t.l_desc=new o(t.dyn_ltree,ft),t.d_desc=new o(t.dyn_dtree,dt),t.bl_desc=new o(t.bl_tree,pt),t.bi_buf=0,t.bi_valid=0,g(t)}function P(t,e,r,i){c(t,(F<<1)+(i?1:0),3),m(t,e,r,!0)}function E(t){c(t,N<<1,3),l(t,K,at),u(t)}function O(t,e,r,i){var n,o,a=0;t.level>0?(t.strm.data_type===M&&(t.strm.data_type=T(t)),w(t,t.l_desc),w(t,t.d_desc),a=C(t),n=t.opt_len+3+7>>>3,(o=t.static_len+3+7>>>3)<=n&&(n=o)):n=o=r+5,r+4<=n&&-1!==e?P(t,e,r,i):t.strategy===D||o===n?(c(t,(N<<1)+(i?1:0),3),_(t,at,st)):(c(t,(B<<1)+(i?1:0),3),A(t,t.l_desc.max_code+1,t.d_desc.max_code+1,a+1),_(t,t.dyn_ltree,t.dyn_dtree)),g(t),i&&v(t)}function R(t,e,r){return t.pending_buf[t.d_buf+2*t.last_lit]=e>>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&r,t.last_lit++,0===e?t.dyn_ltree[2*r]++:(t.matches++,e--,t.dyn_ltree[2*(lt[r]+q+1)]++,t.dyn_dtree[2*a(e)]++),t.last_lit===t.lit_bufsize-1}var L=r(8),D=4,I=0,j=1,M=2,F=0,N=1,B=2,U=3,z=258,W=29,q=256,X=q+1+W,G=30,H=19,Y=2*X+1,V=15,Z=16,J=7,K=256,Q=16,$=17,tt=18,et=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],rt=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],it=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],nt=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],ot=512,at=new Array(2*(X+2));i(at);var st=new Array(2*G);i(st);var ct=new Array(512);i(ct);var lt=new Array(256);i(lt);var ht=new Array(W);i(ht);var ut=new Array(G);i(ut);var ft,dt,pt,gt=!1;e._tr_init=k,e._tr_stored_block=P,e._tr_flush_block=O,e._tr_tally=R,e._tr_align=E},function(t,e,r){"use strict";function i(t){return(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24)}function n(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new v.Buf16(320),this.work=new v.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function o(t){var e;return t&&t.state?(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=j,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new v.Buf32(dt),e.distcode=e.distdyn=new v.Buf32(pt),e.sane=1,e.back=-1,k):O}function a(t){var e;return t&&t.state?(e=t.state,e.wsize=0,e.whave=0,e.wnext=0,o(t)):O}function s(t,e){var r,i;return t&&t.state?(i=t.state,e<0?(r=0,e=-e):(r=1+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?O:(null!==i.window&&i.wbits!==e&&(i.window=null),i.wrap=r,i.wbits=e,a(t))):O}function c(t,e){var r,i;return t?(i=new n,t.state=i,i.window=null,r=s(t,e),r!==k&&(t.state=null),r):O}function l(t){return c(t,vt)}function h(t){if(mt){var e;for(bt=new v.Buf32(512),yt=new v.Buf32(32),e=0;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(_(S,t.lens,0,288,bt,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;_(x,t.lens,0,32,yt,0,t.work,{bits:5}),mt=!1}t.lencode=bt,t.lenbits=9,t.distcode=yt,t.distbits=5}function u(t,e,r,i){var n,o=t.state;return null===o.window&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new v.Buf8(o.wsize)),i>=o.wsize?(v.arraySet(o.window,e,r-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(n=o.wsize-o.wnext,n>i&&(n=i),v.arraySet(o.window,e,r-i,n,o.wnext),i-=n,i?(v.arraySet(o.window,e,r-i,i,0),o.wnext=i,o.whave=o.wsize):(o.wnext+=n,o.wnext===o.wsize&&(o.wnext=0),o.whave<o.wsize&&(o.whave+=n))),0}function f(t,e){var r,n,o,a,s,c,l,f,d,p,g,dt,pt,gt,vt=0,mt,bt,yt,_t,wt,St,xt,Ct,At=new v.Buf8(4),Tt,kt,Pt=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!t||!t.state||!t.output||!t.input&&0!==t.avail_in)return O;r=t.state,r.mode===H&&(r.mode=Y),s=t.next_out,o=t.output,l=t.avail_out,a=t.next_in,n=t.input,c=t.avail_in,f=r.hold,d=r.bits,p=c,g=l,Ct=k;t:for(;;)switch(r.mode){case j:if(0===r.wrap){r.mode=Y;break}for(;d<16;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(2&r.wrap&&35615===f){r.check=0,At[0]=255&f,At[1]=f>>>8&255,r.check=b(r.check,At,2,0),f=0,d=0,r.mode=M;break}if(r.flags=0,r.head&&(r.head.done=!1),!(1&r.wrap)||(((255&f)<<8)+(f>>8))%31){t.msg="incorrect header check",r.mode=ht;break}if((15&f)!==I){t.msg="unknown compression method",r.mode=ht;break}if(f>>>=4,d-=4,xt=8+(15&f),0===r.wbits)r.wbits=xt;else if(xt>r.wbits){t.msg="invalid window size",r.mode=ht;break}r.dmax=1<<xt,t.adler=r.check=1,r.mode=512&f?X:H,f=0,d=0;break;case M:for(;d<16;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(r.flags=f,(255&r.flags)!==I){t.msg="unknown compression method",r.mode=ht;break}if(57344&r.flags){t.msg="unknown header flags set",r.mode=ht;break}r.head&&(r.head.text=f>>8&1),512&r.flags&&(At[0]=255&f,At[1]=f>>>8&255,r.check=b(r.check,At,2,0)),f=0,d=0,r.mode=F;case F:for(;d<32;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}r.head&&(r.head.time=f),512&r.flags&&(At[0]=255&f,At[1]=f>>>8&255,At[2]=f>>>16&255,At[3]=f>>>24&255,r.check=b(r.check,At,4,0)),f=0,d=0,r.mode=N;case N:for(;d<16;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}r.head&&(r.head.xflags=255&f,r.head.os=f>>8),512&r.flags&&(At[0]=255&f,At[1]=f>>>8&255,r.check=b(r.check,At,2,0)),f=0,d=0,r.mode=B;case B:if(1024&r.flags){for(;d<16;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}r.length=f,r.head&&(r.head.extra_len=f),512&r.flags&&(At[0]=255&f,At[1]=f>>>8&255,r.check=b(r.check,At,2,0)),f=0,d=0}else r.head&&(r.head.extra=null);r.mode=U;case U:if(1024&r.flags&&(dt=r.length,dt>c&&(dt=c),dt&&(r.head&&(xt=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),v.arraySet(r.head.extra,n,a,dt,xt)),512&r.flags&&(r.check=b(r.check,n,dt,a)),c-=dt,a+=dt,r.length-=dt),r.length))break t;r.length=0,r.mode=z;case z:if(2048&r.flags){if(0===c)break t;dt=0;do{xt=n[a+dt++],r.head&&xt&&r.length<65536&&(r.head.name+=String.fromCharCode(xt))}while(xt&&dt<c);if(512&r.flags&&(r.check=b(r.check,n,dt,a)),c-=dt,a+=dt,xt)break t}else r.head&&(r.head.name=null);r.length=0,r.mode=W;case W:if(4096&r.flags){if(0===c)break t;dt=0;do{xt=n[a+dt++],r.head&&xt&&r.length<65536&&(r.head.comment+=String.fromCharCode(xt))}while(xt&&dt<c);if(512&r.flags&&(r.check=b(r.check,n,dt,a)),c-=dt,a+=dt,xt)break t}else r.head&&(r.head.comment=null);r.mode=q;case q:if(512&r.flags){for(;d<16;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(f!==(65535&r.check)){t.msg="header crc mismatch",r.mode=ht;break}f=0,d=0}r.head&&(r.head.hcrc=r.flags>>9&1,r.head.done=!0),t.adler=r.check=0,r.mode=H;break;case X:for(;d<32;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}t.adler=r.check=i(f),f=0,d=0,r.mode=G;case G:if(0===r.havedict)return t.next_out=s,t.avail_out=l,t.next_in=a,t.avail_in=c,r.hold=f,r.bits=d,E;t.adler=r.check=1,r.mode=H;case H:if(e===A||e===T)break t;case Y:if(r.last){f>>>=7&d,d-=7&d,r.mode=st;break}for(;d<3;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}switch(r.last=1&f,f>>>=1,d-=1,3&f){case 0:r.mode=V;break;case 1:if(h(r),r.mode=tt,e===T){f>>>=2,d-=2;break t}break;case 2:r.mode=K;break;case 3:t.msg="invalid block type",r.mode=ht}f>>>=2,d-=2;break;case V:for(f>>>=7&d,d-=7&d;d<32;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if((65535&f)!=(f>>>16^65535)){t.msg="invalid stored block lengths",r.mode=ht;break}if(r.length=65535&f,f=0,d=0,r.mode=Z,e===T)break t;case Z:r.mode=J;case J:if(dt=r.length){if(dt>c&&(dt=c),dt>l&&(dt=l),0===dt)break t;v.arraySet(o,n,a,dt,s),c-=dt,a+=dt,l-=dt,s+=dt,r.length-=dt;break}r.mode=H;break;case K:for(;d<14;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(r.nlen=257+(31&f),f>>>=5,d-=5,r.ndist=1+(31&f),f>>>=5,d-=5,r.ncode=4+(15&f),f>>>=4,d-=4,r.nlen>286||r.ndist>30){t.msg="too many length or distance symbols",r.mode=ht;break}r.have=0,r.mode=Q;case Q:for(;r.have<r.ncode;){for(;d<3;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}r.lens[Pt[r.have++]]=7&f,f>>>=3,d-=3}for(;r.have<19;)r.lens[Pt[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,Tt={bits:r.lenbits},Ct=_(w,r.lens,0,19,r.lencode,0,r.work,Tt),r.lenbits=Tt.bits,Ct){t.msg="invalid code lengths set",r.mode=ht;break}r.have=0,r.mode=$;case $:for(;r.have<r.nlen+r.ndist;){for(;vt=r.lencode[f&(1<<r.lenbits)-1],mt=vt>>>24,bt=vt>>>16&255,yt=65535&vt,!(mt<=d);){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(yt<16)f>>>=mt,d-=mt,r.lens[r.have++]=yt;else{if(16===yt){for(kt=mt+2;d<kt;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(f>>>=mt,d-=mt,0===r.have){t.msg="invalid bit length repeat",r.mode=ht;break}xt=r.lens[r.have-1],dt=3+(3&f),f>>>=2,d-=2}else if(17===yt){for(kt=mt+3;d<kt;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}f>>>=mt,d-=mt,xt=0,dt=3+(7&f),f>>>=3,d-=3}else{for(kt=mt+7;d<kt;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}f>>>=mt,d-=mt,xt=0,dt=11+(127&f),f>>>=7,d-=7}if(r.have+dt>r.nlen+r.ndist){t.msg="invalid bit length repeat",r.mode=ht;break}for(;dt--;)r.lens[r.have++]=xt}}if(r.mode===ht)break;if(0===r.lens[256]){t.msg="invalid code -- missing end-of-block",r.mode=ht;break}if(r.lenbits=9,Tt={bits:r.lenbits},Ct=_(S,r.lens,0,r.nlen,r.lencode,0,r.work,Tt),r.lenbits=Tt.bits,Ct){t.msg="invalid literal/lengths set",r.mode=ht;break}if(r.distbits=6,r.distcode=r.distdyn,Tt={bits:r.distbits},Ct=_(x,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,Tt),r.distbits=Tt.bits,Ct){t.msg="invalid distances set",r.mode=ht;break}if(r.mode=tt,e===T)break t;case tt:r.mode=et;case et:if(c>=6&&l>=258){t.next_out=s,t.avail_out=l,t.next_in=a,t.avail_in=c,r.hold=f,r.bits=d,y(t,g),s=t.next_out,o=t.output,l=t.avail_out,a=t.next_in,n=t.input,c=t.avail_in,f=r.hold,d=r.bits,r.mode===H&&(r.back=-1);break}for(r.back=0;vt=r.lencode[f&(1<<r.lenbits)-1],mt=vt>>>24,bt=vt>>>16&255,yt=65535&vt,!(mt<=d);){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(bt&&0==(240&bt)){for(_t=mt,wt=bt,St=yt;vt=r.lencode[St+((f&(1<<_t+wt)-1)>>_t)],mt=vt>>>24,bt=vt>>>16&255,yt=65535&vt,!(_t+mt<=d);){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}f>>>=_t,d-=_t,r.back+=_t}if(f>>>=mt,d-=mt,r.back+=mt,r.length=yt,0===bt){r.mode=at;break}if(32&bt){r.back=-1,r.mode=H;break}if(64&bt){t.msg="invalid literal/length code",r.mode=ht;break}r.extra=15&bt,r.mode=rt;case rt:if(r.extra){for(kt=r.extra;d<kt;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}r.length+=f&(1<<r.extra)-1,f>>>=r.extra,d-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=it;case it:for(;vt=r.distcode[f&(1<<r.distbits)-1],mt=vt>>>24,bt=vt>>>16&255,yt=65535&vt,!(mt<=d);){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(0==(240&bt)){for(_t=mt,wt=bt,St=yt;vt=r.distcode[St+((f&(1<<_t+wt)-1)>>_t)],mt=vt>>>24,bt=vt>>>16&255,yt=65535&vt,!(_t+mt<=d);){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}f>>>=_t,d-=_t,r.back+=_t}if(f>>>=mt,d-=mt,r.back+=mt,64&bt){t.msg="invalid distance code",r.mode=ht;break}r.offset=yt,r.extra=15&bt,r.mode=nt;case nt:if(r.extra){for(kt=r.extra;d<kt;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}r.offset+=f&(1<<r.extra)-1,f>>>=r.extra,d-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){t.msg="invalid distance too far back",r.mode=ht;break}r.mode=ot;case ot:if(0===l)break t;if(dt=g-l,r.offset>dt){if((dt=r.offset-dt)>r.whave&&r.sane){t.msg="invalid distance too far back",r.mode=ht;break}dt>r.wnext?(dt-=r.wnext,pt=r.wsize-dt):pt=r.wnext-dt,dt>r.length&&(dt=r.length),gt=r.window}else gt=o,pt=s-r.offset,dt=r.length;dt>l&&(dt=l),l-=dt,r.length-=dt;do{o[s++]=gt[pt++]}while(--dt);0===r.length&&(r.mode=et);break;case at:if(0===l)break t;o[s++]=r.length,l--,r.mode=et;break;case st:if(r.wrap){for(;d<32;){if(0===c)break t;c--,f|=n[a++]<<d,d+=8}if(g-=l,t.total_out+=g,r.total+=g,g&&(t.adler=r.check=r.flags?b(r.check,o,g,s-g):m(r.check,o,g,s-g)),g=l,(r.flags?f:i(f))!==r.check){t.msg="incorrect data check",r.mode=ht;break}f=0,d=0}r.mode=ct;case ct:if(r.wrap&&r.flags){for(;d<32;){if(0===c)break t;c--,f+=n[a++]<<d,d+=8}if(f!==(4294967295&r.total)){t.msg="incorrect length check",r.mode=ht;break}f=0,d=0}r.mode=lt;case lt:Ct=P;break t;case ht:Ct=R;break t;case ut:return L;case ft:default:return O}return t.next_out=s,t.avail_out=l,t.next_in=a,t.avail_in=c,r.hold=f,r.bits=d,(r.wsize||g!==t.avail_out&&r.mode<ht&&(r.mode<st||e!==C))&&u(t,t.output,t.next_out,g-t.avail_out)?(r.mode=ut,L):(p-=t.avail_in,g-=t.avail_out,t.total_in+=p,t.total_out+=g,r.total+=g,r.wrap&&g&&(t.adler=r.check=r.flags?b(r.check,o,g,t.next_out-g):m(r.check,o,g,t.next_out-g)),t.data_type=r.bits+(r.last?64:0)+(r.mode===H?128:0)+(r.mode===tt||r.mode===Z?256:0),(0===p&&0===g||e===C)&&Ct===k&&(Ct=D),Ct)}function d(t){if(!t||!t.state)return O;var e=t.state;return e.window&&(e.window=null),t.state=null,k}function p(t,e){var r;return t&&t.state?(r=t.state,0==(2&r.wrap)?O:(r.head=e,e.done=!1,k)):O}function g(t,e){var r=e.length,i,n,o;return t&&t.state?(i=t.state,0!==i.wrap&&i.mode!==G?O:i.mode===G&&(n=1,(n=m(n,e,r,0))!==i.check)?R:(o=u(t,e,r,r))?(i.mode=ut,L):(i.havedict=1,k)):O}var v=r(8),m=r(22),b=r(23),y=r(55),_=r(56),w=0,S=1,x=2,C=4,A=5,T=6,k=0,P=1,E=2,O=-2,R=-3,L=-4,D=-5,I=8,j=1,M=2,F=3,N=4,B=5,U=6,z=7,W=8,q=9,X=10,G=11,H=12,Y=13,V=14,Z=15,J=16,K=17,Q=18,$=19,tt=20,et=21,rt=22,it=23,nt=24,ot=25,at=26,st=27,ct=28,lt=29,ht=30,ut=31,ft=32,dt=852,pt=592,gt=15,vt=15,mt=!0,bt,yt;e.inflateReset=a,e.inflateReset2=s,e.inflateResetKeep=o,e.inflateInit=l,e.inflateInit2=c,e.inflate=f,e.inflateEnd=d,e.inflateGetHeader=p,e.inflateSetDictionary=g,e.inflateInfo="pako inflate (from Nodeca project)"},function(t,e,r){"use strict";var i=30,n=12;t.exports=function t(e,r){var i,n,o,a,s,c,l,h,u,f,d,p,g,v,m,b,y,_,w,S,x,C,A,T,k;i=e.state,n=e.next_in,T=e.input,o=n+(e.avail_in-5),a=e.next_out,k=e.output,s=a-(r-e.avail_out),c=a+(e.avail_out-257),l=i.dmax,h=i.wsize,u=i.whave,f=i.wnext,d=i.window,p=i.hold,g=i.bits,v=i.lencode,m=i.distcode,b=(1<<i.lenbits)-1,y=(1<<i.distbits)-1;t:do{g<15&&(p+=T[n++]<<g,g+=8,p+=T[n++]<<g,g+=8),_=v[p&b];e:for(;;){if(w=_>>>24,p>>>=w,g-=w,0===(w=_>>>16&255))k[a++]=65535&_;else{if(!(16&w)){if(0==(64&w)){_=v[(65535&_)+(p&(1<<w)-1)];continue e}if(32&w){i.mode=12;break t}e.msg="invalid literal/length code",i.mode=30;break t}S=65535&_,w&=15,w&&(g<w&&(p+=T[n++]<<g,g+=8),S+=p&(1<<w)-1,p>>>=w,g-=w),g<15&&(p+=T[n++]<<g,g+=8,p+=T[n++]<<g,g+=8),_=m[p&y];r:for(;;){if(w=_>>>24,p>>>=w,g-=w,!(16&(w=_>>>16&255))){if(0==(64&w)){_=m[(65535&_)+(p&(1<<w)-1)];continue r}e.msg="invalid distance code",i.mode=30;break t}if(x=65535&_,w&=15,g<w&&(p+=T[n++]<<g,(g+=8)<w&&(p+=T[n++]<<g,g+=8)),(x+=p&(1<<w)-1)>l){e.msg="invalid distance too far back",i.mode=30;break t}if(p>>>=w,g-=w,w=a-s,x>w){if((w=x-w)>u&&i.sane){e.msg="invalid distance too far back",i.mode=30;break t}if(C=0,A=d,0===f){if(C+=h-w,w<S){S-=w;do{k[a++]=d[C++]}while(--w);C=a-x,A=k}}else if(f<w){if(C+=h+f-w,(w-=f)<S){S-=w;do{k[a++]=d[C++]}while(--w);if(C=0,f<S){w=f,S-=w;do{k[a++]=d[C++]}while(--w);C=a-x,A=k}}}else if(C+=f-w,w<S){S-=w;do{k[a++]=d[C++]}while(--w);C=a-x,A=k}for(;S>2;)k[a++]=A[C++],k[a++]=A[C++],k[a++]=A[C++],S-=3;S&&(k[a++]=A[C++],S>1&&(k[a++]=A[C++]))}else{C=a-x;do{k[a++]=k[C++],k[a++]=k[C++],k[a++]=k[C++],S-=3}while(S>2);S&&(k[a++]=k[C++],S>1&&(k[a++]=k[C++]))}break}}break}}while(n<o&&a<c);S=g>>3,n-=S,g-=S<<3,p&=(1<<g)-1,e.next_in=n,e.next_out=a,e.avail_in=n<o?o-n+5:5-(n-o),e.avail_out=a<c?c-a+257:257-(a-c),i.hold=p,i.bits=g}},function(t,e,r){"use strict";var i=r(8),n=15,o=852,a=592,s=0,c=1,l=2,h=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],u=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],f=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],d=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function t(e,r,n,o,a,s,c,l){var p=l.bits,g=0,v=0,m=0,b=0,y=0,_=0,w=0,S=0,x=0,C=0,A,T,k,P,E,O=null,R=0,L,D=new i.Buf16(16),I=new i.Buf16(16),j=null,M=0,F,N,B;for(g=0;g<=15;g++)D[g]=0;for(v=0;v<o;v++)D[r[n+v]]++;for(y=p,b=15;b>=1&&0===D[b];b--);if(y>b&&(y=b),0===b)return a[s++]=20971520,a[s++]=20971520,l.bits=1,0;for(m=1;m<b&&0===D[m];m++);for(y<m&&(y=m),S=1,g=1;g<=15;g++)if(S<<=1,(S-=D[g])<0)return-1;if(S>0&&(0===e||1!==b))return-1;for(I[1]=0,g=1;g<15;g++)I[g+1]=I[g]+D[g];for(v=0;v<o;v++)0!==r[n+v]&&(c[I[r[n+v]]++]=v);if(0===e?(O=j=c,L=19):1===e?(O=h,R-=257,j=u,M-=257,L=256):(O=f,j=d,L=-1),C=0,v=0,g=m,E=s,_=y,w=0,k=-1,x=1<<y,P=x-1,1===e&&x>852||2===e&&x>592)return 1;for(var U=0;;){U++,F=g-w,c[v]<L?(N=0,B=c[v]):c[v]>L?(N=j[M+c[v]],B=O[R+c[v]]):(N=96,B=0),A=1<<g-w,T=1<<_,m=T;do{T-=A,a[E+(C>>w)+T]=F<<24|N<<16|B|0}while(0!==T);for(A=1<<g-1;C&A;)A>>=1;if(0!==A?(C&=A-1,C+=A):C=0,v++,0==--D[g]){if(g===b)break;g=r[n+c[v]]}if(g>y&&(C&P)!==k){for(0===w&&(w=y),E+=m,_=g-w,S=1<<_;_+w<b&&!((S-=D[_+w])<=0);)_++,S<<=1;if(x+=1<<_,1===e&&x>852||2===e&&x>592)return 1;k=C&P,a[k]=y<<24|_<<16|E-s|0}}return 0!==C&&(a[E+C]=g-w<<24|64<<16|0),l.bits=y,0}},function(t,e,r){"use strict";t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},function(t,e){t.exports=function t(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},function(t,e){"function"==typeof Object.create?t.exports=function t(e,r){e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function t(e,r){e.super_=r;var i=function(){};i.prototype=r.prototype,e.prototype=new i,e.prototype.constructor=e}},function(t,e,r){"use strict";(function(e){/*! <ide> * The buffer module from node.js, for the browser. <ide> * <ide> * @author Feross Aboukhadijeh <[email protected]> <http://feross.org>
Java
apache-2.0
f30733667087ba25baf00d80b39a851c7d540cff
0
wbowling/elasticsearch,Ansh90/elasticsearch,mgalushka/elasticsearch,ThalaivaStars/OrgRepo1,gingerwizard/elasticsearch,nrkkalyan/elasticsearch,ImpressTV/elasticsearch,alexkuk/elasticsearch,Kakakakakku/elasticsearch,andrejserafim/elasticsearch,javachengwc/elasticsearch,kevinkluge/elasticsearch,hirdesh2008/elasticsearch,slavau/elasticsearch,abibell/elasticsearch,ESamir/elasticsearch,rlugojr/elasticsearch,beiske/elasticsearch,feiqitian/elasticsearch,iantruslove/elasticsearch,18098924759/elasticsearch,shreejay/elasticsearch,YosuaMichael/elasticsearch,pozhidaevak/elasticsearch,JackyMai/elasticsearch,himanshuag/elasticsearch,StefanGor/elasticsearch,kaneshin/elasticsearch,rajanm/elasticsearch,ivansun1010/elasticsearch,kcompher/elasticsearch,weipinghe/elasticsearch,MichaelLiZhou/elasticsearch,kevinkluge/elasticsearch,sneivandt/elasticsearch,obourgain/elasticsearch,petmit/elasticsearch,PhaedrusTheGreek/elasticsearch,truemped/elasticsearch,vvcephei/elasticsearch,Siddartha07/elasticsearch,wangtuo/elasticsearch,nazarewk/elasticsearch,jaynblue/elasticsearch,queirozfcom/elasticsearch,IanvsPoplicola/elasticsearch,hydro2k/elasticsearch,elasticdog/elasticsearch,aparo/elasticsearch,easonC/elasticsearch,javachengwc/elasticsearch,MetSystem/elasticsearch,hafkensite/elasticsearch,huanzhong/elasticsearch,wittyameta/elasticsearch,xuzha/elasticsearch,jpountz/elasticsearch,likaiwalkman/elasticsearch,rento19962/elasticsearch,lchennup/elasticsearch,kunallimaye/elasticsearch,sposam/elasticsearch,nrkkalyan/elasticsearch,fekaputra/elasticsearch,khiraiwa/elasticsearch,ajhalani/elasticsearch,brandonkearby/elasticsearch,tkssharma/elasticsearch,szroland/elasticsearch,naveenhooda2000/elasticsearch,episerver/elasticsearch,pritishppai/elasticsearch,naveenhooda2000/elasticsearch,mmaracic/elasticsearch,Liziyao/elasticsearch,kubum/elasticsearch,hanst/elasticsearch,rhoml/elasticsearch,koxa29/elasticsearch,mapr/elasticsearch,MetSystem/elasticsearch,markharwood/elasticsearch,henakamaMSFT/elasticsearch,sarwarbhuiyan/elasticsearch,geidies/elasticsearch,hechunwen/elasticsearch,jimhooker2002/elasticsearch,dataduke/elasticsearch,spiegela/elasticsearch,MaineC/elasticsearch,zhaocloud/elasticsearch,mortonsykes/elasticsearch,onegambler/elasticsearch,girirajsharma/elasticsearch,sreeramjayan/elasticsearch,wuranbo/elasticsearch,xingguang2013/elasticsearch,cnfire/elasticsearch-1,mapr/elasticsearch,nellicus/elasticsearch,nknize/elasticsearch,javachengwc/elasticsearch,myelin/elasticsearch,jaynblue/elasticsearch,xpandan/elasticsearch,golubev/elasticsearch,ouyangkongtong/elasticsearch,Microsoft/elasticsearch,tebriel/elasticsearch,dataduke/elasticsearch,MisterAndersen/elasticsearch,Uiho/elasticsearch,micpalmia/elasticsearch,opendatasoft/elasticsearch,Stacey-Gammon/elasticsearch,bawse/elasticsearch,himanshuag/elasticsearch,feiqitian/elasticsearch,Brijeshrpatel9/elasticsearch,MaineC/elasticsearch,likaiwalkman/elasticsearch,yuy168/elasticsearch,gfyoung/elasticsearch,andrestc/elasticsearch,robin13/elasticsearch,wuranbo/elasticsearch,vroyer/elasticassandra,fekaputra/elasticsearch,schonfeld/elasticsearch,djschny/elasticsearch,diendt/elasticsearch,wayeast/elasticsearch,lmtwga/elasticsearch,onegambler/elasticsearch,VukDukic/elasticsearch,linglaiyao1314/elasticsearch,loconsolutions/elasticsearch,mmaracic/elasticsearch,ricardocerq/elasticsearch,jpountz/elasticsearch,pranavraman/elasticsearch,franklanganke/elasticsearch,AndreKR/elasticsearch,episerver/elasticsearch,Shekharrajak/elasticsearch,hechunwen/elasticsearch,lchennup/elasticsearch,mgalushka/elasticsearch,wimvds/elasticsearch,gfyoung/elasticsearch,Shekharrajak/elasticsearch,rmuir/elasticsearch,tebriel/elasticsearch,martinstuga/elasticsearch,sreeramjayan/elasticsearch,C-Bish/elasticsearch,NBSW/elasticsearch,huanzhong/elasticsearch,wittyameta/elasticsearch,TonyChai24/ESSource,SergVro/elasticsearch,IanvsPoplicola/elasticsearch,mbrukman/elasticsearch,caengcjd/elasticsearch,vorce/es-metrics,iamjakob/elasticsearch,rento19962/elasticsearch,mnylen/elasticsearch,awislowski/elasticsearch,zeroctu/elasticsearch,libosu/elasticsearch,TonyChai24/ESSource,yynil/elasticsearch,rento19962/elasticsearch,alexkuk/elasticsearch,artnowo/elasticsearch,yongminxia/elasticsearch,Widen/elasticsearch,MaineC/elasticsearch,bawse/elasticsearch,sarwarbhuiyan/elasticsearch,infusionsoft/elasticsearch,AndreKR/elasticsearch,MichaelLiZhou/elasticsearch,Uiho/elasticsearch,njlawton/elasticsearch,milodky/elasticsearch,MjAbuz/elasticsearch,zhiqinghuang/elasticsearch,brwe/elasticsearch,a2lin/elasticsearch,vorce/es-metrics,jeteve/elasticsearch,xuzha/elasticsearch,EasonYi/elasticsearch,awislowski/elasticsearch,fforbeck/elasticsearch,abibell/elasticsearch,TonyChai24/ESSource,wittyameta/elasticsearch,amit-shar/elasticsearch,chrismwendt/elasticsearch,jsgao0/elasticsearch,HarishAtGitHub/elasticsearch,alexksikes/elasticsearch,lightslife/elasticsearch,strapdata/elassandra-test,slavau/elasticsearch,rlugojr/elasticsearch,dataduke/elasticsearch,Charlesdong/elasticsearch,yuy168/elasticsearch,glefloch/elasticsearch,gfyoung/elasticsearch,markllama/elasticsearch,vietlq/elasticsearch,LeoYao/elasticsearch,winstonewert/elasticsearch,ESamir/elasticsearch,amit-shar/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,cwurm/elasticsearch,overcome/elasticsearch,elancom/elasticsearch,iantruslove/elasticsearch,cwurm/elasticsearch,Brijeshrpatel9/elasticsearch,rento19962/elasticsearch,golubev/elasticsearch,brwe/elasticsearch,strapdata/elassandra5-rc,avikurapati/elasticsearch,caengcjd/elasticsearch,zhiqinghuang/elasticsearch,huypx1292/elasticsearch,jaynblue/elasticsearch,ulkas/elasticsearch,gmarz/elasticsearch,kenshin233/elasticsearch,dongjoon-hyun/elasticsearch,wangyuxue/elasticsearch,s1monw/elasticsearch,abibell/elasticsearch,sjohnr/elasticsearch,wimvds/elasticsearch,yynil/elasticsearch,strapdata/elassandra,ulkas/elasticsearch,aparo/elasticsearch,nilabhsagar/elasticsearch,LewayneNaidoo/elasticsearch,tahaemin/elasticsearch,loconsolutions/elasticsearch,jpountz/elasticsearch,spiegela/elasticsearch,Charlesdong/elasticsearch,beiske/elasticsearch,kubum/elasticsearch,jango2015/elasticsearch,drewr/elasticsearch,sauravmondallive/elasticsearch,VukDukic/elasticsearch,mkis-/elasticsearch,Fsero/elasticsearch,mohsinh/elasticsearch,zhiqinghuang/elasticsearch,hirdesh2008/elasticsearch,skearns64/elasticsearch,mkis-/elasticsearch,combinatorist/elasticsearch,amit-shar/elasticsearch,abhijitiitr/es,jango2015/elasticsearch,truemped/elasticsearch,wimvds/elasticsearch,KimTaehee/elasticsearch,petmit/elasticsearch,achow/elasticsearch,truemped/elasticsearch,sjohnr/elasticsearch,mnylen/elasticsearch,alexbrasetvik/elasticsearch,girirajsharma/elasticsearch,milodky/elasticsearch,truemped/elasticsearch,kenshin233/elasticsearch,hanst/elasticsearch,ivansun1010/elasticsearch,nezirus/elasticsearch,achow/elasticsearch,aparo/elasticsearch,fred84/elasticsearch,andrejserafim/elasticsearch,myelin/elasticsearch,nomoa/elasticsearch,Rygbee/elasticsearch,mjason3/elasticsearch,lks21c/elasticsearch,winstonewert/elasticsearch,karthikjaps/elasticsearch,mjhennig/elasticsearch,gmarz/elasticsearch,Uiho/elasticsearch,onegambler/elasticsearch,Shekharrajak/elasticsearch,loconsolutions/elasticsearch,socialrank/elasticsearch,strapdata/elassandra-test,areek/elasticsearch,liweinan0423/elasticsearch,mortonsykes/elasticsearch,diendt/elasticsearch,fred84/elasticsearch,xingguang2013/elasticsearch,ricardocerq/elasticsearch,vroyer/elasticassandra,knight1128/elasticsearch,phani546/elasticsearch,Flipkart/elasticsearch,Rygbee/elasticsearch,slavau/elasticsearch,ricardocerq/elasticsearch,himanshuag/elasticsearch,fernandozhu/elasticsearch,lchennup/elasticsearch,jsgao0/elasticsearch,Collaborne/elasticsearch,golubev/elasticsearch,scottsom/elasticsearch,uschindler/elasticsearch,khiraiwa/elasticsearch,HonzaKral/elasticsearch,kalimatas/elasticsearch,infusionsoft/elasticsearch,IanvsPoplicola/elasticsearch,jprante/elasticsearch,s1monw/elasticsearch,onegambler/elasticsearch,coding0011/elasticsearch,F0lha/elasticsearch,lydonchandra/elasticsearch,KimTaehee/elasticsearch,lydonchandra/elasticsearch,trangvh/elasticsearch,mjason3/elasticsearch,nilabhsagar/elasticsearch,hafkensite/elasticsearch,smflorentino/elasticsearch,knight1128/elasticsearch,tkssharma/elasticsearch,winstonewert/elasticsearch,zhiqinghuang/elasticsearch,camilojd/elasticsearch,fubuki/elasticsearch,jw0201/elastic,nazarewk/elasticsearch,franklanganke/elasticsearch,springning/elasticsearch,JackyMai/elasticsearch,kaneshin/elasticsearch,obourgain/elasticsearch,Rygbee/elasticsearch,vvcephei/elasticsearch,masaruh/elasticsearch,lks21c/elasticsearch,javachengwc/elasticsearch,thecocce/elasticsearch,dataduke/elasticsearch,mjhennig/elasticsearch,HarishAtGitHub/elasticsearch,lightslife/elasticsearch,kenshin233/elasticsearch,EasonYi/elasticsearch,nknize/elasticsearch,pranavraman/elasticsearch,drewr/elasticsearch,markwalkom/elasticsearch,sposam/elasticsearch,szroland/elasticsearch,huanzhong/elasticsearch,dataduke/elasticsearch,bestwpw/elasticsearch,GlenRSmith/elasticsearch,artnowo/elasticsearch,avikurapati/elasticsearch,jimczi/elasticsearch,mgalushka/elasticsearch,hydro2k/elasticsearch,janmejay/elasticsearch,slavau/elasticsearch,golubev/elasticsearch,naveenhooda2000/elasticsearch,wuranbo/elasticsearch,wimvds/elasticsearch,tcucchietti/elasticsearch,zeroctu/elasticsearch,nezirus/elasticsearch,lks21c/elasticsearch,Collaborne/elasticsearch,fforbeck/elasticsearch,rmuir/elasticsearch,strapdata/elassandra,liweinan0423/elasticsearch,fubuki/elasticsearch,beiske/elasticsearch,jbertouch/elasticsearch,mjhennig/elasticsearch,F0lha/elasticsearch,nellicus/elasticsearch,geidies/elasticsearch,trangvh/elasticsearch,wangyuxue/elasticsearch,Chhunlong/elasticsearch,feiqitian/elasticsearch,humandb/elasticsearch,koxa29/elasticsearch,dongjoon-hyun/elasticsearch,anti-social/elasticsearch,pritishppai/elasticsearch,yanjunh/elasticsearch,a2lin/elasticsearch,strapdata/elassandra,marcuswr/elasticsearch-dateline,alexshadow007/elasticsearch,ydsakyclguozi/elasticsearch,alexbrasetvik/elasticsearch,lzo/elasticsearch-1,gingerwizard/elasticsearch,mm0/elasticsearch,humandb/elasticsearch,mgalushka/elasticsearch,a2lin/elasticsearch,F0lha/elasticsearch,scorpionvicky/elasticsearch,jimczi/elasticsearch,sarwarbhuiyan/elasticsearch,phani546/elasticsearch,mikemccand/elasticsearch,clintongormley/elasticsearch,ThalaivaStars/OrgRepo1,kcompher/elasticsearch,alexshadow007/elasticsearch,opendatasoft/elasticsearch,ouyangkongtong/elasticsearch,njlawton/elasticsearch,nellicus/elasticsearch,amit-shar/elasticsearch,raishiv/elasticsearch,petabytedata/elasticsearch,dantuffery/elasticsearch,vingupta3/elasticsearch,maddin2016/elasticsearch,jango2015/elasticsearch,sarwarbhuiyan/elasticsearch,mnylen/elasticsearch,MetSystem/elasticsearch,aparo/elasticsearch,infusionsoft/elasticsearch,MetSystem/elasticsearch,abibell/elasticsearch,amaliujia/elasticsearch,socialrank/elasticsearch,trangvh/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,wuranbo/elasticsearch,abibell/elasticsearch,kubum/elasticsearch,YosuaMichael/elasticsearch,gingerwizard/elasticsearch,schonfeld/elasticsearch,davidvgalbraith/elasticsearch,overcome/elasticsearch,markllama/elasticsearch,zhiqinghuang/elasticsearch,18098924759/elasticsearch,alexshadow007/elasticsearch,kingaj/elasticsearch,lks21c/elasticsearch,cnfire/elasticsearch-1,mmaracic/elasticsearch,salyh/elasticsearch,strapdata/elassandra-test,Clairebi/ElasticsearchClone,kubum/elasticsearch,fred84/elasticsearch,ckclark/elasticsearch,kingaj/elasticsearch,njlawton/elasticsearch,socialrank/elasticsearch,andrestc/elasticsearch,kunallimaye/elasticsearch,palecur/elasticsearch,yanjunh/elasticsearch,kingaj/elasticsearch,queirozfcom/elasticsearch,jsgao0/elasticsearch,coding0011/elasticsearch,jprante/elasticsearch,abibell/elasticsearch,skearns64/elasticsearch,tkssharma/elasticsearch,vvcephei/elasticsearch,milodky/elasticsearch,Shekharrajak/elasticsearch,lzo/elasticsearch-1,uboness/elasticsearch,Shepard1212/elasticsearch,chirilo/elasticsearch,bawse/elasticsearch,heng4fun/elasticsearch,marcuswr/elasticsearch-dateline,gfyoung/elasticsearch,karthikjaps/elasticsearch,dylan8902/elasticsearch,yongminxia/elasticsearch,NBSW/elasticsearch,rajanm/elasticsearch,pranavraman/elasticsearch,PhaedrusTheGreek/elasticsearch,vingupta3/elasticsearch,springning/elasticsearch,winstonewert/elasticsearch,AshishThakur/elasticsearch,MaineC/elasticsearch,sauravmondallive/elasticsearch,andrewvc/elasticsearch,andrewvc/elasticsearch,kaneshin/elasticsearch,henakamaMSFT/elasticsearch,rhoml/elasticsearch,ThiagoGarciaAlves/elasticsearch,avikurapati/elasticsearch,kevinkluge/elasticsearch,yongminxia/elasticsearch,zkidkid/elasticsearch,kingaj/elasticsearch,kunallimaye/elasticsearch,lmenezes/elasticsearch,Shepard1212/elasticsearch,vingupta3/elasticsearch,Siddartha07/elasticsearch,slavau/elasticsearch,jw0201/elastic,Kakakakakku/elasticsearch,slavau/elasticsearch,sscarduzio/elasticsearch,liweinan0423/elasticsearch,codebunt/elasticsearch,F0lha/elasticsearch,bawse/elasticsearch,scottsom/elasticsearch,adrianbk/elasticsearch,HonzaKral/elasticsearch,strapdata/elassandra,vietlq/elasticsearch,abhijitiitr/es,wayeast/elasticsearch,salyh/elasticsearch,AshishThakur/elasticsearch,btiernay/elasticsearch,franklanganke/elasticsearch,chirilo/elasticsearch,Chhunlong/elasticsearch,sc0ttkclark/elasticsearch,xuzha/elasticsearch,Siddartha07/elasticsearch,vroyer/elassandra,a2lin/elasticsearch,salyh/elasticsearch,mute/elasticsearch,Rygbee/elasticsearch,lmtwga/elasticsearch,queirozfcom/elasticsearch,lmenezes/elasticsearch,Chhunlong/elasticsearch,dongjoon-hyun/elasticsearch,uschindler/elasticsearch,sneivandt/elasticsearch,jimczi/elasticsearch,ThalaivaStars/OrgRepo1,dongjoon-hyun/elasticsearch,mjhennig/elasticsearch,alexkuk/elasticsearch,Brijeshrpatel9/elasticsearch,VukDukic/elasticsearch,mgalushka/elasticsearch,karthikjaps/elasticsearch,rento19962/elasticsearch,GlenRSmith/elasticsearch,masterweb121/elasticsearch,iamjakob/elasticsearch,wenpos/elasticsearch,truemped/elasticsearch,rmuir/elasticsearch,vingupta3/elasticsearch,Charlesdong/elasticsearch,weipinghe/elasticsearch,yanjunh/elasticsearch,kkirsche/elasticsearch,alexshadow007/elasticsearch,Kakakakakku/elasticsearch,acchen97/elasticsearch,Microsoft/elasticsearch,clintongormley/elasticsearch,mrorii/elasticsearch,s1monw/elasticsearch,camilojd/elasticsearch,18098924759/elasticsearch,vietlq/elasticsearch,elasticdog/elasticsearch,khiraiwa/elasticsearch,JervyShi/elasticsearch,luiseduardohdbackup/elasticsearch,btiernay/elasticsearch,wangtuo/elasticsearch,vroyer/elasticassandra,raishiv/elasticsearch,chrismwendt/elasticsearch,onegambler/elasticsearch,cnfire/elasticsearch-1,yanjunh/elasticsearch,tahaemin/elasticsearch,pranavraman/elasticsearch,wittyameta/elasticsearch,zhaocloud/elasticsearch,salyh/elasticsearch,ckclark/elasticsearch,fooljohnny/elasticsearch,tsohil/elasticsearch,yuy168/elasticsearch,hydro2k/elasticsearch,mkis-/elasticsearch,likaiwalkman/elasticsearch,Brijeshrpatel9/elasticsearch,drewr/elasticsearch,avikurapati/elasticsearch,ulkas/elasticsearch,xuzha/elasticsearch,18098924759/elasticsearch,mnylen/elasticsearch,gmarz/elasticsearch,LewayneNaidoo/elasticsearch,nellicus/elasticsearch,raishiv/elasticsearch,diendt/elasticsearch,nellicus/elasticsearch,nrkkalyan/elasticsearch,Widen/elasticsearch,hydro2k/elasticsearch,martinstuga/elasticsearch,tsohil/elasticsearch,alexbrasetvik/elasticsearch,bestwpw/elasticsearch,Widen/elasticsearch,likaiwalkman/elasticsearch,jprante/elasticsearch,nomoa/elasticsearch,davidvgalbraith/elasticsearch,ivansun1010/elasticsearch,kcompher/elasticsearch,onegambler/elasticsearch,sdauletau/elasticsearch,YosuaMichael/elasticsearch,huypx1292/elasticsearch,Microsoft/elasticsearch,scottsom/elasticsearch,xpandan/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,fernandozhu/elasticsearch,glefloch/elasticsearch,anti-social/elasticsearch,javachengwc/elasticsearch,qwerty4030/elasticsearch,episerver/elasticsearch,bestwpw/elasticsearch,geidies/elasticsearch,feiqitian/elasticsearch,LeoYao/elasticsearch,codebunt/elasticsearch,caengcjd/elasticsearch,sauravmondallive/elasticsearch,gingerwizard/elasticsearch,sc0ttkclark/elasticsearch,tcucchietti/elasticsearch,umeshdangat/elasticsearch,AndreKR/elasticsearch,jw0201/elastic,Fsero/elasticsearch,hechunwen/elasticsearch,queirozfcom/elasticsearch,areek/elasticsearch,petmit/elasticsearch,jimhooker2002/elasticsearch,sposam/elasticsearch,koxa29/elasticsearch,weipinghe/elasticsearch,AleksKochev/elasticsearch,kcompher/elasticsearch,libosu/elasticsearch,HarishAtGitHub/elasticsearch,vietlq/elasticsearch,ricardocerq/elasticsearch,mkis-/elasticsearch,Asimov4/elasticsearch,fforbeck/elasticsearch,zeroctu/elasticsearch,caengcjd/elasticsearch,nilabhsagar/elasticsearch,Ansh90/elasticsearch,zhaocloud/elasticsearch,smflorentino/elasticsearch,drewr/elasticsearch,martinstuga/elasticsearch,polyfractal/elasticsearch,JervyShi/elasticsearch,Stacey-Gammon/elasticsearch,palecur/elasticsearch,SergVro/elasticsearch,yuy168/elasticsearch,anti-social/elasticsearch,lydonchandra/elasticsearch,karthikjaps/elasticsearch,mrorii/elasticsearch,robin13/elasticsearch,strapdata/elassandra-test,Widen/elasticsearch,brwe/elasticsearch,humandb/elasticsearch,drewr/elasticsearch,clintongormley/elasticsearch,mapr/elasticsearch,palecur/elasticsearch,rhoml/elasticsearch,nazarewk/elasticsearch,mbrukman/elasticsearch,xingguang2013/elasticsearch,episerver/elasticsearch,mute/elasticsearch,rhoml/elasticsearch,shreejay/elasticsearch,snikch/elasticsearch,scottsom/elasticsearch,kubum/elasticsearch,snikch/elasticsearch,fubuki/elasticsearch,hydro2k/elasticsearch,scottsom/elasticsearch,Kakakakakku/elasticsearch,ThalaivaStars/OrgRepo1,sc0ttkclark/elasticsearch,sauravmondallive/elasticsearch,Microsoft/elasticsearch,humandb/elasticsearch,strapdata/elassandra-test,strapdata/elassandra-test,adrianbk/elasticsearch,MisterAndersen/elasticsearch,tkssharma/elasticsearch,ESamir/elasticsearch,mute/elasticsearch,iantruslove/elasticsearch,Shekharrajak/elasticsearch,kimchy/elasticsearch,jango2015/elasticsearch,camilojd/elasticsearch,diendt/elasticsearch,kimimj/elasticsearch,naveenhooda2000/elasticsearch,linglaiyao1314/elasticsearch,Liziyao/elasticsearch,mgalushka/elasticsearch,StefanGor/elasticsearch,s1monw/elasticsearch,clintongormley/elasticsearch,maddin2016/elasticsearch,SergVro/elasticsearch,elancom/elasticsearch,lzo/elasticsearch-1,wbowling/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,wbowling/elasticsearch,ulkas/elasticsearch,lmtwga/elasticsearch,caengcjd/elasticsearch,ThiagoGarciaAlves/elasticsearch,nazarewk/elasticsearch,luiseduardohdbackup/elasticsearch,mjason3/elasticsearch,easonC/elasticsearch,mjhennig/elasticsearch,NBSW/elasticsearch,wenpos/elasticsearch,hirdesh2008/elasticsearch,dylan8902/elasticsearch,boliza/elasticsearch,brandonkearby/elasticsearch,humandb/elasticsearch,jw0201/elastic,kimimj/elasticsearch,scorpionvicky/elasticsearch,rajanm/elasticsearch,apepper/elasticsearch,mikemccand/elasticsearch,elasticdog/elasticsearch,aglne/elasticsearch,elancom/elasticsearch,alexksikes/elasticsearch,Ansh90/elasticsearch,obourgain/elasticsearch,artnowo/elasticsearch,nknize/elasticsearch,achow/elasticsearch,masaruh/elasticsearch,Charlesdong/elasticsearch,pablocastro/elasticsearch,vrkansagara/elasticsearch,mm0/elasticsearch,btiernay/elasticsearch,jchampion/elasticsearch,kunallimaye/elasticsearch,diendt/elasticsearch,zhaocloud/elasticsearch,sjohnr/elasticsearch,alexksikes/elasticsearch,uboness/elasticsearch,alexbrasetvik/elasticsearch,zhiqinghuang/elasticsearch,nrkkalyan/elasticsearch,mcku/elasticsearch,MjAbuz/elasticsearch,jango2015/elasticsearch,schonfeld/elasticsearch,thecocce/elasticsearch,kalimatas/elasticsearch,zeroctu/elasticsearch,geidies/elasticsearch,lmtwga/elasticsearch,KimTaehee/elasticsearch,dpursehouse/elasticsearch,pritishppai/elasticsearch,sc0ttkclark/elasticsearch,tebriel/elasticsearch,girirajsharma/elasticsearch,pranavraman/elasticsearch,iacdingping/elasticsearch,kevinkluge/elasticsearch,achow/elasticsearch,kalburgimanjunath/elasticsearch,hanst/elasticsearch,artnowo/elasticsearch,Rygbee/elasticsearch,ThiagoGarciaAlves/elasticsearch,fforbeck/elasticsearch,iacdingping/elasticsearch,mbrukman/elasticsearch,sscarduzio/elasticsearch,18098924759/elasticsearch,mohit/elasticsearch,cnfire/elasticsearch-1,milodky/elasticsearch,weipinghe/elasticsearch,JervyShi/elasticsearch,Collaborne/elasticsearch,pritishppai/elasticsearch,Uiho/elasticsearch,markllama/elasticsearch,tsohil/elasticsearch,yuy168/elasticsearch,Asimov4/elasticsearch,polyfractal/elasticsearch,knight1128/elasticsearch,acchen97/elasticsearch,andrewvc/elasticsearch,adrianbk/elasticsearch,Chhunlong/elasticsearch,hirdesh2008/elasticsearch,djschny/elasticsearch,ZTE-PaaS/elasticsearch,pablocastro/elasticsearch,easonC/elasticsearch,koxa29/elasticsearch,dantuffery/elasticsearch,jango2015/elasticsearch,Kakakakakku/elasticsearch,nilabhsagar/elasticsearch,ivansun1010/elasticsearch,infusionsoft/elasticsearch,Collaborne/elasticsearch,kimchy/elasticsearch,vorce/es-metrics,martinstuga/elasticsearch,phani546/elasticsearch,ImpressTV/elasticsearch,mortonsykes/elasticsearch,linglaiyao1314/elasticsearch,pozhidaevak/elasticsearch,strapdata/elassandra5-rc,himanshuag/elasticsearch,andrestc/elasticsearch,lzo/elasticsearch-1,pozhidaevak/elasticsearch,kimimj/elasticsearch,sjohnr/elasticsearch,snikch/elasticsearch,xuzha/elasticsearch,xingguang2013/elasticsearch,mcku/elasticsearch,Liziyao/elasticsearch,mbrukman/elasticsearch,cwurm/elasticsearch,kenshin233/elasticsearch,overcome/elasticsearch,weipinghe/elasticsearch,lks21c/elasticsearch,sneivandt/elasticsearch,brandonkearby/elasticsearch,pablocastro/elasticsearch,pritishppai/elasticsearch,Liziyao/elasticsearch,Asimov4/elasticsearch,phani546/elasticsearch,Brijeshrpatel9/elasticsearch,ckclark/elasticsearch,HarishAtGitHub/elasticsearch,szroland/elasticsearch,mm0/elasticsearch,gmarz/elasticsearch,bestwpw/elasticsearch,kkirsche/elasticsearch,avikurapati/elasticsearch,jeteve/elasticsearch,sc0ttkclark/elasticsearch,areek/elasticsearch,mapr/elasticsearch,a2lin/elasticsearch,kalburgimanjunath/elasticsearch,heng4fun/elasticsearch,dylan8902/elasticsearch,mjason3/elasticsearch,jbertouch/elasticsearch,lightslife/elasticsearch,camilojd/elasticsearch,sdauletau/elasticsearch,jpountz/elasticsearch,vrkansagara/elasticsearch,ajhalani/elasticsearch,qwerty4030/elasticsearch,sdauletau/elasticsearch,mm0/elasticsearch,apepper/elasticsearch,kingaj/elasticsearch,sposam/elasticsearch,tahaemin/elasticsearch,lzo/elasticsearch-1,C-Bish/elasticsearch,wayeast/elasticsearch,PhaedrusTheGreek/elasticsearch,vingupta3/elasticsearch,diendt/elasticsearch,vrkansagara/elasticsearch,davidvgalbraith/elasticsearch,xuzha/elasticsearch,kaneshin/elasticsearch,xingguang2013/elasticsearch,Ansh90/elasticsearch,shreejay/elasticsearch,ZTE-PaaS/elasticsearch,zhaocloud/elasticsearch,smflorentino/elasticsearch,likaiwalkman/elasticsearch,fooljohnny/elasticsearch,nknize/elasticsearch,kalburgimanjunath/elasticsearch,fekaputra/elasticsearch,jsgao0/elasticsearch,khiraiwa/elasticsearch,dongjoon-hyun/elasticsearch,fforbeck/elasticsearch,amaliujia/elasticsearch,janmejay/elasticsearch,easonC/elasticsearch,kunallimaye/elasticsearch,socialrank/elasticsearch,LewayneNaidoo/elasticsearch,jango2015/elasticsearch,uschindler/elasticsearch,thecocce/elasticsearch,onegambler/elasticsearch,hanswang/elasticsearch,girirajsharma/elasticsearch,Clairebi/ElasticsearchClone,Clairebi/ElasticsearchClone,strapdata/elassandra5-rc,Asimov4/elasticsearch,wuranbo/elasticsearch,pablocastro/elasticsearch,Collaborne/elasticsearch,ckclark/elasticsearch,ThalaivaStars/OrgRepo1,franklanganke/elasticsearch,areek/elasticsearch,NBSW/elasticsearch,mrorii/elasticsearch,abhijitiitr/es,pablocastro/elasticsearch,iacdingping/elasticsearch,andrestc/elasticsearch,vroyer/elassandra,alexkuk/elasticsearch,bestwpw/elasticsearch,MetSystem/elasticsearch,koxa29/elasticsearch,wbowling/elasticsearch,ajhalani/elasticsearch,amaliujia/elasticsearch,kingaj/elasticsearch,kimimj/elasticsearch,kaneshin/elasticsearch,henakamaMSFT/elasticsearch,hirdesh2008/elasticsearch,schonfeld/elasticsearch,hafkensite/elasticsearch,nknize/elasticsearch,MichaelLiZhou/elasticsearch,glefloch/elasticsearch,easonC/elasticsearch,alexbrasetvik/elasticsearch,umeshdangat/elasticsearch,iamjakob/elasticsearch,NBSW/elasticsearch,mnylen/elasticsearch,GlenRSmith/elasticsearch,gingerwizard/elasticsearch,areek/elasticsearch,Ansh90/elasticsearch,yuy168/elasticsearch,wimvds/elasticsearch,kubum/elasticsearch,markwalkom/elasticsearch,wangtuo/elasticsearch,jeteve/elasticsearch,fekaputra/elasticsearch,qwerty4030/elasticsearch,Rygbee/elasticsearch,rmuir/elasticsearch,Uiho/elasticsearch,clintongormley/elasticsearch,cwurm/elasticsearch,micpalmia/elasticsearch,wittyameta/elasticsearch,kcompher/elasticsearch,sposam/elasticsearch,Stacey-Gammon/elasticsearch,likaiwalkman/elasticsearch,fubuki/elasticsearch,dylan8902/elasticsearch,jchampion/elasticsearch,cnfire/elasticsearch-1,MaineC/elasticsearch,pablocastro/elasticsearch,lchennup/elasticsearch,petabytedata/elasticsearch,vroyer/elassandra,Charlesdong/elasticsearch,iamjakob/elasticsearch,alexkuk/elasticsearch,ajhalani/elasticsearch,knight1128/elasticsearch,khiraiwa/elasticsearch,mapr/elasticsearch,fred84/elasticsearch,Charlesdong/elasticsearch,JSCooke/elasticsearch,jeteve/elasticsearch,andrejserafim/elasticsearch,myelin/elasticsearch,nilabhsagar/elasticsearch,sposam/elasticsearch,Flipkart/elasticsearch,wayeast/elasticsearch,F0lha/elasticsearch,ouyangkongtong/elasticsearch,JervyShi/elasticsearch,robin13/elasticsearch,zhiqinghuang/elasticsearch,wimvds/elasticsearch,loconsolutions/elasticsearch,Helen-Zhao/elasticsearch,Uiho/elasticsearch,sc0ttkclark/elasticsearch,PhaedrusTheGreek/elasticsearch,bawse/elasticsearch,ydsakyclguozi/elasticsearch,feiqitian/elasticsearch,luiseduardohdbackup/elasticsearch,mohit/elasticsearch,mute/elasticsearch,libosu/elasticsearch,kevinkluge/elasticsearch,wittyameta/elasticsearch,overcome/elasticsearch,JackyMai/elasticsearch,petabytedata/elasticsearch,truemped/elasticsearch,jeteve/elasticsearch,ulkas/elasticsearch,milodky/elasticsearch,fekaputra/elasticsearch,huypx1292/elasticsearch,jw0201/elastic,YosuaMichael/elasticsearch,Asimov4/elasticsearch,polyfractal/elasticsearch,sdauletau/elasticsearch,mute/elasticsearch,masaruh/elasticsearch,raishiv/elasticsearch,ydsakyclguozi/elasticsearch,vingupta3/elasticsearch,scorpionvicky/elasticsearch,mohit/elasticsearch,LeoYao/elasticsearch,pranavraman/elasticsearch,nezirus/elasticsearch,Stacey-Gammon/elasticsearch,Fsero/elasticsearch,i-am-Nathan/elasticsearch,Clairebi/ElasticsearchClone,mcku/elasticsearch,kalburgimanjunath/elasticsearch,Collaborne/elasticsearch,boliza/elasticsearch,Shekharrajak/elasticsearch,wenpos/elasticsearch,myelin/elasticsearch,fooljohnny/elasticsearch,aparo/elasticsearch,petmit/elasticsearch,girirajsharma/elasticsearch,NBSW/elasticsearch,tkssharma/elasticsearch,peschlowp/elasticsearch,elancom/elasticsearch,acchen97/elasticsearch,hydro2k/elasticsearch,mohit/elasticsearch,mm0/elasticsearch,adrianbk/elasticsearch,PhaedrusTheGreek/elasticsearch,markwalkom/elasticsearch,MisterAndersen/elasticsearch,ZTE-PaaS/elasticsearch,tahaemin/elasticsearch,schonfeld/elasticsearch,sreeramjayan/elasticsearch,opendatasoft/elasticsearch,maddin2016/elasticsearch,rajanm/elasticsearch,drewr/elasticsearch,StefanGor/elasticsearch,martinstuga/elasticsearch,markllama/elasticsearch,robin13/elasticsearch,HarishAtGitHub/elasticsearch,abhijitiitr/es,mikemccand/elasticsearch,hanswang/elasticsearch,zhaocloud/elasticsearch,btiernay/elasticsearch,apepper/elasticsearch,AshishThakur/elasticsearch,libosu/elasticsearch,ulkas/elasticsearch,umeshdangat/elasticsearch,jchampion/elasticsearch,kingaj/elasticsearch,jimhooker2002/elasticsearch,Liziyao/elasticsearch,lydonchandra/elasticsearch,i-am-Nathan/elasticsearch,ZTE-PaaS/elasticsearch,sscarduzio/elasticsearch,coding0011/elasticsearch,socialrank/elasticsearch,fubuki/elasticsearch,davidvgalbraith/elasticsearch,iantruslove/elasticsearch,henakamaMSFT/elasticsearch,pranavraman/elasticsearch,mohsinh/elasticsearch,njlawton/elasticsearch,springning/elasticsearch,micpalmia/elasticsearch,aglne/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,YosuaMichael/elasticsearch,mute/elasticsearch,boliza/elasticsearch,sc0ttkclark/elasticsearch,MisterAndersen/elasticsearch,tahaemin/elasticsearch,rajanm/elasticsearch,adrianbk/elasticsearch,jeteve/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,i-am-Nathan/elasticsearch,truemped/elasticsearch,thecocce/elasticsearch,huanzhong/elasticsearch,bestwpw/elasticsearch,pritishppai/elasticsearch,ouyangkongtong/elasticsearch,lydonchandra/elasticsearch,petmit/elasticsearch,IanvsPoplicola/elasticsearch,awislowski/elasticsearch,dataduke/elasticsearch,18098924759/elasticsearch,achow/elasticsearch,polyfractal/elasticsearch,mbrukman/elasticsearch,acchen97/elasticsearch,wenpos/elasticsearch,rhoml/elasticsearch,dantuffery/elasticsearch,dantuffery/elasticsearch,aglne/elasticsearch,obourgain/elasticsearch,karthikjaps/elasticsearch,beiske/elasticsearch,slavau/elasticsearch,i-am-Nathan/elasticsearch,skearns64/elasticsearch,ouyangkongtong/elasticsearch,kalimatas/elasticsearch,achow/elasticsearch,Fsero/elasticsearch,abhijitiitr/es,heng4fun/elasticsearch,fooljohnny/elasticsearch,markharwood/elasticsearch,sneivandt/elasticsearch,chirilo/elasticsearch,humandb/elasticsearch,smflorentino/elasticsearch,hanst/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,combinatorist/elasticsearch,andrestc/elasticsearch,kalimatas/elasticsearch,beiske/elasticsearch,TonyChai24/ESSource,nezirus/elasticsearch,Shepard1212/elasticsearch,hanswang/elasticsearch,elancom/elasticsearch,tahaemin/elasticsearch,masaruh/elasticsearch,karthikjaps/elasticsearch,salyh/elasticsearch,Brijeshrpatel9/elasticsearch,likaiwalkman/elasticsearch,yanjunh/elasticsearch,iacdingping/elasticsearch,cwurm/elasticsearch,uschindler/elasticsearch,masterweb121/elasticsearch,nazarewk/elasticsearch,markllama/elasticsearch,dpursehouse/elasticsearch,scorpionvicky/elasticsearch,MichaelLiZhou/elasticsearch,lchennup/elasticsearch,combinatorist/elasticsearch,caengcjd/elasticsearch,Siddartha07/elasticsearch,MjAbuz/elasticsearch,rento19962/elasticsearch,brwe/elasticsearch,zkidkid/elasticsearch,lightslife/elasticsearch,lightslife/elasticsearch,andrejserafim/elasticsearch,karthikjaps/elasticsearch,fubuki/elasticsearch,khiraiwa/elasticsearch,zeroctu/elasticsearch,strapdata/elassandra,jpountz/elasticsearch,franklanganke/elasticsearch,kunallimaye/elasticsearch,Fsero/elasticsearch,tcucchietti/elasticsearch,apepper/elasticsearch,markharwood/elasticsearch,GlenRSmith/elasticsearch,himanshuag/elasticsearch,LeoYao/elasticsearch,Microsoft/elasticsearch,Helen-Zhao/elasticsearch,springning/elasticsearch,wbowling/elasticsearch,iamjakob/elasticsearch,masterweb121/elasticsearch,AleksKochev/elasticsearch,opendatasoft/elasticsearch,alexksikes/elasticsearch,Rygbee/elasticsearch,MetSystem/elasticsearch,hanst/elasticsearch,anti-social/elasticsearch,petabytedata/elasticsearch,EasonYi/elasticsearch,vingupta3/elasticsearch,mkis-/elasticsearch,JackyMai/elasticsearch,tsohil/elasticsearch,mortonsykes/elasticsearch,btiernay/elasticsearch,ricardocerq/elasticsearch,bestwpw/elasticsearch,vrkansagara/elasticsearch,nomoa/elasticsearch,rajanm/elasticsearch,EasonYi/elasticsearch,wbowling/elasticsearch,KimTaehee/elasticsearch,rlugojr/elasticsearch,masterweb121/elasticsearch,luiseduardohdbackup/elasticsearch,franklanganke/elasticsearch,AshishThakur/elasticsearch,Flipkart/elasticsearch,kunallimaye/elasticsearch,sarwarbhuiyan/elasticsearch,kkirsche/elasticsearch,socialrank/elasticsearch,kenshin233/elasticsearch,sposam/elasticsearch,YosuaMichael/elasticsearch,hafkensite/elasticsearch,Brijeshrpatel9/elasticsearch,ouyangkongtong/elasticsearch,mcku/elasticsearch,18098924759/elasticsearch,StefanGor/elasticsearch,petabytedata/elasticsearch,MjAbuz/elasticsearch,sreeramjayan/elasticsearch,ajhalani/elasticsearch,HarishAtGitHub/elasticsearch,pozhidaevak/elasticsearch,Fsero/elasticsearch,huypx1292/elasticsearch,rhoml/elasticsearch,humandb/elasticsearch,masaruh/elasticsearch,tkssharma/elasticsearch,jimczi/elasticsearch,jimhooker2002/elasticsearch,andrejserafim/elasticsearch,codebunt/elasticsearch,tsohil/elasticsearch,ZTE-PaaS/elasticsearch,Flipkart/elasticsearch,rlugojr/elasticsearch,tebriel/elasticsearch,himanshuag/elasticsearch,qwerty4030/elasticsearch,s1monw/elasticsearch,weipinghe/elasticsearch,mrorii/elasticsearch,jaynblue/elasticsearch,chirilo/elasticsearch,henakamaMSFT/elasticsearch,fred84/elasticsearch,nrkkalyan/elasticsearch,JervyShi/elasticsearch,abibell/elasticsearch,liweinan0423/elasticsearch,vietlq/elasticsearch,boliza/elasticsearch,djschny/elasticsearch,kalimatas/elasticsearch,ydsakyclguozi/elasticsearch,huypx1292/elasticsearch,mnylen/elasticsearch,mmaracic/elasticsearch,Clairebi/ElasticsearchClone,hanswang/elasticsearch,szroland/elasticsearch,snikch/elasticsearch,koxa29/elasticsearch,yynil/elasticsearch,JSCooke/elasticsearch,sauravmondallive/elasticsearch,skearns64/elasticsearch,dylan8902/elasticsearch,yynil/elasticsearch,KimTaehee/elasticsearch,kimimj/elasticsearch,vvcephei/elasticsearch,ThiagoGarciaAlves/elasticsearch,xpandan/elasticsearch,gingerwizard/elasticsearch,pritishppai/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,ThalaivaStars/OrgRepo1,fekaputra/elasticsearch,jprante/elasticsearch,yongminxia/elasticsearch,Helen-Zhao/elasticsearch,kenshin233/elasticsearch,VukDukic/elasticsearch,smflorentino/elasticsearch,spiegela/elasticsearch,JSCooke/elasticsearch,Chhunlong/elasticsearch,jw0201/elastic,glefloch/elasticsearch,LeoYao/elasticsearch,jimhooker2002/elasticsearch,hafkensite/elasticsearch,maddin2016/elasticsearch,lydonchandra/elasticsearch,HonzaKral/elasticsearch,ouyangkongtong/elasticsearch,aglne/elasticsearch,GlenRSmith/elasticsearch,strapdata/elassandra5-rc,jpountz/elasticsearch,jsgao0/elasticsearch,Widen/elasticsearch,springning/elasticsearch,libosu/elasticsearch,sscarduzio/elasticsearch,queirozfcom/elasticsearch,ivansun1010/elasticsearch,amaliujia/elasticsearch,gingerwizard/elasticsearch,ESamir/elasticsearch,aglne/elasticsearch,lzo/elasticsearch-1,AshishThakur/elasticsearch,qwerty4030/elasticsearch,wayeast/elasticsearch,camilojd/elasticsearch,markharwood/elasticsearch,clintongormley/elasticsearch,djschny/elasticsearch,brandonkearby/elasticsearch,KimTaehee/elasticsearch,lmtwga/elasticsearch,Clairebi/ElasticsearchClone,xpandan/elasticsearch,boliza/elasticsearch,adrianbk/elasticsearch,Uiho/elasticsearch,vorce/es-metrics,girirajsharma/elasticsearch,himanshuag/elasticsearch,jchampion/elasticsearch,szroland/elasticsearch,andrestc/elasticsearch,sarwarbhuiyan/elasticsearch,acchen97/elasticsearch,yuy168/elasticsearch,huanzhong/elasticsearch,F0lha/elasticsearch,elasticdog/elasticsearch,pozhidaevak/elasticsearch,ImpressTV/elasticsearch,lightslife/elasticsearch,phani546/elasticsearch,palecur/elasticsearch,golubev/elasticsearch,beiske/elasticsearch,rlugojr/elasticsearch,brandonkearby/elasticsearch,ESamir/elasticsearch,SergVro/elasticsearch,kalburgimanjunath/elasticsearch,mute/elasticsearch,sjohnr/elasticsearch,fernandozhu/elasticsearch,ckclark/elasticsearch,chrismwendt/elasticsearch,VukDukic/elasticsearch,Charlesdong/elasticsearch,vietlq/elasticsearch,kimimj/elasticsearch,njlawton/elasticsearch,sreeramjayan/elasticsearch,schonfeld/elasticsearch,tcucchietti/elasticsearch,hanst/elasticsearch,Widen/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,opendatasoft/elasticsearch,wayeast/elasticsearch,jchampion/elasticsearch,thecocce/elasticsearch,kcompher/elasticsearch,linglaiyao1314/elasticsearch,iacdingping/elasticsearch,mcku/elasticsearch,xingguang2013/elasticsearch,snikch/elasticsearch,vietlq/elasticsearch,smflorentino/elasticsearch,thecocce/elasticsearch,adrianbk/elasticsearch,zeroctu/elasticsearch,umeshdangat/elasticsearch,jimhooker2002/elasticsearch,zkidkid/elasticsearch,janmejay/elasticsearch,MisterAndersen/elasticsearch,jbertouch/elasticsearch,codebunt/elasticsearch,amaliujia/elasticsearch,micpalmia/elasticsearch,AleksKochev/elasticsearch,linglaiyao1314/elasticsearch,nomoa/elasticsearch,tcucchietti/elasticsearch,markllama/elasticsearch,iantruslove/elasticsearch,AndreKR/elasticsearch,dpursehouse/elasticsearch,iamjakob/elasticsearch,coding0011/elasticsearch,Chhunlong/elasticsearch,luiseduardohdbackup/elasticsearch,chirilo/elasticsearch,huanzhong/elasticsearch,wangyuxue/elasticsearch,sdauletau/elasticsearch,strapdata/elassandra5-rc,ImpressTV/elasticsearch,zkidkid/elasticsearch,codebunt/elasticsearch,mohsinh/elasticsearch,iantruslove/elasticsearch,polyfractal/elasticsearch,lchennup/elasticsearch,AndreKR/elasticsearch,kalburgimanjunath/elasticsearch,KimTaehee/elasticsearch,hydro2k/elasticsearch,trangvh/elasticsearch,xpandan/elasticsearch,mbrukman/elasticsearch,wenpos/elasticsearch,peschlowp/elasticsearch,spiegela/elasticsearch,davidvgalbraith/elasticsearch,aglne/elasticsearch,masterweb121/elasticsearch,andrejserafim/elasticsearch,fernandozhu/elasticsearch,martinstuga/elasticsearch,cnfire/elasticsearch-1,glefloch/elasticsearch,peschlowp/elasticsearch,MichaelLiZhou/elasticsearch,Liziyao/elasticsearch,knight1128/elasticsearch,weipinghe/elasticsearch,nomoa/elasticsearch,geidies/elasticsearch,markwalkom/elasticsearch,gfyoung/elasticsearch,mikemccand/elasticsearch,IanvsPoplicola/elasticsearch,hechunwen/elasticsearch,ckclark/elasticsearch,luiseduardohdbackup/elasticsearch,micpalmia/elasticsearch,camilojd/elasticsearch,Shepard1212/elasticsearch,Siddartha07/elasticsearch,markharwood/elasticsearch,jbertouch/elasticsearch,rmuir/elasticsearch,marcuswr/elasticsearch-dateline,apepper/elasticsearch,awislowski/elasticsearch,hafkensite/elasticsearch,janmejay/elasticsearch,mbrukman/elasticsearch,yongminxia/elasticsearch,amit-shar/elasticsearch,skearns64/elasticsearch,schonfeld/elasticsearch,djschny/elasticsearch,lydonchandra/elasticsearch,SergVro/elasticsearch,mkis-/elasticsearch,socialrank/elasticsearch,mapr/elasticsearch,acchen97/elasticsearch,snikch/elasticsearch,palecur/elasticsearch,alexbrasetvik/elasticsearch,mikemccand/elasticsearch,dylan8902/elasticsearch,Asimov4/elasticsearch,jimczi/elasticsearch,Widen/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,NBSW/elasticsearch,caengcjd/elasticsearch,sjohnr/elasticsearch,MichaelLiZhou/elasticsearch,sarwarbhuiyan/elasticsearch,tsohil/elasticsearch,mmaracic/elasticsearch,queirozfcom/elasticsearch,tebriel/elasticsearch,Fsero/elasticsearch,sauravmondallive/elasticsearch,Shekharrajak/elasticsearch,masterweb121/elasticsearch,kcompher/elasticsearch,episerver/elasticsearch,mrorii/elasticsearch,cnfire/elasticsearch-1,apepper/elasticsearch,robin13/elasticsearch,dpursehouse/elasticsearch,infusionsoft/elasticsearch,tkssharma/elasticsearch,alexkuk/elasticsearch,drewr/elasticsearch,Siddartha07/elasticsearch,apepper/elasticsearch,wangtuo/elasticsearch,achow/elasticsearch,wangtuo/elasticsearch,HonzaKral/elasticsearch,shreejay/elasticsearch,kevinkluge/elasticsearch,markharwood/elasticsearch,i-am-Nathan/elasticsearch,mnylen/elasticsearch,MetSystem/elasticsearch,infusionsoft/elasticsearch,jprante/elasticsearch,yynil/elasticsearch,wimvds/elasticsearch,JSCooke/elasticsearch,janmejay/elasticsearch,myelin/elasticsearch,milodky/elasticsearch,lightslife/elasticsearch,uschindler/elasticsearch,elasticdog/elasticsearch,fernandozhu/elasticsearch,franklanganke/elasticsearch,spiegela/elasticsearch,jaynblue/elasticsearch,szroland/elasticsearch,nellicus/elasticsearch,mjason3/elasticsearch,btiernay/elasticsearch,ulkas/elasticsearch,xingguang2013/elasticsearch,LewayneNaidoo/elasticsearch,naveenhooda2000/elasticsearch,ydsakyclguozi/elasticsearch,LeoYao/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,scorpionvicky/elasticsearch,awislowski/elasticsearch,trangvh/elasticsearch,springning/elasticsearch,yynil/elasticsearch,elancom/elasticsearch,ImpressTV/elasticsearch,alexshadow007/elasticsearch,PhaedrusTheGreek/elasticsearch,alexksikes/elasticsearch,areek/elasticsearch,chrismwendt/elasticsearch,ivansun1010/elasticsearch,AleksKochev/elasticsearch,lmtwga/elasticsearch,luiseduardohdbackup/elasticsearch,Flipkart/elasticsearch,markllama/elasticsearch,wayeast/elasticsearch,areek/elasticsearch,ImpressTV/elasticsearch,jeteve/elasticsearch,djschny/elasticsearch,nrkkalyan/elasticsearch,sdauletau/elasticsearch,combinatorist/elasticsearch,kkirsche/elasticsearch,sdauletau/elasticsearch,springning/elasticsearch,Helen-Zhao/elasticsearch,mohit/elasticsearch,iacdingping/elasticsearch,tebriel/elasticsearch,TonyChai24/ESSource,Shepard1212/elasticsearch,Helen-Zhao/elasticsearch,iacdingping/elasticsearch,polyfractal/elasticsearch,MjAbuz/elasticsearch,hanswang/elasticsearch,codebunt/elasticsearch,AleksKochev/elasticsearch,mm0/elasticsearch,kaneshin/elasticsearch,kimchy/elasticsearch,liweinan0423/elasticsearch,yongminxia/elasticsearch,linglaiyao1314/elasticsearch,overcome/elasticsearch,mohsinh/elasticsearch,lzo/elasticsearch-1,Ansh90/elasticsearch,rento19962/elasticsearch,mrorii/elasticsearch,sneivandt/elasticsearch,Ansh90/elasticsearch,ESamir/elasticsearch,nellicus/elasticsearch,huanzhong/elasticsearch,StefanGor/elasticsearch,C-Bish/elasticsearch,jbertouch/elasticsearch,kkirsche/elasticsearch,tahaemin/elasticsearch,petabytedata/elasticsearch,kkirsche/elasticsearch,vorce/es-metrics,djschny/elasticsearch,mohsinh/elasticsearch,feiqitian/elasticsearch,ThiagoGarciaAlves/elasticsearch,janmejay/elasticsearch,raishiv/elasticsearch,LeoYao/elasticsearch,vvcephei/elasticsearch,anti-social/elasticsearch,mmaracic/elasticsearch,dpursehouse/elasticsearch,queirozfcom/elasticsearch,AshishThakur/elasticsearch,marcuswr/elasticsearch-dateline,hirdesh2008/elasticsearch,combinatorist/elasticsearch,infusionsoft/elasticsearch,chirilo/elasticsearch,Siddartha07/elasticsearch,JSCooke/elasticsearch,ThiagoGarciaAlves/elasticsearch,easonC/elasticsearch,knight1128/elasticsearch,kimimj/elasticsearch,xpandan/elasticsearch,jbertouch/elasticsearch,beiske/elasticsearch,fooljohnny/elasticsearch,jsgao0/elasticsearch,fooljohnny/elasticsearch,mjhennig/elasticsearch,obourgain/elasticsearch,Flipkart/elasticsearch,nezirus/elasticsearch,iamjakob/elasticsearch,davidvgalbraith/elasticsearch,JackyMai/elasticsearch,sscarduzio/elasticsearch,overcome/elasticsearch,JervyShi/elasticsearch,mjhennig/elasticsearch,markwalkom/elasticsearch,acchen97/elasticsearch,dantuffery/elasticsearch,wbowling/elasticsearch,ckclark/elasticsearch,MjAbuz/elasticsearch,btiernay/elasticsearch,dataduke/elasticsearch,amit-shar/elasticsearch,PhaedrusTheGreek/elasticsearch,yongminxia/elasticsearch,vvcephei/elasticsearch,pablocastro/elasticsearch,Collaborne/elasticsearch,amaliujia/elasticsearch,peschlowp/elasticsearch,MichaelLiZhou/elasticsearch,lmtwga/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,tsohil/elasticsearch,huypx1292/elasticsearch,uboness/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,andrestc/elasticsearch,mortonsykes/elasticsearch,aparo/elasticsearch,uboness/elasticsearch,C-Bish/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,heng4fun/elasticsearch,nrkkalyan/elasticsearch,AndreKR/elasticsearch,golubev/elasticsearch,marcuswr/elasticsearch-dateline,peschlowp/elasticsearch,javachengwc/elasticsearch,zeroctu/elasticsearch,gmarz/elasticsearch,iantruslove/elasticsearch,hanswang/elasticsearch,LewayneNaidoo/elasticsearch,hechunwen/elasticsearch,EasonYi/elasticsearch,Stacey-Gammon/elasticsearch,jchampion/elasticsearch,skearns64/elasticsearch,heng4fun/elasticsearch,Kakakakakku/elasticsearch,jaynblue/elasticsearch,vrkansagara/elasticsearch,kubum/elasticsearch,loconsolutions/elasticsearch,linglaiyao1314/elasticsearch,kenshin233/elasticsearch,HarishAtGitHub/elasticsearch,mm0/elasticsearch,zkidkid/elasticsearch,dylan8902/elasticsearch,hirdesh2008/elasticsearch,petabytedata/elasticsearch,hanswang/elasticsearch,MjAbuz/elasticsearch,loconsolutions/elasticsearch,ImpressTV/elasticsearch,coding0011/elasticsearch,Liziyao/elasticsearch,mcku/elasticsearch,Chhunlong/elasticsearch,ydsakyclguozi/elasticsearch,hechunwen/elasticsearch,masterweb121/elasticsearch,lchennup/elasticsearch,rmuir/elasticsearch,winstonewert/elasticsearch,anti-social/elasticsearch,mgalushka/elasticsearch,wittyameta/elasticsearch,brwe/elasticsearch,kevinkluge/elasticsearch,chrismwendt/elasticsearch,shreejay/elasticsearch,YosuaMichael/elasticsearch,elancom/elasticsearch,vrkansagara/elasticsearch,jimhooker2002/elasticsearch,fekaputra/elasticsearch,TonyChai24/ESSource,C-Bish/elasticsearch,opendatasoft/elasticsearch,kalburgimanjunath/elasticsearch,amit-shar/elasticsearch,phani546/elasticsearch,markwalkom/elasticsearch,mcku/elasticsearch,knight1128/elasticsearch,SergVro/elasticsearch,maddin2016/elasticsearch,umeshdangat/elasticsearch,TonyChai24/ESSource,EasonYi/elasticsearch,geidies/elasticsearch,libosu/elasticsearch,sreeramjayan/elasticsearch,hafkensite/elasticsearch,EasonYi/elasticsearch,artnowo/elasticsearch,strapdata/elassandra-test
/* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch licenses this * file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.action.termvector; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.action.support.TransportActions; import org.elasticsearch.action.support.single.shard.TransportShardSingleOperationAction; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.block.ClusterBlockException; import org.elasticsearch.cluster.block.ClusterBlockLevel; import org.elasticsearch.cluster.routing.ShardIterator; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.service.IndexService; import org.elasticsearch.index.shard.service.IndexShard; import org.elasticsearch.indices.IndicesService; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; public class TransportSingleShardMultiTermsVectorAction extends TransportShardSingleOperationAction<MultiTermVectorsShardRequest, MultiTermVectorsShardResponse> { private final IndicesService indicesService; @Inject public TransportSingleShardMultiTermsVectorAction(Settings settings, ClusterService clusterService, TransportService transportService, IndicesService indicesService, ThreadPool threadPool) { super(settings, threadPool, clusterService, transportService); this.indicesService = indicesService; } @Override protected String executor() { return ThreadPool.Names.GET; } @Override protected String transportAction() { return MultiTermVectorsAction.NAME + "/shard"; } @Override protected MultiTermVectorsShardRequest newRequest() { return new MultiTermVectorsShardRequest(); } @Override protected MultiTermVectorsShardResponse newResponse() { return new MultiTermVectorsShardResponse(); } @Override protected ClusterBlockException checkGlobalBlock(ClusterState state, MultiTermVectorsShardRequest request) { return state.blocks().globalBlockedException(ClusterBlockLevel.READ); } @Override protected ClusterBlockException checkRequestBlock(ClusterState state, MultiTermVectorsShardRequest request) { return state.blocks().indexBlockedException(ClusterBlockLevel.READ, request.index()); } @Override protected ShardIterator shards(ClusterState state, MultiTermVectorsShardRequest request) { return clusterService.operationRouting() .getShards(clusterService.state(), request.index(), request.shardId(), request.preference()); } @Override protected void resolveRequest(ClusterState state, MultiTermVectorsShardRequest request) { // no need to set concrete index and routing here, it has already been set by the multi term vectors action on the item // request.index(state.metaData().concreteIndex(request.index())); } @Override protected MultiTermVectorsShardResponse shardOperation(MultiTermVectorsShardRequest request, int shardId) throws ElasticSearchException { MultiTermVectorsShardResponse response = new MultiTermVectorsShardResponse(); for (int i = 0; i < request.locations.size(); i++) { TermVectorRequest termVectorRequest = request.requests.get(i); try { IndexService indexService = indicesService.indexServiceSafe(request.index()); IndexShard indexShard = indexService.shardSafe(shardId); TermVectorResponse termVectorResponse = indexShard.termVectorService().getTermVector(termVectorRequest); response.add(request.locations.get(i), termVectorResponse); } catch (Throwable t) { if (TransportActions.isShardNotAvailableException(t)) { throw (ElasticSearchException) t; } else { logger.debug("[{}][{}] failed to execute multi term vectors for [{}]/[{}]", t, request.index(), shardId, termVectorRequest.type(), termVectorRequest.id()); response.add(request.locations.get(i), new MultiTermVectorsResponse.Failure(request.index(), termVectorRequest.type(), termVectorRequest.id(), ExceptionsHelper.detailedMessage(t))); } } } return response; } }
src/main/java/org/elasticsearch/action/termvector/TransportSingleShardMultiTermsVectorAction.java
/* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch licenses this * file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.action.termvector; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.action.support.single.shard.TransportShardSingleOperationAction; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.block.ClusterBlockException; import org.elasticsearch.cluster.block.ClusterBlockLevel; import org.elasticsearch.cluster.routing.ShardIterator; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.service.IndexService; import org.elasticsearch.index.shard.service.IndexShard; import org.elasticsearch.indices.IndicesService; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; public class TransportSingleShardMultiTermsVectorAction extends TransportShardSingleOperationAction<MultiTermVectorsShardRequest, MultiTermVectorsShardResponse> { private final IndicesService indicesService; @Inject public TransportSingleShardMultiTermsVectorAction(Settings settings, ClusterService clusterService, TransportService transportService, IndicesService indicesService, ThreadPool threadPool) { super(settings, threadPool, clusterService, transportService); this.indicesService = indicesService; } @Override protected String executor() { return ThreadPool.Names.GET; } @Override protected String transportAction() { return MultiTermVectorsAction.NAME + "/shard"; } @Override protected MultiTermVectorsShardRequest newRequest() { return new MultiTermVectorsShardRequest(); } @Override protected MultiTermVectorsShardResponse newResponse() { return new MultiTermVectorsShardResponse(); } @Override protected ClusterBlockException checkGlobalBlock(ClusterState state, MultiTermVectorsShardRequest request) { return state.blocks().globalBlockedException(ClusterBlockLevel.READ); } @Override protected ClusterBlockException checkRequestBlock(ClusterState state, MultiTermVectorsShardRequest request) { return state.blocks().indexBlockedException(ClusterBlockLevel.READ, request.index()); } @Override protected ShardIterator shards(ClusterState state, MultiTermVectorsShardRequest request) { return clusterService.operationRouting() .getShards(clusterService.state(), request.index(), request.shardId(), request.preference()); } @Override protected void resolveRequest(ClusterState state, MultiTermVectorsShardRequest request) { // no need to set concrete index and routing here, it has already been set by the multi term vectors action on the item // request.index(state.metaData().concreteIndex(request.index())); } @Override protected MultiTermVectorsShardResponse shardOperation(MultiTermVectorsShardRequest request, int shardId) throws ElasticSearchException { MultiTermVectorsShardResponse response = new MultiTermVectorsShardResponse(); for (int i = 0; i < request.locations.size(); i++) { TermVectorRequest termVectorRequest = request.requests.get(i); try { IndexService indexService = indicesService.indexServiceSafe(request.index()); IndexShard indexShard = indexService.shardSafe(shardId); TermVectorResponse termVectorResponse = indexShard.termVectorService().getTermVector(termVectorRequest); response.add(request.locations.get(i), termVectorResponse); } catch (Throwable t) { logger.debug("[{}][{}] failed to execute multi term vectors for [{}]/[{}]", t, request.index(), shardId, termVectorRequest.type(), termVectorRequest.id()); response.add(request.locations.get(i), new MultiTermVectorsResponse.Failure(request.index(), termVectorRequest.type(), termVectorRequest.id(), ExceptionsHelper.detailedMessage(t))); } } return response; } }
If there is an exception that indicates that the shard isn't available then the exception should bubble up to the TransportShardSingleOperationAction class, so the shard level request can be retried on a different shard. (multi term vector api)
src/main/java/org/elasticsearch/action/termvector/TransportSingleShardMultiTermsVectorAction.java
If there is an exception that indicates that the shard isn't available then the exception should bubble up to the TransportShardSingleOperationAction class, so the shard level request can be retried on a different shard. (multi term vector api)
<ide><path>rc/main/java/org/elasticsearch/action/termvector/TransportSingleShardMultiTermsVectorAction.java <ide> <ide> import org.elasticsearch.ElasticSearchException; <ide> import org.elasticsearch.ExceptionsHelper; <add>import org.elasticsearch.action.support.TransportActions; <ide> import org.elasticsearch.action.support.single.shard.TransportShardSingleOperationAction; <ide> import org.elasticsearch.cluster.ClusterService; <ide> import org.elasticsearch.cluster.ClusterState; <ide> TermVectorResponse termVectorResponse = indexShard.termVectorService().getTermVector(termVectorRequest); <ide> response.add(request.locations.get(i), termVectorResponse); <ide> } catch (Throwable t) { <del> logger.debug("[{}][{}] failed to execute multi term vectors for [{}]/[{}]", t, request.index(), shardId, termVectorRequest.type(), termVectorRequest.id()); <del> response.add(request.locations.get(i), <del> new MultiTermVectorsResponse.Failure(request.index(), termVectorRequest.type(), termVectorRequest.id(), ExceptionsHelper.detailedMessage(t))); <add> if (TransportActions.isShardNotAvailableException(t)) { <add> throw (ElasticSearchException) t; <add> } else { <add> logger.debug("[{}][{}] failed to execute multi term vectors for [{}]/[{}]", t, request.index(), shardId, termVectorRequest.type(), termVectorRequest.id()); <add> response.add(request.locations.get(i), <add> new MultiTermVectorsResponse.Failure(request.index(), termVectorRequest.type(), termVectorRequest.id(), ExceptionsHelper.detailedMessage(t))); <add> } <ide> } <ide> } <ide>
Java
apache-2.0
1cf0fedd902a523f2970757f248b589d278b9f25
0
johannilsson/sthlmtraveling,johannilsson/sthlmtraveling
/* * Copyright (C) 2013 Johan Nilsson <http://markupartist.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.markupartist.sthlmtraveling; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.os.Bundle; import android.support.annotation.ColorInt; import android.support.design.widget.Snackbar; import android.support.v4.content.ContextCompat; import android.support.v7.app.ActionBar; import android.text.TextUtils; import android.text.format.DateFormat; import android.util.Log; import android.view.MenuItem; import android.view.View; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.UiSettings; import com.google.android.gms.maps.model.BitmapDescriptor; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.Polyline; import com.google.android.gms.maps.model.PolylineOptions; import com.markupartist.sthlmtraveling.data.models.Leg; import com.markupartist.sthlmtraveling.data.models.Route; import com.markupartist.sthlmtraveling.data.models.Step; import com.markupartist.sthlmtraveling.provider.planner.JourneyQuery; import com.markupartist.sthlmtraveling.provider.planner.Planner; import com.markupartist.sthlmtraveling.provider.planner.Planner.IntermediateStop; import com.markupartist.sthlmtraveling.provider.planner.Planner.SubTrip; import com.markupartist.sthlmtraveling.provider.planner.Planner.Trip2; import com.markupartist.sthlmtraveling.provider.site.Site; import com.markupartist.sthlmtraveling.utils.Analytics; import com.markupartist.sthlmtraveling.utils.PolyUtil; import com.markupartist.sthlmtraveling.utils.StringUtils; import com.markupartist.sthlmtraveling.utils.ViewHelper; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; public class ViewOnMapActivity extends BaseFragmentActivity implements OnMapReadyCallback { private static final String TAG = "ViewOnMapActivity"; public static String EXTRA_LOCATION = "com.markupartist.sthlmtraveling.extra.Location"; public static String EXTRA_JOURNEY_QUERY = "com.markupartist.sthlmtraveling.extra.JourneyQuery"; public static String EXTRA_TRIP = "com.markupartist.sthlmtraveling.extra.Trip"; public static String EXTRA_ROUTE = "com.markupartist.sthlmtraveling.extra.Route"; /** * Note that this may be null if the Google Play services APK is not available. */ private GoogleMap mMap; private LatLng mFocusedLatLng; private Trip2 mTrip; private JourneyQuery mJourneyQuery; private Route mRoute; public static Intent createIntent(Context context, JourneyQuery query, Route route) { Intent intent = new Intent(context, ViewOnMapActivity.class); intent.putExtra(ViewOnMapActivity.EXTRA_ROUTE, route); intent.putExtra(ViewOnMapActivity.EXTRA_JOURNEY_QUERY, query); return intent; } public static Intent createIntent(Context context, Trip2 trip, JourneyQuery query, Site location) { Intent intent = new Intent(context, ViewOnMapActivity.class); intent.putExtra(ViewOnMapActivity.EXTRA_TRIP, trip); intent.putExtra(ViewOnMapActivity.EXTRA_JOURNEY_QUERY, query); intent.putExtra(ViewOnMapActivity.EXTRA_LOCATION, location); return intent; } @Override protected void onStart() { super.onStart(); } @Override protected void onStop() { super.onStop(); } @Override public void startActivity(Intent intent) { super.startActivity(intent); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } @Override public void onBackPressed() { super.onBackPressed(); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Analytics.getInstance(this).registerScreen("View on map"); setContentView(R.layout.map); ActionBar actionBar = getSupportActionBar(); //actionBar.setBackgroundDrawable(getResources().getDrawableColorInt(R.drawable.ab_bg_black)); actionBar.setHomeButtonEnabled(true); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayShowHomeEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setTitle(R.string.route_details_label); Bundle extras = getIntent().getExtras(); mRoute = extras.getParcelable(EXTRA_ROUTE); mTrip = extras.getParcelable(EXTRA_TRIP); mJourneyQuery = extras.getParcelable(EXTRA_JOURNEY_QUERY); final Site focusedLocation = extras.getParcelable(EXTRA_LOCATION); if (focusedLocation != null) { mFocusedLatLng = new LatLng( focusedLocation.getLocation().getLatitude(), focusedLocation.getLocation().getLongitude()); } SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); updateStartAndEndPointViews(mJourneyQuery); } public void fetchRoute(final Trip2 trip, final JourneyQuery journeyQuery) { new Thread(new Runnable() { @Override public void run() { try { Planner.getInstance().addIntermediateStops( ViewOnMapActivity.this, trip, journeyQuery); } catch (IOException e) { Log.e(TAG, "Could not fetch intermediate stops."); } runOnUiThread(new Runnable() { @Override public void run() { addRoute(trip); } }); } }).start(); } public void addRoute(Trip2 trip) { for (SubTrip subTrip : trip.subTrips) { float[] hsv = new float[3]; Color.colorToHSV(subTrip.transport.getColor(this), hsv); float hueColor = hsv[0]; // One polyline per subtrip, different colors. PolylineOptions options = new PolylineOptions(); LatLng origin = new LatLng( subTrip.origin.getLocation().getLatitude(), subTrip.origin.getLocation().getLongitude()); options.add(origin); mMap.addMarker(new MarkerOptions() .position(origin) .title(getLocationName(subTrip.origin)) .snippet(getRouteDescription(subTrip)) .icon(BitmapDescriptorFactory.defaultMarker(hueColor))); BitmapDescriptor icon = getColoredMarker(subTrip.transport.getColor(this)); for (IntermediateStop stop : subTrip.intermediateStop) { LatLng intermediateStop = new LatLng( stop.location.getLocation().getLatitude(), stop.location.getLocation().getLongitude()); options.add(intermediateStop); Date date = stop.arrivalTime(); if (date == null) { date = stop.departureTime(); } String time = date != null ? DateFormat.getTimeFormat(this).format(date) : ""; mMap.addMarker(new MarkerOptions() .anchor(0.5f, 0.5f) .position(intermediateStop) .title(getLocationName(stop.location)) .snippet(time) .icon(icon)); } LatLng destination = new LatLng( subTrip.destination.getLocation().getLatitude(), subTrip.destination.getLocation().getLongitude()); options.add(destination); mMap.addMarker(new MarkerOptions() .position(destination) .title(getLocationName(subTrip.destination)) .snippet(DateFormat.getTimeFormat(this).format(subTrip.getArrival())) .icon(BitmapDescriptorFactory.defaultMarker(hueColor))); mMap.addPolyline(options .width(ViewHelper.dipsToPix(getResources(), 8)) .color(subTrip.transport.getColor(this))); } } public String getRouteDescription(SubTrip subTrip) { // TODO: Copied from RouteDetailActivity, centralize please! String description; if ("Walk".equals(subTrip.transport.type)) { description = getString(R.string.trip_map_description_walk, DateFormat.getTimeFormat(this).format(subTrip.getDeparture()), getLocationName(subTrip.destination)); } else { description = getString(R.string.trip_map_description_normal, DateFormat.getTimeFormat(this).format(subTrip.getDeparture()), subTrip.transport.name, subTrip.transport.towards, getLocationName(subTrip.destination)); } return description; } private String getLocationName(Site location) { // TODO: Copied from RouteDetailActivity, centralize please! if (location == null) { return "Unknown"; } if (location.isMyLocation()) { return getString(R.string.my_location); } return location.getName(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; } return super.onOptionsItemSelected(item); } @Override public void onLocationPermissionGranted() { //noinspection ResourceType mMap.setMyLocationEnabled(true); } @Override public void onLocationPermissionRationale() { Snackbar.make(findViewById(R.id.map), R.string.permission_location_needed_maps, Snackbar.LENGTH_INDEFINITE) .setAction(R.string.allow, new View.OnClickListener() { @Override public void onClick(View v) { requestLocationPermission(); } }) .show(); } /** * This is where we can add markers or lines, add listeners or move the camera. In this case, we * just add a marker near Africa. * <p> * This should only be called once and when we are sure that {@link #mMap} is not null. */ private void setUpMap() { if (mTrip != null && mJourneyQuery != null) { fetchRoute(mTrip, mJourneyQuery); mMap.moveCamera(CameraUpdateFactory.newCameraPosition( CameraPosition.fromLatLngZoom(mFocusedLatLng, 16) )); } else if (mRoute != null) { showRoute(); } UiSettings settings = mMap.getUiSettings(); settings.setAllGesturesEnabled(true); settings.setMapToolbarEnabled(false); verifyLocationPermission(); } private void showRoute() { // If we have geometry parse and all. List<LatLng> all = new ArrayList<>(); for (Leg leg : mRoute.getLegs()) { if (leg.getGeometry() != null) { List<LatLng> latLgns = PolyUtil.decode(leg.getGeometry()); drawPolyline(latLgns); all.addAll(latLgns); BitmapDescriptor icon = getColoredMarker(ContextCompat.getColor(this, R.color.primary)); for (Step step : leg.getSteps()) { if ("arrive".equals(step.getCode()) || "depart".equals(step.getCode()) || "waypoint".equals(step.getCode())) { mMap.addMarker(new MarkerOptions() .position(latLgns.get(step.getPosition())) .anchor(0.5f, 0.5f) .icon(icon)); } } } } zoomToFit(all); } BitmapDescriptor getColoredMarker(@ColorInt int colorInt) { Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_line_marker); Bitmap bitmapCopy = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig()); Canvas canvas = new Canvas(bitmapCopy); Paint paint = new Paint(); paint.setColorFilter(new PorterDuffColorFilter(colorInt, PorterDuff.Mode.SRC_ATOP)); canvas.drawBitmap(bitmap, 0f, 0f, paint); return BitmapDescriptorFactory.fromBitmap(bitmapCopy); } private void drawPolyline(List<LatLng> latLngs) { Polyline poly = mMap.addPolyline(new PolylineOptions() .zIndex(1000) .addAll(latLngs) .width(ViewHelper.dipsToPix(getResources(), 8)) .color(ContextCompat.getColor(this, R.color.primary)) .geodesic(true)); poly.setZIndex(Float.MAX_VALUE); } private void zoomToFit(List<LatLng> latLngs) { LatLngBounds.Builder builder = new LatLngBounds.Builder(); for (LatLng latLng : latLngs) { builder.include(latLng); } LatLngBounds bounds = builder.build(); // A "random" value for the top padding, fix to fetch from toolbar later on. int height = ViewHelper.getDisplayHeight(this) - ViewHelper.dipsToPix(getResources(), 52); int width = ViewHelper.getDisplayWidth(this); CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, getResources().getDimensionPixelSize(R.dimen.padding_large)); mMap.moveCamera(cu); //mMap.animateCamera(cu); } /** * Update the action bar with start and end points. * @param journeyQuery the journey query */ protected void updateStartAndEndPointViews(final JourneyQuery journeyQuery) { ActionBar ab = getSupportActionBar(); if (journeyQuery.origin.isMyLocation()) { ab.setTitle(StringUtils.getStyledMyLocationString(this)); } else { ab.setTitle(journeyQuery.origin.getName()); } CharSequence via = null; if (journeyQuery.hasVia()) { via = journeyQuery.via.getName(); } if (journeyQuery.destination.isMyLocation()) { if (via != null) { ab.setSubtitle(TextUtils.join(" • ", new CharSequence[]{via, StringUtils.getStyledMyLocationString(this)})); } else { ab.setSubtitle(StringUtils.getStyledMyLocationString(this)); } } else { if (via != null) { ab.setSubtitle(TextUtils.join(" • ", new CharSequence[]{via, journeyQuery.destination.getName()})); } else { ab.setSubtitle(journeyQuery.destination.getName()); } } } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; setUpMap(); } }
sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/ViewOnMapActivity.java
/* * Copyright (C) 2013 Johan Nilsson <http://markupartist.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.markupartist.sthlmtraveling; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.os.Bundle; import android.support.annotation.ColorInt; import android.support.design.widget.Snackbar; import android.support.v4.content.ContextCompat; import android.support.v7.app.ActionBar; import android.text.TextUtils; import android.text.format.DateFormat; import android.util.Log; import android.view.MenuItem; import android.view.View; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.UiSettings; import com.google.android.gms.maps.model.BitmapDescriptor; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.Polyline; import com.google.android.gms.maps.model.PolylineOptions; import com.markupartist.sthlmtraveling.data.models.Leg; import com.markupartist.sthlmtraveling.data.models.Route; import com.markupartist.sthlmtraveling.data.models.Step; import com.markupartist.sthlmtraveling.provider.planner.JourneyQuery; import com.markupartist.sthlmtraveling.provider.planner.Planner; import com.markupartist.sthlmtraveling.provider.planner.Planner.IntermediateStop; import com.markupartist.sthlmtraveling.provider.planner.Planner.SubTrip; import com.markupartist.sthlmtraveling.provider.planner.Planner.Trip2; import com.markupartist.sthlmtraveling.provider.site.Site; import com.markupartist.sthlmtraveling.utils.Analytics; import com.markupartist.sthlmtraveling.utils.PolyUtil; import com.markupartist.sthlmtraveling.utils.StringUtils; import com.markupartist.sthlmtraveling.utils.ViewHelper; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; public class ViewOnMapActivity extends BaseFragmentActivity implements OnMapReadyCallback { private static final String TAG = "ViewOnMapActivity"; public static String EXTRA_LOCATION = "com.markupartist.sthlmtraveling.extra.Location"; public static String EXTRA_JOURNEY_QUERY = "com.markupartist.sthlmtraveling.extra.JourneyQuery"; public static String EXTRA_TRIP = "com.markupartist.sthlmtraveling.extra.Trip"; public static String EXTRA_ROUTE = "com.markupartist.sthlmtraveling.extra.Route"; /** * Note that this may be null if the Google Play services APK is not available. */ private GoogleMap mMap; private LatLng mFocusedLatLng; private Trip2 mTrip; private JourneyQuery mJourneyQuery; private Route mRoute; public static Intent createIntent(Context context, JourneyQuery query, Route route) { Intent intent = new Intent(context, ViewOnMapActivity.class); intent.putExtra(ViewOnMapActivity.EXTRA_ROUTE, route); intent.putExtra(ViewOnMapActivity.EXTRA_JOURNEY_QUERY, query); return intent; } public static Intent createIntent(Context context, Trip2 trip, JourneyQuery query, Site location) { Intent intent = new Intent(context, ViewOnMapActivity.class); intent.putExtra(ViewOnMapActivity.EXTRA_TRIP, trip); intent.putExtra(ViewOnMapActivity.EXTRA_JOURNEY_QUERY, query); intent.putExtra(ViewOnMapActivity.EXTRA_LOCATION, location); return intent; } @Override protected void onStart() { super.onStart(); } @Override protected void onStop() { super.onStop(); } @Override public void startActivity(Intent intent) { super.startActivity(intent); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } @Override public void onBackPressed() { super.onBackPressed(); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Analytics.getInstance(this).registerScreen("View on map"); setContentView(R.layout.map); ActionBar actionBar = getSupportActionBar(); //actionBar.setBackgroundDrawable(getResources().getDrawableColorInt(R.drawable.ab_bg_black)); actionBar.setHomeButtonEnabled(true); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayShowHomeEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setTitle(R.string.route_details_label); Bundle extras = getIntent().getExtras(); mRoute = extras.getParcelable(EXTRA_ROUTE); mTrip = extras.getParcelable(EXTRA_TRIP); mJourneyQuery = extras.getParcelable(EXTRA_JOURNEY_QUERY); final Site focusedLocation = extras.getParcelable(EXTRA_LOCATION); if (focusedLocation != null) { mFocusedLatLng = new LatLng( focusedLocation.getLocation().getLatitude(), focusedLocation.getLocation().getLongitude()); } SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); updateStartAndEndPointViews(mJourneyQuery); } public void fetchRoute(final Trip2 trip, final JourneyQuery journeyQuery) { new Thread(new Runnable() { @Override public void run() { try { Planner.getInstance().addIntermediateStops( ViewOnMapActivity.this, trip, journeyQuery); } catch (IOException e) { Log.e(TAG, e.getMessage()); } runOnUiThread(new Runnable() { @Override public void run() { addRoute(trip); } }); } }).start(); } public void addRoute(Trip2 trip) { for (SubTrip subTrip : trip.subTrips) { float[] hsv = new float[3]; Color.colorToHSV(subTrip.transport.getColor(this), hsv); float hueColor = hsv[0]; // One polyline per subtrip, different colors. PolylineOptions options = new PolylineOptions(); LatLng origin = new LatLng( subTrip.origin.getLocation().getLatitude(), subTrip.origin.getLocation().getLongitude()); options.add(origin); mMap.addMarker(new MarkerOptions() .position(origin) .title(getLocationName(subTrip.origin)) .snippet(getRouteDescription(subTrip)) .icon(BitmapDescriptorFactory.defaultMarker(hueColor))); BitmapDescriptor icon = getColoredMarker(subTrip.transport.getColor(this)); for (IntermediateStop stop : subTrip.intermediateStop) { LatLng intermediateStop = new LatLng( stop.location.getLocation().getLatitude(), stop.location.getLocation().getLongitude()); options.add(intermediateStop); Date date = stop.arrivalTime(); if (date == null) { date = stop.departureTime(); } String time = date != null ? DateFormat.getTimeFormat(this).format(date) : ""; mMap.addMarker(new MarkerOptions() .anchor(0.5f, 0.5f) .position(intermediateStop) .title(getLocationName(stop.location)) .snippet(time) .icon(icon)); } LatLng destination = new LatLng( subTrip.destination.getLocation().getLatitude(), subTrip.destination.getLocation().getLongitude()); options.add(destination); mMap.addMarker(new MarkerOptions() .position(destination) .title(getLocationName(subTrip.destination)) .snippet(DateFormat.getTimeFormat(this).format(subTrip.getArrival())) .icon(BitmapDescriptorFactory.defaultMarker(hueColor))); mMap.addPolyline(options .width(ViewHelper.dipsToPix(getResources(), 8)) .color(subTrip.transport.getColor(this))); } } public String getRouteDescription(SubTrip subTrip) { // TODO: Copied from RouteDetailActivity, centralize please! String description; if ("Walk".equals(subTrip.transport.type)) { description = getString(R.string.trip_map_description_walk, DateFormat.getTimeFormat(this).format(subTrip.getDeparture()), getLocationName(subTrip.destination)); } else { description = getString(R.string.trip_map_description_normal, DateFormat.getTimeFormat(this).format(subTrip.getDeparture()), subTrip.transport.name, subTrip.transport.towards, getLocationName(subTrip.destination)); } return description; } private String getLocationName(Site location) { // TODO: Copied from RouteDetailActivity, centralize please! if (location == null) { return "Unknown"; } if (location.isMyLocation()) { return getString(R.string.my_location); } return location.getName(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; } return super.onOptionsItemSelected(item); } @Override public void onLocationPermissionGranted() { //noinspection ResourceType mMap.setMyLocationEnabled(true); } @Override public void onLocationPermissionRationale() { Snackbar.make(findViewById(R.id.map), R.string.permission_location_needed_maps, Snackbar.LENGTH_INDEFINITE) .setAction(R.string.allow, new View.OnClickListener() { @Override public void onClick(View v) { requestLocationPermission(); } }) .show(); } /** * This is where we can add markers or lines, add listeners or move the camera. In this case, we * just add a marker near Africa. * <p> * This should only be called once and when we are sure that {@link #mMap} is not null. */ private void setUpMap() { if (mTrip != null && mJourneyQuery != null) { fetchRoute(mTrip, mJourneyQuery); mMap.moveCamera(CameraUpdateFactory.newCameraPosition( CameraPosition.fromLatLngZoom(mFocusedLatLng, 16) )); } else if (mRoute != null) { showRoute(); } UiSettings settings = mMap.getUiSettings(); settings.setAllGesturesEnabled(true); settings.setMapToolbarEnabled(false); verifyLocationPermission(); } private void showRoute() { // If we have geometry parse and all. List<LatLng> all = new ArrayList<>(); for (Leg leg : mRoute.getLegs()) { if (leg.getGeometry() != null) { List<LatLng> latLgns = PolyUtil.decode(leg.getGeometry()); drawPolyline(latLgns); all.addAll(latLgns); BitmapDescriptor icon = getColoredMarker(ContextCompat.getColor(this, R.color.primary)); for (Step step : leg.getSteps()) { if ("arrive".equals(step.getCode()) || "depart".equals(step.getCode()) || "waypoint".equals(step.getCode())) { mMap.addMarker(new MarkerOptions() .position(latLgns.get(step.getPosition())) .anchor(0.5f, 0.5f) .icon(icon)); } } } } zoomToFit(all); } BitmapDescriptor getColoredMarker(@ColorInt int colorInt) { Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_line_marker); Bitmap bitmapCopy = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig()); Canvas canvas = new Canvas(bitmapCopy); Paint paint = new Paint(); paint.setColorFilter(new PorterDuffColorFilter(colorInt, PorterDuff.Mode.SRC_ATOP)); canvas.drawBitmap(bitmap, 0f, 0f, paint); return BitmapDescriptorFactory.fromBitmap(bitmapCopy); } private void drawPolyline(List<LatLng> latLngs) { Polyline poly = mMap.addPolyline(new PolylineOptions() .zIndex(1000) .addAll(latLngs) .width(ViewHelper.dipsToPix(getResources(), 8)) .color(ContextCompat.getColor(this, R.color.primary)) .geodesic(true)); poly.setZIndex(Float.MAX_VALUE); } private void zoomToFit(List<LatLng> latLngs) { LatLngBounds.Builder builder = new LatLngBounds.Builder(); for (LatLng latLng : latLngs) { builder.include(latLng); } LatLngBounds bounds = builder.build(); // A "random" value for the top padding, fix to fetch from toolbar later on. int height = ViewHelper.getDisplayHeight(this) - ViewHelper.dipsToPix(getResources(), 52); int width = ViewHelper.getDisplayWidth(this); CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, getResources().getDimensionPixelSize(R.dimen.padding_large)); mMap.moveCamera(cu); //mMap.animateCamera(cu); } /** * Update the action bar with start and end points. * @param journeyQuery the journey query */ protected void updateStartAndEndPointViews(final JourneyQuery journeyQuery) { ActionBar ab = getSupportActionBar(); if (journeyQuery.origin.isMyLocation()) { ab.setTitle(StringUtils.getStyledMyLocationString(this)); } else { ab.setTitle(journeyQuery.origin.getName()); } CharSequence via = null; if (journeyQuery.hasVia()) { via = journeyQuery.via.getName(); } if (journeyQuery.destination.isMyLocation()) { if (via != null) { ab.setSubtitle(TextUtils.join(" • ", new CharSequence[]{via, StringUtils.getStyledMyLocationString(this)})); } else { ab.setSubtitle(StringUtils.getStyledMyLocationString(this)); } } else { if (via != null) { ab.setSubtitle(TextUtils.join(" • ", new CharSequence[]{via, journeyQuery.destination.getName()})); } else { ab.setSubtitle(journeyQuery.destination.getName()); } } } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; setUpMap(); } }
Change error logging
sthlmtraveling/src/main/java/com/markupartist/sthlmtraveling/ViewOnMapActivity.java
Change error logging
<ide><path>thlmtraveling/src/main/java/com/markupartist/sthlmtraveling/ViewOnMapActivity.java <ide> Planner.getInstance().addIntermediateStops( <ide> ViewOnMapActivity.this, trip, journeyQuery); <ide> } catch (IOException e) { <del> Log.e(TAG, e.getMessage()); <add> Log.e(TAG, "Could not fetch intermediate stops."); <ide> } <ide> runOnUiThread(new Runnable() { <ide> @Override
Java
apache-2.0
c39a453fc0b9b8acf4c8ef43dc643f06d845d893
0
vase4kin/TeamCityApp,vase4kin/TeamCityApp,vase4kin/TeamCityApp
/* * Copyright 2016 Andrey Tolpeev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.vase4kin.teamcityapp.runbuild.view; import android.content.Intent; import android.support.test.InstrumentationRegistry; import android.support.test.espresso.matcher.RootMatchers; import android.support.test.runner.AndroidJUnit4; import com.github.vase4kin.teamcityapp.R; import com.github.vase4kin.teamcityapp.TeamCityApplication; import com.github.vase4kin.teamcityapp.agents.api.Agent; import com.github.vase4kin.teamcityapp.agents.api.Agents; import com.github.vase4kin.teamcityapp.api.TeamCityService; import com.github.vase4kin.teamcityapp.buildlist.api.Build; import com.github.vase4kin.teamcityapp.dagger.components.AppComponent; import com.github.vase4kin.teamcityapp.dagger.components.RestApiComponent; import com.github.vase4kin.teamcityapp.dagger.modules.AppModule; import com.github.vase4kin.teamcityapp.dagger.modules.FakeTeamCityServiceImpl; import com.github.vase4kin.teamcityapp.dagger.modules.Mocks; import com.github.vase4kin.teamcityapp.dagger.modules.RestApiModule; import com.github.vase4kin.teamcityapp.helper.CustomActivityTestRule; import com.github.vase4kin.teamcityapp.properties.api.Properties; import com.github.vase4kin.teamcityapp.runbuild.api.Branch; import com.github.vase4kin.teamcityapp.runbuild.api.Branches; import com.github.vase4kin.teamcityapp.runbuild.interactor.RunBuildInteractor; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.Spy; import java.util.ArrayList; import java.util.List; import it.cosenonjaviste.daggermock.DaggerMockRule; import okhttp3.ResponseBody; import retrofit2.Response; import retrofit2.adapter.rxjava.HttpException; import rx.Observable; import static android.support.test.espresso.Espresso.onData; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard; import static android.support.test.espresso.action.ViewActions.swipeUp; import static android.support.test.espresso.action.ViewActions.typeText; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isChecked; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.isEnabled; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static com.github.vase4kin.teamcityapp.runbuild.interactor.RunBuildInteractor.CODE_FORBIDDEN; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.core.AllOf.allOf; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Tests for {@link RunBuildActivity} */ @RunWith(AndroidJUnit4.class) public class RunBuildActivityTest { private static final String PARAMETER_NAME = "version"; private static final String PARAMETER_VALUE = "1.3.2"; @Rule public DaggerMockRule<RestApiComponent> mDaggerRule = new DaggerMockRule<>(RestApiComponent.class, new RestApiModule(Mocks.URL)) .addComponentDependency(AppComponent.class, new AppModule((TeamCityApplication) InstrumentationRegistry.getInstrumentation().getTargetContext().getApplicationContext())) .set(new DaggerMockRule.ComponentSetter<RestApiComponent>() { @Override public void setComponent(RestApiComponent restApiComponent) { TeamCityApplication app = (TeamCityApplication) InstrumentationRegistry.getInstrumentation().getTargetContext().getApplicationContext(); app.setRestApiInjector(restApiComponent); } }); @Rule public CustomActivityTestRule<RunBuildActivity> mActivityRule = new CustomActivityTestRule<>(RunBuildActivity.class); @Captor private ArgumentCaptor<Build> mBuildCaptor; @Mock ResponseBody mResponseBody; @Spy private TeamCityService mTeamCityService = new FakeTeamCityServiceImpl(); @Before public void setUp() { TeamCityApplication app = (TeamCityApplication) InstrumentationRegistry.getInstrumentation().getTargetContext().getApplicationContext(); app.getRestApiInjector().sharedUserStorage().clearAll(); app.getRestApiInjector().sharedUserStorage().saveGuestUserAccountAndSetItAsActive(Mocks.URL); } @Test public void testUserCanSeeSingleBranchChosenIfBuildTypeHasSingleBranchAvailable() throws Exception { // Prepare intent Intent intent = new Intent(); intent.putExtra(RunBuildInteractor.EXTRA_BUILD_TYPE_ID, "href"); // Starting the activity mActivityRule.launchActivity(intent); // Check the branches autocomplete field has branch as master and it's disabled onView(withId(R.id.autocomplete_branches)).check(matches(allOf(withText("master"), not(isEnabled())))); } @Test public void testUserCanSeeMultipleBranchesIfBuildTypeHasMultipleAvailable() throws Exception { // Prepare mocks List<Branch> branches = new ArrayList<>(); branches.add(new Branch("dev1")); branches.add(new Branch("dev2")); when(mTeamCityService.listBranches(anyString())).thenReturn(Observable.just(new Branches(branches))); // Prepare intent Intent intent = new Intent(); intent.putExtra(RunBuildInteractor.EXTRA_BUILD_TYPE_ID, "href"); // Starting the activity mActivityRule.launchActivity(intent); // Choose branch from autocomplete and verify it is appeared onView(withId(R.id.autocomplete_branches)) .perform(typeText("dev")); onData(allOf(is(instanceOf(String.class)), is("dev1"))) .inRoot(RootMatchers.withDecorView(not(is(mActivityRule.getActivity().getWindow().getDecorView())))) .perform(click()); onView(withText("dev1")).perform(click()); onView(withId(R.id.autocomplete_branches)).check(matches(allOf(withText("dev1"), isEnabled()))); } @Test public void testUserCanStartTheBuild() throws Exception { // Prepare intent Intent intent = new Intent(); intent.putExtra(RunBuildInteractor.EXTRA_BUILD_TYPE_ID, "href"); // Starting the activity mActivityRule.launchActivity(intent); // Starting the build onView(withId(R.id.fab_queue_build)).perform(click()); // Checking triggered build verify(mTeamCityService).queueBuild(mBuildCaptor.capture()); Build capturedBuild = mBuildCaptor.getValue(); assertThat(capturedBuild.getBranchName(), is("master")); assertThat(capturedBuild.getAgent(), is(nullValue())); assertThat(capturedBuild.isPersonal(), is(equalTo(false))); assertThat(capturedBuild.isQueueAtTop(), is(equalTo(false))); assertThat(capturedBuild.isCleanSources(), is(equalTo(true))); // Checking activity is finishing assertThat(mActivityRule.getActivity().isFinishing(), is(true)); } @Test public void testUserCanSeeErrorSnackBarIfServerReturnsAnError() throws Exception { // Prepare mocks when(mTeamCityService.queueBuild(any(Build.class))).thenReturn(Observable.<Build>error(new RuntimeException())); // Prepare intent Intent intent = new Intent(); intent.putExtra(RunBuildInteractor.EXTRA_BUILD_TYPE_ID, "href"); // Starting the activity mActivityRule.launchActivity(intent); // Starting the build onView(withId(R.id.fab_queue_build)).perform(click()); // Checking the error snackbar text onView(withText(R.string.error_base_error)).check(matches(isDisplayed())); } @Test public void testUserCanSeeErrorForbiddenSnackBarIfServerReturnsAnError() throws Exception { // Prepare mocks HttpException httpException = new HttpException(Response.<Build>error(CODE_FORBIDDEN, mResponseBody)); when(mTeamCityService.queueBuild(any(Build.class))).thenReturn(Observable.<Build>error(httpException)); // Prepare intent Intent intent = new Intent(); intent.putExtra(RunBuildInteractor.EXTRA_BUILD_TYPE_ID, "href"); // Starting the activity mActivityRule.launchActivity(intent); // Starting the build onView(withId(R.id.fab_queue_build)).perform(click()); // Checking the error snackbar text onView(withText(R.string.error_forbidden_error)).check(matches(isDisplayed())); } @Test public void testUserCanSeeChooseAgentIfAgentsAvailable() throws Exception { // Prepare mocks List<Agent> agents = new ArrayList<>(); Agent agent = new Agent("agent 1"); agents.add(agent); when(mTeamCityService.listAgents(false, null)).thenReturn(Observable.just(new Agents(1, agents))); // Prepare intent Intent intent = new Intent(); intent.putExtra(RunBuildInteractor.EXTRA_BUILD_TYPE_ID, "href"); // Starting the activity mActivityRule.launchActivity(intent); // Choose agent onView(withId(R.id.chooser_agent)).perform(click()); onView(withText("agent 1")).perform(click()); // Starting the build onView(withId(R.id.fab_queue_build)).perform(click()); // Checking that build was triggered with agent verify(mTeamCityService).queueBuild(mBuildCaptor.capture()); Build capturedBuild = mBuildCaptor.getValue(); assertThat(capturedBuild.getAgent(), is(agent)); // Checking activity is finishing assertThat(mActivityRule.getActivity().isFinishing(), is(true)); } @Test public void testUserCanSeeChooseDefaultAgentIfAgentsAvailable() throws Exception { // Prepare intent Intent intent = new Intent(); intent.putExtra(RunBuildInteractor.EXTRA_BUILD_TYPE_ID, "href"); // Starting the activity mActivityRule.launchActivity(intent); // Check hint for selected agent onView(withId(R.id.selected_agent)).check(matches(withText(R.string.hint_default_filter_agent))); } @Test public void testUserCanSeeNoAgentsAvailableTextIfNoAgentsAvailable() throws Exception { // Prepare mocks when(mTeamCityService.listAgents(false, null)).thenReturn(Observable.<Agents>error(new RuntimeException())); // Prepare intent Intent intent = new Intent(); intent.putExtra(RunBuildInteractor.EXTRA_BUILD_TYPE_ID, "href"); // Starting the activity mActivityRule.launchActivity(intent); // Check no agents onView(withId(R.id.text_no_agents_available)).check(matches(isDisplayed())); } @Test public void testUserCleanAllFilesCheckBoxIsCheckedByDefault() throws Exception { // Prepare intent Intent intent = new Intent(); intent.putExtra(RunBuildInteractor.EXTRA_BUILD_TYPE_ID, "href"); // Starting the activity mActivityRule.launchActivity(intent); // Check clean all files is checked by default onView(withId(R.id.switcher_clean_all_files)).check(matches(isChecked())); } @Test public void testUserCanStartTheBuildWithDefaultParams() throws Exception { // Prepare intent Intent intent = new Intent(); intent.putExtra(RunBuildInteractor.EXTRA_BUILD_TYPE_ID, "href"); // Starting the activity mActivityRule.launchActivity(intent); // Check personal onView(withId(R.id.switcher_is_personal)).perform(click()); // Check queue to the top onView(withId(R.id.switcher_queueAtTop)).perform(click()); // Check clean all files onView(withId(R.id.switcher_clean_all_files)).perform(click()); // Starting the build onView(withId(R.id.fab_queue_build)).perform(click()); // Checking triggered build verify(mTeamCityService).queueBuild(mBuildCaptor.capture()); Build capturedBuild = mBuildCaptor.getValue(); assertThat(capturedBuild.getBranchName(), is("master")); assertThat(capturedBuild.getAgent(), is(nullValue())); assertThat(capturedBuild.isPersonal(), is(equalTo(true))); assertThat(capturedBuild.isQueueAtTop(), is(equalTo(true))); assertThat(capturedBuild.isCleanSources(), is(equalTo(false))); // Checking activity is finishing assertThat(mActivityRule.getActivity().isFinishing(), is(true)); } @Test public void testUserCanStartTheBuildWithCustomParams() throws Exception { // Prepare intent Intent intent = new Intent(); intent.putExtra(RunBuildInteractor.EXTRA_BUILD_TYPE_ID, "href"); // Starting the activity mActivityRule.launchActivity(intent); // Scroll to onView(withId(android.R.id.content)).perform(swipeUp()); // Add new param onView(withId(R.id.button_add_parameter)).perform(click()); // Fill params onView(withId(R.id.parameter_name)).perform(typeText(PARAMETER_NAME)); onView(withId(R.id.parameter_value)).perform(typeText(PARAMETER_VALUE), closeSoftKeyboard()); // Add param onView(withText(R.string.text_add_parameter_button)).perform(click()); // Scroll to onView(withId(android.R.id.content)).perform(swipeUp()); // Check params on view onView(allOf(withId(R.id.parameter_name), isDisplayed())).check(matches(withText(PARAMETER_NAME))); onView(allOf(withId(R.id.parameter_value), isDisplayed())).check(matches(withText(PARAMETER_VALUE))); // Starting the build onView(withId(R.id.fab_queue_build)).perform(click()); // Checking triggered build verify(mTeamCityService).queueBuild(mBuildCaptor.capture()); Build capturedBuild = mBuildCaptor.getValue(); assertThat(capturedBuild.getProperties().getObjects().size(), is(equalTo(1))); Properties.Property capturedProperty = capturedBuild.getProperties().getObjects().get(0); assertThat(capturedProperty.getName(), is(equalTo(PARAMETER_NAME))); assertThat(capturedProperty.getValue(), is(equalTo(PARAMETER_VALUE))); // Checking activity is finishing assertThat(mActivityRule.getActivity().isFinishing(), is(true)); } @Test public void testUserCanStartTheBuildWithClearAllCustomParams() throws Exception { // Prepare intent Intent intent = new Intent(); intent.putExtra(RunBuildInteractor.EXTRA_BUILD_TYPE_ID, "href"); // Starting the activity mActivityRule.launchActivity(intent); // Scroll to onView(withId(android.R.id.content)).perform(swipeUp()); // Add new param onView(withId(R.id.button_add_parameter)).perform(click()); // Fill params onView(withId(R.id.parameter_name)).perform(typeText(PARAMETER_NAME)); onView(withId(R.id.parameter_value)).perform(typeText(PARAMETER_VALUE), closeSoftKeyboard()); // Add param onView(withText(R.string.text_add_parameter_button)).perform(click()); // Scroll to onView(withId(android.R.id.content)).perform(swipeUp()); // Check params on view onView(allOf(withId(R.id.parameter_name), isDisplayed())).check(matches(withText(PARAMETER_NAME))); onView(allOf(withId(R.id.parameter_value), isDisplayed())).check(matches(withText(PARAMETER_VALUE))); // Clear all params onView(withId(R.id.button_clear_parameters)).perform(click()); // Starting the build onView(withId(R.id.fab_queue_build)).perform(click()); // Checking triggered build verify(mTeamCityService).queueBuild(mBuildCaptor.capture()); Build capturedBuild = mBuildCaptor.getValue(); assertThat(capturedBuild.getProperties(), is(nullValue())); // Checking activity is finishing assertThat(mActivityRule.getActivity().isFinishing(), is(true)); } }
app/src/androidTest/java/com/github/vase4kin/teamcityapp/runbuild/view/RunBuildActivityTest.java
/* * Copyright 2016 Andrey Tolpeev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.vase4kin.teamcityapp.runbuild.view; import android.content.Intent; import android.support.test.InstrumentationRegistry; import android.support.test.espresso.matcher.RootMatchers; import android.support.test.runner.AndroidJUnit4; import com.github.vase4kin.teamcityapp.R; import com.github.vase4kin.teamcityapp.TeamCityApplication; import com.github.vase4kin.teamcityapp.agents.api.Agent; import com.github.vase4kin.teamcityapp.agents.api.Agents; import com.github.vase4kin.teamcityapp.api.TeamCityService; import com.github.vase4kin.teamcityapp.buildlist.api.Build; import com.github.vase4kin.teamcityapp.dagger.components.AppComponent; import com.github.vase4kin.teamcityapp.dagger.components.RestApiComponent; import com.github.vase4kin.teamcityapp.dagger.modules.AppModule; import com.github.vase4kin.teamcityapp.dagger.modules.FakeTeamCityServiceImpl; import com.github.vase4kin.teamcityapp.dagger.modules.Mocks; import com.github.vase4kin.teamcityapp.dagger.modules.RestApiModule; import com.github.vase4kin.teamcityapp.helper.CustomActivityTestRule; import com.github.vase4kin.teamcityapp.runbuild.api.Branch; import com.github.vase4kin.teamcityapp.runbuild.api.Branches; import com.github.vase4kin.teamcityapp.runbuild.interactor.RunBuildInteractor; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.Spy; import java.util.ArrayList; import java.util.List; import it.cosenonjaviste.daggermock.DaggerMockRule; import okhttp3.ResponseBody; import retrofit2.Response; import retrofit2.adapter.rxjava.HttpException; import rx.Observable; import static android.support.test.espresso.Espresso.onData; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.typeText; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isChecked; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.isEnabled; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static com.github.vase4kin.teamcityapp.runbuild.interactor.RunBuildInteractor.CODE_FORBIDDEN; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.core.AllOf.allOf; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Tests for {@link RunBuildActivity} */ @RunWith(AndroidJUnit4.class) public class RunBuildActivityTest { @Rule public DaggerMockRule<RestApiComponent> mDaggerRule = new DaggerMockRule<>(RestApiComponent.class, new RestApiModule(Mocks.URL)) .addComponentDependency(AppComponent.class, new AppModule((TeamCityApplication) InstrumentationRegistry.getInstrumentation().getTargetContext().getApplicationContext())) .set(new DaggerMockRule.ComponentSetter<RestApiComponent>() { @Override public void setComponent(RestApiComponent restApiComponent) { TeamCityApplication app = (TeamCityApplication) InstrumentationRegistry.getInstrumentation().getTargetContext().getApplicationContext(); app.setRestApiInjector(restApiComponent); } }); @Rule public CustomActivityTestRule<RunBuildActivity> mActivityRule = new CustomActivityTestRule<>(RunBuildActivity.class); @Captor private ArgumentCaptor<Build> mBuildCaptor; @Mock ResponseBody mResponseBody; @Spy private TeamCityService mTeamCityService = new FakeTeamCityServiceImpl(); @Before public void setUp() { TeamCityApplication app = (TeamCityApplication) InstrumentationRegistry.getInstrumentation().getTargetContext().getApplicationContext(); app.getRestApiInjector().sharedUserStorage().clearAll(); app.getRestApiInjector().sharedUserStorage().saveGuestUserAccountAndSetItAsActive(Mocks.URL); } @Test public void testUserCanSeeSingleBranchChosenIfBuildTypeHasSingleBranchAvailable() throws Exception { // Prepare intent Intent intent = new Intent(); intent.putExtra(RunBuildInteractor.EXTRA_BUILD_TYPE_ID, "href"); // Starting the activity mActivityRule.launchActivity(intent); // Check the branches autocomplete field has branch as master and it's disabled onView(withId(R.id.autocomplete_branches)).check(matches(allOf(withText("master"), not(isEnabled())))); } @Test public void testUserCanSeeMultipleBranchesIfBuildTypeHasMultipleAvailable() throws Exception { // Prepare mocks List<Branch> branches = new ArrayList<>(); branches.add(new Branch("dev1")); branches.add(new Branch("dev2")); when(mTeamCityService.listBranches(anyString())).thenReturn(Observable.just(new Branches(branches))); // Prepare intent Intent intent = new Intent(); intent.putExtra(RunBuildInteractor.EXTRA_BUILD_TYPE_ID, "href"); // Starting the activity mActivityRule.launchActivity(intent); // Choose branch from autocomplete and verify it is appeared onView(withId(R.id.autocomplete_branches)) .perform(typeText("dev")); onData(allOf(is(instanceOf(String.class)), is("dev1"))) .inRoot(RootMatchers.withDecorView(not(is(mActivityRule.getActivity().getWindow().getDecorView())))) .perform(click()); onView(withText("dev1")).perform(click()); onView(withId(R.id.autocomplete_branches)).check(matches(allOf(withText("dev1"), isEnabled()))); } @Test public void testUserCanStartTheBuild() throws Exception { // Prepare intent Intent intent = new Intent(); intent.putExtra(RunBuildInteractor.EXTRA_BUILD_TYPE_ID, "href"); // Starting the activity mActivityRule.launchActivity(intent); // Starting the build onView(withId(R.id.fab_queue_build)).perform(click()); // Checking triggered build verify(mTeamCityService).queueBuild(mBuildCaptor.capture()); Build capturedBuild = mBuildCaptor.getValue(); assertThat(capturedBuild.getBranchName(), is("master")); assertThat(capturedBuild.getAgent(), is(nullValue())); assertThat(capturedBuild.isPersonal(), is(equalTo(false))); assertThat(capturedBuild.isQueueAtTop(), is(equalTo(false))); assertThat(capturedBuild.isCleanSources(), is(equalTo(true))); // Checking activity is finishing assertThat(mActivityRule.getActivity().isFinishing(), is(true)); } @Test public void testUserCanSeeErrorSnackBarIfServerReturnsAnError() throws Exception { // Prepare mocks when(mTeamCityService.queueBuild(any(Build.class))).thenReturn(Observable.<Build>error(new RuntimeException())); // Prepare intent Intent intent = new Intent(); intent.putExtra(RunBuildInteractor.EXTRA_BUILD_TYPE_ID, "href"); // Starting the activity mActivityRule.launchActivity(intent); // Starting the build onView(withId(R.id.fab_queue_build)).perform(click()); // Checking the error snackbar text onView(withText(R.string.error_base_error)).check(matches(isDisplayed())); } @Test public void testUserCanSeeErrorForbiddenSnackBarIfServerReturnsAnError() throws Exception { // Prepare mocks HttpException httpException = new HttpException(Response.<Build>error(CODE_FORBIDDEN, mResponseBody)); when(mTeamCityService.queueBuild(any(Build.class))).thenReturn(Observable.<Build>error(httpException)); // Prepare intent Intent intent = new Intent(); intent.putExtra(RunBuildInteractor.EXTRA_BUILD_TYPE_ID, "href"); // Starting the activity mActivityRule.launchActivity(intent); // Starting the build onView(withId(R.id.fab_queue_build)).perform(click()); // Checking the error snackbar text onView(withText(R.string.error_forbidden_error)).check(matches(isDisplayed())); } @Test public void testUserCanSeeChooseAgentIfAgentsAvailable() throws Exception { // Prepare mocks List<Agent> agents = new ArrayList<>(); Agent agent = new Agent("agent 1"); agents.add(agent); when(mTeamCityService.listAgents(false, null)).thenReturn(Observable.just(new Agents(1, agents))); // Prepare intent Intent intent = new Intent(); intent.putExtra(RunBuildInteractor.EXTRA_BUILD_TYPE_ID, "href"); // Starting the activity mActivityRule.launchActivity(intent); // Choose agent onView(withId(R.id.chooser_agent)).perform(click()); onView(withText("agent 1")).perform(click()); // Starting the build onView(withId(R.id.fab_queue_build)).perform(click()); // Checking that build was triggered with agent verify(mTeamCityService).queueBuild(mBuildCaptor.capture()); Build capturedBuild = mBuildCaptor.getValue(); assertThat(capturedBuild.getAgent(), is(agent)); // Checking activity is finishing assertThat(mActivityRule.getActivity().isFinishing(), is(true)); } @Test public void testUserCanSeeChooseDefaultAgentIfAgentsAvailable() throws Exception { // Prepare intent Intent intent = new Intent(); intent.putExtra(RunBuildInteractor.EXTRA_BUILD_TYPE_ID, "href"); // Starting the activity mActivityRule.launchActivity(intent); // Check hint for selected agent onView(withId(R.id.selected_agent)).check(matches(withText(R.string.hint_default_filter_agent))); } @Test public void testUserCanSeeNoAgentsAvailableTextIfNoAgentsAvailable() throws Exception { // Prepare mocks when(mTeamCityService.listAgents(false, null)).thenReturn(Observable.<Agents>error(new RuntimeException())); // Prepare intent Intent intent = new Intent(); intent.putExtra(RunBuildInteractor.EXTRA_BUILD_TYPE_ID, "href"); // Starting the activity mActivityRule.launchActivity(intent); // Check no agents onView(withId(R.id.text_no_agents_available)).check(matches(isDisplayed())); } @Test public void testUserCleanAllFilesCheckBoxIsCheckedByDefault() throws Exception { // Prepare intent Intent intent = new Intent(); intent.putExtra(RunBuildInteractor.EXTRA_BUILD_TYPE_ID, "href"); // Starting the activity mActivityRule.launchActivity(intent); // Check clean all files is checked by default onView(withId(R.id.switcher_clean_all_files)).check(matches(isChecked())); } @Test public void testUserCanStartTheBuildWithDefaultParams() throws Exception { // Prepare intent Intent intent = new Intent(); intent.putExtra(RunBuildInteractor.EXTRA_BUILD_TYPE_ID, "href"); // Starting the activity mActivityRule.launchActivity(intent); // Check personal onView(withId(R.id.switcher_is_personal)).perform(click()); // Check queue to the top onView(withId(R.id.switcher_queueAtTop)).perform(click()); // Check clean all files onView(withId(R.id.switcher_clean_all_files)).perform(click()); // Starting the build onView(withId(R.id.fab_queue_build)).perform(click()); // Checking triggered build verify(mTeamCityService).queueBuild(mBuildCaptor.capture()); Build capturedBuild = mBuildCaptor.getValue(); assertThat(capturedBuild.getBranchName(), is("master")); assertThat(capturedBuild.getAgent(), is(nullValue())); assertThat(capturedBuild.isPersonal(), is(equalTo(true))); assertThat(capturedBuild.isQueueAtTop(), is(equalTo(true))); assertThat(capturedBuild.isCleanSources(), is(equalTo(false))); // Checking activity is finishing assertThat(mActivityRule.getActivity().isFinishing(), is(true)); } }
Add UI tests on run build with custom params
app/src/androidTest/java/com/github/vase4kin/teamcityapp/runbuild/view/RunBuildActivityTest.java
Add UI tests on run build with custom params
<ide><path>pp/src/androidTest/java/com/github/vase4kin/teamcityapp/runbuild/view/RunBuildActivityTest.java <ide> import com.github.vase4kin.teamcityapp.dagger.modules.Mocks; <ide> import com.github.vase4kin.teamcityapp.dagger.modules.RestApiModule; <ide> import com.github.vase4kin.teamcityapp.helper.CustomActivityTestRule; <add>import com.github.vase4kin.teamcityapp.properties.api.Properties; <ide> import com.github.vase4kin.teamcityapp.runbuild.api.Branch; <ide> import com.github.vase4kin.teamcityapp.runbuild.api.Branches; <ide> import com.github.vase4kin.teamcityapp.runbuild.interactor.RunBuildInteractor; <ide> import static android.support.test.espresso.Espresso.onData; <ide> import static android.support.test.espresso.Espresso.onView; <ide> import static android.support.test.espresso.action.ViewActions.click; <add>import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard; <add>import static android.support.test.espresso.action.ViewActions.swipeUp; <ide> import static android.support.test.espresso.action.ViewActions.typeText; <ide> import static android.support.test.espresso.assertion.ViewAssertions.matches; <ide> import static android.support.test.espresso.matcher.ViewMatchers.isChecked; <ide> @RunWith(AndroidJUnit4.class) <ide> public class RunBuildActivityTest { <ide> <add> private static final String PARAMETER_NAME = "version"; <add> private static final String PARAMETER_VALUE = "1.3.2"; <add> <ide> @Rule <ide> public DaggerMockRule<RestApiComponent> mDaggerRule = new DaggerMockRule<>(RestApiComponent.class, new RestApiModule(Mocks.URL)) <ide> .addComponentDependency(AppComponent.class, new AppModule((TeamCityApplication) InstrumentationRegistry.getInstrumentation().getTargetContext().getApplicationContext())) <ide> // Checking activity is finishing <ide> assertThat(mActivityRule.getActivity().isFinishing(), is(true)); <ide> } <add> <add> @Test <add> public void testUserCanStartTheBuildWithCustomParams() throws Exception { <add> // Prepare intent <add> Intent intent = new Intent(); <add> intent.putExtra(RunBuildInteractor.EXTRA_BUILD_TYPE_ID, "href"); <add> // Starting the activity <add> mActivityRule.launchActivity(intent); <add> // Scroll to <add> onView(withId(android.R.id.content)).perform(swipeUp()); <add> // Add new param <add> onView(withId(R.id.button_add_parameter)).perform(click()); <add> // Fill params <add> onView(withId(R.id.parameter_name)).perform(typeText(PARAMETER_NAME)); <add> onView(withId(R.id.parameter_value)).perform(typeText(PARAMETER_VALUE), closeSoftKeyboard()); <add> // Add param <add> onView(withText(R.string.text_add_parameter_button)).perform(click()); <add> // Scroll to <add> onView(withId(android.R.id.content)).perform(swipeUp()); <add> // Check params on view <add> onView(allOf(withId(R.id.parameter_name), isDisplayed())).check(matches(withText(PARAMETER_NAME))); <add> onView(allOf(withId(R.id.parameter_value), isDisplayed())).check(matches(withText(PARAMETER_VALUE))); <add> // Starting the build <add> onView(withId(R.id.fab_queue_build)).perform(click()); <add> // Checking triggered build <add> verify(mTeamCityService).queueBuild(mBuildCaptor.capture()); <add> Build capturedBuild = mBuildCaptor.getValue(); <add> assertThat(capturedBuild.getProperties().getObjects().size(), is(equalTo(1))); <add> Properties.Property capturedProperty = capturedBuild.getProperties().getObjects().get(0); <add> assertThat(capturedProperty.getName(), is(equalTo(PARAMETER_NAME))); <add> assertThat(capturedProperty.getValue(), is(equalTo(PARAMETER_VALUE))); <add> // Checking activity is finishing <add> assertThat(mActivityRule.getActivity().isFinishing(), is(true)); <add> } <add> <add> @Test <add> public void testUserCanStartTheBuildWithClearAllCustomParams() throws Exception { <add> // Prepare intent <add> Intent intent = new Intent(); <add> intent.putExtra(RunBuildInteractor.EXTRA_BUILD_TYPE_ID, "href"); <add> // Starting the activity <add> mActivityRule.launchActivity(intent); <add> // Scroll to <add> onView(withId(android.R.id.content)).perform(swipeUp()); <add> // Add new param <add> onView(withId(R.id.button_add_parameter)).perform(click()); <add> // Fill params <add> onView(withId(R.id.parameter_name)).perform(typeText(PARAMETER_NAME)); <add> onView(withId(R.id.parameter_value)).perform(typeText(PARAMETER_VALUE), closeSoftKeyboard()); <add> // Add param <add> onView(withText(R.string.text_add_parameter_button)).perform(click()); <add> // Scroll to <add> onView(withId(android.R.id.content)).perform(swipeUp()); <add> // Check params on view <add> onView(allOf(withId(R.id.parameter_name), isDisplayed())).check(matches(withText(PARAMETER_NAME))); <add> onView(allOf(withId(R.id.parameter_value), isDisplayed())).check(matches(withText(PARAMETER_VALUE))); <add> // Clear all params <add> onView(withId(R.id.button_clear_parameters)).perform(click()); <add> // Starting the build <add> onView(withId(R.id.fab_queue_build)).perform(click()); <add> // Checking triggered build <add> verify(mTeamCityService).queueBuild(mBuildCaptor.capture()); <add> Build capturedBuild = mBuildCaptor.getValue(); <add> assertThat(capturedBuild.getProperties(), is(nullValue())); <add> // Checking activity is finishing <add> assertThat(mActivityRule.getActivity().isFinishing(), is(true)); <add> } <ide> }
Java
bsd-3-clause
2b358ea030c00545a7142e0cfd69f53100711237
0
brackeen/Scared,brackeen/Scared,FirstRound/InnoGame,FirstRound/InnoGame
package com.brackeen.scared; import com.brackeen.app.App; import com.brackeen.app.BitmapFont; import com.brackeen.app.view.Button; import com.brackeen.app.view.Label; import com.brackeen.app.view.Scene; import com.brackeen.app.view.View; import java.awt.Color; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.ArrayList; import java.util.List; public class ConsoleScene extends Scene { private static final int CURSOR_BLINK_TICKS = 20; private static final int BORDER_SIZE = 10; private static final int MAX_COMMAND_HISTORY = 200; private static final String PROMPT = "] "; private static List<String> commandHistory = new ArrayList<>(); private final GameScene gameScene; private Button backButton; private Button helpButton; private View textView; private String newCommandLine = ""; private int commandHistoryIndex; private int ticks = 0; private boolean cursorOn = true; public ConsoleScene(GameScene gameScene) { this.gameScene = gameScene; } @Override public void onLoad() { App app = App.getApp(); commandHistoryIndex = commandHistory.size(); final BitmapFont messageFont = new BitmapFont(app.getImage("/ui/message_font.png"), 11, ' '); setBackgroundColor(new Color(12, 12, 12)); backButton = new Button(app.getImage("/ui/back_button_normal.png")); backButton.setHoverImage(app.getImage("/ui/back_button_hover.png")); backButton.setPressedImage(app.getImage("/ui/back_button_pressed.png")); backButton.setAnchor(1, 1); backButton.setButtonListener(new Button.Listener() { public void buttonClicked(Button button) { App.getApp().popScene(); } }); addSubview(backButton); helpButton = new Button(app.getImage("/ui/help_button_normal.png")); helpButton.setHoverImage(app.getImage("/ui/help_button_hover.png")); helpButton.setPressedImage(app.getImage("/ui/help_button_pressed.png")); helpButton.setAnchor(0, 1); helpButton.setButtonListener(new Button.Listener() { public void buttonClicked(Button button) { App.getApp().pushScene(new HelpScene()); } }); addSubview(helpButton); textView = new View(); textView.setLocation(BORDER_SIZE, BORDER_SIZE); addSubview(textView); onResize(); int maxLines = (int)textView.getHeight() / messageFont.getHeight(); for (int i = 0; i < maxLines; i++) { Label label = new Label(messageFont, ""); label.setLocation(0, i * messageFont.getHeight()); textView.addSubview(label); } setKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent ke) { char ch = ke.getKeyChar(); if (messageFont.canDisplay(ch)) { setCurrentLine(getCurrentLine() + ch); } setCursorOn(true); } @Override public void keyPressed(KeyEvent ke) { if (ke.getKeyCode() == KeyEvent.VK_ESCAPE) { App.getApp().popScene(); } else if (ke.getKeyCode() == KeyEvent.VK_BACK_SPACE) { String currentLine = getCurrentLine(); if (currentLine.length() > 0) { setCurrentLine(currentLine.substring(0, currentLine.length() - 1)); setCursorOn(true); } } else if (ke.getKeyCode() == KeyEvent.VK_UP) { commandHistoryIndex = Math.max(0, commandHistoryIndex - 1); setCursorOn(true); } else if (ke.getKeyCode() == KeyEvent.VK_DOWN) { commandHistoryIndex = Math.min(commandHistory.size(), commandHistoryIndex + 1); setCursorOn(true); } else if (ke.getKeyCode() == KeyEvent.VK_ENTER) { setCursorOn(true); String currentLine = getCurrentLine(); App.log(PROMPT + currentLine); if (currentLine.length() > 0) { String response = gameScene.doCommand(currentLine); App.log(response); commandHistory.add(currentLine); if (commandHistory.size() > MAX_COMMAND_HISTORY) { commandHistory.remove(0); } commandHistoryIndex = commandHistory.size(); newCommandLine = ""; } } } @Override public void keyReleased(KeyEvent ke) { } }); } @Override public void onResize() { backButton.setLocation(getWidth() / 2 - BORDER_SIZE/2, getHeight() - BORDER_SIZE); helpButton.setLocation(getWidth() / 2 + BORDER_SIZE/2, getHeight() - BORDER_SIZE); textView.setSize(getWidth() - BORDER_SIZE * 2, getHeight() - BORDER_SIZE * 3 - helpButton.getHeight()); } private void setCursorOn(boolean cursorOn) { this.cursorOn = cursorOn; ticks = 0; } private String getCurrentLine() { String currentLine; if (commandHistoryIndex < commandHistory.size()) { currentLine = commandHistory.get(commandHistoryIndex); } else { currentLine = newCommandLine; } return currentLine; } private void setCurrentLine(String currentLine) { if (commandHistoryIndex < commandHistory.size()) { commandHistory.set(commandHistoryIndex, currentLine); } else { newCommandLine = currentLine; } } @Override public void onTick() { ticks++; if (ticks >= CURSOR_BLINK_TICKS) { setCursorOn(!cursorOn); } List<String> log = App.getApp().getLog(); List<View> labels = textView.getSubviews(); int numLogLines = Math.min(log.size(), labels.size() - 1); for (int i = 0; i < labels.size(); i++) { Label label = (Label)labels.get(i); if (i < numLogLines) { label.setText(log.get(log.size() - numLogLines + i)); } else if (i == numLogLines) { label.setText(PROMPT + getCurrentLine() + (cursorOn ? "_" : "")); } else { label.setText(""); } } } }
src/main/java/com/brackeen/scared/ConsoleScene.java
package com.brackeen.scared; import com.brackeen.app.App; import com.brackeen.app.BitmapFont; import com.brackeen.app.view.Button; import com.brackeen.app.view.Label; import com.brackeen.app.view.Scene; import com.brackeen.app.view.View; import java.awt.Color; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.List; public class ConsoleScene extends Scene { private static final int CURSOR_BLINK_TICKS = 20; private static final int BORDER_SIZE = 10; private static final String PROMPT = "] "; private final GameScene gameScene; private Button backButton; private Button helpButton; private View textView; private String currentLine = ""; private int ticks = 0; private boolean cursorOn = true; public ConsoleScene(GameScene gameScene) { this.gameScene = gameScene; } @Override public void onLoad() { App app = App.getApp(); final BitmapFont messageFont = new BitmapFont(app.getImage("/ui/message_font.png"), 11, ' '); setBackgroundColor(new Color(12, 12, 12)); backButton = new Button(app.getImage("/ui/back_button_normal.png")); backButton.setHoverImage(app.getImage("/ui/back_button_hover.png")); backButton.setPressedImage(app.getImage("/ui/back_button_pressed.png")); backButton.setAnchor(1, 1); backButton.setButtonListener(new Button.Listener() { public void buttonClicked(Button button) { App.getApp().popScene(); } }); addSubview(backButton); helpButton = new Button(app.getImage("/ui/help_button_normal.png")); helpButton.setHoverImage(app.getImage("/ui/help_button_hover.png")); helpButton.setPressedImage(app.getImage("/ui/help_button_pressed.png")); helpButton.setAnchor(0, 1); helpButton.setButtonListener(new Button.Listener() { public void buttonClicked(Button button) { App.getApp().pushScene(new HelpScene()); } }); addSubview(helpButton); textView = new View(); textView.setLocation(BORDER_SIZE, BORDER_SIZE); addSubview(textView); onResize(); int maxLines = (int)textView.getHeight() / messageFont.getHeight(); for (int i = 0; i < maxLines; i++) { Label label = new Label(messageFont, ""); label.setLocation(0, i * messageFont.getHeight()); textView.addSubview(label); } setKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent ke) { char ch = ke.getKeyChar(); if (messageFont.canDisplay(ch)) { currentLine += ch; } setCursorOn(true); } @Override public void keyPressed(KeyEvent ke) { if (ke.getKeyCode() == KeyEvent.VK_ESCAPE) { App.getApp().popScene(); } else if (ke.getKeyCode() == KeyEvent.VK_BACK_SPACE) { if (currentLine.length() > 0) { currentLine = currentLine.substring(0, currentLine.length() - 1); } } else if (ke.getKeyCode() == KeyEvent.VK_ENTER) { App.log(PROMPT + currentLine); String response = gameScene.doCommand(currentLine); App.log(response); currentLine = ""; } } @Override public void keyReleased(KeyEvent ke) { } }); } @Override public void onResize() { backButton.setLocation(getWidth() / 2 - BORDER_SIZE/2, getHeight() - BORDER_SIZE); helpButton.setLocation(getWidth() / 2 + BORDER_SIZE/2, getHeight() - BORDER_SIZE); textView.setSize(getWidth() - BORDER_SIZE * 2, getHeight() - BORDER_SIZE * 3 - helpButton.getHeight()); } private void setCursorOn(boolean cursorOn) { this.cursorOn = cursorOn; ticks = 0; } @Override public void onTick() { ticks++; if (ticks >= CURSOR_BLINK_TICKS) { setCursorOn(!cursorOn); } List<String> log = App.getApp().getLog(); List<View> labels = textView.getSubviews(); int numLogLines = Math.min(log.size(), labels.size() - 1); for (int i = 0; i < labels.size(); i++) { Label label = (Label)labels.get(i); if (i < numLogLines) { label.setText(log.get(log.size() - numLogLines + i)); } else if (i == numLogLines) { label.setText(PROMPT + currentLine + (cursorOn ? "_" : "")); } else { label.setText(""); } } } }
Add command history
src/main/java/com/brackeen/scared/ConsoleScene.java
Add command history
<ide><path>rc/main/java/com/brackeen/scared/ConsoleScene.java <ide> import com.brackeen.app.view.Label; <ide> import com.brackeen.app.view.Scene; <ide> import com.brackeen.app.view.View; <add> <ide> import java.awt.Color; <ide> import java.awt.event.KeyEvent; <ide> import java.awt.event.KeyListener; <add>import java.util.ArrayList; <ide> import java.util.List; <ide> <ide> public class ConsoleScene extends Scene { <ide> <ide> private static final int CURSOR_BLINK_TICKS = 20; <ide> private static final int BORDER_SIZE = 10; <add> private static final int MAX_COMMAND_HISTORY = 200; <ide> private static final String PROMPT = "] "; <add> <add> private static List<String> commandHistory = new ArrayList<>(); <ide> <ide> private final GameScene gameScene; <ide> private Button backButton; <ide> private Button helpButton; <ide> private View textView; <del> private String currentLine = ""; <add> private String newCommandLine = ""; <add> private int commandHistoryIndex; <ide> private int ticks = 0; <ide> private boolean cursorOn = true; <ide> <ide> @Override <ide> public void onLoad() { <ide> App app = App.getApp(); <add> <add> commandHistoryIndex = commandHistory.size(); <ide> <ide> final BitmapFont messageFont = new BitmapFont(app.getImage("/ui/message_font.png"), 11, ' '); <ide> <ide> public void keyTyped(KeyEvent ke) { <ide> char ch = ke.getKeyChar(); <ide> if (messageFont.canDisplay(ch)) { <del> currentLine += ch; <add> setCurrentLine(getCurrentLine() + ch); <ide> } <ide> setCursorOn(true); <ide> } <ide> App.getApp().popScene(); <ide> } <ide> else if (ke.getKeyCode() == KeyEvent.VK_BACK_SPACE) { <add> String currentLine = getCurrentLine(); <ide> if (currentLine.length() > 0) { <del> currentLine = currentLine.substring(0, currentLine.length() - 1); <add> setCurrentLine(currentLine.substring(0, currentLine.length() - 1)); <add> setCursorOn(true); <ide> } <ide> } <add> else if (ke.getKeyCode() == KeyEvent.VK_UP) { <add> commandHistoryIndex = Math.max(0, commandHistoryIndex - 1); <add> setCursorOn(true); <add> } <add> else if (ke.getKeyCode() == KeyEvent.VK_DOWN) { <add> commandHistoryIndex = Math.min(commandHistory.size(), commandHistoryIndex + 1); <add> setCursorOn(true); <add> } <ide> else if (ke.getKeyCode() == KeyEvent.VK_ENTER) { <add> setCursorOn(true); <add> String currentLine = getCurrentLine(); <ide> App.log(PROMPT + currentLine); <del> String response = gameScene.doCommand(currentLine); <del> App.log(response); <del> currentLine = ""; <add> if (currentLine.length() > 0) { <add> String response = gameScene.doCommand(currentLine); <add> App.log(response); <add> <add> commandHistory.add(currentLine); <add> if (commandHistory.size() > MAX_COMMAND_HISTORY) { <add> commandHistory.remove(0); <add> } <add> commandHistoryIndex = commandHistory.size(); <add> newCommandLine = ""; <add> } <ide> } <ide> } <ide> <ide> ticks = 0; <ide> } <ide> <add> private String getCurrentLine() { <add> String currentLine; <add> if (commandHistoryIndex < commandHistory.size()) { <add> currentLine = commandHistory.get(commandHistoryIndex); <add> } <add> else { <add> currentLine = newCommandLine; <add> } <add> return currentLine; <add> } <add> <add> private void setCurrentLine(String currentLine) { <add> if (commandHistoryIndex < commandHistory.size()) { <add> commandHistory.set(commandHistoryIndex, currentLine); <add> } <add> else { <add> newCommandLine = currentLine; <add> } <add> } <add> <ide> @Override <ide> public void onTick() { <ide> ticks++; <ide> label.setText(log.get(log.size() - numLogLines + i)); <ide> } <ide> else if (i == numLogLines) { <del> label.setText(PROMPT + currentLine + (cursorOn ? "_" : "")); <add> label.setText(PROMPT + getCurrentLine() + (cursorOn ? "_" : "")); <ide> } <ide> else { <ide> label.setText("");
Java
apache-2.0
e05a07027541e52a162ad599e5f32ae276ec436c
0
porcelli-forks/guvnor,baldimir/guvnor,baldimir/guvnor,droolsjbpm/guvnor,porcelli-forks/guvnor,etirelli/guvnor,cristianonicolai/guvnor,kiereleaseuser/guvnor,hxf0801/guvnor,cristianonicolai/guvnor,wmedvede/guvnor,adrielparedes/guvnor,nmirasch/guvnor,hxf0801/guvnor,nmirasch/guvnor,psiroky/guvnor,baldimir/guvnor,hxf0801/guvnor,kiereleaseuser/guvnor,droolsjbpm/guvnor,yurloc/guvnor,porcelli-forks/guvnor,mswiderski/guvnor,mbiarnes/guvnor,droolsjbpm/guvnor,etirelli/guvnor,psiroky/guvnor,adrielparedes/guvnor,wmedvede/guvnor,kiereleaseuser/guvnor,nmirasch/guvnor,adrielparedes/guvnor,wmedvede/guvnor,yurloc/guvnor,mbiarnes/guvnor,mbiarnes/guvnor,psiroky/guvnor,etirelli/guvnor,cristianonicolai/guvnor
/* * Copyright 2011 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.guvnor.server.files; import static org.junit.Assert.assertEquals; import java.io.ByteArrayInputStream; import java.util.HashMap; import java.util.UUID; import javax.inject.Inject; import org.drools.guvnor.server.GuvnorTestBase; import org.drools.guvnor.server.ServiceImplementation; import org.drools.guvnor.server.files.ActionsAPI.Parameters; import org.drools.repository.RulesRepository; import org.drools.util.codec.Base64; import org.junit.Test; /** * Some basic unit tests for compilation and snapshot * creation in the ActionsAPIServlet. */ public class ActionAPIServletTest extends GuvnorTestBase { private final String compilationPath = "http://foo/action/compile"; private final String snapshotPath = "http://foo/action/snapshot"; @Inject private ActionsAPIServlet actionsAPIServlet; public ActionAPIServletTest() { autoLoginAsAdmin = false; } /* * Modeled after testPost in RestAPIServletTest. */ @Test public void testCompilation() throws Exception { final String dynamicPackage = "test-action" + UUID.randomUUID(); rulesRepository.createModule(dynamicPackage, "test-action package for testing"); HashMap<String, String> headers = new HashMap<String, String>() { { put( "Authorization", "BASIC " + new String( new Base64().encode( "admin:admin".getBytes() ) ) ); } }; HashMap<String, String> parameters = new HashMap<String, String>() { { put( Parameters.PackageName.toString(), dynamicPackage ); } }; MockHTTPRequest req = new MockHTTPRequest( compilationPath, headers, parameters ); MockHTTPResponse res = new MockHTTPResponse(); actionsAPIServlet.doPost( req, res ); assertEquals( 200, res.status ); } @Test public void testSnapshotCreation() throws Exception { final String dynamicPackage = "test-snap" + UUID.randomUUID(); rulesRepository.createModule(dynamicPackage, "test-snapshot package for testing"); HashMap<String, String> headers = new HashMap<String, String>() { { put( "Authorization", "BASIC " + new String( new Base64().encode( "admin:admin".getBytes() ) ) ); } }; HashMap<String, String> parameters = new HashMap<String, String>() { { put( Parameters.PackageName.toString(), dynamicPackage ); put( Parameters.SnapshotName.toString(), "test-action-snap1" ); } }; ByteArrayInputStream in = new ByteArrayInputStream( "some content".getBytes() ); MockHTTPRequest req = new MockHTTPRequest( snapshotPath, headers, parameters, in ); MockHTTPResponse res = new MockHTTPResponse(); actionsAPIServlet.doPost( req, res ); assertEquals( 200, res.status ); } }
guvnor-webapp-drools/src/test/java/org/drools/guvnor/server/files/ActionAPIServletTest.java
/* * Copyright 2011 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.guvnor.server.files; import static org.junit.Assert.assertEquals; import java.io.ByteArrayInputStream; import java.util.HashMap; import java.util.UUID; import javax.inject.Inject; import org.drools.guvnor.server.GuvnorTestBase; import org.drools.guvnor.server.ServiceImplementation; import org.drools.guvnor.server.files.ActionsAPI.Parameters; import org.drools.repository.RulesRepository; import org.drools.util.codec.Base64; import org.junit.Test; /** * Some basic unit tests for compilation and snapshot * creation in the ActionsAPIServlet. */ public class ActionAPIServletTest extends GuvnorTestBase { private final String compilationPath = "http://foo/action/compile"; private final String snapshotPath = "http://foo/action/snapshot"; @Inject private ActionsAPIServlet actionsAPIServlet; public ActionAPIServletTest() { autoLoginAsAdmin = false; } /* * Modeled after testPost in RestAPIServletTest. */ @Test public void testCompilation() throws Exception { final String dynamicPackage = "test-action" + UUID.randomUUID(); rulesRepository.createModule(dynamicPackage, "test-action package for testing"); HashMap<String, String> headers = new HashMap<String, String>() { { put( "Authorization", "BASIC " + new String( new Base64().encode( "admin:admin".getBytes() ) ) ); } }; HashMap<String, String> parameters = new HashMap<String, String>() { { put( Parameters.PackageName.toString(), dynamicPackage ); } }; MockHTTPRequest req = new MockHTTPRequest( compilationPath, headers, parameters ); MockHTTPResponse res = new MockHTTPResponse(); actionsAPIServlet.doPost( req, res ); assertEquals( 200, res.status ); rulesRepository.logout(); } @Test public void testSnapshotCreation() throws Exception { final String dynamicPackage = "test-snap" + UUID.randomUUID(); rulesRepository.createModule(dynamicPackage, "test-snapshot package for testing"); HashMap<String, String> headers = new HashMap<String, String>() { { put( "Authorization", "BASIC " + new String( new Base64().encode( "admin:admin".getBytes() ) ) ); } }; HashMap<String, String> parameters = new HashMap<String, String>() { { put( Parameters.PackageName.toString(), dynamicPackage ); put( Parameters.SnapshotName.toString(), "test-action-snap1" ); } }; ByteArrayInputStream in = new ByteArrayInputStream( "some content".getBytes() ); MockHTTPRequest req = new MockHTTPRequest( snapshotPath, headers, parameters, in ); MockHTTPResponse res = new MockHTTPResponse(); actionsAPIServlet.doPost( req, res ); assertEquals( 200, res.status ); rulesRepository.logout(); } }
remove unneeded rulesRepository.logout()
guvnor-webapp-drools/src/test/java/org/drools/guvnor/server/files/ActionAPIServletTest.java
remove unneeded rulesRepository.logout()
<ide><path>uvnor-webapp-drools/src/test/java/org/drools/guvnor/server/files/ActionAPIServletTest.java <ide> res ); <ide> assertEquals( 200, <ide> res.status ); <del> rulesRepository.logout(); <ide> } <ide> <ide> @Test <ide> res ); <ide> assertEquals( 200, <ide> res.status ); <del> rulesRepository.logout(); <ide> } <ide> <ide> }
Java
bsd-3-clause
b02452ca53e1a4226d1ac460dedbb4578a4ffb67
0
salesforcefuel/fuel-java,gutsy/fuel-java,salesforcefuel/FuelSDK-Java,salesforce-marketingcloud/FuelSDK-Java,viadeo/fuel-java
// // This file is part of the Fuel Java SDK. // // Copyright (C) 2013, 2014 ExactTarget, Inc. // All rights reserved. // // 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. // package com.exacttarget.fuelsdk; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import org.apache.log4j.Logger; import com.exacttarget.fuelsdk.annotations.ExternalName; import com.exacttarget.fuelsdk.annotations.InternalName; import com.exacttarget.fuelsdk.annotations.SoapObject; import com.exacttarget.fuelsdk.ETDataExtensionColumn.Type; import com.exacttarget.fuelsdk.internal.APIObject; import com.exacttarget.fuelsdk.internal.APIProperty; import com.exacttarget.fuelsdk.internal.DataExtension; import com.exacttarget.fuelsdk.internal.DataExtensionObject; import com.exacttarget.fuelsdk.internal.DeleteOptions; import com.exacttarget.fuelsdk.internal.DeleteRequest; import com.exacttarget.fuelsdk.internal.DeleteResponse; import com.exacttarget.fuelsdk.internal.DeleteResult; import com.exacttarget.fuelsdk.internal.Soap; @SoapObject(internalType = DataExtension.class, unretrievable = { "ID", "Fields" }) public class ETDataExtension extends ETSoapObject { private static Logger logger = Logger.getLogger(ETDataExtension.class); @ExternalName("id") @InternalName("objectID") private String id = null; @ExternalName("name") private String name = null; @ExternalName("description") private String description = null; @ExternalName("folderId") @InternalName("categoryID") private Integer folderId = null; @ExternalName("columns") @InternalName("fields") private List<ETDataExtensionColumn> columns = new ArrayList<ETDataExtensionColumn>(); @ExternalName("isSendable") private Boolean isSendable = null; @ExternalName("isTestable") private Boolean isTestable = null; private boolean isHydrated = false; public ETDataExtension() {} @Override public String getId() { return id; } @Override public void setId(String id) { this.id = id; } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Integer getFolderId() { return folderId; } public void setFolderId(Integer folderId) { this.folderId = folderId; } public List<ETDataExtensionColumn> getColumns() { return columns; } public ETDataExtensionColumn getColumn(String name) { for (ETDataExtensionColumn column : columns) { if (column.getName().equals(name.toLowerCase())) { return column; } } return null; } public ETDataExtensionColumn getPrimaryKeyColumn() throws ETSdkException { if (!isHydrated) { hydrate(); } for (ETDataExtensionColumn column : columns) { if (column.getIsPrimaryKey()) { return column; } } return null; } public void addColumn(String name) { addColumn(name, null, null, null, null, null, null, null); } public void addColumn(String name, Type type) { addColumn(name, type, null, null, null, null, null, null); } public void addColumn(String name, Boolean isPrimaryKey) { addColumn(name, null, null, null, null, isPrimaryKey, null, null); } public void addColumn(String name, Type type, Boolean isPrimaryKey) { addColumn(name, type, null, null, null, isPrimaryKey, null, null); } public void addColumn(String name, Type type, Integer length, Integer precision, Integer scale, Boolean isPrimaryKey, Boolean isRequired, String defaultValue) { ETDataExtensionColumn column = new ETDataExtensionColumn(); column.setName(name.toLowerCase()); if (type != null) { column.setType(type); } else { // default is text type column.setType(Type.TEXT); } // mimics the UI default values for length, precision, and scale if (column.getType() == Type.TEXT) { if (length != null) { column.setLength(length); } else { column.setLength(50); } } if (column.getType() == Type.DECIMAL) { if (precision != null) { column.setPrecision(precision); } else { column.setPrecision(18); } if (scale != null) { column.setScale(scale); } else { column.setScale(0); } } column.setIsPrimaryKey(isPrimaryKey); if (isPrimaryKey != null && isPrimaryKey) { column.setIsRequired(true); } else { column.setIsRequired(isRequired); } column.setDefaultValue(defaultValue); addColumn(column); } public void addColumn(ETDataExtensionColumn column) { columns.add(column); } public Boolean getIsSendable() { return isSendable; } public void setIsSendable(Boolean isSendable) { this.isSendable = isSendable; } public Boolean getIsTestable() { return isTestable; } public void setIsTestable(Boolean isTestable) { this.isTestable = isTestable; } /** * @deprecated * Use <code>getFolderId()</code>. */ @Deprecated public Integer getCategoryId() { return getFolderId(); } /** * @deprecated * Use <code>setFolderId()</code>. */ @Deprecated public void setCategoryId(Integer categoryId) { setFolderId(categoryId); } public ETResponse<ETDataExtensionRow> insert(ETDataExtensionRow... rows) throws ETSdkException { return insert(Arrays.asList(rows)); } public ETResponse<ETDataExtensionRow> insert(List<ETDataExtensionRow> rows) throws ETSdkException { ETClient client = getClient(); for (ETDataExtensionRow row : rows) { // // Set the data extension name if it isn't already set: // if (row.getName() == null) { row.setName(name); } } return client.create(rows); } public ETResponse<ETDataExtensionRow> select() throws ETSdkException { // new String[0] = empty properties return select((ETFilter) null, null, null, new String[0]); } public ETResponse<ETDataExtensionRow> select(String filter, String... columns) throws ETSdkException { // see also: ETClient.retrieve(type, filter, properties) ETFilter f = null; String[] c = columns; try { f = ETFilter.parse(filter); } catch (ETSdkException ex) { if (ex.getCause() instanceof ParseException) { // // The filter argument is actually a column. This is a bit // of a hack, but this method needs to handle the case of // both a filtered and a filterless retrieve with columns, // as having one method for each results in ambiguous methods. // c = new String[columns.length + 1]; c[0] = filter; int i = 1; for (String property : columns) { c[i++] = property; } } else { throw ex; } } return select(f, null, null, c); } public ETResponse<ETDataExtensionRow> select(Integer page, Integer pageSize, String... columns) throws ETSdkException { return select((ETFilter) null, page, pageSize, columns); } public ETResponse<ETDataExtensionRow> select(String filter, Integer page, Integer pageSize, String... columns) throws ETSdkException { return select(ETFilter.parse(filter), page, pageSize, columns); } public ETResponse<ETDataExtensionRow> select(ETFilter filter, Integer page, Integer pageSize, String... columns) throws ETSdkException { ETClient client = getClient(); ETResponse<ETDataExtensionRow> response = new ETResponse<ETDataExtensionRow>(); String path = "/data/v1/customobjectdata/key/" + getKey() + "/rowset"; StringBuilder stringBuilder = new StringBuilder(path); boolean firstQueryParameter = true; String[] properties = new String[0]; // empty by default if (columns.length > 0) { // // Only request those columns specified: // boolean firstField = true; for (String column : columns) { if (column.substring(0, 8).toLowerCase().equals("order by")) { // not actually a column, an order by string properties = new String[1]; properties[0] = columns[columns.length - 1]; } else { if (firstField) { firstField = false; if (firstQueryParameter) { firstQueryParameter = false; stringBuilder.append("?"); } else { stringBuilder.append("&"); } stringBuilder.append("$fields="); } else { stringBuilder.append(","); } stringBuilder.append(column); } } } if (filter != null) { if (firstQueryParameter) { firstQueryParameter = false; stringBuilder.append("?"); } else { stringBuilder.append("&"); } stringBuilder.append("$filter="); stringBuilder.append(toQueryParams(filter)); } path = stringBuilder.toString(); ETRestConnection connection = client.getRestConnection(); JsonObject jsonObject = ETRestObject.retrieve(client, path, page, pageSize, properties); response.setRequestId(connection.getLastCallRequestId()); response.setResponseCode(connection.getLastCallResponseCode()); response.setResponseMessage(connection.getLastCallResponseMessage()); if (jsonObject.get("page") != null) { response.setPage(jsonObject.get("page").getAsInt()); logger.trace("page = " + response.getPage()); response.setPageSize(jsonObject.get("pageSize").getAsInt()); logger.trace("pageSize = " + response.getPageSize()); response.setTotalCount(jsonObject.get("count").getAsInt()); logger.trace("totalCount = " + response.getTotalCount()); if (response.getPage() * response.getPageSize() < response.getTotalCount()) { response.setMoreResults(true); } JsonElement items = jsonObject.get("items"); if (items != null) { JsonArray collection = items.getAsJsonArray(); for (JsonElement element : collection) { JsonObject object = element.getAsJsonObject(); ETDataExtensionRow row = new ETDataExtensionRow(); JsonObject keys = object.get("keys").getAsJsonObject(); for (Map.Entry<String, JsonElement> entry : keys.entrySet()) { row.setColumn(entry.getKey(), entry.getValue().getAsString()); } JsonObject values = object.get("values").getAsJsonObject(); for (Map.Entry<String, JsonElement> entry : values.entrySet()) { row.setColumn(entry.getKey(), entry.getValue().getAsString()); } row.setClient(client); ETResult<ETDataExtensionRow> result = new ETResult<ETDataExtensionRow>(); result.setObject(row); response.addResult(result); } } } return response; } public ETResponse<ETDataExtensionRow> update(ETDataExtensionRow... rows) throws ETSdkException { return update(Arrays.asList(rows)); } public ETResponse<ETDataExtensionRow> update(List<ETDataExtensionRow> rows) throws ETSdkException { ETClient client = getClient(); for (ETDataExtensionRow row : rows) { // // Set the data extension name if it isn't already set: // if (row.getName() == null) { row.setName(name); } } return client.update(rows); } public ETResponse<ETDataExtensionRow> update(String filter, String... values) throws ETSdkException { // XXX can this be optimized? ETResponse<ETDataExtensionRow> response = select(filter); List<ETDataExtensionRow> rows = response.getObjects(); for (ETDataExtensionRow row : rows) { for (String value : values) { ETFilter parsedFilter = ETFilter.parse(value); if (parsedFilter.getOperator() != ETFilter.Operator.EQUALS) { throw new ETSdkException("unsupported operator: " + parsedFilter.getOperator()); } row.setColumn(parsedFilter.getProperty(), parsedFilter.getValue()); } } return update(rows.toArray(new ETDataExtensionRow[rows.size()])); } public ETResponse<ETDataExtensionRow> delete(ETDataExtensionRow... rows) throws ETSdkException { return delete(Arrays.asList(rows)); } public ETResponse<ETDataExtensionRow> delete(List<ETDataExtensionRow> rows) throws ETSdkException { ETClient client = getClient(); // XXX much of this is copied and pasted from ETSoapObject.delete ETResponse<ETDataExtensionRow> response = new ETResponse<ETDataExtensionRow>(); if (rows == null || rows.size() == 0) { return response; } // // Get handle to the SOAP connection: // ETSoapConnection connection = client.getSoapConnection(); // // Automatically refresh the token if necessary: // client.refreshToken(); // // Perform the SOAP delete: // Soap soap = connection.getSoap(); DeleteRequest deleteRequest = new DeleteRequest(); deleteRequest.setOptions(new DeleteOptions()); for (ETDataExtensionRow row : rows) { row.setClient(client); // // We hand construct this one, since all we need // to pass in is the primary key, and we pass it // in to DeleteRequest differently (in the Keys // property) than we received it from // RetrieveRequest (in the Properties property): // DataExtensionObject internalRow = new DataExtensionObject(); DataExtensionObject.Keys keys = new DataExtensionObject.Keys(); ETDataExtensionColumn primaryKeyColumn = getPrimaryKeyColumn(); APIProperty property = new APIProperty(); property.setName(primaryKeyColumn.getName()); property.setValue(row.getColumn(property.getName())); keys.getKey().add(property); internalRow.setName(name); internalRow.setKeys(keys); deleteRequest.getObjects().add(internalRow); } if (logger.isTraceEnabled()) { logger.trace("DeleteRequest:"); logger.trace(" objects = {"); for (APIObject object : deleteRequest.getObjects()) { logger.trace(" " + object); } logger.trace(" }"); } logger.trace("calling soap.delete..."); DeleteResponse deleteResponse = soap.delete(deleteRequest); if (logger.isTraceEnabled()) { logger.trace("DeleteResponse:"); logger.trace(" requestId = " + deleteResponse.getRequestID()); logger.trace(" overallStatus = " + deleteResponse.getOverallStatus()); logger.trace(" results = {"); for (DeleteResult result : deleteResponse.getResults()) { logger.trace(" " + result); } logger.trace(" }"); } response.setRequestId(deleteResponse.getRequestID()); response.setResponseCode(deleteResponse.getOverallStatus()); response.setResponseMessage(deleteResponse.getOverallStatus()); for (DeleteResult deleteResult : deleteResponse.getResults()) { ETResult<ETDataExtensionRow> result = new ETResult<ETDataExtensionRow>(); result.setResponseCode(deleteResult.getStatusCode()); result.setResponseMessage(deleteResult.getStatusMessage()); result.setErrorCode(deleteResult.getErrorCode()); response.addResult(result); } return response; } public ETResponse<ETDataExtensionRow> delete(String filter) throws ETSdkException { // XXX optimize ETResponse<ETDataExtensionRow> response = select(filter); List<ETDataExtensionRow> rows = response.getObjects(); return delete(rows.toArray(new ETDataExtensionRow[rows.size()])); } public ETResponse<ETDataExtensionRow> export(String filter, String file) throws ETSdkException { return export(ETFilter.parse(filter), file); } public ETResponse<ETDataExtensionRow> export(ETFilter filter, String fileName) throws ETSdkException { ETClient client = getClient(); ETResponse<ETDataExtensionRow> response = new ETResponse<ETDataExtensionRow>(); String path = "/data/v1/customobjectdata/export"; StringBuilder stringBuilder = new StringBuilder(path); if (filter != null) { stringBuilder.append("?filter="); stringBuilder.append(toQueryParams(filter)); } path = stringBuilder.toString(); ETRestConnection connection = client.getRestConnection(); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("customerKey", getKey()); jsonObject.addProperty("fileName", fileName); connection.post(path, jsonObject); // XXX handle return value response.setRequestId(connection.getLastCallRequestId()); response.setResponseCode(connection.getLastCallResponseCode()); response.setResponseMessage(connection.getLastCallResponseMessage()); return response; } public void hydrate() throws ETSdkException { ETClient client = getClient(); // // Automatically refresh the token if necessary: // client.refreshToken(); // // Retrieve all columns with CustomerKey = this data extension: // ETFilter filter = new ETFilter(); filter.setProperty("DataExtension.CustomerKey"); filter.setOperator(ETFilter.Operator.EQUALS); filter.addValue(getKey()); ETResponse<ETDataExtensionColumn> response = ETDataExtensionColumn.retrieve(client, filter, null, // page null, // pageSize ETDataExtensionColumn.class, new String[0]); // properties columns = response.getObjects(); // XXX deal with partially loaded DataExtension objects too isHydrated = true; } public static String toQueryParams(ETFilter filter) throws ETSdkException { StringBuilder stringBuilder = new StringBuilder(); ETFilter.Operator operator = filter.getOperator(); switch (operator) { case AND: stringBuilder.append(toQueryParams(filter.getFilters().get(0))); stringBuilder.append("%20"); stringBuilder.append("and"); stringBuilder.append("%20"); stringBuilder.append(toQueryParams(filter.getFilters().get(1))); break; case OR: stringBuilder.append(toQueryParams(filter.getFilters().get(0))); stringBuilder.append("%20"); stringBuilder.append("or"); stringBuilder.append("%20"); stringBuilder.append(toQueryParams(filter.getFilters().get(1))); break; case NOT: stringBuilder.append("not"); stringBuilder.append("%20"); stringBuilder.append(toQueryParams(filter.getFilters().get(0))); break; case EQUALS: stringBuilder.append(filter.getProperty()); stringBuilder.append("%20"); stringBuilder.append("eq"); stringBuilder.append("%20"); stringBuilder.append(toQueryParams(filter.getValue())); break; case NOT_EQUALS: stringBuilder.append(filter.getProperty()); stringBuilder.append("%20"); stringBuilder.append("neq"); stringBuilder.append("%20"); stringBuilder.append(toQueryParams(filter.getValue())); break; case LESS_THAN: stringBuilder.append(filter.getProperty()); stringBuilder.append("%20"); stringBuilder.append("lt"); stringBuilder.append("%20"); stringBuilder.append(toQueryParams(filter.getValue())); break; case LESS_THAN_OR_EQUALS: stringBuilder.append(filter.getProperty()); stringBuilder.append("%20"); stringBuilder.append("lte"); stringBuilder.append("%20"); stringBuilder.append(toQueryParams(filter.getValue())); break; case GREATER_THAN: stringBuilder.append(filter.getProperty()); stringBuilder.append("%20"); stringBuilder.append("gt"); stringBuilder.append("%20"); stringBuilder.append(toQueryParams(filter.getValue())); break; case GREATER_THAN_OR_EQUALS: stringBuilder.append(filter.getProperty()); stringBuilder.append("%20"); stringBuilder.append("gte"); stringBuilder.append("%20"); stringBuilder.append(toQueryParams(filter.getValue())); break; case IS_NULL: stringBuilder.append(filter.getProperty()); stringBuilder.append("%20"); stringBuilder.append("is"); stringBuilder.append("%20"); stringBuilder.append("null"); break; case IS_NOT_NULL: stringBuilder.append(filter.getProperty()); stringBuilder.append("%20"); stringBuilder.append("is"); stringBuilder.append("%20"); stringBuilder.append("not"); stringBuilder.append("%20"); stringBuilder.append("null"); break; case IN: stringBuilder.append(filter.getProperty()); stringBuilder.append("%20"); stringBuilder.append("in"); stringBuilder.append("%20"); stringBuilder.append("("); boolean first = true; for (String value : filter.getValues()) { if (first) { first = false; } else { stringBuilder.append(","); } stringBuilder.append(toQueryParams(value)); } stringBuilder.append(")"); break; case BETWEEN: stringBuilder.append(filter.getProperty()); stringBuilder.append("%20"); stringBuilder.append("between"); stringBuilder.append("%20"); stringBuilder.append(toQueryParams(filter.getValues().get(0))); stringBuilder.append("%20"); stringBuilder.append("and"); stringBuilder.append("%20"); stringBuilder.append(toQueryParams(filter.getValues().get(1))); break; case LIKE: stringBuilder.append(filter.getProperty()); stringBuilder.append("%20"); stringBuilder.append("like"); stringBuilder.append("%20"); stringBuilder.append(toQueryParams(filter.getValue(), true)); break; default: throw new ETSdkException("unsupported operator: " + operator); } return stringBuilder.toString(); } private static String toQueryParams(String value) throws ETSdkException { return toQueryParams(value, false); } private static String toQueryParams(String value, boolean forceQuotes) throws ETSdkException { if (value.equals("")) { forceQuotes = true; } // XXX workaround for FUEL-3348--remove after 02 if (value.contains("-")) { forceQuotes = true; } boolean quotes = forceQuotes; if (!forceQuotes) { // needs quotes in the URL if there's whitespace for (int i = 0; i < value.length(); i++) { if (Character.isWhitespace(value.charAt(i))) { quotes = true; break; } } } String v = null; if (quotes) { v = "'" + value + "'"; } else { v = value.toString(); } try { return URLEncoder.encode(v, "UTF-8"); } catch (UnsupportedEncodingException ex) { throw new ETSdkException("error URL encoding " + v, ex); } } }
src/main/java/com/exacttarget/fuelsdk/ETDataExtension.java
// // This file is part of the Fuel Java SDK. // // Copyright (C) 2013, 2014 ExactTarget, Inc. // All rights reserved. // // 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. // package com.exacttarget.fuelsdk; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import org.apache.log4j.Logger; import com.exacttarget.fuelsdk.annotations.ExternalName; import com.exacttarget.fuelsdk.annotations.InternalName; import com.exacttarget.fuelsdk.annotations.SoapObject; import com.exacttarget.fuelsdk.ETDataExtensionColumn.Type; import com.exacttarget.fuelsdk.internal.APIObject; import com.exacttarget.fuelsdk.internal.APIProperty; import com.exacttarget.fuelsdk.internal.DataExtension; import com.exacttarget.fuelsdk.internal.DataExtensionObject; import com.exacttarget.fuelsdk.internal.DeleteOptions; import com.exacttarget.fuelsdk.internal.DeleteRequest; import com.exacttarget.fuelsdk.internal.DeleteResponse; import com.exacttarget.fuelsdk.internal.DeleteResult; import com.exacttarget.fuelsdk.internal.Soap; @SoapObject(internalType = DataExtension.class, unretrievable = { "ID", "Fields" }) public class ETDataExtension extends ETSoapObject { @ExternalName("id") @InternalName("objectID") private String id = null; @ExternalName("name") private String name = null; @ExternalName("description") private String description = null; @ExternalName("folderId") @InternalName("categoryID") private Integer folderId = null; @ExternalName("columns") @InternalName("fields") private List<ETDataExtensionColumn> columns = new ArrayList<ETDataExtensionColumn>(); @ExternalName("isSendable") private Boolean isSendable = null; @ExternalName("isTestable") private Boolean isTestable = null; private static Logger logger = Logger.getLogger(ETDataExtension.class); private boolean isHydrated = false; public ETDataExtension() {} @Override public String getId() { return id; } @Override public void setId(String id) { this.id = id; } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Integer getFolderId() { return folderId; } public void setFolderId(Integer folderId) { this.folderId = folderId; } public List<ETDataExtensionColumn> getColumns() { return columns; } public ETDataExtensionColumn getColumn(String name) { for (ETDataExtensionColumn column : columns) { if (column.getName().equals(name.toLowerCase())) { return column; } } return null; } public ETDataExtensionColumn getPrimaryKeyColumn() throws ETSdkException { if (!isHydrated) { hydrate(); } for (ETDataExtensionColumn column : columns) { if (column.getIsPrimaryKey()) { return column; } } return null; } public void addColumn(String name) { addColumn(name, null, null, null, null, null, null, null); } public void addColumn(String name, Type type) { addColumn(name, type, null, null, null, null, null, null); } public void addColumn(String name, Boolean isPrimaryKey) { addColumn(name, null, null, null, null, isPrimaryKey, null, null); } public void addColumn(String name, Type type, Boolean isPrimaryKey) { addColumn(name, type, null, null, null, isPrimaryKey, null, null); } public void addColumn(String name, Type type, Integer length, Integer precision, Integer scale, Boolean isPrimaryKey, Boolean isRequired, String defaultValue) { ETDataExtensionColumn column = new ETDataExtensionColumn(); column.setName(name.toLowerCase()); if (type != null) { column.setType(type); } else { // default is text type column.setType(Type.TEXT); } // mimics the UI default values for length, precision, and scale if (column.getType() == Type.TEXT) { if (length != null) { column.setLength(length); } else { column.setLength(50); } } if (column.getType() == Type.DECIMAL) { if (precision != null) { column.setPrecision(precision); } else { column.setPrecision(18); } if (scale != null) { column.setScale(scale); } else { column.setScale(0); } } column.setIsPrimaryKey(isPrimaryKey); if (isPrimaryKey != null && isPrimaryKey) { column.setIsRequired(true); } else { column.setIsRequired(isRequired); } column.setDefaultValue(defaultValue); addColumn(column); } public void addColumn(ETDataExtensionColumn column) { columns.add(column); } public Boolean getIsSendable() { return isSendable; } public void setIsSendable(Boolean isSendable) { this.isSendable = isSendable; } public Boolean getIsTestable() { return isTestable; } public void setIsTestable(Boolean isTestable) { this.isTestable = isTestable; } /** * @deprecated * Use <code>getFolderId()</code>. */ @Deprecated public Integer getCategoryId() { return getFolderId(); } /** * @deprecated * Use <code>setFolderId()</code>. */ @Deprecated public void setCategoryId(Integer categoryId) { setFolderId(categoryId); } public ETResponse<ETDataExtensionRow> insert(ETDataExtensionRow... rows) throws ETSdkException { ETClient client = getClient(); for (ETDataExtensionRow row : rows) { // // Set the data extension name if it isn't already set: // if (row.getName() == null) { row.setName(name); } } return client.create(Arrays.asList(rows)); } public ETResponse<ETDataExtensionRow> select() throws ETSdkException { // new String[0] = empty properties return select((ETFilter) null, null, null, new String[0]); } public ETResponse<ETDataExtensionRow> select(String filter, String... columns) throws ETSdkException { // see also: ETClient.retrieve(type, filter, properties) ETFilter f = null; String[] c = columns; try { f = ETFilter.parse(filter); } catch (ETSdkException ex) { if (ex.getCause() instanceof ParseException) { // // The filter argument is actually a column. This is a bit // of a hack, but this method needs to handle the case of // both a filtered and a filterless retrieve with columns, // as having one method for each results in ambiguous methods. // c = new String[columns.length + 1]; c[0] = filter; int i = 1; for (String property : columns) { c[i++] = property; } } else { throw ex; } } return select(f, null, null, c); } public ETResponse<ETDataExtensionRow> select(Integer page, Integer pageSize, String... columns) throws ETSdkException { return select((ETFilter) null, page, pageSize, columns); } public ETResponse<ETDataExtensionRow> select(String filter, Integer page, Integer pageSize, String... columns) throws ETSdkException { return select(ETFilter.parse(filter), page, pageSize, columns); } public ETResponse<ETDataExtensionRow> select(ETFilter filter, Integer page, Integer pageSize, String... columns) throws ETSdkException { ETClient client = getClient(); ETResponse<ETDataExtensionRow> response = new ETResponse<ETDataExtensionRow>(); String path = "/data/v1/customobjectdata/key/" + getKey() + "/rowset"; StringBuilder stringBuilder = new StringBuilder(path); boolean firstQueryParameter = true; String[] properties = new String[0]; // empty by default if (columns.length > 0) { // // Only request those columns specified: // boolean firstField = true; for (String column : columns) { if (column.substring(0, 8).toLowerCase().equals("order by")) { // not actually a column, an order by string properties = new String[1]; properties[0] = columns[columns.length - 1]; } else { if (firstField) { firstField = false; if (firstQueryParameter) { firstQueryParameter = false; stringBuilder.append("?"); } else { stringBuilder.append("&"); } stringBuilder.append("$fields="); } else { stringBuilder.append(","); } stringBuilder.append(column); } } } if (filter != null) { if (firstQueryParameter) { firstQueryParameter = false; stringBuilder.append("?"); } else { stringBuilder.append("&"); } stringBuilder.append("$filter="); stringBuilder.append(toQueryParams(filter)); } path = stringBuilder.toString(); ETRestConnection connection = client.getRestConnection(); JsonObject jsonObject = ETRestObject.retrieve(client, path, page, pageSize, properties); response.setRequestId(connection.getLastCallRequestId()); response.setResponseCode(connection.getLastCallResponseCode()); response.setResponseMessage(connection.getLastCallResponseMessage()); if (jsonObject.get("page") != null) { response.setPage(jsonObject.get("page").getAsInt()); logger.trace("page = " + response.getPage()); response.setPageSize(jsonObject.get("pageSize").getAsInt()); logger.trace("pageSize = " + response.getPageSize()); response.setTotalCount(jsonObject.get("count").getAsInt()); logger.trace("totalCount = " + response.getTotalCount()); if (response.getPage() * response.getPageSize() < response.getTotalCount()) { response.setMoreResults(true); } JsonElement items = jsonObject.get("items"); if (items != null) { JsonArray collection = items.getAsJsonArray(); for (JsonElement element : collection) { JsonObject object = element.getAsJsonObject(); ETDataExtensionRow row = new ETDataExtensionRow(); JsonObject keys = object.get("keys").getAsJsonObject(); for (Map.Entry<String, JsonElement> entry : keys.entrySet()) { row.setColumn(entry.getKey(), entry.getValue().getAsString()); } JsonObject values = object.get("values").getAsJsonObject(); for (Map.Entry<String, JsonElement> entry : values.entrySet()) { row.setColumn(entry.getKey(), entry.getValue().getAsString()); } row.setClient(client); ETResult<ETDataExtensionRow> result = new ETResult<ETDataExtensionRow>(); result.setObject(row); response.addResult(result); } } } return response; } public ETResponse<ETDataExtensionRow> update(ETDataExtensionRow... rows) throws ETSdkException { ETClient client = getClient(); for (ETDataExtensionRow row : rows) { // // Set the data extension name if it isn't already set: // if (row.getName() == null) { row.setName(name); } } return client.update(Arrays.asList(rows)); } public ETResponse<ETDataExtensionRow> update(String filter, String... values) throws ETSdkException { // XXX can this be optimized? ETResponse<ETDataExtensionRow> response = select(filter); List<ETDataExtensionRow> rows = response.getObjects(); for (ETDataExtensionRow row : rows) { for (String value : values) { ETFilter parsedFilter = ETFilter.parse(value); if (parsedFilter.getOperator() != ETFilter.Operator.EQUALS) { throw new ETSdkException("unsupported operator: " + parsedFilter.getOperator()); } row.setColumn(parsedFilter.getProperty(), parsedFilter.getValue()); } } return update(rows.toArray(new ETDataExtensionRow[rows.size()])); } public ETResponse<ETDataExtensionRow> delete(ETDataExtensionRow... rows) throws ETSdkException { ETClient client = getClient(); // XXX much of this is copied and pasted from ETSoapObject.delete ETResponse<ETDataExtensionRow> response = new ETResponse<ETDataExtensionRow>(); if (rows == null || rows.length == 0) { return response; } // // Get handle to the SOAP connection: // ETSoapConnection connection = client.getSoapConnection(); // // Automatically refresh the token if necessary: // client.refreshToken(); // // Perform the SOAP delete: // Soap soap = connection.getSoap(); DeleteRequest deleteRequest = new DeleteRequest(); deleteRequest.setOptions(new DeleteOptions()); for (ETDataExtensionRow row : rows) { row.setClient(client); // // We hand construct this one, since all we need // to pass in is the primary key, and we pass it // in to DeleteRequest differently (in the Keys // property) than we received it from // RetrieveRequest (in the Properties property): // DataExtensionObject internalRow = new DataExtensionObject(); DataExtensionObject.Keys keys = new DataExtensionObject.Keys(); ETDataExtensionColumn primaryKeyColumn = getPrimaryKeyColumn(); APIProperty property = new APIProperty(); property.setName(primaryKeyColumn.getName()); property.setValue(row.getColumn(property.getName())); keys.getKey().add(property); internalRow.setName(name); internalRow.setKeys(keys); deleteRequest.getObjects().add(internalRow); } if (logger.isTraceEnabled()) { logger.trace("DeleteRequest:"); logger.trace(" objects = {"); for (APIObject object : deleteRequest.getObjects()) { logger.trace(" " + object); } logger.trace(" }"); } logger.trace("calling soap.delete..."); DeleteResponse deleteResponse = soap.delete(deleteRequest); if (logger.isTraceEnabled()) { logger.trace("DeleteResponse:"); logger.trace(" requestId = " + deleteResponse.getRequestID()); logger.trace(" overallStatus = " + deleteResponse.getOverallStatus()); logger.trace(" results = {"); for (DeleteResult result : deleteResponse.getResults()) { logger.trace(" " + result); } logger.trace(" }"); } response.setRequestId(deleteResponse.getRequestID()); response.setResponseCode(deleteResponse.getOverallStatus()); response.setResponseMessage(deleteResponse.getOverallStatus()); for (DeleteResult deleteResult : deleteResponse.getResults()) { ETResult<ETDataExtensionRow> result = new ETResult<ETDataExtensionRow>(); result.setResponseCode(deleteResult.getStatusCode()); result.setResponseMessage(deleteResult.getStatusMessage()); result.setErrorCode(deleteResult.getErrorCode()); response.addResult(result); } return response; } public ETResponse<ETDataExtensionRow> delete(String filter) throws ETSdkException { // XXX optimize ETResponse<ETDataExtensionRow> response = select(filter); List<ETDataExtensionRow> rows = response.getObjects(); return delete(rows.toArray(new ETDataExtensionRow[rows.size()])); } public ETResponse<ETDataExtensionRow> export(String filter, String file) throws ETSdkException { return export(ETFilter.parse(filter), file); } public ETResponse<ETDataExtensionRow> export(ETFilter filter, String fileName) throws ETSdkException { ETClient client = getClient(); ETResponse<ETDataExtensionRow> response = new ETResponse<ETDataExtensionRow>(); String path = "/data/v1/customobjectdata/export"; StringBuilder stringBuilder = new StringBuilder(path); if (filter != null) { stringBuilder.append("?filter="); stringBuilder.append(toQueryParams(filter)); } path = stringBuilder.toString(); ETRestConnection connection = client.getRestConnection(); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("customerKey", getKey()); jsonObject.addProperty("fileName", fileName); connection.post(path, jsonObject); // XXX handle return value response.setRequestId(connection.getLastCallRequestId()); response.setResponseCode(connection.getLastCallResponseCode()); response.setResponseMessage(connection.getLastCallResponseMessage()); return response; } public void hydrate() throws ETSdkException { ETClient client = getClient(); // // Automatically refresh the token if necessary: // client.refreshToken(); // // Retrieve all columns with CustomerKey = this data extension: // ETFilter filter = new ETFilter(); filter.setProperty("DataExtension.CustomerKey"); filter.setOperator(ETFilter.Operator.EQUALS); filter.addValue(getKey()); ETResponse<ETDataExtensionColumn> response = ETDataExtensionColumn.retrieve(client, filter, null, // page null, // pageSize ETDataExtensionColumn.class, new String[0]); // properties columns = response.getObjects(); // XXX deal with partially loaded DataExtension objects too isHydrated = true; } public static String toQueryParams(ETFilter filter) throws ETSdkException { StringBuilder stringBuilder = new StringBuilder(); ETFilter.Operator operator = filter.getOperator(); switch (operator) { case AND: stringBuilder.append(toQueryParams(filter.getFilters().get(0))); stringBuilder.append("%20"); stringBuilder.append("and"); stringBuilder.append("%20"); stringBuilder.append(toQueryParams(filter.getFilters().get(1))); break; case OR: stringBuilder.append(toQueryParams(filter.getFilters().get(0))); stringBuilder.append("%20"); stringBuilder.append("or"); stringBuilder.append("%20"); stringBuilder.append(toQueryParams(filter.getFilters().get(1))); break; case NOT: stringBuilder.append("not"); stringBuilder.append("%20"); stringBuilder.append(toQueryParams(filter.getFilters().get(0))); break; case EQUALS: stringBuilder.append(filter.getProperty()); stringBuilder.append("%20"); stringBuilder.append("eq"); stringBuilder.append("%20"); stringBuilder.append(toQueryParams(filter.getValue())); break; case NOT_EQUALS: stringBuilder.append(filter.getProperty()); stringBuilder.append("%20"); stringBuilder.append("neq"); stringBuilder.append("%20"); stringBuilder.append(toQueryParams(filter.getValue())); break; case LESS_THAN: stringBuilder.append(filter.getProperty()); stringBuilder.append("%20"); stringBuilder.append("lt"); stringBuilder.append("%20"); stringBuilder.append(toQueryParams(filter.getValue())); break; case LESS_THAN_OR_EQUALS: stringBuilder.append(filter.getProperty()); stringBuilder.append("%20"); stringBuilder.append("lte"); stringBuilder.append("%20"); stringBuilder.append(toQueryParams(filter.getValue())); break; case GREATER_THAN: stringBuilder.append(filter.getProperty()); stringBuilder.append("%20"); stringBuilder.append("gt"); stringBuilder.append("%20"); stringBuilder.append(toQueryParams(filter.getValue())); break; case GREATER_THAN_OR_EQUALS: stringBuilder.append(filter.getProperty()); stringBuilder.append("%20"); stringBuilder.append("gte"); stringBuilder.append("%20"); stringBuilder.append(toQueryParams(filter.getValue())); break; case IS_NULL: stringBuilder.append(filter.getProperty()); stringBuilder.append("%20"); stringBuilder.append("is"); stringBuilder.append("%20"); stringBuilder.append("null"); break; case IS_NOT_NULL: stringBuilder.append(filter.getProperty()); stringBuilder.append("%20"); stringBuilder.append("is"); stringBuilder.append("%20"); stringBuilder.append("not"); stringBuilder.append("%20"); stringBuilder.append("null"); break; case IN: stringBuilder.append(filter.getProperty()); stringBuilder.append("%20"); stringBuilder.append("in"); stringBuilder.append("%20"); stringBuilder.append("("); boolean first = true; for (String value : filter.getValues()) { if (first) { first = false; } else { stringBuilder.append(","); } stringBuilder.append(toQueryParams(value)); } stringBuilder.append(")"); break; case BETWEEN: stringBuilder.append(filter.getProperty()); stringBuilder.append("%20"); stringBuilder.append("between"); stringBuilder.append("%20"); stringBuilder.append(toQueryParams(filter.getValues().get(0))); stringBuilder.append("%20"); stringBuilder.append("and"); stringBuilder.append("%20"); stringBuilder.append(toQueryParams(filter.getValues().get(1))); break; case LIKE: stringBuilder.append(filter.getProperty()); stringBuilder.append("%20"); stringBuilder.append("like"); stringBuilder.append("%20"); stringBuilder.append(toQueryParams(filter.getValue(), true)); break; default: throw new ETSdkException("unsupported operator: " + operator); } return stringBuilder.toString(); } private static String toQueryParams(String value) throws ETSdkException { return toQueryParams(value, false); } private static String toQueryParams(String value, boolean forceQuotes) throws ETSdkException { if (value.equals("")) { forceQuotes = true; } // XXX workaround for FUEL-3348--remove after 02 if (value.contains("-")) { forceQuotes = true; } boolean quotes = forceQuotes; if (!forceQuotes) { // needs quotes in the URL if there's whitespace for (int i = 0; i < value.length(); i++) { if (Character.isWhitespace(value.charAt(i))) { quotes = true; break; } } } String v = null; if (quotes) { v = "'" + value + "'"; } else { v = value.toString(); } try { return URLEncoder.encode(v, "UTF-8"); } catch (UnsupportedEncodingException ex) { throw new ETSdkException("error URL encoding " + v, ex); } } }
Added for completeness: insert(List<ETDataExtension> rows); update(List<ETDataExtension> rows); delete(List<ETDataExtension> rows);
src/main/java/com/exacttarget/fuelsdk/ETDataExtension.java
Added for completeness:
<ide><path>rc/main/java/com/exacttarget/fuelsdk/ETDataExtension.java <ide> "ID", "Fields" <ide> }) <ide> public class ETDataExtension extends ETSoapObject { <add> private static Logger logger = Logger.getLogger(ETDataExtension.class); <add> <ide> @ExternalName("id") <ide> @InternalName("objectID") <ide> private String id = null; <ide> @ExternalName("isTestable") <ide> private Boolean isTestable = null; <ide> <del> private static Logger logger = Logger.getLogger(ETDataExtension.class); <del> <ide> private boolean isHydrated = false; <ide> <ide> public ETDataExtension() {} <ide> public ETResponse<ETDataExtensionRow> insert(ETDataExtensionRow... rows) <ide> throws ETSdkException <ide> { <add> return insert(Arrays.asList(rows)); <add> } <add> <add> public ETResponse<ETDataExtensionRow> insert(List<ETDataExtensionRow> rows) <add> throws ETSdkException <add> { <ide> ETClient client = getClient(); <ide> <ide> for (ETDataExtensionRow row : rows) { <ide> } <ide> } <ide> <del> return client.create(Arrays.asList(rows)); <add> return client.create(rows); <ide> } <ide> <ide> public ETResponse<ETDataExtensionRow> select() <ide> public ETResponse<ETDataExtensionRow> update(ETDataExtensionRow... rows) <ide> throws ETSdkException <ide> { <add> return update(Arrays.asList(rows)); <add> } <add> <add> public ETResponse<ETDataExtensionRow> update(List<ETDataExtensionRow> rows) <add> throws ETSdkException <add> { <ide> ETClient client = getClient(); <ide> <ide> for (ETDataExtensionRow row : rows) { <ide> } <ide> } <ide> <del> return client.update(Arrays.asList(rows)); <add> return client.update(rows); <ide> } <ide> <ide> public ETResponse<ETDataExtensionRow> update(String filter, String... values) <ide> public ETResponse<ETDataExtensionRow> delete(ETDataExtensionRow... rows) <ide> throws ETSdkException <ide> { <add> return delete(Arrays.asList(rows)); <add> } <add> <add> public ETResponse<ETDataExtensionRow> delete(List<ETDataExtensionRow> rows) <add> throws ETSdkException <add> { <ide> ETClient client = getClient(); <ide> <ide> // XXX much of this is copied and pasted from ETSoapObject.delete <ide> <ide> ETResponse<ETDataExtensionRow> response = new ETResponse<ETDataExtensionRow>(); <ide> <del> if (rows == null || rows.length == 0) { <add> if (rows == null || rows.size() == 0) { <ide> return response; <ide> } <ide>
Java
apache-2.0
error: pathspec 'src/test/java/edu/brandeis/cs/steele/wn/browser/PreferencesManagerTest.java' did not match any file(s) known to git
3052914e4fb7725b66ae67ba29236f981c48bd23
1
nezda/yawni,nezda/yawni,nezda/yawni,nezda/yawni,nezda/yawni
package edu.brandeis.cs.steele.wn.browser; import junit.framework.JUnit4TestAdapter; import org.junit.*; import static org.junit.Assert.*; import java.io.*; import java.util.*; import java.util.prefs.*; public class PreferencesManagerTest { /** * Normally <code>ignore</code> this test so we don't clear the user preferences * every time we run this test. */ //@Ignore @Test public void test1() throws BackingStoreException { Preferences prefs = Preferences.userNodeForPackage(PreferencesManagerTest.class); // this invalidates the prefs variable prefs.removeNode(); //prefs.sync(); List kids; //kids = Arrays.asList(prefs.childrenNames()); //System.err.println("test1 before: "+prefs+" kids: "+kids); loadDefaults(); prefs = Preferences.userNodeForPackage(PreferencesManagerTest.class); kids = Arrays.asList(prefs.childrenNames()); //System.err.println("test1 after: "+prefs+" kids: "+kids); //System.err.println("k0: "+prefs.get("k0", "FAILED")); assertEquals("v0", prefs.get("k0", "FAILED")); //System.err.println("TestNode: "+prefs.get("/TestNode/k1", "FAILED")); //System.err.println("TestNode: "+prefs.get("TestKey/k1", "FAILED")); assertEquals("v1", prefs.get("TestKey/k1", "FAILED")); //System.err.println("TestNode: "+prefs.node("TestNode").get("k2", "FAILED")); assertEquals("v2", prefs.node("TestNode").get("k2", "FAILED")); // cannot get a child node AND its value directly with a get() assertFalse("v2".equals(prefs.get("TestNode.k2", "FAILED"))); assertFalse("v2".equals(prefs.get("TestNode/k2", "FAILED"))); assertFalse("v2".equals(prefs.get("/TestNode/k2", "FAILED"))); } static void loadDefaults() { final InputStream is = PreferencesManagerTest.class.getResourceAsStream("testPrefs.xml"); try { Preferences.importPreferences(is); is.close(); } catch(InvalidPreferencesFormatException ipfe) { throw new RuntimeException(ipfe); } catch(IOException ioe) { throw new RuntimeException(ioe); } } }
src/test/java/edu/brandeis/cs/steele/wn/browser/PreferencesManagerTest.java
test/learn preferences git-svn-id: 0f0e769425a95b277772daee6ac27d370147d87f@308 158bccb4-7c0b-4fb3-968f-7c40bf2d9062
src/test/java/edu/brandeis/cs/steele/wn/browser/PreferencesManagerTest.java
test/learn preferences
<ide><path>rc/test/java/edu/brandeis/cs/steele/wn/browser/PreferencesManagerTest.java <add>package edu.brandeis.cs.steele.wn.browser; <add> <add>import junit.framework.JUnit4TestAdapter; <add>import org.junit.*; <add>import static org.junit.Assert.*; <add> <add>import java.io.*; <add>import java.util.*; <add>import java.util.prefs.*; <add> <add>public class PreferencesManagerTest { <add> /** <add> * Normally <code>ignore</code> this test so we don't clear the user preferences <add> * every time we run this test. <add> */ <add> //@Ignore <add> @Test <add> public void test1() throws BackingStoreException { <add> Preferences prefs = Preferences.userNodeForPackage(PreferencesManagerTest.class); <add> // this invalidates the prefs variable <add> prefs.removeNode(); <add> //prefs.sync(); <add> List kids; <add> //kids = Arrays.asList(prefs.childrenNames()); <add> //System.err.println("test1 before: "+prefs+" kids: "+kids); <add> loadDefaults(); <add> prefs = Preferences.userNodeForPackage(PreferencesManagerTest.class); <add> kids = Arrays.asList(prefs.childrenNames()); <add> //System.err.println("test1 after: "+prefs+" kids: "+kids); <add> //System.err.println("k0: "+prefs.get("k0", "FAILED")); <add> assertEquals("v0", prefs.get("k0", "FAILED")); <add> //System.err.println("TestNode: "+prefs.get("/TestNode/k1", "FAILED")); <add> //System.err.println("TestNode: "+prefs.get("TestKey/k1", "FAILED")); <add> assertEquals("v1", prefs.get("TestKey/k1", "FAILED")); <add> //System.err.println("TestNode: "+prefs.node("TestNode").get("k2", "FAILED")); <add> assertEquals("v2", prefs.node("TestNode").get("k2", "FAILED")); <add> // cannot get a child node AND its value directly with a get() <add> assertFalse("v2".equals(prefs.get("TestNode.k2", "FAILED"))); <add> assertFalse("v2".equals(prefs.get("TestNode/k2", "FAILED"))); <add> assertFalse("v2".equals(prefs.get("/TestNode/k2", "FAILED"))); <add> } <add> <add> static void loadDefaults() { <add> final InputStream is = PreferencesManagerTest.class.getResourceAsStream("testPrefs.xml"); <add> try { <add> Preferences.importPreferences(is); <add> is.close(); <add> } catch(InvalidPreferencesFormatException ipfe) { <add> throw new RuntimeException(ipfe); <add> } catch(IOException ioe) { <add> throw new RuntimeException(ioe); <add> } <add> } <add>}
Java
apache-2.0
29421bc12f5d549068ab9a030e8e2d9b958989a1
0
sotorrent/so-posthistory-extractor
package de.unitrier.st.soposthistory.gt; import de.unitrier.st.soposthistory.version.PostVersionList; import org.apache.commons.csv.*; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.function.BiFunction; import java.util.logging.Logger; import static de.unitrier.st.soposthistory.util.Util.getClassLogger; // TODO: move to metrics comparison project public class MetricComparisonManager { private static Logger logger = null; private static final CSVFormat csvFormatPostIds; private static final CSVFormat csvFormatMetricComparison; private String name; private Set<Integer> postIds; private Map<Integer, List<Integer>> postHistoryIds; private Map<Integer, PostGroundTruth> postGroundTruth; private Map<Integer, PostVersionList> postVersionLists; private List<BiFunction<String, String, Double>> similarityMetrics; private List<Double> similarityThresholds; private List<MetricComparison> metricComparisons; static { // configure logger try { logger = getClassLogger(MetricComparisonManager.class, false); } catch (IOException e) { e.printStackTrace(); } // configure CSV format for list of PostIds csvFormatPostIds = CSVFormat.DEFAULT .withHeader("PostId", "PostTypeId", "VersionCount") .withDelimiter(';') .withQuote('"') .withQuoteMode(QuoteMode.MINIMAL) .withEscape('\\') .withFirstRecordAsHeader(); // configure CSV format for metric comparison results csvFormatMetricComparison = CSVFormat.DEFAULT .withHeader("Sample", "Metric", "Threshold", "PostId", "PostHistoryId", "RuntimeText", "TruePositivesText", "TrueNegativesText", "FalsePositivesText", "FalseNegativesText", "RuntimeCode", "TruePositivesCode", "TrueNegativesCode", "FalsePositivesCode", "FalseNegativesCode") .withDelimiter(';') .withQuote('"') .withQuoteMode(QuoteMode.MINIMAL) .withEscape('\\') .withNullString("null") .withFirstRecordAsHeader(); } private MetricComparisonManager(String name) { this.name = name; postIds = new HashSet<>(); postHistoryIds = new HashMap<>(); postGroundTruth = new HashMap<>(); postVersionLists = new HashMap<>(); similarityMetrics = new LinkedList<>(); similarityThresholds = new LinkedList<>(); metricComparisons = new LinkedList<>(); addSimilarityMetrics(); addSimilarityThresholds(); } public static MetricComparisonManager create(String name, Path postIdPath, Path postHistoryPath, Path groundTruthPath) { // ensure that input file exists (directories are tested in read methods) if (!Files.exists(postIdPath) || Files.isDirectory(postIdPath)) { throw new IllegalArgumentException("File not found: " + postIdPath); } MetricComparisonManager manager = new MetricComparisonManager(name); try (CSVParser csvParser = new CSVParser(new FileReader(postIdPath.toFile()), csvFormatPostIds)) { logger.info("Reading PostIds from CSV file " + postIdPath.toFile().toString() + " ..."); for (CSVRecord currentRecord : csvParser) { int postId = Integer.parseInt(currentRecord.get("PostId")); int postTypeId = Integer.parseInt(currentRecord.get("PostTypeId")); int versionCount = Integer.parseInt(currentRecord.get("VersionCount")); // add post id to set manager.postIds.add(postId); // read post version list PostVersionList postVersionList = PostVersionList.readFromCSV( postHistoryPath, postId, postTypeId, false ); if (postVersionList.size() != versionCount) { throw new IllegalArgumentException("Version count expected to be " + versionCount + ", but was " + postVersionList.size() ); } manager.postVersionLists.put(postId, postVersionList); manager.postHistoryIds.put(postId, postVersionList.getPostHistoryIds()); // read ground truth PostGroundTruth postGroundTruth = PostGroundTruth.readFromCSV(groundTruthPath, postId); if (postGroundTruth.getPossibleConnections() != postVersionList.getPossibleConnections()) { throw new IllegalArgumentException("Number of possible connections in ground truth is different " + "from number of possible connections in post history."); } manager.postGroundTruth.put(postId, postGroundTruth); } } catch (IOException e) { e.printStackTrace(); } return manager; } public void compareMetrics() { prepareComparison(); for (MetricComparison metricComparison : metricComparisons) { metricComparison.start(); } } private void prepareComparison() { for (int postId : postIds) { for (BiFunction<String, String, Double> similarityMetric : similarityMetrics) { for (double similarityThreshold : similarityThresholds) { MetricComparison metricComparison = new MetricComparison( postId, postVersionLists.get(postId), postGroundTruth.get(postId), similarityMetric, similarityThreshold ); metricComparisons.add(metricComparison); } } } } public void writeToCSV(Path outputDir) { if (!Files.exists(outputDir) || !Files.isDirectory(outputDir)) { throw new IllegalArgumentException("Invalid output directory: " + outputDir); } File outputFile = Paths.get(outputDir.toString(), name + ".csv").toFile(); if (outputFile.exists()) { if (!outputFile.delete()) { throw new IllegalStateException("Error while deleting output file: " + outputFile); } } // TODO: Test CSV export // write metric comparison results logger.info("Writing metric comparison results to CSV file " + outputFile.getName() + " ..."); try (CSVPrinter csvPrinter = new CSVPrinter(new FileWriter(outputFile), csvFormatMetricComparison)) { // header is automatically written for (MetricComparison metricComparison : metricComparisons) { int postId = metricComparison.getPostId(); List<Integer> postHistoryIdsForPost = postHistoryIds.get(postId); for (int postHistoryId : postHistoryIdsForPost) { csvPrinter.printRecord( name, // TODO: This is not correct, we need the method name (Sebastian: I'll try to find a solution) metricComparison.getSimilarityMetric().getClass().getSimpleName(), metricComparison.getSimilarityThreshold(), postId, postHistoryId, metricComparison.getRuntimeText(), metricComparison.getTruePositivesText().get(postHistoryId), metricComparison.getTrueNegativesText().get(postHistoryId), metricComparison.getFalsePositivesText().get(postHistoryId), metricComparison.getFalseNegativesText().get(postHistoryId), metricComparison.getRuntimeCode(), metricComparison.getTruePositivesCode().get(postHistoryId), metricComparison.getTrueNegativesCode().get(postHistoryId), metricComparison.getFalsePositivesCode().get(postHistoryId), metricComparison.getFalseNegativesCode().get(postHistoryId) ); } } } catch (IOException e) { e.printStackTrace(); } } public Map<Integer, PostGroundTruth> getPostGroundTruth() { return postGroundTruth; } public Map<Integer, PostVersionList> getPostVersionLists() { return postVersionLists; } private void addSimilarityThresholds() { for (double threshold=0.3; threshold<0.99; threshold+=0.1) { similarityThresholds.add(threshold); } } private void addSimilarityMetrics() { // ****** Edit based ***** similarityMetrics.add(de.unitrier.st.stringsimilarity.edit.Variants::levenshtein); similarityMetrics.add(de.unitrier.st.stringsimilarity.edit.Variants::levenshteinNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.edit.Variants::damerauLevenshtein); similarityMetrics.add(de.unitrier.st.stringsimilarity.edit.Variants::damerauLevenshteinNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.edit.Variants::optimalAlignment); similarityMetrics.add(de.unitrier.st.stringsimilarity.edit.Variants::optimalAlignmentNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.edit.Variants::longestCommonSubsequence); similarityMetrics.add(de.unitrier.st.stringsimilarity.edit.Variants::longestCommonSubsequenceNormalized); // ****** Fingerprint based ***** similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingTwoGramJaccard); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingThreeGramJaccard); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFourGramJaccard); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFiveGramJaccard); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingTwoGramJaccardNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingThreeGramJaccardNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFourGramJaccardNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFiveGramJaccardNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingTwoGramDice); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingThreeGramDice); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFourGramDice); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFiveGramDice); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingTwoGramDiceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingThreeGramDiceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFourGramDiceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFiveGramDiceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingTwoGramOverlap); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingThreeGramOverlap); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFourGramOverlap); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFiveGramOverlap); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingTwoGramOverlapNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingThreeGramOverlapNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFourGramOverlapNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFiveGramOverlapNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingTwoGramLongestCommonSubsequence); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingThreeGramLongestCommonSubsequence); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFourGramLongestCommonSubsequence); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFiveGramLongestCommonSubsequence); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingTwoGramLongestCommonSubsequenceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingThreeGramLongestCommonSubsequenceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFourGramLongestCommonSubsequenceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFiveGramLongestCommonSubsequenceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingTwoGramOptimalAlignment); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingThreeGramOptimalAlignment); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFourGramOptimalAlignment); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFiveGramOptimalAlignment); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingTwoGramOptimalAlignmentNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingThreeGramOptimalAlignmentNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFourGramOptimalAlignmentNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFiveGramOptimalAlignmentNormalized); // ****** Profile based ***** similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineTokenNormalizedBool); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineTokenNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineTokenNormalizedNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineTwoGramNormalizedBool); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineThreeGramNormalizedBool); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineFourGramNormalizedBool); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineFiveGramNormalizedBool); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineTwoGramNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineThreeGramNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineFourGramNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineFiveGramNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineTwoGramNormalizedNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineThreeGramNormalizedNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineFourGramNormalizedNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineFiveGramNormalizedNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineTwoShingleNormalizedBool); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineThreeShingleNormalizedBool); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineTwoShingleNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineThreeShingleNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineTwoShingleNormalizedNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineThreeShingleNormalizedNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::manhattanTokenNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::manhattanTwoGramNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::manhattanThreeGramNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::manhattanFourGramNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::manhattanFiveGramNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::manhattanTwoShingleNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::manhattanThreeShingleNormalized); // ****** Set based ***** similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::tokenJaccard); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::tokenJaccardNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoGramJaccard); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeGramJaccard); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fourGramJaccard); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fiveGramJaccard); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoGramJaccardNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeGramJaccardNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fourGramJaccardNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fiveGramJaccardNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoGramJaccardNormalizedPadding); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeGramJaccardNormalizedPadding); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fourGramJaccardNormalizedPadding); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fiveGramJaccardNormalizedPadding); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoShingleJaccard); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeShingleJaccard); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoShingleJaccardNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeShingleJaccardNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::tokenDice); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::tokenDiceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoGramDice); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeGramDice); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fourGramDice); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fiveGramDice); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoGramDiceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeGramDiceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fourGramDiceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fiveGramDiceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoGramDiceNormalizedPadding); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeGramDiceNormalizedPadding); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fourGramDiceNormalizedPadding); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fiveGramDiceNormalizedPadding); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoShingleDice); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeShingleDice); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoShingleDiceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeShingleDiceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::tokenOverlap); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::tokenOverlapNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoGramOverlap); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeGramOverlap); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fourGramOverlap); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fiveGramOverlap); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoGramOverlapNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeGramOverlapNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fourGramOverlapNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fiveGramOverlapNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoGramOverlapNormalizedPadding); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeGramOverlapNormalizedPadding); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fourGramOverlapNormalizedPadding); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fiveGramOverlapNormalizedPadding); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoShingleOverlap); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeShingleOverlap); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoShingleOverlapNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeShingleOverlapNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoGramSimilarityKondrak05); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeGramSimilarityKondrak05); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fourGramSimilarityKondrak05); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fiveGramSimilarityKondrak05); } }
src/de/unitrier/st/soposthistory/gt/MetricComparisonManager.java
package de.unitrier.st.soposthistory.gt; import de.unitrier.st.soposthistory.version.PostVersionList; import org.apache.commons.csv.*; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.function.BiFunction; import java.util.logging.Logger; import static de.unitrier.st.soposthistory.util.Util.getClassLogger; // TODO: move to metrics comparison project public class MetricComparisonManager { private static Logger logger = null; private static final CSVFormat csvFormatPostIds; private static final CSVFormat csvFormatMetricComparison; private String name; private Set<Integer> postIds; private Map<Integer, List<Integer>> postHistoryIds; private Map<Integer, PostGroundTruth> postGroundTruth; private Map<Integer, PostVersionList> postVersionLists; private List<BiFunction<String, String, Double>> similarityMetrics; private List<Double> similarityThresholds; private List<MetricComparison> metricComparisons; static { // configure logger try { logger = getClassLogger(MetricComparisonManager.class, false); } catch (IOException e) { e.printStackTrace(); } // configure CSV format for list of PostIds csvFormatPostIds = CSVFormat.DEFAULT .withHeader("PostId", "PostTypeId", "VersionCount") .withDelimiter(';') .withQuote('"') .withQuoteMode(QuoteMode.MINIMAL) .withEscape('\\') .withFirstRecordAsHeader(); // configure CSV format for metric comparison results csvFormatMetricComparison = CSVFormat.DEFAULT .withHeader("Sample", "Metric", "Threshold", "PostId", "PostHistoryId", "RuntimeText", "TruePositivesText", "TrueNegativesText", "FalsePositivesText", "FalseNegativesText", "RuntimeCode", "TruePositivesCode", "TrueNegativesCode", "FalsePositivesCode", "FalseNegativesCode") .withDelimiter(';') .withQuote('"') .withQuoteMode(QuoteMode.MINIMAL) .withEscape('\\') .withNullString("null") .withFirstRecordAsHeader(); } private MetricComparisonManager(String name) { this.name = name; postIds = new HashSet<>(); postHistoryIds = new HashMap<>(); postGroundTruth = new HashMap<>(); postVersionLists = new HashMap<>(); similarityMetrics = new LinkedList<>(); similarityThresholds = new LinkedList<>(); metricComparisons = new LinkedList<>(); addSimilarityMetrics(); addSimilarityThresholds(); } public static MetricComparisonManager create(String name, Path postIdPath, Path postHistoryPath, Path groundTruthPath) { // ensure that input file exists (directories are tested in read methods) if (!Files.exists(postIdPath) || Files.isDirectory(postIdPath)) { throw new IllegalArgumentException("File not found: " + postIdPath); } MetricComparisonManager manager = new MetricComparisonManager(name); try (CSVParser csvParser = new CSVParser(new FileReader(postIdPath.toFile()), csvFormatPostIds)) { logger.info("Reading PostIds from CSV file " + postIdPath.toFile().toString() + " ..."); for (CSVRecord currentRecord : csvParser) { int postId = Integer.parseInt(currentRecord.get("PostId")); int postTypeId = Integer.parseInt(currentRecord.get("PostTypeId")); int versionCount = Integer.parseInt(currentRecord.get("VersionCount")); // add post id to set manager.postIds.add(postId); // read post version list PostVersionList postVersionList = PostVersionList.readFromCSV( postHistoryPath, postId, postTypeId, false ); if (postVersionList.size() != versionCount) { throw new IllegalArgumentException("Version count expected to be " + versionCount + ", but was " + postVersionList.size() ); } manager.postVersionLists.put(postId, postVersionList); manager.postHistoryIds.put(postId, postVersionList.getPostHistoryIds()); // read ground truth PostGroundTruth postGroundTruth = PostGroundTruth.readFromCSV(groundTruthPath, postId); if (postGroundTruth.getPossibleConnections() != postVersionList.getPossibleConnections()) { throw new IllegalArgumentException("Number of possible connections in ground truth is different " + "from number of possible connections in post history."); } manager.postGroundTruth.put(postId, postGroundTruth); } } catch (IOException e) { e.printStackTrace(); } return manager; } public void compareMetrics() { prepareComparison(); for (MetricComparison metricComparison : metricComparisons) { metricComparison.start(); } } private void prepareComparison() { for (int postId : postIds) { for (BiFunction<String, String, Double> similarityMetric : similarityMetrics) { for (double similarityThreshold : similarityThresholds) { MetricComparison metricComparison = new MetricComparison( postId, postVersionLists.get(postId), postGroundTruth.get(postId), similarityMetric, similarityThreshold ); metricComparisons.add(metricComparison); } } } } public void writeToCSV(Path outputDir) { if (!Files.exists(outputDir) || !Files.isDirectory(outputDir)) { throw new IllegalArgumentException("Invalid output directory: " + outputDir); } File outputFile = Paths.get(outputDir.toString(), name + ".csv").toFile(); if (outputFile.exists()) { if (!outputFile.delete()) { throw new IllegalStateException("Error while deleting output file: " + outputFile); } } // TODO: Test CSV export // write metric comparison results logger.info("Writing metric comparison results to CSV file " + outputFile.getName() + " ..."); try (CSVPrinter csvPrinter = new CSVPrinter(new FileWriter(outputFile), csvFormatMetricComparison)) { // header is automatically written for (MetricComparison metricComparison : metricComparisons) { int postId = metricComparison.getPostId(); List<Integer> postHistoryIdsForPost = postHistoryIds.get(postId); for (int postHistoryId : postHistoryIdsForPost) { csvPrinter.printRecord( name, metricComparison.getSimilarityMetric().getClass().getSimpleName(), metricComparison.getSimilarityThreshold(), postId, postHistoryId, metricComparison.getRuntimeText(), metricComparison.getTruePositivesText().get(postHistoryId), metricComparison.getTrueNegativesText().get(postHistoryId), metricComparison.getFalsePositivesText().get(postHistoryId), metricComparison.getFalseNegativesText().get(postHistoryId), metricComparison.getRuntimeCode(), metricComparison.getTruePositivesCode().get(postHistoryId), metricComparison.getTrueNegativesCode().get(postHistoryId), metricComparison.getFalsePositivesCode().get(postHistoryId), metricComparison.getFalseNegativesCode().get(postHistoryId) ); } } } catch (IOException e) { e.printStackTrace(); } } public Map<Integer, PostGroundTruth> getPostGroundTruth() { return postGroundTruth; } public Map<Integer, PostVersionList> getPostVersionLists() { return postVersionLists; } private void addSimilarityThresholds() { for (double threshold=0.3; threshold<0.99; threshold+=0.1) { similarityThresholds.add(threshold); } } private void addSimilarityMetrics() { // ****** Edit based ***** similarityMetrics.add(de.unitrier.st.stringsimilarity.edit.Variants::levenshtein); similarityMetrics.add(de.unitrier.st.stringsimilarity.edit.Variants::levenshteinNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.edit.Variants::damerauLevenshtein); similarityMetrics.add(de.unitrier.st.stringsimilarity.edit.Variants::damerauLevenshteinNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.edit.Variants::optimalAlignment); similarityMetrics.add(de.unitrier.st.stringsimilarity.edit.Variants::optimalAlignmentNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.edit.Variants::longestCommonSubsequence); similarityMetrics.add(de.unitrier.st.stringsimilarity.edit.Variants::longestCommonSubsequenceNormalized); // ****** Fingerprint based ***** similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingTwoGramJaccard); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingThreeGramJaccard); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFourGramJaccard); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFiveGramJaccard); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingTwoGramJaccardNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingThreeGramJaccardNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFourGramJaccardNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFiveGramJaccardNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingTwoGramDice); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingThreeGramDice); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFourGramDice); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFiveGramDice); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingTwoGramDiceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingThreeGramDiceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFourGramDiceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFiveGramDiceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingTwoGramOverlap); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingThreeGramOverlap); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFourGramOverlap); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFiveGramOverlap); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingTwoGramOverlapNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingThreeGramOverlapNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFourGramOverlapNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFiveGramOverlapNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingTwoGramLongestCommonSubsequence); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingThreeGramLongestCommonSubsequence); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFourGramLongestCommonSubsequence); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFiveGramLongestCommonSubsequence); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingTwoGramLongestCommonSubsequenceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingThreeGramLongestCommonSubsequenceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFourGramLongestCommonSubsequenceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFiveGramLongestCommonSubsequenceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingTwoGramOptimalAlignment); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingThreeGramOptimalAlignment); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFourGramOptimalAlignment); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFiveGramOptimalAlignment); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingTwoGramOptimalAlignmentNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingThreeGramOptimalAlignmentNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFourGramOptimalAlignmentNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.fingerprint.Variants::winnowingFiveGramOptimalAlignmentNormalized); // ****** Profile based ***** similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineTokenNormalizedBool); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineTokenNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineTokenNormalizedNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineTwoGramNormalizedBool); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineThreeGramNormalizedBool); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineFourGramNormalizedBool); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineFiveGramNormalizedBool); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineTwoGramNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineThreeGramNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineFourGramNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineFiveGramNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineTwoGramNormalizedNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineThreeGramNormalizedNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineFourGramNormalizedNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineFiveGramNormalizedNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineTwoShingleNormalizedBool); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineThreeShingleNormalizedBool); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineTwoShingleNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineThreeShingleNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineTwoShingleNormalizedNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::cosineThreeShingleNormalizedNormalizedTermFrequency); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::manhattanTokenNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::manhattanTwoGramNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::manhattanThreeGramNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::manhattanFourGramNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::manhattanFiveGramNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::manhattanTwoShingleNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.profile.Variants::manhattanThreeShingleNormalized); // ****** Set based ***** similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::tokenJaccard); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::tokenJaccardNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoGramJaccard); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeGramJaccard); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fourGramJaccard); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fiveGramJaccard); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoGramJaccardNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeGramJaccardNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fourGramJaccardNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fiveGramJaccardNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoGramJaccardNormalizedPadding); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeGramJaccardNormalizedPadding); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fourGramJaccardNormalizedPadding); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fiveGramJaccardNormalizedPadding); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoShingleJaccard); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeShingleJaccard); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoShingleJaccardNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeShingleJaccardNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::tokenDice); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::tokenDiceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoGramDice); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeGramDice); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fourGramDice); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fiveGramDice); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoGramDiceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeGramDiceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fourGramDiceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fiveGramDiceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoGramDiceNormalizedPadding); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeGramDiceNormalizedPadding); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fourGramDiceNormalizedPadding); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fiveGramDiceNormalizedPadding); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoShingleDice); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeShingleDice); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoShingleDiceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeShingleDiceNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::tokenOverlap); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::tokenOverlapNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoGramOverlap); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeGramOverlap); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fourGramOverlap); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fiveGramOverlap); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoGramOverlapNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeGramOverlapNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fourGramOverlapNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fiveGramOverlapNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoGramOverlapNormalizedPadding); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeGramOverlapNormalizedPadding); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fourGramOverlapNormalizedPadding); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fiveGramOverlapNormalizedPadding); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoShingleOverlap); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeShingleOverlap); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoShingleOverlapNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeShingleOverlapNormalized); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::twoGramSimilarityKondrak05); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::threeGramSimilarityKondrak05); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fourGramSimilarityKondrak05); similarityMetrics.add(de.unitrier.st.stringsimilarity.set.Variants::fiveGramSimilarityKondrak05); } }
Add TODO
src/de/unitrier/st/soposthistory/gt/MetricComparisonManager.java
Add TODO
<ide><path>rc/de/unitrier/st/soposthistory/gt/MetricComparisonManager.java <ide> for (int postHistoryId : postHistoryIdsForPost) { <ide> csvPrinter.printRecord( <ide> name, <add> // TODO: This is not correct, we need the method name (Sebastian: I'll try to find a solution) <ide> metricComparison.getSimilarityMetric().getClass().getSimpleName(), <ide> metricComparison.getSimilarityThreshold(), <ide> postId,
JavaScript
mit
2d36db534de2f7895dafa4085fe07387db7cb81d
0
lumpy-brontosaurus/chatnow,Ronll/chatnow,Ronll/chatnow,joksina/chatnow,joksina/chatnow,lumpy-brontosaurus/chatnow
var app = angular.module('geoChat', ['ui.router', 'ngCookies', 'ngResource', 'ngSanitize','btford.socket-io']) .value('nickName', username); var access_token; var username; function statusChangeCallback(response) { if (response.status === 'connected') { FB.api('/me', function(response) { console.log("here"); console.log(JSON.stringify(response)); username = response.name; }); } } function checkLoginState() { FB.getLoginStatus(function(response) { statusChangeCallback(response); }); } window.fbAsyncInit = function() { FB.init({ appId : '438180583036734', status : true, xfbml : true, // parse social plugins on this page version : 'v2.2' // use version 2.2 }); FB.getLoginStatus(function(response) { statusChangeCallback(response); }); FB.Event.subscribe('auth.login', function(resp) { window.location = 'https://chat-geo.herokuapp.com/#/home'; }); FB.Event.subscribe('auth.logout', function(resp) { window.location = 'https://chat-geo.herokuapp.com/'; }); }; // Load the SDK asynchronously (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)){ return; } js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); app.controller('AuthCtrl', ["$scope", "$location", function ($scope, $location) { $scope.FBLogin = function(){ FB.login(function(response) { if (response.authResponse) { // $scope.access_token = FB.getAuthResponse()['accessToken']; // console.log('Access Token = '+ $scope.access_token); console.log('Welcome! Fetching your information... '); FB.api('/me', function(response) { console.log('Good to see you, ' + response.name + '.'); // console.log(response); var accessToken = FB.getAuthResponse().accessToken; console.log(accessToken); }); // $scope.$apply(); } else { console.log('User cancelled login or did not fully authorize.'); } }, {scope: ''}); }; $scope.FBFriends = function() { FB.api('/me/friends?access_token=CAACEdEose0cBAL5TMM7iOge5JauOU5JlAJl6Pt1qzMlkmiwxJo9RezXcY6zWRXslYd1AWZBf43WvULwzg9WKdbGgHL8FqqvOJ8J4582s76sXcoiCT8nZATMSduEFAywHlmZAzoecHNB6b83Wh69GfA3FKDQfAZC9b0faKYLSZAQ8IH4bhetuaoqSV6uTaBZCoxsPDunmtsrAZDZD', function(response) { $scope.$apply(function() { $scope.myFriends = response.data; console.log(response); username = response.name; }); }); }; $scope.FBLogout = function(){ FB.logout(function(response) { console.log("You are logged out"); }); }; }]); app.controller('SocketCtrl', function ($log, $scope, chatSocket, messageFormatter, nickName) { if(statusChangeCallback(response).authResponse.id !== undefined){ FB.api('/me', function(response) { console.log('Good to see you, ' + response.name + '.'); var accessToken = FB.getAuthResponse().accessToken; console.log(accessToken); username = response.name; }); } $scope.nickName = nickName; $scope.messageLog = ''; $scope.sendMessage = function() { var match = $scope.message.match('^\/nick (.*)'); if (angular.isDefined(match) && angular.isArray(match) && match.length === 2) { var oldNick = nickName; nickName = match[1]; $scope.message = ''; $scope.messageLog = messageFormatter(new Date(), nickName, 'nickname changed - from ' + oldNick + ' to ' + nickName + '!') + $scope.messageLog; $scope.nickName = nickName; } $log.debug('sending message', $scope.message); chatSocket.emit('message', nickName, $scope.message); $scope.message = ''; } $scope.$on('socket:broadcast', function(event, data) { $log.debug('got a message', event.name); if (!data.payload) { $log.error('invalid message', 'event', event, 'data', JSON.stringify(data)); return; } $scope.$apply(function() { $scope.messageLog = $scope.messageLog + messageFormatter(new Date(), data.source, data.payload); }); }); }) app.factory('chatSocket', function (socketFactory) { var socket = socketFactory(); socket.forward('broadcast'); return socket; }); app.value('messageFormatter', function(date, nick, message) { return date.toLocaleTimeString() + ' - ' + nick + ' - ' + message + '\n'; }); app.config(function($stateProvider, $urlRouterProvider){ $urlRouterProvider.otherwise('/'); $stateProvider .state('login', { url: '/', templateUrl: 'app/auth/login.html', controller: 'SocketCtrl' }) $stateProvider .state('home', { url: '/home', templateUrl: 'app/chat/chat.html', controller: 'SocketCtrl' }) });
client/app/app.js
var app = angular.module('geoChat', ['ui.router', 'ngCookies', 'ngResource', 'ngSanitize','btford.socket-io']) .value('nickName', username); var access_token; var username; function statusChangeCallback(response) { if (response.status === 'connected') { FB.api('/me', function(response) { console.log("here"); console.log(JSON.stringify(response)); username = response.name; }); } } function checkLoginState() { FB.getLoginStatus(function(response) { statusChangeCallback(response); }); } window.fbAsyncInit = function() { FB.init({ appId : '438180583036734', status : true, xfbml : true, // parse social plugins on this page version : 'v2.2' // use version 2.2 }); FB.getLoginStatus(function(response) { statusChangeCallback(response); }); FB.Event.subscribe('auth.login', function(resp) { window.location = 'https://chat-geo.herokuapp.com/#/home'; }); FB.Event.subscribe('auth.logout', function(resp) { window.location = 'https://chat-geo.herokuapp.com/'; }); }; // Load the SDK asynchronously (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)){ return; } js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); app.controller('AuthCtrl', ["$scope", "$location", function ($scope, $location) { $scope.FBLogin = function(){ FB.login(function(response) { if (response.authResponse) { // $scope.access_token = FB.getAuthResponse()['accessToken']; // console.log('Access Token = '+ $scope.access_token); console.log('Welcome! Fetching your information... '); FB.api('/me', function(response) { console.log('Good to see you, ' + response.name + '.'); // console.log(response); var accessToken = FB.getAuthResponse().accessToken; console.log(accessToken); }); // $scope.$apply(); } else { console.log('User cancelled login or did not fully authorize.'); } }, {scope: ''}); }; $scope.FBFriends = function() { FB.api('/me/friends?access_token=CAACEdEose0cBAL5TMM7iOge5JauOU5JlAJl6Pt1qzMlkmiwxJo9RezXcY6zWRXslYd1AWZBf43WvULwzg9WKdbGgHL8FqqvOJ8J4582s76sXcoiCT8nZATMSduEFAywHlmZAzoecHNB6b83Wh69GfA3FKDQfAZC9b0faKYLSZAQ8IH4bhetuaoqSV6uTaBZCoxsPDunmtsrAZDZD', function(response) { $scope.$apply(function() { $scope.myFriends = response.data; console.log(response); username = response.name; }); }); }; $scope.FBLogout = function(){ FB.logout(function(response) { console.log("You are logged out"); }); }; }]); app.controller('SocketCtrl', function ($log, $scope, chatSocket, messageFormatter, nickName) { if(statusChangeCallback(response).authResponse.id !== undefined){ FB.api('/me', function(response) { console.log('Good to see you, ' + response.name + '.'); var accessToken = FB.getAuthResponse().accessToken; console.log(accessToken); username = response.name; }); } $scope.nickName = username; $scope.messageLog = ''; $scope.sendMessage = function() { var match = $scope.message.match('^\/nick (.*)'); if (angular.isDefined(match) && angular.isArray(match) && match.length === 2) { var oldNick = nickName; nickName = match[1]; $scope.message = ''; $scope.messageLog = messageFormatter(new Date(), nickName, 'nickname changed - from ' + oldNick + ' to ' + nickName + '!') + $scope.messageLog; $scope.nickName = nickName; } $log.debug('sending message', $scope.message); chatSocket.emit('message', nickName, $scope.message); $scope.message = ''; } $scope.$on('socket:broadcast', function(event, data) { $log.debug('got a message', event.name); if (!data.payload) { $log.error('invalid message', 'event', event, 'data', JSON.stringify(data)); return; } $scope.$apply(function() { $scope.messageLog = $scope.messageLog + messageFormatter(new Date(), data.source, data.payload); }); }); }) app.factory('chatSocket', function (socketFactory) { var socket = socketFactory(); socket.forward('broadcast'); return socket; }); app.value('messageFormatter', function(date, nick, message) { return date.toLocaleTimeString() + ' - ' + nick + ' - ' + message + '\n'; }); app.config(function($stateProvider, $urlRouterProvider){ $urlRouterProvider.otherwise('/'); $stateProvider .state('login', { url: '/', templateUrl: 'app/auth/login.html', controller: 'SocketCtrl' }) $stateProvider .state('home', { url: '/home', templateUrl: 'app/chat/chat.html', controller: 'SocketCtrl' }) });
some changes
client/app/app.js
some changes
<ide><path>lient/app/app.js <ide> username = response.name; <ide> }); <ide> } <del> $scope.nickName = username; <add> $scope.nickName = nickName; <ide> $scope.messageLog = ''; <ide> $scope.sendMessage = function() { <ide> var match = $scope.message.match('^\/nick (.*)');
Java
apache-2.0
f02c4f2cd4550b63920b7021f0a35e9f0aba7acd
0
tetrapods/core,tetrapods/core,tetrapods/core,tetrapods/core,tetrapods/core
package io.tetrapod.core; import static io.tetrapod.protocol.core.Core.*; import static io.tetrapod.protocol.core.CoreContract.*; import io.netty.buffer.ByteBuf; import io.netty.channel.*; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.util.ReferenceCountUtil; import io.tetrapod.core.rpc.*; import io.tetrapod.core.rpc.Error; import io.tetrapod.core.serialize.DataSource; import io.tetrapod.core.serialize.StructureAdapter; import io.tetrapod.core.serialize.datasources.ByteBufDataSource; import io.tetrapod.protocol.core.*; import java.io.IOException; import org.slf4j.*; /** * Manages a session between two tetrapods */ public class WireSession extends Session { private static final Logger logger = LoggerFactory.getLogger(WireSession.class); private static final int WIRE_VERSION = 1; private static final int WIRE_OPTIONS = 0x00000000; private static final long LOADED_TIME = System.currentTimeMillis(); private boolean needsHandshake = true; public WireSession(SocketChannel channel, WireSession.Helper helper) { super(channel, helper); channel.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024 * 1024, 0, 4, 0, 0)); channel.pipeline().addLast(this); } private synchronized boolean needsHandshake() { return needsHandshake; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { lastHeardFrom.set(System.currentTimeMillis()); try { final ByteBuf in = (ByteBuf) msg; final int len = in.readInt() - 1; final byte envelope = in.readByte(); logger.trace("{} channelRead {}", this, envelope); if (needsHandshake()) { readHandshake(in, envelope); fireSessionStartEvent(); } else { read(in, len, envelope); } } finally { ReferenceCountUtil.release(msg); } } private void read(final ByteBuf in, final int len, final byte envelope) throws IOException { final long t0 = System.currentTimeMillis(); assert (len == in.readableBytes()); logger.trace("Read message {} with {} bytes", envelope, len); switch (envelope) { case ENVELOPE_REQUEST: readRequest(in); break; case ENVELOPE_RESPONSE: readResponse(in); break; case ENVELOPE_MESSAGE: case ENVELOPE_BROADCAST: readMessage(in, envelope == ENVELOPE_BROADCAST); break; case ENVELOPE_PING: if (theirType == TYPE_SERVICE || theirType == TYPE_TETRAPOD) logger.trace("{} GOT PING, SENDING PONG", this); sendPong(); break; case ENVELOPE_PONG: if (theirType == TYPE_SERVICE || theirType == TYPE_TETRAPOD) logger.trace("{} GOT PONG", this); break; default: logger.error("{} Unexpected Envelope Type {}", this, envelope); close(); } if (System.currentTimeMillis() - t0 > 500) { if (t0 - LOADED_TIME < 30000) { logger.info("Something blocked in read() for {} ms env={}", System.currentTimeMillis() - t0, envelope); } else { logger.warn("Something blocked in read() for {} ms env={}", System.currentTimeMillis() - t0, envelope); } } } private void readHandshake(final ByteBuf in, final byte envelope) throws IOException { if (envelope != ENVELOPE_HANDSHAKE) { throw new IOException(this + "handshake not valid"); } int theirVersion = in.readInt(); @SuppressWarnings("unused") int theirOptions = in.readInt(); if (theirVersion != WIRE_VERSION) { throw new IOException(this + "handshake version does not match " + theirVersion); } logger.trace("{} handshake succeeded", this); synchronized (this) { needsHandshake = false; } } private void readResponse(final ByteBuf in) throws IOException { final ByteBufDataSource reader = new ByteBufDataSource(in); final ResponseHeader header = new ResponseHeader(); boolean logged = false; header.read(reader); final Async async = pendingRequests.remove(header.requestId); if (async != null) { // Dispatches response to ourselves if we sent the request (fromId == myId) or // if fromId is UNADRESSED this handles the edge case where we are registering // ourselves and so did not yet have an entityId if ((async.header.fromId == myId || async.header.fromId == Core.UNADDRESSED) && (async.request != null || async.hasHandler())) { final Structure res = StructureFactory.make(header.contractId, header.structId); if (res != null) { res.read(reader); if (!commsLogIgnore(header.structId)) logged = commsLog("%s [%d] <- %s", this, header.requestId, res.dump()); getDispatcher().dispatch(() -> { if (res instanceof StructureAdapter) { async.setResponse(new ResponseAdapter(res)); } else { async.setResponse((Response) res); } }); } else { logger.warn("{} Could not find response structure {}", this, header.structId); } } else if (relayHandler != null) { // HACK: Expensive, for better debug logs. Response res = null; // if (logger.isDebugEnabled() && header.structId == 1) { // res = (Response) StructureFactory.make(async.header.contractId, header.structId); // if (res != null) { // int mark = in.readerIndex(); // res.read(reader); // in.readerIndex(mark); // } // } if (!commsLogIgnore(header.structId)) logged = commsLog("%s [%d] <- Response.%s", this, header.requestId, res == null ? StructureFactory.getName(header.contractId, header.structId) : res.dump()); relayResponse(header, async, in); } } else { // Typical if the request timed out earlier, and now we've finally received the actual response, it's too late logger.info("{} Could not find pending request for {}", this, header.dump()); } if (!logged && !commsLogIgnore(header.structId)) logged = commsLog("%s [%d] <- Response.%s", this, header.requestId, StructureFactory.getName(header.contractId, header.structId)); } private void readRequest(final ByteBuf in) throws IOException { final DataSource reader = new ByteBufDataSource(in); final RequestHeader header = new RequestHeader(); boolean logged = true; header.read(reader); // set/clobber with known details, unless it's from a trusted tetrapod if (theirType != TYPE_TETRAPOD) { header.fromId = theirId; header.fromType = theirType; } if ((header.toId == DIRECT) || header.toId == myId) { final Request req = (Request) StructureFactory.make(header.contractId, header.structId); if (req != null) { req.read(reader); if (!commsLogIgnore(req)) logged = commsLog("%s [%d] <- %s (from %d)", this, header.requestId, req.dump(), header.fromId); dispatchRequest(header, req); } else { logger.warn("Could not find request structure {}", header.structId); sendResponse(new Error(ERROR_SERIALIZATION), header.requestId); } } else if (relayHandler != null) { if (!commsLogIgnore(header.structId)) logged = commsLog("%s [%d] <- Request.%s (from %d)", this, header.requestId, StructureFactory.getName(header.contractId, header.structId), header.fromId); relayRequest(header, in); } if (!logged && !commsLogIgnore(header.structId)) logged = commsLog("%s [%d] <- Request.%s (from %d)", this, header.requestId, StructureFactory.getName(header.contractId, header.structId), header.fromId); } private void readMessage(ByteBuf in, boolean isBroadcast) throws IOException { final ByteBufDataSource reader = new ByteBufDataSource(in); final MessageHeader header = new MessageHeader(); header.read(reader); if (theirType != TYPE_TETRAPOD) { // fromId MUST be their id, unless it's a tetrapod session, which could be relaying header.fromId = theirId; } if (!commsLogIgnore(header.structId)) { commsLog("%s [M] <- Message: %s (to %s:%d)", this, getNameFor(header), TO_TYPES[header.toType], header.toId); } boolean selfDispatch = header.toType == MessageHeader.TO_ENTITY && (header.toId == myId || header.toId == UNADDRESSED); if (relayHandler == null || selfDispatch) { dispatchMessage(header, reader); } else { relayHandler.relayMessage(header, in, isBroadcast); } } protected void dispatchMessage(final MessageHeader header, final ByteBufDataSource reader) throws IOException { final Object obj = StructureFactory.make(header.contractId, header.structId); final Message msg = (obj instanceof Message) ? (Message) obj : null; if (msg != null) { msg.read(reader); dispatchMessage(header, msg); } else { logger.warn("Could not find message structure {}", header.structId); } } @Override protected ByteBuf makeFrame(Structure header, Structure payload, byte envelope) { return makeFrame(header, payload, envelope, channel.alloc().buffer(128)); } private ByteBuf makeFrame(Structure header, Structure payload, byte envelope, ByteBuf buffer) { final ByteBufDataSource data = new ByteBufDataSource(buffer); buffer.writeInt(0); buffer.writeByte(envelope); try { header.write(data); payload.write(data); buffer.setInt(0, buffer.writerIndex() - 4); // go back and write message length, now that we know it if (buffer.writerIndex() > 1024 * 1024) { throw new RuntimeException("Attempting to write a message > 1mb (" + buffer.writerIndex() + " bytes) " + header.dump()); } return buffer; } catch (IOException e) { ReferenceCountUtil.release(buffer); logger.error(e.getMessage(), e); return null; } } @Override public void channelActive(final ChannelHandlerContext ctx) throws Exception { writeHandshake(); scheduleHealthCheck(); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { fireSessionStopEvent(); cancelAllPendingRequests(); } private void writeHandshake() { logger.trace("{} Writing handshake", this); synchronized (this) { needsHandshake = true; } final ByteBuf buffer = channel.alloc().buffer(9); buffer.writeInt(9); buffer.writeByte(ENVELOPE_HANDSHAKE); buffer.writeInt(WIRE_VERSION); buffer.writeInt(WIRE_OPTIONS); writeFrame(buffer); } @Override protected void sendPing() { final ByteBuf buffer = channel.alloc().buffer(5); buffer.writeInt(1); buffer.writeByte(ENVELOPE_PING); writeFrame(buffer); } @Override protected void sendPong() { final ByteBuf buffer = channel.alloc().buffer(5); buffer.writeInt(1); buffer.writeByte(ENVELOPE_PONG); writeFrame(buffer); } // /////////////////////////////////// RELAY ///////////////////////////////////// @Override protected Object makeFrame(Structure header, ByteBuf payload, byte envelope) { // OPTIMIZE: Find a way to relay without the extra allocation & copy ByteBuf buffer = channel.alloc().buffer(32 + payload.readableBytes()); ByteBufDataSource data = new ByteBufDataSource(buffer); try { buffer.writeInt(0); buffer.writeByte(envelope); header.write(data); buffer.writeBytes(payload); buffer.setInt(0, buffer.writerIndex() - 4); // Write message length, now that we know it return buffer; } catch (IOException e) { ReferenceCountUtil.release(buffer); logger.error(e.getMessage(), e); return null; } } private void relayRequest(final RequestHeader header, final ByteBuf in) { final Session ses = relayHandler.getRelaySession(header.toId, header.contractId); if (ses != null) { ses.sendRelayedRequest(header, in, this, null); } else { logger.warn("Could not find a relay session for {}", header.dump()); sendResponse(new Error(ERROR_SERVICE_UNAVAILABLE), header.requestId); } } private void relayResponse(ResponseHeader header, Async async, ByteBuf in) { header.requestId = async.header.requestId; async.session.sendRelayedResponse(header, in); } public static String dumpBuffer(ByteBuf buf) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < buf.writerIndex(); i++) { sb.append(buf.getByte(i)); sb.append(' '); } return sb.toString(); } @Override public String getPeerHostname() { return channel.remoteAddress().getHostString(); } }
Tetrapod-Core/src/io/tetrapod/core/WireSession.java
package io.tetrapod.core; import static io.tetrapod.protocol.core.Core.*; import static io.tetrapod.protocol.core.CoreContract.*; import io.netty.buffer.ByteBuf; import io.netty.channel.*; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.util.ReferenceCountUtil; import io.tetrapod.core.rpc.*; import io.tetrapod.core.rpc.Error; import io.tetrapod.core.serialize.DataSource; import io.tetrapod.core.serialize.StructureAdapter; import io.tetrapod.core.serialize.datasources.ByteBufDataSource; import io.tetrapod.protocol.core.*; import java.io.IOException; import org.slf4j.*; /** * Manages a session between two tetrapods */ public class WireSession extends Session { private static final Logger logger = LoggerFactory.getLogger(WireSession.class); private static final int WIRE_VERSION = 1; private static final int WIRE_OPTIONS = 0x00000000; private static final long LOADED_TIME = System.currentTimeMillis(); private boolean needsHandshake = true; public WireSession(SocketChannel channel, WireSession.Helper helper) { super(channel, helper); channel.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024 * 1024, 0, 4, 0, 0)); channel.pipeline().addLast(this); } private synchronized boolean needsHandshake() { return needsHandshake; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { lastHeardFrom.set(System.currentTimeMillis()); try { final ByteBuf in = (ByteBuf) msg; final int len = in.readInt() - 1; final byte envelope = in.readByte(); logger.trace("{} channelRead {}", this, envelope); if (needsHandshake()) { readHandshake(in, envelope); fireSessionStartEvent(); } else { read(in, len, envelope); } } finally { ReferenceCountUtil.release(msg); } } private void read(final ByteBuf in, final int len, final byte envelope) throws IOException { final long t0 = System.currentTimeMillis(); assert (len == in.readableBytes()); logger.trace("Read message {} with {} bytes", envelope, len); switch (envelope) { case ENVELOPE_REQUEST: readRequest(in); break; case ENVELOPE_RESPONSE: readResponse(in); break; case ENVELOPE_MESSAGE: case ENVELOPE_BROADCAST: readMessage(in, envelope == ENVELOPE_BROADCAST); break; case ENVELOPE_PING: if (theirType == TYPE_SERVICE || theirType == TYPE_TETRAPOD) logger.trace("{} GOT PING, SENDING PONG", this); sendPong(); break; case ENVELOPE_PONG: if (theirType == TYPE_SERVICE || theirType == TYPE_TETRAPOD) logger.trace("{} GOT PONG", this); break; default: logger.error("{} Unexpected Envelope Type {}", this, envelope); close(); } if (System.currentTimeMillis() - t0 > 500) { if (t0 - LOADED_TIME < 30000) { logger.info("Something blocked in read() for {} ms env={}", System.currentTimeMillis() - t0, envelope); } else { logger.warn("Something blocked in read() for {} ms env={}", System.currentTimeMillis() - t0, envelope); } } } private void readHandshake(final ByteBuf in, final byte envelope) throws IOException { if (envelope != ENVELOPE_HANDSHAKE) { throw new IOException(this + "handshake not valid"); } int theirVersion = in.readInt(); @SuppressWarnings("unused") int theirOptions = in.readInt(); if (theirVersion != WIRE_VERSION) { throw new IOException(this + "handshake version does not match " + theirVersion); } logger.trace("{} handshake succeeded", this); synchronized (this) { needsHandshake = false; } } private void readResponse(final ByteBuf in) throws IOException { final ByteBufDataSource reader = new ByteBufDataSource(in); final ResponseHeader header = new ResponseHeader(); boolean logged = false; header.read(reader); final Async async = pendingRequests.remove(header.requestId); if (async != null) { // Dispatches response to ourselves if we sent the request (fromId == myId) or // if fromId is UNADRESSED this handles the edge case where we are registering // ourselves and so did not yet have an entityId if ((async.header.fromId == myId || async.header.fromId == Core.UNADDRESSED) && (async.request != null || async.hasHandler())) { final Structure res = StructureFactory.make(header.contractId, header.structId); if (res != null) { res.read(reader); if (!commsLogIgnore(header.structId)) logged = commsLog("%s [%d] <- %s", this, header.requestId, res.dump()); getDispatcher().dispatch(() -> { if (res instanceof StructureAdapter) { async.setResponse(new ResponseAdapter(res)); } else { async.setResponse((Response) res); } }); } else { logger.warn("{} Could not find response structure {}", this, header.structId); } } else if (relayHandler != null) { // HACK: Expensive, for better debug logs. Response res = null; // if (logger.isDebugEnabled() && header.structId == 1) { // res = (Response) StructureFactory.make(async.header.contractId, header.structId); // if (res != null) { // int mark = in.readerIndex(); // res.read(reader); // in.readerIndex(mark); // } // } if (!commsLogIgnore(header.structId)) logged = commsLog("%s [%d] <- Response.%s", this, header.requestId, res == null ? StructureFactory.getName(header.contractId, header.structId) : res.dump()); relayResponse(header, async, in); } } else { // Typical if the request timed out earlier, and now we've finally received the actual response, it's too late logger.info("{} Could not find pending request for {}", this, header.dump()); } if (!logged && !commsLogIgnore(header.structId)) logged = commsLog("%s [%d] <- Response.%s", this, header.requestId, StructureFactory.getName(header.contractId, header.structId)); } private void readRequest(final ByteBuf in) throws IOException { final DataSource reader = new ByteBufDataSource(in); final RequestHeader header = new RequestHeader(); boolean logged = true; header.read(reader); // set/clobber with known details, unless it's from a trusted tetrapod if (theirType != TYPE_TETRAPOD) { header.fromId = theirId; header.fromType = theirType; } if ((header.toId == DIRECT) || header.toId == myId) { final Request req = (Request) StructureFactory.make(header.contractId, header.structId); if (req != null) { req.read(reader); if (!commsLogIgnore(req)) logged = commsLog("%s [%d] <- %s", this, header.requestId, req.dump()); dispatchRequest(header, req); } else { logger.warn("Could not find request structure {}", header.structId); sendResponse(new Error(ERROR_SERIALIZATION), header.requestId); } } else if (relayHandler != null) { if (!commsLogIgnore(header.structId)) logged = commsLog("%s [%d] <- Request.%s", this, header.requestId, StructureFactory.getName(header.contractId, header.structId)); relayRequest(header, in); } if (!logged && !commsLogIgnore(header.structId)) logged = commsLog("%s [%d] <- Request.%s", this, header.requestId, StructureFactory.getName(header.contractId, header.structId)); } private void readMessage(ByteBuf in, boolean isBroadcast) throws IOException { final ByteBufDataSource reader = new ByteBufDataSource(in); final MessageHeader header = new MessageHeader(); header.read(reader); if (theirType != TYPE_TETRAPOD) { // fromId MUST be their id, unless it's a tetrapod session, which could be relaying header.fromId = theirId; } if (!commsLogIgnore(header.structId)) { commsLog("%s [M] <- Message: %s (to %s:%d)", this, getNameFor(header), TO_TYPES[header.toType], header.toId); } boolean selfDispatch = header.toType == MessageHeader.TO_ENTITY && (header.toId == myId || header.toId == UNADDRESSED); if (relayHandler == null || selfDispatch) { dispatchMessage(header, reader); } else { relayHandler.relayMessage(header, in, isBroadcast); } } protected void dispatchMessage(final MessageHeader header, final ByteBufDataSource reader) throws IOException { final Object obj = StructureFactory.make(header.contractId, header.structId); final Message msg = (obj instanceof Message) ? (Message) obj : null; if (msg != null) { msg.read(reader); dispatchMessage(header, msg); } else { logger.warn("Could not find message structure {}", header.structId); } } @Override protected ByteBuf makeFrame(Structure header, Structure payload, byte envelope) { return makeFrame(header, payload, envelope, channel.alloc().buffer(128)); } private ByteBuf makeFrame(Structure header, Structure payload, byte envelope, ByteBuf buffer) { final ByteBufDataSource data = new ByteBufDataSource(buffer); buffer.writeInt(0); buffer.writeByte(envelope); try { header.write(data); payload.write(data); buffer.setInt(0, buffer.writerIndex() - 4); // go back and write message length, now that we know it if (buffer.writerIndex() > 1024 * 1024) { throw new RuntimeException("Attempting to write a message > 1mb (" + buffer.writerIndex() + " bytes) " + header.dump()); } return buffer; } catch (IOException e) { ReferenceCountUtil.release(buffer); logger.error(e.getMessage(), e); return null; } } @Override public void channelActive(final ChannelHandlerContext ctx) throws Exception { writeHandshake(); scheduleHealthCheck(); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { fireSessionStopEvent(); cancelAllPendingRequests(); } private void writeHandshake() { logger.trace("{} Writing handshake", this); synchronized (this) { needsHandshake = true; } final ByteBuf buffer = channel.alloc().buffer(9); buffer.writeInt(9); buffer.writeByte(ENVELOPE_HANDSHAKE); buffer.writeInt(WIRE_VERSION); buffer.writeInt(WIRE_OPTIONS); writeFrame(buffer); } @Override protected void sendPing() { final ByteBuf buffer = channel.alloc().buffer(5); buffer.writeInt(1); buffer.writeByte(ENVELOPE_PING); writeFrame(buffer); } @Override protected void sendPong() { final ByteBuf buffer = channel.alloc().buffer(5); buffer.writeInt(1); buffer.writeByte(ENVELOPE_PONG); writeFrame(buffer); } // /////////////////////////////////// RELAY ///////////////////////////////////// @Override protected Object makeFrame(Structure header, ByteBuf payload, byte envelope) { // OPTIMIZE: Find a way to relay without the extra allocation & copy ByteBuf buffer = channel.alloc().buffer(32 + payload.readableBytes()); ByteBufDataSource data = new ByteBufDataSource(buffer); try { buffer.writeInt(0); buffer.writeByte(envelope); header.write(data); buffer.writeBytes(payload); buffer.setInt(0, buffer.writerIndex() - 4); // Write message length, now that we know it return buffer; } catch (IOException e) { ReferenceCountUtil.release(buffer); logger.error(e.getMessage(), e); return null; } } private void relayRequest(final RequestHeader header, final ByteBuf in) { final Session ses = relayHandler.getRelaySession(header.toId, header.contractId); if (ses != null) { ses.sendRelayedRequest(header, in, this, null); } else { logger.warn("Could not find a relay session for {}", header.dump()); sendResponse(new Error(ERROR_SERVICE_UNAVAILABLE), header.requestId); } } private void relayResponse(ResponseHeader header, Async async, ByteBuf in) { header.requestId = async.header.requestId; async.session.sendRelayedResponse(header, in); } public static String dumpBuffer(ByteBuf buf) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < buf.writerIndex(); i++) { sb.append(buf.getByte(i)); sb.append(' '); } return sb.toString(); } @Override public String getPeerHostname() { return channel.remoteAddress().getHostString(); } }
decorate requests in comms logs with from information to make them easier to interpret in isolation
Tetrapod-Core/src/io/tetrapod/core/WireSession.java
decorate requests in comms logs with from information to make them easier to interpret in isolation
<ide><path>etrapod-Core/src/io/tetrapod/core/WireSession.java <ide> if (req != null) { <ide> req.read(reader); <ide> if (!commsLogIgnore(req)) <del> logged = commsLog("%s [%d] <- %s", this, header.requestId, req.dump()); <add> logged = commsLog("%s [%d] <- %s (from %d)", this, header.requestId, req.dump(), header.fromId); <ide> dispatchRequest(header, req); <ide> } else { <ide> logger.warn("Could not find request structure {}", header.structId); <ide> } <ide> } else if (relayHandler != null) { <ide> if (!commsLogIgnore(header.structId)) <del> logged = commsLog("%s [%d] <- Request.%s", this, header.requestId, <del> StructureFactory.getName(header.contractId, header.structId)); <add> logged = commsLog("%s [%d] <- Request.%s (from %d)", this, header.requestId, <add> StructureFactory.getName(header.contractId, header.structId), header.fromId); <ide> relayRequest(header, in); <ide> } <ide> <ide> if (!logged && !commsLogIgnore(header.structId)) <del> logged = commsLog("%s [%d] <- Request.%s", this, header.requestId, StructureFactory.getName(header.contractId, header.structId)); <add> logged = commsLog("%s [%d] <- Request.%s (from %d)", this, header.requestId, StructureFactory.getName(header.contractId, header.structId), header.fromId); <ide> } <ide> <ide> private void readMessage(ByteBuf in, boolean isBroadcast) throws IOException {
JavaScript
mit
d5d68fcc51d0c2268319e6e8f0e9a7c514e8cd80
0
zuzak/dbot,zuzak/dbot
var js = function(dbot) { var dbot = dbot; var commands = { '~js': function(data, params) { var q = data.message.valMatch(/^~js (.*)/, 2); if(data.user == dbot.admin) { dbot.say(data.channel, eval(q[1])); } } }; return { 'onLoad': function() { return commands; } }; }; exports.fetch = function(dbot) { return js(dbot); };
modules/js.js
var js = function(dbot) { var dbot = dbot; var commands = { '~js': function(data, params) { var q = data.message.valMatch(/^~js (.*)/, 2); dbot.say(data.channel, eval(q[1])); } }; return { 'onLoad': function() { return commands; } }; }; exports.fetch = function(dbot) { return js(dbot); };
only admin can run js
modules/js.js
only admin can run js
<ide><path>odules/js.js <ide> var commands = { <ide> '~js': function(data, params) { <ide> var q = data.message.valMatch(/^~js (.*)/, 2); <del> dbot.say(data.channel, eval(q[1])); <add> if(data.user == dbot.admin) { <add> dbot.say(data.channel, eval(q[1])); <add> } <ide> } <ide> }; <ide>
Java
apache-2.0
6fcd5308f9dfc74a405ebd74aa19a16926264aae
0
fl4via/xnio,dmlloyd/xnio,stuartwdouglas/xnio,panossot/xnio,kabir/xnio,panossot/xnio,xnio/xnio,fl4via/xnio,kabir/xnio,xnio/xnio
/* * JBoss, Home of Professional Open Source. * Copyright 2012 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.xnio.nio; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.DatagramChannel; import java.nio.channels.ServerSocketChannel; import java.util.List; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import java.util.concurrent.locks.LockSupport; import org.xnio.Bits; import org.xnio.ChannelListener; import org.xnio.ChannelListeners; import org.xnio.ClosedWorkerException; import org.xnio.IoUtils; import org.xnio.OptionMap; import org.xnio.Options; import org.xnio.StreamConnection; import org.xnio.XnioWorker; import org.xnio.channels.AcceptingChannel; import org.xnio.channels.MulticastMessageChannel; import static org.xnio.IoUtils.safeClose; import static org.xnio.nio.Log.log; /** * @author <a href="mailto:[email protected]">David M. Lloyd</a> */ final class NioXnioWorker extends XnioWorker { private static final int CLOSE_REQ = (1 << 31); private static final int CLOSE_COMP = (1 << 30); // start at 1 for the provided thread pool private volatile int state = 1; private final WorkerThread[] workerThreads; @SuppressWarnings("unused") private volatile Thread shutdownWaiter; private static final AtomicReferenceFieldUpdater<NioXnioWorker, Thread> shutdownWaiterUpdater = AtomicReferenceFieldUpdater.newUpdater(NioXnioWorker.class, Thread.class, "shutdownWaiter"); private static final AtomicIntegerFieldUpdater<NioXnioWorker> stateUpdater = AtomicIntegerFieldUpdater.newUpdater(NioXnioWorker.class, "state"); @SuppressWarnings("deprecation") NioXnioWorker(final NioXnio xnio, final ThreadGroup threadGroup, final OptionMap optionMap, final Runnable terminationTask) throws IOException { super(xnio, threadGroup, optionMap, terminationTask); final int threadCount; if (optionMap.contains(Options.WORKER_IO_THREADS)) { threadCount = optionMap.get(Options.WORKER_IO_THREADS, 0); } else { threadCount = Math.max(optionMap.get(Options.WORKER_READ_THREADS, 1), optionMap.get(Options.WORKER_WRITE_THREADS, 1)); } if (threadCount < 0) { throw new IllegalArgumentException("Worker I/O thread count must be >= 0"); } final long workerStackSize = optionMap.get(Options.STACK_SIZE, 0L); if (workerStackSize < 0L) { throw new IllegalArgumentException("Worker stack size must be >= 0"); } String workerName = getName(); WorkerThread[] workerThreads; workerThreads = new WorkerThread[threadCount]; final boolean markWorkerThreadAsDaemon = optionMap.get(Options.THREAD_DAEMON, false); boolean ok = false; try { for (int i = 0; i < threadCount; i++) { final WorkerThread workerThread = new WorkerThread(this, xnio.mainSelectorCreator.open(), String.format("%s I/O-%d", workerName, Integer.valueOf(i + 1)), threadGroup, workerStackSize, i); // Mark as daemon if the Options.THREAD_DAEMON has been set if (markWorkerThreadAsDaemon) { workerThread.setDaemon(true); } workerThreads[i] = workerThread; } ok = true; } finally { if (! ok) { for (WorkerThread worker : workerThreads) { if (worker != null) safeClose(worker.getSelector()); } } } this.workerThreads = workerThreads; } void start() { for (WorkerThread worker : workerThreads) { openResourceUnconditionally(); worker.start(); } } protected WorkerThread chooseThread() { final WorkerThread[] workerThreads = this.workerThreads; final int length = workerThreads.length; if (length == 0) { throw new IllegalArgumentException("No I/O threads configured"); } if (length == 1) { return workerThreads[0]; } final Random random = IoUtils.getThreadLocalRandom(); return workerThreads[random.nextInt(length)]; } public int getIoThreadCount() { return workerThreads.length; } WorkerThread[] getAll() { return workerThreads; } protected AcceptingChannel<StreamConnection> createTcpConnectionServer(final InetSocketAddress bindAddress, final ChannelListener<? super AcceptingChannel<StreamConnection>> acceptListener, final OptionMap optionMap) throws IOException { checkShutdown(); boolean ok = false; final ServerSocketChannel channel = ServerSocketChannel.open(); try { if (optionMap.contains(Options.RECEIVE_BUFFER)) channel.socket().setReceiveBufferSize(optionMap.get(Options.RECEIVE_BUFFER, -1)); channel.socket().setReuseAddress(optionMap.get(Options.REUSE_ADDRESSES, true)); channel.configureBlocking(false); if (optionMap.contains(Options.BACKLOG)) { channel.socket().bind(bindAddress, optionMap.get(Options.BACKLOG, 128)); } else { channel.socket().bind(bindAddress); } final NioTcpServer server = new NioTcpServer(this, channel, optionMap); server.setAcceptListener(acceptListener); ok = true; return server; } finally { if (! ok) { IoUtils.safeClose(channel); } } } /** {@inheritDoc} */ public MulticastMessageChannel createUdpServer(final InetSocketAddress bindAddress, final ChannelListener<? super MulticastMessageChannel> bindListener, final OptionMap optionMap) throws IOException { checkShutdown(); final DatagramChannel channel = DatagramChannel.open(); channel.configureBlocking(false); if (optionMap.contains(Options.BROADCAST)) channel.socket().setBroadcast(optionMap.get(Options.BROADCAST, false)); if (optionMap.contains(Options.IP_TRAFFIC_CLASS)) channel.socket().setTrafficClass(optionMap.get(Options.IP_TRAFFIC_CLASS, -1)); if (optionMap.contains(Options.RECEIVE_BUFFER)) channel.socket().setReceiveBufferSize(optionMap.get(Options.RECEIVE_BUFFER, -1)); channel.socket().setReuseAddress(optionMap.get(Options.REUSE_ADDRESSES, true)); if (optionMap.contains(Options.SEND_BUFFER)) channel.socket().setSendBufferSize(optionMap.get(Options.SEND_BUFFER, -1)); channel.socket().bind(bindAddress); final NioUdpChannel udpChannel = new NioUdpChannel(this, channel); ChannelListeners.invokeChannelListener(udpChannel, bindListener); return udpChannel; } public boolean isShutdown() { return (state & CLOSE_REQ) != 0; } public boolean isTerminated() { return (state & CLOSE_COMP) != 0; } /** * Open a resource unconditionally (i.e. accepting a connection on an open server). */ void openResourceUnconditionally() { int oldState = stateUpdater.getAndIncrement(this); if (log.isTraceEnabled()) { log.tracef("CAS %s %08x -> %08x", this, Integer.valueOf(oldState), Integer.valueOf(oldState + 1)); } } void checkShutdown() throws ClosedWorkerException { if (isShutdown()) throw new ClosedWorkerException("Worker is shut down"); } void closeResource() { int oldState = stateUpdater.decrementAndGet(this); if (log.isTraceEnabled()) { log.tracef("CAS %s %08x -> %08x", this, Integer.valueOf(oldState + 1), Integer.valueOf(oldState)); } while (oldState == CLOSE_REQ) { if (stateUpdater.compareAndSet(this, CLOSE_REQ, CLOSE_REQ | CLOSE_COMP)) { log.tracef("CAS %s %08x -> %08x (close complete)", this, Integer.valueOf(CLOSE_REQ), Integer.valueOf(CLOSE_REQ | CLOSE_COMP)); safeUnpark(shutdownWaiterUpdater.getAndSet(this, null)); final Runnable task = getTerminationTask(); if (task != null) try { task.run(); } catch (Throwable ignored) {} return; } oldState = state; } } public void shutdown() { int oldState; oldState = state; while ((oldState & CLOSE_REQ) == 0) { // need to do the close ourselves... if (! stateUpdater.compareAndSet(this, oldState, oldState | CLOSE_REQ)) { // changed in the meantime oldState = state; continue; } log.tracef("Initiating shutdown of %s", this); for (WorkerThread worker : workerThreads) { worker.shutdown(); } shutDownTaskPool(); return; } log.tracef("Idempotent shutdown of %s", this); return; } public List<Runnable> shutdownNow() { shutdown(); return shutDownTaskPoolNow(); } public boolean awaitTermination(final long timeout, final TimeUnit unit) throws InterruptedException { int oldState = state; if (Bits.allAreSet(oldState, CLOSE_COMP)) { return true; } long then = System.nanoTime(); long duration = unit.toNanos(timeout); final Thread myThread = Thread.currentThread(); while (Bits.allAreClear(oldState = state, CLOSE_COMP)) { final Thread oldThread = shutdownWaiterUpdater.getAndSet(this, myThread); try { if (Bits.allAreSet(oldState = state, CLOSE_COMP)) { break; } LockSupport.parkNanos(this, duration); if (Thread.interrupted()) { throw new InterruptedException(); } long now = System.nanoTime(); duration -= now - then; if (duration < 0L) { oldState = state; break; } } finally { safeUnpark(oldThread); } } return Bits.allAreSet(oldState, CLOSE_COMP); } public void awaitTermination() throws InterruptedException { int oldState = state; if (Bits.allAreSet(oldState, CLOSE_COMP)) { return; } final Thread myThread = Thread.currentThread(); while (Bits.allAreClear(state, CLOSE_COMP)) { final Thread oldThread = shutdownWaiterUpdater.getAndSet(this, myThread); try { if (Bits.allAreSet(state, CLOSE_COMP)) { break; } LockSupport.park(this); if (Thread.interrupted()) { throw new InterruptedException(); } } finally { safeUnpark(oldThread); } } } private static void safeUnpark(final Thread waiter) { if (waiter != null) LockSupport.unpark(waiter); } protected void taskPoolTerminated() { closeResource(); } public NioXnio getXnio() { return (NioXnio) super.getXnio(); } }
nio-impl/src/main/java/org/xnio/nio/NioXnioWorker.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.xnio.nio; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.DatagramChannel; import java.nio.channels.ServerSocketChannel; import java.util.List; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import java.util.concurrent.locks.LockSupport; import org.xnio.Bits; import org.xnio.ChannelListener; import org.xnio.ChannelListeners; import org.xnio.ClosedWorkerException; import org.xnio.IoUtils; import org.xnio.OptionMap; import org.xnio.Options; import org.xnio.StreamConnection; import org.xnio.XnioWorker; import org.xnio.channels.AcceptingChannel; import org.xnio.channels.MulticastMessageChannel; import static org.xnio.IoUtils.safeClose; import static org.xnio.nio.Log.log; /** * @author <a href="mailto:[email protected]">David M. Lloyd</a> */ final class NioXnioWorker extends XnioWorker { private static final int CLOSE_REQ = (1 << 31); private static final int CLOSE_COMP = (1 << 30); // start at 1 for the provided thread pool private volatile int state = 1; private final WorkerThread[] workerThreads; @SuppressWarnings("unused") private volatile Thread shutdownWaiter; private static final AtomicReferenceFieldUpdater<NioXnioWorker, Thread> shutdownWaiterUpdater = AtomicReferenceFieldUpdater.newUpdater(NioXnioWorker.class, Thread.class, "shutdownWaiter"); private static final AtomicIntegerFieldUpdater<NioXnioWorker> stateUpdater = AtomicIntegerFieldUpdater.newUpdater(NioXnioWorker.class, "state"); @SuppressWarnings("deprecation") NioXnioWorker(final NioXnio xnio, final ThreadGroup threadGroup, final OptionMap optionMap, final Runnable terminationTask) throws IOException { super(xnio, threadGroup, optionMap, terminationTask); final int threadCount; if (optionMap.contains(Options.WORKER_IO_THREADS)) { threadCount = optionMap.get(Options.WORKER_IO_THREADS, 0); } else { threadCount = Math.max(optionMap.get(Options.WORKER_READ_THREADS, 1), optionMap.get(Options.WORKER_WRITE_THREADS, 1)); } if (threadCount < 0) { throw new IllegalArgumentException("Worker I/O thread count must be >= 0"); } final long workerStackSize = optionMap.get(Options.STACK_SIZE, 0L); if (workerStackSize < 0L) { throw new IllegalArgumentException("Worker stack size must be >= 0"); } String workerName = getName(); WorkerThread[] workerThreads; workerThreads = new WorkerThread[threadCount]; final boolean markWorkerThreadAsDaemon = optionMap.get(Options.THREAD_DAEMON, false); boolean ok = false; try { for (int i = 0; i < threadCount; i++) { final WorkerThread workerThread = new WorkerThread(this, xnio.mainSelectorCreator.open(), String.format("%s read-%d", workerName, Integer.valueOf(i + 1)), threadGroup, workerStackSize, i); // Mark as daemon if the Options.THREAD_DAEMON has been set if (markWorkerThreadAsDaemon) { workerThread.setDaemon(true); } workerThreads[i] = workerThread; } ok = true; } finally { if (! ok) { for (WorkerThread worker : workerThreads) { if (worker != null) safeClose(worker.getSelector()); } } } this.workerThreads = workerThreads; } void start() { for (WorkerThread worker : workerThreads) { openResourceUnconditionally(); worker.start(); } } protected WorkerThread chooseThread() { final WorkerThread[] workerThreads = this.workerThreads; final int length = workerThreads.length; if (length == 0) { throw new IllegalArgumentException("No I/O threads configured"); } if (length == 1) { return workerThreads[0]; } final Random random = IoUtils.getThreadLocalRandom(); return workerThreads[random.nextInt(length)]; } public int getIoThreadCount() { return workerThreads.length; } WorkerThread[] getAll() { return workerThreads; } protected AcceptingChannel<StreamConnection> createTcpConnectionServer(final InetSocketAddress bindAddress, final ChannelListener<? super AcceptingChannel<StreamConnection>> acceptListener, final OptionMap optionMap) throws IOException { checkShutdown(); boolean ok = false; final ServerSocketChannel channel = ServerSocketChannel.open(); try { if (optionMap.contains(Options.RECEIVE_BUFFER)) channel.socket().setReceiveBufferSize(optionMap.get(Options.RECEIVE_BUFFER, -1)); channel.socket().setReuseAddress(optionMap.get(Options.REUSE_ADDRESSES, true)); channel.configureBlocking(false); if (optionMap.contains(Options.BACKLOG)) { channel.socket().bind(bindAddress, optionMap.get(Options.BACKLOG, 128)); } else { channel.socket().bind(bindAddress); } final NioTcpServer server = new NioTcpServer(this, channel, optionMap); server.setAcceptListener(acceptListener); ok = true; return server; } finally { if (! ok) { IoUtils.safeClose(channel); } } } /** {@inheritDoc} */ public MulticastMessageChannel createUdpServer(final InetSocketAddress bindAddress, final ChannelListener<? super MulticastMessageChannel> bindListener, final OptionMap optionMap) throws IOException { checkShutdown(); final DatagramChannel channel = DatagramChannel.open(); channel.configureBlocking(false); if (optionMap.contains(Options.BROADCAST)) channel.socket().setBroadcast(optionMap.get(Options.BROADCAST, false)); if (optionMap.contains(Options.IP_TRAFFIC_CLASS)) channel.socket().setTrafficClass(optionMap.get(Options.IP_TRAFFIC_CLASS, -1)); if (optionMap.contains(Options.RECEIVE_BUFFER)) channel.socket().setReceiveBufferSize(optionMap.get(Options.RECEIVE_BUFFER, -1)); channel.socket().setReuseAddress(optionMap.get(Options.REUSE_ADDRESSES, true)); if (optionMap.contains(Options.SEND_BUFFER)) channel.socket().setSendBufferSize(optionMap.get(Options.SEND_BUFFER, -1)); channel.socket().bind(bindAddress); final NioUdpChannel udpChannel = new NioUdpChannel(this, channel); ChannelListeners.invokeChannelListener(udpChannel, bindListener); return udpChannel; } public boolean isShutdown() { return (state & CLOSE_REQ) != 0; } public boolean isTerminated() { return (state & CLOSE_COMP) != 0; } /** * Open a resource unconditionally (i.e. accepting a connection on an open server). */ void openResourceUnconditionally() { int oldState = stateUpdater.getAndIncrement(this); if (log.isTraceEnabled()) { log.tracef("CAS %s %08x -> %08x", this, Integer.valueOf(oldState), Integer.valueOf(oldState + 1)); } } void checkShutdown() throws ClosedWorkerException { if (isShutdown()) throw new ClosedWorkerException("Worker is shut down"); } void closeResource() { int oldState = stateUpdater.decrementAndGet(this); if (log.isTraceEnabled()) { log.tracef("CAS %s %08x -> %08x", this, Integer.valueOf(oldState + 1), Integer.valueOf(oldState)); } while (oldState == CLOSE_REQ) { if (stateUpdater.compareAndSet(this, CLOSE_REQ, CLOSE_REQ | CLOSE_COMP)) { log.tracef("CAS %s %08x -> %08x (close complete)", this, Integer.valueOf(CLOSE_REQ), Integer.valueOf(CLOSE_REQ | CLOSE_COMP)); safeUnpark(shutdownWaiterUpdater.getAndSet(this, null)); final Runnable task = getTerminationTask(); if (task != null) try { task.run(); } catch (Throwable ignored) {} return; } oldState = state; } } public void shutdown() { int oldState; oldState = state; while ((oldState & CLOSE_REQ) == 0) { // need to do the close ourselves... if (! stateUpdater.compareAndSet(this, oldState, oldState | CLOSE_REQ)) { // changed in the meantime oldState = state; continue; } log.tracef("Initiating shutdown of %s", this); for (WorkerThread worker : workerThreads) { worker.shutdown(); } shutDownTaskPool(); return; } log.tracef("Idempotent shutdown of %s", this); return; } public List<Runnable> shutdownNow() { shutdown(); return shutDownTaskPoolNow(); } public boolean awaitTermination(final long timeout, final TimeUnit unit) throws InterruptedException { int oldState = state; if (Bits.allAreSet(oldState, CLOSE_COMP)) { return true; } long then = System.nanoTime(); long duration = unit.toNanos(timeout); final Thread myThread = Thread.currentThread(); while (Bits.allAreClear(oldState = state, CLOSE_COMP)) { final Thread oldThread = shutdownWaiterUpdater.getAndSet(this, myThread); try { if (Bits.allAreSet(oldState = state, CLOSE_COMP)) { break; } LockSupport.parkNanos(this, duration); if (Thread.interrupted()) { throw new InterruptedException(); } long now = System.nanoTime(); duration -= now - then; if (duration < 0L) { oldState = state; break; } } finally { safeUnpark(oldThread); } } return Bits.allAreSet(oldState, CLOSE_COMP); } public void awaitTermination() throws InterruptedException { int oldState = state; if (Bits.allAreSet(oldState, CLOSE_COMP)) { return; } final Thread myThread = Thread.currentThread(); while (Bits.allAreClear(state, CLOSE_COMP)) { final Thread oldThread = shutdownWaiterUpdater.getAndSet(this, myThread); try { if (Bits.allAreSet(state, CLOSE_COMP)) { break; } LockSupport.park(this); if (Thread.interrupted()) { throw new InterruptedException(); } } finally { safeUnpark(oldThread); } } } private static void safeUnpark(final Thread waiter) { if (waiter != null) LockSupport.unpark(waiter); } protected void taskPoolTerminated() { closeResource(); } public NioXnio getXnio() { return (NioXnio) super.getXnio(); } }
Fix thread name
nio-impl/src/main/java/org/xnio/nio/NioXnioWorker.java
Fix thread name
<ide><path>io-impl/src/main/java/org/xnio/nio/NioXnioWorker.java <ide> boolean ok = false; <ide> try { <ide> for (int i = 0; i < threadCount; i++) { <del> final WorkerThread workerThread = new WorkerThread(this, xnio.mainSelectorCreator.open(), String.format("%s read-%d", workerName, Integer.valueOf(i + 1)), threadGroup, workerStackSize, i); <add> final WorkerThread workerThread = new WorkerThread(this, xnio.mainSelectorCreator.open(), String.format("%s I/O-%d", workerName, Integer.valueOf(i + 1)), threadGroup, workerStackSize, i); <ide> // Mark as daemon if the Options.THREAD_DAEMON has been set <ide> if (markWorkerThreadAsDaemon) { <ide> workerThread.setDaemon(true);
Java
bsd-3-clause
95d3f99b40e1bf9b82a1fa39357d70a306144266
0
Jakegogo/concurrent,Jakegogo/concurrent
package utils.typesafe.extended; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; /** * 线程安全的Actor * <br/>支持多个对象操作的顺序执行,可并发提交。与提交线程的关系是同步或异步 * <br/>序列执行子类型 * <br/>需要覆盖run方法, 方法内可以调用super.afterExecute(Object[])执行结束后会进行回调 * <br/>不会因为死锁而阻塞线程,但嵌套死锁会导致后续任务不执行(汗!结果相对于死锁了) * <br/>建议业务逻辑层不创建和执行MultiSafeActor,由托举容器进行创建和执行 * @author Jake * */ public abstract class MultiSafeActor implements Runnable { /** * 上一次执行的Actor */ private static final AtomicReference<MultiSafeActor> head = new AtomicReference<MultiSafeActor>(); private AtomicReference<MultiSafeActor> next = new AtomicReference<MultiSafeActor>(null); private List<MultiSafeType> safeTypes; private List<MultiSafeRunable> safeRunables; private int count; // 计数器 private AtomicInteger curCount = new AtomicInteger(0); private ExecutorService executorService; /** * 构造方法 * @param executorService 线程池 * @param promiseable 线程安全的操作组 */ public MultiSafeActor(ExecutorService executorService, Promiseable<?> promiseable) { if (promiseable == null) { throw new IllegalArgumentException("promiseable cannot be null"); } this.safeTypes = new ArrayList<MultiSafeType>(); this.safeRunables = new ArrayList<MultiSafeRunable>(); this.executorService = executorService; this.when(promiseable); } /** * 构造方法 * @param executorService 线程池 * @param safeTypes 线程安全的类型 */ public MultiSafeActor(ExecutorService executorService, MultiSafeType... safeTypes) { if (safeTypes == null || safeTypes.length == 0) { throw new IllegalArgumentException("safeTypes must more than one arguments"); } List<MultiSafeType> safeTypesList = new ArrayList<MultiSafeType>(); for (MultiSafeType safeType : safeTypes) { safeTypesList.add(safeType); } this.safeTypes = safeTypesList; this.count = safeTypes.length; this.executorService = executorService; initSafeRunnables(safeTypes, executorService); } // 初始化MultiSafeRunable private void initSafeRunnables(MultiSafeType[] safeTypes, ExecutorService executorService) { List<MultiSafeRunable> safeRunables = new ArrayList<MultiSafeRunable>(); for (int i = 0;i < safeTypes.length;i++) { safeRunables.add(new MultiSafeRunable(safeTypes[i], this, executorService)); } this.safeRunables = safeRunables; } /** * 当获取所需要的关联操作后,when代表将子操作纳入本操作组成新的原子性操作 * @param promiseables * @return */ public MultiSafeActor when(Promiseable<?>... promiseables) { if (promiseables == null || promiseables.length == 0) { throw new IllegalArgumentException("promiseables must more than one arguments"); } for (int i = 0;i < promiseables.length;i++) { Promiseable<?> promiseable = promiseables[i]; for (MultiSafeType safeType : promiseable.promiseTypes()) { safeTypes.add(safeType); safeRunables.add(new MultiSafeRunable(safeType, this, executorService)); } } this.count += promiseables.length; return this; } /** * 开始执行Actor */ public void start() { addToQueue(this); } // 追加提交任务 protected void addToQueue(MultiSafeActor runnable) { // messages from the same client are handled orderly AtomicReference<MultiSafeActor> lastRef = head; if (lastRef.get() == null && lastRef.compareAndSet(null, this)) { // No previous job runnable.runQueue(); } else { // CAS loop int casLoop = 1; for (; ; ) { if (casAppend(runnable, lastRef)) return; if (casLoop ++ > 3) { break; } } synchronized (head) { for (; ; ) { if (casAppend(runnable, lastRef)) return; } } } } // 追加到末尾 private boolean casAppend(MultiSafeActor runnable, AtomicReference<MultiSafeActor> lastRef) { MultiSafeActor last = lastRef.get(); AtomicReference<MultiSafeActor> nextRef = last.next; MultiSafeActor next = nextRef.get(); if (next != null) { if (next == last && lastRef.compareAndSet(last, this)) { // previous message is handled, order is // guaranteed. runnable.runQueue(); return true; } } else if (nextRef.compareAndSet(null, this)) { lastRef.compareAndSet(last, this);// fail is OK // successfully append to previous task return true; } return false; } // 执行提交任务 protected void runQueue() { // 执行SafeRunable序列 for (final MultiSafeRunable safeRunable : safeRunables) { safeRunable.execute(); } this.runNextElement(); } // 执行下一个提交任务 protected void runNextElement() { if (!next.compareAndSet(null, this)) { // has more job to run next.get().runQueue(); } } /** * 派发依赖实体线程 * @param exclude 对后一个依赖执行的Runnable */ public void dispathNext(MultiSafeRunable exclude) { for (MultiSafeRunable safeRunable : safeRunables) { if (safeRunable != exclude) { safeRunable.submitRunNext(); } } } public int incrementAndGet() { return this.curCount.incrementAndGet(); } public int getCount() { return count; } /** * 执行异常回调() * @param t Throwable */ public void onException(Throwable t) {} @Override public String toString() { return safeTypes + ", count=" + this.curCount + ", hash=" + this.hashCode(); } }
concur/src-utils/utils/typesafe/extended/MultiSafeActor.java
package utils.typesafe.extended; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; /** * 线程安全的Actor * <br/>支持多个对象操作的顺序执行,可并发提交。与提交线程的关系是同步或异步 * <br/>序列执行子类型 * <br/>需要覆盖run方法, 方法内可以调用super.afterExecute(Object[])执行结束后会进行回调 * <br/>不会因为死锁而阻塞线程,但嵌套死锁会导致后续任务不执行(汗!结果相对于死锁了) * <br/>建议业务逻辑层不创建和执行MultiSafeActor,由托举容器进行创建和执行 * @author Jake * */ public abstract class MultiSafeActor implements Runnable { /** * 上一次执行的Actor */ private static final AtomicReference<MultiSafeActor> head = new AtomicReference<MultiSafeActor>(); private AtomicReference<MultiSafeActor> next = new AtomicReference<MultiSafeActor>(null); private List<MultiSafeType> safeTypes; private List<MultiSafeRunable> safeRunables; private int count; // 计数器 private AtomicInteger curCount = new AtomicInteger(0); private ExecutorService executorService; /** * 构造方法 * @param executorService 线程池 * @param safeTypes 线程安全的类型 */ public MultiSafeActor(ExecutorService executorService, MultiSafeType... safeTypes) { if (safeTypes == null || safeTypes.length == 0) { throw new IllegalArgumentException("safeTypes must more than one arguments"); } List<MultiSafeType> safeTypesList = new ArrayList<MultiSafeType>(); for (MultiSafeType safeType : safeTypes) { safeTypesList.add(safeType); } this.safeTypes = safeTypesList; this.count = safeTypes.length; this.executorService = executorService; initSafeRunnables(safeTypes, executorService); } // 初始化MultiSafeRunable private void initSafeRunnables(MultiSafeType[] safeTypes, ExecutorService executorService) { List<MultiSafeRunable> safeRunables = new ArrayList<MultiSafeRunable>(); for (int i = 0;i < safeTypes.length;i++) { safeRunables.add(new MultiSafeRunable(safeTypes[i], this, executorService)); } this.safeRunables = safeRunables; } /** * 开始执行Actor */ public void start() { addToQueue(this); } /** * 当获取所需要的关联操作后,when代表将子操作纳入本操作组成新的原子性操作 * @param promiseables * @return */ public MultiSafeActor when(Promiseable<?>... promiseables) { if (promiseables == null || promiseables.length == 0) { throw new IllegalArgumentException("promiseables must more than one arguments"); } for (int i = 0;i < promiseables.length;i++) { Promiseable<?> promiseable = promiseables[i]; for (MultiSafeType safeType : promiseable.promiseTypes()) { safeTypes.add(safeType); safeRunables.add(new MultiSafeRunable(safeType, this, executorService)); } } this.count += promiseables.length; return this; } // 追加提交任务 protected void addToQueue(MultiSafeActor runnable) { // messages from the same client are handled orderly AtomicReference<MultiSafeActor> lastRef = head; if (lastRef.get() == null && lastRef.compareAndSet(null, this)) { // No previous job runnable.runQueue(); } else { // CAS loop int casLoop = 1; for (; ; ) { if (casAppend(runnable, lastRef)) return; if (casLoop ++ > 3) { break; } } synchronized (head) { for (; ; ) { if (casAppend(runnable, lastRef)) return; } } } } // 追加到末尾 private boolean casAppend(MultiSafeActor runnable, AtomicReference<MultiSafeActor> lastRef) { MultiSafeActor last = lastRef.get(); AtomicReference<MultiSafeActor> nextRef = last.next; MultiSafeActor next = nextRef.get(); if (next != null) { if (next == last && lastRef.compareAndSet(last, this)) { // previous message is handled, order is // guaranteed. runnable.runQueue(); return true; } } else if (nextRef.compareAndSet(null, this)) { lastRef.compareAndSet(last, this);// fail is OK // successfully append to previous task return true; } return false; } // 执行提交任务 protected void runQueue() { // 执行SafeRunable序列 for (final MultiSafeRunable safeRunable : safeRunables) { safeRunable.execute(); } this.runNextElement(); } // 执行下一个提交任务 protected void runNextElement() { if (!next.compareAndSet(null, this)) { // has more job to run next.get().runQueue(); } } /** * 派发依赖实体线程 * @param exclude 对后一个依赖执行的Runnable */ public void dispathNext(MultiSafeRunable exclude) { for (MultiSafeRunable safeRunable : safeRunables) { if (safeRunable != exclude) { safeRunable.submitRunNext(); } } } public int incrementAndGet() { return this.curCount.incrementAndGet(); } public int getCount() { return count; } /** * 执行异常回调() * @param t Throwable */ public void onException(Throwable t) {} @Override public String toString() { return safeTypes + ", count=" + this.curCount + ", hash=" + this.hashCode(); } }
新增PromiseActor
concur/src-utils/utils/typesafe/extended/MultiSafeActor.java
新增PromiseActor
<ide><path>oncur/src-utils/utils/typesafe/extended/MultiSafeActor.java <ide> <ide> private ExecutorService executorService; <ide> <add> /** <add> * 构造方法 <add> * @param executorService 线程池 <add> * @param promiseable 线程安全的操作组 <add> */ <add> public MultiSafeActor(ExecutorService executorService, Promiseable<?> promiseable) { <add> if (promiseable == null) { <add> throw new IllegalArgumentException("promiseable cannot be null"); <add> } <add> <add> this.safeTypes = new ArrayList<MultiSafeType>(); <add> this.safeRunables = new ArrayList<MultiSafeRunable>(); <add> this.executorService = executorService; <add> <add> this.when(promiseable); <add> } <ide> <ide> /** <ide> * 构造方法 <ide> <ide> <ide> /** <add> * 当获取所需要的关联操作后,when代表将子操作纳入本操作组成新的原子性操作 <add> * @param promiseables <add> * @return <add> */ <add> public MultiSafeActor when(Promiseable<?>... promiseables) { <add> if (promiseables == null || promiseables.length == 0) { <add> throw new IllegalArgumentException("promiseables must more than one arguments"); <add> } <add> <add> for (int i = 0;i < promiseables.length;i++) { <add> Promiseable<?> promiseable = promiseables[i]; <add> for (MultiSafeType safeType : promiseable.promiseTypes()) { <add> safeTypes.add(safeType); <add> safeRunables.add(new MultiSafeRunable(safeType, this, executorService)); <add> } <add> } <add> <add> this.count += promiseables.length; <add> return this; <add> } <add> <add> <add> /** <ide> * 开始执行Actor <ide> */ <ide> public void start() { <ide> addToQueue(this); <ide> } <del> <del> <del> /** <del> * 当获取所需要的关联操作后,when代表将子操作纳入本操作组成新的原子性操作 <del> * @param promiseables <del> * @return <del> */ <del> public MultiSafeActor when(Promiseable<?>... promiseables) { <del> if (promiseables == null || promiseables.length == 0) { <del> throw new IllegalArgumentException("promiseables must more than one arguments"); <del> } <del> <del> for (int i = 0;i < promiseables.length;i++) { <del> Promiseable<?> promiseable = promiseables[i]; <del> for (MultiSafeType safeType : promiseable.promiseTypes()) { <del> safeTypes.add(safeType); <del> safeRunables.add(new MultiSafeRunable(safeType, this, executorService)); <del> } <del> } <del> <del> this.count += promiseables.length; <del> <del> return this; <del> } <ide> <ide> <ide> // 追加提交任务
Java
apache-2.0
ce7a5636aed9229bbd5bb6e009f5b14bdb908b51
0
BuddhistDigitalResourceCenter/xmltoldmigration,BuddhistDigitalResourceCenter/xmltoldmigration
package io.bdrc.xmltoldmigration; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.jena.datatypes.xsd.XSDDatatype; import org.apache.jena.rdf.model.Literal; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.Resource; import org.apache.jena.vocabulary.RDF; import com.opencsv.CSVParser; import com.opencsv.CSVParserBuilder; import com.opencsv.CSVReader; import com.opencsv.CSVReaderBuilder; import io.bdrc.xmltoldmigration.helpers.SymetricNormalization; import io.bdrc.xmltoldmigration.xml2files.CommonMigration; import io.bdrc.xmltoldmigration.xml2files.ImagegroupMigration; import io.bdrc.xmltoldmigration.xml2files.WorkMigration; public class CUDLTransfer { private static final String BDO = CommonMigration.ONTOLOGY_PREFIX; private static final String BDR = CommonMigration.RESOURCE_PREFIX; private static final String ADM = CommonMigration.ADMIN_PREFIX; public static List<String[]> lines; public static final Map<String,String> rKTsRIDMap = getrKTsRIDMap(); public static final HashMap<String,String> scripts = getScripts(); public static final HashMap<String,String> materials = getMaterials(); public static void CUDLDoTransfer() throws IOException { CSVReader reader; CSVParser parser = new CSVParserBuilder().build(); InputStream inputStream = EAPFondsTransfer.class.getClassLoader().getResourceAsStream("cudl.csv"); BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); reader = new CSVReaderBuilder(in) .withCSVParser(parser) .build(); lines=reader.readAll(); for(int x=1;x<lines.size();x++) { writeCUDLFiles(getResourcesFromLine(lines.get(x))); } } public static final HashMap<String,String> getScripts() { final HashMap<String,String> res = new HashMap<>(); res.put("nepālākṣarā","SaNepaleseHooked"); res.put("pāla","SaRanj"); res.put("sinhala","SaSinh"); res.put("Hooked Nepālākṣarā (Bhujimol)","SaNepaleseHooked"); res.put("bengali","SaBeng"); return res; } public static final HashMap<String,String> getMaterials() { final HashMap<String,String> res = new HashMap<>(); res.put("palm_leaf","MaterialPalmLeaf"); res.put("paper","MaterialPaper"); res.put("nep_multi_layered_paper","MaterialMultiLayerPaper"); res.put("corypha_palm_leaf","MaterialCoryphaPalmLeaf"); res.put("mixed","MaterialMixed"); return res; } public static final Map<String,String> getrKTsRIDMap() { final CSVReader reader; final CSVParser parser = new CSVParserBuilder().build(); final Map<String,String> res = new HashMap<>(); final ClassLoader classLoader = MigrationHelpers.class.getClassLoader(); final InputStream inputStream = classLoader.getResourceAsStream("abstract-rkts.csv"); final BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); reader = new CSVReaderBuilder(in) .withCSVParser(parser) .build(); String[] line = null; try { line = reader.readNext(); } catch (IOException e) { e.printStackTrace(); return null; } while (line != null) { if (line.length > 1 && !line[1].contains("?")) res.put(line[1], line[0]); try { line = reader.readNext(); } catch (IOException e) { e.printStackTrace(); return null; } } return res; } public static final String rKTsToBDR(String rKTs) { if (rKTs == null || rKTs.isEmpty() || rKTs.contains("?") || rKTs.contains("&")) return null; rKTs = rKTs.trim(); if (rKTsRIDMap.containsKey(rKTs)) { return rKTsRIDMap.get(rKTs); } String rktsid; try { rktsid = String.format("%04d", Integer.parseInt(rKTs.substring(1))); } catch (Exception e) { return null; } if (rKTs.startsWith("K")) { return "W0RKA"+rktsid; } return "W0RTA"+rktsid; } public static final List<Resource> getResourcesFromLine(String[] line) { final Model workModel = ModelFactory.createDefaultModel(); final List<Resource> res = new ArrayList<>(); CommonMigration.setPrefixes(workModel); String rid=line[0]; Resource work = workModel.createResource(BDR+"W0CDL0"+rid); res.add(work); workModel.add(work,workModel.createProperty(BDO,"workCatalogInfo"),workModel.createLiteral(line[1], "en")); workModel.add(work,workModel.createProperty(BDO,"workBiblioNote"),workModel.createLiteral(line[2], "en")); workModel.add(work, RDF.type, workModel.createResource(BDO+"Work")); String mainTitle=line[6]; String title=line[3]; Literal l=null; if(title.endsWith("@en")) { l=workModel.createLiteral(title); }else { l=workModel.createLiteral(title,"sa-x-iast"); } String altTitle=line[7]; Resource titleR = workModel.createResource(); workModel.add(work, workModel.createProperty(BDO, "workTitle"), titleR); workModel.add(work,workModel.createProperty(CommonMigration.SKOS_PREFIX,"prefLabel"),l); if(!altTitle.equals("")) { workModel.add(work,workModel.createProperty(CommonMigration.SKOS_PREFIX,"altLabel"),workModel.createLiteral(altTitle, "sa-x-iast")); } if(mainTitle.equals("")) { workModel.add(titleR, workModel.createProperty(BDO, "WorkBibliographicalTitle"), l); }else { workModel.add(titleR, workModel.createProperty(BDO, "WorkBibliographicalTitle"), workModel.createLiteral(mainTitle, "sa-x-iast")); } final String abstractWorkRID = rKTsToBDR(line[4]); if (abstractWorkRID != null) { SymetricNormalization.addSymetricProperty(workModel, "workExpressionOf", rid, abstractWorkRID, null); } if(!line[5].equals("")) { workModel.add(work, workModel.createProperty(BDO, "workIsAbout"), workModel.createResource(CommonMigration.RESOURCE_PREFIX+line[5])); } workModel.add(work, workModel.createProperty(ADM, "license"), workModel.createResource(BDR+"LicenseCopyrighted")); // ? workModel.add(work, workModel.getProperty(ADM+"status"), workModel.createResource(BDR+"StatusReleased")); workModel.add(work, workModel.createProperty(ADM, "access"), workModel.createResource(BDR+"AccessOpen")); workModel.add(work, workModel.createProperty(BDO, "workMaterial"), workModel.createResource(BDR+materials.get(line[9]))); workModel.add(work, workModel.createProperty(BDO,"contentProvider"), workModel.createResource(BDR+"CCDL")); workModel.add(work, workModel.createProperty(BDO,"originalRecord"), workModel.createTypedLiteral("https://cudl.lib.cam.ac.uk/view/"+line[0], XSDDatatype.XSDanyURI)); if(!line[14].equals("")) { workModel.add(work, workModel.createProperty(BDO, "workLangScript"), workModel.createResource(BDR+scripts.get(line[14]))); } if (!line[19].isEmpty()) { work.addProperty(workModel.createProperty(BDO, "workDimWidth"), line[19].replace(',','.').trim(), XSDDatatype.XSDdecimal); } if (!line[18].isEmpty()) { work.addProperty(workModel.createProperty(BDO, "workDimHeight"), line[18].replace(',','.').trim(), XSDDatatype.XSDdecimal); } final Model itemModel = ModelFactory.createDefaultModel(); CommonMigration.setPrefixes(itemModel); final String itemRID = "I0CDL0"+rid; if (WorkMigration.addWorkHasItem) { workModel.add(work, workModel.createProperty(BDO, "workHasItemImageAsset"), workModel.createResource(BDR+itemRID)); } Resource item = itemModel.createResource(BDR+itemRID); res.add(item); itemModel.add(item, RDF.type, itemModel.createResource(BDO+"ItemImageAsset")); final String volumeRID = "V0CDL0"+rid; Resource volume = itemModel.createResource(BDR+volumeRID); itemModel.add(volume, RDF.type, itemModel.createResource(BDO+"VolumeImageAsset")); if (ImagegroupMigration.addVolumeOf) itemModel.add(volume, itemModel.createProperty(BDO, "volumeOf"), item); if (ImagegroupMigration.addItemHasVolume) itemModel.add(item, itemModel.createProperty(BDO, "itemHasVolume"), volume); itemModel.add(volume, itemModel.createProperty(BDO, "hasIIIFManifest"), itemModel.createResource(line[8])); itemModel.add(volume, itemModel.createProperty(BDO, "volumeNumber"), itemModel.createTypedLiteral(1, XSDDatatype.XSDinteger)); if (WorkMigration.addItemForWork) { itemModel.add(item, itemModel.createProperty(BDO, "itemImageAssetForWork"), itemModel.createResource(BDR+rid)); } if(!line[10].equals("") && !line[11].equals("")) { Resource event = workModel.createResource(); workModel.add(work, workModel.createProperty(BDO, "workEvent"), event); workModel.add(event, RDF.type, workModel.createResource(BDO+"PublishedEvent")); workModel.add(event, workModel.createProperty(BDO, "notAfter"), workModel.createTypedLiteral(line[11], XSDDatatype.XSDinteger)); workModel.add(event, workModel.createProperty(BDO, "notBefore"), workModel.createTypedLiteral(line[10], XSDDatatype.XSDinteger)); } //itemModel.write(System.out,"TURTLE"); return res; } public static void writeCUDLFiles(List<Resource> resources) { for(Resource r: resources) { String uri=r.getProperty(RDF.type).getObject().asResource().getURI(); switch(uri) { case "http://purl.bdrc.io/ontology/core/Work": final String workOutfileName = MigrationApp.getDstFileName("work", r.getLocalName()); MigrationHelpers.outputOneModel(r.getModel(), r.getLocalName(), workOutfileName, "work"); break; case "http://purl.bdrc.io/ontology/core/ItemImageAsset": final String itemOutfileName = MigrationApp.getDstFileName("item", r.getLocalName()); MigrationHelpers.outputOneModel(r.getModel(), r.getLocalName(), itemOutfileName, "item"); break; } } } }
src/main/java/io/bdrc/xmltoldmigration/CUDLTransfer.java
package io.bdrc.xmltoldmigration; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.jena.datatypes.xsd.XSDDatatype; import org.apache.jena.rdf.model.Literal; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.Resource; import org.apache.jena.vocabulary.RDF; import com.opencsv.CSVParser; import com.opencsv.CSVParserBuilder; import com.opencsv.CSVReader; import com.opencsv.CSVReaderBuilder; import io.bdrc.xmltoldmigration.helpers.SymetricNormalization; import io.bdrc.xmltoldmigration.xml2files.CommonMigration; import io.bdrc.xmltoldmigration.xml2files.ImagegroupMigration; import io.bdrc.xmltoldmigration.xml2files.WorkMigration; public class CUDLTransfer { private static final String BDO = CommonMigration.ONTOLOGY_PREFIX; private static final String BDR = CommonMigration.RESOURCE_PREFIX; private static final String ADM = CommonMigration.ADMIN_PREFIX; public static List<String[]> lines; public static final Map<String,String> rKTsRIDMap = getrKTsRIDMap(); public static final HashMap<String,String> scripts = getScripts(); public static final HashMap<String,String> materials = getMaterials(); public static void CUDLDoTransfer() throws IOException { CSVReader reader; CSVParser parser = new CSVParserBuilder().build(); InputStream inputStream = EAPFondsTransfer.class.getClassLoader().getResourceAsStream("cudl.csv"); BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); reader = new CSVReaderBuilder(in) .withCSVParser(parser) .build(); lines=reader.readAll(); for(int x=1;x<lines.size();x++) { writeCUDLFiles(getResourcesFromLine(lines.get(x))); } } public static final HashMap<String,String> getScripts() { final HashMap<String,String> res = new HashMap<>(); res.put("nepālākṣarā","SaNepaleseHooked"); res.put("pāla","SaRanj"); res.put("sinhala","SaSinh"); res.put("Hooked Nepālākṣarā (Bhujimol)","SaNepaleseHooked"); res.put("bengali","SaBeng"); return res; } public static final HashMap<String,String> getMaterials() { final HashMap<String,String> res = new HashMap<>(); res.put("palm_leaf","MaterialPalmLeaf"); res.put("paper","MaterialPaper"); res.put("nep_multi_layered_paper","MaterialMultiLayerPaper"); res.put("corypha_palm_leaf","MaterialCoryphaPalmLeaf"); res.put("mixed","MaterialMixed"); return res; } public static final Map<String,String> getrKTsRIDMap() { final CSVReader reader; final CSVParser parser = new CSVParserBuilder().build(); final Map<String,String> res = new HashMap<>(); final ClassLoader classLoader = MigrationHelpers.class.getClassLoader(); final InputStream inputStream = classLoader.getResourceAsStream("abstract-rkts.csv"); final BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); reader = new CSVReaderBuilder(in) .withCSVParser(parser) .build(); String[] line = null; try { line = reader.readNext(); } catch (IOException e) { e.printStackTrace(); return null; } while (line != null) { if (line.length > 1 && !line[1].contains("?")) res.put(line[1], line[0]); try { line = reader.readNext(); } catch (IOException e) { e.printStackTrace(); return null; } } return res; } public static final String rKTsToBDR(String rKTs) { if (rKTs == null || rKTs.isEmpty() || rKTs.contains("?") || rKTs.contains("&")) return null; rKTs = rKTs.trim(); if (rKTsRIDMap.containsKey(rKTs)) { return rKTsRIDMap.get(rKTs); } String rktsid; try { rktsid = String.format("%04d", Integer.parseInt(rKTs.substring(1))); } catch (Exception e) { return null; } if (rKTs.startsWith("K")) { return "W0RKA"+rktsid; } return "W0RTA"+rktsid; } public static final List<Resource> getResourcesFromLine(String[] line) { final Model workModel = ModelFactory.createDefaultModel(); final List<Resource> res = new ArrayList<>(); CommonMigration.setPrefixes(workModel); String rid="W0CDL0"+line[0]; Resource work = workModel.createResource(BDR+rid); res.add(work); workModel.add(work,workModel.createProperty(BDO,"workCatalogInfo"),workModel.createLiteral(line[1], "en")); workModel.add(work,workModel.createProperty(BDO,"workBiblioNote"),workModel.createLiteral(line[2], "en")); workModel.add(work, RDF.type, workModel.createResource(BDO+"Work")); String mainTitle=line[6]; String title=line[3]; Literal l=null; if(title.endsWith("@en")) { l=workModel.createLiteral(title); }else { l=workModel.createLiteral(title,"sa-x-iast"); } String altTitle=line[7]; Resource titleR = workModel.createResource(); workModel.add(work, workModel.createProperty(BDO, "workTitle"), titleR); workModel.add(work,workModel.createProperty(CommonMigration.SKOS_PREFIX,"prefLabel"),l); if(!altTitle.equals("")) { workModel.add(work,workModel.createProperty(CommonMigration.SKOS_PREFIX,"altLabel"),workModel.createLiteral(altTitle, "sa-x-iast")); } if(mainTitle.equals("")) { workModel.add(titleR, workModel.createProperty(BDO, "WorkBibliographicalTitle"), l); }else { workModel.add(titleR, workModel.createProperty(BDO, "WorkBibliographicalTitle"), workModel.createLiteral(mainTitle, "sa-x-iast")); } final String abstractWorkRID = rKTsToBDR(line[4]); if (abstractWorkRID != null) { SymetricNormalization.addSymetricProperty(workModel, "workExpressionOf", rid, abstractWorkRID, null); } if(!line[5].equals("")) { workModel.add(work, workModel.createProperty(BDO, "workIsAbout"), workModel.createResource(CommonMigration.RESOURCE_PREFIX+line[5])); } workModel.add(work, workModel.createProperty(ADM, "license"), workModel.createResource(BDR+"LicenseCopyrighted")); // ? workModel.add(work, workModel.getProperty(ADM+"status"), workModel.createResource(BDR+"StatusReleased")); workModel.add(work, workModel.createProperty(ADM, "access"), workModel.createResource(BDR+"AccessOpen")); workModel.add(work, workModel.createProperty(BDO, "workMaterial"), workModel.createResource(BDR+materials.get(line[9]))); workModel.add(work, workModel.createProperty(BDO,"contentProvider"), workModel.createResource(BDR+"CCDL")); workModel.add(work, workModel.createProperty(BDO,"originalRecord"), workModel.createTypedLiteral("https://cudl.lib.cam.ac.uk/view/"+line[0], XSDDatatype.XSDanyURI)); if(!line[14].equals("")) { workModel.add(work, workModel.createProperty(BDO, "workLangScript"), workModel.createResource(BDR+scripts.get(line[14]))); } if (!line[19].isEmpty()) { work.addProperty(workModel.createProperty(BDO, "workDimWidth"), line[19].replace(',','.').trim(), XSDDatatype.XSDdecimal); } if (!line[18].isEmpty()) { work.addProperty(workModel.createProperty(BDO, "workDimHeight"), line[18].replace(',','.').trim(), XSDDatatype.XSDdecimal); } final Model itemModel = ModelFactory.createDefaultModel(); CommonMigration.setPrefixes(itemModel); final String itemRID = "I0CDL0"+rid; if (WorkMigration.addWorkHasItem) { workModel.add(work, workModel.createProperty(BDO, "workHasItemImageAsset"), workModel.createResource(BDR+itemRID)); } Resource item = itemModel.createResource(BDR+itemRID); res.add(item); itemModel.add(item, RDF.type, itemModel.createResource(BDO+"ItemImageAsset")); final String volumeRID = "V0CDL0"+itemRID.substring(1); Resource volume = itemModel.createResource(BDR+volumeRID); itemModel.add(volume, RDF.type, itemModel.createResource(BDO+"VolumeImageAsset")); if (ImagegroupMigration.addVolumeOf) itemModel.add(volume, itemModel.createProperty(BDO, "volumeOf"), item); if (ImagegroupMigration.addItemHasVolume) itemModel.add(item, itemModel.createProperty(BDO, "itemHasVolume"), volume); itemModel.add(volume, itemModel.createProperty(BDO, "hasIIIFManifest"), itemModel.createResource(line[8])); itemModel.add(volume, itemModel.createProperty(BDO, "volumeNumber"), itemModel.createTypedLiteral(1, XSDDatatype.XSDinteger)); if (WorkMigration.addItemForWork) { itemModel.add(item, itemModel.createProperty(BDO, "itemImageAssetForWork"), itemModel.createResource(BDR+rid)); } if(!line[10].equals("") && !line[11].equals("")) { Resource event = workModel.createResource(); workModel.add(work, workModel.createProperty(BDO, "workEvent"), event); workModel.add(event, RDF.type, workModel.createResource(BDO+"PublishedEvent")); workModel.add(event, workModel.createProperty(BDO, "notAfter"), workModel.createTypedLiteral(line[11], XSDDatatype.XSDinteger)); workModel.add(event, workModel.createProperty(BDO, "notBefore"), workModel.createTypedLiteral(line[10], XSDDatatype.XSDinteger)); } //itemModel.write(System.out,"TURTLE"); return res; } public static void writeCUDLFiles(List<Resource> resources) { for(Resource r: resources) { String uri=r.getProperty(RDF.type).getObject().asResource().getURI(); switch(uri) { case "http://purl.bdrc.io/ontology/core/Work": final String workOutfileName = MigrationApp.getDstFileName("work", r.getLocalName()); MigrationHelpers.outputOneModel(r.getModel(), r.getLocalName(), workOutfileName, "work"); break; case "http://purl.bdrc.io/ontology/core/ItemImageAsset": final String itemOutfileName = MigrationApp.getDstFileName("item", r.getLocalName()); MigrationHelpers.outputOneModel(r.getModel(), r.getLocalName(), itemOutfileName, "item"); break; } } } }
fix a few IDs
src/main/java/io/bdrc/xmltoldmigration/CUDLTransfer.java
fix a few IDs
<ide><path>rc/main/java/io/bdrc/xmltoldmigration/CUDLTransfer.java <ide> final Model workModel = ModelFactory.createDefaultModel(); <ide> final List<Resource> res = new ArrayList<>(); <ide> CommonMigration.setPrefixes(workModel); <del> String rid="W0CDL0"+line[0]; <del> Resource work = workModel.createResource(BDR+rid); <add> String rid=line[0]; <add> Resource work = workModel.createResource(BDR+"W0CDL0"+rid); <ide> res.add(work); <ide> workModel.add(work,workModel.createProperty(BDO,"workCatalogInfo"),workModel.createLiteral(line[1], "en")); <ide> workModel.add(work,workModel.createProperty(BDO,"workBiblioNote"),workModel.createLiteral(line[2], "en")); <ide> Resource item = itemModel.createResource(BDR+itemRID); <ide> res.add(item); <ide> itemModel.add(item, RDF.type, itemModel.createResource(BDO+"ItemImageAsset")); <del> final String volumeRID = "V0CDL0"+itemRID.substring(1); <add> final String volumeRID = "V0CDL0"+rid; <ide> Resource volume = itemModel.createResource(BDR+volumeRID); <ide> itemModel.add(volume, RDF.type, itemModel.createResource(BDO+"VolumeImageAsset")); <ide> if (ImagegroupMigration.addVolumeOf)
Java
bsd-3-clause
d03d0939b6e402701080c3b4637e73f727391f86
0
provegard/tinyws
package com.programmaticallyspeaking.tinyws; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.concurrent.Executor; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; public class Server { public static final String ServerName = "TinyWS Server"; public static final String ServerVersion = "0.0.1"; //TODO: Get from resource private static final String HANDSHAKE_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; private static final int SupportedVersion = 13; private final Executor mainExecutor; private final Executor handlerExecutor; private final Options options; private final Logger logger; private ServerSocket serverSocket; private Map<String, WebSocketHandler> handlers = new HashMap<>(); public Server(Executor mainExecutor, Executor handlerExecutor, Options options) { this.mainExecutor = mainExecutor; this.handlerExecutor = handlerExecutor; this.options = options; this.logger = new Logger() { public void log(LogLevel level, String message, Throwable error) { if (isEnabledAt(level)) { try { options.logger.log(level, message, error); } catch (Exception ignore) { // ignore logging errors } } } @Override public boolean isEnabledAt(LogLevel level) { return options.logger != null && options.logger.isEnabledAt(level); } }; } public void addHandler(String endpoint, WebSocketHandler handler) { if (serverSocket != null) throw new IllegalStateException("Please add handlers before starting the server."); handlers.put(endpoint, handler); } public void start() throws IOException { Integer backlog = options.backlog; serverSocket = backlog == null ? new ServerSocket(options.port) : new ServerSocket(options.port, backlog); mainExecutor.execute(this::acceptInLoop); } public void stop() { if (serverSocket == null) return; try { serverSocket.close(); } catch (IOException e) { logger.log(LogLevel.WARN, "Failed to close server socket.", e); } serverSocket = null; } private void acceptInLoop() { try { if (logger.isEnabledAt(LogLevel.INFO)) logger.log(LogLevel.INFO, "Receiving WebSocket clients at " + serverSocket.getLocalSocketAddress(), null); while (true) { Socket clientSocket = serverSocket.accept(); BiConsumer<WebSocketHandler, Consumer<WebSocketHandler>> wrappedHandlerExecutor = (handler, fun) -> { if (handler != null) handlerExecutor.execute(() -> fun.accept(handler)); }; mainExecutor.execute(new ClientHandler(clientSocket, handlers::get, wrappedHandlerExecutor, logger)); } } catch (SocketException e) { logger.log(LogLevel.DEBUG, "Server socket was closed, probably because the server was stopped.", e); } catch (Exception ex) { logger.log(LogLevel.ERROR, "Error accepting a client socket.", ex); } } private static class ClientHandler implements Runnable { private final Socket clientSocket; private final OutputStream out; private final InputStream in; private final Function<String, WebSocketHandler> handlerLookup; private final BiConsumer<WebSocketHandler, Consumer<WebSocketHandler>> handlerExecutor; private final Logger logger; private final PayloadCoder payloadCoder; private final FrameWriter frameWriter; private WebSocketHandler handler; private volatile boolean isClosed; // potentially set from handler thread ClientHandler(Socket clientSocket, Function<String, WebSocketHandler> handlerLookup, BiConsumer<WebSocketHandler, Consumer<WebSocketHandler>> handlerExecutor, Logger logger) throws IOException { this.clientSocket = clientSocket; out = clientSocket.getOutputStream(); in = clientSocket.getInputStream(); this.handlerLookup = handlerLookup; this.handlerExecutor = handlerExecutor; this.logger = logger; payloadCoder = new PayloadCoder(); frameWriter = new FrameWriter(out, payloadCoder); } @Override public void run() { try { communicate(); } catch (WebSocketError ex) { if (logger.isEnabledAt(LogLevel.DEBUG)) { String msg = String.format("Closing with code %d (%s)%s", ex.code, ex.reason, ex.debugDetails != null ? (" because: " + ex.debugDetails) : ""); logger.log(LogLevel.DEBUG, msg, null); } doIgnoringExceptions(() -> frameWriter.writeCloseFrame(ex.code, ex.reason)); handlerExecutor.accept(handler, h -> h.onClosedByClient(ex.code, ex.reason)); } catch (IllegalArgumentException ex) { if (logger.isEnabledAt(LogLevel.WARN)) logger.log(LogLevel.WARN, String.format("WebSocket client from %s sent a malformed request.", clientSocket.getRemoteSocketAddress()), null); sendBadRequestResponse(); } catch (FileNotFoundException ex) { if (logger.isEnabledAt(LogLevel.WARN)) logger.log(LogLevel.WARN, String.format("WebSocket client from %s requested an unknown endpoint.", clientSocket.getRemoteSocketAddress()), null); sendNotFoundResponse(); } catch (SocketException ex) { if (!isClosed) { logger.log(LogLevel.ERROR, "Client socket error.", ex); handlerExecutor.accept(handler, h -> h.onFailure(ex)); } } catch (Exception ex) { logger.log(LogLevel.ERROR, "Client communication error.", ex); handlerExecutor.accept(handler, h -> h.onFailure(ex)); } abort(); } private void abort() { if (isClosed) return; doIgnoringExceptions(clientSocket::close); isClosed = true; } private void communicate() throws IOException, NoSuchAlgorithmException { Headers headers = Headers.read(in); if (!headers.isProperUpgrade()) throw new IllegalArgumentException("Handshake has malformed upgrade."); if (headers.version() != SupportedVersion) throw new IllegalArgumentException("Bad version, must be: " + SupportedVersion); String endpoint = headers.endpoint; if (endpoint == null) throw new IllegalArgumentException("Missing endpoint."); handler = handlerLookup.apply(endpoint); if (handler == null) throw new FileNotFoundException("Unknown endpoint: " + endpoint); if (logger.isEnabledAt(LogLevel.INFO)) logger.log(LogLevel.INFO, String.format("New WebSocket client from %s at endpoint '%s'.", clientSocket.getRemoteSocketAddress(), endpoint), null); handlerExecutor.accept(handler, h -> h.onOpened(new WebSocketClientImpl(frameWriter, this::abort))); String key = headers.key(); String responseKey = createResponseKey(key); if (logger.isEnabledAt(LogLevel.TRACE)) logger.log(LogLevel.TRACE, String.format("Opening handshake key is '%s', sending response key '%s'.", key, responseKey), null); sendHandshakeResponse(responseKey); List<Frame> frameBatch = new ArrayList<>(); while (true) { frameBatch.add(Frame.read(in)); handleBatch(frameBatch); } } private void handleBatch(List<Frame> frameBatch) throws IOException { Frame firstFrame = frameBatch.get(0); if (firstFrame.opCode == 0) throw WebSocketError.protocolError("Continuation frame with nothing to continue."); Frame lastOne = frameBatch.get(frameBatch.size() - 1); if (logger.isEnabledAt(LogLevel.TRACE)) logger.log(LogLevel.TRACE, lastOne.toString(), null); if (!lastOne.isFin) return; if (firstFrame != lastOne) { if (lastOne.isControl()) { // Interleaved control frame frameBatch.remove(frameBatch.size() - 1); handleResultFrame(lastOne); return; } else if (lastOne.opCode > 0) { throw WebSocketError.protocolError("Continuation frame must have opcode 0."); } } Frame result; if (frameBatch.size() > 1) { // Combine payloads! int totalLength = frameBatch.stream().mapToInt(f -> f.payloadData.length).sum(); byte[] allTheData = new byte[totalLength]; int offs = 0; for (Frame frame : frameBatch) { System.arraycopy(frame.payloadData, 0, allTheData, offs, frame.payloadData.length); offs += frame.payloadData.length; } result = new Frame(firstFrame.opCode, allTheData, true); } else result = lastOne; frameBatch.clear(); handleResultFrame(result); } private void handleResultFrame(Frame result) throws IOException { switch (result.opCode) { case 1: String data = payloadCoder.decode(result.payloadData); handlerExecutor.accept(handler, h -> h.onTextMessage(data)); break; case 2: handlerExecutor.accept(handler, h -> h.onBinaryData(result.payloadData)); break; case 8: CloseData cd = result.toCloseData(payloadCoder); if (cd.hasInvalidCode()) throw WebSocketError.protocolError("Invalid close frame code: " + cd.code); // 1000 is normal close int i = cd.code != null ? cd.code : 1000; throw new WebSocketError(i, "", null); case 9: // Ping, send pong! logger.log(LogLevel.TRACE, "Got ping frame, sending pong.", null); frameWriter.writePongFrame(result.payloadData); break; case 10: // Pong is ignored logger.log(LogLevel.TRACE, "Ignoring unsolicited pong frame.", null); break; default: throw WebSocketError.protocolError("Invalid opcode: " + result.opCode); } } private void outputLine(PrintWriter writer, String data) { System.out.println("> " + data); writer.print(data); writer.print("\r\n"); } private void sendHandshakeResponse(String responseKey) { Map<String, String> headers = new HashMap<String, String>() {{ put("Upgrade", "websocket"); put("Connection", "upgrade"); put("Sec-WebSocket-Accept", responseKey); }}; sendResponse(101, "Switching Protocols", headers); } private void sendBadRequestResponse() { // Advertise supported version regardless of what was bad. A bit lazy, but simple. Map<String, String> headers = new HashMap<String, String>() {{ put("Sec-WebSocket-Version", Integer.toString(SupportedVersion)); }}; sendResponse(400, "Bad Request", headers); } private void sendNotFoundResponse() { sendResponse(404, "Not Found", Collections.emptyMap()); } private void sendResponse(int statusCode, String reason, Map<String, String> headers) { PrintWriter writer = new PrintWriter(out, false); outputLine(writer, "HTTP/1.1 " + statusCode + " " + reason); for (Map.Entry<String, String> entry : headers.entrySet()) { outputLine(writer, entry.getKey() + ": " + entry.getValue()); } // https://tools.ietf.org/html/rfc7231#section-7.4.2 outputLine(writer, String.format("Server: %s %s", ServerName, ServerVersion)); // Headers added when we don't do a connection upgrade to WebSocket! if (statusCode >= 200) { // https://tools.ietf.org/html/rfc7230#section-6.1 outputLine(writer, "Connection: close"); // https://tools.ietf.org/html/rfc7230#section-3.3.2 outputLine(writer, "Content-Length: 0"); } outputLine(writer, ""); writer.flush(); // Note: Do NOT close the writer, as the stream must remain open } } private static class Frame { final int opCode; final byte[] payloadData; final boolean isFin; public String toString() { return String.format("Frame[opcode=%d, control=%b, payload length=%d, fragmented=%b]", opCode, isControl(), payloadData.length, !isFin); } boolean isControl() { return (opCode & 8) == 8; } private Frame(int opCode, byte[] payloadData, boolean isFin) { this.opCode = opCode; this.payloadData = payloadData; this.isFin = isFin; } private static int readUnsignedByte(InputStream in) throws IOException { int b = in.read(); if (b < 0) throw new IOException("End of stream"); return b; } private static int toUnsigned(byte b) { int result = b; if (result < 0) result += 256; return result; } private static byte[] readBytes(InputStream in, int len) throws IOException { byte[] buf = new byte[len]; int totalRead = 0; int offs = 0; while (totalRead < len) { int readLen = in.read(buf, offs, len - offs); if (readLen < 0) break; totalRead += readLen; offs += readLen; } if (totalRead != len) throw new IOException("Expected to read " + len + " bytes but read " + totalRead); return buf; } private static long toLong(byte[] data, int offset, int len) { long result = 0; for (int i = offset, j = offset + len; i < j; i++) { result = (result << 8) + toUnsigned(data[i]); } return result; } private static long toLong(byte[] data) { return toLong(data, 0, data.length); } static Frame read(InputStream in) throws IOException { int firstByte = readUnsignedByte(in); boolean isFin = (firstByte & 128) == 128; boolean hasZeroReserved = (firstByte & 112) == 0; if (!hasZeroReserved) throw WebSocketError.protocolError("Non-zero reserved bits in 1st byte: " + (firstByte & 112)); int opCode = (firstByte & 15); boolean isControlFrame = (opCode & 8) == 8; int secondByte = readUnsignedByte(in); boolean isMasked = (secondByte & 128) == 128; int len = (secondByte & 127); if (isControlFrame) { if (len > 125) throw WebSocketError.protocolError("Control frame length exceeding 125 bytes."); if (!isFin) throw WebSocketError.protocolError("Fragmented control frame."); } if (len == 126) { // 2 bytes of extended len long tmp = toLong(readBytes(in, 2)); len = (int) tmp; } else if (len == 127) { // 8 bytes of extended len long tmp = toLong(readBytes(in, 8)); if (tmp > Integer.MAX_VALUE) throw WebSocketError.protocolError("Frame length greater than 0x7fffffff not supported."); len = (int) tmp; } byte[] maskingKey = isMasked ? readBytes(in, 4) : null; byte[] payloadData = unmaskIfNeededInPlace(readBytes(in, len), maskingKey); return new Frame(opCode, payloadData, isFin); } private static byte[] unmaskIfNeededInPlace(byte[] bytes, byte[] maskingKey) { if (maskingKey != null) { for (int i = 0; i < bytes.length; i++) { int j = i % 4; bytes[i] = (byte) (bytes[i] ^ maskingKey[j]); } } return bytes; } CloseData toCloseData(PayloadCoder payloadCoder) throws WebSocketError { if (opCode != 8) throw new IllegalStateException("Not a close frame: " + opCode); if (payloadData.length == 0) return new CloseData(null, null); if (payloadData.length == 1) throw WebSocketError.protocolError("Invalid close frame payload length (1)."); int code = (int) toLong(payloadData, 0, 2); String reason = payloadData.length > 2 ? payloadCoder.decode(payloadData, 2, payloadData.length - 2) : null; return new CloseData(code, reason); } } private static class CloseData { private final Integer code; private final String reason; CloseData(Integer code, String reason) { this.code = code; this.reason = reason; } boolean hasInvalidCode() { if (code == null) return false; // no code isn't invalid if (code < 1000 || code >= 5000) return true; if (code >= 3000) return false; // 3000-3999 and 4000-4999 are valid return code == 1004 || code == 1005 || code == 1006 || code > 1011; } } static class Headers { private final Map<String, String> headers; final String endpoint; private Headers(Map<String, String> headers, String endpoint) { this.headers = headers; this.endpoint = endpoint; } boolean isProperUpgrade() { return "websocket".equalsIgnoreCase(headers.get("Upgrade")) && "Upgrade".equalsIgnoreCase(headers.get("Connection")); } int version() { String versionStr = headers.get("Sec-WebSocket-Version"); try { return Integer.parseInt(versionStr); } catch (Exception ignore) { return 0; } } String key() { String key = headers.get("Sec-WebSocket-Key"); if (key == null) throw new IllegalArgumentException("Missing Sec-WebSocket-Key in handshake."); return key; } static Headers read(InputStream in) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String inputLine, endpoint = null; Map<String, String> headers = new HashMap<>(); while (!"".equals((inputLine = reader.readLine()))) { if (inputLine.startsWith("GET ")) { String[] parts = inputLine.split(" ", 3); if (parts.length != 3) throw new IOException("Unexpected GET line: " + inputLine); endpoint = parts[1]; } String[] keyValue = inputLine.split(":", 2); if (keyValue.length != 2) continue; System.out.println("< " + inputLine); headers.put(keyValue[0], keyValue[1].trim()); } // Note: Do NOT close the reader, because the stream must remain open! return new Headers(headers, endpoint); } } static class PayloadCoder { private final Charset charset = StandardCharsets.UTF_8; private final CharsetDecoder decoder = charset.newDecoder(); String decode(byte[] bytes) throws WebSocketError { return decode(bytes, 0, bytes.length); } /** * Decodes the given byte data as UTF-8 and returns the result as a string. * * @param bytes the byte array * @param offset offset into the array where to start decoding * @param len length of data to decode * @return the decoded string * @throws WebSocketError (1007) thrown if the data are not valid UTF-8 */ synchronized String decode(byte[] bytes, int offset, int len) throws WebSocketError { decoder.reset(); try { CharBuffer buf = decoder.decode(ByteBuffer.wrap(bytes, offset, len)); return buf.toString(); } catch (Exception ex) { throw WebSocketError.invalidFramePayloadData(); } } byte[] encode(String s) { return s.getBytes(charset); } } static class WebSocketError extends IOException { final int code; final String reason; final String debugDetails; WebSocketError(int code, String reason, String debugDetails) { this.code = code; this.reason = reason; this.debugDetails = debugDetails; } static WebSocketError protocolError(String debugDetails) { return new WebSocketError(1002, "Protocol error", debugDetails); } static WebSocketError invalidFramePayloadData() { return new WebSocketError(1007, "Invalid frame payload data", null); } } static class FrameWriter { private final OutputStream out; private final PayloadCoder payloadCoder; FrameWriter(OutputStream out, PayloadCoder payloadCoder) { this.out = out; this.payloadCoder = payloadCoder; } void writeCloseFrame(int code, String reason) throws IOException { byte[] s = payloadCoder.encode(reason); byte[] numBytes = numberToBytes(code, 2); byte[] combined = new byte[numBytes.length + s.length]; System.arraycopy(numBytes, 0, combined, 0, 2); System.arraycopy(s, 0, combined, 2, s.length); writeFrame(8, combined); } void writeTextFrame(String text) throws IOException { byte[] s = payloadCoder.encode(text); writeFrame(1, s); } void writeBinaryFrame(byte[] data) throws IOException { writeFrame(2, data); } void writePongFrame(byte[] data) throws IOException { writeFrame(10, data); } /** * Writes a frame to the output stream. Since FrameWriter is handed out to potentially different threads, * this method is synchronized. * * @param opCode the opcode of the frame * @param data frame data * @throws IOException thrown if writing to the socket fails */ synchronized void writeFrame(int opCode, byte[] data) throws IOException { int firstByte = 128 | opCode; // FIN + opCode int dataLen = data.length; int secondByte; int extraLengthBytes = 0; if (dataLen < 126) { secondByte = dataLen; // no masking } else if (dataLen < 65536) { secondByte = 126; extraLengthBytes = 2; } else { secondByte = 127; extraLengthBytes = 8; } out.write(firstByte); out.write(secondByte); if (extraLengthBytes > 0) { out.write(numberToBytes(data.length, extraLengthBytes)); } out.write(data); out.flush(); } } private static class WebSocketClientImpl implements WebSocketClient { private final FrameWriter writer; private final Runnable closeCallback; WebSocketClientImpl(FrameWriter writer, Runnable closeCallback) { this.writer = writer; this.closeCallback = closeCallback; } public void close(int code, String reason) throws IOException { writer.writeCloseFrame(code, reason); closeCallback.run(); } public void sendTextMessage(String text) throws IOException { writer.writeTextFrame(text); } public void sendBinaryData(byte[] data) throws IOException { writer.writeBinaryFrame(data); } } static byte[] numberToBytes(int number, int len) { byte[] array = new byte[len]; // Start from the end (network byte order), assume array is filled with zeros. for (int i = len - 1; i >= 0; i--) { array[i] = (byte) (number & 0xff); number = number >> 8; } return array; } static String createResponseKey(String key) throws NoSuchAlgorithmException { MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); byte[] rawBytes = (key + HANDSHAKE_GUID).getBytes(); byte[] result = sha1.digest(rawBytes); return Base64.getEncoder().encodeToString(result); } private static void doIgnoringExceptions(RunnableThatThrows runnable) { try { runnable.run(); } catch (Exception ex) { // ignore } } private interface RunnableThatThrows { void run() throws Exception; } public static class Options { Integer backlog; int port; Logger logger; private Options(int port) { this.port = port; } public static Options withPort(int port) { return new Options(port); } public Options withBacklog(int backlog) { if (backlog < 0) throw new IllegalArgumentException("Backlog must be >= 0"); this.backlog = backlog; return this; } public Options withLogger(Logger logger) { this.logger = logger; return this; } } public enum LogLevel { TRACE(0), DEBUG(10), INFO(20), WARN(50), ERROR(100); public final int level; LogLevel(int level) { this.level = level; } } public interface Logger { void log(LogLevel level, String message, Throwable error); boolean isEnabledAt(LogLevel level); } public interface WebSocketClient { void close(int code, String reason) throws IOException; void sendTextMessage(String text) throws IOException; void sendBinaryData(byte[] data) throws IOException; // TODO: Get user-agent, query string params } public interface WebSocketHandler { void onOpened(WebSocketClient client); void onClosedByClient(int code, String reason); void onFailure(Throwable t); void onTextMessage(String text); void onBinaryData(byte[] data); } }
src/main/java/com/programmaticallyspeaking/tinyws/Server.java
package com.programmaticallyspeaking.tinyws; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.concurrent.Executor; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; public class Server { public static final String ServerName = "TinyWS Server"; public static final String ServerVersion = "0.0.1"; //TODO: Get from resource private static final String HANDSHAKE_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; private static final int SupportedVersion = 13; private final Executor mainExecutor; private final Executor handlerExecutor; private final Options options; private final Logger logger; private ServerSocket serverSocket; private Map<String, WebSocketHandler> handlers = new HashMap<>(); public Server(Executor mainExecutor, Executor handlerExecutor, Options options) { this.mainExecutor = mainExecutor; this.handlerExecutor = handlerExecutor; this.options = options; this.logger = new Logger() { public void log(LogLevel level, String message, Throwable error) { if (isEnabledAt(level)) { try { options.logger.log(level, message, error); } catch (Exception ignore) { // ignore logging errors } } } @Override public boolean isEnabledAt(LogLevel level) { return options.logger != null && options.logger.isEnabledAt(level); } }; } public void addHandler(String endpoint, WebSocketHandler handler) { if (serverSocket != null) throw new IllegalStateException("Please add handlers before starting the server."); handlers.put(endpoint, handler); } public void start() throws IOException { Integer backlog = options.backlog; serverSocket = backlog == null ? new ServerSocket(options.port) : new ServerSocket(options.port, backlog); mainExecutor.execute(this::acceptInLoop); } public void stop() { if (serverSocket == null) return; try { serverSocket.close(); } catch (IOException e) { logger.log(LogLevel.WARN, "Failed to close server socket.", e); } serverSocket = null; } private void acceptInLoop() { try { if (logger.isEnabledAt(LogLevel.INFO)) logger.log(LogLevel.INFO, "Receiving WebSocket clients at " + serverSocket.getLocalSocketAddress(), null); while (true) { Socket clientSocket = serverSocket.accept(); BiConsumer<WebSocketHandler, Consumer<WebSocketHandler>> wrappedHandlerExecutor = (handler, fun) -> { if (handler != null) handlerExecutor.execute(() -> fun.accept(handler)); }; mainExecutor.execute(new ClientHandler(clientSocket, handlers::get, wrappedHandlerExecutor, logger)); } } catch (SocketException e) { logger.log(LogLevel.DEBUG, "Server socket was closed, probably because the server was stopped.", e); } catch (Exception ex) { logger.log(LogLevel.ERROR, "Error accepting a client socket.", ex); } } private static class ClientHandler implements Runnable { private final Socket clientSocket; private final OutputStream out; private final InputStream in; private final Function<String, WebSocketHandler> handlerLookup; private final BiConsumer<WebSocketHandler, Consumer<WebSocketHandler>> handlerExecutor; private final Logger logger; private final PayloadCoder payloadCoder; private final FrameWriter frameWriter; private WebSocketHandler handler; private volatile boolean isClosed; // potentially set from handler thread ClientHandler(Socket clientSocket, Function<String, WebSocketHandler> handlerLookup, BiConsumer<WebSocketHandler, Consumer<WebSocketHandler>> handlerExecutor, Logger logger) throws IOException { this.clientSocket = clientSocket; out = clientSocket.getOutputStream(); in = clientSocket.getInputStream(); this.handlerLookup = handlerLookup; this.handlerExecutor = handlerExecutor; this.logger = logger; payloadCoder = new PayloadCoder(); frameWriter = new FrameWriter(out, payloadCoder); } @Override public void run() { try { communicate(); } catch (WebSocketError ex) { if (logger.isEnabledAt(LogLevel.DEBUG)) { String msg = String.format("Closing with code %d (%s)%s", ex.code, ex.reason, ex.debugDetails != null ? (" because: " + ex.debugDetails) : ""); logger.log(LogLevel.DEBUG, msg, null); } doIgnoringExceptions(() -> frameWriter.writeCloseFrame(ex.code, ex.reason)); handlerExecutor.accept(handler, h -> h.onClosedByClient(ex.code, ex.reason)); } catch (IllegalArgumentException ex) { if (logger.isEnabledAt(LogLevel.WARN)) logger.log(LogLevel.WARN, String.format("WebSocket client from %s sent a malformed request.", clientSocket.getRemoteSocketAddress()), null); sendBadRequestResponse(); } catch (FileNotFoundException ex) { if (logger.isEnabledAt(LogLevel.WARN)) logger.log(LogLevel.WARN, String.format("WebSocket client from %s requested an unknown endpoint.", clientSocket.getRemoteSocketAddress()), null); sendNotFoundResponse(); } catch (SocketException ex) { if (!isClosed) { logger.log(LogLevel.ERROR, "Client socket error.", ex); handlerExecutor.accept(handler, h -> h.onFailure(ex)); } } catch (Exception ex) { logger.log(LogLevel.ERROR, "Client communication error.", ex); handlerExecutor.accept(handler, h -> h.onFailure(ex)); } abort(); } private void abort() { if (isClosed) return; doIgnoringExceptions(clientSocket::close); isClosed = true; } private void communicate() throws IOException, NoSuchAlgorithmException { Headers headers = Headers.read(in); if (!headers.isProperUpgrade()) throw new IllegalArgumentException("Handshake has malformed upgrade."); if (headers.version() != SupportedVersion) throw new IllegalArgumentException("Bad version, must be: " + SupportedVersion); String endpoint = headers.endpoint; if (endpoint == null) throw new IllegalArgumentException("Missing endpoint."); handler = handlerLookup.apply(endpoint); if (handler == null) throw new FileNotFoundException("Unknown endpoint: " + endpoint); if (logger.isEnabledAt(LogLevel.INFO)) logger.log(LogLevel.INFO, String.format("New WebSocket client from %s at endpoint '%s'.", clientSocket.getRemoteSocketAddress(), endpoint), null); handlerExecutor.accept(handler, h -> h.onOpened(new WebSocketClientImpl(frameWriter, this::abort))); String key = headers.key(); String responseKey = createResponseKey(key); if (logger.isEnabledAt(LogLevel.TRACE)) logger.log(LogLevel.TRACE, String.format("Opening handshake key is '%s', sending response key '%s'.", key, responseKey), null); sendHandshakeResponse(responseKey); List<Frame> frameBatch = new ArrayList<>(); while (true) { frameBatch.add(Frame.read(in)); handleBatch(frameBatch); } } private void handleBatch(List<Frame> frameBatch) throws IOException { Frame firstFrame = frameBatch.get(0); if (firstFrame.opCode == 0) throw WebSocketError.protocolError("Continuation frame with nothing to continue."); Frame lastOne = frameBatch.get(frameBatch.size() - 1); if (logger.isEnabledAt(LogLevel.TRACE)) logger.log(LogLevel.TRACE, lastOne.toString(), null); if (!lastOne.isFin) return; if (firstFrame != lastOne) { if (lastOne.isControl()) { // Interleaved control frame frameBatch.remove(frameBatch.size() - 1); handleResultFrame(lastOne); return; } else if (lastOne.opCode > 0) { throw WebSocketError.protocolError("Continuation frame must have opcode 0."); } } Frame result; if (frameBatch.size() > 1) { // Combine payloads! int totalLength = frameBatch.stream().mapToInt(f -> f.payloadData.length).sum(); byte[] allTheData = new byte[totalLength]; int offs = 0; for (Frame frame : frameBatch) { System.arraycopy(frame.payloadData, 0, allTheData, offs, frame.payloadData.length); offs += frame.payloadData.length; } result = new Frame(firstFrame.opCode, allTheData, true); } else result = lastOne; frameBatch.clear(); handleResultFrame(result); } private void handleResultFrame(Frame result) throws IOException { switch (result.opCode) { case 1: String data = payloadCoder.decode(result.payloadData); handlerExecutor.accept(handler, h -> h.onTextMessage(data)); break; case 2: handlerExecutor.accept(handler, h -> h.onBinaryData(result.payloadData)); break; case 8: CloseData cd = result.toCloseData(payloadCoder); if (cd.hasInvalidCode()) throw WebSocketError.protocolError("Invalid close frame code: " + cd.code); // 1000 is normal close int i = cd.code != null ? cd.code : 1000; throw new WebSocketError(i, "", null); case 9: // Ping, send pong! logger.log(LogLevel.TRACE, "Got ping frame, sending pong.", null); frameWriter.writePongFrame(result.payloadData); break; case 10: // Pong is ignored logger.log(LogLevel.TRACE, "Ignoring unsolicited pong frame.", null); break; default: throw WebSocketError.protocolError("Invalid opcode: " + result.opCode); } } private void outputLine(PrintWriter writer, String data) { System.out.println("> " + data); writer.print(data); writer.print("\r\n"); } private void sendHandshakeResponse(String responseKey) { Map<String, String> headers = new HashMap<String, String>() {{ put("Upgrade", "websocket"); put("Connection", "upgrade"); put("Sec-WebSocket-Accept", responseKey); }}; sendResponse(101, "Switching Protocols", headers); } private void sendBadRequestResponse() { // Advertise supported version regardless of what was bad. A bit lazy, but simple. Map<String, String> headers = new HashMap<String, String>() {{ put("Sec-WebSocket-Version", Integer.toString(SupportedVersion)); }}; sendResponse(400, "Bad Request", Collections.emptyMap()); } private void sendNotFoundResponse() { sendResponse(404, "Not Found", Collections.emptyMap()); } private void sendResponse(int statusCode, String reason, Map<String, String> headers) { PrintWriter writer = new PrintWriter(out, false); outputLine(writer, "HTTP/1.1 " + statusCode + " " + reason); for (Map.Entry<String, String> entry : headers.entrySet()) { outputLine(writer, entry.getKey() + ": " + entry.getValue()); } // https://tools.ietf.org/html/rfc7231#section-7.4.2 outputLine(writer, String.format("Server: %s %s", ServerName, ServerVersion)); // Headers added when we don't do a connection upgrade to WebSocket! if (statusCode >= 200) { // https://tools.ietf.org/html/rfc7230#section-6.1 outputLine(writer, "Connection: close"); // https://tools.ietf.org/html/rfc7230#section-3.3.2 outputLine(writer, "Content-Length: 0"); } outputLine(writer, ""); writer.flush(); // Note: Do NOT close the writer, as the stream must remain open } } private static class Frame { final int opCode; final byte[] payloadData; final boolean isFin; public String toString() { return String.format("Frame[opcode=%d, control=%b, payload length=%d, fragmented=%b]", opCode, isControl(), payloadData.length, !isFin); } boolean isControl() { return (opCode & 8) == 8; } private Frame(int opCode, byte[] payloadData, boolean isFin) { this.opCode = opCode; this.payloadData = payloadData; this.isFin = isFin; } private static int readUnsignedByte(InputStream in) throws IOException { int b = in.read(); if (b < 0) throw new IOException("End of stream"); return b; } private static int toUnsigned(byte b) { int result = b; if (result < 0) result += 256; return result; } private static byte[] readBytes(InputStream in, int len) throws IOException { byte[] buf = new byte[len]; int totalRead = 0; int offs = 0; while (totalRead < len) { int readLen = in.read(buf, offs, len - offs); if (readLen < 0) break; totalRead += readLen; offs += readLen; } if (totalRead != len) throw new IOException("Expected to read " + len + " bytes but read " + totalRead); return buf; } private static long toLong(byte[] data, int offset, int len) { long result = 0; for (int i = offset, j = offset + len; i < j; i++) { result = (result << 8) + toUnsigned(data[i]); } return result; } private static long toLong(byte[] data) { return toLong(data, 0, data.length); } static Frame read(InputStream in) throws IOException { int firstByte = readUnsignedByte(in); boolean isFin = (firstByte & 128) == 128; boolean hasZeroReserved = (firstByte & 112) == 0; if (!hasZeroReserved) throw WebSocketError.protocolError("Non-zero reserved bits in 1st byte: " + (firstByte & 112)); int opCode = (firstByte & 15); boolean isControlFrame = (opCode & 8) == 8; int secondByte = readUnsignedByte(in); boolean isMasked = (secondByte & 128) == 128; int len = (secondByte & 127); if (isControlFrame) { if (len > 125) throw WebSocketError.protocolError("Control frame length exceeding 125 bytes."); if (!isFin) throw WebSocketError.protocolError("Fragmented control frame."); } if (len == 126) { // 2 bytes of extended len long tmp = toLong(readBytes(in, 2)); len = (int) tmp; } else if (len == 127) { // 8 bytes of extended len long tmp = toLong(readBytes(in, 8)); if (tmp > Integer.MAX_VALUE) throw WebSocketError.protocolError("Frame length greater than 0x7fffffff not supported."); len = (int) tmp; } byte[] maskingKey = isMasked ? readBytes(in, 4) : null; byte[] payloadData = unmaskIfNeededInPlace(readBytes(in, len), maskingKey); return new Frame(opCode, payloadData, isFin); } private static byte[] unmaskIfNeededInPlace(byte[] bytes, byte[] maskingKey) { if (maskingKey != null) { for (int i = 0; i < bytes.length; i++) { int j = i % 4; bytes[i] = (byte) (bytes[i] ^ maskingKey[j]); } } return bytes; } CloseData toCloseData(PayloadCoder payloadCoder) throws WebSocketError { if (opCode != 8) throw new IllegalStateException("Not a close frame: " + opCode); if (payloadData.length == 0) return new CloseData(null, null); if (payloadData.length == 1) throw WebSocketError.protocolError("Invalid close frame payload length (1)."); int code = (int) toLong(payloadData, 0, 2); String reason = payloadData.length > 2 ? payloadCoder.decode(payloadData, 2, payloadData.length - 2) : null; return new CloseData(code, reason); } } private static class CloseData { private final Integer code; private final String reason; CloseData(Integer code, String reason) { this.code = code; this.reason = reason; } boolean hasInvalidCode() { if (code == null) return false; // no code isn't invalid if (code < 1000 || code >= 5000) return true; if (code >= 3000) return false; // 3000-3999 and 4000-4999 are valid return code == 1004 || code == 1005 || code == 1006 || code > 1011; } } static class Headers { private final Map<String, String> headers; final String endpoint; private Headers(Map<String, String> headers, String endpoint) { this.headers = headers; this.endpoint = endpoint; } boolean isProperUpgrade() { return "websocket".equalsIgnoreCase(headers.get("Upgrade")) && "Upgrade".equalsIgnoreCase(headers.get("Connection")); } int version() { String versionStr = headers.get("Sec-WebSocket-Version"); try { return Integer.parseInt(versionStr); } catch (Exception ignore) { return 0; } } String key() { String key = headers.get("Sec-WebSocket-Key"); if (key == null) throw new IllegalArgumentException("Missing Sec-WebSocket-Key in handshake."); return key; } static Headers read(InputStream in) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String inputLine, endpoint = null; Map<String, String> headers = new HashMap<>(); while (!"".equals((inputLine = reader.readLine()))) { if (inputLine.startsWith("GET ")) { String[] parts = inputLine.split(" ", 3); if (parts.length != 3) throw new IOException("Unexpected GET line: " + inputLine); endpoint = parts[1]; } String[] keyValue = inputLine.split(":", 2); if (keyValue.length != 2) continue; System.out.println("< " + inputLine); headers.put(keyValue[0], keyValue[1].trim()); } // Note: Do NOT close the reader, because the stream must remain open! return new Headers(headers, endpoint); } } static class PayloadCoder { private final Charset charset = StandardCharsets.UTF_8; private final CharsetDecoder decoder = charset.newDecoder(); String decode(byte[] bytes) throws WebSocketError { return decode(bytes, 0, bytes.length); } /** * Decodes the given byte data as UTF-8 and returns the result as a string. * * @param bytes the byte array * @param offset offset into the array where to start decoding * @param len length of data to decode * @return the decoded string * @throws WebSocketError (1007) thrown if the data are not valid UTF-8 */ synchronized String decode(byte[] bytes, int offset, int len) throws WebSocketError { decoder.reset(); try { CharBuffer buf = decoder.decode(ByteBuffer.wrap(bytes, offset, len)); return buf.toString(); } catch (Exception ex) { throw WebSocketError.invalidFramePayloadData(); } } byte[] encode(String s) { return s.getBytes(charset); } } static class WebSocketError extends IOException { final int code; final String reason; final String debugDetails; WebSocketError(int code, String reason, String debugDetails) { this.code = code; this.reason = reason; this.debugDetails = debugDetails; } static WebSocketError protocolError(String debugDetails) { return new WebSocketError(1002, "Protocol error", debugDetails); } static WebSocketError invalidFramePayloadData() { return new WebSocketError(1007, "Invalid frame payload data", null); } } static class FrameWriter { private final OutputStream out; private final PayloadCoder payloadCoder; FrameWriter(OutputStream out, PayloadCoder payloadCoder) { this.out = out; this.payloadCoder = payloadCoder; } void writeCloseFrame(int code, String reason) throws IOException { byte[] s = payloadCoder.encode(reason); byte[] numBytes = numberToBytes(code, 2); byte[] combined = new byte[numBytes.length + s.length]; System.arraycopy(numBytes, 0, combined, 0, 2); System.arraycopy(s, 0, combined, 2, s.length); writeFrame(8, combined); } void writeTextFrame(String text) throws IOException { byte[] s = payloadCoder.encode(text); writeFrame(1, s); } void writeBinaryFrame(byte[] data) throws IOException { writeFrame(2, data); } void writePongFrame(byte[] data) throws IOException { writeFrame(10, data); } /** * Writes a frame to the output stream. Since FrameWriter is handed out to potentially different threads, * this method is synchronized. * * @param opCode the opcode of the frame * @param data frame data * @throws IOException thrown if writing to the socket fails */ synchronized void writeFrame(int opCode, byte[] data) throws IOException { int firstByte = 128 | opCode; // FIN + opCode int dataLen = data.length; int secondByte; int extraLengthBytes = 0; if (dataLen < 126) { secondByte = dataLen; // no masking } else if (dataLen < 65536) { secondByte = 126; extraLengthBytes = 2; } else { secondByte = 127; extraLengthBytes = 8; } out.write(firstByte); out.write(secondByte); if (extraLengthBytes > 0) { out.write(numberToBytes(data.length, extraLengthBytes)); } out.write(data); out.flush(); } } private static class WebSocketClientImpl implements WebSocketClient { private final FrameWriter writer; private final Runnable closeCallback; WebSocketClientImpl(FrameWriter writer, Runnable closeCallback) { this.writer = writer; this.closeCallback = closeCallback; } public void close(int code, String reason) throws IOException { writer.writeCloseFrame(code, reason); closeCallback.run(); } public void sendTextMessage(String text) throws IOException { writer.writeTextFrame(text); } public void sendBinaryData(byte[] data) throws IOException { writer.writeBinaryFrame(data); } } static byte[] numberToBytes(int number, int len) { byte[] array = new byte[len]; // Start from the end (network byte order), assume array is filled with zeros. for (int i = len - 1; i >= 0; i--) { array[i] = (byte) (number & 0xff); number = number >> 8; } return array; } static String createResponseKey(String key) throws NoSuchAlgorithmException { MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); byte[] rawBytes = (key + HANDSHAKE_GUID).getBytes(); byte[] result = sha1.digest(rawBytes); return Base64.getEncoder().encodeToString(result); } private static void doIgnoringExceptions(RunnableThatThrows runnable) { try { runnable.run(); } catch (Exception ex) { // ignore } } private interface RunnableThatThrows { void run() throws Exception; } public static class Options { Integer backlog; int port; Logger logger; private Options(int port) { this.port = port; } public static Options withPort(int port) { return new Options(port); } public Options withBacklog(int backlog) { if (backlog < 0) throw new IllegalArgumentException("Backlog must be >= 0"); this.backlog = backlog; return this; } public Options withLogger(Logger logger) { this.logger = logger; return this; } } public enum LogLevel { TRACE(0), DEBUG(10), INFO(20), WARN(50), ERROR(100); public final int level; LogLevel(int level) { this.level = level; } } public interface Logger { void log(LogLevel level, String message, Throwable error); boolean isEnabledAt(LogLevel level); } public interface WebSocketClient { void close(int code, String reason) throws IOException; void sendTextMessage(String text) throws IOException; void sendBinaryData(byte[] data) throws IOException; // TODO: Get user-agent, query string params } public interface WebSocketHandler { void onOpened(WebSocketClient client); void onClosedByClient(int code, String reason); void onFailure(Throwable t); void onTextMessage(String text); void onBinaryData(byte[] data); } }
Forgot to include the headers with a 400 response
src/main/java/com/programmaticallyspeaking/tinyws/Server.java
Forgot to include the headers with a 400 response
<ide><path>rc/main/java/com/programmaticallyspeaking/tinyws/Server.java <ide> Map<String, String> headers = new HashMap<String, String>() {{ <ide> put("Sec-WebSocket-Version", Integer.toString(SupportedVersion)); <ide> }}; <del> sendResponse(400, "Bad Request", Collections.emptyMap()); <add> sendResponse(400, "Bad Request", headers); <ide> } <ide> private void sendNotFoundResponse() { <ide> sendResponse(404, "Not Found", Collections.emptyMap());
JavaScript
mit
14b28b3f9e7cb9089cd832714b55ae22d3e0edb8
0
zettajs/zetta-device
var EventEmitter = require('events').EventEmitter; var uuid = require('node-uuid'); var streams = require('zetta-streams'); var ObjectStream = streams.ObjectStream; var BinaryStream = streams.BinaryStream; var ConsumerStream = streams.ConsumerStream; var Device = module.exports = function Device() { this.id = uuid.v4(); this.streams = {}; // has __getter__ for consumer streams this._streams = {}; // has actual streams supplied to .stream and .monitor this._emitter = new EventEmitter(); this._allowed = {}; this._transitions = {}; this._monitors = []; this._pubsub = null; this._log = null; var self = this; this.on = function(type, handler) { self._emitter.on(type, handler); }.bind(this); // TODO: Namespace this as something weird so there's no accidental override. this.call = this.call.bind(this); this.emit = this._emitter.emit.bind(this._emitter); }; var ReservedKeys = ['id', 'streams', '_streams', 'type', 'state', '_state', '_allowed', '_transitions', '_monitors']; ['log', 'info', 'warn', 'error'].forEach(function(level) { Device.prototype[level] = function(message, data) { this._log.emit(level, (this.name || this.type || 'device') + '-log', message, data); }; }); // Default Remote Update Hook // Filter _monitors and delete keys that are not in the input Device.prototype._remoteUpdate = function(input, cb) { var self = this; var monitors = this._monitors; var inputKeys = Object.keys(input); var acceptableKeyFilter = function(key) { return monitors.indexOf(key) === -1; }; inputKeys .filter(acceptableKeyFilter) .forEach(function(key) { self[key] = input[key]; }); Object.keys(this._properties()) .filter(acceptableKeyFilter) .forEach(function(key) { if (ReservedKeys.indexOf(key) === -1 && inputKeys.indexOf(key) === -1) { delete self[key]; } }); this.save(cb); }; // Default Remote Fetch Hook Device.prototype._remoteFetch = function() { return this._properties(); }; Device.prototype._remoteDestroy = function(cb) { cb(null, true); }; Device.prototype._generate = function(config) { var self = this; this.type = config._type; this.name = config._name; this._state = config._state; this._transitions = config.transitions; this._allowed = config.allowed; if (Object.keys(this._transitions).length) { var stateStream = self._createStream('state', ObjectStream); Object.defineProperty(this, 'state', { get: function(){ return self._state; }, set: function(newValue){ self._state = newValue; stateStream.write(newValue); } }); } this._monitors = []; Object.keys(config.monitors).forEach(function(name) { var m = config.monitors[name]; self._initMonitor(name, m.options); self._monitors.push(name); }); Object.keys(config.streams).forEach(function(name) { var s = config.streams[name]; self._initStream(name, s.handler, s.options); }); // Update remote fetch handler if (typeof config._remoteFetch === 'function') { this._remoteFetch = config._remoteFetch.bind(this); } // Update remote update handler if (typeof config._remoteUpdate === 'function') { this._remoteUpdate = config._remoteUpdate.bind(this); } if (typeof config._remoteDestroy === 'function') { this._remoteDestroy = config._remoteDestroy.bind(this); } }; Device.prototype.available = function(transition) { var allowed = this._allowed[this.state]; if (!allowed) { return false; } if(allowed.indexOf(transition) > -1) { return true; } else { return false; } }; Device.prototype.call = function(/* type, ...args */) { var args = Array.prototype.slice.call(arguments); var type = args[0]; var next = args[args.length-1]; var self = this; var rest = null; if(typeof next !== 'function') { next = function(err){ if (err) { self._log.emit('log', 'device', 'Error calling ' + self.type + ' transition ' + type + ' (' + err + ')'); } }; rest = args.slice(1, args.length); } else { rest = args.slice(1, args.length - 1); } var cb = function callback(err) { if (err) { next(err); return; } var cbArgs = Array.prototype.slice.call(arguments); cbArgs.unshift(type); self._emitter.emit.apply(self._emitter, cbArgs); var args = []; if (self._transitions[type].fields) { self._transitions[type].fields.forEach(function(field, idx) { args.push({ name: field.name, value: rest[idx] }); }); } self._sendLogStreamEvent(type, args, function(json) { self._log.emit('log', 'device', self.type + ' transition ' + type, json); }); next.apply(next, arguments); }; var handlerArgs = rest.concat([cb]); if(this.state == 'zetta-device-destroy') { return next(new Error('Machine destroyed. Cannot use transition ' + type)); } if (this._transitions[type]) { if(this._transitions[type].handler === undefined){ return next(new Error('Machine does not implement transition '+type)); } var state = self.state; if (self.available(type)) { this._transitions[type].handler.apply(this, handlerArgs); } else { next(new Error('Machine cannot use transition ' + type + ' while in ' + state)); } } else { next(new Error('Machine cannot use transition ' + type + ' not defined')); } }; // Helper method to return normal properties on device that does not get overidden by user // setting a remoteFetch function. Device.prototype._properties = function() { var properties = {}; var self = this; var reserved = ['streams']; Object.keys(self).forEach(function(key) { if (reserved.indexOf(key) === -1 && typeof self[key] !== 'function' && key[0] !== '_') { properties[key] = self[key]; } }); this._monitors.forEach(function(name) { properties[name] = self[name]; }); return properties; }; // External method to return properties using default remote fetch or // user supplied remote fetch call Device.prototype.properties = function() { var properties = this._remoteFetch(); // filter out underscored properties Object.keys(properties).forEach(function(key) { if (key[0] === '_') { delete properties[key]; } }); // overide id, name, type, and state properties.id = this.id; properties.type = this.type; properties.name = this.name; // State not always set if (this.state !== undefined) { properties.state = this.state; } return properties; }; // Called from zetta api resource to handle remote update // Provides filters that should run both on user defined update hook and default hook Device.prototype._handleRemoteUpdate = function(properties, cb) { var self = this; Object.keys(properties).forEach(function(key) { // filter all methods and reserved keys and underscored if (typeof self[key] === 'function' || ReservedKeys.indexOf(key) !== -1 || key[0] === '_') { delete properties[key]; } }); // Either default update hook or user supplied this._remoteUpdate(properties, function(err) { if (err) { return cb(err); } self._sendLogStreamEvent('zetta-properties-update', []); cb(); }); }; Device.prototype._handleRemoteDestroy = function(cb) { this._remoteDestroy(function(err, destroyFlag) { if(err) { return cb(err); } cb(null, destroyFlag); }); }; Device.prototype.save = function(cb) { this._registry.save(this, cb); }; Device.prototype._initMonitor = function(queueName, options) { if(!options) { options = {}; } var stream = this._createStream(queueName, ObjectStream); var self = this; var value = this[queueName]; // initialize value Object.defineProperty(this, queueName, { get: function(){ return value; }, set: function(newValue){ value = newValue; stream.write(newValue); } }); if(options.disable) { this.disableStream(queueName); } return this; }; Device.prototype._initStream = function(queueName, handler, options) { if (!options) { options = {}; } var Type = (options.binary) ? BinaryStream : ObjectStream; var stream = this._createStream(queueName, Type); if(options.disable) { this.disableStream(queueName); } handler.call(this, stream); return this; }; Device.prototype.createReadStream = function(name) { var stream = this._streams[name]; if (!stream) { throw new Error('Steam does not exist: ' + name); } var queue = this.type + '/' + this.id + '/' + name; return new ConsumerStream(queue, { objectMode: stream._writableState.objectMode }, this._pubsub); }; Device.prototype._createStream = function(name, StreamType) { var self = this; var queue = this.type + '/' + this.id + '/' + name; var stream = new StreamType(queue, {}, this._pubsub); this._streams[name] = stream; Object.defineProperty(this.streams, name, { get: function(){ return self.createReadStream(name); } }); return stream; }; Device.prototype.transitionsAvailable = function() { var self = this; var allowed = this._allowed[this.state]; var ret = {}; if (!allowed) { return ret; } Object.keys(this._transitions).forEach(function(name) { if (allowed && allowed.indexOf(name) > -1) { ret[name] = self._transitions[name]; } }); return ret; }; Device.prototype._sendLogStreamEvent = function(transition, args, cb) { var self = this; var topic = self.type + '/' + self.id + '/logs'; var json = ObjectStream.format(topic, null); delete json.data; json.transition = transition; json.input = args; json.properties = self.properties(); json.transitions = self.transitionsAvailable(); self._pubsub.publish(topic, json); if(cb) { cb(json); } }; Device.prototype.destroy = function(cb) { var self = this; if(!cb) { cb = function() {}; } self.emit('destroy', self, cb); }; Device.prototype.enableStream = function(name) { this._streams[name].enabled = true; }; Device.prototype.disableStream = function(name) { this._streams[name].enabled = false; };
device.js
var EventEmitter = require('events').EventEmitter; var uuid = require('node-uuid'); var streams = require('zetta-streams'); var ObjectStream = streams.ObjectStream; var BinaryStream = streams.BinaryStream; var ConsumerStream = streams.ConsumerStream; var Device = module.exports = function Device() { this.id = uuid.v4(); this.streams = {}; // has __getter__ for consumer streams this._streams = {}; // has actual streams supplied to .stream and .monitor this._emitter = new EventEmitter(); this._allowed = {}; this._transitions = {}; this._monitors = []; this._pubsub = null; this._log = null; var self = this; this.on = function(type, handler) { self._emitter.on(type, handler); }.bind(this); // TODO: Namespace this as something weird so there's no accidental override. this.call = this.call.bind(this); this.emit = this._emitter.emit.bind(this._emitter); }; var ReservedKeys = ['id', 'streams', '_streams', 'type', 'state', '_state', '_allowed', '_transitions', '_monitors']; ['log', 'info', 'warn', 'error'].forEach(function(level) { Device.prototype[level] = function(message, data) { this._log.emit(level, (this.name || this.type || 'device') + '-log', message, data); }; }); // Default Remote Update Hook // Filter _monitors and delete keys that are not in the input Device.prototype._remoteUpdate = function(input, cb) { var self = this; var monitors = this._monitors; var inputKeys = Object.keys(input); var acceptableKeyFilter = function(key) { return monitors.indexOf(key) === -1; }; inputKeys .filter(acceptableKeyFilter) .forEach(function(key) { self[key] = input[key]; }); Object.keys(this._properties()) .filter(acceptableKeyFilter) .forEach(function(key) { if (ReservedKeys.indexOf(key) === -1 && inputKeys.indexOf(key) === -1) { delete self[key]; } }); this.save(cb); }; // Default Remote Fetch Hook Device.prototype._remoteFetch = function() { return this._properties(); }; Device.prototype._remoteDestroy = function(cb) { cb(null, true); }; Device.prototype._generate = function(config) { var self = this; this.type = config._type; this.name = config._name; this._state = config._state; this._transitions = config.transitions; this._allowed = config.allowed; if (Object.keys(this._transitions).length) { var stateStream = self._createStream('state', ObjectStream); Object.defineProperty(this, 'state', { get: function(){ return self._state; }, set: function(newValue){ self._state = newValue; stateStream.write(newValue); } }); } this._monitors = []; Object.keys(config.monitors).forEach(function(name) { var m = config.monitors[name]; self._initMonitor(name, m.options); self._monitors.push(name); }); Object.keys(config.streams).forEach(function(name) { var s = config.streams[name]; self._initStream(name, s.handler, s.options); }); // Update remote fetch handler if (typeof config._remoteFetch === 'function') { this._remoteFetch = config._remoteFetch.bind(this); } // Update remote update handler if (typeof config._remoteUpdate === 'function') { this._remoteUpdate = config._remoteUpdate.bind(this); } if (typeof config._remoteDestroy === 'function') { this._remoteDestroy = config._remoteDestroy.bind(this); } }; Device.prototype.available = function(transition) { var allowed = this._allowed[this.state]; if (!allowed) { return false; } if(allowed.indexOf(transition) > -1) { return true; } else { return false; } }; Device.prototype.call = function(/* type, ...args */) { var args = Array.prototype.slice.call(arguments); var type = args[0]; var next = args[args.length-1]; var self = this; var rest = null; if(typeof next !== 'function') { next = function(err){ if (err) { self._log.emit('log', 'device', 'Error calling ' + self.type + ' transition ' + type + ' (' + err + ')'); } }; rest = args.slice(1, args.length); } else { rest = args.slice(1, args.length - 1); } var cb = function callback(err) { if (err) { next(err); return; } var cbArgs = Array.prototype.slice.call(arguments); cbArgs.unshift(type); self._emitter.emit.apply(self._emitter, cbArgs); var args = []; if (self._transitions[type].fields) { self._transitions[type].fields.forEach(function(field, idx) { args.push({ name: field.name, value: rest[idx] }); }); } self._sendLogStreamEvent(type, args, function(json) { self._log.emit('log', 'device', self.type + ' transition ' + type, json); }); next.apply(next, arguments); }; var handlerArgs = rest.concat([cb]); if(this.state == 'zetta-device-destroy') { return next(new Error('Machine destroyed. Cannot use transition ' + type)); } if (this._transitions[type]) { if(this._transitions[type].handler === undefined){ return next(new Error('Machine does not implement transition '+type)); } var state = self.state; if (self.available(type)) { this._transitions[type].handler.apply(this, handlerArgs); } else { next(new Error('Machine cannot use transition ' + type + ' while in ' + state)); } } else { next(new Error('Machine cannot use transition ' + type + ' not defined')); } }; // Helper method to return normal properties on device that does not get overidden by user // setting a remoteFetch function. Device.prototype._properties = function() { var properties = {}; var self = this; var reserved = ['streams']; Object.keys(self).forEach(function(key) { if (reserved.indexOf(key) === -1 && typeof self[key] !== 'function' && key[0] !== '_') { properties[key] = self[key]; } }); this._monitors.forEach(function(name) { properties[name] = self[name]; }); return properties; }; // External method to return properties using default remote fetch or // user supplied remote fetch call Device.prototype.properties = function() { var properties = this._remoteFetch(); // filter out underscored properties Object.keys(properties).forEach(function(key) { if (key[0] === '_') { delete properties[key]; } }); // overide id, name, type, and state properties.id = this.id; properties.type = this.type; properties.name = this.name; // State not always set if (this.state !== undefined) { properties.state = this.state; } return properties; }; // Called from zetta api resource to handle remote update // Provides filters that should run both on user defined update hook and default hook Device.prototype._handleRemoteUpdate = function(properties, cb) { var self = this; Object.keys(properties).forEach(function(key) { // filter all methods and reserved keys and underscored if (typeof self[key] === 'function' || ReservedKeys.indexOf(key) !== -1 || key[0] === '_') { delete properties[key]; } }); // Either default update hook or user supplied this._remoteUpdate(properties, function(err) { if (err) { return cb(err); } self._sendLogStreamEvent('zetta-properties-update', []); cb(); }); }; Device.prototype._handleRemoteDestroy = function(cb) { this._remoteDestroy(function(err, destroyFlag) { if(err) { return cb(err); } cb(null, destroyFlag); }); }; Device.prototype.save = function(cb) { this._registry.save(this, cb); }; Device.prototype._initMonitor = function(queueName, options) { if(!options) { options = {}; } var stream = this._createStream(queueName, ObjectStream); var self = this; var value = this[queueName]; // initialize value Object.defineProperty(this, queueName, { get: function(){ return value; }, set: function(newValue){ value = newValue; stream.write(newValue); } }); if(options.disable) { this.disableStream(queueName); } return this; }; Device.prototype._initStream = function(queueName, handler, options) { if (!options) { options = {}; } var Type = (options.binary) ? BinaryStream : ObjectStream; var stream = this._createStream(queueName, Type); handler.call(this, stream); if(options.disable) { this.disableStream(queueName); } return this; }; Device.prototype.createReadStream = function(name) { var stream = this._streams[name]; if (!stream) { throw new Error('Steam does not exist: ' + name); } var queue = this.type + '/' + this.id + '/' + name; return new ConsumerStream(queue, { objectMode: stream._writableState.objectMode }, this._pubsub); }; Device.prototype._createStream = function(name, StreamType) { var self = this; var queue = this.type + '/' + this.id + '/' + name; var stream = new StreamType(queue, {}, this._pubsub); this._streams[name] = stream; Object.defineProperty(this.streams, name, { get: function(){ return self.createReadStream(name); } }); return stream; }; Device.prototype.transitionsAvailable = function() { var self = this; var allowed = this._allowed[this.state]; var ret = {}; if (!allowed) { return ret; } Object.keys(this._transitions).forEach(function(name) { if (allowed && allowed.indexOf(name) > -1) { ret[name] = self._transitions[name]; } }); return ret; }; Device.prototype._sendLogStreamEvent = function(transition, args, cb) { var self = this; var topic = self.type + '/' + self.id + '/logs'; var json = ObjectStream.format(topic, null); delete json.data; json.transition = transition; json.input = args; json.properties = self.properties(); json.transitions = self.transitionsAvailable(); self._pubsub.publish(topic, json); if(cb) { cb(json); } }; Device.prototype.destroy = function(cb) { var self = this; if(!cb) { cb = function() {}; } self.emit('destroy', self, cb); }; Device.prototype.enableStream = function(name) { this._streams[name].enabled = true; }; Device.prototype.disableStream = function(name) { this._streams[name].enabled = false; };
Moved handler call to after stream is disabled
device.js
Moved handler call to after stream is disabled
<ide><path>evice.js <ide> } <ide> var Type = (options.binary) ? BinaryStream : ObjectStream; <ide> var stream = this._createStream(queueName, Type); <del> handler.call(this, stream); <ide> <ide> if(options.disable) { <ide> this.disableStream(queueName); <ide> } <ide> <add> handler.call(this, stream); <ide> return this; <ide> }; <ide>
Java
bsd-3-clause
bc8078ef8e5e3150bf794a4ce91304c4c7ab1425
0
broadinstitute/gatk-protected,broadinstitute/gatk-protected,broadinstitute/gatk-protected,broadinstitute/gatk-protected,broadinstitute/gatk-protected,broadinstitute/gatk-protected
package org.broadinstitute.hellbender.tools.walkers.mutect; import htsjdk.samtools.SAMSequenceDictionary; import htsjdk.variant.variantcontext.VariantContext; import htsjdk.variant.variantcontext.VariantContextBuilder; import htsjdk.variant.variantcontext.writer.VariantContextWriter; import org.broadinstitute.barclay.argparser.Argument; import org.broadinstitute.barclay.argparser.ArgumentCollection; import org.broadinstitute.barclay.argparser.CommandLineProgramProperties; import org.broadinstitute.hellbender.cmdline.StandardArgumentDefinitions; import org.broadinstitute.hellbender.cmdline.programgroups.VariantProgramGroup; import org.broadinstitute.hellbender.engine.*; import org.broadinstitute.hellbender.engine.filters.ReadFilter; import org.broadinstitute.hellbender.utils.variant.GATKVariantContextUtils; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Call somatic SNPs and indels via local re-assembly of haplotypes * * <p>MuTect2 is a somatic SNP and indel caller that combines the DREAM challenge-winning somatic genotyping engine of the original MuTect (<a href='http://www.nature.com/nbt/journal/v31/n3/full/nbt.2514.html'>Cibulskis et al., 2013</a>) with the assembly-based machinery of <a href="https://www.broadinstitute.org/gatk/documentation/tooldocs/org_broadinstitute_gatk_tools_walkers_haplotypecaller_HaplotypeCaller.php">HaplotypeCaller</a>.</p> * * <h3>How MuTect2 works</h3> * <p>The basic operation of MuTect2 proceeds similarly to that of the HaplotypeCaller, with a few key differences.</p> * <p>While the HaplotypeCaller relies on a ploidy assumption (diploid by default) to inform its genotype likelihood and variant quality calculations, MuTect2 allows for a varying allelic fraction for each variant, as is often seen in tumors with purity less than 100%, multiple subclones, and/or copy number variation (either local or aneuploidy). MuTect2 also differs from the HaplotypeCaller in that it does apply some hard filters to variants before producing output. Finally, some of the parameters used for ActiveRegion determination and graph assembly are set to different default values in MuTect2 compared to HaplotypeCaller.</p> * <p>Note that MuTect2 is designed to produce somatic variant calls only, and includes some logic to skip variant sites that are very clearly germline based on the evidence present in the Normal sample compared to the Tumor sample. This is done at an early stage to avoid spending computational resources on germline events. As a result the tool is NOT capable of emitting records for variant calls that are clearly germline unless it is run in artifact-detection mode, which is used for Panel-Of-Normals creation.</p> * <p>Note also that the GVCF generation capabilities of HaplotypeCaller are NOT available in MuTect2, even though some of the relevant arguments are listed below. There are currently no plans to make GVCF calling available in MuTect2.</p> * * <h3>Usage examples</h3> * <p>These are example commands that show how to run Mutect2 for typical use cases. Square brackets ("[ ]") * indicate optional arguments. Note that parameter values shown here may not be the latest recommended; see the * Best Practices documentation for detailed recommendations. </p> * * <br /> * <h4>Tumor/Normal variant calling</h4> * <pre> * java * -jar GenomeAnalysisTK.jar \ * -T Mutect2 \ * -R reference.fasta \ * -I tumor.bam \ * -I normal.bam \ * -tumor tumorSampleName \ // as in the BAM header * -normal normalSampleName \ // as in the BAM header * [--dbsnp dbSNP.vcf] \ * [--cosmic COSMIC.vcf] \ * [-L targets.interval_list] \ * -o output.vcf * </pre> * * <h4>Normal-only calling for panel of normals creation</h4> * <pre> * java * -jar GenomeAnalysisTK.jar * -T Mutect2 * -R reference.fasta * -I:tumor normal1.bam \ * [--dbsnp dbSNP.vcf] \ * [--cosmic COSMIC.vcf] \ * --artifact_detection_mode \ * [-L targets.interval_list] \ * -o output.normal1.vcf * </pre> * <br /> * For full PON creation, call each of your normals separately in artifact detection mode. Then use CombineVariants to * output only sites where a variant was seen in at least two samples: * <pre> * java -jar GenomeAnalysisTK.jar * -T CombineVariants * -R reference.fasta * -V output.normal1.vcf -V output.normal2.vcf [-V output.normal2.vcf ...] \ * -minN 2 \ * --setKey "null" \ * --filteredAreUncalled \ * --filteredrecordsmergetype KEEP_IF_ANY_UNFILTERED \ * [-L targets.interval_list] \ * -o Mutect2_PON.vcf * </pre> * * <h3>Caveats</h3> * <ul> * <li>Mutect2 currently only supports the calling of a single tumor-normal pair at a time</li> * </ul> * */ @CommandLineProgramProperties( summary = "Call somatic SNPs and indels via local re-assembly of haplotypes", oneLineSummary = "Call somatic SNPs and indels via local re-assembly of haplotypes", programGroup = VariantProgramGroup.class ) public final class Mutect2 extends AssemblyRegionWalker { @ArgumentCollection protected M2ArgumentCollection MTAC = new M2ArgumentCollection(); @Argument(fullName = StandardArgumentDefinitions.OUTPUT_LONG_NAME, shortName = StandardArgumentDefinitions.OUTPUT_SHORT_NAME, doc = "File to which variants should be written") public File outputVCF; private VariantContextWriter vcfWriter; private Mutect2Engine m2Engine; @Override protected int defaultReadShardSize() { return 5000; } @Override protected int defaultReadShardPadding() { return 100; } @Override protected int defaultMinAssemblyRegionSize() { return 50; } @Override protected int defaultMaxAssemblyRegionSize() { return 300; } @Override protected int defaultAssemblyRegionPadding() { return 100; } @Override protected int defaultMaxReadsPerAlignmentStart() { return 50; } @Override protected double defaultActiveProbThreshold() { return 0.002; } @Override protected int defaultMaxProbPropagationDistance() { return 50; } @Override public List<ReadFilter> getDefaultReadFilters() { return Mutect2Engine.makeStandardMutect2ReadFilters(); } @Override public AssemblyRegionEvaluator assemblyRegionEvaluator() { return m2Engine; } @Override public void onTraversalStart() { m2Engine = new Mutect2Engine(MTAC, getHeaderForReads(), referenceArguments.getReferenceFileName()); final SAMSequenceDictionary sequenceDictionary = getHeaderForReads().getSequenceDictionary(); vcfWriter = createVCFWriter(outputVCF); m2Engine.writeHeader(vcfWriter, sequenceDictionary); } @Override public Object onTraversalSuccess() { return "SUCCESS"; } @Override public void apply(final AssemblyRegion region, final ReferenceContext referenceContext, final FeatureContext featureContext ) { m2Engine.callRegion(region, referenceContext, featureContext).stream() // Only include calls that start within the current read shard (as opposed to the padded regions around it). // This is critical to avoid duplicating events that span shard boundaries! .filter(call -> getCurrentReadShardBounds().contains(call)) .forEach(vcfWriter::add); } @Override public void closeTool() { if ( vcfWriter != null ) { vcfWriter.close(); } if ( m2Engine != null ) { m2Engine.shutdown(); } } }
src/main/java/org/broadinstitute/hellbender/tools/walkers/mutect/Mutect2.java
package org.broadinstitute.hellbender.tools.walkers.mutect; import htsjdk.samtools.SAMSequenceDictionary; import htsjdk.variant.variantcontext.VariantContext; import htsjdk.variant.variantcontext.VariantContextBuilder; import htsjdk.variant.variantcontext.writer.VariantContextWriter; import org.broadinstitute.barclay.argparser.Argument; import org.broadinstitute.barclay.argparser.ArgumentCollection; import org.broadinstitute.barclay.argparser.CommandLineProgramProperties; import org.broadinstitute.hellbender.cmdline.StandardArgumentDefinitions; import org.broadinstitute.hellbender.cmdline.programgroups.VariantProgramGroup; import org.broadinstitute.hellbender.engine.*; import org.broadinstitute.hellbender.engine.filters.ReadFilter; import org.broadinstitute.hellbender.utils.variant.GATKVariantContextUtils; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Call somatic SNPs and indels via local re-assembly of haplotypes * * <p>Mutect2 is a somatic SNP and indel caller that combines the DREAM challenge-winning somatic genotyping engine of the original Mutect (<a href='http://www.nature.com/nbt/journal/v31/n3/full/nbt.2514.html'>Cibulskis et al., 2013</a>) with the assembly-based machinery of HaplotypeCaller.</p> * * <p>The basic operation of Mutect2 proceeds similarly to that of the <a href="https://www.broadinstitute.org/gatk/guide/tooldocs/org_broadinstitute_gatk_tools_walkers_haplotypecaller_HaplotypeCaller.php">HaplotypeCaller</a> </p> * * <h3>Differences from HaplotypeCaller</h3> * <p>While the HaplotypeCaller relies on a ploidy assumption (diploid by default) to inform its genotype likelihood and * variant quality calculations, Mutect2 allows for a varying allelic fraction for each variant, as is often seen in tumors with purity less * than 100%, multiple subclones, and/or copy number variation (either local or aneuploidy). Mutect2 also differs from the HaplotypeCaller in that it does apply some hard filters * to variants before producing output.</p> * * <h3>Usage examples</h3> * <p>These are example commands that show how to run Mutect2 for typical use cases. Square brackets ("[ ]") * indicate optional arguments. Note that parameter values shown here may not be the latest recommended; see the * Best Practices documentation for detailed recommendations. </p> * * <br /> * <h4>Tumor/Normal variant calling</h4> * <pre> * java * -jar GenomeAnalysisTK.jar \ * -T Mutect2 \ * -R reference.fasta \ * -I tumor.bam \ * -I normal.bam \ * -tumor tumorSampleName \ // as in the BAM header * -normal normalSampleName \ // as in the BAM header * [--dbsnp dbSNP.vcf] \ * [--cosmic COSMIC.vcf] \ * [-L targets.interval_list] \ * -o output.vcf * </pre> * * <h4>Normal-only calling for panel of normals creation</h4> * <pre> * java * -jar GenomeAnalysisTK.jar * -T Mutect2 * -R reference.fasta * -I:tumor normal1.bam \ * [--dbsnp dbSNP.vcf] \ * [--cosmic COSMIC.vcf] \ * --artifact_detection_mode \ * [-L targets.interval_list] \ * -o output.normal1.vcf * </pre> * <br /> * For full PON creation, call each of your normals separately in artifact detection mode. Then use CombineVariants to * output only sites where a variant was seen in at least two samples: * <pre> * java -jar GenomeAnalysisTK.jar * -T CombineVariants * -R reference.fasta * -V output.normal1.vcf -V output.normal2.vcf [-V output.normal2.vcf ...] \ * -minN 2 \ * --setKey "null" \ * --filteredAreUncalled \ * --filteredrecordsmergetype KEEP_IF_ANY_UNFILTERED \ * [-L targets.interval_list] \ * -o Mutect2_PON.vcf * </pre> * * <h3>Caveats</h3> * <ul> * <li>Mutect2 currently only supports the calling of a single tumor-normal pair at a time</li> * </ul> * */ @CommandLineProgramProperties( summary = "Call somatic SNPs and indels via local re-assembly of haplotypes", oneLineSummary = "Call somatic SNPs and indels via local re-assembly of haplotypes", programGroup = VariantProgramGroup.class ) public final class Mutect2 extends AssemblyRegionWalker { @ArgumentCollection protected M2ArgumentCollection MTAC = new M2ArgumentCollection(); @Argument(fullName = StandardArgumentDefinitions.OUTPUT_LONG_NAME, shortName = StandardArgumentDefinitions.OUTPUT_SHORT_NAME, doc = "File to which variants should be written") public File outputVCF; private VariantContextWriter vcfWriter; private Mutect2Engine m2Engine; @Override protected int defaultReadShardSize() { return 5000; } @Override protected int defaultReadShardPadding() { return 100; } @Override protected int defaultMinAssemblyRegionSize() { return 50; } @Override protected int defaultMaxAssemblyRegionSize() { return 300; } @Override protected int defaultAssemblyRegionPadding() { return 100; } @Override protected int defaultMaxReadsPerAlignmentStart() { return 50; } @Override protected double defaultActiveProbThreshold() { return 0.002; } @Override protected int defaultMaxProbPropagationDistance() { return 50; } @Override public List<ReadFilter> getDefaultReadFilters() { return Mutect2Engine.makeStandardMutect2ReadFilters(); } @Override public AssemblyRegionEvaluator assemblyRegionEvaluator() { return m2Engine; } @Override public void onTraversalStart() { m2Engine = new Mutect2Engine(MTAC, getHeaderForReads(), referenceArguments.getReferenceFileName()); final SAMSequenceDictionary sequenceDictionary = getHeaderForReads().getSequenceDictionary(); vcfWriter = createVCFWriter(outputVCF); m2Engine.writeHeader(vcfWriter, sequenceDictionary); } @Override public Object onTraversalSuccess() { return "SUCCESS"; } @Override public void apply(final AssemblyRegion region, final ReferenceContext referenceContext, final FeatureContext featureContext ) { m2Engine.callRegion(region, referenceContext, featureContext).stream() // Only include calls that start within the current read shard (as opposed to the padded regions around it). // This is critical to avoid duplicating events that span shard boundaries! .filter(call -> getCurrentReadShardBounds().contains(call)) .forEach(vcfWriter::add); } @Override public void closeTool() { if ( vcfWriter != null ) { vcfWriter.close(); } if ( m2Engine != null ) { m2Engine.shutdown(); } } }
Update MuTect2 documentation about not computing obvious germline variants
src/main/java/org/broadinstitute/hellbender/tools/walkers/mutect/Mutect2.java
Update MuTect2 documentation about not computing obvious germline variants
<ide><path>rc/main/java/org/broadinstitute/hellbender/tools/walkers/mutect/Mutect2.java <ide> /** <ide> * Call somatic SNPs and indels via local re-assembly of haplotypes <ide> * <del> * <p>Mutect2 is a somatic SNP and indel caller that combines the DREAM challenge-winning somatic genotyping engine of the original Mutect (<a href='http://www.nature.com/nbt/journal/v31/n3/full/nbt.2514.html'>Cibulskis et al., 2013</a>) with the assembly-based machinery of HaplotypeCaller.</p> <add> * <p>MuTect2 is a somatic SNP and indel caller that combines the DREAM challenge-winning somatic genotyping engine of the original MuTect (<a href='http://www.nature.com/nbt/journal/v31/n3/full/nbt.2514.html'>Cibulskis et al., 2013</a>) with the assembly-based machinery of <a href="https://www.broadinstitute.org/gatk/documentation/tooldocs/org_broadinstitute_gatk_tools_walkers_haplotypecaller_HaplotypeCaller.php">HaplotypeCaller</a>.</p> <ide> * <del> * <p>The basic operation of Mutect2 proceeds similarly to that of the <a href="https://www.broadinstitute.org/gatk/guide/tooldocs/org_broadinstitute_gatk_tools_walkers_haplotypecaller_HaplotypeCaller.php">HaplotypeCaller</a> </p> <del> * <del> * <h3>Differences from HaplotypeCaller</h3> <del> * <p>While the HaplotypeCaller relies on a ploidy assumption (diploid by default) to inform its genotype likelihood and <del> * variant quality calculations, Mutect2 allows for a varying allelic fraction for each variant, as is often seen in tumors with purity less <del> * than 100%, multiple subclones, and/or copy number variation (either local or aneuploidy). Mutect2 also differs from the HaplotypeCaller in that it does apply some hard filters <del> * to variants before producing output.</p> <add> * <h3>How MuTect2 works</h3> <add> * <p>The basic operation of MuTect2 proceeds similarly to that of the HaplotypeCaller, with a few key differences.</p> <add> * <p>While the HaplotypeCaller relies on a ploidy assumption (diploid by default) to inform its genotype likelihood and variant quality calculations, MuTect2 allows for a varying allelic fraction for each variant, as is often seen in tumors with purity less than 100%, multiple subclones, and/or copy number variation (either local or aneuploidy). MuTect2 also differs from the HaplotypeCaller in that it does apply some hard filters to variants before producing output. Finally, some of the parameters used for ActiveRegion determination and graph assembly are set to different default values in MuTect2 compared to HaplotypeCaller.</p> <add> * <p>Note that MuTect2 is designed to produce somatic variant calls only, and includes some logic to skip variant sites that are very clearly germline based on the evidence present in the Normal sample compared to the Tumor sample. This is done at an early stage to avoid spending computational resources on germline events. As a result the tool is NOT capable of emitting records for variant calls that are clearly germline unless it is run in artifact-detection mode, which is used for Panel-Of-Normals creation.</p> <add> * <p>Note also that the GVCF generation capabilities of HaplotypeCaller are NOT available in MuTect2, even though some of the relevant arguments are listed below. There are currently no plans to make GVCF calling available in MuTect2.</p> <ide> * <ide> * <h3>Usage examples</h3> <ide> * <p>These are example commands that show how to run Mutect2 for typical use cases. Square brackets ("[ ]")
Java
mit
7ccb1909b7b6a2362aba7aa782a4cf36009583ac
0
OpenWeen/OpenWeen.Droid
package moe.tlaster.openween.activity; import android.app.Activity; import android.app.ActivityOptions; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.annimon.stream.Stream; import com.bumptech.glide.Glide; import com.github.jorgecastilloprz.FABProgressCircle; import com.klinker.android.sliding.SlidingActivity; import com.mikepenz.google_material_typeface_library.GoogleMaterial; import com.mikepenz.iconics.IconicsDrawable; import com.transitionseverywhere.AutoTransition; import com.transitionseverywhere.Slide; import com.transitionseverywhere.TransitionManager; import com.zhy.http.okhttp.OkHttpUtils; import com.zhy.http.okhttp.callback.BitmapCallback; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import de.hdodenhof.circleimageview.CircleImageView; import moe.tlaster.openween.R; import moe.tlaster.openween.adapter.BaseModelAdapter; import moe.tlaster.openween.common.SimpleDividerItemDecoration; import moe.tlaster.openween.common.StaticResource; import moe.tlaster.openween.common.helpers.JsonCallback; import moe.tlaster.openween.common.helpers.WeiboCardHelper; import moe.tlaster.openween.core.api.blocks.Blocks; import moe.tlaster.openween.core.api.friendships.Friends; import moe.tlaster.openween.core.api.statuses.UserTimeline; import moe.tlaster.openween.core.api.user.User; import moe.tlaster.openween.core.model.status.MessageListModel; import moe.tlaster.openween.core.model.status.MessageModel; import moe.tlaster.openween.core.model.user.UserListModel; import moe.tlaster.openween.core.model.user.UserModel; import okhttp3.Call; /** * Created by Asahi on 2016/10/10. */ public class UserActivity extends SlidingActivity { private UserModel mUser; private CircleImageView mCircleImageView; @BindView(R.id.user_stats_card) public View mStatsCard; @BindView(R.id.user_weibo_card) public View mWeiboCard; @BindView(R.id.user_progressbar) public ProgressBar mProgressBar; @BindView(R.id.user_information) public LinearLayout mLinearLayout; private Menu mMenu; @Override public void init(Bundle savedInstanceState) { setContent(R.layout.activity_user); setPrimaryColors(getResources().getColor(R.color.colorPrimary), getResources().getColor(R.color.colorPrimaryDark)); ButterKnife.bind(this); mProgressBar.getIndeterminateDrawable().setColorFilter(Color.RED, android.graphics.PorterDuff.Mode.SRC_IN); View headerView = getLayoutInflater().inflate(R.layout.user_icon, null); mCircleImageView = (CircleImageView) headerView.findViewById(R.id.user_img); mCircleImageView.setImageDrawable(new IconicsDrawable(this) .icon(GoogleMaterial.Icon.gmd_person) .color(Color.WHITE) .sizeDp(24)); setHeaderContent(headerView); String userName = getIntent().getExtras().getString(getString(R.string.user_page_username_name)); mWeiboCard.findViewById(R.id.user_weibo_all).setOnClickListener(this::goAllWeiboList); mWeiboCard.findViewById(R.id.user_weibo_all_bottom).setOnClickListener(this::goAllWeiboList); User.getUser(userName, new JsonCallback<UserModel>() { @Override public void onError(Call call, Exception e, int id) { Toast.makeText(UserActivity.this, "载入失败", Toast.LENGTH_SHORT).show(); } @Override public void onResponse(UserModel response, int id) { if (isDestroyed()) return; if (response == null) { Toast.makeText(UserActivity.this, "该用户不存在", Toast.LENGTH_SHORT).show(); return; } mUser = response; initMenu(); initUser(); initWeibo(); mProgressBar.setVisibility(View.GONE); } }); } private void initMenu() { if (mUser.getID() == StaticResource.getUid()) { mMenu.clear(); return; } String blockUserid = PreferenceManager.getDefaultSharedPreferences(this).getString(getString(R.string.block_userid_key), null); if (TextUtils.isEmpty(blockUserid)) return; if (Arrays.asList(blockUserid.split(",")).contains(String.valueOf(mUser.getID()))) { mMenu.findItem(R.id.menu_user_block).setTitle("已屏蔽"); } else { mMenu.findItem(R.id.menu_user_block).setTitle("屏蔽"); } } private void goAllWeiboList(View view) { Intent intent = new Intent(this, WeiboListActivity.class); intent.putExtra(getString(R.string.weibo_list_user_id_name), mUser.getID()); startActivity(intent); } private void initWeibo() { UserTimeline.getUserTimeline(mUser.getID(), 3, 1, new JsonCallback<MessageListModel>() { @Override public void onError(Call call, Exception e, int id) { } @Override public void onResponse(MessageListModel response, int id) { if (isDestroyed()) return; if (response.getStatuses().size() > 0) { WeiboCardHelper.setData(mWeiboCard.findViewById(R.id.user_weibo_1), response.getStatuses().get(0), UserActivity.this, true); TransitionManager.beginDelayedTransition(mLinearLayout, new Slide(Gravity.BOTTOM)); mWeiboCard.setVisibility(View.VISIBLE); } else mWeiboCard.setVisibility(View.GONE); if (response.getStatuses().size() > 1) WeiboCardHelper.setData(mWeiboCard.findViewById(R.id.user_weibo_2), response.getStatuses().get(1), UserActivity.this, true); else mWeiboCard.findViewById(R.id.user_weibo_2).setVisibility(View.GONE); if (response.getStatuses().size() > 2) WeiboCardHelper.setData(mWeiboCard.findViewById(R.id.user_weibo_3), response.getStatuses().get(2), UserActivity.this, true); else mWeiboCard.findViewById(R.id.user_weibo_3).setVisibility(View.GONE); } }); } private void initUser() { setTitle(mUser.getScreenName()); if (!TextUtils.isEmpty(mUser.getCoverimage())) OkHttpUtils.get().url(mUser.getCoverimage()).build().execute(new BitmapCallback() { @Override public void onError(Call call, Exception e, int id) { } @Override public void onResponse(Bitmap response, int id) { if (!isDestroyed()) setImage(response); } }); OkHttpUtils.get().url(mUser.getAvatarLarge()).build().execute(new BitmapCallback() { @Override public void onError(Call call, Exception e, int id) { } @Override public void onResponse(Bitmap response, int id) { if (isDestroyed()) return; mCircleImageView.setImageBitmap(response); } }); TransitionManager.beginDelayedTransition(mLinearLayout, new Slide(Gravity.BOTTOM)); mStatsCard.setVisibility(View.VISIBLE); mStatsCard.findViewById(R.id.user_stats_following_layout).setOnClickListener(view -> { Intent intent = new Intent(this, UserListActivity.class); intent.putExtra(getString(R.string.weibo_list_user_id_name), mUser.getID()); intent.putExtra(getString(R.string.user_list_type_name), UserListActivity.USER_LIST_TYPE_FOLLOWING); startActivity(intent); }); mStatsCard.findViewById(R.id.user_stats_follower_layout).setOnClickListener(view -> { Intent intent = new Intent(this, UserListActivity.class); intent.putExtra(getString(R.string.weibo_list_user_id_name), mUser.getID()); intent.putExtra(getString(R.string.user_list_type_name), UserListActivity.USER_LIST_TYPE_FOLLOWER); startActivity(intent); }); ((TextView) mStatsCard.findViewById(R.id.user_stats_user_des)).setText(mUser.getDescription()); ((TextView) mStatsCard.findViewById(R.id.user_stats_follower_count)).setText(String.valueOf(mUser.getFollowersCount())); ((TextView) mStatsCard.findViewById(R.id.user_stats_following_count)).setText(String.valueOf(mUser.getFriendsCount())); if (!TextUtils.isEmpty(mUser.getUrl())) ((TextView) mStatsCard.findViewById(R.id.user_stats_url)).setText(mUser.getUrl()); else mStatsCard.findViewById(R.id.user_stats_url_box).setVisibility(View.GONE); if (!TextUtils.isEmpty(mUser.getLocation())) ((TextView) mStatsCard.findViewById(R.id.user_stats_location)).setText(mUser.getLocation()); else mStatsCard.findViewById(R.id.user_stats_location_box).setVisibility(View.GONE); if (!TextUtils.isEmpty(mUser.getVerifiedReason())) ((TextView) mStatsCard.findViewById(R.id.user_verified_reason)).setText(mUser.getVerifiedReason()); else mStatsCard.findViewById(R.id.user_stats_verified_box).setVisibility(View.GONE); ((TextView) mStatsCard.findViewById(R.id.user_stats_created_time)).setText(mUser.getCreatedAtDiffForHuman()); checkForFollowState(); mStatsCard.findViewById(R.id.user_stats_follow_state).setOnClickListener(view -> { mProgressBar.setVisibility(View.VISIBLE); mStatsCard.findViewById(R.id.user_stats_follow_state).setEnabled(false); if (mUser.isFollowing()) { Friends.unfollow(mUser.getID(), new JsonCallback<UserModel>() { @Override public void onError(Call call, Exception e, int id) { Toast.makeText(UserActivity.this, "取消关注失败", Toast.LENGTH_SHORT).show(); mProgressBar.setVisibility(View.GONE); mStatsCard.findViewById(R.id.user_stats_follow_state).setEnabled(true); } @Override public void onResponse(UserModel response, int id) { mUser.setFollowing(!mUser.isFollowing()); checkForFollowState(); mProgressBar.setVisibility(View.GONE); mStatsCard.findViewById(R.id.user_stats_follow_state).setEnabled(true); } }); } else { Friends.follow(mUser.getID(), new JsonCallback<UserModel>() { @Override public void onError(Call call, Exception e, int id) { Toast.makeText(UserActivity.this, "关注失败", Toast.LENGTH_SHORT).show(); mProgressBar.setVisibility(View.GONE); mStatsCard.findViewById(R.id.user_stats_follow_state).setEnabled(true); } @Override public void onResponse(UserModel response, int id) { mUser.setFollowing(!mUser.isFollowing()); checkForFollowState(); mProgressBar.setVisibility(View.GONE); mStatsCard.findViewById(R.id.user_stats_follow_state).setEnabled(true); } }); } }); Friends.getFollowers(mUser.getID(), 3, 0, new JsonCallback<UserListModel>() { @Override public void onError(Call call, Exception e, int id) { } @Override public void onResponse(UserListModel response, int id) { if (isDestroyed()) return; if (response.getUsers().size() > 0) Glide.with(UserActivity.this).load(response.getUsers().get(0).getAvatarLarge()).fitCenter().crossFade().into(((CircleImageView) mStatsCard.findViewById(R.id.user_stats_follower_icon_1))); if (response.getUsers().size() > 1) Glide.with(UserActivity.this).load(response.getUsers().get(1).getAvatarLarge()).fitCenter().crossFade().into(((CircleImageView) mStatsCard.findViewById(R.id.user_stats_follower_icon_2))); if (response.getUsers().size() > 2) Glide.with(UserActivity.this).load(response.getUsers().get(2).getAvatarLarge()).fitCenter().crossFade().into(((CircleImageView) mStatsCard.findViewById(R.id.user_stats_follower_icon_3))); } }); Friends.getFriends(mUser.getID(), 3, 0, new JsonCallback<UserListModel>() { @Override public void onError(Call call, Exception e, int id) { } @Override public void onResponse(UserListModel response, int id) { if (isDestroyed()) return; if (response.getUsers().size() > 0) Glide.with(UserActivity.this).load(response.getUsers().get(0).getAvatarLarge()).fitCenter().crossFade().into(((CircleImageView) mStatsCard.findViewById(R.id.user_stats_following_icon_1))); if (response.getUsers().size() > 1) Glide.with(UserActivity.this).load(response.getUsers().get(1).getAvatarLarge()).fitCenter().crossFade().into(((CircleImageView) mStatsCard.findViewById(R.id.user_stats_following_icon_2))); if (response.getUsers().size() > 2) Glide.with(UserActivity.this).load(response.getUsers().get(2).getAvatarLarge()).fitCenter().crossFade().into(((CircleImageView) mStatsCard.findViewById(R.id.user_stats_following_icon_3))); } }); } private void checkForFollowState() { if (mUser.isFollowing() && mUser.isFollowMe()) ((Button) mStatsCard.findViewById(R.id.user_stats_follow_state)).setText("互相关注"); else if (mUser.isFollowMe()) ((Button) mStatsCard.findViewById(R.id.user_stats_follow_state)).setText("被关注"); else if (mUser.isFollowing()) ((Button) mStatsCard.findViewById(R.id.user_stats_follow_state)).setText("正在关注"); else if (mUser.getID() == StaticResource.getUid()) mStatsCard.findViewById(R.id.user_stats_follow_state).setVisibility(View.INVISIBLE); else ((Button) mStatsCard.findViewById(R.id.user_stats_follow_state)).setText("关注"); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_user, menu); mMenu = menu; return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (mUser != null) { switch (item.getItemId()) { case R.id.menu_user_block: String blockUserid = PreferenceManager.getDefaultSharedPreferences(this).getString(getString(R.string.block_userid_key), null); List<String> blockList; if (TextUtils.isEmpty(blockUserid)) blockList = new ArrayList<>(); else blockList = new ArrayList<>(Arrays.asList(blockUserid.split(","))); if (!blockList.contains(String.valueOf(mUser.getID()))) { blockList.add(String.valueOf(mUser.getID())); mMenu.findItem(R.id.menu_user_block).setTitle("已屏蔽"); } else { blockList.remove(String.valueOf(mUser.getID())); mMenu.findItem(R.id.menu_user_block).setTitle("屏蔽"); } PreferenceManager.getDefaultSharedPreferences(this).edit().putString(getString(R.string.block_userid_key), TextUtils.join(",", blockList)).apply(); break; case R.id.menu_user_blacklist: Blocks.addBlock(mUser.getID(), new JsonCallback<UserModel>() { @Override public void onError(Call call, Exception e, int id) { } @Override public void onResponse(UserModel response, int id) { Toast.makeText(UserActivity.this, "丢进黑名单成功", Toast.LENGTH_SHORT).show(); } }); break; case R.id.menu_user_directmessage: Intent intent = new Intent(this, DirectMessageActivity.class); intent.putExtra(getString(R.string.user_item_name), mUser); startActivity(intent); break; } } return super.onOptionsItemSelected(item); } }
app/src/main/java/moe/tlaster/openween/activity/UserActivity.java
package moe.tlaster.openween.activity; import android.app.Activity; import android.app.ActivityOptions; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.annimon.stream.Stream; import com.bumptech.glide.Glide; import com.github.jorgecastilloprz.FABProgressCircle; import com.klinker.android.sliding.SlidingActivity; import com.mikepenz.google_material_typeface_library.GoogleMaterial; import com.mikepenz.iconics.IconicsDrawable; import com.transitionseverywhere.AutoTransition; import com.transitionseverywhere.Slide; import com.transitionseverywhere.TransitionManager; import com.zhy.http.okhttp.OkHttpUtils; import com.zhy.http.okhttp.callback.BitmapCallback; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import de.hdodenhof.circleimageview.CircleImageView; import moe.tlaster.openween.R; import moe.tlaster.openween.adapter.BaseModelAdapter; import moe.tlaster.openween.common.SimpleDividerItemDecoration; import moe.tlaster.openween.common.StaticResource; import moe.tlaster.openween.common.helpers.JsonCallback; import moe.tlaster.openween.common.helpers.WeiboCardHelper; import moe.tlaster.openween.core.api.blocks.Blocks; import moe.tlaster.openween.core.api.friendships.Friends; import moe.tlaster.openween.core.api.statuses.UserTimeline; import moe.tlaster.openween.core.api.user.User; import moe.tlaster.openween.core.model.status.MessageListModel; import moe.tlaster.openween.core.model.status.MessageModel; import moe.tlaster.openween.core.model.user.UserListModel; import moe.tlaster.openween.core.model.user.UserModel; import okhttp3.Call; /** * Created by Asahi on 2016/10/10. */ public class UserActivity extends SlidingActivity { private UserModel mUser; private CircleImageView mCircleImageView; @BindView(R.id.user_stats_card) public View mStatsCard; @BindView(R.id.user_weibo_card) public View mWeiboCard; @BindView(R.id.user_progressbar) public ProgressBar mProgressBar; @BindView(R.id.user_information) public LinearLayout mLinearLayout; private Menu mMenu; @Override public void init(Bundle savedInstanceState) { setContent(R.layout.activity_user); setPrimaryColors(getResources().getColor(R.color.colorPrimary), getResources().getColor(R.color.colorPrimaryDark)); ButterKnife.bind(this); mProgressBar.getIndeterminateDrawable().setColorFilter(Color.RED, android.graphics.PorterDuff.Mode.SRC_IN); View headerView = getLayoutInflater().inflate(R.layout.user_icon, null); mCircleImageView = (CircleImageView) headerView.findViewById(R.id.user_img); mCircleImageView.setImageDrawable(new IconicsDrawable(this) .icon(GoogleMaterial.Icon.gmd_person) .color(Color.WHITE) .sizeDp(24)); setHeaderContent(headerView); String userName = getIntent().getExtras().getString(getString(R.string.user_page_username_name)); mWeiboCard.findViewById(R.id.user_weibo_all).setOnClickListener(this::goAllWeiboList); mWeiboCard.findViewById(R.id.user_weibo_all_bottom).setOnClickListener(this::goAllWeiboList); User.getUser(userName, new JsonCallback<UserModel>() { @Override public void onError(Call call, Exception e, int id) { Toast.makeText(UserActivity.this, "载入失败", Toast.LENGTH_SHORT).show(); } @Override public void onResponse(UserModel response, int id) { if (isDestroyed()) return; if (response == null) { Toast.makeText(UserActivity.this, "该用户不存在", Toast.LENGTH_SHORT).show(); return; } mUser = response; initMenu(); initUser(); initWeibo(); mProgressBar.setVisibility(View.GONE); } }); } private void initMenu() { if (mUser.getID() == StaticResource.getUid()) mMenu.clear(); String blockUserid = PreferenceManager.getDefaultSharedPreferences(this).getString(getString(R.string.block_userid_key), null); if (TextUtils.isEmpty(blockUserid)) return; if (Arrays.asList(blockUserid.split(",")).contains(String.valueOf(mUser.getID()))) { mMenu.findItem(R.id.menu_user_block).setTitle("已屏蔽"); } else { mMenu.findItem(R.id.menu_user_block).setTitle("屏蔽"); } } private void goAllWeiboList(View view) { Intent intent = new Intent(this, WeiboListActivity.class); intent.putExtra(getString(R.string.weibo_list_user_id_name), mUser.getID()); startActivity(intent); } private void initWeibo() { UserTimeline.getUserTimeline(mUser.getID(), 3, 1, new JsonCallback<MessageListModel>() { @Override public void onError(Call call, Exception e, int id) { } @Override public void onResponse(MessageListModel response, int id) { if (isDestroyed()) return; if (response.getStatuses().size() > 0) { WeiboCardHelper.setData(mWeiboCard.findViewById(R.id.user_weibo_1), response.getStatuses().get(0), UserActivity.this, true); TransitionManager.beginDelayedTransition(mLinearLayout, new Slide(Gravity.BOTTOM)); mWeiboCard.setVisibility(View.VISIBLE); } else mWeiboCard.setVisibility(View.GONE); if (response.getStatuses().size() > 1) WeiboCardHelper.setData(mWeiboCard.findViewById(R.id.user_weibo_2), response.getStatuses().get(1), UserActivity.this, true); else mWeiboCard.findViewById(R.id.user_weibo_2).setVisibility(View.GONE); if (response.getStatuses().size() > 2) WeiboCardHelper.setData(mWeiboCard.findViewById(R.id.user_weibo_3), response.getStatuses().get(2), UserActivity.this, true); else mWeiboCard.findViewById(R.id.user_weibo_3).setVisibility(View.GONE); } }); } private void initUser() { setTitle(mUser.getScreenName()); if (!TextUtils.isEmpty(mUser.getCoverimage())) OkHttpUtils.get().url(mUser.getCoverimage()).build().execute(new BitmapCallback() { @Override public void onError(Call call, Exception e, int id) { } @Override public void onResponse(Bitmap response, int id) { if (!isDestroyed()) setImage(response); } }); OkHttpUtils.get().url(mUser.getAvatarLarge()).build().execute(new BitmapCallback() { @Override public void onError(Call call, Exception e, int id) { } @Override public void onResponse(Bitmap response, int id) { if (isDestroyed()) return; mCircleImageView.setImageBitmap(response); } }); TransitionManager.beginDelayedTransition(mLinearLayout, new Slide(Gravity.BOTTOM)); mStatsCard.setVisibility(View.VISIBLE); mStatsCard.findViewById(R.id.user_stats_following_layout).setOnClickListener(view -> { Intent intent = new Intent(this, UserListActivity.class); intent.putExtra(getString(R.string.weibo_list_user_id_name), mUser.getID()); intent.putExtra(getString(R.string.user_list_type_name), UserListActivity.USER_LIST_TYPE_FOLLOWING); startActivity(intent); }); mStatsCard.findViewById(R.id.user_stats_follower_layout).setOnClickListener(view -> { Intent intent = new Intent(this, UserListActivity.class); intent.putExtra(getString(R.string.weibo_list_user_id_name), mUser.getID()); intent.putExtra(getString(R.string.user_list_type_name), UserListActivity.USER_LIST_TYPE_FOLLOWER); startActivity(intent); }); ((TextView) mStatsCard.findViewById(R.id.user_stats_user_des)).setText(mUser.getDescription()); ((TextView) mStatsCard.findViewById(R.id.user_stats_follower_count)).setText(String.valueOf(mUser.getFollowersCount())); ((TextView) mStatsCard.findViewById(R.id.user_stats_following_count)).setText(String.valueOf(mUser.getFriendsCount())); if (!TextUtils.isEmpty(mUser.getUrl())) ((TextView) mStatsCard.findViewById(R.id.user_stats_url)).setText(mUser.getUrl()); else mStatsCard.findViewById(R.id.user_stats_url_box).setVisibility(View.GONE); if (!TextUtils.isEmpty(mUser.getLocation())) ((TextView) mStatsCard.findViewById(R.id.user_stats_location)).setText(mUser.getLocation()); else mStatsCard.findViewById(R.id.user_stats_location_box).setVisibility(View.GONE); if (!TextUtils.isEmpty(mUser.getVerifiedReason())) ((TextView) mStatsCard.findViewById(R.id.user_verified_reason)).setText(mUser.getVerifiedReason()); else mStatsCard.findViewById(R.id.user_stats_verified_box).setVisibility(View.GONE); ((TextView) mStatsCard.findViewById(R.id.user_stats_created_time)).setText(mUser.getCreatedAtDiffForHuman()); checkForFollowState(); mStatsCard.findViewById(R.id.user_stats_follow_state).setOnClickListener(view -> { mProgressBar.setVisibility(View.VISIBLE); mStatsCard.findViewById(R.id.user_stats_follow_state).setEnabled(false); if (mUser.isFollowing()) { Friends.unfollow(mUser.getID(), new JsonCallback<UserModel>() { @Override public void onError(Call call, Exception e, int id) { Toast.makeText(UserActivity.this, "取消关注失败", Toast.LENGTH_SHORT).show(); mProgressBar.setVisibility(View.GONE); mStatsCard.findViewById(R.id.user_stats_follow_state).setEnabled(true); } @Override public void onResponse(UserModel response, int id) { mUser.setFollowing(!mUser.isFollowing()); checkForFollowState(); mProgressBar.setVisibility(View.GONE); mStatsCard.findViewById(R.id.user_stats_follow_state).setEnabled(true); } }); } else { Friends.follow(mUser.getID(), new JsonCallback<UserModel>() { @Override public void onError(Call call, Exception e, int id) { Toast.makeText(UserActivity.this, "关注失败", Toast.LENGTH_SHORT).show(); mProgressBar.setVisibility(View.GONE); mStatsCard.findViewById(R.id.user_stats_follow_state).setEnabled(true); } @Override public void onResponse(UserModel response, int id) { mUser.setFollowing(!mUser.isFollowing()); checkForFollowState(); mProgressBar.setVisibility(View.GONE); mStatsCard.findViewById(R.id.user_stats_follow_state).setEnabled(true); } }); } }); Friends.getFollowers(mUser.getID(), 3, 0, new JsonCallback<UserListModel>() { @Override public void onError(Call call, Exception e, int id) { } @Override public void onResponse(UserListModel response, int id) { if (isDestroyed()) return; if (response.getUsers().size() > 0) Glide.with(UserActivity.this).load(response.getUsers().get(0).getAvatarLarge()).fitCenter().crossFade().into(((CircleImageView) mStatsCard.findViewById(R.id.user_stats_follower_icon_1))); if (response.getUsers().size() > 1) Glide.with(UserActivity.this).load(response.getUsers().get(1).getAvatarLarge()).fitCenter().crossFade().into(((CircleImageView) mStatsCard.findViewById(R.id.user_stats_follower_icon_2))); if (response.getUsers().size() > 2) Glide.with(UserActivity.this).load(response.getUsers().get(2).getAvatarLarge()).fitCenter().crossFade().into(((CircleImageView) mStatsCard.findViewById(R.id.user_stats_follower_icon_3))); } }); Friends.getFriends(mUser.getID(), 3, 0, new JsonCallback<UserListModel>() { @Override public void onError(Call call, Exception e, int id) { } @Override public void onResponse(UserListModel response, int id) { if (isDestroyed()) return; if (response.getUsers().size() > 0) Glide.with(UserActivity.this).load(response.getUsers().get(0).getAvatarLarge()).fitCenter().crossFade().into(((CircleImageView) mStatsCard.findViewById(R.id.user_stats_following_icon_1))); if (response.getUsers().size() > 1) Glide.with(UserActivity.this).load(response.getUsers().get(1).getAvatarLarge()).fitCenter().crossFade().into(((CircleImageView) mStatsCard.findViewById(R.id.user_stats_following_icon_2))); if (response.getUsers().size() > 2) Glide.with(UserActivity.this).load(response.getUsers().get(2).getAvatarLarge()).fitCenter().crossFade().into(((CircleImageView) mStatsCard.findViewById(R.id.user_stats_following_icon_3))); } }); } private void checkForFollowState() { if (mUser.isFollowing() && mUser.isFollowMe()) ((Button) mStatsCard.findViewById(R.id.user_stats_follow_state)).setText("互相关注"); else if (mUser.isFollowMe()) ((Button) mStatsCard.findViewById(R.id.user_stats_follow_state)).setText("被关注"); else if (mUser.isFollowing()) ((Button) mStatsCard.findViewById(R.id.user_stats_follow_state)).setText("正在关注"); else if (mUser.getID() == StaticResource.getUid()) mStatsCard.findViewById(R.id.user_stats_follow_state).setVisibility(View.INVISIBLE); else ((Button) mStatsCard.findViewById(R.id.user_stats_follow_state)).setText("关注"); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_user, menu); mMenu = menu; return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (mUser != null) { switch (item.getItemId()) { case R.id.menu_user_block: String blockUserid = PreferenceManager.getDefaultSharedPreferences(this).getString(getString(R.string.block_userid_key), null); List<String> blockList; if (TextUtils.isEmpty(blockUserid)) blockList = new ArrayList<>(); else blockList = new ArrayList<>(Arrays.asList(blockUserid.split(","))); if (!blockList.contains(String.valueOf(mUser.getID()))) { blockList.add(String.valueOf(mUser.getID())); mMenu.findItem(R.id.menu_user_block).setTitle("已屏蔽"); } else { blockList.remove(String.valueOf(mUser.getID())); mMenu.findItem(R.id.menu_user_block).setTitle("屏蔽"); } PreferenceManager.getDefaultSharedPreferences(this).edit().putString(getString(R.string.block_userid_key), TextUtils.join(",", blockList)).apply(); break; case R.id.menu_user_blacklist: Blocks.addBlock(mUser.getID(), new JsonCallback<UserModel>() { @Override public void onError(Call call, Exception e, int id) { } @Override public void onResponse(UserModel response, int id) { Toast.makeText(UserActivity.this, "丢进黑名单成功", Toast.LENGTH_SHORT).show(); } }); break; case R.id.menu_user_directmessage: Intent intent = new Intent(this, DirectMessageActivity.class); intent.putExtra(getString(R.string.user_item_name), mUser); startActivity(intent); break; } } return super.onOptionsItemSelected(item); } }
fix #6
app/src/main/java/moe/tlaster/openween/activity/UserActivity.java
fix #6
<ide><path>pp/src/main/java/moe/tlaster/openween/activity/UserActivity.java <ide> } <ide> <ide> private void initMenu() { <del> if (mUser.getID() == StaticResource.getUid()) mMenu.clear(); <add> if (mUser.getID() == StaticResource.getUid()) { <add> mMenu.clear(); <add> return; <add> } <ide> String blockUserid = PreferenceManager.getDefaultSharedPreferences(this).getString(getString(R.string.block_userid_key), null); <ide> if (TextUtils.isEmpty(blockUserid)) return; <ide> if (Arrays.asList(blockUserid.split(",")).contains(String.valueOf(mUser.getID()))) {
JavaScript
bsd-2-clause
55bd53e3dae690f99658a1adeb28acbfcb7a6057
0
mcanthony/RiverTrail,mcanthony/RiverTrail,mcanthony/RiverTrail
/* * Copyright (c) 2011, Intel Corporation * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ "use strict"; //////////////////// //ParallelArray // The constructor for ParallelArrays // Synopsis: // ParallelArray(); // ParallelArray(size, elementalFunction, ...); // ParallelArray(anArray); // ParallelArray(constructor, anArray); // ParallelArray(element0, element1, ... elementN); // ParallelArray(canvas); // Arguments // none // return a ParallelArray without elements. // argument 0 is an Array and there are no more arguments then use the // values in the array to populate the new ParallelArray // argument 1 is an instanceOf Function (the elemental function), // argument 0 is the "size", remaining .. arguments // return a ParallelArray of "size" where each value is the result // of calling the elemental function with the index where its // result goes and any remaining ... arguments // If the size argument is a vector, the index passed to // the elemental function will be a vector, too. If, however, // the size vector is a single scalar value, the index passed to // the elemental value will be a value, as well. // argument 0 is a function and there is one more argument then construct // a new parallel array as above but use the first // argument as constructor for the internal data container; // This form can be used to force the ParallelArray to hold // its data as a typed array // // otherwise Create a ParallelArray initialized to the elements passed // in as arguments. // Discussion // To create a parallel array whose first element is an instanceOf function // one must use the elemental function form and have the elemental function // return the function. // It also means that if one wants to create a ParallelArray with // a single element that is an Array then it must use the // elemental function form with a size of 1 and return the // array from the elemental function. // // Returns // A freshly minted ParallelArray // Notes // <…> is used to indicate a ParallelArray in these examples it is not syntactical sugar actually available to the program. // // pa1 = new ParallelArray(\[[0,1], [2,3], [4,5]]); // <<0,1>, <2,3>, <4.5>> // pa2 = new ParallelArray(pa1); // <<0,1>, <2,3>, <4.5>> // new ParallelArray(<0,1>, <2,3>); // <<0,1>,<2,3>> // new ParallelArray([[0,1],[2]]) // <<0,1>, <2>> // new ParallelArray([<0,1>,<2>]); // <<0,1>, <2>> // new ParallelArray(3, // function(i){return [i, i+1];}); // <<0,1><1,2><2,3>> // new ParallelArray(canvas); // CanvasPixelArray ///////////////// var ParallelArray = function () { // The array object has the following prototype methods that are also implemented // for ParallelArray. // concat, join, slice, toString // See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array // for their description. // The ParallelArray prototype includes the data parallel mechanisms used by ParallelArrays. // // Notes. // Copperheap python - allowed closures to be passed. Pass arguments as free variables.... // // There are other patterns that can be easily derived from these patterns for example max of a ParallelArray // is nothing more that a reduce using the binary max function. // use Proxies to emulate square bracket index selection on ParallelArray objects var enableProxies = false; // check whether the new extension is installed. var useFF4Interface = false; try { if (Components.interfaces.dpoIInterface !== undefined) { useFF4Interface = true; } } catch (ignore) { // useFF4Interface = false; } // check whether the OpenCL implementation supports double var enable64BitFloatingPoint = false; if (useFF4Interface) { var extensions; try { extensions = RiverTrail.compiler.openCLContext.extensions; } catch (ignore) { // extensions = undefined; } if (!extensions) { var dpoI; var dpoP; var dpoC; try { dpoI = new DPOInterface(); dpoP = dpoI.getPlatform(); dpoC = dpoP.createContext(); extensions = dpoC.extensions || dpoP.extensions; } catch (e) { console.log("Unable to query dpoInterface: "+e); } } enable64BitFloatingPoint = (extensions.indexOf("cl_khr_fp64") !== -1); } // this is the storage that is used by default when converting arrays // to typed arrays. var defaultTypedArrayConstructor = useFF4Interface ? (enable64BitFloatingPoint ? Float64Array : Float32Array) : Array; // the default type assigned to JavaScript numbers var defaultNumberType = enable64BitFloatingPoint ? "double" : "float"; // whether to use kernel caching or not var useKernelCaching = true; // whether to use lazy communication of openCL values var useLazyCommunication = false; // whether to cache OpenCL buffers var useBufferCaching = false; // whether to do update in place in scan var useUpdateInPlaceScan = true; // For debugging purposed each parallel array I create has a fingerprint. var fingerprint = 0; var fingerprintTracker = []; var Constants = { // Some constants, when constants are added to JS adjust accordingly "zeroStrideConstant" : [ ], "oneStrideConstant" : [1], "emptyRawArrayConstant" : new defaultTypedArrayConstructor(), "zeroArrayShapeConstant": [0] }; // I create three names for Error here so that we can, should we ever wish // distinguish both or have our own implementation for exceptions var CompilerError = Error; // compilation failed due to wrong program or missing support var CompilerBug = Error; // something went wrong although it should not var CompilerAbort = Error; // exception thrown to influence control flow, e.g., misspeculation // helper function that throws an exception and logs it if verboseDebug is on var debugThrow = function (e) { if (RiverTrail.compiler.verboseDebug) { console.log("Exception: ", JSON.stringify(e)); } throw e; }; // This method wraps the method given by property into a loader for the // actual values of the ParallelArray. On first invocation of the given // method, the function materialize is called before the underlying // method from the prototype/object is executed. var requiresData = function requiresData(pa, property) { pa[property] = function () { pa.materialize(); if (!delete pa[property]) throw new CompilerBug("Deletion of overloaded " + property + " failed"); return pa[property].apply(pa, arguments); }; }; // If this.data is a OpenCL memory object, grab the values and store the OpenCL memory // object in the cache for later use. var materialize = function materialize() { if (useFF4Interface && (this.data instanceof Components.interfaces.dpoIData)) { // we have to first materialise the values on the JavaScript side var cachedOpenCLMem = this.data; this.data = cachedOpenCLMem.getValue(); if (useBufferCaching) { this.cachedOpenCLMem = cachedOpenCLMem; } } }; // Returns true if the values for x an y are withing fuzz. // The purpose is to make sure that if a 64 bit floats is // to a 32 bit float and back that they are recognized as // fuzzyEqual. // This is clearly wrong but need to check with TS to figure out hte // right way to do this. var defaultFuzz = .0000002; // 32 bit IEEE654 has 1 bit of sign, 8 bits of exponent, and 23 bits of mantissa // .0000002 is between 1/(2**22) and 1/(2*23) var fuzzyEqual = function fuzzyEqual (x, y, fuzz) { var diff = x - y; // do the diff now to avoid losing percision from doing abs. if (diff < 0) { diff = -diff; } var absX = (x>0)?x:-x; var absY = (y>0)?y:-y; var normalizedFuzz = ((absX > absY) ? absY : absX) * fuzz; // Avoids 0 if both aren't 0 if (diff <= normalizedFuzz) { // <= so that 0, 0 works since fuzz will go to 0. return true; } return false; }; // Converts the given Array (first argument) into a typed array using the constructor // given as second argument. Validity of conversion is ensured by comparing the result // element-wise using === with the source. If no constructor is provided, the default // is used. var convertToTypedArray = function convertToTypedArray(src, arrayConstructor) { var constructor = arrayConstructor ? arrayConstructor : defaultTypedArrayConstructor; if (src.constructor === constructor) { // transforming the array into an array of the same kind // makes little sense. Besides, if the constructor is the // Array constructor, applying it twice will yield a // doubly nested array! // this.elementalType = constructorToElementalType(constructor); return src; } else { var newTA = new constructor(src); if (arrayConstructor === undefined) { if (src.every(function (val, idx) { return fuzzyEqual(val, newTA[idx], defaultFuzz); })) { return newTA; } else { return undefined; } } else { // we force a typed array due to semantics, so we do not care // whether the resulting values match return newTA; } } }; // late binding of isTypedArray in local namespace var isTypedArray = function lazyLoad(arg) { isTypedArray = RiverTrail.Helper.isTypedArray; return isTypedArray(arg); } var equalsShape = function equalsShape (shapeA, shapeB) { return ((shapeA.length == shapeB.length) && Array.prototype.every.call(shapeA, function (a,idx) { return a == shapeB[idx];})); }; var shapeToStrides = function shapeToStrides(shape) { var strides; var i; if (shape.length == 1) { // Optimize for common case. return Constants.oneStrideConstant; } if (shape.length == 0) { return Constants.zeroStrideConstant; } strides = new Array(shape.length); strides[strides.length-1] = 1; for (i = strides.length-2; i >= 0; i--) { // Calculate from right to left with rightmost being 1. strides[i] = shape[i+1]*strides[i+1]; } // console.log("shapeToStrides: ", strides); return strides; }; // Given the shape of an array return the number of elements. var shapeToLength = function shapeToLength (shape) { var i; var result; if (shape.length == 0) { return 0; } result = shape[0]; for (i=1; i<shape.length;i++) { result = result * shape[i]; } return result; }; // Flatten a multidimensional array to a single dimension. var createFlatArray = function createFlatArray (arr) { // we build localShape and localRank as we go var localShape = []; var localRank = undefined; var flatArray = new Array(); var flatIndex = 0; var flattenFlatParallelArray = function flattenFlatParallelArray (level, pa) { // We know we have a parallel array, we know it is flat. // Flat arrays are flat all the way down. // update/check localShape and localRank pa.shape.forEach( function (v, idx) { if (localShape[level+idx] === undefined) { localShape[level+idx] = v; } else if (localShape[level+idx] !== v) { //throw "wrong shape of nested PA at " + idx + " local " + v + "/global " + localShape[level+idx]; throw "shape mismatch: level " + (level+idx) + " expected " + localShape[level+idx] + " found " + v; } }); if (localRank === undefined) { localRank = level + pa.shape.length; } else if (localRank !== level + pa.shape.length) { throw "dimensionality mismatch; expected " + localRank + " found " + (level + pa.shape.length); } var i; var size = shapeToLength(pa.shape); pa.materialize(); // we have to materialize the array first! for (i=pa.offset;i<pa.offset+size;i++) { flatArray[flatIndex] = pa.data[i]; flatIndex++; } }; var flattenInner = function flattenInner (level, arr) { var i = 0; var thisLevelIndex = 0; if (arr instanceof ParallelArray) { if (arr.flat) { flattenFlatParallelArray(level, arr); return; } } if (localShape[level] === undefined) { localShape[level] = arr.length; } else if (localShape[level] !== arr.length) { // We do not have a regular array. throw "shape mismatch: level " + (level) + " expected " + localShape[level] + " found " + arr.length; } for (thisLevelIndex=0;thisLevelIndex<arr.length;thisLevelIndex++) { if (arr[thisLevelIndex] instanceof Array) { // need to add regular array check... flattenInner(level+1, arr[thisLevelIndex]); } else if (arr[thisLevelIndex] instanceof ParallelArray) { if (arr[thisLevelIndex].flat) { // Flat arrays are flat all the way down. flattenFlatParallelArray(level+1, arr[thisLevelIndex]); } else { flattenInner(level+1, arr[thisLevelIndex].get(i)); } } else { // it's not an array or ParallelArray so it is just an element. flatArray[flatIndex] = arr[thisLevelIndex]; flatIndex++; // check for rank uniformity if (localRank === undefined) { localRank = level; } else if (localRank !== level) { throw "dimensionality mismatch; expected " + localRank + " found " + level; } } } }; // flattenInner try { flattenInner(0, arr); } catch (err) { console.log("flattenArray:", err); return null; }; return flatArray; }; // Given a nested regular array return its shape. var arrShape = function arrShape (arr) { var result = []; while ((arr instanceof Array) || (arr instanceof ParallelArray)) { if (arr instanceof Array) { result.push(arr.length); arr = arr[0]; } else { // It is a ParallelArray result.push(arr.shape[0]); arr = arr.get(0); } } return result; }; // Proxy handler for mapping [<number>] and [<Array>] to call of |get|. // The forwarding part of this proxy is taken from // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Proxy // which in turn was copied from the ECMAScript wiki at // http://wiki.ecmascript.org/doku.php?id=harmony:proxies&s=proxy var makeIndexOpHandler = function makeIndexOpProxy (obj) { return { // Fundamental traps getOwnPropertyDescriptor: function(name) { var desc = Object.getOwnPropertyDescriptor(obj, name); // a trapping proxy's properties must always be configurable if (desc !== undefined) { desc.configurable = true; } return desc; }, getPropertyDescriptor: function(name) { var desc = Object.getPropertyDescriptor(obj, name); // not in ES5 // a trapping proxy's properties must always be configurable if (desc !== undefined) { desc.configurable = true; } return desc; }, getOwnPropertyNames: function() { return Object.getOwnPropertyNames(obj); }, getPropertyNames: function() { return Object.getPropertyNames(obj); // not in ES5 }, defineProperty: function(name, desc) { Object.defineProperty(obj, name, desc); }, delete: function(name) { return delete obj[name]; }, fix: function() { if (Object.isFrozen(obj)) { return Object.getOwnPropertyNames(obj).map(function(name) { return Object.getOwnPropertyDescriptor(obj, name); }); } // As long as obj is not frozen, the proxy won't allow itself to be fixed return undefined; // will cause a TypeError to be thrown }, // derived traps has: function(name) { return name in obj; }, hasOwn: function(name) { return Object.prototype.hasOwnProperty.call(obj, name); }, get: function(receiver, name) { var idx = parseInt(name); if (idx == name) { return obj.get(idx); } else { return obj[name]; } }, set: function(receiver, name, val) { obj[name] = val; return true; }, // bad behavior when set fails in non-strict mode enumerate: function() { var result = []; for (name in obj) { result.push(name); }; return result; }, keys: function() { return Object.keys(obj) } }; } // Helper for constructor that generates an empty array. var createEmptyParallelArray = function createEmptyParallelArray () { this.data = Constants.emptyRawArrayConstant; this.shape = Constants.zeroArrayShapeConstant; this.strides = Constants.oneStrideConstant; this.flat = true; this.offset = 0; return this; }; // Helper for constructor that takes a single element, an array, a typed array, a // ParallelArray, or an image of values. The optional second argument unfluences which // kind of typed array is tried. var createSimpleParallelArray = function createSimpleParallelArray(values, targetType) { if (values instanceof Array) { var flatArray = createFlatArray(values); if (flatArray == null) { // We couldn't flatten the array, it is irregular this.data = new Array(values.length); this.flat = false; for (i=0;i<values.length;i++){ if (values[i] instanceof Array) { this.data[i] = new ParallelArray(values[i]); } else { this.data[i] = values[i]; } } } else { // we have a flat array. this.shape = arrShape(values); this.strides = shapeToStrides(this.shape); this.flat = true; this.offset = 0; this.data = convertToTypedArray(flatArray, targetType); if (this.data === undefined) this.data = flatArray; } } else if (values instanceof ParallelArray) { // Parallel Arrays can share data since they are immutable. this.flat = values.flat; if (this.flat) { this.shape = values.shape; this.strides = values.strides; this.offset = values.offset; } if (targetType === undefined) { this.data = values.data; // ParallelArrays are read only so reuse data this.elementalType = values.elementalType; } else { values.materialize(); this.data = new targetType(values.data); } } else if (isTypedArray(values)) { this.flat = true; this.strides = Constants.oneStrideConstant; this.offset = 0; this.shape = [values.length]; // We create a new typed array and copy the source elements over. // Just calling the constructor with the source array would not // suffice as typed arrays share the underlying buffer... this.data = new values.constructor(values.length); for (var i = 0; i < values.length; i++) { this.data[i] = values[i]; } this.isKnownRegular = true; } else if (values.getContext !== undefined) { // proxy for checking if it's a canvas var context = values.getContext("2d"); var imageData = context.getImageData(0, 0, values.width, values.height); this.data = imageData.data; this.shape = [values.height,values.width,4]; this.strides = [4*values.width,4,1]; this.flat = true; this.offset = 0; this.isKnownRegular = true; } else { this.data = new defaultTypedArrayConstructor(1); this.data[0] = values; if (this.data[0] !== values) { this.data = new Array(1); this.data[0] = values; } this.shape = Constants.oneStrideConstant; this.strides = Constants.oneStrideConstant; this.flat = true; this.offset = 0; } return this; }; // Helper for constructor that builds an ParallelArray comprehension. var createComprehensionParallelArray = function createComprehensionParallelArray(sizeVector, theFunction, extraArgs) { var results; var tempVector; var scalarIndex = false; if (!(sizeVector instanceof Array)) { // Handles just passing the size of a 1 d array in as a number. tempVector = new Array(1); tempVector[0] = sizeVector; sizeVector = tempVector; scalarIndex = true; } // try to execute the comprehension in OpenCL try { return RiverTrail.compiler.compileAndGo(this, theFunction, scalarIndex ? "comprehensionScalar" : "comprehension", sizeVector, extraArgs, enable64BitFloatingPoint); } catch (e) { console.log("comprehension failed: " + e); } var left = new Array(0); results = buildRaw(this, left, sizeVector, arguments[1], extraArgs, scalarIndex); // SAH: once we have computed the values, we can fall back to the simple case. createSimpleParallelArray.call(this, results); return this; }; var createOpenCLMemParallelArray = function( mobj, shape, type) { this.data = mobj; this.shape = shape; this.elementalType = type; this.strides = shapeToStrides( shape); this.flat = true; this.offset = 0; return this; }; // Occasionally we want to surpress the actual execution of the OpenCL and just look at the verboseDebug // information. This reduces browser crashes and makes debugging easier. // Normally this is false. var suppressOpenCL = false; //var suppressOpenCL = true; // kernelCompiler is the OCL parser and code generator. It is generated and placed here the first // the the ParallelArray constructor is called. var kernelCompiler = false; // Used by the constructor to build a ParallelArray with given a size vector and a function. // Used by combine to build the new ParallelArray. /*** buildRaw Synopsis: Used by the constructor to build a ParallelArray with given a size vector and a function. Used by combine to build the new ParallelArray. function buildRaw(theThisArray, left, right, fTemp, extraArgs); Arguments theThisArray: the array you are populating. fTemp: A function left: the indices when concatanated to right form the indices passed to fTemp or to a recursive call to buildRaw right: the indices when concatinated to left form the indices passed to fTemp if right has only one index then the actual calls to fTemp are done for all indices from 0 to right[0] fTemp: The first arg is an array holding the indices of where the resulting element belongs along with any extraArg extraArgs: Args that are passed on to fTemp unchanged. scalarindex: If true, the index passed to the elemental function will be a scalar value Returns A freshly minted JS Array whose elements are the results of applying f to the original ParallelArray (this) along with the indices holding where the resulting element is placed in the result. The indices are the concatination of the arguments left and right. Any extraArgs are also passed to f. The expected use case for combine is for fTemp to reference this at the appropriate indices to build the new element. The expected use case for the constructors is to construct the element using the indices and the extra args. ***/ var buildRaw = function buildRaw(theThisArray, left, right, fTemp, extraArgs, scalarIndex) { var i; var elementalResult; var result; if (right.length == 1) { // Here is where you call the fTemp with the indices. var indices = new Array(left.length+1); // This ends up being the indices passed to the elemental function var applyArgs = new Array(extraArgs.length+1); // indices + extra args. for (i=0;i<extraArgs.length;i++) { // these are the args passed to the elemental functionleave the first arg open for indices. applyArgs[i+1] = extraArgs[i]; } var result = new Array(right[0]); // The number of result to expect for (i=0;i<left.length; i++) { indices[i] = left[i]; // Transfer the non-changing indices. } for (i=0; i<right[0]; i++) { if (scalarIndex) { applyArgs[0] = i; } else { indices[left.length] = i; // This is the index that changes. applyArgs[0] = indices; } elementalResult = fTemp.apply(theThisArray, applyArgs); if (elementalResult instanceof Array) { result[i] = new ParallelArray(elementalResult); } else if (elementalResult instanceof ParallelArray) { result[i] = elementalResult; } else { result[i] = elementalResult; } } return result; } if (scalarIndex) { throw new CompilerBug("buildRaw called with scalarIndex === true but higher rank interation space"); } // Build the new index vectors for the recursive call by moving an index from the right to the left. var newLeft = new Array(left.length+1); var newRight = right.slice(1); // Move the first right to the left. for (i=0;i<left.length;i++) { newLeft[i] = left[i]; } newLeft[newLeft.length-1] = right[0]; var range = newLeft[newLeft.length-1]; result = new Array(range); for (i=0; i<range; i++) { newLeft[newLeft.length-1] = i; result[i] = buildRaw(theThisArray, newLeft, newRight, fTemp, extraArgs, scalarIndex); } return result; }; /** Erase RLH. var calculateSize = function calculateSize(ravel) { var size = 0; var i; if (ravel.length == 0) { return size; } size = 1; for (i=ravel.length-1; i>=0; i--) { size = size * ravel[i]; } return size; }; **/ var partition = function partition(partitionSize) { if (this.flat) { return partitionFlat(this, partitionSize); } var aSlice; var i; var partitionCount = this.length / partitionSize; var newArray = new Array(partitionCount); if (partitionCount*partitionSize != this.length) { throw new RangeError("ParallelArray.partition length not evenly divisible by partitionSize."); } for (i=0; i<partitionCount; i++) { aSlice = this.data.slice(i*partitionSize, (i+1)*partitionSize); newArray[i] = new ParallelArray(aSlice); } return new ParallelArray(newArray); }; var partitionFlat = function partitionFlat(pa, partitionSize) { var newShape = new Array(pa.shape.length+1); var i; for (i=1;i<newShape.length;i++) { newShape[i]=pa.shape[i-1]; } // At this point newShape[0] and newShape[1] need to be adjusted to partitionCount and partitionSize newShape[0] = newShape[1] / partitionSize; newShape[1] = partitionSize; if (shapeToLength(newShape) != shapeToLength(pa.shape)) { throw new RangeError("Attempt to partition ParallelArray unevenly."); } var newPA = new ParallelArray("reshape", pa, newShape); return newPA; }; // Does this parallelArray have the following dimension? var isRegularIndexed = function isRegularIndexed(indices) { if (this.length != indices[0]) { return false; } if (indices.length == 1) { return true; } var i; //var result = true; // SH: the below call to slice should do the same // var tempIndices = new Array(indices.length-1); // for (i=0;i<indices.length-1;i++) { // tempIndices[i] = indices[i+1]; // } var tempIndices = indices.slice(1); // the below could be replaced by this but that would break encapsulation //return this.data.every( function checkElement(x) { return x.isRegularIndexed(tempIndices)} ); for (i=0;i<this.length;i++) { if ((this.get(i).isRegularIndexed(tempIndices)) == false) { return false; } } return true; }; // Is this a regular array? // At this point this does not check for type.... var isRegular = function isRegular() { if (this.isKnownRegular === undefined) { if (this.flat) { this.isKnownRegular = true; // this probable should be changed to something isKnownRegular. } else { // Construct the indices for the first element var thisLevel = new Array(0); var indices = new Array(0); var level = this; while (level instanceof ParallelArray) { indices.push(level.length); level = level.get(0); } // indices holds the length of the indices with the biggest at the start. if (this.isRegularIndexed(indices)) { this.shape = indices; this.isKnownRegular = true; } else { this.isKnownRegular = false; } } } return this.isKnownRegular; }; // Get the shape of a regular array down to the depth requested. // Input depth maximum number of indices to invstigate. // If not provided then depth is infinite. var getShape = function getShape(depth) { if (!this.isRegular()) { throw new TypeError("this is not a regular ParallelArray."); } return (depth === undefined) ? this.shape.slice(0) : this.shape.slice(0, depth); }; // When in the elemental function f "this" is the same as "this" in combine. var combineSeq = function combineSeq(depth, f) { // optional arguments follow var i; var result; var extraArgs; var extraArgOffset = 2; if ((typeof(depth) === 'function') || (depth instanceof low_precision.wrapper)) { f = depth; depth = 1; extraArgOffset = 1; } if (f instanceof low_precision.wrapper) { f = f.unwrap(); } if (!this.isRegular()) { throw new TypeError("ParallelArray.combineSeq this is not a regular ParallelArray."); } if (arguments.length == extraArgOffset) { extraArgs = new Array(); } else { extraArgs = new Array(arguments.length-extraArgOffset); for (i=0;i<extraArgs.length;i++) { extraArgs[i] = arguments[i+extraArgOffset]; } } result = buildRaw(this, (new Array(0)), this.getShape(depth), f, extraArgs, false); // SAH temporarily until cast is implemented return new ParallelArray(result); return new ParallelArray(this.data.constructor, result); }; // combine implements the openCL parallel version of combine. // When in the elemental function f "this" is the same as "this" in combine. /*** Combine Overview Similar to map except this is the entire array and an index is provided since you have the entire array you can access other elements in the array. Arguments depth – the number of dimensions traversed to access an element in this Elemental function described below Optional arguments passed unchanged to elemental function Elemental Function this - The ParallelArray index Location in combine’s result where the result of the elemental function is placed. Suitable as the first argument to “get” to retrieve source values. Optional arguments Same as the optional arguments passed to combine Result An element to be placed in combine’s result at the location indicated by index Returns A freshly minted ParallelArray whose elements are the results of applying the elemental function. Example: an identity function pa.combine(function(i){return this.get(i);}) ***/ var combine = function combine(depth, f) { // optional arguments follow var i; var paResult; var extraArgs; var extraArgOffset = 2; if ((typeof(depth) === 'function') || (depth instanceof low_precision.wrapper)) { f = depth; depth = 1; extraArgOffset = 1; } if (!this.isRegular()) { throw new TypeError("ParallelArray.combine this is not a regular ParallelArray."); } if (arguments.length == extraArgOffset) { extraArgs = new Array(0); } else { // depth is _not_ part of the arguments passed to the elemental function extraArgs = new Array(arguments.length-extraArgOffset); // depth and function account for the 2 for (i=0;i<extraArgs.length;i++) { extraArgs[i] = arguments[i+extraArgOffset]; } } paResult = RiverTrail.compiler.compileAndGo(this, f, "combine", depth, extraArgs, enable64BitFloatingPoint); return paResult; }; /** Fundamental Constructs of ParallelArray – the minimal set from which you should be able to cleanly express 90% of the useful constructs needed by programmers. Map, Combine, Reduce, Scan, Scatter Partition, filter **/ /*** mapSeq Elemental Function this - the entire ParallelArray val - an element from the ParallelArray Optional arguments - Same as the optional arguments passed to map Result An element to be placed in the result at the same offset we found “this” Returns A freshly minted ParallelArray Elements are the results of applying the elemental function to the elements in the original ParallelArray plus any optional arguments. Example: an identity function pa.map(function(val){return val;}) ***/ var mapSeq = function mapSeq (f) { // extra args passed unchanged and unindexed. var len = this.shape[0]; var i, j; var fTemp = f; var args = new Array(arguments.length-1); var result = new Array(len); // SAH: for now we have to manually unwrap. Proxies might be a solution but they // are too underspecified as of yet if (f instanceof low_precision.wrapper) { f = f.unwrap(); } if (arguments.length == 1) { // Just a 1 arg function. for (i=0;i<len;i++) { result[i] = f.apply(this, [this.get(i)]); } } else { for (i=0;i<len;i++) { for (j=1;j<arguments.length;j++) { args[j] = arguments[j]; } args[0] = this.get(i); result[i] = f.apply(this, args); } } // SAH: temporary fix until we use cast if (this.data.constructor === Float32Array) { // Not sure what to do here we have a Float32Array and we are using // these typed arrays to hold our data. Maintaining Float32Array will // potentially only loose precision, this is less of a problem than // converting floats to say 8 bit clamped ints. return new ParallelArray(this.data.constructor, result); } return new ParallelArray(result); return new ParallelArray(this.data.constructor, result); }; // // map - // Same as mapSeq but uses the OpenCL optimized version. // var map = function map (f) { // extra args passed unchanged and unindexed. var len = this.shape[0]; var args = new Array(arguments.length-1); var paResult; if (arguments.length === 1) { // no extra arguments present paResult = RiverTrail.compiler.compileAndGo(this, f, "map", 1, args, enable64BitFloatingPoint); } else { for (var j=1;j<arguments.length;j++) { args[j-1] = arguments[j]; } paResult = RiverTrail.compiler.compileAndGo(this, f, "map", 1, args, enable64BitFloatingPoint); } return paResult; }; /*** reduce Arguments Elemental function described below. Optional arguments passed unchanged to elemental function Elemental Function this - the entire ParallelArray a, b - arguments to be reduced and returned Optional arguments - Same as the optional arguments passed to map Result The result of the reducing a and b, typically used in further applications of the elemental function. Returns The final value, if the ParallelArray has only 1 element then that element is returned. Discussion Reduce is free to group calls to the elemental function in arbitrary ways and order the calls arbitrarily. If the elemental function is associative then the final result will be the same regardless of the ordering. For integers addition is an example of an associative function and the sum of a ParallelArray will always be the same regardless of the order that reduces calls addition. Average is an example of non-associative function. Average(Average(2, 3), 9) is 5 2/3 while Average(2, Average(3, 9)) is 4. Reduce is permitted to chose whichever call ordering it finds convenient. Reduce is only required to return a result consistent with some call ordering and is not required to chose the same call ordering on subsequent calls. Furthermore, reduce does not magically resolve problems related to the well document fact that some floating point numbers are not represented exactly in JavaScript and the underlying hardware. Reduce does not require the elemental function be communitive since it does induce reordering of the arguments passed to the elemental function's. ***/ var reduce = function reduce(f, optionalInit) { // SAH: for now we have to manually unwrap. Proxies might be a solution but they // are too underspecified as of yet if (f instanceof low_precision.wrapper) { f = f.unwrap(); } var len = this.shape[0]; var result; var i; result = this.get(0); for (i=1;i<len;i++) { result = f.call(this, result, this.get(i)); } return result; }; /*** scan Arguments Elemental function described below Optional arguments passed unchanged to elemental function Elemental Function this - the entire ParallelArray a, b - arguments to be reduced and returned Optional arguments - Same as the optional arguments passed to scan Result - The result of the reducing a and b, typically used in further applications of the elemental function. Returns A freshly minted ParallelArray whose ith elements is the results of using the elemental function to reduce the elements between 0 and i in the original ParallelArray. Example: an identity function pa.scan(function(a, b){return b;}) Discussion: We implement what is known as an inclusive scan which means that the value of the ith result is the [0 .. i].reduce(elementalFunction) result. Notice that the first element of the result is the same as the first element in the original ParallelArray. An exclusive scan can be implemented by shifting right end off by one the results of an inclusive scan and inserting the identity at location 0. Similar to reduce scan can arbitrarily reorder the order the calls to the elemental functions. Ignoring floating point anomalies, this cannot be detected if the elemental function is associative so using a elemental function such as addition to create a partial sum will produce the same result regardless of the order in which the elemental function is called. However using a non-associative function can produce different results due to the ordering that scan calls the elemental function. While scan will produce a result consistent with a legal ordering the ordering and the result may differ for each call to scan. Typically the programmer will only call scan with associative functions but there is nothing preventing them doing otherwise. ***/ var scan = function scan(f) { // SAH: for now we have to manually unwrap. Proxies might be a solution but they // are too underspecified as of yet if (f instanceof low_precision.wrapper) { f = f.unwrap(); } if (this.getShape()[0] < 2) { // // handle case where we only have one row => the result is the first element // return this; } var i; var len = this.length; var rawResult = new Array(len); var movingArg; var callArguments = Array.prototype.slice.call(arguments, 0); // array copy var ignoreLength = callArguments.unshift(0); // callArguments now has 2 free location for a and b. if (this.getShape().length < 2) { // // Special case where selection yields a scalar element. Offloading the inner // kernel to OpenCL is most likely not beneficial and we cannot use the offset // based selection as get does not yield a Parallel Array. Using a naive for // loop instead. // rawResult[0] = this.get(0); for (i=1;i<len;i++) { callArguments[0] = rawResult[i-1]; callArguments[1] = this.get(i);; rawResult[i] = f.apply(this, callArguments); } return (new ParallelArray(rawResult)); } // // We have a n-dimensional parallel array, so we try to use offset based selection // and speculative OpenCL exectution // var scanCount = 0; var copySize; // Mutable and knows about the internal offset structure. // The offset now points to the second element this.data[1]. // since the first one is the first one in the result. // Pick up the stride from this to use to step through the array var localStride = this.strides[0]; if (useUpdateInPlaceScan) { // SAH: I speculate that the scan operation is shape uniform. If it is not, // performance goes down the drain anyways so a few extra executions won't // matter. try { rawResult[0] = this.get(0); movingArg = this.get(1); callArguments[0] = rawResult[0]; callArguments[1] = movingArg; rawResult[1] = f.apply(this, callArguments); if ((rawResult[1].data instanceof Components.interfaces.dpoIData) && equalsShape(rawResult[0].getShape(), rawResult[1].getShape())) { // this was computed by openCL and the function is shape preserving. // Try to preallocate and compute the result in place! // We need the real data here, so materialize it movingArg.materialize(); // create a new typed array for the result and store it in updateinplace var updateInPlace = new movingArg.data.constructor(movingArg.data.length); // copy the first line into the result for (i=0; i<localStride; i++) { updateInPlace[i] = this.data[i]; } // copy the second line into the result var last = rawResult[1]; var result = undefined; last.materialize; for (i=0; i <localStride; i++) { updateInPlace[i+localStride] = last.data[i]; } // create a new parallel array to pass as prev var updateInPlacePA = rawResult[0]; // swap the data store of the updateInPlacePA updateInPlacePA.data = updateInPlace; // set up the arguments callArguments[0] = updateInPlacePA; callArguments[1] = movingArg; // set the write offset and updateInPlace info movingArg.updateInPlacePA = updateInPlacePA; movingArg.updateInPlaceOffset = localStride; movingArg.updateInPlaceShape = last.shape; for (i=2;i<len;i++) { // Effectivey change movingArg to refer to the next element in this. movingArg.offset += localStride; updateInPlacePA.offset += localStride; movingArg.updateInPlaceOffset += localStride; movingArg.updateInPlaceUses = 0; // i is the index in the result. result = f.apply(this, callArguments); if (result.data !== movingArg.updateInPlacePA.data) { // we failed to update in place throw new CompilerAbort("speculation failed: result buffer was not used"); } } return new ParallelArray( updateInPlacePA.data, this.shape, this.inferredType); } } catch (e) { // clean up to continute below console.log("scan: speculation failed, reverting to normal mode"); movingArg = this.get(1); rawResult[0] = this.get(0); callArguments[0] = rawResult[0]; } } else { // speculation is disabled, so set up the stage movingArg = this.get(1); rawResult[0] = this.get(0); callArguments[0] = rawResult[0]; callArguments[1] = movingArg; rawResult[1] = f.apply(this, callArguments); } for (i=2;i<len;i++) { // Effectivey change movingArg to refer to the next element in this. movingArg.offset += localStride; callArguments[0] = rawResult[i-1]; // i is the index in the result. rawResult[i] = f.apply(this, callArguments); } return (new ParallelArray(rawResult)); }; /*** filter Arguments Elemental function described below Optional arguments passed unchanged to elemental function Elemental Function this - The ParallelArray index - The location in “this” where the source element is found. Optional arguments - Same as the optional arguments passed to filter Result true (true, 1, or other JavaScript truthy value) if the source element should be placed in filter’s result. false (false, 0, undefined, or other JavaScript falsey value) if the source element should not to be placed in filter’s result. Returns A freshly minted ParallelArray holding source elements where the results of applying the elemental function is true. The order of the elements in the returned ParallelArray is the same as the order of the elements in the source ParallelArray. Example: an identity function pa.filter(function(){return true;}) ***/ var filter = function filter(f) { var len = this.length; // Generate a ParallelArray where t means the corresponding value is in the resulting array. var boolResults = combineSeq.apply(this, arguments); var rawResult; var i, j; var resultSize = 0; for (i=0;i<this.length;i++) { if (boolResults.get(i) != 0) { resultSize++; } } rawResult = new Array(resultSize); j = 0; for (i=0;i<len;i++) { if (boolResults.get(i) == 1) { rawResult[j] = this.get(i); j++; } } return (new ParallelArray(rawResult)); }; /*** scatter Arguments indices: array of indices in the resulting array defaultValue: optional argument indicating the value of elements not set by scatter When not present, the default value is 'undefined’ conflictFunction: optional function to resolve conflicts, details below. length: optional argument indicating the length of the resulting array. If absent, the length is the same as the length of the indices argument Note that scatter does not take an elemental function Optional arguments are ignored. Returns A freshly minted ParallelArray A whose elements are the result of: A[indices[i]] = this[i], when indices[i] is unique A[indices[i]] = conflictFunction(index, A[indices[i]],) when A[indices[i]] has a previously assigned value. defaultValue, when index is not present in 'indices' array Example: an identity function pa.scatter(indices); where indices is a ParallelArray where element === index Handling conflicts Conflicts result when multiple elements are scattered to the same location. Conflicts results in a call to conflictFunction, which is an optional third argument to scatter Arguments this is value from the source array that is currently being scattered Previous value – value in result placed there by some previous iteration It is the programmer’s responsibility to provide a conflictFunction that is associative and commutative since there is no guarantee in what order the conflicts will be resolved. Returns Value to place in result[indices[index]] Example: Resolve conflict with larger number chooseMax(prev){ return (this>prev)?this:prev; } ***/ var scatter = function scatter(indices, defaultValue, conflictFunction, length) { var result; var len = this.shape[0]; var hasDefault = (arguments.length >= 2); var hasConflictFunction = (arguments.length >=3 && arguments[2] != null); var newLen = (arguments.length >= 4 ? length : len); var rawResult = new Array(newLen); var conflictResult = new Array(newLen); var i; if (hasDefault) { for (i = 0; i < newLen; i++) { rawResult[i] = defaultValue; } } for (i = 0; i < indices.length; i++) { var ind = (indices instanceof ParallelArray) ? indices.get(i) : indices[i]; if (ind >= newLen) throw new RangeError("Scatter index out of bounds"); if (conflictResult[ind]) { // we have already placed a value at this location if (hasConflictFunction) { rawResult[ind] = conflictFunction.call(undefined, this.get(i), rawResult[ind]); } else { throw new RangeError("Duplicate indices in scatter"); } } else { rawResult[ind] = this.get(i); conflictResult[ind] = true; } } result = new ParallelArray(rawResult); return result; }; /*** End of the fundemental constructts */ /*** getArray Synopsis: getArray(); Arguments: none Returns Returns a JS array holding a copy of the elements from the ParallelArray. If the element is a ParallelArray then it's elemets are also copied in to a JS Array. ***/ var getArray = function getArray () { var i, result; if ((this.flat) && (this.shape.length === 1)) { result = Array.prototype.slice.call(this.data, this.offset, this.offset + this.length); } else { result = new Array(this.length); for (i=0; i<this.length; i++) { var elem = this.get(i); if (elem instanceof ParallelArray) { result[i] = elem.getArray(); } else { result[i] = elem; } } } return result; }; // This takes a ParallelArray and creates a similar JavaScript array. // By similar the array returned will be of a cononical type. In // particular it will be whatever type the data in the ParallelArray // is held in. A Float32Array would be returned if the original ParallelArray // held the actual data in a Float32Array. var getData = function getData() { var result = new this.data.constructor(this.data); return result; }; /*** get Synopsis: get(index); Arguments index: a integer indicating that you want the element in the highest rank, typically this is used for vectors. index: an array of integers indicating that you want an element in a multiple dimension array. Returns The element refered to by the index/indices. ***/ var get = function get (index) { var i; var result; var offset; var argsAsArray; // For converting from arguements into a real array. if (this.flat) { if (index instanceof Array) { offset = this.offset; var len = index.length; for (i=0;i<len;i++) { // if we go out of bounds, we return undefined if (index[i] < 0 || index[i] >= this.shape[i]) return undefined; offset = offset + index[i]*this.strides[i]; } if (this.shape.length === index.length) { return this.data[offset]; } else { // build a ParallelArray. result = new ParallelArray(this); result.offset = offset; result.elementalType = this.elementalType; /* need to fix up shape somehow. */ result.shape = this.shape.slice(index.length); result.strides = this.strides.slice(index.length); /* changing the shape might invalidate the _fastClasses specialisation, * so better ensure things are still fine */ if (result.__proto__ !== ParallelArray.prototype) { result.__proto__ = _fastClasses[result.shape.length].prototype; } return result; } } // else it is flat but not (index instanceof Array) if (arguments.length == 1) { // One argument that is a scalar index. if ((index < 0) || (index >= this.shape[0])) return undefined; if (this.shape.length == 1) { // a 1D array return this.data[this.offset + index]; } else { // we have a nD array and we want the first dimension so create the new array offset = this.offset+this.strides[0]*index; // build a ParallelArray. result = new ParallelArray(this); result.offset = offset; result.elementalType = this.elementalType; /* need to fix up shape somehow. */ result.shape = this.shape.slice(1); result.strides = this.strides.slice(1); return result; } } // Still a flat array but more than on argument, turn into an array and recurse. argsAsArray = Array.prototype.slice.call(arguments); return this.get(argsAsArray); } // end flat array path. if (arguments.length == 1) { if (!(arguments[0] instanceof Array)) { return this.data[index]; } else { // not flat, index is an array of indices. result = this; for (i=0;i<arguments[0].length;i++) { result = result.data[arguments[0][i]]; // out of bounds => abort further selections if (result === undefined) return result; } return result; } } // not flat, more than one argument. result = this; for (i=0;i<arguments.length;i++) { result = result.data[arguments[i]]; // out of bounds => abort further selections if (result === undefined) return result; } return result; }; // Write content of parallel array into a canvas // XXX: Assumes that image is going to fill the whole canvas var writeToCanvas = function writeToCanvas(canvas) { var i; var context = canvas.getContext("2d"); var currImage = context.getImageData(0, 0, canvas.width, canvas.height); var imageData = context.createImageData(currImage.width, currImage.height); var data = imageData.data; if (useFF4Interface && (this.data instanceof Components.interfaces.dpoIData)) { this.data.writeTo(data); } else { for (var i = 0; i < this.data.length; i++) { data[i] = this.data[i]; } } context.putImageData(imageData, 0, 0); }; // Some functions that mimic the JavaScript Array functionality *** // The array object has the following prototype methods that are also implemented // for ParallelArray. // // concat() // join() // slice() // toString() // See // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array // for a description. // // // concat() Joins two or more arrays, and returns a copy of the joined arrays var concat = function concat () { var len = arguments.length; var result; var applyArgs; var allTypedArrays = isTypedArray(this.data); var allArrays = (this.data instanceof Array); var resultLength = this.length; var offset = 0; var i, j; applyArgs = new Array(arguments.length); for (var i=0; i<len; i++) { applyArgs[i] = arguments[i]; resultLength += arguments[i].length; if (allTypedArrays) { // if this and previous are true check if this arg uses typed arrays. allTypedArrays = isTypedArray(arguments[i].data); allArrays = false; } if (allArrays) { // this and all previous are Arrays. allArrays = (arguments[i].data instanceof Array); } } if (allTypedArrays) { return concatTypedArrayData.apply(this, applyArgs); } if (allArrays) { return concatArrayData.apply(this, applyArgs); } // Nothing simple just do it like the old fashion way, one element at a time. result = new Array(resultLength); // Do this for (i=0;i<this.length;i++) { result[offset] = this.get(i); offset++; } // Do the arguments for (i=0;i<arguments.length; i++) { for (j=0; j<arguments[i].length;j++) { result[offset] = arguments[i].get(j); offset++; } } return new ParallelArray(result); }; // concatTypedArrayData() Joins two or more arrays using typed arrays, and // returns a copy of the joined arrays var concatTypedArrayData = function concatTypedArrayData () { var len = arguments.length; var result; var applyArgs; var i; var resultLength = this.length; var offset; for (i=0;i<arguments.length;i++) { resultLength += arguments[i].length; } result = this.data.constructor(resultLength); result.set(this.data); offset = this.length; for (i=0; i<len; i++) { result.set(arguments[i].data, offset); offset = offset + arguments[i].length; } return new ParallelArray (result); }; // concatTypedArrayData() Joins two or more arrays using typed arrays, and // returns a copy of the joined arrays var concatArrayData = function concatArrayData () { var i; var result = new Array(); result = result.concat(this.data); for (i=0;i<arguments.length;i++) { result = result.concat(arguments.data); } return new ParallelArray (result); }; // join() Joins all elements of an array into a string var join = function join (arg1) { var result; if (!arg1) { result = this.data.join(); } else { if (arg1 instanceof ParallelArray) { result = this.data.join(arg1.data); } else { result = this.data.join(arg1); } } return result; }; // pop() Removes the last element of an array, and returns that element var pop = function pop (f) { throw new TypeError("ParallelArray has no method 'pop' - it is a read only construct."); }; // push() Adds new elements to the end of an array, and returns the new length var push = function push (f) { throw new TypeError("ParallelArray has no method 'push' - it is a read only construct."); }; // reverse() Reverses the order of the elements in an array var reverse = function reverse (f) { throw new TypeError("ParallelArray has no method 'reverse' - it is a read only construct."); }; // shift() Removes the first element of an array, and returns that element var shift = function shift (f) { throw new TypeError("ParallelArray has no method 'shift' - it is a read only construct."); }; // slice() Selects a part of an array, and returns the new array var slice = function slice (startArg, endArg) { var result; if (isTypedArray(this.data)) { // typed arrays use subset instead of slice. return new ParallelArray(this.data.subarray(startArg, endArg)); } return new ParallelArray(this.data.slice(startArg, endArg)); }; // sort() Sorts the elements of an array var sort = function sort (f) { throw new TypeError("ParallelArray has no method 'sort' - it is a read only construct."); }; // splice() Adds/Removes elements from an array var splice = function splice (f) { throw new TypeError("ParallelArray has no method 'splice' - it is a read only construct."); }; // toString() Converts an array to a string, and returns the result var toString = function toString (arg1) { if (this.flat) { var max = this.shape.reduce(function (v, p) { return v*p; }) + this.offset; var res = "["; for (var pos = this.offset; pos < max; pos++) { res += ((pos === this.offset) ? "" : ", ") + this.data[pos]; } res += "]"; return res; } else { return "[" + this.data.join(", ") + "]"; } }; // unshift() Adds new elements to the beginning of an array, and returns the new length var unshift = function unshift (f) { throw new TypeError("ParallelArray has no method 'unshift' - it is a read only construct."); }; var flatten = function flatten () { var len = this.length; var newLength = 0; var shape; var i; if (this.flat) { shape = this.getShape(); if (shape.length == 1) { throw new TypeError("ParallelArray.flatten array is flat"); } var newShape = shape.slice(1); newShape[0] = newShape[0] * shape[0]; return new ParallelArray("reshape", this, newShape); } for (i=0;i<len;i++) { if (this.get(i) instanceof ParallelArray) { newLength = newLength+this.get(i).length; } else { throw new TypeError("ParallelArray.flatten not a ParallelArray of ParallelArrays."); } } var resultArray = new Array(newLength); var next = 0; for (i=0;i<len;i++) { var pa = this.get(i); for (j=0; j<pa.length; j++) { resultArray[next] = pa.get(j); next++; } } return new ParallelArray(resultArray); }; var flattenRegular = function flattenRegular () { var result; if (this.flat) { result = new ParallelArray(this); result.strides = [1]; result.shape = [shapeToLength(this.shape)]; result.offset = 0; return result; } var fillArray = function fillArray ( src, offset, dest) { if (src.length !== 0) { if (src.get(0) instanceof ParallelArray) { for (var pos = 0; pos < src.length; pos++) { offset = fillArray( src.get(pos), offset, dest); } } else { for (var pos = 0; pos < src.length; pos++) { dest[offset] = src.get(pos); offset++; } } } return offset; } if (!this.isRegular()) { throw new TypeError("ParallelArray.flatten called on non-regular array"); } var newLength = this.shape.reduce(function (a,b) { return a * b;}, 1); var resultArray = new Array( newLength); fillArray( this, 0, resultArray); return new ParallelArray( resultArray); }; var inferType = function inferType () { // TODO: deprecated, delete for good throw "inferType is no longer here!"; }; var _fastClasses = function () { var Fast0DPA = function (pa) { // shallow copy of object w/o attributes inherited from prototype // // SAH: The following generic code would be nice to use, but it prevents // some optimisation in Spidermonkey (layout analysis?) and this // has a huge runtime cost... // // var keys = Object.keys(pa); // for (idx in keys) { // this[keys[idx]] = pa[keys[idx]]; // } this.shape = pa.shape; this.strides = pa.strides; this.offset = pa.offset; this.elementalType = pa.elementalType; this.data = pa.data; this.flat = pa.flat; return this; } Fast0DPA.prototype = { "get" : function fastGet0D () { if (arguments.length === 0) { return this; } else { throw "too many indices in get call"; } } }; var Fast1DPA = function (pa) { // shallow copy of object w/o attributes inherited from prototype // // SAH: The following generic code would be nice to use, but it prevents // some optimisation in Spidermonkey (layout analysis?) and this // has a huge runtime cost... // // var keys = Object.keys(pa); // for (idx in keys) { // this[keys[idx]] = pa[keys[idx]]; // } this.shape = pa.shape; this.strides = pa.strides; this.offset = pa.offset; this.elementalType = pa.elementalType; this.data = pa.data; this.flat = pa.flat; return this; } Fast1DPA.prototype = { "get" : function fastGet1D (index) { var aLen = arguments.length; if (aLen === 1) { if (typeof(index) === "number") { if ((index < 0) || (index >= this.shape[0])) return undefined; return this.data[this.offset + index]; } else { /* fall back to slow mode */ return this.__proto__.__proto__.get.call(this, index); } } else if (aLen === 0) { return this; } else { throw "too many indices in get call"; } } }; var Fast2DPA = function (pa) { // shallow copy of object w/o attributes inherited from prototype // // SAH: The following generic code would be nice to use, but it prevents // some optimisation in Spidermonkey (layout analysis?) and this // has a huge runtime cost... // // var keys = Object.keys(pa); // for (idx in keys) { // this[keys[idx]] = pa[keys[idx]]; // } this.shape = pa.shape; this.strides = pa.strides; this.offset = pa.offset; this.elementalType = pa.elementalType; this.data = pa.data; this.flat = pa.flat; return this; } Fast2DPA.prototype = { "get" : function fastGet2D (index, index2) { var result; var aLen = arguments.length; if (aLen === 2) { if ((index < 0) || (index >= this.shape[0]) || (index2 < 0) || (index2 >= this.shape[1])) return undefined; return this.data[this.offset + index * this.strides[0] + index2]; } else if (aLen === 1) { if (typeof index === "number") { if ((index < 0) || (index >= this.shape[0])) return undefined; result = new Fast1DPA(this); result.offset = this.offset + index * this.strides[0]; result.elementalType = this.elementalType; /* need to fix up shape somehow. */ result.shape = this.shape.slice(1); result.strides = this.strides.slice(1); return result; } else { /* fall back to slow mode */ return this.__proto__.__proto__.get.call(this, index); } } else if (aLen === 0) { return this; } else { throw "too many indices in get call"; } } }; var Fast3DPA = function (pa) { // shallow copy of object w/o attributes inherited from prototype // // SAH: The following generic code would be nice to use, but it prevents // some optimisation in Spidermonkey (layout analysis?) and this // has a huge runtime cost... // // var keys = Object.keys(pa); // for (idx in keys) { // this[keys[idx]] = pa[keys[idx]]; // } this.shape = pa.shape; this.strides = pa.strides; this.offset = pa.offset; this.elementalType = pa.elementalType; this.data = pa.data; this.flat = pa.flat; return this; } Fast3DPA.prototype = { "get" : function fastGet3D (index, index2, index3) { var result; var aLen = arguments.length; if (aLen === 3) { if ((index < 0) || (index >= this.shape[0]) || (index2 < 0) || (index2 >= this.shape[1]) || (index3 < 0) || (index3 >= this.shape[2])) return undefined; return this.data[this.offset + index * this.strides[0] + index2 * this.strides[1] + index3]; } else if (aLen === 2) { if ((index < 0) || (index >= this.shape[0]) || (index2 < 0) || (index2 >= this.shape[1])) return undefined; result = new Fast1DPA(this); result.offset = this.offset + index * this.strides[0] + index2 * this.strides[1]; result.elementalType = this.elementalType; /* need to fix up shape somehow. */ result.shape = this.shape.slice(2); result.strides = this.strides.slice(2); return result; } else if (aLen === 1) { if (typeof index === "number") { if ((index < 0) || (index >= this.shape[0])) return undefined; result = new Fast2DPA(this); result.offset = this.offset + index * this.strides[0]; result.elementalType = this.elementalType; /* need to fix up shape somehow. */ result.shape = this.shape.slice(1); result.strides = this.strides.slice(1); return result; } else { /* fall back to slow mode */ return this.__proto__.__proto__.get.call(this, index); } } else { throw "too many indices in get call"; } } }; return [Fast0DPA,Fast1DPA,Fast2DPA,Fast3DPA]; }(); function ParallelArray () { var i, j; var args; var result = this; for (i=0;i<fingerprintTracker.length;i++) { if (fingerprint === fingerprintTracker[i]) { console.log ("(fingerprint === fingerprintTracker)"); } } if (arguments.length == 0) { result = createEmptyParallelArray.call(this); } else if (arguments.length == 1) { result = createSimpleParallelArray.call(this, arguments[0]); } else if ((arguments.length == 2) && (typeof(arguments[0]) == 'function')) { // Special case where we force the type of the result. Should only be used internally result = createSimpleParallelArray.call(this, arguments[1], arguments[0]); } else if ((arguments.length == 3) && (arguments[0] == 'reshape')) { // special constructor used internally to create a clone with different shape result = this; result.shape = arguments[2]; result.strides = shapeToStrides(arguments[2]); result.offset = arguments[1].offset; result.elementalType = arguments[1].elementalType; result.data = arguments[1].data; result.flat = arguments[1].flat; } else if (useFF4Interface && (arguments[0] instanceof Components.interfaces.dpoIData)) { result = createOpenCLMemParallelArray.apply(this, arguments); } else if (typeof(arguments[1]) === 'function' || arguments[1] instanceof low_precision.wrapper) { var extraArgs; if (arguments.length > 2) { extraArgs = new Array(arguments.length -2); // skip the size vector and the function for (i=2;i<arguments.length; i++) { extraArgs[i-2] = arguments[i]; } } else { // No extra args. extraArgs = new Array(0); } result = createComprehensionParallelArray.call(this, arguments[0], arguments[1], extraArgs); } else { // arguments.slice doesn't work since arguments is not really an array so use this approach. var argsAsArray = Array.prototype.slice.call(arguments); result = createSimpleParallelArray.call(this, argsAsArray); } for (i=0;i<fingerprintTracker.length;i++) { if (fingerprint === fingerprintTracker[i]) { console.log ("(fingerprint === fingerprintTracker)"); } } result.uniqueFingerprint = fingerprint++; // use fast code for get if possible if (result.flat && result.shape && result.shape.length < 4) { result = new _fastClasses[result.shape.length](result); } if (enableProxies) { try { // for Chrome/Safari compatability result = Proxy.create(makeIndexOpHandler(result), ParallelArray.prototype); } catch (ignore) {} } if (useFF4Interface && (result.data instanceof Components.interfaces.dpoIData)) { if (useLazyCommunication) { // wrap all functions that need access to the data requiresData(result, "get"); //requiresData(result, "partition"); requiresData(result, "concat"); requiresData(result, "join"); requiresData(result, "slice"); requiresData(result, "toString"); requiresData(result, "getArray"); } else { result.materialize(); } } return result; }; ParallelArray.prototype = { /*** length ***/ // The getter for ParallelArray, there is actually no setter. // NOTE: if this array is non-flat, the length is the length of the data // store. Otherwise it is the first element of the shape. One could // use getShape in both cases, but that will trigger a long computation // for non-flat arrays, which in turn relies on length :-D // get length () { return (this.flat ? this.getShape()[0] : this.data.length); }, set verboseDebug (val) { RiverTrail.compiler.verboseDebug = val; }, set suppressOpenCL (val) { suppressOpenCL = val; }, "materialize" : materialize, "partition" : partition, "isRegularIndexed" : isRegularIndexed, "isRegular" : isRegular, "getShape" : getShape, "map" : map, "mapSeq" : mapSeq, "combine" : combine, "combineSeq" : combineSeq, "reduce" : reduce, "scan" : scan, "filter" : filter, "scatter" : scatter, "getArray" : getArray, "getData" : getData, "get" : get, "writeToCanvas" : writeToCanvas, "concat" : concat, "join" : join, "pop" : pop, "push" : push, "reverse" : reverse, "shift" : shift, "slice" : slice, "sort" : sort, "splice" : splice, "toString" : toString, "unshift" : unshift, "flatten" : flatten, "flattenRegular" : flattenRegular, "inferType" : inferType, get maxPrecision () { return enable64BitFloatingPoint ? 64 : 32; } }; // SAH: Tie up fast classes with the PA prototype. _fastClasses.forEach( function (fc) {fc.prototype.__proto__ = ParallelArray.prototype}); return ParallelArray; }(); // end ParallelArray.prototype var low_precision = function (f) { if (typeof(f) !== "function") { throw new TypeError("low_precision can only be applied to functions"); } return new low_precision.wrapper(f); } low_precision.wrapper = function (f) { this.wrappedFun = f; return this; } low_precision.wrapper.prototype = { "unwrap" : function () { return this.wrappedFun; } };
jslib/ParallelArray.js
/* * Copyright (c) 2011, Intel Corporation * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ "use strict"; //////////////////// //ParallelArray // The constructor for ParallelArrays // Synopsis: // ParallelArray(); // ParallelArray(size, elementalFunction, ...); // ParallelArray(anArray); // ParallelArray(constructor, anArray); // ParallelArray(element0, element1, ... elementN); // ParallelArray(canvas); // Arguments // none // return a ParallelArray without elements. // argument 0 is an Array and there are no more arguments then use the // values in the array to populate the new ParallelArray // argument 1 is an instanceOf Function (the elemental function), // argument 0 is the "size", remaining .. arguments // return a ParallelArray of "size" where each value is the result // of calling the elemental function with the index where its // result goes and any remaining ... arguments // If the size argument is a vector, the index passed to // the elemental function will be a vector, too. If, however, // the size vector is a single scalar value, the index passed to // the elemental value will be a value, as well. // argument 0 is a function and there is one more argument then construct // a new parallel array as above but use the first // argument as constructor for the internal data container; // This form can be used to force the ParallelArray to hold // its data as a typed array // // otherwise Create a ParallelArray initialized to the elements passed // in as arguments. // Discussion // To create a parallel array whose first element is an instanceOf function // one must use the elemental function form and have the elemental function // return the function. // It also means that if one wants to create a ParallelArray with // a single element that is an Array then it must use the // elemental function form with a size of 1 and return the // array from the elemental function. // // Returns // A freshly minted ParallelArray // Notes // <…> is used to indicate a ParallelArray in these examples it is not syntactical sugar actually available to the program. // // pa1 = new ParallelArray(\[[0,1], [2,3], [4,5]]); // <<0,1>, <2,3>, <4.5>> // pa2 = new ParallelArray(pa1); // <<0,1>, <2,3>, <4.5>> // new ParallelArray(<0,1>, <2,3>); // <<0,1>,<2,3>> // new ParallelArray([[0,1],[2]]) // <<0,1>, <2>> // new ParallelArray([<0,1>,<2>]); // <<0,1>, <2>> // new ParallelArray(3, // function(i){return [i, i+1];}); // <<0,1><1,2><2,3>> // new ParallelArray(canvas); // CanvasPixelArray ///////////////// var ParallelArray = function () { // The array object has the following prototype methods that are also implemented // for ParallelArray. // concat, join, slice, toString // See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array // for their description. // The ParallelArray prototype includes the data parallel mechanisms used by ParallelArrays. // // Notes. // Copperheap python - allowed closures to be passed. Pass arguments as free variables.... // // There are other patterns that can be easily derived from these patterns for example max of a ParallelArray // is nothing more that a reduce using the binary max function. // use Proxies to emulate square bracket index selection on ParallelArray objects var enableProxies = false; // check whether the new extension is installed. var useFF4Interface = false; try { if (Components.interfaces.dpoIInterface !== undefined) { useFF4Interface = true; } } catch (ignore) { // useFF4Interface = false; } // check whether the OpenCL implementation supports double var enable64BitFloatingPoint = false; if (useFF4Interface) { var extensions; try { extensions = RiverTrail.compiler.openCLContext.extensions; } catch (ignore) { // extensions = undefined; } if (!extensions) { var dpoI; var dpoP; var dpoC; try { dpoI = new DPOInterface(); dpoP = dpoI.getPlatform(); dpoC = dpoP.createContext(); extensions = dpoC.extensions || dpoP.extensions; } catch (e) { console.log("Unable to query dpoInterface: "+e); } } enable64BitFloatingPoint = (extensions.indexOf("cl_khr_fp64") !== -1); } // this is the storage that is used by default when converting arrays // to typed arrays. var defaultTypedArrayConstructor = useFF4Interface ? (enable64BitFloatingPoint ? Float64Array : Float32Array) : Array; // the default type assigned to JavaScript numbers var defaultNumberType = enable64BitFloatingPoint ? "double" : "float"; // whether to use kernel caching or not var useKernelCaching = true; // whether to use lazy communication of openCL values var useLazyCommunication = false; // whether to cache OpenCL buffers var useBufferCaching = false; // whether to do update in place in scan var useUpdateInPlaceScan = true; // For debugging purposed each parallel array I create has a fingerprint. var fingerprint = 0; var fingerprintTracker = []; var Constants = { // Some constants, when constants are added to JS adjust accordingly "zeroStrideConstant" : [ ], "oneStrideConstant" : [1], "emptyRawArrayConstant" : new defaultTypedArrayConstructor(), "zeroArrayShapeConstant": [0] }; // I create three names for Error here so that we can, should we ever wish // distinguish both or have our own implementation for exceptions var CompilerError = Error; // compilation failed due to wrong program or missing support var CompilerBug = Error; // something went wrong although it should not var CompilerAbort = Error; // exception thrown to influence control flow, e.g., misspeculation // helper function that throws an exception and logs it if verboseDebug is on var debugThrow = function (e) { if (RiverTrail.compiler.verboseDebug) { console.log("Exception: ", JSON.stringify(e)); } throw e; }; // This method wraps the method given by property into a loader for the // actual values of the ParallelArray. On first invocation of the given // method, the function materialize is called before the underlying // method from the prototype/object is executed. var requiresData = function requiresData(pa, property) { pa[property] = function () { pa.materialize(); if (!delete pa[property]) throw new CompilerBug("Deletion of overloaded " + property + " failed"); return pa[property].apply(pa, arguments); }; }; // If this.data is a OpenCL memory object, grab the values and store the OpenCL memory // object in the cache for later use. var materialize = function materialize() { if (useFF4Interface && (this.data instanceof Components.interfaces.dpoIData)) { // we have to first materialise the values on the JavaScript side var cachedOpenCLMem = this.data; this.data = cachedOpenCLMem.getValue(); if (useBufferCaching) { this.cachedOpenCLMem = cachedOpenCLMem; } } }; // Returns true if the values for x an y are withing fuzz. // The purpose is to make sure that if a 64 bit floats is // to a 32 bit float and back that they are recognized as // fuzzyEqual. // This is clearly wrong but need to check with TS to figure out hte // right way to do this. var defaultFuzz = .0000002; // 32 bit IEEE654 has 1 bit of sign, 8 bits of exponent, and 23 bits of mantissa // .0000002 is between 1/(2**22) and 1/(2*23) var fuzzyEqual = function fuzzyEqual (x, y, fuzz) { var diff = x - y; // do the diff now to avoid losing percision from doing abs. if (diff < 0) { diff = -diff; } var absX = (x>0)?x:-x; var absY = (y>0)?y:-y; var normalizedFuzz = ((absX > absY) ? absY : absX) * fuzz; // Avoids 0 if both aren't 0 if (diff <= normalizedFuzz) { // <= so that 0, 0 works since fuzz will go to 0. return true; } return false; }; // Converts the given Array (first argument) into a typed array using the constructor // given as second argument. Validity of conversion is ensured by comparing the result // element-wise using === with the source. If no constructor is provided, the default // is used. var convertToTypedArray = function convertToTypedArray(src, arrayConstructor) { var constructor = arrayConstructor ? arrayConstructor : defaultTypedArrayConstructor; if (src.constructor === constructor) { // transforming the array into an array of the same kind // makes little sense. Besides, if the constructor is the // Array constructor, applying it twice will yield a // doubly nested array! // this.elementalType = constructorToElementalType(constructor); return src; } else { var newTA = new constructor(src); if (arrayConstructor === undefined) { if (src.every(function (val, idx) { return fuzzyEqual(val, newTA[idx], defaultFuzz); })) { return newTA; } else { return undefined; } } else { // we force a typed array due to semantics, so we do not care // whether the resulting values match return newTA; } } }; // late binding of isTypedArray in local namespace var isTypedArray = function lazyLoad(arg) { isTypedArray = RiverTrail.Helper.isTypedArray; return isTypedArray(arg); } var equalsShape = function equalsShape (shapeA, shapeB) { return ((shapeA.length == shapeB.length) && Array.prototype.every.call(shapeA, function (a,idx) { return a == shapeB[idx];})); }; var shapeToStrides = function shapeToStrides(shape) { var strides; var i; if (shape.length == 1) { // Optimize for common case. return Constants.oneStrideConstant; } if (shape.length == 0) { return Constants.zeroStrideConstant; } strides = new Array(shape.length); strides[strides.length-1] = 1; for (i = strides.length-2; i >= 0; i--) { // Calculate from right to left with rightmost being 1. strides[i] = shape[i+1]*strides[i+1]; } // console.log("shapeToStrides: ", strides); return strides; }; // Given the shape of an array return the number of elements. var shapeToLength = function shapeToLength (shape) { var i; var result; if (shape.length == 0) { return 0; } result = shape[0]; for (i=1; i<shape.length;i++) { result = result * shape[i]; } return result; }; // Flatten a multidimensional array to a single dimension. var createFlatArray = function createFlatArray (arr) { // we build localShape and localRank as we go var localShape = []; var localRank = undefined; var flatArray = new Array(); var flatIndex = 0; var flattenFlatParallelArray = function flattenFlatParallelArray (level, pa) { // We know we have a parallel array, we know it is flat. // Flat arrays are flat all the way down. // update/check localShape and localRank pa.shape.forEach( function (v, idx) { if (localShape[level+idx] === undefined) { localShape[level+idx] = v; } else if (localShape[level+idx] !== v) { //throw "wrong shape of nested PA at " + idx + " local " + v + "/global " + localShape[level+idx]; throw "shape mismatch: level " + (level+idx) + " expected " + localShape[level+idx] + " found " + v; } }); if (localRank === undefined) { localRank = level + pa.shape.length; } else if (localRank !== level + pa.shape.length) { throw "dimensionality mismatch; expected " + localRank + " found " + (level + pa.shape.length); } var i; var size = shapeToLength(pa.shape); pa.materialize(); // we have to materialize the array first! for (i=pa.offset;i<pa.offset+size;i++) { flatArray[flatIndex] = pa.data[i]; flatIndex++; } }; var flattenInner = function flattenInner (level, arr) { var i = 0; var thisLevelIndex = 0; if (arr instanceof ParallelArray) { if (arr.flat) { flattenFlatParallelArray(level, arr); return; } } if (localShape[level] === undefined) { localShape[level] = arr.length; } else if (localShape[level] !== arr.length) { // We do not have a regular array. throw "shape mismatch: level " + (level) + " expected " + localShape[level] + " found " + arr.length; } for (thisLevelIndex=0;thisLevelIndex<arr.length;thisLevelIndex++) { if (arr[thisLevelIndex] instanceof Array) { // need to add regular array check... flattenInner(level+1, arr[thisLevelIndex]); } else if (arr[thisLevelIndex] instanceof ParallelArray) { if (arr[thisLevelIndex].flat) { // Flat arrays are flat all the way down. flattenFlatParallelArray(level+1, arr[thisLevelIndex]); } else { flattenInner(level+1, arr[thisLevelIndex].get(i)); } } else { // it's not an array or ParallelArray so it is just an element. flatArray[flatIndex] = arr[thisLevelIndex]; flatIndex++; // check for rank uniformity if (localRank === undefined) { localRank = level; } else if (localRank !== level) { throw "dimensionality mismatch; expected " + localRank + " found " + level; } } } }; // flattenInner try { flattenInner(0, arr); } catch (err) { console.log("flattenArray:", err); return null; }; return flatArray; }; // Given a nested regular array return its shape. var arrShape = function arrShape (arr) { var result = []; while ((arr instanceof Array) || (arr instanceof ParallelArray)) { if (arr instanceof Array) { result.push(arr.length); arr = arr[0]; } else { // It is a ParallelArray result.push(arr.shape[0]); arr = arr.get(0); } } return result; }; // Proxy handler for mapping [<number>] and [<Array>] to call of |get|. // The forwarding part of this proxy is taken from // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Proxy // which in turn was copied from the ECMAScript wiki at // http://wiki.ecmascript.org/doku.php?id=harmony:proxies&s=proxy var makeIndexOpHandler = function makeIndexOpProxy (obj) { return { // Fundamental traps getOwnPropertyDescriptor: function(name) { var desc = Object.getOwnPropertyDescriptor(obj, name); // a trapping proxy's properties must always be configurable if (desc !== undefined) { desc.configurable = true; } return desc; }, getPropertyDescriptor: function(name) { var desc = Object.getPropertyDescriptor(obj, name); // not in ES5 // a trapping proxy's properties must always be configurable if (desc !== undefined) { desc.configurable = true; } return desc; }, getOwnPropertyNames: function() { return Object.getOwnPropertyNames(obj); }, getPropertyNames: function() { return Object.getPropertyNames(obj); // not in ES5 }, defineProperty: function(name, desc) { Object.defineProperty(obj, name, desc); }, delete: function(name) { return delete obj[name]; }, fix: function() { if (Object.isFrozen(obj)) { return Object.getOwnPropertyNames(obj).map(function(name) { return Object.getOwnPropertyDescriptor(obj, name); }); } // As long as obj is not frozen, the proxy won't allow itself to be fixed return undefined; // will cause a TypeError to be thrown }, // derived traps has: function(name) { return name in obj; }, hasOwn: function(name) { return Object.prototype.hasOwnProperty.call(obj, name); }, get: function(receiver, name) { var idx = parseInt(name); if (idx == name) { return obj.get(idx); } else { return obj[name]; } }, set: function(receiver, name, val) { obj[name] = val; return true; }, // bad behavior when set fails in non-strict mode enumerate: function() { var result = []; for (name in obj) { result.push(name); }; return result; }, keys: function() { return Object.keys(obj) } }; } // Helper for constructor that generates an empty array. var createEmptyParallelArray = function createEmptyParallelArray () { this.data = Constants.emptyRawArrayConstant; this.shape = Constants.zeroArrayShapeConstant; this.strides = Constants.oneStrideConstant; this.flat = true; this.offset = 0; return this; }; // Helper for constructor that takes a single element, an array, a typed array, a // ParallelArray, or an image of values. The optional second argument unfluences which // kind of typed array is tried. var createSimpleParallelArray = function createSimpleParallelArray(values, targetType) { if (values instanceof Array) { var flatArray = createFlatArray(values); if (flatArray == null) { // We couldn't flatten the array, it is irregular this.data = new Array(values.length); this.flat = false; for (i=0;i<values.length;i++){ if (values[i] instanceof Array) { this.data[i] = new ParallelArray(values[i]); } else { this.data[i] = values[i]; /** this.shape = this.shape.push(values[i].length); **/ } } } else { // we have a flat array. this.shape = arrShape(values); this.strides = shapeToStrides(this.shape); this.flat = true; this.offset = 0; this.data = convertToTypedArray(flatArray, targetType); if (this.data === undefined) this.data = flatArray; } } else if (values instanceof ParallelArray) { // Parallel Arrays can share data since they are immutable. this.flat = values.flat; if (this.flat) { this.shape = values.shape; this.strides = values.strides; this.offset = values.offset; } if (targetType === undefined) { this.data = values.data; // ParallelArrays are read only so reuse data this.elementalType = values.elementalType; } else { values.materialize(); this.data = new targetType(values.data); } } else if (isTypedArray(values)) { this.flat = true; this.strides = Constants.oneStrideConstant; this.offset = 0; this.shape = [values.length]; // We create a new typed array and copy the source elements over. // Just calling the constructor with the source array would not // suffice as typed arrays share the underlying buffer... this.data = new values.constructor(values.length); for (var i = 0; i < values.length; i++) { this.data[i] = values[i]; } this.isKnownRegular = true; } else if (values.getContext !== undefined) { // proxy for checking if it's a canvas var context = values.getContext("2d"); var imageData = context.getImageData(0, 0, values.width, values.height); this.data = imageData.data; this.shape = [values.height,values.width,4]; this.strides = [4*values.width,4,1]; this.flat = true; this.offset = 0; this.isKnownRegular = true; } else { this.data = new defaultTypedArrayConstructor(1); this.data[0] = values; if (this.data[0] !== values) { this.data = new Array(1); this.data[0] = values; } this.shape = Constants.oneStrideConstant; this.strides = Constants.oneStrideConstant; this.flat = true; this.offset = 0; } return this; }; // Helper for constructor that builds an ParallelArray comprehension. var createComprehensionParallelArray = function createComprehensionParallelArray(sizeVector, theFunction, extraArgs) { var results; var tempVector; var scalarIndex = false; if (!(sizeVector instanceof Array)) { // Handles just passing the size of a 1 d array in as a number. tempVector = new Array(1); tempVector[0] = sizeVector; sizeVector = tempVector; scalarIndex = true; } // try to execute the comprehension in OpenCL try { return RiverTrail.compiler.compileAndGo(this, theFunction, scalarIndex ? "comprehensionScalar" : "comprehension", sizeVector, extraArgs, enable64BitFloatingPoint); } catch (e) { console.log("comprehension failed: " + e); } var left = new Array(0); results = buildRaw(this, left, sizeVector, arguments[1], extraArgs, scalarIndex); // SAH: once we have computed the values, we can fall back to the simple case. createSimpleParallelArray.call(this, results); return this; }; var createOpenCLMemParallelArray = function( mobj, shape, type) { this.data = mobj; this.shape = shape; this.elementalType = type; this.strides = shapeToStrides( shape); this.flat = true; this.offset = 0; return this; }; // Occasionally we want to surpress the actual execution of the OpenCL and just look at the verboseDebug // information. This reduces browser crashes and makes debugging easier. // Normally this is false. var suppressOpenCL = false; //var suppressOpenCL = true; // kernelCompiler is the OCL parser and code generator. It is generated and placed here the first // the the ParallelArray constructor is called. var kernelCompiler = false; // Used by the constructor to build a ParallelArray with given a size vector and a function. // Used by combine to build the new ParallelArray. /*** buildRaw Synopsis: Used by the constructor to build a ParallelArray with given a size vector and a function. Used by combine to build the new ParallelArray. function buildRaw(theThisArray, left, right, fTemp, extraArgs); Arguments theThisArray: the array you are populating. fTemp: A function left: the indices when concatanated to right form the indices passed to fTemp or to a recursive call to buildRaw right: the indices when concatinated to left form the indices passed to fTemp if right has only one index then the actual calls to fTemp are done for all indices from 0 to right[0] fTemp: The first arg is an array holding the indices of where the resulting element belongs along with any extraArg extraArgs: Args that are passed on to fTemp unchanged. scalarindex: If true, the index passed to the elemental function will be a scalar value Returns A freshly minted JS Array whose elements are the results of applying f to the original ParallelArray (this) along with the indices holding where the resulting element is placed in the result. The indices are the concatination of the arguments left and right. Any extraArgs are also passed to f. The expected use case for combine is for fTemp to reference this at the appropriate indices to build the new element. The expected use case for the constructors is to construct the element using the indices and the extra args. ***/ var buildRaw = function buildRaw(theThisArray, left, right, fTemp, extraArgs, scalarIndex) { var i; var elementalResult; var result; if (right.length == 1) { // Here is where you call the fTemp with the indices. var indices = new Array(left.length+1); // This ends up being the indices passed to the elemental function var applyArgs = new Array(extraArgs.length+1); // indices + extra args. for (i=0;i<extraArgs.length;i++) { // these are the args passed to the elemental functionleave the first arg open for indices. applyArgs[i+1] = extraArgs[i]; } var result = new Array(right[0]); // The number of result to expect for (i=0;i<left.length; i++) { indices[i] = left[i]; // Transfer the non-changing indices. } for (i=0; i<right[0]; i++) { if (scalarIndex) { applyArgs[0] = i; } else { indices[left.length] = i; // This is the index that changes. applyArgs[0] = indices; } elementalResult = fTemp.apply(theThisArray, applyArgs); if (elementalResult instanceof Array) { result[i] = new ParallelArray(elementalResult); } else if (elementalResult instanceof ParallelArray) { result[i] = elementalResult; } else { result[i] = elementalResult; } } return result; } if (scalarIndex) { throw new CompilerBug("buildRaw called with scalarIndex === true but higher rank interation space"); } // Build the new index vectors for the recursive call by moving an index from the right to the left. var newLeft = new Array(left.length+1); var newRight = right.slice(1); // Move the first right to the left. for (i=0;i<left.length;i++) { newLeft[i] = left[i]; } newLeft[newLeft.length-1] = right[0]; var range = newLeft[newLeft.length-1]; result = new Array(range); for (i=0; i<range; i++) { newLeft[newLeft.length-1] = i; result[i] = buildRaw(theThisArray, newLeft, newRight, fTemp, extraArgs, scalarIndex); } return result; }; /** Erase RLH. var calculateSize = function calculateSize(ravel) { var size = 0; var i; if (ravel.length == 0) { return size; } size = 1; for (i=ravel.length-1; i>=0; i--) { size = size * ravel[i]; } return size; }; **/ var partition = function partition(partitionSize) { if (this.flat) { return partitionFlat(this, partitionSize); } var aSlice; var i; var partitionCount = this.length / partitionSize; var newArray = new Array(partitionCount); if (partitionCount*partitionSize != this.length) { throw new RangeError("ParallelArray.partition length not evenly divisible by partitionSize."); } for (i=0; i<partitionCount; i++) { aSlice = this.data.slice(i*partitionSize, (i+1)*partitionSize); newArray[i] = new ParallelArray(aSlice); } return new ParallelArray(newArray); }; var partitionFlat = function partitionFlat(pa, partitionSize) { var newShape = new Array(pa.shape.length+1); var i; for (i=1;i<newShape.length;i++) { newShape[i]=pa.shape[i-1]; } // At this point newShape[0] and newShape[1] need to be adjusted to partitionCount and partitionSize newShape[0] = newShape[1] / partitionSize; newShape[1] = partitionSize; if (shapeToLength(newShape) != shapeToLength(pa.shape)) { throw new RangeError("Attempt to partition ParallelArray unevenly."); } var newPA = new ParallelArray("reshape", pa, newShape); return newPA; }; // Does this parallelArray have the following dimension? var isRegularIndexed = function isRegularIndexed(indices) { if (this.length != indices[0]) { return false; } if (indices.length == 1) { return true; } var i; //var result = true; // SH: the below call to slice should do the same // var tempIndices = new Array(indices.length-1); // for (i=0;i<indices.length-1;i++) { // tempIndices[i] = indices[i+1]; // } var tempIndices = indices.slice(1); // the below could be replaced by this but that would break encapsulation //return this.data.every( function checkElement(x) { return x.isRegularIndexed(tempIndices)} ); for (i=0;i<this.length;i++) { if ((this.get(i).isRegularIndexed(tempIndices)) == false) { return false; } } return true; }; // Is this a regular array? // At this point this does not check for type.... var isRegular = function isRegular() { if (this.isKnownRegular === undefined) { if (this.flat) { this.isKnownRegular = true; // this probable should be changed to something isKnownRegular. } else { // Construct the indices for the first element var thisLevel = new Array(0); var indices = new Array(0); var level = this; while (level instanceof ParallelArray) { indices.push(level.length); level = level.get(0); } // indices holds the length of the indices with the biggest at the start. if (this.isRegularIndexed(indices)) { this.shape = indices; this.isKnownRegular = true; } else { this.isKnownRegular = false; } } } return this.isKnownRegular; }; // Get the shape of a regular array down to the depth requested. // Input depth maximum number of indices to invstigate. // If not provided then depth is infinite. var getShape = function getShape(depth) { if (!this.isRegular()) { throw new TypeError("this is not a regular ParallelArray."); } return (depth === undefined) ? this.shape.slice(0) : this.shape.slice(0, depth); }; // When in the elemental function f "this" is the same as "this" in combine. var combineSeq = function combineSeq(depth, f) { // optional arguments follow var i; var result; var extraArgs; var extraArgOffset = 2; if ((typeof(depth) === 'function') || (depth instanceof low_precision.wrapper)) { f = depth; depth = 1; extraArgOffset = 1; } if (f instanceof low_precision.wrapper) { f = f.unwrap(); } if (!this.isRegular()) { throw new TypeError("ParallelArray.combineSeq this is not a regular ParallelArray."); } if (arguments.length == extraArgOffset) { extraArgs = new Array(); } else { extraArgs = new Array(arguments.length-extraArgOffset); for (i=0;i<extraArgs.length;i++) { extraArgs[i] = arguments[i+extraArgOffset]; } } result = buildRaw(this, (new Array(0)), this.getShape(depth), f, extraArgs, false); // SAH temporarily until cast is implemented return new ParallelArray(result); return new ParallelArray(this.data.constructor, result); }; // combine implements the openCL parallel version of combine. // When in the elemental function f "this" is the same as "this" in combine. /*** Combine Overview Similar to map except this is the entire array and an index is provided since you have the entire array you can access other elements in the array. Arguments depth – the number of dimensions traversed to access an element in this Elemental function described below Optional arguments passed unchanged to elemental function Elemental Function this - The ParallelArray index Location in combine’s result where the result of the elemental function is placed. Suitable as the first argument to “get” to retrieve source values. Optional arguments Same as the optional arguments passed to combine Result An element to be placed in combine’s result at the location indicated by index Returns A freshly minted ParallelArray whose elements are the results of applying the elemental function. Example: an identity function pa.combine(function(i){return this.get(i);}) ***/ var combine = function combine(depth, f) { // optional arguments follow var i; var paResult; var extraArgs; var extraArgOffset = 2; if ((typeof(depth) === 'function') || (depth instanceof low_precision.wrapper)) { f = depth; depth = 1; extraArgOffset = 1; } if (!this.isRegular()) { throw new TypeError("ParallelArray.combine this is not a regular ParallelArray."); } if (arguments.length == extraArgOffset) { extraArgs = new Array(0); } else { // depth is _not_ part of the arguments passed to the elemental function extraArgs = new Array(arguments.length-extraArgOffset); // depth and function account for the 2 for (i=0;i<extraArgs.length;i++) { extraArgs[i] = arguments[i+extraArgOffset]; } } paResult = RiverTrail.compiler.compileAndGo(this, f, "combine", depth, extraArgs, enable64BitFloatingPoint); return paResult; }; /** Fundamental Constructs of ParallelArray – the minimal set from which you should be able to cleanly express 90% of the useful constructs needed by programmers. Map, Combine, Reduce, Scan, Scatter Partition, filter **/ /*** mapSeq Elemental Function this - the entire ParallelArray val - an element from the ParallelArray Optional arguments - Same as the optional arguments passed to map Result An element to be placed in the result at the same offset we found “this” Returns A freshly minted ParallelArray Elements are the results of applying the elemental function to the elements in the original ParallelArray plus any optional arguments. Example: an identity function pa.map(function(val){return val;}) ***/ var mapSeq = function mapSeq (f) { // extra args passed unchanged and unindexed. var len = this.shape[0]; var i, j; var fTemp = f; var args = new Array(arguments.length-1); var result = new Array(len); // SAH: for now we have to manually unwrap. Proxies might be a solution but they // are too underspecified as of yet if (f instanceof low_precision.wrapper) { f = f.unwrap(); } if (arguments.length == 1) { // Just a 1 arg function. for (i=0;i<len;i++) { result[i] = f.apply(this, [this.get(i)]); } } else { for (i=0;i<len;i++) { for (j=1;j<arguments.length;j++) { args[j] = arguments[j]; } args[0] = this.get(i); result[i] = f.apply(this, args); } } // SAH: temporary fix until we use cast if (this.data.constructor === Float32Array) { // Not sure what to do here we have a Float32Array and we are using // these typed arrays to hold our data. Maintaining Float32Array will // potentially only loose precision, this is less of a problem than // converting floats to say 8 bit clamped ints. return new ParallelArray(this.data.constructor, result); } return new ParallelArray(result); return new ParallelArray(this.data.constructor, result); }; // // map - // Same as mapSeq but uses the OpenCL optimized version. // var map = function map (f) { // extra args passed unchanged and unindexed. var len = this.shape[0]; var args = new Array(arguments.length-1); var paResult; if (arguments.length === 1) { // no extra arguments present paResult = RiverTrail.compiler.compileAndGo(this, f, "map", 1, args, enable64BitFloatingPoint); } else { for (var j=1;j<arguments.length;j++) { args[j-1] = arguments[j]; } paResult = RiverTrail.compiler.compileAndGo(this, f, "map", 1, args, enable64BitFloatingPoint); } return paResult; }; /*** reduce Arguments Elemental function described below. Optional arguments passed unchanged to elemental function Elemental Function this - the entire ParallelArray a, b - arguments to be reduced and returned Optional arguments - Same as the optional arguments passed to map Result The result of the reducing a and b, typically used in further applications of the elemental function. Returns The final value, if the ParallelArray has only 1 element then that element is returned. Discussion Reduce is free to group calls to the elemental function in arbitrary ways and order the calls arbitrarily. If the elemental function is associative then the final result will be the same regardless of the ordering. For integers addition is an example of an associative function and the sum of a ParallelArray will always be the same regardless of the order that reduces calls addition. Average is an example of non-associative function. Average(Average(2, 3), 9) is 5 2/3 while Average(2, Average(3, 9)) is 4. Reduce is permitted to chose whichever call ordering it finds convenient. Reduce is only required to return a result consistent with some call ordering and is not required to chose the same call ordering on subsequent calls. Furthermore, reduce does not magically resolve problems related to the well document fact that some floating point numbers are not represented exactly in JavaScript and the underlying hardware. Reduce does not require the elemental function be communitive since it does induce reordering of the arguments passed to the elemental function's. ***/ var reduce = function reduce(f, optionalInit) { // SAH: for now we have to manually unwrap. Proxies might be a solution but they // are too underspecified as of yet if (f instanceof low_precision.wrapper) { f = f.unwrap(); } var len = this.shape[0]; var result; var i; result = this.get(0); for (i=1;i<len;i++) { result = f.call(this, result, this.get(i)); } return result; }; /*** scan Arguments Elemental function described below Optional arguments passed unchanged to elemental function Elemental Function this - the entire ParallelArray a, b - arguments to be reduced and returned Optional arguments - Same as the optional arguments passed to scan Result - The result of the reducing a and b, typically used in further applications of the elemental function. Returns A freshly minted ParallelArray whose ith elements is the results of using the elemental function to reduce the elements between 0 and i in the original ParallelArray. Example: an identity function pa.scan(function(a, b){return b;}) Discussion: We implement what is known as an inclusive scan which means that the value of the ith result is the [0 .. i].reduce(elementalFunction) result. Notice that the first element of the result is the same as the first element in the original ParallelArray. An exclusive scan can be implemented by shifting right end off by one the results of an inclusive scan and inserting the identity at location 0. Similar to reduce scan can arbitrarily reorder the order the calls to the elemental functions. Ignoring floating point anomalies, this cannot be detected if the elemental function is associative so using a elemental function such as addition to create a partial sum will produce the same result regardless of the order in which the elemental function is called. However using a non-associative function can produce different results due to the ordering that scan calls the elemental function. While scan will produce a result consistent with a legal ordering the ordering and the result may differ for each call to scan. Typically the programmer will only call scan with associative functions but there is nothing preventing them doing otherwise. ***/ var scan = function scan(f) { // SAH: for now we have to manually unwrap. Proxies might be a solution but they // are too underspecified as of yet if (f instanceof low_precision.wrapper) { f = f.unwrap(); } if (this.getShape()[0] < 2) { // // handle case where we only have one row => the result is the first element // return this; } var i; var len = this.length; var rawResult = new Array(len); var privateThis; var callArguments = Array.prototype.slice.call(arguments, 0); // array copy var ignoreLength = callArguments.unshift(0); // callArguments now has 2 free location for a and b. if (this.getShape().length < 2) { // // Special case where selection yields a scalar element. Offloading the inner // kernel to OpenCL is most likely not beneficial and we cannot use the offset // based selection as get does not yield a Parallel Array. Using a naive for // loop instead. // rawResult[0] = this.get(0); for (i=1;i<len;i++) { callArguments[0] = rawResult[i-1]; callArguments[1] = this.get(i);; rawResult[i] = f.apply(this, callArguments); } return (new ParallelArray(rawResult)); } // // We have a n-dimensional parallel array, so we try to use offset based selection // and speculative OpenCL exectution // var scanCount = 0; var copySize; // Mutable and knows about the internal offset structure. // The offset now points to the second element this.data[1]. // since the first one is the first one in the result. // Pick up the stride from this to use to step through the array var localStride = this.strides[0]; if (useUpdateInPlaceScan) { // SAH: I speculate that the scan operation is shape uniform. If it is not, // performance goes down the drain anyways so a few extra executions won't // matter. try { rawResult[0] = this.get(0); privateThis = this.get(1); callArguments[0] = rawResult[0]; rawResult[1] = f.apply(privateThis, callArguments); if ((rawResult[1].data instanceof Components.interfaces.dpoIData) && equalsShape(rawResult[0].getShape(), rawResult[1].getShape())) { // this was computed by openCL and the function is shape preserving. // Try to preallocate and compute the result in place! // We need the real data here, so materialize it privateThis.materialize(); // create a new typed array for the result and store it in updateinplace var updateInPlace = new privateThis.data.constructor(privateThis.data.length); // copy the first line into the result for (i=0; i<localStride; i++) { updateInPlace[i] = this.data[i]; } // copy the second line into the result var last = rawResult[1]; var result = undefined; last.materialize; for (i=0; i <localStride; i++) { updateInPlace[i+localStride] = last.data[i]; } // create a new parallel array to pass as prev var updateInPlacePA = rawResult[0]; // swap the data store of the updateInPlacePA updateInPlacePA.data = updateInPlace; // set up the arguments callArguments[0] = updateInPlacePA; // set the write offset and updateInPlace info privateThis.updateInPlacePA = updateInPlacePA; privateThis.updateInPlaceOffset = localStride; privateThis.updateInPlaceShape = last.shape; for (i=2;i<len;i++) { // Effectivey change privateThis to refer to the next element in this. privateThis.offset += localStride; updateInPlacePA.offset += localStride; privateThis.updateInPlaceOffset += localStride; privateThis.updateInPlaceUses = 0; // i is the index in the result. result = f.apply(privateThis, callArguments); if (result.data !== privateThis.updateInPlacePA.data) { // we failed to update in place throw new CompilerAbort("speculation failed: result buffer was not used"); } } return new ParallelArray( updateInPlacePA.data, this.shape, this.inferredType); } } catch (e) { // clean up to continute below console.log("scan: speculation failed, reverting to normal mode"); privateThis = this.get(1); rawResult[0] = this.get(0); callArguments[0] = rawResult[0]; } } else { // speculation is disabled, so set up the stage privateThis = this.get(1); rawResult[0] = this.get(0); callArguments[0] = rawResult[0]; rawResult[1] = f.apply(privateThis, callArguments); } for (i=2;i<len;i++) { // Effectivey change privateThis to refer to the next element in this. privateThis.offset += localStride; callArguments[0] = rawResult[i-1]; // i is the index in the result. rawResult[i] = f.apply(privateThis, callArguments); } return (new ParallelArray(rawResult)); }; /*** filter Arguments Elemental function described below Optional arguments passed unchanged to elemental function Elemental Function this - The ParallelArray index - The location in “this” where the source element is found. Optional arguments - Same as the optional arguments passed to filter Result true (true, 1, or other JavaScript truthy value) if the source element should be placed in filter’s result. false (false, 0, undefined, or other JavaScript falsey value) if the source element should not to be placed in filter’s result. Returns A freshly minted ParallelArray holding source elements where the results of applying the elemental function is true. The order of the elements in the returned ParallelArray is the same as the order of the elements in the source ParallelArray. Example: an identity function pa.filter(function(){return true;}) ***/ var filter = function filter(f) { var len = this.length; // Generate a ParallelArray where t means the corresponding value is in the resulting array. var boolResults = combineSeq.apply(this, arguments); var rawResult; var i, j; var resultSize = 0; for (i=0;i<this.length;i++) { if (boolResults.get(i) != 0) { resultSize++; } } rawResult = new Array(resultSize); j = 0; for (i=0;i<len;i++) { if (boolResults.get(i) == 1) { rawResult[j] = this.get(i); j++; } } return (new ParallelArray(rawResult)); }; /*** scatter Arguments indices: array of indices in the resulting array defaultValue: optional argument indicating the value of elements not set by scatter When not present, the default value is 'undefined’ conflictFunction: optional function to resolve conflicts, details below. length: optional argument indicating the length of the resulting array. If absent, the length is the same as the length of the indices argument Note that scatter does not take an elemental function Optional arguments are ignored. Returns A freshly minted ParallelArray A whose elements are the result of: A[indices[i]] = this[i], when indices[i] is unique A[indices[i]] = conflictFunction(index, A[indices[i]],) when A[indices[i]] has a previously assigned value. defaultValue, when index is not present in 'indices' array Example: an identity function pa.scatter(indices); where indices is a ParallelArray where element === index Handling conflicts Conflicts result when multiple elements are scattered to the same location. Conflicts results in a call to conflictFunction, which is an optional third argument to scatter Arguments this is value from the source array that is currently being scattered Previous value – value in result placed there by some previous iteration It is the programmer’s responsibility to provide a conflictFunction that is associative and commutative since there is no guarantee in what order the conflicts will be resolved. Returns Value to place in result[indices[index]] Example: Resolve conflict with larger number chooseMax(prev){ return (this>prev)?this:prev; } ***/ var scatter = function scatter(indices, defaultValue, conflictFunction, length) { var result; var len = this.shape[0]; var hasDefault = (arguments.length >= 2); var hasConflictFunction = (arguments.length >=3 && arguments[2] != null); var newLen = (arguments.length >= 4 ? length : len); var rawResult = new Array(newLen); var conflictResult = new Array(newLen); var i; if (hasDefault) { for (i = 0; i < newLen; i++) { rawResult[i] = defaultValue; } } for (i = 0; i < indices.length; i++) { var ind = (indices instanceof ParallelArray) ? indices.get(i) : indices[i]; if (ind >= newLen) throw new RangeError("Scatter index out of bounds"); if (conflictResult[ind]) { // we have already placed a value at this location if (hasConflictFunction) { rawResult[ind] = conflictFunction.call(undefined, this.get(i), rawResult[ind]); } else { throw new RangeError("Duplicate indices in scatter"); } } else { rawResult[ind] = this.get(i); conflictResult[ind] = true; } } result = new ParallelArray(rawResult); return result; }; /*** End of the fundemental constructts */ /*** getArray Synopsis: getArray(); Arguments: none Returns Returns a JS array holding a copy of the elements from the ParallelArray. If the element is a ParallelArray then it's elemets are also copied in to a JS Array. ***/ var getArray = function getArray () { var i, result; if ((this.flat) && (this.shape.length === 1)) { result = Array.prototype.slice.call(this.data, this.offset, this.offset + this.length); } else { result = new Array(this.length); for (i=0; i<this.length; i++) { var elem = this.get(i); if (elem instanceof ParallelArray) { result[i] = elem.getArray(); } else { result[i] = elem; } } } return result; }; // This takes a ParallelArray and creates a similar JavaScript array. // By similar the array returned will be of a cononical type. In // particular it will be whatever type the data in the ParallelArray // is held in. A Float32Array would be returned if the original ParallelArray // held the actual data in a Float32Array. var getData = function getData() { var result = new this.data.constructor(this.data); return result; }; /*** get Synopsis: get(index); Arguments index: a integer indicating that you want the element in the highest rank, typically this is used for vectors. index: an array of integers indicating that you want an element in a multiple dimension array. Returns The element refered to by the index/indices. ***/ var get = function get (index) { var i; var result; var offset; var argsAsArray; // For converting from arguements into a real array. if (this.flat) { if (index instanceof Array) { offset = this.offset; var len = index.length; for (i=0;i<len;i++) { // if we go out of bounds, we return undefined if (index[i] < 0 || index[i] >= this.shape[i]) return undefined; offset = offset + index[i]*this.strides[i]; } if (this.shape.length === index.length) { return this.data[offset]; } else { // build a ParallelArray. result = new ParallelArray(this); result.offset = offset; result.elementalType = this.elementalType; /* need to fix up shape somehow. */ result.shape = this.shape.slice(index.length); result.strides = this.strides.slice(index.length); /* changing the shape might invalidate the _fastClasses specialisation, * so better ensure things are still fine */ if (result.__proto__ !== ParallelArray.prototype) { result.__proto__ = _fastClasses[result.shape.length].prototype; } return result; } } // else it is flat but not (index instanceof Array) if (arguments.length == 1) { // One argument that is a scalar index. if ((index < 0) || (index >= this.shape[0])) return undefined; if (this.shape.length == 1) { // a 1D array return this.data[this.offset + index]; } else { // we have a nD array and we want the first dimension so create the new array offset = this.offset+this.strides[0]*index; // build a ParallelArray. result = new ParallelArray(this); result.offset = offset; result.elementalType = this.elementalType; /* need to fix up shape somehow. */ result.shape = this.shape.slice(1); result.strides = this.strides.slice(1); return result; } } // Still a flat array but more than on argument, turn into an array and recurse. argsAsArray = Array.prototype.slice.call(arguments); return this.get(argsAsArray); } // end flat array path. if (arguments.length == 1) { if (!(arguments[0] instanceof Array)) { return this.data[index]; } else { // not flat, index is an array of indices. result = this; for (i=0;i<arguments[0].length;i++) { result = result.data[arguments[0][i]]; // out of bounds => abort further selections if (result === undefined) return result; } return result; } } // not flat, more than one argument. result = this; for (i=0;i<arguments.length;i++) { result = result.data[arguments[i]]; // out of bounds => abort further selections if (result === undefined) return result; } return result; }; // Write content of parallel array into a canvas // XXX: Assumes that image is going to fill the whole canvas var writeToCanvas = function writeToCanvas(canvas) { var i; var context = canvas.getContext("2d"); var currImage = context.getImageData(0, 0, canvas.width, canvas.height); var imageData = context.createImageData(currImage.width, currImage.height); var data = imageData.data; if (useFF4Interface && (this.data instanceof Components.interfaces.dpoIData)) { this.data.writeTo(data); } else { for (var i = 0; i < this.data.length; i++) { data[i] = this.data[i]; } } context.putImageData(imageData, 0, 0); }; // Some functions that mimic the JavaScript Array functionality *** // The array object has the following prototype methods that are also implemented // for ParallelArray. // // concat() // join() // slice() // toString() // See // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array // for a description. // // // concat() Joins two or more arrays, and returns a copy of the joined arrays var concat = function concat () { var len = arguments.length; var result; var applyArgs; var allTypedArrays = isTypedArray(this.data); var allArrays = (this.data instanceof Array); var resultLength = this.length; var offset = 0; var i, j; applyArgs = new Array(arguments.length); for (var i=0; i<len; i++) { applyArgs[i] = arguments[i]; resultLength += arguments[i].length; if (allTypedArrays) { // if this and previous are true check if this arg uses typed arrays. allTypedArrays = isTypedArray(arguments[i].data); allArrays = false; } if (allArrays) { // this and all previous are Arrays. allArrays = (arguments[i].data instanceof Array); } } if (allTypedArrays) { return concatTypedArrayData.apply(this, applyArgs); } if (allArrays) { return concatArrayData.apply(this, applyArgs); } // Nothing simple just do it like the old fashion way, one element at a time. result = new Array(resultLength); // Do this for (i=0;i<this.length;i++) { result[offset] = this.get(i); offset++; } // Do the arguments for (i=0;i<arguments.length; i++) { for (j=0; j<arguments[i].length;j++) { result[offset] = arguments[i].get(j); offset++; } } return new ParallelArray(result); }; // concatTypedArrayData() Joins two or more arrays using typed arrays, and // returns a copy of the joined arrays var concatTypedArrayData = function concatTypedArrayData () { var len = arguments.length; var result; var applyArgs; var i; var resultLength = this.length; var offset; for (i=0;i<arguments.length;i++) { resultLength += arguments[i].length; } result = this.data.constructor(resultLength); result.set(this.data); offset = this.length; for (i=0; i<len; i++) { result.set(arguments[i].data, offset); offset = offset + arguments[i].length; } return new ParallelArray (result); }; // concatTypedArrayData() Joins two or more arrays using typed arrays, and // returns a copy of the joined arrays var concatArrayData = function concatArrayData () { var i; var result = new Array(); result = result.concat(this.data); for (i=0;i<arguments.length;i++) { result = result.concat(arguments.data); } return new ParallelArray (result); }; // join() Joins all elements of an array into a string var join = function join (arg1) { var result; if (!arg1) { result = this.data.join(); } else { if (arg1 instanceof ParallelArray) { result = this.data.join(arg1.data); } else { result = this.data.join(arg1); } } return result; }; // pop() Removes the last element of an array, and returns that element var pop = function pop (f) { throw new TypeError("ParallelArray has no method 'pop' - it is a read only construct."); }; // push() Adds new elements to the end of an array, and returns the new length var push = function push (f) { throw new TypeError("ParallelArray has no method 'push' - it is a read only construct."); }; // reverse() Reverses the order of the elements in an array var reverse = function reverse (f) { throw new TypeError("ParallelArray has no method 'reverse' - it is a read only construct."); }; // shift() Removes the first element of an array, and returns that element var shift = function shift (f) { throw new TypeError("ParallelArray has no method 'shift' - it is a read only construct."); }; // slice() Selects a part of an array, and returns the new array var slice = function slice (startArg, endArg) { var result; if (isTypedArray(this.data)) { // typed arrays use subset instead of slice. return new ParallelArray(this.data.subarray(startArg, endArg)); } return new ParallelArray(this.data.slice(startArg, endArg)); }; // sort() Sorts the elements of an array var sort = function sort (f) { throw new TypeError("ParallelArray has no method 'sort' - it is a read only construct."); }; // splice() Adds/Removes elements from an array var splice = function splice (f) { throw new TypeError("ParallelArray has no method 'splice' - it is a read only construct."); }; // toString() Converts an array to a string, and returns the result var toString = function toString (arg1) { var max = this.shape.reduce(function (v, p) { return v*p; }) + this.offset; var res = "["; for (var pos = this.offset; pos < max; pos++) { res += ((pos === this.offset) ? "" : ", ") + this.data[pos]; } res += "]"; return res; }; // unshift() Adds new elements to the beginning of an array, and returns the new length var unshift = function unshift (f) { throw new TypeError("ParallelArray has no method 'unshift' - it is a read only construct."); }; var flatten = function flatten () { var len = this.length; var newLength = 0; var shape; var i; if (this.flat) { shape = this.getShape(); if (shape.length == 1) { throw new TypeError("ParallelArray.flatten array is flat"); } var newShape = shape.slice(1); newShape[0] = newShape[0] * shape[0]; return new ParallelArray("reshape", this, newShape); } for (i=0;i<len;i++) { if (this.get(i) instanceof ParallelArray) { newLength = newLength+this.get(i).length; } else { throw new TypeError("ParallelArray.flatten not a ParallelArray of ParallelArrays."); } } var resultArray = new Array(newLength); var next = 0; for (i=0;i<len;i++) { var pa = this.get(i); for (j=0; j<pa.length; j++) { resultArray[next] = pa.get(j); next++; } } return new ParallelArray(resultArray); }; var flattenRegular = function flattenRegular () { var result; if (this.flat) { result = new ParallelArray(this); result.strides = [1]; result.shape = [shapeToLength(this.shape)]; result.offset = 0; return result; } var fillArray = function fillArray ( src, offset, dest) { if (src.length !== 0) { if (src.get(0) instanceof ParallelArray) { for (var pos = 0; pos < src.length; pos++) { offset = fillArray( src.get(pos), offset, dest); } } else { for (var pos = 0; pos < src.length; pos++) { dest[offset] = src.get(pos); offset++; } } } return offset; } if (!this.isRegular()) { throw new TypeError("ParallelArray.flatten called on non-regular array"); } var newLength = this.shape.reduce(function (a,b) { return a * b;}, 1); var resultArray = new Array( newLength); fillArray( this, 0, resultArray); return new ParallelArray( resultArray); }; var inferType = function inferType () { // TODO: deprecated, delete for good throw "inferType is no longer here!"; }; var _fastClasses = function () { var Fast0DPA = function (pa) { // shallow copy of object w/o attributes inherited from prototype // // SAH: The following generic code would be nice to use, but it prevents // some optimisation in Spidermonkey (layout analysis?) and this // has a huge runtime cost... // // var keys = Object.keys(pa); // for (idx in keys) { // this[keys[idx]] = pa[keys[idx]]; // } this.shape = pa.shape; this.strides = pa.strides; this.offset = pa.offset; this.elementalType = pa.elementalType; this.data = pa.data; this.flat = pa.flat; return this; } Fast0DPA.prototype = { "get" : function fastGet0D () { if (arguments.length === 0) { return this; } else { throw "too many indices in get call"; } } }; var Fast1DPA = function (pa) { // shallow copy of object w/o attributes inherited from prototype // // SAH: The following generic code would be nice to use, but it prevents // some optimisation in Spidermonkey (layout analysis?) and this // has a huge runtime cost... // // var keys = Object.keys(pa); // for (idx in keys) { // this[keys[idx]] = pa[keys[idx]]; // } this.shape = pa.shape; this.strides = pa.strides; this.offset = pa.offset; this.elementalType = pa.elementalType; this.data = pa.data; this.flat = pa.flat; return this; } Fast1DPA.prototype = { "get" : function fastGet1D (index) { var aLen = arguments.length; if (aLen === 1) { if (typeof(index) === "number") { if ((index < 0) || (index >= this.shape[0])) return undefined; return this.data[this.offset + index]; } else { /* fall back to slow mode */ return this.__proto__.__proto__.get.call(this, index); } } else if (aLen === 0) { return this; } else { throw "too many indices in get call"; } } }; var Fast2DPA = function (pa) { // shallow copy of object w/o attributes inherited from prototype // // SAH: The following generic code would be nice to use, but it prevents // some optimisation in Spidermonkey (layout analysis?) and this // has a huge runtime cost... // // var keys = Object.keys(pa); // for (idx in keys) { // this[keys[idx]] = pa[keys[idx]]; // } this.shape = pa.shape; this.strides = pa.strides; this.offset = pa.offset; this.elementalType = pa.elementalType; this.data = pa.data; this.flat = pa.flat; return this; } Fast2DPA.prototype = { "get" : function fastGet2D (index, index2) { var result; var aLen = arguments.length; if (aLen === 2) { if ((index < 0) || (index >= this.shape[0]) || (index2 < 0) || (index2 >= this.shape[1])) return undefined; return this.data[this.offset + index * this.strides[0] + index2]; } else if (aLen === 1) { if (typeof index === "number") { if ((index < 0) || (index >= this.shape[0])) return undefined; result = new Fast1DPA(this); result.offset = this.offset + index * this.strides[0]; result.elementalType = this.elementalType; /* need to fix up shape somehow. */ result.shape = this.shape.slice(1); result.strides = this.strides.slice(1); return result; } else { /* fall back to slow mode */ return this.__proto__.__proto__.get.call(this, index); } } else if (aLen === 0) { return this; } else { throw "too many indices in get call"; } } }; var Fast3DPA = function (pa) { // shallow copy of object w/o attributes inherited from prototype // // SAH: The following generic code would be nice to use, but it prevents // some optimisation in Spidermonkey (layout analysis?) and this // has a huge runtime cost... // // var keys = Object.keys(pa); // for (idx in keys) { // this[keys[idx]] = pa[keys[idx]]; // } this.shape = pa.shape; this.strides = pa.strides; this.offset = pa.offset; this.elementalType = pa.elementalType; this.data = pa.data; this.flat = pa.flat; return this; } Fast3DPA.prototype = { "get" : function fastGet3D (index, index2, index3) { var result; var aLen = arguments.length; if (aLen === 3) { if ((index < 0) || (index >= this.shape[0]) || (index2 < 0) || (index2 >= this.shape[1]) || (index3 < 0) || (index3 >= this.shape[2])) return undefined; return this.data[this.offset + index * this.strides[0] + index2 * this.strides[1] + index3]; } else if (aLen === 2) { if ((index < 0) || (index >= this.shape[0]) || (index2 < 0) || (index2 >= this.shape[1])) return undefined; result = new Fast1DPA(this); result.offset = this.offset + index * this.strides[0] + index2 * this.strides[1]; result.elementalType = this.elementalType; /* need to fix up shape somehow. */ result.shape = this.shape.slice(2); result.strides = this.strides.slice(2); return result; } else if (aLen === 1) { if (typeof index === "number") { if ((index < 0) || (index >= this.shape[0])) return undefined; result = new Fast2DPA(this); result.offset = this.offset + index * this.strides[0]; result.elementalType = this.elementalType; /* need to fix up shape somehow. */ result.shape = this.shape.slice(1); result.strides = this.strides.slice(1); return result; } else { /* fall back to slow mode */ return this.__proto__.__proto__.get.call(this, index); } } else { throw "too many indices in get call"; } } }; return [Fast0DPA,Fast1DPA,Fast2DPA,Fast3DPA]; }(); function ParallelArray () { var i, j; var args; var result = this; for (i=0;i<fingerprintTracker.length;i++) { if (fingerprint === fingerprintTracker[i]) { console.log ("(fingerprint === fingerprintTracker)"); } } if (arguments.length == 0) { result = createEmptyParallelArray.call(this); } else if (arguments.length == 1) { result = createSimpleParallelArray.call(this, arguments[0]); } else if ((arguments.length == 2) && (typeof(arguments[0]) == 'function')) { // Special case where we force the type of the result. Should only be used internally result = createSimpleParallelArray.call(this, arguments[1], arguments[0]); } else if ((arguments.length == 3) && (arguments[0] == 'reshape')) { // special constructor used internally to create a clone with different shape result = this; result.shape = arguments[2]; result.strides = shapeToStrides(arguments[2]); result.offset = arguments[1].offset; result.elementalType = arguments[1].elementalType; result.data = arguments[1].data; result.flat = arguments[1].flat; } else if (useFF4Interface && (arguments[0] instanceof Components.interfaces.dpoIData)) { result = createOpenCLMemParallelArray.apply(this, arguments); } else if (typeof(arguments[1]) === 'function' || arguments[1] instanceof low_precision.wrapper) { var extraArgs; if (arguments.length > 2) { extraArgs = new Array(arguments.length -2); // skip the size vector and the function for (i=2;i<arguments.length; i++) { extraArgs[i-2] = arguments[i]; } } else { // No extra args. extraArgs = new Array(0); } result = createComprehensionParallelArray.call(this, arguments[0], arguments[1], extraArgs); } else { // arguments.slice doesn't work since arguments is not really an array so use this approach. var argsAsArray = Array.prototype.slice.call(arguments); result = createSimpleParallelArray.call(this, argsAsArray); } for (i=0;i<fingerprintTracker.length;i++) { if (fingerprint === fingerprintTracker[i]) { console.log ("(fingerprint === fingerprintTracker)"); } } result.uniqueFingerprint = fingerprint++; // use fast code for get if possible if (result.flat && result.shape && result.shape.length < 4) { result = new _fastClasses[result.shape.length](result); } if (enableProxies) { try { // for Chrome/Safari compatability result = Proxy.create(makeIndexOpHandler(result), ParallelArray.prototype); } catch (ignore) {} } if (useFF4Interface && (result.data instanceof Components.interfaces.dpoIData)) { if (useLazyCommunication) { // wrap all functions that need access to the data requiresData(result, "get"); //requiresData(result, "partition"); requiresData(result, "concat"); requiresData(result, "join"); requiresData(result, "slice"); requiresData(result, "toString"); requiresData(result, "getArray"); } else { result.materialize(); } } return result; }; ParallelArray.prototype = { /*** length ***/ // The getter for ParallelArray, there is actually no setter. // NOTE: if this array is non-flat, the length is the length of the data // store. Otherwise it is the first element of the shape. One could // use getShape in both cases, but that will trigger a long computation // for non-flat arrays, which in turn relies on length :-D // get length () { return (this.flat ? this.getShape()[0] : this.data.length); }, set verboseDebug (val) { RiverTrail.compiler.verboseDebug = val; }, set suppressOpenCL (val) { suppressOpenCL = val; }, "materialize" : materialize, "partition" : partition, "isRegularIndexed" : isRegularIndexed, "isRegular" : isRegular, "getShape" : getShape, "map" : map, "mapSeq" : mapSeq, "combine" : combine, "combineSeq" : combineSeq, "reduce" : reduce, "scan" : scan, "filter" : filter, "scatter" : scatter, "getArray" : getArray, "getData" : getData, "get" : get, "writeToCanvas" : writeToCanvas, "concat" : concat, "join" : join, "pop" : pop, "push" : push, "reverse" : reverse, "shift" : shift, "slice" : slice, "sort" : sort, "splice" : splice, "toString" : toString, "unshift" : unshift, "flatten" : flatten, "flattenRegular" : flattenRegular, "inferType" : inferType, get maxPrecision () { return enable64BitFloatingPoint ? 64 : 32; } }; // SAH: Tie up fast classes with the PA prototype. _fastClasses.forEach( function (fc) {fc.prototype.__proto__ = ParallelArray.prototype}); return ParallelArray; }(); // end ParallelArray.prototype var low_precision = function (f) { if (typeof(f) !== "function") { throw new TypeError("low_precision can only be applied to functions"); } return new low_precision.wrapper(f); } low_precision.wrapper = function (f) { this.wrappedFun = f; return this; } low_precision.wrapper.prototype = { "unwrap" : function () { return this.wrappedFun; } };
fixes issue #20: properly handle new argument order to scan
jslib/ParallelArray.js
fixes issue #20: properly handle new argument order to scan
<ide><path>slib/ParallelArray.js <ide> this.data[i] = new ParallelArray(values[i]); <ide> } else { <ide> this.data[i] = values[i]; <del> /** <del> this.shape = this.shape.push(values[i].length); <del> **/ <ide> } <ide> } <ide> } else { // we have a flat array. <ide> <ide> var len = this.length; <ide> var rawResult = new Array(len); <del> var privateThis; <add> var movingArg; <ide> var callArguments = Array.prototype.slice.call(arguments, 0); // array copy <ide> var ignoreLength = callArguments.unshift(0); // callArguments now has 2 free location for a and b. <ide> if (this.getShape().length < 2) { <ide> // matter. <ide> try { <ide> rawResult[0] = this.get(0); <del> privateThis = this.get(1); <add> movingArg = this.get(1); <ide> callArguments[0] = rawResult[0]; <del> rawResult[1] = f.apply(privateThis, callArguments); <add> callArguments[1] = movingArg; <add> rawResult[1] = f.apply(this, callArguments); <ide> if ((rawResult[1].data instanceof Components.interfaces.dpoIData) && <ide> equalsShape(rawResult[0].getShape(), rawResult[1].getShape())) { <ide> // this was computed by openCL and the function is shape preserving. <ide> // Try to preallocate and compute the result in place! <ide> // We need the real data here, so materialize it <del> privateThis.materialize(); <add> movingArg.materialize(); <ide> // create a new typed array for the result and store it in updateinplace <del> var updateInPlace = new privateThis.data.constructor(privateThis.data.length); <add> var updateInPlace = new movingArg.data.constructor(movingArg.data.length); <ide> // copy the first line into the result <ide> for (i=0; i<localStride; i++) { <ide> updateInPlace[i] = this.data[i]; <ide> updateInPlacePA.data = updateInPlace; <ide> // set up the arguments <ide> callArguments[0] = updateInPlacePA; <add> callArguments[1] = movingArg; <ide> // set the write offset and updateInPlace info <del> privateThis.updateInPlacePA = updateInPlacePA; <del> privateThis.updateInPlaceOffset = localStride; <del> privateThis.updateInPlaceShape = last.shape; <add> movingArg.updateInPlacePA = updateInPlacePA; <add> movingArg.updateInPlaceOffset = localStride; <add> movingArg.updateInPlaceShape = last.shape; <ide> for (i=2;i<len;i++) { <del> // Effectivey change privateThis to refer to the next element in this. <del> privateThis.offset += localStride; <add> // Effectivey change movingArg to refer to the next element in this. <add> movingArg.offset += localStride; <ide> updateInPlacePA.offset += localStride; <del> privateThis.updateInPlaceOffset += localStride; <del> privateThis.updateInPlaceUses = 0; <add> movingArg.updateInPlaceOffset += localStride; <add> movingArg.updateInPlaceUses = 0; <ide> // i is the index in the result. <del> result = f.apply(privateThis, callArguments); <del> if (result.data !== privateThis.updateInPlacePA.data) { <add> result = f.apply(this, callArguments); <add> if (result.data !== movingArg.updateInPlacePA.data) { <ide> // we failed to update in place <ide> throw new CompilerAbort("speculation failed: result buffer was not used"); <ide> } <ide> catch (e) { <ide> // clean up to continute below <ide> console.log("scan: speculation failed, reverting to normal mode"); <del> privateThis = this.get(1); <add> movingArg = this.get(1); <ide> rawResult[0] = this.get(0); <ide> callArguments[0] = rawResult[0]; <ide> } <ide> } else { <ide> // speculation is disabled, so set up the stage <del> privateThis = this.get(1); <add> movingArg = this.get(1); <ide> rawResult[0] = this.get(0); <ide> callArguments[0] = rawResult[0]; <del> rawResult[1] = f.apply(privateThis, callArguments); <add> callArguments[1] = movingArg; <add> rawResult[1] = f.apply(this, callArguments); <ide> } <ide> <ide> for (i=2;i<len;i++) { <del> // Effectivey change privateThis to refer to the next element in this. <del> privateThis.offset += localStride; <add> // Effectivey change movingArg to refer to the next element in this. <add> movingArg.offset += localStride; <ide> callArguments[0] = rawResult[i-1]; <ide> // i is the index in the result. <del> rawResult[i] = f.apply(privateThis, callArguments); <add> rawResult[i] = f.apply(this, callArguments); <ide> } <ide> return (new ParallelArray(rawResult)); <ide> }; <ide> <ide> // toString() Converts an array to a string, and returns the result <ide> var toString = function toString (arg1) { <del> var max = this.shape.reduce(function (v, p) { return v*p; }) + this.offset; <del> var res = "["; <del> for (var pos = this.offset; pos < max; pos++) { <del> res += ((pos === this.offset) ? "" : ", ") + this.data[pos]; <del> } <del> res += "]"; <del> return res; <add> if (this.flat) { <add> var max = this.shape.reduce(function (v, p) { return v*p; }) + this.offset; <add> var res = "["; <add> for (var pos = this.offset; pos < max; pos++) { <add> res += ((pos === this.offset) ? "" : ", ") + this.data[pos]; <add> } <add> res += "]"; <add> return res; <add> } else { <add> return "[" + this.data.join(", ") + "]"; <add> } <ide> }; <ide> <ide> // unshift() Adds new elements to the beginning of an array, and returns the new length
Java
mit
error: pathspec 'src/powers/At_Will.java' did not match any file(s) known to git
f8df3d570d4d02757f2c4c758d8ccf8efe00885a
1
42mileslong/dnd-4e-simulator
package powers; /** * @author Rafi Long */ public class At_Will { }
src/powers/At_Will.java
Created At Will class
src/powers/At_Will.java
Created At Will class
<ide><path>rc/powers/At_Will.java <add>package powers; <add> <add>/** <add> * @author Rafi Long <add> */ <add>public class At_Will { <add>}
Java
agpl-3.0
error: pathspec 'src/test/java/com/akiban/server/test/it/qp/Sort_MixedColumnTypesIT.java' did not match any file(s) known to git
e4f0b01185ad096e6f473ffd92442a3301a307b1
1
jaytaylor/sql-layer,shunwang/sql-layer-1,wfxiang08/sql-layer-1,ngaut/sql-layer,ngaut/sql-layer,qiuyesuifeng/sql-layer,jaytaylor/sql-layer,wfxiang08/sql-layer-1,relateiq/sql-layer,qiuyesuifeng/sql-layer,jaytaylor/sql-layer,relateiq/sql-layer,shunwang/sql-layer-1,relateiq/sql-layer,wfxiang08/sql-layer-1,jaytaylor/sql-layer,ngaut/sql-layer,wfxiang08/sql-layer-1,qiuyesuifeng/sql-layer,relateiq/sql-layer,qiuyesuifeng/sql-layer,ngaut/sql-layer,shunwang/sql-layer-1,shunwang/sql-layer-1
/** * END USER LICENSE AGREEMENT (“EULA”) * * READ THIS AGREEMENT CAREFULLY (date: 9/13/2011): * http://www.akiban.com/licensing/20110913 * * BY INSTALLING OR USING ALL OR ANY PORTION OF THE SOFTWARE, YOU ARE ACCEPTING * ALL OF THE TERMS AND CONDITIONS OF THIS AGREEMENT. YOU AGREE THAT THIS * AGREEMENT IS ENFORCEABLE LIKE ANY WRITTEN AGREEMENT SIGNED BY YOU. * * IF YOU HAVE PAID A LICENSE FEE FOR USE OF THE SOFTWARE AND DO NOT AGREE TO * THESE TERMS, YOU MAY RETURN THE SOFTWARE FOR A FULL REFUND PROVIDED YOU (A) DO * NOT USE THE SOFTWARE AND (B) RETURN THE SOFTWARE WITHIN THIRTY (30) DAYS OF * YOUR INITIAL PURCHASE. * * IF YOU WISH TO USE THE SOFTWARE AS AN EMPLOYEE, CONTRACTOR, OR AGENT OF A * CORPORATION, PARTNERSHIP OR SIMILAR ENTITY, THEN YOU MUST BE AUTHORIZED TO SIGN * FOR AND BIND THE ENTITY IN ORDER TO ACCEPT THE TERMS OF THIS AGREEMENT. THE * LICENSES GRANTED UNDER THIS AGREEMENT ARE EXPRESSLY CONDITIONED UPON ACCEPTANCE * BY SUCH AUTHORIZED PERSONNEL. * * IF YOU HAVE ENTERED INTO A SEPARATE WRITTEN LICENSE AGREEMENT WITH AKIBAN FOR * USE OF THE SOFTWARE, THE TERMS AND CONDITIONS OF SUCH OTHER AGREEMENT SHALL * PREVAIL OVER ANY CONFLICTING TERMS OR CONDITIONS IN THIS AGREEMENT. */ package com.akiban.server.test.it.qp; import com.akiban.ais.model.GroupTable; import com.akiban.ais.model.UserTable; import com.akiban.qp.operator.API; import com.akiban.qp.operator.Cursor; import com.akiban.qp.operator.Operator; import com.akiban.qp.operator.QueryContext; import com.akiban.qp.operator.RowsBuilder; import com.akiban.qp.operator.SimpleQueryContext; import com.akiban.qp.operator.StoreAdapter; import com.akiban.qp.persistitadapter.PersistitAdapter; import com.akiban.qp.row.Row; import com.akiban.qp.rowtype.Schema; import com.akiban.qp.rowtype.UserTableRowType; import com.akiban.server.expression.Expression; import com.akiban.server.expression.std.FieldExpression; import com.akiban.server.test.it.ITBase; import com.akiban.server.types.AkType; import org.junit.Before; import org.junit.Test; import static com.akiban.qp.operator.API.*; public final class Sort_MixedColumnTypesIT extends ITBase { @Before public void createSchema() { customer = createTable( "schema", "customer", "cid int not null primary key", "name varchar(32)", "importance decimal(5,2)" ); createIndex( "schema", "customer", "importance_and_name", "importance", "name" ); // These values have been picked for the following criteria: // - neither 'name' nor 'importance' are consistently ordered relative to cid // - when the rows are ordered by name, they are unordered by importance // - when the rows are ordered by importance, they are unordered by name writeRows( createNewRow(customer, 4L, "Aaa", "32.00"), createNewRow(customer, 2L, "Aaa", "75.25"), createNewRow(customer, 1L, "Ccc", "100.00"), createNewRow(customer, 3L, "Bbb", "120.00") ); schema = new Schema(ddl().getAIS(session())); UserTable cTable = getUserTable(customer); customerRowType = schema.userTableRowType(cTable); customerGroupTable = cTable.getGroup().getGroupTable(); } @Test public void unidirectional() { Ordering ordering = API.ordering(); orderBy(ordering, 1, true); orderBy(ordering, 2, true); Operator plan = sort_Tree( groupScan_Default(customerGroupTable), customerRowType, ordering, SortOption.PRESERVE_DUPLICATES ); Row[] expected = new RowsBuilder(AkType.LONG, AkType.VARCHAR, AkType.DECIMAL) .row(4L, "Aaa", "32.00") .row(2L, "Aaa", "75.25") .row(3L, "Bbb", "120.00") .row(1L, "Ccc", "100.00") .rows().toArray(new Row[4]); compareRows(expected, cursor(plan)); } @Test public void mixed() { Ordering ordering = API.ordering(); orderBy(ordering, 1, true); orderBy(ordering, 2, false); Operator plan = sort_Tree( groupScan_Default(customerGroupTable), customerRowType, ordering, SortOption.PRESERVE_DUPLICATES ); Row[] expected = new RowsBuilder(AkType.LONG, AkType.VARCHAR, AkType.DECIMAL) .row(2L, "Aaa", "75.25") .row(4L, "Aaa", "32.00") .row(3L, "Bbb", "120.00") .row(1L, "Ccc", "100.00") .rows().toArray(new Row[4]); compareRows(expected, cursor(plan)); } private Cursor cursor(Operator plan) { StoreAdapter adapter = new PersistitAdapter(schema, store(), treeService(), session(), configService()); QueryContext context = new SimpleQueryContext(adapter); return API.cursor(plan, context); } private void orderBy(Ordering ordering, int fieldPos, boolean ascending) { Expression fieldExpression = new FieldExpression(customerRowType, fieldPos); ordering.append(fieldExpression, ascending); } private Schema schema; private int customer; private GroupTable customerGroupTable; private UserTableRowType customerRowType; }
src/test/java/com/akiban/server/test/it/qp/Sort_MixedColumnTypesIT.java
adding a test which sorts with different column types.
src/test/java/com/akiban/server/test/it/qp/Sort_MixedColumnTypesIT.java
adding a test which sorts with different column types.
<ide><path>rc/test/java/com/akiban/server/test/it/qp/Sort_MixedColumnTypesIT.java <add>/** <add> * END USER LICENSE AGREEMENT (“EULA”) <add> * <add> * READ THIS AGREEMENT CAREFULLY (date: 9/13/2011): <add> * http://www.akiban.com/licensing/20110913 <add> * <add> * BY INSTALLING OR USING ALL OR ANY PORTION OF THE SOFTWARE, YOU ARE ACCEPTING <add> * ALL OF THE TERMS AND CONDITIONS OF THIS AGREEMENT. YOU AGREE THAT THIS <add> * AGREEMENT IS ENFORCEABLE LIKE ANY WRITTEN AGREEMENT SIGNED BY YOU. <add> * <add> * IF YOU HAVE PAID A LICENSE FEE FOR USE OF THE SOFTWARE AND DO NOT AGREE TO <add> * THESE TERMS, YOU MAY RETURN THE SOFTWARE FOR A FULL REFUND PROVIDED YOU (A) DO <add> * NOT USE THE SOFTWARE AND (B) RETURN THE SOFTWARE WITHIN THIRTY (30) DAYS OF <add> * YOUR INITIAL PURCHASE. <add> * <add> * IF YOU WISH TO USE THE SOFTWARE AS AN EMPLOYEE, CONTRACTOR, OR AGENT OF A <add> * CORPORATION, PARTNERSHIP OR SIMILAR ENTITY, THEN YOU MUST BE AUTHORIZED TO SIGN <add> * FOR AND BIND THE ENTITY IN ORDER TO ACCEPT THE TERMS OF THIS AGREEMENT. THE <add> * LICENSES GRANTED UNDER THIS AGREEMENT ARE EXPRESSLY CONDITIONED UPON ACCEPTANCE <add> * BY SUCH AUTHORIZED PERSONNEL. <add> * <add> * IF YOU HAVE ENTERED INTO A SEPARATE WRITTEN LICENSE AGREEMENT WITH AKIBAN FOR <add> * USE OF THE SOFTWARE, THE TERMS AND CONDITIONS OF SUCH OTHER AGREEMENT SHALL <add> * PREVAIL OVER ANY CONFLICTING TERMS OR CONDITIONS IN THIS AGREEMENT. <add> */ <add> <add>package com.akiban.server.test.it.qp; <add> <add>import com.akiban.ais.model.GroupTable; <add>import com.akiban.ais.model.UserTable; <add>import com.akiban.qp.operator.API; <add>import com.akiban.qp.operator.Cursor; <add>import com.akiban.qp.operator.Operator; <add>import com.akiban.qp.operator.QueryContext; <add>import com.akiban.qp.operator.RowsBuilder; <add>import com.akiban.qp.operator.SimpleQueryContext; <add>import com.akiban.qp.operator.StoreAdapter; <add>import com.akiban.qp.persistitadapter.PersistitAdapter; <add>import com.akiban.qp.row.Row; <add>import com.akiban.qp.rowtype.Schema; <add>import com.akiban.qp.rowtype.UserTableRowType; <add>import com.akiban.server.expression.Expression; <add>import com.akiban.server.expression.std.FieldExpression; <add>import com.akiban.server.test.it.ITBase; <add>import com.akiban.server.types.AkType; <add>import org.junit.Before; <add>import org.junit.Test; <add> <add> <add>import static com.akiban.qp.operator.API.*; <add> <add>public final class Sort_MixedColumnTypesIT extends ITBase { <add> @Before <add> public void createSchema() { <add> customer = createTable( <add> "schema", "customer", <add> "cid int not null primary key", <add> "name varchar(32)", <add> "importance decimal(5,2)" <add> ); <add> createIndex( <add> "schema", "customer", "importance_and_name", <add> "importance", "name" <add> ); <add> // These values have been picked for the following criteria: <add> // - neither 'name' nor 'importance' are consistently ordered relative to cid <add> // - when the rows are ordered by name, they are unordered by importance <add> // - when the rows are ordered by importance, they are unordered by name <add> writeRows( <add> createNewRow(customer, 4L, "Aaa", "32.00"), <add> createNewRow(customer, 2L, "Aaa", "75.25"), <add> createNewRow(customer, 1L, "Ccc", "100.00"), <add> createNewRow(customer, 3L, "Bbb", "120.00") <add> ); <add> <add> schema = new Schema(ddl().getAIS(session())); <add> UserTable cTable = getUserTable(customer); <add> customerRowType = schema.userTableRowType(cTable); <add> customerGroupTable = cTable.getGroup().getGroupTable(); <add> <add> } <add> <add> @Test <add> public void unidirectional() { <add> Ordering ordering = API.ordering(); <add> orderBy(ordering, 1, true); <add> orderBy(ordering, 2, true); <add> <add> Operator plan = sort_Tree( <add> groupScan_Default(customerGroupTable), <add> customerRowType, <add> ordering, <add> SortOption.PRESERVE_DUPLICATES <add> ); <add> Row[] expected = new RowsBuilder(AkType.LONG, AkType.VARCHAR, AkType.DECIMAL) <add> .row(4L, "Aaa", "32.00") <add> .row(2L, "Aaa", "75.25") <add> .row(3L, "Bbb", "120.00") <add> .row(1L, "Ccc", "100.00") <add> .rows().toArray(new Row[4]); <add> compareRows(expected, cursor(plan)); <add> } <add> <add> @Test <add> public void mixed() { <add> Ordering ordering = API.ordering(); <add> orderBy(ordering, 1, true); <add> orderBy(ordering, 2, false); <add> <add> Operator plan = sort_Tree( <add> groupScan_Default(customerGroupTable), <add> customerRowType, <add> ordering, <add> SortOption.PRESERVE_DUPLICATES <add> ); <add> Row[] expected = new RowsBuilder(AkType.LONG, AkType.VARCHAR, AkType.DECIMAL) <add> .row(2L, "Aaa", "75.25") <add> .row(4L, "Aaa", "32.00") <add> .row(3L, "Bbb", "120.00") <add> .row(1L, "Ccc", "100.00") <add> .rows().toArray(new Row[4]); <add> compareRows(expected, cursor(plan)); <add> } <add> <add> private Cursor cursor(Operator plan) { <add> StoreAdapter adapter = new PersistitAdapter(schema, store(), treeService(), session(), configService()); <add> QueryContext context = new SimpleQueryContext(adapter); <add> return API.cursor(plan, context); <add> } <add> <add> private void orderBy(Ordering ordering, int fieldPos, boolean ascending) { <add> Expression fieldExpression = new FieldExpression(customerRowType, fieldPos); <add> ordering.append(fieldExpression, ascending); <add> } <add> <add> private Schema schema; <add> private int customer; <add> private GroupTable customerGroupTable; <add> private UserTableRowType customerRowType; <add>}
Java
epl-1.0
5e8d7d42d87de4eebf4e4104dd76e6922d751627
0
sunix/che,ollie314/che,Patricol/che,TypeFox/che,TypeFox/che,gazarenkov/che-sketch,gazarenkov/che-sketch,jonahkichwacoders/che,stour/che,cemalkilic/che,sudaraka94/che,kaloyan-raev/che,akervern/che,stour/che,sleshchenko/che,cemalkilic/che,kaloyan-raev/che,snjeza/che,slemeur/che,cdietrich/che,lehmanju/che,davidfestal/che,bartlomiej-laczkowski/che,kaloyan-raev/che,codenvy/che,kaloyan-raev/che,lehmanju/che,Mirage20/che,TypeFox/che,davidfestal/che,codenvy/che,stour/che,TypeFox/che,davidfestal/che,slemeur/che,Patricol/che,cdietrich/che,sudaraka94/che,evidolob/che,Patricol/che,jonahkichwacoders/che,Mirage20/che,sleshchenko/che,sleshchenko/che,sudaraka94/che,cemalkilic/che,lehmanju/che,bartlomiej-laczkowski/che,bartlomiej-laczkowski/che,Mirage20/che,lehmanju/che,Mirage20/che,akervern/che,codenvy/che,Patricol/che,evidolob/che,davidfestal/che,Mirage20/che,bartlomiej-laczkowski/che,sudaraka94/che,Patricol/che,sleshchenko/che,sleshchenko/che,ollie314/che,gazarenkov/che-sketch,snjeza/che,bartlomiej-laczkowski/che,bartlomiej-laczkowski/che,snjeza/che,bartlomiej-laczkowski/che,bartlomiej-laczkowski/che,bartlomiej-laczkowski/che,Patricol/che,snjeza/che,sleshchenko/che,sunix/che,cemalkilic/che,jonahkichwacoders/che,jonahkichwacoders/che,akervern/che,gazarenkov/che-sketch,evidolob/che,cemalkilic/che,TypeFox/che,davidfestal/che,kaloyan-raev/che,jonahkichwacoders/che,stour/che,davidfestal/che,sunix/che,cdietrich/che,jonahkichwacoders/che,gazarenkov/che-sketch,ollie314/che,Patricol/che,sleshchenko/che,snjeza/che,sunix/che,Mirage20/che,akervern/che,snjeza/che,Patricol/che,cemalkilic/che,lehmanju/che,sudaraka94/che,snjeza/che,cdietrich/che,akervern/che,TypeFox/che,lehmanju/che,cdietrich/che,lehmanju/che,sleshchenko/che,sleshchenko/che,ollie314/che,gazarenkov/che-sketch,sunix/che,sunix/che,kaloyan-raev/che,evidolob/che,davidfestal/che,sleshchenko/che,cemalkilic/che,gazarenkov/che-sketch,cdietrich/che,sunix/che,ollie314/che,evidolob/che,cdietrich/che,TypeFox/che,sunix/che,gazarenkov/che-sketch,sudaraka94/che,jonahkichwacoders/che,Patricol/che,TypeFox/che,codenvy/che,TypeFox/che,slemeur/che,ollie314/che,gazarenkov/che-sketch,sunix/che,cemalkilic/che,jonahkichwacoders/che,akervern/che,cemalkilic/che,snjeza/che,akervern/che,sudaraka94/che,sudaraka94/che,jonahkichwacoders/che,sudaraka94/che,snjeza/che,sudaraka94/che,akervern/che,davidfestal/che,davidfestal/che,cdietrich/che,jonahkichwacoders/che,cdietrich/che,slemeur/che,davidfestal/che,akervern/che,TypeFox/che,slemeur/che,lehmanju/che,Patricol/che,lehmanju/che
/******************************************************************************* * Copyright (c) 2012-2016 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.commons.lang; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.HttpMethod; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.nio.channels.FileChannel; import java.nio.file.FileSystems; import java.nio.file.FileVisitOption; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.security.DigestInputStream; import java.security.MessageDigest; import java.util.ArrayList; import java.util.EnumSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; import static java.nio.file.FileVisitResult.CONTINUE; import static java.nio.file.FileVisitResult.TERMINATE; public class IoUtil { private static final Logger LOG = LoggerFactory.getLogger(IoUtil.class); private IoUtil() { } /** Represents filter what select any file */ public static final FilenameFilter ANY_FILTER = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return true; } }; /** Represent filter, that excludes .git entries. */ public static final FilenameFilter GIT_FILTER = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return !(".git".equals(name)); } }; /** * Reads bytes from input stream and builds a string from them. * * @param inputStream * source stream * @return string * @throws java.io.IOException * if any i/o error occur */ public static String readStream(InputStream inputStream) throws IOException { if (inputStream == null) { return null; } ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] buf = new byte[8192]; int r; while ((r = inputStream.read(buf)) != -1) { bout.write(buf, 0, r); } return bout.toString("UTF-8"); } /** * Reads bytes from input stream and builds a string from them. InputStream closed after consumption. * * @param inputStream * source stream * @return string * @throws java.io.IOException * if any i/o error occur */ public static String readAndCloseQuietly(InputStream inputStream) throws IOException { try { return readStream(inputStream); } catch (IOException e) { LOG.error(e.getLocalizedMessage(), e); throw e; } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { LOG.error(e.getLocalizedMessage(), e); } } } } /** * Looking for resource by given path. If no file exist by this path, method will try to find it in context. * * @param resource * - path to resource * @return - InputStream of resource * @throws IOException */ public static InputStream getResource(String resource) throws IOException { File resourceFile = new File(resource); if (resourceFile.exists() && !resourceFile.isFile()) { throw new IOException(String.format("%s is not a file. ", resourceFile.getAbsolutePath())); } InputStream is = resourceFile.exists() ? new FileInputStream(resourceFile) : IoUtil.class.getResourceAsStream(resource); if (is == null) { throw new IOException(String.format("Not found resource: %s", resource)); } return is; } /** Remove directory and all its sub-resources with specified path */ public static boolean removeDirectory(String pathToDir) { return deleteRecursive(new File(pathToDir)); } /** * Remove specified file or directory. * * @param fileOrDirectory * the file or directory to cancel * @return <code>true</code> if specified File was deleted and <code>false</code> otherwise */ public static boolean deleteRecursive(File fileOrDirectory) { if (fileOrDirectory.isDirectory()) { File[] list = fileOrDirectory.listFiles(); if (list == null) { return false; } for (File f : list) { if (!deleteRecursive(f)) { return false; } } } if (!fileOrDirectory.delete()) { if (fileOrDirectory.exists()) { return false; } } return true; } /** * Remove specified file or directory. * * @param fileOrDirectory * the file or directory to cancel * @param followLinks * are symbolic links followed or not? * @return <code>true</code> if specified File was deleted and <code>false</code> otherwise */ public static boolean deleteRecursive(File fileOrDirectory, boolean followLinks) { if (fileOrDirectory.isDirectory()) { // If fileOrDirectory represents a symbolic link to a folder, // do not read a target folder content. Just remove this symbolic link. if (!followLinks && java.nio.file.Files.isSymbolicLink(fileOrDirectory.toPath())) { return !fileOrDirectory.exists() || fileOrDirectory.delete(); } File[] list = fileOrDirectory.listFiles(); if (list == null) { return false; } for (File f : list) { if (!deleteRecursive(f, followLinks)) { return false; } } } if (!fileOrDirectory.delete()) { if (fileOrDirectory.exists()) { return false; } } return true; } /** * Download file. * * @param parent * parent directory, may be <code>null</code> then use 'java.io.tmpdir' * @param prefix * prefix of temporary file name, may not be <code>null</code> and must be at least three characters long * @param suffix * suffix of temporary file name, may be <code>null</code> * @param url * URL for download * @return downloaded file * @throws java.io.IOException * if any i/o error occurs */ public static File downloadFile(File parent, String prefix, String suffix, URL url) throws IOException { File file = File.createTempFile(prefix, suffix, parent); URLConnection conn = null; final String protocol = url.getProtocol().toLowerCase(Locale.ENGLISH); try { conn = url.openConnection(); if ("http".equals(protocol) || "https".equals(protocol)) { HttpURLConnection http = (HttpURLConnection)conn; http.setInstanceFollowRedirects(false); http.setRequestMethod(HttpMethod.GET); } try (InputStream input = conn.getInputStream(); FileOutputStream fOutput = new FileOutputStream(file)) { byte[] b = new byte[8192]; int r; while ((r = input.read(b)) != -1) { fOutput.write(b, 0, r); } } } finally { if (conn != null && ("http".equals(protocol) || "https".equals(protocol))) { ((HttpURLConnection)conn).disconnect(); } } return file; } /** * Download file with redirection if got status 301, 302, 303. * Will useful in case redirection http -> https * * @param parent * parent directory, may be <code>null</code> then use 'java.io.tmpdir' * @param prefix * prefix of temporary file name, may not be <code>null</code> and must be at least three characters long * @param suffix * suffix of temporary file name, may be <code>null</code> * @param url * URL for download * @return downloaded file * @throws java.io.IOException * if any i/o error occurs */ public static File downloadFileWithRedirect(File parent, String prefix, String suffix, URL url) throws IOException { File file = File.createTempFile(prefix, suffix, parent); URLConnection conn = null; final String protocol = url.getProtocol().toLowerCase(Locale.ENGLISH); try { conn = url.openConnection(); boolean redirect = false; if ("http".equals(protocol) || "https".equals(protocol)) { HttpURLConnection http = (HttpURLConnection)conn; http.setRequestMethod(HttpMethod.GET); int status = http.getResponseCode(); if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) { redirect = true; } if (redirect) { String newUrl = conn.getHeaderField("Location"); // open the new connection again http.disconnect(); conn = new URL(newUrl).openConnection(); http = (HttpURLConnection)conn; http.setRequestMethod(HttpMethod.GET); } } try (InputStream input = conn.getInputStream(); FileOutputStream fOutput = new FileOutputStream(file)) { byte[] b = new byte[8192]; int r; while ((r = input.read(b)) != -1) { fOutput.write(b, 0, r); } } } finally { if (conn != null && ("http".equals(protocol) || "https".equals(protocol))) { ((HttpURLConnection)conn).disconnect(); } } return file; } /** * Copy file or directory to the specified destination. Existed files in destination directory will be overwritten. * * @param source * copy source * @param target * copy destination * @param filter * copy filter * @throws java.io.IOException * if any i/o error occurs */ public static void copy(File source, File target, FilenameFilter filter) throws IOException { copy(source, target, filter, false, true); } /** * Copy file or directory to the specified destination. Existed files in destination directory will be overwritten. * <p/> * This method use java.nio for coping files. * * @param source * copy source * @param target * copy destination * @param filter * copy filter * @throws java.io.IOException * if any i/o error occurs */ public static void nioCopy(File source, File target, FilenameFilter filter) throws IOException { copy(source, target, filter, true, true); } /** * Copy file or directory to the specified destination. * * @param source * copy source * @param target * copy destination * @param filter * copy filter * @param replaceIfExists * if <code>true</code> existed files in destination directory will be overwritten * @throws java.io.IOException * if any i/o error occurs */ public static void copy(File source, File target, FilenameFilter filter, boolean replaceIfExists) throws IOException { copy(source, target, filter, false, replaceIfExists); } /** * Copy file or directory to the specified destination. * <p/> * This method use java.nio for coping files. * * @param source * copy source * @param target * copy destination * @param filter * copy filter * @param replaceIfExists * if <code>true</code> existed files in destination directory will be overwritten * @throws java.io.IOException * if any i/o error occurs */ public static void nioCopy(File source, File target, FilenameFilter filter, boolean replaceIfExists) throws IOException { copy(source, target, filter, true, replaceIfExists); } private static void copy(File source, File target, FilenameFilter filter, boolean nio, boolean replaceIfExists) throws IOException { if (source.isDirectory()) { if (!(target.exists() || target.mkdirs())) { throw new IOException(String.format("Unable create directory '%s'. ", target.getAbsolutePath())); } if (filter == null) { filter = ANY_FILTER; } String sourceRoot = source.getAbsolutePath(); LinkedList<File> q = new LinkedList<>(); q.add(source); while (!q.isEmpty()) { File current = q.pop(); File[] list = current.listFiles(); if (list != null) { for (File f : list) { if (!filter.accept(current, f.getName())) { continue; } File newFile = new File(target, f.getAbsolutePath().substring(sourceRoot.length() + 1)); if (f.isDirectory()) { if (!(newFile.exists() || newFile.mkdirs())) { throw new IOException(String.format("Unable create directory '%s'. ", newFile.getAbsolutePath())); } if (!f.equals(target)) { q.push(f); } } else { if (nio) { nioCopyFile(f, newFile, replaceIfExists); } else { copyFile(f, newFile, replaceIfExists); } } } } } } else { File parent = target.getParentFile(); if (!(parent.exists() || parent.mkdirs())) { throw new IOException(String.format("Unable create directory '%s'. ", parent.getAbsolutePath())); } if (nio) { nioCopyFile(source, target, replaceIfExists); } else { copyFile(source, target, replaceIfExists); } } } private static void copyFile(File source, File target, boolean replaceIfExists) throws IOException { if (!target.createNewFile()) { if (target.exists() && !replaceIfExists) { throw new IOException(String.format("File '%s' already exists. ", target.getAbsolutePath())); } } byte[] b = new byte[8192]; try (FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(target)) { int r; while ((r = in.read(b)) != -1) { out.write(b, 0, r); } } } private static void nioCopyFile(File source, File target, boolean replaceIfExists) throws IOException { if (!target.createNewFile()) // atomic { if (target.exists() && !replaceIfExists) { throw new IOException(String.format("File '%s' already exists. ", target.getAbsolutePath())); } } try ( FileInputStream sourceStream = new FileInputStream(source); FileOutputStream targetStream = new FileOutputStream(target); FileChannel sourceChannel = sourceStream.getChannel(); FileChannel targetChannel = targetStream.getChannel() ) { final long size = sourceChannel.size(); long transferred = 0L; while (transferred < size) { transferred += targetChannel.transferFrom(sourceChannel, transferred, (size - transferred)); } } } public static List<File> list(File dir, FilenameFilter filter) { if (!dir.isDirectory()) { throw new IllegalArgumentException("Not a directory. "); } if (filter == null) { filter = ANY_FILTER; } List<File> files = new ArrayList<>(); LinkedList<File> q = new LinkedList<>(); q.add(dir); while (!q.isEmpty()) { File current = q.pop(); File[] list = current.listFiles(); if (list != null) { for (File f : list) { if (!filter.accept(current, f.getName())) { continue; } if (f.isDirectory()) { q.push(f); } else { files.add(f); } } } } return files; } public static String countFileHash(File file, MessageDigest digest) throws IOException { byte[] b = new byte[8192]; try (DigestInputStream dis = new DigestInputStream(new FileInputStream(file), digest)) { while (dis.read(b) != -1) ; return toHex(digest.digest()); } } private static final char[] hex = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; public static String toHex(byte[] hash) { StringBuilder b = new StringBuilder(); for (int i = 0; i < hash.length; i++) { b.append(hex[(hash[i] >> 4) & 0x0f]); b.append(hex[hash[i] & 0x0f]); } return b.toString(); } /** * Detects and returns {@code Path} to file by name pattern. * * @param pattern * file name pattern * @param folder * path to folder that contains project sources * @return pom.xml path * @throws java.io.IOException * if an I/O error is thrown while finding pom.xml * @throws IllegalArgumentException * if pom.xml not found */ public static File findFile(String pattern, File folder) throws IOException { Finder finder = new Finder(pattern); Files.walkFileTree(folder.toPath(), EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, finder); if (finder.getFirstMatchedFile() == null) { throw new IllegalArgumentException("File not found."); } return finder.getFirstMatchedFile().toFile(); } /** A {@code FileVisitor} that finds first file that match the specified pattern. */ private static class Finder extends SimpleFileVisitor<Path> { private final PathMatcher matcher; private Path firstMatchedFile; Finder(String pattern) { matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern); } /** {@inheritDoc} */ @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Path fileName = file.getFileName(); if (fileName != null && matcher.matches(fileName)) { firstMatchedFile = file; return TERMINATE; } return CONTINUE; } /** Returns the first matched {@link java.nio.file.Path}. */ Path getFirstMatchedFile() { return firstMatchedFile; } } }
core/commons/che-core-commons-lang/src/main/java/org/eclipse/che/commons/lang/IoUtil.java
/******************************************************************************* * Copyright (c) 2012-2016 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.commons.lang; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.HttpMethod; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.nio.channels.FileChannel; import java.nio.file.FileSystems; import java.nio.file.FileVisitOption; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.security.DigestInputStream; import java.security.MessageDigest; import java.util.ArrayList; import java.util.EnumSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; import static java.nio.file.FileVisitResult.CONTINUE; import static java.nio.file.FileVisitResult.TERMINATE; public class IoUtil { private static final Logger LOG = LoggerFactory.getLogger(IoUtil.class); private IoUtil() { } /** Represents filter what select any file */ public static final FilenameFilter ANY_FILTER = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return true; } }; /** Represent filter, that excludes .git entries. */ public static final FilenameFilter GIT_FILTER = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return !(".git".equals(name)); } }; /** * Reads bytes from input stream and builds a string from them. * * @param inputStream * source stream * @return string * @throws java.io.IOException * if any i/o error occur */ public static String readStream(InputStream inputStream) throws IOException { if (inputStream == null) { return null; } ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] buf = new byte[8192]; int r; while ((r = inputStream.read(buf)) != -1) { bout.write(buf, 0, r); } return bout.toString("UTF-8"); } /** * Reads bytes from input stream and builds a string from them. InputStream closed after consumption. * * @param inputStream * source stream * @return string * @throws java.io.IOException * if any i/o error occur */ public static String readAndCloseQuietly(InputStream inputStream) throws IOException { try { return readStream(inputStream); } catch (IOException e) { LOG.error(e.getLocalizedMessage(), e); throw e; } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { LOG.error(e.getLocalizedMessage(), e); } } } } /** * Looking for resource by given path. If no file exist by this path, method will try to find it in context. * * @param resource * - path to resource * @return - InputStream of resource * @throws IOException */ public static InputStream getResource(String resource) throws IOException { File resourceFile = new File(resource); if (resourceFile.exists() && !resourceFile.isFile()) { throw new IOException(String.format("%s is not a file. ", resourceFile.getAbsolutePath())); } InputStream is = resourceFile.exists() ? new FileInputStream(resourceFile) : IoUtil.class.getResourceAsStream(resource); if (is == null) { throw new IOException(String.format("Not found resource: %s", resource)); } return is; } /** Remove directory and all its sub-resources with specified path */ public static boolean removeDirectory(String pathToDir) { return deleteRecursive(new File(pathToDir)); } /** * Remove specified file or directory. * * @param fileOrDirectory * the file or directory to cancel * @return <code>true</code> if specified File was deleted and <code>false</code> otherwise */ public static boolean deleteRecursive(File fileOrDirectory) { if (fileOrDirectory.isDirectory()) { File[] list = fileOrDirectory.listFiles(); if (list == null) { return false; } for (File f : list) { if (!deleteRecursive(f)) { return false; } } } if (!fileOrDirectory.delete()) { if (fileOrDirectory.exists()) { return false; } } return true; } /** * Remove specified file or directory. * * @param fileOrDirectory * the file or directory to cancel * @param followLinks * are symbolic links followed or not? * @return <code>true</code> if specified File was deleted and <code>false</code> otherwise */ public static boolean deleteRecursive(File fileOrDirectory, boolean followLinks) { if (fileOrDirectory.isDirectory()) { // If fileOrDirectory represents a symbolic link to a folder, // do not read a target folder content. Just remove this symbolic link. if (!followLinks && java.nio.file.Files.isSymbolicLink(fileOrDirectory.toPath())) { return !fileOrDirectory.exists() || fileOrDirectory.delete(); } File[] list = fileOrDirectory.listFiles(); if (list == null) { return false; } for (File f : list) { if (!deleteRecursive(f, followLinks)) { return false; } } } if (!fileOrDirectory.delete()) { if (fileOrDirectory.exists()) { return false; } } return true; } /** * Download file. * * @param parent * parent directory, may be <code>null</code> then use 'java.io.tmpdir' * @param prefix * prefix of temporary file name, may not be <code>null</code> and must be at least three characters long * @param suffix * suffix of temporary file name, may be <code>null</code> * @param url * URL for download * @return downloaded file * @throws java.io.IOException * if any i/o error occurs */ public static File downloadFile(File parent, String prefix, String suffix, URL url) throws IOException { File file = File.createTempFile(prefix, suffix, parent); URLConnection conn = null; final String protocol = url.getProtocol().toLowerCase(Locale.ENGLISH); try { conn = url.openConnection(); if ("http".equals(protocol) || "https".equals(protocol)) { HttpURLConnection http = (HttpURLConnection)conn; http.setInstanceFollowRedirects(false); http.setRequestMethod(HttpMethod.GET); } try (InputStream input = conn.getInputStream(); FileOutputStream fOutput = new FileOutputStream(file)) { byte[] b = new byte[8192]; int r; while ((r = input.read(b)) != -1) { fOutput.write(b, 0, r); } } } finally { if (conn != null && ("http".equals(protocol) || "https".equals(protocol))) { ((HttpURLConnection)conn).disconnect(); } } return file; } /** * Download file with redirection if got status 301, 302, 303. * Will useful in case redirection http -> https * * @param parent * parent directory, may be <code>null</code> then use 'java.io.tmpdir' * @param prefix * prefix of temporary file name, may not be <code>null</code> and must be at least three characters long * @param suffix * suffix of temporary file name, may be <code>null</code> * @param url * URL for download * @return downloaded file * @throws java.io.IOException * if any i/o error occurs */ public static File downloadFileWithRedirect(File parent, String prefix, String suffix, URL url) throws IOException { File file = File.createTempFile(prefix, suffix, parent); URLConnection conn = null; final String protocol = url.getProtocol().toLowerCase(Locale.ENGLISH); try { conn = url.openConnection(); boolean redirect = false; if ("http".equals(protocol) || "https".equals(protocol)) { HttpURLConnection http = (HttpURLConnection)conn; http.setRequestMethod(HttpMethod.GET); int status = http.getResponseCode(); if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) { redirect = true; } if (redirect) { String newUrl = conn.getHeaderField("Location"); // open the new connection again http = (HttpURLConnection)new URL(newUrl).openConnection(); http.setRequestMethod(HttpMethod.GET); } } try (InputStream input = conn.getInputStream(); FileOutputStream fOutput = new FileOutputStream(file)) { byte[] b = new byte[8192]; int r; while ((r = input.read(b)) != -1) { fOutput.write(b, 0, r); } } } finally { if (conn != null && ("http".equals(protocol) || "https".equals(protocol))) { ((HttpURLConnection)conn).disconnect(); } } return file; } /** * Copy file or directory to the specified destination. Existed files in destination directory will be overwritten. * * @param source * copy source * @param target * copy destination * @param filter * copy filter * @throws java.io.IOException * if any i/o error occurs */ public static void copy(File source, File target, FilenameFilter filter) throws IOException { copy(source, target, filter, false, true); } /** * Copy file or directory to the specified destination. Existed files in destination directory will be overwritten. * <p/> * This method use java.nio for coping files. * * @param source * copy source * @param target * copy destination * @param filter * copy filter * @throws java.io.IOException * if any i/o error occurs */ public static void nioCopy(File source, File target, FilenameFilter filter) throws IOException { copy(source, target, filter, true, true); } /** * Copy file or directory to the specified destination. * * @param source * copy source * @param target * copy destination * @param filter * copy filter * @param replaceIfExists * if <code>true</code> existed files in destination directory will be overwritten * @throws java.io.IOException * if any i/o error occurs */ public static void copy(File source, File target, FilenameFilter filter, boolean replaceIfExists) throws IOException { copy(source, target, filter, false, replaceIfExists); } /** * Copy file or directory to the specified destination. * <p/> * This method use java.nio for coping files. * * @param source * copy source * @param target * copy destination * @param filter * copy filter * @param replaceIfExists * if <code>true</code> existed files in destination directory will be overwritten * @throws java.io.IOException * if any i/o error occurs */ public static void nioCopy(File source, File target, FilenameFilter filter, boolean replaceIfExists) throws IOException { copy(source, target, filter, true, replaceIfExists); } private static void copy(File source, File target, FilenameFilter filter, boolean nio, boolean replaceIfExists) throws IOException { if (source.isDirectory()) { if (!(target.exists() || target.mkdirs())) { throw new IOException(String.format("Unable create directory '%s'. ", target.getAbsolutePath())); } if (filter == null) { filter = ANY_FILTER; } String sourceRoot = source.getAbsolutePath(); LinkedList<File> q = new LinkedList<>(); q.add(source); while (!q.isEmpty()) { File current = q.pop(); File[] list = current.listFiles(); if (list != null) { for (File f : list) { if (!filter.accept(current, f.getName())) { continue; } File newFile = new File(target, f.getAbsolutePath().substring(sourceRoot.length() + 1)); if (f.isDirectory()) { if (!(newFile.exists() || newFile.mkdirs())) { throw new IOException(String.format("Unable create directory '%s'. ", newFile.getAbsolutePath())); } if (!f.equals(target)) { q.push(f); } } else { if (nio) { nioCopyFile(f, newFile, replaceIfExists); } else { copyFile(f, newFile, replaceIfExists); } } } } } } else { File parent = target.getParentFile(); if (!(parent.exists() || parent.mkdirs())) { throw new IOException(String.format("Unable create directory '%s'. ", parent.getAbsolutePath())); } if (nio) { nioCopyFile(source, target, replaceIfExists); } else { copyFile(source, target, replaceIfExists); } } } private static void copyFile(File source, File target, boolean replaceIfExists) throws IOException { if (!target.createNewFile()) { if (target.exists() && !replaceIfExists) { throw new IOException(String.format("File '%s' already exists. ", target.getAbsolutePath())); } } byte[] b = new byte[8192]; try (FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(target)) { int r; while ((r = in.read(b)) != -1) { out.write(b, 0, r); } } } private static void nioCopyFile(File source, File target, boolean replaceIfExists) throws IOException { if (!target.createNewFile()) // atomic { if (target.exists() && !replaceIfExists) { throw new IOException(String.format("File '%s' already exists. ", target.getAbsolutePath())); } } try ( FileInputStream sourceStream = new FileInputStream(source); FileOutputStream targetStream = new FileOutputStream(target); FileChannel sourceChannel = sourceStream.getChannel(); FileChannel targetChannel = targetStream.getChannel() ) { final long size = sourceChannel.size(); long transferred = 0L; while (transferred < size) { transferred += targetChannel.transferFrom(sourceChannel, transferred, (size - transferred)); } } } public static List<File> list(File dir, FilenameFilter filter) { if (!dir.isDirectory()) { throw new IllegalArgumentException("Not a directory. "); } if (filter == null) { filter = ANY_FILTER; } List<File> files = new ArrayList<>(); LinkedList<File> q = new LinkedList<>(); q.add(dir); while (!q.isEmpty()) { File current = q.pop(); File[] list = current.listFiles(); if (list != null) { for (File f : list) { if (!filter.accept(current, f.getName())) { continue; } if (f.isDirectory()) { q.push(f); } else { files.add(f); } } } } return files; } public static String countFileHash(File file, MessageDigest digest) throws IOException { byte[] b = new byte[8192]; try (DigestInputStream dis = new DigestInputStream(new FileInputStream(file), digest)) { while (dis.read(b) != -1) ; return toHex(digest.digest()); } } private static final char[] hex = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; public static String toHex(byte[] hash) { StringBuilder b = new StringBuilder(); for (int i = 0; i < hash.length; i++) { b.append(hex[(hash[i] >> 4) & 0x0f]); b.append(hex[hash[i] & 0x0f]); } return b.toString(); } /** * Detects and returns {@code Path} to file by name pattern. * * @param pattern * file name pattern * @param folder * path to folder that contains project sources * @return pom.xml path * @throws java.io.IOException * if an I/O error is thrown while finding pom.xml * @throws IllegalArgumentException * if pom.xml not found */ public static File findFile(String pattern, File folder) throws IOException { Finder finder = new Finder(pattern); Files.walkFileTree(folder.toPath(), EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, finder); if (finder.getFirstMatchedFile() == null) { throw new IllegalArgumentException("File not found."); } return finder.getFirstMatchedFile().toFile(); } /** A {@code FileVisitor} that finds first file that match the specified pattern. */ private static class Finder extends SimpleFileVisitor<Path> { private final PathMatcher matcher; private Path firstMatchedFile; Finder(String pattern) { matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern); } /** {@inheritDoc} */ @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Path fileName = file.getFileName(); if (fileName != null && matcher.matches(fileName)) { firstMatchedFile = file; return TERMINATE; } return CONTINUE; } /** Returns the first matched {@link java.nio.file.Path}. */ Path getFirstMatchedFile() { return firstMatchedFile; } } }
Closing prevous connection if redirect (#1314) CODENVY-538:Closing previous connection if redirect Signed-off-by: Vitaly Parfonov <[email protected]>
core/commons/che-core-commons-lang/src/main/java/org/eclipse/che/commons/lang/IoUtil.java
Closing prevous connection if redirect (#1314)
<ide><path>ore/commons/che-core-commons-lang/src/main/java/org/eclipse/che/commons/lang/IoUtil.java <ide> if (redirect) { <ide> String newUrl = conn.getHeaderField("Location"); <ide> // open the new connection again <del> http = (HttpURLConnection)new URL(newUrl).openConnection(); <add> http.disconnect(); <add> conn = new URL(newUrl).openConnection(); <add> http = (HttpURLConnection)conn; <ide> http.setRequestMethod(HttpMethod.GET); <ide> } <ide> }
Java
mit
16f141afd1a3ff5a566ca49011e95a7e83214264
0
plume-lib/plume-util
// If you edit this file, you must also edit its tests. // For tests of this and the entire plume package, see class TestPlume. package org.plumelib.util; import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.file.StandardOpenOption.APPEND; import static java.nio.file.StandardOpenOption.CREATE; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.Serializable; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Properties; import java.util.Random; import java.util.Set; import java.util.StringTokenizer; import java.util.concurrent.atomic.AtomicBoolean; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /*>>> import org.checkerframework.checker.index.qual.*; import org.checkerframework.checker.lock.qual.*; import org.checkerframework.checker.nullness.qual.*; import org.checkerframework.checker.regex.qual.*; import org.checkerframework.checker.signature.qual.*; import org.checkerframework.common.value.qual.*; import org.checkerframework.dataflow.qual.*; */ /** Utility functions that do not belong elsewhere in the plume package. */ public final class UtilPlume { /** This class is a collection of methods; it does not represent anything. */ private UtilPlume() { throw new Error("do not instantiate"); } private static final String lineSep = System.getProperty("line.separator"); /////////////////////////////////////////////////////////////////////////// /// Array /// // For arrays, see ArraysPlume.java. /////////////////////////////////////////////////////////////////////////// /// BitSet /// /** * Returns true if the cardinality of the intersection of the two BitSets is at least the given * value. * * @param a the first BitSet to intersect * @param b the second BitSet to intersect * @param i the cardinality bound * @return true iff size(a intersect b) &ge; i */ @SuppressWarnings({"purity", "lock"}) // side effect to local state (BitSet) /*@Pure*/ public static boolean intersectionCardinalityAtLeast(BitSet a, BitSet b, /*@NonNegative*/ int i) { // Here are three implementation strategies to determine the // cardinality of the intersection: // 1. a.clone().and(b).cardinality() // 2. do the above, but copy only a subset of the bits initially -- enough // that it should exceed the given number -- and if that fails, do the // whole thing. Unfortunately, bits.get(int, int) isn't optimized // for the case where the indices line up, so I'm not sure at what // point this approach begins to dominate #1. // 3. iterate through both sets with nextSetBit() int size = Math.min(a.length(), b.length()); if (size > 10 * i) { // The size is more than 10 times the limit. So first try processing // just a subset of the bits (4 times the limit). BitSet intersection = a.get(0, 4 * i); intersection.and(b); if (intersection.cardinality() >= i) { return true; } } return (intersectionCardinality(a, b) >= i); } /** * Returns true if the cardinality of the intersection of the three BitSets is at least the given * value. * * @param a the first BitSet to intersect * @param b the second BitSet to intersect * @param c the third BitSet to intersect * @param i the cardinality bound * @return true iff size(a intersect b intersect c) &ge; i */ @SuppressWarnings({"purity", "lock"}) // side effect to local state (BitSet) /*@Pure*/ public static boolean intersectionCardinalityAtLeast( BitSet a, BitSet b, BitSet c, /*@NonNegative*/ int i) { // See comments in intersectionCardinalityAtLeast(BitSet, BitSet, int). // This is a copy of that. int size = Math.min(a.length(), b.length()); size = Math.min(size, c.length()); if (size > 10 * i) { // The size is more than 10 times the limit. So first try processing // just a subset of the bits (4 times the limit). BitSet intersection = a.get(0, 4 * i); intersection.and(b); intersection.and(c); if (intersection.cardinality() >= i) { return true; } } return (intersectionCardinality(a, b, c) >= i); } /** * Returns the cardinality of the intersection of the two BitSets. * * @param a the first BitSet to intersect * @param b the second BitSet to intersect * @return size(a intersect b) */ @SuppressWarnings({"purity", "lock"}) // side effect to local state (BitSet) /*@Pure*/ public static int intersectionCardinality(BitSet a, BitSet b) { BitSet intersection = (BitSet) a.clone(); intersection.and(b); return intersection.cardinality(); } /** * Returns the cardinality of the intersection of the three BitSets. * * @param a the first BitSet to intersect * @param b the second BitSet to intersect * @param c the third BitSet to intersect * @return size(a intersect b intersect c) */ @SuppressWarnings({"purity", "lock"}) // side effect to local state (BitSet) /*@Pure*/ public static int intersectionCardinality(BitSet a, BitSet b, BitSet c) { BitSet intersection = (BitSet) a.clone(); intersection.and(b); intersection.and(c); return intersection.cardinality(); } /////////////////////////////////////////////////////////////////////////// /// BufferedFileReader /// // Convenience methods for creating InputStreams, Readers, BufferedReaders, and LineNumberReaders. /** * Returns an InputStream for the file, accounting for the possibility that the file is * compressed. (A file whose name ends with ".gz" is treated as compressed.) * * <p>Warning: The "gzip" program writes and reads files containing concatenated gzip files. As of * Java 1.4, Java reads just the first one: it silently discards all characters (including gzipped * files) after the first gzipped file. * * @param file the possibly-compressed file to read * @return an InputStream for file * @throws IOException if there is trouble reading the file */ public static InputStream fileInputStream(File file) throws IOException { InputStream in; if (file.getName().endsWith(".gz")) { try { in = new GZIPInputStream(new FileInputStream(file)); } catch (IOException e) { throw new IOException("Problem while reading " + file, e); } } else { in = new FileInputStream(file); } return in; } /** * Returns a Reader for the file, accounting for the possibility that the file is compressed. (A * file whose name ends with ".gz" is treated as compressed.) * * <p>Warning: The "gzip" program writes and reads files containing concatenated gzip files. As of * Java 1.4, Java reads just the first one: it silently discards all characters (including gzipped * files) after the first gzipped file. * * @param filename the possibly-compressed file to read * @return an InputStream for filename * @throws IOException if there is trouble reading the file * @throws FileNotFoundException if the file is not found */ public static InputStreamReader fileReader(String filename) throws FileNotFoundException, IOException { // return fileReader(filename, "ISO-8859-1"); return fileReader(new File(filename), null); } /** * Returns a Reader for the file, accounting for the possibility that the file is compressed. (A * file whose name ends with ".gz" is treated as compressed.) * * <p>Warning: The "gzip" program writes and reads files containing concatenated gzip files. As of * Java 1.4, Java reads just the first one: it silently discards all characters (including gzipped * files) after the first gzipped file. * * @param file the possibly-compressed file to read * @return an InputStreamReader for file * @throws FileNotFoundException if the file cannot be found * @throws IOException if there is trouble reading the file */ public static InputStreamReader fileReader(File file) throws FileNotFoundException, IOException { return fileReader(file, null); } /** * Returns a Reader for the file, accounting for the possibility that the file is compressed. (A * file whose name ends with ".gz" is treated as compressed.) * * <p>Warning: The "gzip" program writes and reads files containing concatenated gzip files. As of * Java 1.4, Java reads just the first one: it silently discards all characters (including gzipped * files) after the first gzipped file. * * @param file the possibly-compressed file to read * @param charsetName null, or the name of a Charset to use when reading the file * @return an InputStreamReader for file * @throws FileNotFoundException if the file cannot be found * @throws IOException if there is trouble reading the file */ public static InputStreamReader fileReader(File file, /*@Nullable*/ String charsetName) throws FileNotFoundException, IOException { InputStream in = new FileInputStream(file); InputStreamReader file_reader; if (charsetName == null) { file_reader = new InputStreamReader(in, UTF_8); } else { file_reader = new InputStreamReader(in, charsetName); } return file_reader; } /** * Returns a BufferedReader for the file, accounting for the possibility that the file is * compressed. (A file whose name ends with ".gz" is treated as compressed.) * * <p>Warning: The "gzip" program writes and reads files containing concatenated gzip files. As of * Java 1.4, Java reads just the first one: it silently discards all characters (including gzipped * files) after the first gzipped file. * * @param filename the possibly-compressed file to read * @return a BufferedReader for file * @throws FileNotFoundException if the file cannot be found * @throws IOException if there is trouble reading the file */ public static BufferedReader bufferedFileReader(String filename) throws FileNotFoundException, IOException { return bufferedFileReader(new File(filename)); } /** * Returns a BufferedReader for the file, accounting for the possibility that the file is * compressed. (A file whose name ends with ".gz" is treated as compressed.) * * <p>Warning: The "gzip" program writes and reads files containing concatenated gzip files. As of * Java 1.4, Java reads just the first one: it silently discards all characters (including gzipped * files) after the first gzipped file. * * @param file the possibility-compressed file to read * @return a BufferedReader for file * @throws FileNotFoundException if the file cannot be found * @throws IOException if there is trouble reading the file */ public static BufferedReader bufferedFileReader(File file) throws FileNotFoundException, IOException { return (bufferedFileReader(file, null)); } /** * Returns a BufferedReader for the file, accounting for the possibility that the file is * compressed. (A file whose name ends with ".gz" is treated as compressed.) * * <p>Warning: The "gzip" program writes and reads files containing concatenated gzip files. As of * Java 1.4, Java reads just the first one: it silently discards all characters (including gzipped * files) after the first gzipped file. * * @param filename the possibly-compressed file to read * @param charsetName the character set to use when reading the file * @return a BufferedReader for filename * @throws FileNotFoundException if the file cannot be found * @throws IOException if there is trouble reading the file */ public static BufferedReader bufferedFileReader(String filename, /*@Nullable*/ String charsetName) throws FileNotFoundException, IOException { return bufferedFileReader(new File(filename), charsetName); } /** * Returns a BufferedReader for the file, accounting for the possibility that the file is * compressed. (A file whose name ends with ".gz" is treated as compressed.) * * <p>Warning: The "gzip" program writes and reads files containing concatenated gzip files. As of * Java 1.4, Java reads just the first one: it silently discards all characters (including gzipped * files) after the first gzipped file. * * @param file the possibly-compressed file to read * @param charsetName the character set to use when reading the file * @return a BufferedReader for file * @throws FileNotFoundException if the file cannot be found * @throws IOException if there is trouble reading the file */ public static BufferedReader bufferedFileReader(File file, /*@Nullable*/ String charsetName) throws FileNotFoundException, IOException { Reader file_reader = fileReader(file, charsetName); return new BufferedReader(file_reader); } /** * Returns a LineNumberReader for the file, accounting for the possibility that the file is * compressed. (A file whose name ends with ".gz" is treated as compressed.) * * <p>Warning: The "gzip" program writes and reads files containing concatenated gzip files. As of * Java 1.4, Java reads just the first one: it silently discards all characters (including gzipped * files) after the first gzipped file. * * @param filename the possibly-compressed file to read * @return a LineNumberReader for filename * @throws FileNotFoundException if the file cannot be found * @throws IOException if there is trouble reading the file */ public static LineNumberReader lineNumberFileReader(String filename) throws FileNotFoundException, IOException { return lineNumberFileReader(new File(filename)); } /** * Returns a LineNumberReader for the file, accounting for the possibility that the file is * compressed. (A file whose name ends with ".gz" is treated as compressed.) * * <p>Warning: The "gzip" program writes and reads files containing concatenated gzip files. As of * Java 1.4, Java reads just the first one: it silently discards all characters (including gzipped * files) after the first gzipped file. * * @param file the possibly-compressed file to read * @return a LineNumberReader for file * @throws FileNotFoundException if the file cannot be found * @throws IOException if there is trouble reading the file */ public static LineNumberReader lineNumberFileReader(File file) throws FileNotFoundException, IOException { Reader file_reader; if (file.getName().endsWith(".gz")) { try { file_reader = new InputStreamReader(new GZIPInputStream(new FileInputStream(file)), "ISO-8859-1"); } catch (IOException e) { throw new IOException("Problem while reading " + file, e); } } else { file_reader = new InputStreamReader(new FileInputStream(file), "ISO-8859-1"); } return new LineNumberReader(file_reader); } /** * Returns a BufferedWriter for the file, accounting for the possibility that the file is * compressed. (A file whose name ends with ".gz" is treated as compressed.) * * <p>Warning: The "gzip" program writes and reads files containing concatenated gzip files. As of * Java 1.4, Java reads just the first one: it silently discards all characters (including gzipped * files) after the first gzipped file. * * @param filename the possibly-compressed file to write * @return a BufferedWriter for filename * @throws IOException if there is trouble writing the file */ public static BufferedWriter bufferedFileWriter(String filename) throws IOException { return bufferedFileWriter(filename, false); } /** * Returns a BufferedWriter for the file, accounting for the possibility that the file is * compressed. (A file whose name ends with ".gz" is treated as compressed.) * * <p>Warning: The "gzip" program writes and reads files containing concatenated gzip files. As of * Java 1.4, Java reads just the first one: it silently discards all characters (including gzipped * files) after the first gzipped file. * * @param filename the possibly-compressed file to write * @param append if true, the resulting BufferedWriter appends to the end of the file instead of * the beginning * @return a BufferedWriter for filename * @throws IOException if there is trouble writing the file */ // Question: should this be rewritten as a wrapper around bufferedFileOutputStream? public static BufferedWriter bufferedFileWriter(String filename, boolean append) throws IOException { if (filename.endsWith(".gz")) { return new BufferedWriter( new OutputStreamWriter( new GZIPOutputStream(new FileOutputStream(filename, append)), UTF_8)); } else { return Files.newBufferedWriter( Paths.get(filename), UTF_8, append ? new StandardOpenOption[] {CREATE, APPEND} : new StandardOpenOption[] {CREATE}); } } /** * Returns a BufferedOutputStream for the file, accounting for the possibility that the file is * compressed. (A file whose name ends with ".gz" is treated as compressed.) * * <p>Warning: The "gzip" program writes and reads files containing concatenated gzip files. As of * Java 1.4, Java reads just the first one: it silently discards all characters (including gzipped * files) after the first gzipped file. * * @param filename the possibly-compressed file to write * @param append if true, the resulting BufferedOutputStream appends to the end of the file * instead of the beginning * @return a BufferedOutputStream for filename * @throws IOException if there is trouble writing the file */ public static BufferedOutputStream bufferedFileOutputStream(String filename, boolean append) throws IOException { OutputStream os = new FileOutputStream(filename, append); if (filename.endsWith(".gz")) { os = new GZIPOutputStream(os); } return new BufferedOutputStream(os); } /////////////////////////////////////////////////////////////////////////// /// Class /// /** * Return true iff sub is a subtype of sup. If sub == sup, then sub is considered a subtype of sub * and this method returns true. * * @param sub class to test for being a subtype * @param sup class to test for being a supertype * @return true iff sub is a subtype of sup */ /*@Pure*/ public static boolean isSubtype(Class<?> sub, Class<?> sup) { if (sub == sup) { return true; } // Handle superclasses Class<?> parent = sub.getSuperclass(); // If parent == null, sub == Object if ((parent != null) && (parent == sup || isSubtype(parent, sup))) { return true; } // Handle interfaces for (Class<?> ifc : sub.getInterfaces()) { if (ifc == sup || isSubtype(ifc, sup)) { return true; } } return false; } /** Used by {@link #classForName}. */ private static HashMap<String, Class<?>> primitiveClasses = new HashMap<String, Class<?>>(8); static { primitiveClasses.put("boolean", Boolean.TYPE); primitiveClasses.put("byte", Byte.TYPE); primitiveClasses.put("char", Character.TYPE); primitiveClasses.put("double", Double.TYPE); primitiveClasses.put("float", Float.TYPE); primitiveClasses.put("int", Integer.TYPE); primitiveClasses.put("long", Long.TYPE); primitiveClasses.put("short", Short.TYPE); } // TODO: should create a method that handles any ClassGetName (including // primitives), but not fully-qualified names. /** * Like {@link Class#forName(String)}, but also works when the string represents a primitive type * or a fully-qualified name (as opposed to a binary name). * * <p>If the given name can't be found, this method changes the last '.' to a dollar sign ($) and * tries again. This accounts for inner classes that are incorrectly passed in in fully-qualified * format instead of binary format. (It should try multiple dollar signs, not just at the last * position.) * * <p>Recall the rather odd specification for {@link Class#forName(String)}: the argument is a * binary name for non-arrays, but a field descriptor for arrays. This method uses the same rules, * but additionally handles primitive types and, for non-arrays, fully-qualified names. * * @param className name of the class * @return the Class corresponding to className * @throws ClassNotFoundException if the class is not found */ // The annotation encourages proper use, even though this can take a // fully-qualified name (only for a non-array). public static Class<?> classForName( /*@ClassGetName*/ String className) throws ClassNotFoundException { Class<?> result = primitiveClasses.get(className); if (result != null) { return result; } else { try { return Class.forName(className); } catch (ClassNotFoundException e) { int pos = className.lastIndexOf('.'); if (pos < 0) { throw e; } @SuppressWarnings("signature") // checked below & exception is handled /*@ClassGetName*/ String inner_name = className.substring(0, pos) + "$" + className.substring(pos + 1); try { return Class.forName(inner_name); } catch (ClassNotFoundException ee) { throw e; } } } } @Deprecated private static HashMap</*@SourceNameForNonArrayNonInner*/ String, /*@FieldDescriptor*/ String> primitiveClassesJvm = new HashMap</*@SourceNameForNonArrayNonInner*/ String, /*@FieldDescriptor*/ String>(8); static { primitiveClassesJvm.put("boolean", "Z"); primitiveClassesJvm.put("byte", "B"); primitiveClassesJvm.put("char", "C"); primitiveClassesJvm.put("double", "D"); primitiveClassesJvm.put("float", "F"); primitiveClassesJvm.put("int", "I"); primitiveClassesJvm.put("long", "J"); primitiveClassesJvm.put("short", "S"); } /** * Convert a binary name to a field descriptor. For example, convert "java.lang.Object[]" to * "[Ljava/lang/Object;" or "int" to "I". * * @param classname name of the class, in binary class name format * @return name of the class, in field descriptor format * @deprecated use version in org.plumelib.bcelutil instead */ @Deprecated @SuppressWarnings("signature") // conversion routine public static /*@FieldDescriptor*/ String binaryNameToFieldDescriptor( /*@BinaryName*/ String classname) { int dims = 0; String sans_array = classname; while (sans_array.endsWith("[]")) { dims++; sans_array = sans_array.substring(0, sans_array.length() - 2); } String result = primitiveClassesJvm.get(sans_array); if (result == null) { result = "L" + sans_array + ";"; } for (int i = 0; i < dims; i++) { result = "[" + result; } return result.replace('.', '/'); } /** * Convert a primitive java type name (e.g., "int", "double", etc.) to a field descriptor (e.g., * "I", "D", etc.). * * @param primitive_name name of the type, in Java format * @return name of the type, in field descriptor format * @throws IllegalArgumentException if primitive_name is not a valid primitive type name * @deprecated use version in org.plumelib.bcelutil instead */ @Deprecated public static /*@FieldDescriptor*/ String primitiveTypeNameToFieldDescriptor( String primitive_name) { String result = primitiveClassesJvm.get(primitive_name); if (result == null) { throw new IllegalArgumentException("Not the name of a primitive type: " + primitive_name); } return result; } /** * Convert from a BinaryName to the format of {@link Class#getName()}. * * @param bn the binary name to convert * @return the class name, in Class.getName format * @deprecated use version in org.plumelib.bcelutil instead */ @Deprecated @SuppressWarnings("signature") // conversion routine public static /*@ClassGetName*/ String binaryNameToClassGetName(/*BinaryName*/ String bn) { if (bn.endsWith("[]")) { return binaryNameToFieldDescriptor(bn).replace('/', '.'); } else { return bn; } } /** * Convert from a FieldDescriptor to the format of {@link Class#getName()}. * * @param fd the class, in field descriptor format * @return the class name, in Class.getName format * @deprecated use version in org.plumelib.bcelutil instead */ @Deprecated @SuppressWarnings("signature") // conversion routine public static /*@ClassGetName*/ String fieldDescriptorToClassGetName( /*FieldDescriptor*/ String fd) { if (fd.startsWith("[")) { return fd.replace('/', '.'); } else { return fieldDescriptorToBinaryName(fd); } } /** * Convert a fully-qualified argument list from Java format to JVML format. For example, convert * "(java.lang.Integer[], int, java.lang.Integer[][])" to * "([Ljava/lang/Integer;I[[Ljava/lang/Integer;)". * * @param arglist an argument list, in Java format * @return argument list, in JVML format * @deprecated use version in org.plumelib.bcelutil instead */ @Deprecated public static String arglistToJvm(String arglist) { if (!(arglist.startsWith("(") && arglist.endsWith(")"))) { throw new Error("Malformed arglist: " + arglist); } String result = "("; String comma_sep_args = arglist.substring(1, arglist.length() - 1); StringTokenizer args_tokenizer = new StringTokenizer(comma_sep_args, ",", false); while (args_tokenizer.hasMoreTokens()) { @SuppressWarnings("signature") // substring /*@BinaryName*/ String arg = args_tokenizer.nextToken().trim(); result += binaryNameToFieldDescriptor(arg); } result += ")"; // System.out.println("arglistToJvm: " + arglist + " => " + result); return result; } @Deprecated private static HashMap<String, String> primitiveClassesFromJvm = new HashMap<String, String>(8); static { primitiveClassesFromJvm.put("Z", "boolean"); primitiveClassesFromJvm.put("B", "byte"); primitiveClassesFromJvm.put("C", "char"); primitiveClassesFromJvm.put("D", "double"); primitiveClassesFromJvm.put("F", "float"); primitiveClassesFromJvm.put("I", "int"); primitiveClassesFromJvm.put("J", "long"); primitiveClassesFromJvm.put("S", "short"); } // does not convert "V" to "void". Should it? /** * Convert a field descriptor to a binary name. For example, convert "[Ljava/lang/Object;" to * "java.lang.Object[]" or "I" to "int". * * @param classname name of the type, in JVML format * @return name of the type, in Java format * @deprecated use version in org.plumelib.bcelutil instead */ @Deprecated @SuppressWarnings("signature") // conversion routine public static /*@BinaryName*/ String fieldDescriptorToBinaryName(String classname) { if (classname.equals("")) { throw new Error("Empty string passed to fieldDescriptorToBinaryName"); } int dims = 0; while (classname.startsWith("[")) { dims++; classname = classname.substring(1); } String result; if (classname.startsWith("L") && classname.endsWith(";")) { result = classname.substring(1, classname.length() - 1); } else { result = primitiveClassesFromJvm.get(classname); if (result == null) { throw new Error("Malformed base class: " + classname); } } for (int i = 0; i < dims; i++) { result += "[]"; } return result.replace('/', '.'); } /** * Convert an argument list from JVML format to Java format. For example, convert * "([Ljava/lang/Integer;I[[Ljava/lang/Integer;)" to "(java.lang.Integer[], int, * java.lang.Integer[][])". * * @param arglist an argument list, in JVML format * @return argument list, in Java format * @deprecated use version in org.plumelib.bcelutil instead */ @Deprecated public static String arglistFromJvm(String arglist) { if (!(arglist.startsWith("(") && arglist.endsWith(")"))) { throw new Error("Malformed arglist: " + arglist); } String result = "("; /*@Positive*/ int pos = 1; while (pos < arglist.length() - 1) { if (pos > 1) { result += ", "; } int nonarray_pos = pos; while (arglist.charAt(nonarray_pos) == '[') { nonarray_pos++; if (nonarray_pos >= arglist.length()) { throw new Error("Malformed arglist: " + arglist); } } char c = arglist.charAt(nonarray_pos); if (c == 'L') { int semi_pos = arglist.indexOf(';', nonarray_pos); if (semi_pos == -1) { throw new Error("Malformed arglist: " + arglist); } String fieldDescriptor = arglist.substring(pos, semi_pos + 1); result += fieldDescriptorToBinaryName(fieldDescriptor); pos = semi_pos + 1; } else { String maybe = fieldDescriptorToBinaryName(arglist.substring(pos, nonarray_pos + 1)); if (maybe == null) { // return null; throw new Error("Malformed arglist: " + arglist); } result += maybe; pos = nonarray_pos + 1; } } return result + ")"; } /////////////////////////////////////////////////////////////////////////// /// ClassLoader /// /** * This static nested class has no purpose but to define defineClassFromFile. * ClassLoader.defineClass is protected, so I subclass ClassLoader in order to call defineClass. */ private static class PromiscuousLoader extends ClassLoader { /** * Converts the bytes in a file into an instance of class Class, and also resolves (links) the * class. Delegates the real work to defineClass. * * @see ClassLoader#defineClass(String,byte[],int,int) * @param className the expected binary name of the class to define, or null if not known * @param pathname the file from which to load the class * @return the {@code Class} object that was created */ public Class<?> defineClassFromFile( /*@BinaryName*/ String className, String pathname) throws FileNotFoundException, IOException { FileInputStream fi = new FileInputStream(pathname); int numbytes = fi.available(); byte[] classBytes = new byte[numbytes]; int bytesRead = fi.read(classBytes); fi.close(); if (bytesRead < numbytes) { throw new Error( String.format( "Expected to read %d bytes from %s, got %d", numbytes, pathname, bytesRead)); } Class<?> return_class = defineClass(className, classBytes, 0, numbytes); resolveClass(return_class); // link the class return return_class; } } private static PromiscuousLoader thePromiscuousLoader = new PromiscuousLoader(); /** * Converts the bytes in a file into an instance of class Class, and resolves (links) the class. * Like {@link ClassLoader#defineClass(String,byte[],int,int)}, but takes a file name rather than * an array of bytes as an argument, and also resolves (links) the class. * * @see ClassLoader#defineClass(String,byte[],int,int) * @param className the name of the class to define, or null if not known * @param pathname the pathname of a .class file * @return a Java Object corresponding to the Class defined in the .class file * @throws FileNotFoundException if the file cannot be found * @throws IOException if there is trouble reading the file */ // Also throws UnsupportedClassVersionError and some other exceptions. public static Class<?> defineClassFromFile( /*@BinaryName*/ String className, String pathname) throws FileNotFoundException, IOException { return thePromiscuousLoader.defineClassFromFile(className, pathname); } /////////////////////////////////////////////////////////////////////////// /// Classpath /// // Perhaps abstract out the simpler addToPath from this /** * Add the directory to the system classpath. * * @param dir directory to add to the system classpath */ public static void addToClasspath(String dir) { // If the dir isn't on CLASSPATH, add it. String pathSep = System.getProperty("path.separator"); // what is the point of the "replace()" call? String cp = System.getProperty("java.class.path", ".").replace('\\', '/'); StringTokenizer tokenizer = new StringTokenizer(cp, pathSep, false); boolean found = false; while (tokenizer.hasMoreTokens() && !found) { found = tokenizer.nextToken().equals(dir); } if (!found) { System.setProperty("java.class.path", dir + pathSep + cp); } } /////////////////////////////////////////////////////////////////////////// /// File /// /** * Count the number of lines in the specified file. * * @param filename file whose size to count * @return number of lines in filename * @throws IOException if there is trouble reading the file */ public static long count_lines(String filename) throws IOException { long count = 0; try (LineNumberReader reader = UtilPlume.lineNumberFileReader(filename)) { while (reader.readLine() != null) { count++; } } return count; } /** * Return the contents of the file, as a list of strings, one per line. * * @param filename the file whose contents to return * @return the contents of {@code filename}, one string per line * @throws IOException if there was a problem reading the file */ public static List<String> fileLines(String filename) throws IOException { List<String> textList = new ArrayList<>(); try (LineNumberReader reader = UtilPlume.lineNumberFileReader(filename)) { String line; while ((line = reader.readLine()) != null) { textList.add(line); } } return textList; } /** * Tries to infer the line separator used in a file. * * @param filename the file to infer a line separator from * @return the inferred line separator used in filename * @throws IOException if there is trouble reading the file */ public static String inferLineSeparator(String filename) throws IOException { return inferLineSeparator(new File(filename)); } /** * Tries to infer the line separator used in a file. * * @param file the file to infer a line separator from * @return the inferred line separator used in filename * @throws IOException if there is trouble reading the file */ public static String inferLineSeparator(File file) throws IOException { try (BufferedReader r = UtilPlume.bufferedFileReader(file)) { int unix = 0; int dos = 0; int mac = 0; while (true) { String s = r.readLine(); if (s == null) { break; } if (s.endsWith("\r\n")) { dos++; } else if (s.endsWith("\r")) { mac++; } else if (s.endsWith("\n")) { unix++; } else { // This can happen only if the last line is not terminated. } } if ((dos > mac && dos > unix) || (lineSep.equals("\r\n") && dos >= unix && dos >= mac)) { return "\r\n"; } if ((mac > dos && mac > unix) || (lineSep.equals("\r") && mac >= dos && mac >= unix)) { return "\r"; } if ((unix > dos && unix > mac) || (lineSep.equals("\n") && unix >= dos && unix >= mac)) { return "\n"; } // The two non-preferred line endings are tied and have more votes than // the preferred line ending. Give up and return the line separator // for the system on which Java is currently running. return lineSep; } } /** * Return true iff files have the same contents. * * @param file1 first file to compare * @param file2 second file to compare * @return true iff the files have the same contents */ /*@Pure*/ public static boolean equalFiles(String file1, String file2) { return equalFiles(file1, file2, false); } /** * Return true iff the files have the same contents. * * @param file1 first file to compare * @param file2 second file to compare * @param trimLines if true, call String.trim on each line before comparing * @return true iff the files have the same contents */ @SuppressWarnings({"purity", "lock"}) // reads files, side effects local state /*@Pure*/ public static boolean equalFiles(String file1, String file2, boolean trimLines) { try (LineNumberReader reader1 = UtilPlume.lineNumberFileReader(file1); LineNumberReader reader2 = UtilPlume.lineNumberFileReader(file2); ) { String line1 = reader1.readLine(); String line2 = reader2.readLine(); while (line1 != null && line2 != null) { if (trimLines) { line1 = line1.trim(); line2 = line2.trim(); } if (!(line1.equals(line2))) { return false; } line1 = reader1.readLine(); line2 = reader2.readLine(); } if (line1 == null && line2 == null) { return true; } return false; } catch (IOException e) { throw new RuntimeException(e); } } /** * Returns true if the file exists and is writable, or if the file can be created. * * @param file the file to create and write * @return true iff the file can be created and written */ public static boolean canCreateAndWrite(File file) { if (file.exists()) { return file.canWrite(); } else { File directory = file.getParentFile(); if (directory == null) { directory = new File("."); } // Does this test need "directory.canRead()" also? return directory.canWrite(); } /// Old implementation; is this equivalent to the new one, above?? // try { // if (file.exists()) { // return file.canWrite(); // } else { // file.createNewFile(); // file.delete(); // return true; // } // } catch (IOException e) { // return false; // } } /// /// Directories /// /** * Creates an empty directory in the default temporary-file directory, using the given prefix and * suffix to generate its name. For example, calling createTempDir("myPrefix", "mySuffix") will * create the following directory: temporaryFileDirectory/myUserName/myPrefix_someString_suffix. * someString is internally generated to ensure no temporary files of the same name are generated. * * @param prefix the prefix string to be used in generating the file's name; must be at least * three characters long * @param suffix the suffix string to be used in generating the file's name; may be null, in which * case the suffix ".tmp" will be used Returns: An abstract pathname denoting a newly-created * empty file * @return a File representing the newly-created temporary directory * @throws IllegalArgumentException If the prefix argument contains fewer than three characters * @throws IOException If a file could not be created * @throws SecurityException If a security manager exists and its * SecurityManager.checkWrite(java.lang.String) method does not allow a file to be created * @see java.io.File#createTempFile(String, String, File) */ public static File createTempDir(String prefix, String suffix) throws IOException { String fs = File.separator; String path = System.getProperty("java.io.tmpdir") + fs + System.getProperty("user.name") + fs; File pathFile = new File(path); if (!pathFile.isDirectory()) { if (!pathFile.mkdirs()) { throw new IOException("Could not create directory: " + pathFile); } } // Call Java runtime to create a file with a unique name File tmpfile = File.createTempFile(prefix + "_", "_", pathFile); String tmpDirPath = tmpfile.getPath() + suffix; File tmpDir = new File(tmpDirPath); if (!tmpDir.mkdirs()) { throw new IOException("Could not create directory: " + tmpDir); } // Now that we have created our directory, we should get rid // of the intermediate TempFile we created. tmpfile.delete(); return tmpDir; } /** * Deletes the directory at dirName and all its files. Also works on regular files. * * @param dirName the directory to delete * @return true if and only if the file or directory is successfully deleted; false otherwise */ public static boolean deleteDir(String dirName) { return deleteDir(new File(dirName)); } /** * Deletes the directory at dir and all its files. Also works on regular files. * * @param dir the directory to delete * @return true if and only if the file or directory is successfully deleted; false otherwise */ public static boolean deleteDir(File dir) { File[] children = dir.listFiles(); if (children != null) { // null means not a directory, or I/O error occurred. for (File child : children) { deleteDir(child); } } return dir.delete(); } /// /// File names (aka filenames) /// // Someone must have already written this. Right? /** * A FilenameFilter that accepts files whose name matches the given wildcard. The wildcard must * contain exactly one "*". */ public static final class WildcardFilter implements FilenameFilter { String prefix; String suffix; public WildcardFilter(String filename) { int astloc = filename.indexOf('*'); if (astloc == -1) { throw new Error("No asterisk in wildcard argument: " + filename); } prefix = filename.substring(0, astloc); suffix = filename.substring(astloc + 1); if (filename.indexOf('*') != -1) { throw new Error("Multiple asterisks in wildcard argument: " + filename); } } @Override public boolean accept(File dir, String name) { return name.startsWith(prefix) && name.endsWith(suffix); } } static final String userHome = System.getProperty("user.home"); /** * Does tilde expansion on a file name (to the user's home directory). * * @param name file whose name to expand * @return file with expanded file */ public static File expandFilename(File name) { String path = name.getPath(); String newname = expandFilename(path); @SuppressWarnings("interning") boolean changed = (newname != path); if (changed) { return new File(newname); } else { return name; } } /** * Does tilde expansion on a file name (to the user's home directory). * * @param name filename to expand * @return expanded filename */ public static String expandFilename(String name) { if (name.contains("~")) { return (name.replace("~", userHome)); } else { return name; } } /** * Return a string version of the filename that can be used in Java source. On Windows, the file * will return a backslash separated string. Since backslash is an escape character, it must be * quoted itself inside the string. * * <p>The current implementation presumes that backslashes don't appear in filenames except as * windows path separators. That seems like a reasonable assumption. * * @param name file whose name to quote * @return a string version of the name that can be used in Java source */ public static String java_source(File name) { return name.getPath().replace("\\", "\\\\"); } /// /// Reading and writing /// /** * Writes an Object to a File. * * @param o the object to write * @param file the file to which to write the object * @throws IOException if there is trouble writing the file */ public static void writeObject(Object o, File file) throws IOException { // 8192 is the buffer size in BufferedReader OutputStream bytes = new BufferedOutputStream(new FileOutputStream(file), 8192); if (file.getName().endsWith(".gz")) { bytes = new GZIPOutputStream(bytes); } ObjectOutputStream objs = new ObjectOutputStream(bytes); objs.writeObject(o); objs.close(); } /** * Reads an Object from a File. * * @param file the file from which to read * @return the object read from the file * @throws IOException if there is trouble reading the file * @throws ClassNotFoundException if the object's class cannot be found */ public static Object readObject(File file) throws IOException, ClassNotFoundException { // 8192 is the buffer size in BufferedReader InputStream istream = new BufferedInputStream(new FileInputStream(file), 8192); if (file.getName().endsWith(".gz")) { try { istream = new GZIPInputStream(istream); } catch (IOException e) { throw new IOException("Problem while reading " + file, e); } } ObjectInputStream objs = new ObjectInputStream(istream); return objs.readObject(); } /** * Reads the entire contents of the reader and returns it as a string. Any IOException encountered * will be turned into an Error. * * @param r the Reader to read * @return the entire contents of the reader, as a string */ public static String readerContents(Reader r) { try { StringBuilder contents = new StringBuilder(); int ch; while ((ch = r.read()) != -1) { contents.append((char) ch); } r.close(); return contents.toString(); } catch (Exception e) { throw new Error("Unexpected error in readerContents(" + r + ")", e); } } // an alternate name would be "fileContents". /** * Reads the entire contents of the file and returns it as a string. Any IOException encountered * will be turned into an Error. * * <p>You could use {@code new String(Files.readAllBytes(...))}, but it requires a Path rather * than a File, and it can throw IOException which has to be caught. * * @param file the file to read * @return the entire contents of the reader, as a string */ public static String readFile(File file) { try { BufferedReader reader = UtilPlume.bufferedFileReader(file); StringBuilder contents = new StringBuilder(); String line = reader.readLine(); while (line != null) { contents.append(line); // Note that this converts line terminators! contents.append(lineSep); line = reader.readLine(); } reader.close(); return contents.toString(); } catch (Exception e) { throw new Error("Unexpected error in readFile(" + file + ")", e); } } /** * Creates a file with the given name and writes the specified string to it. If the file currently * exists (and is writable) it is overwritten Any IOException encountered will be turned into an * Error. * * @param file the file to write to * @param contents the text to put in the file */ public static void writeFile(File file, String contents) { try { Writer writer = Files.newBufferedWriter(file.toPath(), UTF_8); writer.write(contents, 0, contents.length()); writer.close(); } catch (Exception e) { throw new Error("Unexpected error in writeFile(" + file + ")", e); } } /////////////////////////////////////////////////////////////////////////// /// Hashing /// // In hashing, there are two separate issues. First, one must convert // the input datum into an integer. Then, one must transform the // resulting integer in a pseudorandom way so as to result in a number // that is far separated from other values that may have been near it to // begin with. Often these two steps are combined, particularly if // one wishes to avoid creating too large an integer (losing information // off the top bits). // http://burtleburtle.net/bob/hash/hashfaq.html says (of combined methods): // * for (h=0, i=0; i<len; ++i) { h += key[i]; h += (h<<10); h ^= (h>>6); } // h += (h<<3); h ^= (h>>11); h += (h<<15); // is good. // * for (h=0, i=0; i<len; ++i) h = tab[(h^key[i])&0xff]; may be good. // * for (h=0, i=0; i<len; ++i) h = (h>>8)^tab[(key[i]+h)&0xff]; may be good. // In this part of the file, perhaps I will eventually write good hash // functions. For now, write cheesy ones that primarily deal with the // first issue, transforming a data structure into a single number. This // is also known as fingerprinting. /** * Return a hash of the arguments. Note that this differs from the result of {@link * Double#hashCode()}. * * @param x value to be hashed * @return a hash of the arguments */ public static int hash(double x) { return hash(Double.doubleToLongBits(x)); } /** * Return a hash of the arguments. * * @param a value to be hashed * @param b value to be hashed * @return a hash of the arguments */ public static int hash(double a, double b) { double result = 17; result = result * 37 + a; result = result * 37 + b; return hash(result); } /** * Return a hash of the arguments. * * @param a value to be hashed * @param b value to be hashed * @param c value to be hashed * @return a hash of the arguments */ public static int hash(double a, double b, double c) { double result = 17; result = result * 37 + a; result = result * 37 + b; result = result * 37 + c; return hash(result); } /** * Return a hash of the arguments. * * @param a value to be hashed * @return a hash of the arguments */ public static int hash(double /*@Nullable*/ [] a) { double result = 17; if (a != null) { result = result * 37 + a.length; for (int i = 0; i < a.length; i++) { result = result * 37 + a[i]; } } return hash(result); } /** * Return a hash of the arguments. * * @param a value to be hashed * @param b value to be hashed * @return a hash of the arguments */ public static int hash(double /*@Nullable*/ [] a, double /*@Nullable*/ [] b) { return hash(hash(a), hash(b)); } /// Don't define hash with int args; use the long versions instead. /** * Return a hash of the arguments. Note that this differs from the result of {@link * Long#hashCode()}. But it doesn't map -1 and 0 to the same value. * * @param l value to be hashed * @return a hash of the arguments */ public static int hash(long l) { // If possible, use the value itself. if (l >= Integer.MIN_VALUE && l <= Integer.MAX_VALUE) { return (int) l; } int result = 17; int hibits = (int) (l >> 32); int lobits = (int) l; result = result * 37 + hibits; result = result * 37 + lobits; return result; } /** * Return a hash of the arguments. * * @param a value to be hashed * @param b value to be hashed * @return a hash of the arguments */ public static int hash(long a, long b) { long result = 17; result = result * 37 + a; result = result * 37 + b; return hash(result); } /** * Return a hash of the arguments. * * @param a value to be hashed * @param b value to be hashed * @param c value to be hashed * @return a hash of the arguments */ public static int hash(long a, long b, long c) { long result = 17; result = result * 37 + a; result = result * 37 + b; result = result * 37 + c; return hash(result); } /** * Return a hash of the arguments. * * @param a value to be hashed * @return a hash of the arguments */ public static int hash(long /*@Nullable*/ [] a) { long result = 17; if (a != null) { result = result * 37 + a.length; for (int i = 0; i < a.length; i++) { result = result * 37 + a[i]; } } return hash(result); } /** * Return a hash of the arguments. * * @param a value to be hashed * @param b value to be hashed * @return a hash of the arguments */ public static int hash(long /*@Nullable*/ [] a, long /*@Nullable*/ [] b) { return hash(hash(a), hash(b)); } /** * Return a hash of the arguments. * * @param a value to be hashed * @return a hash of the arguments */ public static int hash(/*@Nullable*/ String a) { return (a == null) ? 0 : a.hashCode(); } /** * Return a hash of the arguments. * * @param a value to be hashed * @param b value to be hashed * @return a hash of the arguments */ public static int hash(/*@Nullable*/ String a, /*@Nullable*/ String b) { long result = 17; result = result * 37 + hash(a); result = result * 37 + hash(b); return hash(result); } /** * Return a hash of the arguments. * * @param a value to be hashed * @param b value to be hashed * @param c value to be hashed * @return a hash of the arguments */ public static int hash(/*@Nullable*/ String a, /*@Nullable*/ String b, /*@Nullable*/ String c) { long result = 17; result = result * 37 + hash(a); result = result * 37 + hash(b); result = result * 37 + hash(c); return hash(result); } /** * Return a hash of the arguments. * * @param a value to be hashed * @return a hash of the arguments */ public static int hash(/*@Nullable*/ String /*@Nullable*/ [] a) { long result = 17; if (a != null) { result = result * 37 + a.length; for (int i = 0; i < a.length; i++) { result = result * 37 + hash(a[i]); } } return hash(result); } /////////////////////////////////////////////////////////////////////////// /// Iterator /// /** * Converts an Iterator to an Iterable. The resulting Iterable can be used to produce a single, * working Iterator (the one that was passed in). Subsequent calls to its iterator() method will * fail, because otherwise they would return the same Iterator instance, which may have been * exhausted, or otherwise be in some indeterminate state. Calling iteratorToIterable twice on the * same argument can have similar problems, so don't do that. * * @param source the Iterator to be converted to Iterable * @param <T> the element type * @return source, converted to Iterable */ public static <T> Iterable<T> iteratorToIterable(final Iterator<T> source) { if (source == null) { throw new NullPointerException(); } return new Iterable<T>() { private AtomicBoolean used = new AtomicBoolean(); @Override public Iterator<T> iterator() { if (used.getAndSet(true)) { throw new Error("Call iterator() just once"); } return source; } }; } // Making these classes into functions didn't work because I couldn't get // their arguments into a scope that Java was happy with. /** Converts an Enumeration into an Iterator. */ public static final class EnumerationIterator<T> implements Iterator<T> { Enumeration<T> e; public EnumerationIterator(Enumeration<T> e) { this.e = e; } @Override public boolean hasNext(/*>>>@GuardSatisfied EnumerationIterator<T> this*/) { return e.hasMoreElements(); } @Override public T next(/*>>>@GuardSatisfied EnumerationIterator<T> this*/) { return e.nextElement(); } @Override public void remove(/*>>>@GuardSatisfied EnumerationIterator<T> this*/) { throw new UnsupportedOperationException(); } } /** Converts an Iterator into an Enumeration. */ @SuppressWarnings("JdkObsolete") public static final class IteratorEnumeration<T> implements Enumeration<T> { Iterator<T> itor; public IteratorEnumeration(Iterator<T> itor) { this.itor = itor; } @Override public boolean hasMoreElements() { return itor.hasNext(); } @Override public T nextElement() { return itor.next(); } } // This must already be implemented someplace else. Right?? /** * An Iterator that returns first the elements returned by its first argument, then the elements * returned by its second argument. Like {@link MergedIterator}, but specialized for the case of * two arguments. */ public static final class MergedIterator2<T> implements Iterator<T> { Iterator<T> itor1, itor2; public MergedIterator2(Iterator<T> itor1_, Iterator<T> itor2_) { this.itor1 = itor1_; this.itor2 = itor2_; } @Override public boolean hasNext(/*>>>@GuardSatisfied MergedIterator2<T> this*/) { return (itor1.hasNext() || itor2.hasNext()); } @Override public T next(/*>>>@GuardSatisfied MergedIterator2<T> this*/) { if (itor1.hasNext()) { return itor1.next(); } else if (itor2.hasNext()) { return itor2.next(); } else { throw new NoSuchElementException(); } } @Override public void remove(/*>>>@GuardSatisfied MergedIterator2<T> this*/) { throw new UnsupportedOperationException(); } } // This must already be implemented someplace else. Right?? /** * An Iterator that returns the elements in each of its argument Iterators, in turn. The argument * is an Iterator of Iterators. Like {@link MergedIterator2}, but generalized to arbitrary number * of iterators. */ public static final class MergedIterator<T> implements Iterator<T> { Iterator<Iterator<T>> itorOfItors; public MergedIterator(Iterator<Iterator<T>> itorOfItors) { this.itorOfItors = itorOfItors; } // an empty iterator to prime the pump Iterator<T> current = new ArrayList<T>().iterator(); @Override public boolean hasNext(/*>>>@GuardSatisfied MergedIterator<T> this*/) { while ((!current.hasNext()) && (itorOfItors.hasNext())) { current = itorOfItors.next(); } return current.hasNext(); } @Override public T next(/*>>>@GuardSatisfied MergedIterator<T> this*/) { hasNext(); // for side effect return current.next(); } @Override public void remove(/*>>>@GuardSatisfied MergedIterator<T> this*/) { throw new UnsupportedOperationException(); } } /** An iterator that only returns elements that match the given Filter. */ @SuppressWarnings("assignment.type.incompatible") // problems in DFF branch public static final class FilteredIterator<T> implements Iterator<T> { Iterator<T> itor; Filter<T> filter; public FilteredIterator(Iterator<T> itor, Filter<T> filter) { this.itor = itor; this.filter = filter; } @SuppressWarnings("unchecked") T invalid_t = (T) new Object(); T current = invalid_t; boolean current_valid = false; @Override public boolean hasNext(/*>>>@GuardSatisfied FilteredIterator<T> this*/) { while ((!current_valid) && itor.hasNext()) { current = itor.next(); current_valid = filter.accept(current); } return current_valid; } @Override public T next(/*>>>@GuardSatisfied FilteredIterator<T> this*/) { if (hasNext()) { current_valid = false; @SuppressWarnings("interning") boolean ok = (current != invalid_t); assert ok; return current; } else { throw new NoSuchElementException(); } } @Override public void remove(/*>>>@GuardSatisfied FilteredIterator<T> this*/) { throw new UnsupportedOperationException(); } } /** * Returns an iterator just like its argument, except that the first and last elements are * removed. They can be accessed via the getFirst and getLast methods. */ @SuppressWarnings("assignment.type.incompatible") // problems in DFF branch public static final class RemoveFirstAndLastIterator<T> implements Iterator<T> { Iterator<T> itor; // I don't think this works, because the iterator might itself return null // /*@Nullable*/ T nothing = (/*@Nullable*/ T) null; @SuppressWarnings("unchecked") T nothing = (T) new Object(); T first = nothing; T current = nothing; public RemoveFirstAndLastIterator(Iterator<T> itor) { this.itor = itor; if (itor.hasNext()) { first = itor.next(); } if (itor.hasNext()) { current = itor.next(); } } @Override public boolean hasNext(/*>>>@GuardSatisfied RemoveFirstAndLastIterator<T> this*/) { return itor.hasNext(); } @Override public T next(/*>>>@GuardSatisfied RemoveFirstAndLastIterator<T> this*/) { if (!itor.hasNext()) { throw new NoSuchElementException(); } T tmp = current; current = itor.next(); return tmp; } public T getFirst() { @SuppressWarnings("interning") // check for equality to a special value boolean invalid = (first == nothing); if (invalid) { throw new NoSuchElementException(); } return first; } // Throws an error unless the RemoveFirstAndLastIterator has already // been iterated all the way to its end (so the delegate is pointing to // the last element). Also, this is buggy when the delegate is empty. public T getLast() { if (itor.hasNext()) { throw new Error(); } return current; } @Override public void remove(/*>>>@GuardSatisfied RemoveFirstAndLastIterator<T> this*/) { throw new UnsupportedOperationException(); } } /** * Return a List containing num_elts randomly chosen elements from the iterator, or all the * elements of the iterator if there are fewer. It examines every element of the iterator, but * does not keep them all in memory. * * @param <T> type of the iterator elements * @param itor elements to be randomly selected from * @param num_elts number of elements to select * @return list of num_elts elements from itor */ public static <T> List<T> randomElements(Iterator<T> itor, int num_elts) { return randomElements(itor, num_elts, r); } private static Random r = new Random(); /** * Return a List containing num_elts randomly chosen elements from the iterator, or all the * elements of the iterator if there are fewer. It examines every element of the iterator, but * does not keep them all in memory. * * @param <T> type of the iterator elements * @param itor elements to be randomly selected from * @param num_elts number of elements to select * @param random the Random instance to use to make selections * @return list of num_elts elements from itor */ public static <T> List<T> randomElements(Iterator<T> itor, int num_elts, Random random) { // The elements are chosen with the following probabilities, // where n == num_elts: // n n/2 n/3 n/4 n/5 ... RandomSelector<T> rs = new RandomSelector<T>(num_elts, random); while (itor.hasNext()) { rs.accept(itor.next()); } return rs.getValues(); /* ArrayList<T> result = new ArrayList<T>(num_elts); int i=1; for (int n=0; n<num_elts && itor.hasNext(); n++, i++) { result.add(itor.next()); } for (; itor.hasNext(); i++) { T o = itor.next(); // test random < num_elts/i if (random.nextDouble() * i < num_elts) { // This element will replace one of the existing elements. result.set(random.nextInt(num_elts), o); } } return result; */ } /////////////////////////////////////////////////////////////////////////// /// Map /// // In Python, inlining this gave a 10x speed improvement. // Will the same be true for Java? /** * Increment the Integer which is indexed by key in the Map. If the key isn't in the Map, it is * added. * * @param <T> type of keys in the map * @param m map to have one of its values incremented * @param key the key for the element whose value will be incremented * @param count how much to increment the value by * @return the old value, before it was incremented * @throws Error if the key is in the Map but maps to a non-Integer */ public static <T> /*@Nullable*/ Integer incrementMap(Map<T, Integer> m, T key, int count) { Integer old = m.get(key); int new_total; if (old == null) { new_total = count; } else { new_total = old.intValue() + count; } return m.put(key, new_total); } /** * Returns a multi-line string representation of a map. * * @param <K> type of map keys * @param <V> type of map values * @param m map to be converted to a string * @return a multi-line string representation of m */ public static <K, V> String mapToString(Map<K, V> m) { StringBuilder sb = new StringBuilder(); mapToString(sb, m, ""); return sb.toString(); } /** * Write a multi-line representation of the map into the given Appendable (e.g., a StringBuilder). * * @param <K> type of map keys * @param <V> type of map values * @param sb an Appendable (such as StringBuilder) to which to write a multi-line string * representation of m * @param m map to be converted to a string * @param linePrefix prefix to write at the beginning of each line */ public static <K, V> void mapToString(Appendable sb, Map<K, V> m, String linePrefix) { try { for (Map.Entry<K, V> entry : m.entrySet()) { sb.append(linePrefix); sb.append(Objects.toString(entry.getKey())); sb.append(" => "); sb.append(Objects.toString(entry.getValue())); sb.append(lineSep); } } catch (IOException e) { throw new RuntimeException(e); } } /** * Returns a sorted version of m.keySet(). * * @param <K> type of the map keys * @param <V> type of the map values * @param m a map whose keyset will be sorted * @return a sorted version of m.keySet() */ public static <K extends Comparable<? super K>, V> Collection</*@KeyFor("#1")*/ K> sortedKeySet( Map<K, V> m) { ArrayList</*@KeyFor("#1")*/ K> theKeys = new ArrayList</*@KeyFor("#1")*/ K>(m.keySet()); Collections.sort(theKeys); return theKeys; } /** * Returns a sorted version of m.keySet(). * * @param <K> type of the map keys * @param <V> type of the map values * @param m a map whose keyset will be sorted * @param comparator the Comparator to use for sorting * @return a sorted version of m.keySet() */ public static <K, V> Collection</*@KeyFor("#1")*/ K> sortedKeySet( Map<K, V> m, Comparator<K> comparator) { ArrayList</*@KeyFor("#1")*/ K> theKeys = new ArrayList</*@KeyFor("#1")*/ K>(m.keySet()); Collections.sort(theKeys, comparator); return theKeys; } /////////////////////////////////////////////////////////////////////////// /// Method /// /** * Maps from a comma-delimited string of arg types, such as appears in a method signature, to an * array of Class objects, one for each arg type. Example keys include: "java.lang.String, * java.lang.String, java.lang.Class[]" and "int,int". */ static HashMap<String, Class<?>[]> args_seen = new HashMap<String, Class<?>[]>(); /** * Given a method signature, return the method. * * <p>Example calls are: * * <pre> * UtilPlume.methodForName("org.plumelib.util.UtilPlume.methodForName(java.lang.String, java.lang.String, java.lang.Class[])") * UtilPlume.methodForName("org.plumelib.util.UtilPlume.methodForName(java.lang.String,java.lang.String,java.lang.Class[])") * UtilPlume.methodForName("java.lang.Math.min(int,int)") * </pre> * * @param method a method signature * @return the method corresponding to the given signature * @throws ClassNotFoundException if the class is not found * @throws NoSuchMethodException if the method is not found */ public static Method methodForName(String method) throws ClassNotFoundException, NoSuchMethodException, SecurityException { int oparenpos = method.indexOf('('); int dotpos = method.lastIndexOf('.', oparenpos); int cparenpos = method.indexOf(')', oparenpos); if ((dotpos == -1) || (oparenpos == -1) || (cparenpos == -1)) { throw new Error( "malformed method name should contain a period, open paren, and close paren: " + method + " <<" + dotpos + "," + oparenpos + "," + cparenpos + ">>"); } for (int i = cparenpos + 1; i < method.length(); i++) { if (!Character.isWhitespace(method.charAt(i))) { throw new Error( "malformed method name should contain only whitespace following close paren"); } } @SuppressWarnings("signature") // throws exception if class does not exist /*@BinaryNameForNonArray*/ String classname = method.substring(0, dotpos); String methodname = method.substring(dotpos + 1, oparenpos); String all_argnames = method.substring(oparenpos + 1, cparenpos).trim(); Class<?>[] argclasses = args_seen.get(all_argnames); if (argclasses == null) { String[] argnames; if (all_argnames.equals("")) { argnames = new String[0]; } else { argnames = split(all_argnames, ','); } /*@MonotonicNonNull*/ Class<?>[] argclasses_tmp = new Class<?>[argnames.length]; for (int i = 0; i < argnames.length; i++) { String bnArgname = argnames[i].trim(); /*@ClassGetName*/ String cgnArgname = binaryNameToClassGetName(bnArgname); argclasses_tmp[i] = classForName(cgnArgname); } @SuppressWarnings("cast") Class<?>[] argclasses_res = (/*@NonNull*/ Class<?>[]) argclasses_tmp; argclasses = argclasses_res; args_seen.put(all_argnames, argclasses_res); } return methodForName(classname, methodname, argclasses); } /** * Given a class name and a method name in that class, return the method. * * @param classname class in which to find the method * @param methodname the method name * @param params the parameters of the method * @return the method named classname.methodname with parameters params * @throws ClassNotFoundException if the class is not found * @throws NoSuchMethodException if the method is not found */ public static Method methodForName( /*@BinaryNameForNonArray*/ String classname, String methodname, Class<?>[] params) throws ClassNotFoundException, NoSuchMethodException, SecurityException { Class<?> c = Class.forName(classname); Method m = c.getDeclaredMethod(methodname, params); return m; } /////////////////////////////////////////////////////////////////////////// /// ProcessBuilder /// /** * Execute the given command, and return all its output as a string. * * @param command a command to execute on the command line * @return all the output of the command */ public static String backticks(String... command) { return backticks(Arrays.asList(command)); } /** * Execute the given command, and return all its output as a string. * * @param command a command to execute on the command line, as a list of strings (the command, * then its arguments) * @return all the output of the command */ public static String backticks(List<String> command) { ProcessBuilder pb = new ProcessBuilder(command); pb.redirectErrorStream(true); // TimeLimitProcess p = new TimeLimitProcess(pb.start(), TIMEOUT_SEC * 1000); try { Process p = pb.start(); @SuppressWarnings("nullness") // didn't redirect stream, so getter returns non-null String output = UtilPlume.streamString(p.getInputStream()); return output; } catch (IOException e) { return "IOException: " + e.getMessage(); } } /////////////////////////////////////////////////////////////////////////// /// Properties /// /** * Determines whether a property has value "true", "yes", or "1". * * @see Properties#getProperty * @param p a Properties object in which to look up the property * @param key name of the property to look up * @return true iff the property has value "true", "yes", or "1" */ @SuppressWarnings({"purity", "lock"}) // does not depend on object identity /*@Pure*/ public static boolean propertyIsTrue(Properties p, String key) { String pvalue = p.getProperty(key); if (pvalue == null) { return false; } pvalue = pvalue.toLowerCase(); return (pvalue.equals("true") || pvalue.equals("yes") || pvalue.equals("1")); } /** * Set the property to its previous value concatenated to the given value. Return the previous * value. * * @param p a Properties object in which to look up the property * @param key name of the property to look up * @param value value to concatenate to the previous value of the property * @return the previous value of the property * @see Properties#getProperty * @see Properties#setProperty */ public static /*@Nullable*/ String appendProperty(Properties p, String key, String value) { return (String) p.setProperty(key, p.getProperty(key, "") + value); } /** * Set the property only if it was not previously set. * * @see Properties#getProperty * @see Properties#setProperty * @param p a Properties object in which to look up the property * @param key name of the property to look up * @param value value to set the property to, if it is not already set * @return the previous value of the property */ public static /*@Nullable*/ String setDefaultMaybe(Properties p, String key, String value) { String currentValue = p.getProperty(key); if (currentValue == null) { p.setProperty(key, value); } return currentValue; } /////////////////////////////////////////////////////////////////////////// /// Regexp (regular expression) /// // See RegexUtil class. /////////////////////////////////////////////////////////////////////////// /// Reflection /// // TODO: add method invokeMethod; see // java/Translation/src/graph/tests/Reflect.java (but handle returning a // value). // TODO: make this restore the access to its original value, such as private? /** * Sets the given field, which may be final and/or private. Leaves the field accessible. Intended * for use in readObject and nowhere else! * * @param o object in which to set the field * @param fieldName name of field to set * @param value new value of field * @throws NoSuchFieldException if the field does not exist in the object */ public static void setFinalField(Object o, String fieldName, /*@Nullable*/ Object value) throws NoSuchFieldException { Class<?> c = o.getClass(); while (c != Object.class) { // Class is interned // System.out.printf ("Setting field %s in %s%n", fieldName, c); try { Field f = c.getDeclaredField(fieldName); f.setAccessible(true); f.set(o, value); return; } catch (NoSuchFieldException e) { if (c.getSuperclass() == Object.class) { // Class is interned throw e; } } catch (IllegalAccessException e) { throw new Error("This can't happen: " + e); } c = c.getSuperclass(); assert c != null : "@AssumeAssertion(nullness): c was not Object, so is not null now"; } throw new NoSuchFieldException(fieldName); } // TODO: make this restore the access to its original value, such as private? /** * Reads the given field, which may be private. Leaves the field accessible. Use with care! * * @param o object in which to set the field * @param fieldName name of field to set * @return new value of field * @throws NoSuchFieldException if the field does not exist in the object */ public static /*@Nullable*/ Object getPrivateField(Object o, String fieldName) throws NoSuchFieldException { Class<?> c = o.getClass(); while (c != Object.class) { // Class is interned // System.out.printf ("Setting field %s in %s%n", fieldName, c); try { Field f = c.getDeclaredField(fieldName); f.setAccessible(true); return f.get(o); } catch (IllegalAccessException e) { System.out.println("in getPrivateField, IllegalAccessException: " + e); throw new Error("This can't happen: " + e); } catch (NoSuchFieldException e) { if (c.getSuperclass() == Object.class) { // Class is interned throw e; } // nothing to do; will now examine superclass } c = c.getSuperclass(); assert c != null : "@AssumeAssertion(nullness): c was not Object, so is not null now"; } throw new NoSuchFieldException(fieldName); } /** * Returns the least upper bound of the given classes. * * @param a a class * @param b a class * @return the least upper bound of the two classes, or null if both are null */ public static <T> /*@Nullable*/ Class<T> leastUpperBound( /*@Nullable*/ Class<T> a, /*@Nullable*/ Class<T> b) { if (a == b) { return a; } else if (a == null) { return b; } else if (b == null) { return a; } else if (a == Void.TYPE) { return b; } else if (b == Void.TYPE) { return a; } else if (a.isAssignableFrom(b)) { return a; } else if (b.isAssignableFrom(a)) { return b; } else { // There may not be a unique least upper bound. // Probably return some specific class rather than a wildcard. throw new Error("Not yet implemented"); } } /** * Returns the least upper bound of all the given classes. * * @param classes a non-empty list of classes * @return the least upper bound of all the given classes */ public static <T> /*@Nullable*/ Class<T> leastUpperBound(/*@Nullable*/ Class<T>[] classes) { Class<T> result = null; for (Class<T> clazz : classes) { result = leastUpperBound(result, clazz); } return result; } /** * Returns the least upper bound of the classes of the given objects. * * @param objects a list of objects * @return the least upper bound of the classes of the given objects, or null if all arguments are * null */ public static <T> /*@Nullable*/ Class<T> leastUpperBound(/*@PolyNull*/ Object[] objects) { Class<T> result = null; for (Object obj : objects) { if (obj != null) { result = leastUpperBound(result, (Class<T>) obj.getClass()); } } return result; } /** * Returns the least upper bound of the classes of the given objects. * * @param objects a non-empty list of objects * @return the least upper bound of the classes of the given objects, or null if all arguments are * null */ public static <T> /*@Nullable*/ Class<T> leastUpperBound( List<? extends /*@Nullable*/ Object> objects) { Class<T> result = null; for (Object obj : objects) { if (obj != null) { result = leastUpperBound(result, (Class<T>) obj.getClass()); } } return result; } /////////////////////////////////////////////////////////////////////////// /// Set /// /** * Return the object in this set that is equal to key. The Set abstraction doesn't provide this; * it only provides "contains". Returns null if the argument is null, or if it isn't in the set. * * @param set a set in which to look up the value * @param key the value to look up in the set * @return the object in this set that is equal to key, or null */ public static /*@Nullable*/ Object getFromSet(Set<?> set, Object key) { if (key == null) { return null; } for (Object elt : set) { if (key.equals(elt)) { return elt; } } return null; } /////////////////////////////////////////////////////////////////////////// /// Stream /// /** * Copy the contents of the input stream to the output stream. * * @param from input stream * @param to output stream */ public static void streamCopy(InputStream from, OutputStream to) { byte[] buffer = new byte[1024]; int bytes; try { while (true) { bytes = from.read(buffer); if (bytes == -1) { return; } to.write(buffer, 0, bytes); } } catch (IOException e) { e.printStackTrace(); throw new Error(e); } } /** * Return a String containing all the characters from the input stream. * * @param is input stream to read * @return a String containing all the characters from the input stream */ public static String streamString(InputStream is) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); streamCopy(is, baos); return baos.toString(); } /** * Reads all lines from the stream and returns them in a {@code List<String>}. * * @param stream the stream to read from * @return the list of lines read from the stream * @throws IOException if there is an error reading from the stream */ public static List<String> streamLines(InputStream stream) throws IOException { List<String> outputLines = new ArrayList<>(); try (BufferedReader rdr = new BufferedReader(new InputStreamReader(stream, UTF_8))) { String line; while ((line = rdr.readLine()) != null) { outputLines.add(line); } } return outputLines; } /////////////////////////////////////////////////////////////////////////// /// String /// /** * Return a new string which is the text of target with all instances of oldStr replaced by * newStr. * * @param target the string to do replacement in * @param oldStr the substring to replace * @param newStr the replacement * @return target with all instances of oldStr replaced by newStr */ public static String replaceString(String target, String oldStr, String newStr) { if (oldStr.equals("")) { throw new IllegalArgumentException(); } StringBuilder result = new StringBuilder(); /*@IndexOrHigh("target")*/ int lastend = 0; int pos; while ((pos = target.indexOf(oldStr, lastend)) != -1) { result.append(target.substring(lastend, pos)); result.append(newStr); lastend = pos + oldStr.length(); } result.append(target.substring(lastend)); return result.toString(); } /** * Return an array of Strings representing the characters between successive instances of the * delimiter character. Always returns an array of length at least 1 (it might contain only the * empty string). * * @see #split(String s, String delim) * @param s the string to split * @param delim delimiter to split the string on * @return array of length at least 1, containing s split on delimiter */ public static String[] split(String s, char delim) { ArrayList<String> result_list = new ArrayList<String>(); for (int delimpos = s.indexOf(delim); delimpos != -1; delimpos = s.indexOf(delim)) { result_list.add(s.substring(0, delimpos)); s = s.substring(delimpos + 1); } result_list.add(s); String[] result = result_list.toArray(new /*@NonNull*/ String[result_list.size()]); return result; } /** * Return an array of Strings representing the characters between successive instances of the * delimiter String. Always returns an array of length at least 1 (it might contain only the empty * string). * * @see #split(String s, char delim) * @param s the string to split * @param delim delimiter to split the string on * @return array of length at least 1, containing s split on delimiter */ public static String[] split(String s, String delim) { int delimlen = delim.length(); if (delimlen == 0) { throw new Error("Second argument to split was empty."); } ArrayList<String> result_list = new ArrayList<String>(); for (int delimpos = s.indexOf(delim); delimpos != -1; delimpos = s.indexOf(delim)) { result_list.add(s.substring(0, delimpos)); s = s.substring(delimpos + delimlen); } result_list.add(s); @SuppressWarnings("index") // index checker has no list support: vectors String[] result = result_list.toArray(new /*@NonNull*/ String[result_list.size()]); return result; } /** * Return an array of Strings, one for each line in the argument. Always returns an array of * length at least 1 (it might contain only the empty string). All common line separators (cr, lf, * cr-lf, or lf-cr) are supported. Note that a string that ends with a line separator will return * an empty string as the last element of the array. * * @see #split(String s, char delim) * @param s the string to split * @return an array of Strings, one for each line in the argument */ /*@SideEffectFree*/ /*@StaticallyExecutable*/ public static String[] splitLines(String s) { return s.split("\r\n?|\n\r?", -1); } /** * Concatenate the string representations of the array elements, placing the delimiter between * them. * * <p>If you are using Java 8 or later, then use the {@code String.join()} method instead. * * @see org.plumelib.util.ArraysPlume#toString(int[]) * @param a array of values to concatenate * @param delim delimiter to place between printed representations * @return the concatenation of the string representations of the values, with the delimiter * between */ public static String join(Object[] a, String delim) { if (a.length == 0) { return ""; } if (a.length == 1) { return String.valueOf(a[0]); } StringBuilder sb = new StringBuilder(String.valueOf(a[0])); for (int i = 1; i < a.length; i++) { sb.append(delim).append(a[i]); } return sb.toString(); } /** * Concatenate the string representations of the objects, placing the system-specific line * separator between them. * * @see org.plumelib.util.ArraysPlume#toString(int[]) * @param a array of values to concatenate * @return the concatenation of the string representations of the values, each on its own line */ public static String joinLines(Object... a) { return join(a, lineSep); } /** * Concatenate the string representations of the objects, placing the delimiter between them. * * @see java.util.AbstractCollection#toString() * @param v collection of values to concatenate * @param delim delimiter to place between printed representations * @return the concatenation of the string representations of the values, with the delimiter * between */ public static String join(Iterable<? extends Object> v, String delim) { StringBuilder sb = new StringBuilder(); boolean first = true; Iterator<?> itor = v.iterator(); while (itor.hasNext()) { if (first) { first = false; } else { sb.append(delim); } sb.append(itor.next()); } return sb.toString(); } /** * Concatenate the string representations of the objects, placing the system-specific line * separator between them. * * @see java.util.AbstractCollection#toString() * @param v list of values to concatenate * @return the concatenation of the string representations of the values, each on its own line */ public static String joinLines(List<String> v) { return join(v, lineSep); } /** * Escape \, ", newline, and carriage-return characters in the target as \\, \", \n, and \r; * return a new string if any modifications were necessary. The intent is that by surrounding the * return value with double quote marks, the result will be a Java string literal denoting the * original string. * * @param orig string to quote * @return quoted version of orig */ public static String escapeNonJava(String orig) { StringBuilder sb = new StringBuilder(); // The previous escape character was seen right before this position. /*@IndexOrHigh("orig")*/ int post_esc = 0; int orig_len = orig.length(); for (int i = 0; i < orig_len; i++) { char c = orig.charAt(i); switch (c) { case '\"': case '\\': if (post_esc < i) { sb.append(orig.substring(post_esc, i)); } sb.append('\\'); post_esc = i; break; case '\n': // not lineSep if (post_esc < i) { sb.append(orig.substring(post_esc, i)); } sb.append("\\n"); // not lineSep post_esc = i + 1; break; case '\r': if (post_esc < i) { sb.append(orig.substring(post_esc, i)); } sb.append("\\r"); post_esc = i + 1; break; default: // Nothing to do: i gets incremented } } if (sb.length() == 0) { return orig; } sb.append(orig.substring(post_esc)); return sb.toString(); } // The overhead of this is too high to call in escapeNonJava(String), so // it is inlined there. /** * Like {@link #escapeNonJava(String)}, but for a single character. * * @param ch character to quote * @return quoted version och ch */ public static String escapeNonJava(Character ch) { char c = ch.charValue(); switch (c) { case '\"': return "\\\""; case '\\': return "\\\\"; case '\n': // not lineSep return "\\n"; // not lineSep case '\r': return "\\r"; default: return new String(new char[] {c}); } } /** * Escape unprintable characters in the target, following the usual Java backslash conventions, so * that the result is sure to be printable ASCII. Returns a new string. * * @param orig string to quote * @return quoted version of orig */ public static String escapeNonASCII(String orig) { StringBuilder sb = new StringBuilder(); int orig_len = orig.length(); for (int i = 0; i < orig_len; i++) { char c = orig.charAt(i); sb.append(escapeNonASCII(c)); } return sb.toString(); } /** * Like escapeNonJava(), but quote more characters so that the result is sure to be printable * ASCII. * * <p>This implementatino is not particularly optimized. * * @param c character to quote * @return quoted version of c */ private static String escapeNonASCII(char c) { if (c == '"') { return "\\\""; } else if (c == '\\') { return "\\\\"; } else if (c == '\n') { // not lineSep return "\\n"; // not lineSep } else if (c == '\r') { return "\\r"; } else if (c == '\t') { return "\\t"; } else if (c >= ' ' && c <= '~') { return new String(new char[] {c}); } else if (c < 256) { String octal = Integer.toOctalString(c); while (octal.length() < 3) { octal = '0' + octal; } return "\\" + octal; } else { String hex = Integer.toHexString(c); while (hex.length() < 4) { hex = "0" + hex; } return "\\u" + hex; } } /** * Replace "\\", "\"", "\n", and "\r" sequences by their one-character equivalents. All other * backslashes are removed (for instance, octal/hex escape sequences are not turned into their * respective characters). This is the inverse operation of escapeNonJava(). Previously known as * unquote(). * * @param orig string to quoto * @return quoted version of orig */ public static String unescapeNonJava(String orig) { StringBuilder sb = new StringBuilder(); // The previous escape character was seen just before this position. /*@LTEqLengthOf("orig")*/ int post_esc = 0; int this_esc = orig.indexOf('\\'); while (this_esc != -1) { if (this_esc == orig.length() - 1) { sb.append(orig.substring(post_esc, this_esc + 1)); post_esc = this_esc + 1; break; } switch (orig.charAt(this_esc + 1)) { case 'n': sb.append(orig.substring(post_esc, this_esc)); sb.append('\n'); // not lineSep post_esc = this_esc + 2; break; case 'r': sb.append(orig.substring(post_esc, this_esc)); sb.append('\r'); post_esc = this_esc + 2; break; case '\\': // This is not in the default case because the search would find // the quoted backslash. Here we incluce the first backslash in // the output, but not the first. sb.append(orig.substring(post_esc, this_esc + 1)); post_esc = this_esc + 2; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': sb.append(orig.substring(post_esc, this_esc)); char octal_char = 0; int ii = this_esc + 1; while (ii < orig.length()) { char ch = orig.charAt(ii++); if ((ch < '0') || (ch > '8')) { break; } octal_char = (char) ((octal_char * 8) + Character.digit(ch, 8)); } sb.append(octal_char); post_esc = ii - 1; break; default: // In the default case, retain the character following the backslash, // but discard the backslash itself. "\*" is just a one-character string. sb.append(orig.substring(post_esc, this_esc)); post_esc = this_esc + 1; break; } this_esc = orig.indexOf('\\', post_esc); } if (post_esc == 0) { return orig; } sb.append(orig.substring(post_esc)); return sb.toString(); } /** * Remove all whitespace before or after instances of delimiter. * * @param arg string to remove whitespace in * @param delimiter string to remove whitespace abutting * @return version of arg, with whitespace abutting delimiter removed */ public static String removeWhitespaceAround(String arg, String delimiter) { arg = removeWhitespaceBefore(arg, delimiter); arg = removeWhitespaceAfter(arg, delimiter); return arg; } /** * Remove all whitespace after instances of delimiter. * * @param arg string to remove whitespace in * @param delimiter string to remove whitespace after * @return version of arg, with whitespace after delimiter removed */ public static String removeWhitespaceAfter(String arg, String delimiter) { if (delimiter == null || delimiter.equals("")) { throw new IllegalArgumentException("Bad delimiter: \"" + delimiter + "\""); } // String orig = arg; int delim_len = delimiter.length(); int delim_index = arg.indexOf(delimiter); while (delim_index > -1) { int non_ws_index = delim_index + delim_len; while ((non_ws_index < arg.length()) && (Character.isWhitespace(arg.charAt(non_ws_index)))) { non_ws_index++; } // if (non_ws_index == arg.length()) { // System.out.println("No nonspace character at end of: " + arg); // } else { // System.out.println("'" + arg.charAt(non_ws_index) + "' not a space character at " + // non_ws_index + " in: " + arg); // } if (non_ws_index != delim_index + delim_len) { arg = arg.substring(0, delim_index + delim_len) + arg.substring(non_ws_index); } delim_index = arg.indexOf(delimiter, delim_index + 1); } return arg; } /** * Remove all whitespace before instances of delimiter. * * @param arg string to remove whitespace in * @param delimiter string to remove whitespace before * @return version of arg, with whitespace before delimiter removed */ public static String removeWhitespaceBefore(String arg, String delimiter) { if (delimiter == null || delimiter.equals("")) { throw new IllegalArgumentException("Bad delimiter: \"" + delimiter + "\""); } // System.out.println("removeWhitespaceBefore(\"" + arg + "\", \"" + delimiter + "\")"); // String orig = arg; int delim_index = arg.indexOf(delimiter); while (delim_index > -1) { int non_ws_index = delim_index - 1; while ((non_ws_index >= 0) && (Character.isWhitespace(arg.charAt(non_ws_index)))) { non_ws_index--; } // if (non_ws_index == -1) { // System.out.println("No nonspace character at front of: " + arg); // } else { // System.out.println("'" + arg.charAt(non_ws_index) + "' not a space character at " + // non_ws_index + " in: " + arg); // } if (non_ws_index != delim_index - 1) { arg = arg.substring(0, non_ws_index + 1) + arg.substring(delim_index); } delim_index = arg.indexOf(delimiter, non_ws_index + 2); } return arg; } /** * Return either "n <em>noun</em>" or "n <em>noun</em>s" depending on n. Adds "es" to words ending * with "ch", "s", "sh", or "x". * * @param n count of nouns * @param noun word being counted * @return noun, if n==1; otherwise, pluralization of noun */ public static String nplural(int n, String noun) { if (n == 1) { return n + " " + noun; } else if (noun.endsWith("ch") || noun.endsWith("s") || noun.endsWith("sh") || noun.endsWith("x")) { return n + " " + noun + "es"; } else { return n + " " + noun + "s"; } } /** * Returns a string of the specified length, truncated if necessary, and padded with spaces to the * left if necessary. * * @param s string to truncate or pad * @param length goal length * @return s truncated or padded to length characters */ public static String lpad(String s, /*@NonNegative*/ int length) { if (s.length() < length) { StringBuilder buf = new StringBuilder(); for (int i = s.length(); i < length; i++) { buf.append(' '); } return buf.toString() + s; } else { return s.substring(0, length); } } /** * Returns a string of the specified length, truncated if necessary, and padded with spaces to the * right if necessary. * * @param s string to truncate or pad * @param length goal length * @return s truncated or padded to length characters */ public static String rpad(String s, /*@NonNegative*/ int length) { if (s.length() < length) { StringBuilder buf = new StringBuilder(s); for (int i = s.length(); i < length; i++) { buf.append(' '); } return buf.toString(); } else { return s.substring(0, length); } } /** * Converts the int to a String, then formats it using {@link #rpad(String,int)}. * * @param num int whose string representation to truncate or pad * @param length goal length * @return a string representation of num truncated or padded to length characters */ public static String rpad(int num, /*@NonNegative*/ int length) { return rpad(String.valueOf(num), length); } /** * Converts the double to a String, then formats it using {@link #rpad(String,int)}. * * @param num double whose string representation to truncate or pad * @param length goal length * @return a string representation of num truncated or padded to length characters */ public static String rpad(double num, /*@NonNegative*/ int length) { return rpad(String.valueOf(num), length); } /** * Same as built-in String comparison, but accept null arguments, and place them at the beginning. */ public static class NullableStringComparator implements Comparator<String>, Serializable { static final long serialVersionUID = 20150812L; /*@Pure*/ @Override public int compare(String s1, String s2) { if (s1 == null && s2 == null) { return 0; } if (s1 == null && s2 != null) { return 1; } if (s1 != null && s2 == null) { return -1; } return s1.compareTo(s2); } } // This could test the types of the elemets, and do something more sophisticated based on the // types. /** * Attempt to order Objects. Puts null at the beginning. Returns 0 for equal elements. Otherwise, * orders by the result of {@code toString()}. * * <p>Note: if toString returns a nondeterministic value, such as one that depends on the result * of {@code hashCode()}, then this comparator may yield different orderings from run to run of a * program. */ public static class ObjectComparator implements Comparator</*@Nullable*/ Object>, Serializable { static final long serialVersionUID = 20170420L; @SuppressWarnings({ "purity.not.deterministic.call", "lock" }) // toString is being used in a deterministic way /*@Pure*/ @Override public int compare(/*@Nullable*/ Object o1, /*@Nullable*/ Object o2) { // Make null compare smaller than anything else if ((o1 == o2)) { return 0; } if (o1 == null) { return -1; } if (o2 == null) { return 1; } if (o1.equals(o2)) { return 0; } // Don't compare output of hashCode() because it is non-deterministic from run to run. String s1 = o1.toString(); String s2 = o2.toString(); return s1.compareTo(s2); } } /** * Return the number of times the character appears in the string. * * @param s string to search in * @param ch character to search for * @return number of times the character appears in the string */ public static int count(String s, int ch) { int result = 0; int pos = s.indexOf(ch); while (pos > -1) { result++; pos = s.indexOf(ch, pos + 1); } return result; } /** * Return the number of times the second string appears in the first. * * @param s string to search in * @param sub non-empty string to search for * @return number of times the substring appears in the string */ public static int count(String s, String sub) { if (sub.equals("")) { throw new IllegalArgumentException("second argument must not be empty"); } int result = 0; int pos = s.indexOf(sub); while (pos > -1) { result++; pos = s.indexOf(sub, pos + 1); } return result; } /////////////////////////////////////////////////////////////////////////// /// StringTokenizer /// /** * Return a ArrayList of the Strings returned by {@link * java.util.StringTokenizer#StringTokenizer(String,String,boolean)} with the given arguments. * * <p>The static type is {@code ArrayList<Object>} because StringTokenizer extends {@code * Enumeration<Object>} instead of {@code Enumeration<String>} as it should (probably due to * backward-compatibility). * * @param str a string to be parsed * @param delim the delimiters * @param returnDelims flag indicating whether to return the delimiters as tokens * @return vector of strings resulting from tokenization */ public static ArrayList<Object> tokens(String str, String delim, boolean returnDelims) { return makeArrayList(new StringTokenizer(str, delim, returnDelims)); } /** * Return a ArrayList of the Strings returned by {@link * java.util.StringTokenizer#StringTokenizer(String,String)} with the given arguments. * * @param str a string to be parsed * @param delim the delimiters * @return vector of strings resulting from tokenization */ public static ArrayList<Object> tokens(String str, String delim) { return makeArrayList(new StringTokenizer(str, delim)); } /** * Return a ArrayList of the Strings returned by {@link * java.util.StringTokenizer#StringTokenizer(String)} with the given arguments. * * @param str a string to be parsed * @return vector of strings resulting from tokenization */ public static ArrayList<Object> tokens(String str) { return makeArrayList(new StringTokenizer(str)); } /////////////////////////////////////////////////////////////////////////// /// Throwable /// /** * Return a String representation of the backtrace of the given Throwable. To see a backtrace at * the the current location, do {@code backtrace(new Throwable())}. * * @param t the Throwable to obtain a backtrace of * @return a String representation of the backtrace of the given Throwable */ public static String backTrace(Throwable t) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); pw.close(); String result = sw.toString(); return result; } /////////////////////////////////////////////////////////////////////////// /// Collections /// /** * Return the sorted version of the list. Does not alter the list. Simply calls {@code * Collections.sort(List<T>, Comparator<? super T>)}. * * @return a sorted version of the list * @param <T> type of elements of the list * @param l a list to sort * @param c a sorted version of the list */ public static <T> List<T> sortList(List<T> l, Comparator<? super T> c) { List<T> result = new ArrayList<T>(l); Collections.sort(result, c); return result; } // This should perhaps be named withoutDuplicates to emphasize that // it does not side-effect its argument. /** * Return a copy of the list with duplicates removed. Retains the original order. * * @param <T> type of elements of the list * @param l a list to remove duplicates from * @return a copy of the list with duplicates removed */ public static <T> List<T> removeDuplicates(List<T> l) { HashSet<T> hs = new LinkedHashSet<T>(l); List<T> result = new ArrayList<T>(hs); return result; } /** All calls to deepEquals that are currently underway. */ private static HashSet<WeakIdentityPair<Object, Object>> deepEqualsUnderway = new HashSet<WeakIdentityPair<Object, Object>>(); /** * Determines deep equality for the elements. * * <ul> * <li>If both are primitive arrays, uses java.util.Arrays.equals. * <li>If both are Object[], uses java.util.Arrays.deepEquals and does not recursively call this * method. * <li>If both are lists, uses deepEquals recursively on each element. * <li>For other types, just uses equals() and does not recursively call this method. * </ul> * * @param o1 first value to compare * @param o2 second value to comare * @return true iff o1 and o2 are deeply equal */ @SuppressWarnings({"purity", "lock"}) // side effect to static field deepEqualsUnderway /*@Pure*/ public static boolean deepEquals(/*@Nullable*/ Object o1, /*@Nullable*/ Object o2) { @SuppressWarnings("interning") boolean sameObject = (o1 == o2); if (sameObject) { return true; } if (o1 == null || o2 == null) { return false; } if (o1 instanceof boolean[] && o2 instanceof boolean[]) { return Arrays.equals((boolean[]) o1, (boolean[]) o2); } if (o1 instanceof byte[] && o2 instanceof byte[]) { return Arrays.equals((byte[]) o1, (byte[]) o2); } if (o1 instanceof char[] && o2 instanceof char[]) { return Arrays.equals((char[]) o1, (char[]) o2); } if (o1 instanceof double[] && o2 instanceof double[]) { return Arrays.equals((double[]) o1, (double[]) o2); } if (o1 instanceof float[] && o2 instanceof float[]) { return Arrays.equals((float[]) o1, (float[]) o2); } if (o1 instanceof int[] && o2 instanceof int[]) { return Arrays.equals((int[]) o1, (int[]) o2); } if (o1 instanceof long[] && o2 instanceof long[]) { return Arrays.equals((long[]) o1, (long[]) o2); } if (o1 instanceof short[] && o2 instanceof short[]) { return Arrays.equals((short[]) o1, (short[]) o2); } @SuppressWarnings({"purity", "lock"}) // creates local state WeakIdentityPair<Object, Object> mypair = new WeakIdentityPair<Object, Object>(o1, o2); if (deepEqualsUnderway.contains(mypair)) { return true; } if (o1 instanceof Object[] && o2 instanceof Object[]) { return Arrays.deepEquals((Object[]) o1, (Object[]) o2); } if (o1 instanceof List<?> && o2 instanceof List<?>) { List<?> l1 = (List<?>) o1; List<?> l2 = (List<?>) o2; if (l1.size() != l2.size()) { return false; } try { deepEqualsUnderway.add(mypair); for (int i = 0; i < l1.size(); i++) { Object e1 = l1.get(i); Object e2 = l2.get(i); if (!deepEquals(e1, e2)) { return false; } } } finally { deepEqualsUnderway.remove(mypair); } return true; } return o1.equals(o2); } /////////////////////////////////////////////////////////////////////////// /// ArrayList /// /** * Returns a vector containing the elements of the enumeration. * * @param <T> type of the enumeration and vector elements * @param e an enumeration to convert to a ArrayList * @return a vector containing the elements of the enumeration */ public static <T> ArrayList<T> makeArrayList(Enumeration<T> e) { ArrayList<T> result = new ArrayList<T>(); while (e.hasMoreElements()) { result.add(e.nextElement()); } return result; } // Rather than writing something like ArrayListToStringArray, use // v.toArray(new String[0]) /** * Returns a list of lists of each combination (with repetition, but not permutations) of the * specified objects starting at index {@code start} over {@code dims} dimensions, for {@code dims * > 0}. * * <p>For example, create_combinations (1, 0, {a, b, c}) returns: * * <pre> * {a}, {b}, {c} * </pre> * * And create_combinations (2, 0, {a, b, c}) returns: * * <pre> * {a, a}, {a, b}, {a, c} * {b, b}, {b, c}, * {c, c} * </pre> * * @param <T> type of the input list elements, and type of the innermost output list elements * @param dims number of dimensions: that is, size of each innermost list * @param start initial index * @param objs list of elements to create combinations of * @return list of lists of length dims, each of which combines elements from objs */ public static <T> List<List<T>> create_combinations( int dims, /*@NonNegative*/ int start, List<T> objs) { if (dims < 1) { throw new IllegalArgumentException(); } List<List<T>> results = new ArrayList<List<T>>(); for (int i = start; i < objs.size(); i++) { if (dims == 1) { List<T> simple = new ArrayList<T>(); simple.add(objs.get(i)); results.add(simple); } else { List<List<T>> combos = create_combinations(dims - 1, i, objs); for (List<T> lt : combos) { List<T> simple = new ArrayList<T>(); simple.add(objs.get(i)); simple.addAll(lt); results.add(simple); } } } return (results); } /** * Returns a list of lists of each combination (with repetition, but not permutations) of integers * from start to cnt (inclusive) over arity dimensions. * * <p>For example, create_combinations (1, 0, 2) returns: * * <pre> * {0}, {1}, {2} * </pre> * * And create_combinations (2, 10, 2) returns: * * <pre> * {10, 10}, {10, 11}, {10, 12} * {11, 11} {11, 12}, * {12, 12} * </pre> * * @param arity size of each innermost list * @param start initial value * @param cnt maximum element value * @return list of lists of length arity, each of which combines integers from start to cnt */ public static ArrayList<ArrayList<Integer>> create_combinations( int arity, /*@NonNegative*/ int start, int cnt) { ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>(); // Return a list with one zero length element if arity is zero if (arity == 0) { results.add(new ArrayList<Integer>()); return (results); } for (int i = start; i <= cnt; i++) { ArrayList<ArrayList<Integer>> combos = create_combinations(arity - 1, i, cnt); for (ArrayList<Integer> li : combos) { ArrayList<Integer> simple = new ArrayList<Integer>(); simple.add(i); simple.addAll(li); results.add(simple); } } return (results); } /** * Returns the simple unqualified class name that corresponds to the specified fully qualified * name. For example, if qualified_name is java.lang.String, String will be returned. * * @deprecated use {@link #fullyQualifiedNameToSimpleName} instead. * @param qualified_name the fully-qualified name of a class * @return the simple unqualified name of the class */ @Deprecated public static /*@ClassGetSimpleName*/ String unqualified_name( /*@FullyQualifiedName*/ String qualified_name) { return fullyQualifiedNameToSimpleName(qualified_name); } /** * Returns the simple unqualified class name that corresponds to the specified fully qualified * name. For example, if qualified_name is java.lang.String, String will be returned. * * @param qualified_name the fully-qualified name of a class * @return the simple unqualified name of the class */ // TODO: does not follow the specification for inner classes (where the // type name should be empty), but I think this is more informative anyway. @SuppressWarnings("signature") // string conversion public static /*@ClassGetSimpleName*/ String fullyQualifiedNameToSimpleName( /*@FullyQualifiedName*/ String qualified_name) { int offset = qualified_name.lastIndexOf('.'); if (offset == -1) { return (qualified_name); } return (qualified_name.substring(offset + 1)); } /** * Returns the simple unqualified class name that corresponds to the specified class. For example * if qualified name of the class is java.lang.String, String will be returned. * * @deprecated use {@link Class#getSimpleName()} instead. * @param cls a class * @return the simple unqualified name of the class */ @Deprecated public static /*@ClassGetSimpleName*/ String unqualified_name(Class<?> cls) { return cls.getSimpleName(); } /** * Convert a number into an abbreviation such as "5.00K" for 5000 or "65.0M" for 65000000. K * stands for 1000, not 1024; M stands for 1000000, not 1048576, etc. There are always exactly 3 * decimal digits of precision in the result (counting both sides of the decimal point). * * @param val a numeric value * @return an abbreviated string representation of the value */ public static String abbreviateNumber(long val) { double dval = (double) val; String mag = ""; if (val < 1000) { // nothing to do } else if (val < 1000000) { dval = val / 1000.0; mag = "K"; } else if (val < 1000000000) { dval = val / 1000000.0; mag = "M"; } else { dval = val / 1000000000.0; mag = "G"; } String precision = "0"; if (dval < 10) { precision = "2"; } else if (dval < 100) { precision = "1"; } @SuppressWarnings("formatter") // format string computed from precision and mag String result = String.format("%,1." + precision + "f" + mag, dval); return result; } }
src/main/java/org/plumelib/util/UtilPlume.java
// If you edit this file, you must also edit its tests. // For tests of this and the entire plume package, see class TestPlume. package org.plumelib.util; import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.file.StandardOpenOption.APPEND; import static java.nio.file.StandardOpenOption.CREATE; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.Serializable; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Properties; import java.util.Random; import java.util.Set; import java.util.StringTokenizer; import java.util.concurrent.atomic.AtomicBoolean; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /*>>> import org.checkerframework.checker.index.qual.*; import org.checkerframework.checker.lock.qual.*; import org.checkerframework.checker.nullness.qual.*; import org.checkerframework.checker.regex.qual.*; import org.checkerframework.checker.signature.qual.*; import org.checkerframework.common.value.qual.*; import org.checkerframework.dataflow.qual.*; */ /** Utility functions that do not belong elsewhere in the plume package. */ public final class UtilPlume { /** This class is a collection of methods; it does not represent anything. */ private UtilPlume() { throw new Error("do not instantiate"); } private static final String lineSep = System.getProperty("line.separator"); /////////////////////////////////////////////////////////////////////////// /// Array /// // For arrays, see ArraysPlume.java. /////////////////////////////////////////////////////////////////////////// /// BitSet /// /** * Returns true if the cardinality of the intersection of the two BitSets is at least the given * value. * * @param a the first BitSet to intersect * @param b the second BitSet to intersect * @param i the cardinality bound * @return true iff size(a intersect b) &ge; i */ @SuppressWarnings({"purity", "lock"}) // side effect to local state (BitSet) /*@Pure*/ public static boolean intersectionCardinalityAtLeast(BitSet a, BitSet b, /*@NonNegative*/ int i) { // Here are three implementation strategies to determine the // cardinality of the intersection: // 1. a.clone().and(b).cardinality() // 2. do the above, but copy only a subset of the bits initially -- enough // that it should exceed the given number -- and if that fails, do the // whole thing. Unfortunately, bits.get(int, int) isn't optimized // for the case where the indices line up, so I'm not sure at what // point this approach begins to dominate #1. // 3. iterate through both sets with nextSetBit() int size = Math.min(a.length(), b.length()); if (size > 10 * i) { // The size is more than 10 times the limit. So first try processing // just a subset of the bits (4 times the limit). BitSet intersection = a.get(0, 4 * i); intersection.and(b); if (intersection.cardinality() >= i) { return true; } } return (intersectionCardinality(a, b) >= i); } /** * Returns true if the cardinality of the intersection of the three BitSets is at least the given * value. * * @param a the first BitSet to intersect * @param b the second BitSet to intersect * @param c the third BitSet to intersect * @param i the cardinality bound * @return true iff size(a intersect b intersect c) &ge; i */ @SuppressWarnings({"purity", "lock"}) // side effect to local state (BitSet) /*@Pure*/ public static boolean intersectionCardinalityAtLeast( BitSet a, BitSet b, BitSet c, /*@NonNegative*/ int i) { // See comments in intersectionCardinalityAtLeast(BitSet, BitSet, int). // This is a copy of that. int size = Math.min(a.length(), b.length()); size = Math.min(size, c.length()); if (size > 10 * i) { // The size is more than 10 times the limit. So first try processing // just a subset of the bits (4 times the limit). BitSet intersection = a.get(0, 4 * i); intersection.and(b); intersection.and(c); if (intersection.cardinality() >= i) { return true; } } return (intersectionCardinality(a, b, c) >= i); } /** * Returns the cardinality of the intersection of the two BitSets. * * @param a the first BitSet to intersect * @param b the second BitSet to intersect * @return size(a intersect b) */ @SuppressWarnings({"purity", "lock"}) // side effect to local state (BitSet) /*@Pure*/ public static int intersectionCardinality(BitSet a, BitSet b) { BitSet intersection = (BitSet) a.clone(); intersection.and(b); return intersection.cardinality(); } /** * Returns the cardinality of the intersection of the three BitSets. * * @param a the first BitSet to intersect * @param b the second BitSet to intersect * @param c the third BitSet to intersect * @return size(a intersect b intersect c) */ @SuppressWarnings({"purity", "lock"}) // side effect to local state (BitSet) /*@Pure*/ public static int intersectionCardinality(BitSet a, BitSet b, BitSet c) { BitSet intersection = (BitSet) a.clone(); intersection.and(b); intersection.and(c); return intersection.cardinality(); } /////////////////////////////////////////////////////////////////////////// /// BufferedFileReader /// // Convenience methods for creating InputStreams, Readers, BufferedReaders, and LineNumberReaders. /** * Returns an InputStream for the file, accounting for the possibility that the file is * compressed. (A file whose name ends with ".gz" is treated as compressed.) * * <p>Warning: The "gzip" program writes and reads files containing concatenated gzip files. As of * Java 1.4, Java reads just the first one: it silently discards all characters (including gzipped * files) after the first gzipped file. * * @param file the possibly-compressed file to read * @return an InputStream for file * @throws IOException if there is trouble reading the file */ public static InputStream fileInputStream(File file) throws IOException { InputStream in; if (file.getName().endsWith(".gz")) { try { in = new GZIPInputStream(new FileInputStream(file)); } catch (IOException e) { throw new IOException("Problem while reading " + file, e); } } else { in = new FileInputStream(file); } return in; } /** * Returns a Reader for the file, accounting for the possibility that the file is compressed. (A * file whose name ends with ".gz" is treated as compressed.) * * <p>Warning: The "gzip" program writes and reads files containing concatenated gzip files. As of * Java 1.4, Java reads just the first one: it silently discards all characters (including gzipped * files) after the first gzipped file. * * @param filename the possibly-compressed file to read * @return an InputStream for filename * @throws IOException if there is trouble reading the file * @throws FileNotFoundException if the file is not found */ public static InputStreamReader fileReader(String filename) throws FileNotFoundException, IOException { // return fileReader(filename, "ISO-8859-1"); return fileReader(new File(filename), null); } /** * Returns a Reader for the file, accounting for the possibility that the file is compressed. (A * file whose name ends with ".gz" is treated as compressed.) * * <p>Warning: The "gzip" program writes and reads files containing concatenated gzip files. As of * Java 1.4, Java reads just the first one: it silently discards all characters (including gzipped * files) after the first gzipped file. * * @param file the possibly-compressed file to read * @return an InputStreamReader for file * @throws FileNotFoundException if the file cannot be found * @throws IOException if there is trouble reading the file */ public static InputStreamReader fileReader(File file) throws FileNotFoundException, IOException { return fileReader(file, null); } /** * Returns a Reader for the file, accounting for the possibility that the file is compressed. (A * file whose name ends with ".gz" is treated as compressed.) * * <p>Warning: The "gzip" program writes and reads files containing concatenated gzip files. As of * Java 1.4, Java reads just the first one: it silently discards all characters (including gzipped * files) after the first gzipped file. * * @param file the possibly-compressed file to read * @param charsetName null, or the name of a Charset to use when reading the file * @return an InputStreamReader for file * @throws FileNotFoundException if the file cannot be found * @throws IOException if there is trouble reading the file */ public static InputStreamReader fileReader(File file, /*@Nullable*/ String charsetName) throws FileNotFoundException, IOException { InputStream in = new FileInputStream(file); InputStreamReader file_reader; if (charsetName == null) { file_reader = new InputStreamReader(in, UTF_8); } else { file_reader = new InputStreamReader(in, charsetName); } return file_reader; } /** * Returns a BufferedReader for the file, accounting for the possibility that the file is * compressed. (A file whose name ends with ".gz" is treated as compressed.) * * <p>Warning: The "gzip" program writes and reads files containing concatenated gzip files. As of * Java 1.4, Java reads just the first one: it silently discards all characters (including gzipped * files) after the first gzipped file. * * @param filename the possibly-compressed file to read * @return a BufferedReader for file * @throws FileNotFoundException if the file cannot be found * @throws IOException if there is trouble reading the file */ public static BufferedReader bufferedFileReader(String filename) throws FileNotFoundException, IOException { return bufferedFileReader(new File(filename)); } /** * Returns a BufferedReader for the file, accounting for the possibility that the file is * compressed. (A file whose name ends with ".gz" is treated as compressed.) * * <p>Warning: The "gzip" program writes and reads files containing concatenated gzip files. As of * Java 1.4, Java reads just the first one: it silently discards all characters (including gzipped * files) after the first gzipped file. * * @param file the possibility-compressed file to read * @return a BufferedReader for file * @throws FileNotFoundException if the file cannot be found * @throws IOException if there is trouble reading the file */ public static BufferedReader bufferedFileReader(File file) throws FileNotFoundException, IOException { return (bufferedFileReader(file, null)); } /** * Returns a BufferedReader for the file, accounting for the possibility that the file is * compressed. (A file whose name ends with ".gz" is treated as compressed.) * * <p>Warning: The "gzip" program writes and reads files containing concatenated gzip files. As of * Java 1.4, Java reads just the first one: it silently discards all characters (including gzipped * files) after the first gzipped file. * * @param filename the possibly-compressed file to read * @param charsetName the character set to use when reading the file * @return a BufferedReader for filename * @throws FileNotFoundException if the file cannot be found * @throws IOException if there is trouble reading the file */ public static BufferedReader bufferedFileReader(String filename, /*@Nullable*/ String charsetName) throws FileNotFoundException, IOException { return bufferedFileReader(new File(filename), charsetName); } /** * Returns a BufferedReader for the file, accounting for the possibility that the file is * compressed. (A file whose name ends with ".gz" is treated as compressed.) * * <p>Warning: The "gzip" program writes and reads files containing concatenated gzip files. As of * Java 1.4, Java reads just the first one: it silently discards all characters (including gzipped * files) after the first gzipped file. * * @param file the possibly-compressed file to read * @param charsetName the character set to use when reading the file * @return a BufferedReader for file * @throws FileNotFoundException if the file cannot be found * @throws IOException if there is trouble reading the file */ public static BufferedReader bufferedFileReader(File file, /*@Nullable*/ String charsetName) throws FileNotFoundException, IOException { Reader file_reader = fileReader(file, charsetName); return new BufferedReader(file_reader); } /** * Returns a LineNumberReader for the file, accounting for the possibility that the file is * compressed. (A file whose name ends with ".gz" is treated as compressed.) * * <p>Warning: The "gzip" program writes and reads files containing concatenated gzip files. As of * Java 1.4, Java reads just the first one: it silently discards all characters (including gzipped * files) after the first gzipped file. * * @param filename the possibly-compressed file to read * @return a LineNumberReader for filename * @throws FileNotFoundException if the file cannot be found * @throws IOException if there is trouble reading the file */ public static LineNumberReader lineNumberFileReader(String filename) throws FileNotFoundException, IOException { return lineNumberFileReader(new File(filename)); } /** * Returns a LineNumberReader for the file, accounting for the possibility that the file is * compressed. (A file whose name ends with ".gz" is treated as compressed.) * * <p>Warning: The "gzip" program writes and reads files containing concatenated gzip files. As of * Java 1.4, Java reads just the first one: it silently discards all characters (including gzipped * files) after the first gzipped file. * * @param file the possibly-compressed file to read * @return a LineNumberReader for file * @throws FileNotFoundException if the file cannot be found * @throws IOException if there is trouble reading the file */ public static LineNumberReader lineNumberFileReader(File file) throws FileNotFoundException, IOException { Reader file_reader; if (file.getName().endsWith(".gz")) { try { file_reader = new InputStreamReader(new GZIPInputStream(new FileInputStream(file)), "ISO-8859-1"); } catch (IOException e) { throw new IOException("Problem while reading " + file, e); } } else { file_reader = new InputStreamReader(new FileInputStream(file), "ISO-8859-1"); } return new LineNumberReader(file_reader); } /** * Returns a BufferedWriter for the file, accounting for the possibility that the file is * compressed. (A file whose name ends with ".gz" is treated as compressed.) * * <p>Warning: The "gzip" program writes and reads files containing concatenated gzip files. As of * Java 1.4, Java reads just the first one: it silently discards all characters (including gzipped * files) after the first gzipped file. * * @param filename the possibly-compressed file to write * @return a BufferedWriter for filename * @throws IOException if there is trouble writing the file */ public static BufferedWriter bufferedFileWriter(String filename) throws IOException { return bufferedFileWriter(filename, false); } /** * Returns a BufferedWriter for the file, accounting for the possibility that the file is * compressed. (A file whose name ends with ".gz" is treated as compressed.) * * <p>Warning: The "gzip" program writes and reads files containing concatenated gzip files. As of * Java 1.4, Java reads just the first one: it silently discards all characters (including gzipped * files) after the first gzipped file. * * @param filename the possibly-compressed file to write * @param append if true, the resulting BufferedWriter appends to the end of the file instead of * the beginning * @return a BufferedWriter for filename * @throws IOException if there is trouble writing the file */ // Question: should this be rewritten as a wrapper around bufferedFileOutputStream? public static BufferedWriter bufferedFileWriter(String filename, boolean append) throws IOException { if (filename.endsWith(".gz")) { return new BufferedWriter( new OutputStreamWriter( new GZIPOutputStream(new FileOutputStream(filename, append)), UTF_8)); } else { return Files.newBufferedWriter( Paths.get(filename), UTF_8, append ? new StandardOpenOption[] {CREATE, APPEND} : new StandardOpenOption[] {CREATE}); } } /** * Returns a BufferedOutputStream for the file, accounting for the possibility that the file is * compressed. (A file whose name ends with ".gz" is treated as compressed.) * * <p>Warning: The "gzip" program writes and reads files containing concatenated gzip files. As of * Java 1.4, Java reads just the first one: it silently discards all characters (including gzipped * files) after the first gzipped file. * * @param filename the possibly-compressed file to write * @param append if true, the resulting BufferedOutputStream appends to the end of the file * instead of the beginning * @return a BufferedOutputStream for filename * @throws IOException if there is trouble writing the file */ public static BufferedOutputStream bufferedFileOutputStream(String filename, boolean append) throws IOException { OutputStream os = new FileOutputStream(filename, append); if (filename.endsWith(".gz")) { os = new GZIPOutputStream(os); } return new BufferedOutputStream(os); } /////////////////////////////////////////////////////////////////////////// /// Class /// /** * Return true iff sub is a subtype of sup. If sub == sup, then sub is considered a subtype of sub * and this method returns true. * * @param sub class to test for being a subtype * @param sup class to test for being a supertype * @return true iff sub is a subtype of sup */ /*@Pure*/ public static boolean isSubtype(Class<?> sub, Class<?> sup) { if (sub == sup) { return true; } // Handle superclasses Class<?> parent = sub.getSuperclass(); // If parent == null, sub == Object if ((parent != null) && (parent == sup || isSubtype(parent, sup))) { return true; } // Handle interfaces for (Class<?> ifc : sub.getInterfaces()) { if (ifc == sup || isSubtype(ifc, sup)) { return true; } } return false; } /** Used by {@link #classForName}. */ private static HashMap<String, Class<?>> primitiveClasses = new HashMap<String, Class<?>>(8); static { primitiveClasses.put("boolean", Boolean.TYPE); primitiveClasses.put("byte", Byte.TYPE); primitiveClasses.put("char", Character.TYPE); primitiveClasses.put("double", Double.TYPE); primitiveClasses.put("float", Float.TYPE); primitiveClasses.put("int", Integer.TYPE); primitiveClasses.put("long", Long.TYPE); primitiveClasses.put("short", Short.TYPE); } // TODO: should create a method that handles any ClassGetName (including // primitives), but not fully-qualified names. /** * Like {@link Class#forName(String)}, but also works when the string represents a primitive type * or a fully-qualified name (as opposed to a binary name). * * <p>If the given name can't be found, this method changes the last '.' to a dollar sign ($) and * tries again. This accounts for inner classes that are incorrectly passed in in fully-qualified * format instead of binary format. (It should try multiple dollar signs, not just at the last * position.) * * <p>Recall the rather odd specification for {@link Class#forName(String)}: the argument is a * binary name for non-arrays, but a field descriptor for arrays. This method uses the same rules, * but additionally handles primitive types and, for non-arrays, fully-qualified names. * * @param className name of the class * @return the Class corresponding to className * @throws ClassNotFoundException if the class is not found */ // The annotation encourages proper use, even though this can take a // fully-qualified name (only for a non-array). public static Class<?> classForName( /*@ClassGetName*/ String className) throws ClassNotFoundException { Class<?> result = primitiveClasses.get(className); if (result != null) { return result; } else { try { return Class.forName(className); } catch (ClassNotFoundException e) { int pos = className.lastIndexOf('.'); if (pos < 0) { throw e; } @SuppressWarnings("signature") // checked below & exception is handled /*@ClassGetName*/ String inner_name = className.substring(0, pos) + "$" + className.substring(pos + 1); try { return Class.forName(inner_name); } catch (ClassNotFoundException ee) { throw e; } } } } @Deprecated private static HashMap</*@SourceNameForNonArrayNonInner*/ String, /*@FieldDescriptor*/ String> primitiveClassesJvm = new HashMap</*@SourceNameForNonArrayNonInner*/ String, /*@FieldDescriptor*/ String>(8); static { primitiveClassesJvm.put("boolean", "Z"); primitiveClassesJvm.put("byte", "B"); primitiveClassesJvm.put("char", "C"); primitiveClassesJvm.put("double", "D"); primitiveClassesJvm.put("float", "F"); primitiveClassesJvm.put("int", "I"); primitiveClassesJvm.put("long", "J"); primitiveClassesJvm.put("short", "S"); } /** * Convert a binary name to a field descriptor. For example, convert "java.lang.Object[]" to * "[Ljava/lang/Object;" or "int" to "I". * * @param classname name of the class, in binary class name format * @return name of the class, in field descriptor format * @deprecated use version in org.plumelib.bcelutil instead */ @Deprecated @SuppressWarnings("signature") // conversion routine public static /*@FieldDescriptor*/ String binaryNameToFieldDescriptor( /*@BinaryName*/ String classname) { int dims = 0; String sans_array = classname; while (sans_array.endsWith("[]")) { dims++; sans_array = sans_array.substring(0, sans_array.length() - 2); } String result = primitiveClassesJvm.get(sans_array); if (result == null) { result = "L" + sans_array + ";"; } for (int i = 0; i < dims; i++) { result = "[" + result; } return result.replace('.', '/'); } /** * Convert a primitive java type name (e.g., "int", "double", etc.) to a field descriptor (e.g., * "I", "D", etc.). * * @param primitive_name name of the type, in Java format * @return name of the type, in field descriptor format * @throws IllegalArgumentException if primitive_name is not a valid primitive type name * @deprecated use version in org.plumelib.bcelutil instead */ @Deprecated public static /*@FieldDescriptor*/ String primitiveTypeNameToFieldDescriptor( String primitive_name) { String result = primitiveClassesJvm.get(primitive_name); if (result == null) { throw new IllegalArgumentException("Not the name of a primitive type: " + primitive_name); } return result; } /** * Convert from a BinaryName to the format of {@link Class#getName()}. * * @param bn the binary name to convert * @return the class name, in Class.getName format * @deprecated use version in org.plumelib.bcelutil instead */ @Deprecated @SuppressWarnings("signature") // conversion routine public static /*@ClassGetName*/ String binaryNameToClassGetName(/*BinaryName*/ String bn) { if (bn.endsWith("[]")) { return binaryNameToFieldDescriptor(bn).replace('/', '.'); } else { return bn; } } /** * Convert from a FieldDescriptor to the format of {@link Class#getName()}. * * @param fd the class, in field descriptor format * @return the class name, in Class.getName format * @deprecated use version in org.plumelib.bcelutil instead */ @Deprecated @SuppressWarnings("signature") // conversion routine public static /*@ClassGetName*/ String fieldDescriptorToClassGetName( /*FieldDescriptor*/ String fd) { if (fd.startsWith("[")) { return fd.replace('/', '.'); } else { return fieldDescriptorToBinaryName(fd); } } /** * Convert a fully-qualified argument list from Java format to JVML format. For example, convert * "(java.lang.Integer[], int, java.lang.Integer[][])" to * "([Ljava/lang/Integer;I[[Ljava/lang/Integer;)". * * @param arglist an argument list, in Java format * @return argument list, in JVML format * @deprecated use version in org.plumelib.bcelutil instead */ @Deprecated public static String arglistToJvm(String arglist) { if (!(arglist.startsWith("(") && arglist.endsWith(")"))) { throw new Error("Malformed arglist: " + arglist); } String result = "("; String comma_sep_args = arglist.substring(1, arglist.length() - 1); StringTokenizer args_tokenizer = new StringTokenizer(comma_sep_args, ",", false); while (args_tokenizer.hasMoreTokens()) { @SuppressWarnings("signature") // substring /*@BinaryName*/ String arg = args_tokenizer.nextToken().trim(); result += binaryNameToFieldDescriptor(arg); } result += ")"; // System.out.println("arglistToJvm: " + arglist + " => " + result); return result; } @Deprecated private static HashMap<String, String> primitiveClassesFromJvm = new HashMap<String, String>(8); static { primitiveClassesFromJvm.put("Z", "boolean"); primitiveClassesFromJvm.put("B", "byte"); primitiveClassesFromJvm.put("C", "char"); primitiveClassesFromJvm.put("D", "double"); primitiveClassesFromJvm.put("F", "float"); primitiveClassesFromJvm.put("I", "int"); primitiveClassesFromJvm.put("J", "long"); primitiveClassesFromJvm.put("S", "short"); } // does not convert "V" to "void". Should it? /** * Convert a field descriptor to a binary name. For example, convert "[Ljava/lang/Object;" to * "java.lang.Object[]" or "I" to "int". * * @param classname name of the type, in JVML format * @return name of the type, in Java format * @deprecated use version in org.plumelib.bcelutil instead */ @Deprecated @SuppressWarnings("signature") // conversion routine public static /*@BinaryName*/ String fieldDescriptorToBinaryName(String classname) { if (classname.equals("")) { throw new Error("Empty string passed to fieldDescriptorToBinaryName"); } int dims = 0; while (classname.startsWith("[")) { dims++; classname = classname.substring(1); } String result; if (classname.startsWith("L") && classname.endsWith(";")) { result = classname.substring(1, classname.length() - 1); } else { result = primitiveClassesFromJvm.get(classname); if (result == null) { throw new Error("Malformed base class: " + classname); } } for (int i = 0; i < dims; i++) { result += "[]"; } return result.replace('/', '.'); } /** * Convert an argument list from JVML format to Java format. For example, convert * "([Ljava/lang/Integer;I[[Ljava/lang/Integer;)" to "(java.lang.Integer[], int, * java.lang.Integer[][])". * * @param arglist an argument list, in JVML format * @return argument list, in Java format * @deprecated use version in org.plumelib.bcelutil instead */ @Deprecated public static String arglistFromJvm(String arglist) { if (!(arglist.startsWith("(") && arglist.endsWith(")"))) { throw new Error("Malformed arglist: " + arglist); } String result = "("; /*@Positive*/ int pos = 1; while (pos < arglist.length() - 1) { if (pos > 1) { result += ", "; } int nonarray_pos = pos; while (arglist.charAt(nonarray_pos) == '[') { nonarray_pos++; if (nonarray_pos >= arglist.length()) { throw new Error("Malformed arglist: " + arglist); } } char c = arglist.charAt(nonarray_pos); if (c == 'L') { int semi_pos = arglist.indexOf(';', nonarray_pos); if (semi_pos == -1) { throw new Error("Malformed arglist: " + arglist); } String fieldDescriptor = arglist.substring(pos, semi_pos + 1); result += fieldDescriptorToBinaryName(fieldDescriptor); pos = semi_pos + 1; } else { String maybe = fieldDescriptorToBinaryName(arglist.substring(pos, nonarray_pos + 1)); if (maybe == null) { // return null; throw new Error("Malformed arglist: " + arglist); } result += maybe; pos = nonarray_pos + 1; } } return result + ")"; } /////////////////////////////////////////////////////////////////////////// /// ClassLoader /// /** * This static nested class has no purpose but to define defineClassFromFile. * ClassLoader.defineClass is protected, so I subclass ClassLoader in order to call defineClass. */ private static class PromiscuousLoader extends ClassLoader { /** * Converts the bytes in a file into an instance of class Class, and also resolves (links) the * class. Delegates the real work to defineClass. * * @see ClassLoader#defineClass(String,byte[],int,int) * @param className the expected binary name of the class to define, or null if not known * @param pathname the file from which to load the class * @return the {@code Class} object that was created */ public Class<?> defineClassFromFile( /*@BinaryName*/ String className, String pathname) throws FileNotFoundException, IOException { FileInputStream fi = new FileInputStream(pathname); int numbytes = fi.available(); byte[] classBytes = new byte[numbytes]; int bytesRead = fi.read(classBytes); fi.close(); if (bytesRead < numbytes) { throw new Error( String.format( "Expected to read %d bytes from %s, got %d", numbytes, pathname, bytesRead)); } Class<?> return_class = defineClass(className, classBytes, 0, numbytes); resolveClass(return_class); // link the class return return_class; } } private static PromiscuousLoader thePromiscuousLoader = new PromiscuousLoader(); /** * Converts the bytes in a file into an instance of class Class, and resolves (links) the class. * Like {@link ClassLoader#defineClass(String,byte[],int,int)}, but takes a file name rather than * an array of bytes as an argument, and also resolves (links) the class. * * @see ClassLoader#defineClass(String,byte[],int,int) * @param className the name of the class to define, or null if not known * @param pathname the pathname of a .class file * @return a Java Object corresponding to the Class defined in the .class file * @throws FileNotFoundException if the file cannot be found * @throws IOException if there is trouble reading the file */ // Also throws UnsupportedClassVersionError and some other exceptions. public static Class<?> defineClassFromFile( /*@BinaryName*/ String className, String pathname) throws FileNotFoundException, IOException { return thePromiscuousLoader.defineClassFromFile(className, pathname); } /////////////////////////////////////////////////////////////////////////// /// Classpath /// // Perhaps abstract out the simpler addToPath from this /** * Add the directory to the system classpath. * * @param dir directory to add to the system classpath */ public static void addToClasspath(String dir) { // If the dir isn't on CLASSPATH, add it. String pathSep = System.getProperty("path.separator"); // what is the point of the "replace()" call? String cp = System.getProperty("java.class.path", ".").replace('\\', '/'); StringTokenizer tokenizer = new StringTokenizer(cp, pathSep, false); boolean found = false; while (tokenizer.hasMoreTokens() && !found) { found = tokenizer.nextToken().equals(dir); } if (!found) { System.setProperty("java.class.path", dir + pathSep + cp); } } /////////////////////////////////////////////////////////////////////////// /// File /// /** * Count the number of lines in the specified file. * * @param filename file whose size to count * @return number of lines in filename * @throws IOException if there is trouble reading the file */ public static long count_lines(String filename) throws IOException { long count = 0; try (LineNumberReader reader = UtilPlume.lineNumberFileReader(filename)) { while (reader.readLine() != null) { count++; } } return count; } /** * Return the contents of the file, as a list of strings, one per line. * * @param filename the file whose contents to return * @return the contents of {@code filename}, one string per line * @throws IOException if there was a problem reading the file */ public static List<String> fileLines(String filename) throws IOException { List<String> textList = new ArrayList<>(); try (LineNumberReader reader = UtilPlume.lineNumberFileReader(filename)) { String line; while ((line = reader.readLine()) != null) { textList.add(line); } } return textList; } /** * Tries to infer the line separator used in a file. * * @param filename the file to infer a line separator from * @return the inferred line separator used in filename * @throws IOException if there is trouble reading the file */ public static String inferLineSeparator(String filename) throws IOException { return inferLineSeparator(new File(filename)); } /** * Tries to infer the line separator used in a file. * * @param file the file to infer a line separator from * @return the inferred line separator used in filename * @throws IOException if there is trouble reading the file */ public static String inferLineSeparator(File file) throws IOException { try (BufferedReader r = UtilPlume.bufferedFileReader(file)) { int unix = 0; int dos = 0; int mac = 0; while (true) { String s = r.readLine(); if (s == null) { break; } if (s.endsWith("\r\n")) { dos++; } else if (s.endsWith("\r")) { mac++; } else if (s.endsWith("\n")) { unix++; } else { // This can happen only if the last line is not terminated. } } if ((dos > mac && dos > unix) || (lineSep.equals("\r\n") && dos >= unix && dos >= mac)) { return "\r\n"; } if ((mac > dos && mac > unix) || (lineSep.equals("\r") && mac >= dos && mac >= unix)) { return "\r"; } if ((unix > dos && unix > mac) || (lineSep.equals("\n") && unix >= dos && unix >= mac)) { return "\n"; } // The two non-preferred line endings are tied and have more votes than // the preferred line ending. Give up and return the line separator // for the system on which Java is currently running. return lineSep; } } /** * Return true iff files have the same contents. * * @param file1 first file to compare * @param file2 second file to compare * @return true iff the files have the same contents */ /*@Pure*/ public static boolean equalFiles(String file1, String file2) { return equalFiles(file1, file2, false); } /** * Return true iff the files have the same contents. * * @param file1 first file to compare * @param file2 second file to compare * @param trimLines if true, call String.trim on each line before comparing * @return true iff the files have the same contents */ @SuppressWarnings({"purity", "lock"}) // reads files, side effects local state /*@Pure*/ public static boolean equalFiles(String file1, String file2, boolean trimLines) { try (LineNumberReader reader1 = UtilPlume.lineNumberFileReader(file1); LineNumberReader reader2 = UtilPlume.lineNumberFileReader(file2); ) { String line1 = reader1.readLine(); String line2 = reader2.readLine(); while (line1 != null && line2 != null) { if (trimLines) { line1 = line1.trim(); line2 = line2.trim(); } if (!(line1.equals(line2))) { return false; } line1 = reader1.readLine(); line2 = reader2.readLine(); } if (line1 == null && line2 == null) { return true; } return false; } catch (IOException e) { throw new RuntimeException(e); } } /** * Returns true if the file exists and is writable, or if the file can be created. * * @param file the file to create and write * @return true iff the file can be created and written */ public static boolean canCreateAndWrite(File file) { if (file.exists()) { return file.canWrite(); } else { File directory = file.getParentFile(); if (directory == null) { directory = new File("."); } // Does this test need "directory.canRead()" also? return directory.canWrite(); } /// Old implementation; is this equivalent to the new one, above?? // try { // if (file.exists()) { // return file.canWrite(); // } else { // file.createNewFile(); // file.delete(); // return true; // } // } catch (IOException e) { // return false; // } } /// /// Directories /// /** * Creates an empty directory in the default temporary-file directory, using the given prefix and * suffix to generate its name. For example, calling createTempDir("myPrefix", "mySuffix") will * create the following directory: temporaryFileDirectory/myUserName/myPrefix_someString_suffix. * someString is internally generated to ensure no temporary files of the same name are generated. * * @param prefix the prefix string to be used in generating the file's name; must be at least * three characters long * @param suffix the suffix string to be used in generating the file's name; may be null, in which * case the suffix ".tmp" will be used Returns: An abstract pathname denoting a newly-created * empty file * @return a File representing the newly-created temporary directory * @throws IllegalArgumentException If the prefix argument contains fewer than three characters * @throws IOException If a file could not be created * @throws SecurityException If a security manager exists and its * SecurityManager.checkWrite(java.lang.String) method does not allow a file to be created * @see java.io.File#createTempFile(String, String, File) */ public static File createTempDir(String prefix, String suffix) throws IOException { String fs = File.separator; String path = System.getProperty("java.io.tmpdir") + fs + System.getProperty("user.name") + fs; File pathFile = new File(path); if (!pathFile.isDirectory()) { if (!pathFile.mkdirs()) { throw new IOException("Could not create directory: " + pathFile); } } // Call Java runtime to create a file with a unique name File tmpfile = File.createTempFile(prefix + "_", "_", pathFile); String tmpDirPath = tmpfile.getPath() + suffix; File tmpDir = new File(tmpDirPath); if (!tmpDir.mkdirs()) { throw new IOException("Could not create directory: " + tmpDir); } // Now that we have created our directory, we should get rid // of the intermediate TempFile we created. tmpfile.delete(); return tmpDir; } /** * Deletes the directory at dirName and all its files. Also works on regular files. * * @param dirName the directory to delete * @return true if and only if the file or directory is successfully deleted; false otherwise */ public static boolean deleteDir(String dirName) { return deleteDir(new File(dirName)); } /** * Deletes the directory at dir and all its files. Also works on regular files. * * @param dir the directory to delete * @return true if and only if the file or directory is successfully deleted; false otherwise */ public static boolean deleteDir(File dir) { File[] children = dir.listFiles(); if (children != null) { // null means not a directory, or I/O error occurred. for (File child : children) { deleteDir(child); } } return dir.delete(); } /// /// File names (aka filenames) /// // Someone must have already written this. Right? /** * A FilenameFilter that accepts files whose name matches the given wildcard. The wildcard must * contain exactly one "*". */ public static final class WildcardFilter implements FilenameFilter { String prefix; String suffix; public WildcardFilter(String filename) { int astloc = filename.indexOf('*'); if (astloc == -1) { throw new Error("No asterisk in wildcard argument: " + filename); } prefix = filename.substring(0, astloc); suffix = filename.substring(astloc + 1); if (filename.indexOf('*') != -1) { throw new Error("Multiple asterisks in wildcard argument: " + filename); } } @Override public boolean accept(File dir, String name) { return name.startsWith(prefix) && name.endsWith(suffix); } } static final String userHome = System.getProperty("user.home"); /** * Does tilde expansion on a file name (to the user's home directory). * * @param name file whose name to expand * @return file with expanded file */ public static File expandFilename(File name) { String path = name.getPath(); String newname = expandFilename(path); @SuppressWarnings("interning") boolean changed = (newname != path); if (changed) { return new File(newname); } else { return name; } } /** * Does tilde expansion on a file name (to the user's home directory). * * @param name filename to expand * @return expanded filename */ public static String expandFilename(String name) { if (name.contains("~")) { return (name.replace("~", userHome)); } else { return name; } } /** * Return a string version of the filename that can be used in Java source. On Windows, the file * will return a backslash separated string. Since backslash is an escape character, it must be * quoted itself inside the string. * * <p>The current implementation presumes that backslashes don't appear in filenames except as * windows path separators. That seems like a reasonable assumption. * * @param name file whose name to quote * @return a string version of the name that can be used in Java source */ public static String java_source(File name) { return name.getPath().replace("\\", "\\\\"); } /// /// Reading and writing /// /** * Writes an Object to a File. * * @param o the object to write * @param file the file to which to write the object * @throws IOException if there is trouble writing the file */ public static void writeObject(Object o, File file) throws IOException { // 8192 is the buffer size in BufferedReader OutputStream bytes = new BufferedOutputStream(new FileOutputStream(file), 8192); if (file.getName().endsWith(".gz")) { bytes = new GZIPOutputStream(bytes); } ObjectOutputStream objs = new ObjectOutputStream(bytes); objs.writeObject(o); objs.close(); } /** * Reads an Object from a File. * * @param file the file from which to read * @return the object read from the file * @throws IOException if there is trouble reading the file * @throws ClassNotFoundException if the object's class cannot be found */ public static Object readObject(File file) throws IOException, ClassNotFoundException { // 8192 is the buffer size in BufferedReader InputStream istream = new BufferedInputStream(new FileInputStream(file), 8192); if (file.getName().endsWith(".gz")) { try { istream = new GZIPInputStream(istream); } catch (IOException e) { throw new IOException("Problem while reading " + file, e); } } ObjectInputStream objs = new ObjectInputStream(istream); return objs.readObject(); } /** * Reads the entire contents of the reader and returns it as a string. Any IOException encountered * will be turned into an Error. * * @param r the Reader to read * @return the entire contents of the reader, as a string */ public static String readerContents(Reader r) { try { StringBuilder contents = new StringBuilder(); int ch; while ((ch = r.read()) != -1) { contents.append((char) ch); } r.close(); return contents.toString(); } catch (Exception e) { throw new Error("Unexpected error in readerContents(" + r + ")", e); } } // an alternate name would be "fileContents". /** * Reads the entire contents of the file and returns it as a string. Any IOException encountered * will be turned into an Error. * * <p>You could use {@code new String(Files.readAllBytes(...))}, but it requires a Path rather * than a File, and it can throw IOException which has to be caught. * * @param file the file to read * @return the entire contents of the reader, as a string */ public static String readFile(File file) { try { BufferedReader reader = UtilPlume.bufferedFileReader(file); StringBuilder contents = new StringBuilder(); String line = reader.readLine(); while (line != null) { contents.append(line); // Note that this converts line terminators! contents.append(lineSep); line = reader.readLine(); } reader.close(); return contents.toString(); } catch (Exception e) { throw new Error("Unexpected error in readFile(" + file + ")", e); } } /** * Creates a file with the given name and writes the specified string to it. If the file currently * exists (and is writable) it is overwritten Any IOException encountered will be turned into an * Error. * * @param file the file to write to * @param contents the text to put in the file */ public static void writeFile(File file, String contents) { try { Writer writer = Files.newBufferedWriter(file.toPath(), UTF_8); writer.write(contents, 0, contents.length()); writer.close(); } catch (Exception e) { throw new Error("Unexpected error in writeFile(" + file + ")", e); } } /////////////////////////////////////////////////////////////////////////// /// Hashing /// // In hashing, there are two separate issues. First, one must convert // the input datum into an integer. Then, one must transform the // resulting integer in a pseudorandom way so as to result in a number // that is far separated from other values that may have been near it to // begin with. Often these two steps are combined, particularly if // one wishes to avoid creating too large an integer (losing information // off the top bits). // http://burtleburtle.net/bob/hash/hashfaq.html says (of combined methods): // * for (h=0, i=0; i<len; ++i) { h += key[i]; h += (h<<10); h ^= (h>>6); } // h += (h<<3); h ^= (h>>11); h += (h<<15); // is good. // * for (h=0, i=0; i<len; ++i) h = tab[(h^key[i])&0xff]; may be good. // * for (h=0, i=0; i<len; ++i) h = (h>>8)^tab[(key[i]+h)&0xff]; may be good. // In this part of the file, perhaps I will eventually write good hash // functions. For now, write cheesy ones that primarily deal with the // first issue, transforming a data structure into a single number. This // is also known as fingerprinting. /** * Return a hash of the arguments. Note that this differs from the result of {@link * Double#hashCode()}. * * @param x value to be hashed * @return a hash of the arguments */ public static int hash(double x) { return hash(Double.doubleToLongBits(x)); } /** * Return a hash of the arguments. * * @param a value to be hashed * @param b value to be hashed * @return a hash of the arguments */ public static int hash(double a, double b) { double result = 17; result = result * 37 + a; result = result * 37 + b; return hash(result); } /** * Return a hash of the arguments. * * @param a value to be hashed * @param b value to be hashed * @param c value to be hashed * @return a hash of the arguments */ public static int hash(double a, double b, double c) { double result = 17; result = result * 37 + a; result = result * 37 + b; result = result * 37 + c; return hash(result); } /** * Return a hash of the arguments. * * @param a value to be hashed * @return a hash of the arguments */ public static int hash(double /*@Nullable*/ [] a) { double result = 17; if (a != null) { result = result * 37 + a.length; for (int i = 0; i < a.length; i++) { result = result * 37 + a[i]; } } return hash(result); } /** * Return a hash of the arguments. * * @param a value to be hashed * @param b value to be hashed * @return a hash of the arguments */ public static int hash(double /*@Nullable*/ [] a, double /*@Nullable*/ [] b) { return hash(hash(a), hash(b)); } /// Don't define hash with int args; use the long versions instead. /** * Return a hash of the arguments. Note that this differs from the result of {@link * Long#hashCode()}. But it doesn't map -1 and 0 to the same value. * * @param l value to be hashed * @return a hash of the arguments */ public static int hash(long l) { // If possible, use the value itself. if (l >= Integer.MIN_VALUE && l <= Integer.MAX_VALUE) { return (int) l; } int result = 17; int hibits = (int) (l >> 32); int lobits = (int) l; result = result * 37 + hibits; result = result * 37 + lobits; return result; } /** * Return a hash of the arguments. * * @param a value to be hashed * @param b value to be hashed * @return a hash of the arguments */ public static int hash(long a, long b) { long result = 17; result = result * 37 + a; result = result * 37 + b; return hash(result); } /** * Return a hash of the arguments. * * @param a value to be hashed * @param b value to be hashed * @param c value to be hashed * @return a hash of the arguments */ public static int hash(long a, long b, long c) { long result = 17; result = result * 37 + a; result = result * 37 + b; result = result * 37 + c; return hash(result); } /** * Return a hash of the arguments. * * @param a value to be hashed * @return a hash of the arguments */ public static int hash(long /*@Nullable*/ [] a) { long result = 17; if (a != null) { result = result * 37 + a.length; for (int i = 0; i < a.length; i++) { result = result * 37 + a[i]; } } return hash(result); } /** * Return a hash of the arguments. * * @param a value to be hashed * @param b value to be hashed * @return a hash of the arguments */ public static int hash(long /*@Nullable*/ [] a, long /*@Nullable*/ [] b) { return hash(hash(a), hash(b)); } /** * Return a hash of the arguments. * * @param a value to be hashed * @return a hash of the arguments */ public static int hash(/*@Nullable*/ String a) { return (a == null) ? 0 : a.hashCode(); } /** * Return a hash of the arguments. * * @param a value to be hashed * @param b value to be hashed * @return a hash of the arguments */ public static int hash(/*@Nullable*/ String a, /*@Nullable*/ String b) { long result = 17; result = result * 37 + hash(a); result = result * 37 + hash(b); return hash(result); } /** * Return a hash of the arguments. * * @param a value to be hashed * @param b value to be hashed * @param c value to be hashed * @return a hash of the arguments */ public static int hash(/*@Nullable*/ String a, /*@Nullable*/ String b, /*@Nullable*/ String c) { long result = 17; result = result * 37 + hash(a); result = result * 37 + hash(b); result = result * 37 + hash(c); return hash(result); } /** * Return a hash of the arguments. * * @param a value to be hashed * @return a hash of the arguments */ public static int hash(/*@Nullable*/ String /*@Nullable*/ [] a) { long result = 17; if (a != null) { result = result * 37 + a.length; for (int i = 0; i < a.length; i++) { result = result * 37 + hash(a[i]); } } return hash(result); } /////////////////////////////////////////////////////////////////////////// /// Iterator /// /** * Converts an Iterator to an Iterable. The resulting Iterable can be used to produce a single, * working Iterator (the one that was passed in). Subsequent calls to its iterator() method will * fail, because otherwise they would return the same Iterator instance, which may have been * exhausted, or otherwise be in some indeterminate state. Calling iteratorToIterable twice on the * same argument can have similar problems, so don't do that. * * @param source the Iterator to be converted to Iterable * @param <T> the element type * @return source, converted to Iterable */ public static <T> Iterable<T> iteratorToIterable(final Iterator<T> source) { if (source == null) { throw new NullPointerException(); } return new Iterable<T>() { private AtomicBoolean used = new AtomicBoolean(); @Override public Iterator<T> iterator() { if (used.getAndSet(true)) { throw new Error("Call iterator() just once"); } return source; } }; } // Making these classes into functions didn't work because I couldn't get // their arguments into a scope that Java was happy with. /** Converts an Enumeration into an Iterator. */ public static final class EnumerationIterator<T> implements Iterator<T> { Enumeration<T> e; public EnumerationIterator(Enumeration<T> e) { this.e = e; } @Override public boolean hasNext(/*>>>@GuardSatisfied EnumerationIterator<T> this*/) { return e.hasMoreElements(); } @Override public T next(/*>>>@GuardSatisfied EnumerationIterator<T> this*/) { return e.nextElement(); } @Override public void remove(/*>>>@GuardSatisfied EnumerationIterator<T> this*/) { throw new UnsupportedOperationException(); } } /** Converts an Iterator into an Enumeration. */ @SuppressWarnings("JdkObsolete") public static final class IteratorEnumeration<T> implements Enumeration<T> { Iterator<T> itor; public IteratorEnumeration(Iterator<T> itor) { this.itor = itor; } @Override public boolean hasMoreElements() { return itor.hasNext(); } @Override public T nextElement() { return itor.next(); } } // This must already be implemented someplace else. Right?? /** * An Iterator that returns first the elements returned by its first argument, then the elements * returned by its second argument. Like {@link MergedIterator}, but specialized for the case of * two arguments. */ public static final class MergedIterator2<T> implements Iterator<T> { Iterator<T> itor1, itor2; public MergedIterator2(Iterator<T> itor1_, Iterator<T> itor2_) { this.itor1 = itor1_; this.itor2 = itor2_; } @Override public boolean hasNext(/*>>>@GuardSatisfied MergedIterator2<T> this*/) { return (itor1.hasNext() || itor2.hasNext()); } @Override public T next(/*>>>@GuardSatisfied MergedIterator2<T> this*/) { if (itor1.hasNext()) { return itor1.next(); } else if (itor2.hasNext()) { return itor2.next(); } else { throw new NoSuchElementException(); } } @Override public void remove(/*>>>@GuardSatisfied MergedIterator2<T> this*/) { throw new UnsupportedOperationException(); } } // This must already be implemented someplace else. Right?? /** * An Iterator that returns the elements in each of its argument Iterators, in turn. The argument * is an Iterator of Iterators. Like {@link MergedIterator2}, but generalized to arbitrary number * of iterators. */ public static final class MergedIterator<T> implements Iterator<T> { Iterator<Iterator<T>> itorOfItors; public MergedIterator(Iterator<Iterator<T>> itorOfItors) { this.itorOfItors = itorOfItors; } // an empty iterator to prime the pump Iterator<T> current = new ArrayList<T>().iterator(); @Override public boolean hasNext(/*>>>@GuardSatisfied MergedIterator<T> this*/) { while ((!current.hasNext()) && (itorOfItors.hasNext())) { current = itorOfItors.next(); } return current.hasNext(); } @Override public T next(/*>>>@GuardSatisfied MergedIterator<T> this*/) { hasNext(); // for side effect return current.next(); } @Override public void remove(/*>>>@GuardSatisfied MergedIterator<T> this*/) { throw new UnsupportedOperationException(); } } /** An iterator that only returns elements that match the given Filter. */ @SuppressWarnings("assignment.type.incompatible") // problems in DFF branch public static final class FilteredIterator<T> implements Iterator<T> { Iterator<T> itor; Filter<T> filter; public FilteredIterator(Iterator<T> itor, Filter<T> filter) { this.itor = itor; this.filter = filter; } @SuppressWarnings("unchecked") T invalid_t = (T) new Object(); T current = invalid_t; boolean current_valid = false; @Override public boolean hasNext(/*>>>@GuardSatisfied FilteredIterator<T> this*/) { while ((!current_valid) && itor.hasNext()) { current = itor.next(); current_valid = filter.accept(current); } return current_valid; } @Override public T next(/*>>>@GuardSatisfied FilteredIterator<T> this*/) { if (hasNext()) { current_valid = false; @SuppressWarnings("interning") boolean ok = (current != invalid_t); assert ok; return current; } else { throw new NoSuchElementException(); } } @Override public void remove(/*>>>@GuardSatisfied FilteredIterator<T> this*/) { throw new UnsupportedOperationException(); } } /** * Returns an iterator just like its argument, except that the first and last elements are * removed. They can be accessed via the getFirst and getLast methods. */ @SuppressWarnings("assignment.type.incompatible") // problems in DFF branch public static final class RemoveFirstAndLastIterator<T> implements Iterator<T> { Iterator<T> itor; // I don't think this works, because the iterator might itself return null // /*@Nullable*/ T nothing = (/*@Nullable*/ T) null; @SuppressWarnings("unchecked") T nothing = (T) new Object(); T first = nothing; T current = nothing; public RemoveFirstAndLastIterator(Iterator<T> itor) { this.itor = itor; if (itor.hasNext()) { first = itor.next(); } if (itor.hasNext()) { current = itor.next(); } } @Override public boolean hasNext(/*>>>@GuardSatisfied RemoveFirstAndLastIterator<T> this*/) { return itor.hasNext(); } @Override public T next(/*>>>@GuardSatisfied RemoveFirstAndLastIterator<T> this*/) { if (!itor.hasNext()) { throw new NoSuchElementException(); } T tmp = current; current = itor.next(); return tmp; } public T getFirst() { @SuppressWarnings("interning") // check for equality to a special value boolean invalid = (first == nothing); if (invalid) { throw new NoSuchElementException(); } return first; } // Throws an error unless the RemoveFirstAndLastIterator has already // been iterated all the way to its end (so the delegate is pointing to // the last element). Also, this is buggy when the delegate is empty. public T getLast() { if (itor.hasNext()) { throw new Error(); } return current; } @Override public void remove(/*>>>@GuardSatisfied RemoveFirstAndLastIterator<T> this*/) { throw new UnsupportedOperationException(); } } /** * Return a List containing num_elts randomly chosen elements from the iterator, or all the * elements of the iterator if there are fewer. It examines every element of the iterator, but * does not keep them all in memory. * * @param <T> type of the iterator elements * @param itor elements to be randomly selected from * @param num_elts number of elements to select * @return list of num_elts elements from itor */ public static <T> List<T> randomElements(Iterator<T> itor, int num_elts) { return randomElements(itor, num_elts, r); } private static Random r = new Random(); /** * Return a List containing num_elts randomly chosen elements from the iterator, or all the * elements of the iterator if there are fewer. It examines every element of the iterator, but * does not keep them all in memory. * * @param <T> type of the iterator elements * @param itor elements to be randomly selected from * @param num_elts number of elements to select * @param random the Random instance to use to make selections * @return list of num_elts elements from itor */ public static <T> List<T> randomElements(Iterator<T> itor, int num_elts, Random random) { // The elements are chosen with the following probabilities, // where n == num_elts: // n n/2 n/3 n/4 n/5 ... RandomSelector<T> rs = new RandomSelector<T>(num_elts, random); while (itor.hasNext()) { rs.accept(itor.next()); } return rs.getValues(); /* ArrayList<T> result = new ArrayList<T>(num_elts); int i=1; for (int n=0; n<num_elts && itor.hasNext(); n++, i++) { result.add(itor.next()); } for (; itor.hasNext(); i++) { T o = itor.next(); // test random < num_elts/i if (random.nextDouble() * i < num_elts) { // This element will replace one of the existing elements. result.set(random.nextInt(num_elts), o); } } return result; */ } /////////////////////////////////////////////////////////////////////////// /// Map /// // In Python, inlining this gave a 10x speed improvement. // Will the same be true for Java? /** * Increment the Integer which is indexed by key in the Map. If the key isn't in the Map, it is * added. * * @param <T> type of keys in the map * @param m map to have one of its values incremented * @param key the key for the element whose value will be incremented * @param count how much to increment the value by * @return the old value, before it was incremented * @throws Error if the key is in the Map but maps to a non-Integer */ public static <T> /*@Nullable*/ Integer incrementMap(Map<T, Integer> m, T key, int count) { Integer old = m.get(key); int new_total; if (old == null) { new_total = count; } else { new_total = old.intValue() + count; } return m.put(key, new_total); } /** * Returns a multi-line string representation of a map. * * @param <K> type of map keys * @param <V> type of map values * @param m map to be converted to a string * @return a multi-line string representation of m */ public static <K, V> String mapToString(Map<K, V> m) { StringBuilder sb = new StringBuilder(); mapToString(sb, m, ""); return sb.toString(); } /** * Write a multi-line representation of the map into the given Appendable (e.g., a StringBuilder). * * @param <K> type of map keys * @param <V> type of map values * @param sb an Appendable (such as StringBuilder) to which to write a multi-line string * representation of m * @param m map to be converted to a string * @param linePrefix prefix to write at the beginning of each line */ public static <K, V> void mapToString(Appendable sb, Map<K, V> m, String linePrefix) { try { for (Map.Entry<K, V> entry : m.entrySet()) { sb.append(linePrefix); sb.append(Objects.toString(entry.getKey())); sb.append(" => "); sb.append(Objects.toString(entry.getValue())); sb.append(lineSep); } } catch (IOException e) { throw new RuntimeException(e); } } /** * Returns a sorted version of m.keySet(). * * @param <K> type of the map keys * @param <V> type of the map values * @param m a map whose keyset will be sorted * @return a sorted version of m.keySet() */ public static <K extends Comparable<? super K>, V> Collection</*@KeyFor("#1")*/ K> sortedKeySet( Map<K, V> m) { ArrayList</*@KeyFor("#1")*/ K> theKeys = new ArrayList</*@KeyFor("#1")*/ K>(m.keySet()); Collections.sort(theKeys); return theKeys; } /** * Returns a sorted version of m.keySet(). * * @param <K> type of the map keys * @param <V> type of the map values * @param m a map whose keyset will be sorted * @param comparator the Comparator to use for sorting * @return a sorted version of m.keySet() */ public static <K, V> Collection</*@KeyFor("#1")*/ K> sortedKeySet( Map<K, V> m, Comparator<K> comparator) { ArrayList</*@KeyFor("#1")*/ K> theKeys = new ArrayList</*@KeyFor("#1")*/ K>(m.keySet()); Collections.sort(theKeys, comparator); return theKeys; } /////////////////////////////////////////////////////////////////////////// /// Method /// /** * Maps from a comma-delimited string of arg types, such as appears in a method signature, to an * array of Class objects, one for each arg type. Example keys include: "java.lang.String, * java.lang.String, java.lang.Class[]" and "int,int". */ static HashMap<String, Class<?>[]> args_seen = new HashMap<String, Class<?>[]>(); /** * Given a method signature, return the method. * * <p>Example calls are: * * <pre> * UtilPlume.methodForName("org.plumelib.util.UtilPlume.methodForName(java.lang.String, java.lang.String, java.lang.Class[])") * UtilPlume.methodForName("org.plumelib.util.UtilPlume.methodForName(java.lang.String,java.lang.String,java.lang.Class[])") * UtilPlume.methodForName("java.lang.Math.min(int,int)") * </pre> * * @param method a method signature * @return the method corresponding to the given signature * @throws ClassNotFoundException if the class is not found * @throws NoSuchMethodException if the method is not found */ public static Method methodForName(String method) throws ClassNotFoundException, NoSuchMethodException, SecurityException { int oparenpos = method.indexOf('('); int dotpos = method.lastIndexOf('.', oparenpos); int cparenpos = method.indexOf(')', oparenpos); if ((dotpos == -1) || (oparenpos == -1) || (cparenpos == -1)) { throw new Error( "malformed method name should contain a period, open paren, and close paren: " + method + " <<" + dotpos + "," + oparenpos + "," + cparenpos + ">>"); } for (int i = cparenpos + 1; i < method.length(); i++) { if (!Character.isWhitespace(method.charAt(i))) { throw new Error( "malformed method name should contain only whitespace following close paren"); } } @SuppressWarnings("signature") // throws exception if class does not exist /*@BinaryNameForNonArray*/ String classname = method.substring(0, dotpos); String methodname = method.substring(dotpos + 1, oparenpos); String all_argnames = method.substring(oparenpos + 1, cparenpos).trim(); Class<?>[] argclasses = args_seen.get(all_argnames); if (argclasses == null) { String[] argnames; if (all_argnames.equals("")) { argnames = new String[0]; } else { argnames = split(all_argnames, ','); } /*@MonotonicNonNull*/ Class<?>[] argclasses_tmp = new Class<?>[argnames.length]; for (int i = 0; i < argnames.length; i++) { String bnArgname = argnames[i].trim(); /*@ClassGetName*/ String cgnArgname = binaryNameToClassGetName(bnArgname); argclasses_tmp[i] = classForName(cgnArgname); } @SuppressWarnings("cast") Class<?>[] argclasses_res = (/*@NonNull*/ Class<?>[]) argclasses_tmp; argclasses = argclasses_res; args_seen.put(all_argnames, argclasses_res); } return methodForName(classname, methodname, argclasses); } /** * Given a class name and a method name in that class, return the method. * * @param classname class in which to find the method * @param methodname the method name * @param params the parameters of the method * @return the method named classname.methodname with parameters params * @throws ClassNotFoundException if the class is not found * @throws NoSuchMethodException if the method is not found */ public static Method methodForName( /*@BinaryNameForNonArray*/ String classname, String methodname, Class<?>[] params) throws ClassNotFoundException, NoSuchMethodException, SecurityException { Class<?> c = Class.forName(classname); Method m = c.getDeclaredMethod(methodname, params); return m; } /////////////////////////////////////////////////////////////////////////// /// ProcessBuilder /// /** * Execute the given command, and return all its output as a string. * * @param command a command to execute on the command line * @return all the output of the command */ public static String backticks(String... command) { return backticks(Arrays.asList(command)); } /** * Execute the given command, and return all its output as a string. * * @param command a command to execute on the command line, as a list of strings (the command, * then its arguments) * @return all the output of the command */ public static String backticks(List<String> command) { ProcessBuilder pb = new ProcessBuilder(command); pb.redirectErrorStream(true); // TimeLimitProcess p = new TimeLimitProcess(pb.start(), TIMEOUT_SEC * 1000); try { Process p = pb.start(); @SuppressWarnings("nullness") // didn't redirect stream, so getter returns non-null String output = UtilPlume.streamString(p.getInputStream()); return output; } catch (IOException e) { return "IOException: " + e.getMessage(); } } /////////////////////////////////////////////////////////////////////////// /// Properties /// /** * Determines whether a property has value "true", "yes", or "1". * * @see Properties#getProperty * @param p a Properties object in which to look up the property * @param key name of the property to look up * @return true iff the property has value "true", "yes", or "1" */ @SuppressWarnings({"purity", "lock"}) // does not depend on object identity /*@Pure*/ public static boolean propertyIsTrue(Properties p, String key) { String pvalue = p.getProperty(key); if (pvalue == null) { return false; } pvalue = pvalue.toLowerCase(); return (pvalue.equals("true") || pvalue.equals("yes") || pvalue.equals("1")); } /** * Set the property to its previous value concatenated to the given value. Return the previous * value. * * @param p a Properties object in which to look up the property * @param key name of the property to look up * @param value value to concatenate to the previous value of the property * @return the previous value of the property * @see Properties#getProperty * @see Properties#setProperty */ public static /*@Nullable*/ String appendProperty(Properties p, String key, String value) { return (String) p.setProperty(key, p.getProperty(key, "") + value); } /** * Set the property only if it was not previously set. * * @see Properties#getProperty * @see Properties#setProperty * @param p a Properties object in which to look up the property * @param key name of the property to look up * @param value value to set the property to, if it is not already set * @return the previous value of the property */ public static /*@Nullable*/ String setDefaultMaybe(Properties p, String key, String value) { String currentValue = p.getProperty(key); if (currentValue == null) { p.setProperty(key, value); } return currentValue; } /////////////////////////////////////////////////////////////////////////// /// Regexp (regular expression) /// // See RegexUtil class. /////////////////////////////////////////////////////////////////////////// /// Reflection /// // TODO: add method invokeMethod; see // java/Translation/src/graph/tests/Reflect.java (but handle returning a // value). // TODO: make this restore the access to its original value, such as private? /** * Sets the given field, which may be final and/or private. Leaves the field accessible. Intended * for use in readObject and nowhere else! * * @param o object in which to set the field * @param fieldName name of field to set * @param value new value of field * @throws NoSuchFieldException if the field does not exist in the object */ public static void setFinalField(Object o, String fieldName, /*@Nullable*/ Object value) throws NoSuchFieldException { Class<?> c = o.getClass(); while (c != Object.class) { // Class is interned // System.out.printf ("Setting field %s in %s%n", fieldName, c); try { Field f = c.getDeclaredField(fieldName); f.setAccessible(true); f.set(o, value); return; } catch (NoSuchFieldException e) { if (c.getSuperclass() == Object.class) { // Class is interned throw e; } } catch (IllegalAccessException e) { throw new Error("This can't happen: " + e); } c = c.getSuperclass(); assert c != null : "@AssumeAssertion(nullness): c was not Object, so is not null now"; } throw new NoSuchFieldException(fieldName); } // TODO: make this restore the access to its original value, such as private? /** * Reads the given field, which may be private. Leaves the field accessible. Use with care! * * @param o object in which to set the field * @param fieldName name of field to set * @return new value of field * @throws NoSuchFieldException if the field does not exist in the object */ public static /*@Nullable*/ Object getPrivateField(Object o, String fieldName) throws NoSuchFieldException { Class<?> c = o.getClass(); while (c != Object.class) { // Class is interned // System.out.printf ("Setting field %s in %s%n", fieldName, c); try { Field f = c.getDeclaredField(fieldName); f.setAccessible(true); return f.get(o); } catch (IllegalAccessException e) { System.out.println("in getPrivateField, IllegalAccessException: " + e); throw new Error("This can't happen: " + e); } catch (NoSuchFieldException e) { if (c.getSuperclass() == Object.class) { // Class is interned throw e; } // nothing to do; will now examine superclass } c = c.getSuperclass(); assert c != null : "@AssumeAssertion(nullness): c was not Object, so is not null now"; } throw new NoSuchFieldException(fieldName); } /** * Returns the least upper bound of the given classes. * * @param a a class * @param b a class * @return the least upper bound of the two classes, or null if both are null */ public static <T> /*@Nullable*/ Class<T> leastUpperBound( /*@Nullable*/ Class<T> a, /*@Nullable*/ Class<T> b) { if (a == b) { return a; } else if (a == null) { return b; } else if (b == null) { return a; } else if (a == Void.TYPE) { return b; } else if (b == Void.TYPE) { return a; } else if (a.isAssignableFrom(b)) { return a; } else if (b.isAssignableFrom(a)) { return b; } else { // There may not be a unique least upper bound. // Probably return some specific class rather than a wildcard. throw new Error("Not yet implemented"); } } /** * Returns the least upper bound of all the given classes. * * @param classes a non-empty list of classes * @return the least upper bound of all the given classes */ public static <T> /*@Nullable*/ Class<T> leastUpperBound(/*@Nullable*/ Class<T>[] classes) { Class<T> result = null; for (Class<T> clazz : classes) { result = leastUpperBound(result, clazz); } return result; } /** * Returns the least upper bound of the classes of the given objects. * * @param objects a list of objects * @return the least upper bound of the classes of the given objects, or null if all arguments are * null */ public static <T> /*@Nullable*/ Class<T> leastUpperBound(/*@PolyNull*/ Object[] objects) { Class<T> result = null; for (Object obj : objects) { if (obj != null) { result = leastUpperBound(result, (Class<T>) obj.getClass()); } } return result; } /** * Returns the least upper bound of the classes of the given objects. * * @param objects a non-empty list of objects * @return the least upper bound of the classes of the given objects, or null if all arguments are * null */ public static <T> /*@Nullable*/ Class<T> leastUpperBound( List<? extends /*@Nullable*/ Object> objects) { Class<T> result = null; for (Object obj : objects) { if (obj != null) { result = leastUpperBound(result, (Class<T>) obj.getClass()); } } return result; } /////////////////////////////////////////////////////////////////////////// /// Set /// /** * Return the object in this set that is equal to key. The Set abstraction doesn't provide this; * it only provides "contains". Returns null if the argument is null, or if it isn't in the set. * * @param set a set in which to look up the value * @param key the value to look up in the set * @return the object in this set that is equal to key, or null */ public static /*@Nullable*/ Object getFromSet(Set<?> set, Object key) { if (key == null) { return null; } for (Object elt : set) { if (key.equals(elt)) { return elt; } } return null; } /////////////////////////////////////////////////////////////////////////// /// Stream /// /** * Copy the contents of the input stream to the output stream. * * @param from input stream * @param to output stream */ public static void streamCopy(InputStream from, OutputStream to) { byte[] buffer = new byte[1024]; int bytes; try { while (true) { bytes = from.read(buffer); if (bytes == -1) { return; } to.write(buffer, 0, bytes); } } catch (IOException e) { e.printStackTrace(); throw new Error(e); } } /** * Return a String containing all the characters from the input stream. * * @param is input stream to read * @return a String containing all the characters from the input stream */ public static String streamString(InputStream is) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); streamCopy(is, baos); return baos.toString(); } /** * Reads all lines from the stream and returns them in a {@code List<String>}. * * @param stream the stream to read from * @return the list of lines read from the stream * @throws IOException if there is an error reading from the stream */ public static List<String> streamLines(InputStream stream) throws IOException { List<String> outputLines = new ArrayList<>(); try (BufferedReader rdr = new BufferedReader(new InputStreamReader(stream, UTF_8))) { String line; while ((line = rdr.readLine()) != null) { outputLines.add(line); } } return outputLines; } /////////////////////////////////////////////////////////////////////////// /// String /// /** * Return a new string which is the text of target with all instances of oldStr replaced by * newStr. * * @param target the string to do replacement in * @param oldStr the substring to replace * @param newStr the replacement * @return target with all instances of oldStr replaced by newStr */ public static String replaceString(String target, String oldStr, String newStr) { if (oldStr.equals("")) { throw new IllegalArgumentException(); } StringBuilder result = new StringBuilder(); /*@IndexOrHigh("target")*/ int lastend = 0; int pos; while ((pos = target.indexOf(oldStr, lastend)) != -1) { result.append(target.substring(lastend, pos)); result.append(newStr); lastend = pos + oldStr.length(); } result.append(target.substring(lastend)); return result.toString(); } /** * Return an array of Strings representing the characters between successive instances of the * delimiter character. Always returns an array of length at least 1 (it might contain only the * empty string). * * @see #split(String s, String delim) * @param s the string to split * @param delim delimiter to split the string on * @return array of length at least 1, containing s split on delimiter */ public static String[] split(String s, char delim) { ArrayList<String> result_list = new ArrayList<String>(); for (int delimpos = s.indexOf(delim); delimpos != -1; delimpos = s.indexOf(delim)) { result_list.add(s.substring(0, delimpos)); s = s.substring(delimpos + 1); } result_list.add(s); String[] result = result_list.toArray(new /*@NonNull*/ String[result_list.size()]); return result; } /** * Return an array of Strings representing the characters between successive instances of the * delimiter String. Always returns an array of length at least 1 (it might contain only the empty * string). * * @see #split(String s, char delim) * @param s the string to split * @param delim delimiter to split the string on * @return array of length at least 1, containing s split on delimiter */ public static String[] split(String s, String delim) { int delimlen = delim.length(); if (delimlen == 0) { throw new Error("Second argument to split was empty."); } ArrayList<String> result_list = new ArrayList<String>(); for (int delimpos = s.indexOf(delim); delimpos != -1; delimpos = s.indexOf(delim)) { result_list.add(s.substring(0, delimpos)); s = s.substring(delimpos + delimlen); } result_list.add(s); @SuppressWarnings("index") // index checker has no list support: vectors String[] result = result_list.toArray(new /*@NonNull*/ String[result_list.size()]); return result; } /** * Return an array of Strings, one for each line in the argument. Always returns an array of * length at least 1 (it might contain only the empty string). All common line separators (cr, lf, * cr-lf, or lf-cr) are supported. Note that a string that ends with a line separator will return * an empty string as the last element of the array. * * @see #split(String s, char delim) * @param s the string to split * @return an array of Strings, one for each line in the argument */ /*@SideEffectFree*/ /*@StaticallyExecutable*/ public static String[] splitLines(String s) { return s.split("\r\n?|\n\r?", -1); } /** * Concatenate the string representations of the array elements, placing the delimiter between * them. * * <p>If you are using Java 8 or later, then use the {@code String.join()} method instead. * * @see org.plumelib.util.ArraysPlume#toString(int[]) * @param a array of values to concatenate * @param delim delimiter to place between printed representations * @return the concatenation of the string representations of the values, with the delimiter * between */ public static String join(Object[] a, String delim) { if (a.length == 0) { return ""; } if (a.length == 1) { return String.valueOf(a[0]); } StringBuilder sb = new StringBuilder(String.valueOf(a[0])); for (int i = 1; i < a.length; i++) { sb.append(delim).append(a[i]); } return sb.toString(); } /** * Concatenate the string representations of the objects, placing the system-specific line * separator between them. * * @see org.plumelib.util.ArraysPlume#toString(int[]) * @param a array of values to concatenate * @return the concatenation of the string representations of the values, each on its own line */ public static String joinLines(Object... a) { return join(a, lineSep); } /** * Concatenate the string representations of the objects, placing the delimiter between them. * * @see java.util.AbstractCollection#toString() * @param v collection of values to concatenate * @param delim delimiter to place between printed representations * @return the concatenation of the string representations of the values, with the delimiter * between */ public static String join(Iterable<? extends Object> v, String delim) { StringBuilder sb = new StringBuilder(); boolean first = true; Iterator<?> itor = v.iterator(); while (itor.hasNext()) { if (first) { first = false; } else { sb.append(delim); } sb.append(itor.next()); } return sb.toString(); } /** * Concatenate the string representations of the objects, placing the system-specific line * separator between them. * * @see java.util.AbstractCollection#toString() * @param v list of values to concatenate * @return the concatenation of the string representations of the values, each on its own line */ public static String joinLines(List<String> v) { return join(v, lineSep); } /** * Escape \, ", newline, and carriage-return characters in the target as \\, \", \n, and \r; * return a new string if any modifications were necessary. The intent is that by surrounding the * return value with double quote marks, the result will be a Java string literal denoting the * original string. * * @param orig string to quote * @return quoted version of orig */ public static String escapeNonJava(String orig) { StringBuilder sb = new StringBuilder(); // The previous escape character was seen right before this position. /*@IndexOrHigh("orig")*/ int post_esc = 0; int orig_len = orig.length(); for (int i = 0; i < orig_len; i++) { char c = orig.charAt(i); switch (c) { case '\"': case '\\': if (post_esc < i) { sb.append(orig.substring(post_esc, i)); } sb.append('\\'); post_esc = i; break; case '\n': // not lineSep if (post_esc < i) { sb.append(orig.substring(post_esc, i)); } sb.append("\\n"); // not lineSep post_esc = i + 1; break; case '\r': if (post_esc < i) { sb.append(orig.substring(post_esc, i)); } sb.append("\\r"); post_esc = i + 1; break; default: // Nothing to do: i gets incremented } } if (sb.length() == 0) { return orig; } sb.append(orig.substring(post_esc)); return sb.toString(); } // The overhead of this is too high to call in escapeNonJava(String), so // it is inlined there. /** * Like {@link #escapeNonJava(String)}, but for a single character. * * @param ch character to quote * @return quoted version och ch */ public static String escapeNonJava(Character ch) { char c = ch.charValue(); switch (c) { case '\"': return "\\\""; case '\\': return "\\\\"; case '\n': // not lineSep return "\\n"; // not lineSep case '\r': return "\\r"; default: return new String(new char[] {c}); } } /** * Escape unprintable characters in the target, following the usual Java backslash conventions, so * that the result is sure to be printable ASCII. Returns a new string. * * @param orig string to quote * @return quoted version of orig */ public static String escapeNonASCII(String orig) { StringBuilder sb = new StringBuilder(); int orig_len = orig.length(); for (int i = 0; i < orig_len; i++) { char c = orig.charAt(i); sb.append(escapeNonASCII(c)); } return sb.toString(); } /** * Like escapeNonJava(), but quote more characters so that the result is sure to be printable * ASCII. * * <p>This implementatino is not particularly optimized. * * @param c character to quote * @return quoted version of c */ private static String escapeNonASCII(char c) { if (c == '"') { return "\\\""; } else if (c == '\\') { return "\\\\"; } else if (c == '\n') { // not lineSep return "\\n"; // not lineSep } else if (c == '\r') { return "\\r"; } else if (c == '\t') { return "\\t"; } else if (c >= ' ' && c <= '~') { return new String(new char[] {c}); } else if (c < 256) { String octal = Integer.toOctalString(c); while (octal.length() < 3) { octal = '0' + octal; } return "\\" + octal; } else { String hex = Integer.toHexString(c); while (hex.length() < 4) { hex = "0" + hex; } return "\\u" + hex; } } /** * Replace "\\", "\"", "\n", and "\r" sequences by their one-character equivalents. All other * backslashes are removed (for instance, octal/hex escape sequences are not turned into their * respective characters). This is the inverse operation of escapeNonJava(). Previously known as * unquote(). * * @param orig string to quoto * @return quoted version of orig */ public static String unescapeNonJava(String orig) { StringBuilder sb = new StringBuilder(); // The previous escape character was seen just before this position. /*@LTEqLengthOf("orig")*/ int post_esc = 0; int this_esc = orig.indexOf('\\'); while (this_esc != -1) { if (this_esc == orig.length() - 1) { sb.append(orig.substring(post_esc, this_esc + 1)); post_esc = this_esc + 1; break; } switch (orig.charAt(this_esc + 1)) { case 'n': sb.append(orig.substring(post_esc, this_esc)); sb.append('\n'); // not lineSep post_esc = this_esc + 2; break; case 'r': sb.append(orig.substring(post_esc, this_esc)); sb.append('\r'); post_esc = this_esc + 2; break; case '\\': // This is not in the default case because the search would find // the quoted backslash. Here we incluce the first backslash in // the output, but not the first. sb.append(orig.substring(post_esc, this_esc + 1)); post_esc = this_esc + 2; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': sb.append(orig.substring(post_esc, this_esc)); char octal_char = 0; int ii = this_esc + 1; while (ii < orig.length()) { char ch = orig.charAt(ii++); if ((ch < '0') || (ch > '8')) { break; } octal_char = (char) ((octal_char * 8) + Character.digit(ch, 8)); } sb.append(octal_char); post_esc = ii - 1; break; default: // In the default case, retain the character following the backslash, // but discard the backslash itself. "\*" is just a one-character string. sb.append(orig.substring(post_esc, this_esc)); post_esc = this_esc + 1; break; } this_esc = orig.indexOf('\\', post_esc); } if (post_esc == 0) { return orig; } sb.append(orig.substring(post_esc)); return sb.toString(); } /** * Remove all whitespace before or after instances of delimiter. * * @param arg string to remove whitespace in * @param delimiter string to remove whitespace abutting * @return version of arg, with whitespace abutting delimiter removed */ public static String removeWhitespaceAround(String arg, String delimiter) { arg = removeWhitespaceBefore(arg, delimiter); arg = removeWhitespaceAfter(arg, delimiter); return arg; } /** * Remove all whitespace after instances of delimiter. * * @param arg string to remove whitespace in * @param delimiter string to remove whitespace after * @return version of arg, with whitespace after delimiter removed */ public static String removeWhitespaceAfter(String arg, String delimiter) { if (delimiter == null || delimiter.equals("")) { throw new IllegalArgumentException("Bad delimiter: \"" + delimiter + "\""); } // String orig = arg; int delim_len = delimiter.length(); int delim_index = arg.indexOf(delimiter); while (delim_index > -1) { int non_ws_index = delim_index + delim_len; while ((non_ws_index < arg.length()) && (Character.isWhitespace(arg.charAt(non_ws_index)))) { non_ws_index++; } // if (non_ws_index == arg.length()) { // System.out.println("No nonspace character at end of: " + arg); // } else { // System.out.println("'" + arg.charAt(non_ws_index) + "' not a space character at " + // non_ws_index + " in: " + arg); // } if (non_ws_index != delim_index + delim_len) { arg = arg.substring(0, delim_index + delim_len) + arg.substring(non_ws_index); } delim_index = arg.indexOf(delimiter, delim_index + 1); } return arg; } /** * Remove all whitespace before instances of delimiter. * * @param arg string to remove whitespace in * @param delimiter string to remove whitespace before * @return version of arg, with whitespace before delimiter removed */ public static String removeWhitespaceBefore(String arg, String delimiter) { if (delimiter == null || delimiter.equals("")) { throw new IllegalArgumentException("Bad delimiter: \"" + delimiter + "\""); } // System.out.println("removeWhitespaceBefore(\"" + arg + "\", \"" + delimiter + "\")"); // String orig = arg; int delim_index = arg.indexOf(delimiter); while (delim_index > -1) { int non_ws_index = delim_index - 1; while ((non_ws_index >= 0) && (Character.isWhitespace(arg.charAt(non_ws_index)))) { non_ws_index--; } // if (non_ws_index == -1) { // System.out.println("No nonspace character at front of: " + arg); // } else { // System.out.println("'" + arg.charAt(non_ws_index) + "' not a space character at " + // non_ws_index + " in: " + arg); // } if (non_ws_index != delim_index - 1) { arg = arg.substring(0, non_ws_index + 1) + arg.substring(delim_index); } delim_index = arg.indexOf(delimiter, non_ws_index + 2); } return arg; } /** * Return either "n <em>noun</em>" or "n <em>noun</em>s" depending on n. Adds "es" to words ending * with "ch", "s", "sh", or "x". * * @param n count of nouns * @param noun word being counted * @return noun, if n==1; otherwise, pluralization of noun */ public static String nplural(int n, String noun) { if (n == 1) { return n + " " + noun; } else if (noun.endsWith("ch") || noun.endsWith("s") || noun.endsWith("sh") || noun.endsWith("x")) { return n + " " + noun + "es"; } else { return n + " " + noun + "s"; } } /** * Returns a string of the specified length, truncated if necessary, and padded with spaces to the * left if necessary. * * @param s string to truncate or pad * @param length goal length * @return s truncated or padded to length characters */ public static String lpad(String s, /*@NonNegative*/ int length) { if (s.length() < length) { StringBuilder buf = new StringBuilder(); for (int i = s.length(); i < length; i++) { buf.append(' '); } return buf.toString() + s; } else { return s.substring(0, length); } } /** * Returns a string of the specified length, truncated if necessary, and padded with spaces to the * right if necessary. * * @param s string to truncate or pad * @param length goal length * @return s truncated or padded to length characters */ public static String rpad(String s, /*@NonNegative*/ int length) { if (s.length() < length) { StringBuilder buf = new StringBuilder(s); for (int i = s.length(); i < length; i++) { buf.append(' '); } return buf.toString(); } else { return s.substring(0, length); } } /** * Converts the int to a String, then formats it using {@link #rpad(String,int)}. * * @param num int whose string representation to truncate or pad * @param length goal length * @return a string representation of num truncated or padded to length characters */ public static String rpad(int num, /*@NonNegative*/ int length) { return rpad(String.valueOf(num), length); } /** * Converts the double to a String, then formats it using {@link #rpad(String,int)}. * * @param num double whose string representation to truncate or pad * @param length goal length * @return a string representation of num truncated or padded to length characters */ public static String rpad(double num, /*@NonNegative*/ int length) { return rpad(String.valueOf(num), length); } /** * Same as built-in String comparison, but accept null arguments, and place them at the beginning. */ public static class NullableStringComparator implements Comparator<String>, Serializable { static final long serialVersionUID = 20150812L; /*@Pure*/ @Override public int compare(String s1, String s2) { if (s1 == null && s2 == null) { return 0; } if (s1 == null && s2 != null) { return 1; } if (s1 != null && s2 == null) { return -1; } return s1.compareTo(s2); } } // This could test the types of the elemets, and do something more sophisticated based on the // types. /** * Attempt to order Objects. Puts null at the beginning. Returns 0 for equal elements. Otherwise, * orders by the result of {@code toString()}. * * <p>Note: if toString returns a nondeterministic value, such as one that depends on the result * of {@code hashCode()}, then this comparator may yield different orderings from run to run of a * program. */ public static class ObjectComparator implements Comparator</*@Nullable*/ Object>, Serializable { static final long serialVersionUID = 20170420L; @SuppressWarnings({ "purity.not.deterministic.call", "lock" }) // toString is being used in a deterministic way /*@Pure*/ @Override public int compare(/*@Nullable*/ Object o1, /*@Nullable*/ Object o2) { // Make null compare smaller than anything else if ((o1 == o2)) { return 0; } if (o1 == null) { return -1; } if (o2 == null) { return 1; } if (o1.equals(o2)) { return 0; } // Don't compare output of hashCode() because it is non-deterministic from run to run. String s1 = o1.toString(); String s2 = o2.toString(); return s1.compareTo(s2); } } /** * Return the number of times the character appears in the string. * * @param s string to search in * @param ch character to search for * @return number of times the character appears in the string */ public static int count(String s, int ch) { int result = 0; int pos = s.indexOf(ch); while (pos > -1) { result++; pos = s.indexOf(ch, pos + 1); } return result; } /** * Return the number of times the second string appears in the first. * * @param s string to search in * @param sub string to search for * @return number of times the substring appears in the string */ public static int count(String s, String sub) { int result = 0; int pos = s.indexOf(sub); while (pos > -1) { result++; pos = s.indexOf(sub, pos + 1); } return result; } /////////////////////////////////////////////////////////////////////////// /// StringTokenizer /// /** * Return a ArrayList of the Strings returned by {@link * java.util.StringTokenizer#StringTokenizer(String,String,boolean)} with the given arguments. * * <p>The static type is {@code ArrayList<Object>} because StringTokenizer extends {@code * Enumeration<Object>} instead of {@code Enumeration<String>} as it should (probably due to * backward-compatibility). * * @param str a string to be parsed * @param delim the delimiters * @param returnDelims flag indicating whether to return the delimiters as tokens * @return vector of strings resulting from tokenization */ public static ArrayList<Object> tokens(String str, String delim, boolean returnDelims) { return makeArrayList(new StringTokenizer(str, delim, returnDelims)); } /** * Return a ArrayList of the Strings returned by {@link * java.util.StringTokenizer#StringTokenizer(String,String)} with the given arguments. * * @param str a string to be parsed * @param delim the delimiters * @return vector of strings resulting from tokenization */ public static ArrayList<Object> tokens(String str, String delim) { return makeArrayList(new StringTokenizer(str, delim)); } /** * Return a ArrayList of the Strings returned by {@link * java.util.StringTokenizer#StringTokenizer(String)} with the given arguments. * * @param str a string to be parsed * @return vector of strings resulting from tokenization */ public static ArrayList<Object> tokens(String str) { return makeArrayList(new StringTokenizer(str)); } /////////////////////////////////////////////////////////////////////////// /// Throwable /// /** * Return a String representation of the backtrace of the given Throwable. To see a backtrace at * the the current location, do {@code backtrace(new Throwable())}. * * @param t the Throwable to obtain a backtrace of * @return a String representation of the backtrace of the given Throwable */ public static String backTrace(Throwable t) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); pw.close(); String result = sw.toString(); return result; } /////////////////////////////////////////////////////////////////////////// /// Collections /// /** * Return the sorted version of the list. Does not alter the list. Simply calls {@code * Collections.sort(List<T>, Comparator<? super T>)}. * * @return a sorted version of the list * @param <T> type of elements of the list * @param l a list to sort * @param c a sorted version of the list */ public static <T> List<T> sortList(List<T> l, Comparator<? super T> c) { List<T> result = new ArrayList<T>(l); Collections.sort(result, c); return result; } // This should perhaps be named withoutDuplicates to emphasize that // it does not side-effect its argument. /** * Return a copy of the list with duplicates removed. Retains the original order. * * @param <T> type of elements of the list * @param l a list to remove duplicates from * @return a copy of the list with duplicates removed */ public static <T> List<T> removeDuplicates(List<T> l) { HashSet<T> hs = new LinkedHashSet<T>(l); List<T> result = new ArrayList<T>(hs); return result; } /** All calls to deepEquals that are currently underway. */ private static HashSet<WeakIdentityPair<Object, Object>> deepEqualsUnderway = new HashSet<WeakIdentityPair<Object, Object>>(); /** * Determines deep equality for the elements. * * <ul> * <li>If both are primitive arrays, uses java.util.Arrays.equals. * <li>If both are Object[], uses java.util.Arrays.deepEquals and does not recursively call this * method. * <li>If both are lists, uses deepEquals recursively on each element. * <li>For other types, just uses equals() and does not recursively call this method. * </ul> * * @param o1 first value to compare * @param o2 second value to comare * @return true iff o1 and o2 are deeply equal */ @SuppressWarnings({"purity", "lock"}) // side effect to static field deepEqualsUnderway /*@Pure*/ public static boolean deepEquals(/*@Nullable*/ Object o1, /*@Nullable*/ Object o2) { @SuppressWarnings("interning") boolean sameObject = (o1 == o2); if (sameObject) { return true; } if (o1 == null || o2 == null) { return false; } if (o1 instanceof boolean[] && o2 instanceof boolean[]) { return Arrays.equals((boolean[]) o1, (boolean[]) o2); } if (o1 instanceof byte[] && o2 instanceof byte[]) { return Arrays.equals((byte[]) o1, (byte[]) o2); } if (o1 instanceof char[] && o2 instanceof char[]) { return Arrays.equals((char[]) o1, (char[]) o2); } if (o1 instanceof double[] && o2 instanceof double[]) { return Arrays.equals((double[]) o1, (double[]) o2); } if (o1 instanceof float[] && o2 instanceof float[]) { return Arrays.equals((float[]) o1, (float[]) o2); } if (o1 instanceof int[] && o2 instanceof int[]) { return Arrays.equals((int[]) o1, (int[]) o2); } if (o1 instanceof long[] && o2 instanceof long[]) { return Arrays.equals((long[]) o1, (long[]) o2); } if (o1 instanceof short[] && o2 instanceof short[]) { return Arrays.equals((short[]) o1, (short[]) o2); } @SuppressWarnings({"purity", "lock"}) // creates local state WeakIdentityPair<Object, Object> mypair = new WeakIdentityPair<Object, Object>(o1, o2); if (deepEqualsUnderway.contains(mypair)) { return true; } if (o1 instanceof Object[] && o2 instanceof Object[]) { return Arrays.deepEquals((Object[]) o1, (Object[]) o2); } if (o1 instanceof List<?> && o2 instanceof List<?>) { List<?> l1 = (List<?>) o1; List<?> l2 = (List<?>) o2; if (l1.size() != l2.size()) { return false; } try { deepEqualsUnderway.add(mypair); for (int i = 0; i < l1.size(); i++) { Object e1 = l1.get(i); Object e2 = l2.get(i); if (!deepEquals(e1, e2)) { return false; } } } finally { deepEqualsUnderway.remove(mypair); } return true; } return o1.equals(o2); } /////////////////////////////////////////////////////////////////////////// /// ArrayList /// /** * Returns a vector containing the elements of the enumeration. * * @param <T> type of the enumeration and vector elements * @param e an enumeration to convert to a ArrayList * @return a vector containing the elements of the enumeration */ public static <T> ArrayList<T> makeArrayList(Enumeration<T> e) { ArrayList<T> result = new ArrayList<T>(); while (e.hasMoreElements()) { result.add(e.nextElement()); } return result; } // Rather than writing something like ArrayListToStringArray, use // v.toArray(new String[0]) /** * Returns a list of lists of each combination (with repetition, but not permutations) of the * specified objects starting at index {@code start} over {@code dims} dimensions, for {@code dims * > 0}. * * <p>For example, create_combinations (1, 0, {a, b, c}) returns: * * <pre> * {a}, {b}, {c} * </pre> * * And create_combinations (2, 0, {a, b, c}) returns: * * <pre> * {a, a}, {a, b}, {a, c} * {b, b}, {b, c}, * {c, c} * </pre> * * @param <T> type of the input list elements, and type of the innermost output list elements * @param dims number of dimensions: that is, size of each innermost list * @param start initial index * @param objs list of elements to create combinations of * @return list of lists of length dims, each of which combines elements from objs */ public static <T> List<List<T>> create_combinations( int dims, /*@NonNegative*/ int start, List<T> objs) { if (dims < 1) { throw new IllegalArgumentException(); } List<List<T>> results = new ArrayList<List<T>>(); for (int i = start; i < objs.size(); i++) { if (dims == 1) { List<T> simple = new ArrayList<T>(); simple.add(objs.get(i)); results.add(simple); } else { List<List<T>> combos = create_combinations(dims - 1, i, objs); for (List<T> lt : combos) { List<T> simple = new ArrayList<T>(); simple.add(objs.get(i)); simple.addAll(lt); results.add(simple); } } } return (results); } /** * Returns a list of lists of each combination (with repetition, but not permutations) of integers * from start to cnt (inclusive) over arity dimensions. * * <p>For example, create_combinations (1, 0, 2) returns: * * <pre> * {0}, {1}, {2} * </pre> * * And create_combinations (2, 10, 2) returns: * * <pre> * {10, 10}, {10, 11}, {10, 12} * {11, 11} {11, 12}, * {12, 12} * </pre> * * @param arity size of each innermost list * @param start initial value * @param cnt maximum element value * @return list of lists of length arity, each of which combines integers from start to cnt */ public static ArrayList<ArrayList<Integer>> create_combinations( int arity, /*@NonNegative*/ int start, int cnt) { ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>(); // Return a list with one zero length element if arity is zero if (arity == 0) { results.add(new ArrayList<Integer>()); return (results); } for (int i = start; i <= cnt; i++) { ArrayList<ArrayList<Integer>> combos = create_combinations(arity - 1, i, cnt); for (ArrayList<Integer> li : combos) { ArrayList<Integer> simple = new ArrayList<Integer>(); simple.add(i); simple.addAll(li); results.add(simple); } } return (results); } /** * Returns the simple unqualified class name that corresponds to the specified fully qualified * name. For example, if qualified_name is java.lang.String, String will be returned. * * @deprecated use {@link #fullyQualifiedNameToSimpleName} instead. * @param qualified_name the fully-qualified name of a class * @return the simple unqualified name of the class */ @Deprecated public static /*@ClassGetSimpleName*/ String unqualified_name( /*@FullyQualifiedName*/ String qualified_name) { return fullyQualifiedNameToSimpleName(qualified_name); } /** * Returns the simple unqualified class name that corresponds to the specified fully qualified * name. For example, if qualified_name is java.lang.String, String will be returned. * * @param qualified_name the fully-qualified name of a class * @return the simple unqualified name of the class */ // TODO: does not follow the specification for inner classes (where the // type name should be empty), but I think this is more informative anyway. @SuppressWarnings("signature") // string conversion public static /*@ClassGetSimpleName*/ String fullyQualifiedNameToSimpleName( /*@FullyQualifiedName*/ String qualified_name) { int offset = qualified_name.lastIndexOf('.'); if (offset == -1) { return (qualified_name); } return (qualified_name.substring(offset + 1)); } /** * Returns the simple unqualified class name that corresponds to the specified class. For example * if qualified name of the class is java.lang.String, String will be returned. * * @deprecated use {@link Class#getSimpleName()} instead. * @param cls a class * @return the simple unqualified name of the class */ @Deprecated public static /*@ClassGetSimpleName*/ String unqualified_name(Class<?> cls) { return cls.getSimpleName(); } /** * Convert a number into an abbreviation such as "5.00K" for 5000 or "65.0M" for 65000000. K * stands for 1000, not 1024; M stands for 1000000, not 1048576, etc. There are always exactly 3 * decimal digits of precision in the result (counting both sides of the decimal point). * * @param val a numeric value * @return an abbreviated string representation of the value */ public static String abbreviateNumber(long val) { double dval = (double) val; String mag = ""; if (val < 1000) { // nothing to do } else if (val < 1000000) { dval = val / 1000.0; mag = "K"; } else if (val < 1000000000) { dval = val / 1000000.0; mag = "M"; } else { dval = val / 1000000000.0; mag = "G"; } String precision = "0"; if (dval < 10) { precision = "2"; } else if (dval < 100) { precision = "1"; } @SuppressWarnings("formatter") // format string computed from precision and mag String result = String.format("%,1." + precision + "f" + mag, dval); return result; } }
Prevent infinite loop
src/main/java/org/plumelib/util/UtilPlume.java
Prevent infinite loop
<ide><path>rc/main/java/org/plumelib/util/UtilPlume.java <ide> * Return the number of times the second string appears in the first. <ide> * <ide> * @param s string to search in <del> * @param sub string to search for <add> * @param sub non-empty string to search for <ide> * @return number of times the substring appears in the string <ide> */ <ide> public static int count(String s, String sub) { <add> if (sub.equals("")) { <add> throw new IllegalArgumentException("second argument must not be empty"); <add> } <ide> int result = 0; <ide> int pos = s.indexOf(sub); <ide> while (pos > -1) {
JavaScript
cc0-1.0
41e496bc20c83865a1662180b9525bc958d07655
0
iterami/common,iterami/common,iterami/common
'use strict'; // Required args: todo, url function core_ajax(args){ args = core_args({ 'args': args, 'defaults': { 'data': null, 'readyState': 4, 'status': 200, 'type': 'GET', }, }); let ajax = new XMLHttpRequest(); ajax.onreadystatechange = function(){ if(this.readyState === args['readyState'] && this.status === args['status']){ args['todo'](this.responseText); } }; ajax.open( args['type'], args['url'] ); ajax.send(args['data']); } // Required args: args, defaults function core_args(args){ if(args['args'] === void 0){ args['args'] = {}; } for(let arg in args['defaults']){ if(args['args'][arg] === void 0){ args['args'][arg] = args['defaults'][arg]; } } return args['args']; } // Required args: todo function core_call(args){ args = core_args({ 'args': args, 'defaults': { 'args': void 0, }, }); if(core_type({ 'var': args['todo'], })){ window[args['todo']](args['args']); } } // Required args: number function core_digits_min(args){ args = core_args({ 'args': args, 'defaults': { 'digits': 2, }, }); let result = args['number'] < 0 ? '-' : ''; args['number'] = Math.abs(args['number']); result += args['number']; while(String(result).length < args['digits']){ result = '0' + result; } return result; } function core_entity_create(args){ args = core_args({ 'args': args, 'defaults': { 'id': core_id_count, 'properties': {}, 'types': [], }, }); core_id_count++; let entity = {}; for(let type in core_entity_types_default){ core_entity_handle_defaults({ 'entity': entity, 'id': args['id'], 'type': core_entity_types_default[type], }); } for(let type in args['types']){ core_entity_handle_defaults({ 'entity': entity, 'id': args['id'], 'type': args['types'][type], }); } for(let property in args['properties']){ entity[property] = core_handle_defaults({ 'default': entity[property], 'var': args['properties'][property], }); } core_entities[args['id']] = entity; for(let type in core_entity_types_default){ core_entity_info[core_entity_types_default[type]]['todo'](args['id']); } for(let type in args['types']){ core_entity_info[args['types'][type]]['todo'](args['id']); } return args['id']; } // Required args: id, type function core_entity_handle_defaults(args){ for(let property in core_entity_info[args['type']]['default']){ args['entity'][property] = core_handle_defaults({ 'default': args['entity'][property], 'var': core_entity_info[args['type']]['default'][property], }); } if(core_groups[args['type']][args['id']] === void 0){ core_group_add({ 'entities': [ args['id'], ], 'group': args['type'], }); core_entity_info[args['type']]['count']++; } for(let group in core_entity_info[args['type']]['groups']){ core_group_add({ 'entities': [ args['id'], ], 'group': core_entity_info[args['type']]['groups'][group], }); } } // Required args: entities function core_entity_remove(args){ args = core_args({ 'args': args, 'defaults': { 'delete-empty': false, }, }); core_group_remove_all({ 'delete-empty': args['delete-empty'], 'entities': args['entities'], }); for(let entity in args['entities']){ delete core_entities[args['entities'][entity]]; } } function core_entity_remove_all(args){ args = core_args({ 'args': args, 'defaults': { 'delete-empty': false, 'group': false, }, }); for(let entity in core_entities){ if(args['group'] !== false && !core_groups[args['group']][entity]){ continue; } core_entity_remove({ 'delete-empty': args['delete-empty'], 'entities': [ entity, ], }); } } // Required args: type function core_entity_set(args){ args = core_args({ 'args': args, 'defaults': { 'default': false, 'groups': [], 'properties': {}, 'todo': function(){}, }, }); core_entity_info[args['type']] = { 'count': 0, 'default': args['properties'], 'groups': args['groups'], 'todo': args['todo'], }; if(args['default']){ core_entity_types_default.push(args['type']); } core_group_create({ 'ids': [ args['type'], ], }); } function core_escape(){ core_menu_open = !core_menu_open; if(!core_menu_open){ document.getElementById('core-menu').style.display = 'none'; document.getElementById('core-ui').style.userSelect = 'none'; document.getElementById('repo-ui').style.display = 'block'; core_storage_save(); core_interval_resume_all(); }else{ core_interval_pause_all(); document.getElementById('repo-ui').style.display = 'none'; document.getElementById('core-ui').style.userSelect = 'auto'; document.getElementById('core-menu').style.display = 'inline'; } core_call({ 'todo': 'repo_escape', }); } function core_events_bind(args){ args = core_args({ 'args': args, 'defaults': { 'beforeunload': false, 'clearkeys': false, 'clearmouse': false, 'elements': false, 'keybinds': false, 'mousebinds': false, }, }); if(args['beforeunload'] !== false){ core_events['beforeunload'] = core_handle_defaults({ 'default': { 'loop': false, 'preventDefault': false, 'solo': false, 'state': false, 'todo': function(){}, }, 'var': args['beforeunload'], }); } if(args['keybinds'] !== false){ core_keys_updatebinds({ 'clear': args['clearkeys'], 'keybinds': args['keybinds'], }); } if(args['mousebinds'] !== false){ core_mouse_updatebinds({ 'clear': args['clearmouse'], 'mousebinds': args['mousebinds'], }); } if(args['elements'] !== false){ for(let element in args['elements']){ let domelement = document.getElementById(element); for(let event in args['elements'][element]){ domelement[event] = args['elements'][element][event]; } } } } function core_events_keyinfo(event){ let code = event.keyCode || event.which; return { 'code': code, 'key': String.fromCharCode(code), }; } function core_events_todoloop(){ for(let key in core_keys){ if(core_keys[key]['state'] && core_keys[key]['loop']){ core_keys[key]['todo'](); } } for(let mousebind in core_mouse['todo']){ if(core_mouse['todo'][mousebind]['loop']){ core_mouse['todo'][mousebind]['todo'](); } } } // Required args: file, todo function core_file(args){ args = core_args({ 'args': args, 'defaults': { 'type': 'readAsDataURL', }, }); let filereader = new FileReader(); filereader.onload = function(event){ args['todo'](event); }; filereader[args['type']](args['file']); } // Required args: entities, group function core_group_add(args){ if(!(args['group'] in core_groups)){ core_group_create({ 'id': args['group'], }); } for(let entity in args['entities']){ if(core_groups[args['group']][args['entities'][entity]]){ return; } core_groups[args['group']][args['entities'][entity]] = true; core_groups['_length'][args['group']]++; } } // Required args: ids function core_group_create(args){ for(let id in args['ids']){ core_groups[args['ids'][id]] = {}; core_groups['_length'][args['ids'][id]] = 0; } } // Required args: groups, todo function core_group_modify(args){ args = core_args({ 'args': args, 'defaults': { 'pretodo': false, }, }); let pretodo = {}; if(args['pretodo'] !== false){ pretodo = args['pretodo'](); } for(let group in args['groups']){ for(let entity in core_groups[args['groups'][group]]){ args['todo']( entity, pretodo ); } } } // Required args: entities, from, to function core_group_move(args){ core_group_remove({ 'entities': args['entities'], 'group': args['from'], }); core_group_add({ 'entities': args['entities'], 'group': args['to'], }); } // Required args: entities, group function core_group_remove(args){ args = core_args({ 'args': args, 'defaults': { 'delete-empty': false, }, }); if(core_groups[args['group']] === void 0){ return; } for(let entity in args['entities']){ if(!core_groups[args['group']][args['entities'][entity]]){ continue; } delete core_groups[args['group']][args['entities'][entity]]; core_groups['_length'][args['group']]--; if(core_entity_info[args['group']]){ core_entity_info[args['group']]['count']--; } } if(args['delete-empty'] && core_groups['_length'][args['group']] === 0){ delete core_groups[args['group']]; delete core_groups['_length'][args['group']]; } } // Required args: entities function core_group_remove_all(args){ args = core_args({ 'args': args, 'defaults': { 'delete-empty': false, }, }); for(let group in core_groups){ if(group === '_length'){ continue; } core_group_remove({ 'delete-empty': args['delete-empty'], 'entities': args['entities'], 'group': group, }); } } function core_handle_beforeunload(event){ let result = core_handle_event({ 'event': event, 'key': 'beforeunload', 'object': core_events, 'todo': true, }); core_storage_save(); if(core_type({ 'type': 'string', 'var': result, })){ return result; } } function core_handle_blur(event){ for(let key in core_keys){ core_keys[key]['state'] = false; } core_mouse['down-0'] = false; core_mouse['down-1'] = false; core_mouse['down-2'] = false; core_mouse['down-3'] = false; core_mouse['down-4'] = false; } function core_handle_contextmenu(event){ let result = core_handle_event({ 'event': event, 'key': 'contextmenu', 'object': core_mouse['todo'], 'todo': true, }); if(result === void 0 && !core_menu_open){ return false; } } function core_handle_defaults(args){ args = core_args({ 'args': args, 'defaults': { 'default': {}, 'var': {}, }, }); if(!core_type({ 'type': 'object', 'var': args['var'], })){ return args['var']; } let object = args['default']; for(let property in args['var']){ object[property] = core_handle_defaults({ 'var': args['var'][property], }); } return object; } // Required args: event, key, object function core_handle_event(args){ args = core_args({ 'args': args, 'defaults': { 'state': void 0, 'todo': void 0, }, }); if(args['object'].hasOwnProperty(args['key'])){ if(args['object'][args['key']]['preventDefault'] && !core_menu_open){ args['event'].preventDefault(); } let returned = void 0; if(args['todo'] !== void 0 && !args['object'][args['key']]['loop']){ returned = args['object'][args['key']]['todo'](args['event']); } if(args['state'] !== void 0){ args['object'][args['key']]['state'] = args['state']; } if(returned !== void 0){ return returned; } return args['object'][args['key']]['solo']; } return false; } function core_handle_gamepadconnected(event){ let gamepad = event.gamepad; core_gamepads[gamepad.index] = gamepad; } function core_handle_gamepaddisconnected(event){ delete core_gamepads[event.gamepad.index]; } function core_handle_keydown(event){ if(event.ctrlKey){ return; } let key = core_events_keyinfo(event); if(core_menu_open && core_menu_block_events && key['code'] !== 27){ return; } if(core_handle_event({ 'event': event, 'key': key['code'], 'object': core_keys, 'state': true, 'todo': true, })){ return; } core_handle_event({ 'event': event, 'key': 'all', 'object': core_keys, 'state': true, 'todo': true, }); } function core_handle_keyup(event){ let key = core_events_keyinfo(event); if(core_handle_event({ 'event': event, 'key': key['code'], 'object': core_keys, 'state': false, })){ return; } if(core_keys.hasOwnProperty('all')){ let all = false; for(let key in core_keys){ if(key !== 'all' && core_keys[key]['state']){ all = true; break; } } core_keys['all']['state'] = all; } } function core_handle_mousedown(event){ if((core_menu_open && core_menu_block_events) || event['target'].tagName.toLowerCase() === 'input'){ return; } core_mouse['down-' + event.button] = true; core_mouse['down-x'] = core_mouse['x']; core_mouse['down-y'] = core_mouse['y']; core_handle_event({ 'event': event, 'key': 'mousedown', 'object': core_mouse['todo'], 'todo': true, }); } function core_handle_mousemove(event){ if(core_menu_open && core_menu_block_events){ return; } core_mouse['movement-x'] = event.movementX * core_storage_data['mouse-sensitivity']; core_mouse['movement-y'] = event.movementY * core_storage_data['mouse-sensitivity']; core_mouse['x'] = event.pageX; core_mouse['y'] = event.pageY; core_handle_event({ 'event': event, 'key': 'mousemove', 'object': core_mouse['todo'], 'todo': true, }); } function core_handle_mouseup(event){ core_mouse['down-' + event.button] = false; core_handle_event({ 'event': event, 'key': 'mouseup', 'object': core_mouse['todo'], 'todo': true, }); } function core_handle_mousewheel(event){ if(core_menu_open && core_menu_block_events){ return; } core_handle_event({ 'event': event, 'key': 'mousewheel', 'object': core_mouse['todo'], 'todo': true, }); } function core_handle_pointerlockchange(event){ let element = document.getElementById(core_mouse['pointerlock-id']); if(!element){ return; } core_mouse['pointerlock-state'] = element === document.pointerLockElement; if(!core_mouse['pointerlock-state']){ core_escape(); } }; // Required args: hex function core_hex_to_rgb(args){ if(args['hex'][0] === '#'){ args['hex'] = args['hex'].slice(1); } if(args['hex'].length === 3){ args['hex'] = args['hex'][0] + args['hex'][0] + args['hex'][1] + args['hex'][1] + args['hex'][2] + args['hex'][2]; } let rgb = { 'blue': '0x' + args['hex'][4] + args['hex'][5] | 0, 'green': '0x' + args['hex'][2] + args['hex'][3] | 0, 'red': '0x' + args['hex'][0] + args['hex'][1] | 0, }; return 'rgb(' + rgb['red'] + ', ' + rgb['green'] + ', ' + rgb['blue'] + ')'; } function core_html(args){ args = core_args({ 'args': args, 'defaults': { 'parent': false, 'properties': {}, 'type': 'div', }, }); let element = document.createElement(args['type']); for(let property in args['properties']){ element[property] = core_handle_defaults({ 'var': args['properties'][property], }); } if(typeof args['parent'] === 'string'){ document.getElementById(args['parent']).appendChild(element); }else if(typeof args['parent'] === 'object'){ args['parent'].appendChild(element); } return element; } // Required args: string function core_html_format(args){ return core_replace_multiple({ 'patterns': { //'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;', '\'': '&apos;', '\n\r': '<br>', }, 'string': args['string'], }); } // Required args: id, properties function core_html_modify(args){ let element = document.getElementById(args['id']); if(!element){ return; } Object.assign( element, args['properties'] ); } // Required args: id, src function core_image(args){ args = core_args({ 'args': args, 'defaults': { 'todo': function(){}, }, }); let image = new Image(); image.onload = args['todo']; image.src = args['src']; core_images[args['id']] = image; return image; } function core_init(){ // Core menu init. let core_ui = core_html({ 'properties': { 'id': 'core-ui', }, }) document.body.appendChild(core_ui); core_html({ 'parent': 'core-ui', 'properties': { 'id': 'core-toggle', 'onclick': core_escape, 'type': 'button', 'value': 'ESC', }, 'type': 'input', }); core_html({ 'parent': 'core-ui', 'properties': { 'id': 'core-menu', 'innerHTML': '<a href=../index.htm id=core-menu-root></a>/<a class=external id=core-menu-title rel=noopener></a>' + '<div id=core-menu-info></div><hr>' + '<span id=core-menu-tabs></span>' + '<div id=core-menu-tabcontent></div>' + '<input id=settings-reset type=button value="Reset All Settings">' + '<input id=settings-save type=button value="Save Settings">', }, 'type': 'span', }); core_html({ 'parent': 'core-ui', 'properties': { 'id': 'repo-ui', }, }); // Global storage. core_tab_create({ 'content': '<table><tr><td><input id=audio-volume><td>Audio Volume' + '<tr><td><input id=color-negative type=color><td>Color Negative' + '<tr><td><input id=color-positive type=color><td>Color Positive' + '<tr><td><input id=decimals><td>Decimals' + '<tr><td><input id=jump><td>Jump' + '<tr><td><input id=mouse-sensitivity><td>Mouse Sensitivity' + '<tr><td><input id=move-↑><td>Move ↑' + '<tr><td><input id=move-←><td>Move ←' + '<tr><td><input id=move-↓><td>Move ↓' + '<tr><td><input id=move-→><td>Move →</table>', 'group': 'core-menu', 'id': 'iterami', 'label': 'iterami', }); core_storage_add({ 'prefix': 'core-', 'storage': { 'audio-volume': 1, 'color-negative': '#663366', 'color-positive': '#206620', 'decimals': 7, 'jump': 32, 'mouse-sensitivity': 1, 'move-←': 65, 'move-↑': 87, 'move-→': 68, 'move-↓': 83, }, }); core_storage_update(); // Events + Keyboard/Mouse. core_mouse = { 'down-0': false, 'down-1': false, 'down-2': false, 'down-3': false, 'down-4': false, 'down-x': 0, 'down-y': 0, 'movement-x': 0, 'movement-y': 0, 'pointerlock-id': 'canvas', 'pointerlock-state': false, 'todo': {}, 'x': 0, 'y': 0, }; document.onpointerlockchange = core_handle_pointerlockchange; window.onbeforeunload = core_handle_beforeunload; window.onblur = core_handle_blur; window.oncontextmenu = core_handle_contextmenu; window.ongamepadconnected = core_handle_gamepadconnected; window.ongamepaddisconnected = core_handle_gamepaddisconnected; window.onkeydown = core_handle_keydown; window.onkeyup = core_handle_keyup; window.onmousedown = core_handle_mousedown; window.onmousemove = core_handle_mousemove; window.onmouseup = core_handle_mouseup; window.ontouchend = core_handle_mouseup; window.ontouchmove = core_handle_mousemove; window.ontouchstart = core_handle_mousedown; window.onwheel = core_handle_mousewheel; core_events_bind({ 'elements': { 'settings-reset': { 'onclick': core_storage_reset, }, 'settings-save': { 'onclick': core_storage_save, }, }, }); core_keys_rebind(); core_call({ 'todo': 'repo_init', }); } // Required args: id function core_interval_animationFrame(args){ core_intervals[args['id']]['var'] = window.requestAnimationFrame(core_intervals[args['id']]['todo']); } // Required args: id, todo function core_interval_modify(args){ args = core_args({ 'args': args, 'defaults': { 'animationFrame': false, 'clear': 'clearInterval', 'interval': 25, 'paused': false, 'set': 'setInterval', }, }); if(args['id'] in core_intervals){ core_interval_pause({ 'id': args['id'], }); } core_intervals[args['id']] = { 'animationFrame': args['animationFrame'], 'clear': args['clear'], 'interval': args['interval'], 'paused': args['paused'], 'set': args['set'], 'todo': args['todo'], }; if(!args['paused']){ core_interval_resume({ 'id': args['id'], }); } } // Required args: id function core_interval_pause(args){ if(!(args['id'] in core_intervals)){ return; } window[core_intervals[args['id']]['animationFrame'] ? 'cancelAnimationFrame' : core_intervals[args['id']]['clear']](core_intervals[args['id']]['var']); core_intervals[args['id']]['paused'] = true; } function core_interval_pause_all(){ for(let interval in core_intervals){ if(!core_intervals[interval]['paused']){ core_interval_pause({ 'id': interval, }); } } } // Required args: id function core_interval_remove(args){ if(!(args['id'] in core_intervals)){ return; } core_interval_pause({ 'id': args['id'], }); delete core_intervals[args['id']]; } function core_interval_remove_all(){ for(let interval in core_intervals){ core_interval_remove({ 'id': interval, }); } } // Required args: id function core_interval_resume(args){ if(!(args['id'] in core_intervals)){ return; } if(!core_intervals[args['id']]['paused']){ core_interval_pause({ 'id': args['id'], }); } core_intervals[args['id']]['paused'] = false; if(core_intervals[args['id']]['animationFrame']){ core_intervals[args['id']]['var'] = window.requestAnimationFrame(core_intervals[args['id']]['todo']); }else{ core_intervals[args['id']]['var'] = window[core_intervals[args['id']]['set']]( core_intervals[args['id']]['todo'], core_intervals[args['id']]['interval'] ); } } function core_interval_resume_all(){ for(let interval in core_intervals){ core_interval_resume({ 'id': interval, }); } } function core_keys_rebind(){ let keybinds = {}; Object.assign( keybinds, core_key_rebinds ); keybinds[27] = {// Escape 'solo': true, 'todo': core_escape, }; keybinds[core_storage_data['jump']] = {}; keybinds[core_storage_data['move-←']] = {}; keybinds[core_storage_data['move-↑']] = {}; keybinds[core_storage_data['move-→']] = {}; keybinds[core_storage_data['move-↓']] = {}; core_events_bind({ 'clearkeys': true, 'keybinds': keybinds, }); } // Required args: keybinds function core_keys_updatebinds(args){ args = core_args({ 'args': args, 'defaults': { 'clear': false, }, }); if(args['clear']){ core_keys = {}; } for(let keybind in args['keybinds']){ let key = keybind; if(keybind !== 'all'){ key = Number.parseInt( key, 10 ); if(Number.isNaN(key)){ key = keybind.charCodeAt(0); } } core_keys[key] = core_handle_defaults({ 'default': { 'loop': false, 'preventDefault': false, 'solo': false, 'state': false, 'todo': function(){}, }, 'var': args['keybinds'][keybind], }); } } // Required args: mousebinds function core_mouse_updatebinds(args){ args = core_args({ 'args': args, 'defaults': { 'clear': false, }, }); if(args['clear']){ core_mouse['todo'] = {}; } for(let mousebind in args['mousebinds']){ core_mouse['todo'][mousebind] = { 'loop': args['mousebinds'][mousebind]['loop'] || false, 'preventDefault': args['mousebinds'][mousebind]['preventDefault'] || false, 'todo': args['mousebinds'][mousebind]['todo'] || function(){}, }; } } // Required args: number function core_number_format(args){ args = core_args({ 'args': args, 'defaults': { 'decimals': core_storage_data['decimals'], }, }); return new Intl.NumberFormat( void 0, { 'maximumFractionDigits': args['decimals'], } ).format(args['number']); } function core_random_boolean(args){ args = core_args({ 'args': args, 'defaults': { 'chance': .5, }, }); return Math.random() < args['chance']; } function core_random_hex(){ let color = core_random_rgb(); let blue = '0' + color['blue'].toString(16); let green = '0' + color['green'].toString(16); let red = '0' + color['red'].toString(16); return red.slice(-2) + green.slice(-2) + blue.slice(-2); } function core_random_integer(args){ args = core_args({ 'args': args, 'defaults': { 'max': 100, 'todo': 'floor', }, }); return Math[args['todo']](core_random_number({ 'multiplier': args['max'], })); } // Required args: object function core_random_key(args){ let keys = Object.keys(args['object']); return keys[core_random_integer({ 'max': keys.length, })]; } function core_random_number(args){ args = core_args({ 'args': args, 'defaults': { 'multiplier': 1, }, }); return Math.random() * args['multiplier']; } function core_random_rgb(){ return { 'blue': core_random_integer({ 'max': 256, }), 'green': core_random_integer({ 'max': 256, }), 'red': core_random_integer({ 'max': 256, }), }; } function core_random_string(args){ args = core_args({ 'args': args, 'defaults': { 'characters': '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'length': 100, }, }); let string = ''; for(let loopCounter = 0; loopCounter < args['length']; loopCounter++){ string += args['characters'][core_random_integer({ 'max': args['characters'].length, })]; } return string; } // Required args: patterns, string function core_replace_multiple(args){ for(let pattern in args['patterns']){ args['string'] = args['string'].replace( new RegExp( pattern, 'g' ), args['patterns'][pattern] ); } return args['string']; } // Required args: title function core_repo_init(args){ args = core_args({ 'args': args, 'defaults': { 'beforeunload': false, 'entities': {}, 'events': {}, 'github': 'iterami', 'globals': {}, 'images': {}, 'info': '', 'keybinds': false, 'menu': false, 'menu-block-events': true, 'mousebinds': false, 'storage': {}, 'storage-menu': '', 'tabs': {}, 'ui': '', }, }); Object.assign( window, args['globals'] ); if(args['menu']){ core_escape(); } for(let entity in args['entities']){ core_entity_set({ 'default': args['entities'][entity]['default'], 'groups': args['entities'][entity]['groups'], 'properties': args['entities'][entity]['properties'], 'todo': args['entities'][entity]['todo'], 'type': entity, }); } core_repo_title = args['title']; core_storage_add({ 'storage': args['storage'], }); if(args['info'].length > 0){ document.getElementById('core-menu-info').innerHTML = '<hr>' + args['info']; } if(args['storage-menu'].length > 0){ core_tab_create({ 'content': args['storage-menu'], 'group': 'core-menu', 'id': 'repo', 'label': core_repo_title, }); } document.getElementById('core-menu-root').innerHTML = args['github']; let repo_title = document.getElementById('core-menu-title'); repo_title.href = 'https://github.com/' + args['github'] + '/' + core_repo_title; repo_title.innerHTML = core_repo_title; document.getElementById('repo-ui').innerHTML = args['ui']; let have_default = false; for(let tab in args['tabs']){ core_tab_create({ 'content': args['tabs'][tab]['content'], 'group': args['tabs'][tab]['group'], 'id': tab, 'label': args['tabs'][tab]['label'], }); if(args['tabs'][tab]['default']){ core_tab_switch({ 'id': 'tab_' + args['tabs'][tab]['group'] + '_' + tab, }); have_default = true; } } if(!have_default){ core_tab_switch({ 'id': 'tab_core-menu_repo', }); } core_storage_update(); if(args['keybinds'] !== false){ core_key_rebinds = args['keybinds']; } core_menu_block_events = args['menu-block-events']; core_events_bind({ 'beforeunload': args['beforeunload'], 'elements': args['events'], 'keybinds': args['keybinds'], 'mousebinds': args['mousebinds'], }); for(let image in args['images']){ core_image({ 'id': image, 'src': args['images'][image], }); } } function core_requestpointerlock(args){ if(core_menu_open){ return; } args = core_args({ 'args': args, 'defaults': { 'id': 'canvas', }, }); let element = document.getElementById(args['id']); if(!element){ return; } element.requestPointerLock(); core_mouse['pointerlock-id'] = args['id']; } // Required args: number function core_round(args){ args = core_args({ 'args': args, 'defaults': { 'decimals': core_storage_data['decimals'], }, }); let eIndex = String(args['number']).indexOf('e'); let eString = ''; if(eIndex >= 0){ eString = String(args['number']).slice(eIndex); args['number'] = String(args['number']).slice( 0, eIndex ); let power = Number(eString.slice(2)); if(power === args['decimals']){ eString = 'e-' + (power + 1); } } let result = Number( Math.round(args['number'] + 'e+' + args['decimals']) + 'e-' + args['decimals'] ); if(eString.length > 0){ result = Number(result + eString); } if(Number.isNaN(result) || Math.abs(result) < Number('1e-' + args['decimals'])){ result = 0; } return result; } // Required args: array, todo function core_sort_custom(args){ args = core_args({ 'args': args, 'defaults': { 'reverse': false, }, }); args['array'].sort(args['todo']); if(args['reverse']){ args['array'].reverse(); } return args['array']; } // Required args: array function core_sort_numbers(args){ return core_sort_custom({ 'array': args['array'], 'reverse': args['reverse'], 'todo': function(a, b){ return a - b; }, }); } // Required args: array function core_sort_random(args){ return core_sort_custom({ 'array': args['array'], 'todo': function(a, b){ return Math.random() - .5; }, }); } // Required args: array, property function core_sort_property(args){ return core_sort_custom({ 'array': args['array'], 'reverse': args['reverse'], 'todo': function(a, b){ if(a[args['property']] > b[args['property']]){ return 1; }else if(a[args['property']] < b[args['property']]){ return -1; } return 0; }, }); } // Required args: array function core_sort_strings(args){ return core_sort_custom({ 'array': args['array'], 'reverse': args['reverse'], 'todo': function(a, b){ return a.localeCompare(b); }, }); } // Required args: storage function core_storage_add(args){ args = core_args({ 'args': args, 'defaults': { 'prefix': core_repo_title + '-', }, }); for(let key in args['storage']){ core_storage_info[key] = { 'default': args['storage'][key], 'prefix': args['prefix'], }; core_storage_data[key] = window.localStorage.getItem(args['prefix'] + key); if(core_storage_data[key] === null){ core_storage_data[key] = core_storage_info[key]['default']; } core_storage_data[key] = core_type_convert({ 'template': core_storage_info[key]['default'], 'value': core_storage_data[key], }); } } // Required args: element, key function core_storage_element_property(args){ return core_type({ 'type': 'boolean', 'var': core_storage_info[args['key']]['default'], }) ? 'checked' : (args['element'].tagName === 'DIV' || args['element'].tagName === 'SPAN' ? 'innerHTML' : 'value'); } function core_storage_reset(){ if(!window.confirm('Reset all settings?')){ return false; } for(let key in core_storage_data){ core_storage_data[key] = core_storage_info[key]['default']; window.localStorage.removeItem(core_storage_info[key]['prefix'] + key); } core_storage_update(); return true; } function core_storage_save(){ for(let key in core_storage_data){ let element = document.getElementById(key); core_storage_data[key] = element[core_storage_element_property({ 'element': element, 'key': key, })]; let data = core_type_convert({ 'template': core_storage_info[key]['default'], 'value': core_storage_data[key], }); core_storage_data[key] = data; if(data !== void 0 && data !== NaN && String(data).length > 0 && data !== core_storage_info[key]['default']){ window.localStorage.setItem( core_storage_info[key]['prefix'] + key, data ); }else{ window.localStorage.removeItem(core_storage_info[key]['prefix'] + key); } } core_keys_rebind(); } function core_storage_update(args){ args = core_args({ 'args': args, 'defaults': { 'keys': false, }, }); let keys = []; if(args['keys'] === false){ for(let key in core_storage_data){ keys.push(key); } }else{ keys = args['keys']; } for(let key in keys){ let element = document.getElementById(keys[key]); element[core_storage_element_property({ 'element': element, 'key': keys[key], })] = core_storage_data[keys[key]]; } } // Required args: content, group, id, label function core_tab_create(args){ core_tabs[args['id']] = { 'content': args['content'], 'group': args['group'], }; core_html({ 'parent': args['group'] + '-tabs', 'properties': { 'id': 'tab_' + args['group'] + '_' + args['id'], 'onclick': function(){ core_tab_switch({ 'id': this.id, }); }, 'type': 'button', 'value': args['label'], }, 'type': 'input', }); core_html({ 'parent': args['group'] + '-tabcontent', 'properties': { 'id': 'tabcontent-' + args['id'], 'innerHTML': args['content'], 'style': 'display:none', }, }); } // Required args: id function core_tab_switch(args){ let info = args['id'].split('_'); let element = document.getElementById('tabcontent-' + info[2]); if(!element){ return; } for(let tab in core_tabs){ if(core_tabs[tab]['group'] === info[1] && tab !== info[2]){ document.getElementById('tabcontent-' + tab).style.display = 'none'; } } element.style.display = element.style.display === 'block' ? 'none' : 'block'; } // Required args: expect, function function core_test_function(args){ args = core_args({ 'args': args, 'defaults': { 'args': {}, }, }); let test = false; let returned = window[args['function']](args['args']); if(core_type({ 'type': 'function', 'var': args['expect'], })){ test = args['expect'](returned); }else if(core_type({ 'type': 'array', 'var': args['expect'], }) || core_type({ 'type': 'object', 'var': args['expect'], })){ test = true; for(let item in returned){ if(args['expect'][item] === void 0 || returned[item] !== args['expect'][item]){ test = false; break; } } }else{ test = returned === args['expect']; } return { 'returned': returned, 'test': test, }; } // Required args: var function core_type(args){ args = core_args({ 'args': args, 'defaults': { 'type': 'function', }, }); if(args['type'] === 'function'){ return typeof args['var'] === 'function' || typeof window[args['var']] === 'function'; }else if(args['type'] === 'array'){ return args['var'] instanceof Array; }else if(args['type'] === 'object'){ return args['var'] instanceof Object && !(args['var'] instanceof Array) && typeof args['var'] !== 'function'; } return typeof args['var'] === args['type']; } // Required args: template, value function core_type_convert(args){ if(core_type({ 'type': 'string', 'var': args['template'], })){ return args['value']; }else if(!Number.isNaN(Number.parseFloat(args['template']))){ return Number.parseFloat(args['value']); }else if(core_type({ 'type': 'boolean', 'var': args['template'], }) && !core_type({ 'type': 'boolean', 'var': args['value'], })){ return args['value'] === 'true'; } return args['value']; } function core_ui_update(args){ args = core_args({ 'args': args, 'defaults': { 'ids': {}, }, }); for(let id in args['ids']){ if(core_ui_values[id] === args['ids'][id]){ continue; } core_ui_values[id] = args['ids'][id]; let element = document.getElementById(id); element[element.tagName !== 'INPUT' ? 'innerHTML' : 'value'] = args['ids'][id]; let elements = document.getElementsByClassName(id); for(let i = 0; i < elements.length; i++){ let item = elements.item(i); item[item.tagName !== 'INPUT' ? 'innerHTML' : 'value'] = args['ids'][id]; } } } function core_uri(args){ args = core_args({ 'args': args, 'defaults': { 'id': 'buffer', 'quality': 1, 'type': 'image/png', }, }); return document.getElementById(args['id']).toDataURL( args['type'], args['quality'] ); } window.core_entities = {}; window.core_entity_info = {}; window.core_entity_types_default = []; window.core_events = {}; window.core_gamepads = {}; window.core_groups = { '_length': {}, }; window.core_id_count = 0; window.core_images = {}; window.core_intervals = {}; window.core_key_rebinds = {}; window.core_keys = {}; window.core_menu_block_events = true; window.core_menu_open = false; window.core_mode = 0; window.core_mouse = {}; window.core_repo_title = ''; window.core_storage_data = {}; window.core_storage_info = {}; window.core_tabs = {}; window.core_ui_values = {}; window.onload = core_init;
js/core.js
'use strict'; // Required args: todo, url function core_ajax(args){ args = core_args({ 'args': args, 'defaults': { 'data': null, 'readyState': 4, 'status': 200, 'type': 'GET', }, }); let ajax = new XMLHttpRequest(); ajax.onreadystatechange = function(){ if(this.readyState === args['readyState'] && this.status === args['status']){ args['todo'](this.responseText); } }; ajax.open( args['type'], args['url'] ); ajax.send(args['data']); } // Required args: args, defaults function core_args(args){ if(args['args'] === void 0){ args['args'] = {}; } for(let arg in args['defaults']){ if(args['args'][arg] === void 0){ args['args'][arg] = args['defaults'][arg]; } } return args['args']; } // Required args: todo function core_call(args){ args = core_args({ 'args': args, 'defaults': { 'args': void 0, }, }); if(core_type({ 'var': args['todo'], })){ window[args['todo']](args['args']); } } // Required args: number function core_digits_min(args){ args = core_args({ 'args': args, 'defaults': { 'digits': 2, }, }); let result = args['number'] < 0 ? '-' : ''; args['number'] = Math.abs(args['number']); result += args['number']; while(String(result).length < args['digits']){ result = '0' + result; } return result; } function core_entity_create(args){ args = core_args({ 'args': args, 'defaults': { 'id': core_id_count, 'properties': {}, 'types': [], }, }); core_id_count++; let entity = {}; for(let type in core_entity_types_default){ core_entity_handle_defaults({ 'entity': entity, 'id': args['id'], 'type': core_entity_types_default[type], }); } for(let type in args['types']){ core_entity_handle_defaults({ 'entity': entity, 'id': args['id'], 'type': args['types'][type], }); } for(let property in args['properties']){ entity[property] = core_handle_defaults({ 'default': entity[property], 'var': args['properties'][property], }); } core_entities[args['id']] = entity; for(let type in core_entity_types_default){ core_entity_info[core_entity_types_default[type]]['todo'](args['id']); } for(let type in args['types']){ core_entity_info[args['types'][type]]['todo'](args['id']); } return args['id']; } // Required args: id, type function core_entity_handle_defaults(args){ for(let property in core_entity_info[args['type']]['default']){ args['entity'][property] = core_handle_defaults({ 'default': args['entity'][property], 'var': core_entity_info[args['type']]['default'][property], }); } if(core_groups[args['type']][args['id']] === void 0){ core_group_add({ 'entities': [ args['id'], ], 'group': args['type'], }); core_entity_info[args['type']]['count']++; } for(let group in core_entity_info[args['type']]['groups']){ core_group_add({ 'entities': [ args['id'], ], 'group': core_entity_info[args['type']]['groups'][group], }); } } // Required args: entities function core_entity_remove(args){ args = core_args({ 'args': args, 'defaults': { 'delete-empty': false, }, }); core_group_remove_all({ 'delete-empty': args['delete-empty'], 'entities': args['entities'], }); for(let entity in args['entities']){ delete core_entities[args['entities'][entity]]; } } function core_entity_remove_all(args){ args = core_args({ 'args': args, 'defaults': { 'delete-empty': false, 'group': false, }, }); for(let entity in core_entities){ if(args['group'] !== false && !core_groups[args['group']][entity]){ continue; } core_entity_remove({ 'delete-empty': args['delete-empty'], 'entities': [ entity, ], }); } } // Required args: type function core_entity_set(args){ args = core_args({ 'args': args, 'defaults': { 'default': false, 'groups': [], 'properties': {}, 'todo': function(){}, }, }); core_entity_info[args['type']] = { 'count': 0, 'default': args['properties'], 'groups': args['groups'], 'todo': args['todo'], }; if(args['default']){ core_entity_types_default.push(args['type']); } core_group_create({ 'ids': [ args['type'], ], }); } function core_escape(){ core_menu_open = !core_menu_open; if(!core_menu_open){ document.getElementById('core-menu').style.display = 'none'; document.getElementById('core-ui').style.userSelect = 'none'; document.getElementById('repo-ui').style.display = 'block'; core_storage_save(); core_interval_resume_all(); }else{ core_interval_pause_all(); document.getElementById('repo-ui').style.display = 'none'; document.getElementById('core-ui').style.userSelect = 'auto'; document.getElementById('core-menu').style.display = 'inline'; } core_call({ 'todo': 'repo_escape', }); } function core_events_bind(args){ args = core_args({ 'args': args, 'defaults': { 'beforeunload': false, 'clearkeys': false, 'clearmouse': false, 'elements': false, 'keybinds': false, 'mousebinds': false, }, }); if(args['beforeunload'] !== false){ core_events['beforeunload'] = core_handle_defaults({ 'default': { 'loop': false, 'preventDefault': false, 'solo': false, 'state': false, 'todo': function(){}, }, 'var': args['beforeunload'], }); } if(args['keybinds'] !== false){ core_keys_updatebinds({ 'clear': args['clearkeys'], 'keybinds': args['keybinds'], }); } if(args['mousebinds'] !== false){ core_mouse_updatebinds({ 'clear': args['clearmouse'], 'mousebinds': args['mousebinds'], }); } if(args['elements'] !== false){ for(let element in args['elements']){ let domelement = document.getElementById(element); for(let event in args['elements'][element]){ domelement[event] = args['elements'][element][event]; } } } } function core_events_keyinfo(event){ let code = event.keyCode || event.which; return { 'code': code, 'key': String.fromCharCode(code), }; } function core_events_todoloop(){ for(let key in core_keys){ if(core_keys[key]['state'] && core_keys[key]['loop']){ core_keys[key]['todo'](); } } for(let mousebind in core_mouse['todo']){ if(core_mouse['todo'][mousebind]['loop']){ core_mouse['todo'][mousebind]['todo'](); } } } // Required args: file, todo function core_file(args){ args = core_args({ 'args': args, 'defaults': { 'type': 'readAsDataURL', }, }); let filereader = new FileReader(); filereader.onload = function(event){ args['todo'](event); }; filereader[args['type']](args['file']); } // Required args: entities, group function core_group_add(args){ if(!(args['group'] in core_groups)){ core_group_create({ 'id': args['group'], }); } for(let entity in args['entities']){ if(core_groups[args['group']][args['entities'][entity]]){ return; } core_groups[args['group']][args['entities'][entity]] = true; core_groups['_length'][args['group']]++; } } // Required args: ids function core_group_create(args){ for(let id in args['ids']){ core_groups[args['ids'][id]] = {}; core_groups['_length'][args['ids'][id]] = 0; } } // Required args: groups, todo function core_group_modify(args){ args = core_args({ 'args': args, 'defaults': { 'pretodo': false, }, }); let pretodo = {}; if(args['pretodo'] !== false){ pretodo = args['pretodo'](); } for(let group in args['groups']){ for(let entity in core_groups[args['groups'][group]]){ args['todo']( entity, pretodo ); } } } // Required args: entities, from, to function core_group_move(args){ core_group_remove({ 'entities': args['entities'], 'group': args['from'], }); core_group_add({ 'entities': args['entities'], 'group': args['to'], }); } // Required args: entities, group function core_group_remove(args){ args = core_args({ 'args': args, 'defaults': { 'delete-empty': false, }, }); if(core_groups[args['group']] === void 0){ return; } for(let entity in args['entities']){ if(!core_groups[args['group']][args['entities'][entity]]){ continue; } delete core_groups[args['group']][args['entities'][entity]]; core_groups['_length'][args['group']]--; if(core_entity_info[args['group']]){ core_entity_info[args['group']]['count']--; } } if(args['delete-empty'] && core_groups['_length'][args['group']] === 0){ delete core_groups[args['group']]; delete core_groups['_length'][args['group']]; } } // Required args: entities function core_group_remove_all(args){ args = core_args({ 'args': args, 'defaults': { 'delete-empty': false, }, }); for(let group in core_groups){ if(group === '_length'){ continue; } core_group_remove({ 'delete-empty': args['delete-empty'], 'entities': args['entities'], 'group': group, }); } } function core_handle_beforeunload(event){ let result = core_handle_event({ 'event': event, 'key': 'beforeunload', 'object': core_events, 'todo': true, }); core_storage_save(); if(core_type({ 'type': 'string', 'var': result, })){ return result; } } function core_handle_blur(event){ for(let key in core_keys){ core_keys[key]['state'] = false; } core_mouse['down-0'] = false; core_mouse['down-1'] = false; core_mouse['down-2'] = false; core_mouse['down-3'] = false; core_mouse['down-4'] = false; } function core_handle_contextmenu(event){ let result = core_handle_event({ 'event': event, 'key': 'contextmenu', 'object': core_mouse['todo'], 'todo': true, }); if(result === void 0 && !core_menu_open){ return false; } } function core_handle_defaults(args){ args = core_args({ 'args': args, 'defaults': { 'default': {}, 'var': {}, }, }); if(!core_type({ 'type': 'object', 'var': args['var'], })){ return args['var']; } let object = args['default']; for(let property in args['var']){ object[property] = core_handle_defaults({ 'var': args['var'][property], }); } return object; } // Required args: event, key, object function core_handle_event(args){ args = core_args({ 'args': args, 'defaults': { 'state': void 0, 'todo': void 0, }, }); if(args['object'].hasOwnProperty(args['key'])){ if(args['object'][args['key']]['preventDefault'] && !core_menu_open){ args['event'].preventDefault(); } let returned = void 0; if(args['todo'] !== void 0 && !args['object'][args['key']]['loop']){ returned = args['object'][args['key']]['todo'](args['event']); } if(args['state'] !== void 0){ args['object'][args['key']]['state'] = args['state']; } if(returned !== void 0){ return returned; } return args['object'][args['key']]['solo']; } return false; } function core_handle_gamepadconnected(event){ let gamepad = event.gamepad; core_gamepads[gamepad.index] = gamepad; } function core_handle_gamepaddisconnected(event){ delete core_gamepads[event.gamepad.index]; } function core_handle_keydown(event){ if(event.ctrlKey){ return; } let key = core_events_keyinfo(event); if(core_menu_open && core_menu_block_events && key['code'] !== 27){ return; } if(core_handle_event({ 'event': event, 'key': key['code'], 'object': core_keys, 'state': true, 'todo': true, })){ return; } core_handle_event({ 'event': event, 'key': 'all', 'object': core_keys, 'state': true, 'todo': true, }); } function core_handle_keyup(event){ let key = core_events_keyinfo(event); if(core_handle_event({ 'event': event, 'key': key['code'], 'object': core_keys, 'state': false, })){ return; } if(core_keys.hasOwnProperty('all')){ let all = false; for(let key in core_keys){ if(key !== 'all' && core_keys[key]['state']){ all = true; break; } } core_keys['all']['state'] = all; } } function core_handle_mousedown(event){ if((core_menu_open && core_menu_block_events) || event['target'].tagName.toLowerCase() === 'input'){ return; } core_mouse['down-' + event.button] = true; core_mouse['down-x'] = core_mouse['x']; core_mouse['down-y'] = core_mouse['y']; core_handle_event({ 'event': event, 'key': 'mousedown', 'object': core_mouse['todo'], 'todo': true, }); } function core_handle_mousemove(event){ if(core_menu_open && core_menu_block_events){ return; } core_mouse['movement-x'] = event.movementX * core_storage_data['mouse-sensitivity']; core_mouse['movement-y'] = event.movementY * core_storage_data['mouse-sensitivity']; core_mouse['x'] = event.pageX; core_mouse['y'] = event.pageY; core_handle_event({ 'event': event, 'key': 'mousemove', 'object': core_mouse['todo'], 'todo': true, }); } function core_handle_mouseup(event){ core_mouse['down-' + event.button] = false; core_handle_event({ 'event': event, 'key': 'mouseup', 'object': core_mouse['todo'], 'todo': true, }); } function core_handle_mousewheel(event){ if(core_menu_open && core_menu_block_events){ return; } core_handle_event({ 'event': event, 'key': 'mousewheel', 'object': core_mouse['todo'], 'todo': true, }); } function core_handle_pointerlockchange(event){ let element = document.getElementById(core_mouse['pointerlock-id']); if(!element){ return; } core_mouse['pointerlock-state'] = element === document.pointerLockElement; if(!core_mouse['pointerlock-state']){ core_escape(); } }; // Required args: hex function core_hex_to_rgb(args){ if(args['hex'][0] === '#'){ args['hex'] = args['hex'].slice(1); } if(args['hex'].length === 3){ args['hex'] = args['hex'][0] + args['hex'][0] + args['hex'][1] + args['hex'][1] + args['hex'][2] + args['hex'][2]; } let rgb = { 'blue': '0x' + args['hex'][4] + args['hex'][5] | 0, 'green': '0x' + args['hex'][2] + args['hex'][3] | 0, 'red': '0x' + args['hex'][0] + args['hex'][1] | 0, }; return 'rgb(' + rgb['red'] + ', ' + rgb['green'] + ', ' + rgb['blue'] + ')'; } function core_html(args){ args = core_args({ 'args': args, 'defaults': { 'parent': false, 'properties': {}, 'type': 'div', }, }); let element = document.createElement(args['type']); for(let property in args['properties']){ element[property] = core_handle_defaults({ 'var': args['properties'][property], }); } if(typeof args['parent'] === 'string'){ document.getElementById(args['parent']).appendChild(element); }else if(typeof args['parent'] === 'object'){ args['parent'].appendChild(element); } return element; } // Required args: string function core_html_format(args){ return core_replace_multiple({ 'patterns': { //'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;', '\'': '&apos;', '\n\r': '<br>', }, 'string': args['string'], }); } // Required args: id, properties function core_html_modify(args){ let element = document.getElementById(args['id']); if(!element){ return; } Object.assign( element, args['properties'] ); } // Required args: id, src function core_image(args){ args = core_args({ 'args': args, 'defaults': { 'todo': function(){}, }, }); let image = new Image(); image.onload = args['todo']; image.src = args['src']; core_images[args['id']] = image; return image; } function core_init(){ // Core menu init. let core_ui = core_html({ 'properties': { 'id': 'core-ui', }, }) document.body.appendChild(core_ui); core_html({ 'parent': 'core-ui', 'properties': { 'id': 'core-toggle', 'onclick': core_escape, 'type': 'button', 'value': 'ESC', }, 'type': 'input', }); core_html({ 'parent': 'core-ui', 'properties': { 'id': 'core-menu', 'innerHTML': '<a href=../index.htm id=core-menu-root></a>/<a class=external id=core-menu-title rel=noopener></a>' + '<div id=core-menu-info></div><hr>' + '<span id=core-menu-tabs></span>' + '<div id=core-menu-tabcontent></div>' + '<input id=settings-reset type=button value="Reset Settings">', }, 'type': 'span', }); core_html({ 'parent': 'core-ui', 'properties': { 'id': 'repo-ui', }, }); // Global storage. core_tab_create({ 'content': '<table><tr><td><input id=audio-volume><td>Audio Volume' + '<tr><td><input id=color-negative type=color><td>Color Negative' + '<tr><td><input id=color-positive type=color><td>Color Positive' + '<tr><td><input id=decimals><td>Decimals' + '<tr><td><input id=jump><td>Jump' + '<tr><td><input id=mouse-sensitivity><td>Mouse Sensitivity' + '<tr><td><input id=move-↑><td>Move ↑' + '<tr><td><input id=move-←><td>Move ←' + '<tr><td><input id=move-↓><td>Move ↓' + '<tr><td><input id=move-→><td>Move →</table>', 'group': 'core-menu', 'id': 'iterami', 'label': 'iterami', }); core_storage_add({ 'prefix': 'core-', 'storage': { 'audio-volume': 1, 'color-negative': '#663366', 'color-positive': '#206620', 'decimals': 7, 'jump': 32, 'mouse-sensitivity': 1, 'move-←': 65, 'move-↑': 87, 'move-→': 68, 'move-↓': 83, }, }); core_storage_update(); // Events + Keyboard/Mouse. core_mouse = { 'down-0': false, 'down-1': false, 'down-2': false, 'down-3': false, 'down-4': false, 'down-x': 0, 'down-y': 0, 'movement-x': 0, 'movement-y': 0, 'pointerlock-id': 'canvas', 'pointerlock-state': false, 'todo': {}, 'x': 0, 'y': 0, }; document.onpointerlockchange = core_handle_pointerlockchange; window.onbeforeunload = core_handle_beforeunload; window.onblur = core_handle_blur; window.oncontextmenu = core_handle_contextmenu; window.ongamepadconnected = core_handle_gamepadconnected; window.ongamepaddisconnected = core_handle_gamepaddisconnected; window.onkeydown = core_handle_keydown; window.onkeyup = core_handle_keyup; window.onmousedown = core_handle_mousedown; window.onmousemove = core_handle_mousemove; window.onmouseup = core_handle_mouseup; window.ontouchend = core_handle_mouseup; window.ontouchmove = core_handle_mousemove; window.ontouchstart = core_handle_mousedown; window.onwheel = core_handle_mousewheel; core_events_bind({ 'elements': { 'settings-reset': { 'onclick': core_storage_reset, }, }, }); core_keys_rebind(); core_call({ 'todo': 'repo_init', }); } // Required args: id function core_interval_animationFrame(args){ core_intervals[args['id']]['var'] = window.requestAnimationFrame(core_intervals[args['id']]['todo']); } // Required args: id, todo function core_interval_modify(args){ args = core_args({ 'args': args, 'defaults': { 'animationFrame': false, 'clear': 'clearInterval', 'interval': 25, 'paused': false, 'set': 'setInterval', }, }); if(args['id'] in core_intervals){ core_interval_pause({ 'id': args['id'], }); } core_intervals[args['id']] = { 'animationFrame': args['animationFrame'], 'clear': args['clear'], 'interval': args['interval'], 'paused': args['paused'], 'set': args['set'], 'todo': args['todo'], }; if(!args['paused']){ core_interval_resume({ 'id': args['id'], }); } } // Required args: id function core_interval_pause(args){ if(!(args['id'] in core_intervals)){ return; } window[core_intervals[args['id']]['animationFrame'] ? 'cancelAnimationFrame' : core_intervals[args['id']]['clear']](core_intervals[args['id']]['var']); core_intervals[args['id']]['paused'] = true; } function core_interval_pause_all(){ for(let interval in core_intervals){ if(!core_intervals[interval]['paused']){ core_interval_pause({ 'id': interval, }); } } } // Required args: id function core_interval_remove(args){ if(!(args['id'] in core_intervals)){ return; } core_interval_pause({ 'id': args['id'], }); delete core_intervals[args['id']]; } function core_interval_remove_all(){ for(let interval in core_intervals){ core_interval_remove({ 'id': interval, }); } } // Required args: id function core_interval_resume(args){ if(!(args['id'] in core_intervals)){ return; } if(!core_intervals[args['id']]['paused']){ core_interval_pause({ 'id': args['id'], }); } core_intervals[args['id']]['paused'] = false; if(core_intervals[args['id']]['animationFrame']){ core_intervals[args['id']]['var'] = window.requestAnimationFrame(core_intervals[args['id']]['todo']); }else{ core_intervals[args['id']]['var'] = window[core_intervals[args['id']]['set']]( core_intervals[args['id']]['todo'], core_intervals[args['id']]['interval'] ); } } function core_interval_resume_all(){ for(let interval in core_intervals){ core_interval_resume({ 'id': interval, }); } } function core_keys_rebind(){ let keybinds = {}; Object.assign( keybinds, core_key_rebinds ); keybinds[27] = {// Escape 'solo': true, 'todo': core_escape, }; keybinds[core_storage_data['jump']] = {}; keybinds[core_storage_data['move-←']] = {}; keybinds[core_storage_data['move-↑']] = {}; keybinds[core_storage_data['move-→']] = {}; keybinds[core_storage_data['move-↓']] = {}; core_events_bind({ 'clearkeys': true, 'keybinds': keybinds, }); } // Required args: keybinds function core_keys_updatebinds(args){ args = core_args({ 'args': args, 'defaults': { 'clear': false, }, }); if(args['clear']){ core_keys = {}; } for(let keybind in args['keybinds']){ let key = keybind; if(keybind !== 'all'){ key = Number.parseInt( key, 10 ); if(Number.isNaN(key)){ key = keybind.charCodeAt(0); } } core_keys[key] = core_handle_defaults({ 'default': { 'loop': false, 'preventDefault': false, 'solo': false, 'state': false, 'todo': function(){}, }, 'var': args['keybinds'][keybind], }); } } // Required args: mousebinds function core_mouse_updatebinds(args){ args = core_args({ 'args': args, 'defaults': { 'clear': false, }, }); if(args['clear']){ core_mouse['todo'] = {}; } for(let mousebind in args['mousebinds']){ core_mouse['todo'][mousebind] = { 'loop': args['mousebinds'][mousebind]['loop'] || false, 'preventDefault': args['mousebinds'][mousebind]['preventDefault'] || false, 'todo': args['mousebinds'][mousebind]['todo'] || function(){}, }; } } // Required args: number function core_number_format(args){ args = core_args({ 'args': args, 'defaults': { 'decimals': core_storage_data['decimals'], }, }); return new Intl.NumberFormat( void 0, { 'maximumFractionDigits': args['decimals'], } ).format(args['number']); } function core_random_boolean(args){ args = core_args({ 'args': args, 'defaults': { 'chance': .5, }, }); return Math.random() < args['chance']; } function core_random_hex(){ let color = core_random_rgb(); let blue = '0' + color['blue'].toString(16); let green = '0' + color['green'].toString(16); let red = '0' + color['red'].toString(16); return red.slice(-2) + green.slice(-2) + blue.slice(-2); } function core_random_integer(args){ args = core_args({ 'args': args, 'defaults': { 'max': 100, 'todo': 'floor', }, }); return Math[args['todo']](core_random_number({ 'multiplier': args['max'], })); } // Required args: object function core_random_key(args){ let keys = Object.keys(args['object']); return keys[core_random_integer({ 'max': keys.length, })]; } function core_random_number(args){ args = core_args({ 'args': args, 'defaults': { 'multiplier': 1, }, }); return Math.random() * args['multiplier']; } function core_random_rgb(){ return { 'blue': core_random_integer({ 'max': 256, }), 'green': core_random_integer({ 'max': 256, }), 'red': core_random_integer({ 'max': 256, }), }; } function core_random_string(args){ args = core_args({ 'args': args, 'defaults': { 'characters': '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'length': 100, }, }); let string = ''; for(let loopCounter = 0; loopCounter < args['length']; loopCounter++){ string += args['characters'][core_random_integer({ 'max': args['characters'].length, })]; } return string; } // Required args: patterns, string function core_replace_multiple(args){ for(let pattern in args['patterns']){ args['string'] = args['string'].replace( new RegExp( pattern, 'g' ), args['patterns'][pattern] ); } return args['string']; } // Required args: title function core_repo_init(args){ args = core_args({ 'args': args, 'defaults': { 'beforeunload': false, 'entities': {}, 'events': {}, 'github': 'iterami', 'globals': {}, 'images': {}, 'info': '', 'keybinds': false, 'menu': false, 'menu-block-events': true, 'mousebinds': false, 'storage': {}, 'storage-menu': '', 'tabs': {}, 'ui': '', }, }); Object.assign( window, args['globals'] ); if(args['menu']){ core_escape(); } for(let entity in args['entities']){ core_entity_set({ 'default': args['entities'][entity]['default'], 'groups': args['entities'][entity]['groups'], 'properties': args['entities'][entity]['properties'], 'todo': args['entities'][entity]['todo'], 'type': entity, }); } core_repo_title = args['title']; core_storage_add({ 'storage': args['storage'], }); if(args['info'].length > 0){ document.getElementById('core-menu-info').innerHTML = '<hr>' + args['info']; } if(args['storage-menu'].length > 0){ core_tab_create({ 'content': args['storage-menu'], 'group': 'core-menu', 'id': 'repo', 'label': core_repo_title, }); } document.getElementById('core-menu-root').innerHTML = args['github']; let repo_title = document.getElementById('core-menu-title'); repo_title.href = 'https://github.com/' + args['github'] + '/' + core_repo_title; repo_title.innerHTML = core_repo_title; document.getElementById('repo-ui').innerHTML = args['ui']; let have_default = false; for(let tab in args['tabs']){ core_tab_create({ 'content': args['tabs'][tab]['content'], 'group': args['tabs'][tab]['group'], 'id': tab, 'label': args['tabs'][tab]['label'], }); if(args['tabs'][tab]['default']){ core_tab_switch({ 'id': 'tab_' + args['tabs'][tab]['group'] + '_' + tab, }); have_default = true; } } if(!have_default){ core_tab_switch({ 'id': 'tab_core-menu_repo', }); } core_storage_update(); if(args['keybinds'] !== false){ core_key_rebinds = args['keybinds']; } core_menu_block_events = args['menu-block-events']; core_events_bind({ 'beforeunload': args['beforeunload'], 'elements': args['events'], 'keybinds': args['keybinds'], 'mousebinds': args['mousebinds'], }); for(let image in args['images']){ core_image({ 'id': image, 'src': args['images'][image], }); } } function core_requestpointerlock(args){ if(core_menu_open){ return; } args = core_args({ 'args': args, 'defaults': { 'id': 'canvas', }, }); let element = document.getElementById(args['id']); if(!element){ return; } element.requestPointerLock(); core_mouse['pointerlock-id'] = args['id']; } // Required args: number function core_round(args){ args = core_args({ 'args': args, 'defaults': { 'decimals': core_storage_data['decimals'], }, }); let eIndex = String(args['number']).indexOf('e'); let eString = ''; if(eIndex >= 0){ eString = String(args['number']).slice(eIndex); args['number'] = String(args['number']).slice( 0, eIndex ); let power = Number(eString.slice(2)); if(power === args['decimals']){ eString = 'e-' + (power + 1); } } let result = Number( Math.round(args['number'] + 'e+' + args['decimals']) + 'e-' + args['decimals'] ); if(eString.length > 0){ result = Number(result + eString); } if(Number.isNaN(result) || Math.abs(result) < Number('1e-' + args['decimals'])){ result = 0; } return result; } // Required args: array, todo function core_sort_custom(args){ args = core_args({ 'args': args, 'defaults': { 'reverse': false, }, }); args['array'].sort(args['todo']); if(args['reverse']){ args['array'].reverse(); } return args['array']; } // Required args: array function core_sort_numbers(args){ return core_sort_custom({ 'array': args['array'], 'reverse': args['reverse'], 'todo': function(a, b){ return a - b; }, }); } // Required args: array function core_sort_random(args){ return core_sort_custom({ 'array': args['array'], 'todo': function(a, b){ return Math.random() - .5; }, }); } // Required args: array, property function core_sort_property(args){ return core_sort_custom({ 'array': args['array'], 'reverse': args['reverse'], 'todo': function(a, b){ if(a[args['property']] > b[args['property']]){ return 1; }else if(a[args['property']] < b[args['property']]){ return -1; } return 0; }, }); } // Required args: array function core_sort_strings(args){ return core_sort_custom({ 'array': args['array'], 'reverse': args['reverse'], 'todo': function(a, b){ return a.localeCompare(b); }, }); } // Required args: storage function core_storage_add(args){ args = core_args({ 'args': args, 'defaults': { 'prefix': core_repo_title + '-', }, }); for(let key in args['storage']){ core_storage_info[key] = { 'default': args['storage'][key], 'prefix': args['prefix'], }; core_storage_data[key] = window.localStorage.getItem(args['prefix'] + key); if(core_storage_data[key] === null){ core_storage_data[key] = core_storage_info[key]['default']; } core_storage_data[key] = core_type_convert({ 'template': core_storage_info[key]['default'], 'value': core_storage_data[key], }); } } // Required args: element, key function core_storage_element_property(args){ return core_type({ 'type': 'boolean', 'var': core_storage_info[args['key']]['default'], }) ? 'checked' : (args['element'].tagName === 'DIV' || args['element'].tagName === 'SPAN' ? 'innerHTML' : 'value'); } function core_storage_reset(){ if(!window.confirm('Reset ' + core_repo_title + ' settings?')){ return false; } for(let key in core_storage_data){ core_storage_data[key] = core_storage_info[key]['default']; window.localStorage.removeItem(core_storage_info[key]['prefix'] + key); } core_storage_update(); return true; } function core_storage_save(){ for(let key in core_storage_data){ let element = document.getElementById(key); core_storage_data[key] = element[core_storage_element_property({ 'element': element, 'key': key, })]; let data = core_type_convert({ 'template': core_storage_info[key]['default'], 'value': core_storage_data[key], }); core_storage_data[key] = data; if(data !== void 0 && data !== NaN && String(data).length > 0 && data !== core_storage_info[key]['default']){ window.localStorage.setItem( core_storage_info[key]['prefix'] + key, data ); }else{ window.localStorage.removeItem(core_storage_info[key]['prefix'] + key); } } core_keys_rebind(); } function core_storage_update(args){ args = core_args({ 'args': args, 'defaults': { 'keys': false, }, }); let keys = []; if(args['keys'] === false){ for(let key in core_storage_data){ keys.push(key); } }else{ keys = args['keys']; } for(let key in keys){ let element = document.getElementById(keys[key]); element[core_storage_element_property({ 'element': element, 'key': keys[key], })] = core_storage_data[keys[key]]; } } // Required args: content, group, id, label function core_tab_create(args){ core_tabs[args['id']] = { 'content': args['content'], 'group': args['group'], }; core_html({ 'parent': args['group'] + '-tabs', 'properties': { 'id': 'tab_' + args['group'] + '_' + args['id'], 'onclick': function(){ core_tab_switch({ 'id': this.id, }); }, 'type': 'button', 'value': args['label'], }, 'type': 'input', }); core_html({ 'parent': args['group'] + '-tabcontent', 'properties': { 'id': 'tabcontent-' + args['id'], 'innerHTML': args['content'], 'style': 'display:none', }, }); } // Required args: id function core_tab_switch(args){ let info = args['id'].split('_'); let element = document.getElementById('tabcontent-' + info[2]); if(!element){ return; } for(let tab in core_tabs){ if(core_tabs[tab]['group'] === info[1] && tab !== info[2]){ document.getElementById('tabcontent-' + tab).style.display = 'none'; } } element.style.display = element.style.display === 'block' ? 'none' : 'block'; } // Required args: expect, function function core_test_function(args){ args = core_args({ 'args': args, 'defaults': { 'args': {}, }, }); let test = false; let returned = window[args['function']](args['args']); if(core_type({ 'type': 'function', 'var': args['expect'], })){ test = args['expect'](returned); }else if(core_type({ 'type': 'array', 'var': args['expect'], }) || core_type({ 'type': 'object', 'var': args['expect'], })){ test = true; for(let item in returned){ if(args['expect'][item] === void 0 || returned[item] !== args['expect'][item]){ test = false; break; } } }else{ test = returned === args['expect']; } return { 'returned': returned, 'test': test, }; } // Required args: var function core_type(args){ args = core_args({ 'args': args, 'defaults': { 'type': 'function', }, }); if(args['type'] === 'function'){ return typeof args['var'] === 'function' || typeof window[args['var']] === 'function'; }else if(args['type'] === 'array'){ return args['var'] instanceof Array; }else if(args['type'] === 'object'){ return args['var'] instanceof Object && !(args['var'] instanceof Array) && typeof args['var'] !== 'function'; } return typeof args['var'] === args['type']; } // Required args: template, value function core_type_convert(args){ if(core_type({ 'type': 'string', 'var': args['template'], })){ return args['value']; }else if(!Number.isNaN(Number.parseFloat(args['template']))){ return Number.parseFloat(args['value']); }else if(core_type({ 'type': 'boolean', 'var': args['template'], }) && !core_type({ 'type': 'boolean', 'var': args['value'], })){ return args['value'] === 'true'; } return args['value']; } function core_ui_update(args){ args = core_args({ 'args': args, 'defaults': { 'ids': {}, }, }); for(let id in args['ids']){ if(core_ui_values[id] === args['ids'][id]){ continue; } core_ui_values[id] = args['ids'][id]; let element = document.getElementById(id); element[element.tagName !== 'INPUT' ? 'innerHTML' : 'value'] = args['ids'][id]; let elements = document.getElementsByClassName(id); for(let i = 0; i < elements.length; i++){ let item = elements.item(i); item[item.tagName !== 'INPUT' ? 'innerHTML' : 'value'] = args['ids'][id]; } } } function core_uri(args){ args = core_args({ 'args': args, 'defaults': { 'id': 'buffer', 'quality': 1, 'type': 'image/png', }, }); return document.getElementById(args['id']).toDataURL( args['type'], args['quality'] ); } window.core_entities = {}; window.core_entity_info = {}; window.core_entity_types_default = []; window.core_events = {}; window.core_gamepads = {}; window.core_groups = { '_length': {}, }; window.core_id_count = 0; window.core_images = {}; window.core_intervals = {}; window.core_key_rebinds = {}; window.core_keys = {}; window.core_menu_block_events = true; window.core_menu_open = false; window.core_mode = 0; window.core_mouse = {}; window.core_repo_title = ''; window.core_storage_data = {}; window.core_storage_info = {}; window.core_tabs = {}; window.core_ui_values = {}; window.onload = core_init;
added settings save button, improved settings reset button clarity
js/core.js
added settings save button, improved settings reset button clarity
<ide><path>s/core.js <ide> + '<div id=core-menu-info></div><hr>' <ide> + '<span id=core-menu-tabs></span>' <ide> + '<div id=core-menu-tabcontent></div>' <del> + '<input id=settings-reset type=button value="Reset Settings">', <add> + '<input id=settings-reset type=button value="Reset All Settings">' <add> + '<input id=settings-save type=button value="Save Settings">', <ide> }, <ide> 'type': 'span', <ide> }); <ide> 'settings-reset': { <ide> 'onclick': core_storage_reset, <ide> }, <add> 'settings-save': { <add> 'onclick': core_storage_save, <add> }, <ide> }, <ide> }); <ide> core_keys_rebind(); <ide> } <ide> <ide> function core_storage_reset(){ <del> if(!window.confirm('Reset ' + core_repo_title + ' settings?')){ <add> if(!window.confirm('Reset all settings?')){ <ide> return false; <ide> } <ide>
Java
mit
a97e71c69edc2cb9e9efa15ff73b898cebabc5c9
0
sdl/Testy,sdl/Testy,sdl/Testy,sdl/Testy
package com.sdl.weblocator.extjs; import com.extjs.selenium.button.Button; import com.extjs.selenium.conditions.MessageBoxSuccessCondition; import com.extjs.selenium.form.TextField; import com.extjs.selenium.grid.GridPanel; import com.extjs.selenium.tab.TabPanel; import com.extjs.selenium.window.MessageBox; import com.extjs.selenium.window.Window; import com.sdl.bootstrap.form.Form; import com.sdl.selenium.conditions.Condition; import com.sdl.selenium.conditions.ConditionManager; import com.sdl.selenium.conditions.ElementRemovedSuccessCondition; import com.sdl.selenium.conditions.RenderSuccessCondition; import com.sdl.selenium.web.SearchType; import com.sdl.selenium.web.WebLocator; import com.sdl.selenium.web.form.SimpleTextField; import com.sdl.selenium.web.table.SimpleTable; import com.sdl.selenium.web.table.TableCell; import com.sdl.selenium.web.utils.Utils; import com.sdl.weblocator.TestBase; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import org.openqa.selenium.Keys; import org.openqa.selenium.interactions.Actions; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.io.File; import java.io.IOException; public class DeployTesty extends TestBase { private static final Logger logger = Logger.getLogger(DeployTesty.class); // Rulati acest test dupa ce ati oprit orice test!!!! private static final String DOMAIN_USER = "user-ul de domeniu"; private static final String DOMAIN_PASS = "parola de domeniu"; private WebLocator loginEl = new WebLocator().setElPath("//span/a[.//*[text()='log in']]"); private WebLocator logOutEl = new WebLocator().setElPath("//span/a[.//*[text()='log out']]"); private Form loginForm = new Form().setName("login"); private SimpleTextField login = new SimpleTextField(loginForm).setName("j_username"); private SimpleTextField pass = new SimpleTextField(loginForm).setName("j_password"); private WebLocator logInButton = new WebLocator(loginForm).setId("yui-gen1-button"); private SimpleTable table = new SimpleTable().setId("main-table"); private WebLocator buildNow = new WebLocator(table, "//a[@class='task-link' and text()='Build Now']"); private SimpleTable buildHistory = new SimpleTable().setId("buildHistory"); private WebLocator buildNowEl = new WebLocator(buildHistory).setClasses("build-row", "no-wrap", "transitive").setPosition(1); private WebLocator logInNexus = new WebLocator().setId("head-link-r"); private Window nexusLogInWindow = new Window("Nexus Log In"); private TextField userName = new TextField(nexusLogInWindow, "Username:"); private TextField password = new TextField(nexusLogInWindow, "Password:"); private Button logIn = new Button(nexusLogInWindow, "Log In"); private WebLocator viewRepositories = new WebLocator().setId("view-repositories"); private GridPanel repositoryGridPanel = new GridPanel(viewRepositories); private TabPanel browseStorage = new TabPanel(viewRepositories, "Browse Storage"); private SimpleTable table1 = new SimpleTable(browseStorage).setCls("x-toolbar-ct"); private WebLocator testyDir = new WebLocator().setElPath("//a[@class='x-tree-node-anchor' and count(.//span[text()='Testy']) > 0]"); private TableCell tableCell = table1.getTableCell(4, new TableCell(3, "Path Lookup:", SearchType.EQUALS)); private TextField searchField = new TextField(tableCell); @BeforeClass public void startTests() { driver.get("http://cluj-jenkins01:8080/job/testy/"); } @Test public void loginJenkins() { loginEl.click(); loginForm.ready(10); login.setValue(DOMAIN_USER); pass.setValue(DOMAIN_PASS); logInButton.click(); logOutEl.ready(10); } @Test(dependsOnMethods = "loginJenkins") public void deployOnJenkins() { buildNow.click(); String testyDir = System.getProperty("user.home") + "\\.m2\\repository\\com\\sdl\\lt\\Testy"; cleanDir(testyDir); waitRenderEl(buildNowEl, 5000); waitRemovedEl(buildNowEl, 720000); } @Test(dependsOnMethods = "deployOnJenkins") public void loginAsAdminSDLNexus() { driver.get("http://cluj-nexus01:8081/nexus/#view-repositories;oss-sonatype-snapshots"); logInNexus.ready(); Utils.sleep(1000); logInNexus.click(); Utils.sleep(1000); userName.ready(); userName.setValue("admin"); password.setValue("admin123"); logIn.click(); } @Test(dependsOnMethods = "loginAsAdminSDLNexus") public void removeFormSDLNexus() { repositoryGridPanel.rowSelect("OSS Sonatype Snapshots"); browseStorage.setActive(); searchField.setValue("com/sdl/lt/Testy"); testyDir.ready(10); Utils.sleep(1000); Actions action = new Actions(driver); action.contextClick(testyDir.currentElement).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.RETURN).build().perform(); confirmYesMSG("Delete the selected \"/com/sdl/lt/Testy/\" folder?"); Utils.sleep(1000); } private void cleanDir(String path) { try { FileUtils.cleanDirectory(new File(path)); } catch (IOException e) { logger.debug("not found " + path); } } private boolean waitRemovedEl(WebLocator el, long time) { return new ConditionManager(time).add(new ElementRemovedSuccessCondition(el)).execute().isSuccess(); } private boolean waitRenderEl(WebLocator el, long time) { return new ConditionManager(time).add(new RenderSuccessCondition(el)).execute().isSuccess(); } private boolean confirmYesMSG(String msg) { boolean success = false; Condition condition = new ConditionManager(16000).add(new MessageBoxSuccessCondition(msg)).execute(); if (condition.isSuccess()) { MessageBox.pressYes(); success = true; } return success; } }
src/test/functional/java/com/sdl/weblocator/extjs/DeployTesty.java
package com.sdl.weblocator.extjs; import com.extjs.selenium.button.Button; import com.extjs.selenium.conditions.MessageBoxSuccessCondition; import com.extjs.selenium.form.TextField; import com.extjs.selenium.grid.GridPanel; import com.extjs.selenium.tab.TabPanel; import com.extjs.selenium.window.MessageBox; import com.extjs.selenium.window.Window; import com.sdl.bootstrap.form.Form; import com.sdl.selenium.conditions.Condition; import com.sdl.selenium.conditions.ConditionManager; import com.sdl.selenium.conditions.ElementRemovedSuccessCondition; import com.sdl.selenium.conditions.RenderSuccessCondition; import com.sdl.selenium.web.SearchType; import com.sdl.selenium.web.WebLocator; import com.sdl.selenium.web.form.SimpleTextField; import com.sdl.selenium.web.table.SimpleTable; import com.sdl.selenium.web.table.TableCell; import com.sdl.selenium.web.utils.Utils; import com.sdl.weblocator.TestBase; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import org.openqa.selenium.Keys; import org.openqa.selenium.interactions.Actions; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.io.File; import java.io.IOException; public class DeployTesty extends TestBase { private static final Logger logger = Logger.getLogger(DeployTesty.class); // Rulati acest test dupa ce ati oprit orice test!!!! private static final String DOMAIN_USER = "user-ul de domeniu"; private static final String DOMAIN_PASS = "parola de domeniu"; private WebLocator loginEl = new WebLocator().setElPath("//span/a[.//*[text()='log in']]"); private WebLocator logOutEl = new WebLocator().setElPath("//span/a[.//*[text()='log out']]"); private Form loginForm = new Form().setName("login"); private SimpleTextField login = new SimpleTextField(loginForm).setName("j_username"); private SimpleTextField pass = new SimpleTextField(loginForm).setName("j_password"); private WebLocator logInButton = new WebLocator(loginForm).setId("yui-gen1-button"); private SimpleTable table = new SimpleTable().setId("main-table"); private WebLocator buildNow = new WebLocator(table, "//a[@class='task-link' and text()='Build Now']"); private SimpleTable buildHistory = new SimpleTable().setId("buildHistory"); private WebLocator buildNowEl = new WebLocator(buildHistory).setClasses("build-row", "no-wrap", "transitive").setPosition(1); private WebLocator logInNexus = new WebLocator().setId("head-link-r"); private Window nexusLogInWindow = new Window("Nexus Log In"); private TextField userName = new TextField(nexusLogInWindow, "Username:"); private TextField password = new TextField(nexusLogInWindow, "Password:"); private Button logIn = new Button(nexusLogInWindow, "Log In"); private WebLocator viewRepositories = new WebLocator().setId("view-repositories"); private GridPanel repositoryGridPanel = new GridPanel(viewRepositories); private TabPanel browseStorage = new TabPanel(viewRepositories, "Browse Storage"); private SimpleTable table1 = new SimpleTable(browseStorage).setCls("x-toolbar-ct"); private WebLocator testyDir = new WebLocator().setElPath("//a[@class='x-tree-node-anchor' and count(.//span[text()='Testy']) > 0]"); private TableCell tableCell = table1.getTableCell(4, new TableCell(3, "Path Lookup:", SearchType.EQUALS)); private TextField searchField = new TextField(tableCell); @BeforeClass public void startTests() { driver.get("http://cluj-jenkins01:8080/job/testy/"); } @Test public void loginJenkins() { loginEl.click(); loginForm.ready(10); login.setValue(DOMAIN_USER); pass.setValue(DOMAIN_PASS); logInButton.click(); logOutEl.ready(10); } @Test(dependsOnMethods = "loginJenkins") public void deployOnJenkins() { buildNow.click(); String testyDir = System.getProperty("user.home") + "\\.m2\\repository\\com\\sdl\\lt\\Testy"; cleanDir(testyDir); waitRenderEl(buildNowEl, 5000); waitRemovedEl(buildNowEl, 720000); } @Test(dependsOnMethods = "deployOnJenkins") public void loginAsAdminSDLNexus() { driver.get("http://cfg-mgmt-server:8081/nexus/index.html#view-repositories;oss-sonatype-snapshots"); logInNexus.ready(); Utils.sleep(1000); logInNexus.click(); Utils.sleep(1000); userName.ready(); userName.setValue("admin"); password.setValue("admin123"); logIn.click(); } @Test(dependsOnMethods = "loginAsAdminSDLNexus") public void removeFormSDLNexus() { repositoryGridPanel.rowSelect("sonatype-nexus-snapshots"); browseStorage.setActive(); searchField.setValue("com/sdl/lt/Testy"); testyDir.ready(10); Utils.sleep(1000); Actions action = new Actions(driver); action.contextClick(testyDir.currentElement).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.RETURN).build().perform(); confirmYesMSG("Delete the selected \"/com/sdl/lt/Testy/\" folder?"); Utils.sleep(1000); } private void cleanDir(String path) { try { FileUtils.cleanDirectory(new File(path)); } catch (IOException e) { logger.debug("not found " + path); } } private boolean waitRemovedEl(WebLocator el, long time) { return new ConditionManager(time).add(new ElementRemovedSuccessCondition(el)).execute().isSuccess(); } private boolean waitRenderEl(WebLocator el, long time) { return new ConditionManager(time).add(new RenderSuccessCondition(el)).execute().isSuccess(); } private boolean confirmYesMSG(String msg) { boolean success = false; Condition condition = new ConditionManager(16000).add(new MessageBoxSuccessCondition(msg)).execute(); if (condition.isSuccess()) { MessageBox.pressYes(); success = true; } return success; } }
fix new nexus url
src/test/functional/java/com/sdl/weblocator/extjs/DeployTesty.java
fix new nexus url
<ide><path>rc/test/functional/java/com/sdl/weblocator/extjs/DeployTesty.java <ide> <ide> @Test(dependsOnMethods = "deployOnJenkins") <ide> public void loginAsAdminSDLNexus() { <del> driver.get("http://cfg-mgmt-server:8081/nexus/index.html#view-repositories;oss-sonatype-snapshots"); <add> driver.get("http://cluj-nexus01:8081/nexus/#view-repositories;oss-sonatype-snapshots"); <ide> logInNexus.ready(); <ide> Utils.sleep(1000); <ide> logInNexus.click(); <ide> <ide> @Test(dependsOnMethods = "loginAsAdminSDLNexus") <ide> public void removeFormSDLNexus() { <del> repositoryGridPanel.rowSelect("sonatype-nexus-snapshots"); <add> repositoryGridPanel.rowSelect("OSS Sonatype Snapshots"); <ide> browseStorage.setActive(); <ide> searchField.setValue("com/sdl/lt/Testy"); <ide> testyDir.ready(10);
JavaScript
apache-2.0
eeb01563f8b64974b8f75185db2c5c380da0380c
0
matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,aperezdc/matrix-react-sdk,aperezdc/matrix-react-sdk,aperezdc/matrix-react-sdk,aperezdc/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk
/* Copyright 2015, 2016 OpenMarket Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ var React = require("react"); var sdk = require('../../../index'); var MatrixClientPeg = require("../../../MatrixClientPeg"); module.exports = React.createClass({ displayName: 'EncryptedEventDialog', propTypes: { onFinished: React.PropTypes.func, }, componentWillMount: function() { var client = MatrixClientPeg.get(); client.on("deviceVerificationChanged", this.onDeviceVerificationChanged); client.downloadKeys([this.props.event.getSender()], true).done(()=>{ var devices = client.getStoredDevicesForUser(this.props.event.getSender()); this.setState({ device: this.refreshDevice() }); }, (err)=>{ console.log("Error downloading devices", err); }); }, componentWillUnmount: function() { var client = MatrixClientPeg.get(); if (client) { client.removeListener("deviceVerificationChanged", this.onDeviceVerificationChanged); } }, refreshDevice: function() { // XXX: gutwrench - is there any reason not to expose this on MatrixClient itself? return MatrixClientPeg.get()._crypto.getDeviceByIdentityKey( this.props.event.getSender(), this.props.event.getWireContent().algorithm, this.props.event.getWireContent().sender_key ); }, getInitialState: function() { return { device: this.refreshDevice() }; }, onDeviceVerificationChanged: function(userId, device) { if (userId == this.props.event.getSender()) { this.setState({ device: this.refreshDevice() }); } }, onKeyDown: function(e) { if (e.keyCode === 27) { // escape e.stopPropagation(); e.preventDefault(); this.props.onFinished(false); } }, render: function() { var event = this.props.event; var device = this.state.device; var MemberDeviceInfo = sdk.getComponent('rooms.MemberDeviceInfo'); return ( <div className="mx_EncryptedEventDialog" onKeyDown={ this.onKeyDown }> <div className="mx_Dialog_title"> End-to-end encryption information </div> <div className="mx_Dialog_content"> <table> <tbody> <tr> <td>Sent by</td> <td>{ event.getSender() }</td> </tr> <tr> <td>Sender device name</td> <td>{ device ? device.getDisplayName() : <i>unknown device</i>}</td> </tr> <tr> <td>Sender device ID</td> <td>{ device ? <code>{ device.deviceId }</code> : <i>unknown device</i>}</td> </tr> <tr> <td>Sender device verification</td> <td>{ MatrixClientPeg.get().isEventSenderVerified(event) ? "verified" : <b>NOT verified</b> }</td> </tr> <tr> <td>Sender device ed25519 identity key</td> <td>{ device ? <code>{device.getFingerprint()}</code> : <i>unknown device</i>}</td> </tr> <tr> <td>Sender device curve25519 olm key</td> <td><code>{ event.getWireContent().sender_key || <i>none</i> }</code></td> </tr> <tr> <td>Algorithm</td> <td>{ event.getWireContent().algorithm || <i>unencrypted</i> }</td> </tr> { event.getContent().msgtype === 'm.bad.encrypted' ? ( <tr> <td>Decryption error</td> <td>{ event.getContent().body }</td> </tr> ) : '' } <tr> <td>Session ID</td> <td><code>{ event.getWireContent().session_id || <i>none</i> }</code></td> </tr> </tbody> </table> </div> <div className="mx_Dialog_buttons"> <button className="mx_Dialog_primary" onClick={ this.props.onFinished } autoFocus={ true }> OK </button> <MemberDeviceInfo ref="memberDeviceInfo" hideInfo={true} device={ this.state.device } userId={ this.props.event.getSender() }/> </div> </div> ); } });
src/components/views/dialogs/EncryptedEventDialog.js
/* Copyright 2015, 2016 OpenMarket Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ var React = require("react"); var sdk = require('../../../index'); var MatrixClientPeg = require("../../../MatrixClientPeg"); module.exports = React.createClass({ displayName: 'EncryptedEventDialog', propTypes: { onFinished: React.PropTypes.func, }, componentWillMount: function() { var client = MatrixClientPeg.get(); client.on("deviceVerificationChanged", this.onDeviceVerificationChanged); }, componentWillUnmount: function() { var client = MatrixClientPeg.get(); if (client) { client.removeListener("deviceVerificationChanged", this.onDeviceVerificationChanged); } }, refreshDevice: function() { // XXX: gutwrench - is there any reason not to expose this on MatrixClient itself? return MatrixClientPeg.get()._crypto.getDeviceByIdentityKey( this.props.event.getSender(), this.props.event.getWireContent().algorithm, this.props.event.getWireContent().sender_key ); }, getInitialState: function() { return { device: this.refreshDevice() }; }, onDeviceVerificationChanged: function(userId, device) { if (userId == this.props.event.getSender()) { this.setState({ device: this.refreshDevice() }); } }, render: function() { var event = this.props.event; var device = this.state.device; var MemberDeviceInfo = sdk.getComponent('rooms.MemberDeviceInfo'); return ( <div className="mx_EncryptedEventDialog"> <div className="mx_Dialog_title"> End-to-end encryption information </div> <div className="mx_Dialog_content"> <table> <tbody> <tr> <td>Sent by</td> <td>{ event.getSender() }</td> </tr> <tr> <td>Sender device name</td> <td>{ device ? device.getDisplayName() : <i>unknown device</i>}</td> </tr> <tr> <td>Sender device ID</td> <td>{ device ? <code>{ device.deviceId }</code> : <i>unknown device</i>}</td> </tr> <tr> <td>Sender device verification</td> <td>{ MatrixClientPeg.get().isEventSenderVerified(event) ? "verified" : <b>NOT verified</b> }</td> </tr> <tr> <td>Sender device ed25519 identity key</td> <td>{ device ? <code>{device.getFingerprint()}</code> : <i>unknown device</i>}</td> </tr> <tr> <td>Sender device curve25519 olm key</td> <td><code>{ event.getWireContent().sender_key || <i>none</i> }</code></td> </tr> <tr> <td>Algorithm</td> <td>{ event.getWireContent().algorithm || <i>unencrypted</i> }</td> </tr> { event.getContent().msgtype === 'm.bad.encrypted' ? ( <tr> <td>Decryption error</td> <td>{ event.getContent().body }</td> </tr> ) : '' } <tr> <td>Session ID</td> <td><code>{ event.getWireContent().session_id || <i>none</i> }</code></td> </tr> </tbody> </table> </div> <div className="mx_Dialog_buttons"> <button className="mx_Dialog_primary" onClick={ this.props.onFinished } autoFocus={ true }> OK </button> <MemberDeviceInfo ref="memberDeviceInfo" hideInfo={true} device={ this.state.device } userId={ this.props.event.getSender() }/> </div> </div> ); } });
add dialog keyboard shortcuts. download keys on demand
src/components/views/dialogs/EncryptedEventDialog.js
add dialog keyboard shortcuts. download keys on demand
<ide><path>rc/components/views/dialogs/EncryptedEventDialog.js <ide> componentWillMount: function() { <ide> var client = MatrixClientPeg.get(); <ide> client.on("deviceVerificationChanged", this.onDeviceVerificationChanged); <add> <add> client.downloadKeys([this.props.event.getSender()], true).done(()=>{ <add> var devices = client.getStoredDevicesForUser(this.props.event.getSender()); <add> this.setState({ device: this.refreshDevice() }); <add> }, (err)=>{ <add> console.log("Error downloading devices", err); <add> }); <ide> }, <ide> <ide> componentWillUnmount: function() { <ide> } <ide> }, <ide> <add> onKeyDown: function(e) { <add> if (e.keyCode === 27) { // escape <add> e.stopPropagation(); <add> e.preventDefault(); <add> this.props.onFinished(false); <add> } <add> }, <add> <ide> render: function() { <ide> var event = this.props.event; <ide> var device = this.state.device; <ide> var MemberDeviceInfo = sdk.getComponent('rooms.MemberDeviceInfo'); <ide> <ide> return ( <del> <div className="mx_EncryptedEventDialog"> <add> <div className="mx_EncryptedEventDialog" onKeyDown={ this.onKeyDown }> <ide> <div className="mx_Dialog_title"> <ide> End-to-end encryption information <ide> </div>
Java
apache-2.0
2fd4dcade876dc11a65da6f4f873d235c4037a49
0
apucher/pinot,linkedin/pinot,linkedin/pinot,linkedin/pinot,fx19880617/pinot-1,tkao1000/pinot,linkedin/pinot,izzizz/pinot,Hanmourang/Pinot,pinotlytics/pinot,sajavadi/pinot,linkedin/pinot,tkao1000/pinot,izzizz/pinot,tkao1000/pinot,sajavadi/pinot,apucher/pinot,apucher/pinot,sajavadi/pinot,izzizz/pinot,sajavadi/pinot,izzizz/pinot,tkao1000/pinot,Hanmourang/Pinot,fx19880617/pinot-1,fx19880617/pinot-1,Hanmourang/Pinot,sajavadi/pinot,pinotlytics/pinot,pinotlytics/pinot,apucher/pinot,tkao1000/pinot,izzizz/pinot,pinotlytics/pinot,izzizz/pinot,fx19880617/pinot-1,Hanmourang/Pinot,Hanmourang/Pinot,apucher/pinot,fx19880617/pinot-1,Hanmourang/Pinot,pinotlytics/pinot,pinotlytics/pinot
/** * Copyright (C) 2014-2015 LinkedIn Corp. ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.linkedin.pinot.hadoop.job.mapper; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.codehaus.jackson.map.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.linkedin.pinot.common.data.Schema; import com.linkedin.pinot.common.utils.TarGzCompressionUtils; import com.linkedin.pinot.core.data.readers.CSVRecordReaderConfig; import com.linkedin.pinot.core.data.readers.FileFormat; import com.linkedin.pinot.core.data.readers.RecordReaderConfig; import com.linkedin.pinot.core.indexsegment.generator.SegmentGeneratorConfig; import com.linkedin.pinot.core.segment.creator.impl.SegmentIndexCreationDriverImpl; public class HadoopSegmentCreationMapReduceJob { public static class HadoopSegmentCreationMapper extends Mapper<LongWritable, Text, LongWritable, Text> { private static Logger LOGGER = LoggerFactory.getLogger(HadoopSegmentCreationMapper.class); private Configuration _properties; private String _inputFilePath; private String _outputPath; private String _tableName; private String _postfix; private Path _currentHdfsWorkDir; private String _currentDiskWorkDir; // Temporary HDFS path for local machine private String _localHdfsSegmentTarPath; private String _localDiskSegmentDirectory; private String _localDiskSegmentTarPath; @Override public void setup(Context context) throws IOException, InterruptedException { _currentHdfsWorkDir = FileOutputFormat.getWorkOutputPath(context); _currentDiskWorkDir = "pinot_hadoop_tmp"; // Temporary HDFS path for local machine _localHdfsSegmentTarPath = _currentHdfsWorkDir + "/segmentTar"; // Temporary DISK path for local machine _localDiskSegmentDirectory = _currentDiskWorkDir + "/segments/"; _localDiskSegmentTarPath = _currentDiskWorkDir + "/segmentsTar/"; new File(_localDiskSegmentTarPath).mkdirs(); LOGGER.info("*********************************************************************"); LOGGER.info("Configurations : {}", context.getConfiguration().toString()); LOGGER.info("*********************************************************************"); LOGGER.info("Current HDFS working dir : {}", _currentHdfsWorkDir); LOGGER.info("Current DISK working dir : {}", new File(_currentDiskWorkDir).getAbsolutePath()); LOGGER.info("*********************************************************************"); _properties = context.getConfiguration(); _outputPath = _properties.get("path.to.output"); _tableName = _properties.get("segment.table.name"); _postfix = _properties.get("segment.name.postfix", null); if (_outputPath == null || _tableName == null) { throw new RuntimeException( "Missing configs: " + "\n\toutputPath: " + _properties.get("path.to.output") + "\n\ttableName: " + _properties.get("segment.table.name")); } } @Override public void cleanup(Context context) throws IOException, InterruptedException { FileUtils.deleteQuietly(new File(_currentDiskWorkDir)); } @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); String[] lineSplits = line.split(" "); LOGGER.info("*********************************************************************"); LOGGER.info("mapper input : {}", value); LOGGER.info("PATH_TO_OUTPUT : {}", _outputPath); LOGGER.info("TABLE_NAME : {}", _tableName); LOGGER.info("num lines : {}", lineSplits.length); for (String split : lineSplits) { LOGGER.info("Command line : {}", split); } LOGGER.info("*********************************************************************"); if (lineSplits.length != 3) { throw new RuntimeException("Input to the mapper is malformed, please contact the pinot team"); } _inputFilePath = lineSplits[1].trim(); Schema schema = new ObjectMapper().readValue(context.getConfiguration().get("data.schema"), Schema.class); LOGGER.info("*********************************************************************"); LOGGER.info("input data file path : {}", _inputFilePath); LOGGER.info("local hdfs segment tar path: {}", _localHdfsSegmentTarPath); LOGGER.info("local disk segment path: {}", _localDiskSegmentDirectory); LOGGER.info("local disk segment tar path: {}", _localDiskSegmentTarPath); LOGGER.info("data schema: {}", _localDiskSegmentTarPath); LOGGER.info("*********************************************************************"); try { createSegment(_inputFilePath, schema, lineSplits[2]); LOGGER.info("finished segment creation job successfully"); } catch (Exception e) { LOGGER.error("Got exceptions during creating segments!", e); } context.write(new LongWritable(Long.parseLong(lineSplits[2])), new Text(FileSystem.get(new Configuration()).listStatus(new Path(_localHdfsSegmentTarPath + "/"))[0].getPath().getName())); LOGGER.info("finished the job successfully"); } private String createSegment(String dataFilePath, Schema schema, String seqId) throws Exception { final FileSystem fs = FileSystem.get(new Configuration()); final Path hdfsDataPath = new Path(dataFilePath); final File dataPath = new File(_currentDiskWorkDir, "data"); if (dataPath.exists()) { dataPath.delete(); } dataPath.mkdir(); final Path localAvroPath = new Path(dataPath + "/" + hdfsDataPath.getName()); fs.copyToLocalFile(hdfsDataPath, localAvroPath); LOGGER.info("Data schema is : {}", schema); SegmentGeneratorConfig segmentGeneratorConfig = new SegmentGeneratorConfig(schema); segmentGeneratorConfig.setTableName(_tableName); segmentGeneratorConfig.setInputFilePath(new File(dataPath, hdfsDataPath.getName()).getAbsolutePath()); FileFormat fileFormat = getFileFormat(dataFilePath); segmentGeneratorConfig.setInputFileFormat(fileFormat); if (null != _postfix) { segmentGeneratorConfig.setSegmentNamePostfix(String.format("%s-%s", _postfix, seqId)); } else { segmentGeneratorConfig.setSegmentNamePostfix(seqId); } segmentGeneratorConfig.setRecordeReaderConfig(getReaderConfig(fileFormat)); segmentGeneratorConfig.setIndexOutputDir(_localDiskSegmentDirectory); SegmentIndexCreationDriverImpl driver = new SegmentIndexCreationDriverImpl(); driver.init(segmentGeneratorConfig); driver.build(); // Tar the segment directory into file. String segmentName = (new File(_localDiskSegmentDirectory).listFiles()[0]).getName(); String localSegmentPath = new File(_localDiskSegmentDirectory, segmentName).getAbsolutePath(); String localTarPath = _localDiskSegmentTarPath + "/" + segmentName + ".tar.gz"; LOGGER.info("Trying to tar the segment to: {}", localTarPath); TarGzCompressionUtils.createTarGzOfDirectory(localSegmentPath, localTarPath); String hdfsTarPath = _localHdfsSegmentTarPath + "/" + segmentName + ".tar.gz"; LOGGER.info("*********************************************************************"); LOGGER.info("Copy from : {} to {}", localTarPath, hdfsTarPath); LOGGER.info("*********************************************************************"); fs.copyFromLocalFile(true, true, new Path(localTarPath), new Path(hdfsTarPath)); return segmentName; } private RecordReaderConfig getReaderConfig(FileFormat fileFormat) { RecordReaderConfig readerConfig = null; switch (fileFormat) { case CSV: readerConfig = new CSVRecordReaderConfig(); break; case AVRO: break; case JSON: break; default: break; } return readerConfig; } private FileFormat getFileFormat(String dataFilePath) { if (dataFilePath.endsWith(".json")) { return FileFormat.JSON; } if (dataFilePath.endsWith(".csv")) { return FileFormat.CSV; } if (dataFilePath.endsWith(".avro")) { return FileFormat.AVRO; } throw new RuntimeException("Not support file format - " + dataFilePath); } } }
pinot-hadoop/src/main/java/com/linkedin/pinot/hadoop/job/mapper/HadoopSegmentCreationMapReduceJob.java
/** * Copyright (C) 2014-2015 LinkedIn Corp. ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.linkedin.pinot.hadoop.job.mapper; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.codehaus.jackson.map.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.stringtemplate.v4.compiler.STParser.list_return; import com.linkedin.pinot.common.data.Schema; import com.linkedin.pinot.common.utils.TarGzCompressionUtils; import com.linkedin.pinot.core.data.readers.CSVRecordReaderConfig; import com.linkedin.pinot.core.data.readers.FileFormat; import com.linkedin.pinot.core.data.readers.RecordReaderConfig; import com.linkedin.pinot.core.indexsegment.generator.SegmentGeneratorConfig; import com.linkedin.pinot.core.segment.creator.impl.SegmentIndexCreationDriverImpl; public class HadoopSegmentCreationMapReduceJob { public static class HadoopSegmentCreationMapper extends Mapper<LongWritable, Text, LongWritable, Text> { private static Logger LOGGER = LoggerFactory.getLogger(HadoopSegmentCreationMapper.class); private Configuration _properties; private String _inputFilePath; private String _outputPath; private String _tableName; private Path _currentHdfsWorkDir; private String _currentDiskWorkDir; // Temporary HDFS path for local machine private String _localHdfsSegmentTarPath; private String _localDiskSegmentDirectory; private String _localDiskSegmentTarPath; @Override public void setup(Context context) throws IOException, InterruptedException { _currentHdfsWorkDir = FileOutputFormat.getWorkOutputPath(context); _currentDiskWorkDir = "pinot_hadoop_tmp"; // Temporary HDFS path for local machine _localHdfsSegmentTarPath = _currentHdfsWorkDir + "/segmentTar"; // Temporary DISK path for local machine _localDiskSegmentDirectory = _currentDiskWorkDir + "/segments/"; _localDiskSegmentTarPath = _currentDiskWorkDir + "/segmentsTar/"; new File(_localDiskSegmentTarPath).mkdirs(); LOGGER.info("*********************************************************************"); LOGGER.info("Configurations : {}", context.getConfiguration().toString()); LOGGER.info("*********************************************************************"); LOGGER.info("Current HDFS working dir : {}", _currentHdfsWorkDir); LOGGER.info("Current DISK working dir : {}", new File(_currentDiskWorkDir).getAbsolutePath()); LOGGER.info("*********************************************************************"); _properties = context.getConfiguration(); _outputPath = _properties.get("path.to.output"); _tableName = _properties.get("segment.table.name"); if (_outputPath == null || _tableName == null) { throw new RuntimeException( "Missing configs: " + "\n\toutputPath: " + _properties.get("path.to.output") + "\n\ttableName: " + _properties.get("segment.table.name")); } } @Override public void cleanup(Context context) throws IOException, InterruptedException { FileUtils.deleteQuietly(new File(_currentDiskWorkDir)); } @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); String[] lineSplits = line.split(" "); LOGGER.info("*********************************************************************"); LOGGER.info("mapper input : {}", value); LOGGER.info("PATH_TO_OUTPUT : {}", _outputPath); LOGGER.info("TABLE_NAME : {}", _tableName); LOGGER.info("num lines : {}", lineSplits.length); for (String split : lineSplits) { LOGGER.info("Command line : {}", split); } LOGGER.info("*********************************************************************"); if (lineSplits.length != 3) { throw new RuntimeException("Input to the mapper is malformed, please contact the pinot team"); } _inputFilePath = lineSplits[1].trim(); Schema schema = new ObjectMapper().readValue(context.getConfiguration().get("data.schema"), Schema.class); LOGGER.info("*********************************************************************"); LOGGER.info("input data file path : {}", _inputFilePath); LOGGER.info("local hdfs segment tar path: {}", _localHdfsSegmentTarPath); LOGGER.info("local disk segment path: {}", _localDiskSegmentDirectory); LOGGER.info("local disk segment tar path: {}", _localDiskSegmentTarPath); LOGGER.info("data schema: {}", _localDiskSegmentTarPath); LOGGER.info("*********************************************************************"); try { createSegment(_inputFilePath, schema, lineSplits[2]); LOGGER.info("finished segment creation job successfully"); } catch (Exception e) { LOGGER.error("Got exceptions during creating segments!", e); } context.write(new LongWritable(Long.parseLong(lineSplits[2])), new Text(FileSystem.get(new Configuration()).listStatus(new Path(_localHdfsSegmentTarPath + "/"))[0].getPath().getName())); LOGGER.info("finished the job successfully"); } private String createSegment(String dataFilePath, Schema schema, String seqId) throws Exception { final FileSystem fs = FileSystem.get(new Configuration()); final Path hdfsDataPath = new Path(dataFilePath); final File dataPath = new File(_currentDiskWorkDir, "data"); if (dataPath.exists()) { dataPath.delete(); } dataPath.mkdir(); final Path localAvroPath = new Path(dataPath + "/" + hdfsDataPath.getName()); fs.copyToLocalFile(hdfsDataPath, localAvroPath); LOGGER.info("Data schema is : {}", schema); SegmentGeneratorConfig segmentGeneratorConfig = new SegmentGeneratorConfig(schema); segmentGeneratorConfig.setTableName(_tableName); segmentGeneratorConfig.setInputFilePath(new File(dataPath, hdfsDataPath.getName()).getAbsolutePath()); FileFormat fileFormat = getFileFormat(dataFilePath); segmentGeneratorConfig.setInputFileFormat(fileFormat); segmentGeneratorConfig.setSegmentNamePostfix(seqId); segmentGeneratorConfig.setRecordeReaderConfig(getReaderConfig(fileFormat)); segmentGeneratorConfig.setIndexOutputDir(_localDiskSegmentDirectory); SegmentIndexCreationDriverImpl driver = new SegmentIndexCreationDriverImpl(); driver.init(segmentGeneratorConfig); driver.build(); // Tar the segment directory into file. String segmentName = (new File(_localDiskSegmentDirectory).listFiles()[0]).getName(); String localSegmentPath = new File(_localDiskSegmentDirectory, segmentName).getAbsolutePath(); String localTarPath = _localDiskSegmentTarPath + "/" + segmentName + ".tar.gz"; LOGGER.info("Trying to tar the segment to: {}", localTarPath); TarGzCompressionUtils.createTarGzOfDirectory(localSegmentPath, localTarPath); String hdfsTarPath = _localHdfsSegmentTarPath + "/" + segmentName + ".tar.gz"; LOGGER.info("*********************************************************************"); LOGGER.info("Copy from : {} to {}", localTarPath, hdfsTarPath); LOGGER.info("*********************************************************************"); fs.copyFromLocalFile(true, true, new Path(localTarPath), new Path(hdfsTarPath)); return segmentName; } private RecordReaderConfig getReaderConfig(FileFormat fileFormat) { RecordReaderConfig readerConfig = null; switch (fileFormat) { case CSV: readerConfig = new CSVRecordReaderConfig(); break; case AVRO: break; case JSON: break; default: break; } return readerConfig; } private FileFormat getFileFormat(String dataFilePath) { if (dataFilePath.endsWith(".json")) { return FileFormat.JSON; } if (dataFilePath.endsWith(".csv")) { return FileFormat.CSV; } if (dataFilePath.endsWith(".avro")) { return FileFormat.AVRO; } throw new RuntimeException("Not support file format - " + dataFilePath); } } }
Adding postfix config segment.name.postfix to hadoop segment creation job configs.
pinot-hadoop/src/main/java/com/linkedin/pinot/hadoop/job/mapper/HadoopSegmentCreationMapReduceJob.java
Adding postfix config segment.name.postfix to hadoop segment creation job configs.
<ide><path>inot-hadoop/src/main/java/com/linkedin/pinot/hadoop/job/mapper/HadoopSegmentCreationMapReduceJob.java <ide> import org.codehaus.jackson.map.ObjectMapper; <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <del>import org.stringtemplate.v4.compiler.STParser.list_return; <ide> <ide> import com.linkedin.pinot.common.data.Schema; <ide> import com.linkedin.pinot.common.utils.TarGzCompressionUtils; <ide> private String _inputFilePath; <ide> private String _outputPath; <ide> private String _tableName; <add> private String _postfix; <ide> <ide> private Path _currentHdfsWorkDir; <ide> private String _currentDiskWorkDir; <ide> <ide> _outputPath = _properties.get("path.to.output"); <ide> _tableName = _properties.get("segment.table.name"); <add> _postfix = _properties.get("segment.name.postfix", null); <ide> if (_outputPath == null || _tableName == null) { <ide> throw new RuntimeException( <ide> "Missing configs: " + <ide> <ide> FileFormat fileFormat = getFileFormat(dataFilePath); <ide> segmentGeneratorConfig.setInputFileFormat(fileFormat); <del> segmentGeneratorConfig.setSegmentNamePostfix(seqId); <add> if (null != _postfix) { <add> segmentGeneratorConfig.setSegmentNamePostfix(String.format("%s-%s", _postfix, seqId)); <add> } else { <add> segmentGeneratorConfig.setSegmentNamePostfix(seqId); <add> } <ide> segmentGeneratorConfig.setRecordeReaderConfig(getReaderConfig(fileFormat)); <ide> <ide> segmentGeneratorConfig.setIndexOutputDir(_localDiskSegmentDirectory);
Java
apache-2.0
021c90a99e65efa90f74d82ff5fb44c165e88b65
0
eFaps/eFapsApp-Commons
/* * Copyright 2003 - 2015 The eFaps Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.efaps.esjp.erp.util; import java.util.UUID; import org.efaps.admin.common.SystemConfiguration; import org.efaps.admin.datamodel.IBitEnum; import org.efaps.admin.datamodel.attributetype.BitEnumType; import org.efaps.admin.program.esjp.EFapsApplication; import org.efaps.admin.program.esjp.EFapsUUID; import org.efaps.api.annotation.EFapsSysConfAttribute; import org.efaps.api.annotation.EFapsSysConfLink; import org.efaps.api.annotation.EFapsSystemConfiguration; import org.efaps.esjp.admin.common.systemconfiguration.BooleanSysConfAttribute; import org.efaps.esjp.admin.common.systemconfiguration.PropertiesSysConfAttribute; import org.efaps.esjp.admin.common.systemconfiguration.StringSysConfAttribute; import org.efaps.esjp.admin.common.systemconfiguration.SysConfLink; import org.efaps.util.cache.CacheReloadException; /** * TODO comment! * * @author The eFaps Team */ @EFapsUUID("2806f80c-8395-41ce-9410-0c6bbb4614b7") @EFapsApplication("eFapsApp-Commons") @EFapsSystemConfiguration("9ac2673a-18f9-41ba-b9be-5b0980bdf6f3") public final class ERP { /** The base. */ public static final String BASE = "org.efaps.commons."; /** Commons-Configuration. */ public static final UUID SYSCONFUUID = UUID.fromString("9ac2673a-18f9-41ba-b9be-5b0980bdf6f3"); /** See description. */ @EFapsSysConfAttribute public static final StringSysConfAttribute COMPANY_NAME = new StringSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "CompanyName") .description("Name of the selected company."); /** See description. */ @EFapsSysConfAttribute public static final StringSysConfAttribute COMPANY_TAX = new StringSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "CompanyTaxNumber") .description("Tax number of the selected company."); /** See description. */ @EFapsSysConfAttribute public static final StringSysConfAttribute COMPANY_ACTIVITY = new StringSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "CompanyActivity") .description("Activity of the selected company."); /** See description. */ @EFapsSysConfAttribute public static final StringSysConfAttribute COMPANY_STREET = new StringSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "CompanyStreet") .description("Street of the selected company."); /** See description. */ @EFapsSysConfAttribute public static final StringSysConfAttribute COMPANY_REGION = new StringSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "CompanyRegion") .description("Region of the selected company."); /** See description. */ @EFapsSysConfAttribute public static final StringSysConfAttribute COMPANY_CITY = new StringSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "CompanyCity") .description("City of the selected company."); /** See description. */ @EFapsSysConfAttribute public static final StringSysConfAttribute COMPANY_DISTRICT = new StringSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "CompanyDistrict") .description("District of the selected company."); /** See description. */ @EFapsSysConfAttribute public static final StringSysConfAttribute COMPANY_COUNTRY = new StringSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "CompanyCountry") .defaultValue("PE") .description("Country of the selected company."); /** See description. */ @EFapsSysConfAttribute public static final StringSysConfAttribute COMPANY_UBIGEO = new StringSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "CompanyUbigeo") .defaultValue("150101") .description("Ubigeo of the company."); /** See description. */ @EFapsSysConfAttribute public static final StringSysConfAttribute COMPANY_ESTABLECIMIENTO = new StringSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "CompanyEstablecimiento") .defaultValue("0000") .description("Establecimiento of the company."); /** See description. */ @EFapsSysConfAttribute public static final PropertiesSysConfAttribute FILTERREPORTCONFIG = new PropertiesSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "Config4FilteredReport") .description("Basic Configurations for Filtered Reports."); /** See description. */ @EFapsSysConfAttribute public static final PropertiesSysConfAttribute DOCSTATUSCREATE = new PropertiesSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "DocumentStatus4Create") .description("TYPENAME.Status.") .concatenate(true); /** See description. */ @EFapsSysConfAttribute public static final PropertiesSysConfAttribute RELATIONSHIPS = new PropertiesSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "Relationships") .description("Properties like TYPENAME.Relationship, TYPENAME.FromAttribute and " + "TYPENAME.ToAttribute. Optional TYPENAME.Unique") .concatenate(true); /** See description. */ @EFapsSysConfAttribute public static final PropertiesSysConfAttribute JASPERKEY = new PropertiesSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "JasperKey") .description("Set a JasperReport for a Type. Used for Common Documents.") .concatenate(true); /** See description. */ @EFapsSysConfAttribute public static final PropertiesSysConfAttribute NUMBERFRMT = new PropertiesSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "NumberFormatter") .description("Set Formatting information for numbers..") .concatenate(true); /** See description. */ @EFapsSysConfAttribute public static final PropertiesSysConfAttribute NUMBERGENERATOR = new PropertiesSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "NumberGenerators") .description("Set a NumberGenerator for a Type. Used for Common Documents") .concatenate(true); /** See description. */ @EFapsSysConfAttribute public static final PropertiesSysConfAttribute RATEFRMT = new PropertiesSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "RateFormatter") .description("Set Formatting information for rates") .addDefaultValue("Rate", "0.000000000000") .addDefaultValue("RateUI", "0.000") .addDefaultValue("SaleRate", "0.000000000000") .addDefaultValue("SaleRateUI", "0.000") .description("Can be overwritten by using TYPE.Rate, TYPE.SalesRateUI etc.") .concatenate(true); /** See description. */ @EFapsSysConfAttribute public static final PropertiesSysConfAttribute RATEINFO = new PropertiesSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "RateInfo4Key") .description("Set Info information for rates.") .addDefaultValue("DOCDATEPURCHASE", "purchase") .addDefaultValue("DOCDATESALE", "sale") .addDefaultValue("TRANSDATEPURCHASE", "purchase") .addDefaultValue("TRANSDATESALE", "sale") .concatenate(true); /** See description. */ @EFapsSysConfAttribute public static final PropertiesSysConfAttribute ACTIONDEF = new PropertiesSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "ActionDefinition") .description(" Key: Normally the type name.Values: One of EDIT, CREATE, NONE\n" + "To be able to set the date:\n" + "KEY.Date=true") .concatenate(true); /** See description. */ @EFapsSysConfAttribute public static final PropertiesSysConfAttribute WARNING = new PropertiesSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "Warning") .description(" Key: Normally the type name"); /** See description. */ @EFapsSysConfAttribute public static final PropertiesSysConfAttribute CURRENCIES = new PropertiesSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "Currencies") .description("Configuration related to Currencies.\n" + "CURRENCY: UUID or ISOCODE of Currency\n" + "CURRENCY.ForceDailyRate=true\n" + "CURRENCY.Force4Role01=ROLE\n" + "CURRENCY.Warn4Role01=ROLE\n"); /** See description. */ @EFapsSysConfLink public static final SysConfLink CURRENCYBASE = new SysConfLink() .sysConfUUID(SYSCONFUUID) .key(BASE + "CurrencyBase") .description("Base Currency."); /** See description. */ @EFapsSysConfAttribute public static final BooleanSysConfAttribute BIN_ACTIVATE = new BooleanSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "BinUser.Activate") .description("Activate the mechanism for BinUser"); /** * Enum used for a multistate for Activation in ERP_DocumentType. */ public enum DocTypeActivation implements IBitEnum { /** NONE. */ NONE, /** Docu. */ TAX, /** Outgoing. */ NOTAX; /** * {@inheritDoc} */ @Override public int getInt() { return BitEnumType.getInt4Index(ordinal()); } /** * {@inheritDoc} */ @Override public int getBitIndex() { return ordinal(); } } /** * Enum used for a multistate for Configuration in ERP_DocumentType. */ public enum DocTypeConfiguration implements IBitEnum { /** Documents will be used in the PurchaseRecors from Accounting. */ PURCHASERECORD, /** * Documents is marked as a type valid for Professional * Service. */ PROFESSIONALSERVICE; /** * {@inheritDoc} */ @Override public int getInt() { return BitEnumType.getInt4Index(ordinal()); } /** * {@inheritDoc} */ @Override public int getBitIndex() { return ordinal(); } } /** * Enum used for a multistate for Configuration in ERP_DocumentType. */ public enum DocRelationSituation implements IBitEnum { /** The partial. */ PARTIAL; /** * {@inheritDoc} */ @Override public int getInt() { return BitEnumType.getInt4Index(ordinal()); } /** * {@inheritDoc} */ @Override public int getBitIndex() { return ordinal(); } } /** * Singelton. */ private ERP() { } /** * @return the SystemConfigruation for Sales * @throws CacheReloadException on error */ public static SystemConfiguration getSysConfig() throws CacheReloadException { return SystemConfiguration.get(SYSCONFUUID); } }
src/main/efaps/ESJP/org/efaps/esjp/erp/util/ERP.java
/* * Copyright 2003 - 2015 The eFaps Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.efaps.esjp.erp.util; import java.util.UUID; import org.efaps.admin.common.SystemConfiguration; import org.efaps.admin.datamodel.IBitEnum; import org.efaps.admin.datamodel.attributetype.BitEnumType; import org.efaps.admin.program.esjp.EFapsApplication; import org.efaps.admin.program.esjp.EFapsUUID; import org.efaps.api.annotation.EFapsSysConfAttribute; import org.efaps.api.annotation.EFapsSysConfLink; import org.efaps.api.annotation.EFapsSystemConfiguration; import org.efaps.esjp.admin.common.systemconfiguration.BooleanSysConfAttribute; import org.efaps.esjp.admin.common.systemconfiguration.PropertiesSysConfAttribute; import org.efaps.esjp.admin.common.systemconfiguration.StringSysConfAttribute; import org.efaps.esjp.admin.common.systemconfiguration.SysConfLink; import org.efaps.util.cache.CacheReloadException; /** * TODO comment! * * @author The eFaps Team */ @EFapsUUID("2806f80c-8395-41ce-9410-0c6bbb4614b7") @EFapsApplication("eFapsApp-Commons") @EFapsSystemConfiguration("9ac2673a-18f9-41ba-b9be-5b0980bdf6f3") public final class ERP { /** The base. */ public static final String BASE = "org.efaps.commons."; /** Commons-Configuration. */ public static final UUID SYSCONFUUID = UUID.fromString("9ac2673a-18f9-41ba-b9be-5b0980bdf6f3"); /** See description. */ @EFapsSysConfAttribute public static final StringSysConfAttribute COMPANY_NAME = new StringSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "CompanyName") .description("Name of the selected company."); /** See description. */ @EFapsSysConfAttribute public static final StringSysConfAttribute COMPANY_TAX = new StringSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "CompanyTaxNumber") .description("Tax number of the selected company."); /** See description. */ @EFapsSysConfAttribute public static final StringSysConfAttribute COMPANY_ACTIVITY = new StringSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "CompanyActivity") .description("Activity of the selected company."); /** See description. */ @EFapsSysConfAttribute public static final StringSysConfAttribute COMPANY_STREET = new StringSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "CompanyStreet") .description("Street of the selected company."); /** See description. */ @EFapsSysConfAttribute public static final StringSysConfAttribute COMPANY_REGION = new StringSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "CompanyRegion") .description("Region of the selected company."); /** See description. */ @EFapsSysConfAttribute public static final StringSysConfAttribute COMPANY_CITY = new StringSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "CompanyCity") .description("City of the selected company."); /** See description. */ @EFapsSysConfAttribute public static final StringSysConfAttribute COMPANY_DISTRICT = new StringSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "CompanyDistrict") .description("District of the selected company."); /** See description. */ @EFapsSysConfAttribute public static final StringSysConfAttribute COMPANY_COUNTRY = new StringSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "CompanyCountry") .defaultValue("PE") .description("Country of the selected company."); /** See description. */ @EFapsSysConfAttribute public static final StringSysConfAttribute COMPANY_UBIGEO = new StringSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "CompanyUbigeo") .defaultValue("150101") .description("Ubigeo of the company."); /** See description. */ @EFapsSysConfAttribute public static final StringSysConfAttribute COMPANY_ESTABLECIMIENTO = new StringSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "CompanyEstablecimiento") .defaultValue("1000") .description("Establecimiento of the company."); /** See description. */ @EFapsSysConfAttribute public static final PropertiesSysConfAttribute FILTERREPORTCONFIG = new PropertiesSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "Config4FilteredReport") .description("Basic Configurations for Filtered Reports."); /** See description. */ @EFapsSysConfAttribute public static final PropertiesSysConfAttribute DOCSTATUSCREATE = new PropertiesSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "DocumentStatus4Create") .description("TYPENAME.Status.") .concatenate(true); /** See description. */ @EFapsSysConfAttribute public static final PropertiesSysConfAttribute RELATIONSHIPS = new PropertiesSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "Relationships") .description("Properties like TYPENAME.Relationship, TYPENAME.FromAttribute and " + "TYPENAME.ToAttribute. Optional TYPENAME.Unique") .concatenate(true); /** See description. */ @EFapsSysConfAttribute public static final PropertiesSysConfAttribute JASPERKEY = new PropertiesSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "JasperKey") .description("Set a JasperReport for a Type. Used for Common Documents.") .concatenate(true); /** See description. */ @EFapsSysConfAttribute public static final PropertiesSysConfAttribute NUMBERFRMT = new PropertiesSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "NumberFormatter") .description("Set Formatting information for numbers..") .concatenate(true); /** See description. */ @EFapsSysConfAttribute public static final PropertiesSysConfAttribute NUMBERGENERATOR = new PropertiesSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "NumberGenerators") .description("Set a NumberGenerator for a Type. Used for Common Documents") .concatenate(true); /** See description. */ @EFapsSysConfAttribute public static final PropertiesSysConfAttribute RATEFRMT = new PropertiesSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "RateFormatter") .description("Set Formatting information for rates") .addDefaultValue("Rate", "0.000000000000") .addDefaultValue("RateUI", "0.000") .addDefaultValue("SaleRate", "0.000000000000") .addDefaultValue("SaleRateUI", "0.000") .description("Can be overwritten by using TYPE.Rate, TYPE.SalesRateUI etc.") .concatenate(true); /** See description. */ @EFapsSysConfAttribute public static final PropertiesSysConfAttribute RATEINFO = new PropertiesSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "RateInfo4Key") .description("Set Info information for rates.") .addDefaultValue("DOCDATEPURCHASE", "purchase") .addDefaultValue("DOCDATESALE", "sale") .addDefaultValue("TRANSDATEPURCHASE", "purchase") .addDefaultValue("TRANSDATESALE", "sale") .concatenate(true); /** See description. */ @EFapsSysConfAttribute public static final PropertiesSysConfAttribute ACTIONDEF = new PropertiesSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "ActionDefinition") .description(" Key: Normally the type name.Values: One of EDIT, CREATE, NONE\n" + "To be able to set the date:\n" + "KEY.Date=true") .concatenate(true); /** See description. */ @EFapsSysConfAttribute public static final PropertiesSysConfAttribute WARNING = new PropertiesSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "Warning") .description(" Key: Normally the type name"); /** See description. */ @EFapsSysConfAttribute public static final PropertiesSysConfAttribute CURRENCIES = new PropertiesSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "Currencies") .description("Configuration related to Currencies.\n" + "CURRENCY: UUID or ISOCODE of Currency\n" + "CURRENCY.ForceDailyRate=true\n" + "CURRENCY.Force4Role01=ROLE\n" + "CURRENCY.Warn4Role01=ROLE\n"); /** See description. */ @EFapsSysConfLink public static final SysConfLink CURRENCYBASE = new SysConfLink() .sysConfUUID(SYSCONFUUID) .key(BASE + "CurrencyBase") .description("Base Currency."); /** See description. */ @EFapsSysConfAttribute public static final BooleanSysConfAttribute BIN_ACTIVATE = new BooleanSysConfAttribute() .sysConfUUID(SYSCONFUUID) .key(BASE + "BinUser.Activate") .description("Activate the mechanism for BinUser"); /** * Enum used for a multistate for Activation in ERP_DocumentType. */ public enum DocTypeActivation implements IBitEnum { /** NONE. */ NONE, /** Docu. */ TAX, /** Outgoing. */ NOTAX; /** * {@inheritDoc} */ @Override public int getInt() { return BitEnumType.getInt4Index(ordinal()); } /** * {@inheritDoc} */ @Override public int getBitIndex() { return ordinal(); } } /** * Enum used for a multistate for Configuration in ERP_DocumentType. */ public enum DocTypeConfiguration implements IBitEnum { /** Documents will be used in the PurchaseRecors from Accounting. */ PURCHASERECORD, /** * Documents is marked as a type valid for Professional * Service. */ PROFESSIONALSERVICE; /** * {@inheritDoc} */ @Override public int getInt() { return BitEnumType.getInt4Index(ordinal()); } /** * {@inheritDoc} */ @Override public int getBitIndex() { return ordinal(); } } /** * Enum used for a multistate for Configuration in ERP_DocumentType. */ public enum DocRelationSituation implements IBitEnum { /** The partial. */ PARTIAL; /** * {@inheritDoc} */ @Override public int getInt() { return BitEnumType.getInt4Index(ordinal()); } /** * {@inheritDoc} */ @Override public int getBitIndex() { return ordinal(); } } /** * Singelton. */ private ERP() { } /** * @return the SystemConfigruation for Sales * @throws CacheReloadException on error */ public static SystemConfiguration getSysConfig() throws CacheReloadException { return SystemConfiguration.get(SYSCONFUUID); } }
Change default value
src/main/efaps/ESJP/org/efaps/esjp/erp/util/ERP.java
Change default value
<ide><path>rc/main/efaps/ESJP/org/efaps/esjp/erp/util/ERP.java <ide> public static final StringSysConfAttribute COMPANY_ESTABLECIMIENTO = new StringSysConfAttribute() <ide> .sysConfUUID(SYSCONFUUID) <ide> .key(BASE + "CompanyEstablecimiento") <del> .defaultValue("1000") <add> .defaultValue("0000") <ide> .description("Establecimiento of the company."); <ide> <ide> /** See description. */
Java
mit
error: pathspec 'JavaMain/src/com/dw/leetcode/Clone_Graph_133.java' did not match any file(s) known to git
5f135fe2280242eb875c0f53be3576168c694397
1
emacslisp/Java,emacslisp/Java,emacslisp/Java,emacslisp/Java
package com.dw.leetcode; import java.util.*; //@todo: finish clone graph with 133 public class Clone_Graph_133 { static class UndirectedGraphNode { int label; List<UndirectedGraphNode> neighbors; UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); } }; public static UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { if(node == null) return null; Map<Integer,UndirectedGraphNode> nodeMap = new HashMap<Integer,UndirectedGraphNode>(); Map<Integer,UndirectedGraphNode> rootMap = new HashMap<Integer,UndirectedGraphNode>(); UndirectedGraphNode root = new UndirectedGraphNode(node.label); return root; } public static void foo() { } public static void main(String[] args) { } }
JavaMain/src/com/dw/leetcode/Clone_Graph_133.java
add 133 clone graph
JavaMain/src/com/dw/leetcode/Clone_Graph_133.java
add 133 clone graph
<ide><path>avaMain/src/com/dw/leetcode/Clone_Graph_133.java <add>package com.dw.leetcode; <add> <add>import java.util.*; <add> <add>//@todo: finish clone graph with 133 <add> <add>public class Clone_Graph_133 { <add> static class UndirectedGraphNode { <add> int label; <add> List<UndirectedGraphNode> neighbors; <add> <add> UndirectedGraphNode(int x) { <add> label = x; <add> neighbors = new ArrayList<UndirectedGraphNode>(); <add> } <add> }; <add> <add> public static UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { <add> if(node == null) return null; <add> <add> Map<Integer,UndirectedGraphNode> nodeMap = new HashMap<Integer,UndirectedGraphNode>(); <add> Map<Integer,UndirectedGraphNode> rootMap = new HashMap<Integer,UndirectedGraphNode>(); <add> <add> UndirectedGraphNode root = new UndirectedGraphNode(node.label); <add> <add> <add> <add> return root; <add> } <add> <add> public static void foo() { <add> <add> } <add> <add> public static void main(String[] args) { <add> <add> } <add>}
Java
apache-2.0
434c8f8211e9415984fe0fa89d7d7ce2d915e986
0
drinkjava2/jSQLBox
/* * Copyright (C) 2016 Yong Zhu. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by * applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS * OF ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ package com.github.drinkjava2.jtinynet.parser; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.github.drinkjava2.jdialects.StrUtils; import com.github.drinkjava2.jtinynet.TinyNetException; /** * SimpleExpressionParser parse a String, return true or false * * In SimpleExpressionParser, the parse method only support below keywords: * * <pre> > < = >= <= + - * / equals equalsIgnoreCase contains containsIgnoreCase startWith startWithIgnoreCase endWith endWithIgnoreCase or and not ' () ? 0~9 beanFields selectedSize level * * </pre> * * For example: "userName startWith ? and not(-age*10 -age>?) or address * contains if(age>?,'FOO','BAR') * * @author Yong Zhu ([email protected]) * @since 1.0.0 */ public class SimpleExpressionParser { private static final Map<String, Func> FUNCTIONMAP = new HashMap<String, Func>(); static { FUNCTIONMAP.put("*", new Func(3, 2)); FUNCTIONMAP.put("/", new Func(3, 2)); FUNCTIONMAP.put("+", new Func(4, 2)); FUNCTIONMAP.put("-", new Func(4, 2)); FUNCTIONMAP.put("not", new Func(5, 1)); FUNCTIONMAP.put("equals", new Func(6, 2)); FUNCTIONMAP.put("equalsIgnoreCase", new Func(6, 2)); FUNCTIONMAP.put("contains", new Func(6, 2)); FUNCTIONMAP.put("containsIgnoreCase", new Func(6, 2)); FUNCTIONMAP.put("startWith", new Func(6, 2)); FUNCTIONMAP.put("startWithIgnoreCase", new Func(6, 2)); FUNCTIONMAP.put("endWith", new Func(6, 2)); FUNCTIONMAP.put("endWithIgnoreCase", new Func(6, 2)); FUNCTIONMAP.put(">", new Func(8, 2)); FUNCTIONMAP.put("<", new Func(8, 2)); FUNCTIONMAP.put("=", new Func(8, 2)); FUNCTIONMAP.put(">=", new Func(8, 2)); FUNCTIONMAP.put("<=", new Func(8, 2)); FUNCTIONMAP.put("<>", new Func(8, 2)); FUNCTIONMAP.put("or", new Func(10, 2)); FUNCTIONMAP.put("and", new Func(10, 2)); } private static final Set<String> FUNCTIONNAMES = FUNCTIONMAP.keySet(); /** * Parse a expression String, return true if pass validate, false if failed for * validate * * @param bean The bean be validated * @param level Current search level * @param selectedSize Current selected Node QTY * @param expression The expression * @param params The expression parameter array * @return true if pass validate, false if failed for validate */ public static boolean parse(Object bean, int level, int selectedSize, String expression, Object... params) { if (StrUtils.isEmpty(expression)) return true; return true; } public static class Func { public int priority; public int operatorQTY; public Func(int priority, int operatorQTY) { this.priority = priority; this.operatorQTY = operatorQTY; } } public static class Item { private int priority; private Object value; private char type; // S:String, B:Boolean, L: Long, D:Double, P:parameter, I:items, // U:Unknow_Function_Or_Variant private List<Item> subItem; public String getDebugInfo() { String result = "\rItemValue="; if (value != null) result += value; if (subItem != null) { for (Item Item : subItem) { result += " " + Item.getDebugInfo(); } } return result; } } public static class keywordResult { } public static class SearchResult { private Item item; private int leftStart; private int leftEnd; private SearchResult(Item item, int leftStart, int leftEnd) { this.item = item; this.leftStart = leftStart; this.leftEnd = leftEnd; } } private static boolean isLetterNumber(char c) { return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || c == '_' || c == '.'; } public static SearchResult findFirstResult(char[] chars, int start, int end) { if (start > end) return null; boolean letters = false; StringBuilder sb = new StringBuilder(); for (int i = start; i <= end; i++) { if (!letters) {// no letters found if (chars[i] == '?') { Item item = new Item(); item.type = 'V'; item.value = "?"; return new SearchResult(item, i + 1, end); } else if (chars[i] == '\'') { for (int j = i + 1; j <= end; j++) { if (chars[j] == '\'' && chars[j - 1] != '\\') { Item item = new Item(); item.type = 'S'; item.value = sb.toString(); return new SearchResult(item, j + 1, end); } else sb.append(chars[j]); } throw new TinyNetException("Miss right ' charactor in expression."); } else if (chars[i] == '(') { int count = 1; boolean inString = false; for (int j = i + 1; j <= end; j++) { if (!inString) { if (chars[j] == '(') count++; else if (chars[j] == ')') { count--; if (count == 0) { List<Item> subItems = seperateCharsToItems(chars, i + 1, j - 1); Item item = new Item(); item.type = 'I'; item.subItem = subItems; return new SearchResult(item, j + 1, end); } } else if (chars[j] == '\'') { inString = true; } } else { if (chars[j] == '\'' && chars[j - 1] != '\\') { inString = false; } } } throw new TinyNetException("Miss right ) charactor in expression."); } else if (chars[i] > ' ') { letters = true; sb.append(chars[i]); } } else {// letters found if (chars[i] == '?' || chars[i] == '\'' || chars[i] == '(' || chars[i] <= ' ' || isLetterNumber(chars[i]) != isLetterNumber(chars[i - 1])) { Item item = new Item(); item.type = 'U'; item.value = sb.toString(); return new SearchResult(item, i, end); } else { sb.append(chars[i]); } } } if (sb.length() > 0) { Item item = new Item(); item.type = 'U'; item.value = sb.toString(); return new SearchResult(item, end + 1, end); } else return null; } public static List<Item> seperateCharsToItems(char[] chars, int start, int end) { List<Item> items = new ArrayList<Item>(); SearchResult result = findFirstResult(chars, start, end); while (result != null) { items.add(result.item); result = findFirstResult(chars, result.leftStart, result.leftEnd); } return items; } public static Object doParse(String expression) { char[] chars = (" " + expression + " ").toCharArray(); List<Item> items = seperateCharsToItems(chars, 1, chars.length - 2); for (Item item : items) { System.out.print(item.getDebugInfo()); } return null; } public static void main(String[] args) { String s = "35*(24 -6*)+7/(4-6)"; doParse(s); } }
jsqlbox/src/main/java/com/github/drinkjava2/jtinynet/parser/SimpleExpressionParser.java
/* * Copyright (C) 2016 Yong Zhu. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by * applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS * OF ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ package com.github.drinkjava2.jtinynet.parser; import java.util.List; import com.github.drinkjava2.jdialects.StrUtils; /** * SimpleExpressionParser parse a String, return true or false * * In SimpleExpressionParser, the parse method only support below keywords: * * <pre> * ==========Math======== * > * < * = * >= * <= * + * - * * * / * * ==========String======== * equals * equalsIgnoreCase * contains * containsIgnoreCase * startWith * startWithIgnoreCase * endWith * endWithIgnoreCase * ' * * ==========Logic======== * or * and * not * ( * ) * if(condition, doTrue, doFalse) * * ==========Parameter========= * ? * * ========= Other ========== * &#64;selectedSize * &#64;level * * </pre> * * For example: "userName startWith ? and not(-age*10 -age>?) or address * contains if(age>?,'FOO','BAR') * * @author Yong Zhu ([email protected]) * @since 1.0.0 */ public class SimpleExpressionParser { /** * Parse a expression String, return true if pass validate, false if failed for * validate * * @param bean The bean be validated * @param level Current search level * @param selectedSize Current selected Node QTY * @param expression The expression * @param params The expression parameter array * @return true if pass validate, false if failed for validate */ public static boolean parse(Object bean, int level, int selectedSize, String expression, Object... params) { if (StrUtils.isEmpty(expression)) return true; return false; } private static class Item{ private char type;//O:operator, V:value, I:items private int operatorPriority; private Object value; private char valueType; //S:String, B:Boolean, L: Long, D:Double private List<Item> subItem; } }
work on simple parser
jsqlbox/src/main/java/com/github/drinkjava2/jtinynet/parser/SimpleExpressionParser.java
work on simple parser
<ide><path>sqlbox/src/main/java/com/github/drinkjava2/jtinynet/parser/SimpleExpressionParser.java <ide> */ <ide> package com.github.drinkjava2.jtinynet.parser; <ide> <add>import java.util.ArrayList; <add>import java.util.HashMap; <ide> import java.util.List; <add>import java.util.Map; <add>import java.util.Set; <ide> <ide> import com.github.drinkjava2.jdialects.StrUtils; <add>import com.github.drinkjava2.jtinynet.TinyNetException; <ide> <ide> /** <ide> * SimpleExpressionParser parse a String, return true or false <ide> * In SimpleExpressionParser, the parse method only support below keywords: <ide> * <ide> * <pre> <del> * ==========Math======== <del> * > <del> * < <del> * = <del> * >= <del> * <= <del> * + <del> * - <del> * * <del> * / <del> * <del> * ==========String======== <del> * equals <del> * equalsIgnoreCase <del> * contains <del> * containsIgnoreCase <del> * startWith <del> * startWithIgnoreCase <del> * endWith <del> * endWithIgnoreCase <del> * ' <del> * <del> * ==========Logic======== <del> * or <del> * and <del> * not <del> * ( <del> * ) <del> * if(condition, doTrue, doFalse) <del> * <del> * ==========Parameter========= <del> * ? <del> * <del> * ========= Other ========== <del> * &#64;selectedSize <del> * &#64;level <add>> <add>< <add>= <add>>= <add><= <add>+ <add>- <add>* <add>/ <add>equals <add>equalsIgnoreCase <add>contains <add>containsIgnoreCase <add>startWith <add>startWithIgnoreCase <add>endWith <add>endWithIgnoreCase <add>or <add>and <add>not <add> <add> <add>' <add>() <add>? <add>0~9 <add> <add>beanFields <add>selectedSize <add>level <ide> * <ide> * </pre> <ide> * <ide> * @since 1.0.0 <ide> */ <ide> public class SimpleExpressionParser { <add> private static final Map<String, Func> FUNCTIONMAP = new HashMap<String, Func>(); <add> static { <add> FUNCTIONMAP.put("*", new Func(3, 2)); <add> FUNCTIONMAP.put("/", new Func(3, 2)); <add> FUNCTIONMAP.put("+", new Func(4, 2)); <add> FUNCTIONMAP.put("-", new Func(4, 2)); <add> FUNCTIONMAP.put("not", new Func(5, 1)); <add> FUNCTIONMAP.put("equals", new Func(6, 2)); <add> FUNCTIONMAP.put("equalsIgnoreCase", new Func(6, 2)); <add> FUNCTIONMAP.put("contains", new Func(6, 2)); <add> FUNCTIONMAP.put("containsIgnoreCase", new Func(6, 2)); <add> FUNCTIONMAP.put("startWith", new Func(6, 2)); <add> FUNCTIONMAP.put("startWithIgnoreCase", new Func(6, 2)); <add> FUNCTIONMAP.put("endWith", new Func(6, 2)); <add> FUNCTIONMAP.put("endWithIgnoreCase", new Func(6, 2)); <add> FUNCTIONMAP.put(">", new Func(8, 2)); <add> FUNCTIONMAP.put("<", new Func(8, 2)); <add> FUNCTIONMAP.put("=", new Func(8, 2)); <add> FUNCTIONMAP.put(">=", new Func(8, 2)); <add> FUNCTIONMAP.put("<=", new Func(8, 2)); <add> FUNCTIONMAP.put("<>", new Func(8, 2)); <add> FUNCTIONMAP.put("or", new Func(10, 2)); <add> FUNCTIONMAP.put("and", new Func(10, 2)); <add> } <add> private static final Set<String> FUNCTIONNAMES = FUNCTIONMAP.keySet(); <ide> <ide> /** <ide> * Parse a expression String, return true if pass validate, false if failed for <ide> public static boolean parse(Object bean, int level, int selectedSize, String expression, Object... params) { <ide> if (StrUtils.isEmpty(expression)) <ide> return true; <del> return false; <del> } <del> private static class Item{ <del> private char type;//O:operator, V:value, I:items <del> private int operatorPriority; <add> return true; <add> } <add> <add> public static class Func { <add> public int priority; <add> public int operatorQTY; <add> <add> public Func(int priority, int operatorQTY) { <add> this.priority = priority; <add> this.operatorQTY = operatorQTY; <add> } <add> } <add> <add> public static class Item { <add> private int priority; <ide> private Object value; <del> private char valueType; //S:String, B:Boolean, L: Long, D:Double <add> private char type; // S:String, B:Boolean, L: Long, D:Double, P:parameter, I:items, <add> // U:Unknow_Function_Or_Variant <ide> private List<Item> subItem; <add> <add> public String getDebugInfo() { <add> String result = "\rItemValue="; <add> if (value != null) <add> result += value; <add> if (subItem != null) { <add> for (Item Item : subItem) { <add> result += " " + Item.getDebugInfo(); <add> } <add> } <add> return result; <add> } <add> } <add> <add> public static class keywordResult { <add> } <add> <add> public static class SearchResult { <add> private Item item; <add> private int leftStart; <add> private int leftEnd; <add> <add> private SearchResult(Item item, int leftStart, int leftEnd) { <add> this.item = item; <add> this.leftStart = leftStart; <add> this.leftEnd = leftEnd; <add> } <add> } <add> <add> private static boolean isLetterNumber(char c) { <add> return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || c == '_' || c == '.'; <add> } <add> <add> public static SearchResult findFirstResult(char[] chars, int start, int end) { <add> if (start > end) <add> return null; <add> boolean letters = false; <add> StringBuilder sb = new StringBuilder(); <add> for (int i = start; i <= end; i++) { <add> if (!letters) {// no letters found <add> if (chars[i] == '?') { <add> Item item = new Item(); <add> item.type = 'V'; <add> item.value = "?"; <add> return new SearchResult(item, i + 1, end); <add> } else if (chars[i] == '\'') { <add> for (int j = i + 1; j <= end; j++) { <add> if (chars[j] == '\'' && chars[j - 1] != '\\') { <add> Item item = new Item(); <add> item.type = 'S'; <add> item.value = sb.toString(); <add> return new SearchResult(item, j + 1, end); <add> } else <add> sb.append(chars[j]); <add> } <add> throw new TinyNetException("Miss right ' charactor in expression."); <add> } else if (chars[i] == '(') { <add> int count = 1; <add> boolean inString = false; <add> for (int j = i + 1; j <= end; j++) { <add> if (!inString) { <add> if (chars[j] == '(') <add> count++; <add> else if (chars[j] == ')') { <add> count--; <add> if (count == 0) { <add> List<Item> subItems = seperateCharsToItems(chars, i + 1, j - 1); <add> Item item = new Item(); <add> item.type = 'I'; <add> item.subItem = subItems; <add> return new SearchResult(item, j + 1, end); <add> } <add> } else if (chars[j] == '\'') { <add> inString = true; <add> } <add> } else { <add> if (chars[j] == '\'' && chars[j - 1] != '\\') { <add> inString = false; <add> } <add> } <add> } <add> throw new TinyNetException("Miss right ) charactor in expression."); <add> } else if (chars[i] > ' ') { <add> letters = true; <add> sb.append(chars[i]); <add> } <add> } else {// letters found <add> if (chars[i] == '?' || chars[i] == '\'' || chars[i] == '(' || chars[i] <= ' ' <add> || isLetterNumber(chars[i]) != isLetterNumber(chars[i - 1])) { <add> Item item = new Item(); <add> item.type = 'U'; <add> item.value = sb.toString(); <add> return new SearchResult(item, i, end); <add> } else { <add> sb.append(chars[i]); <add> } <add> } <add> } <add> if (sb.length() > 0) { <add> Item item = new Item(); <add> item.type = 'U'; <add> item.value = sb.toString(); <add> return new SearchResult(item, end + 1, end); <add> } else <add> return null; <add> } <add> <add> public static List<Item> seperateCharsToItems(char[] chars, int start, int end) { <add> List<Item> items = new ArrayList<Item>(); <add> SearchResult result = findFirstResult(chars, start, end); <add> while (result != null) { <add> items.add(result.item); <add> result = findFirstResult(chars, result.leftStart, result.leftEnd); <add> } <add> return items; <add> } <add> <add> public static Object doParse(String expression) { <add> char[] chars = (" " + expression + " ").toCharArray(); <add> List<Item> items = seperateCharsToItems(chars, 1, chars.length - 2); <add> for (Item item : items) { <add> System.out.print(item.getDebugInfo()); <add> } <add> return null; <add> } <add> <add> public static void main(String[] args) { <add> String s = "35*(24 -6*)+7/(4-6)"; <add> doParse(s); <ide> } <ide> <ide> }
Java
apache-2.0
a7328a6f657796602ef2a6d35ddd9d9ad9e2da6f
0
google/closure-compiler,monetate/closure-compiler,monetate/closure-compiler,google/closure-compiler,nawawi/closure-compiler,ChadKillingsworth/closure-compiler,nawawi/closure-compiler,google/closure-compiler,google/closure-compiler,nawawi/closure-compiler,nawawi/closure-compiler,monetate/closure-compiler,ChadKillingsworth/closure-compiler,monetate/closure-compiler,ChadKillingsworth/closure-compiler,ChadKillingsworth/closure-compiler
/* * Copyright 2020 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp.serialization; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static java.util.Arrays.stream; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.javascript.jscomp.colors.Color; import com.google.javascript.jscomp.colors.ColorRegistry; import com.google.javascript.jscomp.colors.DebugInfo; import com.google.javascript.jscomp.colors.NativeColorId; import com.google.javascript.jscomp.colors.SingletonColorFields; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; import java.util.function.Function; /** * Convert a {@link TypePool} (from a single compilation) into {@link Color}s. * * <p>Future work will be necessary to let this class convert multiple type-pools coming from * different libraries. For now it only handles a single type-pool. */ public final class ColorDeserializer { private final ImmutableList<Color> colorPool; private final ColorRegistry colorRegistry; /** Error emitted when the deserializer sees a serialized type it cannot support deserialize */ public static final class InvalidSerializedFormatException extends RuntimeException { public InvalidSerializedFormatException(String msg) { super("Invalid serialized TypeProto format: " + msg); } } private ColorDeserializer(ImmutableList<Color> colorPool, ColorRegistry colorRegistry) { this.colorPool = colorPool; this.colorRegistry = colorRegistry; } public ColorRegistry getRegistry() { return this.colorRegistry; } /** * Builds a pool of Colors and a {@link ColorRegistry} from the given pool of types. * * <p>This method does all of the deserialization work in advance so that {@link #getRegistry()} * and {@link #pointerToColor(TypePointer)} willexecute in constant time. */ public static ColorDeserializer buildFromTypePool(TypePool typePool) { ImmutableMultimap.Builder<Integer, TypePointer> disambiguationEdges = ImmutableMultimap.builder(); for (SubtypingEdge edge : typePool.getDisambiguationEdgesList()) { TypePointer subtype = edge.getSubtype(); TypePointer supertype = edge.getSupertype(); if (subtype.getValueCase() != TypePointer.ValueCase.POOL_OFFSET || supertype.getValueCase() != TypePointer.ValueCase.POOL_OFFSET) { throw new InvalidSerializedFormatException( "Subtyping only supported for pool offsets, found " + subtype + " , " + supertype); } disambiguationEdges.put(subtype.getPoolOffset(), supertype); } ColorRegistry colorRegistry = ColorRegistry.createWithInvalidatingNatives( typePool.getInvalidatingNativeList().stream() .map(ColorDeserializer::nativeTypeToColor) .collect(toImmutableSet())); ImmutableMap<NativeType, Color> nativeColors = stream(NativeType.values()) // The UNRECOGNIZED type is added by the Java proto format. Since TypedAST protos aren't // passed between processes we don't expect to see it in the deserializer. .filter(nativeType -> !NativeType.UNRECOGNIZED.equals(nativeType)) .collect( toImmutableMap( Function.identity(), (nativeType) -> colorRegistry.get(nativeTypeToColor(nativeType)))); ImmutableList<Color> colorPool = new ColorPoolBuilder(typePool, disambiguationEdges.build(), nativeColors).build(); return new ColorDeserializer(colorPool, colorRegistry); } /** * Contains necessary logic and mutable state to create a pool of {@link Color}s from a {@link * TypePool}. */ private static final class ColorPoolBuilder { private final ArrayList<Color> colorPool; // filled in as we go. initially all null // to avoid infinite recursion on types in cycles private final Set<TypeProto> currentlyDeserializing = new LinkedHashSet<>(); // keys are indices into the type pool and values are pointers to its supertypes private final ImmutableMultimap<Integer, TypePointer> disambiguationEdges; private final TypePool typePool; private final ImmutableMap<NativeType, Color> nativeToColor; private ColorPoolBuilder( TypePool typePool, ImmutableMultimap<Integer, TypePointer> disambiguationEdges, ImmutableMap<NativeType, Color> nativeToColor) { this.typePool = typePool; this.colorPool = new ArrayList<>(); this.disambiguationEdges = disambiguationEdges; colorPool.addAll(Collections.nCopies(typePool.getTypeCount(), null)); this.nativeToColor = nativeToColor; } private ImmutableList<Color> build() { for (int i = 0; i < this.typePool.getTypeCount(); i++) { if (this.colorPool.get(i) == null) { this.deserializeTypeByOffset(i); } } return ImmutableList.copyOf(this.colorPool); } /** * Given an index into the type pool, creating its corresponding color if not already * deserialized. */ private void deserializeTypeByOffset(int i) { Color color = deserializeType(i, typePool.getTypeList().get(i)); colorPool.set(i, color); } /** * Safely deserializes a type after verifying it's not going to cause infinite recursion * * <p>Currently this always initializes a new {@link Color} and we assume there are no duplicate * types in the serialized type pool. */ private Color deserializeType(int i, TypeProto serialized) { if (currentlyDeserializing.contains(serialized)) { throw new InvalidSerializedFormatException( "Cannot deserialize type in cycle " + serialized); } currentlyDeserializing.add(serialized); Color newColor = deserializeTypeAssumingSafe(i, serialized); currentlyDeserializing.remove(serialized); return newColor; } /** Creates a color from a TypeProto without checking for any type cycles */ private Color deserializeTypeAssumingSafe(int offset, TypeProto serialized) { switch (serialized.getKindCase()) { case OBJECT: return createObjectColor(offset, serialized.getObject()); case UNION: return createUnionColor(serialized.getUnion()); case KIND_NOT_SET: throw new InvalidSerializedFormatException( "Expected all Types to have a Kind, found " + serialized); } throw new AssertionError(); } private Color createObjectColor(int offset, ObjectTypeProto serialized) { ImmutableList<Color> directSupertypes = this.disambiguationEdges.get(offset).stream() .map(this::pointerToColor) .collect(toImmutableList()); ObjectTypeProto.DebugInfo serializedDebugInfo = serialized.getDebugInfo(); SingletonColorFields.Builder builder = SingletonColorFields.builder() .setId(serialized.getUuid()) .setInvalidating(serialized.getIsInvalidating()) .setPropertiesKeepOriginalName(serialized.getPropertiesKeepOriginalName()) .setDisambiguationSupertypes(directSupertypes) .setDebugInfo( DebugInfo.builder() .setFilename(serializedDebugInfo.getFilename()) .setClassName(serializedDebugInfo.getClassName()) .build()); if (serialized.hasPrototype()) { builder.setPrototype(this.pointerToColor(serialized.getPrototype())); } if (serialized.hasInstanceType()) { builder.setInstanceColor(this.pointerToColor(serialized.getInstanceType())); } builder.setConstructor(serialized.getMarkedConstructor()); return Color.createSingleton(builder.build()); } private Color createUnionColor(UnionTypeProto serialized) { if (serialized.getUnionMemberCount() <= 1) { throw new InvalidSerializedFormatException( "Unions must have >= 2 elements, found " + serialized); } ImmutableSet<Color> allAlternates = serialized.getUnionMemberList().stream() .map(this::pointerToColor) .collect(toImmutableSet()); if (allAlternates.size() == 1) { return Iterables.getOnlyElement(allAlternates); } else { return Color.createUnion(allAlternates); } } private Color pointerToColor(TypePointer typePointer) { switch (typePointer.getValueCase()) { case NATIVE_TYPE: return this.nativeToColor.get(typePointer.getNativeType()); case POOL_OFFSET: int poolOffset = typePointer.getPoolOffset(); if (poolOffset < 0 || poolOffset >= this.colorPool.size()) { throw new InvalidSerializedFormatException( "TypeProto pointer has out-of-bounds pool offset: " + typePointer + " for pool size " + this.colorPool.size()); } if (this.colorPool.get(typePointer.getPoolOffset()) == null) { this.deserializeTypeByOffset(poolOffset); } return this.colorPool.get(poolOffset); case VALUE_NOT_SET: throw new InvalidSerializedFormatException( "Cannot dereference TypePointer " + typePointer); } throw new AssertionError(); } } private static NativeColorId nativeTypeToColor(NativeType nativeType) { switch (nativeType) { case TOP_OBJECT: return NativeColorId.TOP_OBJECT; case UNKNOWN_TYPE: return NativeColorId.UNKNOWN; // Primitives case BIGINT_TYPE: return NativeColorId.BIGINT; case BOOLEAN_TYPE: return NativeColorId.BOOLEAN; case NULL_OR_VOID_TYPE: return NativeColorId.NULL_OR_VOID; case NUMBER_TYPE: return NativeColorId.NUMBER; case STRING_TYPE: return NativeColorId.STRING; case SYMBOL_TYPE: return NativeColorId.SYMBOL; // Boxed primitives case BIGINT_OBJECT_TYPE: return NativeColorId.BIGINT_OBJECT; case BOOLEAN_OBJECT_TYPE: return NativeColorId.BOOLEAN_OBJECT; case NUMBER_OBJECT_TYPE: return NativeColorId.NUMBER_OBJECT; case STRING_OBJECT_TYPE: return NativeColorId.STRING_OBJECT; case SYMBOL_OBJECT_TYPE: return NativeColorId.SYMBOL_OBJECT; case UNRECOGNIZED: throw new InvalidSerializedFormatException("Unrecognized NativeType " + nativeType); } throw new AssertionError(); } public Color pointerToColor(TypePointer typePointer) { switch (typePointer.getValueCase()) { case NATIVE_TYPE: NativeColorId nativeColorId = nativeTypeToColor(typePointer.getNativeType()); return this.colorRegistry.get(nativeColorId); case POOL_OFFSET: int poolOffset = typePointer.getPoolOffset(); if (poolOffset < 0 || poolOffset >= this.colorPool.size()) { throw new InvalidSerializedFormatException( "TypeProto pointer has out-of-bounds pool offset: " + typePointer + " for pool size " + this.colorPool.size()); } return checkNotNull(this.colorPool.get(poolOffset)); case VALUE_NOT_SET: throw new InvalidSerializedFormatException("Cannot dereference TypePointer " + typePointer); } throw new AssertionError(); } }
src/com/google/javascript/jscomp/serialization/ColorDeserializer.java
/* * Copyright 2020 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp.serialization; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static java.util.Arrays.stream; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.javascript.jscomp.colors.Color; import com.google.javascript.jscomp.colors.ColorRegistry; import com.google.javascript.jscomp.colors.DebugInfo; import com.google.javascript.jscomp.colors.NativeColorId; import com.google.javascript.jscomp.colors.SingletonColorFields; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; import java.util.function.Function; /** * Convert a {@link TypePool} (from a single compilation) into {@link Color}s. * * <p>Future work will be necessary to let this class convert multiple type-pools coming from * different libraries. For now it only handles a single type-pool. */ public final class ColorDeserializer { private final ImmutableList<Color> colorPool; private final ColorRegistry colorRegistry; /** Error emitted when the deserializer sees a serialized type it cannot support deserialize */ public static final class InvalidSerializedFormatException extends RuntimeException { public InvalidSerializedFormatException(String msg) { super("Invalid serialized TypeProto format: " + msg); } } private ColorDeserializer(ImmutableList<Color> colorPool, ColorRegistry colorRegistry) { this.colorPool = colorPool; this.colorRegistry = colorRegistry; } public ColorRegistry getRegistry() { return this.colorRegistry; } /** * Builds a pool of Colors and a {@link ColorRegistry} from the given pool of types. * * <p>This method does all of the deserialization work in advance so that {@link #getRegistry()} * and {@link #pointerToColor(TypePointer)} willexecute in constant time. */ public static ColorDeserializer buildFromTypePool(TypePool typePool) { ImmutableMultimap.Builder<Integer, TypePointer> disambiguationEdges = ImmutableMultimap.builder(); for (SubtypingEdge edge : typePool.getDisambiguationEdgesList()) { TypePointer subtype = edge.getSubtype(); TypePointer supertype = edge.getSupertype(); if (subtype.getValueCase() != TypePointer.ValueCase.POOL_OFFSET || supertype.getValueCase() != TypePointer.ValueCase.POOL_OFFSET) { throw new InvalidSerializedFormatException( "Subtyping only supported for pool offsets, found " + subtype + " , " + supertype); } disambiguationEdges.put(subtype.getPoolOffset(), supertype); } ColorRegistry colorRegistry = ColorRegistry.createWithInvalidatingNatives( typePool.getInvalidatingNativeList().stream() .map(ColorDeserializer::nativeTypeToColor) .collect(toImmutableSet())); ImmutableMap<NativeType, Color> nativeColors = stream(NativeType.values()) .filter((nativeType) -> nativeTypeToColor(nativeType) != null) .collect( toImmutableMap( Function.identity(), (nativeType) -> colorRegistry.get(nativeTypeToColor(nativeType)))); ImmutableList<Color> colorPool = new ColorPoolBuilder(typePool, disambiguationEdges.build(), nativeColors).build(); return new ColorDeserializer(colorPool, colorRegistry); } /** * Contains necessary logic and mutable state to create a pool of {@link Color}s from a {@link * TypePool}. */ private static final class ColorPoolBuilder { private final ArrayList<Color> colorPool; // filled in as we go. initially all null // to avoid infinite recursion on types in cycles private final Set<TypeProto> currentlyDeserializing = new LinkedHashSet<>(); // keys are indices into the type pool and values are pointers to its supertypes private final ImmutableMultimap<Integer, TypePointer> disambiguationEdges; private final TypePool typePool; private final ImmutableMap<NativeType, Color> nativeToColor; private ColorPoolBuilder( TypePool typePool, ImmutableMultimap<Integer, TypePointer> disambiguationEdges, ImmutableMap<NativeType, Color> nativeToColor) { this.typePool = typePool; this.colorPool = new ArrayList<>(); this.disambiguationEdges = disambiguationEdges; colorPool.addAll(Collections.nCopies(typePool.getTypeCount(), null)); this.nativeToColor = nativeToColor; } private ImmutableList<Color> build() { for (int i = 0; i < this.typePool.getTypeCount(); i++) { if (this.colorPool.get(i) == null) { this.deserializeTypeByOffset(i); } } return ImmutableList.copyOf(this.colorPool); } /** * Given an index into the type pool, creating its corresponding color if not already * deserialized. */ private void deserializeTypeByOffset(int i) { Color color = deserializeType(i, typePool.getTypeList().get(i)); colorPool.set(i, color); } /** * Safely deserializes a type after verifying it's not going to cause infinite recursion * * <p>Currently this always initializes a new {@link Color} and we assume there are no duplicate * types in the serialized type pool. */ private Color deserializeType(int i, TypeProto serialized) { if (currentlyDeserializing.contains(serialized)) { throw new InvalidSerializedFormatException( "Cannot deserialize type in cycle " + serialized); } currentlyDeserializing.add(serialized); Color newColor = deserializeTypeAssumingSafe(i, serialized); currentlyDeserializing.remove(serialized); return newColor; } /** Creates a color from a TypeProto without checking for any type cycles */ private Color deserializeTypeAssumingSafe(int offset, TypeProto serialized) { switch (serialized.getKindCase()) { case OBJECT: return createObjectColor(offset, serialized.getObject()); case UNION: return createUnionColor(serialized.getUnion()); case KIND_NOT_SET: throw new InvalidSerializedFormatException( "Expected all Types to have a Kind, found " + serialized); } throw new AssertionError(); } private Color createObjectColor(int offset, ObjectTypeProto serialized) { ImmutableList<Color> directSupertypes = this.disambiguationEdges.get(offset).stream() .map(this::pointerToColor) .collect(toImmutableList()); ObjectTypeProto.DebugInfo serializedDebugInfo = serialized.getDebugInfo(); SingletonColorFields.Builder builder = SingletonColorFields.builder() .setId(serialized.getUuid()) .setInvalidating(serialized.getIsInvalidating()) .setPropertiesKeepOriginalName(serialized.getPropertiesKeepOriginalName()) .setDisambiguationSupertypes(directSupertypes) .setDebugInfo( DebugInfo.builder() .setFilename(serializedDebugInfo.getFilename()) .setClassName(serializedDebugInfo.getClassName()) .build()); if (serialized.hasPrototype()) { builder.setPrototype(this.pointerToColor(serialized.getPrototype())); } if (serialized.hasInstanceType()) { builder.setInstanceColor(this.pointerToColor(serialized.getInstanceType())); } builder.setConstructor(serialized.getMarkedConstructor()); return Color.createSingleton(builder.build()); } private Color createUnionColor(UnionTypeProto serialized) { if (serialized.getUnionMemberCount() <= 1) { throw new InvalidSerializedFormatException( "Unions must have >= 2 elements, found " + serialized); } ImmutableSet<Color> allAlternates = serialized.getUnionMemberList().stream() .map(this::pointerToColor) .collect(toImmutableSet()); if (allAlternates.size() == 1) { return Iterables.getOnlyElement(allAlternates); } else { return Color.createUnion(allAlternates); } } private Color pointerToColor(TypePointer typePointer) { switch (typePointer.getValueCase()) { case NATIVE_TYPE: return this.nativeToColor.get(typePointer.getNativeType()); case POOL_OFFSET: int poolOffset = typePointer.getPoolOffset(); if (poolOffset < 0 || poolOffset >= this.colorPool.size()) { throw new InvalidSerializedFormatException( "TypeProto pointer has out-of-bounds pool offset: " + typePointer + " for pool size " + this.colorPool.size()); } if (this.colorPool.get(typePointer.getPoolOffset()) == null) { this.deserializeTypeByOffset(poolOffset); } return this.colorPool.get(poolOffset); case VALUE_NOT_SET: throw new InvalidSerializedFormatException( "Cannot dereference TypePointer " + typePointer); } throw new AssertionError(); } } @SuppressWarnings("UnnecessaryDefaultInEnumSwitch") // needed for J2CL protos private static NativeColorId nativeTypeToColor(NativeType nativeType) { switch (nativeType) { case TOP_OBJECT: return NativeColorId.TOP_OBJECT; case UNKNOWN_TYPE: return NativeColorId.UNKNOWN; // Primitives case BIGINT_TYPE: return NativeColorId.BIGINT; case BOOLEAN_TYPE: return NativeColorId.BOOLEAN; case NULL_OR_VOID_TYPE: return NativeColorId.NULL_OR_VOID; case NUMBER_TYPE: return NativeColorId.NUMBER; case STRING_TYPE: return NativeColorId.STRING; case SYMBOL_TYPE: return NativeColorId.SYMBOL; // Boxed primitives case BIGINT_OBJECT_TYPE: return NativeColorId.BIGINT_OBJECT; case BOOLEAN_OBJECT_TYPE: return NativeColorId.BOOLEAN_OBJECT; case NUMBER_OBJECT_TYPE: return NativeColorId.NUMBER_OBJECT; case STRING_OBJECT_TYPE: return NativeColorId.STRING_OBJECT; case SYMBOL_OBJECT_TYPE: return NativeColorId.SYMBOL_OBJECT; default: // Switch cannot be exhaustive because Java protos add an additional "UNRECOGNIZED" field // while J2CL protos do not. return null; } } public Color pointerToColor(TypePointer typePointer) { switch (typePointer.getValueCase()) { case NATIVE_TYPE: NativeColorId nativeColorId = nativeTypeToColor(typePointer.getNativeType()); if (nativeColorId == null) { throw new InvalidSerializedFormatException( "Unrecognized NativeType " + typePointer.getNativeType()); } return this.colorRegistry.get(nativeColorId); case POOL_OFFSET: int poolOffset = typePointer.getPoolOffset(); if (poolOffset < 0 || poolOffset >= this.colorPool.size()) { throw new InvalidSerializedFormatException( "TypeProto pointer has out-of-bounds pool offset: " + typePointer + " for pool size " + this.colorPool.size()); } return checkNotNull(this.colorPool.get(poolOffset)); case VALUE_NOT_SET: throw new InvalidSerializedFormatException("Cannot dereference TypePointer " + typePointer); } throw new AssertionError(); } }
Clean up proto enum handling now that J2CL protos have an UNRECOGNIZED value PiperOrigin-RevId: 355005704
src/com/google/javascript/jscomp/serialization/ColorDeserializer.java
Clean up proto enum handling now that J2CL protos have an UNRECOGNIZED value
<ide><path>rc/com/google/javascript/jscomp/serialization/ColorDeserializer.java <ide> <ide> ImmutableMap<NativeType, Color> nativeColors = <ide> stream(NativeType.values()) <del> .filter((nativeType) -> nativeTypeToColor(nativeType) != null) <add> // The UNRECOGNIZED type is added by the Java proto format. Since TypedAST protos aren't <add> // passed between processes we don't expect to see it in the deserializer. <add> .filter(nativeType -> !NativeType.UNRECOGNIZED.equals(nativeType)) <ide> .collect( <ide> toImmutableMap( <ide> Function.identity(), <ide> } <ide> <ide> return ImmutableList.copyOf(this.colorPool); <del> } <add> } <ide> <ide> /** <ide> * Given an index into the type pool, creating its corresponding color if not already <ide> } <ide> } <ide> <del> @SuppressWarnings("UnnecessaryDefaultInEnumSwitch") // needed for J2CL protos <ide> private static NativeColorId nativeTypeToColor(NativeType nativeType) { <ide> switch (nativeType) { <ide> case TOP_OBJECT: <ide> return NativeColorId.STRING_OBJECT; <ide> case SYMBOL_OBJECT_TYPE: <ide> return NativeColorId.SYMBOL_OBJECT; <del> default: <del> // Switch cannot be exhaustive because Java protos add an additional "UNRECOGNIZED" field <del> // while J2CL protos do not. <del> return null; <del> } <add> <add> case UNRECOGNIZED: <add> throw new InvalidSerializedFormatException("Unrecognized NativeType " + nativeType); <add> } <add> throw new AssertionError(); <ide> } <ide> <ide> public Color pointerToColor(TypePointer typePointer) { <ide> switch (typePointer.getValueCase()) { <ide> case NATIVE_TYPE: <ide> NativeColorId nativeColorId = nativeTypeToColor(typePointer.getNativeType()); <del> if (nativeColorId == null) { <del> throw new InvalidSerializedFormatException( <del> "Unrecognized NativeType " + typePointer.getNativeType()); <del> } <ide> return this.colorRegistry.get(nativeColorId); <ide> case POOL_OFFSET: <ide> int poolOffset = typePointer.getPoolOffset();
Java
apache-2.0
c52601d5aeca852c6cd1d68827961a2de347ab00
0
opensingular/singular-core,opensingular/singular-core,opensingular/singular-core,opensingular/singular-core
/* * Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opensingular.form.wicket.mapper.attachment.list; import org.apache.commons.lang3.StringUtils; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.json.JSONObject; import org.apache.wicket.ajax.markup.html.form.AjaxButton; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.MarkupStream; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.JavaScriptHeaderItem; import org.apache.wicket.markup.head.OnDomReadyHeaderItem; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.markup.repeater.RefreshingView; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.request.http.flow.AbortWithHttpErrorCodeException; import org.apache.wicket.request.resource.PackageResourceReference; import org.opensingular.form.SIList; import org.opensingular.form.servlet.MimeTypes; import org.opensingular.form.type.basic.AtrBasic; import org.opensingular.form.type.core.attachment.IAttachmentPersistenceHandler; import org.opensingular.form.type.core.attachment.SIAttachment; import org.opensingular.form.wicket.WicketBuildContext; import org.opensingular.form.wicket.enums.ViewMode; import org.opensingular.form.wicket.mapper.attachment.BaseJQueryFileUploadBehavior; import org.opensingular.form.wicket.mapper.attachment.DownloadLink; import org.opensingular.form.wicket.mapper.attachment.DownloadSupportedBehavior; import org.opensingular.form.wicket.mapper.attachment.upload.AttachmentKey; import org.opensingular.form.wicket.mapper.attachment.upload.FileUploadManager; import org.opensingular.form.wicket.mapper.attachment.upload.FileUploadManagerFactory; import org.opensingular.form.wicket.mapper.attachment.upload.UploadResponseWriter; import org.opensingular.form.wicket.mapper.attachment.upload.info.UploadResponseInfo; import org.opensingular.form.wicket.mapper.attachment.upload.servlet.FileUploadServlet; import org.opensingular.form.wicket.mapper.behavior.RequiredListLabelClassAppender; import org.opensingular.form.wicket.model.SInstanceListItemModel; import org.opensingular.lib.commons.util.Loggable; import org.opensingular.lib.wicket.util.jquery.JQuery; import org.opensingular.lib.wicket.util.resource.DefaultIcons; import org.opensingular.lib.commons.ui.Icon; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.*; import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; import static org.opensingular.form.wicket.mapper.attachment.upload.servlet.FileUploadServlet.PARAM_NAME; import static org.opensingular.lib.wicket.util.util.Shortcuts.$b; import static org.opensingular.lib.wicket.util.util.WicketUtils.$m; /** * Lista os uploads múltiplos. * <p> * O upload múltiplo executado via jquery para a servlet {@link FileUploadServlet} atualiza * o código no cliente via javascript por meio do código java script associado a esse painel FileListUploadPanel.js * Para manter os models atualizados o js cliente se comunica com esse panel através do {@link org.opensingular.form.wicket.mapper.attachment.list.FileListUploadPanel.AddFileBehavior} * para remover os arquivos e atualizar os models o js cliente se comunica com esse panel através do {@link org.opensingular.form.wicket.mapper.attachment.list.FileListUploadPanel.RemoveFileBehavior} * * @author fabricio, vinicius */ public class FileListUploadPanel extends Panel implements Loggable { private final FileUploadManagerFactory upManagerFactory = new FileUploadManagerFactory(); private final UploadResponseWriter upResponseWriter = new UploadResponseWriter(); private final Component fileField; private final WebMarkupContainer fileList; private final AddFileBehavior adder; private final RemoveFileBehavior remover; private final DownloadSupportedBehavior downloader; private final WicketBuildContext ctx; private AttachmentKey uploadId; public FileListUploadPanel(String id, IModel<SIList<SIAttachment>> model, WicketBuildContext ctx) { super(id, model); this.ctx = ctx; adder = new AddFileBehavior(); remover = new RemoveFileBehavior(model); downloader = new DownloadSupportedBehavior(model); Label label = new Label("uploadLabel", $m.get(() -> ctx.getCurrentInstance().asAtr().getLabel())); label.add($b.visibleIfModelObject(StringUtils::isNotEmpty)); Label subtitle = new Label("uploadSubtitle", $m.get(() -> ctx.getCurrentInstance().asAtr().getSubtitle())); label.add($b.visibleIfModelObject(StringUtils::isNotEmpty)); ViewMode viewMode = ctx.getViewMode(); if (isEdition(viewMode)) { label.add(new RequiredListLabelClassAppender(model)); } add(label); add(subtitle); fileList = new WebMarkupContainer("fileList"); add(fileList.add(new FilesListView("fileItem", model, ctx))); fileField = new WebMarkupContainer("fileUpload"); add(new WebMarkupContainer("button-container") .add(fileField) .add(new LabelWithIcon("fileUploadLabel", Model.of(""), DefaultIcons.PLUS, Model.of(fileField.getMarkupId()))) .add($b.visibleIf(() -> isEdition(viewMode)))); add(ctx.createFeedbackCompactPanel("feedback")); add(new WebMarkupContainer("empty-box") .add(new WebMarkupContainer("select-file-link") .add(new Label("select-file-link-message", $m.ofValue("Selecione o(s) arquivo(s)"))) .add($b.visibleIf(() -> isEdition(viewMode))) .add($b.onReadyScript(c -> JQuery.on(c, "click", JQuery.$(fileField).append(".click();"))))) .add(new Label("empty-message", $m.ofValue("Nenhum arquivo adicionado")) .add($b.visibleIf(() -> !isEdition(viewMode)))) .add($b.visibleIf(() -> model.getObject().isEmpty()))); add(adder, remover, downloader); add($b.classAppender("FileListUploadPanel")); add($b.classAppender("FileListUploadPanel_disabled", $m.get(() -> !this.isEnabledInHierarchy()))); if (viewMode != null && viewMode.isVisualization() && model.getObject().isEmpty()) { add($b.classAppender("FileListUploadPanel_empty")); } } private boolean isEdition(ViewMode viewMode) { return viewMode != null && viewMode.isEdition(); } @Override protected void onConfigure() { super.onConfigure(); final FileUploadManager fileUploadManager = getFileUploadManager(); if (uploadId == null || !fileUploadManager.findUploadInfoByAttachmentKey(uploadId).isPresent()) { final AtrBasic atrAttachment = getModelObject().getElementsType().asAtr(); this.uploadId = fileUploadManager.createUpload(atrAttachment.getMaxFileSize(), null, atrAttachment.getAllowedFileTypes(), this::getTemporaryHandler); } } private IAttachmentPersistenceHandler getTemporaryHandler() { return ctx.getCurrentInstance().getDocument().getAttachmentPersistenceTemporaryHandler(); } private static void removeFileFrom(SIList<SIAttachment> list, String fileId) { SIAttachment file = findFileByID(list, fileId); if (file != null) list.remove(file); } private static SIAttachment findFileByID(SIList<SIAttachment> list, String fileId) { for (SIAttachment file : list) if (file.getFileId().equals(fileId)) return file; return null; } @Override public void renderHead(IHeaderResponse response) { super.renderHead(response); response.render(JavaScriptHeaderItem.forReference(resourceRef("FileListUploadPanel.js"))); response.render(OnDomReadyHeaderItem.forScript(generateInitJS())); } private String generateInitJS() { if (ctx.getViewMode().isEdition()) { return "" //@formatter:off + "\n $(function () { " + "\n window.FileListUploadPanel.setup(" + new JSONObject() .put("param_name", PARAM_NAME) .put("component_id", this.getMarkupId()) .put("file_field_id", fileField.getMarkupId()) .put("fileList_id", fileList.getMarkupId()) .put("upload_url", uploadUrl()) .put("download_url", downloader.getUrl()) .put("add_url", adder.getUrl()) .put("remove_url", remover.getUrl()) .put("max_file_size", getMaxFileSize()) .put("allowed_file_types", getAllowedTypes()) .put("allowed_file_extensions", getAllowedExtensions()) .toString(2) + "); " + "\n });"; //@formatter:on } else { return ""; } } private Set<String> getAllowedExtensions(){ return MimeTypes.getExtensionsFormMimeTypes(getAllowedTypes(), true); } protected List<String> getAllowedTypes() { return defaultIfNull( getModelObject().getElementsType().asAtr().getAllowedFileTypes(), Collections.<String>emptyList()); } private long getMaxFileSize() { return getModelObject().getElementsType().asAtr().getMaxFileSize(); } @SuppressWarnings("unchecked") public IModel<SIList<SIAttachment>> getModel() { return (IModel<SIList<SIAttachment>>) getDefaultModel(); } @SuppressWarnings("unchecked") public SIList<SIAttachment> getModelObject() { return (SIList<SIAttachment>) getDefaultModelObject(); } private PackageResourceReference resourceRef(String resourceName) { return new PackageResourceReference(getClass(), resourceName); } private String uploadUrl() { return FileUploadServlet.getUploadUrl(getServletRequest(), uploadId); } private HttpServletRequest getServletRequest() { return (HttpServletRequest) getWebRequest().getContainerRequest(); } private FileUploadManager getFileUploadManager() { return upManagerFactory.getFileUploadManagerFromSessionOrMakeAndAttach(getServletRequest().getSession()); } public static class LabelWithIcon extends Label { private final Icon icon; private final IModel<String> forAttrValue; public LabelWithIcon(String id, IModel<?> model, Icon icon, IModel<String> forAttrValue) { super(id, model); this.icon = icon; this.forAttrValue = forAttrValue; } @Override protected void onInitialize() { super.onInitialize(); if (forAttrValue != null) { add($b.attr("for", forAttrValue.getObject())); } } @Override public void onComponentTagBody(MarkupStream markupStream, ComponentTag openTag) { replaceComponentTagBody(markupStream, openTag, "<i class='" + icon.getCssClass() + "'></i>\n" + getDefaultModelObjectAsString()); } } private class AddFileBehavior extends BaseJQueryFileUploadBehavior<SIList<SIAttachment>> { public AddFileBehavior() { super(FileListUploadPanel.this.getModel()); } @Override public void onResourceRequested() { final HttpServletResponse httpResp = (HttpServletResponse) getWebResponse().getContainerResponse(); try { final String pFileId = getParamFileId("fileId").toString(); final String pName = getParamFileId("name").toString(); getLogger().debug("FileListUploadPanel.AddFileBehavior(fileId={},name={})", pFileId, pName); Optional<UploadResponseInfo> responseInfo = getFileUploadManager().consumeFile(pFileId, attachment -> { final SIAttachment si = currentInstance().addNew(); si.update(attachment); return new UploadResponseInfo(si); }); UploadResponseInfo uploadResponseInfo = responseInfo .orElseThrow(() -> new AbortWithHttpErrorCodeException(HttpServletResponse.SC_NOT_FOUND)); upResponseWriter.writeJsonObjectResponseTo(httpResp, uploadResponseInfo); } catch (Exception e) { getLogger().error(e.getMessage(), e); throw new AbortWithHttpErrorCodeException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } } private class RemoveFileBehavior extends BaseJQueryFileUploadBehavior<SIList<SIAttachment>> { public RemoveFileBehavior(IModel<SIList<SIAttachment>> listModel) { super(listModel); } @Override public void onResourceRequested() { try { String fileId = getParamFileId("fileId").toString(); removeFileFrom(currentInstance(), fileId); } catch (Exception e) { getLogger().error(e.getMessage(), e); throw new AbortWithHttpErrorCodeException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } } private class FilesListView extends RefreshingView<SIAttachment> { private final WicketBuildContext ctx; public FilesListView(String id, IModel<SIList<SIAttachment>> listModel, WicketBuildContext ctx) { super(id, listModel); this.ctx = ctx; } @SuppressWarnings("unchecked") public SIList<SIAttachment> getAttackmentList() { return (SIList<SIAttachment>) getDefaultModelObject(); } @SuppressWarnings("unchecked") public IModel<SIList<SIAttachment>> getAttackmentListModel() { return (IModel<SIList<SIAttachment>>) getDefaultModel(); } @Override protected Iterator<IModel<SIAttachment>> getItemModels() { final SIList<SIAttachment> objList = this.getAttackmentList(); final List<IModel<SIAttachment>> modelList = new ArrayList<>(); for (int i = 0; i < objList.size(); i++) modelList.add(new SInstanceListItemModel<>(this.getAttackmentListModel(), i)); return modelList.iterator(); } @Override protected void populateItem(Item<SIAttachment> item) { IModel<SIAttachment> itemModel = item.getModel(); item.add(new DownloadLink("downloadLink", itemModel, downloader)); item.add(new RemoveButton("remove_btn", itemModel)); } private class RemoveButton extends AjaxButton { private final IModel<SIAttachment> itemModel; public RemoveButton(String id, IModel<SIAttachment> itemModel) { super(id); this.itemModel = itemModel; } protected void onSubmit(AjaxRequestTarget target, Form<?> form) { super.onSubmit(target, form); SIAttachment file = itemModel.getObject(); removeFileFrom(FilesListView.this.getAttackmentList(), file.getFileId()); target.add(FileListUploadPanel.this); target.add(fileList); } @Override public boolean isVisible() { return ctx.getViewMode().isEdition(); } } } }
form/wicket/src/main/java/org/opensingular/form/wicket/mapper/attachment/list/FileListUploadPanel.java
/* * Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opensingular.form.wicket.mapper.attachment.list; import org.apache.commons.lang3.StringUtils; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.json.JSONObject; import org.apache.wicket.ajax.markup.html.form.AjaxButton; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.MarkupStream; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.JavaScriptHeaderItem; import org.apache.wicket.markup.head.OnDomReadyHeaderItem; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.markup.repeater.RefreshingView; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.request.http.flow.AbortWithHttpErrorCodeException; import org.apache.wicket.request.resource.PackageResourceReference; import org.opensingular.form.SIList; import org.opensingular.form.type.basic.AtrBasic; import org.opensingular.form.type.core.attachment.IAttachmentPersistenceHandler; import org.opensingular.form.type.core.attachment.SIAttachment; import org.opensingular.form.wicket.WicketBuildContext; import org.opensingular.form.wicket.enums.ViewMode; import org.opensingular.form.wicket.mapper.attachment.BaseJQueryFileUploadBehavior; import org.opensingular.form.wicket.mapper.attachment.DownloadLink; import org.opensingular.form.wicket.mapper.attachment.DownloadSupportedBehavior; import org.opensingular.form.wicket.mapper.attachment.upload.AttachmentKey; import org.opensingular.form.wicket.mapper.attachment.upload.FileUploadManager; import org.opensingular.form.wicket.mapper.attachment.upload.FileUploadManagerFactory; import org.opensingular.form.wicket.mapper.attachment.upload.UploadResponseWriter; import org.opensingular.form.wicket.mapper.attachment.upload.info.UploadResponseInfo; import org.opensingular.form.wicket.mapper.attachment.upload.servlet.FileUploadServlet; import org.opensingular.form.wicket.mapper.behavior.RequiredListLabelClassAppender; import org.opensingular.form.wicket.model.SInstanceListItemModel; import org.opensingular.lib.commons.util.Loggable; import org.opensingular.lib.wicket.util.jquery.JQuery; import org.opensingular.lib.wicket.util.resource.DefaultIcons; import org.opensingular.lib.commons.ui.Icon; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.*; import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; import static org.opensingular.form.wicket.mapper.attachment.upload.servlet.FileUploadServlet.PARAM_NAME; import static org.opensingular.lib.wicket.util.util.Shortcuts.$b; import static org.opensingular.lib.wicket.util.util.WicketUtils.$m; /** * Lista os uploads múltiplos. * <p> * O upload múltiplo executado via jquery para a servlet {@link FileUploadServlet} atualiza * o código no cliente via javascript por meio do código java script associado a esse painel FileListUploadPanel.js * Para manter os models atualizados o js cliente se comunica com esse panel através do {@link org.opensingular.form.wicket.mapper.attachment.list.FileListUploadPanel.AddFileBehavior} * para remover os arquivos e atualizar os models o js cliente se comunica com esse panel através do {@link org.opensingular.form.wicket.mapper.attachment.list.FileListUploadPanel.RemoveFileBehavior} * * @author fabricio, vinicius */ public class FileListUploadPanel extends Panel implements Loggable { private final FileUploadManagerFactory upManagerFactory = new FileUploadManagerFactory(); private final UploadResponseWriter upResponseWriter = new UploadResponseWriter(); private final Component fileField; private final WebMarkupContainer fileList; private final AddFileBehavior adder; private final RemoveFileBehavior remover; private final DownloadSupportedBehavior downloader; private final WicketBuildContext ctx; private AttachmentKey uploadId; public FileListUploadPanel(String id, IModel<SIList<SIAttachment>> model, WicketBuildContext ctx) { super(id, model); this.ctx = ctx; adder = new AddFileBehavior(); remover = new RemoveFileBehavior(model); downloader = new DownloadSupportedBehavior(model); Label label = new Label("uploadLabel", $m.get(() -> ctx.getCurrentInstance().asAtr().getLabel())); label.add($b.visibleIfModelObject(StringUtils::isNotEmpty)); Label subtitle = new Label("uploadSubtitle", $m.get(() -> ctx.getCurrentInstance().asAtr().getSubtitle())); label.add($b.visibleIfModelObject(StringUtils::isNotEmpty)); ViewMode viewMode = ctx.getViewMode(); if (isEdition(viewMode)) { label.add(new RequiredListLabelClassAppender(model)); } add(label); add(subtitle); fileList = new WebMarkupContainer("fileList"); add(fileList.add(new FilesListView("fileItem", model, ctx))); fileField = new WebMarkupContainer("fileUpload"); add(new WebMarkupContainer("button-container") .add(fileField) .add(new LabelWithIcon("fileUploadLabel", Model.of(""), DefaultIcons.PLUS, Model.of(fileField.getMarkupId()))) .add($b.visibleIf(() -> isEdition(viewMode)))); add(ctx.createFeedbackCompactPanel("feedback")); add(new WebMarkupContainer("empty-box") .add(new WebMarkupContainer("select-file-link") .add(new Label("select-file-link-message", $m.ofValue("Selecione o(s) arquivo(s)"))) .add($b.visibleIf(() -> isEdition(viewMode))) .add($b.onReadyScript(c -> JQuery.on(c, "click", JQuery.$(fileField).append(".click();"))))) .add(new Label("empty-message", $m.ofValue("Nenhum arquivo adicionado")) .add($b.visibleIf(() -> !isEdition(viewMode)))) .add($b.visibleIf(() -> model.getObject().isEmpty()))); add(adder, remover, downloader); add($b.classAppender("FileListUploadPanel")); add($b.classAppender("FileListUploadPanel_disabled", $m.get(() -> !this.isEnabledInHierarchy()))); if (viewMode != null && viewMode.isVisualization() && model.getObject().isEmpty()) { add($b.classAppender("FileListUploadPanel_empty")); } } private boolean isEdition(ViewMode viewMode) { return viewMode != null && viewMode.isEdition(); } @Override protected void onConfigure() { super.onConfigure(); final FileUploadManager fileUploadManager = getFileUploadManager(); if (uploadId == null || !fileUploadManager.findUploadInfoByAttachmentKey(uploadId).isPresent()) { final AtrBasic atrAttachment = getModelObject().getElementsType().asAtr(); this.uploadId = fileUploadManager.createUpload(atrAttachment.getMaxFileSize(), null, atrAttachment.getAllowedFileTypes(), this::getTemporaryHandler); } } private IAttachmentPersistenceHandler getTemporaryHandler() { return ctx.getCurrentInstance().getDocument().getAttachmentPersistenceTemporaryHandler(); } private static void removeFileFrom(SIList<SIAttachment> list, String fileId) { SIAttachment file = findFileByID(list, fileId); if (file != null) list.remove(file); } private static SIAttachment findFileByID(SIList<SIAttachment> list, String fileId) { for (SIAttachment file : list) if (file.getFileId().equals(fileId)) return file; return null; } @Override public void renderHead(IHeaderResponse response) { super.renderHead(response); response.render(JavaScriptHeaderItem.forReference(resourceRef("FileListUploadPanel.js"))); response.render(OnDomReadyHeaderItem.forScript(generateInitJS())); } private String generateInitJS() { if (ctx.getViewMode().isEdition()) { return "" //@formatter:off + "\n $(function () { " + "\n window.FileListUploadPanel.setup(" + new JSONObject() .put("param_name", PARAM_NAME) .put("component_id", this.getMarkupId()) .put("file_field_id", fileField.getMarkupId()) .put("fileList_id", fileList.getMarkupId()) .put("upload_url", uploadUrl()) .put("download_url", downloader.getUrl()) .put("add_url", adder.getUrl()) .put("remove_url", remover.getUrl()) .put("max_file_size", getMaxFileSize()) .put("allowed_file_types", getAllowedTypes()) .toString(2) + "); " + "\n });"; //@formatter:on } else { return ""; } } protected List<String> getAllowedTypes() { return defaultIfNull( getModelObject().getElementsType().asAtr().getAllowedFileTypes(), Collections.<String>emptyList()); } private long getMaxFileSize() { return getModelObject().getElementsType().asAtr().getMaxFileSize(); } @SuppressWarnings("unchecked") public IModel<SIList<SIAttachment>> getModel() { return (IModel<SIList<SIAttachment>>) getDefaultModel(); } @SuppressWarnings("unchecked") public SIList<SIAttachment> getModelObject() { return (SIList<SIAttachment>) getDefaultModelObject(); } private PackageResourceReference resourceRef(String resourceName) { return new PackageResourceReference(getClass(), resourceName); } private String uploadUrl() { return FileUploadServlet.getUploadUrl(getServletRequest(), uploadId); } private HttpServletRequest getServletRequest() { return (HttpServletRequest) getWebRequest().getContainerRequest(); } private FileUploadManager getFileUploadManager() { return upManagerFactory.getFileUploadManagerFromSessionOrMakeAndAttach(getServletRequest().getSession()); } public static class LabelWithIcon extends Label { private final Icon icon; private final IModel<String> forAttrValue; public LabelWithIcon(String id, IModel<?> model, Icon icon, IModel<String> forAttrValue) { super(id, model); this.icon = icon; this.forAttrValue = forAttrValue; } @Override protected void onInitialize() { super.onInitialize(); if (forAttrValue != null) { add($b.attr("for", forAttrValue.getObject())); } } @Override public void onComponentTagBody(MarkupStream markupStream, ComponentTag openTag) { replaceComponentTagBody(markupStream, openTag, "<i class='" + icon.getCssClass() + "'></i>\n" + getDefaultModelObjectAsString()); } } private class AddFileBehavior extends BaseJQueryFileUploadBehavior<SIList<SIAttachment>> { public AddFileBehavior() { super(FileListUploadPanel.this.getModel()); } @Override public void onResourceRequested() { final HttpServletResponse httpResp = (HttpServletResponse) getWebResponse().getContainerResponse(); try { final String pFileId = getParamFileId("fileId").toString(); final String pName = getParamFileId("name").toString(); getLogger().debug("FileListUploadPanel.AddFileBehavior(fileId={},name={})", pFileId, pName); Optional<UploadResponseInfo> responseInfo = getFileUploadManager().consumeFile(pFileId, attachment -> { final SIAttachment si = currentInstance().addNew(); si.update(attachment); return new UploadResponseInfo(si); }); UploadResponseInfo uploadResponseInfo = responseInfo .orElseThrow(() -> new AbortWithHttpErrorCodeException(HttpServletResponse.SC_NOT_FOUND)); upResponseWriter.writeJsonObjectResponseTo(httpResp, uploadResponseInfo); } catch (Exception e) { getLogger().error(e.getMessage(), e); throw new AbortWithHttpErrorCodeException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } } private class RemoveFileBehavior extends BaseJQueryFileUploadBehavior<SIList<SIAttachment>> { public RemoveFileBehavior(IModel<SIList<SIAttachment>> listModel) { super(listModel); } @Override public void onResourceRequested() { try { String fileId = getParamFileId("fileId").toString(); removeFileFrom(currentInstance(), fileId); } catch (Exception e) { getLogger().error(e.getMessage(), e); throw new AbortWithHttpErrorCodeException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } } private class FilesListView extends RefreshingView<SIAttachment> { private final WicketBuildContext ctx; public FilesListView(String id, IModel<SIList<SIAttachment>> listModel, WicketBuildContext ctx) { super(id, listModel); this.ctx = ctx; } @SuppressWarnings("unchecked") public SIList<SIAttachment> getAttackmentList() { return (SIList<SIAttachment>) getDefaultModelObject(); } @SuppressWarnings("unchecked") public IModel<SIList<SIAttachment>> getAttackmentListModel() { return (IModel<SIList<SIAttachment>>) getDefaultModel(); } @Override protected Iterator<IModel<SIAttachment>> getItemModels() { final SIList<SIAttachment> objList = this.getAttackmentList(); final List<IModel<SIAttachment>> modelList = new ArrayList<>(); for (int i = 0; i < objList.size(); i++) modelList.add(new SInstanceListItemModel<>(this.getAttackmentListModel(), i)); return modelList.iterator(); } @Override protected void populateItem(Item<SIAttachment> item) { IModel<SIAttachment> itemModel = item.getModel(); item.add(new DownloadLink("downloadLink", itemModel, downloader)); item.add(new RemoveButton("remove_btn", itemModel)); } private class RemoveButton extends AjaxButton { private final IModel<SIAttachment> itemModel; public RemoveButton(String id, IModel<SIAttachment> itemModel) { super(id); this.itemModel = itemModel; } protected void onSubmit(AjaxRequestTarget target, Form<?> form) { super.onSubmit(target, form); SIAttachment file = itemModel.getObject(); removeFileFrom(FilesListView.this.getAttackmentList(), file.getFileId()); target.add(FileListUploadPanel.this); target.add(fileList); } @Override public boolean isVisible() { return ctx.getViewMode().isEdition(); } } } }
corrigindo validação de tipos
form/wicket/src/main/java/org/opensingular/form/wicket/mapper/attachment/list/FileListUploadPanel.java
corrigindo validação de tipos
<ide><path>orm/wicket/src/main/java/org/opensingular/form/wicket/mapper/attachment/list/FileListUploadPanel.java <ide> import org.apache.wicket.request.http.flow.AbortWithHttpErrorCodeException; <ide> import org.apache.wicket.request.resource.PackageResourceReference; <ide> import org.opensingular.form.SIList; <add>import org.opensingular.form.servlet.MimeTypes; <ide> import org.opensingular.form.type.basic.AtrBasic; <ide> import org.opensingular.form.type.core.attachment.IAttachmentPersistenceHandler; <ide> import org.opensingular.form.type.core.attachment.SIAttachment; <ide> .put("remove_url", remover.getUrl()) <ide> .put("max_file_size", getMaxFileSize()) <ide> .put("allowed_file_types", getAllowedTypes()) <del> .toString(2) + "); " <add> .put("allowed_file_extensions", getAllowedExtensions()) <add> .toString(2) + "); " <ide> + "\n });"; <ide> //@formatter:on <ide> } else { <ide> return ""; <ide> } <ide> } <add> <add> private Set<String> getAllowedExtensions(){ <add> return MimeTypes.getExtensionsFormMimeTypes(getAllowedTypes(), true); <add> } <add> <ide> <ide> protected List<String> getAllowedTypes() { <ide> return defaultIfNull(
Java
bsd-3-clause
abaaf83477f4890be6fcfa62500182d7d44be43a
0
Team997Coders/2017SteamBot2,Team997Coders/2017SteamBot2
package org.usfirst.frc.team997.robot; import org.usfirst.frc.team997.robot.commands.DriveToAngle; import org.usfirst.frc.team997.robot.commands.DriveToggle; import org.usfirst.frc.team997.robot.commands.Shoot; import org.usfirst.frc.team997.robot.commands.ShootSpinner; import org.usfirst.frc.team997.robot.subsystems.Climber; import org.usfirst.frc.team997.robot.subsystems.DriveTrain; import org.usfirst.frc.team997.robot.subsystems.Elevator; import org.usfirst.frc.team997.robot.subsystems.Shooter; import org.usfirst.frc.team997.robot.RobotMap.PDP; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj.PowerDistributionPanel; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { public static OI oi; public static DriveTrain driveTrain; public static Shooter shooter; public static DriveToAngle driveToAngleCommand; public static Climber climber; public static PowerDistributionPanel pdp; public static Elevator elevator; final String defaultAuto = "Default"; final String customAuto = "My Auto"; String autoSelected; SendableChooser<String> chooser = new SendableChooser<>(); /** * This function is run when the robot is first started up and should be * used for any initialization code. */ @Override public void robotInit() { try { shooter = new Shooter(1, 2); } catch (Exception e) { e.printStackTrace(); } //try { driveTrain = new DriveTrain(); //driveToAngleCommand = new DriveToAngle(); /*} catch (Exception e){ e.printStackTrace(); }*/ Scheduler.getInstance().add(new ShootSpinner()); Scheduler.getInstance().add(new Shoot()); climber = new Climber(); chooser.addDefault("Default Auto", defaultAuto); chooser.addObject("My Auto", customAuto); SmartDashboard.putData("Auto choices", chooser); //OI INITIALIZATION MUST MUST MUST MUST BE LAST oi = new OI(); } /** * This autonomous (along with the chooser code above) shows how to select * between different autonomous modes using the dashboard. The sendable * chooser code works with the Java SmartDashboard. If you prefer the * LabVIEW Dashboard, remove all of the chooser code and uncomment the * getString line to get the auto name from the text box below the Gyro * * You can add additional auto modes by adding additional comparisons to the * switch structure below with additional strings. If using the * SendableChooser make sure to add them to the chooser code above as well. */ @Override public void autonomousInit() { autoSelected = chooser.getSelected(); // autoSelected = SmartDashboard.getString("Auto Selector", // defaultAuto); System.out.println("Auto selected: " + autoSelected); } /** * This function is called periodically during autonomous */ @Override public void autonomousPeriodic() { //SmartDashboard.putNumber("DriveTrain Yaw", Robot.driveTrain.ahrs.getYaw()); switch (autoSelected) { case customAuto: // Put custom auto code here break; case defaultAuto: default: // Put default auto code here break; } } private int tickcount; @Override public void teleopPeriodic() { //SmartDashboard.putNumber("DriveTrain Yaw", Robot.driveTrain.ahrs.getYaw()); ++tickcount; SmartDashboard.putNumber("tickCount", tickcount); Scheduler.getInstance().run(); Scheduler.getInstance().add(new DriveToggle()); SmartDashboard.putNumber("DriveTrain Left Voltage 1", pdp.getCurrent(RobotMap.PDP.leftDriveMotor[0])); SmartDashboard.putNumber("DriveTrain Left Voltage 2", pdp.getCurrent(RobotMap.PDP.leftDriveMotor[1])); SmartDashboard.putNumber("DriveTrain Left Voltage 3", pdp.getCurrent(RobotMap.PDP.leftDriveMotor[2])); SmartDashboard.putNumber("DriveTrain Right Voltage 1", pdp.getCurrent(RobotMap.PDP.rightDriveMotor[0])); SmartDashboard.putNumber("DriveTrain Right Voltage 2", pdp.getCurrent(RobotMap.PDP.rightDriveMotor[1])); SmartDashboard.putNumber("DriveTrain Right Voltage 3", pdp.getCurrent(RobotMap.PDP.rightDriveMotor[2])); } public void disabledPeriodic() { //SmartDashboard.putNumber("DriveTrain Yaw", Robot.driveTrain.ahrs.getYaw()); } /** * This function is called periodically during test mode */ @Override public void testPeriodic() { SmartDashboard.putNumber("DriveTrain Yaw", Robot.driveTrain.ahrs.getYaw()); } public static double deadband(double x) { if(Math.abs(x) < 0.05) { return 0; } return x; } public static double clamp(double x) { if(x > 1) { return 1; } else if(x < -1) { return -1; } return x; } public static double averageCurrent(int[] ports) { double result = 0; if (ports.length != 0) { for (int i = 0; i != ports.length; ++i) { result += pdp.getCurrent(ports[i]); } result /= ports.length; } return result; } }
src/org/usfirst/frc/team997/robot/Robot.java
package org.usfirst.frc.team997.robot; import org.usfirst.frc.team997.robot.commands.DriveToAngle; import org.usfirst.frc.team997.robot.commands.DriveToggle; import org.usfirst.frc.team997.robot.commands.Shoot; import org.usfirst.frc.team997.robot.commands.ShootSpinner; import org.usfirst.frc.team997.robot.subsystems.Climber; import org.usfirst.frc.team997.robot.subsystems.DriveTrain; import org.usfirst.frc.team997.robot.subsystems.Elevator; import org.usfirst.frc.team997.robot.subsystems.Shooter; import org.usfirst.frc.team997.robot.RobotMap.PDP; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj.PowerDistributionPanel; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { public static OI oi; public static DriveTrain driveTrain; public static Shooter shooter; public static DriveToAngle driveToAngleCommand; public static Climber climber; public static PowerDistributionPanel pdp; public static Elevator elevator; final String defaultAuto = "Default"; final String customAuto = "My Auto"; String autoSelected; SendableChooser<String> chooser = new SendableChooser<>(); /** * This function is run when the robot is first started up and should be * used for any initialization code. */ @Override public void robotInit() { try { shooter = new Shooter(1, 2); } catch (Exception e) { e.printStackTrace(); } //try { driveTrain = new DriveTrain(); //driveToAngleCommand = new DriveToAngle(); /*} catch (Exception e){ e.printStackTrace(); }*/ Scheduler.getInstance().add(new ShootSpinner()); Scheduler.getInstance().add(new Shoot()); climber = new Climber(); chooser.addDefault("Default Auto", defaultAuto); chooser.addObject("My Auto", customAuto); SmartDashboard.putData("Auto choices", chooser); //OI INITIALIZATION MUST MUST MUST MUST BE LAST oi = new OI(); } /** * This autonomous (along with the chooser code above) shows how to select * between different autonomous modes using the dashboard. The sendable * chooser code works with the Java SmartDashboard. If you prefer the * LabVIEW Dashboard, remove all of the chooser code and uncomment the * getString line to get the auto name from the text box below the Gyro * * You can add additional auto modes by adding additional comparisons to the * switch structure below with additional strings. If using the * SendableChooser make sure to add them to the chooser code above as well. */ @Override public void autonomousInit() { autoSelected = chooser.getSelected(); // autoSelected = SmartDashboard.getString("Auto Selector", // defaultAuto); System.out.println("Auto selected: " + autoSelected); } /** * This function is called periodically during autonomous */ @Override public void autonomousPeriodic() { //SmartDashboard.putNumber("DriveTrain Yaw", Robot.driveTrain.ahrs.getYaw()); switch (autoSelected) { case customAuto: // Put custom auto code here break; case defaultAuto: default: // Put default auto code here break; } } private int tickcount; @Override public void teleopPeriodic() { //SmartDashboard.putNumber("DriveTrain Yaw", Robot.driveTrain.ahrs.getYaw()); ++tickcount; SmartDashboard.putNumber("tickCount", tickcount); Scheduler.getInstance().run(); Scheduler.getInstance().add(new DriveToggle()); SmartDashboard.putNumber("DriveTrain Left Voltage 1", pdp.getCurrent(RobotMap.PDP.leftDriveMotor[0])); SmartDashboard.putNumber("DriveTrain Left Voltage 2", pdp.getCurrent(RobotMap.PDP.leftDriveMotor[1])); SmartDashboard.putNumber("DriveTrain Left Voltage 3", pdp.getCurrent(RobotMap.PDP.leftDriveMotor[2])); SmartDashboard.putNumber("DriveTrain Right Voltage 1", pdp.getCurrent(RobotMap.PDP.rightDriveMotor[0])); SmartDashboard.putNumber("DriveTrain Right Voltage 2", pdp.getCurrent(RobotMap.PDP.rightDriveMotor[1])); SmartDashboard.putNumber("DriveTrain Right Voltage 3", pdp.getCurrent(RobotMap.PDP.rightDriveMotor[2])); } public void disabledPeriodic() { //SmartDashboard.putNumber("DriveTrain Yaw", Robot.driveTrain.ahrs.getYaw()); } /** * This function is called periodically during test mode */ @Override public void testPeriodic() { SmartDashboard.putNumber("DriveTrain Yaw", Robot.driveTrain.ahrs.getYaw()); } public static double deadband(double x) { if(Math.abs(x) < 0.05) { return 0; } return x; } public static double clamp(double x) { if(x > 1) { return 1; } else if(x < -1) { return -1; } return x; } }
Add averageCurrent(int[] ports)
src/org/usfirst/frc/team997/robot/Robot.java
Add averageCurrent(int[] ports)
<ide><path>rc/org/usfirst/frc/team997/robot/Robot.java <ide> return -1; <ide> } <ide> return x; <del> <add> } <add> <add> public static double averageCurrent(int[] ports) { <add> double result = 0; <add> if (ports.length != 0) { <add> for (int i = 0; i != ports.length; ++i) { <add> result += pdp.getCurrent(ports[i]); <add> } <add> result /= ports.length; <add> } <add> return result; <ide> } <ide> } <ide>
Java
lgpl-2.1
2610401e1fcf2e1106ea0d8dd41fba3ae5b5d014
0
tgvaughan/beast2,tgvaughan/beast2,Anaphory/beast2,tgvaughan/beast2,tgvaughan/beast2,Anaphory/beast2,CompEvol/beast2,CompEvol/beast2,CompEvol/beast2,Anaphory/beast2,CompEvol/beast2,Anaphory/beast2
package beast.util; import static beast.util.OutputUtils.format; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import beast.app.BEASTVersion; import beast.app.util.Utils; import beast.core.util.ESS; import beast.core.util.Log; public class LogAnalyser { public static final int BURN_IN_PERCENTAGE = 10; // default protected final String fileName; /** * column labels in log file * */ protected String[] m_sLabels; /** * distinguish various column types * */ protected enum type { REAL, INTEGER, BOOL, NOMINAL } protected type[] m_types; /** * range of a column, if it is not a REAL * */ protected List<String>[] m_ranges; /** * data from log file with burn-in removed * */ protected Double[][] m_fTraces; /** * statistics on the data, one per column. First column (sample nr) is not set * */ Double[] m_fMean, m_fStdError, m_fStdDev, m_fMedian, m_f95HPDup, m_f95HPDlow, m_fESS, m_fACT, m_fGeometricMean; /** * used for storing comments before the actual log file commences * */ protected String m_sPreAmble; /** * If set, analyzer works in "quiet" mode. */ protected boolean quiet = false; final protected static String BAR = "|---------|---------|---------|---------|---------|---------|---------|---------|"; public LogAnalyser() { fileName = null; } /** * * @param args * @param burnInPercentage burnInPercentage typical = 10; percentage of data that can be ignored * @throws IOException */ public LogAnalyser(String[] args, int burnInPercentage) throws IOException { fileName = args[args.length - 1]; readLogFile(fileName, burnInPercentage); calcStats(); } public LogAnalyser(String[] args) throws IOException { this(args, BURN_IN_PERCENTAGE); } public LogAnalyser(String fileName, int burnInPercentage) throws IOException { this.fileName = fileName; readLogFile(fileName, burnInPercentage); calcStats(); } public LogAnalyser(String fileName, int burnInPercentage, boolean quiet) throws IOException { this.fileName = fileName; this.quiet = quiet; readLogFile(fileName, burnInPercentage); calcStats(); } public LogAnalyser(String fileName) throws IOException { this(fileName, BURN_IN_PERCENTAGE); } @SuppressWarnings("unchecked") protected void readLogFile(String fileName, int burnInPercentage) throws IOException { log("\nLoading " + fileName); BufferedReader fin = new BufferedReader(new FileReader(fileName)); String str; m_sPreAmble = ""; m_sLabels = null; int data = 0; // first, sweep through the log file to determine size of the log while (fin.ready()) { str = fin.readLine(); if (str.indexOf('#') < 0 && str.matches(".*[0-9a-zA-Z].*")) { if (m_sLabels == null) m_sLabels = str.split("\\s"); else data++; } else { m_sPreAmble += str + "\n"; } } int lines = Math.max(1, data / 80); // reserve memory int items = m_sLabels.length; m_ranges = new List[items]; int burnIn = data * burnInPercentage / 100; m_fTraces = new Double[items][data - burnIn]; fin.close(); fin = new BufferedReader(new FileReader(fileName)); data = -burnIn - 1; logln(", burnin " + burnInPercentage + "%, skipping " + burnIn + " log lines\n\n" + BAR); // grab data from the log, ignoring burn in samples m_types = new type[items]; Arrays.fill(m_types, type.INTEGER); while (fin.ready()) { str = fin.readLine(); int i = 0; if (str.indexOf('#') < 0 && str.matches("[0-9].*")) // { //data++; if (++data >= 0) //{ for (String str2 : str.split("\\s")) { try { if (str2.indexOf('.') >= 0) { m_types[i] = type.REAL; } m_fTraces[i][data] = Double.parseDouble(str2); } catch (Exception e) { if (m_ranges[i] == null) { m_ranges[i] = new ArrayList<>(); } if (!m_ranges[i].contains(str2)) { m_ranges[i].add(str2); } m_fTraces[i][data] = 1.0 * m_ranges[i].indexOf(str2); } i++; } //} //} if (data % lines == 0) { log("*"); } } logln(""); // determine types for (int i = 0; i < items; i++) if (m_ranges[i] != null) if (m_ranges[i].size() == 2 && m_ranges[i].contains("true") && m_ranges[i].contains("false") || m_ranges[i].size() == 1 && (m_ranges[i].contains("true") || m_ranges[i].contains("false"))) m_types[i] = type.BOOL; else m_types[i] = type.NOMINAL; fin.close(); } // readLogFile /** * calculate statistics on the data, one per column. * First column (sample nr) is not set * */ void calcStats() { logln("\nCalculating statistics\n\n" + BAR); int stars = 0; int items = m_sLabels.length; m_fMean = new Double[items]; m_fStdError = new Double[items]; m_fStdDev = new Double[items]; m_fMedian = new Double[items]; m_f95HPDlow = new Double[items]; m_f95HPDup = new Double[items]; m_fESS = new Double[items]; m_fACT = new Double[items]; m_fGeometricMean = new Double[items]; int sampleInterval = (int) (m_fTraces[0][1] - m_fTraces[0][0]); for (int i = 1; i < items; i++) { // calc mean and standard deviation Double[] trace = m_fTraces[i]; double sum = 0, sum2 = 0; for (double f : trace) { sum += f; sum2 += f * f; } if (m_types[i] != type.NOMINAL) { m_fMean[i] = sum / trace.length; m_fStdDev[i] = Math.sqrt(sum2 / trace.length - m_fMean[i] * m_fMean[i]); } else { m_fMean[i] = Double.NaN; m_fStdDev[i] = Double.NaN; } if (m_types[i] == type.REAL || m_types[i] == type.INTEGER) { // calc median, and 95% HPD interval Double[] sorted = trace.clone(); Arrays.sort(sorted); m_fMedian[i] = sorted[trace.length / 2]; // n instances cover 95% of the trace, reduced down by 1 to match Tracer int n = (int) ((sorted.length - 1) * 95.0 / 100.0); double minRange = Double.MAX_VALUE; int hpdIndex = 0; for (int k = 0; k < sorted.length - n; k++) { double range = sorted[k + n] - sorted[k]; if (range < minRange) { minRange = range; hpdIndex = k; } } m_f95HPDlow[i] = sorted[hpdIndex]; m_f95HPDup[i] = sorted[hpdIndex + n]; // calc effective sample size m_fACT[i] = ESS.ACT(m_fTraces[i], sampleInterval); m_fStdError[i] = ESS.stdErrorOfMean(trace, sampleInterval); m_fESS[i] = trace.length / (m_fACT[i] / sampleInterval); // calc geometric mean if (sorted[0] > 0) { // geometric mean is only defined when all elements are positive double gm = 0; for (double f : trace) gm += Math.log(f); m_fGeometricMean[i] = Math.exp(gm / trace.length); } else m_fGeometricMean[i] = Double.NaN; } else { m_fMedian[i] = Double.NaN; m_f95HPDlow[i] = Double.NaN; m_f95HPDup[i] = Double.NaN; m_fACT[i] = Double.NaN; m_fESS[i] = Double.NaN; m_fGeometricMean[i] = Double.NaN; } while (stars < 80 * (i + 1) / items) { log("*"); stars++; } } logln("\n"); } // calcStats public void setData(Double[][] traces, String[] labels, type[] types) { m_fTraces = traces.clone(); m_sLabels = labels.clone(); m_types = types.clone(); calcStats(); } public void setData(Double[] trace, int sampleStep) { Double[][] traces = new Double[2][]; traces[0] = new Double[trace.length]; for (int i = 0; i < trace.length; i++) { traces[0][i] = (double) i * sampleStep; } traces[1] = trace.clone(); setData(traces, new String[]{"column", "data"}, new type[]{type.REAL, type.REAL}); } public int indexof(String label) { return CollectionUtils.indexof(label, m_sLabels); } /** * First column "Sample" (sample nr) needs to be removed * @return */ public List<String> getLabels() { if (m_sLabels.length < 2) return new ArrayList<>(); return CollectionUtils.toList(m_sLabels, 1, m_sLabels.length); } public Double [] getTrace(int index) { return m_fTraces[index].clone(); } public Double [] getTrace(String label) { return m_fTraces[indexof(label)].clone(); } public double getMean(String label) { return getMean(indexof(label)); } public double getStdError(String label) { return getStdError(indexof(label)); } public double getStdDev(String label) { return getStdDev(indexof(label)); } public double getMedian(String label) { return getMedian(indexof(label)); } public double get95HPDup(String label) { return get95HPDup(indexof(label)); } public double get95HPDlow(String label) { return get95HPDlow(indexof(label)); } public double getESS(String label) { return getESS(indexof(label)); } public double getACT(String label) { return getACT(indexof(label)); } public double getGeometricMean(String label) { return getGeometricMean(indexof(label)); } public double getMean(int column) { return m_fMean[column]; } public double getStdDev(int column) { return m_fStdDev[column]; } public double getStdError(int column) { return m_fStdError[column]; } public double getMedian(int column) { return m_fMedian[column]; } public double get95HPDup(int column) { return m_f95HPDup[column]; } public double get95HPDlow(int column) { return m_f95HPDlow[column]; } public double getESS(int column) { return m_fESS[column]; } public double getACT(int column) { return m_fACT[column]; } public double getGeometricMean(int column) { return m_fGeometricMean[column]; } public double getMean(Double[] trace) { setData(trace, 1); return m_fMean[1]; } public double getStdDev(Double[] trace) { setData(trace, 1); return m_fStdDev[1]; } public double getMedian(Double[] trace) { setData(trace, 1); return m_fMedian[1]; } public double get95HPDup(Double[] trace) { setData(trace, 1); return m_f95HPDup[1]; } public double get95HPDlow(Double[] trace) { setData(trace, 1); return m_f95HPDlow[1]; } public double getESS(Double[] trace) { setData(trace, 1); return m_fESS[1]; } public double getACT(Double[] trace, int sampleStep) { setData(trace, sampleStep); return m_fACT[1]; } public double getGeometricMean(Double[] trace) { setData(trace, 1); return m_fGeometricMean[1]; } public String getLogFile() { return fileName; } /** * print statistics for each column except first column (sample nr). * */ final String SPACE = OutputUtils.SPACE; public void print(PrintStream out) { // set up header for prefix, if any is specified String prefix = System.getProperty("prefix"); String prefixHead = (prefix == null ? "" : "prefix "); if (prefix != null) { String [] p = prefix.trim().split("\\s+"); if (p.length > 1) { prefixHead = ""; for (int i = 0; i < p.length; i++) { prefixHead += "prefix" + i + " "; } } } try { // delay so that stars can be flushed from stderr Thread.sleep(100); } catch (Exception e) { } int max = 0; for (int i = 1; i < m_sLabels.length; i++) max = Math.max(m_sLabels[i].length(), max); String space = ""; for (int i = 0; i < max; i++) space += " "; out.println("item" + space.substring(4) + " " + prefixHead + format("mean") + format("stderr") + format("stddev") + format("median") + format("95%HPDlo") + format("95%HPDup") + format("ACT") + format("ESS") + format("geometric-mean")); for (int i = 1; i < m_sLabels.length; i++) { out.println(m_sLabels[i] + space.substring(m_sLabels[i].length()) + SPACE + (prefix == null ? "" : prefix + SPACE) + format(m_fMean[i]) + SPACE + format(m_fStdError[i]) + SPACE + format(m_fStdDev[i]) + SPACE + format(m_fMedian[i]) + SPACE + format(m_f95HPDlow[i]) + SPACE + format(m_f95HPDup[i]) + SPACE + format(m_fACT[i]) + SPACE + format(m_fESS[i]) + SPACE + format(m_fGeometricMean[i])); } } /** * Display header used in one-line mode. * * @param out output stream */ public void printOneLineHeader(PrintStream out) { String[] postFix = { "mean", "stderr", "stddev", "median", "95%HPDlo", "95%HPDup", "ACT", "ESS", "geometric-mean" }; for (int paramIdx=1; paramIdx<m_sLabels.length; paramIdx++) { for (int i=0; i<postFix.length; i++) { if (paramIdx> 1 || i>0) out.print("\t"); out.print(m_sLabels[paramIdx] + "." + postFix[i]); } } out.println(); } /** * Display results for single log on one line. * * @param out output stream */ public void printOneLine(PrintStream out) { for (int paramIdx=1; paramIdx<m_sLabels.length; paramIdx++) { if (paramIdx>1) out.print("\t"); out.print(m_fMean[paramIdx] + "\t"); out.print(m_fStdError[paramIdx] + "\t"); out.print(m_fStdDev[paramIdx] + "\t"); out.print(m_fMedian[paramIdx] + "\t"); out.print(m_f95HPDlow[paramIdx] + "\t"); out.print(m_f95HPDup[paramIdx] + "\t"); out.print(m_fACT[paramIdx] + "\t"); out.print(m_fESS[paramIdx] + "\t"); out.print(m_fGeometricMean[paramIdx]); } out.println(); } protected void log(String s) { if (!quiet) Log.warning.print(s); } protected void logln(String s) { if (!quiet) Log.warning.println(s); } static void printUsageAndExit() { System.out.println("LogAnalyser [-b <burninPercentage] [file1] ... [filen]"); System.out.println("-burnin <burninPercentage>"); System.out.println("--burnin <burninPercentage>"); System.out.println("-b <burninPercentage> percentage of log file to disregard, default " + BURN_IN_PERCENTAGE); System.out.println("-oneline Display only one line of output per file.\n" + " Header is generated from the first file only.\n" + " (Implies quiet mode.)"); System.out.println("-quiet Quiet mode. Avoid printing status updates to stderr."); System.out.println("-help"); System.out.println("--help"); System.out.println("-h print this message"); System.out.println("[fileX] log file to analyse. Multiple files are allowed, each is analysed separately"); System.exit(0); } /** * @param args */ public static void main(String[] args) { try { LogAnalyser analyser; // process args int burninPercentage = BURN_IN_PERCENTAGE; boolean oneLine = false; boolean quiet = false; List<String> files = new ArrayList<>(); int i = 0; while (i < args.length) { String arg = args[i]; switch (arg) { case "-b": case "-burnin": case "--burnin": if (i+1 >= args.length) { Log.warning.println("-b argument requires another argument"); printUsageAndExit(); } burninPercentage = Integer.parseInt(args[i+1]); i += 2; break; case "-oneline": oneLine = true; i += 1; break; case "-quiet": quiet = true; i += 1; break; case "-h": case "-help": case "--help": printUsageAndExit(); break; default: if (arg.startsWith("-")) { Log.warning.println("unrecognised command " + arg); printUsageAndExit(); } files.add(arg); i++; } } if (files.size() == 0) { // no file specified, open file dialog to select one BEASTVersion version = new BEASTVersion(); File file = Utils.getLoadFile("LogAnalyser " + version.getVersionString() + " - Select log file to analyse", null, "BEAST log (*.log) Files", "log", "txt"); if (file == null) { return; } analyser = new LogAnalyser(file.getAbsolutePath(), burninPercentage, quiet); analyser.print(System.out); } else { // process files if (oneLine) { for (int idx=0; idx<files.size(); idx++) { analyser = new LogAnalyser(files.get(idx), burninPercentage, true); if (idx == 0) analyser.printOneLineHeader(System.out); analyser.printOneLine(System.out); } } else { for (String file : files) { analyser = new LogAnalyser(file, burninPercentage, quiet); analyser.print(System.out); } } } } catch (Exception e) { e.printStackTrace(); } } }
src/beast/util/LogAnalyser.java
package beast.util; import static beast.util.OutputUtils.format; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import beast.app.BEASTVersion; import beast.app.util.Utils; import beast.core.util.ESS; import beast.core.util.Log; public class LogAnalyser { public static final int BURN_IN_PERCENTAGE = 10; // default protected final String fileName; /** * column labels in log file * */ protected String[] m_sLabels; /** * distinguish various column types * */ protected enum type { REAL, INTEGER, BOOL, NOMINAL } protected type[] m_types; /** * range of a column, if it is not a REAL * */ protected List<String>[] m_ranges; /** * data from log file with burn-in removed * */ protected Double[][] m_fTraces; /** * statistics on the data, one per column. First column (sample nr) is not set * */ Double[] m_fMean, m_fStdError, m_fStdDev, m_fMedian, m_f95HPDup, m_f95HPDlow, m_fESS, m_fACT, m_fGeometricMean; /** * used for storing comments before the actual log file commences * */ protected String m_sPreAmble; /** * If set, analyzer works in "quiet" mode. */ protected boolean quiet = false; final protected static String BAR = "|---------|---------|---------|---------|---------|---------|---------|---------|"; public LogAnalyser() { fileName = null; } /** * * @param args * @param burnInPercentage burnInPercentage typical = 10; percentage of data that can be ignored * @throws IOException */ public LogAnalyser(String[] args, int burnInPercentage) throws IOException { fileName = args[args.length - 1]; readLogFile(fileName, burnInPercentage); calcStats(); } public LogAnalyser(String[] args) throws IOException { this(args, BURN_IN_PERCENTAGE); } public LogAnalyser(String fileName, int burnInPercentage) throws IOException { this.fileName = fileName; readLogFile(fileName, burnInPercentage); calcStats(); } public LogAnalyser(String fileName, int burnInPercentage, boolean quiet) throws IOException { this.fileName = fileName; this.quiet = quiet; readLogFile(fileName, burnInPercentage); calcStats(); } public LogAnalyser(String fileName) throws IOException { this(fileName, BURN_IN_PERCENTAGE); } @SuppressWarnings("unchecked") protected void readLogFile(String fileName, int burnInPercentage) throws IOException { log("\nLoading " + fileName); BufferedReader fin = new BufferedReader(new FileReader(fileName)); String str; m_sPreAmble = ""; m_sLabels = null; int data = 0; // first, sweep through the log file to determine size of the log while (fin.ready()) { str = fin.readLine(); if (str.indexOf('#') < 0 && str.matches(".*[0-9a-zA-Z].*")) { if (m_sLabels == null) m_sLabels = str.split("\\s"); else data++; } else { m_sPreAmble += str + "\n"; } } int lines = Math.max(1, data / 80); // reserve memory int items = m_sLabels.length; m_ranges = new List[items]; int burnIn = data * burnInPercentage / 100; m_fTraces = new Double[items][data - burnIn]; fin.close(); fin = new BufferedReader(new FileReader(fileName)); data = -burnIn - 1; logln(", burnin " + burnInPercentage + "%, skipping " + burnIn + " log lines\n\n" + BAR); // grab data from the log, ignoring burn in samples m_types = new type[items]; Arrays.fill(m_types, type.INTEGER); while (fin.ready()) { str = fin.readLine(); int i = 0; if (str.indexOf('#') < 0 && str.matches("[0-9].*")) // { //data++; if (++data >= 0) //{ for (String str2 : str.split("\\s")) { try { if (str2.indexOf('.') >= 0) { m_types[i] = type.REAL; } m_fTraces[i][data] = Double.parseDouble(str2); } catch (Exception e) { if (m_ranges[i] == null) { m_ranges[i] = new ArrayList<>(); } if (!m_ranges[i].contains(str2)) { m_ranges[i].add(str2); } m_fTraces[i][data] = 1.0 * m_ranges[i].indexOf(str2); } i++; } //} //} if (data % lines == 0) { log("*"); } } logln(""); // determine types for (int i = 0; i < items; i++) if (m_ranges[i] != null) if (m_ranges[i].size() == 2 && m_ranges[i].contains("true") && m_ranges[i].contains("false") || m_ranges[i].size() == 1 && (m_ranges[i].contains("true") || m_ranges[i].contains("false"))) m_types[i] = type.BOOL; else m_types[i] = type.NOMINAL; fin.close(); } // readLogFile /** * calculate statistics on the data, one per column. * First column (sample nr) is not set * */ void calcStats() { logln("\nCalculating statistics\n\n" + BAR); int stars = 0; int items = m_sLabels.length; m_fMean = new Double[items]; m_fStdError = new Double[items]; m_fStdDev = new Double[items]; m_fMedian = new Double[items]; m_f95HPDlow = new Double[items]; m_f95HPDup = new Double[items]; m_fESS = new Double[items]; m_fACT = new Double[items]; m_fGeometricMean = new Double[items]; int sampleInterval = (int) (m_fTraces[0][1] - m_fTraces[0][0]); for (int i = 1; i < items; i++) { // calc mean and standard deviation Double[] trace = m_fTraces[i]; double sum = 0, sum2 = 0; for (double f : trace) { sum += f; sum2 += f * f; } if (m_types[i] != type.NOMINAL) { m_fMean[i] = sum / trace.length; m_fStdDev[i] = Math.sqrt(sum2 / trace.length - m_fMean[i] * m_fMean[i]); } else { m_fMean[i] = Double.NaN; m_fStdDev[i] = Double.NaN; } if (m_types[i] == type.REAL || m_types[i] == type.INTEGER) { // calc median, and 95% HPD interval Double[] sorted = trace.clone(); Arrays.sort(sorted); m_fMedian[i] = sorted[trace.length / 2]; // n instances cover 95% of the trace, reduced down by 1 to match Tracer int n = (int) ((sorted.length - 1) * 95.0 / 100.0); double minRange = Double.MAX_VALUE; int hpdIndex = 0; for (int k = 0; k < sorted.length - n; k++) { double range = sorted[k + n] - sorted[k]; if (range < minRange) { minRange = range; hpdIndex = k; } } m_f95HPDlow[i] = sorted[hpdIndex]; m_f95HPDup[i] = sorted[hpdIndex + n]; // calc effective sample size m_fACT[i] = ESS.ACT(m_fTraces[i], sampleInterval); m_fStdError[i] = ESS.stdErrorOfMean(trace, sampleInterval); m_fESS[i] = trace.length / (m_fACT[i] / sampleInterval); // calc geometric mean if (sorted[0] > 0) { // geometric mean is only defined when all elements are positive double gm = 0; for (double f : trace) gm += Math.log(f); m_fGeometricMean[i] = Math.exp(gm / trace.length); } else m_fGeometricMean[i] = Double.NaN; } else { m_fMedian[i] = Double.NaN; m_f95HPDlow[i] = Double.NaN; m_f95HPDup[i] = Double.NaN; m_fACT[i] = Double.NaN; m_fESS[i] = Double.NaN; m_fGeometricMean[i] = Double.NaN; } while (stars < 80 * (i + 1) / items) { log("*"); stars++; } } logln("\n"); } // calcStats public void setData(Double[][] traces, String[] labels, type[] types) { m_fTraces = traces.clone(); m_sLabels = labels.clone(); m_types = types.clone(); calcStats(); } public void setData(Double[] trace, int sampleStep) { Double[][] traces = new Double[2][]; traces[0] = new Double[trace.length]; for (int i = 0; i < trace.length; i++) { traces[0][i] = (double) i * sampleStep; } traces[1] = trace.clone(); setData(traces, new String[]{"column", "data"}, new type[]{type.REAL, type.REAL}); } public int indexof(String label) { return CollectionUtils.indexof(label, m_sLabels); } /** * First column "Sample" (sample nr) needs to be removed * @return */ public List<String> getLabels() { if (m_sLabels.length < 2) return new ArrayList<>(); return CollectionUtils.toList(m_sLabels, 1, m_sLabels.length); } public Double [] getTrace(int index) { return m_fTraces[index].clone(); } public Double [] getTrace(String label) { return m_fTraces[indexof(label)].clone(); } public double getMean(String label) { return getMean(indexof(label)); } public double getStdError(String label) { return getStdError(indexof(label)); } public double getStdDev(String label) { return getStdDev(indexof(label)); } public double getMedian(String label) { return getMedian(indexof(label)); } public double get95HPDup(String label) { return get95HPDup(indexof(label)); } public double get95HPDlow(String label) { return get95HPDlow(indexof(label)); } public double getESS(String label) { return getESS(indexof(label)); } public double getACT(String label) { return getACT(indexof(label)); } public double getGeometricMean(String label) { return getGeometricMean(indexof(label)); } public double getMean(int column) { return m_fMean[column]; } public double getStdDev(int column) { return m_fStdDev[column]; } public double getStdError(int column) { return m_fStdError[column]; } public double getMedian(int column) { return m_fMedian[column]; } public double get95HPDup(int column) { return m_f95HPDup[column]; } public double get95HPDlow(int column) { return m_f95HPDlow[column]; } public double getESS(int column) { return m_fESS[column]; } public double getACT(int column) { return m_fACT[column]; } public double getGeometricMean(int column) { return m_fGeometricMean[column]; } public double getMean(Double[] trace) { setData(trace, 1); return m_fMean[1]; } public double getStdDev(Double[] trace) { setData(trace, 1); return m_fStdDev[1]; } public double getMedian(Double[] trace) { setData(trace, 1); return m_fMedian[1]; } public double get95HPDup(Double[] trace) { setData(trace, 1); return m_f95HPDup[1]; } public double get95HPDlow(Double[] trace) { setData(trace, 1); return m_f95HPDlow[1]; } public double getESS(Double[] trace) { setData(trace, 1); return m_fESS[1]; } public double getACT(Double[] trace, int sampleStep) { setData(trace, sampleStep); return m_fACT[1]; } public double getGeometricMean(Double[] trace) { setData(trace, 1); return m_fGeometricMean[1]; } public String getLogFile() { return fileName; } /** * print statistics for each column except first column (sample nr). * */ final String SPACE = OutputUtils.SPACE; public void print(PrintStream out) { // set up header for prefix, if any is specified String prefix = System.getProperty("prefix"); String prefixHead = (prefix == null ? "" : "prefix "); if (prefix != null) { String [] p = prefix.trim().split("\\s+"); if (p.length > 1) { prefixHead = ""; for (int i = 0; i < p.length; i++) { prefixHead += "prefix" + i + " "; } } } try { // delay so that stars can be flushed from stderr Thread.sleep(100); } catch (Exception e) { } int max = 0; for (int i = 1; i < m_sLabels.length; i++) max = Math.max(m_sLabels[i].length(), max); String space = ""; for (int i = 0; i < max; i++) space += " "; out.println("item" + space.substring(4) + " " + prefixHead + format("mean") + format("stderr") + format("stddev") + format("median") + format("95%HPDlo") + format("95%HPDup") + format("ACT") + format("ESS") + format("geometric-mean")); for (int i = 1; i < m_sLabels.length; i++) { out.println(m_sLabels[i] + space.substring(m_sLabels[i].length()) + SPACE + (prefix == null ? "" : prefix + SPACE) + format(m_fMean[i]) + SPACE + format(m_fStdError[i]) + SPACE + format(m_fStdDev[i]) + SPACE + format(m_fMedian[i]) + SPACE + format(m_f95HPDlow[i]) + SPACE + format(m_f95HPDup[i]) + SPACE + format(m_fACT[i]) + SPACE + format(m_fESS[i]) + SPACE + format(m_fGeometricMean[i])); } } /** * Display header used in one-line mode. * * @param out output stream */ public void printOneLineHeader(PrintStream out) { String[] postFix = { "mean", "stderr", "stddev", "median", "95%HPDlo", "95%HPDup", "ACT", "ESS", "geometric-mean" }; for (int paramIdx=1; paramIdx<m_sLabels.length; paramIdx++) { for (int i=0; i<postFix.length; i++) { if (paramIdx> 1 || i>0) out.print("\t"); out.print(m_sLabels[paramIdx] + "." + postFix[i]); } } out.println(); } /** * Display results for single log on one line. * * @param out output stream */ public void printOneLine(PrintStream out) { for (int paramIdx=1; paramIdx<m_sLabels.length; paramIdx++) { if (paramIdx>1) out.print("\t"); out.print(m_fMean[paramIdx] + "\t"); out.print(m_fStdError[paramIdx] + "\t"); out.print(m_fStdDev[paramIdx] + "\t"); out.print(m_fMedian[paramIdx] + "\t"); out.print(m_f95HPDlow[paramIdx] + "\t"); out.print(m_f95HPDup[paramIdx] + "\t"); out.print(m_fACT[paramIdx] + "\t"); out.print(m_fESS[paramIdx] + "\t"); out.print(m_fGeometricMean[paramIdx]); } out.println(); } protected void log(String s) { if (!quiet) Log.warning.print(s); } protected void logln(String s) { if (!quiet) Log.warning.println(s); } static void printUsageAndExit() { System.out.println("LogAnalyser [-b <burninPercentage] [file1] ... [filen]"); System.out.println("-burnin <burninPercentage>"); System.out.println("--burnin <burninPercentage>"); System.out.println("-b <burninPercentage> percentage of log file to disregard, default " + BURN_IN_PERCENTAGE); System.out.println("-oneline Display only one line of output per file.\n" + " Header is generated from the first file only.\n" + " (Implies quiet mode.)"); System.out.println("-quiet Quiet mode. Avoid printing status updates to stderr."); System.out.println("-help"); System.out.println("--help"); System.out.println("-h print this message"); System.out.println("[fileX] log file to analyse. Multiple files are allowed, each is analysed separately"); System.exit(0); } /** * @param args */ public static void main(String[] args) { try { LogAnalyser analyser; // process args int burninPercentage = BURN_IN_PERCENTAGE; boolean oneLine = false; boolean quiet = true; List<String> files = new ArrayList<>(); int i = 0; while (i < args.length) { String arg = args[i]; switch (arg) { case "-b": case "-burnin": case "--burnin": if (i+1 >= args.length) { Log.warning.println("-b argument requires another argument"); printUsageAndExit(); } burninPercentage = Integer.parseInt(args[i+1]); i += 2; break; case "-oneline": oneLine = true; i += 1; break; case "-quiet": quiet = true; i += 1; break; case "-h": case "-help": case "--help": printUsageAndExit(); break; default: if (arg.startsWith("-")) { Log.warning.println("unrecognised command " + arg); printUsageAndExit(); } files.add(arg); i++; } } if (files.size() == 0) { // no file specified, open file dialog to select one BEASTVersion version = new BEASTVersion(); File file = Utils.getLoadFile("LogAnalyser " + version.getVersionString() + " - Select log file to analyse", null, "BEAST log (*.log) Files", "log", "txt"); if (file == null) { return; } analyser = new LogAnalyser(file.getAbsolutePath(), burninPercentage, quiet); analyser.print(System.out); } else { // process files if (oneLine) { for (int idx=0; idx<files.size(); idx++) { analyser = new LogAnalyser(files.get(idx), burninPercentage, true); if (idx == 0) analyser.printOneLineHeader(System.out); analyser.printOneLine(System.out); } } else { for (String file : files) { analyser = new LogAnalyser(file, burninPercentage, quiet); analyser.print(System.out); } } } } catch (Exception e) { e.printStackTrace(); } } }
initialise quiet flag to false in LogAnalysers, closes #542
src/beast/util/LogAnalyser.java
initialise quiet flag to false in LogAnalysers, closes #542
<ide><path>rc/beast/util/LogAnalyser.java <ide> // process args <ide> int burninPercentage = BURN_IN_PERCENTAGE; <ide> boolean oneLine = false; <del> boolean quiet = true; <add> boolean quiet = false; <ide> List<String> files = new ArrayList<>(); <ide> int i = 0; <ide> while (i < args.length) {
Java
mit
f5de59a86c609950ab23e3dd6e469933d068cddd
0
iwanbolzern/connect-four
package prg2.connectfour; import java.awt.Dimension; import javax.swing.*; import prg2.connectfour.logic.Color; import prg2.connectfour.logic.bot.GameTheory; import prg2.connectfour.ui.HomeScreen; import prg2.connectfour.ui.PlayGround; import prg2.connectfour.ui.PlayGroundSizeDialog; import prg2.connectfour.ui.SearchPlayerScreen; import prg2.connectfour.ui.HomeScreen.GameMode; import prg2.connectfour.utils.Pair; import prg2.connectfour.utils.Utils; import prg2.connectfour.comlayer.InvitationResponseMsg; import prg2.connectfour.comlayer.InvitationMsg; import prg2.connectfour.comlayer.NetworkPlayer; import prg2.connectfour.comlayer.NetworkEnv; public class ConnectFour extends JFrame { private NetworkEnv networkEnv; // Screens private HomeScreen homeScreen; private SearchPlayerScreen searchPlayerScreen; private PlayGround playGround; private String name; private ConnectFour() { initHomeScreen(); add(homeScreen); } private void transition(JPanel from, JPanel to) { this.remove(from); this.add(to); this.revalidate(); } private void initHomeScreen() { homeScreen = new HomeScreen(); homeScreen.addPlayListener(new HomeScreen.PlayHandler() { @Override public void onPlayClicked(HomeScreen.GameMode mode, String playerName, int x, int y) { name = playerName; if(mode == GameMode.NETWORK) { initNetwork(playerName); initSearchPlayerScreen(playerName, x, y); transition(homeScreen, searchPlayerScreen); } else if(mode == GameMode.SINGLE) { initSinglePlayGround(x, y); transition(homeScreen, playGround); } else if(mode == GameMode.LOAD_GAME) { // TODO: implement load game } else { throw new IllegalArgumentException("Game mode not known"); } } }); } private void initNetwork(String playerName) { this.networkEnv = new NetworkEnv(); this.networkEnv.init(playerName); } private void initSearchPlayerScreen(String playerName, int x, int y) { this.searchPlayerScreen = new SearchPlayerScreen(this.networkEnv, x, y); this.searchPlayerScreen.addStartGameListener(new SearchPlayerScreen.StartGameHandler() { @Override public void startGame(InvitationMsg invitation, NetworkPlayer player, InvitationResponseMsg invitationResponse) { String gameToken = networkEnv.sendStartGame(player, invitation.getInvitationToken()); initNetworkPlayGround(gameToken, player, invitation.getX(), invitation.getY(), false); transition(searchPlayerScreen, playGround); } @Override public void startGame(InvitationMsg invitation, NetworkPlayer player) { networkEnv.addStartGameListener(new NetworkEnv.StartGameHandler() { @Override public void startGame(String gameToken, int x, int y) { initNetworkPlayGround(gameToken, player, x, y, true); transition(searchPlayerScreen, playGround); } }); } }); this.searchPlayerScreen.init(); } private void initNetworkPlayGround(String gameToken, NetworkPlayer player, int x, int y, boolean canIStart) { this.playGround = new PlayGround(x, y, name); this.playGround.networkInit(this.networkEnv, gameToken, player, canIStart); this.playGround.addEndGameListener(new PlayGround.EndGameHandler() { @Override public void endGame() { initHomeScreen(); transition(playGround, homeScreen); } }); } private void initSinglePlayGround(int x, int y) { this.playGround = new PlayGround(x, y, name); GameTheory bot = new GameTheory("Best of all", Color.Yellow); this.playGround.singleInit(bot); this.playGround.addEndGameListener(new PlayGround.EndGameHandler() { @Override public void endGame() { initHomeScreen(); transition(playGround, homeScreen); } }); } public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); JFrame mainFrame = new ConnectFour(); mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); mainFrame.setTitle("Connect four - Have fun"); mainFrame.setPreferredSize(new Dimension(800, 600)); mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH); mainFrame.pack(); mainFrame.setVisible(true); } }
src/main/java/prg2/connectfour/ConnectFour.java
package prg2.connectfour; import java.awt.Dimension; import javax.swing.*; import prg2.connectfour.logic.Color; import prg2.connectfour.logic.bot.GameTheory; import prg2.connectfour.ui.HomeScreen; import prg2.connectfour.ui.PlayGround; import prg2.connectfour.ui.PlayGroundSizeDialog; import prg2.connectfour.ui.SearchPlayerScreen; import prg2.connectfour.ui.HomeScreen.GameMode; import prg2.connectfour.utils.Pair; import prg2.connectfour.utils.Utils; import prg2.connectfour.comlayer.InvitationResponseMsg; import prg2.connectfour.comlayer.InvitationMsg; import prg2.connectfour.comlayer.NetworkPlayer; import prg2.connectfour.comlayer.NetworkEnv; public class ConnectFour extends JFrame { private NetworkEnv networkEnv; // Screens private HomeScreen homeScreen; private SearchPlayerScreen searchPlayerScreen; private PlayGround playGround; private String name; private ConnectFour() { initHomeScreen(); add(homeScreen); } private void transition(JPanel from, JPanel to) { this.remove(from); this.add(to); this.revalidate(); } private void initHomeScreen() { homeScreen = new HomeScreen(); homeScreen.addPlayListener(new HomeScreen.PlayHandler() { @Override public void onPlayClicked(HomeScreen.GameMode mode, String playerName, int x, int y) { name = playerName; if(mode == GameMode.NETWORK) { initNetwork(playerName); initSearchPlayerScreen(playerName, x, y); transition(homeScreen, searchPlayerScreen); } else if(mode == GameMode.SINGLE) { initSinglePlayGround(x, y); transition(homeScreen, playGround); } else if(mode == GameMode.LOAD_GAME) { // TODO: implement load game } else { throw new IllegalArgumentException("Game mode not known"); } } }); } private void initNetwork(String playerName) { this.networkEnv = new NetworkEnv(); this.networkEnv.init(playerName); } private void initSearchPlayerScreen(String playerName, int x, int y) { this.searchPlayerScreen = new SearchPlayerScreen(this.networkEnv, x, y); this.searchPlayerScreen.addStartGameListener(new SearchPlayerScreen.StartGameHandler() { @Override public void startGame(InvitationMsg invitation, NetworkPlayer player, InvitationResponseMsg invitationResponse) { String gameToken = networkEnv.sendStartGame(player, invitation.getInvitationToken()); initNetworkPlayGround(gameToken, player, invitation.getX(), invitation.getY(), false); transition(searchPlayerScreen, playGround); } @Override public void startGame(InvitationMsg invitation, NetworkPlayer player) { networkEnv.addStartGameListener(new NetworkEnv.StartGameHandler() { @Override public void startGame(String gameToken, int x, int y) { initNetworkPlayGround(gameToken, player, x, y, true); transition(searchPlayerScreen, playGround); } }); } }); this.searchPlayerScreen.init(); } private void initNetworkPlayGround(String gameToken, NetworkPlayer player, int x, int y, boolean canIStart) { this.playGround = new PlayGround(x, y, name); this.playGround.networkInit(this.networkEnv, gameToken, player, canIStart); this.playGround.addEndGameListener(new PlayGround.EndGameHandler() { @Override public void endGame() { initHomeScreen(); transition(playGround, homeScreen); } }); } private void initSinglePlayGround(int x, int y) { this.playGround = new PlayGround(x, y, name); GameTheory bot = new GameTheory("Best of all", Color.Yellow); this.playGround.singleInit(bot); this.playGround.addEndGameListener(new PlayGround.EndGameHandler() { @Override public void endGame() { initHomeScreen(); transition(playGround, homeScreen); } }); } public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); JFrame mainFrame = new ConnectFour(); mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); mainFrame.setTitle("Connect four - Have fun"); mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH); mainFrame.pack(); mainFrame.setVisible(true); } }
prefered size fixed
src/main/java/prg2/connectfour/ConnectFour.java
prefered size fixed
<ide><path>rc/main/java/prg2/connectfour/ConnectFour.java <ide> JFrame mainFrame = new ConnectFour(); <ide> mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); <ide> mainFrame.setTitle("Connect four - Have fun"); <add> mainFrame.setPreferredSize(new Dimension(800, 600)); <ide> mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH); <ide> mainFrame.pack(); <ide> mainFrame.setVisible(true);
JavaScript
lgpl-2.1
fc3c52ebf4113eb0d1ff04b4c21a0b4f1e9cda71
0
FernCreek/tinymce,tinymce/tinymce,FernCreek/tinymce,TeamupCom/tinymce,tinymce/tinymce,tinymce/tinymce,FernCreek/tinymce,TeamupCom/tinymce
asynctest( 'EventRegistryTest', [ 'ephox.agar.alien.Truncate', 'ephox.agar.api.Assertions', 'ephox.agar.api.Chain', 'ephox.agar.api.GeneralSteps', 'ephox.agar.api.Logger', 'ephox.agar.api.Pipeline', 'ephox.agar.api.Step', 'ephox.agar.api.UiFinder', 'ephox.alloy.events.EventRegistry', 'ephox.compass.Arr', 'ephox.numerosity.api.JSON', 'ephox.peanut.Fun', 'ephox.perhaps.Result', 'ephox.sugar.api.Attr', 'ephox.sugar.api.Compare', 'ephox.sugar.api.Element', 'ephox.sugar.api.Html', 'ephox.sugar.api.Insert', 'global!document' ], function (Truncate, Assertions, Chain, GeneralSteps, Logger, Pipeline, Step, UiFinder, EventRegistry, Arr, Json, Fun, Result, Attr, Compare, Element, Html, Insert, document) { var success = arguments[arguments.length - 2]; var failure = arguments[arguments.length - 1]; var body = Element.fromDom(document.body); var page = Element.fromTag('div'); Html.set(page, '<div alloy-id="comp-1">' + '<div alloy-id="comp-2">' + '<div alloy-id="comp-3">' + '<div alloy-id="comp-4">' + '<div alloy-id="comp-5"></div>' + '</div>' + '</div>' + '</div>' + '</div>' ); var isRoot = Fun.curry(Compare.eq, page); Insert.append(body, page); var events = EventRegistry(); events.registerId([ 'extra-args' ], 'comp-1', { 'event.alpha': function (extra) { return 'event.alpha.1(' + extra + ')'; }, 'event.only': function (extra) { return 'event.only(' + extra + ')'; } }); events.registerId([ 'extra-args' ], 'comp-4', { 'event.alpha': function (extra) { return 'event.alpha.4(' + extra + ')'; } }); var sAssertFilterByType = function (expected, type) { return Step.sync(function () { var filtered = events.filterByType(type); var raw = Arr.map(filtered, function (f) { return { handler: f.handler(), id: f.id() }; }).sort(); Assertions.assertEq('filter(' + type + ') = ' + Json.stringify(expected), expected, raw); }); }; var sAssertNotFound = function (label, type, id) { return Logger.t( 'Test: ' + label + '\nLooking for handlers for id = ' + id + ' and event = ' + type + '. Should not find any', GeneralSteps.sequence([ Chain.asStep(page, [ UiFinder.cFindIn('[alloy-id="' + id + '"]'), Chain.binder(function (target) { var handler = events.find(isRoot, type, target); return handler.fold(function () { return Result.value({ }); }, function (h) { return Result.error( 'Unexpected handler found: ' + Json.stringify({ element: Truncate.getHtml(h.element()), handler: h.handler() }) ); }); }) ]) ]) ); }; var sAssertFind = function (label, expected, type, id) { return Logger.t( 'Test: ' + label + '\nLooking for handlers for id = ' + id + ' and event = ' + type, GeneralSteps.sequence([ Chain.asStep(page, [ UiFinder.cFindIn('[alloy-id="' + id + '"]'), Chain.binder(function (target) { var handler = events.find(isRoot, type, target); return handler.fold(function () { return Result.error('Could not find handler'); }, function (h) { // TODO: Update to use named chains when they become available. Assertions.assertEq('find(' + type + ', ' + id + ') = true', expected.target, Attr.get(h.element(), 'alloy-id')); Assertions.assertEq('find(' + type + ', ' + id + ') = ' + Json.stringify(expected.handler), expected.handler, h.handler()); return Result.value(h); }); }) ]) ]) ); }; Pipeline.async({}, [ sAssertFilterByType([ ], 'event.none'), sAssertFilterByType([ { handler: 'event.alpha.1(extra-args)', id: 'comp-1' }, { handler: 'event.alpha.4(extra-args)', id: 'comp-4' } ], 'event.alpha' ), sAssertFind('comp-1!', { handler: 'event.alpha.1(extra-args)', target: 'comp-1' }, 'event.alpha', 'comp-1'), sAssertFind('comp-2 > comp-1', { handler: 'event.alpha.1(extra-args)', target: 'comp-1' }, 'event.alpha', 'comp-2'), sAssertFind('comp-3 > comp-2 > comp-1', { handler: 'event.alpha.1(extra-args)', target: 'comp-1' }, 'event.alpha', 'comp-3'), sAssertFind('comp-4!', { handler: 'event.alpha.4(extra-args)', target: 'comp-4' }, 'event.alpha', 'comp-4'), sAssertFind('comp-5 > comp-4!', { handler: 'event.alpha.4(extra-args)', target: 'comp-4' }, 'event.alpha', 'comp-5'), sAssertNotFound('comp-5 > comp-4 > comp-3 > comp-2 > comp-1 > NOT FOUND', 'event.beta', 'comp-5'), sAssertFind( 'comp-5 > comp-4 > comp-3 > comp-2 > comp-1!', { handler: 'event.only(extra-args)', target: 'comp-1' }, 'event.only', 'comp-5' ) ], function () { success(); }, failure); } );
src/test/js/browser/events/EventRegistryTest.js
asynctest( 'EventRegistryTest', [ 'ephox.agar.api.Pipeline', 'ephox.agar.api.RawAssertions', 'ephox.agar.api.Step', 'ephox.alloy.events.EventRegistry', 'ephox.compass.Arr', 'ephox.numerosity.api.JSON', 'ephox.peanut.Fun', 'ephox.sugar.api.Element', 'ephox.sugar.api.Html', 'ephox.sugar.api.Insert', 'global!document' ], function (Pipeline, RawAssertions, Step, EventRegistry, Arr, Json, Fun, Element, Html, Insert, document) { var success = arguments[arguments.length - 2]; var failure = arguments[arguments.length - 1]; var body = Element.fromDom(document.body); var page = Element.fromTag('div'); Html.set(page, '<div alloy-id="comp-1">' + '<div alloy-id="comp-2">' + '<div alloy-id="comp-3">' + '<div alloy-id="comp-4">' + '<div alloy-id-"comp-5"></div>' + '</div>' + '</div>' + '</div>' + '</div>' ); Insert.append(body, page); var events = EventRegistry(); events.registerId([ 'extraArgs' ], 'comp-1', { 'event.alpha': function (extra) { return 'f(' + extra + ')'; } }); var sAssertFilterByType = function (expected, type) { return Step.sync(function () { var filtered = events.filterByType(type); var raw = Arr.map(filtered, function (f) { console.log('f', f); return { handler: f.handler(), id: f.id() }; }); RawAssertions.assertEq('filter(' + type + ') = ' + Json.stringify(expected), expected, raw); }); }; Pipeline.async({}, [ sAssertFilterByType([ ], 'event.none'), sAssertFilterByType([ { handler: 'f(extraArgs)', id: 'comp-1' } ], 'event.alpha' ), ], function () { success(); }, failure); } );
VAN-1: Assertions for EventRegistry
src/test/js/browser/events/EventRegistryTest.js
VAN-1: Assertions for EventRegistry
<ide><path>rc/test/js/browser/events/EventRegistryTest.js <ide> 'EventRegistryTest', <ide> <ide> [ <add> 'ephox.agar.alien.Truncate', <add> 'ephox.agar.api.Assertions', <add> 'ephox.agar.api.Chain', <add> 'ephox.agar.api.GeneralSteps', <add> 'ephox.agar.api.Logger', <ide> 'ephox.agar.api.Pipeline', <del> 'ephox.agar.api.RawAssertions', <ide> 'ephox.agar.api.Step', <add> 'ephox.agar.api.UiFinder', <ide> 'ephox.alloy.events.EventRegistry', <ide> 'ephox.compass.Arr', <ide> 'ephox.numerosity.api.JSON', <ide> 'ephox.peanut.Fun', <add> 'ephox.perhaps.Result', <add> 'ephox.sugar.api.Attr', <add> 'ephox.sugar.api.Compare', <ide> 'ephox.sugar.api.Element', <ide> 'ephox.sugar.api.Html', <ide> 'ephox.sugar.api.Insert', <ide> 'global!document' <ide> ], <ide> <del> function (Pipeline, RawAssertions, Step, EventRegistry, Arr, Json, Fun, Element, Html, Insert, document) { <add> function (Truncate, Assertions, Chain, GeneralSteps, Logger, Pipeline, Step, UiFinder, EventRegistry, Arr, Json, Fun, Result, Attr, Compare, Element, Html, Insert, document) { <ide> var success = arguments[arguments.length - 2]; <ide> var failure = arguments[arguments.length - 1]; <ide> <ide> '<div alloy-id="comp-2">' + <ide> '<div alloy-id="comp-3">' + <ide> '<div alloy-id="comp-4">' + <del> '<div alloy-id-"comp-5"></div>' + <add> '<div alloy-id="comp-5"></div>' + <ide> '</div>' + <ide> '</div>' + <ide> '</div>' + <ide> '</div>' <ide> ); <ide> <add> var isRoot = Fun.curry(Compare.eq, page); <add> <ide> Insert.append(body, page); <ide> <ide> var events = EventRegistry(); <ide> <del> events.registerId([ 'extraArgs' ], 'comp-1', { <add> events.registerId([ 'extra-args' ], 'comp-1', { <ide> 'event.alpha': function (extra) { <del> return 'f(' + extra + ')'; <add> return 'event.alpha.1(' + extra + ')'; <add> }, <add> 'event.only': function (extra) { <add> return 'event.only(' + extra + ')'; <add> } <add> }); <add> <add> events.registerId([ 'extra-args' ], 'comp-4', { <add> 'event.alpha': function (extra) { <add> return 'event.alpha.4(' + extra + ')'; <ide> } <ide> }); <ide> <ide> return Step.sync(function () { <ide> var filtered = events.filterByType(type); <ide> var raw = Arr.map(filtered, function (f) { <del> console.log('f', f); <ide> return { handler: f.handler(), id: f.id() }; <del> }); <add> }).sort(); <ide> <del> RawAssertions.assertEq('filter(' + type + ') = ' + Json.stringify(expected), expected, raw); <add> Assertions.assertEq('filter(' + type + ') = ' + Json.stringify(expected), expected, raw); <ide> }); <add> }; <add> <add> var sAssertNotFound = function (label, type, id) { <add> return Logger.t( <add> 'Test: ' + label + '\nLooking for handlers for id = ' + id + ' and event = ' + type + '. Should not find any', <add> GeneralSteps.sequence([ <add> Chain.asStep(page, [ <add> UiFinder.cFindIn('[alloy-id="' + id + '"]'), <add> Chain.binder(function (target) { <add> var handler = events.find(isRoot, type, target); <add> return handler.fold(function () { <add> return Result.value({ }); <add> }, function (h) { <add> return Result.error( <add> 'Unexpected handler found: ' + Json.stringify({ <add> element: Truncate.getHtml(h.element()), <add> handler: h.handler() <add> }) <add> ); <add> }); <add> }) <add> ]) <add> ]) <add> ); <add> }; <add> <add> var sAssertFind = function (label, expected, type, id) { <add> return Logger.t( <add> 'Test: ' + label + '\nLooking for handlers for id = ' + id + ' and event = ' + type, <add> GeneralSteps.sequence([ <add> Chain.asStep(page, [ <add> UiFinder.cFindIn('[alloy-id="' + id + '"]'), <add> Chain.binder(function (target) { <add> var handler = events.find(isRoot, type, target); <add> return handler.fold(function () { <add> return Result.error('Could not find handler'); <add> }, function (h) { <add> // TODO: Update to use named chains when they become available. <add> Assertions.assertEq('find(' + type + ', ' + id + ') = true', expected.target, Attr.get(h.element(), 'alloy-id')); <add> Assertions.assertEq('find(' + type + ', ' + id + ') = ' + Json.stringify(expected.handler), expected.handler, h.handler()); <add> return Result.value(h); <add> }); <add> }) <add> ]) <add> ]) <add> ); <ide> }; <ide> <ide> Pipeline.async({}, [ <ide> sAssertFilterByType([ ], 'event.none'), <ide> sAssertFilterByType([ <del> { handler: 'f(extraArgs)', id: 'comp-1' } <add> { handler: 'event.alpha.1(extra-args)', id: 'comp-1' }, <add> { handler: 'event.alpha.4(extra-args)', id: 'comp-4' } <ide> ], 'event.alpha' ), <ide> <del> <ide> <add> sAssertFind('comp-1!', { handler: 'event.alpha.1(extra-args)', target: 'comp-1' }, 'event.alpha', 'comp-1'), <add> <add> sAssertFind('comp-2 > comp-1', { handler: 'event.alpha.1(extra-args)', target: 'comp-1' }, 'event.alpha', 'comp-2'), <add> <add> sAssertFind('comp-3 > comp-2 > comp-1', { handler: 'event.alpha.1(extra-args)', target: 'comp-1' }, 'event.alpha', 'comp-3'), <add> <add> sAssertFind('comp-4!', { handler: 'event.alpha.4(extra-args)', target: 'comp-4' }, 'event.alpha', 'comp-4'), <add> <add> sAssertFind('comp-5 > comp-4!', { handler: 'event.alpha.4(extra-args)', target: 'comp-4' }, 'event.alpha', 'comp-5'), <add> <add> sAssertNotFound('comp-5 > comp-4 > comp-3 > comp-2 > comp-1 > NOT FOUND', 'event.beta', 'comp-5'), <add> <add> sAssertFind( <add> 'comp-5 > comp-4 > comp-3 > comp-2 > comp-1!', <add> { handler: 'event.only(extra-args)', target: 'comp-1' }, <add> 'event.only', 'comp-5' <add> ) <ide> ], function () { success(); }, failure); <ide> <ide> }
Java
apache-2.0
fff19bc2221d4ebd59f2934d8daeb3a0993169b3
0
rouazana/james,aduprat/james,aduprat/james,chibenwa/james,rouazana/james,rouazana/james,aduprat/james,chibenwa/james,chibenwa/james,chibenwa/james,rouazana/james,aduprat/james
/**************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * ****************************************************************/ package org.apache.james.smtpserver.mina; import java.util.LinkedList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.james.api.protocol.ProtocolHandlerChain; import org.apache.james.smtpserver.protocol.ConnectHandler; import org.apache.james.smtpserver.protocol.LineHandler; import org.apache.james.smtpserver.protocol.SMTPConfiguration; import org.apache.james.smtpserver.protocol.SMTPResponse; import org.apache.james.smtpserver.protocol.SMTPRetCode; import org.apache.james.smtpserver.protocol.SMTPSession; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.ssl.SslContextFactory; /** * This IoHandler handling the calling of ConnectHandler and LineHandlers * * */ public class SMTPIoHandler extends IoHandlerAdapter{ private Log logger; private ProtocolHandlerChain chain; private SMTPConfiguration conf; private SslContextFactory contextFactory; public SMTPIoHandler(ProtocolHandlerChain chain, SMTPConfiguration conf, Log logger) { this(chain,conf,logger,null); } public SMTPIoHandler(ProtocolHandlerChain chain, SMTPConfiguration conf, Log logger, SslContextFactory contextFactory) { this.chain = chain; this.conf = conf; this.logger = logger; this.contextFactory = contextFactory; } /** * @see org.apache.mina.core.service.IoHandlerAdapter#messageReceived(org.apache.mina.core.session.IoSession, java.lang.Object) */ public void messageReceived(IoSession session, Object message) throws Exception { SMTPSession smtpSession = (SMTPSession) session.getAttribute(SMTPSessionImpl.SMTP_SESSION); LinkedList<LineHandler> lineHandlers = chain.getHandlers(LineHandler.class); if (lineHandlers.size() > 0) { ((LineHandler) lineHandlers.getLast()).onLine(smtpSession, (String) message); } } /** * @see org.apache.mina.core.service.IoHandler#exceptionCaught(org.apache.mina.core.session.IoSession, * java.lang.Throwable) */ public void exceptionCaught(IoSession session, Throwable exception) throws Exception { logger.error("Caught exception: " + session.getCurrentWriteMessage(), exception); // write an error to the client if the session is stil connected if (session.isConnected()) session.write(new SMTPResponse(SMTPRetCode.LOCAL_ERROR, "Unable to process smtp request")); } /** * @see org.apache.mina.core.service.IoHandler#sessionCreated(org.apache.mina.core.session.IoSession) */ public void sessionCreated(IoSession session) throws Exception { SMTPSession smtpSession; if (contextFactory == null) { smtpSession= new SMTPSessionImpl(conf, logger, session); } else { smtpSession= new SMTPSessionImpl(conf, logger, session, contextFactory.newInstance()); } // Add attribute session.setAttribute(SMTPSessionImpl.SMTP_SESSION,smtpSession); } /** * @see org.apache.mina.core.service.IoHandler#sessionIdle(org.apache.mina.core.session.IoSession, * org.apache.mina.core.session.IdleStatus) */ public void sessionIdle(IoSession session, IdleStatus status) throws Exception { logger.debug("Connection timed out"); //session.write("Connection timeout"); } /** * @see org.apache.mina.core.service.IoHandler#sessionOpened(org.apache.mina.core.session.IoSession) */ public void sessionOpened(IoSession session) throws Exception { List<ConnectHandler> connectHandlers = chain .getHandlers(ConnectHandler.class); if (connectHandlers != null) { for (int i = 0; i < connectHandlers.size(); i++) { connectHandlers.get(i).onConnect( (SMTPSession) session.getAttribute(SMTPSessionImpl.SMTP_SESSION)); } } } }
smtpserver-function/src/main/java/org/apache/james/smtpserver/mina/SMTPIoHandler.java
/**************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * ****************************************************************/ package org.apache.james.smtpserver.mina; import java.util.LinkedList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.james.api.protocol.ProtocolHandlerChain; import org.apache.james.smtpserver.protocol.ConnectHandler; import org.apache.james.smtpserver.protocol.LineHandler; import org.apache.james.smtpserver.protocol.SMTPConfiguration; import org.apache.james.smtpserver.protocol.SMTPResponse; import org.apache.james.smtpserver.protocol.SMTPRetCode; import org.apache.james.smtpserver.protocol.SMTPSession; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.ssl.SslContextFactory; /** * This IoHandler handling the calling of ConnectHandler and LineHandlers * * */ public class SMTPIoHandler extends IoHandlerAdapter{ private Log logger; private ProtocolHandlerChain chain; private SMTPConfiguration conf; private SslContextFactory contextFactory; public SMTPIoHandler(ProtocolHandlerChain chain, SMTPConfiguration conf, Log logger) { this(chain,conf,logger,null); } public SMTPIoHandler(ProtocolHandlerChain chain, SMTPConfiguration conf, Log logger, SslContextFactory contextFactory) { this.chain = chain; this.conf = conf; this.logger = logger; this.contextFactory = contextFactory; } /** * @see org.apache.mina.core.service.IoHandlerAdapter#messageReceived(org.apache.mina.core.session.IoSession, java.lang.Object) */ public void messageReceived(IoSession session, Object message) throws Exception { SMTPSession smtpSession = (SMTPSession) session.getAttribute(SMTPSessionImpl.SMTP_SESSION); LinkedList<LineHandler> lineHandlers = chain.getHandlers(LineHandler.class); if (lineHandlers.size() > 0) { ((LineHandler) lineHandlers.getLast()).onLine(smtpSession, (String) message); } } /** * @see org.apache.mina.core.service.IoHandler#exceptionCaught(org.apache.mina.core.session.IoSession, * java.lang.Throwable) */ public void exceptionCaught(IoSession session, Throwable exception) throws Exception { logger.error("Caught exception: " + session.getCurrentWriteMessage(), exception); session.write(new SMTPResponse(SMTPRetCode.LOCAL_ERROR, "Unable to process smtp request")); } /** * @see org.apache.mina.core.service.IoHandler#sessionCreated(org.apache.mina.core.session.IoSession) */ public void sessionCreated(IoSession session) throws Exception { SMTPSession smtpSession; if (contextFactory == null) { smtpSession= new SMTPSessionImpl(conf, logger, session); } else { smtpSession= new SMTPSessionImpl(conf, logger, session, contextFactory.newInstance()); } // Add attributes session.setAttribute(SMTPSessionImpl.SMTP_SESSION,smtpSession); } /** * @see org.apache.mina.core.service.IoHandler#sessionIdle(org.apache.mina.core.session.IoSession, * org.apache.mina.core.session.IdleStatus) */ public void sessionIdle(IoSession session, IdleStatus status) throws Exception { logger.debug("Connection timed out"); session.write("Connection timeout"); } /** * @see org.apache.mina.core.service.IoHandler#sessionOpened(org.apache.mina.core.session.IoSession) */ public void sessionOpened(IoSession session) throws Exception { List<ConnectHandler> connectHandlers = chain .getHandlers(ConnectHandler.class); if (connectHandlers != null) { for (int i = 0; i < connectHandlers.size(); i++) { connectHandlers.get(i).onConnect( (SMTPSession) session.getAttribute(SMTPSessionImpl.SMTP_SESSION)); } } } }
Only write error back to client if the session is still connected git-svn-id: de9d04cf23151003780adc3e4ddb7078e3680318@900564 13f79535-47bb-0310-9956-ffa450edef68
smtpserver-function/src/main/java/org/apache/james/smtpserver/mina/SMTPIoHandler.java
Only write error back to client if the session is still connected
<ide><path>mtpserver-function/src/main/java/org/apache/james/smtpserver/mina/SMTPIoHandler.java <ide> logger.error("Caught exception: " + session.getCurrentWriteMessage(), <ide> exception); <ide> <del> session.write(new SMTPResponse(SMTPRetCode.LOCAL_ERROR, "Unable to process smtp request")); <add> // write an error to the client if the session is stil connected <add> if (session.isConnected()) session.write(new SMTPResponse(SMTPRetCode.LOCAL_ERROR, "Unable to process smtp request")); <ide> } <ide> <ide> /** <ide> } else { <ide> smtpSession= new SMTPSessionImpl(conf, logger, session, contextFactory.newInstance()); <ide> } <del> // Add attributes <del> <add> <add> // Add attribute <ide> session.setAttribute(SMTPSessionImpl.SMTP_SESSION,smtpSession); <ide> } <ide> <ide> public void sessionIdle(IoSession session, IdleStatus status) <ide> throws Exception { <ide> logger.debug("Connection timed out"); <del> session.write("Connection timeout"); <add> //session.write("Connection timeout"); <ide> } <ide> <ide> /**
Java
lgpl-2.1
4c0b6fac4db43eccde09177da6e86cbe7230dd9c
0
exedio/copernica,exedio/copernica,exedio/copernica
/* * Copyright (C) 2004-2005 exedio GmbH (www.exedio.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.exedio.cope; import java.sql.SQLException; import org.hsqldb.jdbcDriver; import com.exedio.dsmf.HsqldbDriver; final class HsqldbDatabase extends Database implements DatabaseTimestampCapable { static { try { Class.forName(jdbcDriver.class.getName()); } catch(ClassNotFoundException e) { throw new NestingRuntimeException(e); } } protected HsqldbDatabase(final Properties properties) { super(new HsqldbDriver(), properties); } String getIntegerType(final int precision) { // TODO: use precision to select between TINYINT, SMALLINT, INTEGER, BIGINT, NUMBER return (precision <= 10) ? "integer" : "bigint"; } String getDoubleType(final int precision) { return "double"; } String getStringType(final int maxLength) { return "varchar("+maxLength+")"; } String getDayType() { return "date"; } public String getDateTimestampType() { return "timestamp"; } boolean isLimitClauseInSelect() { return true; } boolean appendLimitClause(final Statement bf, final int start, final int count) { // TODO: use appendValue to support prepared statements bf.append(" limit "). append(start). append(' '). append(count!=Query.UNLIMITED_COUNT ? count : 0); return true; } protected boolean supportsRightOuterJoins() { return false; } private final String extractConstraintName(final SQLException e, final int vendorCode, final String start) { //System.out.println("-u-"+e.getClass()+" "+e.getCause()+" "+e.getErrorCode()+" "+e.getLocalizedMessage()+" "+e.getSQLState()+" "+e.getNextException()); if(e.getErrorCode()!=vendorCode) return null; final String m = e.getMessage(); if(m.startsWith(start)) { final int startLength = start.length(); final int pos = m.indexOf(' ', startLength); return (pos<0) ? m.substring(startLength) : m.substring(startLength, pos); } else return null; } protected String extractUniqueConstraintName(final SQLException e) { return extractConstraintName(e, -104, "Unique constraint violation: "); } }
lib/hsqldbsrc/com/exedio/cope/HsqldbDatabase.java
/* * Copyright (C) 2004-2005 exedio GmbH (www.exedio.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.exedio.cope; import java.sql.SQLException; import org.hsqldb.jdbcDriver; import com.exedio.dsmf.HsqldbDriver; final class HsqldbDatabase extends Database implements DatabaseTimestampCapable { static { try { Class.forName(jdbcDriver.class.getName()); } catch(ClassNotFoundException e) { throw new NestingRuntimeException(e); } } protected HsqldbDatabase(final Properties properties) { super(new HsqldbDriver(), properties); } String getIntegerType(final int precision) { // TODO: use precision to select between TINYINT, SMALLINT, INTEGER, BIGINT, NUMBER return (precision <= 10) ? "integer" : "bigint"; } String getDoubleType(final int precision) { return "double"; } String getStringType(final int maxLength) { return "varchar("+maxLength+")"; } String getDayType() { return "date"; } public String getDateTimestampType() { return "timestamp"; } boolean isLimitClauseInSelect() { return true; } boolean appendLimitClause(final Statement bf, final int start, final int count) { // TODO: use appendValue to support prepared statements bf.append(" limit "). append(start). append(' '). append(count!=Query.UNLIMITED_COUNT ? count : 0); return true; } protected boolean supportsRightOuterJoins() { return false; } private final String extractConstraintName(final SQLException e, final int vendorCode, final String start, final char end) { //System.out.println("-u-"+e.getClass()+" "+e.getCause()+" "+e.getErrorCode()+" "+e.getLocalizedMessage()+" "+e.getSQLState()+" "+e.getNextException()); if(e.getErrorCode()!=vendorCode) return null; final String m = e.getMessage(); if(m.startsWith(start)) { if(end=='\0') return m.substring(start.length()); else { final int pos = m.indexOf(end, start.length()); if(pos<0) return null; return m.substring(start.length(), pos); } } else return null; } protected String extractUniqueConstraintName(final SQLException e) { return extractConstraintName(e, -104, "Unique constraint violation: ", '\0'); } }
make extractConstraintName more defensive, preparation for prepared statements git-svn-id: 9dbc6da3594b32e13bcf3b3752e372ea5bc7c2cc@3707 e7d4fc99-c606-0410-b9bf-843393a9eab7
lib/hsqldbsrc/com/exedio/cope/HsqldbDatabase.java
make extractConstraintName more defensive, preparation for prepared statements
<ide><path>ib/hsqldbsrc/com/exedio/cope/HsqldbDatabase.java <ide> return false; <ide> } <ide> <del> private final String extractConstraintName(final SQLException e, final int vendorCode, final String start, final char end) <add> private final String extractConstraintName(final SQLException e, final int vendorCode, final String start) <ide> { <ide> //System.out.println("-u-"+e.getClass()+" "+e.getCause()+" "+e.getErrorCode()+" "+e.getLocalizedMessage()+" "+e.getSQLState()+" "+e.getNextException()); <ide> <ide> final String m = e.getMessage(); <ide> if(m.startsWith(start)) <ide> { <del> if(end=='\0') <del> return m.substring(start.length()); <del> else <del> { <del> final int pos = m.indexOf(end, start.length()); <del> if(pos<0) <del> return null; <del> return m.substring(start.length(), pos); <del> } <add> final int startLength = start.length(); <add> final int pos = m.indexOf(' ', startLength); <add> return (pos<0) ? m.substring(startLength) : m.substring(startLength, pos); <ide> } <ide> else <ide> return null; <ide> <ide> protected String extractUniqueConstraintName(final SQLException e) <ide> { <del> return extractConstraintName(e, -104, "Unique constraint violation: ", '\0'); <add> return extractConstraintName(e, -104, "Unique constraint violation: "); <ide> } <ide> <ide> }
Java
apache-2.0
30ac2a53fc5fc3de69d07787d149e237a651b77e
0
synthetichealth/synthea,synthetichealth/synthea,synthetichealth/synthea
package org.mitre.synthea.helpers; import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.dataformat.csv.CsvMapper; import com.fasterxml.jackson.dataformat.csv.CsvSchema; import com.fasterxml.jackson.dataformat.csv.CsvSchema.ColumnType; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Helper class to translate CSV data back and forth between raw string data and a simple data * structure. */ public class SimpleCSV { /** * Parse the data from the given CSV file into a List of Maps, where the key is the * column name. Uses a LinkedHashMap specifically to ensure the order of columns is preserved in * the resulting maps. * * @param csvData * Raw CSV data * @return parsed data * @throws IOException * if any exception occurs while parsing the data */ public static List<LinkedHashMap<String, String>> parse(String csvData) throws IOException { // Read schema from the first line; start with bootstrap instance // to enable reading of schema from the first line // NOTE: reads schema and uses it for binding CsvMapper mapper = new CsvMapper(); // use first row as header; otherwise defaults are fine CsvSchema schema = CsvSchema.emptySchema().withHeader(); MappingIterator<LinkedHashMap<String, String>> it = mapper.readerFor(LinkedHashMap.class) .with(schema).readValues(csvData); return it.readAll(); } /** * Parse the data from the given CSV file into an Iterator of Maps, where the key is the * column name. Uses a LinkedHashMap specifically to ensure the order of columns is preserved in * the resulting maps. Uses an Iterator, as opposed to a list, in order to parse line by line and * avoid memory overload. * * @param csvData * Raw CSV data * @return parsed data * @throws IOException * if any exception occurs while parsing the data */ public static Iterator<LinkedHashMap<String, String>> parseLineByLine(String csvData) throws IOException { CsvMapper mapper = new CsvMapper(); // use first row as header; otherwise defaults are fine CsvSchema schema = CsvSchema.emptySchema().withHeader(); MappingIterator<LinkedHashMap<String, String>> it = mapper.readerFor(LinkedHashMap.class) .with(schema).readValues(csvData); return it; } /** * Convert the data in the given List of Maps to a String of CSV data. * Each Map in the List represents one line of the resulting CSV. Uses the keySet from the * first Map to populate the set of columns. This means that the first Map must contain all * the columns desired in the final CSV. The order of the columns is specified by the order * provided by the first Map's keySet, so using an ordered Map implementation * (such as LinkedHashMap) is recommended. * * @param data List of Map data. CSV data read/modified from SimpleCSV.parse(...) * @return data formatted as a String containing raw CSV data * @throws IOException on file IO write errors. */ public static String unparse(List<? extends Map<String, String>> data) throws IOException { CsvMapper mapper = new CsvMapper(); CsvSchema.Builder schemaBuilder = CsvSchema.builder(); schemaBuilder.setUseHeader(true); Collection<String> columns = data.get(0).keySet(); schemaBuilder.addColumns(columns, ColumnType.STRING); return mapper.writer(schemaBuilder.build()).writeValueAsString(data); } }
src/main/java/org/mitre/synthea/helpers/SimpleCSV.java
package org.mitre.synthea.helpers; import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.dataformat.csv.CsvMapper; import com.fasterxml.jackson.dataformat.csv.CsvSchema; import com.fasterxml.jackson.dataformat.csv.CsvSchema.ColumnType; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Helper class to translate CSV data back and forth between raw string data and a simple data * structure. */ public class SimpleCSV { /** * Parse the data from the given CSV file into a List of Maps, where the key is the * column name. Uses a LinkedHashMap specifically to ensure the order of columns is preserved in * the resulting maps. * * @param csvData * Raw CSV data * @return parsed data * @throws IOException * if any exception occurs while parsing the data */ public static List<LinkedHashMap<String, String>> parse(String csvData) throws IOException { // Read schema from the first line; start with bootstrap instance // to enable reading of schema from the first line // NOTE: reads schema and uses it for binding CsvMapper mapper = new CsvMapper(); // use first row as header; otherwise defaults are fine CsvSchema schema = CsvSchema.emptySchema().withHeader(); MappingIterator<LinkedHashMap<String, String>> it = mapper.readerFor(LinkedHashMap.class) .with(schema).readValues(csvData); return it.readAll(); } /** * Parse the data from the given CSV file into an Iterator of Maps, where the key is the * column name. Uses a LinkedHashMap specifically to ensure the order of columns is preserved in * the resulting maps. Uses an Iterator, as opposed to a list, in order to parse line by line and * avoid memory overload. * * @param csvData * Raw CSV data * @return parsed data * @throws IOException * if any exception occurs while parsing the data */ public static Iterator<LinkedHashMap<String, String>> parseLineByLine(String csvData) throws IOException { CsvMapper mapper = new CsvMapper(); // use first row as header; otherwise defaults are fine CsvSchema schema = CsvSchema.emptySchema().withHeader(); MappingIterator<LinkedHashMap<String, String>> it = mapper.readerFor(LinkedHashMap.class) .with(schema).readValues(csvData); return it; } /** * Convert the data in the given List of Maps to a String of CSV data. * Each Map in the List represents one line of the resulting CSV. Uses the keySet from the * first Map to populate the set of columns. This means that the first Map must contain all * the columns desired in the final CSV. The order of the columns is specified by the order * provided by the first Map's keySet, so using an ordered Map implementation * (such as LinkedHashMap) is recommended. * * @param data List of Map data. CSV data read/modified from SimpleCSV.parse(...) * @return data formatted as a String containing raw CSV data * @throws IOException on file IO write errors. */ public static String unparse(List<? extends Map<String, String>> data) throws IOException { CsvMapper mapper = new CsvMapper(); CsvSchema.Builder schemaBuilder = CsvSchema.builder(); schemaBuilder.setUseHeader(true); Collection<String> columns = data.get(0).keySet(); schemaBuilder.addColumns(columns, ColumnType.STRING); return mapper.writer(schemaBuilder.build()).writeValueAsString(data); } }
Remove whitespace.
src/main/java/org/mitre/synthea/helpers/SimpleCSV.java
Remove whitespace.
<ide><path>rc/main/java/org/mitre/synthea/helpers/SimpleCSV.java <ide> <ide> MappingIterator<LinkedHashMap<String, String>> it = mapper.readerFor(LinkedHashMap.class) <ide> .with(schema).readValues(csvData); <del> <ide> <ide> return it.readAll(); <ide> }
Java
agpl-3.0
cacb032fc46d76632d0384fe235c37c47e899291
0
mbrossard/cryptonit-cloud,mbrossard/cryptonit-cloud,mbrossard/cryptonit-cloud
package org.cryptonit.cloud.timestamping; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import org.bouncycastle.tsp.TSPException; import org.bouncycastle.tsp.TimeStampRequest; import org.bouncycastle.tsp.TimeStampResponse; import org.cryptonit.cloud.interfaces.TimestampingAuthority; import org.cryptonit.cloud.interfaces.TimestampingAuthorityFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Mathias Brossard */ @Path("/timestamp") public class Application { private static final Logger LOGGER = LoggerFactory.getLogger(Application.class); private static TimestampingAuthorityFactory tsaFactory = null; @POST @Consumes("application/timestamp-query") @Produces("application/timestamp-reply") public Response timestamp(@Context HttpServletRequest request, @Context HttpHeaders headers) throws IOException, TSPException { TimeStampRequest tsq = new TimeStampRequest(request.getInputStream()); TimestampingAuthority tsa = tsaFactory.getTimestampingAuthority(request.getServerName()); TimeStampResponse tsr = tsa.timestamp(tsq); return Response.ok(tsr.getEncoded()).build(); } public static void setTimestampingAuthorityFactory(TimestampingAuthorityFactory factory) { tsaFactory = factory; } }
src/main/java/org/cryptonit/cloud/timestamping/Application.java
package org.cryptonit.cloud.timestamping; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import org.bouncycastle.tsp.TSPException; import org.bouncycastle.tsp.TimeStampRequest; import org.bouncycastle.tsp.TimeStampResponse; import org.cryptonit.cloud.interfaces.TimestampingAuthority; import org.cryptonit.cloud.interfaces.TimestampingAuthorityFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Mathias Brossard */ @Path("/timestamp") public class Application { private static final Logger LOGGER = LoggerFactory.getLogger(Application.class); private static TimestampingAuthorityFactory tsaFactory = null; @POST public Response timestamp(@Context HttpServletRequest request, @Context HttpHeaders headers) throws IOException, TSPException { TimeStampRequest tsq = new TimeStampRequest(request.getInputStream()); TimestampingAuthority tsa = tsaFactory.getTimestampingAuthority(request.getServerName()); TimeStampResponse tsr = tsa.timestamp(tsq); return Response.ok(tsr.getEncoded()).build(); } public static void setTimestampingAuthorityFactory(TimestampingAuthorityFactory factory) { tsaFactory = factory; } }
Add content types to POST
src/main/java/org/cryptonit/cloud/timestamping/Application.java
Add content types to POST
<ide><path>rc/main/java/org/cryptonit/cloud/timestamping/Application.java <ide> <ide> import java.io.IOException; <ide> import javax.servlet.http.HttpServletRequest; <add>import javax.ws.rs.Consumes; <ide> import javax.ws.rs.POST; <ide> import javax.ws.rs.Path; <add>import javax.ws.rs.Produces; <ide> import javax.ws.rs.core.Context; <ide> import javax.ws.rs.core.HttpHeaders; <ide> import javax.ws.rs.core.Response; <ide> private static TimestampingAuthorityFactory tsaFactory = null; <ide> <ide> @POST <add> @Consumes("application/timestamp-query") <add> @Produces("application/timestamp-reply") <ide> public Response timestamp(@Context HttpServletRequest request, <ide> @Context HttpHeaders headers) throws IOException, TSPException { <ide> TimeStampRequest tsq = new TimeStampRequest(request.getInputStream());
Java
apache-2.0
8b216bb87c7760439f76cdd1366c87d8461a851c
0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.jdisc.http.server.jetty; import com.google.inject.AbstractModule; import com.google.inject.Module; import com.yahoo.container.logging.ConnectionLog; import com.yahoo.container.logging.ConnectionLogEntry; import com.yahoo.container.logging.ConnectionLogEntry.SslHandshakeFailure.ExceptionEntry; import com.yahoo.container.logging.RequestLog; import com.yahoo.container.logging.RequestLogEntry; import com.yahoo.jdisc.References; import com.yahoo.jdisc.Request; import com.yahoo.jdisc.Response; import com.yahoo.jdisc.application.BindingSetSelector; import com.yahoo.jdisc.application.MetricConsumer; import com.yahoo.jdisc.handler.AbstractRequestHandler; import com.yahoo.jdisc.handler.CompletionHandler; import com.yahoo.jdisc.handler.ContentChannel; import com.yahoo.jdisc.handler.NullContent; import com.yahoo.jdisc.handler.RequestHandler; import com.yahoo.jdisc.handler.ResponseDispatch; import com.yahoo.jdisc.handler.ResponseHandler; import com.yahoo.jdisc.http.ConnectorConfig; import com.yahoo.jdisc.http.ConnectorConfig.Throttling; import com.yahoo.jdisc.http.Cookie; import com.yahoo.jdisc.http.HttpRequest; import com.yahoo.jdisc.http.HttpResponse; import com.yahoo.jdisc.http.ServerConfig; import com.yahoo.jdisc.http.server.jetty.TestDrivers.TlsClientAuth; import com.yahoo.jdisc.service.BindingSetNotFoundException; import com.yahoo.security.KeyUtils; import com.yahoo.security.Pkcs10Csr; import com.yahoo.security.Pkcs10CsrBuilder; import com.yahoo.security.SslContextBuilder; import com.yahoo.security.X509CertificateBuilder; import com.yahoo.security.X509CertificateUtils; import com.yahoo.security.tls.TlsContext; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.FormBodyPart; import org.apache.http.entity.mime.content.StringBody; import org.assertj.core.api.Assertions; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.ProxyProtocolClientConnectionFactory.V1; import org.eclipse.jetty.client.ProxyProtocolClientConnectionFactory.V2; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.server.handler.AbstractHandlerContainer; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import javax.net.ssl.SSLHandshakeException; import javax.security.auth.x500.X500Principal; import java.io.IOException; import java.math.BigInteger; import java.net.BindException; import java.net.URI; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.security.KeyPair; import java.security.PrivateKey; import java.security.cert.X509Certificate; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import static com.yahoo.jdisc.Response.Status.GATEWAY_TIMEOUT; import static com.yahoo.jdisc.Response.Status.INTERNAL_SERVER_ERROR; import static com.yahoo.jdisc.Response.Status.NOT_FOUND; import static com.yahoo.jdisc.Response.Status.OK; import static com.yahoo.jdisc.Response.Status.REQUEST_URI_TOO_LONG; import static com.yahoo.jdisc.Response.Status.UNAUTHORIZED; import static com.yahoo.jdisc.Response.Status.UNSUPPORTED_MEDIA_TYPE; import static com.yahoo.jdisc.http.HttpHeaders.Names.CONNECTION; import static com.yahoo.jdisc.http.HttpHeaders.Names.CONTENT_TYPE; import static com.yahoo.jdisc.http.HttpHeaders.Names.COOKIE; import static com.yahoo.jdisc.http.HttpHeaders.Names.X_DISABLE_CHUNKING; import static com.yahoo.jdisc.http.HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED; import static com.yahoo.jdisc.http.HttpHeaders.Values.CLOSE; import static com.yahoo.jdisc.http.server.jetty.SimpleHttpClient.ResponseValidator; import static com.yahoo.security.KeyAlgorithm.EC; import static com.yahoo.security.SignatureAlgorithm.SHA256_WITH_ECDSA; import static org.cthul.matchers.CthulMatchers.containsPattern; import static org.cthul.matchers.CthulMatchers.matchesPattern; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.startsWith; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.anyOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeTrue; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * @author Oyvind Bakksjo * @author Simon Thoresen Hult * @author bjorncs */ public class HttpServerTest { private static final Logger log = Logger.getLogger(HttpServerTest.class.getName()); @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); @Test public void requireThatServerCanListenToRandomPort() throws Exception { final TestDriver driver = TestDrivers.newInstance(mockRequestHandler()); assertNotEquals(0, driver.server().getListenPort()); assertTrue(driver.close()); } @Test public void requireThatServerCanNotListenToBoundPort() throws Exception { final TestDriver driver = TestDrivers.newInstance(mockRequestHandler()); try { TestDrivers.newConfiguredInstance( mockRequestHandler(), new ServerConfig.Builder(), new ConnectorConfig.Builder() .listenPort(driver.server().getListenPort()) ); } catch (final Throwable t) { assertThat(t.getCause(), instanceOf(BindException.class)); } assertTrue(driver.close()); } @Test public void requireThatBindingSetNotFoundReturns404() throws Exception { final TestDriver driver = TestDrivers.newConfiguredInstance( mockRequestHandler(), new ServerConfig.Builder() .developerMode(true), new ConnectorConfig.Builder(), newBindingSetSelector("unknown")); driver.client().get("/status.html") .expectStatusCode(is(NOT_FOUND)) .expectContent(containsPattern(Pattern.compile( Pattern.quote(BindingSetNotFoundException.class.getName()) + ": No binding set named &apos;unknown&apos;\\.\n\tat .+", Pattern.DOTALL | Pattern.MULTILINE))); assertTrue(driver.close()); } @Test public void requireThatTooLongInitLineReturns414() throws Exception { final TestDriver driver = TestDrivers.newConfiguredInstance( mockRequestHandler(), new ServerConfig.Builder(), new ConnectorConfig.Builder() .requestHeaderSize(1)); driver.client().get("/status.html") .expectStatusCode(is(REQUEST_URI_TOO_LONG)); assertTrue(driver.close()); } @Test public void requireThatAccessLogIsCalledForRequestRejectedByJetty() throws Exception { BlockingQueueRequestLog requestLogMock = new BlockingQueueRequestLog(); final TestDriver driver = TestDrivers.newConfiguredInstance( mockRequestHandler(), new ServerConfig.Builder(), new ConnectorConfig.Builder().requestHeaderSize(1), binder -> binder.bind(RequestLog.class).toInstance(requestLogMock)); driver.client().get("/status.html") .expectStatusCode(is(REQUEST_URI_TOO_LONG)); RequestLogEntry entry = requestLogMock.poll(Duration.ofSeconds(30)); assertEquals(414, entry.statusCode().getAsInt()); assertThat(driver.close(), is(true)); } @Test public void requireThatServerCanEcho() throws Exception { final TestDriver driver = TestDrivers.newInstance(new EchoRequestHandler()); driver.client().get("/status.html") .expectStatusCode(is(OK)); assertTrue(driver.close()); } @Test public void requireThatServerCanEchoCompressed() throws Exception { final TestDriver driver = TestDrivers.newInstance(new EchoRequestHandler()); SimpleHttpClient client = driver.newClient(true); client.get("/status.html") .expectStatusCode(is(OK)); assertTrue(driver.close()); } @Test public void requireThatServerCanHandleMultipleRequests() throws Exception { final TestDriver driver = TestDrivers.newInstance(new EchoRequestHandler()); driver.client().get("/status.html") .expectStatusCode(is(OK)); driver.client().get("/status.html") .expectStatusCode(is(OK)); assertTrue(driver.close()); } @Test public void requireThatFormPostWorks() throws Exception { final TestDriver driver = TestDrivers.newInstance(new ParameterPrinterRequestHandler()); final String requestContent = generateContent('a', 30); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .setContent(requestContent) .execute(); response.expectStatusCode(is(OK)) .expectContent(startsWith('{' + requestContent + "=[]}")); assertTrue(driver.close()); } @Test public void requireThatFormPostDoesNotRemoveContentByDefault() throws Exception { final TestDriver driver = TestDrivers.newInstance(new ParameterPrinterRequestHandler()); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .setContent("foo=bar") .execute(); response.expectStatusCode(is(OK)) .expectContent(is("{foo=[bar]}foo=bar")); assertTrue(driver.close()); } @Test public void requireThatFormPostKeepsContentWhenConfiguredTo() throws Exception { final TestDriver driver = newDriverWithFormPostContentRemoved(new ParameterPrinterRequestHandler(), false); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .setContent("foo=bar") .execute(); response.expectStatusCode(is(OK)) .expectContent(is("{foo=[bar]}foo=bar")); assertTrue(driver.close()); } @Test public void requireThatFormPostRemovesContentWhenConfiguredTo() throws Exception { final TestDriver driver = newDriverWithFormPostContentRemoved(new ParameterPrinterRequestHandler(), true); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .setContent("foo=bar") .execute(); response.expectStatusCode(is(OK)) .expectContent(is("{foo=[bar]}")); assertTrue(driver.close()); } @Test public void requireThatFormPostWithCharsetSpecifiedWorks() throws Exception { final TestDriver driver = TestDrivers.newInstance(new ParameterPrinterRequestHandler()); final String requestContent = generateContent('a', 30); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(X_DISABLE_CHUNKING, "true") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED + ";charset=UTF-8") .setContent(requestContent) .execute(); response.expectStatusCode(is(OK)) .expectContent(startsWith('{' + requestContent + "=[]}")); assertTrue(driver.close()); } @Test public void requireThatEmptyFormPostWorks() throws Exception { final TestDriver driver = TestDrivers.newInstance(new ParameterPrinterRequestHandler()); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .execute(); response.expectStatusCode(is(OK)) .expectContent(is("{}")); assertTrue(driver.close()); } @Test public void requireThatFormParametersAreParsed() throws Exception { final TestDriver driver = TestDrivers.newInstance(new ParameterPrinterRequestHandler()); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .setContent("a=b&c=d") .execute(); response.expectStatusCode(is(OK)) .expectContent(startsWith("{a=[b], c=[d]}")); assertTrue(driver.close()); } @Test public void requireThatUriParametersAreParsed() throws Exception { final TestDriver driver = TestDrivers.newInstance(new ParameterPrinterRequestHandler()); final ResponseValidator response = driver.client().newPost("/status.html?a=b&c=d") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .execute(); response.expectStatusCode(is(OK)) .expectContent(is("{a=[b], c=[d]}")); assertTrue(driver.close()); } @Test public void requireThatFormAndUriParametersAreMerged() throws Exception { final TestDriver driver = TestDrivers.newInstance(new ParameterPrinterRequestHandler()); final ResponseValidator response = driver.client().newPost("/status.html?a=b&c=d1") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .setContent("c=d2&e=f") .execute(); response.expectStatusCode(is(OK)) .expectContent(startsWith("{a=[b], c=[d1, d2], e=[f]}")); assertTrue(driver.close()); } @Test public void requireThatFormCharsetIsHonored() throws Exception { final TestDriver driver = newDriverWithFormPostContentRemoved(new ParameterPrinterRequestHandler(), true); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED + ";charset=ISO-8859-1") .setBinaryContent(new byte[]{66, (byte) 230, 114, 61, 98, 108, (byte) 229}) .execute(); response.expectStatusCode(is(OK)) .expectContent(is("{B\u00e6r=[bl\u00e5]}")); assertTrue(driver.close()); } @Test public void requireThatUnknownFormCharsetIsTreatedAsBadRequest() throws Exception { final TestDriver driver = TestDrivers.newInstance(new ParameterPrinterRequestHandler()); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED + ";charset=FLARBA-GARBA-7") .setContent("a=b") .execute(); response.expectStatusCode(is(UNSUPPORTED_MEDIA_TYPE)); assertTrue(driver.close()); } @Test public void requireThatFormPostWithPercentEncodedContentIsDecoded() throws Exception { final TestDriver driver = TestDrivers.newInstance(new ParameterPrinterRequestHandler()); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .setContent("%20%3D%C3%98=%22%25+") .execute(); response.expectStatusCode(is(OK)) .expectContent(startsWith("{ =\u00d8=[\"% ]}")); assertTrue(driver.close()); } @Test public void requireThatFormPostWithThrowingHandlerIsExceptionSafe() throws Exception { final TestDriver driver = TestDrivers.newInstance(new ThrowingHandler()); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .setContent("a=b") .execute(); response.expectStatusCode(is(INTERNAL_SERVER_ERROR)); assertTrue(driver.close()); } @Test public void requireThatMultiPostWorks() throws Exception { // This is taken from tcpdump of bug 5433352 and reassembled here to see that httpserver passes things on. final String startTxtContent = "this is a test for POST."; final String updaterConfContent = "identifier = updater\n" + "server_type = gds\n"; final TestDriver driver = TestDrivers.newInstance(new EchoRequestHandler()); final ResponseValidator response = driver.client().newPost("/status.html") .setMultipartContent( newFileBody("", "start.txt", startTxtContent), newFileBody("", "updater.conf", updaterConfContent)) .execute(); response.expectStatusCode(is(OK)) .expectContent(containsString(startTxtContent)) .expectContent(containsString(updaterConfContent)); } @Test public void requireThatRequestCookiesAreReceived() throws Exception { final TestDriver driver = TestDrivers.newInstance(new CookiePrinterRequestHandler()); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(COOKIE, "foo=bar") .execute(); response.expectStatusCode(is(OK)) .expectContent(containsString("[foo=bar]")); assertTrue(driver.close()); } @Test public void requireThatSetCookieHeaderIsCorrect() throws Exception { final TestDriver driver = TestDrivers.newInstance(new CookieSetterRequestHandler( new Cookie("foo", "bar") .setDomain(".localhost") .setHttpOnly(true) .setPath("/foopath") .setSecure(true))); driver.client().get("/status.html") .expectStatusCode(is(OK)) .expectHeader("Set-Cookie", is("foo=bar; Path=/foopath; Domain=.localhost; Secure; HttpOnly")); assertTrue(driver.close()); } @Test public void requireThatTimeoutWorks() throws Exception { final UnresponsiveHandler requestHandler = new UnresponsiveHandler(); final TestDriver driver = TestDrivers.newInstance(requestHandler); driver.client().get("/status.html") .expectStatusCode(is(GATEWAY_TIMEOUT)); ResponseDispatch.newInstance(OK).dispatch(requestHandler.responseHandler); assertTrue(driver.close()); } // Header with no value is disallowed by https://tools.ietf.org/html/rfc7230#section-3.2 // Details in https://github.com/eclipse/jetty.project/issues/1116 @Test public void requireThatHeaderWithNullValueIsOmitted() throws Exception { final TestDriver driver = TestDrivers.newInstance(new EchoWithHeaderRequestHandler("X-Foo", null)); driver.client().get("/status.html") .expectStatusCode(is(OK)) .expectNoHeader("X-Foo"); assertTrue(driver.close()); } // Header with empty value is allowed by https://tools.ietf.org/html/rfc7230#section-3.2 // Details in https://github.com/eclipse/jetty.project/issues/1116 @Test public void requireThatHeaderWithEmptyValueIsAllowed() throws Exception { final TestDriver driver = TestDrivers.newInstance(new EchoWithHeaderRequestHandler("X-Foo", "")); driver.client().get("/status.html") .expectStatusCode(is(OK)) .expectHeader("X-Foo", is("")); assertTrue(driver.close()); } @Test public void requireThatNoConnectionHeaderMeansKeepAliveInHttp11KeepAliveDisabled() throws Exception { final TestDriver driver = TestDrivers.newInstance(new EchoWithHeaderRequestHandler(CONNECTION, CLOSE)); driver.client().get("/status.html") .expectHeader(CONNECTION, is(CLOSE)); assertThat(driver.close(), is(true)); } @Test public void requireThatConnectionIsClosedAfterXRequests() throws Exception { final int MAX_KEEPALIVE_REQUESTS = 100; final TestDriver driver = TestDrivers.newConfiguredInstance(new EchoRequestHandler(), new ServerConfig.Builder(), new ConnectorConfig.Builder().maxRequestsPerConnection(MAX_KEEPALIVE_REQUESTS)); for (int i = 0; i < MAX_KEEPALIVE_REQUESTS - 1; i++) { driver.client().get("/status.html") .expectStatusCode(is(OK)) .expectNoHeader(CONNECTION); } driver.client().get("/status.html") .expectStatusCode(is(OK)) .expectHeader(CONNECTION, is(CLOSE)); assertTrue(driver.close()); } @Test public void requireThatServerCanRespondToSslRequest() throws Exception { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); final TestDriver driver = TestDrivers.newInstanceWithSsl(new EchoRequestHandler(), certificateFile, privateKeyFile, TlsClientAuth.WANT); driver.client().get("/status.html") .expectStatusCode(is(OK)); assertTrue(driver.close()); } @Test public void requireThatTlsClientAuthenticationEnforcerRejectsRequestsForNonWhitelistedPaths() throws IOException { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); TestDriver driver = TestDrivers.newInstanceWithSsl(new EchoRequestHandler(), certificateFile, privateKeyFile, TlsClientAuth.WANT); SSLContext trustStoreOnlyCtx = new SslContextBuilder() .withTrustStore(certificateFile) .build(); new SimpleHttpClient(trustStoreOnlyCtx, driver.server().getListenPort(), false) .get("/dummy.html") .expectStatusCode(is(UNAUTHORIZED)); assertTrue(driver.close()); } @Test public void requireThatTlsClientAuthenticationEnforcerAllowsRequestForWhitelistedPaths() throws IOException { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); TestDriver driver = TestDrivers.newInstanceWithSsl(new EchoRequestHandler(), certificateFile, privateKeyFile, TlsClientAuth.WANT); SSLContext trustStoreOnlyCtx = new SslContextBuilder() .withTrustStore(certificateFile) .build(); new SimpleHttpClient(trustStoreOnlyCtx, driver.server().getListenPort(), false) .get("/status.html") .expectStatusCode(is(OK)); assertTrue(driver.close()); } @Test public void requireThatConnectedAtReturnsNonZero() throws Exception { final TestDriver driver = TestDrivers.newInstance(new ConnectedAtRequestHandler()); driver.client().get("/status.html") .expectStatusCode(is(OK)) .expectContent(matchesPattern("\\d{13,}")); assertThat(driver.close(), is(true)); } @Test public void requireThatGzipEncodingRequestsAreAutomaticallyDecompressed() throws Exception { TestDriver driver = TestDrivers.newInstance(new ParameterPrinterRequestHandler()); String requestContent = generateContent('a', 30); ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .setGzipContent(requestContent) .execute(); response.expectStatusCode(is(OK)) .expectContent(startsWith('{' + requestContent + "=[]}")); assertTrue(driver.close()); } @Test public void requireThatResponseStatsAreCollected() throws Exception { RequestTypeHandler handler = new RequestTypeHandler(); TestDriver driver = TestDrivers.newInstance(handler); HttpResponseStatisticsCollector statisticsCollector = ((AbstractHandlerContainer) driver.server().server().getHandler()) .getChildHandlerByClass(HttpResponseStatisticsCollector.class); { List<HttpResponseStatisticsCollector.StatisticsEntry> stats = statisticsCollector.takeStatistics(); assertEquals(0, stats.size()); } { driver.client().newPost("/status.html").execute(); var entry = waitForStatistics(statisticsCollector); assertEquals("http", entry.scheme); assertEquals("POST", entry.method); assertEquals("http.status.2xx", entry.name); assertEquals("write", entry.requestType); assertEquals(1, entry.value); } { driver.client().newGet("/status.html").execute(); var entry = waitForStatistics(statisticsCollector); assertEquals("http", entry.scheme); assertEquals("GET", entry.method); assertEquals("http.status.2xx", entry.name); assertEquals("read", entry.requestType); assertEquals(1, entry.value); } { handler.setRequestType(Request.RequestType.READ); driver.client().newPost("/status.html").execute(); var entry = waitForStatistics(statisticsCollector); assertEquals("Handler overrides request type", "read", entry.requestType); } assertTrue(driver.close()); } private HttpResponseStatisticsCollector.StatisticsEntry waitForStatistics(HttpResponseStatisticsCollector statisticsCollector) { List<HttpResponseStatisticsCollector.StatisticsEntry> entries = Collections.emptyList(); int tries = 0; while (entries.isEmpty() && tries < 10000) { entries = statisticsCollector.takeStatistics(); if (entries.isEmpty()) try {Thread.sleep(100); } catch (InterruptedException e) {} tries++; } assertEquals(1, entries.size()); return entries.get(0); } @Test public void requireThatConnectionThrottleDoesNotBlockConnectionsBelowThreshold() throws Exception { TestDriver driver = TestDrivers.newConfiguredInstance( new EchoRequestHandler(), new ServerConfig.Builder(), new ConnectorConfig.Builder() .throttling(new Throttling.Builder() .enabled(true) .maxAcceptRate(10) .maxHeapUtilization(1.0) .maxConnections(10))); driver.client().get("/status.html") .expectStatusCode(is(OK)); assertTrue(driver.close()); } @Test public void requireThatMetricIsIncrementedWhenClientIsMissingCertificateOnHandshake() throws IOException { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); var metricConsumer = new MetricConsumerMock(); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); TestDriver driver = createSslTestDriver(certificateFile, privateKeyFile, metricConsumer, connectionLog); SSLContext clientCtx = new SslContextBuilder() .withTrustStore(certificateFile) .build(); assertHttpsRequestTriggersSslHandshakeException( driver, clientCtx, null, null, "Received fatal alert: bad_certificate"); verify(metricConsumer.mockitoMock(), atLeast(1)) .add(MetricDefinitions.SSL_HANDSHAKE_FAILURE_MISSING_CLIENT_CERT, 1L, MetricConsumerMock.STATIC_CONTEXT); assertTrue(driver.close()); Assertions.assertThat(connectionLog.logEntries()).hasSize(1); assertSslHandshakeFailurePresent( connectionLog.logEntries().get(0), SSLHandshakeException.class, SslHandshakeFailure.MISSING_CLIENT_CERT.failureType()); } @Test public void requireThatMetricIsIncrementedWhenClientUsesIncompatibleTlsVersion() throws IOException { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); var metricConsumer = new MetricConsumerMock(); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); TestDriver driver = createSslTestDriver(certificateFile, privateKeyFile, metricConsumer, connectionLog); SSLContext clientCtx = new SslContextBuilder() .withTrustStore(certificateFile) .withKeyStore(privateKeyFile, certificateFile) .build(); boolean tlsv11Enabled = List.of(clientCtx.getDefaultSSLParameters().getProtocols()).contains("TLSv1.1"); assumeTrue("TLSv1.1 must be enabled in installed JDK", tlsv11Enabled); assertHttpsRequestTriggersSslHandshakeException(driver, clientCtx, "TLSv1.1", null, "protocol"); verify(metricConsumer.mockitoMock(), atLeast(1)) .add(MetricDefinitions.SSL_HANDSHAKE_FAILURE_INCOMPATIBLE_PROTOCOLS, 1L, MetricConsumerMock.STATIC_CONTEXT); assertTrue(driver.close()); Assertions.assertThat(connectionLog.logEntries()).hasSize(1); assertSslHandshakeFailurePresent( connectionLog.logEntries().get(0), SSLHandshakeException.class, SslHandshakeFailure.INCOMPATIBLE_PROTOCOLS.failureType()); } @Test public void requireThatMetricIsIncrementedWhenClientUsesIncompatibleCiphers() throws IOException { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); var metricConsumer = new MetricConsumerMock(); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); TestDriver driver = createSslTestDriver(certificateFile, privateKeyFile, metricConsumer, connectionLog); SSLContext clientCtx = new SslContextBuilder() .withTrustStore(certificateFile) .withKeyStore(privateKeyFile, certificateFile) .build(); assertHttpsRequestTriggersSslHandshakeException( driver, clientCtx, null, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", "Received fatal alert: handshake_failure"); verify(metricConsumer.mockitoMock(), atLeast(1)) .add(MetricDefinitions.SSL_HANDSHAKE_FAILURE_INCOMPATIBLE_CIPHERS, 1L, MetricConsumerMock.STATIC_CONTEXT); assertTrue(driver.close()); Assertions.assertThat(connectionLog.logEntries()).hasSize(1); assertSslHandshakeFailurePresent( connectionLog.logEntries().get(0), SSLHandshakeException.class, SslHandshakeFailure.INCOMPATIBLE_CIPHERS.failureType()); } @Test public void requireThatMetricIsIncrementedWhenClientUsesInvalidCertificateInHandshake() throws IOException { Path serverPrivateKeyFile = tmpFolder.newFile().toPath(); Path serverCertificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(serverPrivateKeyFile, serverCertificateFile); var metricConsumer = new MetricConsumerMock(); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); TestDriver driver = createSslTestDriver(serverCertificateFile, serverPrivateKeyFile, metricConsumer, connectionLog); Path clientPrivateKeyFile = tmpFolder.newFile().toPath(); Path clientCertificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(clientPrivateKeyFile, clientCertificateFile); SSLContext clientCtx = new SslContextBuilder() .withKeyStore(clientPrivateKeyFile, clientCertificateFile) .withTrustStore(serverCertificateFile) .build(); assertHttpsRequestTriggersSslHandshakeException( driver, clientCtx, null, null, "Received fatal alert: certificate_unknown"); verify(metricConsumer.mockitoMock(), atLeast(1)) .add(MetricDefinitions.SSL_HANDSHAKE_FAILURE_INVALID_CLIENT_CERT, 1L, MetricConsumerMock.STATIC_CONTEXT); assertTrue(driver.close()); Assertions.assertThat(connectionLog.logEntries()).hasSize(1); assertSslHandshakeFailurePresent( connectionLog.logEntries().get(0), SSLHandshakeException.class, SslHandshakeFailure.INVALID_CLIENT_CERT.failureType()); } @Test public void requireThatMetricIsIncrementedWhenClientUsesExpiredCertificateInHandshake() throws IOException { Path rootPrivateKeyFile = tmpFolder.newFile().toPath(); Path rootCertificateFile = tmpFolder.newFile().toPath(); Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); Instant notAfter = Instant.now().minus(100, ChronoUnit.DAYS); generatePrivateKeyAndCertificate(rootPrivateKeyFile, rootCertificateFile, privateKeyFile, certificateFile, notAfter); var metricConsumer = new MetricConsumerMock(); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); TestDriver driver = createSslTestDriver(rootCertificateFile, rootPrivateKeyFile, metricConsumer, connectionLog); SSLContext clientCtx = new SslContextBuilder() .withTrustStore(rootCertificateFile) .withKeyStore(privateKeyFile, certificateFile) .build(); assertHttpsRequestTriggersSslHandshakeException( driver, clientCtx, null, null, "Received fatal alert: certificate_unknown"); verify(metricConsumer.mockitoMock(), atLeast(1)) .add(MetricDefinitions.SSL_HANDSHAKE_FAILURE_EXPIRED_CLIENT_CERT, 1L, MetricConsumerMock.STATIC_CONTEXT); assertTrue(driver.close()); Assertions.assertThat(connectionLog.logEntries()).hasSize(1); } @Test public void requireThatProxyProtocolIsAcceptedAndActualRemoteAddressStoredInAccessLog() throws Exception { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); InMemoryRequestLog requestLogMock = new InMemoryRequestLog(); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); TestDriver driver = createSslWithProxyProtocolTestDriver(certificateFile, privateKeyFile, requestLogMock, /*mixedMode*/connectionLog, false); String proxiedRemoteAddress = "192.168.0.100"; int proxiedRemotePort = 12345; sendJettyClientRequest(driver, certificateFile, new V1.Tag(proxiedRemoteAddress, proxiedRemotePort)); sendJettyClientRequest(driver, certificateFile, new V2.Tag(proxiedRemoteAddress, proxiedRemotePort)); assertTrue(driver.close()); assertEquals(2, requestLogMock.entries().size()); assertLogEntryHasRemote(requestLogMock.entries().get(0), proxiedRemoteAddress, proxiedRemotePort); assertLogEntryHasRemote(requestLogMock.entries().get(1), proxiedRemoteAddress, proxiedRemotePort); Assertions.assertThat(connectionLog.logEntries()).hasSize(2); assertLogEntryHasRemote(connectionLog.logEntries().get(0), proxiedRemoteAddress, proxiedRemotePort); assertLogEntryHasRemote(connectionLog.logEntries().get(1), proxiedRemoteAddress, proxiedRemotePort); } @Test public void requireThatConnectorWithProxyProtocolMixedEnabledAcceptsBothProxyProtocolAndHttps() throws Exception { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); InMemoryRequestLog requestLogMock = new InMemoryRequestLog(); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); TestDriver driver = createSslWithProxyProtocolTestDriver(certificateFile, privateKeyFile, requestLogMock, /*mixedMode*/connectionLog, true); String proxiedRemoteAddress = "192.168.0.100"; sendJettyClientRequest(driver, certificateFile, null); sendJettyClientRequest(driver, certificateFile, new V2.Tag(proxiedRemoteAddress, 12345)); assertTrue(driver.close()); assertEquals(2, requestLogMock.entries().size()); assertLogEntryHasRemote(requestLogMock.entries().get(0), "127.0.0.1", 0); assertLogEntryHasRemote(requestLogMock.entries().get(1), proxiedRemoteAddress, 0); Assertions.assertThat(connectionLog.logEntries()).hasSize(2); assertLogEntryHasRemote(connectionLog.logEntries().get(0), null, 0); assertLogEntryHasRemote(connectionLog.logEntries().get(1), proxiedRemoteAddress, 12345); } @Test public void requireThatJdiscLocalPortPropertyIsNotOverriddenByProxyProtocol() throws Exception { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); InMemoryRequestLog requestLogMock = new InMemoryRequestLog(); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); TestDriver driver = createSslWithProxyProtocolTestDriver(certificateFile, privateKeyFile, requestLogMock, connectionLog, /*mixedMode*/false); String proxiedRemoteAddress = "192.168.0.100"; int proxiedRemotePort = 12345; String proxyLocalAddress = "10.0.0.10"; int proxyLocalPort = 23456; V2.Tag v2Tag = new V2.Tag(V2.Tag.Command.PROXY, null, V2.Tag.Protocol.STREAM, proxiedRemoteAddress, proxiedRemotePort, proxyLocalAddress, proxyLocalPort, null); ContentResponse response = sendJettyClientRequest(driver, certificateFile, v2Tag); assertTrue(driver.close()); int clientPort = Integer.parseInt(response.getHeaders().get("Jdisc-Local-Port")); assertNotEquals(proxyLocalPort, clientPort); assertNotEquals(proxyLocalPort, connectionLog.logEntries().get(0).localPort().get().intValue()); } @Test public void requireThatConnectionIsTrackedInConnectionLog() throws Exception { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); Module overrideModule = binder -> binder.bind(ConnectionLog.class).toInstance(connectionLog); TestDriver driver = TestDrivers.newInstanceWithSsl(new OkRequestHandler(), certificateFile, privateKeyFile, TlsClientAuth.NEED, overrideModule); int listenPort = driver.server().getListenPort(); StringBuilder builder = new StringBuilder(); for (int i = 0; i < 1000; i++) { builder.append(i); } byte[] content = builder.toString().getBytes(); for (int i = 0; i < 100; i++) { driver.client().newPost("/status.html").setBinaryContent(content).execute() .expectStatusCode(is(OK)); } assertTrue(driver.close()); List<ConnectionLogEntry> logEntries = connectionLog.logEntries(); Assertions.assertThat(logEntries).hasSize(1); ConnectionLogEntry logEntry = logEntries.get(0); assertEquals(4, UUID.fromString(logEntry.id()).version()); Assertions.assertThat(logEntry.timestamp()).isAfter(Instant.EPOCH); Assertions.assertThat(logEntry.requests()).hasValue(100L); Assertions.assertThat(logEntry.responses()).hasValue(100L); Assertions.assertThat(logEntry.peerAddress()).hasValue("127.0.0.1"); Assertions.assertThat(logEntry.localAddress()).hasValue("127.0.0.1"); Assertions.assertThat(logEntry.localPort()).hasValue(listenPort); Assertions.assertThat(logEntry.httpBytesReceived()).hasValueSatisfying(value -> Assertions.assertThat(value).isGreaterThan(100000L)); Assertions.assertThat(logEntry.httpBytesSent()).hasValueSatisfying(value -> Assertions.assertThat(value).isGreaterThan(10000L)); Assertions.assertThat(logEntry.sslProtocol()).hasValueSatisfying(TlsContext.ALLOWED_PROTOCOLS::contains); Assertions.assertThat(logEntry.sslPeerSubject()).hasValue("CN=localhost"); Assertions.assertThat(logEntry.sslCipherSuite()).hasValueSatisfying(cipher -> Assertions.assertThat(cipher).isNotBlank()); Assertions.assertThat(logEntry.sslSessionId()).hasValueSatisfying(sessionId -> Assertions.assertThat(sessionId).hasSize(64)); Assertions.assertThat(logEntry.sslPeerNotBefore()).hasValue(Instant.EPOCH); Assertions.assertThat(logEntry.sslPeerNotAfter()).hasValue(Instant.EPOCH.plus(100_000, ChronoUnit.DAYS)); } @Test public void requireThatRequestIsTrackedInAccessLog() throws IOException, InterruptedException { BlockingQueueRequestLog requestLogMock = new BlockingQueueRequestLog(); TestDriver driver = TestDrivers.newConfiguredInstance( new EchoRequestHandler(), new ServerConfig.Builder(), new ConnectorConfig.Builder(), binder -> binder.bind(RequestLog.class).toInstance(requestLogMock)); driver.client().newPost("/status.html").setContent("abcdef").execute().expectStatusCode(is(OK)); assertThat(driver.close(), is(true)); RequestLogEntry entry = requestLogMock.poll(Duration.ofSeconds(30)); Assertions.assertThat(entry.statusCode()).hasValue(200); Assertions.assertThat(entry.requestSize()).hasValue(6); } private ContentResponse sendJettyClientRequest(TestDriver testDriver, Path certificateFile, Object tag) throws Exception { HttpClient client = createJettyHttpClient(certificateFile); try { int maxAttempts = 3; for (int attempt = 0; attempt < maxAttempts; attempt++) { try { ContentResponse response = client.newRequest(URI.create("https://localhost:" + testDriver.server().getListenPort() + "/")) .tag(tag) .send(); assertEquals(200, response.getStatus()); return response; } catch (ExecutionException e) { // Retry when the server closes the connection before the TLS handshake is completed. This have been observed in CI. // We have been unable to reproduce this locally. The cause is therefor currently unknown. log.log(Level.WARNING, String.format("Attempt %d failed: %s", attempt, e.getMessage()), e); Thread.sleep(10); } } throw new AssertionError("Failed to send request, see log for details"); } finally { client.stop(); } } // Using Jetty's http client as Apache httpclient does not support the proxy-protocol v1/v2. private static HttpClient createJettyHttpClient(Path certificateFile) throws Exception { SslContextFactory.Client clientSslCtxFactory = new SslContextFactory.Client(); clientSslCtxFactory.setHostnameVerifier(NoopHostnameVerifier.INSTANCE); clientSslCtxFactory.setSslContext(new SslContextBuilder().withTrustStore(certificateFile).build()); HttpClient client = new HttpClient(clientSslCtxFactory); client.start(); return client; } private static void assertLogEntryHasRemote(RequestLogEntry entry, String expectedAddress, int expectedPort) { assertEquals(expectedAddress, entry.peerAddress().get()); if (expectedPort > 0) { assertEquals(expectedPort, entry.peerPort().getAsInt()); } } private static void assertLogEntryHasRemote(ConnectionLogEntry entry, String expectedAddress, int expectedPort) { if (expectedAddress != null) { Assertions.assertThat(entry.remoteAddress()).hasValue(expectedAddress); } else { Assertions.assertThat(entry.remoteAddress()).isEmpty(); } if (expectedPort > 0) { Assertions.assertThat(entry.remotePort()).hasValue(expectedPort); } else { Assertions.assertThat(entry.remotePort()).isEmpty(); } } private static void assertSslHandshakeFailurePresent( ConnectionLogEntry entry, Class<? extends SSLHandshakeException> expectedException, String expectedType) { Assertions.assertThat(entry.sslHandshakeFailure()).isPresent(); ConnectionLogEntry.SslHandshakeFailure failure = entry.sslHandshakeFailure().get(); assertEquals(expectedType, failure.type()); ExceptionEntry exceptionEntry = failure.exceptionChain().get(0); assertEquals(expectedException.getName(), exceptionEntry.name()); } private static TestDriver createSslWithProxyProtocolTestDriver( Path certificateFile, Path privateKeyFile, RequestLog requestLog, ConnectionLog connectionLog, boolean mixedMode) { ConnectorConfig.Builder connectorConfig = new ConnectorConfig.Builder() .proxyProtocol(new ConnectorConfig.ProxyProtocol.Builder() .enabled(true) .mixedMode(mixedMode)) .ssl(new ConnectorConfig.Ssl.Builder() .enabled(true) .privateKeyFile(privateKeyFile.toString()) .certificateFile(certificateFile.toString()) .caCertificateFile(certificateFile.toString())); return TestDrivers.newConfiguredInstance( new EchoRequestHandler(), new ServerConfig.Builder().connectionLog(new ServerConfig.ConnectionLog.Builder().enabled(true)), connectorConfig, binder -> { binder.bind(RequestLog.class).toInstance(requestLog); binder.bind(ConnectionLog.class).toInstance(connectionLog); }); } private static TestDriver createSslTestDriver( Path serverCertificateFile, Path serverPrivateKeyFile, MetricConsumerMock metricConsumer, InMemoryConnectionLog connectionLog) throws IOException { Module extraModule = binder -> { binder.bind(MetricConsumer.class).toInstance(metricConsumer.mockitoMock()); binder.bind(ConnectionLog.class).toInstance(connectionLog); }; return TestDrivers.newInstanceWithSsl( new EchoRequestHandler(), serverCertificateFile, serverPrivateKeyFile, TlsClientAuth.NEED, extraModule); } private static void assertHttpsRequestTriggersSslHandshakeException( TestDriver testDriver, SSLContext sslContext, String protocolOverride, String cipherOverride, String expectedExceptionSubstring) throws IOException { List<String> protocols = protocolOverride != null ? List.of(protocolOverride) : null; List<String> ciphers = cipherOverride != null ? List.of(cipherOverride) : null; try (var client = new SimpleHttpClient(sslContext, protocols, ciphers, testDriver.server().getListenPort(), false)) { client.get("/status.html"); fail("SSLHandshakeException expected"); } catch (SSLHandshakeException e) { assertThat(e.getMessage(), containsString(expectedExceptionSubstring)); } catch (SSLException e) { // This exception is thrown if Apache httpclient's write thread detects the handshake failure before the read thread. log.log(Level.WARNING, "Client failed to get a proper TLS handshake response: " + e.getMessage(), e); // Only ignore a subset of exceptions assertThat(e.getMessage(), anyOf(containsString("readHandshakeRecord"), containsString("Broken pipe"))); } } private static void generatePrivateKeyAndCertificate(Path privateKeyFile, Path certificateFile) throws IOException { KeyPair keyPair = KeyUtils.generateKeypair(EC); Files.writeString(privateKeyFile, KeyUtils.toPem(keyPair.getPrivate())); X509Certificate certificate = X509CertificateBuilder .fromKeypair( keyPair, new X500Principal("CN=localhost"), Instant.EPOCH, Instant.EPOCH.plus(100_000, ChronoUnit.DAYS), SHA256_WITH_ECDSA, BigInteger.ONE) .build(); Files.writeString(certificateFile, X509CertificateUtils.toPem(certificate)); } private static void generatePrivateKeyAndCertificate(Path rootPrivateKeyFile, Path rootCertificateFile, Path privateKeyFile, Path certificateFile, Instant notAfter) throws IOException { generatePrivateKeyAndCertificate(rootPrivateKeyFile, rootCertificateFile); X509Certificate rootCertificate = X509CertificateUtils.fromPem(Files.readString(rootCertificateFile)); PrivateKey privateKey = KeyUtils.fromPemEncodedPrivateKey(Files.readString(rootPrivateKeyFile)); KeyPair keyPair = KeyUtils.generateKeypair(EC); Files.writeString(privateKeyFile, KeyUtils.toPem(keyPair.getPrivate())); Pkcs10Csr csr = Pkcs10CsrBuilder.fromKeypair(new X500Principal("CN=myclient"), keyPair, SHA256_WITH_ECDSA).build(); X509Certificate certificate = X509CertificateBuilder .fromCsr(csr, rootCertificate.getSubjectX500Principal(), Instant.EPOCH, notAfter, privateKey, SHA256_WITH_ECDSA, BigInteger.ONE) .build(); Files.writeString(certificateFile, X509CertificateUtils.toPem(certificate)); } private static RequestHandler mockRequestHandler() { final RequestHandler mockRequestHandler = mock(RequestHandler.class); when(mockRequestHandler.refer()).thenReturn(References.NOOP_REFERENCE); return mockRequestHandler; } private static String generateContent(final char c, final int len) { final StringBuilder ret = new StringBuilder(len); for (int i = 0; i < len; ++i) { ret.append(c); } return ret.toString(); } private static TestDriver newDriverWithFormPostContentRemoved(RequestHandler requestHandler, boolean removeFormPostBody) throws Exception { return TestDrivers.newConfiguredInstance( requestHandler, new ServerConfig.Builder() .removeRawPostBodyForWwwUrlEncodedPost(removeFormPostBody), new ConnectorConfig.Builder()); } private static FormBodyPart newFileBody(final String parameterName, final String fileName, final String fileContent) { return new FormBodyPart( parameterName, new StringBody(fileContent, ContentType.TEXT_PLAIN) { @Override public String getFilename() { return fileName; } @Override public String getTransferEncoding() { return "binary"; } @Override public String getMimeType() { return ""; } @Override public String getCharset() { return null; } }); } private static class ConnectedAtRequestHandler extends AbstractRequestHandler { @Override public ContentChannel handleRequest(final Request request, final ResponseHandler handler) { final HttpRequest httpRequest = (HttpRequest)request; final String connectedAt = String.valueOf(httpRequest.getConnectedAt(TimeUnit.MILLISECONDS)); final ContentChannel ch = handler.handleResponse(new Response(OK)); ch.write(ByteBuffer.wrap(connectedAt.getBytes(StandardCharsets.UTF_8)), null); ch.close(null); return null; } } private static class CookieSetterRequestHandler extends AbstractRequestHandler { final Cookie cookie; CookieSetterRequestHandler(final Cookie cookie) { this.cookie = cookie; } @Override public ContentChannel handleRequest(final Request request, final ResponseHandler handler) { final HttpResponse response = HttpResponse.newInstance(OK); response.encodeSetCookieHeader(Collections.singletonList(cookie)); ResponseDispatch.newInstance(response).dispatch(handler); return null; } } private static class CookiePrinterRequestHandler extends AbstractRequestHandler { @Override public ContentChannel handleRequest(final Request request, final ResponseHandler handler) { final List<Cookie> cookies = new ArrayList<>(((HttpRequest)request).decodeCookieHeader()); Collections.sort(cookies, new CookieComparator()); final ContentChannel out = ResponseDispatch.newInstance(Response.Status.OK).connect(handler); out.write(StandardCharsets.UTF_8.encode(cookies.toString()), null); out.close(null); return null; } } private static class ParameterPrinterRequestHandler extends AbstractRequestHandler { private static final CompletionHandler NULL_COMPLETION_HANDLER = null; @Override public ContentChannel handleRequest(Request request, ResponseHandler handler) { Map<String, List<String>> parameters = new TreeMap<>(((HttpRequest)request).parameters()); ContentChannel responseContentChannel = ResponseDispatch.newInstance(Response.Status.OK).connect(handler); responseContentChannel.write(ByteBuffer.wrap(parameters.toString().getBytes(StandardCharsets.UTF_8)), NULL_COMPLETION_HANDLER); // Have the request content written back to the response. return responseContentChannel; } } private static class RequestTypeHandler extends AbstractRequestHandler { private Request.RequestType requestType = null; public void setRequestType(Request.RequestType requestType) { this.requestType = requestType; } @Override public ContentChannel handleRequest(Request request, ResponseHandler handler) { Response response = new Response(OK); response.setRequestType(requestType); return handler.handleResponse(response); } } private static class ThrowingHandler extends AbstractRequestHandler { @Override public ContentChannel handleRequest(final Request request, final ResponseHandler handler) { throw new RuntimeException("Deliberately thrown exception"); } } private static class UnresponsiveHandler extends AbstractRequestHandler { ResponseHandler responseHandler; @Override public ContentChannel handleRequest(final Request request, final ResponseHandler handler) { request.setTimeout(100, TimeUnit.MILLISECONDS); responseHandler = handler; return null; } } private static class EchoRequestHandler extends AbstractRequestHandler { @Override public ContentChannel handleRequest(final Request request, final ResponseHandler handler) { int port = request.getUri().getPort(); Response response = new Response(OK); response.headers().put("Jdisc-Local-Port", Integer.toString(port)); return handler.handleResponse(response); } } private static class OkRequestHandler extends AbstractRequestHandler { @Override public ContentChannel handleRequest(Request request, ResponseHandler handler) { Response response = new Response(OK); handler.handleResponse(response).close(null); return NullContent.INSTANCE; } } private static class EchoWithHeaderRequestHandler extends AbstractRequestHandler { final String headerName; final String headerValue; EchoWithHeaderRequestHandler(final String headerName, final String headerValue) { this.headerName = headerName; this.headerValue = headerValue; } @Override public ContentChannel handleRequest(final Request request, final ResponseHandler handler) { final Response response = new Response(OK); response.headers().add(headerName, headerValue); return handler.handleResponse(response); } } private static Module newBindingSetSelector(final String setName) { return new AbstractModule() { @Override protected void configure() { bind(BindingSetSelector.class).toInstance(new BindingSetSelector() { @Override public String select(final URI uri) { return setName; } }); } }; } private static class CookieComparator implements Comparator<Cookie> { @Override public int compare(final Cookie lhs, final Cookie rhs) { return lhs.getName().compareTo(rhs.getName()); } } }
container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpServerTest.java
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.jdisc.http.server.jetty; import com.google.inject.AbstractModule; import com.google.inject.Module; import com.yahoo.container.logging.ConnectionLog; import com.yahoo.container.logging.ConnectionLogEntry; import com.yahoo.container.logging.ConnectionLogEntry.SslHandshakeFailure.ExceptionEntry; import com.yahoo.container.logging.RequestLog; import com.yahoo.container.logging.RequestLogEntry; import com.yahoo.jdisc.References; import com.yahoo.jdisc.Request; import com.yahoo.jdisc.Response; import com.yahoo.jdisc.application.BindingSetSelector; import com.yahoo.jdisc.application.MetricConsumer; import com.yahoo.jdisc.handler.AbstractRequestHandler; import com.yahoo.jdisc.handler.CompletionHandler; import com.yahoo.jdisc.handler.ContentChannel; import com.yahoo.jdisc.handler.NullContent; import com.yahoo.jdisc.handler.RequestHandler; import com.yahoo.jdisc.handler.ResponseDispatch; import com.yahoo.jdisc.handler.ResponseHandler; import com.yahoo.jdisc.http.ConnectorConfig; import com.yahoo.jdisc.http.ConnectorConfig.Throttling; import com.yahoo.jdisc.http.Cookie; import com.yahoo.jdisc.http.HttpRequest; import com.yahoo.jdisc.http.HttpResponse; import com.yahoo.jdisc.http.ServerConfig; import com.yahoo.jdisc.http.server.jetty.TestDrivers.TlsClientAuth; import com.yahoo.jdisc.service.BindingSetNotFoundException; import com.yahoo.security.KeyUtils; import com.yahoo.security.Pkcs10Csr; import com.yahoo.security.Pkcs10CsrBuilder; import com.yahoo.security.SslContextBuilder; import com.yahoo.security.X509CertificateBuilder; import com.yahoo.security.X509CertificateUtils; import com.yahoo.security.tls.TlsContext; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.FormBodyPart; import org.apache.http.entity.mime.content.StringBody; import org.assertj.core.api.Assertions; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.ProxyProtocolClientConnectionFactory.V1; import org.eclipse.jetty.client.ProxyProtocolClientConnectionFactory.V2; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.server.handler.AbstractHandlerContainer; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import javax.net.ssl.SSLHandshakeException; import javax.security.auth.x500.X500Principal; import java.io.IOException; import java.math.BigInteger; import java.net.BindException; import java.net.URI; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.security.KeyPair; import java.security.PrivateKey; import java.security.cert.X509Certificate; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import static com.yahoo.jdisc.Response.Status.GATEWAY_TIMEOUT; import static com.yahoo.jdisc.Response.Status.INTERNAL_SERVER_ERROR; import static com.yahoo.jdisc.Response.Status.NOT_FOUND; import static com.yahoo.jdisc.Response.Status.OK; import static com.yahoo.jdisc.Response.Status.REQUEST_URI_TOO_LONG; import static com.yahoo.jdisc.Response.Status.UNAUTHORIZED; import static com.yahoo.jdisc.Response.Status.UNSUPPORTED_MEDIA_TYPE; import static com.yahoo.jdisc.http.HttpHeaders.Names.CONNECTION; import static com.yahoo.jdisc.http.HttpHeaders.Names.CONTENT_TYPE; import static com.yahoo.jdisc.http.HttpHeaders.Names.COOKIE; import static com.yahoo.jdisc.http.HttpHeaders.Names.X_DISABLE_CHUNKING; import static com.yahoo.jdisc.http.HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED; import static com.yahoo.jdisc.http.HttpHeaders.Values.CLOSE; import static com.yahoo.jdisc.http.server.jetty.SimpleHttpClient.ResponseValidator; import static com.yahoo.security.KeyAlgorithm.EC; import static com.yahoo.security.SignatureAlgorithm.SHA256_WITH_ECDSA; import static org.cthul.matchers.CthulMatchers.containsPattern; import static org.cthul.matchers.CthulMatchers.matchesPattern; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.startsWith; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.anyOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeTrue; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * @author Oyvind Bakksjo * @author Simon Thoresen Hult * @author bjorncs */ public class HttpServerTest { private static final Logger log = Logger.getLogger(HttpServerTest.class.getName()); @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); @Test public void requireThatServerCanListenToRandomPort() throws Exception { final TestDriver driver = TestDrivers.newInstance(mockRequestHandler()); assertNotEquals(0, driver.server().getListenPort()); assertTrue(driver.close()); } @Test public void requireThatServerCanNotListenToBoundPort() throws Exception { final TestDriver driver = TestDrivers.newInstance(mockRequestHandler()); try { TestDrivers.newConfiguredInstance( mockRequestHandler(), new ServerConfig.Builder(), new ConnectorConfig.Builder() .listenPort(driver.server().getListenPort()) ); } catch (final Throwable t) { assertThat(t.getCause(), instanceOf(BindException.class)); } assertTrue(driver.close()); } @Test public void requireThatBindingSetNotFoundReturns404() throws Exception { final TestDriver driver = TestDrivers.newConfiguredInstance( mockRequestHandler(), new ServerConfig.Builder() .developerMode(true), new ConnectorConfig.Builder(), newBindingSetSelector("unknown")); driver.client().get("/status.html") .expectStatusCode(is(NOT_FOUND)) .expectContent(containsPattern(Pattern.compile( Pattern.quote(BindingSetNotFoundException.class.getName()) + ": No binding set named &apos;unknown&apos;\\.\n\tat .+", Pattern.DOTALL | Pattern.MULTILINE))); assertTrue(driver.close()); } @Test public void requireThatTooLongInitLineReturns414() throws Exception { final TestDriver driver = TestDrivers.newConfiguredInstance( mockRequestHandler(), new ServerConfig.Builder(), new ConnectorConfig.Builder() .requestHeaderSize(1)); driver.client().get("/status.html") .expectStatusCode(is(REQUEST_URI_TOO_LONG)); assertTrue(driver.close()); } @Test public void requireThatAccessLogIsCalledForRequestRejectedByJetty() throws Exception { BlockingQueueRequestLog requestLogMock = new BlockingQueueRequestLog(); final TestDriver driver = TestDrivers.newConfiguredInstance( mockRequestHandler(), new ServerConfig.Builder(), new ConnectorConfig.Builder().requestHeaderSize(1), binder -> binder.bind(RequestLog.class).toInstance(requestLogMock)); driver.client().get("/status.html") .expectStatusCode(is(REQUEST_URI_TOO_LONG)); RequestLogEntry entry = requestLogMock.poll(Duration.ofSeconds(30)); assertEquals(414, entry.statusCode().getAsInt()); assertThat(driver.close(), is(true)); } @Test public void requireThatServerCanEcho() throws Exception { final TestDriver driver = TestDrivers.newInstance(new EchoRequestHandler()); driver.client().get("/status.html") .expectStatusCode(is(OK)); assertTrue(driver.close()); } @Test public void requireThatServerCanEchoCompressed() throws Exception { final TestDriver driver = TestDrivers.newInstance(new EchoRequestHandler()); SimpleHttpClient client = driver.newClient(true); client.get("/status.html") .expectStatusCode(is(OK)); assertTrue(driver.close()); } @Test public void requireThatServerCanHandleMultipleRequests() throws Exception { final TestDriver driver = TestDrivers.newInstance(new EchoRequestHandler()); driver.client().get("/status.html") .expectStatusCode(is(OK)); driver.client().get("/status.html") .expectStatusCode(is(OK)); assertTrue(driver.close()); } @Test public void requireThatFormPostWorks() throws Exception { final TestDriver driver = TestDrivers.newInstance(new ParameterPrinterRequestHandler()); final String requestContent = generateContent('a', 30); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .setContent(requestContent) .execute(); response.expectStatusCode(is(OK)) .expectContent(startsWith('{' + requestContent + "=[]}")); assertTrue(driver.close()); } @Test public void requireThatFormPostDoesNotRemoveContentByDefault() throws Exception { final TestDriver driver = TestDrivers.newInstance(new ParameterPrinterRequestHandler()); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .setContent("foo=bar") .execute(); response.expectStatusCode(is(OK)) .expectContent(is("{foo=[bar]}foo=bar")); assertTrue(driver.close()); } @Test public void requireThatFormPostKeepsContentWhenConfiguredTo() throws Exception { final TestDriver driver = newDriverWithFormPostContentRemoved(new ParameterPrinterRequestHandler(), false); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .setContent("foo=bar") .execute(); response.expectStatusCode(is(OK)) .expectContent(is("{foo=[bar]}foo=bar")); assertTrue(driver.close()); } @Test public void requireThatFormPostRemovesContentWhenConfiguredTo() throws Exception { final TestDriver driver = newDriverWithFormPostContentRemoved(new ParameterPrinterRequestHandler(), true); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .setContent("foo=bar") .execute(); response.expectStatusCode(is(OK)) .expectContent(is("{foo=[bar]}")); assertTrue(driver.close()); } @Test public void requireThatFormPostWithCharsetSpecifiedWorks() throws Exception { final TestDriver driver = TestDrivers.newInstance(new ParameterPrinterRequestHandler()); final String requestContent = generateContent('a', 30); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(X_DISABLE_CHUNKING, "true") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED + ";charset=UTF-8") .setContent(requestContent) .execute(); response.expectStatusCode(is(OK)) .expectContent(startsWith('{' + requestContent + "=[]}")); assertTrue(driver.close()); } @Test public void requireThatEmptyFormPostWorks() throws Exception { final TestDriver driver = TestDrivers.newInstance(new ParameterPrinterRequestHandler()); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .execute(); response.expectStatusCode(is(OK)) .expectContent(is("{}")); assertTrue(driver.close()); } @Test public void requireThatFormParametersAreParsed() throws Exception { final TestDriver driver = TestDrivers.newInstance(new ParameterPrinterRequestHandler()); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .setContent("a=b&c=d") .execute(); response.expectStatusCode(is(OK)) .expectContent(startsWith("{a=[b], c=[d]}")); assertTrue(driver.close()); } @Test public void requireThatUriParametersAreParsed() throws Exception { final TestDriver driver = TestDrivers.newInstance(new ParameterPrinterRequestHandler()); final ResponseValidator response = driver.client().newPost("/status.html?a=b&c=d") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .execute(); response.expectStatusCode(is(OK)) .expectContent(is("{a=[b], c=[d]}")); assertTrue(driver.close()); } @Test public void requireThatFormAndUriParametersAreMerged() throws Exception { final TestDriver driver = TestDrivers.newInstance(new ParameterPrinterRequestHandler()); final ResponseValidator response = driver.client().newPost("/status.html?a=b&c=d1") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .setContent("c=d2&e=f") .execute(); response.expectStatusCode(is(OK)) .expectContent(startsWith("{a=[b], c=[d1, d2], e=[f]}")); assertTrue(driver.close()); } @Test public void requireThatFormCharsetIsHonored() throws Exception { final TestDriver driver = newDriverWithFormPostContentRemoved(new ParameterPrinterRequestHandler(), true); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED + ";charset=ISO-8859-1") .setBinaryContent(new byte[]{66, (byte) 230, 114, 61, 98, 108, (byte) 229}) .execute(); response.expectStatusCode(is(OK)) .expectContent(is("{B\u00e6r=[bl\u00e5]}")); assertTrue(driver.close()); } @Test public void requireThatUnknownFormCharsetIsTreatedAsBadRequest() throws Exception { final TestDriver driver = TestDrivers.newInstance(new ParameterPrinterRequestHandler()); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED + ";charset=FLARBA-GARBA-7") .setContent("a=b") .execute(); response.expectStatusCode(is(UNSUPPORTED_MEDIA_TYPE)); assertTrue(driver.close()); } @Test public void requireThatFormPostWithPercentEncodedContentIsDecoded() throws Exception { final TestDriver driver = TestDrivers.newInstance(new ParameterPrinterRequestHandler()); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .setContent("%20%3D%C3%98=%22%25+") .execute(); response.expectStatusCode(is(OK)) .expectContent(startsWith("{ =\u00d8=[\"% ]}")); assertTrue(driver.close()); } @Test public void requireThatFormPostWithThrowingHandlerIsExceptionSafe() throws Exception { final TestDriver driver = TestDrivers.newInstance(new ThrowingHandler()); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .setContent("a=b") .execute(); response.expectStatusCode(is(INTERNAL_SERVER_ERROR)); assertTrue(driver.close()); } @Test public void requireThatMultiPostWorks() throws Exception { // This is taken from tcpdump of bug 5433352 and reassembled here to see that httpserver passes things on. final String startTxtContent = "this is a test for POST."; final String updaterConfContent = "identifier = updater\n" + "server_type = gds\n"; final TestDriver driver = TestDrivers.newInstance(new EchoRequestHandler()); final ResponseValidator response = driver.client().newPost("/status.html") .setMultipartContent( newFileBody("", "start.txt", startTxtContent), newFileBody("", "updater.conf", updaterConfContent)) .execute(); response.expectStatusCode(is(OK)) .expectContent(containsString(startTxtContent)) .expectContent(containsString(updaterConfContent)); } @Test public void requireThatRequestCookiesAreReceived() throws Exception { final TestDriver driver = TestDrivers.newInstance(new CookiePrinterRequestHandler()); final ResponseValidator response = driver.client().newPost("/status.html") .addHeader(COOKIE, "foo=bar") .execute(); response.expectStatusCode(is(OK)) .expectContent(containsString("[foo=bar]")); assertTrue(driver.close()); } @Test public void requireThatSetCookieHeaderIsCorrect() throws Exception { final TestDriver driver = TestDrivers.newInstance(new CookieSetterRequestHandler( new Cookie("foo", "bar") .setDomain(".localhost") .setHttpOnly(true) .setPath("/foopath") .setSecure(true))); driver.client().get("/status.html") .expectStatusCode(is(OK)) .expectHeader("Set-Cookie", is("foo=bar; Path=/foopath; Domain=.localhost; Secure; HttpOnly")); assertTrue(driver.close()); } @Test public void requireThatTimeoutWorks() throws Exception { final UnresponsiveHandler requestHandler = new UnresponsiveHandler(); final TestDriver driver = TestDrivers.newInstance(requestHandler); driver.client().get("/status.html") .expectStatusCode(is(GATEWAY_TIMEOUT)); ResponseDispatch.newInstance(OK).dispatch(requestHandler.responseHandler); assertTrue(driver.close()); } // Header with no value is disallowed by https://tools.ietf.org/html/rfc7230#section-3.2 // Details in https://github.com/eclipse/jetty.project/issues/1116 @Test public void requireThatHeaderWithNullValueIsOmitted() throws Exception { final TestDriver driver = TestDrivers.newInstance(new EchoWithHeaderRequestHandler("X-Foo", null)); driver.client().get("/status.html") .expectStatusCode(is(OK)) .expectNoHeader("X-Foo"); assertTrue(driver.close()); } // Header with empty value is allowed by https://tools.ietf.org/html/rfc7230#section-3.2 // Details in https://github.com/eclipse/jetty.project/issues/1116 @Test public void requireThatHeaderWithEmptyValueIsAllowed() throws Exception { final TestDriver driver = TestDrivers.newInstance(new EchoWithHeaderRequestHandler("X-Foo", "")); driver.client().get("/status.html") .expectStatusCode(is(OK)) .expectHeader("X-Foo", is("")); assertTrue(driver.close()); } @Test public void requireThatNoConnectionHeaderMeansKeepAliveInHttp11KeepAliveDisabled() throws Exception { final TestDriver driver = TestDrivers.newInstance(new EchoWithHeaderRequestHandler(CONNECTION, CLOSE)); driver.client().get("/status.html") .expectHeader(CONNECTION, is(CLOSE)); assertThat(driver.close(), is(true)); } @Test public void requireThatConnectionIsClosedAfterXRequests() throws Exception { final int MAX_KEEPALIVE_REQUESTS = 100; final TestDriver driver = TestDrivers.newConfiguredInstance(new EchoRequestHandler(), new ServerConfig.Builder(), new ConnectorConfig.Builder().maxRequestsPerConnection(MAX_KEEPALIVE_REQUESTS)); for (int i = 0; i < MAX_KEEPALIVE_REQUESTS - 1; i++) { driver.client().get("/status.html") .expectStatusCode(is(OK)) .expectNoHeader(CONNECTION); } driver.client().get("/status.html") .expectStatusCode(is(OK)) .expectHeader(CONNECTION, is(CLOSE)); assertTrue(driver.close()); } @Test public void requireThatServerCanRespondToSslRequest() throws Exception { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); final TestDriver driver = TestDrivers.newInstanceWithSsl(new EchoRequestHandler(), certificateFile, privateKeyFile, TlsClientAuth.WANT); driver.client().get("/status.html") .expectStatusCode(is(OK)); assertTrue(driver.close()); } @Test public void requireThatTlsClientAuthenticationEnforcerRejectsRequestsForNonWhitelistedPaths() throws IOException { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); TestDriver driver = TestDrivers.newInstanceWithSsl(new EchoRequestHandler(), certificateFile, privateKeyFile, TlsClientAuth.WANT); SSLContext trustStoreOnlyCtx = new SslContextBuilder() .withTrustStore(certificateFile) .build(); new SimpleHttpClient(trustStoreOnlyCtx, driver.server().getListenPort(), false) .get("/dummy.html") .expectStatusCode(is(UNAUTHORIZED)); assertTrue(driver.close()); } @Test public void requireThatTlsClientAuthenticationEnforcerAllowsRequestForWhitelistedPaths() throws IOException { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); TestDriver driver = TestDrivers.newInstanceWithSsl(new EchoRequestHandler(), certificateFile, privateKeyFile, TlsClientAuth.WANT); SSLContext trustStoreOnlyCtx = new SslContextBuilder() .withTrustStore(certificateFile) .build(); new SimpleHttpClient(trustStoreOnlyCtx, driver.server().getListenPort(), false) .get("/status.html") .expectStatusCode(is(OK)); assertTrue(driver.close()); } @Test public void requireThatConnectedAtReturnsNonZero() throws Exception { final TestDriver driver = TestDrivers.newInstance(new ConnectedAtRequestHandler()); driver.client().get("/status.html") .expectStatusCode(is(OK)) .expectContent(matchesPattern("\\d{13,}")); assertThat(driver.close(), is(true)); } @Test public void requireThatGzipEncodingRequestsAreAutomaticallyDecompressed() throws Exception { TestDriver driver = TestDrivers.newInstance(new ParameterPrinterRequestHandler()); String requestContent = generateContent('a', 30); ResponseValidator response = driver.client().newPost("/status.html") .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED) .setGzipContent(requestContent) .execute(); response.expectStatusCode(is(OK)) .expectContent(startsWith('{' + requestContent + "=[]}")); assertTrue(driver.close()); } @Test public void requireThatResponseStatsAreCollected() throws Exception { RequestTypeHandler handler = new RequestTypeHandler(); TestDriver driver = TestDrivers.newInstance(handler); HttpResponseStatisticsCollector statisticsCollector = ((AbstractHandlerContainer) driver.server().server().getHandler()) .getChildHandlerByClass(HttpResponseStatisticsCollector.class); { List<HttpResponseStatisticsCollector.StatisticsEntry> stats = statisticsCollector.takeStatistics(); assertEquals(0, stats.size()); } { driver.client().newPost("/status.html").execute(); var entry = waitForStatistics(statisticsCollector); assertEquals("http", entry.scheme); assertEquals("POST", entry.method); assertEquals("http.status.2xx", entry.name); assertEquals("write", entry.requestType); assertEquals(1, entry.value); } { driver.client().newGet("/status.html").execute(); var entry = waitForStatistics(statisticsCollector); assertEquals("http", entry.scheme); assertEquals("GET", entry.method); assertEquals("http.status.2xx", entry.name); assertEquals("read", entry.requestType); assertEquals(1, entry.value); } { handler.setRequestType(Request.RequestType.READ); driver.client().newPost("/status.html").execute(); var entry = waitForStatistics(statisticsCollector); assertEquals("Handler overrides request type", "read", entry.requestType); } assertTrue(driver.close()); } private HttpResponseStatisticsCollector.StatisticsEntry waitForStatistics(HttpResponseStatisticsCollector statisticsCollector) { List<HttpResponseStatisticsCollector.StatisticsEntry> entries = Collections.emptyList(); int tries = 0; while (entries.isEmpty() && tries < 10000) { entries = statisticsCollector.takeStatistics(); if (entries.isEmpty()) try {Thread.sleep(100); } catch (InterruptedException e) {} tries++; } assertEquals(1, entries.size()); return entries.get(0); } @Test public void requireThatConnectionThrottleDoesNotBlockConnectionsBelowThreshold() throws Exception { TestDriver driver = TestDrivers.newConfiguredInstance( new EchoRequestHandler(), new ServerConfig.Builder(), new ConnectorConfig.Builder() .throttling(new Throttling.Builder() .enabled(true) .maxAcceptRate(10) .maxHeapUtilization(1.0) .maxConnections(10))); driver.client().get("/status.html") .expectStatusCode(is(OK)); assertTrue(driver.close()); } @Test public void requireThatMetricIsIncrementedWhenClientIsMissingCertificateOnHandshake() throws IOException { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); var metricConsumer = new MetricConsumerMock(); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); TestDriver driver = createSslTestDriver(certificateFile, privateKeyFile, metricConsumer, connectionLog); SSLContext clientCtx = new SslContextBuilder() .withTrustStore(certificateFile) .build(); assertHttpsRequestTriggersSslHandshakeException( driver, clientCtx, null, null, "Received fatal alert: bad_certificate"); verify(metricConsumer.mockitoMock(), atLeast(1)) .add(MetricDefinitions.SSL_HANDSHAKE_FAILURE_MISSING_CLIENT_CERT, 1L, MetricConsumerMock.STATIC_CONTEXT); assertTrue(driver.close()); Assertions.assertThat(connectionLog.logEntries()).hasSize(1); assertSslHandshakeFailurePresent( connectionLog.logEntries().get(0), SSLHandshakeException.class, SslHandshakeFailure.MISSING_CLIENT_CERT.failureType()); } @Test public void requireThatMetricIsIncrementedWhenClientUsesIncompatibleTlsVersion() throws IOException { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); var metricConsumer = new MetricConsumerMock(); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); TestDriver driver = createSslTestDriver(certificateFile, privateKeyFile, metricConsumer, connectionLog); SSLContext clientCtx = new SslContextBuilder() .withTrustStore(certificateFile) .withKeyStore(privateKeyFile, certificateFile) .build(); boolean tlsv11Enabled = List.of(clientCtx.getDefaultSSLParameters().getProtocols()).contains("TLSv1.1"); assumeTrue("TLSv1.1 must be enabled in installed JDK", tlsv11Enabled); assertHttpsRequestTriggersSslHandshakeException(driver, clientCtx, "TLSv1.1", null, "protocol"); verify(metricConsumer.mockitoMock(), atLeast(1)) .add(MetricDefinitions.SSL_HANDSHAKE_FAILURE_INCOMPATIBLE_PROTOCOLS, 1L, MetricConsumerMock.STATIC_CONTEXT); assertTrue(driver.close()); Assertions.assertThat(connectionLog.logEntries()).hasSize(1); assertSslHandshakeFailurePresent( connectionLog.logEntries().get(0), SSLHandshakeException.class, SslHandshakeFailure.INCOMPATIBLE_PROTOCOLS.failureType()); } @Test public void requireThatMetricIsIncrementedWhenClientUsesIncompatibleCiphers() throws IOException { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); var metricConsumer = new MetricConsumerMock(); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); TestDriver driver = createSslTestDriver(certificateFile, privateKeyFile, metricConsumer, connectionLog); SSLContext clientCtx = new SslContextBuilder() .withTrustStore(certificateFile) .withKeyStore(privateKeyFile, certificateFile) .build(); assertHttpsRequestTriggersSslHandshakeException( driver, clientCtx, null, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", "Received fatal alert: handshake_failure"); verify(metricConsumer.mockitoMock(), atLeast(1)) .add(MetricDefinitions.SSL_HANDSHAKE_FAILURE_INCOMPATIBLE_CIPHERS, 1L, MetricConsumerMock.STATIC_CONTEXT); assertTrue(driver.close()); Assertions.assertThat(connectionLog.logEntries()).hasSize(1); assertSslHandshakeFailurePresent( connectionLog.logEntries().get(0), SSLHandshakeException.class, SslHandshakeFailure.INCOMPATIBLE_CIPHERS.failureType()); } @Test public void requireThatMetricIsIncrementedWhenClientUsesInvalidCertificateInHandshake() throws IOException { Path serverPrivateKeyFile = tmpFolder.newFile().toPath(); Path serverCertificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(serverPrivateKeyFile, serverCertificateFile); var metricConsumer = new MetricConsumerMock(); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); TestDriver driver = createSslTestDriver(serverCertificateFile, serverPrivateKeyFile, metricConsumer, connectionLog); Path clientPrivateKeyFile = tmpFolder.newFile().toPath(); Path clientCertificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(clientPrivateKeyFile, clientCertificateFile); SSLContext clientCtx = new SslContextBuilder() .withKeyStore(clientPrivateKeyFile, clientCertificateFile) .withTrustStore(serverCertificateFile) .build(); assertHttpsRequestTriggersSslHandshakeException( driver, clientCtx, null, null, "Received fatal alert: certificate_unknown"); verify(metricConsumer.mockitoMock(), atLeast(1)) .add(MetricDefinitions.SSL_HANDSHAKE_FAILURE_INVALID_CLIENT_CERT, 1L, MetricConsumerMock.STATIC_CONTEXT); assertTrue(driver.close()); Assertions.assertThat(connectionLog.logEntries()).hasSize(1); assertSslHandshakeFailurePresent( connectionLog.logEntries().get(0), SSLHandshakeException.class, SslHandshakeFailure.INVALID_CLIENT_CERT.failureType()); } @Test public void requireThatMetricIsIncrementedWhenClientUsesExpiredCertificateInHandshake() throws IOException { Path rootPrivateKeyFile = tmpFolder.newFile().toPath(); Path rootCertificateFile = tmpFolder.newFile().toPath(); Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); Instant notAfter = Instant.now().minus(100, ChronoUnit.DAYS); generatePrivateKeyAndCertificate(rootPrivateKeyFile, rootCertificateFile, privateKeyFile, certificateFile, notAfter); var metricConsumer = new MetricConsumerMock(); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); TestDriver driver = createSslTestDriver(rootCertificateFile, rootPrivateKeyFile, metricConsumer, connectionLog); SSLContext clientCtx = new SslContextBuilder() .withTrustStore(rootCertificateFile) .withKeyStore(privateKeyFile, certificateFile) .build(); assertHttpsRequestTriggersSslHandshakeException( driver, clientCtx, null, null, "Received fatal alert: certificate_unknown"); verify(metricConsumer.mockitoMock(), atLeast(1)) .add(MetricDefinitions.SSL_HANDSHAKE_FAILURE_EXPIRED_CLIENT_CERT, 1L, MetricConsumerMock.STATIC_CONTEXT); assertTrue(driver.close()); Assertions.assertThat(connectionLog.logEntries()).hasSize(1); } @Test public void requireThatProxyProtocolIsAcceptedAndActualRemoteAddressStoredInAccessLog() throws Exception { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); InMemoryRequestLog requestLogMock = new InMemoryRequestLog(); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); TestDriver driver = createSslWithProxyProtocolTestDriver(certificateFile, privateKeyFile, requestLogMock, /*mixedMode*/connectionLog, false); String proxiedRemoteAddress = "192.168.0.100"; int proxiedRemotePort = 12345; sendJettyClientRequest(driver, certificateFile, new V1.Tag(proxiedRemoteAddress, proxiedRemotePort)); sendJettyClientRequest(driver, certificateFile, new V2.Tag(proxiedRemoteAddress, proxiedRemotePort)); assertTrue(driver.close()); assertEquals(2, requestLogMock.entries().size()); assertLogEntryHasRemote(requestLogMock.entries().get(0), proxiedRemoteAddress, proxiedRemotePort); assertLogEntryHasRemote(requestLogMock.entries().get(1), proxiedRemoteAddress, proxiedRemotePort); Assertions.assertThat(connectionLog.logEntries()).hasSize(2); assertLogEntryHasRemote(connectionLog.logEntries().get(0), proxiedRemoteAddress, proxiedRemotePort); assertLogEntryHasRemote(connectionLog.logEntries().get(1), proxiedRemoteAddress, proxiedRemotePort); } @Test public void requireThatConnectorWithProxyProtocolMixedEnabledAcceptsBothProxyProtocolAndHttps() throws Exception { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); InMemoryRequestLog requestLogMock = new InMemoryRequestLog(); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); TestDriver driver = createSslWithProxyProtocolTestDriver(certificateFile, privateKeyFile, requestLogMock, /*mixedMode*/connectionLog, true); String proxiedRemoteAddress = "192.168.0.100"; sendJettyClientRequest(driver, certificateFile, null); sendJettyClientRequest(driver, certificateFile, new V2.Tag(proxiedRemoteAddress, 12345)); assertTrue(driver.close()); assertEquals(2, requestLogMock.entries().size()); assertLogEntryHasRemote(requestLogMock.entries().get(0), "127.0.0.1", 0); assertLogEntryHasRemote(requestLogMock.entries().get(1), proxiedRemoteAddress, 0); Assertions.assertThat(connectionLog.logEntries()).hasSize(2); assertLogEntryHasRemote(connectionLog.logEntries().get(0), null, 0); assertLogEntryHasRemote(connectionLog.logEntries().get(1), proxiedRemoteAddress, 12345); } @Test public void requireThatJdiscLocalPortPropertyIsNotOverriddenByProxyProtocol() throws Exception { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); InMemoryRequestLog requestLogMock = new InMemoryRequestLog(); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); TestDriver driver = createSslWithProxyProtocolTestDriver(certificateFile, privateKeyFile, requestLogMock, connectionLog, /*mixedMode*/false); String proxiedRemoteAddress = "192.168.0.100"; int proxiedRemotePort = 12345; String proxyLocalAddress = "10.0.0.10"; int proxyLocalPort = 23456; V2.Tag v2Tag = new V2.Tag(V2.Tag.Command.PROXY, null, V2.Tag.Protocol.STREAM, proxiedRemoteAddress, proxiedRemotePort, proxyLocalAddress, proxyLocalPort, null); ContentResponse response = sendJettyClientRequest(driver, certificateFile, v2Tag); assertTrue(driver.close()); int clientPort = Integer.parseInt(response.getHeaders().get("Jdisc-Local-Port")); assertNotEquals(proxyLocalPort, clientPort); assertNotEquals(proxyLocalPort, connectionLog.logEntries().get(0).localPort().get().intValue()); } @Test public void requireThatConnectionIsTrackedInConnectionLog() throws Exception { Path privateKeyFile = tmpFolder.newFile().toPath(); Path certificateFile = tmpFolder.newFile().toPath(); generatePrivateKeyAndCertificate(privateKeyFile, certificateFile); InMemoryConnectionLog connectionLog = new InMemoryConnectionLog(); Module overrideModule = binder -> binder.bind(ConnectionLog.class).toInstance(connectionLog); TestDriver driver = TestDrivers.newInstanceWithSsl(new OkRequestHandler(), certificateFile, privateKeyFile, TlsClientAuth.NEED, overrideModule); int listenPort = driver.server().getListenPort(); StringBuilder builder = new StringBuilder(); for (int i = 0; i < 1000; i++) { builder.append(i); } byte[] content = builder.toString().getBytes(); for (int i = 0; i < 100; i++) { driver.client().newPost("/status.html").setBinaryContent(content).execute() .expectStatusCode(is(OK)); } assertTrue(driver.close()); List<ConnectionLogEntry> logEntries = connectionLog.logEntries(); Assertions.assertThat(logEntries).hasSize(1); ConnectionLogEntry logEntry = logEntries.get(0); assertEquals(4, UUID.fromString(logEntry.id()).version()); Assertions.assertThat(logEntry.timestamp()).isAfter(Instant.EPOCH); Assertions.assertThat(logEntry.requests()).hasValue(100L); Assertions.assertThat(logEntry.responses()).hasValue(100L); Assertions.assertThat(logEntry.peerAddress()).hasValue("127.0.0.1"); Assertions.assertThat(logEntry.localAddress()).hasValue("127.0.0.1"); Assertions.assertThat(logEntry.localPort()).hasValue(listenPort); Assertions.assertThat(logEntry.httpBytesReceived()).hasValueSatisfying(value -> Assertions.assertThat(value).isGreaterThan(100000L)); Assertions.assertThat(logEntry.httpBytesSent()).hasValueSatisfying(value -> Assertions.assertThat(value).isGreaterThan(10000L)); Assertions.assertThat(logEntry.sslProtocol()).hasValueSatisfying(TlsContext.ALLOWED_PROTOCOLS::contains); Assertions.assertThat(logEntry.sslPeerSubject()).hasValue("CN=localhost"); Assertions.assertThat(logEntry.sslCipherSuite()).hasValueSatisfying(cipher -> Assertions.assertThat(cipher).isNotBlank()); Assertions.assertThat(logEntry.sslSessionId()).hasValueSatisfying(sessionId -> Assertions.assertThat(sessionId).hasSize(64)); Assertions.assertThat(logEntry.sslPeerNotBefore()).hasValue(Instant.EPOCH); Assertions.assertThat(logEntry.sslPeerNotAfter()).hasValue(Instant.EPOCH.plus(100_000, ChronoUnit.DAYS)); } @Test public void requireThatRequestIsTrackedInAccessLog() throws IOException { InMemoryRequestLog requestLogMock = new InMemoryRequestLog(); TestDriver driver = TestDrivers.newConfiguredInstance( new EchoRequestHandler(), new ServerConfig.Builder(), new ConnectorConfig.Builder(), binder -> binder.bind(RequestLog.class).toInstance(requestLogMock)); driver.client().newPost("/status.html").setContent("abcdef").execute().expectStatusCode(is(OK)); assertThat(driver.close(), is(true)); RequestLogEntry entry = requestLogMock.entries().get(0); Assertions.assertThat(entry.statusCode()).hasValue(200); Assertions.assertThat(entry.requestSize()).hasValue(6); } private ContentResponse sendJettyClientRequest(TestDriver testDriver, Path certificateFile, Object tag) throws Exception { HttpClient client = createJettyHttpClient(certificateFile); try { int maxAttempts = 3; for (int attempt = 0; attempt < maxAttempts; attempt++) { try { ContentResponse response = client.newRequest(URI.create("https://localhost:" + testDriver.server().getListenPort() + "/")) .tag(tag) .send(); assertEquals(200, response.getStatus()); return response; } catch (ExecutionException e) { // Retry when the server closes the connection before the TLS handshake is completed. This have been observed in CI. // We have been unable to reproduce this locally. The cause is therefor currently unknown. log.log(Level.WARNING, String.format("Attempt %d failed: %s", attempt, e.getMessage()), e); Thread.sleep(10); } } throw new AssertionError("Failed to send request, see log for details"); } finally { client.stop(); } } // Using Jetty's http client as Apache httpclient does not support the proxy-protocol v1/v2. private static HttpClient createJettyHttpClient(Path certificateFile) throws Exception { SslContextFactory.Client clientSslCtxFactory = new SslContextFactory.Client(); clientSslCtxFactory.setHostnameVerifier(NoopHostnameVerifier.INSTANCE); clientSslCtxFactory.setSslContext(new SslContextBuilder().withTrustStore(certificateFile).build()); HttpClient client = new HttpClient(clientSslCtxFactory); client.start(); return client; } private static void assertLogEntryHasRemote(RequestLogEntry entry, String expectedAddress, int expectedPort) { assertEquals(expectedAddress, entry.peerAddress().get()); if (expectedPort > 0) { assertEquals(expectedPort, entry.peerPort().getAsInt()); } } private static void assertLogEntryHasRemote(ConnectionLogEntry entry, String expectedAddress, int expectedPort) { if (expectedAddress != null) { Assertions.assertThat(entry.remoteAddress()).hasValue(expectedAddress); } else { Assertions.assertThat(entry.remoteAddress()).isEmpty(); } if (expectedPort > 0) { Assertions.assertThat(entry.remotePort()).hasValue(expectedPort); } else { Assertions.assertThat(entry.remotePort()).isEmpty(); } } private static void assertSslHandshakeFailurePresent( ConnectionLogEntry entry, Class<? extends SSLHandshakeException> expectedException, String expectedType) { Assertions.assertThat(entry.sslHandshakeFailure()).isPresent(); ConnectionLogEntry.SslHandshakeFailure failure = entry.sslHandshakeFailure().get(); assertEquals(expectedType, failure.type()); ExceptionEntry exceptionEntry = failure.exceptionChain().get(0); assertEquals(expectedException.getName(), exceptionEntry.name()); } private static TestDriver createSslWithProxyProtocolTestDriver( Path certificateFile, Path privateKeyFile, RequestLog requestLog, ConnectionLog connectionLog, boolean mixedMode) { ConnectorConfig.Builder connectorConfig = new ConnectorConfig.Builder() .proxyProtocol(new ConnectorConfig.ProxyProtocol.Builder() .enabled(true) .mixedMode(mixedMode)) .ssl(new ConnectorConfig.Ssl.Builder() .enabled(true) .privateKeyFile(privateKeyFile.toString()) .certificateFile(certificateFile.toString()) .caCertificateFile(certificateFile.toString())); return TestDrivers.newConfiguredInstance( new EchoRequestHandler(), new ServerConfig.Builder().connectionLog(new ServerConfig.ConnectionLog.Builder().enabled(true)), connectorConfig, binder -> { binder.bind(RequestLog.class).toInstance(requestLog); binder.bind(ConnectionLog.class).toInstance(connectionLog); }); } private static TestDriver createSslTestDriver( Path serverCertificateFile, Path serverPrivateKeyFile, MetricConsumerMock metricConsumer, InMemoryConnectionLog connectionLog) throws IOException { Module extraModule = binder -> { binder.bind(MetricConsumer.class).toInstance(metricConsumer.mockitoMock()); binder.bind(ConnectionLog.class).toInstance(connectionLog); }; return TestDrivers.newInstanceWithSsl( new EchoRequestHandler(), serverCertificateFile, serverPrivateKeyFile, TlsClientAuth.NEED, extraModule); } private static void assertHttpsRequestTriggersSslHandshakeException( TestDriver testDriver, SSLContext sslContext, String protocolOverride, String cipherOverride, String expectedExceptionSubstring) throws IOException { List<String> protocols = protocolOverride != null ? List.of(protocolOverride) : null; List<String> ciphers = cipherOverride != null ? List.of(cipherOverride) : null; try (var client = new SimpleHttpClient(sslContext, protocols, ciphers, testDriver.server().getListenPort(), false)) { client.get("/status.html"); fail("SSLHandshakeException expected"); } catch (SSLHandshakeException e) { assertThat(e.getMessage(), containsString(expectedExceptionSubstring)); } catch (SSLException e) { // This exception is thrown if Apache httpclient's write thread detects the handshake failure before the read thread. log.log(Level.WARNING, "Client failed to get a proper TLS handshake response: " + e.getMessage(), e); // Only ignore a subset of exceptions assertThat(e.getMessage(), anyOf(containsString("readHandshakeRecord"), containsString("Broken pipe"))); } } private static void generatePrivateKeyAndCertificate(Path privateKeyFile, Path certificateFile) throws IOException { KeyPair keyPair = KeyUtils.generateKeypair(EC); Files.writeString(privateKeyFile, KeyUtils.toPem(keyPair.getPrivate())); X509Certificate certificate = X509CertificateBuilder .fromKeypair( keyPair, new X500Principal("CN=localhost"), Instant.EPOCH, Instant.EPOCH.plus(100_000, ChronoUnit.DAYS), SHA256_WITH_ECDSA, BigInteger.ONE) .build(); Files.writeString(certificateFile, X509CertificateUtils.toPem(certificate)); } private static void generatePrivateKeyAndCertificate(Path rootPrivateKeyFile, Path rootCertificateFile, Path privateKeyFile, Path certificateFile, Instant notAfter) throws IOException { generatePrivateKeyAndCertificate(rootPrivateKeyFile, rootCertificateFile); X509Certificate rootCertificate = X509CertificateUtils.fromPem(Files.readString(rootCertificateFile)); PrivateKey privateKey = KeyUtils.fromPemEncodedPrivateKey(Files.readString(rootPrivateKeyFile)); KeyPair keyPair = KeyUtils.generateKeypair(EC); Files.writeString(privateKeyFile, KeyUtils.toPem(keyPair.getPrivate())); Pkcs10Csr csr = Pkcs10CsrBuilder.fromKeypair(new X500Principal("CN=myclient"), keyPair, SHA256_WITH_ECDSA).build(); X509Certificate certificate = X509CertificateBuilder .fromCsr(csr, rootCertificate.getSubjectX500Principal(), Instant.EPOCH, notAfter, privateKey, SHA256_WITH_ECDSA, BigInteger.ONE) .build(); Files.writeString(certificateFile, X509CertificateUtils.toPem(certificate)); } private static RequestHandler mockRequestHandler() { final RequestHandler mockRequestHandler = mock(RequestHandler.class); when(mockRequestHandler.refer()).thenReturn(References.NOOP_REFERENCE); return mockRequestHandler; } private static String generateContent(final char c, final int len) { final StringBuilder ret = new StringBuilder(len); for (int i = 0; i < len; ++i) { ret.append(c); } return ret.toString(); } private static TestDriver newDriverWithFormPostContentRemoved(RequestHandler requestHandler, boolean removeFormPostBody) throws Exception { return TestDrivers.newConfiguredInstance( requestHandler, new ServerConfig.Builder() .removeRawPostBodyForWwwUrlEncodedPost(removeFormPostBody), new ConnectorConfig.Builder()); } private static FormBodyPart newFileBody(final String parameterName, final String fileName, final String fileContent) { return new FormBodyPart( parameterName, new StringBody(fileContent, ContentType.TEXT_PLAIN) { @Override public String getFilename() { return fileName; } @Override public String getTransferEncoding() { return "binary"; } @Override public String getMimeType() { return ""; } @Override public String getCharset() { return null; } }); } private static class ConnectedAtRequestHandler extends AbstractRequestHandler { @Override public ContentChannel handleRequest(final Request request, final ResponseHandler handler) { final HttpRequest httpRequest = (HttpRequest)request; final String connectedAt = String.valueOf(httpRequest.getConnectedAt(TimeUnit.MILLISECONDS)); final ContentChannel ch = handler.handleResponse(new Response(OK)); ch.write(ByteBuffer.wrap(connectedAt.getBytes(StandardCharsets.UTF_8)), null); ch.close(null); return null; } } private static class CookieSetterRequestHandler extends AbstractRequestHandler { final Cookie cookie; CookieSetterRequestHandler(final Cookie cookie) { this.cookie = cookie; } @Override public ContentChannel handleRequest(final Request request, final ResponseHandler handler) { final HttpResponse response = HttpResponse.newInstance(OK); response.encodeSetCookieHeader(Collections.singletonList(cookie)); ResponseDispatch.newInstance(response).dispatch(handler); return null; } } private static class CookiePrinterRequestHandler extends AbstractRequestHandler { @Override public ContentChannel handleRequest(final Request request, final ResponseHandler handler) { final List<Cookie> cookies = new ArrayList<>(((HttpRequest)request).decodeCookieHeader()); Collections.sort(cookies, new CookieComparator()); final ContentChannel out = ResponseDispatch.newInstance(Response.Status.OK).connect(handler); out.write(StandardCharsets.UTF_8.encode(cookies.toString()), null); out.close(null); return null; } } private static class ParameterPrinterRequestHandler extends AbstractRequestHandler { private static final CompletionHandler NULL_COMPLETION_HANDLER = null; @Override public ContentChannel handleRequest(Request request, ResponseHandler handler) { Map<String, List<String>> parameters = new TreeMap<>(((HttpRequest)request).parameters()); ContentChannel responseContentChannel = ResponseDispatch.newInstance(Response.Status.OK).connect(handler); responseContentChannel.write(ByteBuffer.wrap(parameters.toString().getBytes(StandardCharsets.UTF_8)), NULL_COMPLETION_HANDLER); // Have the request content written back to the response. return responseContentChannel; } } private static class RequestTypeHandler extends AbstractRequestHandler { private Request.RequestType requestType = null; public void setRequestType(Request.RequestType requestType) { this.requestType = requestType; } @Override public ContentChannel handleRequest(Request request, ResponseHandler handler) { Response response = new Response(OK); response.setRequestType(requestType); return handler.handleResponse(response); } } private static class ThrowingHandler extends AbstractRequestHandler { @Override public ContentChannel handleRequest(final Request request, final ResponseHandler handler) { throw new RuntimeException("Deliberately thrown exception"); } } private static class UnresponsiveHandler extends AbstractRequestHandler { ResponseHandler responseHandler; @Override public ContentChannel handleRequest(final Request request, final ResponseHandler handler) { request.setTimeout(100, TimeUnit.MILLISECONDS); responseHandler = handler; return null; } } private static class EchoRequestHandler extends AbstractRequestHandler { @Override public ContentChannel handleRequest(final Request request, final ResponseHandler handler) { int port = request.getUri().getPort(); Response response = new Response(OK); response.headers().put("Jdisc-Local-Port", Integer.toString(port)); return handler.handleResponse(response); } } private static class OkRequestHandler extends AbstractRequestHandler { @Override public ContentChannel handleRequest(Request request, ResponseHandler handler) { Response response = new Response(OK); handler.handleResponse(response).close(null); return NullContent.INSTANCE; } } private static class EchoWithHeaderRequestHandler extends AbstractRequestHandler { final String headerName; final String headerValue; EchoWithHeaderRequestHandler(final String headerName, final String headerValue) { this.headerName = headerName; this.headerValue = headerValue; } @Override public ContentChannel handleRequest(final Request request, final ResponseHandler handler) { final Response response = new Response(OK); response.headers().add(headerName, headerValue); return handler.handleResponse(response); } } private static Module newBindingSetSelector(final String setName) { return new AbstractModule() { @Override protected void configure() { bind(BindingSetSelector.class).toInstance(new BindingSetSelector() { @Override public String select(final URI uri) { return setName; } }); } }; } private static class CookieComparator implements Comparator<Cookie> { @Override public int compare(final Cookie lhs, final Cookie rhs) { return lhs.getName().compareTo(rhs.getName()); } } }
Use BlockingQueueRequestLog
container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpServerTest.java
Use BlockingQueueRequestLog
<ide><path>ontainer-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpServerTest.java <ide> } <ide> <ide> @Test <del> public void requireThatRequestIsTrackedInAccessLog() throws IOException { <del> InMemoryRequestLog requestLogMock = new InMemoryRequestLog(); <add> public void requireThatRequestIsTrackedInAccessLog() throws IOException, InterruptedException { <add> BlockingQueueRequestLog requestLogMock = new BlockingQueueRequestLog(); <ide> TestDriver driver = TestDrivers.newConfiguredInstance( <ide> new EchoRequestHandler(), <ide> new ServerConfig.Builder(), <ide> binder -> binder.bind(RequestLog.class).toInstance(requestLogMock)); <ide> driver.client().newPost("/status.html").setContent("abcdef").execute().expectStatusCode(is(OK)); <ide> assertThat(driver.close(), is(true)); <del> RequestLogEntry entry = requestLogMock.entries().get(0); <add> RequestLogEntry entry = requestLogMock.poll(Duration.ofSeconds(30)); <ide> Assertions.assertThat(entry.statusCode()).hasValue(200); <ide> Assertions.assertThat(entry.requestSize()).hasValue(6); <ide> }
Java
apache-2.0
5d421a4002ecf90d5ecef834eb806d0ee34f54a4
0
qtproject/qtqa-gerrit,WANdisco/gerrit,joshuawilson/merrit,joshuawilson/merrit,MerritCR/merrit,joshuawilson/merrit,gerrit-review/gerrit,joshuawilson/merrit,MerritCR/merrit,joshuawilson/merrit,MerritCR/merrit,GerritCodeReview/gerrit,gerrit-review/gerrit,qtproject/qtqa-gerrit,MerritCR/merrit,qtproject/qtqa-gerrit,WANdisco/gerrit,gerrit-review/gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,gerrit-review/gerrit,MerritCR/merrit,joshuawilson/merrit,GerritCodeReview/gerrit,MerritCR/merrit,GerritCodeReview/gerrit,WANdisco/gerrit,gerrit-review/gerrit,WANdisco/gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,WANdisco/gerrit,gerrit-review/gerrit,GerritCodeReview/gerrit,joshuawilson/merrit,MerritCR/merrit,gerrit-review/gerrit,WANdisco/gerrit,MerritCR/merrit,joshuawilson/merrit
// Copyright (C) 2015 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.extensions.api.groups; import com.google.gerrit.extensions.client.ListGroupsOption; import com.google.gerrit.extensions.common.GroupInfo; import com.google.gerrit.extensions.restapi.NotImplementedException; import com.google.gerrit.extensions.restapi.RestApiException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Map; public interface Groups { /** * Look up a group by ID. * <p> * <strong>Note:</strong> This method eagerly reads the group. Methods that * mutate the group do not necessarily re-read the group. Therefore, calling a * getter method on an instance after calling a mutation method on that same * instance is not guaranteed to reflect the mutation. It is not recommended * to store references to {@code groupApi} instances. * * @param id any identifier supported by the REST API, including group name or * UUID. * @return API for accessing the group. * @throws RestApiException if an error occurred. */ GroupApi id(String id) throws RestApiException; /** Create a new group with the given name and default options. */ GroupApi create(String name) throws RestApiException; /** Create a new group. */ GroupApi create(GroupInput input) throws RestApiException; /** @return new request for listing groups. */ ListRequest list(); abstract class ListRequest { private final EnumSet<ListGroupsOption> options = EnumSet.noneOf(ListGroupsOption.class); private final List<String> projects = new ArrayList<>(); private final List<String> groups = new ArrayList<>(); private boolean visibleToAll; private String user; private boolean owned; private int limit; private int start; private String substring; private String suggest; public List<GroupInfo> get() throws RestApiException { Map<String, GroupInfo> map = getAsMap(); List<GroupInfo> result = new ArrayList<>(map.size()); for (Map.Entry<String, GroupInfo> e : map.entrySet()) { // ListGroups "helpfully" nulls out names when converting to a map. e.getValue().name = e.getKey(); result.add(e.getValue()); } return Collections.unmodifiableList(result); } public abstract Map<String, GroupInfo> getAsMap() throws RestApiException; public ListRequest addOption(ListGroupsOption option) { options.add(option); return this; } public ListRequest addOptions(ListGroupsOption... options) { return addOptions(Arrays.asList(options)); } public ListRequest addOptions(Iterable<ListGroupsOption> options) { for (ListGroupsOption option : options) { this.options.add(option); } return this; } public ListRequest withProject(String project) { projects.add(project); return this; } public ListRequest addGroup(String uuid) { groups.add(uuid); return this; } public ListRequest withVisibleToAll(boolean visible) { visibleToAll = visible; return this; } public ListRequest withUser(String user) { this.user = user; return this; } public ListRequest withOwned(boolean owned) { this.owned = owned; return this; } public ListRequest withLimit(int limit) { this.limit = limit; return this; } public ListRequest withStart(int start) { this.start = start; return this; } public ListRequest withSubstring(String substring) { this.substring = substring; return this; } public ListRequest withSuggest(String suggest) { this.suggest = suggest; return this; } public EnumSet<ListGroupsOption> getOptions() { return options; } public List<String> getProjects() { return Collections.unmodifiableList(projects); } public List<String> getGroups() { return Collections.unmodifiableList(groups); } public boolean getVisibleToAll() { return visibleToAll; } public String getUser() { return user; } public boolean getOwned() { return owned; } public int getLimit() { return limit; } public int getStart() { return start; } public String getSubstring() { return substring; } public String getSuggest() { return suggest; } } /** * A default implementation which allows source compatibility * when adding new methods to the interface. **/ class NotImplemented implements Groups { @Override public GroupApi id(String id) throws RestApiException { throw new NotImplementedException(); } @Override public GroupApi create(String name) throws RestApiException { throw new NotImplementedException(); } @Override public GroupApi create(GroupInput input) throws RestApiException { throw new NotImplementedException(); } @Override public ListRequest list() { throw new NotImplementedException(); } } }
gerrit-extension-api/src/main/java/com/google/gerrit/extensions/api/groups/Groups.java
// Copyright (C) 2015 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.extensions.api.groups; import com.google.gerrit.extensions.client.ListGroupsOption; import com.google.gerrit.extensions.common.GroupInfo; import com.google.gerrit.extensions.restapi.NotImplementedException; import com.google.gerrit.extensions.restapi.RestApiException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Map; public interface Groups { /** * Look up a group by ID. * <p> * <strong>Note:</strong> This method eagerly reads the group. Methods that * mutate the group do not necessarily re-read the group. Therefore, calling a * getter method on an instance after calling a mutation method on that same * instance is not guaranteed to reflect the mutation. It is not recommended * to store references to {@code groupApi} instances. * * @param id any identifier supported by the REST API, including group name or * UUID. * @return API for accessing the group. * @throws RestApiException if an error occurred. */ GroupApi id(String id) throws RestApiException; /** Create a new group with the given name and default options. */ GroupApi create(String name) throws RestApiException; /** Create a new group. */ GroupApi create(GroupInput input) throws RestApiException; /** @return new request for listing groups. */ ListRequest list(); abstract class ListRequest { private final EnumSet<ListGroupsOption> options = EnumSet.noneOf(ListGroupsOption.class); private final List<String> projects = new ArrayList<>(); private final List<String> groups = new ArrayList<>(); private boolean visibleToAll; private String user; private boolean owned; private int limit; private int start; private String substring; private String suggest; public List<GroupInfo> get() throws RestApiException { Map<String, GroupInfo> map = getAsMap(); List<GroupInfo> result = new ArrayList<>(map.size()); for (Map.Entry<String, GroupInfo> e : map.entrySet()) { // ListGroups "helpfully" nulls out names when converting to a map. e.getValue().name = e.getKey(); result.add(e.getValue()); } return Collections.unmodifiableList(result); } public abstract Map<String, GroupInfo> getAsMap() throws RestApiException; public ListRequest addOption(ListGroupsOption option) { options.add(option); return this; } public ListRequest addOptions(ListGroupsOption... options) { return addOptions(Arrays.asList(options)); } public ListRequest addOptions(Iterable<ListGroupsOption> options) { for (ListGroupsOption option : options) { this.options.add(option); } return this; } public ListRequest withProject(String project) { projects.add(project); return this; } public ListRequest addGroup(String uuid) { groups.add(uuid); return this; } public ListRequest withVisibleToAll(boolean visible) { visibleToAll = visible; return this; } public ListRequest withUser(String user) { this.user = user; return this; } public ListRequest withLimit(int limit) { this.limit = limit; return this; } public ListRequest withStart(int start) { this.start = start; return this; } public ListRequest withSubstring(String substring) { this.substring = substring; return this; } public ListRequest withSuggest(String suggest) { this.suggest = suggest; return this; } public EnumSet<ListGroupsOption> getOptions() { return options; } public List<String> getProjects() { return Collections.unmodifiableList(projects); } public List<String> getGroups() { return Collections.unmodifiableList(groups); } public boolean getVisibleToAll() { return visibleToAll; } public String getUser() { return user; } public boolean getOwned() { return owned; } public int getLimit() { return limit; } public int getStart() { return start; } public String getSubstring() { return substring; } public String getSuggest() { return suggest; } } /** * A default implementation which allows source compatibility * when adding new methods to the interface. **/ class NotImplemented implements Groups { @Override public GroupApi id(String id) throws RestApiException { throw new NotImplementedException(); } @Override public GroupApi create(String name) throws RestApiException { throw new NotImplementedException(); } @Override public GroupApi create(GroupInput input) throws RestApiException { throw new NotImplementedException(); } @Override public ListRequest list() { throw new NotImplementedException(); } } }
Groups: Add missing fluent setter ListRequest#withOwned Change-Id: Ibb50df85f82bbbb4f7d6fb1d6794519160b5f7db
gerrit-extension-api/src/main/java/com/google/gerrit/extensions/api/groups/Groups.java
Groups: Add missing fluent setter ListRequest#withOwned
<ide><path>errit-extension-api/src/main/java/com/google/gerrit/extensions/api/groups/Groups.java <ide> return this; <ide> } <ide> <add> public ListRequest withOwned(boolean owned) { <add> this.owned = owned; <add> return this; <add> } <add> <ide> public ListRequest withLimit(int limit) { <ide> this.limit = limit; <ide> return this;
JavaScript
mit
50c193f170d4f148ec91f4b44bc60713279d0498
0
ARCANESOFT/foundation-assets,ARCANESOFT/foundation-assets
'use strict'; /* -------------------------------------------------------------------------- * Gulp libs * -------------------------------------------------------------------------- */ var gulp = require('gulp'), concat = require('gulp-concat'), less = require('gulp-less'), minifyCss = require('gulp-minify-css'), notify = require('gulp-notify'), rename = require('gulp-rename'), uglify = require('gulp-uglify'); /* -------------------------------------------------------------------------- * Directories & Files * -------------------------------------------------------------------------- */ var dirs = {}; dirs.base = '.'; dirs.bower = dirs.base + '/bower'; dirs.src = dirs.base + '/src'; dirs.dist = dirs.base + '/dist'; var files = { vendorJs: [ dirs.bower + '/jquery/dist/jquery.js', dirs.bower + '/jquery-ui/jquery-ui.js', dirs.src + '/js/vendors/jquery-ui-fix.js', dirs.bower + '/bootstrap/dist/js/bootstrap.js', dirs.bower + '/vue/dist/vue.js', dirs.bower + '/raphael/raphael.js', dirs.bower + '/morris.js/morris.js', dirs.bower + '/sweetalert/dist/sweetalert-dev.js', dirs.src + '/js/vendors/jquery.sparkline.js', dirs.src + '/js/vendors/jquery-jvectormap.js', dirs.src + '/js/vendors/jquery-jvectormap-world-mill-en.js', dirs.bower + '/jquery-knob/js/jquery.knob.js', dirs.bower + '/moment/moment.js', dirs.bower + '/fullcalendar/dist/fullcalendar.js', dirs.bower + '/fullcalendar/dist/lang-all.js', dirs.bower + '/bootstrap-daterangepicker/daterangepicker.js', dirs.bower + '/bootstrap-daterangepicker/daterangepicker.js', dirs.bower + '/bootstrap-datepicker/dist/js/bootstrap-datepicker.js', dirs.src + '/js/vendors/bootstrap-datepicker-fix.js', dirs.src + '/js/vendors/bootstrap3-wysihtml5.all.js', dirs.bower + '/slimScroll/jquery.slimscroll.js', dirs.bower + '/fastclick/lib/fastclick.js', dirs.bower + '/ion.rangeslider/js/ion.rangeSlider.js', dirs.bower + '/seiyria-bootstrap-slider/js/bootstrap-slider.js' ], fonts: [ dirs.bower + '/bootstrap/fonts/*', dirs.bower + '/font-awesome/fonts/*', dirs.bower + '/ionicons/fonts/*' ] }; /* -------------------------------------------------------------------------- * Main Tasks * -------------------------------------------------------------------------- */ gulp.task('all', [ 'default', 'vendors' ]); gulp.task('default', [ 'less', 'js' ]); gulp.task('vendors', [ 'js-vendors', 'img-vendors', 'fonts-vendors' ]); /* -------------------------------------------------------------------------- * Tasks * -------------------------------------------------------------------------- */ gulp.task('less', function () { return gulp.src(dirs.src + '/less/style.less') .on('error', notify.onError({ title: 'Error compiling LESS.', message: 'Error: <%= error.message %>', onLast: true, sound: true })) .pipe(less()) .pipe(gulp.dest(dirs.dist + '/css')) .pipe(minifyCss({ keepSpecialComments: 0 })) .pipe(rename({ extname: '.min.css' })) .pipe(gulp.dest(dirs.dist + '/css/')) .pipe(notify({ title: 'Less compiled', message: 'Less compiled with success !', onLast: true, sound: false })); }); gulp.task('js', function () { return gulp.src(dirs.src + '/js/main.js') .on('error', notify.onError({ title: 'Error compiling Javascript.', message: 'Error: <%= error.message %>', onLast: true, sound: true })) .pipe(gulp.dest(dirs.dist + '/js')) .pipe(uglify()) .pipe(rename({ extname: '.min.js' })) .pipe(gulp.dest(dirs.dist + '/js')) .pipe(notify({ title: 'Javascript compiled', message: 'Javascript compiled with success !', onLast: true, sound: false })); }); gulp.task('js-vendors', function() { return gulp.src(files.vendorJs) .pipe(concat('vendors.js')) .pipe(gulp.dest(dirs.dist + '/js')) .pipe(uglify()) .pipe(rename({ extname: '.min.js' })) .pipe(gulp.dest(dirs.dist + '/js')); }); gulp.task('img-vendors', function() { return gulp.src(dirs.bower + '/ion.rangeslider/img/*') .pipe(gulp.dest(dirs.dist + '/img/plugins/RangeSlider')); }); gulp.task('fonts-vendors', function() { return gulp.src(files.fonts) .pipe(gulp.dest(dirs.dist + '/fonts')); });
gulpfile.js
'use strict'; /* -------------------------------------------------------------------------- * Gulp libs * -------------------------------------------------------------------------- */ var gulp = require('gulp'), concat = require('gulp-concat'), less = require('gulp-less'), minifyCss = require('gulp-minify-css'), notify = require('gulp-notify'), rename = require('gulp-rename'), uglify = require('gulp-uglify'); /* -------------------------------------------------------------------------- * Directories & Files * -------------------------------------------------------------------------- */ var dirs = {}; dirs.base = '.'; dirs.bower = dirs.base + '/bower'; dirs.src = dirs.base + '/src'; dirs.dist = dirs.base + '/dist'; var files = { vendorJs: [ dirs.bower + '/jquery/dist/jquery.js', dirs.bower + '/jquery-ui/jquery-ui.js', dirs.src + '/js/vendors/jquery-ui-fix.js', dirs.bower + '/bootstrap/dist/js/bootstrap.js', dirs.bower + '/vue/dist/vue.js', dirs.bower + '/raphael/raphael.js', dirs.bower + '/morris.js/morris.js', dirs.bower + '/sweetalert/dist/sweetalert-dev.js', dirs.src + '/js/vendors/jquery.sparkline.js', dirs.src + '/js/vendors/jquery-jvectormap.js', dirs.src + '/js/vendors/jquery-jvectormap-world-mill-en.js', dirs.bower + '/jquery-knob/js/jquery.knob.js', dirs.bower + '/moment/moment.js', dirs.bower + '/fullcalendar/dist/fullcalendar.js', dirs.bower + '/fullcalendar/dist/lang-all.js', dirs.bower + '/bootstrap-daterangepicker/daterangepicker.js', dirs.bower + '/bootstrap-daterangepicker/daterangepicker.js', dirs.bower + '/bootstrap-datepicker/dist/js/bootstrap-datepicker.js', dirs.src + '/js/vendors/bootstrap-datepicker-fix.js', dirs.src + '/js/vendors/bootstrap3-wysihtml5.all.js', dirs.bower + '/slimScroll/jquery.slimscroll.js', dirs.bower + '/fastclick/lib/fastclick.js' ], fonts: [ dirs.bower + '/bootstrap/fonts/*', dirs.bower + '/font-awesome/fonts/*', dirs.bower + '/ionicons/fonts/*' ] }; /* -------------------------------------------------------------------------- * Main Tasks * -------------------------------------------------------------------------- */ gulp.task('all', [ 'default', 'vendors' ]); gulp.task('default', [ 'less', 'js' ]); gulp.task('vendors', [ 'js-vendors', 'img-vendors', 'fonts-vendors' ]); /* -------------------------------------------------------------------------- * Tasks * -------------------------------------------------------------------------- */ gulp.task('less', function () { return gulp.src(dirs.src + '/less/style.less') .on('error', notify.onError({ title: 'Error compiling LESS.', message: 'Error: <%= error.message %>', onLast: true, sound: true })) .pipe(less()) .pipe(gulp.dest(dirs.dist + '/css')) .pipe(minifyCss({ keepSpecialComments: 0 })) .pipe(rename({ extname: '.min.css' })) .pipe(gulp.dest(dirs.dist + '/css/')) .pipe(notify({ title: 'Less compiled', message: 'Less compiled with success !', onLast: true, sound: false })); }); gulp.task('js', function () { return gulp.src(dirs.src + '/js/main.js') .on('error', notify.onError({ title: 'Error compiling Javascript.', message: 'Error: <%= error.message %>', onLast: true, sound: true })) .pipe(gulp.dest(dirs.dist + '/js')) .pipe(uglify()) .pipe(rename({ extname: '.min.js' })) .pipe(gulp.dest(dirs.dist + '/js')) .pipe(notify({ title: 'Javascript compiled', message: 'Javascript compiled with success !', onLast: true, sound: false })); }); gulp.task('js-vendors', function() { return gulp.src(files.vendorJs) .pipe(concat('vendors.js')) .pipe(gulp.dest(dirs.dist + '/js')) .pipe(uglify()) .pipe(rename({ extname: '.min.js' })) .pipe(gulp.dest(dirs.dist + '/js')); }); gulp.task('img-vendors', function() { // }); gulp.task('fonts-vendors', function() { return gulp.src(files.fonts) .pipe(gulp.dest(dirs.dist + '/fonts')); });
Updating gulpfile.js
gulpfile.js
Updating gulpfile.js
<ide><path>ulpfile.js <ide> dirs.src + '/js/vendors/bootstrap-datepicker-fix.js', <ide> dirs.src + '/js/vendors/bootstrap3-wysihtml5.all.js', <ide> dirs.bower + '/slimScroll/jquery.slimscroll.js', <del> dirs.bower + '/fastclick/lib/fastclick.js' <add> dirs.bower + '/fastclick/lib/fastclick.js', <add> dirs.bower + '/ion.rangeslider/js/ion.rangeSlider.js', <add> dirs.bower + '/seiyria-bootstrap-slider/js/bootstrap-slider.js' <ide> ], <ide> fonts: [ <ide> dirs.bower + '/bootstrap/fonts/*', <ide> }); <ide> <ide> gulp.task('img-vendors', function() { <del> // <add> return gulp.src(dirs.bower + '/ion.rangeslider/img/*') <add> .pipe(gulp.dest(dirs.dist + '/img/plugins/RangeSlider')); <ide> }); <ide> <ide> gulp.task('fonts-vendors', function() {
Java
apache-2.0
61433e690ec10deff1a684199b2ba43ee985c46b
0
netzwerg/paleo
/* * Copyright 2016 Rahel Lüthy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.netzwerg.paleo.io; import ch.netzwerg.paleo.DataFrame; import ch.netzwerg.paleo.schema.Schema; import org.openjdk.jmh.annotations.*; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.concurrent.TimeUnit; @Warmup(iterations = 1) @Measurement(iterations = 1) @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) @SuppressWarnings("unused") public class ParserBenchmarks { // TODO: Generate data in a @Setup fixture (using logic in DataGeneratorTest) private static final String PARENT_DIR = "/Users/netzwerg/switchdrive/Projects/greenrad/Data/Simulated/1-mio/"; private static final String SCHEMA = PARENT_DIR + "artificial.json"; @Benchmark public void parseWithSchema() throws IOException { FileReader schema = new FileReader(SCHEMA); DataFrame dataFrame = Parser.parseTabDelimited(Schema.parseJson(schema), new File(PARENT_DIR)); if (dataFrame.getRowCount() != 1_000_000) { throw new IllegalArgumentException("Parsing failed – expected 1 mio rows"); } } }
paleo-io/src/jmh/java/ch/netzwerg/paleo/io/ParserBenchmarks.java
/* * Copyright 2016 Rahel Lüthy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.netzwerg.paleo.io; import ch.netzwerg.paleo.DataFrame; import ch.netzwerg.paleo.schema.Schema; import org.openjdk.jmh.annotations.*; import java.io.File; import java.io.FileReader; import java.io.IOException; @Warmup(iterations = 1) @Measurement(iterations = 1) @BenchmarkMode(Mode.Throughput) @SuppressWarnings("unused") public class ParserBenchmarks { // TODO: Generate data in a @Setup fixture (using logic in DataGeneratorTest) private static final String PARENT_DIR = "/Users/netzwerg/switchdrive/Projects/greenrad/Data/Simulated/1-mio/"; private static final String SCHEMA = PARENT_DIR + "artificial.json"; @Benchmark public void parseWithSchema() throws IOException { FileReader schema = new FileReader(SCHEMA); DataFrame dataFrame = Parser.parseTabDelimited(Schema.parseJson(schema), new File(PARENT_DIR)); if (dataFrame.getRowCount() != 1_000_000) { throw new IllegalArgumentException("Parsing failed – expected 1 mio rows"); } } }
#17: Measure average execution time in ms
paleo-io/src/jmh/java/ch/netzwerg/paleo/io/ParserBenchmarks.java
#17: Measure average execution time in ms
<ide><path>aleo-io/src/jmh/java/ch/netzwerg/paleo/io/ParserBenchmarks.java <ide> import java.io.File; <ide> import java.io.FileReader; <ide> import java.io.IOException; <add>import java.util.concurrent.TimeUnit; <ide> <ide> @Warmup(iterations = 1) <ide> @Measurement(iterations = 1) <del>@BenchmarkMode(Mode.Throughput) <add>@BenchmarkMode(Mode.AverageTime) <add>@OutputTimeUnit(TimeUnit.MILLISECONDS) <ide> @SuppressWarnings("unused") <ide> public class ParserBenchmarks { <ide>
Java
mit
57b16dcf545d5078fc46313201aef8d93d8b8823
0
markovandooren/chameleon
package org.aikodi.chameleon.support.input; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.StringBufferInputStream; import java.util.HashSet; import java.util.List; import java.util.Set; import org.aikodi.chameleon.core.document.Document; import org.aikodi.chameleon.core.element.Element; import org.aikodi.chameleon.exception.ChameleonProgrammerException; import org.aikodi.chameleon.input.ModelFactory; import org.aikodi.chameleon.input.NoLocationException; import org.aikodi.chameleon.input.ParseException; import org.aikodi.chameleon.input.SourceManager; import org.aikodi.chameleon.plugin.LanguagePluginImpl; import org.aikodi.chameleon.workspace.View; import org.antlr.runtime.RecognitionException; import be.kuleuven.cs.distrinet.rejuse.association.Association; import be.kuleuven.cs.distrinet.rejuse.io.DirectoryScanner; public abstract class ModelFactoryUsingANTLR3 extends LanguagePluginImpl implements ModelFactory { public ModelFactoryUsingANTLR3() { } @Override public abstract ModelFactoryUsingANTLR3 clone(); private boolean _debug; public void setDebug(boolean value) { _debug = value; } public boolean debug() { return _debug; } @Override public void parse(InputStream inputStream, Document cu) throws IOException, ParseException { try { ChameleonANTLR3Parser<?> parser = getParser(inputStream, cu.view()); // cu.disconnectChildren(); //FIXME: this is crap. I set the document, and later on set the view, // while they are (and must be) connected anyway parser.setDocument(cu); parser.compilationUnit(); } catch (RecognitionException e) { throw new ParseException(e,cu); } catch(RuntimeException e) { throw e; } catch (Throwable t) { t.printStackTrace(); } } protected abstract ChameleonANTLR3Parser<?> getParser(InputStream inputStream, View view) throws IOException; }
src/org/aikodi/chameleon/support/input/ModelFactoryUsingANTLR3.java
package org.aikodi.chameleon.support.input; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.StringBufferInputStream; import java.util.HashSet; import java.util.List; import java.util.Set; import org.aikodi.chameleon.core.document.Document; import org.aikodi.chameleon.core.element.Element; import org.aikodi.chameleon.exception.ChameleonProgrammerException; import org.aikodi.chameleon.input.ModelFactory; import org.aikodi.chameleon.input.NoLocationException; import org.aikodi.chameleon.input.ParseException; import org.aikodi.chameleon.input.SourceManager; import org.aikodi.chameleon.plugin.LanguagePluginImpl; import org.aikodi.chameleon.workspace.View; import org.antlr.runtime.RecognitionException; import be.kuleuven.cs.distrinet.rejuse.association.Association; import be.kuleuven.cs.distrinet.rejuse.io.DirectoryScanner; public abstract class ModelFactoryUsingANTLR3 extends LanguagePluginImpl implements ModelFactory { public ModelFactoryUsingANTLR3() { } @Override public abstract ModelFactoryUsingANTLR3 clone(); private boolean _debug; public void setDebug(boolean value) { _debug = value; } public boolean debug() { return _debug; } @Override public void parse(InputStream inputStream, Document cu) throws IOException, ParseException { try { ChameleonANTLR3Parser<?> parser = getParser(inputStream, cu.view()); // cu.disconnectChildren(); //FIXME: this is crap. I set the document, and later on set the view, // while they are (and must be) connected anyway parser.setDocument(cu); parser.compilationUnit(); } catch (RecognitionException e) { throw new ParseException(e,cu); } catch (Throwable t) { t.printStackTrace(); } } protected abstract ChameleonANTLR3Parser<?> getParser(InputStream inputStream, View view) throws IOException; }
Propagate the runtime exception
src/org/aikodi/chameleon/support/input/ModelFactoryUsingANTLR3.java
Propagate the runtime exception
<ide><path>rc/org/aikodi/chameleon/support/input/ModelFactoryUsingANTLR3.java <ide> parser.compilationUnit(); <ide> } catch (RecognitionException e) { <ide> throw new ParseException(e,cu); <del> } catch (Throwable t) { <add> } catch(RuntimeException e) { <add> throw e; <add> } <add> catch (Throwable t) { <ide> t.printStackTrace(); <ide> } <ide> }
Java
apache-2.0
377554104b263ee3632cdf61e52a975b2572a80b
0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
/* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.core.keygen; import org.junit.Test; import java.util.Properties; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class UUIDKeyGeneratorTest { private UUIDKeyGenerator uuidKeyGenerator = new UUIDKeyGenerator(); @Test public void assertGenerateKey() { assertThat(((String) uuidKeyGenerator.generateKey()).length(), is(32)); } @Test public void assertGetProperties() { assertThat(uuidKeyGenerator.getProperties().entrySet().size(), is(0)); } @Test public void assertSetProperties() { Properties properties = new Properties(); properties.setProperty("key1", "value1"); uuidKeyGenerator.setProperties(properties); assertThat(uuidKeyGenerator.getProperties().get("key1"), is((Object) "value1")); } }
sharding-core/src/test/java/io/shardingsphere/core/keygen/UUIDKeyGeneratorTest.java
/* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.core.keygen; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class UUIDKeyGeneratorTest { private UUIDKeyGenerator uuidKeyGenerator = new UUIDKeyGenerator(); @Test public void assertGenerateKey() { assertThat(((String) uuidKeyGenerator.generateKey()).length(), is(32)); } @Test public void assertGetProperties() { } @Test public void assertSetProperties() { } }
ADD assertSetProperties()
sharding-core/src/test/java/io/shardingsphere/core/keygen/UUIDKeyGeneratorTest.java
ADD assertSetProperties()
<ide><path>harding-core/src/test/java/io/shardingsphere/core/keygen/UUIDKeyGeneratorTest.java <ide> <ide> import org.junit.Test; <ide> <add>import java.util.Properties; <add> <ide> import static org.hamcrest.CoreMatchers.is; <ide> import static org.junit.Assert.assertThat; <ide> <ide> <ide> @Test <ide> public void assertGetProperties() { <add> assertThat(uuidKeyGenerator.getProperties().entrySet().size(), is(0)); <ide> } <ide> <ide> @Test <ide> public void assertSetProperties() { <add> Properties properties = new Properties(); <add> properties.setProperty("key1", "value1"); <add> uuidKeyGenerator.setProperties(properties); <add> assertThat(uuidKeyGenerator.getProperties().get("key1"), is((Object) "value1")); <ide> } <ide> }
Java
apache-2.0
04e36262d21d674456cbc69946f70be2b65ddb49
0
jaeksoft/opensearchserver,jaeksoft/opensearchserver
/* * Copyright 2017-2018 Emmanuel Keller / Jaeksoft * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jaeksoft.opensearchserver.services; import com.jaeksoft.opensearchserver.model.ActiveStatus; import com.jaeksoft.opensearchserver.model.UserRecord; import com.nimbusds.jose.JOSEException; import com.nimbusds.jose.JWSSigner; import com.nimbusds.jose.JWSVerifier; import com.nimbusds.jose.KeyLengthException; import com.nimbusds.jose.crypto.MACSigner; import com.nimbusds.jose.crypto.MACVerifier; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.SignedJWT; import com.qwazr.utils.LoggerUtils; import com.qwazr.utils.StringUtils; import com.qwazr.utils.concurrent.ThreadUtils; import io.undertow.security.idm.Account; import io.undertow.security.idm.Credential; import javax.ws.rs.NotSupportedException; import java.net.URI; import java.text.ParseException; import java.util.Date; import java.util.Objects; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; public class JwtUsersService implements UsersService { private final static Logger LOGGER = LoggerUtils.getLogger(JwtUsersService.class); private final JWSSigner signer; private final String sharedSecret; private final URI jwtUri; public JwtUsersService(ConfigService configService) throws KeyLengthException { sharedSecret = Objects.requireNonNull(configService.getOss2JwtKey(), "The oss2JwtKey configuration parameter is missing."); jwtUri = Objects.requireNonNull(configService.getOss2JwtUrl(), "The oss2JwtUrl configuration parameter is missing."); signer = new MACSigner(sharedSecret); } @Override public UserRecord getUserById(UUID userId) { return null; } @Override public boolean isSingleSignOn() { return true; } @Override public String getSingleSignOnRedirectUrl() { return jwtUri.toString(); } @Override public Account verify(Account account) { return account; } @Override public Account verify(String token, Credential credential) { if (StringUtils.isBlank(token)) return null; try { final SignedJWT signedJWT = SignedJWT.parse(token); final JWSVerifier verifier = new MACVerifier(sharedSecret); if (!signedJWT.verify(verifier)) { ThreadUtils.sleep(2, TimeUnit.SECONDS); return null; } final JWTClaimsSet claimsSet = signedJWT.getJWTClaimsSet(); final Date expirationTime = claimsSet.getExpirationTime(); if (expirationTime == null || new Date().after(expirationTime)) return null; final String email = claimsSet.getStringClaim("email"); final String name = claimsSet.getStringClaim("name"); final String id = claimsSet.getStringClaim("id"); if (StringUtils.isBlank(id)) return null; return new UserAccount(new JwtUserRecord(UUID.fromString(id), name, email)); } catch (ParseException | JOSEException | IllegalArgumentException e) { LOGGER.log(Level.WARNING, e, e::getMessage); return null; } } @Override public Account verify(Credential credential) { return null; } private class JwtUserRecord implements UserRecord { private final UUID id; private final String name; private final String email; private JwtUserRecord(UUID id, String name, String email) { this.id = id; this.name = name; this.email = email; } @Override public UUID getId() { return id; } @Override public String getName() { return name; } @Override public String getEmail() { return email; } @Override public ActiveStatus getStatus() { return ActiveStatus.ENABLED; } @Override public boolean matchPassword(String applicationSalt, String clearPassword) { throw new NotSupportedException("Matching password is not supported."); } } }
src/main/java/com/jaeksoft/opensearchserver/services/JwtUsersService.java
/* * Copyright 2017-2018 Emmanuel Keller / Jaeksoft * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jaeksoft.opensearchserver.services; import com.jaeksoft.opensearchserver.model.ActiveStatus; import com.jaeksoft.opensearchserver.model.UserRecord; import com.nimbusds.jose.JOSEException; import com.nimbusds.jose.JWSSigner; import com.nimbusds.jose.JWSVerifier; import com.nimbusds.jose.KeyLengthException; import com.nimbusds.jose.crypto.MACSigner; import com.nimbusds.jose.crypto.MACVerifier; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.SignedJWT; import com.qwazr.utils.LoggerUtils; import com.qwazr.utils.StringUtils; import com.qwazr.utils.concurrent.ThreadUtils; import io.undertow.security.idm.Account; import io.undertow.security.idm.Credential; import javax.ws.rs.NotSupportedException; import java.net.URI; import java.text.ParseException; import java.util.Date; import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; public class JwtUsersService implements UsersService { private final static Logger LOGGER = LoggerUtils.getLogger(JwtUsersService.class); private final JWSSigner signer; private final String sharedSecret; private final URI jwtUri; private final Map<UUID, UserAccount> userAccounts; public JwtUsersService(ConfigService configService) throws KeyLengthException { sharedSecret = Objects.requireNonNull(configService.getOss2JwtKey(), "The oss2JwtKey configuration parameter is missing."); jwtUri = Objects.requireNonNull(configService.getOss2JwtUrl(), "The oss2JwtUrl configuration parameter is missing."); signer = new MACSigner(sharedSecret); userAccounts = new ConcurrentHashMap<>(); } @Override public UserRecord getUserById(UUID userId) { return null; } @Override public boolean isSingleSignOn() { return true; } @Override public String getSingleSignOnRedirectUrl() { return jwtUri.toString(); } @Override public Account verify(Account account) { if (!(account instanceof UserAccount)) return null; return userAccounts.get(((UserAccount) account).getPrincipal().getId()); } @Override public Account verify(String token, Credential credential) { if (StringUtils.isBlank(token)) return null; try { final SignedJWT signedJWT = SignedJWT.parse(token); final JWSVerifier verifier = new MACVerifier(sharedSecret); if (!signedJWT.verify(verifier)) { ThreadUtils.sleep(2, TimeUnit.SECONDS); return null; } final JWTClaimsSet claimsSet = signedJWT.getJWTClaimsSet(); final Date expirationTime = claimsSet.getExpirationTime(); if (expirationTime == null || new Date().after(expirationTime)) return null; final String email = claimsSet.getStringClaim("email"); final String name = claimsSet.getStringClaim("name"); final String id = claimsSet.getStringClaim("id"); if (StringUtils.isBlank(id)) return null; final UserAccount userAccount = new UserAccount(new JwtUserRecord(UUID.fromString(id), name, email)); userAccounts.put(userAccount.getPrincipal().getId(), userAccount); return userAccount; } catch (ParseException | JOSEException | IllegalArgumentException e) { LOGGER.log(Level.WARNING, e, e::getMessage); return null; } } @Override public Account verify(Credential credential) { return null; } private class JwtUserRecord implements UserRecord { private final UUID id; private final String name; private final String email; private JwtUserRecord(UUID id, String name, String email) { this.id = id; this.name = name; this.email = email; } @Override public UUID getId() { return id; } @Override public String getName() { return name; } @Override public String getEmail() { return email; } @Override public ActiveStatus getStatus() { return ActiveStatus.ENABLED; } @Override public boolean matchPassword(String applicationSalt, String clearPassword) { throw new NotSupportedException("Matching password is not supported."); } } }
Fix URI redirection issue
src/main/java/com/jaeksoft/opensearchserver/services/JwtUsersService.java
Fix URI redirection issue
<ide><path>rc/main/java/com/jaeksoft/opensearchserver/services/JwtUsersService.java <ide> import java.net.URI; <ide> import java.text.ParseException; <ide> import java.util.Date; <del>import java.util.Map; <ide> import java.util.Objects; <ide> import java.util.UUID; <del>import java.util.concurrent.ConcurrentHashMap; <ide> import java.util.concurrent.TimeUnit; <ide> import java.util.logging.Level; <ide> import java.util.logging.Logger; <ide> private final String sharedSecret; <ide> private final URI jwtUri; <ide> <del> private final Map<UUID, UserAccount> userAccounts; <del> <ide> public JwtUsersService(ConfigService configService) throws KeyLengthException { <ide> sharedSecret = <ide> Objects.requireNonNull(configService.getOss2JwtKey(), "The oss2JwtKey configuration parameter is missing."); <ide> jwtUri = <ide> Objects.requireNonNull(configService.getOss2JwtUrl(), "The oss2JwtUrl configuration parameter is missing."); <ide> signer = new MACSigner(sharedSecret); <del> userAccounts = new ConcurrentHashMap<>(); <ide> } <ide> <ide> @Override <ide> <ide> @Override <ide> public Account verify(Account account) { <del> if (!(account instanceof UserAccount)) <del> return null; <del> return userAccounts.get(((UserAccount) account).getPrincipal().getId()); <add> return account; <ide> } <ide> <ide> @Override <ide> if (StringUtils.isBlank(id)) <ide> return null; <ide> <del> final UserAccount userAccount = new UserAccount(new JwtUserRecord(UUID.fromString(id), name, email)); <del> userAccounts.put(userAccount.getPrincipal().getId(), userAccount); <del> return userAccount; <add> return new UserAccount(new JwtUserRecord(UUID.fromString(id), name, email)); <ide> } catch (ParseException | JOSEException | IllegalArgumentException e) { <ide> LOGGER.log(Level.WARNING, e, e::getMessage); <ide> return null;
Java
lgpl-2.1
f3be5f6b15ef1c69ab91993cae2df6b59e688a62
0
evolvedmicrobe/beast-mcmc,luminwin/beast-mcmc,JifengJiang/beast-mcmc,JifengJiang/beast-mcmc,luminwin/beast-mcmc,danieljue/beast-mcmc,luminwin/beast-mcmc,luminwin/beast-mcmc,evolvedmicrobe/beast-mcmc,evolvedmicrobe/beast-mcmc,JifengJiang/beast-mcmc,evolvedmicrobe/beast-mcmc,danieljue/beast-mcmc,danieljue/beast-mcmc,JifengJiang/beast-mcmc,danieljue/beast-mcmc,JifengJiang/beast-mcmc,evolvedmicrobe/beast-mcmc,luminwin/beast-mcmc,danieljue/beast-mcmc
/* * DiscreteStatistics.java * * Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package dr.stats; import dr.util.HeapSort; /** * simple discrete statistics (mean, variance, cumulative probability, quantiles etc.) * * @version $Id: DiscreteStatistics.java,v 1.11 2006/07/02 21:14:53 rambaut Exp $ * * @author Korbinian Strimmer * @author Alexei Drummond */ public class DiscreteStatistics { // // Public stuff // /** * compute mean * * @param x list of numbers * * @return mean */ public static double mean(double[] x) { double m = 0; int len = x.length; for (int i = 0; i < len; i++) { m += x[i]; } return m/(double) len; } /** * compute median * * @param x list of numbers * @param indices index sorting x * * @return median */ public static double median(double[] x, int[] indices) { int pos = x.length/2; if (x.length % 2 == 1) { return x[indices[pos]]; } else { return (x[indices[pos-1]]+x[indices[pos]])/2.0; } } /** * compute median * * @param x list of numbers * * @return median */ public static double median(double[] x) { if (x == null || x.length == 0) { throw new IllegalArgumentException(); } int[] indices = new int[x.length]; HeapSort.sort(x, indices); return median(x, indices); } /** * compute variance (ML estimator) * * @param x list of numbers * @param mean assumed mean of x * * @return variance of x (ML estimator) */ public static double variance(double[] x, double mean) { double var = 0; int len = x.length; for (int i = 0; i < len; i++) { double diff = x[i]-mean; var += diff*diff; } int n; if (len < 2) { n = 1; // to avoid division by zero } else { n = len-1; // for ML estimate } return var/ (double) n; } /** * compute covariance * * @param x list of numbers * @param y list of numbers * * @return covariance of x and y */ public static double covariance(double[] x, double[] y) { return covariance(x, y, mean(x), mean(y), stdev(x), stdev(y)); } /** * compute covariance * * @param x list of numbers * @param y list of numbers * @param xmean assumed mean of x * @param ymean assumed mean of y * @param xstdev assumed stdev of x * @param ystdev assumed stdev of y * * @return covariance of x and y */ public static double covariance(double[] x, double[] y, double xmean, double ymean, double xstdev, double ystdev) { if (x.length != y.length) throw new IllegalArgumentException("x and y arrays must be same length!"); double covar = 0.0; for (int i =0; i < x.length; i++) { covar += (x[i]-xmean)*(y[i]-ymean); } covar /= x.length; covar /= (xstdev*ystdev); return covar; } /** * compute fisher skewness * * @param x list of numbers * * @return skewness of x */ public static double skewness(double[] x) { double mean = mean(x); double stdev = stdev(x); double skew = 0.0; double len = x.length; for (double xv : x) { double diff = xv - mean; diff /= stdev; skew += (diff * diff * diff); } skew *= (len / ((len - 1) * (len - 2))); return skew; } /** * compute standard deviation * * @param x list of numbers * * @return standard deviation of x */ public static double stdev(double[] x) { return Math.sqrt(variance(x)); } /** * compute variance (ML estimator) * * @param x list of numbers * * @return variance of x (ML estimator) */ public static double variance(double[] x) { double m = mean(x); return variance(x, m); } /** * compute variance of sample mean (ML estimator) * * @param x list of numbers * @param mean assumed mean of x * * @return variance of x (ML estimator) */ public static double varianceSampleMean(double[] x, double mean) { return variance(x, mean)/(double) x.length; } /** * compute variance of sample mean (ML estimator) * * @param x list of numbers * * @return variance of x (ML estimator) */ public static double varianceSampleMean(double[] x) { return variance(x)/(double) x.length; } /** * compute the q-th quantile for a distribution of x * (= inverse cdf) * * @param q quantile (0 < q <= 1) * @param x discrete distribution (an unordered list of numbers) * @param indices index sorting x * * @return q-th quantile */ public static double quantile(double q, double[] x, int[] indices) { if (q < 0.0 || q > 1.0) throw new IllegalArgumentException("Quantile out of range"); if (q == 0.0) { // for q==0 we have to "invent" an entry smaller than the smallest x return x[indices[0]] - 1.0; } return x[indices[(int) Math.ceil(q*indices.length)-1]]; } /** * compute the q-th quantile for a distribution of x * (= inverse cdf) * * @param q quantile (0 <= q <= 1) * @param x discrete distribution (an unordered list of numbers) * * @return q-th quantile */ public static double quantile(double q, double[] x) { int[] indices = new int[x.length]; HeapSort.sort(x, indices); return quantile(q, x, indices); } /** * compute the q-th quantile for a distribution of x * (= inverse cdf) * * @param q quantile (0 <= q <= 1) * @param x discrete distribution (an unordered list of numbers) * @param count use only first count entries in x * * @return q-th quantile */ public static double quantile(double q, double[] x, int count) { int[] indices = new int[count]; HeapSort.sort(x, indices); return quantile(q, x, indices); } /** * Determine the highest posterior density for a list of values. * The HPD is the smallest interval containing the required amount of elements. * * @param proportion of elements inside the interval * @param x values * @param indices index sorting x * @return the interval, an array of {low, high} values. */ public static double[] HPDInterval(double proportion, double[] x, int[] indices) { double minRange = Double.MAX_VALUE; int hpdIndex = 0; final int diff = (int) Math.round(proportion * (double) x.length); for (int i = 0; i <= (x.length - diff); i++) { final double minValue = x[indices[i]]; final double maxValue = x[indices[i + diff - 1]]; final double range = Math.abs(maxValue - minValue); if (range < minRange) { minRange = range; hpdIndex = i; } } return new double[] { x[indices[hpdIndex]] , x[indices[hpdIndex + diff - 1]] }; } /** * compute the cumulative probability Pr(x <= z) for a given z * and a distribution of x * * @param z threshold value * @param x discrete distribution (an unordered list of numbers) * @param indices index sorting x * * @return cumulative probability */ public static double cdf(double z, double[] x, int[] indices) { int i; for (i = 0; i < x.length; i++) { if (x[indices[i]] > z) break; } return (double) i/ (double) x.length; } /** * compute the cumulative probability Pr(x <= z) for a given z * and a distribution of x * * @param z threshold value * @param x discrete distribution (an unordered list of numbers) * * @return cumulative probability */ public static double cdf(double z, double[] x) { int[] indices = new int[x.length]; HeapSort.sort(x, indices); return cdf(z, x, indices); } public static double max(double[] x) { double max = x[0]; for (int i = 1; i < x.length; i++) { if (x[i] > max) max = x[i]; } return max; } public static double min(double[] x) { double min = x[0]; for (int i = 1; i < x.length; i++) { if (x[i] < min) min = x[i]; } return min; } }
src/dr/stats/DiscreteStatistics.java
/* * DiscreteStatistics.java * * Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package dr.stats; import dr.util.HeapSort; /** * simple discrete statistics (mean, variance, cumulative probability, quantiles etc.) * * @version $Id: DiscreteStatistics.java,v 1.11 2006/07/02 21:14:53 rambaut Exp $ * * @author Korbinian Strimmer * @author Alexei Drummond */ public class DiscreteStatistics { // // Public stuff // /** * compute mean * * @param x list of numbers * * @return mean */ public static double mean(double[] x) { double m = 0; int len = x.length; for (int i = 0; i < len; i++) { m += x[i]; } return m/(double) len; } /** * compute median * * @param x list of numbers * @param indices index sorting x * * @return median */ public static double median(double[] x, int[] indices) { int pos = x.length/2; if (x.length % 2 == 1) { return x[indices[pos]]; } else { return (x[indices[pos-1]]+x[indices[pos]])/2.0; } } /** * compute median * * @param x list of numbers * * @return median */ public static double median(double[] x) { if (x == null || x.length == 0) { throw new IllegalArgumentException(); } int[] indices = new int[x.length]; HeapSort.sort(x, indices); return median(x, indices); } /** * compute variance (ML estimator) * * @param x list of numbers * @param mean assumed mean of x * * @return variance of x (ML estimator) */ public static double variance(double[] x, double mean) { double var = 0; int len = x.length; for (int i = 0; i < len; i++) { double diff = x[i]-mean; var += diff*diff; } int n; if (len < 2) { n = 1; // to avoid division by zero } else { n = len-1; // for ML estimate } return var/ (double) n; } /** * compute covariance * * @param x list of numbers * @param y list of numbers * * @return covariance of x and y */ public static double covariance(double[] x, double[] y) { return covariance(x, y, mean(x), mean(y), stdev(x), stdev(y)); } /** * compute covariance * * @param x list of numbers * @param y list of numbers * @param xmean assumed mean of x * @param ymean assumed mean of y * @param xstdev assumed stdev of x * @param ystdev assumed stdev of y * * @return covariance of x and y */ public static double covariance(double[] x, double[] y, double xmean, double ymean, double xstdev, double ystdev) { if (x.length != y.length) throw new IllegalArgumentException("x and y arrays must be same length!"); double covar = 0.0; for (int i =0; i < x.length; i++) { covar += (x[i]-xmean)*(y[i]-ymean); } covar /= x.length; covar /= (xstdev*ystdev); return covar; } /** * compute fisher skewness * * @param x list of numbers * * @return skewness of x */ public static double skewness(double[] x) { double mean = mean(x); double stdev = stdev(x); double skew = 0.0; double len = x.length; for (double xv : x) { double diff = xv - mean; diff /= stdev; skew += (diff * diff * diff); } skew *= (len / ((len - 1) * (len - 2))); return skew; } /** * compute standard deviation * * @param x list of numbers * * @return standard deviation of x */ public static double stdev(double[] x) { return Math.sqrt(variance(x)); } /** * compute variance (ML estimator) * * @param x list of numbers * * @return variance of x (ML estimator) */ public static double variance(double[] x) { double m = mean(x); return variance(x, m); } /** * compute variance of sample mean (ML estimator) * * @param x list of numbers * @param mean assumed mean of x * * @return variance of x (ML estimator) */ public static double varianceSampleMean(double[] x, double mean) { return variance(x, mean)/(double) x.length; } /** * compute variance of sample mean (ML estimator) * * @param x list of numbers * * @return variance of x (ML estimator) */ public static double varianceSampleMean(double[] x) { return variance(x)/(double) x.length; } /** * compute the q-th quantile for a distribution of x * (= inverse cdf) * * @param q quantile (0 < q <= 1) * @param x discrete distribution (an unordered list of numbers) * @param indices index sorting x * * @return q-th quantile */ public static double quantile(double q, double[] x, int[] indices) { if (q < 0.0 || q > 1.0) throw new IllegalArgumentException("Quantile out of range"); if (q == 0.0) { // for q==0 we have to "invent" an entry smaller than the smallest x return x[indices[0]] - 1.0; } return x[indices[(int) Math.ceil(q*indices.length)-1]]; } /** * compute the q-th quantile for a distribution of x * (= inverse cdf) * * @param q quantile (0 <= q <= 1) * @param x discrete distribution (an unordered list of numbers) * * @return q-th quantile */ public static double quantile(double q, double[] x) { int[] indices = new int[x.length]; HeapSort.sort(x, indices); return quantile(q, x, indices); } /** * compute the q-th quantile for a distribution of x * (= inverse cdf) * * @param q quantile (0 <= q <= 1) * @param x discrete distribution (an unordered list of numbers) * * @return q-th quantile */ public static double quantile(double q, double[] x, int count) { int[] indices = new int[count]; HeapSort.sort(x, indices); return quantile(q, x, indices); } /** * Determine the highest posterior density for a list of values. * The HPD is the smallest interval containing the required amount of elements. * * @param proportion of elements inside the interval * @param x values * @param indices index sorting x * @return the interval, an array of {low, high} values. */ public static double[] HPDInterval(double proportion, double[] x, int[] indices) { double minRange = Double.MAX_VALUE; int hpdIndex = 0; final int diff = (int) Math.round(proportion * (double) x.length); for (int i = 0; i <= (x.length - diff); i++) { final double minValue = x[indices[i]]; final double maxValue = x[indices[i + diff - 1]]; final double range = Math.abs(maxValue - minValue); if (range < minRange) { minRange = range; hpdIndex = i; } } return new double[] { x[indices[hpdIndex]] , x[indices[hpdIndex + diff - 1]] }; } /** * compute the cumulative probability Pr(x <= z) for a given z * and a distribution of x * * @param z threshold value * @param x discrete distribution (an unordered list of numbers) * @param indices index sorting x * * @return cumulative probability */ public static double cdf(double z, double[] x, int[] indices) { int i; for (i = 0; i < x.length; i++) { if (x[indices[i]] > z) break; } return (double) i/ (double) x.length; } /** * compute the cumulative probability Pr(x <= z) for a given z * and a distribution of x * * @param z threshold value * @param x discrete distribution (an unordered list of numbers) * * @return cumulative probability */ public static double cdf(double z, double[] x) { int[] indices = new int[x.length]; HeapSort.sort(x, indices); return cdf(z, x, indices); } public static double max(double[] x) { double max = x[0]; for (int i = 1; i < x.length; i++) { if (x[i] > max) max = x[i]; } return max; } public static double min(double[] x) { double min = x[0]; for (int i = 1; i < x.length; i++) { if (x[i] < min) min = x[i]; } return min; } }
comment addition
src/dr/stats/DiscreteStatistics.java
comment addition
<ide><path>rc/dr/stats/DiscreteStatistics.java <ide> * <ide> * @param q quantile (0 <= q <= 1) <ide> * @param x discrete distribution (an unordered list of numbers) <add> * @param count use only first count entries in x <ide> * <ide> * @return q-th quantile <ide> */
Java
apache-2.0
51bab2de7a3be286f211550c67b11dca90879c72
0
Valkryst/Schillsaver
package model; import com.valkryst.VMVC.Settings; import com.valkryst.VMVC.model.Model; import javafx.application.Platform; import javafx.scene.control.Tab; import javafx.scene.control.TextArea; import lombok.Getter; import lombok.Setter; import misc.BlockSize; import misc.FrameDimension; import misc.FrameRate; import misc.Job; import org.apache.commons.io.FilenameUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import view.MainView; import java.awt.Dimension; import java.io.*; import java.util.*; public class MainModel extends Model { /** The jobs. */ @Getter @Setter private Map<String, Job> jobs = new HashMap<>(); /** Deserializes the jobs map, if the file exists. */ public void loadJobs() { final String filePath = System.getProperty("user.dir") + "/Jobs.ser"; try ( final FileInputStream fis = new FileInputStream(filePath); final ObjectInputStream ois = new ObjectInputStream(fis); ) { final Object object = ois.readObject(); jobs = (Map<String, Job>) object; } catch (IOException | ClassNotFoundException e) { final Logger logger = LogManager.getLogger(); logger.error(e); // Delete the file: final File file = new File(filePath); if (file.exists()) { file.delete(); } } } /** Serializes the jobs map to a file. */ public void saveJobs() { final String filePath = System.getProperty("user.dir") + "/Jobs.ser"; if (jobs.size() == 0) { // Delete the file: final File file = new File(filePath); if (file.exists()) { file.delete(); } return; } try ( final FileOutputStream fos = new FileOutputStream(filePath, false); final ObjectOutputStream oos = new ObjectOutputStream(fos); ) { oos.writeObject(jobs); } catch (IOException e) { final Logger logger = LogManager.getLogger(); logger.error(e); } } public List<Thread> prepareEncodingJobs(final Settings settings, final MainView view) { final List<Thread> encodingJobs = new ArrayList<>(); for (final Job job : getEncodingJobs()) { final Tab tab = view.addOutputTab(job.getName()); final Thread thread = new Thread(() -> { tab.setClosable(false); // Prepare Files: final File inputFile; final File outputFile; try { inputFile = job.zipFiles(settings); outputFile = new File(job.getOutputDirectory() + FilenameUtils.removeExtension(inputFile.getName()) + ".mp4"); // Construct FFMPEG String: final FrameDimension frameDimension = FrameDimension.valueOf(settings.getStringSetting("Encoding Frame Dimensions")); final Dimension blockSize = BlockSize.valueOf(settings.getStringSetting("Encoding Block Size")).getBlockSize(); final FrameRate frameRate = FrameRate.valueOf(settings.getStringSetting("Encoding Frame Rate")); final String codec = settings.getStringSetting("Encoding Codec"); final StringBuilder sb = new StringBuilder(); final Formatter formatter = new Formatter(sb, Locale.US); formatter.format("\"%s\" -f rawvideo -pix_fmt monob -s %dx%d -r %d -i \"%s\" -vf \"scale=iw*%d:-1\" -sws_flags neighbor -c:v %s -threads 8 -loglevel %s -y \"%s\"", settings.getStringSetting("FFMPEG Executable Path"), frameDimension.getWidth() / blockSize.width, frameDimension.getHeight() / blockSize.height, frameRate.getFrameRate(), inputFile.getAbsolutePath(), blockSize.width, codec, "verbose", job.getOutputDirectory(), outputFile.getAbsolutePath()); final String ffmpegLaunchCommand = sb.toString(); sb.append(System.lineSeparator()); sb.append(System.lineSeparator()); sb.append(System.lineSeparator()); Platform.runLater(() -> ((TextArea) tab.getContent()).appendText(sb.toString())); // Construct FFMPEG Process: final ProcessBuilder builder = new ProcessBuilder(ffmpegLaunchCommand); builder.redirectErrorStream(true); final Process process = builder.start(); Runtime.getRuntime().addShutdownHook(new Thread(process::destroy)); // Run FFMPEG Process: try ( final InputStream is = process.getInputStream(); final InputStreamReader isr = new InputStreamReader(is); final BufferedReader br = new BufferedReader(isr); ) { String line; while ((line = br.readLine()) != null) { final String temp = line; Platform.runLater(() -> ((TextArea) tab.getContent()).appendText(temp)); } } catch (final IOException e) { final Logger logger = LogManager.getLogger(); logger.error(e); final TextArea outputArea = ((TextArea) tab.getContent()); outputArea.appendText("Error:"); outputArea.appendText("\n\t" + e.getMessage()); outputArea.appendText("\n\tSee log file for more information."); process.destroy(); tab.setClosable(true); return; } Platform.runLater(() -> ((TextArea) tab.getContent()).appendText("Encoding Complete")); } catch (final IOException e) { final Logger logger = LogManager.getLogger(); logger.error(e); final TextArea outputArea = ((TextArea) tab.getContent()); outputArea.appendText("Error:"); outputArea.appendText("\n\t" + e.getMessage()); outputArea.appendText("\n\tSee log file for more information."); tab.setClosable(true); return; } tab.setClosable(true); }); encodingJobs.add(thread); } return encodingJobs; } public List<Thread> prepareDecodingJobs(final Settings settings, final MainView view) { final List<Thread> decodingJobs = new ArrayList<>(); for (final Job job : getDecodingJobs()) { final Tab tab = view.addOutputTab(job.getName()); for (final File inputFile : job.getFiles()) { final Thread thread = new Thread(() -> { tab.setClosable(false); System.err.println("DECODE STUFF NOT IMPLEMENTED, MAINMODEL"); inputFile.delete(); tab.setClosable(true); }); decodingJobs.add(thread); } } return decodingJobs; } /** * Retrieves an unmodifiable list of encoding jobs. * * @return * The list of encoding jobs. */ private List<Job> getEncodingJobs() { final List<Job> encodingJobs = new ArrayList<>(); for (final Job job : jobs.values()) { if (job.isEncodeJob()) { encodingJobs.add(job); } } return Collections.unmodifiableList(encodingJobs); } /** * Retrieves an unmodifiable list of decoding jobs. * * @return * The list of decoding jobs. */ private List<Job> getDecodingJobs() { final List<Job> decodingJobs = new ArrayList<>(); for (final Job job : jobs.values()) { if (job.isEncodeJob() == false) { decodingJobs.add(job); } } return Collections.unmodifiableList(decodingJobs); } }
src/model/MainModel.java
package model; import com.valkryst.VMVC.Settings; import com.valkryst.VMVC.model.Model; import javafx.scene.control.Tab; import javafx.scene.control.TextArea; import lombok.Getter; import lombok.Setter; import misc.Job; import org.apache.commons.io.FilenameUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import view.MainView; import java.io.*; import java.util.*; public class MainModel extends Model { /** The jobs. */ @Getter @Setter private Map<String, Job> jobs = new HashMap<>(); /** Deserializes the jobs map, if the file exists. */ public void loadJobs() { final String filePath = System.getProperty("user.dir") + "/Jobs.ser"; try ( final FileInputStream fis = new FileInputStream(filePath); final ObjectInputStream ois = new ObjectInputStream(fis); ) { final Object object = ois.readObject(); jobs = (Map<String, Job>) object; } catch (IOException | ClassNotFoundException e) { final Logger logger = LogManager.getLogger(); logger.error(e); // Delete the file: final File file = new File(filePath); if (file.exists()) { file.delete(); } } } /** Serializes the jobs map to a file. */ public void saveJobs() { final String filePath = System.getProperty("user.dir") + "/Jobs.ser"; if (jobs.size() == 0) { // Delete the file: final File file = new File(filePath); if (file.exists()) { file.delete(); } return; } try ( final FileOutputStream fos = new FileOutputStream(filePath, false); final ObjectOutputStream oos = new ObjectOutputStream(fos); ) { oos.writeObject(jobs); } catch (IOException e) { final Logger logger = LogManager.getLogger(); logger.error(e); } } public List<Thread> prepareEncodingJobs(final Settings settings, final MainView view) { final List<Thread> encodingJobs = new ArrayList<>(); for (final Job job : getEncodingJobs()) { final Tab tab = view.addOutputTab(job.getName()); final Thread thread = new Thread(() -> { tab.setClosable(false); // Prepare Files: final File inputFile; final File outputFile; try { inputFile = job.zipFiles(settings); outputFile = new File(job.getOutputDirectory() + FilenameUtils.removeExtension(inputFile.getName()) + ".mp4"); } catch (final IOException e) { final Logger logger = LogManager.getLogger(); logger.error(e); final TextArea outputArea = ((TextArea) tab.getContent()); outputArea.appendText("Error:"); outputArea.appendText("\n\t" + e.getMessage()); outputArea.appendText("\n\tSee log file for more information."); tab.setClosable(true); return; } // todo FFMPEG STUFF System.err.println("ENCODE STUFF NOT IMPLEMENTED, MAINMODEL"); tab.setClosable(true); }); encodingJobs.add(thread); } return encodingJobs; } public List<Thread> prepareDecodingJobs(final Settings settings, final MainView view) { final List<Thread> decodingJobs = new ArrayList<>(); for (final Job job : getDecodingJobs()) { final Tab tab = view.addOutputTab(job.getName()); for (final File inputFile : job.getFiles()) { final Thread thread = new Thread(() -> { tab.setClosable(false); System.err.println("DECODE STUFF NOT IMPLEMENTED, MAINMODEL"); inputFile.delete(); tab.setClosable(true); }); decodingJobs.add(thread); } } return decodingJobs; } /** * Retrieves an unmodifiable list of encoding jobs. * * @return * The list of encoding jobs. */ private List<Job> getEncodingJobs() { final List<Job> encodingJobs = new ArrayList<>(); for (final Job job : jobs.values()) { if (job.isEncodeJob()) { encodingJobs.add(job); } } return Collections.unmodifiableList(encodingJobs); } /** * Retrieves an unmodifiable list of decoding jobs. * * @return * The list of decoding jobs. */ private List<Job> getDecodingJobs() { final List<Job> decodingJobs = new ArrayList<>(); for (final Job job : jobs.values()) { if (job.isEncodeJob() == false) { decodingJobs.add(job); } } return Collections.unmodifiableList(decodingJobs); } }
Partially implements ffmpeg encoding.
src/model/MainModel.java
Partially implements ffmpeg encoding.
<ide><path>rc/model/MainModel.java <ide> <ide> import com.valkryst.VMVC.Settings; <ide> import com.valkryst.VMVC.model.Model; <add>import javafx.application.Platform; <ide> import javafx.scene.control.Tab; <ide> import javafx.scene.control.TextArea; <ide> import lombok.Getter; <ide> import lombok.Setter; <add>import misc.BlockSize; <add>import misc.FrameDimension; <add>import misc.FrameRate; <ide> import misc.Job; <ide> import org.apache.commons.io.FilenameUtils; <ide> import org.apache.logging.log4j.LogManager; <ide> import org.apache.logging.log4j.Logger; <ide> import view.MainView; <ide> <add>import java.awt.Dimension; <ide> import java.io.*; <ide> import java.util.*; <ide> <ide> try { <ide> inputFile = job.zipFiles(settings); <ide> outputFile = new File(job.getOutputDirectory() + FilenameUtils.removeExtension(inputFile.getName()) + ".mp4"); <add> <add> // Construct FFMPEG String: <add> final FrameDimension frameDimension = FrameDimension.valueOf(settings.getStringSetting("Encoding Frame Dimensions")); <add> final Dimension blockSize = BlockSize.valueOf(settings.getStringSetting("Encoding Block Size")).getBlockSize(); <add> final FrameRate frameRate = FrameRate.valueOf(settings.getStringSetting("Encoding Frame Rate")); <add> final String codec = settings.getStringSetting("Encoding Codec"); <add> <add> final StringBuilder sb = new StringBuilder(); <add> final Formatter formatter = new Formatter(sb, Locale.US); <add> <add> formatter.format("\"%s\" -f rawvideo -pix_fmt monob -s %dx%d -r %d -i \"%s\" -vf \"scale=iw*%d:-1\" -sws_flags neighbor -c:v %s -threads 8 -loglevel %s -y \"%s\"", <add> settings.getStringSetting("FFMPEG Executable Path"), <add> frameDimension.getWidth() / blockSize.width, <add> frameDimension.getHeight() / blockSize.height, <add> frameRate.getFrameRate(), <add> inputFile.getAbsolutePath(), <add> blockSize.width, <add> codec, <add> "verbose", <add> job.getOutputDirectory(), <add> outputFile.getAbsolutePath()); <add> <add> final String ffmpegLaunchCommand = sb.toString(); <add> sb.append(System.lineSeparator()); <add> sb.append(System.lineSeparator()); <add> sb.append(System.lineSeparator()); <add> <add> Platform.runLater(() -> ((TextArea) tab.getContent()).appendText(sb.toString())); <add> <add> <add> // Construct FFMPEG Process: <add> final ProcessBuilder builder = new ProcessBuilder(ffmpegLaunchCommand); <add> builder.redirectErrorStream(true); <add> <add> final Process process = builder.start(); <add> Runtime.getRuntime().addShutdownHook(new Thread(process::destroy)); <add> <add> // Run FFMPEG Process: <add> try ( <add> final InputStream is = process.getInputStream(); <add> final InputStreamReader isr = new InputStreamReader(is); <add> final BufferedReader br = new BufferedReader(isr); <add> ) { <add> String line; <add> while ((line = br.readLine()) != null) { <add> final String temp = line; <add> Platform.runLater(() -> ((TextArea) tab.getContent()).appendText(temp)); <add> } <add> } catch (final IOException e) { <add> final Logger logger = LogManager.getLogger(); <add> logger.error(e); <add> <add> final TextArea outputArea = ((TextArea) tab.getContent()); <add> outputArea.appendText("Error:"); <add> outputArea.appendText("\n\t" + e.getMessage()); <add> outputArea.appendText("\n\tSee log file for more information."); <add> <add> process.destroy(); <add> tab.setClosable(true); <add> return; <add> } <add> <add> <add> Platform.runLater(() -> ((TextArea) tab.getContent()).appendText("Encoding Complete")); <ide> } catch (final IOException e) { <ide> final Logger logger = LogManager.getLogger(); <ide> logger.error(e); <ide> tab.setClosable(true); <ide> return; <ide> } <del> <del> // todo FFMPEG STUFF <del> System.err.println("ENCODE STUFF NOT IMPLEMENTED, MAINMODEL"); <ide> <ide> tab.setClosable(true); <ide> });
Java
apache-2.0
c667e8f5a4c55206af6ebab1317abb2cfa014856
0
cscorley/solr-only-mirror,cscorley/solr-only-mirror,cscorley/solr-only-mirror
package org.apache.solr.cloud; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.MalformedURLException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeoutException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer; import org.apache.solr.client.solrj.request.CoreAdminRequest.WaitForState; import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrException.ErrorCode; import org.apache.solr.common.cloud.CloudState; import org.apache.solr.common.cloud.CoreState; import org.apache.solr.common.cloud.OnReconnect; import org.apache.solr.common.cloud.SolrZkClient; import org.apache.solr.common.cloud.ZkCmdExecutor; import org.apache.solr.common.cloud.ZkCoreNodeProps; import org.apache.solr.common.cloud.ZkNodeProps; import org.apache.solr.common.cloud.ZkStateReader; import org.apache.solr.common.cloud.ZooKeeperException; import org.apache.solr.common.params.SolrParams; import org.apache.solr.core.CoreContainer; import org.apache.solr.core.CoreDescriptor; import org.apache.solr.core.SolrCore; import org.apache.solr.update.UpdateLog; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.KeeperException.NoNodeException; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Handle ZooKeeper interactions. * * notes: loads everything on init, creates what's not there - further updates * are prompted with Watches. * * TODO: exceptions during shutdown on attempts to update cloud state * */ public final class ZkController { private static Logger log = LoggerFactory.getLogger(ZkController.class); static final String NEWL = System.getProperty("line.separator"); private final static Pattern URL_POST = Pattern.compile("https?://(.*)"); private final static Pattern URL_PREFIX = Pattern.compile("(https?://).*"); private final boolean SKIP_AUTO_RECOVERY = Boolean.getBoolean("solrcloud.skip.autorecovery"); // package private for tests static final String CONFIGS_ZKNODE = "/configs"; public final static String COLLECTION_PARAM_PREFIX="collection."; public final static String CONFIGNAME_PROP="configName"; private Map<String, CoreState> coreStates = null; private long coreStatesVersion; // bumped by 1 each time we serialize coreStates... sync on coreStates private long coreStatesPublishedVersion; // last version published to ZK... sync on coreStatesPublishLock private Object coreStatesPublishLock = new Object(); // only publish one at a time private final Map<String, ElectionContext> electionContexts = Collections.synchronizedMap(new HashMap<String, ElectionContext>()); private SolrZkClient zkClient; private ZkCmdExecutor cmdExecutor; private ZkStateReader zkStateReader; private LeaderElector leaderElector; private String zkServerAddress; private String localHostPort; private String localHostContext; private String localHostName; private String localHost; private String hostName; private LeaderElector overseerElector; // this can be null in which case recovery will be inactive private CoreContainer cc; public static void main(String[] args) throws Exception { // start up a tmp zk server first String zkServerAddress = args[0]; String solrPort = args[1]; String confDir = args[2]; String confName = args[3]; String solrHome = null; if (args.length == 5) { solrHome = args[4]; } SolrZkServer zkServer = null; if (solrHome != null) { zkServer = new SolrZkServer("true", null, solrHome, solrPort); zkServer.parseConfig(); zkServer.start(); } SolrZkClient zkClient = new SolrZkClient(zkServerAddress, 15000, 5000, new OnReconnect() { @Override public void command() { }}); uploadConfigDir(zkClient, new File(confDir), confName); if (solrHome != null) { zkServer.stop(); } } /** * @param cc if null, recovery will not be enabled * @param zkServerAddress * @param zkClientTimeout * @param zkClientConnectTimeout * @param localHost * @param locaHostPort * @param localHostContext * @param registerOnReconnect * @throws InterruptedException * @throws TimeoutException * @throws IOException */ public ZkController(CoreContainer cc, String zkServerAddress, int zkClientTimeout, int zkClientConnectTimeout, String localHost, String locaHostPort, String localHostContext, final CurrentCoreDescriptorProvider registerOnReconnect) throws InterruptedException, TimeoutException, IOException { this.cc = cc; if (localHostContext.contains("/")) { throw new IllegalArgumentException("localHostContext (" + localHostContext + ") should not contain a /"); } this.zkServerAddress = zkServerAddress; this.localHostPort = locaHostPort; this.localHostContext = localHostContext; this.localHost = localHost; zkClient = new SolrZkClient(zkServerAddress, zkClientTimeout, zkClientConnectTimeout, // on reconnect, reload cloud info new OnReconnect() { public void command() { try { // we need to create all of our lost watches // seems we dont need to do this again... //Overseer.createClientNodes(zkClient, getNodeName()); ElectionContext context = new OverseerElectionContext(getNodeName(), zkClient, zkStateReader); overseerElector.joinElection(context, null); zkStateReader.createClusterStateWatchersAndUpdate(); List<CoreDescriptor> descriptors = registerOnReconnect .getCurrentDescriptors(); if (descriptors != null) { // before registering as live, make sure everyone is in a // down state for (CoreDescriptor descriptor : descriptors) { final String coreZkNodeName = getNodeName() + "_" + descriptor.getName(); publishAsDown(getBaseUrl(), descriptor, coreZkNodeName, descriptor.getName()); waitForLeaderToSeeDownState(descriptor, coreZkNodeName, true); } } // we have to register as live first to pick up docs in the buffer createEphemeralLiveNode(); // re register all descriptors if (descriptors != null) { for (CoreDescriptor descriptor : descriptors) { // TODO: we need to think carefully about what happens when it was // a leader that was expired - as well as what to do about leaders/overseers // with connection loss register(descriptor.getName(), descriptor, true); } } } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); throw new ZooKeeperException( SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (Exception e) { SolrException.log(log, "", e); throw new ZooKeeperException( SolrException.ErrorCode.SERVER_ERROR, "", e); } } }); cmdExecutor = new ZkCmdExecutor(); leaderElector = new LeaderElector(zkClient); zkStateReader = new ZkStateReader(zkClient); init(); } /** * Closes the underlying ZooKeeper client. */ public void close() { try { zkClient.close(); } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); log.warn("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } } /** * @param collection * @param fileName * @return true if config file exists * @throws KeeperException * @throws InterruptedException */ public boolean configFileExists(String collection, String fileName) throws KeeperException, InterruptedException { Stat stat = zkClient.exists(CONFIGS_ZKNODE + "/" + collection + "/" + fileName, null, true); return stat != null; } /** * @return information about the cluster from ZooKeeper */ public CloudState getCloudState() { return zkStateReader.getCloudState(); } /** * @param zkConfigName * @param fileName * @return config file data (in bytes) * @throws KeeperException * @throws InterruptedException */ public byte[] getConfigFileData(String zkConfigName, String fileName) throws KeeperException, InterruptedException { String zkPath = CONFIGS_ZKNODE + "/" + zkConfigName + "/" + fileName; byte[] bytes = zkClient.getData(zkPath, null, null, true); if (bytes == null) { log.error("Config file contains no data:" + zkPath); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "Config file contains no data:" + zkPath); } return bytes; } // TODO: consider how this is done private String getHostAddress() throws IOException { if (localHost == null) { localHost = "http://" + InetAddress.getLocalHost().getHostName(); } else { Matcher m = URL_PREFIX.matcher(localHost); if (m.matches()) { String prefix = m.group(1); localHost = prefix + localHost; } else { localHost = "http://" + localHost; } } return localHost; } public String getHostName() { return hostName; } public SolrZkClient getZkClient() { return zkClient; } /** * @return zookeeper server address */ public String getZkServerAddress() { return zkServerAddress; } private void init() { try { localHostName = getHostAddress(); Matcher m = URL_POST.matcher(localHostName); if (m.matches()) { hostName = m.group(1); } else { log.error("Unrecognized host:" + localHostName); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "Unrecognized host:" + localHostName); } // makes nodes zkNode cmdExecutor.ensureExists(ZkStateReader.LIVE_NODES_ZKNODE, zkClient); Overseer.createClientNodes(zkClient, getNodeName()); createEphemeralLiveNode(); cmdExecutor.ensureExists(ZkStateReader.COLLECTIONS_ZKNODE, zkClient); syncNodeState(); overseerElector = new LeaderElector(zkClient); ElectionContext context = new OverseerElectionContext(getNodeName(), zkClient, zkStateReader); overseerElector.setup(context); overseerElector.joinElection(context, null); zkStateReader.createClusterStateWatchersAndUpdate(); } catch (IOException e) { log.error("", e); throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Can't create ZooKeeperController", e); } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (KeeperException e) { log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } } /* * sync internal state with zk on startup */ private void syncNodeState() throws KeeperException, InterruptedException { log.debug("Syncing internal state with zk. Current: " + coreStates); final String path = Overseer.STATES_NODE + "/" + getNodeName(); final byte[] data = zkClient.getData(path, null, null, true); coreStates = new HashMap<String,CoreState>(); if (data != null) { CoreState[] states = CoreState.load(data); List<CoreState> stateList = Arrays.asList(states); for(CoreState coreState: stateList) { coreStates.put(coreState.getCoreName(), coreState); } } log.debug("after sync: " + coreStates); } public boolean isConnected() { return zkClient.isConnected(); } private void createEphemeralLiveNode() throws KeeperException, InterruptedException { String nodeName = getNodeName(); String nodePath = ZkStateReader.LIVE_NODES_ZKNODE + "/" + nodeName; log.info("Register node as live in ZooKeeper:" + nodePath); try { boolean nodeDeleted = true; try { // we attempt a delete in the case of a quick server bounce - // if there was not a graceful shutdown, the node may exist // until expiration timeout - so a node won't be created here because // it exists, but eventually the node will be removed. So delete // in case it exists and create a new node. zkClient.delete(nodePath, -1, true); } catch (KeeperException.NoNodeException e) { // fine if there is nothing to delete // TODO: annoying that ZK logs a warning on us nodeDeleted = false; } if (nodeDeleted) { log .info("Found a previous node that still exists while trying to register a new live node " + nodePath + " - removing existing node to create another."); } zkClient.makePath(nodePath, CreateMode.EPHEMERAL, true); } catch (KeeperException e) { // its okay if the node already exists if (e.code() != KeeperException.Code.NODEEXISTS) { throw e; } } } public String getNodeName() { return hostName + ":" + localHostPort + "_" + localHostContext; } /** * @param path * @return true if the path exists * @throws KeeperException * @throws InterruptedException */ public boolean pathExists(String path) throws KeeperException, InterruptedException { return zkClient.exists(path, true); } /** * @param collection * @return config value * @throws KeeperException * @throws InterruptedException * @throws IOException */ public String readConfigName(String collection) throws KeeperException, InterruptedException, IOException { String configName = null; String path = ZkStateReader.COLLECTIONS_ZKNODE + "/" + collection; if (log.isInfoEnabled()) { log.info("Load collection config from:" + path); } byte[] data = zkClient.getData(path, null, null, true); if(data != null) { ZkNodeProps props = ZkNodeProps.load(data); configName = props.get(CONFIGNAME_PROP); } if (configName != null && !zkClient.exists(CONFIGS_ZKNODE + "/" + configName, true)) { log.error("Specified config does not exist in ZooKeeper:" + configName); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "Specified config does not exist in ZooKeeper:" + configName); } return configName; } /** * Register shard with ZooKeeper. * * @param coreName * @param desc * @return the shardId for the SolrCore * @throws Exception */ public String register(String coreName, final CoreDescriptor desc) throws Exception { return register(coreName, desc, false); } /** * Register shard with ZooKeeper. * * @param coreName * @param desc * @param recoverReloadedCores * @return the shardId for the SolrCore * @throws Exception */ public String register(String coreName, final CoreDescriptor desc, boolean recoverReloadedCores) throws Exception { final String baseUrl = getBaseUrl(); final CloudDescriptor cloudDesc = desc.getCloudDescriptor(); final String collection = cloudDesc.getCollectionName(); final String coreZkNodeName = getNodeName() + "_" + coreName; String shardId = cloudDesc.getShardId(); Map<String,String> props = new HashMap<String,String>(); // we only put a subset of props into the leader node props.put(ZkStateReader.BASE_URL_PROP, baseUrl); props.put(ZkStateReader.CORE_NAME_PROP, coreName); props.put(ZkStateReader.NODE_NAME_PROP, getNodeName()); if (log.isInfoEnabled()) { log.info("Register shard - core:" + coreName + " address:" + baseUrl + " shardId:" + shardId); } ZkNodeProps leaderProps = new ZkNodeProps(props); // rather than look in the cluster state file, we go straight to the zknodes // here, because on cluster restart there could be stale leader info in the // cluster state node that won't be updated for a moment String leaderUrl = getLeaderProps(collection, cloudDesc.getShardId()).getCoreUrl(); // now wait until our currently cloud state contains the latest leader String cloudStateLeader = zkStateReader.getLeaderUrl(collection, cloudDesc.getShardId(), 30000); int tries = 0; while (!leaderUrl.equals(cloudStateLeader)) { if (tries == 60) { throw new SolrException(ErrorCode.SERVER_ERROR, "There is conflicting information about the leader of shard: " + cloudDesc.getShardId()); } Thread.sleep(1000); tries++; cloudStateLeader = zkStateReader.getLeaderUrl(collection, cloudDesc.getShardId(), 30000); } String ourUrl = ZkCoreNodeProps.getCoreUrl(baseUrl, coreName); log.info("We are " + ourUrl + " and leader is " + leaderUrl); boolean isLeader = leaderUrl.equals(ourUrl); SolrCore core = null; if (cc != null) { // CoreContainer only null in tests try { core = cc.getCore(desc.getName()); if (isLeader) { // recover from local transaction log and wait for it to complete before // going active // TODO: should this be moved to another thread? To recoveryStrat? // TODO: should this actually be done earlier, before (or as part of) // leader election perhaps? // TODO: ensure that a replica that is trying to recover waits until I'm // active (or don't make me the // leader until my local replay is done. But this replay is only needed // on the leader - replicas // will do recovery anyway UpdateLog ulog = core.getUpdateHandler().getUpdateLog(); if (!core.isReloaded() && ulog != null) { Future<UpdateLog.RecoveryInfo> recoveryFuture = core.getUpdateHandler() .getUpdateLog().recoverFromLog(); if (recoveryFuture != null) { recoveryFuture.get(); // NOTE: this could potentially block for // minutes or more! // TODO: public as recovering in the mean time? } } } boolean didRecovery = checkRecovery(coreName, desc, recoverReloadedCores, isLeader, cloudDesc, collection, coreZkNodeName, shardId, leaderProps, core, cc); if (!didRecovery) { publishAsActive(baseUrl, desc, coreZkNodeName, coreName); } } finally { if (core != null) { core.close(); } } } else { publishAsActive(baseUrl, desc, coreZkNodeName, coreName); } // make sure we have an update cluster state right away zkStateReader.updateCloudState(true); return shardId; } /** * Get leader props directly from zk nodes. * * @param collection * @param slice * @return * @throws KeeperException * @throws InterruptedException */ private ZkCoreNodeProps getLeaderProps(final String collection, final String slice) throws KeeperException, InterruptedException { int iterCount = 60; while (iterCount-- > 0) try { byte[] data = zkClient.getData( ZkStateReader.getShardLeadersPath(collection, slice), null, null, true); ZkCoreNodeProps leaderProps = new ZkCoreNodeProps( ZkNodeProps.load(data)); return leaderProps; } catch (NoNodeException e) { Thread.sleep(500); } throw new RuntimeException("Could not get leader props"); } private void joinElection(final String collection, final String shardZkNodeName, String shardId, ZkNodeProps leaderProps, SolrCore core) throws InterruptedException, KeeperException, IOException { ElectionContext context = new ShardLeaderElectionContext(leaderElector, shardId, collection, shardZkNodeName, leaderProps, this, cc); leaderElector.setup(context); electionContexts.put(shardZkNodeName, context); leaderElector.joinElection(context, core); } /** * @param coreName * @param desc * @param recoverReloadedCores * @param isLeader * @param cloudDesc * @param collection * @param shardZkNodeName * @param shardId * @param leaderProps * @param core * @param cc * @return whether or not a recovery was started * @throws InterruptedException * @throws KeeperException * @throws IOException * @throws ExecutionException */ private boolean checkRecovery(String coreName, final CoreDescriptor desc, boolean recoverReloadedCores, final boolean isLeader, final CloudDescriptor cloudDesc, final String collection, final String shardZkNodeName, String shardId, ZkNodeProps leaderProps, SolrCore core, CoreContainer cc) throws InterruptedException, KeeperException, IOException, ExecutionException { if (SKIP_AUTO_RECOVERY) { log.warn("Skipping recovery according to sys prop solrcloud.skip.autorecovery"); return false; } boolean doRecovery = true; if (!isLeader) { if (core.isReloaded() && !recoverReloadedCores) { doRecovery = false; } if (doRecovery) { log.info("Core needs to recover:" + core.getName()); core.getUpdateHandler().getSolrCoreState().doRecovery(cc, coreName); return true; } } else { log.info("I am the leader, no recovery necessary"); } return false; } public String getBaseUrl() { final String baseUrl = localHostName + ":" + localHostPort + "/" + localHostContext; return baseUrl; } void publishAsActive(String shardUrl, final CoreDescriptor cd, String shardZkNodeName, String coreName) { Map<String,String> finalProps = new HashMap<String,String>(); finalProps.put(ZkStateReader.BASE_URL_PROP, shardUrl); finalProps.put(ZkStateReader.CORE_NAME_PROP, coreName); finalProps.put(ZkStateReader.NODE_NAME_PROP, getNodeName()); finalProps.put(ZkStateReader.STATE_PROP, ZkStateReader.ACTIVE); publishState(cd, shardZkNodeName, coreName, finalProps); } public void publish(CoreDescriptor cd, String state) { Map<String,String> finalProps = new HashMap<String,String>(); finalProps.put(ZkStateReader.BASE_URL_PROP, getBaseUrl()); finalProps.put(ZkStateReader.CORE_NAME_PROP, cd.getName()); finalProps.put(ZkStateReader.NODE_NAME_PROP, getNodeName()); finalProps.put(ZkStateReader.STATE_PROP, state); publishState(cd, getNodeName() + "_" + cd.getName(), cd.getName(), finalProps); } void publishAsDown(String baseUrl, final CoreDescriptor cd, String shardZkNodeName, String coreName) { Map<String,String> finalProps = new HashMap<String,String>(); finalProps.put(ZkStateReader.BASE_URL_PROP, baseUrl); finalProps.put(ZkStateReader.CORE_NAME_PROP, coreName); finalProps.put(ZkStateReader.NODE_NAME_PROP, getNodeName()); finalProps.put(ZkStateReader.STATE_PROP, ZkStateReader.DOWN); publishState(cd, shardZkNodeName, coreName, finalProps); } void publishAsRecoveryFailed(String baseUrl, final CoreDescriptor cd, String shardZkNodeName, String coreName) { Map<String,String> finalProps = new HashMap<String,String>(); finalProps.put(ZkStateReader.BASE_URL_PROP, baseUrl); finalProps.put(ZkStateReader.CORE_NAME_PROP, coreName); finalProps.put(ZkStateReader.NODE_NAME_PROP, getNodeName()); finalProps.put(ZkStateReader.STATE_PROP, ZkStateReader.RECOVERY_FAILED); publishState(cd, shardZkNodeName, coreName, finalProps); } private boolean needsToBeAssignedShardId(final CoreDescriptor desc, final CloudState state, final String shardZkNodeName) { final CloudDescriptor cloudDesc = desc.getCloudDescriptor(); final String shardId = state.getShardId(shardZkNodeName); if (shardId != null) { cloudDesc.setShardId(shardId); return false; } return true; } /** * @param coreName * @param cloudDesc * @throws KeeperException * @throws InterruptedException */ public void unregister(String coreName, CloudDescriptor cloudDesc) throws InterruptedException, KeeperException { final String zkNodeName = getNodeName() + "_" + coreName; synchronized (coreStates) { coreStates.remove(zkNodeName); } publishState(); ElectionContext context = electionContexts.remove(zkNodeName); if (context != null) { context.cancelElection(); } } /** * @param dir * @param zkPath * @throws IOException * @throws KeeperException * @throws InterruptedException */ public void uploadToZK(File dir, String zkPath) throws IOException, KeeperException, InterruptedException { uploadToZK(zkClient, dir, zkPath); } /** * @param dir * @param configName * @throws IOException * @throws KeeperException * @throws InterruptedException */ public void uploadConfigDir(File dir, String configName) throws IOException, KeeperException, InterruptedException { uploadToZK(zkClient, dir, ZkController.CONFIGS_ZKNODE + "/" + configName); } // convenience for testing void printLayoutToStdOut() throws KeeperException, InterruptedException { zkClient.printLayoutToStdOut(); } public void createCollectionZkNode(CloudDescriptor cd) throws KeeperException, InterruptedException, IOException { String collection = cd.getCollectionName(); log.info("Check for collection zkNode:" + collection); String collectionPath = ZkStateReader.COLLECTIONS_ZKNODE + "/" + collection; try { if(!zkClient.exists(collectionPath, true)) { log.info("Creating collection in ZooKeeper:" + collection); SolrParams params = cd.getParams(); try { Map<String,String> collectionProps = new HashMap<String,String>(); // TODO: if collection.configName isn't set, and there isn't already a conf in zk, just use that? String defaultConfigName = System.getProperty(COLLECTION_PARAM_PREFIX+CONFIGNAME_PROP, "configuration1"); // params passed in - currently only done via core admin (create core commmand). if (params != null) { Iterator<String> iter = params.getParameterNamesIterator(); while (iter.hasNext()) { String paramName = iter.next(); if (paramName.startsWith(COLLECTION_PARAM_PREFIX)) { collectionProps.put(paramName.substring(COLLECTION_PARAM_PREFIX.length()), params.get(paramName)); } } // if the config name wasn't passed in, use the default if (!collectionProps.containsKey(CONFIGNAME_PROP)) getConfName(collection, collectionPath, collectionProps); } else if(System.getProperty("bootstrap_confdir") != null) { // if we are bootstrapping a collection, default the config for // a new collection to the collection we are bootstrapping log.info("Setting config for collection:" + collection + " to " + defaultConfigName); Properties sysProps = System.getProperties(); for (String sprop : System.getProperties().stringPropertyNames()) { if (sprop.startsWith(COLLECTION_PARAM_PREFIX)) { collectionProps.put(sprop.substring(COLLECTION_PARAM_PREFIX.length()), sysProps.getProperty(sprop)); } } // if the config name wasn't passed in, use the default if (!collectionProps.containsKey(CONFIGNAME_PROP)) collectionProps.put(CONFIGNAME_PROP, defaultConfigName); } else { getConfName(collection, collectionPath, collectionProps); } ZkNodeProps zkProps = new ZkNodeProps(collectionProps); zkClient.makePath(collectionPath, ZkStateReader.toJSON(zkProps), CreateMode.PERSISTENT, null, true); // ping that there is a new collection zkClient.setData(ZkStateReader.COLLECTIONS_ZKNODE, (byte[])null, true); } catch (KeeperException e) { // its okay if the node already exists if (e.code() != KeeperException.Code.NODEEXISTS) { throw e; } } } else { log.info("Collection zkNode exists"); } } catch (KeeperException e) { // its okay if another beats us creating the node if (e.code() != KeeperException.Code.NODEEXISTS) { throw e; } } } private void getConfName(String collection, String collectionPath, Map<String,String> collectionProps) throws KeeperException, InterruptedException { // check for configName log.info("Looking for collection configName"); int retry = 1; for (; retry < 6; retry++) { if (zkClient.exists(collectionPath, true)) { ZkNodeProps cProps = ZkNodeProps.load(zkClient.getData(collectionPath, null, null, true)); if (cProps.containsKey(CONFIGNAME_PROP)) { break; } } // if there is only one conf, use that List<String> configNames = zkClient.getChildren(CONFIGS_ZKNODE, null, true); if (configNames.size() == 1) { // no config set named, but there is only 1 - use it log.info("Only one config set found in zk - using it:" + configNames.get(0)); collectionProps.put(CONFIGNAME_PROP, configNames.get(0)); break; } log.info("Could not find collection configName - pausing for 2 seconds and trying again - try: " + retry); Thread.sleep(2000); } if (retry == 6) { log.error("Could not find configName for collection " + collection); throw new ZooKeeperException( SolrException.ErrorCode.SERVER_ERROR, "Could not find configName for collection " + collection); } } public ZkStateReader getZkStateReader() { return zkStateReader; } private void publishState(CoreDescriptor cd, String shardZkNodeName, String coreName, Map<String,String> props) { CloudDescriptor cloudDesc = cd.getCloudDescriptor(); if (cloudDesc.getRoles() != null) { props.put(ZkStateReader.ROLES_PROP, cloudDesc.getRoles()); } if (cloudDesc.getShardId() == null && needsToBeAssignedShardId(cd, zkStateReader.getCloudState(), shardZkNodeName)) { // publish with no shard id so we are assigned one, and then look for it doPublish(shardZkNodeName, coreName, props, cloudDesc); String shardId; try { shardId = doGetShardIdProcess(coreName, cloudDesc); } catch (InterruptedException e) { throw new SolrException(ErrorCode.SERVER_ERROR, "Interrupted"); } cloudDesc.setShardId(shardId); } if (!props.containsKey(ZkStateReader.SHARD_ID_PROP) && cloudDesc.getShardId() != null) { props.put(ZkStateReader.SHARD_ID_PROP, cloudDesc.getShardId()); } doPublish(shardZkNodeName, coreName, props, cloudDesc); } private void doPublish(String shardZkNodeName, String coreName, Map<String,String> props, CloudDescriptor cloudDesc) { Integer numShards = cloudDesc.getNumShards(); if (numShards == null) { numShards = Integer.getInteger(ZkStateReader.NUM_SHARDS_PROP); } CoreState coreState = new CoreState(coreName, cloudDesc.getCollectionName(), props, numShards); synchronized (coreStates) { coreStates.put(shardZkNodeName, coreState); } publishState(); } private void publishState() { final String nodePath = "/node_states/" + getNodeName(); long version; byte[] coreStatesData; synchronized (coreStates) { version = ++coreStatesVersion; coreStatesData = ZkStateReader.toJSON(coreStates.values()); } // if multiple threads are trying to publish state, make sure that we never write // an older version after a newer version. synchronized (coreStatesPublishLock) { try { if (version < coreStatesPublishedVersion) { log.info("Another thread already published a newer coreStates: ours="+version + " lastPublished=" + coreStatesPublishedVersion); } else { zkClient.setData(nodePath, coreStatesData, true); coreStatesPublishedVersion = version; // put it after so it won't be set if there's an exception } } catch (KeeperException e) { throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "could not publish node state", e); } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "could not publish node state", e); } } } private String doGetShardIdProcess(String coreName, CloudDescriptor descriptor) throws InterruptedException { final String shardZkNodeName = getNodeName() + "_" + coreName; int retryCount = 120; while (retryCount-- > 0) { final String shardId = zkStateReader.getCloudState().getShardId( shardZkNodeName); if (shardId != null) { return shardId; } try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } throw new SolrException(ErrorCode.SERVER_ERROR, "Could not get shard_id for core: " + coreName); } public static void uploadToZK(SolrZkClient zkClient, File dir, String zkPath) throws IOException, KeeperException, InterruptedException { File[] files = dir.listFiles(); if (files == null) { throw new IllegalArgumentException("Illegal directory: " + dir); } for(File file : files) { if (!file.getName().startsWith(".")) { if (!file.isDirectory()) { zkClient.makePath(zkPath + "/" + file.getName(), file, false, true); } else { uploadToZK(zkClient, file, zkPath + "/" + file.getName()); } } } } public static void uploadConfigDir(SolrZkClient zkClient, File dir, String configName) throws IOException, KeeperException, InterruptedException { uploadToZK(zkClient, dir, ZkController.CONFIGS_ZKNODE + "/" + configName); } public void preRegisterSetup(SolrCore core, CoreDescriptor cd, boolean waitForNotLive) { // before becoming available, make sure we are not live and active // this also gets us our assigned shard id if it was not specified publish(cd, ZkStateReader.DOWN); String shardId = cd.getCloudDescriptor().getShardId(); Map<String,String> props = new HashMap<String,String>(); // we only put a subset of props into the leader node props.put(ZkStateReader.BASE_URL_PROP, getBaseUrl()); props.put(ZkStateReader.CORE_NAME_PROP, cd.getName()); props.put(ZkStateReader.NODE_NAME_PROP, getNodeName()); final String coreZkNodeName = getNodeName() + "_" + cd.getName(); ZkNodeProps ourProps = new ZkNodeProps(props); String collection = cd.getCloudDescriptor() .getCollectionName(); try { joinElection(collection, coreZkNodeName, shardId, ourProps, core); } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (KeeperException e) { throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (IOException e) { throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } waitForLeaderToSeeDownState(cd, coreZkNodeName, waitForNotLive); } private ZkCoreNodeProps waitForLeaderToSeeDownState( CoreDescriptor descriptor, final String shardZkNodeName, boolean waitForNotLive) { CloudDescriptor cloudDesc = descriptor.getCloudDescriptor(); String collection = cloudDesc.getCollectionName(); String shard = cloudDesc.getShardId(); ZkCoreNodeProps leaderProps; try { // go straight to zk, not the cloud state - we must have current info leaderProps = getLeaderProps(collection, shard); } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (KeeperException e) { throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } String leaderBaseUrl = leaderProps.getBaseUrl(); String leaderCoreName = leaderProps.getCoreName(); String ourUrl = ZkCoreNodeProps.getCoreUrl(getBaseUrl(), descriptor.getName()); boolean isLeader = leaderProps.getCoreUrl().equals(ourUrl); if (!isLeader && !SKIP_AUTO_RECOVERY) { // wait until the leader sees us as down before we are willing to accept // updates. CommonsHttpSolrServer server = null; try { server = new CommonsHttpSolrServer(leaderBaseUrl); } catch (MalformedURLException e) { throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } server.setConnectionTimeout(45000); server.setSoTimeout(45000); WaitForState prepCmd = new WaitForState(); prepCmd.setCoreName(leaderCoreName); prepCmd.setNodeName(getNodeName()); prepCmd.setCoreNodeName(shardZkNodeName); prepCmd.setState(ZkStateReader.DOWN); prepCmd.setPauseFor(5000); if (waitForNotLive){ prepCmd.setCheckLive(false); } // let's retry a couple times - perhaps the leader just went down, // or perhaps he is just not quite ready for us yet for (int i = 0; i < 3; i++) { try { server.request(prepCmd); break; } catch (Exception e) { SolrException.log(log, "There was a problem making a request to the leader", e); try { Thread.sleep(2000); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } } } server.shutdown(); } return leaderProps; } }
core/src/java/org/apache/solr/cloud/ZkController.java
package org.apache.solr.cloud; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.MalformedURLException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeoutException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer; import org.apache.solr.client.solrj.request.CoreAdminRequest.WaitForState; import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrException.ErrorCode; import org.apache.solr.common.cloud.CloudState; import org.apache.solr.common.cloud.CoreState; import org.apache.solr.common.cloud.OnReconnect; import org.apache.solr.common.cloud.SolrZkClient; import org.apache.solr.common.cloud.ZkCmdExecutor; import org.apache.solr.common.cloud.ZkCoreNodeProps; import org.apache.solr.common.cloud.ZkNodeProps; import org.apache.solr.common.cloud.ZkStateReader; import org.apache.solr.common.cloud.ZooKeeperException; import org.apache.solr.common.params.SolrParams; import org.apache.solr.core.CoreContainer; import org.apache.solr.core.CoreDescriptor; import org.apache.solr.core.SolrCore; import org.apache.solr.update.UpdateLog; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.KeeperException.NoNodeException; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Handle ZooKeeper interactions. * * notes: loads everything on init, creates what's not there - further updates * are prompted with Watches. * * TODO: exceptions during shutdown on attempts to update cloud state * */ public final class ZkController { private static Logger log = LoggerFactory.getLogger(ZkController.class); static final String NEWL = System.getProperty("line.separator"); private final static Pattern URL_POST = Pattern.compile("https?://(.*)"); private final static Pattern URL_PREFIX = Pattern.compile("(https?://).*"); private final boolean SKIP_AUTO_RECOVERY = Boolean.getBoolean("solrcloud.skip.autorecovery"); // package private for tests static final String CONFIGS_ZKNODE = "/configs"; public final static String COLLECTION_PARAM_PREFIX="collection."; public final static String CONFIGNAME_PROP="configName"; private Map<String, CoreState> coreStates = null; private final Map<String, ElectionContext> electionContexts = Collections.synchronizedMap(new HashMap<String, ElectionContext>()); private SolrZkClient zkClient; private ZkCmdExecutor cmdExecutor; private ZkStateReader zkStateReader; private LeaderElector leaderElector; private String zkServerAddress; private String localHostPort; private String localHostContext; private String localHostName; private String localHost; private String hostName; private LeaderElector overseerElector; // this can be null in which case recovery will be inactive private CoreContainer cc; public static void main(String[] args) throws Exception { // start up a tmp zk server first String zkServerAddress = args[0]; String solrPort = args[1]; String confDir = args[2]; String confName = args[3]; String solrHome = null; if (args.length == 5) { solrHome = args[4]; } SolrZkServer zkServer = null; if (solrHome != null) { zkServer = new SolrZkServer("true", null, solrHome, solrPort); zkServer.parseConfig(); zkServer.start(); } SolrZkClient zkClient = new SolrZkClient(zkServerAddress, 15000, 5000, new OnReconnect() { @Override public void command() { }}); uploadConfigDir(zkClient, new File(confDir), confName); if (solrHome != null) { zkServer.stop(); } } /** * @param cc if null, recovery will not be enabled * @param zkServerAddress * @param zkClientTimeout * @param zkClientConnectTimeout * @param localHost * @param locaHostPort * @param localHostContext * @param registerOnReconnect * @throws InterruptedException * @throws TimeoutException * @throws IOException */ public ZkController(CoreContainer cc, String zkServerAddress, int zkClientTimeout, int zkClientConnectTimeout, String localHost, String locaHostPort, String localHostContext, final CurrentCoreDescriptorProvider registerOnReconnect) throws InterruptedException, TimeoutException, IOException { this.cc = cc; if (localHostContext.contains("/")) { throw new IllegalArgumentException("localHostContext (" + localHostContext + ") should not contain a /"); } this.zkServerAddress = zkServerAddress; this.localHostPort = locaHostPort; this.localHostContext = localHostContext; this.localHost = localHost; zkClient = new SolrZkClient(zkServerAddress, zkClientTimeout, zkClientConnectTimeout, // on reconnect, reload cloud info new OnReconnect() { public void command() { try { // we need to create all of our lost watches // seems we dont need to do this again... //Overseer.createClientNodes(zkClient, getNodeName()); ElectionContext context = new OverseerElectionContext(getNodeName(), zkClient, zkStateReader); overseerElector.joinElection(context, null); zkStateReader.createClusterStateWatchersAndUpdate(); List<CoreDescriptor> descriptors = registerOnReconnect .getCurrentDescriptors(); if (descriptors != null) { // before registering as live, make sure everyone is in a // down state for (CoreDescriptor descriptor : descriptors) { final String coreZkNodeName = getNodeName() + "_" + descriptor.getName(); publishAsDown(getBaseUrl(), descriptor, coreZkNodeName, descriptor.getName()); waitForLeaderToSeeDownState(descriptor, coreZkNodeName, true); } } // we have to register as live first to pick up docs in the buffer createEphemeralLiveNode(); // re register all descriptors if (descriptors != null) { for (CoreDescriptor descriptor : descriptors) { // TODO: we need to think carefully about what happens when it was // a leader that was expired - as well as what to do about leaders/overseers // with connection loss register(descriptor.getName(), descriptor, true); } } } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); throw new ZooKeeperException( SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (Exception e) { SolrException.log(log, "", e); throw new ZooKeeperException( SolrException.ErrorCode.SERVER_ERROR, "", e); } } }); cmdExecutor = new ZkCmdExecutor(); leaderElector = new LeaderElector(zkClient); zkStateReader = new ZkStateReader(zkClient); init(); } /** * Closes the underlying ZooKeeper client. */ public void close() { try { zkClient.close(); } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); log.warn("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } } /** * @param collection * @param fileName * @return true if config file exists * @throws KeeperException * @throws InterruptedException */ public boolean configFileExists(String collection, String fileName) throws KeeperException, InterruptedException { Stat stat = zkClient.exists(CONFIGS_ZKNODE + "/" + collection + "/" + fileName, null, true); return stat != null; } /** * @return information about the cluster from ZooKeeper */ public CloudState getCloudState() { return zkStateReader.getCloudState(); } /** * @param zkConfigName * @param fileName * @return config file data (in bytes) * @throws KeeperException * @throws InterruptedException */ public byte[] getConfigFileData(String zkConfigName, String fileName) throws KeeperException, InterruptedException { String zkPath = CONFIGS_ZKNODE + "/" + zkConfigName + "/" + fileName; byte[] bytes = zkClient.getData(zkPath, null, null, true); if (bytes == null) { log.error("Config file contains no data:" + zkPath); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "Config file contains no data:" + zkPath); } return bytes; } // TODO: consider how this is done private String getHostAddress() throws IOException { if (localHost == null) { localHost = "http://" + InetAddress.getLocalHost().getHostName(); } else { Matcher m = URL_PREFIX.matcher(localHost); if (m.matches()) { String prefix = m.group(1); localHost = prefix + localHost; } else { localHost = "http://" + localHost; } } return localHost; } public String getHostName() { return hostName; } public SolrZkClient getZkClient() { return zkClient; } /** * @return zookeeper server address */ public String getZkServerAddress() { return zkServerAddress; } private void init() { try { localHostName = getHostAddress(); Matcher m = URL_POST.matcher(localHostName); if (m.matches()) { hostName = m.group(1); } else { log.error("Unrecognized host:" + localHostName); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "Unrecognized host:" + localHostName); } // makes nodes zkNode cmdExecutor.ensureExists(ZkStateReader.LIVE_NODES_ZKNODE, zkClient); Overseer.createClientNodes(zkClient, getNodeName()); createEphemeralLiveNode(); cmdExecutor.ensureExists(ZkStateReader.COLLECTIONS_ZKNODE, zkClient); syncNodeState(); overseerElector = new LeaderElector(zkClient); ElectionContext context = new OverseerElectionContext(getNodeName(), zkClient, zkStateReader); overseerElector.setup(context); overseerElector.joinElection(context, null); zkStateReader.createClusterStateWatchersAndUpdate(); } catch (IOException e) { log.error("", e); throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Can't create ZooKeeperController", e); } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (KeeperException e) { log.error("", e); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } } /* * sync internal state with zk on startup */ private void syncNodeState() throws KeeperException, InterruptedException { log.debug("Syncing internal state with zk. Current: " + coreStates); final String path = Overseer.STATES_NODE + "/" + getNodeName(); final byte[] data = zkClient.getData(path, null, null, true); coreStates = new HashMap<String,CoreState>(); if (data != null) { CoreState[] states = CoreState.load(data); List<CoreState> stateList = Arrays.asList(states); for(CoreState coreState: stateList) { coreStates.put(coreState.getCoreName(), coreState); } } log.debug("after sync: " + coreStates); } public boolean isConnected() { return zkClient.isConnected(); } private void createEphemeralLiveNode() throws KeeperException, InterruptedException { String nodeName = getNodeName(); String nodePath = ZkStateReader.LIVE_NODES_ZKNODE + "/" + nodeName; log.info("Register node as live in ZooKeeper:" + nodePath); try { boolean nodeDeleted = true; try { // we attempt a delete in the case of a quick server bounce - // if there was not a graceful shutdown, the node may exist // until expiration timeout - so a node won't be created here because // it exists, but eventually the node will be removed. So delete // in case it exists and create a new node. zkClient.delete(nodePath, -1, true); } catch (KeeperException.NoNodeException e) { // fine if there is nothing to delete // TODO: annoying that ZK logs a warning on us nodeDeleted = false; } if (nodeDeleted) { log .info("Found a previous node that still exists while trying to register a new live node " + nodePath + " - removing existing node to create another."); } zkClient.makePath(nodePath, CreateMode.EPHEMERAL, true); } catch (KeeperException e) { // its okay if the node already exists if (e.code() != KeeperException.Code.NODEEXISTS) { throw e; } } } public String getNodeName() { return hostName + ":" + localHostPort + "_" + localHostContext; } /** * @param path * @return true if the path exists * @throws KeeperException * @throws InterruptedException */ public boolean pathExists(String path) throws KeeperException, InterruptedException { return zkClient.exists(path, true); } /** * @param collection * @return config value * @throws KeeperException * @throws InterruptedException * @throws IOException */ public String readConfigName(String collection) throws KeeperException, InterruptedException, IOException { String configName = null; String path = ZkStateReader.COLLECTIONS_ZKNODE + "/" + collection; if (log.isInfoEnabled()) { log.info("Load collection config from:" + path); } byte[] data = zkClient.getData(path, null, null, true); if(data != null) { ZkNodeProps props = ZkNodeProps.load(data); configName = props.get(CONFIGNAME_PROP); } if (configName != null && !zkClient.exists(CONFIGS_ZKNODE + "/" + configName, true)) { log.error("Specified config does not exist in ZooKeeper:" + configName); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "Specified config does not exist in ZooKeeper:" + configName); } return configName; } /** * Register shard with ZooKeeper. * * @param coreName * @param desc * @return the shardId for the SolrCore * @throws Exception */ public String register(String coreName, final CoreDescriptor desc) throws Exception { return register(coreName, desc, false); } /** * Register shard with ZooKeeper. * * @param coreName * @param desc * @param recoverReloadedCores * @return the shardId for the SolrCore * @throws Exception */ public String register(String coreName, final CoreDescriptor desc, boolean recoverReloadedCores) throws Exception { final String baseUrl = getBaseUrl(); final CloudDescriptor cloudDesc = desc.getCloudDescriptor(); final String collection = cloudDesc.getCollectionName(); final String coreZkNodeName = getNodeName() + "_" + coreName; String shardId = cloudDesc.getShardId(); Map<String,String> props = new HashMap<String,String>(); // we only put a subset of props into the leader node props.put(ZkStateReader.BASE_URL_PROP, baseUrl); props.put(ZkStateReader.CORE_NAME_PROP, coreName); props.put(ZkStateReader.NODE_NAME_PROP, getNodeName()); if (log.isInfoEnabled()) { log.info("Register shard - core:" + coreName + " address:" + baseUrl + " shardId:" + shardId); } ZkNodeProps leaderProps = new ZkNodeProps(props); // rather than look in the cluster state file, we go straight to the zknodes // here, because on cluster restart there could be stale leader info in the // cluster state node that won't be updated for a moment String leaderUrl = getLeaderProps(collection, cloudDesc.getShardId()).getCoreUrl(); // now wait until our currently cloud state contains the latest leader String cloudStateLeader = zkStateReader.getLeaderUrl(collection, cloudDesc.getShardId(), 30000); int tries = 0; while (!leaderUrl.equals(cloudStateLeader)) { if (tries == 60) { throw new SolrException(ErrorCode.SERVER_ERROR, "There is conflicting information about the leader of shard: " + cloudDesc.getShardId()); } Thread.sleep(1000); tries++; cloudStateLeader = zkStateReader.getLeaderUrl(collection, cloudDesc.getShardId(), 30000); } String ourUrl = ZkCoreNodeProps.getCoreUrl(baseUrl, coreName); log.info("We are " + ourUrl + " and leader is " + leaderUrl); boolean isLeader = leaderUrl.equals(ourUrl); SolrCore core = null; if (cc != null) { // CoreContainer only null in tests try { core = cc.getCore(desc.getName()); if (isLeader) { // recover from local transaction log and wait for it to complete before // going active // TODO: should this be moved to another thread? To recoveryStrat? // TODO: should this actually be done earlier, before (or as part of) // leader election perhaps? // TODO: ensure that a replica that is trying to recover waits until I'm // active (or don't make me the // leader until my local replay is done. But this replay is only needed // on the leader - replicas // will do recovery anyway UpdateLog ulog = core.getUpdateHandler().getUpdateLog(); if (!core.isReloaded() && ulog != null) { Future<UpdateLog.RecoveryInfo> recoveryFuture = core.getUpdateHandler() .getUpdateLog().recoverFromLog(); if (recoveryFuture != null) { recoveryFuture.get(); // NOTE: this could potentially block for // minutes or more! // TODO: public as recovering in the mean time? } } } boolean didRecovery = checkRecovery(coreName, desc, recoverReloadedCores, isLeader, cloudDesc, collection, coreZkNodeName, shardId, leaderProps, core, cc); if (!didRecovery) { publishAsActive(baseUrl, desc, coreZkNodeName, coreName); } } finally { if (core != null) { core.close(); } } } else { publishAsActive(baseUrl, desc, coreZkNodeName, coreName); } // make sure we have an update cluster state right away zkStateReader.updateCloudState(true); return shardId; } /** * Get leader props directly from zk nodes. * * @param collection * @param slice * @return * @throws KeeperException * @throws InterruptedException */ private ZkCoreNodeProps getLeaderProps(final String collection, final String slice) throws KeeperException, InterruptedException { int iterCount = 60; while (iterCount-- > 0) try { byte[] data = zkClient.getData( ZkStateReader.getShardLeadersPath(collection, slice), null, null, true); ZkCoreNodeProps leaderProps = new ZkCoreNodeProps( ZkNodeProps.load(data)); return leaderProps; } catch (NoNodeException e) { Thread.sleep(500); } throw new RuntimeException("Could not get leader props"); } private void joinElection(final String collection, final String shardZkNodeName, String shardId, ZkNodeProps leaderProps, SolrCore core) throws InterruptedException, KeeperException, IOException { ElectionContext context = new ShardLeaderElectionContext(leaderElector, shardId, collection, shardZkNodeName, leaderProps, this, cc); leaderElector.setup(context); electionContexts.put(shardZkNodeName, context); leaderElector.joinElection(context, core); } /** * @param coreName * @param desc * @param recoverReloadedCores * @param isLeader * @param cloudDesc * @param collection * @param shardZkNodeName * @param shardId * @param leaderProps * @param core * @param cc * @return whether or not a recovery was started * @throws InterruptedException * @throws KeeperException * @throws IOException * @throws ExecutionException */ private boolean checkRecovery(String coreName, final CoreDescriptor desc, boolean recoverReloadedCores, final boolean isLeader, final CloudDescriptor cloudDesc, final String collection, final String shardZkNodeName, String shardId, ZkNodeProps leaderProps, SolrCore core, CoreContainer cc) throws InterruptedException, KeeperException, IOException, ExecutionException { if (SKIP_AUTO_RECOVERY) { log.warn("Skipping recovery according to sys prop solrcloud.skip.autorecovery"); return false; } boolean doRecovery = true; if (!isLeader) { if (core.isReloaded() && !recoverReloadedCores) { doRecovery = false; } if (doRecovery) { log.info("Core needs to recover:" + core.getName()); core.getUpdateHandler().getSolrCoreState().doRecovery(cc, coreName); return true; } } else { log.info("I am the leader, no recovery necessary"); } return false; } public String getBaseUrl() { final String baseUrl = localHostName + ":" + localHostPort + "/" + localHostContext; return baseUrl; } void publishAsActive(String shardUrl, final CoreDescriptor cd, String shardZkNodeName, String coreName) { Map<String,String> finalProps = new HashMap<String,String>(); finalProps.put(ZkStateReader.BASE_URL_PROP, shardUrl); finalProps.put(ZkStateReader.CORE_NAME_PROP, coreName); finalProps.put(ZkStateReader.NODE_NAME_PROP, getNodeName()); finalProps.put(ZkStateReader.STATE_PROP, ZkStateReader.ACTIVE); publishState(cd, shardZkNodeName, coreName, finalProps); } public void publish(CoreDescriptor cd, String state) { Map<String,String> finalProps = new HashMap<String,String>(); finalProps.put(ZkStateReader.BASE_URL_PROP, getBaseUrl()); finalProps.put(ZkStateReader.CORE_NAME_PROP, cd.getName()); finalProps.put(ZkStateReader.NODE_NAME_PROP, getNodeName()); finalProps.put(ZkStateReader.STATE_PROP, state); publishState(cd, getNodeName() + "_" + cd.getName(), cd.getName(), finalProps); } void publishAsDown(String baseUrl, final CoreDescriptor cd, String shardZkNodeName, String coreName) { Map<String,String> finalProps = new HashMap<String,String>(); finalProps.put(ZkStateReader.BASE_URL_PROP, baseUrl); finalProps.put(ZkStateReader.CORE_NAME_PROP, coreName); finalProps.put(ZkStateReader.NODE_NAME_PROP, getNodeName()); finalProps.put(ZkStateReader.STATE_PROP, ZkStateReader.DOWN); publishState(cd, shardZkNodeName, coreName, finalProps); } void publishAsRecoveryFailed(String baseUrl, final CoreDescriptor cd, String shardZkNodeName, String coreName) { Map<String,String> finalProps = new HashMap<String,String>(); finalProps.put(ZkStateReader.BASE_URL_PROP, baseUrl); finalProps.put(ZkStateReader.CORE_NAME_PROP, coreName); finalProps.put(ZkStateReader.NODE_NAME_PROP, getNodeName()); finalProps.put(ZkStateReader.STATE_PROP, ZkStateReader.RECOVERY_FAILED); publishState(cd, shardZkNodeName, coreName, finalProps); } private boolean needsToBeAssignedShardId(final CoreDescriptor desc, final CloudState state, final String shardZkNodeName) { final CloudDescriptor cloudDesc = desc.getCloudDescriptor(); final String shardId = state.getShardId(shardZkNodeName); if (shardId != null) { cloudDesc.setShardId(shardId); return false; } return true; } /** * @param coreName * @param cloudDesc * @throws KeeperException * @throws InterruptedException */ public void unregister(String coreName, CloudDescriptor cloudDesc) throws InterruptedException, KeeperException { final String zkNodeName = getNodeName() + "_" + coreName; synchronized (coreStates) { coreStates.remove(zkNodeName); } publishState(); ElectionContext context = electionContexts.remove(zkNodeName); if (context != null) { context.cancelElection(); } } /** * @param dir * @param zkPath * @throws IOException * @throws KeeperException * @throws InterruptedException */ public void uploadToZK(File dir, String zkPath) throws IOException, KeeperException, InterruptedException { uploadToZK(zkClient, dir, zkPath); } /** * @param dir * @param configName * @throws IOException * @throws KeeperException * @throws InterruptedException */ public void uploadConfigDir(File dir, String configName) throws IOException, KeeperException, InterruptedException { uploadToZK(zkClient, dir, ZkController.CONFIGS_ZKNODE + "/" + configName); } // convenience for testing void printLayoutToStdOut() throws KeeperException, InterruptedException { zkClient.printLayoutToStdOut(); } public void createCollectionZkNode(CloudDescriptor cd) throws KeeperException, InterruptedException, IOException { String collection = cd.getCollectionName(); log.info("Check for collection zkNode:" + collection); String collectionPath = ZkStateReader.COLLECTIONS_ZKNODE + "/" + collection; try { if(!zkClient.exists(collectionPath, true)) { log.info("Creating collection in ZooKeeper:" + collection); SolrParams params = cd.getParams(); try { Map<String,String> collectionProps = new HashMap<String,String>(); // TODO: if collection.configName isn't set, and there isn't already a conf in zk, just use that? String defaultConfigName = System.getProperty(COLLECTION_PARAM_PREFIX+CONFIGNAME_PROP, "configuration1"); // params passed in - currently only done via core admin (create core commmand). if (params != null) { Iterator<String> iter = params.getParameterNamesIterator(); while (iter.hasNext()) { String paramName = iter.next(); if (paramName.startsWith(COLLECTION_PARAM_PREFIX)) { collectionProps.put(paramName.substring(COLLECTION_PARAM_PREFIX.length()), params.get(paramName)); } } // if the config name wasn't passed in, use the default if (!collectionProps.containsKey(CONFIGNAME_PROP)) getConfName(collection, collectionPath, collectionProps); } else if(System.getProperty("bootstrap_confdir") != null) { // if we are bootstrapping a collection, default the config for // a new collection to the collection we are bootstrapping log.info("Setting config for collection:" + collection + " to " + defaultConfigName); Properties sysProps = System.getProperties(); for (String sprop : System.getProperties().stringPropertyNames()) { if (sprop.startsWith(COLLECTION_PARAM_PREFIX)) { collectionProps.put(sprop.substring(COLLECTION_PARAM_PREFIX.length()), sysProps.getProperty(sprop)); } } // if the config name wasn't passed in, use the default if (!collectionProps.containsKey(CONFIGNAME_PROP)) collectionProps.put(CONFIGNAME_PROP, defaultConfigName); } else { getConfName(collection, collectionPath, collectionProps); } ZkNodeProps zkProps = new ZkNodeProps(collectionProps); zkClient.makePath(collectionPath, ZkStateReader.toJSON(zkProps), CreateMode.PERSISTENT, null, true); // ping that there is a new collection zkClient.setData(ZkStateReader.COLLECTIONS_ZKNODE, (byte[])null, true); } catch (KeeperException e) { // its okay if the node already exists if (e.code() != KeeperException.Code.NODEEXISTS) { throw e; } } } else { log.info("Collection zkNode exists"); } } catch (KeeperException e) { // its okay if another beats us creating the node if (e.code() != KeeperException.Code.NODEEXISTS) { throw e; } } } private void getConfName(String collection, String collectionPath, Map<String,String> collectionProps) throws KeeperException, InterruptedException { // check for configName log.info("Looking for collection configName"); int retry = 1; for (; retry < 6; retry++) { if (zkClient.exists(collectionPath, true)) { ZkNodeProps cProps = ZkNodeProps.load(zkClient.getData(collectionPath, null, null, true)); if (cProps.containsKey(CONFIGNAME_PROP)) { break; } } // if there is only one conf, use that List<String> configNames = zkClient.getChildren(CONFIGS_ZKNODE, null, true); if (configNames.size() == 1) { // no config set named, but there is only 1 - use it log.info("Only one config set found in zk - using it:" + configNames.get(0)); collectionProps.put(CONFIGNAME_PROP, configNames.get(0)); break; } log.info("Could not find collection configName - pausing for 2 seconds and trying again - try: " + retry); Thread.sleep(2000); } if (retry == 6) { log.error("Could not find configName for collection " + collection); throw new ZooKeeperException( SolrException.ErrorCode.SERVER_ERROR, "Could not find configName for collection " + collection); } } public ZkStateReader getZkStateReader() { return zkStateReader; } private void publishState(CoreDescriptor cd, String shardZkNodeName, String coreName, Map<String,String> props) { CloudDescriptor cloudDesc = cd.getCloudDescriptor(); if (cloudDesc.getRoles() != null) { props.put(ZkStateReader.ROLES_PROP, cloudDesc.getRoles()); } if (cloudDesc.getShardId() == null && needsToBeAssignedShardId(cd, zkStateReader.getCloudState(), shardZkNodeName)) { // publish with no shard id so we are assigned one, and then look for it doPublish(shardZkNodeName, coreName, props, cloudDesc); String shardId; try { shardId = doGetShardIdProcess(coreName, cloudDesc); } catch (InterruptedException e) { throw new SolrException(ErrorCode.SERVER_ERROR, "Interrupted"); } cloudDesc.setShardId(shardId); } if (!props.containsKey(ZkStateReader.SHARD_ID_PROP) && cloudDesc.getShardId() != null) { props.put(ZkStateReader.SHARD_ID_PROP, cloudDesc.getShardId()); } doPublish(shardZkNodeName, coreName, props, cloudDesc); } private void doPublish(String shardZkNodeName, String coreName, Map<String,String> props, CloudDescriptor cloudDesc) { Integer numShards = cloudDesc.getNumShards(); if (numShards == null) { numShards = Integer.getInteger(ZkStateReader.NUM_SHARDS_PROP); } CoreState coreState = new CoreState(coreName, cloudDesc.getCollectionName(), props, numShards); synchronized (coreStates) { coreStates.put(shardZkNodeName, coreState); } publishState(); } private void publishState() { final String nodePath = "/node_states/" + getNodeName(); synchronized (coreStates) { try { zkClient.setData(nodePath, ZkStateReader.toJSON(coreStates.values()), true); } catch (KeeperException e) { throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "could not publish node state", e); } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "could not publish node state", e); } } } private String doGetShardIdProcess(String coreName, CloudDescriptor descriptor) throws InterruptedException { final String shardZkNodeName = getNodeName() + "_" + coreName; int retryCount = 120; while (retryCount-- > 0) { final String shardId = zkStateReader.getCloudState().getShardId( shardZkNodeName); if (shardId != null) { return shardId; } try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } throw new SolrException(ErrorCode.SERVER_ERROR, "Could not get shard_id for core: " + coreName); } public static void uploadToZK(SolrZkClient zkClient, File dir, String zkPath) throws IOException, KeeperException, InterruptedException { File[] files = dir.listFiles(); if (files == null) { throw new IllegalArgumentException("Illegal directory: " + dir); } for(File file : files) { if (!file.getName().startsWith(".")) { if (!file.isDirectory()) { zkClient.makePath(zkPath + "/" + file.getName(), file, false, true); } else { uploadToZK(zkClient, file, zkPath + "/" + file.getName()); } } } } public static void uploadConfigDir(SolrZkClient zkClient, File dir, String configName) throws IOException, KeeperException, InterruptedException { uploadToZK(zkClient, dir, ZkController.CONFIGS_ZKNODE + "/" + configName); } public void preRegisterSetup(SolrCore core, CoreDescriptor cd, boolean waitForNotLive) { // before becoming available, make sure we are not live and active // this also gets us our assigned shard id if it was not specified publish(cd, ZkStateReader.DOWN); String shardId = cd.getCloudDescriptor().getShardId(); Map<String,String> props = new HashMap<String,String>(); // we only put a subset of props into the leader node props.put(ZkStateReader.BASE_URL_PROP, getBaseUrl()); props.put(ZkStateReader.CORE_NAME_PROP, cd.getName()); props.put(ZkStateReader.NODE_NAME_PROP, getNodeName()); final String coreZkNodeName = getNodeName() + "_" + cd.getName(); ZkNodeProps ourProps = new ZkNodeProps(props); String collection = cd.getCloudDescriptor() .getCollectionName(); try { joinElection(collection, coreZkNodeName, shardId, ourProps, core); } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (KeeperException e) { throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (IOException e) { throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } waitForLeaderToSeeDownState(cd, coreZkNodeName, waitForNotLive); } private ZkCoreNodeProps waitForLeaderToSeeDownState( CoreDescriptor descriptor, final String shardZkNodeName, boolean waitForNotLive) { CloudDescriptor cloudDesc = descriptor.getCloudDescriptor(); String collection = cloudDesc.getCollectionName(); String shard = cloudDesc.getShardId(); ZkCoreNodeProps leaderProps; try { // go straight to zk, not the cloud state - we must have current info leaderProps = getLeaderProps(collection, shard); } catch (InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } catch (KeeperException e) { throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } String leaderBaseUrl = leaderProps.getBaseUrl(); String leaderCoreName = leaderProps.getCoreName(); String ourUrl = ZkCoreNodeProps.getCoreUrl(getBaseUrl(), descriptor.getName()); boolean isLeader = leaderProps.getCoreUrl().equals(ourUrl); if (!isLeader && !SKIP_AUTO_RECOVERY) { // wait until the leader sees us as down before we are willing to accept // updates. CommonsHttpSolrServer server = null; try { server = new CommonsHttpSolrServer(leaderBaseUrl); } catch (MalformedURLException e) { throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e); } server.setConnectionTimeout(45000); server.setSoTimeout(45000); WaitForState prepCmd = new WaitForState(); prepCmd.setCoreName(leaderCoreName); prepCmd.setNodeName(getNodeName()); prepCmd.setCoreNodeName(shardZkNodeName); prepCmd.setState(ZkStateReader.DOWN); prepCmd.setPauseFor(5000); if (waitForNotLive){ prepCmd.setCheckLive(false); } // let's retry a couple times - perhaps the leader just went down, // or perhaps he is just not quite ready for us yet for (int i = 0; i < 3; i++) { try { server.request(prepCmd); break; } catch (Exception e) { SolrException.log(log, "There was a problem making a request to the leader", e); try { Thread.sleep(2000); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } } } server.shutdown(); } return leaderProps; } }
SOLR-3080: separate sync for publishing coreStates git-svn-id: 308d55f399f3bd9aa0560a10e81a003040006c48@1293391 13f79535-47bb-0310-9956-ffa450edef68
core/src/java/org/apache/solr/cloud/ZkController.java
SOLR-3080: separate sync for publishing coreStates
<ide><path>ore/src/java/org/apache/solr/cloud/ZkController.java <ide> public final static String CONFIGNAME_PROP="configName"; <ide> <ide> private Map<String, CoreState> coreStates = null; <add> private long coreStatesVersion; // bumped by 1 each time we serialize coreStates... sync on coreStates <add> private long coreStatesPublishedVersion; // last version published to ZK... sync on coreStatesPublishLock <add> private Object coreStatesPublishLock = new Object(); // only publish one at a time <add> <ide> private final Map<String, ElectionContext> electionContexts = Collections.synchronizedMap(new HashMap<String, ElectionContext>()); <ide> <ide> private SolrZkClient zkClient; <ide> private void publishState() { <ide> final String nodePath = "/node_states/" + getNodeName(); <ide> <add> long version; <add> byte[] coreStatesData; <ide> synchronized (coreStates) { <add> version = ++coreStatesVersion; <add> coreStatesData = ZkStateReader.toJSON(coreStates.values()); <add> } <add> <add> // if multiple threads are trying to publish state, make sure that we never write <add> // an older version after a newer version. <add> synchronized (coreStatesPublishLock) { <ide> try { <del> zkClient.setData(nodePath, ZkStateReader.toJSON(coreStates.values()), <del> true); <del> <add> if (version < coreStatesPublishedVersion) { <add> log.info("Another thread already published a newer coreStates: ours="+version + " lastPublished=" + coreStatesPublishedVersion); <add> } else { <add> zkClient.setData(nodePath, coreStatesData, true); <add> coreStatesPublishedVersion = version; // put it after so it won't be set if there's an exception <add> } <ide> } catch (KeeperException e) { <ide> throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, <ide> "could not publish node state", e);
JavaScript
agpl-3.0
11426c148c4d257a8c2a2e8539457eb4c5d02801
0
chamerling/rse-chamerling,chamerling/rse-chamerling,heroandtn3/openpaas-esn,heroandtn3/openpaas-esn,heroandtn3/openpaas-esn
'use strict'; /* global chai: false */ var expect = chai.expect; describe('The Domain Angular module', function() { beforeEach(angular.mock.module('esn.domain')); describe('domainAPI service', function() { describe('inviteUsers() method', function() { beforeEach(angular.mock.inject(function(domainAPI, $httpBackend, Restangular) { this.domainAPI = domainAPI; this.$httpBackend = $httpBackend; this.domainId = '123456789'; // The full response configuration option has to be set at the application level // It is set here to get the same behavior Restangular.setFullResponse(true); })); it('should send a POST to /domains/:uuid/invitations', function() { var users = ['[email protected]', '[email protected]', '[email protected]', '[email protected]']; this.$httpBackend.expectPOST('/domains/' + this.domainId + '/invitations', users).respond(202); this.domainAPI.inviteUsers(this.domainId, users); this.$httpBackend.flush(); }); it('should return a promise', function() { var promise = this.domainAPI.inviteUsers(this.domainId, {}); expect(promise.then).to.be.a.function; }); }); describe('getMembers() method', function() { beforeEach(angular.mock.inject(function(domainAPI, $httpBackend, Restangular) { this.domainAPI = domainAPI; this.$httpBackend = $httpBackend; this.domainId = '123456789'; this.response = [{name: 'MyDomain', company_name: 'MyAwesomeCompany'}]; this.headers = {'x-esn-items-count': this.response.length}; // The full response configuration option has to be set at the application level // It is set here to get the same behavior Restangular.setFullResponse(true); })); it('should send a request to /domains/:uuid', function() { this.$httpBackend.expectGET('/domains/' + this.domainId + '/members').respond(200, this.response, this.headers); this.domainAPI.getMembers(this.domainId); this.$httpBackend.flush(); }); it('should send a request to /domains/:uuid/members?limit=10&offset=20', function() { var query = {limit: 10, offset: 20}; this.$httpBackend.expectGET('/domains/' + this.domainId + '/members?limit=' + query.limit + '&offset=20').respond(200, this.response, this.headers); this.domainAPI.getMembers(this.domainId, query); this.$httpBackend.flush(); }); it('should send a request to /domains/:uuid?search=foo+bar', function() { var query = {search: 'foo bar'}; this.$httpBackend.expectGET('/domains/' + this.domainId + '/members?search=foo+bar').respond(200, this.response, this.headers); this.domainAPI.getMembers(this.domainId, query); this.$httpBackend.flush(); }); it('should be able to get the count header from the response', function(done) { this.$httpBackend.expectGET('/domains/' + this.domainId + '/members').respond(200, this.response, this.headers); var self = this; this.domainAPI.getMembers(this.domainId, {}).then( function(data) { expect(data).to.be.not.null; expect(data.headers).to.be.a.function; expect(data.headers('x-esn-items-count')).to.be.not.null; expect(data.headers('x-esn-items-count')).to.equal('' + self.headers['x-esn-items-count']); done(); }, function(err) { done(err); }); this.$httpBackend.flush(); }); it('should return a promise', function() { var promise = this.domainAPI.getMembers(this.domainId, {}); expect(promise.then).to.be.a.function; }); }); }); });
test/unit-frontend/modules/domain.js
'use strict'; /* global chai: false */ var expect = chai.expect; describe('The Domain Angular module', function() { beforeEach(angular.mock.module('esn.domain')); describe('domainAPI service', function() { describe('inviteUsers() method', function() { beforeEach(angular.mock.inject(function(domainAPI, $httpBackend, Restangular) { this.domainAPI = domainAPI; this.$httpBackend = $httpBackend; this.domainId = '123456789'; // The full response configuration option has to be set at the application level // It is set here to get the same behavior Restangular.setFullResponse(true); })); it('should send a POST to /domains/:uuid/invitations', function() { var users = ['[email protected]']; this.$httpBackend.expectPOST('/domains/' + this.domainId + '/invitations', users).respond(202); this.domainAPI.inviteUsers(this.domainId, users); this.$httpBackend.flush(); }); it('should return a promise', function() { var promise = this.domainAPI.inviteUsers(this.domainId, {}); expect(promise.then).to.be.a.function; }); }); describe('getMembers() method', function() { beforeEach(angular.mock.inject(function(domainAPI, $httpBackend, Restangular) { this.domainAPI = domainAPI; this.$httpBackend = $httpBackend; this.domainId = '123456789'; this.response = [{name: 'MyDomain', company_name: 'MyAwesomeCompany'}]; this.headers = {'x-esn-items-count': this.response.length}; // The full response configuration option has to be set at the application level // It is set here to get the same behavior Restangular.setFullResponse(true); })); it('should send a request to /domains/:uuid', function() { this.$httpBackend.expectGET('/domains/' + this.domainId + '/members').respond(200, this.response, this.headers); this.domainAPI.getMembers(this.domainId); this.$httpBackend.flush(); }); it('should send a request to /domains/:uuid/members?limit=10&offset=20', function() { var query = {limit: 10, offset: 20}; this.$httpBackend.expectGET('/domains/' + this.domainId + '/members?limit=' + query.limit + '&offset=20').respond(200, this.response, this.headers); this.domainAPI.getMembers(this.domainId, query); this.$httpBackend.flush(); }); it('should send a request to /domains/:uuid?search=foo+bar', function() { var query = {search: 'foo bar'}; this.$httpBackend.expectGET('/domains/' + this.domainId + '/members?search=foo+bar').respond(200, this.response, this.headers); this.domainAPI.getMembers(this.domainId, query); this.$httpBackend.flush(); }); it('should be able to get the count header from the response', function(done) { this.$httpBackend.expectGET('/domains/' + this.domainId + '/members').respond(200, this.response, this.headers); var self = this; this.domainAPI.getMembers(this.domainId, {}).then( function(data) { expect(data).to.be.not.null; expect(data.headers).to.be.a.function; expect(data.headers('x-esn-items-count')).to.be.not.null; expect(data.headers('x-esn-items-count')).to.equal('' + self.headers['x-esn-items-count']); done(); }, function(err) { done(err); }); this.$httpBackend.flush(); }); it('should return a promise', function() { var promise = this.domainAPI.getMembers(this.domainId, {}); expect(promise.then).to.be.a.function; }); }); }); });
OR-202 Push more email in the test
test/unit-frontend/modules/domain.js
OR-202 Push more email in the test
<ide><path>est/unit-frontend/modules/domain.js <ide> })); <ide> <ide> it('should send a POST to /domains/:uuid/invitations', function() { <del> var users = ['[email protected]']; <add> var users = ['[email protected]', '[email protected]', '[email protected]', '[email protected]']; <ide> this.$httpBackend.expectPOST('/domains/' + this.domainId + '/invitations', users).respond(202); <ide> this.domainAPI.inviteUsers(this.domainId, users); <ide> this.$httpBackend.flush();
JavaScript
mit
af1e8a3c644a2f56d4ecb52f65d0aaf62a3f27d6
0
BrowserSync/browser-sync-client
var gulp = require("gulp"); var karma = require('gulp-karma'); var jshint = require('gulp-jshint'); var contribs = require('gulp-contribs'); var browserify = require('gulp-browserify'); var uglify = require('gulp-uglify'); var through2 = require('through2'); var rename = require('gulp-rename'); var testFiles = [ 'test/todo.js' ]; gulp.task('test', function() { // Be sure to return the stream return gulp.src(testFiles) .pipe(karma({ configFile: 'test/karma.conf.ci.js', action: 'run' })); }); gulp.task('test:watch', function() { gulp.src(testFiles) .pipe(karma({ configFile: 'test/karma.conf.js', action: 'watch' })); }); gulp.task('lint-test', function () { gulp.src(['test/client-new/*.js', 'test/middleware/*.js']) .pipe(jshint('test/.jshintrc')) .pipe(jshint.reporter("default")) .pipe(jshint.reporter("fail")) }); gulp.task('lint-lib', function () { gulp.src(['lib/*', '!lib/browser-sync-client.js', '!lib/events.js']) .pipe(jshint('lib/.jshintrc')) .pipe(jshint.reporter("default")) .pipe(jshint.reporter("fail")) }); gulp.task('contribs', function () { gulp.src('README.md') .pipe(contribs()) .pipe(gulp.dest("./")) }); /** * Strip debug statements * @returns {*} */ var stripDebug = function () { return through2.obj(function (file, enc, cb) { var string = file.contents.toString(); var regex = /\/\*\*debug:start\*\*\/[\s\S]*\/\*\*debug:end\*\*\//g; var stripped = string.replace(regex, ""); file.contents = new Buffer(stripped); this.push(file); cb(); }); }; // Basic usage gulp.task('build-dist', function() { // Single entry point to browserify gulp.src('lib/index.js') .pipe(browserify()) .pipe(gulp.dest('./dist')) .pipe(stripDebug()) .pipe(uglify()) .pipe(rename("index.min.js")) .pipe(gulp.dest('./dist')); }); gulp.task('build-dev', function() { // Single entry point to browserify gulp.src('lib/index.js') .pipe(browserify()) .pipe(gulp.dest('./dist')) }); gulp.task("dev", ['build-dist'], function () { gulp.watch(["lib/*.js", "test/client-new/**/*.js"], ['build-dist']); }); gulp.task('default', ["lint-lib", "lint-test", "build-dist", "test"]);
gulpfile.js
var gulp = require("gulp"); var karma = require('gulp-karma'); var jshint = require('gulp-jshint'); var contribs = require('gulp-contribs'); var browserify = require('gulp-browserify'); var uglify = require('gulp-uglify'); var through2 = require('through2'); var rename = require('gulp-rename'); var testFiles = [ 'test/todo.js' ]; gulp.task('test', function() { // Be sure to return the stream return gulp.src(testFiles) .pipe(karma({ configFile: 'test/karma.conf.ci.js', action: 'run' })); }); gulp.task('test:watch', function() { gulp.src(testFiles) .pipe(karma({ configFile: 'test/karma.conf.js', action: 'watch' })); }); gulp.task('lint-test', function () { gulp.src(['test/client-new/*.js', 'test/middleware/*.js']) .pipe(jshint('test/.jshintrc')) .pipe(jshint.reporter("default")) .pipe(jshint.reporter("fail")) }); gulp.task('lint-lib', function () { gulp.src(['lib/*', '!lib/browser-sync-client.js', '!lib/events.js']) .pipe(jshint('lib/.jshintrc')) .pipe(jshint.reporter("default")) .pipe(jshint.reporter("fail")) }); gulp.task('contribs', function () { gulp.src('README.md') .pipe(contribs()) .pipe(gulp.dest("./")) }); /** * Strip debug statements * @returns {*} */ var stripDebug = function () { return through2.obj(function (file, enc, cb) { var string = file.contents.toString(); var regex = /\/\*\*debug:start\*\*\/[\s\S]*\/\*\*debug:end\*\*\//g; var stripped = string.replace(regex, ""); file.contents = new Buffer(stripped); this.push(file); cb(); }); }; // Basic usage gulp.task('build-dist', function() { // Single entry point to browserify gulp.src('lib/index.js') .pipe(browserify()) .pipe(gulp.dest('./dist')) .pipe(stripDebug()) .pipe(uglify()) .pipe(rename("index.min.js")) .pipe(gulp.dest('./dist')); }); gulp.task('build-dev', function() { // Single entry point to browserify gulp.src('lib/index.js') .pipe(browserify()) .pipe(gulp.dest('./dist')) }); gulp.task("dev", ['build-dist'], function () { gulp.watch(["lib/*.js", "test/client-new/**/*.js"], ['build-dist']); }); gulp.task('default', ["lint-lib", "lint-test", "test"]);
Add building to CI
gulpfile.js
Add building to CI
<ide><path>ulpfile.js <ide> gulp.watch(["lib/*.js", "test/client-new/**/*.js"], ['build-dist']); <ide> }); <ide> <del>gulp.task('default', ["lint-lib", "lint-test", "test"]); <add>gulp.task('default', ["lint-lib", "lint-test", "build-dist", "test"]);
Java
apache-2.0
c7c76d7924c15331248af07aa76bb06e63cdbe8d
0
mwaylabs/relution-jenkins-plugin,mwaylabs/relution-jenkins-plugin,jenkinsci/relution-plugin,mwaylabs/relution-jenkins-plugin
/* * Copyright (c) 2013-2014 M-Way Solutions GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jenkinsci.plugins.relution_publisher.configuration.jobs; import org.apache.commons.lang.StringUtils; import org.jenkinsci.plugins.relution_publisher.builder.ArtifactFileUploader; import org.jenkinsci.plugins.relution_publisher.configuration.global.Store; import org.jenkinsci.plugins.relution_publisher.configuration.global.StoreConfiguration; import org.jenkinsci.plugins.relution_publisher.constants.UploadMode; import org.jenkinsci.plugins.relution_publisher.entities.Version; import org.jenkinsci.plugins.relution_publisher.logging.Log; import org.jenkinsci.plugins.relution_publisher.util.Builds; import org.kohsuke.stapler.DataBoundConstructor; import java.io.IOException; import java.security.AlgorithmParameterGenerator; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.Security; import java.util.List; import javax.crypto.Cipher; import javax.inject.Inject; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.Result; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Publisher; import hudson.tasks.Recorder; /** * Publishes a {@link Version} to the Relution Enterprise Appstore using the * {@link ArtifactFileUploader} to perform the actual upload of the file. */ public class ArtifactPublisher extends Recorder { private final List<Publication> publications; @DataBoundConstructor public ArtifactPublisher(final List<Publication> publications) { this.getDescriptor().setPublications(publications); this.publications = publications; } public List<Publication> getPublications() { return this.publications; } @Override public ArtifactPublisherDescriptor getDescriptor() { return (ArtifactPublisherDescriptor) super.getDescriptor(); } @Override public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.NONE; } @Override public boolean perform(final AbstractBuild<?, ?> build, final Launcher launcher, final BuildListener listener) throws InterruptedException, IOException { final Log log = new Log(listener); log.write(); if (this.publications == null) { log.write(this, "Skipped, no publications configured"); Builds.setResult(build, Result.UNSTABLE, log); return true; } final StoreConfiguration configuration = this.getDescriptor().getGlobalConfiguration(); if (configuration.isDebugEnabled()) { this.logRuntimeInformation(log); this.logProviderInformation(log); this.logKeyLengthInformation(log); } for (final Publication publication : this.publications) { final Store store = configuration.getStore(publication.getStoreId()); this.publish(build, publication, store, log); log.write(); } return true; } private void logRuntimeInformation(final Log log) { log.write(this, "Java VM : %s, %s", System.getProperty("java.vm.name"), System.getProperty("java.version")); log.write(this, "Java home : %s", System.getProperty("java.home")); log.write(this, "Java vendor : %s (Specification: %s)", System.getProperty("java.vendor"), System.getProperty("java.specification.vendor")); log.write(); } private void logProviderInformation(final Log log) { log.write(this, "Available security providers:"); final Provider[] providers = Security.getProviders(); for (final Provider provider : providers) { log.write( this, "%s %s", provider.getName(), String.valueOf(provider.getVersion())); } log.write(); } private void logKeyLengthInformation(final Log log) { try { final int maxKeyLength = Cipher.getMaxAllowedKeyLength("AES"); final String value = (maxKeyLength < Integer.MAX_VALUE) ? String.valueOf(maxKeyLength) : "Unrestricted"; log.write(this, "Max. allowed key length: %s", value); } catch (final NoSuchAlgorithmException e) { log.write(this, "Max. allowed key length: <error>"); } this.testDHKeypairSize(log, 1024); this.testDHKeypairSize(log, 2048); this.testDHKeypairSize(log, 4096); log.write(); } private void testDHKeypairSize(final Log log, final int sizeBits) { try { final AlgorithmParameterGenerator apg = AlgorithmParameterGenerator.getInstance("DiffieHellman"); apg.init(sizeBits); log.write(this, "DH keypair with %,d bits is supported", sizeBits); } catch (final Exception e) { log.write(this, "DH keypair with %,d bits is UNSUPPORTED", sizeBits); } } private void publish(final AbstractBuild<?, ?> build, final Publication publication, final Store store, final Log log) throws IOException, InterruptedException { if (store == null) { log.write( this, "The store configured for '%s' no longer exists, please verify your configuration.", publication.getArtifactPath()); Builds.setResult(build, Result.UNSTABLE, log); return; } if (!this.shouldPublish(build, publication, store, log)) { log.write(this, "Not publishing to '%s' because result of build was %s.", store, build.getResult()); return; } final Result result = build.getResult(); final ArtifactFileUploader publisher = new ArtifactFileUploader(result, publication, store, log); log.write(this, "Publishing '%s' to '%s'", publication.getArtifactPath(), store.toString()); final FilePath workspace = build.getWorkspace(); if (workspace == null) { log.write(this, "Unable to publish, workspace of build is undefined."); return; } workspace.act(publisher); final Result newResult = publisher.getResult(); Builds.setResult(build, newResult, log); } private boolean shouldPublish(final AbstractBuild<?, ?> build, final Publication publication, final Store store, final Log log) { if (build.getResult() == Result.SUCCESS) { return true; } final String key = !publication.usesDefaultUploadMode() ? publication.getUploadMode() : store.getUploadMode(); if (build.getResult() == Result.UNSTABLE && StringUtils.equals(key, UploadMode.UNSTABLE.key)) { log.write(this, "Will upload build with result %s, as configured", build.getResult()); return true; } return false; } @Extension public static final class ArtifactPublisherDescriptor extends BuildStepDescriptor<Publisher> { @Inject private StoreConfiguration globalConfiguration; private List<Publication> publications; public ArtifactPublisherDescriptor() { this.load(); } public StoreConfiguration getGlobalConfiguration() { return this.globalConfiguration; } public List<Publication> getPublications() { return this.publications; } public void setPublications(final List<Publication> publications) { this.publications = publications; } @Override @SuppressWarnings("rawtypes") public boolean isApplicable(final Class<? extends AbstractProject> clazz) { return true; } @Override public String getDisplayName() { return "Deploy to Relution Enterprise Appstore"; } } }
relution-publisher/src/main/java/org/jenkinsci/plugins/relution_publisher/configuration/jobs/ArtifactPublisher.java
/* * Copyright (c) 2013-2014 M-Way Solutions GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jenkinsci.plugins.relution_publisher.configuration.jobs; import org.apache.commons.lang.StringUtils; import org.jenkinsci.plugins.relution_publisher.builder.ArtifactFileUploader; import org.jenkinsci.plugins.relution_publisher.configuration.global.Store; import org.jenkinsci.plugins.relution_publisher.configuration.global.StoreConfiguration; import org.jenkinsci.plugins.relution_publisher.constants.UploadMode; import org.jenkinsci.plugins.relution_publisher.entities.Version; import org.jenkinsci.plugins.relution_publisher.logging.Log; import org.jenkinsci.plugins.relution_publisher.util.Builds; import org.kohsuke.stapler.DataBoundConstructor; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.Security; import java.util.List; import javax.crypto.Cipher; import javax.inject.Inject; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.Result; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Publisher; import hudson.tasks.Recorder; /** * Publishes a {@link Version} to the Relution Enterprise Appstore using the * {@link ArtifactFileUploader} to perform the actual upload of the file. */ public class ArtifactPublisher extends Recorder { private final List<Publication> publications; @DataBoundConstructor public ArtifactPublisher(final List<Publication> publications) { this.getDescriptor().setPublications(publications); this.publications = publications; } public List<Publication> getPublications() { return this.publications; } @Override public ArtifactPublisherDescriptor getDescriptor() { return (ArtifactPublisherDescriptor) super.getDescriptor(); } @Override public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.NONE; } @Override public boolean perform(final AbstractBuild<?, ?> build, final Launcher launcher, final BuildListener listener) throws InterruptedException, IOException { final Log log = new Log(listener); log.write(); if (this.publications == null) { log.write(this, "Skipped, no publications configured"); Builds.setResult(build, Result.UNSTABLE, log); return true; } final StoreConfiguration configuration = this.getDescriptor().getGlobalConfiguration(); if (configuration.isDebugEnabled()) { this.logRuntimeInformation(log); this.logProviderInformation(log); this.logKeyLengthInformation(log); } for (final Publication publication : this.publications) { final Store store = configuration.getStore(publication.getStoreId()); this.publish(build, publication, store, log); log.write(); } return true; } private void logRuntimeInformation(final Log log) { log.write(this, "Java VM : %s, %s", System.getProperty("java.vm.name"), System.getProperty("java.version")); log.write(this, "Java home : %s", System.getProperty("java.home")); log.write(this, "Java vendor : %s (Specification: %s)", System.getProperty("java.vendor"), System.getProperty("java.specification.vendor")); log.write(); } private void logProviderInformation(final Log log) { log.write(this, "Available security providers:"); final Provider[] providers = Security.getProviders(); for (final Provider provider : providers) { log.write( this, "%s %s", provider.getName(), String.valueOf(provider.getVersion())); } log.write(); } private void logKeyLengthInformation(final Log log) { try { final int maxKeyLength = Cipher.getMaxAllowedKeyLength("AES"); final String value = (maxKeyLength < Integer.MAX_VALUE) ? String.valueOf(maxKeyLength) : "Unrestricted"; log.write(this, "Max. allowed key length: %s", value); } catch (final NoSuchAlgorithmException e) { log.write(this, "Max. allowed key length: <error>"); } log.write(); } private void publish(final AbstractBuild<?, ?> build, final Publication publication, final Store store, final Log log) throws IOException, InterruptedException { if (store == null) { log.write( this, "The store configured for '%s' no longer exists, please verify your configuration.", publication.getArtifactPath()); Builds.setResult(build, Result.UNSTABLE, log); return; } if (!this.shouldPublish(build, publication, store, log)) { log.write(this, "Not publishing to '%s' because result of build was %s.", store, build.getResult()); return; } final Result result = build.getResult(); final ArtifactFileUploader publisher = new ArtifactFileUploader(result, publication, store, log); log.write(this, "Publishing '%s' to '%s'", publication.getArtifactPath(), store.toString()); final FilePath workspace = build.getWorkspace(); if (workspace == null) { log.write(this, "Unable to publish, workspace of build is undefined."); return; } workspace.act(publisher); final Result newResult = publisher.getResult(); Builds.setResult(build, newResult, log); } private boolean shouldPublish(final AbstractBuild<?, ?> build, final Publication publication, final Store store, final Log log) { if (build.getResult() == Result.SUCCESS) { return true; } final String key = !publication.usesDefaultUploadMode() ? publication.getUploadMode() : store.getUploadMode(); if (build.getResult() == Result.UNSTABLE && StringUtils.equals(key, UploadMode.UNSTABLE.key)) { log.write(this, "Will upload build with result %s, as configured", build.getResult()); return true; } return false; } @Extension public static final class ArtifactPublisherDescriptor extends BuildStepDescriptor<Publisher> { @Inject private StoreConfiguration globalConfiguration; private List<Publication> publications; public ArtifactPublisherDescriptor() { this.load(); } public StoreConfiguration getGlobalConfiguration() { return this.globalConfiguration; } public List<Publication> getPublications() { return this.publications; } public void setPublications(final List<Publication> publications) { this.publications = publications; } @Override @SuppressWarnings("rawtypes") public boolean isApplicable(final Class<? extends AbstractProject> clazz) { return true; } @Override public String getDisplayName() { return "Deploy to Relution Enterprise Appstore"; } } }
Add the supported DH key pair size in bits to the debug log output. This adds log entries that show whether a key pair size of 1024, 2048 and 4096 bits for DiffieHellman is supported by the current platform and Java VM. For example, if a key pair size of 2048 bits is unsupported and the store's SSL certificate uses a key with 2048 bits the upload will fail. See issue #3.
relution-publisher/src/main/java/org/jenkinsci/plugins/relution_publisher/configuration/jobs/ArtifactPublisher.java
Add the supported DH key pair size in bits to the debug log output.
<ide><path>elution-publisher/src/main/java/org/jenkinsci/plugins/relution_publisher/configuration/jobs/ArtifactPublisher.java <ide> import org.kohsuke.stapler.DataBoundConstructor; <ide> <ide> import java.io.IOException; <add>import java.security.AlgorithmParameterGenerator; <ide> import java.security.NoSuchAlgorithmException; <ide> import java.security.Provider; <ide> import java.security.Security; <ide> <ide> } catch (final NoSuchAlgorithmException e) { <ide> log.write(this, "Max. allowed key length: <error>"); <del> } <del> log.write(); <add> <add> } <add> this.testDHKeypairSize(log, 1024); <add> this.testDHKeypairSize(log, 2048); <add> this.testDHKeypairSize(log, 4096); <add> log.write(); <add> } <add> <add> private void testDHKeypairSize(final Log log, final int sizeBits) { <add> try { <add> final AlgorithmParameterGenerator apg = AlgorithmParameterGenerator.getInstance("DiffieHellman"); <add> apg.init(sizeBits); <add> log.write(this, "DH keypair with %,d bits is supported", sizeBits); <add> } catch (final Exception e) { <add> log.write(this, "DH keypair with %,d bits is UNSUPPORTED", sizeBits); <add> } <ide> } <ide> <ide> private void publish(final AbstractBuild<?, ?> build, final Publication publication, final Store store, final Log log)
Java
mit
1af5a485c9dfdc1b3c951d66cddcec9cdc884037
0
CS2103AUG2016-W15-C3/main
package seedu.taskell.logic.parser; import static seedu.taskell.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.taskell.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import static seedu.taskell.commons.core.Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import seedu.taskell.commons.exceptions.IllegalValueException; import seedu.taskell.commons.util.StringUtil; import seedu.taskell.logic.commands.*; import seedu.taskell.logic.commands.edit.EditDescriptionCommand; import seedu.taskell.logic.commands.edit.EditEndDateCommand; import seedu.taskell.logic.commands.edit.EditEndTimeCommand; import seedu.taskell.logic.commands.edit.EditPriorityCommand; import seedu.taskell.logic.commands.edit.EditStartDateCommand; import seedu.taskell.logic.commands.edit.EditStartTimeCommand; import seedu.taskell.logic.commands.list.ListAllCommand; import seedu.taskell.logic.commands.list.ListCommand; import seedu.taskell.logic.commands.list.ListDateCommand; import seedu.taskell.logic.commands.list.ListDoneCommand; import seedu.taskell.logic.commands.list.ListPriorityCommand; import seedu.taskell.model.History; import seedu.taskell.model.HistoryManager; import seedu.taskell.model.tag.Tag; import seedu.taskell.model.task.Task; import seedu.taskell.model.task.TaskDate; import seedu.taskell.model.task.TaskPriority; import seedu.taskell.model.task.TaskTime; /** * Parses user input. */ public class Parser { /** * Used for initial separation of command word and args. */ private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)"); private static final Pattern TASK_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)"); private static final Pattern KEYWORDS_ARGS_FORMAT = Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one private static final Pattern TASK_DATA_ARGS_FORMAT = // '/' forward slashes // are reserved for // delimiter prefixes Pattern.compile("(?<description>[^/]+)" + " (?<isTaskTypePrivate>p?)p/(?<taskType>[^/]+)" + " (?<isTaskDatePrivate>p?)p/(?<startDate>[^/]+)" + " (?<isStartPrivate>p?)e/(?<startTime>[^/]+)" + " (?<isEndPrivate>p?)e/(?<endTime>[^/]+)" + " (?<isTaskPriorityPrivate>p?)a/(?<taskPriority>[^/]+)" + " (?<isTaskCompletePrivate>p?)a/(?<taskComplete>[^/]+)" + "(?<tagArguments>(?: t/[^/]+)*)"); // variable // number private static final String BY = "by"; private static final String ON = "on"; private static final String AT = "at"; private static final String FROM = "from"; private static final String TO = "to"; private static History history; public Parser() { history = HistoryManager.getInstance(); } /** * Parses user input into command for execution. * * @param userInput * full user input string * @return the command based on the user input */ public Command parseCommand(String userInput) { final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } final String commandWord = matcher.group("commandWord"); final String arguments = matcher.group("arguments"); if (commandWord.equals(AddCommand.COMMAND_WORD) || commandWord.equals(DeleteCommand.COMMAND_WORD) || commandWord.contains(UndoCommand.EDIT)) { IncorrectCommand.setIsUndoableCommand(true); history.addCommand(userInput, commandWord); } else { IncorrectCommand.setIsUndoableCommand(false); } switch (commandWord) { case AddCommand.COMMAND_WORD: return prepareAdd(arguments); case SelectCommand.COMMAND_WORD: return prepareSelect(arguments); case DeleteCommand.COMMAND_WORD: return prepareDelete(arguments); case EditStartDateCommand.COMMAND_WORD: return prepareEditStartDate(arguments); case EditEndDateCommand.COMMAND_WORD: return prepareEditEndDate(arguments); case EditDescriptionCommand.COMMAND_WORD_1: return prepareEditDescription(arguments); case EditDescriptionCommand.COMMAND_WORD_2: return prepareEditDescription(arguments); case EditStartTimeCommand.COMMAND_WORD: return prepareEditStartTime(arguments); case EditEndTimeCommand.COMMAND_WORD: return prepareEditEndTime(arguments); case EditPriorityCommand.COMMAND_WORD: return prepareEditPriority(arguments); case ClearCommand.COMMAND_WORD: return new ClearCommand(); case FindCommand.COMMAND_WORD: return prepareFind(arguments); case FindTagCommand.COMMAND_WORD: return prepareFindByTag(arguments); case ListCommand.COMMAND_WORD: return new ListCommand(); case ListAllCommand.COMMAND_WORD: return new ListAllCommand(); case ListDoneCommand.COMMAND_WORD: return new ListDoneCommand(); case ListDateCommand.COMMAND_WORD: return prepareListDate(arguments); case ListPriorityCommand.COMMAND_WORD: return prepareListPriority(arguments); case UndoCommand.COMMAND_WORD: return prepareUndo(arguments); case SaveStorageLocationCommand.COMMAND_WORD: return prepareSaveStorageLocation(arguments); case ExitCommand.COMMAND_WORD: return new ExitCommand(); case HelpCommand.COMMAND_WORD: return new HelpCommand(); case DoneCommand.COMMAND_WORD: return prepareDone(arguments); case ViewHistoryCommand.COMMAND_WORD_1: return new ViewHistoryCommand(); case ViewHistoryCommand.COMMAND_WORD_2: return new ViewHistoryCommand(); case ViewCalendarCommand.COMMAND_WORD_1: return new ViewCalendarCommand(); case ViewCalendarCommand.COMMAND_WORD_2: return new ViewCalendarCommand(); default: return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND); } } //@@author A0142073R private Command prepareListDate(String arguments) { if (arguments.isEmpty()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ListDateCommand.MESSAGE_USAGE)); } StringTokenizer st = new StringTokenizer(arguments.trim(), " "); String date = st.nextToken(); if (!TaskDate.isValidDate(date)) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ListDateCommand.MESSAGE_USAGE)); } return new ListDateCommand(date); } private Command prepareListPriority(String args) { if (args.isEmpty()) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, ListPriorityCommand.MESSAGE_USAGE)); } StringTokenizer st = new StringTokenizer(args.trim(), " "); String intValue = st.nextToken(); if (st.hasMoreTokens()) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, ListPriorityCommand.MESSAGE_USAGE)); } if (!isInt(intValue)) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditEndDateCommand.MESSAGE_USAGE)); } int targetIdx = Integer.valueOf(intValue); if (targetIdx < 0 || targetIdx > 3) { return new IncorrectCommand( String.format(MESSAGE_INVALID_TASK_DISPLAYED_INDEX, ListPriorityCommand.MESSAGE_USAGE)); } else return new ListPriorityCommand(intValue); } /** * Parses arguments in the context of the edit task startDate command. * * @param args * full command args string * @return the prepared command */ private Command prepareEditStartDate(String args) { String arguments = ""; if (args.isEmpty()) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditStartDateCommand.MESSAGE_USAGE)); } StringTokenizer st = new StringTokenizer(args.trim(), " "); String intValue = st.nextToken(); if (!isInt(intValue)) { return new IncorrectCommand( String.format(MESSAGE_INVALID_TASK_DISPLAYED_INDEX, EditEndDateCommand.MESSAGE_USAGE)); } int targetIdx = Integer.valueOf(intValue); arguments = st.nextToken(); if (st.hasMoreTokens()) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditStartDateCommand.MESSAGE_USAGE)); } if (!TaskDate.isValidDate(arguments)) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditStartDateCommand.MESSAGE_USAGE)); } try { return new EditStartDateCommand(targetIdx, arguments); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } /** * Parses arguments in the context of the edit task description command. * * @param args * full command args string * @return the prepared command */ private Command prepareEditDescription(String args) { String arguments = ""; if (args.isEmpty()) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditDescriptionCommand.MESSAGE_USAGE)); } StringTokenizer st = new StringTokenizer(args.trim(), " "); String intValue = st.nextToken(); if (!isInt(intValue)) { return new IncorrectCommand( String.format(MESSAGE_INVALID_TASK_DISPLAYED_INDEX, EditDescriptionCommand.MESSAGE_USAGE)); } int targetIdx = Integer.valueOf(intValue); while (st.hasMoreTokens()) { arguments += st.nextToken() + " "; } arguments = arguments.trim(); try { return new EditDescriptionCommand(targetIdx, arguments); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } /** * Parses arguments in the context of the edit start time command. * * @param args * full command args string * @return the prepared command */ private Command prepareEditStartTime(String args) { String arguments = ""; if (args.isEmpty()) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditStartTimeCommand.MESSAGE_USAGE)); } StringTokenizer st = new StringTokenizer(args.trim(), " "); String intValue = st.nextToken(); if (!isInt(intValue)) { return new IncorrectCommand( String.format(MESSAGE_INVALID_TASK_DISPLAYED_INDEX, EditStartTimeCommand.MESSAGE_USAGE)); } int targetIdx = Integer.valueOf(intValue); arguments = st.nextToken(); if (st.hasMoreTokens()) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditStartTimeCommand.MESSAGE_USAGE)); } if (!TaskTime.isValidTime(arguments)) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditStartTimeCommand.MESSAGE_USAGE)); } try { return new EditStartTimeCommand(targetIdx, arguments); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } /** * Parses arguments in the context of the edit task endDate command. * * @param args * full command args string * @return the prepared command */ private Command prepareEditEndDate(String args) { String arguments = ""; if (args.isEmpty()) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditEndDateCommand.MESSAGE_USAGE)); } StringTokenizer st = new StringTokenizer(args.trim(), " "); String intValue = st.nextToken(); if (!isInt(intValue)) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditEndDateCommand.MESSAGE_USAGE)); } int targetIdx = Integer.valueOf(intValue); arguments = st.nextToken(); if (st.hasMoreTokens() || !TaskDate.isValidDate(arguments)) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditEndDateCommand.MESSAGE_USAGE)); } try { return new EditEndDateCommand(targetIdx, arguments); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } /** * Parses arguments in the context of the edit task end time command. * * @param args * full command args string * @return the prepared command */ private Command prepareEditEndTime(String args) { String arguments = ""; if (args.isEmpty()) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditEndTimeCommand.MESSAGE_USAGE)); } StringTokenizer st = new StringTokenizer(args.trim(), " "); String intValue = st.nextToken(); if (!isInt(intValue)) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditEndTimeCommand.MESSAGE_USAGE)); } int targetIdx = Integer.valueOf(intValue); arguments = st.nextToken(); if (st.hasMoreTokens() || !TaskTime.isValidTime(arguments)) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditEndTimeCommand.MESSAGE_USAGE)); } try { return new EditEndTimeCommand(targetIdx, arguments); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } /** * Parses arguments in the context of the edit task priority command. * * @param args * full command args string * @return the prepared command */ private Command prepareEditPriority(String args) { String arguments = ""; if (args.isEmpty()) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditPriorityCommand.MESSAGE_USAGE)); } StringTokenizer st = new StringTokenizer(args.trim(), " "); int targetIdx = Integer.valueOf(st.nextToken()); arguments = st.nextToken(); if (st.hasMoreTokens() || !TaskPriority.isValidPriority(arguments)) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditPriorityCommand.MESSAGE_USAGE)); } try { return new EditPriorityCommand(targetIdx, arguments); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } //@@author //@@author A0139257X /** * Parses arguments in the context of the add task command. * * @param args * full command args string * @return the prepared command */ private Command prepareAdd(String args) { if (args.isEmpty()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE)); } ArrayList<String> argsList = tokenizeArguments(args); Queue<String> initialQueue = initialiseArgQueue(argsList); Queue<String> descriptionQueue = new LinkedList<String>(); Queue<String> byQueue = new LinkedList<String>(); Queue<String> onQueue = new LinkedList<String>(); Queue<String> atQueue = new LinkedList<String>(); Queue<String> fromQueue = new LinkedList<String>(); Queue<String> toQueue = new LinkedList<String>(); String description = ""; String startDate = TaskDate.DEFAULT_DATE; String endDate = startDate; String startTime = TaskTime.DEFAULT_START_TIME; String endTime = TaskTime.DEFAULT_END_TIME; String token = ""; String taskPriority = TaskPriority.DEFAULT_PRIORITY; String tagString = ""; int priorityCount = 0; boolean hasStartDate = false; boolean hasEndDate = false; boolean hasStartTime = false; boolean hasEndTime = false; while (!initialQueue.isEmpty()) { token = initialQueue.poll().trim(); String tempToken = ""; if (!token.equals(BY) && !token.equals(ON) && !token.equals(AT) && !token.equals(FROM) && !token.equals(TO) && !TaskDate.isValidDate(token) && !TaskTime.isValidTime(token) && !token.startsWith(Tag.PREFIX) && !token.startsWith(TaskPriority.PREFIX)) { tempToken = flushQueue(byQueue, onQueue, atQueue, fromQueue, toQueue); if (!tempToken.isEmpty()) { descriptionQueue.offer(tempToken); } descriptionQueue.offer(token); continue; } else if (token.equals(BY)) { tempToken = flushQueue(byQueue, onQueue, atQueue, fromQueue, toQueue); if (!tempToken.isEmpty()) { descriptionQueue.offer(tempToken); } byQueue.offer(token); continue; } else if (token.equals(ON)) { tempToken = flushQueue(byQueue, onQueue, atQueue, fromQueue, toQueue); if (!tempToken.isEmpty()) { descriptionQueue.offer(tempToken); } onQueue.offer(token); continue; } else if (token.equals(AT)) { tempToken = flushQueue(byQueue, onQueue, atQueue, fromQueue, toQueue); if (!tempToken.isEmpty()) { descriptionQueue.offer(tempToken); } atQueue.offer(token); continue; } else if (token.equals(FROM)) { tempToken = flushQueue(byQueue, onQueue, atQueue, fromQueue, toQueue); if (!tempToken.isEmpty()) { descriptionQueue.offer(tempToken); } fromQueue.offer(token); continue; } else if (token.equals(TO)) { tempToken = flushQueue(byQueue, onQueue, atQueue, fromQueue, toQueue); if (!tempToken.isEmpty()) { descriptionQueue.offer(tempToken); } toQueue.offer(token); continue; } else if (token.startsWith(Tag.PREFIX)) { tempToken = flushQueue(byQueue, onQueue, atQueue, fromQueue, toQueue); if (!tempToken.isEmpty()) { descriptionQueue.offer(tempToken); } tagString += " " + token; continue; } else if (token.startsWith(TaskPriority.PREFIX)) { tempToken = flushQueue(byQueue, onQueue, atQueue, fromQueue, toQueue); if (!tempToken.isEmpty()) { descriptionQueue.offer(tempToken); } if (priorityCount > 0) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE)); } else { taskPriority = token.substring(token.indexOf(TaskPriority.PREFIX) + 2); priorityCount++; } continue; } else if (TaskDate.isValidDate(token)) { if (byQueue.isEmpty() && onQueue.isEmpty() && atQueue.isEmpty() && fromQueue.isEmpty() && toQueue.isEmpty()) { descriptionQueue.offer(token); } else if (!onQueue.isEmpty()) { if (!hasStartDate) { onQueue.poll(); startDate = token; hasStartDate = true; } else { descriptionQueue.offer(onQueue.poll()); descriptionQueue.offer(token); } } else if (!byQueue.isEmpty()) { if (!hasEndDate) { byQueue.poll(); endDate = token; hasEndDate = true; } else { descriptionQueue.offer(byQueue.poll()); descriptionQueue.offer(token); } } else if (!atQueue.isEmpty()) { descriptionQueue.offer(atQueue.poll()); descriptionQueue.offer(token); } else if (!fromQueue.isEmpty()) { if (!hasStartDate) { fromQueue.poll(); startDate = token; hasStartDate = true; } else { descriptionQueue.offer(fromQueue.poll()); descriptionQueue.offer(token); } } else if (!toQueue.isEmpty()) { if (!hasEndDate) { toQueue.poll(); endDate = token; hasEndDate = true; } else { descriptionQueue.offer(toQueue.poll()); descriptionQueue.offer(token); } } } else if (TaskTime.isValidTime(token)) { if (byQueue.isEmpty() && onQueue.isEmpty() && atQueue.isEmpty() && fromQueue.isEmpty() && toQueue.isEmpty()) { descriptionQueue.offer(token); } else if (!byQueue.isEmpty()) { if (!hasEndTime) { byQueue.poll(); endTime = token; hasEndTime = true; } else { descriptionQueue.offer(byQueue.poll()); descriptionQueue.offer(token); } } else if (!atQueue.isEmpty()) { if (!hasStartTime) { atQueue.poll(); startTime = token; hasStartTime = true; } else { descriptionQueue.offer(atQueue.poll()); descriptionQueue.offer(token); } } else if (!fromQueue.isEmpty()) { if (!hasStartTime) { fromQueue.poll(); startTime = token; hasStartTime = true; } else { descriptionQueue.offer(fromQueue.poll()); descriptionQueue.offer(token); } } else if (!toQueue.isEmpty()) { if (!hasEndTime) { toQueue.poll(); endTime = token; hasEndTime = true; } else { descriptionQueue.offer(toQueue.poll()); descriptionQueue.offer(token); } } else if (!onQueue.isEmpty()) { descriptionQueue.offer(onQueue.poll()); descriptionQueue.offer(token); } } } String tempToken = flushQueue(byQueue, onQueue, atQueue, fromQueue, toQueue); if (!tempToken.isEmpty()) { descriptionQueue.offer(tempToken); } while (!descriptionQueue.isEmpty()) { description += descriptionQueue.poll() + " "; } description.trim(); if (!hasEndDate) { endDate = startDate; } if ((TaskDate.isValidToday(startDate) && !hasStartTime) || startDate.equals(TaskDate.DEFAULT_DATE) && !hasStartTime) { startTime = TaskTime.getTimeNow().toString(); } if (hasStartDate || hasEndDate || hasStartTime || hasEndTime) { try { return new AddCommand(description, Task.EVENT_TASK, startDate, endDate, startTime, endTime, taskPriority, getTagsFromArgs(tagString)); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } else { try { return new AddCommand(description, Task.FLOATING_TASK, startDate, endDate, startTime, endTime, taskPriority, getTagsFromArgs(tagString)); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } } private String flushQueue(Queue<String> byQueue, Queue<String> onQueue, Queue<String> atQueue, Queue<String> fromQueue, Queue<String> toQueue) { String token = ""; if (!byQueue.isEmpty()) { token = byQueue.poll(); } else if (!onQueue.isEmpty()) { token = onQueue.poll(); } else if (!atQueue.isEmpty()) { token = atQueue.poll(); } else if (!fromQueue.isEmpty()) { token = fromQueue.poll(); } else if (!toQueue.isEmpty()) { token = toQueue.poll(); } return token; } private Queue<String> initialiseArgQueue(ArrayList<String> argsList) { Queue<String> argsQueue = new LinkedList<String>(); for (String arg : argsList) { argsQueue.offer(arg); } return argsQueue; } private ArrayList<String> tokenizeArguments(String args) { ArrayList<String> argsList = new ArrayList<String>(); StringTokenizer st = new StringTokenizer(args, " "); while (st.hasMoreTokens()) { argsList.add(st.nextToken()); } return argsList; } //@@author /** * Extracts the new task's tags from the add command's tag arguments string. * Merges duplicate tag strings. */ private static Set<String> getTagsFromArgs(String tagArguments) throws IllegalValueException { // no tags if (tagArguments.isEmpty()) { return Collections.emptySet(); } // replace first delimiter prefix, then split final Collection<String> tagStrings = Arrays .asList(tagArguments.replaceFirst(" " + Tag.PREFIX, "").split(" " + Tag.PREFIX)); return new HashSet<>(tagStrings); } /** * Parses arguments in the context of the delete task command. * * @param args * full command args string * @return the prepared command */ private Command prepareDelete(String args) { Optional<Integer> index = parseIndex(args); if (!index.isPresent()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE)); } return new DeleteCommand(index.get()); } /** * Parses arguments in the context of the select task command. * * @param args * full command args string * @return the prepared command */ private Command prepareSelect(String args) { Optional<Integer> index = parseIndex(args); if (!index.isPresent()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE)); } return new SelectCommand(index.get()); } /** * Returns the specified index in the {@code command} IF a positive unsigned * integer is given as the index. Returns an {@code Optional.empty()} * otherwise. */ private Optional<Integer> parseIndex(String command) { final Matcher matcher = TASK_INDEX_ARGS_FORMAT.matcher(command.trim()); if (!matcher.matches()) { return Optional.empty(); } String index = matcher.group("targetIndex"); if (!StringUtil.isUnsignedInteger(index)) { return Optional.empty(); } return Optional.of(Integer.parseInt(index)); } /** * Parses arguments in the context of the find task command. * * @param args * string * @return the prepared command */ private Command prepareFind(String args) { final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); } // keywords delimited by whitespace final String[] keywords = matcher.group("keywords").split("\\s+"); final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords)); return new FindCommand(keywordSet); } /** @@author A0142130A **/ /** * Parses arguments in the context of undo command. * */ private Command prepareUndo(String args) { Optional<Integer> index = parseIndex(args); if (!index.isPresent()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, UndoCommand.MESSAGE_USAGE)); } return new UndoCommand(index.get()); } /** * Parses arguments in the context of the find task by tags command. * * @param args * full command args string * @return the prepared command */ private Command prepareFindByTag(String args) { final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindTagCommand.MESSAGE_USAGE)); } // keywords delimited by whitespace final String[] keywords = matcher.group("keywords").split("\\s+"); final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords)); return new FindTagCommand(keywordSet); } /** * Parses arguments in the context of the save storage location command. * * @param args * full command args string * @return the prepared command */ private Command prepareSaveStorageLocation(String args) { if (args.isEmpty()) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, SaveStorageLocationCommand.MESSAGE_USAGE)); } return new SaveStorageLocationCommand(args); } /** @@author **/ //@@author A0148004R /** * Parses arguments in the context of the done task command. * * @param args * full command args string * @return the prepared command */ private Command prepareDone(String args) { Optional<Integer> index = parseIndex(args); if (!index.isPresent()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, DoneCommand.MESSAGE_USAGE)); } return new DoneCommand(index.get()); } //@@author //@@author A0142073R private static boolean isInt(String s) { try { int i = Integer.parseInt(s); return true; } catch (NumberFormatException er) { return false; } } //@@author }
src/main/java/seedu/taskell/logic/parser/Parser.java
package seedu.taskell.logic.parser; import static seedu.taskell.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.taskell.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import static seedu.taskell.commons.core.Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import seedu.taskell.commons.exceptions.IllegalValueException; import seedu.taskell.commons.util.StringUtil; import seedu.taskell.logic.commands.*; import seedu.taskell.logic.commands.edit.EditDescriptionCommand; import seedu.taskell.logic.commands.edit.EditEndDateCommand; import seedu.taskell.logic.commands.edit.EditEndTimeCommand; import seedu.taskell.logic.commands.edit.EditPriorityCommand; import seedu.taskell.logic.commands.edit.EditStartDateCommand; import seedu.taskell.logic.commands.edit.EditStartTimeCommand; import seedu.taskell.logic.commands.list.ListAllCommand; import seedu.taskell.logic.commands.list.ListCommand; import seedu.taskell.logic.commands.list.ListDateCommand; import seedu.taskell.logic.commands.list.ListDoneCommand; import seedu.taskell.logic.commands.list.ListPriorityCommand; import seedu.taskell.model.tag.Tag; import seedu.taskell.model.task.Task; import seedu.taskell.model.task.TaskDate; import seedu.taskell.model.task.TaskPriority; import seedu.taskell.model.task.TaskTime; /** * Parses user input. */ public class Parser { /** * Used for initial separation of command word and args. */ private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)"); private static final Pattern TASK_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)"); private static final Pattern KEYWORDS_ARGS_FORMAT = Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one private static final Pattern TASK_DATA_ARGS_FORMAT = // '/' forward slashes // are reserved for // delimiter prefixes Pattern.compile("(?<description>[^/]+)" + " (?<isTaskTypePrivate>p?)p/(?<taskType>[^/]+)" + " (?<isTaskDatePrivate>p?)p/(?<startDate>[^/]+)" + " (?<isStartPrivate>p?)e/(?<startTime>[^/]+)" + " (?<isEndPrivate>p?)e/(?<endTime>[^/]+)" + " (?<isTaskPriorityPrivate>p?)a/(?<taskPriority>[^/]+)" + " (?<isTaskCompletePrivate>p?)a/(?<taskComplete>[^/]+)" + "(?<tagArguments>(?: t/[^/]+)*)"); // variable // number private static final String BY = "by"; private static final String ON = "on"; private static final String AT = "at"; private static final String FROM = "from"; private static final String TO = "to"; public Parser() { } /** * Parses user input into command for execution. * * @param userInput * full user input string * @return the command based on the user input */ public Command parseCommand(String userInput) { final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } final String commandWord = matcher.group("commandWord"); final String arguments = matcher.group("arguments"); switch (commandWord) { case AddCommand.COMMAND_WORD: UndoCommand.addCommandToHistory(userInput, commandWord); return prepareAdd(arguments); case SelectCommand.COMMAND_WORD: return prepareSelect(arguments); case DeleteCommand.COMMAND_WORD: UndoCommand.addCommandToHistory(userInput, commandWord); return prepareDelete(arguments); case EditStartDateCommand.COMMAND_WORD: UndoCommand.addCommandToHistory(userInput, commandWord); return prepareEditStartDate(arguments); case EditEndDateCommand.COMMAND_WORD: UndoCommand.addCommandToHistory(userInput, commandWord); return prepareEditEndDate(arguments); case EditDescriptionCommand.COMMAND_WORD_1: UndoCommand.addCommandToHistory(userInput, commandWord); return prepareEditDescription(arguments); case EditDescriptionCommand.COMMAND_WORD_2: UndoCommand.addCommandToHistory(userInput, commandWord); return prepareEditDescription(arguments); case EditStartTimeCommand.COMMAND_WORD: UndoCommand.addCommandToHistory(userInput, commandWord); return prepareEditStartTime(arguments); case EditEndTimeCommand.COMMAND_WORD: UndoCommand.addCommandToHistory(userInput, commandWord); return prepareEditEndTime(arguments); case EditPriorityCommand.COMMAND_WORD: UndoCommand.addCommandToHistory(userInput, commandWord); return prepareEditPriority(arguments); case ClearCommand.COMMAND_WORD: return new ClearCommand(); case FindCommand.COMMAND_WORD: return prepareFind(arguments); case FindTagCommand.COMMAND_WORD: return prepareFindByTag(arguments); case ListCommand.COMMAND_WORD: return new ListCommand(); case ListAllCommand.COMMAND_WORD: return new ListAllCommand(); case ListDoneCommand.COMMAND_WORD: return new ListDoneCommand(); case ListDateCommand.COMMAND_WORD: return prepareListDate(arguments); case ListPriorityCommand.COMMAND_WORD: return prepareListPriority(arguments); case UndoCommand.COMMAND_WORD: return prepareUndo(arguments); case SaveStorageLocationCommand.COMMAND_WORD: return prepareSaveStorageLocation(arguments); case ExitCommand.COMMAND_WORD: return new ExitCommand(); case HelpCommand.COMMAND_WORD: return new HelpCommand(); case DoneCommand.COMMAND_WORD: return prepareDone(arguments); case ViewHistoryCommand.COMMAND_WORD_1: return new ViewHistoryCommand(); case ViewHistoryCommand.COMMAND_WORD_2: return new ViewHistoryCommand(); case ViewCalendarCommand.COMMAND_WORD_1: return new ViewCalendarCommand(); case ViewCalendarCommand.COMMAND_WORD_2: return new ViewCalendarCommand(); default: return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND); } } //@@author A0142073R private Command prepareListDate(String arguments) { if (arguments.isEmpty()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ListDateCommand.MESSAGE_USAGE)); } StringTokenizer st = new StringTokenizer(arguments.trim(), " "); String date = st.nextToken(); if (!TaskDate.isValidDate(date)) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ListDateCommand.MESSAGE_USAGE)); } return new ListDateCommand(date); } private Command prepareListPriority(String args) { if (args.isEmpty()) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, ListPriorityCommand.MESSAGE_USAGE)); } StringTokenizer st = new StringTokenizer(args.trim(), " "); String intValue = st.nextToken(); if (st.hasMoreTokens()) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, ListPriorityCommand.MESSAGE_USAGE)); } if (!isInt(intValue)) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditEndDateCommand.MESSAGE_USAGE)); } int targetIdx = Integer.valueOf(intValue); if (targetIdx < 0 || targetIdx > 3) { return new IncorrectCommand( String.format(MESSAGE_INVALID_TASK_DISPLAYED_INDEX, ListPriorityCommand.MESSAGE_USAGE)); } else return new ListPriorityCommand(intValue); } /** * Parses arguments in the context of the edit task startDate command. * * @param args * full command args string * @return the prepared command */ private Command prepareEditStartDate(String args) { String arguments = ""; if (args.isEmpty()) { UndoCommand.deletePreviousCommand(); return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditStartDateCommand.MESSAGE_USAGE)); } StringTokenizer st = new StringTokenizer(args.trim(), " "); String intValue = st.nextToken(); if (!isInt(intValue)) { UndoCommand.deletePreviousCommand(); return new IncorrectCommand( String.format(MESSAGE_INVALID_TASK_DISPLAYED_INDEX, EditEndDateCommand.MESSAGE_USAGE)); } int targetIdx = Integer.valueOf(intValue); arguments = st.nextToken(); if (st.hasMoreTokens()) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditStartDateCommand.MESSAGE_USAGE)); } if (!TaskDate.isValidDate(arguments)) { UndoCommand.deletePreviousCommand(); return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditStartDateCommand.MESSAGE_USAGE)); } try { return new EditStartDateCommand(targetIdx, arguments); } catch (IllegalValueException ive) { UndoCommand.deletePreviousCommand(); return new IncorrectCommand(ive.getMessage()); } } /** * Parses arguments in the context of the edit task description command. * * @param args * full command args string * @return the prepared command */ private Command prepareEditDescription(String args) { String arguments = ""; if (args.isEmpty()) { UndoCommand.deletePreviousCommand(); return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditDescriptionCommand.MESSAGE_USAGE)); } StringTokenizer st = new StringTokenizer(args.trim(), " "); String intValue = st.nextToken(); if (!isInt(intValue)) { UndoCommand.deletePreviousCommand(); return new IncorrectCommand( String.format(MESSAGE_INVALID_TASK_DISPLAYED_INDEX, EditDescriptionCommand.MESSAGE_USAGE)); } int targetIdx = Integer.valueOf(intValue); while (st.hasMoreTokens()) { arguments += st.nextToken() + " "; } arguments = arguments.trim(); try { return new EditDescriptionCommand(targetIdx, arguments); } catch (IllegalValueException ive) { UndoCommand.deletePreviousCommand(); return new IncorrectCommand(ive.getMessage()); } } /** * Parses arguments in the context of the edit start time command. * * @param args * full command args string * @return the prepared command */ private Command prepareEditStartTime(String args) { String arguments = ""; if (args.isEmpty()) { UndoCommand.deletePreviousCommand(); return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditStartTimeCommand.MESSAGE_USAGE)); } StringTokenizer st = new StringTokenizer(args.trim(), " "); String intValue = st.nextToken(); if (!isInt(intValue)) { UndoCommand.deletePreviousCommand(); return new IncorrectCommand( String.format(MESSAGE_INVALID_TASK_DISPLAYED_INDEX, EditStartTimeCommand.MESSAGE_USAGE)); } int targetIdx = Integer.valueOf(intValue); arguments = st.nextToken(); if (st.hasMoreTokens()) { UndoCommand.deletePreviousCommand(); return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditStartTimeCommand.MESSAGE_USAGE)); } if (!TaskTime.isValidTime(arguments)) { UndoCommand.deletePreviousCommand(); return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditStartTimeCommand.MESSAGE_USAGE)); } try { return new EditStartTimeCommand(targetIdx, arguments); } catch (IllegalValueException ive) { UndoCommand.deletePreviousCommand(); return new IncorrectCommand(ive.getMessage()); } } /** * Parses arguments in the context of the edit task endDate command. * * @param args * full command args string * @return the prepared command */ private Command prepareEditEndDate(String args) { String arguments = ""; if (args.isEmpty()) { UndoCommand.deletePreviousCommand(); return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditEndDateCommand.MESSAGE_USAGE)); } StringTokenizer st = new StringTokenizer(args.trim(), " "); String intValue = st.nextToken(); if (!isInt(intValue)) { UndoCommand.deletePreviousCommand(); return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditEndDateCommand.MESSAGE_USAGE)); } int targetIdx = Integer.valueOf(intValue); arguments = st.nextToken(); if (st.hasMoreTokens() || !TaskDate.isValidDate(arguments)) { UndoCommand.deletePreviousCommand(); return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditEndDateCommand.MESSAGE_USAGE)); } try { return new EditEndDateCommand(targetIdx, arguments); } catch (IllegalValueException ive) { UndoCommand.deletePreviousCommand(); return new IncorrectCommand(ive.getMessage()); } } /** * Parses arguments in the context of the edit task end time command. * * @param args * full command args string * @return the prepared command */ private Command prepareEditEndTime(String args) { String arguments = ""; if (args.isEmpty()) { UndoCommand.deletePreviousCommand(); return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditEndTimeCommand.MESSAGE_USAGE)); } StringTokenizer st = new StringTokenizer(args.trim(), " "); String intValue = st.nextToken(); if (!isInt(intValue)) { UndoCommand.deletePreviousCommand(); return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditEndTimeCommand.MESSAGE_USAGE)); } int targetIdx = Integer.valueOf(intValue); arguments = st.nextToken(); if (st.hasMoreTokens() || !TaskTime.isValidTime(arguments)) { UndoCommand.deletePreviousCommand(); return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditEndTimeCommand.MESSAGE_USAGE)); } try { return new EditEndTimeCommand(targetIdx, arguments); } catch (IllegalValueException ive) { UndoCommand.deletePreviousCommand(); return new IncorrectCommand(ive.getMessage()); } } /** * Parses arguments in the context of the edit task priority command. * * @param args * full command args string * @return the prepared command */ private Command prepareEditPriority(String args) { String arguments = ""; if (args.isEmpty()) { UndoCommand.deletePreviousCommand(); return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditPriorityCommand.MESSAGE_USAGE)); } StringTokenizer st = new StringTokenizer(args.trim(), " "); int targetIdx = Integer.valueOf(st.nextToken()); arguments = st.nextToken(); if (st.hasMoreTokens() || !TaskPriority.isValidPriority(arguments)) { UndoCommand.deletePreviousCommand(); return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditPriorityCommand.MESSAGE_USAGE)); } try { return new EditPriorityCommand(targetIdx, arguments); } catch (IllegalValueException ive) { UndoCommand.deletePreviousCommand(); return new IncorrectCommand(ive.getMessage()); } } //@@author //@@author A0139257X /** * Parses arguments in the context of the add task command. * * @param args * full command args string * @return the prepared command */ private Command prepareAdd(String args) { if (args.isEmpty()) { UndoCommand.deletePreviousCommand(); return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE)); } ArrayList<String> argsList = tokenizeArguments(args); Queue<String> initialQueue = initialiseArgQueue(argsList); Queue<String> descriptionQueue = new LinkedList<String>(); Queue<String> byQueue = new LinkedList<String>(); Queue<String> onQueue = new LinkedList<String>(); Queue<String> atQueue = new LinkedList<String>(); Queue<String> fromQueue = new LinkedList<String>(); Queue<String> toQueue = new LinkedList<String>(); String description = ""; String startDate = TaskDate.DEFAULT_DATE; String endDate = startDate; String startTime = TaskTime.DEFAULT_START_TIME; String endTime = TaskTime.DEFAULT_END_TIME; String token = ""; String taskPriority = TaskPriority.DEFAULT_PRIORITY; String tagString = ""; int priorityCount = 0; boolean hasStartDate = false; boolean hasEndDate = false; boolean hasStartTime = false; boolean hasEndTime = false; while (!initialQueue.isEmpty()) { token = initialQueue.poll().trim(); String tempToken = ""; if (!token.equals(BY) && !token.equals(ON) && !token.equals(AT) && !token.equals(FROM) && !token.equals(TO) && !TaskDate.isValidDate(token) && !TaskTime.isValidTime(token) && !token.startsWith(Tag.PREFIX) && !token.startsWith(TaskPriority.PREFIX)) { tempToken = flushQueue(byQueue, onQueue, atQueue, fromQueue, toQueue); if (!tempToken.isEmpty()) { descriptionQueue.offer(tempToken); } descriptionQueue.offer(token); continue; } else if (token.equals(BY)) { tempToken = flushQueue(byQueue, onQueue, atQueue, fromQueue, toQueue); if (!tempToken.isEmpty()) { descriptionQueue.offer(tempToken); } byQueue.offer(token); continue; } else if (token.equals(ON)) { tempToken = flushQueue(byQueue, onQueue, atQueue, fromQueue, toQueue); if (!tempToken.isEmpty()) { descriptionQueue.offer(tempToken); } onQueue.offer(token); continue; } else if (token.equals(AT)) { tempToken = flushQueue(byQueue, onQueue, atQueue, fromQueue, toQueue); if (!tempToken.isEmpty()) { descriptionQueue.offer(tempToken); } atQueue.offer(token); continue; } else if (token.equals(FROM)) { tempToken = flushQueue(byQueue, onQueue, atQueue, fromQueue, toQueue); if (!tempToken.isEmpty()) { descriptionQueue.offer(tempToken); } fromQueue.offer(token); continue; } else if (token.equals(TO)) { tempToken = flushQueue(byQueue, onQueue, atQueue, fromQueue, toQueue); if (!tempToken.isEmpty()) { descriptionQueue.offer(tempToken); } toQueue.offer(token); continue; } else if (token.startsWith(Tag.PREFIX)) { tempToken = flushQueue(byQueue, onQueue, atQueue, fromQueue, toQueue); if (!tempToken.isEmpty()) { descriptionQueue.offer(tempToken); } tagString += " " + token; continue; } else if (token.startsWith(TaskPriority.PREFIX)) { tempToken = flushQueue(byQueue, onQueue, atQueue, fromQueue, toQueue); if (!tempToken.isEmpty()) { descriptionQueue.offer(tempToken); } if (priorityCount > 0) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE)); } else { taskPriority = token.substring(token.indexOf(TaskPriority.PREFIX) + 2); priorityCount++; } continue; } else if (TaskDate.isValidDate(token)) { if (byQueue.isEmpty() && onQueue.isEmpty() && atQueue.isEmpty() && fromQueue.isEmpty() && toQueue.isEmpty()) { descriptionQueue.offer(token); } else if (!onQueue.isEmpty()) { if (!hasStartDate) { onQueue.poll(); startDate = token; hasStartDate = true; } else { descriptionQueue.offer(onQueue.poll()); descriptionQueue.offer(token); } } else if (!byQueue.isEmpty()) { if (!hasEndDate) { byQueue.poll(); endDate = token; hasEndDate = true; } else { descriptionQueue.offer(byQueue.poll()); descriptionQueue.offer(token); } } else if (!atQueue.isEmpty()) { descriptionQueue.offer(atQueue.poll()); descriptionQueue.offer(token); } else if (!fromQueue.isEmpty()) { if (!hasStartDate) { fromQueue.poll(); startDate = token; hasStartDate = true; } else { descriptionQueue.offer(fromQueue.poll()); descriptionQueue.offer(token); } } else if (!toQueue.isEmpty()) { if (!hasEndDate) { toQueue.poll(); endDate = token; hasEndDate = true; } else { descriptionQueue.offer(toQueue.poll()); descriptionQueue.offer(token); } } } else if (TaskTime.isValidTime(token)) { if (byQueue.isEmpty() && onQueue.isEmpty() && atQueue.isEmpty() && fromQueue.isEmpty() && toQueue.isEmpty()) { descriptionQueue.offer(token); } else if (!byQueue.isEmpty()) { if (!hasEndTime) { byQueue.poll(); endTime = token; hasEndTime = true; } else { descriptionQueue.offer(byQueue.poll()); descriptionQueue.offer(token); } } else if (!atQueue.isEmpty()) { if (!hasStartTime) { atQueue.poll(); startTime = token; hasStartTime = true; } else { descriptionQueue.offer(atQueue.poll()); descriptionQueue.offer(token); } } else if (!fromQueue.isEmpty()) { if (!hasStartTime) { fromQueue.poll(); startTime = token; hasStartTime = true; } else { descriptionQueue.offer(fromQueue.poll()); descriptionQueue.offer(token); } } else if (!toQueue.isEmpty()) { if (!hasEndTime) { toQueue.poll(); endTime = token; hasEndTime = true; } else { descriptionQueue.offer(toQueue.poll()); descriptionQueue.offer(token); } } else if (!onQueue.isEmpty()) { descriptionQueue.offer(onQueue.poll()); descriptionQueue.offer(token); } } } String tempToken = flushQueue(byQueue, onQueue, atQueue, fromQueue, toQueue); if (!tempToken.isEmpty()) { descriptionQueue.offer(tempToken); } while (!descriptionQueue.isEmpty()) { description += descriptionQueue.poll() + " "; } description.trim(); if (!hasEndDate) { endDate = startDate; } if ((TaskDate.isValidToday(startDate) && !hasStartTime) || startDate.equals(TaskDate.DEFAULT_DATE) && !hasStartTime) { startTime = TaskTime.getTimeNow().toString(); } if (hasStartDate || hasEndDate || hasStartTime || hasEndTime) { try { return new AddCommand(description, Task.EVENT_TASK, startDate, endDate, startTime, endTime, taskPriority, getTagsFromArgs(tagString)); } catch (IllegalValueException ive) { UndoCommand.deletePreviousCommand(); return new IncorrectCommand(ive.getMessage()); } } else { try { return new AddCommand(description, Task.FLOATING_TASK, startDate, endDate, startTime, endTime, taskPriority, getTagsFromArgs(tagString)); } catch (IllegalValueException ive) { UndoCommand.deletePreviousCommand(); return new IncorrectCommand(ive.getMessage()); } } } private String flushQueue(Queue<String> byQueue, Queue<String> onQueue, Queue<String> atQueue, Queue<String> fromQueue, Queue<String> toQueue) { String token = ""; if (!byQueue.isEmpty()) { token = byQueue.poll(); } else if (!onQueue.isEmpty()) { token = onQueue.poll(); } else if (!atQueue.isEmpty()) { token = atQueue.poll(); } else if (!fromQueue.isEmpty()) { token = fromQueue.poll(); } else if (!toQueue.isEmpty()) { token = toQueue.poll(); } return token; } private Queue<String> initialiseArgQueue(ArrayList<String> argsList) { Queue<String> argsQueue = new LinkedList<String>(); for (String arg : argsList) { argsQueue.offer(arg); } return argsQueue; } private ArrayList<String> tokenizeArguments(String args) { ArrayList<String> argsList = new ArrayList<String>(); StringTokenizer st = new StringTokenizer(args, " "); while (st.hasMoreTokens()) { argsList.add(st.nextToken()); } return argsList; } //@@author /** * Extracts the new task's tags from the add command's tag arguments string. * Merges duplicate tag strings. */ private static Set<String> getTagsFromArgs(String tagArguments) throws IllegalValueException { // no tags if (tagArguments.isEmpty()) { return Collections.emptySet(); } // replace first delimiter prefix, then split final Collection<String> tagStrings = Arrays .asList(tagArguments.replaceFirst(" " + Tag.PREFIX, "").split(" " + Tag.PREFIX)); return new HashSet<>(tagStrings); } /** * Parses arguments in the context of the delete task command. * * @param args * full command args string * @return the prepared command */ private Command prepareDelete(String args) { Optional<Integer> index = parseIndex(args); if (!index.isPresent()) { UndoCommand.deletePreviousCommand(); return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE)); } return new DeleteCommand(index.get()); } /** * Parses arguments in the context of the select task command. * * @param args * full command args string * @return the prepared command */ private Command prepareSelect(String args) { Optional<Integer> index = parseIndex(args); if (!index.isPresent()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE)); } return new SelectCommand(index.get()); } /** * Returns the specified index in the {@code command} IF a positive unsigned * integer is given as the index. Returns an {@code Optional.empty()} * otherwise. */ private Optional<Integer> parseIndex(String command) { final Matcher matcher = TASK_INDEX_ARGS_FORMAT.matcher(command.trim()); if (!matcher.matches()) { return Optional.empty(); } String index = matcher.group("targetIndex"); if (!StringUtil.isUnsignedInteger(index)) { return Optional.empty(); } return Optional.of(Integer.parseInt(index)); } /** * Parses arguments in the context of the find task command. * * @param args * string * @return the prepared command */ private Command prepareFind(String args) { final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); } // keywords delimited by whitespace final String[] keywords = matcher.group("keywords").split("\\s+"); final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords)); return new FindCommand(keywordSet); } /** @@author A0142130A **/ /** * Parses arguments in the context of undo command. * */ private Command prepareUndo(String args) { Optional<Integer> index = parseIndex(args); if (!index.isPresent()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, UndoCommand.MESSAGE_USAGE)); } return new UndoCommand(index.get()); } /** * Parses arguments in the context of the find task by tags command. * * @param args * full command args string * @return the prepared command */ private Command prepareFindByTag(String args) { final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindTagCommand.MESSAGE_USAGE)); } // keywords delimited by whitespace final String[] keywords = matcher.group("keywords").split("\\s+"); final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords)); return new FindTagCommand(keywordSet); } /** * Parses arguments in the context of the save storage location command. * * @param args * full command args string * @return the prepared command */ private Command prepareSaveStorageLocation(String args) { if (args.isEmpty()) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, SaveStorageLocationCommand.MESSAGE_USAGE)); } return new SaveStorageLocationCommand(args); } /** @@author **/ //@@author A0148004R /** * Parses arguments in the context of the done task command. * * @param args * full command args string * @return the prepared command */ private Command prepareDone(String args) { Optional<Integer> index = parseIndex(args); if (!index.isPresent()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, DoneCommand.MESSAGE_USAGE)); } return new DoneCommand(index.get()); } //@@author //@@author A0142073R private static boolean isInt(String s) { try { int i = Integer.parseInt(s); return true; } catch (NumberFormatException er) { return false; } } //@@author }
refactor
src/main/java/seedu/taskell/logic/parser/Parser.java
refactor
<ide><path>rc/main/java/seedu/taskell/logic/parser/Parser.java <ide> import seedu.taskell.logic.commands.list.ListDateCommand; <ide> import seedu.taskell.logic.commands.list.ListDoneCommand; <ide> import seedu.taskell.logic.commands.list.ListPriorityCommand; <add>import seedu.taskell.model.History; <add>import seedu.taskell.model.HistoryManager; <ide> import seedu.taskell.model.tag.Tag; <ide> import seedu.taskell.model.task.Task; <ide> import seedu.taskell.model.task.TaskDate; <ide> private static final String AT = "at"; <ide> private static final String FROM = "from"; <ide> private static final String TO = "to"; <add> <add> private static History history; <ide> <ide> public Parser() { <add> history = HistoryManager.getInstance(); <ide> } <ide> <ide> /** <ide> <ide> final String commandWord = matcher.group("commandWord"); <ide> final String arguments = matcher.group("arguments"); <add> <add> if (commandWord.equals(AddCommand.COMMAND_WORD) <add> || commandWord.equals(DeleteCommand.COMMAND_WORD) <add> || commandWord.contains(UndoCommand.EDIT)) { <add> IncorrectCommand.setIsUndoableCommand(true); <add> history.addCommand(userInput, commandWord); <add> } else { <add> IncorrectCommand.setIsUndoableCommand(false); <add> } <ide> <ide> switch (commandWord) { <ide> <ide> case AddCommand.COMMAND_WORD: <del> UndoCommand.addCommandToHistory(userInput, commandWord); <ide> return prepareAdd(arguments); <ide> <ide> case SelectCommand.COMMAND_WORD: <ide> return prepareSelect(arguments); <ide> <ide> case DeleteCommand.COMMAND_WORD: <del> UndoCommand.addCommandToHistory(userInput, commandWord); <ide> return prepareDelete(arguments); <ide> <ide> case EditStartDateCommand.COMMAND_WORD: <del> UndoCommand.addCommandToHistory(userInput, commandWord); <ide> return prepareEditStartDate(arguments); <ide> <ide> case EditEndDateCommand.COMMAND_WORD: <del> UndoCommand.addCommandToHistory(userInput, commandWord); <ide> return prepareEditEndDate(arguments); <ide> <ide> case EditDescriptionCommand.COMMAND_WORD_1: <del> UndoCommand.addCommandToHistory(userInput, commandWord); <ide> return prepareEditDescription(arguments); <ide> <ide> case EditDescriptionCommand.COMMAND_WORD_2: <del> UndoCommand.addCommandToHistory(userInput, commandWord); <ide> return prepareEditDescription(arguments); <ide> <ide> case EditStartTimeCommand.COMMAND_WORD: <del> UndoCommand.addCommandToHistory(userInput, commandWord); <ide> return prepareEditStartTime(arguments); <ide> <ide> case EditEndTimeCommand.COMMAND_WORD: <del> UndoCommand.addCommandToHistory(userInput, commandWord); <ide> return prepareEditEndTime(arguments); <ide> <ide> case EditPriorityCommand.COMMAND_WORD: <del> UndoCommand.addCommandToHistory(userInput, commandWord); <ide> return prepareEditPriority(arguments); <ide> <ide> case ClearCommand.COMMAND_WORD: <ide> private Command prepareEditStartDate(String args) { <ide> String arguments = ""; <ide> if (args.isEmpty()) { <del> UndoCommand.deletePreviousCommand(); <ide> return new IncorrectCommand( <ide> String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditStartDateCommand.MESSAGE_USAGE)); <ide> } <ide> StringTokenizer st = new StringTokenizer(args.trim(), " "); <ide> String intValue = st.nextToken(); <ide> if (!isInt(intValue)) { <del> UndoCommand.deletePreviousCommand(); <ide> return new IncorrectCommand( <ide> String.format(MESSAGE_INVALID_TASK_DISPLAYED_INDEX, EditEndDateCommand.MESSAGE_USAGE)); <ide> } <ide> String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditStartDateCommand.MESSAGE_USAGE)); <ide> } <ide> if (!TaskDate.isValidDate(arguments)) { <del> UndoCommand.deletePreviousCommand(); <ide> return new IncorrectCommand( <ide> String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditStartDateCommand.MESSAGE_USAGE)); <ide> } <ide> try { <ide> return new EditStartDateCommand(targetIdx, arguments); <ide> } catch (IllegalValueException ive) { <del> UndoCommand.deletePreviousCommand(); <ide> return new IncorrectCommand(ive.getMessage()); <ide> } <ide> } <ide> private Command prepareEditDescription(String args) { <ide> String arguments = ""; <ide> if (args.isEmpty()) { <del> UndoCommand.deletePreviousCommand(); <ide> return new IncorrectCommand( <ide> String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditDescriptionCommand.MESSAGE_USAGE)); <ide> } <ide> StringTokenizer st = new StringTokenizer(args.trim(), " "); <ide> String intValue = st.nextToken(); <ide> if (!isInt(intValue)) { <del> UndoCommand.deletePreviousCommand(); <ide> return new IncorrectCommand( <ide> String.format(MESSAGE_INVALID_TASK_DISPLAYED_INDEX, EditDescriptionCommand.MESSAGE_USAGE)); <ide> } <ide> try { <ide> return new EditDescriptionCommand(targetIdx, arguments); <ide> } catch (IllegalValueException ive) { <del> UndoCommand.deletePreviousCommand(); <ide> return new IncorrectCommand(ive.getMessage()); <ide> } <ide> } <ide> private Command prepareEditStartTime(String args) { <ide> String arguments = ""; <ide> if (args.isEmpty()) { <del> UndoCommand.deletePreviousCommand(); <ide> return new IncorrectCommand( <ide> String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditStartTimeCommand.MESSAGE_USAGE)); <ide> } <ide> StringTokenizer st = new StringTokenizer(args.trim(), " "); <ide> String intValue = st.nextToken(); <ide> if (!isInt(intValue)) { <del> UndoCommand.deletePreviousCommand(); <ide> return new IncorrectCommand( <ide> String.format(MESSAGE_INVALID_TASK_DISPLAYED_INDEX, EditStartTimeCommand.MESSAGE_USAGE)); <ide> } <ide> int targetIdx = Integer.valueOf(intValue); <ide> arguments = st.nextToken(); <ide> if (st.hasMoreTokens()) { <del> UndoCommand.deletePreviousCommand(); <ide> return new IncorrectCommand( <ide> String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditStartTimeCommand.MESSAGE_USAGE)); <ide> } <ide> <ide> if (!TaskTime.isValidTime(arguments)) { <del> UndoCommand.deletePreviousCommand(); <ide> return new IncorrectCommand( <ide> String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditStartTimeCommand.MESSAGE_USAGE)); <ide> } <ide> try { <ide> return new EditStartTimeCommand(targetIdx, arguments); <ide> } catch (IllegalValueException ive) { <del> UndoCommand.deletePreviousCommand(); <ide> return new IncorrectCommand(ive.getMessage()); <ide> } <ide> } <ide> private Command prepareEditEndDate(String args) { <ide> String arguments = ""; <ide> if (args.isEmpty()) { <del> UndoCommand.deletePreviousCommand(); <ide> return new IncorrectCommand( <ide> String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditEndDateCommand.MESSAGE_USAGE)); <ide> } <ide> StringTokenizer st = new StringTokenizer(args.trim(), " "); <ide> String intValue = st.nextToken(); <ide> if (!isInt(intValue)) { <del> UndoCommand.deletePreviousCommand(); <ide> return new IncorrectCommand( <ide> String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditEndDateCommand.MESSAGE_USAGE)); <ide> } <ide> int targetIdx = Integer.valueOf(intValue); <ide> arguments = st.nextToken(); <ide> if (st.hasMoreTokens() || !TaskDate.isValidDate(arguments)) { <del> UndoCommand.deletePreviousCommand(); <ide> return new IncorrectCommand( <ide> String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditEndDateCommand.MESSAGE_USAGE)); <ide> } <ide> try { <ide> return new EditEndDateCommand(targetIdx, arguments); <ide> } catch (IllegalValueException ive) { <del> UndoCommand.deletePreviousCommand(); <ide> return new IncorrectCommand(ive.getMessage()); <ide> } <ide> } <ide> private Command prepareEditEndTime(String args) { <ide> String arguments = ""; <ide> if (args.isEmpty()) { <del> UndoCommand.deletePreviousCommand(); <ide> return new IncorrectCommand( <ide> String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditEndTimeCommand.MESSAGE_USAGE)); <ide> } <ide> StringTokenizer st = new StringTokenizer(args.trim(), " "); <ide> String intValue = st.nextToken(); <ide> if (!isInt(intValue)) { <del> UndoCommand.deletePreviousCommand(); <ide> return new IncorrectCommand( <ide> String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditEndTimeCommand.MESSAGE_USAGE)); <ide> } <ide> int targetIdx = Integer.valueOf(intValue); <ide> arguments = st.nextToken(); <ide> if (st.hasMoreTokens() || !TaskTime.isValidTime(arguments)) { <del> UndoCommand.deletePreviousCommand(); <ide> return new IncorrectCommand( <ide> String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditEndTimeCommand.MESSAGE_USAGE)); <ide> } <ide> try { <ide> return new EditEndTimeCommand(targetIdx, arguments); <ide> } catch (IllegalValueException ive) { <del> UndoCommand.deletePreviousCommand(); <ide> return new IncorrectCommand(ive.getMessage()); <ide> } <ide> } <ide> private Command prepareEditPriority(String args) { <ide> String arguments = ""; <ide> if (args.isEmpty()) { <del> UndoCommand.deletePreviousCommand(); <ide> return new IncorrectCommand( <ide> String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditPriorityCommand.MESSAGE_USAGE)); <ide> } <ide> int targetIdx = Integer.valueOf(st.nextToken()); <ide> arguments = st.nextToken(); <ide> if (st.hasMoreTokens() || !TaskPriority.isValidPriority(arguments)) { <del> UndoCommand.deletePreviousCommand(); <ide> return new IncorrectCommand( <ide> String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditPriorityCommand.MESSAGE_USAGE)); <ide> } <ide> try { <ide> return new EditPriorityCommand(targetIdx, arguments); <ide> } catch (IllegalValueException ive) { <del> UndoCommand.deletePreviousCommand(); <ide> return new IncorrectCommand(ive.getMessage()); <ide> } <ide> } <ide> */ <ide> private Command prepareAdd(String args) { <ide> if (args.isEmpty()) { <del> UndoCommand.deletePreviousCommand(); <ide> return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE)); <ide> } <ide> <ide> return new AddCommand(description, Task.EVENT_TASK, startDate, endDate, startTime, endTime, <ide> taskPriority, getTagsFromArgs(tagString)); <ide> } catch (IllegalValueException ive) { <del> UndoCommand.deletePreviousCommand(); <ide> return new IncorrectCommand(ive.getMessage()); <ide> } <ide> } else { <ide> return new AddCommand(description, Task.FLOATING_TASK, startDate, endDate, startTime, endTime, <ide> taskPriority, getTagsFromArgs(tagString)); <ide> } catch (IllegalValueException ive) { <del> UndoCommand.deletePreviousCommand(); <ide> return new IncorrectCommand(ive.getMessage()); <ide> } <ide> } <ide> <ide> Optional<Integer> index = parseIndex(args); <ide> if (!index.isPresent()) { <del> UndoCommand.deletePreviousCommand(); <ide> return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE)); <ide> } <ide>
Java
apache-2.0
c5087dfced44d3555edf01fc41d5a68504c475c4
0
SpineEventEngine/core-java,SpineEventEngine/core-java,SpineEventEngine/core-java
/* * Copyright 2016, TeamDev Ltd. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * 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 org.spine3.server; import com.google.common.collect.Lists; import com.google.common.util.concurrent.MoreExecutors; import com.google.protobuf.Message; import com.google.protobuf.StringValue; import io.grpc.stub.StreamObserver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spine3.base.Command; import org.spine3.base.Event; import org.spine3.base.EventContext; import org.spine3.base.Failure; import org.spine3.base.Response; import org.spine3.server.command.CommandBus; import org.spine3.server.command.CommandDispatcher; import org.spine3.server.command.CommandStore; import org.spine3.server.entity.Entity; import org.spine3.server.entity.Repository; import org.spine3.server.event.EventBus; import org.spine3.server.event.EventDispatcher; import org.spine3.server.event.EventStore; import org.spine3.server.integration.IntegrationEvent; import org.spine3.server.integration.IntegrationEventContext; import org.spine3.server.integration.grpc.IntegrationEventSubscriberGrpc.IntegrationEventSubscriber; import org.spine3.server.storage.StorageFactory; import org.spine3.validate.Validate; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable; import java.util.List; import java.util.concurrent.Executor; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static org.spine3.base.Responses.isOk; import static org.spine3.protobuf.Messages.fromAny; import static org.spine3.protobuf.Messages.toAny; import static org.spine3.protobuf.Values.newStringValue; import static org.spine3.util.Logging.closed; /** * A facade for configuration and entry point for handling commands. * * @author Alexander Yevsyukov * @author Mikhail Melnik */ public class BoundedContext implements IntegrationEventSubscriber, AutoCloseable { /** * The default name for a {@code BoundedContext}. */ public static final String DEFAULT_NAME = "Main"; /** * The name of the bounded context, which is used to distinguish the context in an application with * several bounded contexts. */ private final String name; /** * If `true` the bounded context serves many organizations. */ private final boolean multitenant; private final StorageFactory storageFactory; private final CommandBus commandBus; private final EventBus eventBus; private final List<Repository<?, ?>> repositories = Lists.newLinkedList(); private BoundedContext(Builder builder) { this.name = builder.name; this.multitenant = builder.multitenant; this.storageFactory = builder.storageFactory; this.commandBus = builder.commandBus; this.eventBus = builder.eventBus; } /** * Creates a new builder for {@code BoundedContext}. * * @return new builder instance */ public static Builder newBuilder() { return new Builder(); } /** * Closes the {@code BoundedContext} performing all necessary clean-ups. * * <p>This method performs the following: * <ol> * <li>Closes associated {@link StorageFactory}. * <li>Closes {@link CommandBus}. * <li>Closes {@link EventBus}. * <li>Closes {@link CommandStore}. * <li>Closes {@link EventStore}. * <li>Shuts down all registered repositories. Each registered repository is: * <ul> * <li>un-registered from {@link CommandBus} * <li>un-registered from {@link EventBus} * <li>detached from its storage * </ul> * </ol> * @throws Exception caused by closing one of the components */ @Override public void close() throws Exception { storageFactory.close(); commandBus.close(); eventBus.close(); shutDownRepositories(); log().info(closed(nameForLogging())); } private void shutDownRepositories() throws Exception { for (Repository<?, ?> repository : repositories) { repository.close(); } repositories.clear(); } private String nameForLogging() { return getClass().getSimpleName() + ' ' + getName(); } /** * Obtains a name of the bounded context. * * <p>The name allows to identify a bounded context if a multi-context application. * If the name was not defined, during the building process, the context would get {@link #DEFAULT_NAME}. * * @return the name of this {@code BoundedContext} */ public String getName() { return name; } /** * @return {@code true} if the bounded context serves many organizations */ @CheckReturnValue public boolean isMultitenant() { return multitenant; } /** * Registers the passed repository with the {@code BoundedContext}. * * <p>If the repository does not have a storage assigned, it will be initialized * using the {@code StorageFactory} associated with this bounded context. * * @param repository the repository to register * @param <I> the type of IDs used in the repository * @param <E> the type of entities or aggregates * @see Repository#initStorage(StorageFactory) */ @SuppressWarnings("ChainOfInstanceofChecks") public <I, E extends Entity<I, ?>> void register(Repository<I, E> repository) { checkStorageAssigned(repository); repositories.add(repository); if (repository instanceof CommandDispatcher) { commandBus.register((CommandDispatcher) repository); } if (repository instanceof EventDispatcher) { eventBus.register((EventDispatcher) repository); } } private void checkStorageAssigned(Repository repository) { if (!repository.storageAssigned()) { repository.initStorage(this.storageFactory); } } @SuppressWarnings("ChainOfInstanceofChecks") private void unregister(Repository<?, ?> repository) throws Exception { if (repository instanceof CommandDispatcher) { commandBus.unregister((CommandDispatcher) repository); } if (repository instanceof EventDispatcher) { eventBus.unregister((EventDispatcher) repository); } } @Override public void notify(IntegrationEvent integrationEvent, StreamObserver<Response> responseObserver) { /** * TODO:2016-05-11:alexander.litus: use {@link StreamObserver#onError} * instead of returning responses, see {@link CommandBus#post(Command, StreamObserver)}. */ try { final Message message = fromAny(integrationEvent.getMessage()); final Response response = validateIntegrationEventMessage(message); responseObserver.onNext(response); responseObserver.onCompleted(); if (isOk(response)) { final Event event = toEvent(integrationEvent); eventBus.post(event); } } catch (RuntimeException e) { responseObserver.onError(e); } } /** * Validates an incoming integration event message. * * @param eventMessage a message to validate * @return a response with {@code OK} value if the command is valid, or * with {@link org.spine3.base.Error}/{@link Failure} value otherwise */ protected Response validateIntegrationEventMessage(Message eventMessage) { final Response response = eventBus.validate(eventMessage); return response; } private static Event toEvent(IntegrationEvent integrationEvent) { final IntegrationEventContext sourceContext = integrationEvent.getContext(); final StringValue producerId = newStringValue(sourceContext.getBoundedContextName()); final EventContext context = EventContext.newBuilder() .setEventId(sourceContext.getEventId()) .setTimestamp(sourceContext.getTimestamp()) .setProducerId(toAny(producerId)) .build(); final Event.Builder result = Event.newBuilder() .setMessage(integrationEvent.getMessage()) .setContext(context); return result.build(); } /** * Convenience method for obtaining instance of {@link CommandBus}. * * @return instance of {@code CommandDispatcher} used in the application */ @CheckReturnValue public CommandBus getCommandBus() { return this.commandBus; } /** * Convenience method for obtaining instance of {@link EventBus}. * * @return instance of {@code EventBus} used in the application */ @CheckReturnValue public EventBus getEventBus() { return this.eventBus; } /** * A builder for producing {@code BoundedContext} instances. * * <p>An application can have more than one bounded context. To distinguish * them use {@link #setName(String)}. If no name is given the default name will be assigned. */ public static class Builder { private String name = DEFAULT_NAME; private StorageFactory storageFactory; private CommandStore commandStore; private CommandBus commandBus; private EventStore eventStore; private Executor eventStoreStreamExecutor; private EventBus eventBus; private boolean multitenant; /** * Sets the name for a new bounded context. * * <p>If the name is not defined in the builder, the context will get {@link #DEFAULT_NAME}. * * <p>It is the responsibility of an application developer to provide meaningful and unique * names for bounded contexts. The framework does not check for duplication of names. * * @param name a name for a new bounded context. Cannot be null, empty, or blank */ public Builder setName(String name) { this.name = Validate.checkNotEmptyOrBlank(name, "name"); return this; } /** * Returns the previously set name or {@link #DEFAULT_NAME} * if the name was not explicitly set. */ public String getName() { return name; } public Builder setMultitenant(boolean value) { this.multitenant = value; return this; } public boolean isMultitenant() { return this.multitenant; } public Builder setStorageFactory(StorageFactory storageFactory) { this.storageFactory = checkNotNull(storageFactory); return this; } @Nullable public StorageFactory getStorageFactory() { return storageFactory; } public Builder setCommandStore(CommandStore commandStore) { this.commandStore = checkNotNull(commandStore); return this; } @Nullable public CommandStore getCommandStore() { return this.commandStore; } public Builder setCommandBus(CommandBus commandBus) { this.commandBus = checkNotNull(commandBus); return this; } @Nullable public CommandBus getCommandBus() { return commandBus; } /** * Specifies {@code EventStore} to be used when creating new {@code EventBus}. * * <p>This method can be called if {@link #setEventStoreStreamExecutor(Executor)} * was not called before. * * @see #setEventStoreStreamExecutor(Executor) */ public Builder setEventStore(EventStore eventStore) { checkState(eventStoreStreamExecutor == null, "eventStoreStreamExecutor already set."); this.eventStore = checkNotNull(eventStore); return this; } /** * Specifies an {@code Executor} for returning event stream from {@code EventStore}. * * <p>This {@code Executor} instance will be used for creating * new {@code EventStore} instance when building {@code BoundedContext}, <em>if</em> * {@code EventStore} was not explicitly set in the builder. * * <p>If an {@code Executor} is not set in the builder, {@link MoreExecutors#directExecutor()} * will be used. * * @see #setEventStore(EventStore) */ @SuppressWarnings("MethodParameterNamingConvention") public Builder setEventStoreStreamExecutor(Executor eventStoreStreamExecutor) { checkState(eventStore == null, "EventStore is already configured."); this.eventStoreStreamExecutor = eventStoreStreamExecutor; return this; } @Nullable public Executor getEventStoreStreamExecutor() { return eventStoreStreamExecutor; } @Nullable public EventStore getEventStore() { return eventStore; } public Builder setEventBus(EventBus eventBus) { this.eventBus = checkNotNull(eventBus); return this; } @Nullable public EventBus getEventBus() { return eventBus; } public BoundedContext build() { checkNotNull(storageFactory, "storageFactory must be set"); /* If some of the properties were not set, create them using set StorageFactory. */ if (commandStore == null) { commandStore = createCommandStore(); } if (commandBus == null) { commandBus = createCommandBus(); } if (eventStore == null) { eventStore = createEventStore(); } if (eventBus == null) { eventBus = createEventBus(); } commandBus.setMultitenant(this.multitenant); final BoundedContext result = new BoundedContext(this); log().info(result.nameForLogging() + " created."); return result; } private CommandStore createCommandStore() { final CommandStore result = new CommandStore(storageFactory.createCommandStorage()); return result; } private EventStore createEventStore() { if (eventStoreStreamExecutor == null) { this.eventStoreStreamExecutor = MoreExecutors.directExecutor(); } final EventStore result = EventStore.newBuilder() .setStreamExecutor(eventStoreStreamExecutor) .setStorage(storageFactory.createEventStorage()) .setLogger(EventStore.log()) .build(); return result; } private CommandBus createCommandBus() { if (commandStore == null) { this.commandStore = createCommandStore(); } final CommandBus commandBus = CommandBus.newInstance(commandStore); return commandBus; } private EventBus createEventBus() { if (eventStore == null) { this.eventStore = createEventStore(); } final EventBus eventBus = EventBus.newInstance(eventStore); return eventBus; } } private enum LogSingleton { INSTANCE; @SuppressWarnings("NonSerializableFieldInSerializableClass") private final Logger value = LoggerFactory.getLogger(BoundedContext.class); } private static Logger log() { return LogSingleton.INSTANCE.value; } }
server/src/main/java/org/spine3/server/BoundedContext.java
/* * Copyright 2016, TeamDev Ltd. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * 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 org.spine3.server; import com.google.common.collect.Lists; import com.google.common.util.concurrent.MoreExecutors; import com.google.protobuf.Message; import com.google.protobuf.StringValue; import io.grpc.stub.StreamObserver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spine3.base.Command; import org.spine3.base.Event; import org.spine3.base.EventContext; import org.spine3.base.Failure; import org.spine3.base.Response; import org.spine3.server.command.CommandBus; import org.spine3.server.command.CommandDispatcher; import org.spine3.server.command.CommandStore; import org.spine3.server.entity.Entity; import org.spine3.server.entity.Repository; import org.spine3.server.event.EventBus; import org.spine3.server.event.EventDispatcher; import org.spine3.server.event.EventStore; import org.spine3.server.integration.IntegrationEvent; import org.spine3.server.integration.IntegrationEventContext; import org.spine3.server.integration.grpc.IntegrationEventSubscriberGrpc.IntegrationEventSubscriber; import org.spine3.server.storage.StorageFactory; import org.spine3.validate.Validate; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable; import java.util.List; import java.util.concurrent.Executor; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static org.spine3.base.Responses.isOk; import static org.spine3.protobuf.Messages.fromAny; import static org.spine3.protobuf.Messages.toAny; import static org.spine3.protobuf.Values.newStringValue; import static org.spine3.util.Logging.closed; /** * A facade for configuration and entry point for handling commands. * * @author Alexander Yevsyukov * @author Mikhail Melnik */ public class BoundedContext implements IntegrationEventSubscriber, AutoCloseable { /** * The default name for a {@code BoundedContext}. */ public static final String DEFAULT_NAME = "Main"; /** * The name of the bounded context, which is used to distinguish the context in an application with * several bounded contexts. */ private final String name; /** * If `true` the bounded context serves many organizations. */ private final boolean multitenant; //TODO:2016-01-16:alexander.yevsyukov: Set all passed storages multitenant too. // Or require storageFactory be multitenant and create correspondingly configured storages. // There should be CurrentTenant, which keeps thread-local reference to the currently set TenantId. // Implementations like namespace support of GCP would wrap over their APIs. private final StorageFactory storageFactory; private final CommandBus commandBus; private final EventBus eventBus; private final List<Repository<?, ?>> repositories = Lists.newLinkedList(); private BoundedContext(Builder builder) { this.name = builder.name; this.multitenant = builder.multitenant; this.storageFactory = builder.storageFactory; this.commandBus = builder.commandBus; this.eventBus = builder.eventBus; } /** * Creates a new builder for {@code BoundedContext}. * * @return new builder instance */ public static Builder newBuilder() { return new Builder(); } /** * Closes the {@code BoundedContext} performing all necessary clean-ups. * * <p>This method performs the following: * <ol> * <li>Closes associated {@link StorageFactory}. * <li>Closes {@link CommandBus}. * <li>Closes {@link EventBus}. * <li>Closes {@link CommandStore}. * <li>Closes {@link EventStore}. * <li>Shuts down all registered repositories. Each registered repository is: * <ul> * <li>un-registered from {@link CommandBus} * <li>un-registered from {@link EventBus} * <li>detached from its storage * </ul> * </ol> * @throws Exception caused by closing one of the components */ @Override public void close() throws Exception { storageFactory.close(); commandBus.close(); eventBus.close(); shutDownRepositories(); log().info(closed(nameForLogging())); } private void shutDownRepositories() throws Exception { for (Repository<?, ?> repository : repositories) { repository.close(); } repositories.clear(); } private String nameForLogging() { return getClass().getSimpleName() + ' ' + getName(); } /** * Obtains a name of the bounded context. * * <p>The name allows to identify a bounded context if a multi-context application. * If the name was not defined, during the building process, the context would get {@link #DEFAULT_NAME}. * * @return the name of this {@code BoundedContext} */ public String getName() { return name; } /** * @return {@code true} if the bounded context serves many organizations */ @CheckReturnValue public boolean isMultitenant() { return multitenant; } /** * Registers the passed repository with the {@code BoundedContext}. * * <p>If the repository does not have a storage assigned, it will be initialized * using the {@code StorageFactory} associated with this bounded context. * * @param repository the repository to register * @param <I> the type of IDs used in the repository * @param <E> the type of entities or aggregates * @see Repository#initStorage(StorageFactory) */ @SuppressWarnings("ChainOfInstanceofChecks") public <I, E extends Entity<I, ?>> void register(Repository<I, E> repository) { checkStorageAssigned(repository); repositories.add(repository); if (repository instanceof CommandDispatcher) { commandBus.register((CommandDispatcher) repository); } if (repository instanceof EventDispatcher) { eventBus.register((EventDispatcher) repository); } } private void checkStorageAssigned(Repository repository) { if (!repository.storageAssigned()) { repository.initStorage(this.storageFactory); } } @SuppressWarnings("ChainOfInstanceofChecks") private void unregister(Repository<?, ?> repository) throws Exception { if (repository instanceof CommandDispatcher) { commandBus.unregister((CommandDispatcher) repository); } if (repository instanceof EventDispatcher) { eventBus.unregister((EventDispatcher) repository); } } @Override public void notify(IntegrationEvent integrationEvent, StreamObserver<Response> responseObserver) { /** * TODO:2016-05-11:alexander.litus: use {@link StreamObserver#onError} * instead of returning responses, see {@link CommandBus#post(Command, StreamObserver)}. */ try { final Message message = fromAny(integrationEvent.getMessage()); final Response response = validateIntegrationEventMessage(message); responseObserver.onNext(response); responseObserver.onCompleted(); if (isOk(response)) { final Event event = toEvent(integrationEvent); eventBus.post(event); } } catch (RuntimeException e) { responseObserver.onError(e); } } /** * Validates an incoming integration event message. * * @param eventMessage a message to validate * @return a response with {@code OK} value if the command is valid, or * with {@link org.spine3.base.Error}/{@link Failure} value otherwise */ protected Response validateIntegrationEventMessage(Message eventMessage) { final Response response = eventBus.validate(eventMessage); return response; } private static Event toEvent(IntegrationEvent integrationEvent) { final IntegrationEventContext sourceContext = integrationEvent.getContext(); final StringValue producerId = newStringValue(sourceContext.getBoundedContextName()); final EventContext context = EventContext.newBuilder() .setEventId(sourceContext.getEventId()) .setTimestamp(sourceContext.getTimestamp()) .setProducerId(toAny(producerId)) .build(); final Event.Builder result = Event.newBuilder() .setMessage(integrationEvent.getMessage()) .setContext(context); return result.build(); } /** * Convenience method for obtaining instance of {@link CommandBus}. * * @return instance of {@code CommandDispatcher} used in the application */ @CheckReturnValue public CommandBus getCommandBus() { return this.commandBus; } /** * Convenience method for obtaining instance of {@link EventBus}. * * @return instance of {@code EventBus} used in the application */ @CheckReturnValue public EventBus getEventBus() { return this.eventBus; } /** * A builder for producing {@code BoundedContext} instances. * * <p>An application can have more than one bounded context. To distinguish * them use {@link #setName(String)}. If no name is given the default name will be assigned. */ public static class Builder { private String name = DEFAULT_NAME; private StorageFactory storageFactory; private CommandStore commandStore; private CommandBus commandBus; private EventStore eventStore; private Executor eventStoreStreamExecutor; private EventBus eventBus; private boolean multitenant; /** * Sets the name for a new bounded context. * * <p>If the name is not defined in the builder, the context will get {@link #DEFAULT_NAME}. * * <p>It is the responsibility of an application developer to provide meaningful and unique * names for bounded contexts. The framework does not check for duplication of names. * * @param name a name for a new bounded context. Cannot be null, empty, or blank */ public Builder setName(String name) { this.name = Validate.checkNotEmptyOrBlank(name, "name"); return this; } /** * Returns the previously set name or {@link #DEFAULT_NAME} * if the name was not explicitly set. */ public String getName() { return name; } public Builder setMultitenant(boolean value) { this.multitenant = value; return this; } public boolean isMultitenant() { return this.multitenant; } public Builder setStorageFactory(StorageFactory storageFactory) { this.storageFactory = checkNotNull(storageFactory); return this; } @Nullable public StorageFactory getStorageFactory() { return storageFactory; } public Builder setCommandStore(CommandStore commandStore) { this.commandStore = checkNotNull(commandStore); return this; } @Nullable public CommandStore getCommandStore() { return this.commandStore; } public Builder setCommandBus(CommandBus commandBus) { this.commandBus = checkNotNull(commandBus); return this; } @Nullable public CommandBus getCommandBus() { return commandBus; } /** * Specifies {@code EventStore} to be used when creating new {@code EventBus}. * * <p>This method can be called if {@link #setEventStoreStreamExecutor(Executor)} * was not called before. * * @see #setEventStoreStreamExecutor(Executor) */ public Builder setEventStore(EventStore eventStore) { checkState(eventStoreStreamExecutor == null, "eventStoreStreamExecutor already set."); this.eventStore = checkNotNull(eventStore); return this; } /** * Specifies an {@code Executor} for returning event stream from {@code EventStore}. * * <p>This {@code Executor} instance will be used for creating * new {@code EventStore} instance when building {@code BoundedContext}, <em>if</em> * {@code EventStore} was not explicitly set in the builder. * * <p>If an {@code Executor} is not set in the builder, {@link MoreExecutors#directExecutor()} * will be used. * * @see #setEventStore(EventStore) */ @SuppressWarnings("MethodParameterNamingConvention") public Builder setEventStoreStreamExecutor(Executor eventStoreStreamExecutor) { checkState(eventStore == null, "EventStore is already configured."); this.eventStoreStreamExecutor = eventStoreStreamExecutor; return this; } @Nullable public Executor getEventStoreStreamExecutor() { return eventStoreStreamExecutor; } @Nullable public EventStore getEventStore() { return eventStore; } public Builder setEventBus(EventBus eventBus) { this.eventBus = checkNotNull(eventBus); return this; } @Nullable public EventBus getEventBus() { return eventBus; } public BoundedContext build() { checkNotNull(storageFactory, "storageFactory must be set"); /* If some of the properties were not set, create them using set StorageFactory. */ if (commandStore == null) { commandStore = createCommandStore(); } if (commandBus == null) { commandBus = createCommandBus(); } if (eventStore == null) { eventStore = createEventStore(); } if (eventBus == null) { eventBus = createEventBus(); } commandBus.setMultitenant(this.multitenant); final BoundedContext result = new BoundedContext(this); log().info(result.nameForLogging() + " created."); return result; } private CommandStore createCommandStore() { final CommandStore result = new CommandStore(storageFactory.createCommandStorage()); return result; } private EventStore createEventStore() { if (eventStoreStreamExecutor == null) { this.eventStoreStreamExecutor = MoreExecutors.directExecutor(); } final EventStore result = EventStore.newBuilder() .setStreamExecutor(eventStoreStreamExecutor) .setStorage(storageFactory.createEventStorage()) .setLogger(EventStore.log()) .build(); return result; } private CommandBus createCommandBus() { if (commandStore == null) { this.commandStore = createCommandStore(); } final CommandBus commandBus = CommandBus.newInstance(commandStore); return commandBus; } private EventBus createEventBus() { if (eventStore == null) { this.eventStore = createEventStore(); } final EventBus eventBus = EventBus.newInstance(eventStore); return eventBus; } } private enum LogSingleton { INSTANCE; @SuppressWarnings("NonSerializableFieldInSerializableClass") private final Logger value = LoggerFactory.getLogger(BoundedContext.class); } private static Logger log() { return LogSingleton.INSTANCE.value; } }
Remove completed TODO.
server/src/main/java/org/spine3/server/BoundedContext.java
Remove completed TODO.
<ide><path>erver/src/main/java/org/spine3/server/BoundedContext.java <ide> * If `true` the bounded context serves many organizations. <ide> */ <ide> private final boolean multitenant; <del> //TODO:2016-01-16:alexander.yevsyukov: Set all passed storages multitenant too. <del> // Or require storageFactory be multitenant and create correspondingly configured storages. <del> // There should be CurrentTenant, which keeps thread-local reference to the currently set TenantId. <del> // Implementations like namespace support of GCP would wrap over their APIs. <del> <ide> private final StorageFactory storageFactory; <ide> private final CommandBus commandBus; <ide> private final EventBus eventBus;
JavaScript
mit
1cddd0a4dc0537bc0ce20eeb1b61cd0968129059
0
NiklasGollenstede/es6lib
(function(global) { 'use strict'; /* globals URL, location, */ // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. const document = typeof window !== 'undefined' && global.navigator && global.document; const importScripts = typeof window === 'undefined' && typeof navigator === 'object' && typeof global.importScripts === 'function'; const webExt = document && !importScripts && (() => { const api = (global.browser || global.chrome); if (api && api.extension && typeof api.extension.getURL === 'function') { return api; } })(); const isGenerator = code => (/^function\s*\*/).test(code); const resolved = Promise.resolve(); const Modules = { }; // id ==> Module const Loading = { }; // url ==> Module (with .loading === true) let mainModule = null; let baseUrl = '', hiddenBaseUrl = null; let prefixMap = { }; let modIdMap = null; let defIdMap = null; let shimMap = null; let loadScript = url => { throw new Error(`No JavaScript loader available to load "${ url }"`); }; { // set default baseUrl const path = getCallingScript(0); const fromNM = (/\/node_modules\/(?:require|es6lib)\/require\.js$/).test(path); const url = (fromNM ? new URL('../../', path) : new URL('./', location)); baseUrl = url.href.slice(0, url.href.length - url.hash.length - url.search.length); } if (webExt) { const actualBaseUrl = webExt.extension.getURL(''); if (baseUrl !== actualBaseUrl) { hiddenBaseUrl = baseUrl; } baseUrl = actualBaseUrl; } function getCallingScript(offset = 0) { const src = document && document.currentScript && document.currentScript.src; if (src) { return src; } const stack = (new Error).stack.split(/$/m); const line = stack[(/^Error/).test(stack[0]) + 1 + offset]; const parts = line.split(/(?:\@|\(|\ )/g); const url = parts[parts.length - 1].replace(/\:\d+(?:\:\d+)?\)?$/, ''); if (hiddenBaseUrl !== null && url.startsWith(hiddenBaseUrl)) { return url.replace(hiddenBaseUrl, baseUrl); } return url; } function parseDepsDestr(factory, name, code) { let index = 0; // the next position of interest function next(exp) { exp.lastIndex = index; const match = exp.exec(code)[0]; index = exp.lastIndex; return match; } const getWord = (/[a-zA-Z_]\w*/g); const nextWord = next.bind(null, getWord); const getString = (/(?:'.*?'|".*?"|`.*?`)/g); const nextString = next.bind(null, getString); const getLine = (/(?:\r?\n|\r)\s*/g); const nextLine = next.bind(null, getLine); function local(name) { const string = './'+ name.split('').map((c, i) => { const l = c.toLowerCase(); return l === c ? c : i === 0 ? l : '-'+ l; }).join(''); return { name, toString() { return string; }, }; } index = (/^\s*(?:async\s*)?(?:function\s*)?(?:\*\s*)?(?:\(\s*)?/).exec(code)[0].length; // skip ' async function * ( ' if (code[index] === ')') { return [ ]; } // argument list closes immediately if (code[index] !== '{') { return [ ]; } // no destructuring assignment const deps = [ ]; loop: do { nextLine(); switch (code[index]) { case '}': break loop; // exit case '/': { code[index + 1] !== '/' && unexpected(); } break; case '[': case "'": case '"': case '`': { deps.push(nextString().slice(1, -1)); } break; default: { !(/[a-zA-Z_]/).test(code[index]) && unexpected(); deps.push(local(nextWord())); } } } while (true); function unexpected() { throw new Error(`Unexpected char '${ code[index] }' in destructuring module definition of "${ name }" at char ${ index }`); } return deps; } function parseDepsBody(factory, name, code) { if (factory.length === 0) { return [ ]; } const require = (/require\s*\(\s*(?:"(.*?)"|'.*?'|`.*?`)\s*\)/g); const whitespace = (/\s*/g); // try to find an early way out let match, found = false; while ((match = require.exec(code))) { const requireAt = match.index; const dotAt = code.lastIndexOf('.', requireAt); whitespace.lastIndex = dotAt; if (dotAt >= 0 && dotAt + whitespace.exec(code)[0].length === requireAt) { continue; } found = true; break; } const deps = [ 'require', 'exports', 'module', ]; if (!found) { return deps.slice(0, factory.length); } const stringsAndComments = (/(\'(?:[^\\]|\\[^\\]|(?:\\\\)*)*?\'|\"(?:[^\\]|\\[^\\]|(?:\\\\)*)*?\"|\`(?:[^\\]|\\[^\\]|(?:\\\\)*)*?\`)|\/\/[^]*?$|\/\*[^]*?\*\/|\/(?:[^\\]|\\[^\\]|(?:\\\\)*)*?\//gm); /* which (using the 'regexpx' module) is: RegExpX('gmsX')` ( # strings, allow multiple lines # these need to be put back if they are 'simple' \' (?:[^\\]|\\[^\\]|(?:\\\\)*)*? \' | \" (?:[^\\]|\\[^\\]|(?:\\\\)*)*? \" # substitutions in template strings should be put back too, # but even just finding the closing bracket is not trivial, # especially because the expressions themselves can contain strings and comments # so they are (currently) ignored | \` (?:[^\\]|\\[^\\]|(?:\\\\)*)*? \` ) | \/\/ .*? $ # line comments | \/\* .*? \*\/ # block comments | \/ (?:[^\\]|\\[^\\]|(?:\\\\)*)*? \/ # RegExp literals `; and the expression between the quotes is: RegExpX` (?: [^\\] # something that's not a backslash | \\ [^\\] # a backslash followed by something that's not | (?: \\\\ )* # an even number of backslashes )*? `; */ code = code.replace(stringsAndComments, (_, s) => (s && (s = s.slice(1, -1)) && !require.test(s) ? '"'+ s +'"' : '')); require.lastIndex = 0; while ((match = require.exec(code))) { const requireAt = match.index; const dotAt = code.lastIndexOf('.', requireAt); whitespace.lastIndex = dotAt; if (dotAt >= 0 && dotAt + whitespace.exec(code)[0].length === requireAt) { continue; } deps.push(match[1]); } return deps.length === 3 ? deps.slice(0, factory.length) : deps; } function hasPendingPath(from, to) { if (from._children.size === 0) { return false; } return from.children.some(child => { if (child._resolved) { return false; } if (child === to) { return true; } // unless somebody messes with the ._resolved property, this traverses a directed acyclic graph return hasPendingPath(child, to); }); } function makeObject(names, values) { // TODO: use a Proxy to directly throw for undefined properties? const object = { }; for (let i = 0; i < names.length; ++i) { object[names[i].name || names[i]] = values[i]; } return object; } function define(/* id, deps, factory */) { // parse arguments let id, deps, factory; switch (arguments.length) { case 3: { [ id, deps, factory, ] = arguments; if (!Array.isArray(deps)) { badArg(); } } break; case 2: { factory = arguments[1]; const first = arguments[0]; typeof first === 'string' ? (id = first) : (deps = first); } break; case 1: { factory = arguments[0]; } break; default: { badArg(); } } // get id let src = ''; if (id === undefined) { src = getCallingScript(1); const url = new URL(src); src = url.href.slice(0, url.href.length - url.hash.length - url.search.length); id = src.replace(/\.js$/, ''); if (id.startsWith(baseUrl)) { id = id.slice(baseUrl.length); } else if (id.startsWith('/')) { id = id.slice(1); } } if (typeof id !== 'string') { badArg(); } if ((/^[\.\\\/]/).test(id)) { throw new Error('The module id must be an absolute path'); } function badArg () { throw new TypeError('Bad signature, should be define(id?: string, dependencies?: Array<string>, factory: function|any)'); } // get/create Module const module = src && Loading[src] || Modules[id] || (Modules[id] = new Module(null, null, id)); if (module._loaded) { throw new Error(`Duplicate definition of module "${ id }"`); } module._loaded = true; delete Loading[src]; if (typeof factory !== 'function') { resolved.then(() => { module.exports = factory; module._resolved = true; module.promise.resolve(module.exports); }); return module.promise.then(() => module.exports); } const code = factory +''; module.factory = factory; // get deps let special = false; if (!deps) { if ( factory.length === 1 && (deps = parseDepsDestr(factory, id, code)).length ) { special = true; } else { deps = parseDepsBody(factory, id, code); } } const promise = resolved.then(() => Promise.all(deps.map(dep => { switch (dep.name || dep) { case 'require': return module.require; case 'exports': return module.exports; case 'module': return module; default: return module.requireAsync(dep +'', true); } }))) .then(modules => { const result = special ? factory(makeObject(deps, modules)) : factory(...modules); return isGenerator(code) ? spawn(result) : result; }) .catch(error => { console.error(`Definition of ${ id } failed:`, error); throw error; }) .then(exports => { exports != null && (module.exports = exports); module._resolved = true; module.promise.resolve(module); }) .catch(module.promise.reject); return module.promise; } define.amd = { destructuring: true, generator: true, promise: true, }; class Module { constructor(parent, url, id) { this.url = url ? new URL(url) : id ? new URL(resolveUrl(id) +'.js') : ''; this.id = id; this.parent = parent; this.factory = null; this.exports = { }; this._children = new Set; this.promise = new PromiseCapability(); this._loaded = false; this._resolved = false; this.isShim = false; this._require = null; Object.defineProperty(this, 'require', { get() { if (this._require) { return this._require; } const require = this._require = Module.prototype.require.bind(this); require.async = Module.prototype.requireAsync.bind(this); require.toUrl = Module.prototype.requireToUrl.bind(this); require.resolve = resolveId.bind(null, this.id); require.cache = Modules; require.config = config; Object.defineProperty(require, 'main', { get() { return mainModule; }, set(module) { if (module instanceof Module) { mainModule = module; } else { throw new Error(`require.main must be a Module`); } }, enumerable: true, configurable: true, }); return require; }, enumerable: true, configurable: true, }); } require(name) { if (typeof name === 'string') { let split = 0, id = ''; if ((split = name.indexOf('!')) >= 0) { // get the plugin const pluginId = resolveId(this.id, name.slice(0, split)); const plugin = Modules[pluginId]; if (!plugin || !plugin._resolved) { throw new Error(`The plugin "${ pluginId }" is not defined (yet)`); } id = pluginId +'!'+ resolveByPlugin(plugin, this.id, name.slice(split + 1)); } else { id = resolveId(this.id, name); } const module = Modules[id]; if (!module || !module._resolved) { throw new Error(`The module "${ id }" is not defined (yet)`); } this._children.add(module); return module.exports; } const [ names, done, ] = arguments; if (Array.isArray(names) && typeof done === 'function') { Promise.all(names.map(name => this.requireAsync(name, true))) .then(result => done(...result)) .catch(error => { console.error(`Failed to require([ ${ names }, ], ...)`); throw error; }); } else { throw new Error(`require must be called with (string) or (Array, function)`); } } requireAsync(name, fast, plugin) { let split = 0, id = ''; if (plugin) { id = name; } else if ((split = name.indexOf('!')) >= 0) { // get the plugin const pluginId = resolveId(this.id, name.slice(0, split)); const resName = name.slice(split + 1); if (fast && (plugin = Modules[pluginId]) && plugin._resolved) { id = resolveByPlugin(plugin, this.id, resName); } else { return this.requireAsync(pluginId) .then(() => { const plugin = Modules[pluginId]; return this.requireAsync(resolveByPlugin(plugin, this.id, resName), true, plugin); }); } } else { id = resolveId(this.id, name); } let module = Modules[id]; if (module) { this._children.add(module); if (module._resolved) { if (fast) { return module.exports; } return Promise.resolve(module.exports); } if (hasPendingPath(module, this)) { console.warn(`Found cyclic dependency to "${ id }", passing it's unfinished exports to "${ this.id }"`); this._children.delete(module); if (fast) { this.promise.then(() => this._children.add(module)); return module.exports; } return Promise.reject(Error(`Asynchronously requiring "${ name }" from "${ this.id }" would create a cyclic waiting condition`)); } return module.promise.then(() => module.exports); } if (plugin) { const fullId = plugin.id +'!'+ id; module = new Module(this, 'plugin:'+ fullId, fullId); !plugin.exports.dynamic && (Modules[fullId] = module) && this._children.add(module); plugin.exports.load(id, this.require, module.promise.resolve, { cancel: module.promise.reject, }); return module.promise.then(exports => { module.exports = exports; module._loaded = module._resolved = true; return exports; }); } const url = resolveUrl(id) +'.js'; module = Modules[id] = Loading[url] = new Module(this, url, id); this._children.add(module); loadScript(url) .then(() => { if (module._loaded) { return; } if (this.isShim) { module._loaded = module._resolved = module.isShim = true; module.promise.resolve(module.exports); return console.info(`The shim dependency "${ url }" of "${ this.id }" didn't call define`); } const error = `The script at "${ url }" did not call define with the expected id`; console.error(error); module.promise.reject(new Error(error)); }) .catch(error => { const message = `Failed to load script "${ url }" first requested from "${ this.url }"`; console.error(message +', due to:', error); module.promise.reject(new Error(message)); }); return module.promise.then(() => module.exports); } requireToUrl(path) { return resolveUrl(resolveId(this.id, path)); } get children () { return Array.from(this._children); } get loaded () { return this._loaded; } get resolved () { return this._resolved; } } const globalModule = new Module(null, '', ''); const require = globalModule.require; function PromiseCapability() { let y, n, promise = new Promise((_y, _n) => (y = _y, n = _n)); promise.resolve = y; promise.reject = n; return promise; } function resolveId(from, to) { let id = to +''; if (id.startsWith('.')) { if (!from) { throw new Error(`Can't resolve relative module id from global require, use the one passed into the define callback instead`); } const url = new URL(id, typeof from === 'string' ? baseUrl + from : from); id = url.href.slice(0, url.href.length - url.hash.length - url.search.length); if (id.startsWith(baseUrl)) { id = id.slice(baseUrl.length); } else if (id.startsWith('/')) { id = id.slice(1); } } else if (id.startsWith('/')) { id = id.slice(1); } if (id.endsWith('/')) { id += 'index'; } if (!modIdMap && !defIdMap || typeof from !== 'string') { return id; } const maps = Object.keys(modIdMap || { }) .filter(prefix => isIdPrefix(from, prefix)) .sort((a, b) => b.length - a.length) .map(key => modIdMap[key]) .concat(defIdMap || [ ]); for (let map of maps) { const prefix = Object.keys(map) .filter(prefix => isIdPrefix(id, prefix)) .reduce((a, b) => a.length > b.length ? a : b, ''); if (prefix) { return map[prefix] + id.slice(prefix.length); } } return id; } function resolveUrl(id) { const prefix = Object.keys(prefixMap) .filter(prefix => isIdPrefix(id, prefix)) .reduce((a, b) => a.length > b.length ? a : b, ''); if (!prefix) { return baseUrl + id; } return prefixMap[prefix] + id.slice(prefix.length); } function isIdPrefix(id, prefix) { return ( id === prefix || id.length > prefix.length && id.startsWith(prefix) && ( prefix.endsWith('/') || id[prefix.length] === '/' || (/^\.[^\\\/]+$/).test(id.slice(prefix.length)) ) ); } function resolveByPlugin(plugin, from, id) { if (plugin.exports && plugin.exports.normalize) { return plugin.exports.normalize(id, resolveId.bind(null, from)); } return resolveId(from, id); } function onContentScriptMessage(message, sender, reply) { if (!Array.isArray(message) || !Array.isArray(message[2]) || message[0] !== 'require.loadScript' || message[1] !== 1 || !sender.tab) { return; } let url = message[2][0]; if (!url.startsWith(baseUrl)) { return reply([ '', -1, [ 'Can only load local resources', ], ]); } url = url.slice(baseUrl.length - 1); webExt.tabs.executeScript(sender.tab.id, { file: url, }, () => { if (webExt.runtime.lastError) { return reply([ '', -1, [ webExt.runtime.lastError.message, ], ]); } return reply([ '', 1, [ null, ], ]); }); return true; } if (webExt && !document.currentScript) { // webExtension and not loaded via <script> tag loadScript = url => new Promise((resolve, reject) => webExt.runtime.sendMessage([ 'require.loadScript', 1, [ url, ], ], reply => { if (webExt.runtime.lastError) { return reject(webExt.runtime.lastError); } if (!Array.isArray(reply)) { return reject(new Error('Failed to load script. Bad reply')); } const threw = reply[1] < 0; threw ? reject(reply[2][0]) : resolve(); })); } else if (document) { // normal DOM window loadScript = url => new Promise((resolve, reject) => { const script = document.createElement('script'); script.onload = resolve; script.onerror = reject; script.src = url; document.documentElement.appendChild(script).remove(); }); } else if (importScripts) { // for WebWorkers, untested const requested = [ ]; loadScript = url => { requested.push(url); resolved.then( () => requested.length && importScripts(requested.splice(0, Infinity)) ); }; } function spawn(iterator) { const next = arg => handle(iterator.next(arg)); const _throw = arg => handle(iterator.throw(arg)); const handle = ({ done, value, }) => done ? Promise.resolve(value) : Promise.resolve(value).then(next, _throw); return resolved.then(next); } function config(options) { if (options == null || typeof options !== 'object') { return; } if ('baseUrl' in options) { const url = new URL(options.baseUrl.replace(/^"(.*)"$/g, '$1'), location); baseUrl = url.href.slice(0, url.href.length - url.hash.length - url.search.length); } /// Set an id to be the main module. Loads the module if needed. if ('main' in options) { const id = resolveId(location, options.main.replace(/^"(.*)"$/g, '$1')); require.async(id); // TODO: .catch ? require.main = require.cache[id]; require.main.parent = null; } if ('paths' in options) { const paths = typeof options.paths === 'string' ? JSON.parse(options.paths) : options.paths; Object.keys(paths).forEach(prefix => { const url = new URL(paths[prefix], baseUrl); prefixMap[prefix] = url.href.slice(0, url.href.length - url.hash.length - url.search.length); }); } if ('map' in options) { const map = typeof options.map === 'string' ? JSON.parse(options.map) : options.map; Object.keys(map).forEach(id => { const idMap = Object.assign(map[id]); if (typeof idMap !== 'object') { return; } if (id === '*') { defIdMap = idMap; } else { modIdMap = modIdMap || { }; modIdMap[id] = idMap; } }); } if ('shim' in options) { const shims = typeof options.shim === 'string' ? JSON.parse(options.shim) : options.shim; Object.keys(shims).forEach(id => { const shim = shims[id]; if (!shim || typeof shim !== 'object') { return; } const isArray = Array.isArray(shim); const deps = ((isArray ? shim : shim.deps) || [ ]).slice(); const globalPath = !isArray && typeof shim.exports === 'string' && shim.exports.split('.') || [ ]; const init = !isArray && typeof shim.init === 'function' ? shim.init : shim.exports === 'function' ? shim.exports : undefined; id = resolveId('', id); const url = resolveUrl(id) +'.js'; define(id, deps, function*() { (yield loadScript(url).catch(() => { const error = `Failed to load script "${ url }" first requested from ${ this.url }.js`; console.error(error); throw new Error(error); })); Modules[id]._loaded = true; const exports = globalPath.reduce((object, key) => object != null && object[key], global); if (!exports) { const error = `The script at "${ url }" did not set the global variable "${ globalPath.join('.') }"`; console.error(error); throw new Error(error); } const result = init && (yield init.apply(global, arguments)); return result !== undefined ? result : globalPath.length ? exports : undefined; }); Modules[id]._loaded = false; Modules[id].isShim = true; }); } if ('serveContentScripts' in options) { const value = options.serveContentScripts; if (value === 'false' || value === false) { webExt.runtime.onMessage.removeListener(onContentScriptMessage); } else { webExt.runtime.onMessage.addListener(onContentScriptMessage); } } } /// set the config specified in the script tag via < data-...="..." > config(document.currentScript && document.currentScript.dataset); global.define = define; global.require = require; })((function() { /* jshint strict: false */ return this; })());
require.js
(function(global) { 'use strict'; /* globals URL, location, */ // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. const document = typeof window !== 'undefined' && global.navigator && global.document; const importScripts = typeof window === 'undefined' && typeof navigator === 'object' && typeof global.importScripts === 'function'; const webExt = document && !document.currentScript && !importScripts && (() => { const api = (global.browser || global.chrome); if (api && api.extension && typeof api.extension.getURL === 'function') { return api; } })(); const isGenerator = code => (/^function\s*\*/).test(code); const resolved = Promise.resolve(); const Modules = { }; // id ==> Module const Loading = { }; // url ==> Module (with .loading === true) let mainModule = null; let baseUrl = '', hiddenBaseUrl = null; let prefixMap = { }; let modIdMap = null; let defIdMap = null; let shimMap = null; let loadScript = url => { throw new Error(`No JavaScript loader available to load "${ url }"`); }; { // set default baseUrl const path = getCallingScript(0); const fromNM = (/\/node_modules\/(?:require|es6lib)\/require\.js$/).test(path); const url = (fromNM ? new URL('../../', path) : new URL('./', location)); baseUrl = url.href.slice(0, url.href.length - url.hash.length - url.search.length); } if (webExt) { const actualBaseUrl = webExt.extension.getURL(''); if (baseUrl !== actualBaseUrl) { hiddenBaseUrl = baseUrl; } baseUrl = actualBaseUrl; } function getCallingScript(offset = 0) { const src = document && document.currentScript && document.currentScript.src; if (src) { return src; } const stack = (new Error).stack.split(/$/m); const line = stack[(/^Error/).test(stack[0]) + 1 + offset]; const parts = line.split(/(?:\@|\(|\ )/g); const url = parts[parts.length - 1].replace(/\:\d+(?:\:\d+)?\)?$/, ''); if (hiddenBaseUrl !== null && url.startsWith(hiddenBaseUrl)) { return url.replace(hiddenBaseUrl, baseUrl); } return url; } function parseDepsDestr(factory, name, code) { let index = 0; // the next position of interest function next(exp) { exp.lastIndex = index; const match = exp.exec(code)[0]; index = exp.lastIndex; return match; } const getWord = (/[a-zA-Z_]\w*/g); const nextWord = next.bind(null, getWord); const getString = (/(?:'.*?'|".*?"|`.*?`)/g); const nextString = next.bind(null, getString); const getLine = (/(?:\r?\n|\r)\s*/g); const nextLine = next.bind(null, getLine); function local(name) { const string = './'+ name.split('').map((c, i) => { const l = c.toLowerCase(); return l === c ? c : i === 0 ? l : '-'+ l; }).join(''); return { name, toString() { return string; }, }; } index = (/^\s*(?:async\s*)?(?:function\s*)?(?:\*\s*)?(?:\(\s*)?/).exec(code)[0].length; // skip ' async function * ( ' if (code[index] === ')') { return [ ]; } // argument list closes immediately if (code[index] !== '{') { return [ ]; } // no destructuring assignment const deps = [ ]; loop: do { nextLine(); switch (code[index]) { case '}': break loop; // exit case '/': { code[index + 1] !== '/' && unexpected(); } break; case '[': case "'": case '"': case '`': { deps.push(nextString().slice(1, -1)); } break; default: { !(/[a-zA-Z_]/).test(code[index]) && unexpected(); deps.push(local(nextWord())); } } } while (true); function unexpected() { throw new Error(`Unexpected char '${ code[index] }' in destructuring module definition of "${ name }" at char ${ index }`); } return deps; } function parseDepsBody(factory, name, code) { if (factory.length === 0) { return [ ]; } const require = (/require\s*\(\s*(?:"(.*?)"|'.*?'|`.*?`)\s*\)/g); const whitespace = (/\s*/g); // try to find an early way out let match, found = false; while ((match = require.exec(code))) { const requireAt = match.index; const dotAt = code.lastIndexOf('.', requireAt); whitespace.lastIndex = dotAt; if (dotAt >= 0 && dotAt + whitespace.exec(code)[0].length === requireAt) { continue; } found = true; break; } const deps = [ 'require', 'exports', 'module', ]; if (!found) { return deps.slice(0, factory.length); } const stringsAndComments = (/(\'(?:[^\\]|\\[^\\]|(?:\\\\)*)*?\'|\"(?:[^\\]|\\[^\\]|(?:\\\\)*)*?\"|\`(?:[^\\]|\\[^\\]|(?:\\\\)*)*?\`)|\/\/[^]*?$|\/\*[^]*?\*\/|\/(?:[^\\]|\\[^\\]|(?:\\\\)*)*?\//gm); /* which (using the 'regexpx' module) is: RegExpX('gmsX')` ( # strings, allow multiple lines # these need to be put back if they are 'simple' \' (?:[^\\]|\\[^\\]|(?:\\\\)*)*? \' | \" (?:[^\\]|\\[^\\]|(?:\\\\)*)*? \" # substitutions in template strings should be put back too, # but even just finding the closing bracket is not trivial, # especially because the expressions themselves can contain strings and comments # so they are (currently) ignored | \` (?:[^\\]|\\[^\\]|(?:\\\\)*)*? \` ) | \/\/ .*? $ # line comments | \/\* .*? \*\/ # block comments | \/ (?:[^\\]|\\[^\\]|(?:\\\\)*)*? \/ # RegExp literals `; and the expression between the quotes is: RegExpX` (?: [^\\] # something that's not a backslash | \\ [^\\] # a backslash followed by something that's not | (?: \\\\ )* # an even number of backslashes )*? `; */ code = code.replace(stringsAndComments, (_, s) => (s && (s = s.slice(1, -1)) && !require.test(s) ? '"'+ s +'"' : '')); require.lastIndex = 0; while ((match = require.exec(code))) { const requireAt = match.index; const dotAt = code.lastIndexOf('.', requireAt); whitespace.lastIndex = dotAt; if (dotAt >= 0 && dotAt + whitespace.exec(code)[0].length === requireAt) { continue; } deps.push(match[1]); } return deps.length === 3 ? deps.slice(0, factory.length) : deps; } function hasPendingPath(from, to) { if (from._children.size === 0) { return false; } return from.children.some(child => { if (child._resolved) { return false; } if (child === to) { return true; } // unless somebody messes with the ._resolved property, this traverses a directed acyclic graph return hasPendingPath(child, to); }); } function makeObject(names, values) { // TODO: use a Proxy to directly throw for undefined properties? const object = { }; for (let i = 0; i < names.length; ++i) { object[names[i].name || names[i]] = values[i]; } return object; } function define(/* id, deps, factory */) { // parse arguments let id, deps, factory; switch (arguments.length) { case 3: { [ id, deps, factory, ] = arguments; if (!Array.isArray(deps)) { badArg(); } } break; case 2: { factory = arguments[1]; const first = arguments[0]; typeof first === 'string' ? (id = first) : (deps = first); } break; case 1: { factory = arguments[0]; } break; default: { badArg(); } } // get id let src = ''; if (id === undefined) { src = getCallingScript(1); const url = new URL(src); src = url.href.slice(0, url.href.length - url.hash.length - url.search.length); id = src.replace(/\.js$/, ''); if (id.startsWith(baseUrl)) { id = id.slice(baseUrl.length); } else if (id.startsWith('/')) { id = id.slice(1); } } if (typeof id !== 'string') { badArg(); } if ((/^[\.\\\/]/).test(id)) { throw new Error('The module id must be an absolute path'); } function badArg () { throw new TypeError('Bad signature, should be define(id?: string, dependencies?: Array<string>, factory: function|any)'); } // get/create Module const module = src && Loading[src] || Modules[id] || (Modules[id] = new Module(null, null, id)); if (module._loaded) { throw new Error(`Duplicate definition of module "${ id }"`); } module._loaded = true; delete Loading[src]; if (typeof factory !== 'function') { resolved.then(() => { module.exports = factory; module._resolved = true; module.promise.resolve(module.exports); }); return module.promise.then(() => module.exports); } const code = factory +''; module.factory = factory; // get deps let special = false; if (!deps) { if ( factory.length === 1 && (deps = parseDepsDestr(factory, id, code)).length ) { special = true; } else { deps = parseDepsBody(factory, id, code); } } const promise = resolved.then(() => Promise.all(deps.map(dep => { switch (dep.name || dep) { case 'require': return module.require; case 'exports': return module.exports; case 'module': return module; default: return module.requireAsync(dep +'', true); } }))) .then(modules => { const result = special ? factory(makeObject(deps, modules)) : factory(...modules); return isGenerator(code) ? spawn(result) : result; }) .catch(error => { console.error(`Definition of ${ id } failed:`, error); throw error; }) .then(exports => { exports != null && (module.exports = exports); module._resolved = true; module.promise.resolve(module); }) .catch(module.promise.reject); return module.promise; } define.amd = { destructuring: true, generator: true, promise: true, }; class Module { constructor(parent, url, id) { this.url = url ? new URL(url) : id ? new URL(resolveUrl(id) +'.js') : ''; this.id = id; this.parent = parent; this.factory = null; this.exports = { }; this._children = new Set; this.promise = new PromiseCapability(); this._loaded = false; this._resolved = false; this.isShim = false; this._require = null; Object.defineProperty(this, 'require', { get() { if (this._require) { return this._require; } const require = this._require = Module.prototype.require.bind(this); require.async = Module.prototype.requireAsync.bind(this); require.toUrl = Module.prototype.requireToUrl.bind(this); require.resolve = resolveId.bind(null, this.id); require.cache = Modules; require.config = config; Object.defineProperty(require, 'main', { get() { return mainModule; }, set(module) { if (module instanceof Module) { mainModule = module; } else { throw new Error(`require.main must be a Module`); } }, enumerable: true, configurable: true, }); return require; }, enumerable: true, configurable: true, }); } require(name) { if (typeof name === 'string') { let split = 0, id = ''; if ((split = name.indexOf('!')) >= 0) { // get the plugin const pluginId = resolveId(this.id, name.slice(0, split)); const plugin = Modules[pluginId]; if (!plugin || !plugin._resolved) { throw new Error(`The plugin "${ pluginId }" is not defined (yet)`); } id = pluginId +'!'+ resolveByPlugin(plugin, this.id, name.slice(split + 1)); } else { id = resolveId(this.id, name); } const module = Modules[id]; if (!module || !module._resolved) { throw new Error(`The module "${ id }" is not defined (yet)`); } this._children.add(module); return module.exports; } const [ names, done, ] = arguments; if (Array.isArray(names) && typeof done === 'function') { Promise.all(names.map(name => this.requireAsync(name, true))) .then(result => done(...result)) .catch(error => { console.error(`Failed to require([ ${ names }, ], ...)`); throw error; }); } else { throw new Error(`require must be called with (string) or (Array, function)`); } } requireAsync(name, fast, plugin) { let split = 0, id = ''; if (plugin) { id = name; } else if ((split = name.indexOf('!')) >= 0) { // get the plugin const pluginId = resolveId(this.id, name.slice(0, split)); const resName = name.slice(split + 1); if (fast && (plugin = Modules[pluginId]) && plugin._resolved) { id = resolveByPlugin(plugin, this.id, resName); } else { return this.requireAsync(pluginId) .then(() => { const plugin = Modules[pluginId]; return this.requireAsync(resolveByPlugin(plugin, this.id, resName), true, plugin); }); } } else { id = resolveId(this.id, name); } let module = Modules[id]; if (module) { this._children.add(module); if (module._resolved) { if (fast) { return module.exports; } return Promise.resolve(module.exports); } if (hasPendingPath(module, this)) { console.warn(`Found cyclic dependency to "${ id }", passing it's unfinished exports to "${ this.id }"`); this._children.delete(module); if (fast) { this.promise.then(() => this._children.add(module)); return module.exports; } return Promise.reject(Error(`Asynchronously requiring "${ name }" from "${ this.id }" would create a cyclic waiting condition`)); } return module.promise.then(() => module.exports); } if (plugin) { const fullId = plugin.id +'!'+ id; module = new Module(this, 'plugin:'+ fullId, fullId); !plugin.exports.dynamic && (Modules[fullId] = module) && this._children.add(module); plugin.exports.load(id, this.require, module.promise.resolve, { cancel: module.promise.reject, }); return module.promise.then(exports => { module.exports = exports; module._loaded = module._resolved = true; return exports; }); } const url = resolveUrl(id) +'.js'; module = Modules[id] = Loading[url] = new Module(this, url, id); this._children.add(module); loadScript(url) .then(() => { if (module._loaded) { return; } if (this.isShim) { module._loaded = module._resolved = module.isShim = true; module.promise.resolve(module.exports); return console.info(`The shim dependency "${ url }" of "${ this.id }" didn't call define`); } const error = `The script at "${ url }" did not call define with the expected id`; console.error(error); module.promise.reject(new Error(error)); }) .catch(error => { const message = `Failed to load script "${ url }" first requested from "${ this.url }"`; console.error(message +', due to:', error); module.promise.reject(new Error(message)); }); return module.promise.then(() => module.exports); } requireToUrl(path) { return resolveUrl(resolveId(this.id, path)); } get children () { return Array.from(this._children); } get loaded () { return this._loaded; } get resolved () { return this._resolved; } } const globalModule = new Module(null, '', ''); const require = globalModule.require; function PromiseCapability() { let y, n, promise = new Promise((_y, _n) => (y = _y, n = _n)); promise.resolve = y; promise.reject = n; return promise; } function resolveId(from, to) { let id = to +''; if (id.startsWith('.')) { if (!from) { throw new Error(`Can't resolve relative module id from global require, use the one passed into the define callback instead`); } const url = new URL(id, typeof from === 'string' ? baseUrl + from : from); id = url.href.slice(0, url.href.length - url.hash.length - url.search.length); if (id.startsWith(baseUrl)) { id = id.slice(baseUrl.length); } else if (id.startsWith('/')) { id = id.slice(1); } } else if (id.startsWith('/')) { id = id.slice(1); } if (id.endsWith('/')) { id += 'index'; } if (!modIdMap && !defIdMap || typeof from !== 'string') { return id; } const maps = Object.keys(modIdMap || { }) .filter(prefix => isIdPrefix(from, prefix)) .sort((a, b) => b.length - a.length) .map(key => modIdMap[key]) .concat(defIdMap || [ ]); for (let map of maps) { const prefix = Object.keys(map) .filter(prefix => isIdPrefix(id, prefix)) .reduce((a, b) => a.length > b.length ? a : b, ''); if (prefix) { return map[prefix] + id.slice(prefix.length); } } return id; } function resolveUrl(id) { const prefix = Object.keys(prefixMap) .filter(prefix => isIdPrefix(id, prefix)) .reduce((a, b) => a.length > b.length ? a : b, ''); if (!prefix) { return baseUrl + id; } return prefixMap[prefix] + id.slice(prefix.length); } function isIdPrefix(id, prefix) { return ( id === prefix || id.length > prefix.length && id.startsWith(prefix) && ( prefix.endsWith('/') || id[prefix.length] === '/' || (/^\.[^\\\/]+$/).test(id.slice(prefix.length)) ) ); } function resolveByPlugin(plugin, from, id) { if (plugin.exports && plugin.exports.normalize) { return plugin.exports.normalize(id, resolveId.bind(null, from)); } return resolveId(from, id); } if (webExt) { // webExtension and not loaded via <script> tag loadScript = url => new Promise((resolve, reject) => webExt.runtime.sendMessage([ 'require.loadScript', 1, [ url, ], ], reply => { if (webExt.runtime.lastError) { return reject(webExt.runtime.lastError); } if (!Array.isArray(reply)) { return reject(new Error('Failed to load script. Bad reply')); } const threw = reply[1] < 0; threw ? reject(reply[2][0]) : resolve(); })); } else if (document) { // normal DOM window loadScript = url => new Promise((resolve, reject) => { const script = document.createElement('script'); script.onload = resolve; script.onerror = reject; script.src = url; document.documentElement.appendChild(script).remove(); }); } else if (importScripts) { // for WebWorkers, untested const requested = [ ]; loadScript = url => { requested.push(url); resolved.then( () => requested.length && importScripts(requested.splice(0, Infinity)) ); }; } function spawn(iterator) { const next = arg => handle(iterator.next(arg)); const _throw = arg => handle(iterator.throw(arg)); const handle = ({ done, value, }) => done ? Promise.resolve(value) : Promise.resolve(value).then(next, _throw); return resolved.then(next); } function config(options) { if (options == null || typeof options !== 'object') { return; } if ('baseUrl' in options) { const url = new URL(options.baseUrl.replace(/^"(.*)"$/g, '$1'), location); baseUrl = url.href.slice(0, url.href.length - url.hash.length - url.search.length); } /// Set an id to be the main module. Loads the module if needed. if ('main' in options) { const id = resolveId(location, options.main.replace(/^"(.*)"$/g, '$1')); require.async(id); // TODO: .catch ? require.main = require.cache[id]; require.main.parent = null; } if ('paths' in options) { const paths = typeof options.paths === 'string' ? JSON.parse(options.paths) : options.paths; Object.keys(paths).forEach(prefix => { const url = new URL(paths[prefix], baseUrl); prefixMap[prefix] = url.href.slice(0, url.href.length - url.hash.length - url.search.length); }); } if ('map' in options) { const map = typeof options.map === 'string' ? JSON.parse(options.map) : options.map; Object.keys(map).forEach(id => { const idMap = Object.assign(map[id]); if (typeof idMap !== 'object') { return; } if (id === '*') { defIdMap = idMap; } else { modIdMap = modIdMap || { }; modIdMap[id] = idMap; } }); } if ('shim' in options) { const shims = typeof options.shim === 'string' ? JSON.parse(options.shim) : options.shim; Object.keys(shims).forEach(id => { const shim = shims[id]; if (!shim || typeof shim !== 'object') { return; } const isArray = Array.isArray(shim); const deps = ((isArray ? shim : shim.deps) || [ ]).slice(); const globalPath = !isArray && typeof shim.exports === 'string' && shim.exports.split('.') || [ ]; const init = !isArray && typeof shim.init === 'function' ? shim.init : shim.exports === 'function' ? shim.exports : undefined; id = resolveId('', id); const url = resolveUrl(id) +'.js'; define(id, deps, function*() { (yield loadScript(url).catch(() => { const error = `Failed to load script "${ url }" first requested from ${ this.url }.js`; console.error(error); throw new Error(error); })); Modules[id]._loaded = true; const exports = globalPath.reduce((object, key) => object != null && object[key], global); if (!exports) { const error = `The script at "${ url }" did not set the global variable "${ globalPath.join('.') }"`; console.error(error); throw new Error(error); } const result = init && (yield init.apply(global, arguments)); return result !== undefined ? result : globalPath.length ? exports : undefined; }); Modules[id]._loaded = false; Modules[id].isShim = true; }); } } /// set the config specified in the script tag via < data-...="..." > config(document.currentScript && document.currentScript.dataset); global.define = define; global.require = require; })((function() { /* jshint strict: false */ return this; })());
require.js: add serveContentScripts option
require.js
require.js: add serveContentScripts option
<ide><path>equire.js <ide> <ide> const document = typeof window !== 'undefined' && global.navigator && global.document; <ide> const importScripts = typeof window === 'undefined' && typeof navigator === 'object' && typeof global.importScripts === 'function'; <del>const webExt = document && !document.currentScript && !importScripts && (() => { <add>const webExt = document && !importScripts && (() => { <ide> const api = (global.browser || global.chrome); <ide> if (api && api.extension && typeof api.extension.getURL === 'function') { return api; } <ide> })(); <ide> return resolveId(from, id); <ide> } <ide> <del>if (webExt) { // webExtension and not loaded via <script> tag <add>function onContentScriptMessage(message, sender, reply) { <add> if (!Array.isArray(message) || !Array.isArray(message[2]) || message[0] !== 'require.loadScript' || message[1] !== 1 || !sender.tab) { return; } <add> let url = message[2][0]; <add> if (!url.startsWith(baseUrl)) { return reply([ '', -1, [ 'Can only load local resources', ], ]); } <add> url = url.slice(baseUrl.length - 1); <add> webExt.tabs.executeScript(sender.tab.id, { file: url, }, () => { <add> if (webExt.runtime.lastError) { return reply([ '', -1, [ webExt.runtime.lastError.message, ], ]); } <add> return reply([ '', 1, [ null, ], ]); <add> }); <add> return true; <add>} <add> <add>if (webExt && !document.currentScript) { // webExtension and not loaded via <script> tag <ide> loadScript = url => new Promise((resolve, reject) => webExt.runtime.sendMessage([ 'require.loadScript', 1, [ url, ], ], reply => { <ide> if (webExt.runtime.lastError) { return reject(webExt.runtime.lastError); } <ide> if (!Array.isArray(reply)) { return reject(new Error('Failed to load script. Bad reply')); } <ide> }); <ide> } <ide> <add> if ('serveContentScripts' in options) { <add> const value = options.serveContentScripts; <add> if (value === 'false' || value === false) { <add> webExt.runtime.onMessage.removeListener(onContentScriptMessage); <add> } else { <add> webExt.runtime.onMessage.addListener(onContentScriptMessage); <add> } <add> } <ide> } <ide> <ide> /// set the config specified in the script tag via < data-...="..." >
Java
apache-2.0
2451364be0b2ad5bc56c2296a51ba157e19b2998
0
bkromhout/Minerva
package com.bkromhout.minerva; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.support.v7.view.ActionMode; import android.support.v7.widget.ButtonBarLayout; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import com.afollestad.materialdialogs.MaterialDialog; import com.bkromhout.minerva.adapters.TagCardAdapter; import com.bkromhout.minerva.events.TagCardClickEvent; import com.bkromhout.minerva.realm.RBook; import com.bkromhout.minerva.realm.RTag; import com.bkromhout.minerva.util.Util; import com.bkromhout.realmrecyclerview.RealmRecyclerView; import com.google.common.collect.Lists; import com.jakewharton.rxbinding.widget.RxTextView; import com.jakewharton.rxbinding.widget.TextViewTextChangeEvent; import difflib.Delta; import difflib.DiffUtils; import difflib.Patch; import io.realm.Case; import io.realm.Realm; import io.realm.RealmResults; import io.realm.Sort; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import rx.Observer; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; /** * Activity used to apply (and remove) tags to (and from) books. */ public class TaggingActivity extends AppCompatActivity implements ActionMode.Callback { // Views. @Bind(R.id.toolbar) Toolbar toolbar; @Bind(R.id.recycler) RealmRecyclerView recyclerView; @Bind(R.id.tag_filter) EditText filter; @Bind(R.id.buttons) ButtonBarLayout buttons; @Bind(R.id.cancel) Button btnCancel; @Bind(R.id.save) Button btnSave; /** * Instance of {@link TaggingHelper}. */ private TaggingHelper taggingHelper; /** * Instance of Realm. */ private Realm realm; /** * The list of {@link RTag}s being shown. */ private RealmResults<RTag> items; /** * Recycler view adapter. */ private TagCardAdapter adapter; /** * Filter edit text change subscription. */ private Subscription filterChangeSub; /** * Convenience method to set up the {@link TaggingHelper} then start this activity from a fragment. * @param fragment The fragment to return a result to. * @param book The selected {@link RBook}. */ public static void start(Fragment fragment, RBook book) { start(fragment, Lists.asList(book, new RBook[] {})); } /** * Convenience method to set up the {@link TaggingHelper} then start this activity from a fragment. * @param fragment The fragment to return a result to. * @param selectedBooks The selected {@link RBook}s. */ public static void start(Fragment fragment, List<RBook> selectedBooks) { TaggingActivity.TaggingHelper.get().init(selectedBooks, RTag.tagListToStringList(RTag.listOfSharedTags(selectedBooks))); fragment.startActivityForResult(new Intent(fragment.getContext(), TaggingActivity.class), C.RC_TAG_ACTIVITY); } /** * Convenience method to set up the {@link TaggingHelper} then start this activity from an activity. * @param activity The activity to return a result to. * @param book The selected {@link RBook}. */ public static void start(Activity activity, RBook book) { start(activity, Lists.asList(book, new RBook[] {})); } /** * Convenience method to set up the {@link TaggingHelper} then start this activity from an activity. * @param activity The activity to return a result to. * @param selectedBooks The selected {@link RBook}s. */ public static void start(Activity activity, List<RBook> selectedBooks) { // Initialize the tagging helper. TaggingActivity.TaggingHelper.get().init(selectedBooks, RTag.tagListToStringList(RTag.listOfSharedTags(selectedBooks))); activity.startActivityForResult(new Intent(activity, TaggingActivity.class), C.RC_TAG_ACTIVITY); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set result as canceled. setResult(RESULT_CANCELED); // Create and bind views. setContentView(R.layout.activity_tagging); ButterKnife.bind(this); // Set up toolbar. setSupportActionBar(toolbar); //noinspection ConstantConditions getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); // Get TaggingHelper, Realm, then set up the rest of UI. taggingHelper = TaggingHelper.get(); realm = Realm.getDefaultInstance(); initUi(); } /** * Init the UI. */ private void initUi() { // Set up filter edit text to have a debounce before it filters the list. filterChangeSub = RxTextView.textChangeEvents(filter) .skip(1) .debounce(500, TimeUnit.MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe(getFilterObserver()); // Set up recycler view. if (taggingHelper.filter.isEmpty()) items = realm.allObjectsSorted(RTag.class, "sortName", Sort.ASCENDING); else applyFilter(taggingHelper.filter); adapter = new TagCardAdapter(this, items); recyclerView.setAdapter(adapter); } @Override public boolean onPrepareOptionsMenu(Menu menu) { Util.forceMenuIcons(menu, this, getClass().getSimpleName()); return super.onPrepareOptionsMenu(menu); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.tagging, menu); return super.onCreateOptionsMenu(menu); } @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } @Override public void onStop() { super.onStop(); EventBus.getDefault().unregister(this); } @Override public void onDestroy() { super.onDestroy(); // Close adapter. if (adapter != null) adapter.close(); // Close Realm. if (realm != null) { realm.close(); realm = null; } // Unsubscribe from filter edit text. if (filterChangeSub != null && !filterChangeSub.isUnsubscribed()) filterChangeSub.unsubscribe(); } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { mode.setTitle(R.string.title_tag_edit_mode); buttons.setVisibility(View.GONE); adapter.setInActionMode(true); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { Util.forceMenuIcons(menu, this, getClass().getSimpleName()); return true; } @Override public void onDestroyActionMode(ActionMode mode) { adapter.setInActionMode(false); buttons.setVisibility(View.VISIBLE); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; case R.id.action_new_tag: new MaterialDialog.Builder(this) .title(R.string.action_new_tag) .content(R.string.new_tag_prompt) .autoDismiss(false) .negativeText(R.string.cancel) .input(R.string.tag_name_hint, 0, false, (dialog, input) -> { String newName = input.toString().trim(); try (Realm iRealm = Realm.getDefaultInstance()) { if (iRealm.where(RTag.class).equalTo("name", newName).findFirst() == null) { // Name is available, create the RTag then dismiss the dialog. iRealm.executeTransaction(tRealm -> tRealm.copyToRealm(new RTag(newName))); dialog.dismiss(); } else { //noinspection ConstantConditions dialog.getInputEditText().setError(C.getStr(R.string.err_name_taken)); } } }) .show(); return true; case R.id.action_edit_tags: startSupportActionMode(this); return true; default: return super.onOptionsItemSelected(item); } } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { default: return false; } } /** * Get the observer to use to handle filter text changes. * @return Filter text change observer */ private Observer<TextViewTextChangeEvent> getFilterObserver() { return new Observer<TextViewTextChangeEvent>() { @Override public void onCompleted() { // Nothing. } @Override public void onError(Throwable e) { // Shouldn't happen, but we'll log it if it does. Log.e("TaggingActivity", "Some error occurred due to the filter observer!"); e.printStackTrace(); } @Override public void onNext(TextViewTextChangeEvent textViewTextChangeEvent) { // Apply filter to items and then update adapter's copy of items. applyFilter(textViewTextChangeEvent.text().toString()); adapter.updateRealmResults(items); } }; } /** * Called when the cancel button is clicked. */ @OnClick(R.id.cancel) void onCancelButtonClicked() { finish(); } /** * Called when the save button is clicked. */ @OnClick(R.id.save) void onSaveButtonClicked() { // Use the two lists to get deltas, then use them to figure out which tags were added and which were removed. Patch<String> patch = DiffUtils.diff(taggingHelper.oldCheckedItems, taggingHelper.newCheckedItems); List<String> removedTagNames = getDeltaLines(Delta.TYPE.DELETE, patch.getDeltas()); List<String> addedTagNames = getDeltaLines(Delta.TYPE.INSERT, patch.getDeltas()); // Remove and add the applicable tags. RTag.removeTagsFromBooks(taggingHelper.selectedBooks, RTag.stringListToTagList(removedTagNames, false)); RTag.addTagsToBooks(taggingHelper.selectedBooks, RTag.stringListToTagList(addedTagNames, true)); // Reset the TaggingHelper and finish this activity. taggingHelper = null; TaggingHelper.reset(); setResult(RESULT_OK); finish(); } /** * Take a list of Deltas and return a list of lines which are within deltas of the specified {@code type}. * @param deltaType Type of Delta to pull lines from. * @param deltas List of deltas. * @return List of strings. */ private List<String> getDeltaLines(Delta.TYPE deltaType, List<Delta<String>> deltas) { ArrayList<String> lines = new ArrayList<>(); // Loop through all of the deltas. for (Delta delta : deltas) { // For all of the specified type, add their lines to the list. if (delta.getType().equals(deltaType)) { // Have to look in different places based on the type of delta. if (deltaType == Delta.TYPE.DELETE) //noinspection unchecked lines.addAll(delta.getOriginal().getLines()); else if (deltaType == Delta.TYPE.INSERT) //noinspection unchecked lines.addAll(delta.getRevised().getLines()); } } return lines; } /** * Applies the current filter string by re-querying Realm for a new {@link #items} list. Does NOT update the * adapter. */ private void applyFilter(String filter) { taggingHelper.filter = filter; items = realm.where(RTag.class) .contains("name", filter, Case.INSENSITIVE) .findAllSorted("sortName"); } /** * Called when one of the action buttons is clicked on a tag card. * @param event {@link TagCardClickEvent}. */ @Subscribe public void onTagCardAction(TagCardClickEvent event) { switch (event.getType()) { case RENAME: // Show rename dialog. new MaterialDialog.Builder(this) .title(R.string.title_rename_tag) .content(R.string.rename_tag_prompt) .autoDismiss(false) .negativeText(R.string.cancel) .input(C.getStr(R.string.tag_name_hint), event.getName(), false, (dialog, input) -> { String newName = input.toString().trim(); // If it's the same name, do nothing, just dismiss. if (event.getName().equals(newName)) { dialog.dismiss(); return; } // Get Realm and check if name already exists. try (Realm iRealm = Realm.getDefaultInstance()) { if (iRealm.where(RTag.class).equalTo("name", newName).findFirst() == null) { // Name is available; rename the RTag. iRealm.executeTransaction(tRealm -> { RTag rTag = tRealm.where(RTag.class) .equalTo("name", event.getName()) .findFirst(); rTag.setName(newName); rTag.setSortName(newName.toLowerCase()); }); // Now make sure that we swap the old name for the new one in the old/new lists. TaggingHelper th = TaggingHelper.get(); if (th.oldCheckedItems.remove(event.getName())) th.oldCheckedItems.add(newName); if (th.newCheckedItems.remove(event.getName())) th.newCheckedItems.add(newName); dialog.dismiss(); } else { // Name already exists, set the error text and _don't_ dismiss the dialog. //noinspection ConstantConditions dialog.getInputEditText().setError(C.getStr(R.string.err_name_taken)); } } }) .show(); break; case DELETE: // Show delete confirm dialog. new MaterialDialog.Builder(this) .title(R.string.title_delete_tag) .content(C.getStr(R.string.delete_tag_prompt, event.getName())) .positiveText(R.string.yes) .negativeText(R.string.no) .onPositive((dialog, which) -> { // Get Realm instance, then delete the list. // TODO do we need to manually loop through the tagged books and remove the tag first??? Realm.getDefaultInstance() .executeTransaction(tRealm -> tRealm .where(RTag.class) .equalTo("name", event.getName()) .findFirst() .removeFromRealm()); // Remove tag name from the lists (if present). TaggingHelper th = TaggingHelper.get(); th.oldCheckedItems.remove(event.getName()); th.newCheckedItems.remove(event.getName()); }) .show(); break; } } /** * Class to help us hold complex objects until not needed any longer. */ public static class TaggingHelper { /** * Instance of tagging helper. */ private static TaggingHelper INSTANCE = null; /** * List of {@link RBook}s whose will be modified. */ public List<RBook> selectedBooks; /** * List of originally checked tags. */ public List<String> oldCheckedItems; /** * List of finally checked tags. */ public List<String> newCheckedItems; /** * Current filter string. */ public String filter = ""; /** * Get the current instance of {@link TaggingHelper}. * @return {@link TaggingHelper} instance. */ public static TaggingHelper get() { if (INSTANCE == null) reset(); return INSTANCE; } /** * Resets the current {@link TaggingHelper} instance. */ public static void reset() { INSTANCE = new TaggingHelper(); } private TaggingHelper() { selectedBooks = null; oldCheckedItems = new ArrayList<>(); newCheckedItems = new ArrayList<>(); } /** * Convenience method for initializing the {@link TaggingHelper}. * @param books List of books. * @param currCheckedItems List of tags to have checked. */ public void init(List<RBook> books, List<String> currCheckedItems) { this.selectedBooks = books; this.oldCheckedItems = currCheckedItems; this.newCheckedItems = new ArrayList<>(currCheckedItems); } } }
app/src/main/java/com/bkromhout/minerva/TaggingActivity.java
package com.bkromhout.minerva; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.support.v7.view.ActionMode; import android.support.v7.widget.ButtonBarLayout; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import com.afollestad.materialdialogs.MaterialDialog; import com.bkromhout.minerva.adapters.TagCardAdapter; import com.bkromhout.minerva.events.TagCardClickEvent; import com.bkromhout.minerva.realm.RBook; import com.bkromhout.minerva.realm.RTag; import com.bkromhout.minerva.util.Util; import com.bkromhout.realmrecyclerview.RealmRecyclerView; import com.google.common.collect.Lists; import com.jakewharton.rxbinding.widget.RxTextView; import com.jakewharton.rxbinding.widget.TextViewTextChangeEvent; import difflib.Delta; import difflib.DiffUtils; import difflib.Patch; import io.realm.Case; import io.realm.Realm; import io.realm.RealmResults; import io.realm.Sort; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import rx.Observer; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; /** * Activity used to apply (and remove) tags to (and from) books. */ public class TaggingActivity extends AppCompatActivity implements ActionMode.Callback { // Views. @Bind(R.id.toolbar) Toolbar toolbar; @Bind(R.id.recycler) RealmRecyclerView recyclerView; @Bind(R.id.tag_filter) EditText filter; @Bind(R.id.buttons) ButtonBarLayout buttons; @Bind(R.id.cancel) Button btnCancel; @Bind(R.id.save) Button btnSave; /** * Instance of {@link TaggingHelper}. */ private TaggingHelper taggingHelper; /** * Instance of Realm. */ private Realm realm; /** * The list of {@link RTag}s being shown. */ private RealmResults<RTag> items; /** * Recycler view adapter. */ private TagCardAdapter adapter; /** * Filter edit text change subscription. */ private Subscription filterChangeSub; /** * Convenience method to set up the {@link TaggingHelper} then start this activity from a fragment. * @param fragment The fragment to return a result to. * @param book The selected {@link RBook}. */ public static void start(Fragment fragment, RBook book) { start(fragment, Lists.asList(book, new RBook[] {})); } /** * Convenience method to set up the {@link TaggingHelper} then start this activity from a fragment. * @param fragment The fragment to return a result to. * @param selectedBooks The selected {@link RBook}s. */ public static void start(Fragment fragment, List<RBook> selectedBooks) { TaggingActivity.TaggingHelper.get().init(selectedBooks, RTag.tagListToStringList(RTag.listOfSharedTags(selectedBooks))); fragment.startActivityForResult(new Intent(fragment.getContext(), TaggingActivity.class), C.RC_TAG_ACTIVITY); } /** * Convenience method to set up the {@link TaggingHelper} then start this activity from an activity. * @param activity The activity to return a result to. * @param book The selected {@link RBook}. */ public static void start(Activity activity, RBook book) { start(activity, Lists.asList(book, new RBook[] {})); } /** * Convenience method to set up the {@link TaggingHelper} then start this activity from an activity. * @param activity The activity to return a result to. * @param selectedBooks The selected {@link RBook}s. */ public static void start(Activity activity, List<RBook> selectedBooks) { // Initialize the tagging helper. TaggingActivity.TaggingHelper.get().init(selectedBooks, RTag.tagListToStringList(RTag.listOfSharedTags(selectedBooks))); activity.startActivityForResult(new Intent(activity, TaggingActivity.class), C.RC_TAG_ACTIVITY); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set result as canceled. setResult(RESULT_CANCELED); // Create and bind views. setContentView(R.layout.activity_tagging); ButterKnife.bind(this); // Set up toolbar. setSupportActionBar(toolbar); //noinspection ConstantConditions getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); // Get TaggingHelper, Realm, then set up the rest of UI. taggingHelper = TaggingHelper.get(); realm = Realm.getDefaultInstance(); initUi(); } /** * Init the UI. */ private void initUi() { // Set up filter edit text to have a debounce before it filters the list. filterChangeSub = RxTextView.textChangeEvents(filter) .skip(1) .debounce(500, TimeUnit.MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe(getFilterObserver()); // Set up recycler view. if (taggingHelper.filter.isEmpty()) items = realm.allObjectsSorted(RTag.class, "sortName", Sort.ASCENDING); else applyFilter(taggingHelper.filter); adapter = new TagCardAdapter(this, items); recyclerView.setAdapter(adapter); } @Override public boolean onPrepareOptionsMenu(Menu menu) { Util.forceMenuIcons(menu, this, getClass().getSimpleName()); return super.onPrepareOptionsMenu(menu); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.tagging, menu); return super.onCreateOptionsMenu(menu); } @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } @Override public void onStop() { super.onStop(); EventBus.getDefault().unregister(this); } @Override public void onDestroy() { super.onDestroy(); // Close adapter. if (adapter != null) adapter.close(); // Close Realm. if (realm != null) { realm.close(); realm = null; } // Unsubscribe from filter edit text. if (filterChangeSub != null && !filterChangeSub.isUnsubscribed()) filterChangeSub.unsubscribe(); } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { mode.setTitle(R.string.title_tag_edit_mode); buttons.setVisibility(View.GONE); adapter.setInActionMode(true); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { Util.forceMenuIcons(menu, this, getClass().getSimpleName()); return true; } @Override public void onDestroyActionMode(ActionMode mode) { adapter.setInActionMode(false); buttons.setVisibility(View.VISIBLE); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; case R.id.action_new_tag: new MaterialDialog.Builder(this) .title(R.string.action_new_tag) .content(R.string.new_tag_prompt) .autoDismiss(false) .negativeText(R.string.cancel) .input(R.string.tag_name_hint, 0, false, (dialog, input) -> { String newName = input.toString().trim(); try (Realm iRealm = Realm.getDefaultInstance()) { if (iRealm.where(RTag.class).equalTo("name", newName).findFirst() == null) { // Name is available, create the RTag then dismiss the dialog. iRealm.executeTransaction(tRealm -> tRealm.copyToRealm(new RTag(newName))); dialog.dismiss(); } else { //noinspection ConstantConditions dialog.getInputEditText().setError(C.getStr(R.string.err_name_taken)); } } }) .show(); return true; case R.id.action_edit_tags: startSupportActionMode(this); return true; default: return super.onOptionsItemSelected(item); } } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { default: return false; } } /** * Get the observer to use to handle filter text changes. * @return Filter text change observer */ private Observer<TextViewTextChangeEvent> getFilterObserver() { return new Observer<TextViewTextChangeEvent>() { @Override public void onCompleted() { // Nothing. } @Override public void onError(Throwable e) { // Shouldn't happen, but we'll log it if it does. Log.e("TaggingActivity", "Some error occurred due to the filter observer!"); e.printStackTrace(); } @Override public void onNext(TextViewTextChangeEvent textViewTextChangeEvent) { // Apply filter to items and then update adapter's copy of items. applyFilter(textViewTextChangeEvent.text().toString()); adapter.updateRealmResults(items); } }; } /** * Called when the cancel button is clicked. */ @OnClick(R.id.cancel) void onCancelButtonClicked() { finish(); } /** * Called when the save button is clicked. */ @OnClick(R.id.save) void onSaveButtonClicked() { // Use the two lists to get deltas, then use them to figure out which tags were added and which were removed. Patch<String> patch = DiffUtils.diff(taggingHelper.origCheckedItems, taggingHelper.newCheckedItems); List<String> removedTagNames = getDeltaLines(Delta.TYPE.DELETE, patch.getDeltas()); List<String> addedTagNames = getDeltaLines(Delta.TYPE.INSERT, patch.getDeltas()); // Remove and add the applicable tags. RTag.removeTagsFromBooks(taggingHelper.selectedBooks, RTag.stringListToTagList(removedTagNames, false)); RTag.addTagsToBooks(taggingHelper.selectedBooks, RTag.stringListToTagList(addedTagNames, true)); // Reset the TaggingHelper and finish this activity. taggingHelper = null; TaggingHelper.reset(); setResult(RESULT_OK); finish(); } /** * Take a list of Deltas and return a list of lines which are within deltas of the specified {@code type}. * @param deltaType Type of Delta to pull lines from. * @param deltas List of deltas. * @return List of strings. */ private List<String> getDeltaLines(Delta.TYPE deltaType, List<Delta<String>> deltas) { ArrayList<String> lines = new ArrayList<>(); // Loop through all of the deltas. for (Delta delta : deltas) { // For all of the specified type, add their lines to the list. if (delta.getType().equals(deltaType)) { // Have to look in different places based on the type of delta. if (deltaType == Delta.TYPE.DELETE) //noinspection unchecked lines.addAll(delta.getOriginal().getLines()); else if (deltaType == Delta.TYPE.INSERT) //noinspection unchecked lines.addAll(delta.getRevised().getLines()); } } return lines; } /** * Applies the current filter string by re-querying Realm for a new {@link #items} list. Does NOT update the * adapter. */ private void applyFilter(String filter) { taggingHelper.filter = filter; items = realm.where(RTag.class) .contains("name", filter, Case.INSENSITIVE) .findAllSorted("sortName"); } /** * Called when one of the action buttons is clicked on a tag card. * @param event {@link TagCardClickEvent}. */ @Subscribe public void onTagCardAction(TagCardClickEvent event) { switch (event.getType()) { case RENAME: // Show rename dialog. new MaterialDialog.Builder(this) .title(R.string.title_rename_tag) .content(R.string.rename_tag_prompt) .autoDismiss(false) .negativeText(R.string.cancel) .input(R.string.tag_name_hint, 0, false, (dialog, input) -> { String newName = input.toString().trim(); // If it's the same name, do nothing, just dismiss. if (event.getName().equals(newName)) { dialog.dismiss(); return; } // Get Realm and check if name already exists. try (Realm iRealm = Realm.getDefaultInstance()) { if (iRealm.where(RTag.class).equalTo("name", newName).findFirst() == null) { // Name is available; rename the RTag then dismiss the dialog. // TODO Do we need to manually rename/readd the tags?? iRealm.executeTransaction(tRealm -> { RTag rTag = tRealm.where(RTag.class) .equalTo("name", event.getName()) .findFirst(); rTag.setName(newName); rTag.setSortName(newName.toLowerCase()); }); dialog.dismiss(); } else { // Name already exists, set the error text and _don't_ dismiss the dialog. //noinspection ConstantConditions dialog.getInputEditText().setError(C.getStr(R.string.err_name_taken)); } } }) .show(); break; case DELETE: // Show delete confirm dialog. new MaterialDialog.Builder(this) .title(R.string.title_delete_tag) .content(C.getStr(R.string.delete_tag_prompt, event.getName())) .positiveText(R.string.yes) .negativeText(R.string.no) .onPositive((dialog, which) -> { // Get Realm instance, then delete the list. // TODO do we need to manually loop through the tagged books and remove the tag first??? Realm.getDefaultInstance() .executeTransaction(tRealm -> tRealm .where(RTag.class) .equalTo("name", event.getName()) .findFirst() .removeFromRealm()); // Remove tag name from the lists (if present). TaggingHelper th = TaggingHelper.get(); th.origCheckedItems.remove(event.getName()); th.newCheckedItems.remove(event.getName()); }) .show(); break; } } /** * Class to help us hold complex objects until not needed any longer. */ public static class TaggingHelper { /** * Instance of tagging helper. */ private static TaggingHelper INSTANCE = null; /** * List of {@link RBook}s whose will be modified. */ public List<RBook> selectedBooks; /** * List of originally checked tags. */ public List<String> origCheckedItems; /** * List of finally checked tags. */ public List<String> newCheckedItems; /** * Current filter string. */ public String filter = ""; /** * Get the current instance of {@link TaggingHelper}. * @return {@link TaggingHelper} instance. */ public static TaggingHelper get() { if (INSTANCE == null) reset(); return INSTANCE; } /** * Resets the current {@link TaggingHelper} instance. */ public static void reset() { INSTANCE = new TaggingHelper(); } private TaggingHelper() { selectedBooks = null; origCheckedItems = new ArrayList<>(); newCheckedItems = new ArrayList<>(); } /** * Convenience method for initializing the {@link TaggingHelper}. * @param books List of books. * @param currCheckedItems List of tags to have checked. */ public void init(List<RBook> books, List<String> currCheckedItems) { this.selectedBooks = books; this.origCheckedItems = currCheckedItems; this.newCheckedItems = new ArrayList<>(currCheckedItems); } } }
Stay consistent when renaming
app/src/main/java/com/bkromhout/minerva/TaggingActivity.java
Stay consistent when renaming
<ide><path>pp/src/main/java/com/bkromhout/minerva/TaggingActivity.java <ide> @OnClick(R.id.save) <ide> void onSaveButtonClicked() { <ide> // Use the two lists to get deltas, then use them to figure out which tags were added and which were removed. <del> Patch<String> patch = DiffUtils.diff(taggingHelper.origCheckedItems, taggingHelper.newCheckedItems); <add> Patch<String> patch = DiffUtils.diff(taggingHelper.oldCheckedItems, taggingHelper.newCheckedItems); <ide> List<String> removedTagNames = getDeltaLines(Delta.TYPE.DELETE, patch.getDeltas()); <ide> List<String> addedTagNames = getDeltaLines(Delta.TYPE.INSERT, patch.getDeltas()); <ide> <ide> .content(R.string.rename_tag_prompt) <ide> .autoDismiss(false) <ide> .negativeText(R.string.cancel) <del> .input(R.string.tag_name_hint, 0, false, (dialog, input) -> { <add> .input(C.getStr(R.string.tag_name_hint), event.getName(), false, (dialog, input) -> { <ide> String newName = input.toString().trim(); <ide> <ide> // If it's the same name, do nothing, just dismiss. <ide> // Get Realm and check if name already exists. <ide> try (Realm iRealm = Realm.getDefaultInstance()) { <ide> if (iRealm.where(RTag.class).equalTo("name", newName).findFirst() == null) { <del> // Name is available; rename the RTag then dismiss the dialog. <del> // TODO Do we need to manually rename/readd the tags?? <add> // Name is available; rename the RTag. <ide> iRealm.executeTransaction(tRealm -> { <ide> RTag rTag = tRealm.where(RTag.class) <ide> .equalTo("name", event.getName()) <ide> rTag.setName(newName); <ide> rTag.setSortName(newName.toLowerCase()); <ide> }); <add> <add> // Now make sure that we swap the old name for the new one in the old/new lists. <add> TaggingHelper th = TaggingHelper.get(); <add> if (th.oldCheckedItems.remove(event.getName())) th.oldCheckedItems.add(newName); <add> if (th.newCheckedItems.remove(event.getName())) th.newCheckedItems.add(newName); <add> <ide> dialog.dismiss(); <ide> } else { <ide> // Name already exists, set the error text and _don't_ dismiss the dialog. <ide> <ide> // Remove tag name from the lists (if present). <ide> TaggingHelper th = TaggingHelper.get(); <del> th.origCheckedItems.remove(event.getName()); <add> th.oldCheckedItems.remove(event.getName()); <ide> th.newCheckedItems.remove(event.getName()); <ide> }) <ide> .show(); <ide> /** <ide> * List of originally checked tags. <ide> */ <del> public List<String> origCheckedItems; <add> public List<String> oldCheckedItems; <ide> /** <ide> * List of finally checked tags. <ide> */ <ide> <ide> private TaggingHelper() { <ide> selectedBooks = null; <del> origCheckedItems = new ArrayList<>(); <add> oldCheckedItems = new ArrayList<>(); <ide> newCheckedItems = new ArrayList<>(); <ide> } <ide> <ide> */ <ide> public void init(List<RBook> books, List<String> currCheckedItems) { <ide> this.selectedBooks = books; <del> this.origCheckedItems = currCheckedItems; <add> this.oldCheckedItems = currCheckedItems; <ide> this.newCheckedItems = new ArrayList<>(currCheckedItems); <ide> } <ide> }
Java
apache-2.0
6d911c44b3979159fea32b11ab0fabaa49bf46e2
0
jguerinet/android-utils,jguerinet/android-utils,jguerinet/Suitcase,jguerinet/Suitcase
/* * Copyright 2017 Julien Guerinet * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.guerinet.utils; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.os.Process; import android.support.annotation.ColorInt; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RawRes; import android.support.annotation.StringRes; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v4.graphics.drawable.DrawableCompat; import android.support.v4.util.Pair; import android.util.Log; import android.view.MenuItem; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.UUID; import okio.BufferedSource; import okio.Okio; /** * Static utility classes * @author Julien Guerinet * @since 1.0.0 */ public class Utils { /** * @return Randomly generated UUID */ public static String uuid() { return UUID.randomUUID().toString(); } /** * Displays a toast of short length * * @param context App context * @param message Message to show */ public static void toast(Context context, @StringRes int message) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } /** * Displays a toast of Short length * * @param context App context * @param message Message to show */ public static void toast(Context context, @NonNull String message) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } /** * Opens a given URL * * @param context App context * @param url URL to open */ public static void openURL(Context context, String url) { // Check that http:// or https:// is there if (!url.toLowerCase().startsWith(("http://").toLowerCase()) && !url.toLowerCase().startsWith(("https://").toLowerCase())) { url = "http://" + url; } Intent intent = new Intent(Intent.ACTION_VIEW) .setData(Uri.parse(url)); context.startActivity(intent); } /** * Opens a given PDF * * @param context App context * @param path Path to the PDF * @throws ActivityNotFoundException If no suitable app was found */ public static void openPDF(Context context, Uri path) throws ActivityNotFoundException { // Check if there is a PDF reader PackageManager packageManager = context.getPackageManager(); Intent intent = new Intent(Intent.ACTION_VIEW) .setType("application/pdf"); List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); if (list.size() > 0) { // If there is one, use it intent = new Intent(Intent.ACTION_VIEW) .setDataAndType(path, "application/pdf") .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_GRANT_READ_URI_PERMISSION); context.startActivity(intent); } else { // If not, throw the exception throw new ActivityNotFoundException("No PDF app found"); } } /** * Opens the URL to an app in the Play Store or in the browser if the Play Store does not exist * * @param context App context * @param packageName App package name */ public static void openPlayStoreApp(Context context, String packageName) { try { context.startActivity(new Intent( Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageName))); } catch (ActivityNotFoundException e) { // If the user user dot have the play store installed, open it in their browser openURL(context, "https://play.google.com/store/apps/details?id=" + packageName); } } /** * Opens the URL to the app this context represents in the Play Store of in the browser if the * Play Store does not exist * @param context App context, which will be used to get the package name */ public static void openPlayStoreApp(Context context) { openPlayStoreApp(context, context.getPackageName()); } /** * @param context App context * @return App package info, null if an error */ private static PackageInfo getPackageInfo(Context context) { try { return context.getPackageManager().getPackageInfo(context.getPackageName(), 0); } catch (PackageManager.NameNotFoundException e) { Log.e("Utils", "Package Info not found", e); return null; } } /** * @param context App context * @return App version code */ public static int versionCode(Context context) { PackageInfo info = getPackageInfo(context); return info == null ? -1 : info.versionCode; } /** * @param context App context * @return App version name */ public static String versionName(Context context) { PackageInfo info = getPackageInfo(context); return info == null ? null : info.versionName; } /** * @return The device manufacturer and model */ public static String device() { String model = Build.MODEL; // Add the manufacturer if it's not there already if (!model.startsWith(Build.MANUFACTURER)) { model = Build.MANUFACTURER + " " + model; } return model; } /** * Checks if the passed version is newer than the current version. Assumes the version names * are in the X.X.X format. Will not check if they are less than 3 numbers, will only check * the first 3 if there are more * * @param context App context * @param newVersionName New version name String * @return True if the passed version is more recent, false otherwise */ public static boolean isNewerVersion(Context context, String newVersionName) { String currentVersionName = versionName(context); // Check if they are non null if (currentVersionName == null || newVersionName == null) { return false; } // Split them with periods String[] newVersion = newVersionName.split("."); String[] currentVersion = currentVersionName.split("."); // If they have less than three numbers, we can't continue if (newVersion.length < 3 || currentVersion.length < 3) { return false; } for (int i = 0; i < 3; i ++) { try { int newNumber = Integer.parseInt(newVersion[i]); int currentNumber = Integer.parseInt(currentVersion[i]); if (newNumber > currentNumber) { // New number is higher than the current number: update necessary return true; } else if (newNumber < currentNumber) { // New number is lower than the current number: no update necessary return false; } } catch (Exception e) { // Error parsing the number, return false return false; } } // Current Version is the same as the new version: no update necessary return false; } /** * Tints the drawable with the given color * * @param drawable The drawable to tint * @param color The new color * @return The wrapped drawable with the tint */ public static Drawable setTint(Drawable drawable, @ColorInt int color) { // Wrap the drawable in the compat library drawable = DrawableCompat.wrap(drawable).mutate(); // Tint the drawable with the compat library DrawableCompat.setTint(drawable, color); return drawable; } /** * Tints and sets the image in an {@link ImageView} * * @param imageView The {@link ImageView} with the drawable to tint * @param color The new color */ public static void setTint(ImageView imageView, @ColorInt int color) { imageView.setImageDrawable(setTint(imageView.getDrawable(), color)); } /** * Tints and sets the image on a {@link MenuItem} * * @param item The {@link MenuItem} with the drawable to change * @param color The new color */ public static void setTint(MenuItem item, @ColorInt int color) { item.setIcon(setTint(item.getIcon(), color)); } /** * Tints the compound drawable at the given position of a TextView * * @param textView The TextView with the compound drawable * @param position The position of the compound drawable (0: left, 1: top, 2: right, 3: bottom) * @param color The new color */ public static void setTint(TextView textView, int position, @ColorInt int color) { Drawable drawable = setTint(textView.getCompoundDrawables()[position], color); // Set the drawable back Drawable left = null, top = null, right = null, bottom = null; switch (position) { case 0: left = drawable; break; case 1: top = drawable; break; case 2: right = drawable; break; case 3: bottom = drawable; break; } textView.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom); } /** * Deletes the contents of a folder and possibly the folder itself * * @param folder The folder to recursively delete * @param deleteFolder True if the parent folder should be deleted as well, false otherwise */ @SuppressWarnings("ResultOfMethodCallIgnored") public static void deleteFolderContents(File folder, boolean deleteFolder) { File[] files = folder.listFiles(); if (files != null) { // Go through the folder's files for (File f: files) { if (f.isDirectory()) { // Recursively call this method if the file is a folder deleteFolderContents(f, true); } else { // Delete the file if it is a file f.delete(); } } } // Only delete the folder if necessary if (deleteFolder) { folder.delete(); } } /** * @param folder The folder to recursively delete */ @SuppressWarnings("ResultOfMethodCallIgnored") public static void deleteFolder(File folder) { deleteFolderContents(folder, true); } /** * Returns a folder from the external files directory, creates it before returning it * if it doesn't exist * * @param context App context * @param folderName Folder name * @param type Folder type * @return The folder */ @SuppressWarnings("ResultOfMethodCallIgnored") public static File getFolder(Context context, String folderName, @Nullable String type) { File folder = new File(context.getExternalFilesDir(type), folderName); // Create it if it doesn't exist already or it isn't a directory if (!folder.exists() || !folder.isDirectory()) { folder.mkdirs(); } return folder; } /** * Returns URL params in a String format * * @param params List of name-value pairs containing all of the keys and associated * values * @return The query String */ public static String getQuery(List<Pair<String, String>> params) { try { StringBuilder result = new StringBuilder(); boolean first = true; // Add the original '?' result.append("?"); // Go through the pairs for (Pair<String, String> pair : params) { if (first) { // First only happens once to avoid the first '&' first = false; } else { // If not first, add the & to chain them together result.append("&"); } // Append the key and value result.append(URLEncoder.encode(pair.first, "UTF-8")); result.append("="); result.append(URLEncoder.encode(pair.second, "UTF-8")); } return result.toString(); } catch (UnsupportedEncodingException e) { Log.e("Utils", "Unsupported encoding while getting the query params", e); return ""; } } /** * @param manager The {@link ConnectivityManager} instance * @return True if the user is connected to the internet, false otherwise */ public static boolean isConnected(ConnectivityManager manager) { NetworkInfo info = manager.getActiveNetworkInfo(); return info != null && info.isConnectedOrConnecting(); } /** * @param context App context * @return True if the user is connected to the internet, false otherwise */ public static boolean isConnected(Context context) { ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); return isConnected(manager); } /** * Returns a BufferedSource for a file in the raw folder (can be used with Moshi for example) * * @param context App context * @param fileId Resource Id of the file to read from the raw folder * @return The {@link BufferedSource} */ public static BufferedSource sourceFromRaw(Context context, @RawRes int fileId) { return Okio.buffer(Okio.source(context.getResources().openRawResource(fileId))); } /** * Reads a String from a file in the raw folder * * @param context App context * @param fileId Resource Id of the file to read from the raw folder * @return The contents of the file in String format */ public static String stringFromRaw(Context context, @RawRes int fileId) { try { return sourceFromRaw(context, fileId).readUtf8(); } catch (IOException e) { Log.e("Utils", "Error reading String from raw", e); } return null; } /** * Returns the resource Id for a given attribute Id to set an attribute programmatically * * @param context App context * @param attributeId Attribute Id * @return Corresponding resource Id */ public static int getResourceFromAttributes(Context context, int attributeId) { // Get the attribute in a TypedArray form int[] attrs = new int[]{attributeId}; TypedArray typedArray = context.obtainStyledAttributes(attrs); // Extract the resource Id int backgroundResource = typedArray.getResourceId(0, 0); // Recycle the typedArray typedArray.recycle(); return backgroundResource; } /** * Gets the logs and saves them to the given file * Note: Okio is needed for this * * @param file File to write the logs in * @throws IOException */ public static void getLogs(File file) throws IOException { // Get an input stream java.lang.Process process = Runtime.getRuntime().exec("logcat -v time -d " + Process.myPid()); BufferedSource source = Okio.buffer(Okio.source(process.getInputStream())); StringBuilder builder = new StringBuilder(); List<String> logs = new ArrayList<>(); // Read from the source line by line String string; while ((string = source.readUtf8Line()) != null) { logs.add(string); } // Close the source source.close(); // Only keep the last 500 lines int index = 0; if (logs.size() > 500) { index = logs.size() - 500; } // Append the lines one by one with a line break in between for (; index < logs.size(); index ++) { builder.append(logs.get(index)); builder.append("\n"); } // Clear the list of logs logs.clear(); // If a copy already exists, delete it if (file.exists()) { //noinspection ResultOfMethodCallIgnored file.delete(); } // Write everything to the file Okio.buffer(Okio.sink(file)).writeUtf8(builder.toString()).flush(); } /* MARSHMALLOW PERMISSIONS */ /** * Checks if a given permission is granted * * @param context App context * @param permission Permission to check * @return True if the permission is granted, false otherwise */ @SuppressWarnings("BooleanMethodIsAlwaysInverted") public static boolean isPermissionGranted(Context context, String permission) { return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED; } /** * Checks if the given permission has been granted, and requests it if it hasn't * * @param activity Calling activity * @param permission Permission needed * @param requestCode Request code to use if we need to ask for the permission * @return True if the permission has already been granted, false otherwise */ public static boolean requestPermission(Activity activity, String permission, int requestCode) { // Check that we have the permission if (!isPermissionGranted(activity, permission)) { // Request the permission ActivityCompat.requestPermissions(activity, new String[]{permission}, requestCode); return false; } // If we already have the permission, return true return true; } }
library/src/main/java/com/guerinet/utils/Utils.java
/* * Copyright 2016 Julien Guerinet * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.guerinet.utils; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.os.Process; import android.support.annotation.ColorInt; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RawRes; import android.support.annotation.StringRes; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v4.graphics.drawable.DrawableCompat; import android.support.v4.util.Pair; import android.util.Log; import android.view.MenuItem; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import okio.BufferedSource; import okio.Okio; /** * Static utility classes * @author Julien Guerinet * @since 1.0.0 */ public class Utils { /** * Displays a toast of short length * * @param context App context * @param message Message to show */ public static void toast(Context context, @StringRes int message) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } /** * Displays a toast of Short length * * @param context App context * @param message Message to show */ public static void toast(Context context, @NonNull String message) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } /** * Opens a given URL * * @param context App context * @param url URL to open */ public static void openURL(Context context, String url) { // Check that http:// or https:// is there if (!url.toLowerCase().startsWith(("http://").toLowerCase()) && !url.toLowerCase().startsWith(("https://").toLowerCase())) { url = "http://" + url; } Intent intent = new Intent(Intent.ACTION_VIEW) .setData(Uri.parse(url)); context.startActivity(intent); } /** * Opens a given PDF * * @param context App context * @param path Path to the PDF * @throws ActivityNotFoundException If no suitable app was found */ public static void openPDF(Context context, Uri path) throws ActivityNotFoundException { // Check if there is a PDF reader PackageManager packageManager = context.getPackageManager(); Intent intent = new Intent(Intent.ACTION_VIEW) .setType("application/pdf"); List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); if (list.size() > 0) { // If there is one, use it intent = new Intent(Intent.ACTION_VIEW) .setDataAndType(path, "application/pdf") .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_GRANT_READ_URI_PERMISSION); context.startActivity(intent); } else { // If not, throw the exception throw new ActivityNotFoundException("No PDF app found"); } } /** * Opens the URL to an app in the Play Store or in the browser if the Play Store does not exist * * @param context App context * @param packageName App package name */ public static void openPlayStoreApp(Context context, String packageName) { try { context.startActivity(new Intent( Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageName))); } catch (ActivityNotFoundException e) { // If the user user dot have the play store installed, open it in their browser openURL(context, "https://play.google.com/store/apps/details?id=" + packageName); } } /** * Opens the URL to the app this context represents in the Play Store of in the browser if the * Play Store does not exist * @param context App context, which will be used to get the package name */ public static void openPlayStoreApp(Context context) { openPlayStoreApp(context, context.getPackageName()); } /** * @param context App context * @return App package info, null if an error */ private static PackageInfo getPackageInfo(Context context) { try { return context.getPackageManager().getPackageInfo(context.getPackageName(), 0); } catch (PackageManager.NameNotFoundException e) { Log.e("Utils", "Package Info not found", e); return null; } } /** * @param context App context * @return App version code */ public static int versionCode(Context context) { PackageInfo info = getPackageInfo(context); return info == null ? -1 : info.versionCode; } /** * @param context App context * @return App version name */ public static String versionName(Context context) { PackageInfo info = getPackageInfo(context); return info == null ? null : info.versionName; } /** * @return The device manufacturer and model */ public static String device() { String model = Build.MODEL; // Add the manufacturer if it's not there already if (!model.startsWith(Build.MANUFACTURER)) { model = Build.MANUFACTURER + " " + model; } return model; } /** * Checks if the passed version is newer than the current version. Assumes the version names * are in the X.X.X format. Will not check if they are less than 3 numbers, will only check * the first 3 if there are more * * @param context App context * @param newVersionName New version name String * @return True if the passed version is more recent, false otherwise */ public static boolean isNewerVersion(Context context, String newVersionName) { String currentVersionName = versionName(context); // Check if they are non null if (currentVersionName == null || newVersionName == null) { return false; } // Split them with periods String[] newVersion = newVersionName.split("."); String[] currentVersion = currentVersionName.split("."); // If they have less than three numbers, we can't continue if (newVersion.length < 3 || currentVersion.length < 3) { return false; } for (int i = 0; i < 3; i ++) { try { int newNumber = Integer.parseInt(newVersion[i]); int currentNumber = Integer.parseInt(currentVersion[i]); if (newNumber > currentNumber) { // New number is higher than the current number: update necessary return true; } else if (newNumber < currentNumber) { // New number is lower than the current number: no update necessary return false; } } catch (Exception e) { // Error parsing the number, return false return false; } } // Current Version is the same as the new version: no update necessary return false; } /** * Tints the drawable with the given color * * @param drawable The drawable to tint * @param color The new color * @return The wrapped drawable with the tint */ public static Drawable setTint(Drawable drawable, @ColorInt int color) { // Wrap the drawable in the compat library drawable = DrawableCompat.wrap(drawable).mutate(); // Tint the drawable with the compat library DrawableCompat.setTint(drawable, color); return drawable; } /** * Tints and sets the image in an {@link ImageView} * * @param imageView The {@link ImageView} with the drawable to tint * @param color The new color */ public static void setTint(ImageView imageView, @ColorInt int color) { imageView.setImageDrawable(setTint(imageView.getDrawable(), color)); } /** * Tints and sets the image on a {@link MenuItem} * * @param item The {@link MenuItem} with the drawable to change * @param color The new color */ public static void setTint(MenuItem item, @ColorInt int color) { item.setIcon(setTint(item.getIcon(), color)); } /** * Tints the compound drawable at the given position of a TextView * * @param textView The TextView with the compound drawable * @param position The position of the compound drawable (0: left, 1: top, 2: right, 3: bottom) * @param color The new color */ public static void setTint(TextView textView, int position, @ColorInt int color) { Drawable drawable = setTint(textView.getCompoundDrawables()[position], color); // Set the drawable back Drawable left = null, top = null, right = null, bottom = null; switch (position) { case 0: left = drawable; break; case 1: top = drawable; break; case 2: right = drawable; break; case 3: bottom = drawable; break; } textView.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom); } /** * Deletes the contents of a folder and possibly the folder itself * * @param folder The folder to recursively delete * @param deleteFolder True if the parent folder should be deleted as well, false otherwise */ @SuppressWarnings("ResultOfMethodCallIgnored") public static void deleteFolderContents(File folder, boolean deleteFolder) { File[] files = folder.listFiles(); if (files != null) { // Go through the folder's files for (File f: files) { if (f.isDirectory()) { // Recursively call this method if the file is a folder deleteFolderContents(f, true); } else { // Delete the file if it is a file f.delete(); } } } // Only delete the folder if necessary if (deleteFolder) { folder.delete(); } } /** * @param folder The folder to recursively delete */ @SuppressWarnings("ResultOfMethodCallIgnored") public static void deleteFolder(File folder) { deleteFolderContents(folder, true); } /** * Returns a folder from the external files directory, creates it before returning it * if it doesn't exist * * @param context App context * @param folderName Folder name * @param type Folder type * @return The folder */ @SuppressWarnings("ResultOfMethodCallIgnored") public static File getFolder(Context context, String folderName, @Nullable String type) { File folder = new File(context.getExternalFilesDir(type), folderName); // Create it if it doesn't exist already or it isn't a directory if (!folder.exists() || !folder.isDirectory()) { folder.mkdirs(); } return folder; } /** * Returns URL params in a String format * * @param params List of name-value pairs containing all of the keys and associated * values * @return The query String */ public static String getQuery(List<Pair<String, String>> params) { try { StringBuilder result = new StringBuilder(); boolean first = true; // Add the original '?' result.append("?"); // Go through the pairs for (Pair<String, String> pair : params) { if (first) { // First only happens once to avoid the first '&' first = false; } else { // If not first, add the & to chain them together result.append("&"); } // Append the key and value result.append(URLEncoder.encode(pair.first, "UTF-8")); result.append("="); result.append(URLEncoder.encode(pair.second, "UTF-8")); } return result.toString(); } catch (UnsupportedEncodingException e) { Log.e("Utils", "Unsupported encoding while getting the query params", e); return ""; } } /** * @param manager The {@link ConnectivityManager} instance * @return True if the user is connected to the internet, false otherwise */ public static boolean isConnected(ConnectivityManager manager) { NetworkInfo info = manager.getActiveNetworkInfo(); return info != null && info.isConnectedOrConnecting(); } /** * @param context App context * @return True if the user is connected to the internet, false otherwise */ public static boolean isConnected(Context context) { ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); return isConnected(manager); } /** * Returns a BufferedSource for a file in the raw folder (can be used with Moshi for example) * * @param context App context * @param fileId Resource Id of the file to read from the raw folder * @return The {@link BufferedSource} */ public static BufferedSource sourceFromRaw(Context context, @RawRes int fileId) { return Okio.buffer(Okio.source(context.getResources().openRawResource(fileId))); } /** * Reads a String from a file in the raw folder * * @param context App context * @param fileId Resource Id of the file to read from the raw folder * @return The contents of the file in String format */ public static String stringFromRaw(Context context, @RawRes int fileId) { try { return sourceFromRaw(context, fileId).readUtf8(); } catch (IOException e) { Log.e("Utils", "Error reading String from raw", e); } return null; } /** * Returns the resource Id for a given attribute Id to set an attribute programmatically * * @param context App context * @param attributeId Attribute Id * @return Corresponding resource Id */ public static int getResourceFromAttributes(Context context, int attributeId) { // Get the attribute in a TypedArray form int[] attrs = new int[]{attributeId}; TypedArray typedArray = context.obtainStyledAttributes(attrs); // Extract the resource Id int backgroundResource = typedArray.getResourceId(0, 0); // Recycle the typedArray typedArray.recycle(); return backgroundResource; } /** * Gets the logs and saves them to the given file * Note: Okio is needed for this * * @param file File to write the logs in * @throws IOException */ public static void getLogs(File file) throws IOException { // Get an input stream java.lang.Process process = Runtime.getRuntime().exec("logcat -v time -d " + Process.myPid()); BufferedSource source = Okio.buffer(Okio.source(process.getInputStream())); StringBuilder builder = new StringBuilder(); List<String> logs = new ArrayList<>(); // Read from the source line by line String string; while ((string = source.readUtf8Line()) != null) { logs.add(string); } // Close the source source.close(); // Only keep the last 500 lines int index = 0; if (logs.size() > 500) { index = logs.size() - 500; } // Append the lines one by one with a line break in between for (; index < logs.size(); index ++) { builder.append(logs.get(index)); builder.append("\n"); } // Clear the list of logs logs.clear(); // If a copy already exists, delete it if (file.exists()) { //noinspection ResultOfMethodCallIgnored file.delete(); } // Write everything to the file Okio.buffer(Okio.sink(file)).writeUtf8(builder.toString()).flush(); } /* MARSHMALLOW PERMISSIONS */ /** * Checks if a given permission is granted * * @param context App context * @param permission Permission to check * @return True if the permission is granted, false otherwise */ @SuppressWarnings("BooleanMethodIsAlwaysInverted") public static boolean isPermissionGranted(Context context, String permission) { return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED; } /** * Checks if the given permission has been granted, and requests it if it hasn't * * @param activity Calling activity * @param permission Permission needed * @param requestCode Request code to use if we need to ask for the permission * @return True if the permission has already been granted, false otherwise */ public static boolean requestPermission(Activity activity, String permission, int requestCode) { // Check that we have the permission if (!isPermissionGranted(activity, permission)) { // Request the permission ActivityCompat.requestPermissions(activity, new String[]{permission}, requestCode); return false; } // If we already have the permission, return true return true; } }
Added method to generate a UUID
library/src/main/java/com/guerinet/utils/Utils.java
Added method to generate a UUID
<ide><path>ibrary/src/main/java/com/guerinet/utils/Utils.java <ide> /* <del> * Copyright 2016 Julien Guerinet <add> * Copyright 2017 Julien Guerinet <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import java.net.URLEncoder; <ide> import java.util.ArrayList; <ide> import java.util.List; <add>import java.util.UUID; <ide> <ide> import okio.BufferedSource; <ide> import okio.Okio; <ide> * @since 1.0.0 <ide> */ <ide> public class Utils { <add> <add> /** <add> * @return Randomly generated UUID <add> */ <add> public static String uuid() { <add> return UUID.randomUUID().toString(); <add> } <ide> <ide> /** <ide> * Displays a toast of short length
Java
bsd-3-clause
1d770852eb72c3ee1190dc68dc568f17704c6de8
0
ndexbio/ndex-rest,ndexbio/ndex-rest,ndexbio/ndex-rest,ndexbio/ndex-rest
package org.ndexbio.rest.services; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.List; import java.util.UUID; import javax.annotation.security.PermitAll; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.commons.io.FilenameUtils; import org.jboss.resteasy.annotations.providers.multipart.MultipartForm; import org.ndexbio.common.access.NdexDatabase; import org.ndexbio.common.access.NetworkAOrientDBDAO; import org.ndexbio.common.models.dao.orientdb.Helper; import org.ndexbio.common.models.dao.orientdb.NetworkDAO; import org.ndexbio.common.models.dao.orientdb.NetworkDAOTx; import org.ndexbio.common.models.dao.orientdb.NetworkDocDAO; import org.ndexbio.common.models.dao.orientdb.NetworkSearchDAO; import org.ndexbio.common.models.dao.orientdb.TaskDAO; import org.ndexbio.model.exceptions.NdexException; import org.ndexbio.model.exceptions.ObjectNotFoundException; import org.ndexbio.model.exceptions.UnauthorizedOperationException; import org.ndexbio.model.network.query.EdgeCollectionQuery; import org.ndexbio.model.object.Membership; import org.ndexbio.model.object.NdexPropertyValuePair; import org.ndexbio.model.object.NdexProvenanceEventType; import org.ndexbio.model.object.Permissions; import org.ndexbio.model.object.Priority; import org.ndexbio.model.object.ProvenanceEntity; import org.ndexbio.model.object.ProvenanceEvent; import org.ndexbio.model.object.SimpleNetworkQuery; import org.ndexbio.model.object.SimplePathQuery; import org.ndexbio.model.object.SimplePropertyValuePair; import org.ndexbio.model.object.Status; import org.ndexbio.model.object.Task; import org.ndexbio.model.object.TaskType; import org.ndexbio.model.object.User; import org.ndexbio.common.models.object.network.RawNamespace; import org.ndexbio.common.persistence.orientdb.NdexNetworkCloneService; import org.ndexbio.common.persistence.orientdb.NdexPersistenceService; import org.ndexbio.common.persistence.orientdb.PropertyGraphLoader; import org.ndexbio.common.query.NetworkFilterQueryExecutor; import org.ndexbio.common.query.NetworkFilterQueryExecutorFactory; import org.ndexbio.common.util.NdexUUIDFactory; //import org.ndexbio.model.object.SearchParameters; import org.ndexbio.model.object.network.BaseTerm; import org.ndexbio.model.object.network.FileFormat; import org.ndexbio.model.object.network.Namespace; import org.ndexbio.model.object.network.Network; import org.ndexbio.model.object.network.NetworkSummary; import org.ndexbio.model.object.network.PropertyGraphNetwork; import org.ndexbio.model.object.network.VisibilityType; import org.ndexbio.rest.annotations.ApiDoc; import org.ndexbio.rest.helpers.UploadedFile; import org.ndexbio.task.Configuration; import org.ndexbio.task.NdexServerQueue; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import com.orientechnologies.orient.core.record.impl.ODocument; import org.slf4j.Logger; @Path("/network") public class NetworkAService extends NdexService { static Logger logger = LoggerFactory.getLogger(NetworkAService.class); static private final String readOnlyParameter = "readOnly"; public NetworkAService(@Context HttpServletRequest httpRequest) { super(httpRequest); } /* * * Operations returning or setting Network Elements * */ @PermitAll @GET @Path("/{networkId}/baseTerm/{skipBlocks}/{blockSize}") @Produces("application/json") @ApiDoc("Retrieves a list of BaseTerm objects from the network specified by 'networkId'. The maximum number of " + "BaseTerm objects to retrieve in the query is set by 'blockSize' (which may be any number chosen by the " + "user) while 'skipBlocks' specifies the number of blocks that have already been read.") public List<BaseTerm> getBaseTerms( @PathParam("networkId") final String networkId, @PathParam("skipBlocks") final int skipBlocks, @PathParam("blockSize") final int blockSize) throws IllegalArgumentException, NdexException { logger.info(userNameForLog() + "[start: Getting BaseTerm objects from network " + networkId + ", skipBlocks " + skipBlocks + ", blockSize " + blockSize + "]"); ODatabaseDocumentTx db = null; try { db = NdexDatabase.getInstance().getAConnection(); NetworkDAO daoNew = new NetworkDAO(db); return (List<BaseTerm>) daoNew.getBaseTerms(networkId); } finally { if ( db != null) db.close(); logger.info(userNameForLog() + "[end: Got BaseTerm objects from network " + networkId + ", skipBlocks " + skipBlocks + ", blockSize " + blockSize + "]"); } } @PermitAll @GET @Path("/{networkId}/namespace/{skipBlocks}/{blockSize}") @Produces("application/json") @ApiDoc("Retrieves a list of Namespace objects from the network specified by 'networkId'. The maximum number of " + "Namespace objects to retrieve in the query is set by 'blockSize' (which may be any number chosen by the " + "user) while 'skipBlocks' specifies the number of blocks that have already been read.") public List<Namespace> getNamespaces( @PathParam("networkId") final String networkId, @PathParam("skipBlocks") final int skipBlocks, @PathParam("blockSize") final int blockSize) throws IllegalArgumentException, NdexException { logger.info(userNameForLog() + "[start: Getting list of namespaces for network " + networkId + ", skipBlocks " + skipBlocks + ", blockSize " + blockSize + "]"); ODatabaseDocumentTx db = null; try { db = NdexDatabase.getInstance().getAConnection(); NetworkDAO daoNew = new NetworkDAO(db); return (List<Namespace>) daoNew.getNamespaces(networkId); } finally { if ( db != null) db.close(); logger.info(userNameForLog() + "[end: Got list of namespaces for network " + networkId + ", skipBlocks " + skipBlocks + ", blockSize " + blockSize + "]"); } } @POST @Path("/{networkId}/namespace") @Produces("application/json") @ApiDoc("Adds the POSTed Namespace object to the network specified by 'networkId'.") public void addNamespace( @PathParam("networkId") final String networkId, final Namespace namespace ) throws IllegalArgumentException, NdexException, IOException { logger.info(userNameForLog() + "[start: Adding namespace to the network " + networkId + "]"); NdexDatabase db = null; NdexPersistenceService networkService = null; try { db = NdexDatabase.getInstance(); networkService = new NdexPersistenceService( db, UUID.fromString(networkId)); //networkService.get networkService.getNamespace(new RawNamespace(namespace.getPrefix(), namespace.getUri())); //DW: Handle provenance ProvenanceEntity oldProv = networkService.getNetworkProvenance(); ProvenanceEntity newProv = new ProvenanceEntity(); newProv.setUri( oldProv.getUri() ); Helper.populateProvenanceEntity(newProv, networkService.getCurrentNetwork()); Timestamp now = new Timestamp(Calendar.getInstance().getTimeInMillis()); ProvenanceEvent event = new ProvenanceEvent(NdexProvenanceEventType.ADD_NAMESPACE, now); List<SimplePropertyValuePair> eventProperties = new ArrayList<>(); Helper.addUserInfoToProvenanceEventProperties( eventProperties, this.getLoggedInUser()); String namespaceString = namespace.getPrefix() + " : " + namespace.getUri(); eventProperties.add( new SimplePropertyValuePair("namespace", namespaceString)); event.setProperties(eventProperties); List<ProvenanceEntity> oldProvList = new ArrayList<>(); oldProvList.add(oldProv); event.setInputs(oldProvList); newProv.setCreationEvent(event); networkService.setNetworkProvenance(newProv); networkService.commit(); networkService.close(); } finally { if (networkService != null) networkService.close(); logger.info(userNameForLog() + "[end: Added namespace to the network " + networkId + "]"); } } /************************************************************************** * Returns network provenance. * @throws IOException * @throws JsonMappingException * @throws JsonParseException * @throws NdexException * **************************************************************************/ @PermitAll @GET @Path("/{networkId}/provenance") @Produces("application/json") @ApiDoc("Retrieves the 'provenance' field of the network specified by 'networkId' as a ProvenanceEntity object, " + "if it exists. The ProvenanceEntity object is expected to represent the current state of the network and" + " to contain a tree-structure of ProvenanceEvent and ProvenanceEntity objects that describe the networks " + "provenance history.") public ProvenanceEntity getProvenance( @PathParam("networkId") final String networkId) throws IllegalArgumentException, JsonParseException, JsonMappingException, IOException, NdexException { logger.info(userNameForLog() + "[start: Getting provenance of network " + networkId + "]"); if ( ! isSearchable(networkId) ) throw new UnauthorizedOperationException("Network " + networkId + " is not readable to this user."); try (NetworkDocDAO daoNew = new NetworkDocDAO()) { return daoNew.getProvenance(UUID.fromString(networkId)); } finally { logger.info(userNameForLog() + "[end: Got provenance of network " + networkId + "]"); } } /************************************************************************** * Updates network provenance. * @throws Exception * **************************************************************************/ @PUT @Path("/{networkId}/provenance") @Produces("application/json") @ApiDoc("Updates the 'provenance' field of the network specified by 'networkId' to be the ProvenanceEntity object" + " in the PUT data. The ProvenanceEntity object is expected to represent the current state of the network" + " and to contain a tree-structure of ProvenanceEvent and ProvenanceEntity objects that describe the " + "networks provenance history.") public ProvenanceEntity setProvenance(@PathParam("networkId")final String networkId, final ProvenanceEntity provenance) throws Exception { logger.info(userNameForLog() + "[start: Updating provenance of network " + networkId + "]"); ODatabaseDocumentTx db = null; NetworkDAO daoNew = null; try { db = NdexDatabase.getInstance().getAConnection(); User user = getLoggedInUser(); if ( !Helper.checkPermissionOnNetworkByAccountName(db, networkId, user.getAccountName(), Permissions.WRITE)) { logger.error(userNameForLog() + "[end: No write permissions for user account " + user.getAccountName() + " on network " + networkId + "]"); throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } daoNew = new NetworkDAO(db); if(daoNew.networkIsReadOnly(networkId)) { daoNew.close(); logger.info(userNameForLog() + "[end: Can't modify readonly network " + networkId + "]"); throw new NdexException ("Can't update readonly network."); } UUID networkUUID = UUID.fromString(networkId); daoNew.setProvenance(networkUUID, provenance); daoNew.commit(); return daoNew.getProvenance(networkUUID); } catch (Exception e) { if (null != daoNew) daoNew.rollback(); logger.error(userNameForLog() + "[end: Updating provenance of network " + networkId + ". Exception caught:]", e); throw e; } finally { if (null != db) db.close(); logger.info(userNameForLog() + "[end: Updated provenance of network " + networkId + "]"); } } /************************************************************************** * Sets network properties. * @throws Exception * **************************************************************************/ @PUT @Path("/{networkId}/properties") @Produces("application/json") @ApiDoc("Updates the 'properties' field of the network specified by 'networkId' to be the list of " + "NdexPropertyValuePair objects in the PUT data.") public int setNetworkProperties( @PathParam("networkId")final String networkId, final List<NdexPropertyValuePair> properties) throws Exception { logger.info(userNameForLog() + "[start: Updating properties of network " + networkId + "]"); ODatabaseDocumentTx db = null; NetworkDAO daoNew = null; try { db = NdexDatabase.getInstance().getAConnection(); User user = getLoggedInUser(); if ( !Helper.checkPermissionOnNetworkByAccountName(db, networkId, user.getAccountName(), Permissions.WRITE)) { logger.error(userNameForLog() + "[end: No write permissions for user account " + user.getAccountName() + " on network " + networkId + "]"); throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } daoNew = new NetworkDAO(db); if(daoNew.networkIsReadOnly(networkId)) { daoNew.close(); logger.info(userNameForLog() + "[end: Can't delete readonly network " + networkId + "]"); throw new NdexException ("Can't update readonly network."); } UUID networkUUID = UUID.fromString(networkId); int i = daoNew.setNetworkProperties(networkUUID, properties); //DW: Handle provenance ProvenanceEntity oldProv = daoNew.getProvenance(networkUUID); ProvenanceEntity newProv = new ProvenanceEntity(); newProv.setUri( oldProv.getUri() ); Helper.populateProvenanceEntity(newProv, daoNew, networkId); NetworkSummary summary = daoNew.getNetworkSummary(daoNew.getRecordByUUIDStr(networkId, null)); Helper.populateProvenanceEntity(newProv, summary); ProvenanceEvent event = new ProvenanceEvent(NdexProvenanceEventType.SET_NETWORK_PROPERTIES, summary.getModificationTime()); List<SimplePropertyValuePair> eventProperties = new ArrayList<>(); Helper.addUserInfoToProvenanceEventProperties( eventProperties, user); for( NdexPropertyValuePair vp : properties ) { SimplePropertyValuePair svp = new SimplePropertyValuePair(vp.getPredicateString(), vp.getValue()); eventProperties.add(svp); } event.setProperties(eventProperties); List<ProvenanceEntity> oldProvList = new ArrayList<>(); oldProvList.add(oldProv); event.setInputs(oldProvList); newProv.setCreationEvent(event); daoNew.setProvenance(networkUUID, newProv); daoNew.commit(); //logInfo(logger, "Finished updating properties of network " + networkId); return i; } catch (Exception e) { //logger.severe("Error occurred when update network properties: " + e.getMessage()); //e.printStackTrace(); if (null != daoNew) daoNew.rollback(); logger.error(userNameForLog() + "[end: Updating properties of network " + networkId + ". Exception caught:]", e); throw new NdexException(e.getMessage()); } finally { if (null != db) db.close(); logger.info(userNameForLog() + "[end: Updated properties of network " + networkId + "]"); } } @PUT @Path("/{networkId}/presentationProperties") @Produces("application/json") @ApiDoc("Updates the'presentationProperties' field of the network specified by 'networkId' to be the list of " + "SimplePropertyValuePair objects in the PUT data.") public int setNetworkPresentationProperties( @PathParam("networkId")final String networkId, final List<SimplePropertyValuePair> properties) throws Exception { logger.info(userNameForLog() + "[start: Updating presentationProperties field of network " + networkId + "]"); ODatabaseDocumentTx db = null; NetworkDAO daoNew = null; try { db = NdexDatabase.getInstance().getAConnection(); User user = getLoggedInUser(); if ( !Helper.checkPermissionOnNetworkByAccountName(db, networkId, user.getAccountName(), Permissions.WRITE)) { logger.error(userNameForLog() + "[end: No write permissions for user account " + user.getAccountName() + " on network " + networkId + "]"); throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } daoNew = new NetworkDAO(db); UUID networkUUID = UUID.fromString(networkId); if(daoNew.networkIsReadOnly(networkId)) { daoNew.close(); logger.info(userNameForLog() + "[end: Can't delete readonly network " + networkId + "]"); throw new NdexException ("Can't update readonly network."); } int i = daoNew.setNetworkPresentationProperties(networkUUID, properties); //DW: Handle provenance ProvenanceEntity oldProv = daoNew.getProvenance(networkUUID); ProvenanceEntity newProv = new ProvenanceEntity(); newProv.setUri( oldProv.getUri() ); NetworkSummary summary = daoNew.getNetworkSummary(daoNew.getRecordByUUIDStr(networkId, null)); Helper.populateProvenanceEntity(newProv, summary); ProvenanceEvent event = new ProvenanceEvent(NdexProvenanceEventType.SET_PRESENTATION_PROPERTIES, summary.getModificationTime()); List<SimplePropertyValuePair> eventProperties = new ArrayList<>(); Helper.addUserInfoToProvenanceEventProperties( eventProperties, user); for( SimplePropertyValuePair vp : properties ) { SimplePropertyValuePair svp = new SimplePropertyValuePair(vp.getName(), vp.getValue()); eventProperties.add(svp); } event.setProperties(eventProperties); List<ProvenanceEntity> oldProvList = new ArrayList<>(); oldProvList.add(oldProv); event.setInputs(oldProvList); newProv.setCreationEvent(event); daoNew.setProvenance(networkUUID, newProv); daoNew.commit(); return i; } catch (Exception e) { if (null != daoNew) { daoNew.rollback(); daoNew = null; } logger.error(userNameForLog() + "[end: Updating presentationProperties field of network " + networkId + ". Exception caught:]", e); throw e; } finally { if (null != db) db.close(); logger.info(userNameForLog() + "[end: Updated presentationProperties field of network " + networkId + "]"); } } /* * * Operations returning Networks * */ @PermitAll @GET @Path("/{networkId}") @Produces("application/json") @ApiDoc("Retrieves a NetworkSummary object based on the network specified by 'networkUUID'. This method returns " + "an error if the network is not found or if the authenticated user does not have READ permission for the " + "network.") public NetworkSummary getNetworkSummary( @PathParam("networkId") final String networkId) throws IllegalArgumentException, NdexException { logger.info(userNameForLog() + "[start: Getting networkSummary of network " + networkId + "]"); ODatabaseDocumentTx db = null; try { db = NdexDatabase.getInstance().getAConnection(); NetworkDocDAO networkDocDao = new NetworkDocDAO(db); VisibilityType vt = Helper.getNetworkVisibility(db, networkId); boolean hasPrivilege = (vt == VisibilityType.PUBLIC || vt== VisibilityType.DISCOVERABLE); if ( !hasPrivilege && getLoggedInUser() != null) { hasPrivilege = networkDocDao.checkPrivilege(getLoggedInUser().getAccountName(), networkId, Permissions.READ); } if ( hasPrivilege) { ODocument doc = networkDocDao.getNetworkDocByUUIDString(networkId); if (doc == null) throw new ObjectNotFoundException("Network with ID: " + networkId + " doesn't exist."); NetworkSummary summary = NetworkDocDAO.getNetworkSummary(doc); db.close(); db = null; //logInfo(logger, "NetworkSummary of " + networkId + " returned."); return summary; } } finally { if (db != null) db.close(); logger.info(userNameForLog() + "[end: Got networkSummary of network " + networkId + "]"); } logger.error(userNameForLog() + "[end: Getting networkSummary of network " + networkId + " Throwing WebApplicationException exception ...]"); throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } @PermitAll @GET @Path("/{networkId}/edge/asNetwork/{skipBlocks}/{blockSize}") @Produces("application/json") @ApiDoc("Retrieves a subnetwork of a network based on a block (where a block is simply a contiguous set) of edges" + ". The network is specified by 'networkId' and the maximum number of edges to retrieve in the query is " + "set by 'blockSize' (which may be any number chosen by the user) while 'skipBlocks' specifies the " + "number of blocks that have already been read. The subnetwork is returned as a Network object containing " + "the Edge objects specified by the query along with all of the other network elements relevant to the " + "edges. (Compare this method to getPropertyGraphEdges).\n") public Network getEdges( @PathParam("networkId") final String networkId, @PathParam("skipBlocks") final int skipBlocks, @PathParam("blockSize") final int blockSize) throws IllegalArgumentException, NdexException { logger.info(userNameForLog() + "[start: Getting edges of network " + networkId + ", skipBlocks " + skipBlocks + ", blockSize " + blockSize +"]"); ODatabaseDocumentTx db = null; try { db = NdexDatabase.getInstance().getAConnection(); NetworkDAO dao = new NetworkDAO(db); Network n = dao.getNetwork(UUID.fromString(networkId), skipBlocks, blockSize); return n; } finally { if ( db !=null) db.close(); logger.info(userNameForLog() + "[end: Got edges of network " + networkId + ", skipBlocks " + skipBlocks + ", blockSize " + blockSize +"]"); } } @PermitAll @GET @Path("/{networkId}/asNetwork") // @Produces("application/json") @ApiDoc("Retrieve an entire network specified by 'networkId' as a Network object. (Compare this method to " + "getCompleteNetworkAsPropertyGraph).") // new Implmentation to handle cached network public Response getCompleteNetwork( @PathParam("networkId") final String networkId) throws IllegalArgumentException, NdexException { logger.info(userNameForLog() + "[start: Getting complete network " + networkId + "]"); if ( isSearchable(networkId) ) { ODatabaseDocumentTx db = NdexDatabase.getInstance().getAConnection(); NetworkDAO daoNew = new NetworkDAO(db); NetworkSummary sum = daoNew.getNetworkSummaryById(networkId); long commitId = sum.getReadOnlyCommitId(); if ( commitId > 0 && commitId == sum.getReadOnlyCacheId()) { daoNew.close(); try { FileInputStream in = new FileInputStream( Configuration.getInstance().getNdexNetworkCachePath() + commitId +".gz") ; setZipFlag(); logger.info(userNameForLog() + "[end: return cached network " + networkId + "]"); return Response.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(in).build(); } catch (IOException e) { throw new NdexException ("Ndex server can't find file: " + e.getMessage()); } } Network n = daoNew.getNetworkById(UUID.fromString(networkId)); daoNew.close(); logger.info(userNameForLog() + "[end: return complete network " + networkId + "]"); return Response.ok(n,MediaType.APPLICATION_JSON_TYPE).build(); } else throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } @PermitAll @GET @Path("/export/{networkId}/{format}") @Produces("application/json") @ApiDoc("Retrieve an entire network specified by 'networkId' as a Network object. (Compare this method to " + "getCompleteNetworkAsPropertyGraph).") public String exportNetwork( @PathParam("networkId") final String networkId, @PathParam("format") final String format) throws NdexException { logger.info(userNameForLog() + "[start: request to export network " + networkId + "]"); if ( isSearchable(networkId) ) { String networkName =null; try (NetworkDAO networkdao = new NetworkDAO(NdexDatabase.getInstance().getAConnection())){ networkName = networkdao.getNetworkSummaryById(networkId).getName(); } Task exportNetworkTask = new Task(); exportNetworkTask.setTaskType(TaskType.EXPORT_NETWORK_TO_FILE); exportNetworkTask.setPriority(Priority.LOW); exportNetworkTask.setResource(networkId); exportNetworkTask.setStatus(Status.QUEUED); exportNetworkTask.setDescription("Export network \""+ networkName + "\" in " + format + " format"); try { exportNetworkTask.setFormat(FileFormat.valueOf(format)); } catch ( Exception e) { throw new NdexException ("Invalid network format for network export."); } try (TaskDAO taskDAO = new TaskDAO(NdexDatabase.getInstance().getAConnection()) ){ UUID taskId = taskDAO.createTask(getLoggedInUser().getAccountName(),exportNetworkTask); taskDAO.commit(); logger.info(userNameForLog() + "[end: task created to export network " + networkId + "]"); return taskId.toString(); } catch (Exception e) { logger.error(userNameForLog() + "[end: Exception caught:]", e); throw new NdexException(e.getMessage()); } } throw new UnauthorizedOperationException("User doesn't have read access to this network."); } @PermitAll @GET @Path("/{networkId}/asPropertyGraph") @Produces("application/json") @ApiDoc("Retrieves an entire network specified by 'networkId' as a PropertyGraphNetwork object. A user may wish " + "to retrieve a PropertyGraphNetwork rather than an ordinary Network when the would like to work with the " + "network with a table-oriented data structure, for example, an R or Python data frame. (Compare this " + "method to getCompleteNetwork).") public PropertyGraphNetwork getCompleteNetworkAsPropertyGraph( @PathParam("networkId") final String networkId) throws IllegalArgumentException, NdexException, JsonProcessingException { logger.info(userNameForLog() + "[start: Retrieving an entire network " + networkId + "as a PropertyGraphNetwork object]"); if ( isSearchable(networkId) ) { ODatabaseDocumentTx db =null; try { db = NdexDatabase.getInstance().getAConnection(); NetworkDAO daoNew = new NetworkDAO(db); PropertyGraphNetwork n = daoNew.getProperytGraphNetworkById(UUID.fromString(networkId)); return n; } finally { if (db !=null ) db.close(); logger.info(userNameForLog() + "[end: Retrieved an entire network " + networkId + "as a PropertyGraphNetwork object]"); } } else { logger.error(userNameForLog() + "[end: Retrieving an entire network " + networkId + "as a PropertyGraphNetwork object. Throwing WebApplicationException exception ...]"); throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } } @PermitAll @GET @Path("/{networkId}/edge/asPropertyGraph/{skipBlocks}/{blockSize}") @Produces("application/json") @ApiDoc("Retrieves a subnetwork of a network based on a block (where a block is simply a contiguous set) of edges" + ". The network is specified by 'networkId' and the maximum number of edges to retrieve in the query is " + "set by 'blockSize' (which may be any number chosen by the user) while 'skipBlocks' specifies number of " + "blocks that have already been read. The subnetwork is returned as a PropertyGraphNetwork object " + "containing the PropertyGraphEdge objects specified by the query along with all of the PropertyGraphNode " + "objects and network information relevant to the edges. (Compare this method to getEdges).") public PropertyGraphNetwork getPropertyGraphEdges( @PathParam("networkId") final String networkId, @PathParam("skipBlocks") final int skipBlocks, @PathParam("blockSize") final int blockSize) throws IllegalArgumentException, NdexException { logger.info(userNameForLog() + "[start: Retrieving a subnetwork of network " + networkId + " with skipBlocks " + skipBlocks + " and blockSize " + blockSize + "]"); ODatabaseDocumentTx db = NdexDatabase.getInstance().getAConnection(); NetworkDAO dao = new NetworkDAO(db); PropertyGraphNetwork n = dao.getProperytGraphNetworkById(UUID.fromString(networkId),skipBlocks, blockSize); db.close(); logger.info(userNameForLog() + "[end: Retrieved a subnetwork of network " + networkId + " with skipBlocks " + skipBlocks + " and blockSize " + blockSize + "]"); return n; } /************************************************************************** * Retrieves array of user membership objects * * @param networkId * The network ID. * @throws IllegalArgumentException * Bad input. * @throws ObjectNotFoundException * The group doesn't exist. * @throws NdexException * Failed to query the database. **************************************************************************/ @GET @PermitAll @Path("/{networkId}/user/{permission}/{skipBlocks}/{blockSize}") @Produces("application/json") @ApiDoc("Retrieves a list of Membership objects which specify user permissions for the network specified by " + "'networkId'. The value of the 'permission' parameter constrains the type of the returned Membership " + "objects and may take the following set of values: READ, WRITE, and ADMIN. Memberships of all types can " + "be retrieved by permission = 'ALL'. The maximum number of Membership objects to retrieve in the query " + "is set by 'blockSize' (which may be any number chosen by the user) while 'skipBlocks' specifies the " + "number of blocks that have already been read.") public List<Membership> getNetworkUserMemberships(@PathParam("networkId") final String networkId, @PathParam("permission") final String permissions , @PathParam("skipBlocks") int skipBlocks, @PathParam("blockSize") int blockSize) throws NdexException { //logInfo( logger, "Get all " + permissions + " accounts on network " + networkId); logger.info(userNameForLog() + "[start: Get all " + permissions + "accounts on network " + networkId + ", skipBlocks " + skipBlocks + " blockSize " + blockSize + "]"); Permissions permission = Permissions.valueOf(permissions.toUpperCase()); ODatabaseDocumentTx db = null; try { db = NdexDatabase.getInstance().getAConnection(); NetworkDAO networkDao = new NetworkDAO(db); List<Membership> results = networkDao.getNetworkUserMemberships( UUID.fromString(networkId), permission, skipBlocks, blockSize); //logInfo(logger, results.size() + " members returned for network " + networkId); logger.info(userNameForLog() + "[end: Got " + results.size() + " members returned for network " + networkId + "]"); return results; } finally { if (db != null) db.close(); } } @DELETE @Path("/{networkId}/member/{userUUID}") @Produces("application/json") @ApiDoc("Removes any permission for the network specified by 'networkId' for the user specified by 'userUUID': it" + " deletes any Membership object that specifies a permission for the user-network combination. This method" + " will return an error if the authenticated user making the request does not have sufficient permissions " + "to make the deletion or if the network or user is not found. Removal is also denied if it would leave " + "the network without any user having ADMIN permissions: NDEx does not permit networks to become 'orphans'" + " without any owner.") public int deleteNetworkMembership( @PathParam("networkId") final String networkId, @PathParam("userUUID") final String userUUID ) throws IllegalArgumentException, NdexException { logger.info(userNameForLog() + "[start: Removing any permissions for network " + networkId + " for user " + userUUID + "]"); ODatabaseDocumentTx db = null; try { db = NdexDatabase.getInstance().getAConnection(); User user = getLoggedInUser(); NetworkDAO networkDao = new NetworkDAO(db); if (!Helper.isAdminOfNetwork(db, networkId, user.getExternalId().toString())) { logger.error(userNameForLog() + "[end: User " + userUUID + " not an admin of network " + networkId + ". Throwing WebApplicationException exception ...]"); throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } int count = networkDao.revokePrivilege(networkId, userUUID); db.commit(); logger.info(userNameForLog() + "[end: Removed any permissions for network " + networkId + " for user " + userUUID + "]"); return count; } finally { if (db != null) db.close(); } } /* * * Operations on Network permissions * */ @POST @Path("/{networkId}/member") @Produces("application/json") @ApiDoc("POSTs a Membership object to update the permission of a user specified by userUUID for the network " + "specified by networkUUID. The permission is updated to the value specified in the 'permission' field of " + "the Membership. This method returns 1 if the update is performed and 0 if the update is redundant, " + "where the user already has the specified permission. It also returns an error if the authenticated user " + "making the request does not have sufficient permissions or if the network or user is not found. It also " + "returns an error if it would leave the network without any user having ADMIN permissions: NDEx does not " + "permit networks to become 'orphans' without any owner.") public int updateNetworkMembership( @PathParam("networkId") final String networkId, final Membership membership ) throws IllegalArgumentException, NdexException { logger.info(userNameForLog() + "[start: Updating membership for network " + networkId + "]"); ODatabaseDocumentTx db = null; try { db = NdexDatabase.getInstance().getAConnection(); User user = getLoggedInUser(); NetworkDAO networkDao = new NetworkDAO(db); if (!Helper.isAdminOfNetwork(db, networkId, user.getExternalId().toString())) { logger.error(userNameForLog() + "[end: User " + user.getExternalId().toString() + " not an admin of network " + networkId + ". Throwing WebApplicationException exception ...]"); throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } int count = networkDao.grantPrivilege(networkId, membership.getMemberUUID().toString(), membership.getPermissions()); db.commit(); logger.info(userNameForLog() + "[end: Updated membership for network " + networkId + "]"); return count; } finally { if (db != null) db.close(); } } @POST @Path("/{networkId}/summary") @Produces("application/json") @ApiDoc("POSTs a NetworkSummary object to update the pro information of the network specified by networkUUID." + " The NetworkSummary POSTed may be only partially populated. The only fields that will be acted on are: " + "'name', 'description','version', and 'visibility' if they are present.") public void updateNetworkProfile( @PathParam("networkId") final String networkId, final NetworkSummary summary ) throws IllegalArgumentException, NdexException, IOException { logger.info(userNameForLog() + "[start: Updating profile information of network " + networkId + "]"); ODatabaseDocumentTx db = null; try { db = NdexDatabase.getInstance().getAConnection(); User user = getLoggedInUser(); NetworkDAO networkDao = new NetworkDAO(db); if(networkDao.networkIsReadOnly(networkId)) { networkDao.close(); logger.info(userNameForLog() + "[end: Can't modify readonly network " + networkId + "]"); throw new NdexException ("Can't update readonly network."); } if ( !Helper.checkPermissionOnNetworkByAccountName(db, networkId, user.getAccountName(), Permissions.WRITE)) { logger.error(userNameForLog() + "[end: No write permissions for user account " + user.getAccountName() + " on network " + networkId + ". Throwing WebApplicationException exception ...]"); throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } UUID networkUUID = UUID.fromString(networkId); networkDao.updateNetworkProfile(networkUUID, summary); //DW: Handle provenance //Special Logic. Test whether we should record provenance at all. //If the only thing that has changed is the visibility, we should not add a provenance //event. ProvenanceEntity oldProv = networkDao.getProvenance(networkUUID); String oldName = "", oldDescription = "", oldVersion =""; for( SimplePropertyValuePair oldProperty : oldProv.getProperties() ) { if( oldProperty.getName() == null ) continue; if( oldProperty.getName().equals("dc:title") ) oldName = oldProperty.getValue().trim(); else if( oldProperty.getName().equals("description") ) oldDescription = oldProperty.getValue().trim(); else if( oldProperty.getName().equals("version") ) oldVersion = oldProperty.getValue().trim(); } //Treat all summary values that are null like "" String summaryName = summary.getName() == null ? "" : summary.getName().trim(); String summaryDescription = summary.getDescription() == null ? "" : summary.getDescription().trim(); String summaryVersion = summary.getVersion() == null ? "" : summary.getVersion().trim(); if( !oldName.equals(summaryName) || !oldDescription.equals(summaryDescription) || !oldVersion.equals(summaryVersion) ) { ProvenanceEntity newProv = new ProvenanceEntity(); newProv.setUri(oldProv.getUri()); Helper.populateProvenanceEntity(newProv, networkDao, networkId); ProvenanceEvent event = new ProvenanceEvent(NdexProvenanceEventType.UPDATE_NETWORK_PROFILE, summary.getModificationTime()); List<SimplePropertyValuePair> eventProperties = new ArrayList<>(); Helper.addUserInfoToProvenanceEventProperties(eventProperties, user); if (summary.getName() != null) eventProperties.add(new SimplePropertyValuePair("dc:title", summary.getName())); if (summary.getDescription() != null) eventProperties.add(new SimplePropertyValuePair("description", summary.getDescription())); if (summary.getVersion() != null) eventProperties.add(new SimplePropertyValuePair("version", summary.getVersion())); event.setProperties(eventProperties); List<ProvenanceEntity> oldProvList = new ArrayList<>(); oldProvList.add(oldProv); event.setInputs(oldProvList); newProv.setCreationEvent(event); networkDao.setProvenance(networkUUID, newProv); } db.commit(); } finally { if (db != null) db.close(); logger.info(userNameForLog() + "[end: Updated the pro information for network " + networkId + "]"); } } @PermitAll @POST @Path("/{networkId}/asNetwork/query") @Produces("application/json") @ApiDoc("Retrieves a 'neighborhood' subnetwork of a network based on identifiers specified in a POSTed " + "SimplePathQuery object based on a parameter set by the user. The network to be queried is specified by " + "networkId. In the first step of the query, a set of base terms exactly matching identifiers found in the" + " 'searchString' field of the SimplePathQuery is selected. In the second step, " + "nodes are selected that reference the base terms identified in the network. Finally, " + "a set of edges is selected by traversing outwards from each of these selected nodes, " + "up to the limit specified by the 'searchDepth' field of the SimplePathQuery. The subnetwork is returned" + " as a Network object containing the selected Edge objects along with any other network elements relevant" + " to the edges.") public Network queryNetwork( @PathParam("networkId") final String networkId, final SimplePathQuery queryParameters // @PathParam("skipBlocks") final int skipBlocks, // @PathParam("blockSize") final int blockSize ) throws IllegalArgumentException, NdexException { //logInfo (logger, "Neighborhood search on " + networkId + " with phrase \"" + queryParameters.getSearchString() + "\""); logger.info(userNameForLog() + "[start: Retrieving neighborhood subnetwork for network " + networkId + " with phrase \"" + queryParameters.getSearchString() + "\"]"); try (ODatabaseDocumentTx db = NdexDatabase.getInstance().getAConnection()) { NetworkDAO networkDao = new NetworkDAO(db); VisibilityType vt = Helper.getNetworkVisibility(db, networkId); boolean hasPrivilege = (vt == VisibilityType.PUBLIC ); if ( !hasPrivilege && getLoggedInUser() != null) { hasPrivilege = networkDao.checkPrivilege( (getLoggedInUser() == null ? null : getLoggedInUser().getAccountName()), networkId, Permissions.READ); } if ( hasPrivilege) { NetworkAOrientDBDAO dao = NetworkAOrientDBDAO.getInstance(); Network n = dao.queryForSubnetwork(networkId, queryParameters); //logInfo(logger, "Subnetwork from query returned." ); logger.info(userNameForLog() + "[end: Subnetwork for network " + networkId + " with phrase \"" + queryParameters.getSearchString() + "\" retrieved]"); return n; //getProperytGraphNetworkById(UUID.fromString(networkId),skipBlocks, blockSize); } logger.error(userNameForLog() + "[end: Retrieving neighborhood subnetwork for network " + networkId + " with phrase \"" + queryParameters.getSearchString() + "\". Throwing WebApplicationException exception ...]"); throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } } @PermitAll @POST @Path("/{networkId}/asNetwork/prototypeNetworkQuery") @Produces("application/json") @ApiDoc("Retrieves a 'neighborhood' subnetwork of a network based on identifiers specified in a POSTed " + "SimplePathQuery object based on a parameter set by the user. The network to be queried is specified by " + "networkId. In the first step of the query, a set of base terms exactly matching identifiers found in the" + " 'searchString' field of the SimplePathQuery is selected. In the second step, " + "nodes are selected that reference the base terms identified in the network. Finally, " + "a set of edges is selected by traversing outwards from each of these selected nodes, " + "up to the limit specified by the 'searchDepth' field of the SimplePathQuery. The subnetwork is returned" + " as a Network object containing the selected Edge objects along with any other network elements relevant" + " to the edges.") public Network queryNetworkByEdgeFilter( @PathParam("networkId") final String networkId, final EdgeCollectionQuery query ) throws IllegalArgumentException, NdexException { logger.info(userNameForLog() + "[start: filter query on network " + networkId + "\"]"); if ( !isSearchable(networkId ) ) { throw new UnauthorizedOperationException("Network is not readable to this user."); } NetworkFilterQueryExecutor queryExecutor = NetworkFilterQueryExecutorFactory.createODBExecutor(networkId, query); Network result = queryExecutor.evaluate(); logger.info(userNameForLog() + "[end: filter query on network " + networkId + "\"]"); return result; } private boolean isSearchable(String networkId) throws ObjectNotFoundException, NdexException { try ( NetworkDocDAO networkDao = new NetworkDocDAO() ) { VisibilityType vt = Helper.getNetworkVisibility(networkDao.getDBConnection(), networkId); boolean hasPrivilege = (vt == VisibilityType.PUBLIC ); if ( !hasPrivilege && getLoggedInUser() != null) { hasPrivilege = networkDao.checkPrivilege( (getLoggedInUser() == null ? null : getLoggedInUser().getAccountName()), networkId, Permissions.READ); } return hasPrivilege; } } @PermitAll @POST @Path("/{networkId}/asPropertyGraph/query") @Produces("application/json") @ApiDoc("Retrieves a 'neighborhood' subnetwork of a network based on identifiers specified in a POSTed " + "SimplePathQuery object. The network is specified by networkId. In the first step of the query, " + "a set of base terms exactly matching identifiers found in the searchString of the SimplePathQuery is " + "selected. In the second step, nodes are selected that reference the base terms identified in the network" + ". Finally, a set of edges is selected by traversing outwards from each of these selected nodes, " + "up to the limit specified by the 'searchDepth' field of the SimplePathQuery. The subnetwork is returned" + " as a PropertyGraphNetwork object containing the selected PropertyGraphEdge objects along with any other" + " network information relevant to the edges.") public PropertyGraphNetwork queryNetworkAsPropertyGraph( @PathParam("networkId") final String networkId, final SimplePathQuery queryParameters // @PathParam("skipBlocks") final int skipBlocks, // @PathParam("blockSize") final int blockSize ) throws IllegalArgumentException, NdexException { logger.info(userNameForLog() + "[start: Retrieving neighborhood subnetwork for network " + networkId + " based on SimplePathQuery object]"); ODatabaseDocumentTx db = null; try { db = NdexDatabase.getInstance().getAConnection(); NetworkDAO networkDao = new NetworkDAO(db); VisibilityType vt = Helper.getNetworkVisibility(db, networkId); boolean hasPrivilege = (vt == VisibilityType.PUBLIC ); if ( !hasPrivilege && getLoggedInUser() != null) { hasPrivilege = networkDao.checkPrivilege( (getLoggedInUser() == null ? null : getLoggedInUser().getAccountName()), networkId, Permissions.READ); } db.close(); db = null; if ( hasPrivilege) { NetworkAOrientDBDAO dao = NetworkAOrientDBDAO.getInstance(); PropertyGraphNetwork n = dao.queryForSubPropertyGraphNetwork(networkId, queryParameters); logger.info(userNameForLog() + "[start: Retrieved neighborhood subnetwork for network " + networkId + " based on SimplePathQuery object]"); return n; } } finally { if ( db !=null) db.close(); } logger.error(userNameForLog() + "[end: Retrieving neighborhood subnetwork for network " + networkId + " based on SimplePathQuery object. Throwing WebApplicationException exception ...]"); throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } /* @PermitAll @POST @Path("/{networkId}/asPropertyGraph/query/{skipBlocks}/{blockSize}") @Produces("application/json") @ApiDoc("Retrieves a 'neighborhood' subnetwork of a network based on identifiers specified in a POSTed " + "SimplePathQuery object . The network is specified by networkId and the maximum number of edges to " + "retrieve in the query is set by 'blockSize' (which may be any number chosen by the user) while " + "'skipBlocks' specifies the number of blocks that have already been read before performing the next read." + " In the first step of the query, a set of base terms exactly matching identifiers found in the " + "searchString of the SimplePathQuery is selected. In the second step, nodes are selected that reference " + "the base terms identified in the network. Finally, a set of edges is selected by traversing outwards " + "from each of these selected nodes, up to the limit specified by the 'searchDepth' field of the " + "SimplePathQuery. The subnetwork is returned as a PropertyGraphNetwork object containing the selected " + "PropertyGraphEdge objects along with any other network information relevant to the edges.") public PropertyGraphNetwork queryNetworkAsPropertyGraph( @PathParam("networkId") final String networkId, final NetworkQueryParameters queryParameters, @PathParam("skipBlocks") final int skipBlocks, @PathParam("blockSize") final int blockSize) throws IllegalArgumentException, NdexException, JsonProcessingException { ODatabaseDocumentTx db = NdexAOrientDBConnectionPool.getInstance().acquire(); NetworkDAO dao = new NetworkDAO(db); PropertyGraphNetwork n = dao.getProperytGraphNetworkById(UUID.fromString(networkId)); db.close(); return n; } */ /* * * Network Search * */ @POST @PermitAll @Path("/search/{skipBlocks}/{blockSize}") @Produces("application/json") @ApiDoc("Returns a list of NetworkSummary objects based on a POSTed NetworkQuery object. The NetworkQuery may be " + "either a NetworkSimpleQuery specifying only a search string or a NetworkMembershipQuery that also " + "constrains the search to networks administered by a user or group. The maximum number of NetworkSummary " + "objects to retrieve in the query is set by 'blockSize' (which may be any number chosen by the user) " + "while 'skipBlocks' specifies number of blocks that have already been read.") public Collection<NetworkSummary> searchNetwork( final SimpleNetworkQuery query, @PathParam("skipBlocks") final int skipBlocks, @PathParam("blockSize") final int blockSize) throws IllegalArgumentException, NdexException { //logInfo ( logger, "Search networks: \"" + query.getSearchString() + "\""); logger.info(userNameForLog() + "[start: Retrieving NetworkSummary objects using query \"" + query.getSearchString() + "\"]"); if(query.getAccountName() != null) query.setAccountName(query.getAccountName().toLowerCase()); try (ODatabaseDocumentTx db = NdexDatabase.getInstance().getAConnection()) { NetworkSearchDAO dao = new NetworkSearchDAO(db); Collection<NetworkSummary> result = new ArrayList <> (); result = dao.findNetworks(query, skipBlocks, blockSize, this.getLoggedInUser()); //logInfo ( logger, result.size() + " networks returned from search."); logger.info(userNameForLog() + "[end: Retrieved " + result.size() + " NetworkSummary objects]"); return result; } catch (Exception e) { //e.printStackTrace(); //logger.error(userNameForLog() + "[end: Updating properties of network " + networkId + " Exception caught: " + e + "]"); logger.error(userNameForLog() + "[end: Retrieving NetworkSummary objects using query \"" + query.getSearchString() + "\". Exception caught:]", e); throw new NdexException(e.getMessage()); } } @POST @Path("/asPropertyGraph") @Produces("application/json") @ApiDoc("Creates a new network based on a POSTed NetworkPropertyGraph object. This method errors if the " + "NetworkPropertyGraph object is not provided or if it does not specify a name. It also errors if the " + "NetworkPropertyGraph object is larger than a maximum size for network creation set in the NDEx server " + "configuration. A NetworkSummary object for the new network is returned.") public NetworkSummary createNetwork(final PropertyGraphNetwork newNetwork) throws Exception { Preconditions .checkArgument(null != newNetwork, "A network is required"); Preconditions.checkArgument( !Strings.isNullOrEmpty(newNetwork.getName()), "A network name is required"); logger.info(userNameForLog() + "[start: Creating a new network based on a POSTed NetworkPropertyGraph object]"); NdexDatabase db = NdexDatabase.getInstance(); PropertyGraphLoader pgl = null; pgl = new PropertyGraphLoader(db); NetworkSummary ns = pgl.insertNetwork(newNetwork, getLoggedInUser()); logger.info(userNameForLog() + "[end: Created a new network based on a POSTed NetworkPropertyGraph object]"); return ns; } /* comment out this function for now, until we can make this function thread safe. * @PUT @Path("/asPropertyGraph") @Produces("application/json") @ApiDoc("Updates an existing network using a PUT call using a NetworkPropertyGraph object. The NetworkPropertyGraph object must contain a " + "UUID (this would normally be the case for a NetworkPropertyGraph object retrieved from NDEx, " + "so no additional work is required in the most common case) and the user must have permission to modify " + "this network. This method errors if the NetworkPropertyGraph object is not provided or if it does not have a valid " + "UUID on the server. It also errors if the NetworkPropertyGraph object is larger than a maximum size for network " + "creation set in the NDEx server configuration. A NetworkSummary object is returned.") public NetworkSummary updateNetwork(final PropertyGraphNetwork newNetwork) throws Exception { Preconditions .checkArgument(null != newNetwork, "A network is required"); Preconditions.checkArgument( !Strings.isNullOrEmpty(newNetwork.getName()), "A network name is required"); NdexDatabase db = new NdexDatabase(Configuration.getInstance().getHostURI()); PropertyGraphLoader pgl = null; ODatabaseDocumentTx conn = null; try { conn = db.getAConnection(); User user = getLoggedInUser(); String uuidStr = null; for ( NdexPropertyValuePair p : newNetwork.getProperties()) { if ( p.getPredicateString().equals ( PropertyGraphNetwork.uuid) ) { uuidStr = p.getValue(); break; } } if ( uuidStr == null) throw new NdexException ("updateNetwork: UUID not found in PropertyGraph."); if (!Helper.checkPermissionOnNetworkByAccountName(conn, uuidStr, user.getAccountName(), Permissions.WRITE)) { throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } pgl = new PropertyGraphLoader(db); return pgl.updateNetwork(newNetwork); } finally { if (db!=null) db.close(); if( conn!=null) conn.close(); } } */ @POST @Path("/asNetwork") @Produces("application/json") @ApiDoc("Creates a new network based on a POSTed Network object. This method errors if the Network object is not " + "provided or if it does not specify a name. It also errors if the Network object is larger than a maximum" + " size for network creation set in the NDEx server configuration. A NetworkSummary object is returned.") public NetworkSummary createNetwork(final Network newNetwork) throws Exception { Preconditions .checkArgument(null != newNetwork, "A network is required"); Preconditions.checkArgument( !Strings.isNullOrEmpty(newNetwork.getName()), "A network name is required"); logger.info(userNameForLog() + "[start: Creating a new network based on a POSTed Network object]"); NdexDatabase db = NdexDatabase.getInstance(); NdexNetworkCloneService service = null; try { newNetwork.setVisibility(VisibilityType.PRIVATE); service = new NdexNetworkCloneService(db, newNetwork, getLoggedInUser().getAccountName()); NetworkSummary summary = service.cloneNetwork(); //DW: Provenance ProvenanceEntity entity = new ProvenanceEntity(); entity.setUri(summary.getURI()); Helper.populateProvenanceEntity(entity, summary); ProvenanceEvent event = new ProvenanceEvent(NdexProvenanceEventType.PROGRAM_UPLOAD, summary.getModificationTime()); List<SimplePropertyValuePair> eventProperties = new ArrayList<>(); Helper.addUserInfoToProvenanceEventProperties( eventProperties, this.getLoggedInUser()); event.setProperties(eventProperties); entity.setCreationEvent(event); service.setNetworkProvenance(entity); logger.info(userNameForLog() + "[end: Created a new network based on a POSTed Network object]"); return summary; } finally { if ( service !=null) service.close(); } } @PUT @Path("/asNetwork") @Produces("application/json") @ApiDoc("Updates an existing network using a PUT call using a Network object. The Network object must contain a " + "UUID (this would normally be the case for a Network object retrieved from NDEx, " + "so no additional work is required in the most common case) and the user must have permission to modify " + "this network. This method errors if the Network object is not provided or if it does not have a valid " + "UUID on the server. It also errors if the Network object is larger than a maximum size for network " + "creation set in the NDEx server configuration. A NetworkSummary object is returned.") public NetworkSummary updateNetwork(final Network newNetwork) throws Exception { Preconditions .checkArgument(null != newNetwork, "A network is required"); Preconditions.checkArgument( !Strings.isNullOrEmpty(newNetwork.getName()), "A network name is required"); try ( ODatabaseDocumentTx conn = NdexDatabase.getInstance().getAConnection() ) { User user = getLoggedInUser(); if (!Helper.checkPermissionOnNetworkByAccountName(conn, newNetwork.getExternalId().toString(), user.getAccountName(), Permissions.WRITE)) { throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } NetworkDocDAO daoNew = new NetworkDocDAO(conn); if(daoNew.networkIsReadOnly(newNetwork.getExternalId().toString())) { daoNew.close(); logger.info(userNameForLog() + "[end: Can't update readonly network " + newNetwork.getExternalId().toString() + "]"); throw new NdexException ("Can't modify readonly network."); } } try ( NdexNetworkCloneService service = new NdexNetworkCloneService(NdexDatabase.getInstance(), newNetwork, getLoggedInUser().getAccountName()) ) { return service.updateNetwork(); } } @DELETE @Path("/{UUID}") @Produces("application/json") @ApiDoc("Deletes the network specified by 'UUID'.") public void deleteNetwork(final @PathParam("UUID") String id) throws NdexException { logger.info(userNameForLog() + "[start: Deleting network " + id + "]"); String userAcc = getLoggedInUser().getAccountName(); //logInfo(logger, "Deleting network " + id); ODatabaseDocumentTx db = null; try{ db = NdexDatabase.getInstance().getAConnection(); if (!Helper.checkPermissionOnNetworkByAccountName(db, id, userAcc, Permissions.ADMIN)) { throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } try (NetworkDAO networkDao = new NetworkDAO(db)) { if(networkDao.networkIsReadOnly(id)) { logger.info(userNameForLog() + "[end: Can't delete readonly network " + id + "]"); throw new NdexException ("Can't delete readonly network."); } //logger.info("Start deleting network " + id); networkDao.logicalDeleteNetwork(id); networkDao.commit(); Task task = new Task(); task.setTaskType(TaskType.SYSTEM_DELETE_NETWORK); task.setResource(id); NdexServerQueue.INSTANCE.addSystemTask(task); } db = null; logger.info(userNameForLog() + "[end: Deleted network " + id + "]"); //logger.info("Network " + id + " deleted."); } finally { if ( db != null) db.close(); } } /************************************************************************** * Saves an uploaded network file. Determines the type of file uploaded, * saves the file, and creates a task. * * @param uploadedNetwork * The uploaded network file. * @throws IllegalArgumentException * Bad input. * @throws NdexException * Failed to parse the file, or create the network in the * database. **************************************************************************/ /* * refactored to support non-transactional database operations */ @POST @Path("/upload") @Consumes("multipart/form-data") @Produces("application/json") @ApiDoc("Upload a network file into the current users NDEx account. This can take some time while background " + "processing converts the data from the file into the common NDEx format. This method errors if the " + "network is missing or if it has no filename or no file data.") public void uploadNetwork(@MultipartForm UploadedFile uploadedNetwork) throws IllegalArgumentException, SecurityException, NdexException { logger.info(userNameForLog() + "[start: Uploading network file]"); try { Preconditions .checkNotNull(uploadedNetwork, "A network is required"); Preconditions.checkState( !Strings.isNullOrEmpty(uploadedNetwork.getFilename()), "A file name containg the network data is required"); Preconditions.checkNotNull(uploadedNetwork.getFileData(), "Network file data is required"); Preconditions.checkState(uploadedNetwork.getFileData().length > 0, "The file data is empty"); } catch (Exception e1) { logger.error(userNameForLog() + "[end: Uploading network file. Exception caught:]", e1 ); throw new NdexException(e1.getMessage()); } String ext = FilenameUtils.getExtension(uploadedNetwork.getFilename()).toLowerCase(); if ( !ext.equals("sif") && !ext.equals("xbel") && !ext.equals("xgmml") && !ext.equals("owl") && !ext.equals("xls") && ! ext.equals("xlsx")) { logger.error(userNameForLog() + "[end: The uploaded file type is not supported; must be Excel, XGMML, SIF, BioPAX or XBEL. Throwing IllegalArgumentException...]"); throw new NdexException( "The uploaded file type is not supported; must be Excel, XGMML, SIF, BioPAX or XBEL."); } UUID taskId = NdexUUIDFactory.INSTANCE.getNDExUUID(); final File uploadedNetworkPath = new File(Configuration.getInstance().getNdexRoot() + "/uploaded-networks"); if (!uploadedNetworkPath.exists()) uploadedNetworkPath.mkdir(); String fileFullPath = uploadedNetworkPath.getAbsolutePath() + "/" + taskId + "." + ext; final File uploadedNetworkFile = new File(fileFullPath); if (!uploadedNetworkFile.exists()) try { uploadedNetworkFile.createNewFile(); } catch (IOException e1) { //e1.printStackTrace(); logger.error(userNameForLog() + "[end: Failed to create file " + fileFullPath + " on server when uploading " + uploadedNetwork.getFilename() + ". Exception caught:]", e1); throw new NdexException ("Failed to create file " + fileFullPath + " on server when uploading " + uploadedNetwork.getFilename() + ": " + e1.getMessage()); } try ( FileOutputStream saveNetworkFile = new FileOutputStream(uploadedNetworkFile)) { saveNetworkFile.write(uploadedNetwork.getFileData()); saveNetworkFile.flush(); } catch (IOException e1) { //e1.printStackTrace(); logger.error(userNameForLog() + "[end: Failed to write content to file " + fileFullPath + " on server when uploading " + uploadedNetwork.getFilename() + ". Exception caught:]", e1 ); throw new NdexException ("Failed to write content to file " + fileFullPath + " on server when uploading " + uploadedNetwork.getFilename() + ": " + e1.getMessage()); } final String userAccount = this.getLoggedInUser().getAccountName(); Task processNetworkTask = new Task(); processNetworkTask.setExternalId(taskId); processNetworkTask.setDescription(uploadedNetwork.getFilename()); processNetworkTask.setTaskType(TaskType.PROCESS_UPLOADED_NETWORK); processNetworkTask.setPriority(Priority.LOW); processNetworkTask.setProgress(0); processNetworkTask.setResource(fileFullPath); processNetworkTask.setStatus(Status.QUEUED); try (TaskDAO dao = new TaskDAO(NdexDatabase.getInstance().getAConnection())){ dao.createTask(userAccount, processNetworkTask); dao.commit(); } catch (IllegalArgumentException iae) { logger.error(userNameForLog() + "[end: Exception caught:]", iae); throw iae; } catch (Exception e) { //Logger.getLogger(this.getClass().getName()).severe("Failed to process uploaded network: " // + uploadedNetwork.getFilename() + ". " + e.getMessage()); logger.error(userNameForLog() + "[end: Exception caught:]", e); throw new NdexException(e.getMessage()); } } @GET @Path("/{networkId}/setFlag/{parameter}={value}") @Produces("application/json") @ApiDoc("Set the certain Ndex system flag onnetwork. Supported parameters are:"+ "readOnly={true|false}") public String setNetworkFlag( @PathParam("networkId") final String networkId, @PathParam("parameter") final String parameter, @PathParam("value") final String value) throws IllegalArgumentException, NdexException { logger.info(userNameForLog() + "[start: Setting " + parameter + "=" + value + " for network " + networkId + "]"); try (ODatabaseDocumentTx db = NdexDatabase.getInstance().getAConnection()){ if (Helper.isAdminOfNetwork(db, networkId, getLoggedInUser().getExternalId().toString())) { if ( parameter.equals(readOnlyParameter)) { boolean bv = Boolean.parseBoolean(value); try (NetworkDAOTx daoNew = new NetworkDAOTx()) { long oldId = daoNew.setReadOnlyFlag(networkId, bv, getLoggedInUser().getAccountName()); logger.info(userNameForLog() + "[end: setting " + parameter + "=" + value + " for network " + networkId + "]"); return Long.toString(oldId); } } } throw new UnauthorizedOperationException("Only an administrator can set a network flag."); } } }
src/main/java/org/ndexbio/rest/services/NetworkAService.java
package org.ndexbio.rest.services; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.List; import java.util.UUID; import javax.annotation.security.PermitAll; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.commons.io.FilenameUtils; import org.jboss.resteasy.annotations.providers.multipart.MultipartForm; import org.ndexbio.common.access.NdexDatabase; import org.ndexbio.common.access.NetworkAOrientDBDAO; import org.ndexbio.common.models.dao.orientdb.Helper; import org.ndexbio.common.models.dao.orientdb.NetworkDAO; import org.ndexbio.common.models.dao.orientdb.NetworkDAOTx; import org.ndexbio.common.models.dao.orientdb.NetworkDocDAO; import org.ndexbio.common.models.dao.orientdb.NetworkSearchDAO; import org.ndexbio.common.models.dao.orientdb.TaskDAO; import org.ndexbio.model.exceptions.NdexException; import org.ndexbio.model.exceptions.ObjectNotFoundException; import org.ndexbio.model.exceptions.UnauthorizedOperationException; import org.ndexbio.model.network.query.EdgeCollectionQuery; import org.ndexbio.model.object.Membership; import org.ndexbio.model.object.NdexPropertyValuePair; import org.ndexbio.model.object.Permissions; import org.ndexbio.model.object.Priority; import org.ndexbio.model.object.ProvenanceEntity; import org.ndexbio.model.object.ProvenanceEvent; import org.ndexbio.model.object.SimpleNetworkQuery; import org.ndexbio.model.object.SimplePathQuery; import org.ndexbio.model.object.SimplePropertyValuePair; import org.ndexbio.model.object.Status; import org.ndexbio.model.object.Task; import org.ndexbio.model.object.TaskType; import org.ndexbio.model.object.User; import org.ndexbio.common.models.object.network.RawNamespace; import org.ndexbio.common.persistence.orientdb.NdexNetworkCloneService; import org.ndexbio.common.persistence.orientdb.NdexPersistenceService; import org.ndexbio.common.persistence.orientdb.PropertyGraphLoader; import org.ndexbio.common.query.NetworkFilterQueryExecutor; import org.ndexbio.common.query.NetworkFilterQueryExecutorFactory; import org.ndexbio.common.util.NdexUUIDFactory; //import org.ndexbio.model.object.SearchParameters; import org.ndexbio.model.object.network.BaseTerm; import org.ndexbio.model.object.network.FileFormat; import org.ndexbio.model.object.network.Namespace; import org.ndexbio.model.object.network.Network; import org.ndexbio.model.object.network.NetworkSummary; import org.ndexbio.model.object.network.PropertyGraphNetwork; import org.ndexbio.model.object.network.VisibilityType; import org.ndexbio.rest.annotations.ApiDoc; import org.ndexbio.rest.helpers.UploadedFile; import org.ndexbio.task.Configuration; import org.ndexbio.task.NdexServerQueue; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import com.orientechnologies.orient.core.record.impl.ODocument; import org.slf4j.Logger; @Path("/network") public class NetworkAService extends NdexService { static Logger logger = LoggerFactory.getLogger(NetworkAService.class); static private final String readOnlyParameter = "readOnly"; public NetworkAService(@Context HttpServletRequest httpRequest) { super(httpRequest); } /* * * Operations returning or setting Network Elements * */ @PermitAll @GET @Path("/{networkId}/baseTerm/{skipBlocks}/{blockSize}") @Produces("application/json") @ApiDoc("Retrieves a list of BaseTerm objects from the network specified by 'networkId'. The maximum number of " + "BaseTerm objects to retrieve in the query is set by 'blockSize' (which may be any number chosen by the " + "user) while 'skipBlocks' specifies the number of blocks that have already been read.") public List<BaseTerm> getBaseTerms( @PathParam("networkId") final String networkId, @PathParam("skipBlocks") final int skipBlocks, @PathParam("blockSize") final int blockSize) throws IllegalArgumentException, NdexException { logger.info(userNameForLog() + "[start: Getting BaseTerm objects from network " + networkId + ", skipBlocks " + skipBlocks + ", blockSize " + blockSize + "]"); ODatabaseDocumentTx db = null; try { db = NdexDatabase.getInstance().getAConnection(); NetworkDAO daoNew = new NetworkDAO(db); return (List<BaseTerm>) daoNew.getBaseTerms(networkId); } finally { if ( db != null) db.close(); logger.info(userNameForLog() + "[end: Got BaseTerm objects from network " + networkId + ", skipBlocks " + skipBlocks + ", blockSize " + blockSize + "]"); } } @PermitAll @GET @Path("/{networkId}/namespace/{skipBlocks}/{blockSize}") @Produces("application/json") @ApiDoc("Retrieves a list of Namespace objects from the network specified by 'networkId'. The maximum number of " + "Namespace objects to retrieve in the query is set by 'blockSize' (which may be any number chosen by the " + "user) while 'skipBlocks' specifies the number of blocks that have already been read.") public List<Namespace> getNamespaces( @PathParam("networkId") final String networkId, @PathParam("skipBlocks") final int skipBlocks, @PathParam("blockSize") final int blockSize) throws IllegalArgumentException, NdexException { logger.info(userNameForLog() + "[start: Getting list of namespaces for network " + networkId + ", skipBlocks " + skipBlocks + ", blockSize " + blockSize + "]"); ODatabaseDocumentTx db = null; try { db = NdexDatabase.getInstance().getAConnection(); NetworkDAO daoNew = new NetworkDAO(db); return (List<Namespace>) daoNew.getNamespaces(networkId); } finally { if ( db != null) db.close(); logger.info(userNameForLog() + "[end: Got list of namespaces for network " + networkId + ", skipBlocks " + skipBlocks + ", blockSize " + blockSize + "]"); } } @POST @Path("/{networkId}/namespace") @Produces("application/json") @ApiDoc("Adds the POSTed Namespace object to the network specified by 'networkId'.") public void addNamespace( @PathParam("networkId") final String networkId, final Namespace namespace ) throws IllegalArgumentException, NdexException, IOException { logger.info(userNameForLog() + "[start: Adding namespace to the network " + networkId + "]"); NdexDatabase db = null; NdexPersistenceService networkService = null; try { db = NdexDatabase.getInstance(); networkService = new NdexPersistenceService( db, UUID.fromString(networkId)); //networkService.get networkService.getNamespace(new RawNamespace(namespace.getPrefix(), namespace.getUri())); //DW: Handle provenance ProvenanceEntity oldProv = networkService.getNetworkProvenance(); ProvenanceEntity newProv = new ProvenanceEntity(); newProv.setUri( oldProv.getUri() ); Helper.populateProvenanceEntity(newProv, networkService.getCurrentNetwork()); Timestamp now = new Timestamp(Calendar.getInstance().getTimeInMillis()); ProvenanceEvent event = new ProvenanceEvent("Add Namespace", now); List<SimplePropertyValuePair> eventProperties = new ArrayList<>(); Helper.addUserInfoToProvenanceEventProperties( eventProperties, this.getLoggedInUser()); String namespaceString = namespace.getPrefix() + " : " + namespace.getUri(); eventProperties.add( new SimplePropertyValuePair("namespace", namespaceString)); event.setProperties(eventProperties); List<ProvenanceEntity> oldProvList = new ArrayList<>(); oldProvList.add(oldProv); event.setInputs(oldProvList); newProv.setCreationEvent(event); networkService.setNetworkProvenance(newProv); networkService.commit(); networkService.close(); } finally { if (networkService != null) networkService.close(); logger.info(userNameForLog() + "[end: Added namespace to the network " + networkId + "]"); } } /************************************************************************** * Returns network provenance. * @throws IOException * @throws JsonMappingException * @throws JsonParseException * @throws NdexException * **************************************************************************/ @PermitAll @GET @Path("/{networkId}/provenance") @Produces("application/json") @ApiDoc("Retrieves the 'provenance' field of the network specified by 'networkId' as a ProvenanceEntity object, " + "if it exists. The ProvenanceEntity object is expected to represent the current state of the network and" + " to contain a tree-structure of ProvenanceEvent and ProvenanceEntity objects that describe the networks " + "provenance history.") public ProvenanceEntity getProvenance( @PathParam("networkId") final String networkId) throws IllegalArgumentException, JsonParseException, JsonMappingException, IOException, NdexException { logger.info(userNameForLog() + "[start: Getting provenance of network " + networkId + "]"); if ( ! isSearchable(networkId) ) throw new UnauthorizedOperationException("Network " + networkId + " is not readable to this user."); try (NetworkDocDAO daoNew = new NetworkDocDAO()) { return daoNew.getProvenance(UUID.fromString(networkId)); } finally { logger.info(userNameForLog() + "[end: Got provenance of network " + networkId + "]"); } } /************************************************************************** * Updates network provenance. * @throws Exception * **************************************************************************/ @PUT @Path("/{networkId}/provenance") @Produces("application/json") @ApiDoc("Updates the 'provenance' field of the network specified by 'networkId' to be the ProvenanceEntity object" + " in the PUT data. The ProvenanceEntity object is expected to represent the current state of the network" + " and to contain a tree-structure of ProvenanceEvent and ProvenanceEntity objects that describe the " + "networks provenance history.") public ProvenanceEntity setProvenance(@PathParam("networkId")final String networkId, final ProvenanceEntity provenance) throws Exception { logger.info(userNameForLog() + "[start: Updating provenance of network " + networkId + "]"); ODatabaseDocumentTx db = null; NetworkDAO daoNew = null; try { db = NdexDatabase.getInstance().getAConnection(); User user = getLoggedInUser(); if ( !Helper.checkPermissionOnNetworkByAccountName(db, networkId, user.getAccountName(), Permissions.WRITE)) { logger.error(userNameForLog() + "[end: No write permissions for user account " + user.getAccountName() + " on network " + networkId + "]"); throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } daoNew = new NetworkDAO(db); if(daoNew.networkIsReadOnly(networkId)) { daoNew.close(); logger.info(userNameForLog() + "[end: Can't modify readonly network " + networkId + "]"); throw new NdexException ("Can't update readonly network."); } UUID networkUUID = UUID.fromString(networkId); daoNew.setProvenance(networkUUID, provenance); daoNew.commit(); return daoNew.getProvenance(networkUUID); } catch (Exception e) { if (null != daoNew) daoNew.rollback(); logger.error(userNameForLog() + "[end: Updating provenance of network " + networkId + ". Exception caught:]", e); throw e; } finally { if (null != db) db.close(); logger.info(userNameForLog() + "[end: Updated provenance of network " + networkId + "]"); } } /************************************************************************** * Sets network properties. * @throws Exception * **************************************************************************/ @PUT @Path("/{networkId}/properties") @Produces("application/json") @ApiDoc("Updates the 'properties' field of the network specified by 'networkId' to be the list of " + "NdexPropertyValuePair objects in the PUT data.") public int setNetworkProperties( @PathParam("networkId")final String networkId, final List<NdexPropertyValuePair> properties) throws Exception { logger.info(userNameForLog() + "[start: Updating properties of network " + networkId + "]"); ODatabaseDocumentTx db = null; NetworkDAO daoNew = null; try { db = NdexDatabase.getInstance().getAConnection(); User user = getLoggedInUser(); if ( !Helper.checkPermissionOnNetworkByAccountName(db, networkId, user.getAccountName(), Permissions.WRITE)) { logger.error(userNameForLog() + "[end: No write permissions for user account " + user.getAccountName() + " on network " + networkId + "]"); throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } daoNew = new NetworkDAO(db); if(daoNew.networkIsReadOnly(networkId)) { daoNew.close(); logger.info(userNameForLog() + "[end: Can't delete readonly network " + networkId + "]"); throw new NdexException ("Can't update readonly network."); } UUID networkUUID = UUID.fromString(networkId); int i = daoNew.setNetworkProperties(networkUUID, properties); //DW: Handle provenance ProvenanceEntity oldProv = daoNew.getProvenance(networkUUID); ProvenanceEntity newProv = new ProvenanceEntity(); newProv.setUri( oldProv.getUri() ); Helper.populateProvenanceEntity(newProv, daoNew, networkId); NetworkSummary summary = daoNew.getNetworkSummary(daoNew.getRecordByUUIDStr(networkId, null)); Helper.populateProvenanceEntity(newProv, summary); ProvenanceEvent event = new ProvenanceEvent("Set Network Properties", summary.getModificationTime()); List<SimplePropertyValuePair> eventProperties = new ArrayList<>(); Helper.addUserInfoToProvenanceEventProperties( eventProperties, user); for( NdexPropertyValuePair vp : properties ) { SimplePropertyValuePair svp = new SimplePropertyValuePair(vp.getPredicateString(), vp.getValue()); eventProperties.add(svp); } event.setProperties(eventProperties); List<ProvenanceEntity> oldProvList = new ArrayList<>(); oldProvList.add(oldProv); event.setInputs(oldProvList); newProv.setCreationEvent(event); daoNew.setProvenance(networkUUID, newProv); daoNew.commit(); //logInfo(logger, "Finished updating properties of network " + networkId); return i; } catch (Exception e) { //logger.severe("Error occurred when update network properties: " + e.getMessage()); //e.printStackTrace(); if (null != daoNew) daoNew.rollback(); logger.error(userNameForLog() + "[end: Updating properties of network " + networkId + ". Exception caught:]", e); throw new NdexException(e.getMessage()); } finally { if (null != db) db.close(); logger.info(userNameForLog() + "[end: Updated properties of network " + networkId + "]"); } } @PUT @Path("/{networkId}/presentationProperties") @Produces("application/json") @ApiDoc("Updates the'presentationProperties' field of the network specified by 'networkId' to be the list of " + "SimplePropertyValuePair objects in the PUT data.") public int setNetworkPresentationProperties( @PathParam("networkId")final String networkId, final List<SimplePropertyValuePair> properties) throws Exception { logger.info(userNameForLog() + "[start: Updating presentationProperties field of network " + networkId + "]"); ODatabaseDocumentTx db = null; NetworkDAO daoNew = null; try { db = NdexDatabase.getInstance().getAConnection(); User user = getLoggedInUser(); if ( !Helper.checkPermissionOnNetworkByAccountName(db, networkId, user.getAccountName(), Permissions.WRITE)) { logger.error(userNameForLog() + "[end: No write permissions for user account " + user.getAccountName() + " on network " + networkId + "]"); throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } daoNew = new NetworkDAO(db); UUID networkUUID = UUID.fromString(networkId); if(daoNew.networkIsReadOnly(networkId)) { daoNew.close(); logger.info(userNameForLog() + "[end: Can't delete readonly network " + networkId + "]"); throw new NdexException ("Can't update readonly network."); } int i = daoNew.setNetworkPresentationProperties(networkUUID, properties); //DW: Handle provenance ProvenanceEntity oldProv = daoNew.getProvenance(networkUUID); ProvenanceEntity newProv = new ProvenanceEntity(); newProv.setUri( oldProv.getUri() ); NetworkSummary summary = daoNew.getNetworkSummary(daoNew.getRecordByUUIDStr(networkId, null)); Helper.populateProvenanceEntity(newProv, summary); ProvenanceEvent event = new ProvenanceEvent("Set Network Presentation Properties", summary.getModificationTime()); List<SimplePropertyValuePair> eventProperties = new ArrayList<>(); Helper.addUserInfoToProvenanceEventProperties( eventProperties, user); for( SimplePropertyValuePair vp : properties ) { SimplePropertyValuePair svp = new SimplePropertyValuePair(vp.getName(), vp.getValue()); eventProperties.add(svp); } event.setProperties(eventProperties); List<ProvenanceEntity> oldProvList = new ArrayList<>(); oldProvList.add(oldProv); event.setInputs(oldProvList); newProv.setCreationEvent(event); daoNew.setProvenance(networkUUID, newProv); daoNew.commit(); return i; } catch (Exception e) { if (null != daoNew) { daoNew.rollback(); daoNew = null; } logger.error(userNameForLog() + "[end: Updating presentationProperties field of network " + networkId + ". Exception caught:]", e); throw e; } finally { if (null != db) db.close(); logger.info(userNameForLog() + "[end: Updated presentationProperties field of network " + networkId + "]"); } } /* * * Operations returning Networks * */ @PermitAll @GET @Path("/{networkId}") @Produces("application/json") @ApiDoc("Retrieves a NetworkSummary object based on the network specified by 'networkUUID'. This method returns " + "an error if the network is not found or if the authenticated user does not have READ permission for the " + "network.") public NetworkSummary getNetworkSummary( @PathParam("networkId") final String networkId) throws IllegalArgumentException, NdexException { logger.info(userNameForLog() + "[start: Getting networkSummary of network " + networkId + "]"); ODatabaseDocumentTx db = null; try { db = NdexDatabase.getInstance().getAConnection(); NetworkDocDAO networkDocDao = new NetworkDocDAO(db); VisibilityType vt = Helper.getNetworkVisibility(db, networkId); boolean hasPrivilege = (vt == VisibilityType.PUBLIC || vt== VisibilityType.DISCOVERABLE); if ( !hasPrivilege && getLoggedInUser() != null) { hasPrivilege = networkDocDao.checkPrivilege(getLoggedInUser().getAccountName(), networkId, Permissions.READ); } if ( hasPrivilege) { ODocument doc = networkDocDao.getNetworkDocByUUIDString(networkId); if (doc == null) throw new ObjectNotFoundException("Network with ID: " + networkId + " doesn't exist."); NetworkSummary summary = NetworkDocDAO.getNetworkSummary(doc); db.close(); db = null; //logInfo(logger, "NetworkSummary of " + networkId + " returned."); return summary; } } finally { if (db != null) db.close(); logger.info(userNameForLog() + "[end: Got networkSummary of network " + networkId + "]"); } logger.error(userNameForLog() + "[end: Getting networkSummary of network " + networkId + " Throwing WebApplicationException exception ...]"); throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } @PermitAll @GET @Path("/{networkId}/edge/asNetwork/{skipBlocks}/{blockSize}") @Produces("application/json") @ApiDoc("Retrieves a subnetwork of a network based on a block (where a block is simply a contiguous set) of edges" + ". The network is specified by 'networkId' and the maximum number of edges to retrieve in the query is " + "set by 'blockSize' (which may be any number chosen by the user) while 'skipBlocks' specifies the " + "number of blocks that have already been read. The subnetwork is returned as a Network object containing " + "the Edge objects specified by the query along with all of the other network elements relevant to the " + "edges. (Compare this method to getPropertyGraphEdges).\n") public Network getEdges( @PathParam("networkId") final String networkId, @PathParam("skipBlocks") final int skipBlocks, @PathParam("blockSize") final int blockSize) throws IllegalArgumentException, NdexException { logger.info(userNameForLog() + "[start: Getting edges of network " + networkId + ", skipBlocks " + skipBlocks + ", blockSize " + blockSize +"]"); ODatabaseDocumentTx db = null; try { db = NdexDatabase.getInstance().getAConnection(); NetworkDAO dao = new NetworkDAO(db); Network n = dao.getNetwork(UUID.fromString(networkId), skipBlocks, blockSize); return n; } finally { if ( db !=null) db.close(); logger.info(userNameForLog() + "[end: Got edges of network " + networkId + ", skipBlocks " + skipBlocks + ", blockSize " + blockSize +"]"); } } @PermitAll @GET @Path("/{networkId}/asNetwork") // @Produces("application/json") @ApiDoc("Retrieve an entire network specified by 'networkId' as a Network object. (Compare this method to " + "getCompleteNetworkAsPropertyGraph).") // new Implmentation to handle cached network public Response getCompleteNetwork( @PathParam("networkId") final String networkId) throws IllegalArgumentException, NdexException { logger.info(userNameForLog() + "[start: Getting complete network " + networkId + "]"); if ( isSearchable(networkId) ) { ODatabaseDocumentTx db = NdexDatabase.getInstance().getAConnection(); NetworkDAO daoNew = new NetworkDAO(db); NetworkSummary sum = daoNew.getNetworkSummaryById(networkId); long commitId = sum.getReadOnlyCommitId(); if ( commitId > 0 && commitId == sum.getReadOnlyCacheId()) { daoNew.close(); try { FileInputStream in = new FileInputStream( Configuration.getInstance().getNdexNetworkCachePath() + commitId +".gz") ; setZipFlag(); logger.info(userNameForLog() + "[end: return cached network " + networkId + "]"); return Response.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(in).build(); } catch (IOException e) { throw new NdexException ("Ndex server can't find file: " + e.getMessage()); } } Network n = daoNew.getNetworkById(UUID.fromString(networkId)); daoNew.close(); logger.info(userNameForLog() + "[end: return complete network " + networkId + "]"); return Response.ok(n,MediaType.APPLICATION_JSON_TYPE).build(); } else throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } @PermitAll @GET @Path("/export/{networkId}/{format}") @Produces("application/json") @ApiDoc("Retrieve an entire network specified by 'networkId' as a Network object. (Compare this method to " + "getCompleteNetworkAsPropertyGraph).") public String exportNetwork( @PathParam("networkId") final String networkId, @PathParam("format") final String format) throws NdexException { logger.info(userNameForLog() + "[start: request to export network " + networkId + "]"); if ( isSearchable(networkId) ) { String networkName =null; try (NetworkDAO networkdao = new NetworkDAO(NdexDatabase.getInstance().getAConnection())){ networkName = networkdao.getNetworkSummaryById(networkId).getName(); } Task exportNetworkTask = new Task(); exportNetworkTask.setTaskType(TaskType.EXPORT_NETWORK_TO_FILE); exportNetworkTask.setPriority(Priority.LOW); exportNetworkTask.setResource(networkId); exportNetworkTask.setStatus(Status.QUEUED); exportNetworkTask.setDescription("Export network \""+ networkName + "\" in " + format + " format"); try { exportNetworkTask.setFormat(FileFormat.valueOf(format)); } catch ( Exception e) { throw new NdexException ("Invalid network format for network export."); } try (TaskDAO taskDAO = new TaskDAO(NdexDatabase.getInstance().getAConnection()) ){ UUID taskId = taskDAO.createTask(getLoggedInUser().getAccountName(),exportNetworkTask); taskDAO.commit(); logger.info(userNameForLog() + "[end: task created to export network " + networkId + "]"); return taskId.toString(); } catch (Exception e) { logger.error(userNameForLog() + "[end: Exception caught:]", e); throw new NdexException(e.getMessage()); } } throw new UnauthorizedOperationException("User doesn't have read access to this network."); } @PermitAll @GET @Path("/{networkId}/asPropertyGraph") @Produces("application/json") @ApiDoc("Retrieves an entire network specified by 'networkId' as a PropertyGraphNetwork object. A user may wish " + "to retrieve a PropertyGraphNetwork rather than an ordinary Network when the would like to work with the " + "network with a table-oriented data structure, for example, an R or Python data frame. (Compare this " + "method to getCompleteNetwork).") public PropertyGraphNetwork getCompleteNetworkAsPropertyGraph( @PathParam("networkId") final String networkId) throws IllegalArgumentException, NdexException, JsonProcessingException { logger.info(userNameForLog() + "[start: Retrieving an entire network " + networkId + "as a PropertyGraphNetwork object]"); if ( isSearchable(networkId) ) { ODatabaseDocumentTx db =null; try { db = NdexDatabase.getInstance().getAConnection(); NetworkDAO daoNew = new NetworkDAO(db); PropertyGraphNetwork n = daoNew.getProperytGraphNetworkById(UUID.fromString(networkId)); return n; } finally { if (db !=null ) db.close(); logger.info(userNameForLog() + "[end: Retrieved an entire network " + networkId + "as a PropertyGraphNetwork object]"); } } else { logger.error(userNameForLog() + "[end: Retrieving an entire network " + networkId + "as a PropertyGraphNetwork object. Throwing WebApplicationException exception ...]"); throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } } @PermitAll @GET @Path("/{networkId}/edge/asPropertyGraph/{skipBlocks}/{blockSize}") @Produces("application/json") @ApiDoc("Retrieves a subnetwork of a network based on a block (where a block is simply a contiguous set) of edges" + ". The network is specified by 'networkId' and the maximum number of edges to retrieve in the query is " + "set by 'blockSize' (which may be any number chosen by the user) while 'skipBlocks' specifies number of " + "blocks that have already been read. The subnetwork is returned as a PropertyGraphNetwork object " + "containing the PropertyGraphEdge objects specified by the query along with all of the PropertyGraphNode " + "objects and network information relevant to the edges. (Compare this method to getEdges).") public PropertyGraphNetwork getPropertyGraphEdges( @PathParam("networkId") final String networkId, @PathParam("skipBlocks") final int skipBlocks, @PathParam("blockSize") final int blockSize) throws IllegalArgumentException, NdexException { logger.info(userNameForLog() + "[start: Retrieving a subnetwork of network " + networkId + " with skipBlocks " + skipBlocks + " and blockSize " + blockSize + "]"); ODatabaseDocumentTx db = NdexDatabase.getInstance().getAConnection(); NetworkDAO dao = new NetworkDAO(db); PropertyGraphNetwork n = dao.getProperytGraphNetworkById(UUID.fromString(networkId),skipBlocks, blockSize); db.close(); logger.info(userNameForLog() + "[end: Retrieved a subnetwork of network " + networkId + " with skipBlocks " + skipBlocks + " and blockSize " + blockSize + "]"); return n; } /************************************************************************** * Retrieves array of user membership objects * * @param networkId * The network ID. * @throws IllegalArgumentException * Bad input. * @throws ObjectNotFoundException * The group doesn't exist. * @throws NdexException * Failed to query the database. **************************************************************************/ @GET @PermitAll @Path("/{networkId}/user/{permission}/{skipBlocks}/{blockSize}") @Produces("application/json") @ApiDoc("Retrieves a list of Membership objects which specify user permissions for the network specified by " + "'networkId'. The value of the 'permission' parameter constrains the type of the returned Membership " + "objects and may take the following set of values: READ, WRITE, and ADMIN. Memberships of all types can " + "be retrieved by permission = 'ALL'. The maximum number of Membership objects to retrieve in the query " + "is set by 'blockSize' (which may be any number chosen by the user) while 'skipBlocks' specifies the " + "number of blocks that have already been read.") public List<Membership> getNetworkUserMemberships(@PathParam("networkId") final String networkId, @PathParam("permission") final String permissions , @PathParam("skipBlocks") int skipBlocks, @PathParam("blockSize") int blockSize) throws NdexException { //logInfo( logger, "Get all " + permissions + " accounts on network " + networkId); logger.info(userNameForLog() + "[start: Get all " + permissions + "accounts on network " + networkId + ", skipBlocks " + skipBlocks + " blockSize " + blockSize + "]"); Permissions permission = Permissions.valueOf(permissions.toUpperCase()); ODatabaseDocumentTx db = null; try { db = NdexDatabase.getInstance().getAConnection(); NetworkDAO networkDao = new NetworkDAO(db); List<Membership> results = networkDao.getNetworkUserMemberships( UUID.fromString(networkId), permission, skipBlocks, blockSize); //logInfo(logger, results.size() + " members returned for network " + networkId); logger.info(userNameForLog() + "[end: Got " + results.size() + " members returned for network " + networkId + "]"); return results; } finally { if (db != null) db.close(); } } @DELETE @Path("/{networkId}/member/{userUUID}") @Produces("application/json") @ApiDoc("Removes any permission for the network specified by 'networkId' for the user specified by 'userUUID': it" + " deletes any Membership object that specifies a permission for the user-network combination. This method" + " will return an error if the authenticated user making the request does not have sufficient permissions " + "to make the deletion or if the network or user is not found. Removal is also denied if it would leave " + "the network without any user having ADMIN permissions: NDEx does not permit networks to become 'orphans'" + " without any owner.") public int deleteNetworkMembership( @PathParam("networkId") final String networkId, @PathParam("userUUID") final String userUUID ) throws IllegalArgumentException, NdexException { logger.info(userNameForLog() + "[start: Removing any permissions for network " + networkId + " for user " + userUUID + "]"); ODatabaseDocumentTx db = null; try { db = NdexDatabase.getInstance().getAConnection(); User user = getLoggedInUser(); NetworkDAO networkDao = new NetworkDAO(db); if (!Helper.isAdminOfNetwork(db, networkId, user.getExternalId().toString())) { logger.error(userNameForLog() + "[end: User " + userUUID + " not an admin of network " + networkId + ". Throwing WebApplicationException exception ...]"); throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } int count = networkDao.revokePrivilege(networkId, userUUID); db.commit(); logger.info(userNameForLog() + "[end: Removed any permissions for network " + networkId + " for user " + userUUID + "]"); return count; } finally { if (db != null) db.close(); } } /* * * Operations on Network permissions * */ @POST @Path("/{networkId}/member") @Produces("application/json") @ApiDoc("POSTs a Membership object to update the permission of a user specified by userUUID for the network " + "specified by networkUUID. The permission is updated to the value specified in the 'permission' field of " + "the Membership. This method returns 1 if the update is performed and 0 if the update is redundant, " + "where the user already has the specified permission. It also returns an error if the authenticated user " + "making the request does not have sufficient permissions or if the network or user is not found. It also " + "returns an error if it would leave the network without any user having ADMIN permissions: NDEx does not " + "permit networks to become 'orphans' without any owner.") public int updateNetworkMembership( @PathParam("networkId") final String networkId, final Membership membership ) throws IllegalArgumentException, NdexException { logger.info(userNameForLog() + "[start: Updating membership for network " + networkId + "]"); ODatabaseDocumentTx db = null; try { db = NdexDatabase.getInstance().getAConnection(); User user = getLoggedInUser(); NetworkDAO networkDao = new NetworkDAO(db); if (!Helper.isAdminOfNetwork(db, networkId, user.getExternalId().toString())) { logger.error(userNameForLog() + "[end: User " + user.getExternalId().toString() + " not an admin of network " + networkId + ". Throwing WebApplicationException exception ...]"); throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } int count = networkDao.grantPrivilege(networkId, membership.getMemberUUID().toString(), membership.getPermissions()); db.commit(); logger.info(userNameForLog() + "[end: Updated membership for network " + networkId + "]"); return count; } finally { if (db != null) db.close(); } } @POST @Path("/{networkId}/summary") @Produces("application/json") @ApiDoc("POSTs a NetworkSummary object to update the pro information of the network specified by networkUUID." + " The NetworkSummary POSTed may be only partially populated. The only fields that will be acted on are: " + "'name', 'description','version', and 'visibility' if they are present.") public void updateNetworkProfile( @PathParam("networkId") final String networkId, final NetworkSummary summary ) throws IllegalArgumentException, NdexException, IOException { logger.info(userNameForLog() + "[start: Updating profile information of network " + networkId + "]"); ODatabaseDocumentTx db = null; try { db = NdexDatabase.getInstance().getAConnection(); User user = getLoggedInUser(); NetworkDAO networkDao = new NetworkDAO(db); if(networkDao.networkIsReadOnly(networkId)) { networkDao.close(); logger.info(userNameForLog() + "[end: Can't modify readonly network " + networkId + "]"); throw new NdexException ("Can't update readonly network."); } if ( !Helper.checkPermissionOnNetworkByAccountName(db, networkId, user.getAccountName(), Permissions.WRITE)) { logger.error(userNameForLog() + "[end: No write permissions for user account " + user.getAccountName() + " on network " + networkId + ". Throwing WebApplicationException exception ...]"); throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } UUID networkUUID = UUID.fromString(networkId); networkDao.updateNetworkProfile(networkUUID, summary); //DW: Handle provenance //Special Logic. Test whether we should record provenance at all. //If the only thing that has changed is the visibility, we should not add a provenance //event. ProvenanceEntity oldProv = networkDao.getProvenance(networkUUID); String oldName = "", oldDescription = "", oldVersion =""; for( SimplePropertyValuePair oldProperty : oldProv.getProperties() ) { if( oldProperty.getName() == null ) continue; if( oldProperty.getName().equals("dc:title") ) oldName = oldProperty.getValue().trim(); else if( oldProperty.getName().equals("description") ) oldDescription = oldProperty.getValue().trim(); else if( oldProperty.getName().equals("version") ) oldVersion = oldProperty.getValue().trim(); } //Treat all summary values that are null like "" String summaryName = summary.getName() == null ? "" : summary.getName().trim(); String summaryDescription = summary.getDescription() == null ? "" : summary.getDescription().trim(); String summaryVersion = summary.getVersion() == null ? "" : summary.getVersion().trim(); if( !oldName.equals(summaryName) || !oldDescription.equals(summaryDescription) || !oldVersion.equals(summaryVersion) ) { ProvenanceEntity newProv = new ProvenanceEntity(); newProv.setUri(oldProv.getUri()); Helper.populateProvenanceEntity(newProv, networkDao, networkId); ProvenanceEvent event = new ProvenanceEvent("Update Network Profile", summary.getModificationTime()); List<SimplePropertyValuePair> eventProperties = new ArrayList<>(); Helper.addUserInfoToProvenanceEventProperties(eventProperties, user); if (summary.getName() != null) eventProperties.add(new SimplePropertyValuePair("dc:title", summary.getName())); if (summary.getDescription() != null) eventProperties.add(new SimplePropertyValuePair("description", summary.getDescription())); if (summary.getVersion() != null) eventProperties.add(new SimplePropertyValuePair("version", summary.getVersion())); event.setProperties(eventProperties); List<ProvenanceEntity> oldProvList = new ArrayList<>(); oldProvList.add(oldProv); event.setInputs(oldProvList); newProv.setCreationEvent(event); networkDao.setProvenance(networkUUID, newProv); } db.commit(); } finally { if (db != null) db.close(); logger.info(userNameForLog() + "[end: Updated the pro information for network " + networkId + "]"); } } @PermitAll @POST @Path("/{networkId}/asNetwork/query") @Produces("application/json") @ApiDoc("Retrieves a 'neighborhood' subnetwork of a network based on identifiers specified in a POSTed " + "SimplePathQuery object based on a parameter set by the user. The network to be queried is specified by " + "networkId. In the first step of the query, a set of base terms exactly matching identifiers found in the" + " 'searchString' field of the SimplePathQuery is selected. In the second step, " + "nodes are selected that reference the base terms identified in the network. Finally, " + "a set of edges is selected by traversing outwards from each of these selected nodes, " + "up to the limit specified by the 'searchDepth' field of the SimplePathQuery. The subnetwork is returned" + " as a Network object containing the selected Edge objects along with any other network elements relevant" + " to the edges.") public Network queryNetwork( @PathParam("networkId") final String networkId, final SimplePathQuery queryParameters // @PathParam("skipBlocks") final int skipBlocks, // @PathParam("blockSize") final int blockSize ) throws IllegalArgumentException, NdexException { //logInfo (logger, "Neighborhood search on " + networkId + " with phrase \"" + queryParameters.getSearchString() + "\""); logger.info(userNameForLog() + "[start: Retrieving neighborhood subnetwork for network " + networkId + " with phrase \"" + queryParameters.getSearchString() + "\"]"); try (ODatabaseDocumentTx db = NdexDatabase.getInstance().getAConnection()) { NetworkDAO networkDao = new NetworkDAO(db); VisibilityType vt = Helper.getNetworkVisibility(db, networkId); boolean hasPrivilege = (vt == VisibilityType.PUBLIC ); if ( !hasPrivilege && getLoggedInUser() != null) { hasPrivilege = networkDao.checkPrivilege( (getLoggedInUser() == null ? null : getLoggedInUser().getAccountName()), networkId, Permissions.READ); } if ( hasPrivilege) { NetworkAOrientDBDAO dao = NetworkAOrientDBDAO.getInstance(); Network n = dao.queryForSubnetwork(networkId, queryParameters); //logInfo(logger, "Subnetwork from query returned." ); logger.info(userNameForLog() + "[end: Subnetwork for network " + networkId + " with phrase \"" + queryParameters.getSearchString() + "\" retrieved]"); return n; //getProperytGraphNetworkById(UUID.fromString(networkId),skipBlocks, blockSize); } logger.error(userNameForLog() + "[end: Retrieving neighborhood subnetwork for network " + networkId + " with phrase \"" + queryParameters.getSearchString() + "\". Throwing WebApplicationException exception ...]"); throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } } @PermitAll @POST @Path("/{networkId}/asNetwork/prototypeNetworkQuery") @Produces("application/json") @ApiDoc("Retrieves a 'neighborhood' subnetwork of a network based on identifiers specified in a POSTed " + "SimplePathQuery object based on a parameter set by the user. The network to be queried is specified by " + "networkId. In the first step of the query, a set of base terms exactly matching identifiers found in the" + " 'searchString' field of the SimplePathQuery is selected. In the second step, " + "nodes are selected that reference the base terms identified in the network. Finally, " + "a set of edges is selected by traversing outwards from each of these selected nodes, " + "up to the limit specified by the 'searchDepth' field of the SimplePathQuery. The subnetwork is returned" + " as a Network object containing the selected Edge objects along with any other network elements relevant" + " to the edges.") public Network queryNetworkByEdgeFilter( @PathParam("networkId") final String networkId, final EdgeCollectionQuery query ) throws IllegalArgumentException, NdexException { logger.info(userNameForLog() + "[start: filter query on network " + networkId + "\"]"); if ( !isSearchable(networkId ) ) { throw new UnauthorizedOperationException("Network is not readable to this user."); } NetworkFilterQueryExecutor queryExecutor = NetworkFilterQueryExecutorFactory.createODBExecutor(networkId, query); Network result = queryExecutor.evaluate(); logger.info(userNameForLog() + "[end: filter query on network " + networkId + "\"]"); return result; } private boolean isSearchable(String networkId) throws ObjectNotFoundException, NdexException { try ( NetworkDocDAO networkDao = new NetworkDocDAO() ) { VisibilityType vt = Helper.getNetworkVisibility(networkDao.getDBConnection(), networkId); boolean hasPrivilege = (vt == VisibilityType.PUBLIC ); if ( !hasPrivilege && getLoggedInUser() != null) { hasPrivilege = networkDao.checkPrivilege( (getLoggedInUser() == null ? null : getLoggedInUser().getAccountName()), networkId, Permissions.READ); } return hasPrivilege; } } @PermitAll @POST @Path("/{networkId}/asPropertyGraph/query") @Produces("application/json") @ApiDoc("Retrieves a 'neighborhood' subnetwork of a network based on identifiers specified in a POSTed " + "SimplePathQuery object. The network is specified by networkId. In the first step of the query, " + "a set of base terms exactly matching identifiers found in the searchString of the SimplePathQuery is " + "selected. In the second step, nodes are selected that reference the base terms identified in the network" + ". Finally, a set of edges is selected by traversing outwards from each of these selected nodes, " + "up to the limit specified by the 'searchDepth' field of the SimplePathQuery. The subnetwork is returned" + " as a PropertyGraphNetwork object containing the selected PropertyGraphEdge objects along with any other" + " network information relevant to the edges.") public PropertyGraphNetwork queryNetworkAsPropertyGraph( @PathParam("networkId") final String networkId, final SimplePathQuery queryParameters // @PathParam("skipBlocks") final int skipBlocks, // @PathParam("blockSize") final int blockSize ) throws IllegalArgumentException, NdexException { logger.info(userNameForLog() + "[start: Retrieving neighborhood subnetwork for network " + networkId + " based on SimplePathQuery object]"); ODatabaseDocumentTx db = null; try { db = NdexDatabase.getInstance().getAConnection(); NetworkDAO networkDao = new NetworkDAO(db); VisibilityType vt = Helper.getNetworkVisibility(db, networkId); boolean hasPrivilege = (vt == VisibilityType.PUBLIC ); if ( !hasPrivilege && getLoggedInUser() != null) { hasPrivilege = networkDao.checkPrivilege( (getLoggedInUser() == null ? null : getLoggedInUser().getAccountName()), networkId, Permissions.READ); } db.close(); db = null; if ( hasPrivilege) { NetworkAOrientDBDAO dao = NetworkAOrientDBDAO.getInstance(); PropertyGraphNetwork n = dao.queryForSubPropertyGraphNetwork(networkId, queryParameters); logger.info(userNameForLog() + "[start: Retrieved neighborhood subnetwork for network " + networkId + " based on SimplePathQuery object]"); return n; } } finally { if ( db !=null) db.close(); } logger.error(userNameForLog() + "[end: Retrieving neighborhood subnetwork for network " + networkId + " based on SimplePathQuery object. Throwing WebApplicationException exception ...]"); throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } /* @PermitAll @POST @Path("/{networkId}/asPropertyGraph/query/{skipBlocks}/{blockSize}") @Produces("application/json") @ApiDoc("Retrieves a 'neighborhood' subnetwork of a network based on identifiers specified in a POSTed " + "SimplePathQuery object . The network is specified by networkId and the maximum number of edges to " + "retrieve in the query is set by 'blockSize' (which may be any number chosen by the user) while " + "'skipBlocks' specifies the number of blocks that have already been read before performing the next read." + " In the first step of the query, a set of base terms exactly matching identifiers found in the " + "searchString of the SimplePathQuery is selected. In the second step, nodes are selected that reference " + "the base terms identified in the network. Finally, a set of edges is selected by traversing outwards " + "from each of these selected nodes, up to the limit specified by the 'searchDepth' field of the " + "SimplePathQuery. The subnetwork is returned as a PropertyGraphNetwork object containing the selected " + "PropertyGraphEdge objects along with any other network information relevant to the edges.") public PropertyGraphNetwork queryNetworkAsPropertyGraph( @PathParam("networkId") final String networkId, final NetworkQueryParameters queryParameters, @PathParam("skipBlocks") final int skipBlocks, @PathParam("blockSize") final int blockSize) throws IllegalArgumentException, NdexException, JsonProcessingException { ODatabaseDocumentTx db = NdexAOrientDBConnectionPool.getInstance().acquire(); NetworkDAO dao = new NetworkDAO(db); PropertyGraphNetwork n = dao.getProperytGraphNetworkById(UUID.fromString(networkId)); db.close(); return n; } */ /* * * Network Search * */ @POST @PermitAll @Path("/search/{skipBlocks}/{blockSize}") @Produces("application/json") @ApiDoc("Returns a list of NetworkSummary objects based on a POSTed NetworkQuery object. The NetworkQuery may be " + "either a NetworkSimpleQuery specifying only a search string or a NetworkMembershipQuery that also " + "constrains the search to networks administered by a user or group. The maximum number of NetworkSummary " + "objects to retrieve in the query is set by 'blockSize' (which may be any number chosen by the user) " + "while 'skipBlocks' specifies number of blocks that have already been read.") public Collection<NetworkSummary> searchNetwork( final SimpleNetworkQuery query, @PathParam("skipBlocks") final int skipBlocks, @PathParam("blockSize") final int blockSize) throws IllegalArgumentException, NdexException { //logInfo ( logger, "Search networks: \"" + query.getSearchString() + "\""); logger.info(userNameForLog() + "[start: Retrieving NetworkSummary objects using query \"" + query.getSearchString() + "\"]"); if(query.getAccountName() != null) query.setAccountName(query.getAccountName().toLowerCase()); try (ODatabaseDocumentTx db = NdexDatabase.getInstance().getAConnection()) { NetworkSearchDAO dao = new NetworkSearchDAO(db); Collection<NetworkSummary> result = new ArrayList <> (); result = dao.findNetworks(query, skipBlocks, blockSize, this.getLoggedInUser()); //logInfo ( logger, result.size() + " networks returned from search."); logger.info(userNameForLog() + "[end: Retrieved " + result.size() + " NetworkSummary objects]"); return result; } catch (Exception e) { //e.printStackTrace(); //logger.error(userNameForLog() + "[end: Updating properties of network " + networkId + " Exception caught: " + e + "]"); logger.error(userNameForLog() + "[end: Retrieving NetworkSummary objects using query \"" + query.getSearchString() + "\". Exception caught:]", e); throw new NdexException(e.getMessage()); } } @POST @Path("/asPropertyGraph") @Produces("application/json") @ApiDoc("Creates a new network based on a POSTed NetworkPropertyGraph object. This method errors if the " + "NetworkPropertyGraph object is not provided or if it does not specify a name. It also errors if the " + "NetworkPropertyGraph object is larger than a maximum size for network creation set in the NDEx server " + "configuration. A NetworkSummary object for the new network is returned.") public NetworkSummary createNetwork(final PropertyGraphNetwork newNetwork) throws Exception { Preconditions .checkArgument(null != newNetwork, "A network is required"); Preconditions.checkArgument( !Strings.isNullOrEmpty(newNetwork.getName()), "A network name is required"); logger.info(userNameForLog() + "[start: Creating a new network based on a POSTed NetworkPropertyGraph object]"); NdexDatabase db = NdexDatabase.getInstance(); PropertyGraphLoader pgl = null; pgl = new PropertyGraphLoader(db); NetworkSummary ns = pgl.insertNetwork(newNetwork, getLoggedInUser()); logger.info(userNameForLog() + "[end: Created a new network based on a POSTed NetworkPropertyGraph object]"); return ns; } /* comment out this function for now, until we can make this function thread safe. * @PUT @Path("/asPropertyGraph") @Produces("application/json") @ApiDoc("Updates an existing network using a PUT call using a NetworkPropertyGraph object. The NetworkPropertyGraph object must contain a " + "UUID (this would normally be the case for a NetworkPropertyGraph object retrieved from NDEx, " + "so no additional work is required in the most common case) and the user must have permission to modify " + "this network. This method errors if the NetworkPropertyGraph object is not provided or if it does not have a valid " + "UUID on the server. It also errors if the NetworkPropertyGraph object is larger than a maximum size for network " + "creation set in the NDEx server configuration. A NetworkSummary object is returned.") public NetworkSummary updateNetwork(final PropertyGraphNetwork newNetwork) throws Exception { Preconditions .checkArgument(null != newNetwork, "A network is required"); Preconditions.checkArgument( !Strings.isNullOrEmpty(newNetwork.getName()), "A network name is required"); NdexDatabase db = new NdexDatabase(Configuration.getInstance().getHostURI()); PropertyGraphLoader pgl = null; ODatabaseDocumentTx conn = null; try { conn = db.getAConnection(); User user = getLoggedInUser(); String uuidStr = null; for ( NdexPropertyValuePair p : newNetwork.getProperties()) { if ( p.getPredicateString().equals ( PropertyGraphNetwork.uuid) ) { uuidStr = p.getValue(); break; } } if ( uuidStr == null) throw new NdexException ("updateNetwork: UUID not found in PropertyGraph."); if (!Helper.checkPermissionOnNetworkByAccountName(conn, uuidStr, user.getAccountName(), Permissions.WRITE)) { throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } pgl = new PropertyGraphLoader(db); return pgl.updateNetwork(newNetwork); } finally { if (db!=null) db.close(); if( conn!=null) conn.close(); } } */ @POST @Path("/asNetwork") @Produces("application/json") @ApiDoc("Creates a new network based on a POSTed Network object. This method errors if the Network object is not " + "provided or if it does not specify a name. It also errors if the Network object is larger than a maximum" + " size for network creation set in the NDEx server configuration. A NetworkSummary object is returned.") public NetworkSummary createNetwork(final Network newNetwork) throws Exception { Preconditions .checkArgument(null != newNetwork, "A network is required"); Preconditions.checkArgument( !Strings.isNullOrEmpty(newNetwork.getName()), "A network name is required"); logger.info(userNameForLog() + "[start: Creating a new network based on a POSTed Network object]"); NdexDatabase db = NdexDatabase.getInstance(); NdexNetworkCloneService service = null; try { newNetwork.setVisibility(VisibilityType.PRIVATE); service = new NdexNetworkCloneService(db, newNetwork, getLoggedInUser().getAccountName()); NetworkSummary summary = service.cloneNetwork(); //DW: Provenance ProvenanceEntity entity = new ProvenanceEntity(); entity.setUri(summary.getURI()); Helper.populateProvenanceEntity(entity, summary); ProvenanceEvent event = new ProvenanceEvent("Program Upload", summary.getModificationTime()); List<SimplePropertyValuePair> eventProperties = new ArrayList<>(); Helper.addUserInfoToProvenanceEventProperties( eventProperties, this.getLoggedInUser()); event.setProperties(eventProperties); entity.setCreationEvent(event); service.setNetworkProvenance(entity); logger.info(userNameForLog() + "[end: Created a new network based on a POSTed Network object]"); return summary; } finally { if ( service !=null) service.close(); } } @PUT @Path("/asNetwork") @Produces("application/json") @ApiDoc("Updates an existing network using a PUT call using a Network object. The Network object must contain a " + "UUID (this would normally be the case for a Network object retrieved from NDEx, " + "so no additional work is required in the most common case) and the user must have permission to modify " + "this network. This method errors if the Network object is not provided or if it does not have a valid " + "UUID on the server. It also errors if the Network object is larger than a maximum size for network " + "creation set in the NDEx server configuration. A NetworkSummary object is returned.") public NetworkSummary updateNetwork(final Network newNetwork) throws Exception { Preconditions .checkArgument(null != newNetwork, "A network is required"); Preconditions.checkArgument( !Strings.isNullOrEmpty(newNetwork.getName()), "A network name is required"); try ( ODatabaseDocumentTx conn = NdexDatabase.getInstance().getAConnection() ) { User user = getLoggedInUser(); if (!Helper.checkPermissionOnNetworkByAccountName(conn, newNetwork.getExternalId().toString(), user.getAccountName(), Permissions.WRITE)) { throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } NetworkDocDAO daoNew = new NetworkDocDAO(conn); if(daoNew.networkIsReadOnly(newNetwork.getExternalId().toString())) { daoNew.close(); logger.info(userNameForLog() + "[end: Can't update readonly network " + newNetwork.getExternalId().toString() + "]"); throw new NdexException ("Can't modify readonly network."); } } try ( NdexNetworkCloneService service = new NdexNetworkCloneService(NdexDatabase.getInstance(), newNetwork, getLoggedInUser().getAccountName()) ) { return service.updateNetwork(); } } @DELETE @Path("/{UUID}") @Produces("application/json") @ApiDoc("Deletes the network specified by 'UUID'.") public void deleteNetwork(final @PathParam("UUID") String id) throws NdexException { logger.info(userNameForLog() + "[start: Deleting network " + id + "]"); String userAcc = getLoggedInUser().getAccountName(); //logInfo(logger, "Deleting network " + id); ODatabaseDocumentTx db = null; try{ db = NdexDatabase.getInstance().getAConnection(); if (!Helper.checkPermissionOnNetworkByAccountName(db, id, userAcc, Permissions.ADMIN)) { throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } try (NetworkDAO networkDao = new NetworkDAO(db)) { if(networkDao.networkIsReadOnly(id)) { logger.info(userNameForLog() + "[end: Can't delete readonly network " + id + "]"); throw new NdexException ("Can't delete readonly network."); } //logger.info("Start deleting network " + id); networkDao.logicalDeleteNetwork(id); networkDao.commit(); Task task = new Task(); task.setTaskType(TaskType.SYSTEM_DELETE_NETWORK); task.setResource(id); NdexServerQueue.INSTANCE.addSystemTask(task); } db = null; logger.info(userNameForLog() + "[end: Deleted network " + id + "]"); //logger.info("Network " + id + " deleted."); } finally { if ( db != null) db.close(); } } /************************************************************************** * Saves an uploaded network file. Determines the type of file uploaded, * saves the file, and creates a task. * * @param uploadedNetwork * The uploaded network file. * @throws IllegalArgumentException * Bad input. * @throws NdexException * Failed to parse the file, or create the network in the * database. **************************************************************************/ /* * refactored to support non-transactional database operations */ @POST @Path("/upload") @Consumes("multipart/form-data") @Produces("application/json") @ApiDoc("Upload a network file into the current users NDEx account. This can take some time while background " + "processing converts the data from the file into the common NDEx format. This method errors if the " + "network is missing or if it has no filename or no file data.") public void uploadNetwork(@MultipartForm UploadedFile uploadedNetwork) throws IllegalArgumentException, SecurityException, NdexException { logger.info(userNameForLog() + "[start: Uploading network file]"); try { Preconditions .checkNotNull(uploadedNetwork, "A network is required"); Preconditions.checkState( !Strings.isNullOrEmpty(uploadedNetwork.getFilename()), "A file name containg the network data is required"); Preconditions.checkNotNull(uploadedNetwork.getFileData(), "Network file data is required"); Preconditions.checkState(uploadedNetwork.getFileData().length > 0, "The file data is empty"); } catch (Exception e1) { logger.error(userNameForLog() + "[end: Uploading network file. Exception caught:]", e1 ); throw new NdexException(e1.getMessage()); } String ext = FilenameUtils.getExtension(uploadedNetwork.getFilename()).toLowerCase(); if ( !ext.equals("sif") && !ext.equals("xbel") && !ext.equals("xgmml") && !ext.equals("owl") && !ext.equals("xls") && ! ext.equals("xlsx")) { logger.error(userNameForLog() + "[end: The uploaded file type is not supported; must be Excel, XGMML, SIF, BioPAX or XBEL. Throwing IllegalArgumentException...]"); throw new NdexException( "The uploaded file type is not supported; must be Excel, XGMML, SIF, BioPAX or XBEL."); } UUID taskId = NdexUUIDFactory.INSTANCE.getNDExUUID(); final File uploadedNetworkPath = new File(Configuration.getInstance().getNdexRoot() + "/uploaded-networks"); if (!uploadedNetworkPath.exists()) uploadedNetworkPath.mkdir(); String fileFullPath = uploadedNetworkPath.getAbsolutePath() + "/" + taskId + "." + ext; final File uploadedNetworkFile = new File(fileFullPath); if (!uploadedNetworkFile.exists()) try { uploadedNetworkFile.createNewFile(); } catch (IOException e1) { //e1.printStackTrace(); logger.error(userNameForLog() + "[end: Failed to create file " + fileFullPath + " on server when uploading " + uploadedNetwork.getFilename() + ". Exception caught:]", e1); throw new NdexException ("Failed to create file " + fileFullPath + " on server when uploading " + uploadedNetwork.getFilename() + ": " + e1.getMessage()); } try ( FileOutputStream saveNetworkFile = new FileOutputStream(uploadedNetworkFile)) { saveNetworkFile.write(uploadedNetwork.getFileData()); saveNetworkFile.flush(); } catch (IOException e1) { //e1.printStackTrace(); logger.error(userNameForLog() + "[end: Failed to write content to file " + fileFullPath + " on server when uploading " + uploadedNetwork.getFilename() + ". Exception caught:]", e1 ); throw new NdexException ("Failed to write content to file " + fileFullPath + " on server when uploading " + uploadedNetwork.getFilename() + ": " + e1.getMessage()); } final String userAccount = this.getLoggedInUser().getAccountName(); Task processNetworkTask = new Task(); processNetworkTask.setExternalId(taskId); processNetworkTask.setDescription(uploadedNetwork.getFilename()); processNetworkTask.setTaskType(TaskType.PROCESS_UPLOADED_NETWORK); processNetworkTask.setPriority(Priority.LOW); processNetworkTask.setProgress(0); processNetworkTask.setResource(fileFullPath); processNetworkTask.setStatus(Status.QUEUED); try (TaskDAO dao = new TaskDAO(NdexDatabase.getInstance().getAConnection())){ dao.createTask(userAccount, processNetworkTask); dao.commit(); } catch (IllegalArgumentException iae) { logger.error(userNameForLog() + "[end: Exception caught:]", iae); throw iae; } catch (Exception e) { //Logger.getLogger(this.getClass().getName()).severe("Failed to process uploaded network: " // + uploadedNetwork.getFilename() + ". " + e.getMessage()); logger.error(userNameForLog() + "[end: Exception caught:]", e); throw new NdexException(e.getMessage()); } } @GET @Path("/{networkId}/setFlag/{parameter}={value}") @Produces("application/json") @ApiDoc("Set the certain Ndex system flag onnetwork. Supported parameters are:"+ "readOnly={true|false}") public String setNetworkFlag( @PathParam("networkId") final String networkId, @PathParam("parameter") final String parameter, @PathParam("value") final String value) throws IllegalArgumentException, NdexException { logger.info(userNameForLog() + "[start: Setting " + parameter + "=" + value + " for network " + networkId + "]"); try (ODatabaseDocumentTx db = NdexDatabase.getInstance().getAConnection()){ if (Helper.isAdminOfNetwork(db, networkId, getLoggedInUser().getExternalId().toString())) { if ( parameter.equals(readOnlyParameter)) { boolean bv = Boolean.parseBoolean(value); try (NetworkDAOTx daoNew = new NetworkDAOTx()) { long oldId = daoNew.setReadOnlyFlag(networkId, bv, getLoggedInUser().getAccountName()); logger.info(userNameForLog() + "[end: setting " + parameter + "=" + value + " for network " + networkId + "]"); return Long.toString(oldId); } } } throw new UnauthorizedOperationException("Only an administrator can set a network flag."); } } }
Refactoring: using NdexProvenaceEventType.
src/main/java/org/ndexbio/rest/services/NetworkAService.java
Refactoring: using NdexProvenaceEventType.
<ide><path>rc/main/java/org/ndexbio/rest/services/NetworkAService.java <ide> import org.ndexbio.model.network.query.EdgeCollectionQuery; <ide> import org.ndexbio.model.object.Membership; <ide> import org.ndexbio.model.object.NdexPropertyValuePair; <add>import org.ndexbio.model.object.NdexProvenanceEventType; <ide> import org.ndexbio.model.object.Permissions; <ide> import org.ndexbio.model.object.Priority; <ide> import org.ndexbio.model.object.ProvenanceEntity; <ide> Helper.populateProvenanceEntity(newProv, networkService.getCurrentNetwork()); <ide> <ide> Timestamp now = new Timestamp(Calendar.getInstance().getTimeInMillis()); <del> ProvenanceEvent event = new ProvenanceEvent("Add Namespace", now); <add> ProvenanceEvent event = new ProvenanceEvent(NdexProvenanceEventType.ADD_NAMESPACE, now); <ide> List<SimplePropertyValuePair> eventProperties = new ArrayList<>(); <ide> Helper.addUserInfoToProvenanceEventProperties( eventProperties, this.getLoggedInUser()); <ide> String namespaceString = namespace.getPrefix() + " : " + namespace.getUri(); <ide> <ide> NetworkSummary summary = daoNew.getNetworkSummary(daoNew.getRecordByUUIDStr(networkId, null)); <ide> Helper.populateProvenanceEntity(newProv, summary); <del> ProvenanceEvent event = new ProvenanceEvent("Set Network Properties", summary.getModificationTime()); <add> ProvenanceEvent event = new ProvenanceEvent(NdexProvenanceEventType.SET_NETWORK_PROPERTIES, summary.getModificationTime()); <ide> List<SimplePropertyValuePair> eventProperties = new ArrayList<>(); <ide> Helper.addUserInfoToProvenanceEventProperties( eventProperties, user); <ide> for( NdexPropertyValuePair vp : properties ) <ide> <ide> NetworkSummary summary = daoNew.getNetworkSummary(daoNew.getRecordByUUIDStr(networkId, null)); <ide> Helper.populateProvenanceEntity(newProv, summary); <del> ProvenanceEvent event = new ProvenanceEvent("Set Network Presentation Properties", summary.getModificationTime()); <add> ProvenanceEvent event = new ProvenanceEvent(NdexProvenanceEventType.SET_PRESENTATION_PROPERTIES, summary.getModificationTime()); <ide> <ide> List<SimplePropertyValuePair> eventProperties = new ArrayList<>(); <ide> Helper.addUserInfoToProvenanceEventProperties( eventProperties, user); <ide> <ide> Helper.populateProvenanceEntity(newProv, networkDao, networkId); <ide> <del> ProvenanceEvent event = new ProvenanceEvent("Update Network Profile", summary.getModificationTime()); <add> ProvenanceEvent event = new ProvenanceEvent(NdexProvenanceEventType.UPDATE_NETWORK_PROFILE, summary.getModificationTime()); <ide> <ide> List<SimplePropertyValuePair> eventProperties = new ArrayList<>(); <ide> Helper.addUserInfoToProvenanceEventProperties(eventProperties, user); <ide> <ide> Helper.populateProvenanceEntity(entity, summary); <ide> <del> ProvenanceEvent event = new ProvenanceEvent("Program Upload", summary.getModificationTime()); <add> ProvenanceEvent event = new ProvenanceEvent(NdexProvenanceEventType.PROGRAM_UPLOAD, summary.getModificationTime()); <ide> <ide> List<SimplePropertyValuePair> eventProperties = new ArrayList<>(); <ide> Helper.addUserInfoToProvenanceEventProperties( eventProperties, this.getLoggedInUser());
Java
apache-2.0
a7d30136a24cfb6e70269e1612ed6d3598c03d12
0
ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,jerome79/OG-Platform,jerome79/OG-Platform,DevStreet/FinanceAnalytics,codeaudit/OG-Platform,McLeodMoores/starling,nssales/OG-Platform,nssales/OG-Platform,McLeodMoores/starling,jeorme/OG-Platform,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,McLeodMoores/starling,jerome79/OG-Platform,nssales/OG-Platform,jerome79/OG-Platform,jeorme/OG-Platform,jeorme/OG-Platform,codeaudit/OG-Platform,McLeodMoores/starling,nssales/OG-Platform,ChinaQuants/OG-Platform,ChinaQuants/OG-Platform,ChinaQuants/OG-Platform,codeaudit/OG-Platform,jeorme/OG-Platform,DevStreet/FinanceAnalytics
/** * Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.analytics.financial.interestrate.payments.method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.Validate; import com.opengamma.analytics.financial.interestrate.InstrumentDerivative; import com.opengamma.analytics.financial.interestrate.InterestRateCurveSensitivity; import com.opengamma.analytics.financial.interestrate.YieldCurveBundle; import com.opengamma.analytics.financial.interestrate.method.PricingMethod; import com.opengamma.analytics.financial.interestrate.payments.derivative.CouponONCompounded; import com.opengamma.analytics.financial.model.interestrate.curve.YieldAndDiscountCurve; import com.opengamma.util.money.CurrencyAmount; import com.opengamma.util.tuple.DoublesPair; /** * @deprecated Use {@link com.opengamma.analytics.financial.interestrate.payments.provider.CouponONCompoundedDiscountingMethod} */ @Deprecated public final class CouponONCompoundedDiscountingMethod implements PricingMethod { /** * The method unique instance. */ private static final CouponONCompoundedDiscountingMethod INSTANCE = new CouponONCompoundedDiscountingMethod(); /** * Return the unique instance of the class. * @return The instance. */ public static CouponONCompoundedDiscountingMethod getInstance() { return INSTANCE; } /** * Private constructor. */ private CouponONCompoundedDiscountingMethod() { } /** * Computes the present value. * @param coupon The coupon. * @param curves The curves. * @return The present value. */ public CurrencyAmount presentValue(final CouponONCompounded coupon, final YieldCurveBundle curves) { Validate.notNull(coupon, "Coupon"); Validate.notNull(curves, "Curves"); final YieldAndDiscountCurve forwardCurve = curves.getCurve(coupon.getForwardCurveName()); final YieldAndDiscountCurve discountingCurve = curves.getCurve(coupon.getFundingCurveName()); double ratio = 1.0; double forwardRatei; for (int i = 0; i < coupon.getFixingPeriodAccrualFactors().length; i++) { forwardRatei = (forwardCurve.getDiscountFactor(coupon.getFixingPeriodEndTimes()[i]) / forwardCurve.getDiscountFactor(coupon.getFixingPeriodStartTimes()[i]) - 1) / coupon.getFixingPeriodAccrualFactorsActAct()[i]; ratio *= Math.pow(1 + forwardRatei, coupon.getFixingPeriodAccrualFactors()[i]); } final double df = discountingCurve.getDiscountFactor(coupon.getPaymentTime()); final double pv = df * coupon.getNotionalAccrued() * ratio; return CurrencyAmount.of(coupon.getCurrency(), pv); } @Override public CurrencyAmount presentValue(final InstrumentDerivative instrument, final YieldCurveBundle curves) { Validate.isTrue(instrument instanceof CouponONCompounded, "Coupon ON compounded"); return presentValue(instrument, curves); } /** * Compute the present value sensitivity to rates of a OIS coupon by discounting. * @param coupon The coupon. * @param curves The yield curves. Should contain the discounting and forward curves associated. * @return The present value curve sensitivities. */ public InterestRateCurveSensitivity presentValueCurveSensitivity(final CouponONCompounded coupon, final YieldCurveBundle curves) { Validate.notNull(coupon, "Coupon"); Validate.notNull(curves, "Curves"); final YieldAndDiscountCurve forwardCurve = curves.getCurve(coupon.getForwardCurveName()); final YieldAndDiscountCurve discountingCurve = curves.getCurve(coupon.getFundingCurveName()); final double df = discountingCurve.getDiscountFactor(coupon.getPaymentTime()); double ratio = 1.0; final double[] discountFactorStart = new double[coupon.getFixingPeriodAccrualFactors().length]; final double[] discountFactorEnd = new double[coupon.getFixingPeriodAccrualFactors().length]; final double[] forwardRate = new double[coupon.getFixingPeriodAccrualFactors().length]; for (int i = 0; i < coupon.getFixingPeriodAccrualFactors().length; i++) { discountFactorStart[i] = forwardCurve.getDiscountFactor(coupon.getFixingPeriodStartTimes()[i]); discountFactorEnd[i] = forwardCurve.getDiscountFactor(coupon.getFixingPeriodEndTimes()[i]); // forwardRate[i] = (discountFactorEnd[i] / discountFactorStart[i] - 1) / coupon.getFixingPeriodAccrualFactorsActAct()[i]; forwardRate[i] = (discountFactorStart[i] / discountFactorEnd[i] - 1) / coupon.getFixingPeriodAccrualFactorsActAct()[i]; ratio *= Math.pow(1 + forwardRate[i], coupon.getFixingPeriodAccrualFactors()[i]); } // Backward sweep final double pvBar = 1.0; final double ratioBar = coupon.getNotionalAccrued() * df * pvBar; final double[] discountFactorStartBar = new double[coupon.getFixingPeriodAccrualFactors().length]; final double[] discountFactorEndBar = new double[coupon.getFixingPeriodAccrualFactors().length]; final double[] forwardBar = new double[coupon.getFixingPeriodAccrualFactors().length]; for (int i = 0; i < coupon.getFixingPeriodAccrualFactors().length; i++) { // forwardBar[i] = ratioBar * ratioBar * coupon.getFixingPeriodAccrualFactors()[i] / // (1 + forwardRate[i]); forwardBar[i] = ratio * ratioBar * coupon.getFixingPeriodAccrualFactors()[i] / (1 + forwardRate[i]); // discountFactorStartBar[i] = forwardBar[i] * discountFactorEnd[i] / (discountFactorStart[i] * discountFactorStart[i]) / coupon.getFixingPeriodAccrualFactorsActAct()[i]; // discountFactorEndBar[i] = -forwardBar[i] / (discountFactorStart[i] * coupon.getFixingPeriodAccrualFactorsActAct()[i]); discountFactorStartBar[i] = forwardBar[i] / (discountFactorEnd[i] * coupon.getFixingPeriodAccrualFactorsActAct()[i]); discountFactorEndBar[i] = -forwardBar[i] * discountFactorStart[i] / (discountFactorEnd[i] * discountFactorEnd[i]) / coupon.getFixingPeriodAccrualFactorsActAct()[i]; } final double dfBar = coupon.getNotionalAccrued() * ratio * pvBar; final Map<String, List<DoublesPair>> mapDsc = new HashMap<>(); final List<DoublesPair> listDiscounting = new ArrayList<>(); listDiscounting.add(new DoublesPair(coupon.getPaymentTime(), -coupon.getPaymentTime() * df * dfBar)); mapDsc.put(coupon.getFundingCurveName(), listDiscounting); InterestRateCurveSensitivity result = new InterestRateCurveSensitivity(mapDsc); final Map<String, List<DoublesPair>> mapFwd = new HashMap<>(); final List<DoublesPair> listForward = new ArrayList<>(); for (int i = 0; i < coupon.getFixingPeriodAccrualFactors().length; i++) { listForward.add(new DoublesPair(coupon.getFixingPeriodStartTimes()[i], -coupon.getFixingPeriodStartTimes()[i] * discountFactorStart[i] * discountFactorStartBar[i])); listForward.add(new DoublesPair(coupon.getFixingPeriodEndTimes()[i], -coupon.getFixingPeriodEndTimes()[i] * discountFactorEnd[i] * discountFactorEndBar[i])); } mapFwd.put(coupon.getForwardCurveName(), listForward); result = result.plus(new InterestRateCurveSensitivity(mapFwd)); return result; } }
projects/OG-Analytics/src/main/java/com/opengamma/analytics/financial/interestrate/payments/method/CouponONCompoundedDiscountingMethod.java
/** * Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.analytics.financial.interestrate.payments.method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.Validate; import com.opengamma.analytics.financial.interestrate.InstrumentDerivative; import com.opengamma.analytics.financial.interestrate.InterestRateCurveSensitivity; import com.opengamma.analytics.financial.interestrate.YieldCurveBundle; import com.opengamma.analytics.financial.interestrate.method.PricingMethod; import com.opengamma.analytics.financial.interestrate.payments.derivative.CouponONCompounded; import com.opengamma.analytics.financial.model.interestrate.curve.YieldAndDiscountCurve; import com.opengamma.util.money.CurrencyAmount; import com.opengamma.util.tuple.DoublesPair; /** * @deprecated Use {@link com.opengamma.analytics.financial.interestrate.payments.provider.CouponONCompoundedDiscountingMethod} */ @Deprecated public final class CouponONCompoundedDiscountingMethod implements PricingMethod { /** * The method unique instance. */ private static final CouponONCompoundedDiscountingMethod INSTANCE = new CouponONCompoundedDiscountingMethod(); /** * Return the unique instance of the class. * @return The instance. */ public static CouponONCompoundedDiscountingMethod getInstance() { return INSTANCE; } /** * Private constructor. */ private CouponONCompoundedDiscountingMethod() { } /** * Computes the present value. * @param coupon The coupon. * @param curves The curves. * @return The present value. */ public CurrencyAmount presentValue(final CouponONCompounded coupon, final YieldCurveBundle curves) { Validate.notNull(coupon, "Coupon"); Validate.notNull(curves, "Curves"); final YieldAndDiscountCurve forwardCurve = curves.getCurve(coupon.getForwardCurveName()); final YieldAndDiscountCurve discountingCurve = curves.getCurve(coupon.getFundingCurveName()); double ratio = 1.0; double forwardRatei; for (int i = 0; i < coupon.getFixingPeriodAccrualFactors().length; i++) { forwardRatei = (forwardCurve.getDiscountFactor(coupon.getFixingPeriodEndTimes()[i]) / forwardCurve.getDiscountFactor(coupon.getFixingPeriodStartTimes()[i]) - 1) / coupon.getFixingPeriodAccrualFactorsActAct()[i]; ratio *= Math.pow(1 + forwardRatei, coupon.getFixingPeriodAccrualFactors()[i]); } final double df = discountingCurve.getDiscountFactor(coupon.getPaymentTime()); final double pv = df * coupon.getNotionalAccrued() * ratio; return CurrencyAmount.of(coupon.getCurrency(), pv); } @Override public CurrencyAmount presentValue(final InstrumentDerivative instrument, final YieldCurveBundle curves) { Validate.isTrue(instrument instanceof CouponONCompounded, "Coupon ON compounded"); return presentValue(instrument, curves); } /** * Compute the present value sensitivity to rates of a OIS coupon by discounting. * @param coupon The coupon. * @param curves The yield curves. Should contain the discounting and forward curves associated. * @return The present value curve sensitivities. */ public InterestRateCurveSensitivity presentValueCurveSensitivity(final CouponONCompounded coupon, final YieldCurveBundle curves) { Validate.notNull(coupon, "Coupon"); Validate.notNull(curves, "Curves"); final YieldAndDiscountCurve forwardCurve = curves.getCurve(coupon.getForwardCurveName()); final YieldAndDiscountCurve discountingCurve = curves.getCurve(coupon.getFundingCurveName()); final double df = discountingCurve.getDiscountFactor(coupon.getPaymentTime()); double ratio = 1.0; final double[] discountFactorStart = new double[coupon.getFixingPeriodAccrualFactors().length]; final double[] discountFactorEnd = new double[coupon.getFixingPeriodAccrualFactors().length]; final double[] forwardRate = new double[coupon.getFixingPeriodAccrualFactors().length]; for (int i = 0; i < coupon.getFixingPeriodAccrualFactors().length; i++) { discountFactorStart[i] = forwardCurve.getDiscountFactor(coupon.getFixingPeriodStartTimes()[i]); discountFactorEnd[i] = forwardCurve.getDiscountFactor(coupon.getFixingPeriodEndTimes()[i]); forwardRate[i] = (discountFactorEnd[i] / discountFactorStart[i] - 1) / coupon.getFixingPeriodAccrualFactorsActAct()[i]; ratio *= Math.pow(1 + forwardRate[i], coupon.getFixingPeriodAccrualFactors()[i]); } // Backward sweep final double pvBar = 1.0; final double ratioBar = coupon.getNotionalAccrued() * df * pvBar; final double[] discountFactorStartBar = new double[coupon.getFixingPeriodAccrualFactors().length]; final double[] discountFactorEndBar = new double[coupon.getFixingPeriodAccrualFactors().length]; final double[] forwardBar = new double[coupon.getFixingPeriodAccrualFactors().length]; for (int i = 0; i < coupon.getFixingPeriodAccrualFactors().length; i++) { forwardBar[i] = ratioBar * ratioBar * coupon.getFixingPeriodAccrualFactors()[i] / (1 + forwardRate[i]); discountFactorStartBar[i] = forwardBar[i] * discountFactorEnd[i] / (discountFactorStart[i] * discountFactorStart[i]) / coupon.getFixingPeriodAccrualFactorsActAct()[i]; discountFactorEndBar[i] = forwardBar[i] / (discountFactorStart[i] * coupon.getFixingPeriodAccrualFactorsActAct()[i]); } final double dfBar = coupon.getNotionalAccrued() * ratio * pvBar; final Map<String, List<DoublesPair>> mapDsc = new HashMap<>(); final List<DoublesPair> listDiscounting = new ArrayList<>(); listDiscounting.add(new DoublesPair(coupon.getPaymentTime(), -coupon.getPaymentTime() * df * dfBar)); mapDsc.put(coupon.getFundingCurveName(), listDiscounting); InterestRateCurveSensitivity result = new InterestRateCurveSensitivity(mapDsc); final Map<String, List<DoublesPair>> mapFwd = new HashMap<>(); final List<DoublesPair> listForward = new ArrayList<>(); for (int i = 0; i < coupon.getFixingPeriodAccrualFactors().length; i++) { listForward.add(new DoublesPair(coupon.getFixingPeriodStartTimes()[i], -coupon.getFixingPeriodStartTimes()[i] * discountFactorStart[i] * discountFactorStartBar[i])); listForward.add(new DoublesPair(coupon.getFixingPeriodEndTimes()[i], -coupon.getFixingPeriodEndTimes()[i] * discountFactorEnd[i] * discountFactorEndBar[i])); } mapFwd.put(coupon.getForwardCurveName(), listForward); result = result.plus(new InterestRateCurveSensitivity(mapFwd)); return result; } }
PLAT-4732: Changing PV01 calculation of BRL Pre-DI swaps with the new adjoint sensitivity formulae
projects/OG-Analytics/src/main/java/com/opengamma/analytics/financial/interestrate/payments/method/CouponONCompoundedDiscountingMethod.java
PLAT-4732: Changing PV01 calculation of BRL Pre-DI swaps with the new adjoint sensitivity formulae
<ide><path>rojects/OG-Analytics/src/main/java/com/opengamma/analytics/financial/interestrate/payments/method/CouponONCompoundedDiscountingMethod.java <ide> for (int i = 0; i < coupon.getFixingPeriodAccrualFactors().length; i++) { <ide> discountFactorStart[i] = forwardCurve.getDiscountFactor(coupon.getFixingPeriodStartTimes()[i]); <ide> discountFactorEnd[i] = forwardCurve.getDiscountFactor(coupon.getFixingPeriodEndTimes()[i]); <del> <del> forwardRate[i] = (discountFactorEnd[i] / discountFactorStart[i] - 1) / coupon.getFixingPeriodAccrualFactorsActAct()[i]; <add> <add>// forwardRate[i] = (discountFactorEnd[i] / discountFactorStart[i] - 1) / coupon.getFixingPeriodAccrualFactorsActAct()[i]; <add> forwardRate[i] = (discountFactorStart[i] / discountFactorEnd[i] - 1) / coupon.getFixingPeriodAccrualFactorsActAct()[i]; <ide> ratio *= Math.pow(1 + forwardRate[i], coupon.getFixingPeriodAccrualFactors()[i]); <ide> } <ide> // Backward sweep <ide> final double[] discountFactorEndBar = new double[coupon.getFixingPeriodAccrualFactors().length]; <ide> final double[] forwardBar = new double[coupon.getFixingPeriodAccrualFactors().length]; <ide> for (int i = 0; i < coupon.getFixingPeriodAccrualFactors().length; i++) { <del> forwardBar[i] = ratioBar * ratioBar * coupon.getFixingPeriodAccrualFactors()[i] / <del> (1 + forwardRate[i]); <del> discountFactorStartBar[i] = forwardBar[i] * discountFactorEnd[i] / (discountFactorStart[i] * discountFactorStart[i]) / coupon.getFixingPeriodAccrualFactorsActAct()[i]; <del> discountFactorEndBar[i] = forwardBar[i] / (discountFactorStart[i] * coupon.getFixingPeriodAccrualFactorsActAct()[i]); <add>// forwardBar[i] = ratioBar * ratioBar * coupon.getFixingPeriodAccrualFactors()[i] / <add>// (1 + forwardRate[i]); <add> forwardBar[i] = ratio * ratioBar * coupon.getFixingPeriodAccrualFactors()[i] / (1 + forwardRate[i]); <add>// discountFactorStartBar[i] = forwardBar[i] * discountFactorEnd[i] / (discountFactorStart[i] * discountFactorStart[i]) / coupon.getFixingPeriodAccrualFactorsActAct()[i]; <add>// discountFactorEndBar[i] = -forwardBar[i] / (discountFactorStart[i] * coupon.getFixingPeriodAccrualFactorsActAct()[i]); <add> discountFactorStartBar[i] = forwardBar[i] / (discountFactorEnd[i] * coupon.getFixingPeriodAccrualFactorsActAct()[i]); <add> discountFactorEndBar[i] = -forwardBar[i] * discountFactorStart[i] / (discountFactorEnd[i] * discountFactorEnd[i]) / coupon.getFixingPeriodAccrualFactorsActAct()[i]; <ide> } <ide> final double dfBar = coupon.getNotionalAccrued() * ratio * pvBar; <ide> final Map<String, List<DoublesPair>> mapDsc = new HashMap<>();
Java
mit
19571b85e7c32862ccf9d608433c2773e236ef3c
0
IamWaffle/CryptoWatch
package cryptowatch; import com.eclipsesource.json.Json; import com.eclipsesource.json.JsonArray; import com.eclipsesource.json.JsonValue; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Objects; import java.util.Timer; import java.util.TimerTask; import org.apache.commons.io.IOUtils; public class Market { static JsonArray arrayBittrex; public static void startTimer(){ Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { String url = "https://bittrex.com/api/v1.1/public/getmarketsummaries"; try { URL url2 = new URL(url); URLConnection con = url2.openConnection(); InputStream in = con.getInputStream(); String encoding = "UTF-8"; String rawBittrex = IOUtils.toString(in, encoding); arrayBittrex = Json.parse(rawBittrex).asObject().get("result").asArray(); } catch(MalformedURLException e) {} catch(IOException e) {} } }, 0,5000); } public static float getPrice(String exchange, String market) { if(exchange.equals("bittrex")) { int numArrays = arrayBittrex.size(); for(int i=0; i<numArrays; i++){ if(market.equalsIgnoreCase(arrayBittrex.get(i).asObject().getString("MarketName", ""))) { float last = arrayBittrex.get(i).asObject().getFloat("Last", 0); return last; } } } return 0; } }
src/cryptowatch/Market.java
package cryptowatch; import com.eclipsesource.json.Json; import com.eclipsesource.json.JsonArray; import com.eclipsesource.json.JsonValue; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Objects; import java.util.Timer; import java.util.TimerTask; import org.apache.commons.io.IOUtils; public class Market { static String rawBittrex; public static void startTimer(){ Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { String url = "https://bittrex.com/api/v1.1/public/getmarketsummaries"; try { URL url2 = new URL(url); URLConnection con = url2.openConnection(); InputStream in = con.getInputStream(); String encoding = "UTF-8"; rawBittrex = IOUtils.toString(in, encoding); } catch(MalformedURLException e) {} catch(IOException e) {} } }, 0,5000); } public static float getPrice(String exchange, String market) { if(exchange.equals("bittrex")) { JsonArray arrayBittrex = Json.parse(rawBittrex).asObject().get("result").asArray(); int numArrays = Json.parse(rawBittrex).asObject().get("result").asArray().size(); for(int i=0; i<numArrays; i++){ if(market.equalsIgnoreCase(arrayBittrex.get(i).asObject().getString("MarketName", ""))) { float last = arrayBittrex.get(i).asObject().getFloat("Last", 0); return last; } } } return 0; } }
Reorganize strings and arrays
src/cryptowatch/Market.java
Reorganize strings and arrays
<ide><path>rc/cryptowatch/Market.java <ide> import org.apache.commons.io.IOUtils; <ide> <ide> public class Market { <del> static String rawBittrex; <add> static JsonArray arrayBittrex; <ide> <ide> public static void startTimer(){ <ide> Timer timer = new Timer(); <ide> URLConnection con = url2.openConnection(); <ide> InputStream in = con.getInputStream(); <ide> String encoding = "UTF-8"; <del> rawBittrex = IOUtils.toString(in, encoding); <add> String rawBittrex = IOUtils.toString(in, encoding); <add> arrayBittrex = Json.parse(rawBittrex).asObject().get("result").asArray(); <ide> } <ide> catch(MalformedURLException e) {} <ide> catch(IOException e) {} <ide> <ide> public static float getPrice(String exchange, String market) { <ide> if(exchange.equals("bittrex")) { <del> JsonArray arrayBittrex = Json.parse(rawBittrex).asObject().get("result").asArray(); <del> int numArrays = Json.parse(rawBittrex).asObject().get("result").asArray().size(); <del> <add> int numArrays = arrayBittrex.size(); <ide> for(int i=0; i<numArrays; i++){ <ide> if(market.equalsIgnoreCase(arrayBittrex.get(i).asObject().getString("MarketName", ""))) { <ide> float last = arrayBittrex.get(i).asObject().getFloat("Last", 0);
Java
mit
error: pathspec 'AIC_InvertedIndex/src/com/aic/keywordanalysis/CountryNametoCountryCode.java' did not match any file(s) known to git
9045cad4a27e17a9e176a599f744067ad6e777f1
1
lokresh88/TwitterTigers,lokresh88/TwitterTigers,lokresh88/TwitterTigers
package com.aic.keywordanalysis; import java.util.ArrayList; import java.util.HashMap; public class CountryNametoCountryCode { static HashMap<String,String> NametoCode = new HashMap<String, String>(); // ArrayList<String> Country = new ArrayList<String>(); // ArrayList<String> Code = new ArrayList<String>(); public void BuildHashMap() { String Codes="AF,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CY,CZ,DK,DJ,DM,DO,TP,EC,EG,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,FX,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,AN,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,KN,LC,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,SS,GS,ES,LK,SH,PM,SD,SR,SJ,SZ,SE,CH,SY,TW,TJ,TZ,TH,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW"; String Countries="AFGHANISTAN,ALBANIA,ALGERIA,AMERICAN SAMOA,ANDORRA,ANGOLA,ANGUILLA,ANTARCTICA,ANTIGUA AND BARBUDA,ARGENTINA,ARMENIA,ARUBA,AUSTRALIA,AUSTRIA,AZERBAIJAN,BAHAMAS,BAHRAIN,BANGLADESH,BARBADOS,BELARUS,BELGIUM,BELIZE,BENIN,BERMUDA,BHUTAN,BOLIVIA,BOSNIA AND HERZEGOWINA,BOTSWANA,BOUVET ISLAND,BRAZIL,BRITISH INDIAN OCEAN TERRITORY,BRUNEI DARUSSALAM,BULGARIA,BURKINA FASO,BURUNDI,CAMBODIA,CAMEROON,CANADA,CAPE VERDE,CAYMAN ISLANDS,CENTRAL AFRICAN REPUBLIC,CHAD,CHILE,CHINA,CHRISTMAS ISLAND,COCOS (KEELING) ISLANDS,COLOMBIA,COMOROS,CONGO,COOK ISLANDS,COSTA RICA,COTE D'IVOIRE,CROATIA,CUBA,CYPRUS,CZECH REPUBLIC,DENMARK,DJIBOUTI,DOMINICA,DOMINICAN REPUBLIC,EAST TIMOR,ECUADOR,EGYPT,EL SALVADOR,EQUATORIAL GUINEA,ERITREA,ESTONIA,ETHIOPIA,FALKLAND ISLANDS (MALVINAS),FAROE ISLANDS,FIJI,FINLAND,FRANCE,FRANCE METROPOLITAN,FRENCH GUIANA,FRENCH POLYNESIA,FRENCH SOUTHERN TERRITORIES,GABON,GAMBIA,GEORGIA,GERMANY,GHANA,GIBRALTAR,GREECE,GREENLAND,GRENADA,GUADELOUPE,GUAM,GUATEMALA,GUINEA,GUINEA-BISSAU,GUYANA,HAITI,HEARD AND MC DONALD ISLANDS,HOLY SEE (VATICAN CITY STATE),HONDURAS,HONG KONG,HUNGARY,ICELAND,INDIA,INDONESIA,IRAN (ISLAMIC REPUBLIC OF),IRAQ,IRELAND,ISRAEL,ITALY,JAMAICA,JAPAN,JORDAN,KAZAKHSTAN,KENYA,KIRIBATI,SOUTH KOREA,NORTH KOREA, REPUBLIC OF,KUWAIT,KYRGYZSTAN,LAOS ,LATVIA,LEBANON,LESOTHO,LIBERIA,LIBYAN ARAB JAMAHIRIYA,LIECHTENSTEIN,LITHUANIA,LUXEMBOURG,MACAU,MACEDONIA,MADAGASCAR,MALAWI,MALAYSIA,MALDIVES,MALI,MALTA,MARSHALL ISLANDS,MARTINIQUE,MAURITANIA,MAURITIUS,MAYOTTE,MEXICO,MICRONESIA,MOLDOVA,MONACO,MONGOLIA,MONTENEGRO,MONTSERRAT,MOROCCO,MOZAMBIQUE,MYANMAR,NAMIBIA,NAURU,NEPAL,NETHERLANDS,NETHERLANDS ANTILLES,NEW CALEDONIA,NEW ZEALAND,NICARAGUA,NIGER,NIGERIA,NIUE,NORFOLK ISLAND,NORTHERN MARIANA ISLANDS,NORWAY,OMAN,PAKISTAN,PALAU,PANAMA,PAPUA NEW GUINEA,PARAGUAY,PERU,PHILIPPINES,PITCAIRN,POLAND,PORTUGAL,PUERTO RICO,QATAR,REUNION,ROMANIA,RUSSIAN FEDERATION,RWANDA,SAINT KITTS AND NEVIS,SAINT LUCIA,SAINT VINCENT AND THE GRENADINES,SAMOA,SAN MARINO,SAO TOME AND PRINCIPE,SAUDI ARABIA,SENEGAL,SERBIA,SEYCHELLES,SIERRA LEONE,SINGAPORE,SLOVAKIA (Slovak Republic),SLOVENIA,SOLOMON ISLANDS,SOMALIA,SOUTH AFRICA,SOUTH SUDAN,SOUTH GEORGIA AND SOUTH S.S.,SPAIN,SRI LANKA,ST. HELENA,ST. PIERRE AND MIQUELON,SUDAN,SURINAME,SVALBARD AND JAN MAYEN ISLANDS,SWAZILAND,SWEDEN,SWITZERLAND,SYRIAN ARAB REPUBLIC,TAIWAN,TAJIKISTAN,TANZANIA,THAILAND,TOGO,TOKELAU,TONGA,TRINIDAD AND TOBAGO,TUNISIA,TURKEY,TURKMENISTAN,TURKS AND CAICOS ISLANDS,TUVALU,UGANDA,UKRAINE,UNITED ARAB EMIRATES,UNITED KINGDOM,UNITED STATES,U.S. MINOR ISLANDS, URUGUAY,UZBEKISTAN,VANUATU,VENEZUELA,VIET NAM,VIRGIN ISLANDS (BRITISH),VIRGIN ISLANDS (U.S.),WALLIS AND FUTUNA ISLANDS,WESTERN SAHARA,YEMEN,ZAMBIA,ZIMBABWE"; // System.out.println(Codes.length()); //System.out.println(Countries.length()); String[] Codesplit=Codes.split(","); String[] Countrysplit=Countries.split(","); System.out.println(Codesplit.length); System.out.println(Countrysplit.length); for(int i=0;i<Countrysplit.length;i++) { NametoCode.put(Countrysplit[i],Codesplit[i]); System.out.println("Code:"+NametoCode.get(Countrysplit[i])); System.out.println("Country:"+Countrysplit[i]); } } public String getCountryCode(String CountryName) { return NametoCode.get(CountryName); } }
AIC_InvertedIndex/src/com/aic/keywordanalysis/CountryNametoCountryCode.java
Check in for CountryName to Country Code
AIC_InvertedIndex/src/com/aic/keywordanalysis/CountryNametoCountryCode.java
Check in for CountryName to Country Code
<ide><path>IC_InvertedIndex/src/com/aic/keywordanalysis/CountryNametoCountryCode.java <add>package com.aic.keywordanalysis; <add>import java.util.ArrayList; <add>import java.util.HashMap; <add>public class CountryNametoCountryCode { <add> static HashMap<String,String> NametoCode = new HashMap<String, String>(); <add>// ArrayList<String> Country = new ArrayList<String>(); <add>// ArrayList<String> Code = new ArrayList<String>(); <add> <add> public void BuildHashMap() <add> { <add> String Codes="AF,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CY,CZ,DK,DJ,DM,DO,TP,EC,EG,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,FX,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,AN,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,KN,LC,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,SS,GS,ES,LK,SH,PM,SD,SR,SJ,SZ,SE,CH,SY,TW,TJ,TZ,TH,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW"; <add> String Countries="AFGHANISTAN,ALBANIA,ALGERIA,AMERICAN SAMOA,ANDORRA,ANGOLA,ANGUILLA,ANTARCTICA,ANTIGUA AND BARBUDA,ARGENTINA,ARMENIA,ARUBA,AUSTRALIA,AUSTRIA,AZERBAIJAN,BAHAMAS,BAHRAIN,BANGLADESH,BARBADOS,BELARUS,BELGIUM,BELIZE,BENIN,BERMUDA,BHUTAN,BOLIVIA,BOSNIA AND HERZEGOWINA,BOTSWANA,BOUVET ISLAND,BRAZIL,BRITISH INDIAN OCEAN TERRITORY,BRUNEI DARUSSALAM,BULGARIA,BURKINA FASO,BURUNDI,CAMBODIA,CAMEROON,CANADA,CAPE VERDE,CAYMAN ISLANDS,CENTRAL AFRICAN REPUBLIC,CHAD,CHILE,CHINA,CHRISTMAS ISLAND,COCOS (KEELING) ISLANDS,COLOMBIA,COMOROS,CONGO,COOK ISLANDS,COSTA RICA,COTE D'IVOIRE,CROATIA,CUBA,CYPRUS,CZECH REPUBLIC,DENMARK,DJIBOUTI,DOMINICA,DOMINICAN REPUBLIC,EAST TIMOR,ECUADOR,EGYPT,EL SALVADOR,EQUATORIAL GUINEA,ERITREA,ESTONIA,ETHIOPIA,FALKLAND ISLANDS (MALVINAS),FAROE ISLANDS,FIJI,FINLAND,FRANCE,FRANCE METROPOLITAN,FRENCH GUIANA,FRENCH POLYNESIA,FRENCH SOUTHERN TERRITORIES,GABON,GAMBIA,GEORGIA,GERMANY,GHANA,GIBRALTAR,GREECE,GREENLAND,GRENADA,GUADELOUPE,GUAM,GUATEMALA,GUINEA,GUINEA-BISSAU,GUYANA,HAITI,HEARD AND MC DONALD ISLANDS,HOLY SEE (VATICAN CITY STATE),HONDURAS,HONG KONG,HUNGARY,ICELAND,INDIA,INDONESIA,IRAN (ISLAMIC REPUBLIC OF),IRAQ,IRELAND,ISRAEL,ITALY,JAMAICA,JAPAN,JORDAN,KAZAKHSTAN,KENYA,KIRIBATI,SOUTH KOREA,NORTH KOREA, REPUBLIC OF,KUWAIT,KYRGYZSTAN,LAOS ,LATVIA,LEBANON,LESOTHO,LIBERIA,LIBYAN ARAB JAMAHIRIYA,LIECHTENSTEIN,LITHUANIA,LUXEMBOURG,MACAU,MACEDONIA,MADAGASCAR,MALAWI,MALAYSIA,MALDIVES,MALI,MALTA,MARSHALL ISLANDS,MARTINIQUE,MAURITANIA,MAURITIUS,MAYOTTE,MEXICO,MICRONESIA,MOLDOVA,MONACO,MONGOLIA,MONTENEGRO,MONTSERRAT,MOROCCO,MOZAMBIQUE,MYANMAR,NAMIBIA,NAURU,NEPAL,NETHERLANDS,NETHERLANDS ANTILLES,NEW CALEDONIA,NEW ZEALAND,NICARAGUA,NIGER,NIGERIA,NIUE,NORFOLK ISLAND,NORTHERN MARIANA ISLANDS,NORWAY,OMAN,PAKISTAN,PALAU,PANAMA,PAPUA NEW GUINEA,PARAGUAY,PERU,PHILIPPINES,PITCAIRN,POLAND,PORTUGAL,PUERTO RICO,QATAR,REUNION,ROMANIA,RUSSIAN FEDERATION,RWANDA,SAINT KITTS AND NEVIS,SAINT LUCIA,SAINT VINCENT AND THE GRENADINES,SAMOA,SAN MARINO,SAO TOME AND PRINCIPE,SAUDI ARABIA,SENEGAL,SERBIA,SEYCHELLES,SIERRA LEONE,SINGAPORE,SLOVAKIA (Slovak Republic),SLOVENIA,SOLOMON ISLANDS,SOMALIA,SOUTH AFRICA,SOUTH SUDAN,SOUTH GEORGIA AND SOUTH S.S.,SPAIN,SRI LANKA,ST. HELENA,ST. PIERRE AND MIQUELON,SUDAN,SURINAME,SVALBARD AND JAN MAYEN ISLANDS,SWAZILAND,SWEDEN,SWITZERLAND,SYRIAN ARAB REPUBLIC,TAIWAN,TAJIKISTAN,TANZANIA,THAILAND,TOGO,TOKELAU,TONGA,TRINIDAD AND TOBAGO,TUNISIA,TURKEY,TURKMENISTAN,TURKS AND CAICOS ISLANDS,TUVALU,UGANDA,UKRAINE,UNITED ARAB EMIRATES,UNITED KINGDOM,UNITED STATES,U.S. MINOR ISLANDS, URUGUAY,UZBEKISTAN,VANUATU,VENEZUELA,VIET NAM,VIRGIN ISLANDS (BRITISH),VIRGIN ISLANDS (U.S.),WALLIS AND FUTUNA ISLANDS,WESTERN SAHARA,YEMEN,ZAMBIA,ZIMBABWE"; <add> // System.out.println(Codes.length()); <add> //System.out.println(Countries.length()); <add> String[] Codesplit=Codes.split(","); <add> String[] Countrysplit=Countries.split(","); <add> System.out.println(Codesplit.length); <add> System.out.println(Countrysplit.length); <add> for(int i=0;i<Countrysplit.length;i++) <add> { <add> NametoCode.put(Countrysplit[i],Codesplit[i]); <add> System.out.println("Code:"+NametoCode.get(Countrysplit[i])); <add> System.out.println("Country:"+Countrysplit[i]); <add> <add> } <add> } <add> public String getCountryCode(String CountryName) <add> { <add> return NametoCode.get(CountryName); <add> } <add>}
Java
apache-2.0
2963d59ed21de246390426cbdb57c160a4f65303
0
JingchengDu/hbase,JingchengDu/hbase,ndimiduk/hbase,Apache9/hbase,mahak/hbase,mahak/hbase,ndimiduk/hbase,vincentpoon/hbase,ChinmaySKulkarni/hbase,ultratendency/hbase,francisliu/hbase,bijugs/hbase,vincentpoon/hbase,ndimiduk/hbase,HubSpot/hbase,ChinmaySKulkarni/hbase,bijugs/hbase,gustavoanatoly/hbase,bijugs/hbase,Eshcar/hbase,JingchengDu/hbase,Apache9/hbase,Apache9/hbase,francisliu/hbase,Apache9/hbase,apurtell/hbase,HubSpot/hbase,ultratendency/hbase,Apache9/hbase,JingchengDu/hbase,mahak/hbase,mahak/hbase,ChinmaySKulkarni/hbase,bijugs/hbase,mahak/hbase,gustavoanatoly/hbase,francisliu/hbase,apurtell/hbase,mahak/hbase,apurtell/hbase,vincentpoon/hbase,ultratendency/hbase,ChinmaySKulkarni/hbase,ChinmaySKulkarni/hbase,mahak/hbase,mahak/hbase,francisliu/hbase,Apache9/hbase,mahak/hbase,vincentpoon/hbase,Eshcar/hbase,ndimiduk/hbase,vincentpoon/hbase,bijugs/hbase,ndimiduk/hbase,vincentpoon/hbase,bijugs/hbase,gustavoanatoly/hbase,vincentpoon/hbase,ndimiduk/hbase,Eshcar/hbase,HubSpot/hbase,apurtell/hbase,ultratendency/hbase,HubSpot/hbase,gustavoanatoly/hbase,francisliu/hbase,bijugs/hbase,ultratendency/hbase,ChinmaySKulkarni/hbase,bijugs/hbase,HubSpot/hbase,ultratendency/hbase,gustavoanatoly/hbase,ndimiduk/hbase,JingchengDu/hbase,gustavoanatoly/hbase,francisliu/hbase,Eshcar/hbase,gustavoanatoly/hbase,francisliu/hbase,ultratendency/hbase,Apache9/hbase,HubSpot/hbase,francisliu/hbase,JingchengDu/hbase,apurtell/hbase,apurtell/hbase,francisliu/hbase,Eshcar/hbase,Apache9/hbase,apurtell/hbase,Eshcar/hbase,gustavoanatoly/hbase,ChinmaySKulkarni/hbase,JingchengDu/hbase,Apache9/hbase,ChinmaySKulkarni/hbase,gustavoanatoly/hbase,ndimiduk/hbase,francisliu/hbase,JingchengDu/hbase,ultratendency/hbase,ndimiduk/hbase,Apache9/hbase,gustavoanatoly/hbase,apurtell/hbase,bijugs/hbase,vincentpoon/hbase,apurtell/hbase,bijugs/hbase,ChinmaySKulkarni/hbase,apurtell/hbase,ultratendency/hbase,HubSpot/hbase,vincentpoon/hbase,Eshcar/hbase,ndimiduk/hbase,Eshcar/hbase,mahak/hbase,HubSpot/hbase,ultratendency/hbase,JingchengDu/hbase,HubSpot/hbase,JingchengDu/hbase,ChinmaySKulkarni/hbase,Eshcar/hbase,Eshcar/hbase,vincentpoon/hbase,HubSpot/hbase
/** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.tool; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.time.StopWatch; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.AuthUtil; import org.apache.hadoop.hbase.ChoreService; import org.apache.hadoop.hbase.DoNotRetryIOException; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.HRegionLocation; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.MetaTableAccessor; import org.apache.hadoop.hbase.NamespaceDescriptor; import org.apache.hadoop.hbase.ScheduledChore; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.TableNotEnabledException; import org.apache.hadoop.hbase.TableNotFoundException; import org.apache.hadoop.hbase.client.Admin; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.RegionLocator; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter; import org.apache.hadoop.hbase.tool.Canary.RegionTask.TaskType; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; import org.apache.hadoop.hbase.util.Pair; import org.apache.hadoop.hbase.util.ReflectionUtils; import org.apache.hadoop.hbase.util.RegionSplitter; import org.apache.hadoop.util.GenericOptionsParser; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; /** * HBase Canary Tool, that that can be used to do * "canary monitoring" of a running HBase cluster. * * Here are two modes * 1. region mode - Foreach region tries to get one row per column family * and outputs some information about failure or latency. * * 2. regionserver mode - Foreach regionserver tries to get one row from one table * selected randomly and outputs some information about failure or latency. */ public final class Canary implements Tool { // Sink interface used by the canary to outputs information public interface Sink { public long getReadFailureCount(); public void publishReadFailure(HRegionInfo region, Exception e); public void publishReadFailure(HRegionInfo region, HColumnDescriptor column, Exception e); public void publishReadTiming(HRegionInfo region, HColumnDescriptor column, long msTime); public long getWriteFailureCount(); public void publishWriteFailure(HRegionInfo region, Exception e); public void publishWriteFailure(HRegionInfo region, HColumnDescriptor column, Exception e); public void publishWriteTiming(HRegionInfo region, HColumnDescriptor column, long msTime); } // new extended sink for output regionserver mode info // do not change the Sink interface directly due to maintaining the API public interface ExtendedSink extends Sink { public void publishReadFailure(String table, String server); public void publishReadTiming(String table, String server, long msTime); } // Simple implementation of canary sink that allows to plot on // file or standard output timings or failures. public static class StdOutSink implements Sink { protected AtomicLong readFailureCount = new AtomicLong(0), writeFailureCount = new AtomicLong(0); @Override public long getReadFailureCount() { return readFailureCount.get(); } @Override public void publishReadFailure(HRegionInfo region, Exception e) { readFailureCount.incrementAndGet(); LOG.error(String.format("read from region %s failed", region.getRegionNameAsString()), e); } @Override public void publishReadFailure(HRegionInfo region, HColumnDescriptor column, Exception e) { readFailureCount.incrementAndGet(); LOG.error(String.format("read from region %s column family %s failed", region.getRegionNameAsString(), column.getNameAsString()), e); } @Override public void publishReadTiming(HRegionInfo region, HColumnDescriptor column, long msTime) { LOG.info(String.format("read from region %s column family %s in %dms", region.getRegionNameAsString(), column.getNameAsString(), msTime)); } @Override public long getWriteFailureCount() { return writeFailureCount.get(); } @Override public void publishWriteFailure(HRegionInfo region, Exception e) { writeFailureCount.incrementAndGet(); LOG.error(String.format("write to region %s failed", region.getRegionNameAsString()), e); } @Override public void publishWriteFailure(HRegionInfo region, HColumnDescriptor column, Exception e) { writeFailureCount.incrementAndGet(); LOG.error(String.format("write to region %s column family %s failed", region.getRegionNameAsString(), column.getNameAsString()), e); } @Override public void publishWriteTiming(HRegionInfo region, HColumnDescriptor column, long msTime) { LOG.info(String.format("write to region %s column family %s in %dms", region.getRegionNameAsString(), column.getNameAsString(), msTime)); } } // a ExtendedSink implementation public static class RegionServerStdOutSink extends StdOutSink implements ExtendedSink { @Override public void publishReadFailure(String table, String server) { readFailureCount.incrementAndGet(); LOG.error(String.format("Read from table:%s on region server:%s", table, server)); } @Override public void publishReadTiming(String table, String server, long msTime) { LOG.info(String.format("Read from table:%s on region server:%s in %dms", table, server, msTime)); } } /** * For each column family of the region tries to get one row and outputs the latency, or the * failure. */ static class RegionTask implements Callable<Void> { public enum TaskType{ READ, WRITE } private Connection connection; private HRegionInfo region; private Sink sink; private TaskType taskType; RegionTask(Connection connection, HRegionInfo region, Sink sink, TaskType taskType) { this.connection = connection; this.region = region; this.sink = sink; this.taskType = taskType; } @Override public Void call() { switch (taskType) { case READ: return read(); case WRITE: return write(); default: return read(); } } public Void read() { Table table = null; HTableDescriptor tableDesc = null; try { if (LOG.isDebugEnabled()) { LOG.debug(String.format("reading table descriptor for table %s", region.getTable())); } table = connection.getTable(region.getTable()); tableDesc = table.getTableDescriptor(); } catch (IOException e) { LOG.debug("sniffRegion failed", e); sink.publishReadFailure(region, e); if (table != null) { try { table.close(); } catch (IOException ioe) { LOG.error("Close table failed", e); } } return null; } byte[] startKey = null; Get get = null; Scan scan = null; ResultScanner rs = null; StopWatch stopWatch = new StopWatch(); for (HColumnDescriptor column : tableDesc.getColumnFamilies()) { stopWatch.reset(); startKey = region.getStartKey(); // Can't do a get on empty start row so do a Scan of first element if any instead. if (startKey.length > 0) { get = new Get(startKey); get.setCacheBlocks(false); get.setFilter(new FirstKeyOnlyFilter()); get.addFamily(column.getName()); } else { scan = new Scan(); scan.setRaw(true); scan.setCaching(1); scan.setCacheBlocks(false); scan.setFilter(new FirstKeyOnlyFilter()); scan.addFamily(column.getName()); scan.setMaxResultSize(1L); scan.setSmall(true); } if (LOG.isDebugEnabled()) { LOG.debug(String.format("reading from table %s region %s column family %s and key %s", tableDesc.getTableName(), region.getRegionNameAsString(), column.getNameAsString(), Bytes.toStringBinary(startKey))); } try { stopWatch.start(); if (startKey.length > 0) { table.get(get); } else { rs = table.getScanner(scan); rs.next(); } stopWatch.stop(); sink.publishReadTiming(region, column, stopWatch.getTime()); } catch (Exception e) { sink.publishReadFailure(region, column, e); } finally { if (rs != null) { rs.close(); } scan = null; get = null; startKey = null; } } try { table.close(); } catch (IOException e) { LOG.error("Close table failed", e); } return null; } /** * Check writes for the canary table * @return */ private Void write() { Table table = null; HTableDescriptor tableDesc = null; try { table = connection.getTable(region.getTable()); tableDesc = table.getTableDescriptor(); byte[] rowToCheck = region.getStartKey(); if (rowToCheck.length == 0) { rowToCheck = new byte[]{0x0}; } int writeValueSize = connection.getConfiguration().getInt(HConstants.HBASE_CANARY_WRITE_VALUE_SIZE_KEY, 10); for (HColumnDescriptor column : tableDesc.getColumnFamilies()) { Put put = new Put(rowToCheck); byte[] value = new byte[writeValueSize]; Bytes.random(value); put.addColumn(column.getName(), HConstants.EMPTY_BYTE_ARRAY, value); if (LOG.isDebugEnabled()) { LOG.debug(String.format("writing to table %s region %s column family %s and key %s", tableDesc.getTableName(), region.getRegionNameAsString(), column.getNameAsString(), Bytes.toStringBinary(rowToCheck))); } try { long startTime = System.currentTimeMillis(); table.put(put); long time = System.currentTimeMillis() - startTime; sink.publishWriteTiming(region, column, time); } catch (Exception e) { sink.publishWriteFailure(region, column, e); } } table.close(); } catch (IOException e) { sink.publishWriteFailure(region, e); } return null; } } /** * Get one row from a region on the regionserver and outputs the latency, or the failure. */ static class RegionServerTask implements Callable<Void> { private Connection connection; private String serverName; private HRegionInfo region; private ExtendedSink sink; private AtomicLong successes; RegionServerTask(Connection connection, String serverName, HRegionInfo region, ExtendedSink sink, AtomicLong successes) { this.connection = connection; this.serverName = serverName; this.region = region; this.sink = sink; this.successes = successes; } @Override public Void call() { TableName tableName = null; Table table = null; Get get = null; byte[] startKey = null; Scan scan = null; StopWatch stopWatch = new StopWatch(); // monitor one region on every region server stopWatch.reset(); try { tableName = region.getTable(); table = connection.getTable(tableName); startKey = region.getStartKey(); // Can't do a get on empty start row so do a Scan of first element if any instead. if (LOG.isDebugEnabled()) { LOG.debug(String.format("reading from region server %s table %s region %s and key %s", serverName, region.getTable(), region.getRegionNameAsString(), Bytes.toStringBinary(startKey))); } if (startKey.length > 0) { get = new Get(startKey); get.setCacheBlocks(false); get.setFilter(new FirstKeyOnlyFilter()); stopWatch.start(); table.get(get); stopWatch.stop(); } else { scan = new Scan(); scan.setCacheBlocks(false); scan.setFilter(new FirstKeyOnlyFilter()); scan.setCaching(1); scan.setMaxResultSize(1L); scan.setSmall(true); stopWatch.start(); ResultScanner s = table.getScanner(scan); s.next(); s.close(); stopWatch.stop(); } successes.incrementAndGet(); sink.publishReadTiming(tableName.getNameAsString(), serverName, stopWatch.getTime()); } catch (TableNotFoundException tnfe) { LOG.error("Table may be deleted", tnfe); // This is ignored because it doesn't imply that the regionserver is dead } catch (TableNotEnabledException tnee) { // This is considered a success since we got a response. successes.incrementAndGet(); LOG.debug("The targeted table was disabled. Assuming success."); } catch (DoNotRetryIOException dnrioe) { sink.publishReadFailure(tableName.getNameAsString(), serverName); LOG.error(dnrioe); } catch (IOException e) { sink.publishReadFailure(tableName.getNameAsString(), serverName); LOG.error(e); } finally { if (table != null) { try { table.close(); } catch (IOException e) {/* DO NOTHING */ LOG.error("Close table failed", e); } } scan = null; get = null; startKey = null; } return null; } } private static final int USAGE_EXIT_CODE = 1; private static final int INIT_ERROR_EXIT_CODE = 2; private static final int TIMEOUT_ERROR_EXIT_CODE = 3; private static final int ERROR_EXIT_CODE = 4; private static final long DEFAULT_INTERVAL = 6000; private static final long DEFAULT_TIMEOUT = 600000; // 10 mins private static final int MAX_THREADS_NUM = 16; // #threads to contact regions private static final Log LOG = LogFactory.getLog(Canary.class); public static final TableName DEFAULT_WRITE_TABLE_NAME = TableName.valueOf( NamespaceDescriptor.SYSTEM_NAMESPACE_NAME_STR, "canary"); private static final String CANARY_TABLE_FAMILY_NAME = "Test"; private Configuration conf = null; private long interval = 0; private Sink sink = null; private boolean useRegExp; private long timeout = DEFAULT_TIMEOUT; private boolean failOnError = true; private boolean regionServerMode = false; private boolean regionServerAllRegions = false; private boolean writeSniffing = false; private boolean treatFailureAsError = false; private TableName writeTableName = DEFAULT_WRITE_TABLE_NAME; private ExecutorService executor; // threads to retrieve data from regionservers public Canary() { this(new ScheduledThreadPoolExecutor(1), new RegionServerStdOutSink()); } public Canary(ExecutorService executor, Sink sink) { this.executor = executor; this.sink = sink; } @Override public Configuration getConf() { return conf; } @Override public void setConf(Configuration conf) { this.conf = conf; } private int parseArgs(String[] args) { int index = -1; // Process command line args for (int i = 0; i < args.length; i++) { String cmd = args[i]; if (cmd.startsWith("-")) { if (index >= 0) { // command line args must be in the form: [opts] [table 1 [table 2 ...]] System.err.println("Invalid command line options"); printUsageAndExit(); } if (cmd.equals("-help")) { // user asked for help, print the help and quit. printUsageAndExit(); } else if (cmd.equals("-daemon") && interval == 0) { // user asked for daemon mode, set a default interval between checks interval = DEFAULT_INTERVAL; } else if (cmd.equals("-interval")) { // user has specified an interval for canary breaths (-interval N) i++; if (i == args.length) { System.err.println("-interval needs a numeric value argument."); printUsageAndExit(); } try { interval = Long.parseLong(args[i]) * 1000; } catch (NumberFormatException e) { System.err.println("-interval needs a numeric value argument."); printUsageAndExit(); } } else if(cmd.equals("-regionserver")) { this.regionServerMode = true; } else if(cmd.equals("-allRegions")) { this.regionServerAllRegions = true; } else if(cmd.equals("-writeSniffing")) { this.writeSniffing = true; } else if(cmd.equals("-treatFailureAsError")) { this.treatFailureAsError = true; } else if (cmd.equals("-e")) { this.useRegExp = true; } else if (cmd.equals("-t")) { i++; if (i == args.length) { System.err.println("-t needs a numeric value argument."); printUsageAndExit(); } try { this.timeout = Long.parseLong(args[i]); } catch (NumberFormatException e) { System.err.println("-t needs a numeric value argument."); printUsageAndExit(); } } else if (cmd.equals("-writeTable")) { i++; if (i == args.length) { System.err.println("-writeTable needs a string value argument."); printUsageAndExit(); } this.writeTableName = TableName.valueOf(args[i]); } else if (cmd.equals("-f")) { i++; if (i == args.length) { System.err .println("-f needs a boolean value argument (true|false)."); printUsageAndExit(); } this.failOnError = Boolean.parseBoolean(args[i]); } else { // no options match System.err.println(cmd + " options is invalid."); printUsageAndExit(); } } else if (index < 0) { // keep track of first table name specified by the user index = i; } } if (this.regionServerAllRegions && !this.regionServerMode) { System.err.println("-allRegions can only be specified in regionserver mode."); printUsageAndExit(); } return index; } @Override public int run(String[] args) throws Exception { int index = parseArgs(args); ChoreService choreService = null; // Launches chore for refreshing kerberos credentials if security is enabled. // Please see http://hbase.apache.org/book.html#_running_canary_in_a_kerberos_enabled_cluster // for more details. final ScheduledChore authChore = AuthUtil.getAuthChore(conf); if (authChore != null) { choreService = new ChoreService("CANARY_TOOL"); choreService.scheduleChore(authChore); } // Start to prepare the stuffs Monitor monitor = null; Thread monitorThread = null; long startTime = 0; long currentTimeLength = 0; // Get a connection to use in below. try (Connection connection = ConnectionFactory.createConnection(this.conf)) { do { // Do monitor !! try { monitor = this.newMonitor(connection, index, args); monitorThread = new Thread(monitor); startTime = System.currentTimeMillis(); monitorThread.start(); while (!monitor.isDone()) { // wait for 1 sec Thread.sleep(1000); // exit if any error occurs if (this.failOnError && monitor.hasError()) { monitorThread.interrupt(); if (monitor.initialized) { return monitor.errorCode; } else { return INIT_ERROR_EXIT_CODE; } } currentTimeLength = System.currentTimeMillis() - startTime; if (currentTimeLength > this.timeout) { LOG.error("The monitor is running too long (" + currentTimeLength + ") after timeout limit:" + this.timeout + " will be killed itself !!"); if (monitor.initialized) { return TIMEOUT_ERROR_EXIT_CODE; } else { return INIT_ERROR_EXIT_CODE; } } } if (this.failOnError && monitor.finalCheckForErrors()) { monitorThread.interrupt(); return monitor.errorCode; } } finally { if (monitor != null) monitor.close(); } Thread.sleep(interval); } while (interval > 0); } // try-with-resources close if (choreService != null) { choreService.shutdown(); } return monitor.errorCode; } private void printUsageAndExit() { System.err.printf( "Usage: bin/hbase %s [opts] [table1 [table2]...] | [regionserver1 [regionserver2]..]%n", getClass().getName()); System.err.println(" where [opts] are:"); System.err.println(" -help Show this help and exit."); System.err.println(" -regionserver replace the table argument to regionserver,"); System.err.println(" which means to enable regionserver mode"); System.err.println(" -allRegions Tries all regions on a regionserver,"); System.err.println(" only works in regionserver mode."); System.err.println(" -daemon Continuous check at defined intervals."); System.err.println(" -interval <N> Interval between checks (sec)"); System.err.println(" -e Use table/regionserver as regular expression"); System.err.println(" which means the table/regionserver is regular expression pattern"); System.err.println(" -f <B> stop whole program if first error occurs," + " default is true"); System.err.println(" -t <N> timeout for a check, default is 600000 (milisecs)"); System.err.println(" -writeSniffing enable the write sniffing in canary"); System.err.println(" -treatFailureAsError treats read / write failure as error"); System.err.println(" -writeTable The table used for write sniffing." + " Default is hbase:canary"); System.err .println(" -D<configProperty>=<value> assigning or override the configuration params"); System.exit(USAGE_EXIT_CODE); } /** * A Factory method for {@link Monitor}. * Can be overridden by user. * @param index a start index for monitor target * @param args args passed from user * @return a Monitor instance */ public Monitor newMonitor(final Connection connection, int index, String[] args) { Monitor monitor = null; String[] monitorTargets = null; if(index >= 0) { int length = args.length - index; monitorTargets = new String[length]; System.arraycopy(args, index, monitorTargets, 0, length); } if (this.regionServerMode) { monitor = new RegionServerMonitor(connection, monitorTargets, this.useRegExp, (ExtendedSink) this.sink, this.executor, this.regionServerAllRegions, this.treatFailureAsError); } else { monitor = new RegionMonitor(connection, monitorTargets, this.useRegExp, this.sink, this.executor, this.writeSniffing, this.writeTableName, this.treatFailureAsError); } return monitor; } // a Monitor super-class can be extended by users public static abstract class Monitor implements Runnable, Closeable { protected Connection connection; protected Admin admin; protected String[] targets; protected boolean useRegExp; protected boolean treatFailureAsError; protected boolean initialized = false; protected boolean done = false; protected int errorCode = 0; protected Sink sink; protected ExecutorService executor; public boolean isDone() { return done; } public boolean hasError() { return errorCode != 0; } public boolean finalCheckForErrors() { if (errorCode != 0) { return true; } return treatFailureAsError && (sink.getReadFailureCount() > 0 || sink.getWriteFailureCount() > 0); } @Override public void close() throws IOException { if (this.admin != null) this.admin.close(); } protected Monitor(Connection connection, String[] monitorTargets, boolean useRegExp, Sink sink, ExecutorService executor, boolean treatFailureAsError) { if (null == connection) throw new IllegalArgumentException("connection shall not be null"); this.connection = connection; this.targets = monitorTargets; this.useRegExp = useRegExp; this.treatFailureAsError = treatFailureAsError; this.sink = sink; this.executor = executor; } @Override public abstract void run(); protected boolean initAdmin() { if (null == this.admin) { try { this.admin = this.connection.getAdmin(); } catch (Exception e) { LOG.error("Initial HBaseAdmin failed...", e); this.errorCode = INIT_ERROR_EXIT_CODE; } } else if (admin.isAborted()) { LOG.error("HBaseAdmin aborted"); this.errorCode = INIT_ERROR_EXIT_CODE; } return !this.hasError(); } } // a monitor for region mode private static class RegionMonitor extends Monitor { // 10 minutes private static final int DEFAULT_WRITE_TABLE_CHECK_PERIOD = 10 * 60 * 1000; // 1 days private static final int DEFAULT_WRITE_DATA_TTL = 24 * 60 * 60; private long lastCheckTime = -1; private boolean writeSniffing; private TableName writeTableName; private int writeDataTTL; private float regionsLowerLimit; private float regionsUpperLimit; private int checkPeriod; public RegionMonitor(Connection connection, String[] monitorTargets, boolean useRegExp, Sink sink, ExecutorService executor, boolean writeSniffing, TableName writeTableName, boolean treatFailureAsError) { super(connection, monitorTargets, useRegExp, sink, executor, treatFailureAsError); Configuration conf = connection.getConfiguration(); this.writeSniffing = writeSniffing; this.writeTableName = writeTableName; this.writeDataTTL = conf.getInt(HConstants.HBASE_CANARY_WRITE_DATA_TTL_KEY, DEFAULT_WRITE_DATA_TTL); this.regionsLowerLimit = conf.getFloat(HConstants.HBASE_CANARY_WRITE_PERSERVER_REGIONS_LOWERLIMIT_KEY, 1.0f); this.regionsUpperLimit = conf.getFloat(HConstants.HBASE_CANARY_WRITE_PERSERVER_REGIONS_UPPERLIMIT_KEY, 1.5f); this.checkPeriod = conf.getInt(HConstants.HBASE_CANARY_WRITE_TABLE_CHECK_PERIOD_KEY, DEFAULT_WRITE_TABLE_CHECK_PERIOD); } @Override public void run() { if (this.initAdmin()) { try { List<Future<Void>> taskFutures = new LinkedList<Future<Void>>(); if (this.targets != null && this.targets.length > 0) { String[] tables = generateMonitorTables(this.targets); this.initialized = true; for (String table : tables) { taskFutures.addAll(Canary.sniff(admin, sink, table, executor, TaskType.READ)); } } else { taskFutures.addAll(sniff(TaskType.READ)); } if (writeSniffing) { if (EnvironmentEdgeManager.currentTime() - lastCheckTime > checkPeriod) { try { checkWriteTableDistribution(); } catch (IOException e) { LOG.error("Check canary table distribution failed!", e); } lastCheckTime = EnvironmentEdgeManager.currentTime(); } // sniff canary table with write operation taskFutures.addAll(Canary.sniff(admin, sink, admin.getTableDescriptor(writeTableName), executor, TaskType.WRITE)); } for (Future<Void> future : taskFutures) { try { future.get(); } catch (ExecutionException e) { LOG.error("Sniff region failed!", e); } } } catch (Exception e) { LOG.error("Run regionMonitor failed", e); this.errorCode = ERROR_EXIT_CODE; } } this.done = true; } private String[] generateMonitorTables(String[] monitorTargets) throws IOException { String[] returnTables = null; if (this.useRegExp) { Pattern pattern = null; HTableDescriptor[] tds = null; Set<String> tmpTables = new TreeSet<String>(); try { if (LOG.isDebugEnabled()) { LOG.debug(String.format("reading list of tables")); } tds = this.admin.listTables(pattern); if (tds == null) { tds = new HTableDescriptor[0]; } for (String monitorTarget : monitorTargets) { pattern = Pattern.compile(monitorTarget); for (HTableDescriptor td : tds) { if (pattern.matcher(td.getNameAsString()).matches()) { tmpTables.add(td.getNameAsString()); } } } } catch (IOException e) { LOG.error("Communicate with admin failed", e); throw e; } if (tmpTables.size() > 0) { returnTables = tmpTables.toArray(new String[tmpTables.size()]); } else { String msg = "No HTable found, tablePattern:" + Arrays.toString(monitorTargets); LOG.error(msg); this.errorCode = INIT_ERROR_EXIT_CODE; throw new TableNotFoundException(msg); } } else { returnTables = monitorTargets; } return returnTables; } /* * canary entry point to monitor all the tables. */ private List<Future<Void>> sniff(TaskType taskType) throws Exception { if (LOG.isDebugEnabled()) { LOG.debug(String.format("reading list of tables")); } List<Future<Void>> taskFutures = new LinkedList<Future<Void>>(); for (HTableDescriptor table : admin.listTables()) { if (admin.isTableEnabled(table.getTableName()) && (!table.getTableName().equals(writeTableName))) { taskFutures.addAll(Canary.sniff(admin, sink, table, executor, taskType)); } } return taskFutures; } private void checkWriteTableDistribution() throws IOException { if (!admin.tableExists(writeTableName)) { int numberOfServers = admin.getClusterStatus().getServers().size(); if (numberOfServers == 0) { throw new IllegalStateException("No live regionservers"); } createWriteTable(numberOfServers); } if (!admin.isTableEnabled(writeTableName)) { admin.enableTable(writeTableName); } int numberOfServers = admin.getClusterStatus().getServers().size(); List<Pair<HRegionInfo, ServerName>> pairs = MetaTableAccessor.getTableRegionsAndLocations(connection, writeTableName); int numberOfRegions = pairs.size(); if (numberOfRegions < numberOfServers * regionsLowerLimit || numberOfRegions > numberOfServers * regionsUpperLimit) { admin.disableTable(writeTableName); admin.deleteTable(writeTableName); createWriteTable(numberOfServers); } HashSet<ServerName> serverSet = new HashSet<ServerName>(); for (Pair<HRegionInfo, ServerName> pair : pairs) { serverSet.add(pair.getSecond()); } int numberOfCoveredServers = serverSet.size(); if (numberOfCoveredServers < numberOfServers) { admin.balancer(); } } private void createWriteTable(int numberOfServers) throws IOException { int numberOfRegions = (int)(numberOfServers * regionsLowerLimit); LOG.info("Number of live regionservers: " + numberOfServers + ", " + "pre-splitting the canary table into " + numberOfRegions + " regions " + "(current lower limit of regions per server is " + regionsLowerLimit + " and you can change it by config: " + HConstants.HBASE_CANARY_WRITE_PERSERVER_REGIONS_LOWERLIMIT_KEY + " )"); HTableDescriptor desc = new HTableDescriptor(writeTableName); HColumnDescriptor family = new HColumnDescriptor(CANARY_TABLE_FAMILY_NAME); family.setMaxVersions(1); family.setTimeToLive(writeDataTTL); desc.addFamily(family); byte[][] splits = new RegionSplitter.HexStringSplit().split(numberOfRegions); admin.createTable(desc, splits); } } /** * Canary entry point for specified table. * @throws Exception */ public static void sniff(final Admin admin, TableName tableName) throws Exception { sniff(admin, tableName, TaskType.READ); } /** * Canary entry point for specified table with task type(read/write) * @throws Exception */ public static void sniff(final Admin admin, TableName tableName, TaskType taskType) throws Exception { List<Future<Void>> taskFutures = Canary.sniff(admin, new StdOutSink(), tableName.getNameAsString(), new ScheduledThreadPoolExecutor(1), taskType); for (Future<Void> future : taskFutures) { future.get(); } } /** * Canary entry point for specified table. * @throws Exception */ private static List<Future<Void>> sniff(final Admin admin, final Sink sink, String tableName, ExecutorService executor, TaskType taskType) throws Exception { if (LOG.isDebugEnabled()) { LOG.debug(String.format("checking table is enabled and getting table descriptor for table %s", tableName)); } if (admin.isTableEnabled(TableName.valueOf(tableName))) { return Canary.sniff(admin, sink, admin.getTableDescriptor(TableName.valueOf(tableName)), executor, taskType); } else { LOG.warn(String.format("Table %s is not enabled", tableName)); } return new LinkedList<Future<Void>>(); } /* * Loops over regions that owns this table, and output some information abouts the state. */ private static List<Future<Void>> sniff(final Admin admin, final Sink sink, HTableDescriptor tableDesc, ExecutorService executor, TaskType taskType) throws Exception { if (LOG.isDebugEnabled()) { LOG.debug(String.format("reading list of regions for table %s", tableDesc.getTableName())); } Table table = null; try { table = admin.getConnection().getTable(tableDesc.getTableName()); } catch (TableNotFoundException e) { return new ArrayList<Future<Void>>(); } List<RegionTask> tasks = new ArrayList<RegionTask>(); try { for (HRegionInfo region : admin.getTableRegions(tableDesc.getTableName())) { tasks.add(new RegionTask(admin.getConnection(), region, sink, taskType)); } } finally { table.close(); } return executor.invokeAll(tasks); } // a monitor for regionserver mode private static class RegionServerMonitor extends Monitor { private boolean allRegions; public RegionServerMonitor(Connection connection, String[] monitorTargets, boolean useRegExp, ExtendedSink sink, ExecutorService executor, boolean allRegions, boolean treatFailureAsError) { super(connection, monitorTargets, useRegExp, sink, executor, treatFailureAsError); this.allRegions = allRegions; } private ExtendedSink getSink() { return (ExtendedSink) this.sink; } @Override public void run() { if (this.initAdmin() && this.checkNoTableNames()) { Map<String, List<HRegionInfo>> rsAndRMap = this.filterRegionServerByName(); this.initialized = true; this.monitorRegionServers(rsAndRMap); } this.done = true; } private boolean checkNoTableNames() { List<String> foundTableNames = new ArrayList<String>(); TableName[] tableNames = null; if (LOG.isDebugEnabled()) { LOG.debug(String.format("reading list of tables")); } try { tableNames = this.admin.listTableNames(); } catch (IOException e) { LOG.error("Get listTableNames failed", e); this.errorCode = INIT_ERROR_EXIT_CODE; return false; } if (this.targets == null || this.targets.length == 0) return true; for (String target : this.targets) { for (TableName tableName : tableNames) { if (target.equals(tableName.getNameAsString())) { foundTableNames.add(target); } } } if (foundTableNames.size() > 0) { System.err.println("Cannot pass a tablename when using the -regionserver " + "option, tablenames:" + foundTableNames.toString()); this.errorCode = USAGE_EXIT_CODE; } return foundTableNames.size() == 0; } private void monitorRegionServers(Map<String, List<HRegionInfo>> rsAndRMap) { List<RegionServerTask> tasks = new ArrayList<RegionServerTask>(); Map<String, AtomicLong> successMap = new HashMap<String, AtomicLong>(); Random rand = new Random(); for (Map.Entry<String, List<HRegionInfo>> entry : rsAndRMap.entrySet()) { String serverName = entry.getKey(); AtomicLong successes = new AtomicLong(0); successMap.put(serverName, successes); if (this.allRegions) { for (HRegionInfo region : entry.getValue()) { tasks.add(new RegionServerTask(this.connection, serverName, region, getSink(), successes)); } } else { // random select a region if flag not set HRegionInfo region = entry.getValue().get(rand.nextInt(entry.getValue().size())); tasks.add(new RegionServerTask(this.connection, serverName, region, getSink(), successes)); } } try { for (Future<Void> future : this.executor.invokeAll(tasks)) { try { future.get(); } catch (ExecutionException e) { LOG.error("Sniff regionserver failed!", e); this.errorCode = ERROR_EXIT_CODE; } } if (this.allRegions) { for (Map.Entry<String, List<HRegionInfo>> entry : rsAndRMap.entrySet()) { String serverName = entry.getKey(); LOG.info("Successfully read " + successMap.get(serverName) + " regions out of " + entry.getValue().size() + " on regionserver:" + serverName); } } } catch (InterruptedException e) { this.errorCode = ERROR_EXIT_CODE; LOG.error("Sniff regionserver interrupted!", e); } } private Map<String, List<HRegionInfo>> filterRegionServerByName() { Map<String, List<HRegionInfo>> regionServerAndRegionsMap = this.getAllRegionServerByName(); regionServerAndRegionsMap = this.doFilterRegionServerByName(regionServerAndRegionsMap); return regionServerAndRegionsMap; } private Map<String, List<HRegionInfo>> getAllRegionServerByName() { Map<String, List<HRegionInfo>> rsAndRMap = new HashMap<String, List<HRegionInfo>>(); Table table = null; RegionLocator regionLocator = null; try { if (LOG.isDebugEnabled()) { LOG.debug(String.format("reading list of tables and locations")); } HTableDescriptor[] tableDescs = this.admin.listTables(); List<HRegionInfo> regions = null; for (HTableDescriptor tableDesc : tableDescs) { table = this.admin.getConnection().getTable(tableDesc.getTableName()); regionLocator = this.admin.getConnection().getRegionLocator(tableDesc.getTableName()); for (HRegionLocation location : regionLocator.getAllRegionLocations()) { ServerName rs = location.getServerName(); String rsName = rs.getHostname(); HRegionInfo r = location.getRegionInfo(); if (rsAndRMap.containsKey(rsName)) { regions = rsAndRMap.get(rsName); } else { regions = new ArrayList<HRegionInfo>(); rsAndRMap.put(rsName, regions); } regions.add(r); } table.close(); } } catch (IOException e) { String msg = "Get HTables info failed"; LOG.error(msg, e); this.errorCode = INIT_ERROR_EXIT_CODE; } finally { if (table != null) { try { table.close(); } catch (IOException e) { LOG.warn("Close table failed", e); } } } return rsAndRMap; } private Map<String, List<HRegionInfo>> doFilterRegionServerByName( Map<String, List<HRegionInfo>> fullRsAndRMap) { Map<String, List<HRegionInfo>> filteredRsAndRMap = null; if (this.targets != null && this.targets.length > 0) { filteredRsAndRMap = new HashMap<String, List<HRegionInfo>>(); Pattern pattern = null; Matcher matcher = null; boolean regExpFound = false; for (String rsName : this.targets) { if (this.useRegExp) { regExpFound = false; pattern = Pattern.compile(rsName); for (Map.Entry<String, List<HRegionInfo>> entry : fullRsAndRMap.entrySet()) { matcher = pattern.matcher(entry.getKey()); if (matcher.matches()) { filteredRsAndRMap.put(entry.getKey(), entry.getValue()); regExpFound = true; } } if (!regExpFound) { LOG.info("No RegionServerInfo found, regionServerPattern:" + rsName); } } else { if (fullRsAndRMap.containsKey(rsName)) { filteredRsAndRMap.put(rsName, fullRsAndRMap.get(rsName)); } else { LOG.info("No RegionServerInfo found, regionServerName:" + rsName); } } } } else { filteredRsAndRMap = fullRsAndRMap; } return filteredRsAndRMap; } } public static void main(String[] args) throws Exception { final Configuration conf = HBaseConfiguration.create(); // loading the generic options to conf new GenericOptionsParser(conf, args); int numThreads = conf.getInt("hbase.canary.threads.num", MAX_THREADS_NUM); LOG.info("Number of exection threads " + numThreads); ExecutorService executor = new ScheduledThreadPoolExecutor(numThreads); Class<? extends Sink> sinkClass = conf.getClass("hbase.canary.sink.class", RegionServerStdOutSink.class, Sink.class); Sink sink = ReflectionUtils.newInstance(sinkClass); int exitCode = ToolRunner.run(conf, new Canary(executor, sink), args); executor.shutdown(); System.exit(exitCode); } }
hbase-server/src/main/java/org/apache/hadoop/hbase/tool/Canary.java
/** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.tool; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.time.StopWatch; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.AuthUtil; import org.apache.hadoop.hbase.ChoreService; import org.apache.hadoop.hbase.DoNotRetryIOException; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.HRegionLocation; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.MetaTableAccessor; import org.apache.hadoop.hbase.NamespaceDescriptor; import org.apache.hadoop.hbase.ScheduledChore; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.TableNotEnabledException; import org.apache.hadoop.hbase.TableNotFoundException; import org.apache.hadoop.hbase.client.Admin; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.RegionLocator; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter; import org.apache.hadoop.hbase.tool.Canary.RegionTask.TaskType; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; import org.apache.hadoop.hbase.util.Pair; import org.apache.hadoop.hbase.util.ReflectionUtils; import org.apache.hadoop.hbase.util.RegionSplitter; import org.apache.hadoop.util.GenericOptionsParser; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; /** * HBase Canary Tool, that that can be used to do * "canary monitoring" of a running HBase cluster. * * Here are two modes * 1. region mode - Foreach region tries to get one row per column family * and outputs some information about failure or latency. * * 2. regionserver mode - Foreach regionserver tries to get one row from one table * selected randomly and outputs some information about failure or latency. */ public final class Canary implements Tool { // Sink interface used by the canary to outputs information public interface Sink { public long getReadFailureCount(); public void publishReadFailure(HRegionInfo region, Exception e); public void publishReadFailure(HRegionInfo region, HColumnDescriptor column, Exception e); public void publishReadTiming(HRegionInfo region, HColumnDescriptor column, long msTime); public long getWriteFailureCount(); public void publishWriteFailure(HRegionInfo region, Exception e); public void publishWriteFailure(HRegionInfo region, HColumnDescriptor column, Exception e); public void publishWriteTiming(HRegionInfo region, HColumnDescriptor column, long msTime); } // new extended sink for output regionserver mode info // do not change the Sink interface directly due to maintaining the API public interface ExtendedSink extends Sink { public void publishReadFailure(String table, String server); public void publishReadTiming(String table, String server, long msTime); } // Simple implementation of canary sink that allows to plot on // file or standard output timings or failures. public static class StdOutSink implements Sink { protected AtomicLong readFailureCount = new AtomicLong(0), writeFailureCount = new AtomicLong(0); @Override public long getReadFailureCount() { return readFailureCount.get(); } @Override public void publishReadFailure(HRegionInfo region, Exception e) { readFailureCount.incrementAndGet(); LOG.error(String.format("read from region %s failed", region.getRegionNameAsString()), e); } @Override public void publishReadFailure(HRegionInfo region, HColumnDescriptor column, Exception e) { readFailureCount.incrementAndGet(); LOG.error(String.format("read from region %s column family %s failed", region.getRegionNameAsString(), column.getNameAsString()), e); } @Override public void publishReadTiming(HRegionInfo region, HColumnDescriptor column, long msTime) { LOG.info(String.format("read from region %s column family %s in %dms", region.getRegionNameAsString(), column.getNameAsString(), msTime)); } @Override public long getWriteFailureCount() { return writeFailureCount.get(); } @Override public void publishWriteFailure(HRegionInfo region, Exception e) { writeFailureCount.incrementAndGet(); LOG.error(String.format("write to region %s failed", region.getRegionNameAsString()), e); } @Override public void publishWriteFailure(HRegionInfo region, HColumnDescriptor column, Exception e) { writeFailureCount.incrementAndGet(); LOG.error(String.format("write to region %s column family %s failed", region.getRegionNameAsString(), column.getNameAsString()), e); } @Override public void publishWriteTiming(HRegionInfo region, HColumnDescriptor column, long msTime) { LOG.info(String.format("write to region %s column family %s in %dms", region.getRegionNameAsString(), column.getNameAsString(), msTime)); } } // a ExtendedSink implementation public static class RegionServerStdOutSink extends StdOutSink implements ExtendedSink { @Override public void publishReadFailure(String table, String server) { readFailureCount.incrementAndGet(); LOG.error(String.format("Read from table:%s on region server:%s", table, server)); } @Override public void publishReadTiming(String table, String server, long msTime) { LOG.info(String.format("Read from table:%s on region server:%s in %dms", table, server, msTime)); } } /** * For each column family of the region tries to get one row and outputs the latency, or the * failure. */ static class RegionTask implements Callable<Void> { public enum TaskType{ READ, WRITE } private Connection connection; private HRegionInfo region; private Sink sink; private TaskType taskType; RegionTask(Connection connection, HRegionInfo region, Sink sink, TaskType taskType) { this.connection = connection; this.region = region; this.sink = sink; this.taskType = taskType; } @Override public Void call() { switch (taskType) { case READ: return read(); case WRITE: return write(); default: return read(); } } public Void read() { Table table = null; HTableDescriptor tableDesc = null; try { if (LOG.isDebugEnabled()) { LOG.debug(String.format("reading table descriptor for table %s", region.getTable())); } table = connection.getTable(region.getTable()); tableDesc = table.getTableDescriptor(); } catch (IOException e) { LOG.debug("sniffRegion failed", e); sink.publishReadFailure(region, e); if (table != null) { try { table.close(); } catch (IOException ioe) { LOG.error("Close table failed", e); } } return null; } byte[] startKey = null; Get get = null; Scan scan = null; ResultScanner rs = null; StopWatch stopWatch = new StopWatch(); for (HColumnDescriptor column : tableDesc.getColumnFamilies()) { stopWatch.reset(); startKey = region.getStartKey(); // Can't do a get on empty start row so do a Scan of first element if any instead. if (startKey.length > 0) { get = new Get(startKey); get.setCacheBlocks(false); get.setFilter(new FirstKeyOnlyFilter()); get.addFamily(column.getName()); } else { scan = new Scan(); scan.setRaw(true); scan.setCaching(1); scan.setCacheBlocks(false); scan.setFilter(new FirstKeyOnlyFilter()); scan.addFamily(column.getName()); scan.setMaxResultSize(1L); scan.setSmall(true); } if (LOG.isDebugEnabled()) { LOG.debug(String.format("reading from table %s region %s column family %s and key %s", tableDesc.getTableName(), region.getRegionNameAsString(), column.getNameAsString(), Bytes.toStringBinary(startKey))); } try { stopWatch.start(); if (startKey.length > 0) { table.get(get); } else { rs = table.getScanner(scan); rs.next(); } stopWatch.stop(); sink.publishReadTiming(region, column, stopWatch.getTime()); } catch (Exception e) { sink.publishReadFailure(region, column, e); } finally { if (rs != null) { rs.close(); } scan = null; get = null; startKey = null; } } try { table.close(); } catch (IOException e) { LOG.error("Close table failed", e); } return null; } /** * Check writes for the canary table * @return */ private Void write() { Table table = null; HTableDescriptor tableDesc = null; try { table = connection.getTable(region.getTable()); tableDesc = table.getTableDescriptor(); byte[] rowToCheck = region.getStartKey(); if (rowToCheck.length == 0) { rowToCheck = new byte[]{0x0}; } int writeValueSize = connection.getConfiguration().getInt(HConstants.HBASE_CANARY_WRITE_VALUE_SIZE_KEY, 10); for (HColumnDescriptor column : tableDesc.getColumnFamilies()) { Put put = new Put(rowToCheck); byte[] value = new byte[writeValueSize]; Bytes.random(value); put.addColumn(column.getName(), HConstants.EMPTY_BYTE_ARRAY, value); if (LOG.isDebugEnabled()) { LOG.debug(String.format("writing to table %s region %s column family %s and key %s", tableDesc.getTableName(), region.getRegionNameAsString(), column.getNameAsString(), Bytes.toStringBinary(rowToCheck))); } try { long startTime = System.currentTimeMillis(); table.put(put); long time = System.currentTimeMillis() - startTime; sink.publishWriteTiming(region, column, time); } catch (Exception e) { sink.publishWriteFailure(region, column, e); } } table.close(); } catch (IOException e) { sink.publishWriteFailure(region, e); } return null; } } /** * Get one row from a region on the regionserver and outputs the latency, or the failure. */ static class RegionServerTask implements Callable<Void> { private Connection connection; private String serverName; private HRegionInfo region; private ExtendedSink sink; private AtomicLong successes; RegionServerTask(Connection connection, String serverName, HRegionInfo region, ExtendedSink sink, AtomicLong successes) { this.connection = connection; this.serverName = serverName; this.region = region; this.sink = sink; this.successes = successes; } @Override public Void call() { TableName tableName = null; Table table = null; Get get = null; byte[] startKey = null; Scan scan = null; StopWatch stopWatch = new StopWatch(); // monitor one region on every region server stopWatch.reset(); try { tableName = region.getTable(); table = connection.getTable(tableName); startKey = region.getStartKey(); // Can't do a get on empty start row so do a Scan of first element if any instead. if (LOG.isDebugEnabled()) { LOG.debug(String.format("reading from region server %s table %s region %s and key %s", serverName, region.getTable(), region.getRegionNameAsString(), Bytes.toStringBinary(startKey))); } if (startKey.length > 0) { get = new Get(startKey); get.setCacheBlocks(false); get.setFilter(new FirstKeyOnlyFilter()); stopWatch.start(); table.get(get); stopWatch.stop(); } else { scan = new Scan(); scan.setCacheBlocks(false); scan.setFilter(new FirstKeyOnlyFilter()); scan.setCaching(1); scan.setMaxResultSize(1L); scan.setSmall(true); stopWatch.start(); ResultScanner s = table.getScanner(scan); s.next(); s.close(); stopWatch.stop(); } successes.incrementAndGet(); sink.publishReadTiming(tableName.getNameAsString(), serverName, stopWatch.getTime()); } catch (TableNotFoundException tnfe) { LOG.error("Table may be deleted", tnfe); // This is ignored because it doesn't imply that the regionserver is dead } catch (TableNotEnabledException tnee) { // This is considered a success since we got a response. successes.incrementAndGet(); LOG.debug("The targeted table was disabled. Assuming success."); } catch (DoNotRetryIOException dnrioe) { sink.publishReadFailure(tableName.getNameAsString(), serverName); LOG.error(dnrioe); } catch (IOException e) { sink.publishReadFailure(tableName.getNameAsString(), serverName); LOG.error(e); } finally { if (table != null) { try { table.close(); } catch (IOException e) {/* DO NOTHING */ LOG.error("Close table failed", e); } } scan = null; get = null; startKey = null; } return null; } } private static final int USAGE_EXIT_CODE = 1; private static final int INIT_ERROR_EXIT_CODE = 2; private static final int TIMEOUT_ERROR_EXIT_CODE = 3; private static final int ERROR_EXIT_CODE = 4; private static final long DEFAULT_INTERVAL = 6000; private static final long DEFAULT_TIMEOUT = 600000; // 10 mins private static final int MAX_THREADS_NUM = 16; // #threads to contact regions private static final Log LOG = LogFactory.getLog(Canary.class); public static final TableName DEFAULT_WRITE_TABLE_NAME = TableName.valueOf( NamespaceDescriptor.SYSTEM_NAMESPACE_NAME_STR, "canary"); private static final String CANARY_TABLE_FAMILY_NAME = "Test"; private Configuration conf = null; private long interval = 0; private Sink sink = null; private boolean useRegExp; private long timeout = DEFAULT_TIMEOUT; private boolean failOnError = true; private boolean regionServerMode = false; private boolean regionServerAllRegions = false; private boolean writeSniffing = false; private boolean treatFailureAsError = false; private TableName writeTableName = DEFAULT_WRITE_TABLE_NAME; private ExecutorService executor; // threads to retrieve data from regionservers public Canary() { this(new ScheduledThreadPoolExecutor(1), new RegionServerStdOutSink()); } public Canary(ExecutorService executor, Sink sink) { this.executor = executor; this.sink = sink; } @Override public Configuration getConf() { return conf; } @Override public void setConf(Configuration conf) { this.conf = conf; } private int parseArgs(String[] args) { int index = -1; // Process command line args for (int i = 0; i < args.length; i++) { String cmd = args[i]; if (cmd.startsWith("-")) { if (index >= 0) { // command line args must be in the form: [opts] [table 1 [table 2 ...]] System.err.println("Invalid command line options"); printUsageAndExit(); } if (cmd.equals("-help")) { // user asked for help, print the help and quit. printUsageAndExit(); } else if (cmd.equals("-daemon") && interval == 0) { // user asked for daemon mode, set a default interval between checks interval = DEFAULT_INTERVAL; } else if (cmd.equals("-interval")) { // user has specified an interval for canary breaths (-interval N) i++; if (i == args.length) { System.err.println("-interval needs a numeric value argument."); printUsageAndExit(); } try { interval = Long.parseLong(args[i]) * 1000; } catch (NumberFormatException e) { System.err.println("-interval needs a numeric value argument."); printUsageAndExit(); } } else if(cmd.equals("-regionserver")) { this.regionServerMode = true; } else if(cmd.equals("-allRegions")) { this.regionServerAllRegions = true; } else if(cmd.equals("-writeSniffing")) { this.writeSniffing = true; } else if(cmd.equals("-treatFailureAsError")) { this.treatFailureAsError = true; } else if (cmd.equals("-e")) { this.useRegExp = true; } else if (cmd.equals("-t")) { i++; if (i == args.length) { System.err.println("-t needs a numeric value argument."); printUsageAndExit(); } try { this.timeout = Long.parseLong(args[i]); } catch (NumberFormatException e) { System.err.println("-t needs a numeric value argument."); printUsageAndExit(); } } else if (cmd.equals("-writeTable")) { i++; if (i == args.length) { System.err.println("-writeTable needs a string value argument."); printUsageAndExit(); } this.writeTableName = TableName.valueOf(args[i]); } else if (cmd.equals("-f")) { i++; if (i == args.length) { System.err .println("-f needs a boolean value argument (true|false)."); printUsageAndExit(); } this.failOnError = Boolean.parseBoolean(args[i]); } else { // no options match System.err.println(cmd + " options is invalid."); printUsageAndExit(); } } else if (index < 0) { // keep track of first table name specified by the user index = i; } } if (this.regionServerAllRegions && !this.regionServerMode) { System.err.println("-allRegions can only be specified in regionserver mode."); printUsageAndExit(); } return index; } @Override public int run(String[] args) throws Exception { int index = parseArgs(args); ChoreService choreService = null; // Launches chore for refreshing kerberos credentials if security is enabled. // Please see http://hbase.apache.org/book.html#_running_canary_in_a_kerberos_enabled_cluster // for more details. final ScheduledChore authChore = AuthUtil.getAuthChore(conf); if (authChore != null) { choreService = new ChoreService("CANARY_TOOL"); choreService.scheduleChore(authChore); } // Start to prepare the stuffs Monitor monitor = null; Thread monitorThread = null; long startTime = 0; long currentTimeLength = 0; // Get a connection to use in below. try (Connection connection = ConnectionFactory.createConnection(this.conf)) { do { // Do monitor !! try { monitor = this.newMonitor(connection, index, args); monitorThread = new Thread(monitor); startTime = System.currentTimeMillis(); monitorThread.start(); while (!monitor.isDone()) { // wait for 1 sec Thread.sleep(1000); // exit if any error occurs if (this.failOnError && monitor.hasError()) { monitorThread.interrupt(); if (monitor.initialized) { System.exit(monitor.errorCode); } else { System.exit(INIT_ERROR_EXIT_CODE); } } currentTimeLength = System.currentTimeMillis() - startTime; if (currentTimeLength > this.timeout) { LOG.error("The monitor is running too long (" + currentTimeLength + ") after timeout limit:" + this.timeout + " will be killed itself !!"); if (monitor.initialized) { System.exit(TIMEOUT_ERROR_EXIT_CODE); } else { System.exit(INIT_ERROR_EXIT_CODE); } break; } } if (this.failOnError && monitor.finalCheckForErrors()) { monitorThread.interrupt(); System.exit(monitor.errorCode); } } finally { if (monitor != null) monitor.close(); } Thread.sleep(interval); } while (interval > 0); } // try-with-resources close if (choreService != null) { choreService.shutdown(); } return(monitor.errorCode); } private void printUsageAndExit() { System.err.printf( "Usage: bin/hbase %s [opts] [table1 [table2]...] | [regionserver1 [regionserver2]..]%n", getClass().getName()); System.err.println(" where [opts] are:"); System.err.println(" -help Show this help and exit."); System.err.println(" -regionserver replace the table argument to regionserver,"); System.err.println(" which means to enable regionserver mode"); System.err.println(" -allRegions Tries all regions on a regionserver,"); System.err.println(" only works in regionserver mode."); System.err.println(" -daemon Continuous check at defined intervals."); System.err.println(" -interval <N> Interval between checks (sec)"); System.err.println(" -e Use table/regionserver as regular expression"); System.err.println(" which means the table/regionserver is regular expression pattern"); System.err.println(" -f <B> stop whole program if first error occurs," + " default is true"); System.err.println(" -t <N> timeout for a check, default is 600000 (milisecs)"); System.err.println(" -writeSniffing enable the write sniffing in canary"); System.err.println(" -treatFailureAsError treats read / write failure as error"); System.err.println(" -writeTable The table used for write sniffing." + " Default is hbase:canary"); System.err .println(" -D<configProperty>=<value> assigning or override the configuration params"); System.exit(USAGE_EXIT_CODE); } /** * A Factory method for {@link Monitor}. * Can be overridden by user. * @param index a start index for monitor target * @param args args passed from user * @return a Monitor instance */ public Monitor newMonitor(final Connection connection, int index, String[] args) { Monitor monitor = null; String[] monitorTargets = null; if(index >= 0) { int length = args.length - index; monitorTargets = new String[length]; System.arraycopy(args, index, monitorTargets, 0, length); } if (this.regionServerMode) { monitor = new RegionServerMonitor(connection, monitorTargets, this.useRegExp, (ExtendedSink) this.sink, this.executor, this.regionServerAllRegions, this.treatFailureAsError); } else { monitor = new RegionMonitor(connection, monitorTargets, this.useRegExp, this.sink, this.executor, this.writeSniffing, this.writeTableName, this.treatFailureAsError); } return monitor; } // a Monitor super-class can be extended by users public static abstract class Monitor implements Runnable, Closeable { protected Connection connection; protected Admin admin; protected String[] targets; protected boolean useRegExp; protected boolean treatFailureAsError; protected boolean initialized = false; protected boolean done = false; protected int errorCode = 0; protected Sink sink; protected ExecutorService executor; public boolean isDone() { return done; } public boolean hasError() { return errorCode != 0; } public boolean finalCheckForErrors() { if (errorCode != 0) { return true; } return treatFailureAsError && (sink.getReadFailureCount() > 0 || sink.getWriteFailureCount() > 0); } @Override public void close() throws IOException { if (this.admin != null) this.admin.close(); } protected Monitor(Connection connection, String[] monitorTargets, boolean useRegExp, Sink sink, ExecutorService executor, boolean treatFailureAsError) { if (null == connection) throw new IllegalArgumentException("connection shall not be null"); this.connection = connection; this.targets = monitorTargets; this.useRegExp = useRegExp; this.treatFailureAsError = treatFailureAsError; this.sink = sink; this.executor = executor; } @Override public abstract void run(); protected boolean initAdmin() { if (null == this.admin) { try { this.admin = this.connection.getAdmin(); } catch (Exception e) { LOG.error("Initial HBaseAdmin failed...", e); this.errorCode = INIT_ERROR_EXIT_CODE; } } else if (admin.isAborted()) { LOG.error("HBaseAdmin aborted"); this.errorCode = INIT_ERROR_EXIT_CODE; } return !this.hasError(); } } // a monitor for region mode private static class RegionMonitor extends Monitor { // 10 minutes private static final int DEFAULT_WRITE_TABLE_CHECK_PERIOD = 10 * 60 * 1000; // 1 days private static final int DEFAULT_WRITE_DATA_TTL = 24 * 60 * 60; private long lastCheckTime = -1; private boolean writeSniffing; private TableName writeTableName; private int writeDataTTL; private float regionsLowerLimit; private float regionsUpperLimit; private int checkPeriod; public RegionMonitor(Connection connection, String[] monitorTargets, boolean useRegExp, Sink sink, ExecutorService executor, boolean writeSniffing, TableName writeTableName, boolean treatFailureAsError) { super(connection, monitorTargets, useRegExp, sink, executor, treatFailureAsError); Configuration conf = connection.getConfiguration(); this.writeSniffing = writeSniffing; this.writeTableName = writeTableName; this.writeDataTTL = conf.getInt(HConstants.HBASE_CANARY_WRITE_DATA_TTL_KEY, DEFAULT_WRITE_DATA_TTL); this.regionsLowerLimit = conf.getFloat(HConstants.HBASE_CANARY_WRITE_PERSERVER_REGIONS_LOWERLIMIT_KEY, 1.0f); this.regionsUpperLimit = conf.getFloat(HConstants.HBASE_CANARY_WRITE_PERSERVER_REGIONS_UPPERLIMIT_KEY, 1.5f); this.checkPeriod = conf.getInt(HConstants.HBASE_CANARY_WRITE_TABLE_CHECK_PERIOD_KEY, DEFAULT_WRITE_TABLE_CHECK_PERIOD); } @Override public void run() { if (this.initAdmin()) { try { List<Future<Void>> taskFutures = new LinkedList<Future<Void>>(); if (this.targets != null && this.targets.length > 0) { String[] tables = generateMonitorTables(this.targets); this.initialized = true; for (String table : tables) { taskFutures.addAll(Canary.sniff(admin, sink, table, executor, TaskType.READ)); } } else { taskFutures.addAll(sniff(TaskType.READ)); } if (writeSniffing) { if (EnvironmentEdgeManager.currentTime() - lastCheckTime > checkPeriod) { try { checkWriteTableDistribution(); } catch (IOException e) { LOG.error("Check canary table distribution failed!", e); } lastCheckTime = EnvironmentEdgeManager.currentTime(); } // sniff canary table with write operation taskFutures.addAll(Canary.sniff(admin, sink, admin.getTableDescriptor(writeTableName), executor, TaskType.WRITE)); } for (Future<Void> future : taskFutures) { try { future.get(); } catch (ExecutionException e) { LOG.error("Sniff region failed!", e); } } } catch (Exception e) { LOG.error("Run regionMonitor failed", e); this.errorCode = ERROR_EXIT_CODE; } } this.done = true; } private String[] generateMonitorTables(String[] monitorTargets) throws IOException { String[] returnTables = null; if (this.useRegExp) { Pattern pattern = null; HTableDescriptor[] tds = null; Set<String> tmpTables = new TreeSet<String>(); try { if (LOG.isDebugEnabled()) { LOG.debug(String.format("reading list of tables")); } tds = this.admin.listTables(pattern); if (tds == null) { tds = new HTableDescriptor[0]; } for (String monitorTarget : monitorTargets) { pattern = Pattern.compile(monitorTarget); for (HTableDescriptor td : tds) { if (pattern.matcher(td.getNameAsString()).matches()) { tmpTables.add(td.getNameAsString()); } } } } catch (IOException e) { LOG.error("Communicate with admin failed", e); throw e; } if (tmpTables.size() > 0) { returnTables = tmpTables.toArray(new String[tmpTables.size()]); } else { String msg = "No HTable found, tablePattern:" + Arrays.toString(monitorTargets); LOG.error(msg); this.errorCode = INIT_ERROR_EXIT_CODE; throw new TableNotFoundException(msg); } } else { returnTables = monitorTargets; } return returnTables; } /* * canary entry point to monitor all the tables. */ private List<Future<Void>> sniff(TaskType taskType) throws Exception { if (LOG.isDebugEnabled()) { LOG.debug(String.format("reading list of tables")); } List<Future<Void>> taskFutures = new LinkedList<Future<Void>>(); for (HTableDescriptor table : admin.listTables()) { if (admin.isTableEnabled(table.getTableName()) && (!table.getTableName().equals(writeTableName))) { taskFutures.addAll(Canary.sniff(admin, sink, table, executor, taskType)); } } return taskFutures; } private void checkWriteTableDistribution() throws IOException { if (!admin.tableExists(writeTableName)) { int numberOfServers = admin.getClusterStatus().getServers().size(); if (numberOfServers == 0) { throw new IllegalStateException("No live regionservers"); } createWriteTable(numberOfServers); } if (!admin.isTableEnabled(writeTableName)) { admin.enableTable(writeTableName); } int numberOfServers = admin.getClusterStatus().getServers().size(); List<Pair<HRegionInfo, ServerName>> pairs = MetaTableAccessor.getTableRegionsAndLocations(connection, writeTableName); int numberOfRegions = pairs.size(); if (numberOfRegions < numberOfServers * regionsLowerLimit || numberOfRegions > numberOfServers * regionsUpperLimit) { admin.disableTable(writeTableName); admin.deleteTable(writeTableName); createWriteTable(numberOfServers); } HashSet<ServerName> serverSet = new HashSet<ServerName>(); for (Pair<HRegionInfo, ServerName> pair : pairs) { serverSet.add(pair.getSecond()); } int numberOfCoveredServers = serverSet.size(); if (numberOfCoveredServers < numberOfServers) { admin.balancer(); } } private void createWriteTable(int numberOfServers) throws IOException { int numberOfRegions = (int)(numberOfServers * regionsLowerLimit); LOG.info("Number of live regionservers: " + numberOfServers + ", " + "pre-splitting the canary table into " + numberOfRegions + " regions " + "(current lower limit of regions per server is " + regionsLowerLimit + " and you can change it by config: " + HConstants.HBASE_CANARY_WRITE_PERSERVER_REGIONS_LOWERLIMIT_KEY + " )"); HTableDescriptor desc = new HTableDescriptor(writeTableName); HColumnDescriptor family = new HColumnDescriptor(CANARY_TABLE_FAMILY_NAME); family.setMaxVersions(1); family.setTimeToLive(writeDataTTL); desc.addFamily(family); byte[][] splits = new RegionSplitter.HexStringSplit().split(numberOfRegions); admin.createTable(desc, splits); } } /** * Canary entry point for specified table. * @throws Exception */ public static void sniff(final Admin admin, TableName tableName) throws Exception { sniff(admin, tableName, TaskType.READ); } /** * Canary entry point for specified table with task type(read/write) * @throws Exception */ public static void sniff(final Admin admin, TableName tableName, TaskType taskType) throws Exception { List<Future<Void>> taskFutures = Canary.sniff(admin, new StdOutSink(), tableName.getNameAsString(), new ScheduledThreadPoolExecutor(1), taskType); for (Future<Void> future : taskFutures) { future.get(); } } /** * Canary entry point for specified table. * @throws Exception */ private static List<Future<Void>> sniff(final Admin admin, final Sink sink, String tableName, ExecutorService executor, TaskType taskType) throws Exception { if (LOG.isDebugEnabled()) { LOG.debug(String.format("checking table is enabled and getting table descriptor for table %s", tableName)); } if (admin.isTableEnabled(TableName.valueOf(tableName))) { return Canary.sniff(admin, sink, admin.getTableDescriptor(TableName.valueOf(tableName)), executor, taskType); } else { LOG.warn(String.format("Table %s is not enabled", tableName)); } return new LinkedList<Future<Void>>(); } /* * Loops over regions that owns this table, and output some information abouts the state. */ private static List<Future<Void>> sniff(final Admin admin, final Sink sink, HTableDescriptor tableDesc, ExecutorService executor, TaskType taskType) throws Exception { if (LOG.isDebugEnabled()) { LOG.debug(String.format("reading list of regions for table %s", tableDesc.getTableName())); } Table table = null; try { table = admin.getConnection().getTable(tableDesc.getTableName()); } catch (TableNotFoundException e) { return new ArrayList<Future<Void>>(); } List<RegionTask> tasks = new ArrayList<RegionTask>(); try { for (HRegionInfo region : admin.getTableRegions(tableDesc.getTableName())) { tasks.add(new RegionTask(admin.getConnection(), region, sink, taskType)); } } finally { table.close(); } return executor.invokeAll(tasks); } // a monitor for regionserver mode private static class RegionServerMonitor extends Monitor { private boolean allRegions; public RegionServerMonitor(Connection connection, String[] monitorTargets, boolean useRegExp, ExtendedSink sink, ExecutorService executor, boolean allRegions, boolean treatFailureAsError) { super(connection, monitorTargets, useRegExp, sink, executor, treatFailureAsError); this.allRegions = allRegions; } private ExtendedSink getSink() { return (ExtendedSink) this.sink; } @Override public void run() { if (this.initAdmin() && this.checkNoTableNames()) { Map<String, List<HRegionInfo>> rsAndRMap = this.filterRegionServerByName(); this.initialized = true; this.monitorRegionServers(rsAndRMap); } this.done = true; } private boolean checkNoTableNames() { List<String> foundTableNames = new ArrayList<String>(); TableName[] tableNames = null; if (LOG.isDebugEnabled()) { LOG.debug(String.format("reading list of tables")); } try { tableNames = this.admin.listTableNames(); } catch (IOException e) { LOG.error("Get listTableNames failed", e); this.errorCode = INIT_ERROR_EXIT_CODE; return false; } if (this.targets == null || this.targets.length == 0) return true; for (String target : this.targets) { for (TableName tableName : tableNames) { if (target.equals(tableName.getNameAsString())) { foundTableNames.add(target); } } } if (foundTableNames.size() > 0) { System.err.println("Cannot pass a tablename when using the -regionserver " + "option, tablenames:" + foundTableNames.toString()); this.errorCode = USAGE_EXIT_CODE; } return foundTableNames.size() == 0; } private void monitorRegionServers(Map<String, List<HRegionInfo>> rsAndRMap) { List<RegionServerTask> tasks = new ArrayList<RegionServerTask>(); Map<String, AtomicLong> successMap = new HashMap<String, AtomicLong>(); Random rand = new Random(); for (Map.Entry<String, List<HRegionInfo>> entry : rsAndRMap.entrySet()) { String serverName = entry.getKey(); AtomicLong successes = new AtomicLong(0); successMap.put(serverName, successes); if (this.allRegions) { for (HRegionInfo region : entry.getValue()) { tasks.add(new RegionServerTask(this.connection, serverName, region, getSink(), successes)); } } else { // random select a region if flag not set HRegionInfo region = entry.getValue().get(rand.nextInt(entry.getValue().size())); tasks.add(new RegionServerTask(this.connection, serverName, region, getSink(), successes)); } } try { for (Future<Void> future : this.executor.invokeAll(tasks)) { try { future.get(); } catch (ExecutionException e) { LOG.error("Sniff regionserver failed!", e); this.errorCode = ERROR_EXIT_CODE; } } if (this.allRegions) { for (Map.Entry<String, List<HRegionInfo>> entry : rsAndRMap.entrySet()) { String serverName = entry.getKey(); LOG.info("Successfully read " + successMap.get(serverName) + " regions out of " + entry.getValue().size() + " on regionserver:" + serverName); } } } catch (InterruptedException e) { this.errorCode = ERROR_EXIT_CODE; LOG.error("Sniff regionserver interrupted!", e); } } private Map<String, List<HRegionInfo>> filterRegionServerByName() { Map<String, List<HRegionInfo>> regionServerAndRegionsMap = this.getAllRegionServerByName(); regionServerAndRegionsMap = this.doFilterRegionServerByName(regionServerAndRegionsMap); return regionServerAndRegionsMap; } private Map<String, List<HRegionInfo>> getAllRegionServerByName() { Map<String, List<HRegionInfo>> rsAndRMap = new HashMap<String, List<HRegionInfo>>(); Table table = null; RegionLocator regionLocator = null; try { if (LOG.isDebugEnabled()) { LOG.debug(String.format("reading list of tables and locations")); } HTableDescriptor[] tableDescs = this.admin.listTables(); List<HRegionInfo> regions = null; for (HTableDescriptor tableDesc : tableDescs) { table = this.admin.getConnection().getTable(tableDesc.getTableName()); regionLocator = this.admin.getConnection().getRegionLocator(tableDesc.getTableName()); for (HRegionLocation location : regionLocator.getAllRegionLocations()) { ServerName rs = location.getServerName(); String rsName = rs.getHostname(); HRegionInfo r = location.getRegionInfo(); if (rsAndRMap.containsKey(rsName)) { regions = rsAndRMap.get(rsName); } else { regions = new ArrayList<HRegionInfo>(); rsAndRMap.put(rsName, regions); } regions.add(r); } table.close(); } } catch (IOException e) { String msg = "Get HTables info failed"; LOG.error(msg, e); this.errorCode = INIT_ERROR_EXIT_CODE; } finally { if (table != null) { try { table.close(); } catch (IOException e) { LOG.warn("Close table failed", e); } } } return rsAndRMap; } private Map<String, List<HRegionInfo>> doFilterRegionServerByName( Map<String, List<HRegionInfo>> fullRsAndRMap) { Map<String, List<HRegionInfo>> filteredRsAndRMap = null; if (this.targets != null && this.targets.length > 0) { filteredRsAndRMap = new HashMap<String, List<HRegionInfo>>(); Pattern pattern = null; Matcher matcher = null; boolean regExpFound = false; for (String rsName : this.targets) { if (this.useRegExp) { regExpFound = false; pattern = Pattern.compile(rsName); for (Map.Entry<String, List<HRegionInfo>> entry : fullRsAndRMap.entrySet()) { matcher = pattern.matcher(entry.getKey()); if (matcher.matches()) { filteredRsAndRMap.put(entry.getKey(), entry.getValue()); regExpFound = true; } } if (!regExpFound) { LOG.info("No RegionServerInfo found, regionServerPattern:" + rsName); } } else { if (fullRsAndRMap.containsKey(rsName)) { filteredRsAndRMap.put(rsName, fullRsAndRMap.get(rsName)); } else { LOG.info("No RegionServerInfo found, regionServerName:" + rsName); } } } } else { filteredRsAndRMap = fullRsAndRMap; } return filteredRsAndRMap; } } public static void main(String[] args) throws Exception { final Configuration conf = HBaseConfiguration.create(); // loading the generic options to conf new GenericOptionsParser(conf, args); int numThreads = conf.getInt("hbase.canary.threads.num", MAX_THREADS_NUM); LOG.info("Number of exection threads " + numThreads); ExecutorService executor = new ScheduledThreadPoolExecutor(numThreads); Class<? extends Sink> sinkClass = conf.getClass("hbase.canary.sink.class", RegionServerStdOutSink.class, Sink.class); Sink sink = ReflectionUtils.newInstance(sinkClass); int exitCode = ToolRunner.run(conf, new Canary(executor, sink), args); executor.shutdown(); System.exit(exitCode); } }
HBASE-15229 Canary Tools should not call System.Exit on error (Vishal Khandelwal)
hbase-server/src/main/java/org/apache/hadoop/hbase/tool/Canary.java
HBASE-15229 Canary Tools should not call System.Exit on error (Vishal Khandelwal)
<ide><path>base-server/src/main/java/org/apache/hadoop/hbase/tool/Canary.java <ide> if (this.failOnError && monitor.hasError()) { <ide> monitorThread.interrupt(); <ide> if (monitor.initialized) { <del> System.exit(monitor.errorCode); <add> return monitor.errorCode; <ide> } else { <del> System.exit(INIT_ERROR_EXIT_CODE); <add> return INIT_ERROR_EXIT_CODE; <ide> } <ide> } <ide> currentTimeLength = System.currentTimeMillis() - startTime; <ide> + ") after timeout limit:" + this.timeout <ide> + " will be killed itself !!"); <ide> if (monitor.initialized) { <del> System.exit(TIMEOUT_ERROR_EXIT_CODE); <add> return TIMEOUT_ERROR_EXIT_CODE; <ide> } else { <del> System.exit(INIT_ERROR_EXIT_CODE); <add> return INIT_ERROR_EXIT_CODE; <ide> } <del> break; <ide> } <ide> } <ide> <ide> if (this.failOnError && monitor.finalCheckForErrors()) { <ide> monitorThread.interrupt(); <del> System.exit(monitor.errorCode); <add> return monitor.errorCode; <ide> } <ide> } finally { <ide> if (monitor != null) monitor.close(); <ide> if (choreService != null) { <ide> choreService.shutdown(); <ide> } <del> return(monitor.errorCode); <add> return monitor.errorCode; <ide> } <ide> <ide> private void printUsageAndExit() {
Java
mit
577d96d2826d2823798e130f5cabe17a7dd1fcfb
0
markenwerk/java-commons-iterators
/* * Copyright (c) 2016 Torsten Krause, Markenwerk GmbH * * 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. */ package net.markenwerk.commons.iterators; import java.util.Iterator; import net.markenwerk.commons.interfaces.Handler; import net.markenwerk.commons.interfaces.Predicate; /** * An {@link RemoveHandlerIterator} is an {@link Iterator} that can be wrapped * around a given {@link Iterator} and intercepts every call to * {@linkplain RemoveHandlerIterator#remove()} and calls a given {@link Handler} * for the current value. * * @param <Payload> * The payload type. * @author Torsten Krause (tk at markenwerk dot net) * @since 2.2.0 */ public final class RemoveHandlerIterator<Payload> implements Iterator<Payload> { private final Iterator<? extends Payload> iterator; private final Handler<Payload> removeHandler; private boolean nextCalled; private Payload current; private boolean currentRemoved; /** * Creates a new {@link RemoveHandlerIterator} from the given * {@link Iterator} and the given {@link Predicate}. * * @param iterator * The {@link Iterator}, around which the new * {@link NullFreeIterator} will be wrapped. * @param removeHandler * The {@link Handler} to be used. * * @throws IllegalArgumentException * If the given {@link Iterator} is {@literal null} of if the * given {@link Handler} is {@literal null}. */ public RemoveHandlerIterator(Iterator<? extends Payload> iterator, Handler<Payload> removeHandler) throws IllegalArgumentException { if (null == iterator) { throw new IllegalArgumentException("iterator is null"); } if (null == removeHandler) { throw new IllegalArgumentException("removeHandler is null"); } this.iterator = iterator; this.removeHandler = removeHandler; } @Override public boolean hasNext() { nextCalled = true; return iterator.hasNext(); } @Override public Payload next() { nextCalled = true; current = iterator.next(); currentRemoved = false; return current; } @Override public void remove() throws IllegalStateException { if (!nextCalled) { throw new IllegalStateException("next() hasn't been called yet"); } else if (currentRemoved) { throw new IllegalStateException("remove() has alreade been called"); } else { currentRemoved = true; removeHandler.handle(current); } } }
src/main/java/net/markenwerk/commons/iterators/RemoveHandlerIterator.java
/* * Copyright (c) 2016 Torsten Krause, Markenwerk GmbH * * 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. */ package net.markenwerk.commons.iterators; import java.util.Iterator; import net.markenwerk.commons.interfaces.Handler; import net.markenwerk.commons.interfaces.Predicate; /** * An {@link RemoveHandlerIterator} is an {@link Iterator} that can be wrapped * around a given {@link Iterator} and intercepts every call to * {@linkplain RemoveHandlerIterator#remove()} and calls a given {@link Handler} * for the current value. * * @param <Payload> * The payload type. * @author Torsten Krause (tk at markenwerk dot net) * @since 2.2.0 */ public final class RemoveHandlerIterator<Payload> implements Iterator<Payload> { private final Iterator<? extends Payload> iterator; private final Handler<Payload> removeHandler; private boolean nextCalled; private Payload current; private boolean currentRemoved; /** * Creates a new {@link RemoveHandlerIterator} from the given * {@link Iterator} and the given {@link Predicate}. * * @param iterator * The {@link Iterator}, around which the new * {@link NullFreeIterator} will be wrapped. * @param removeHandler * The {@link Handler} to be used. * * @throws IllegalArgumentException * If the given {@link Iterator} is {@literal null}. */ public RemoveHandlerIterator(Iterator<? extends Payload> iterator, Handler<Payload> removeHandler) throws IllegalArgumentException { if (null == iterator) { throw new IllegalArgumentException("iterator is null"); } if (null == removeHandler) { throw new IllegalArgumentException("removeHandler is null"); } this.iterator = iterator; this.removeHandler = removeHandler; } @Override public boolean hasNext() { nextCalled = true; return iterator.hasNext(); } @Override public Payload next() { nextCalled = true; current = iterator.next(); currentRemoved = false; return current; } @Override public void remove() throws IllegalStateException { if (!nextCalled) { throw new IllegalStateException("next() hasn't been called yet"); } else if (currentRemoved) { throw new IllegalStateException("remove() has alreade been called"); } else { currentRemoved = true; removeHandler.handle(current); } } }
ficed javadoc
src/main/java/net/markenwerk/commons/iterators/RemoveHandlerIterator.java
ficed javadoc
<ide><path>rc/main/java/net/markenwerk/commons/iterators/RemoveHandlerIterator.java <ide> * The {@link Handler} to be used. <ide> * <ide> * @throws IllegalArgumentException <del> * If the given {@link Iterator} is {@literal null}. <add> * If the given {@link Iterator} is {@literal null} of if the <add> * given {@link Handler} is {@literal null}. <ide> */ <ide> public RemoveHandlerIterator(Iterator<? extends Payload> iterator, Handler<Payload> removeHandler) <ide> throws IllegalArgumentException {