/*
 * 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 com.onegravity.rteditor.utils.io;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Stack;

/**
 * General filename and filepath manipulation utilities.
 *

 * When dealing with filenames you can hit problems when moving from a Windows
 * based development machine to a Unix based production machine.
 * This class aims to help avoid those problems.
 *

 * NOTE: You may be able to avoid using this class entirely simply by
 * using JDK {@link File File} objects and the two argument constructor
 * {@link File#File(File, String) File(File,String)}.
 *

 * Most methods on this class are designed to work the same on both Unix and Windows.
 * Those that don't include 'System', 'Unix' or 'Windows' in their name.
 *

 * Most methods recognise both separators (forward and back), and both
 * sets of prefixes. See the javadoc of each method for details.
 *

 * This class defines six components within a filename
 * (example C:\dev\project\file.txt):
 *

 *
the prefix - C:\

 *
the path - dev\project\

 *
the full path - C:\dev\project\

 *
the name - file.txt

 *
the base name - file

 *
the extension - txt

 *

 * Note that this class works best if directory filenames end with a separator.
 * If you omit the last separator, it is impossible to determine if the filename
 * corresponds to a file or a directory. As a result, we have chosen to say
 * it corresponds to a file.
 *

 * This class only supports Unix and Windows style names.
 * Prefixes are matched as follows:
 *

 * Windows:
 * a\b\c.txt           --> ""          --> relative
 * \a\b\c.txt          --> "\"         --> current drive absolute
 * C:a\b\c.txt         --> "C:"        --> drive relative
 * C:\a\b\c.txt        --> "C:\"       --> absolute
 * \\server\a\b\c.txt  --> "\\server\" --> UNC
 *
 * Unix:
 * a/b/c.txt           --> ""          --> relative
 * /a/b/c.txt          --> "/"         --> absolute
 * ~/a/b/c.txt         --> "~/"        --> current user
 * ~                   --> "~/"        --> current user (slash added)
 * ~user/a/b/c.txt     --> "~user/"    --> named user
 * ~user               --> "~user/"    --> named user (slash added)
 *

 * Both prefix styles are matched always, irrespective of the machine that you are
 * currently running on.
 *

 * Origin of code: Excalibur, Alexandria, Tomcat, Commons-Utils.
 *
 * @version $Id: FilenameUtils.java 1307462 2012-03-30 15:13:11Z ggregory $
 * @since 1.1
 */
public class FilenameUtils {

    /**
     * The extension separator character.
     * @since 1.4
     */
    public static final char EXTENSION_SEPARATOR = '.';

    /**
     * The extension separator String.
     * @since 1.4
     */
    public static final String EXTENSION_SEPARATOR_STR = Character.toString(EXTENSION_SEPARATOR);

    /**
     * The Unix separator character.
     */
    private static final char UNIX_SEPARATOR = '/';

    /**
     * The Windows separator character.
     */
    private static final char WINDOWS_SEPARATOR = '\\';

    /**
     * The system separator character.
     */
    private static final char SYSTEM_SEPARATOR = File.separatorChar;

    /**
     * The separator character that is the opposite of the system separator.
     */
    private static final char OTHER_SEPARATOR;
    static {
        if (isSystemWindows()) {
            OTHER_SEPARATOR = UNIX_SEPARATOR;
        } else {
            OTHER_SEPARATOR = WINDOWS_SEPARATOR;
        }
    }

    /**
     * Instances should NOT be constructed in standard programming.
     */
    public FilenameUtils() {
        super();
    }

    //-----------------------------------------------------------------------
    /**
     * Determines if Windows file system is in use.
     *
     * @return true if the system is Windows
     */
    static boolean isSystemWindows() {
        return SYSTEM_SEPARATOR == WINDOWS_SEPARATOR;
    }

    //-----------------------------------------------------------------------
    /**
     * Checks if the character is a separator.
     *
     * @param ch  the character to check
     * @return true if it is a separator character
     */
    private static boolean isSeparator(char ch) {
        return ch == UNIX_SEPARATOR || ch == WINDOWS_SEPARATOR;
    }

    //-----------------------------------------------------------------------
    /**
     * Normalizes a path, removing double and single dot path steps.
     *

     * This method normalizes a path to a standard format.
     * The input may contain separators in either Unix or Windows format.
     * The output will contain separators in the format of the system.
     *

     * A trailing slash will be retained.
     * A double slash will be merged to a single slash (but UNC names are handled).
     * A single dot path segment will be removed.
     * A double dot will cause that path segment and the one before to be removed.
     * If the double dot has no parent path segment to work with, {@code null}
     * is returned.
     *

     * The output will be the same on both Unix and Windows except
     * for the separator character.
     *

     * /foo//               -->   /foo/
     * /foo/./              -->   /foo/
     * /foo/../bar          -->   /bar
     * /foo/../bar/         -->   /bar/
     * /foo/../bar/../baz   -->   /baz
     * //foo//./bar         -->   /foo/bar
     * /../                 -->   null
     * ../foo               -->   null
     * foo/bar/..           -->   foo/
     * foo/../../bar        -->   null
     * foo/../bar           -->   bar
     * //server/foo/../bar  -->   //server/bar
     * //server/../bar      -->   null
     * C:\foo\..\bar        -->   C:\bar
     * C:\..\bar            -->   null
     * ~/foo/../bar/        -->   ~/bar/
     * ~/../bar             -->   null
     *

     * (Note the file separator returned will be correct for Windows/Unix)
     *
     * @param filename  the filename to normalize, null returns null
     * @return the normalized filename, or null if invalid
     */
    public static String normalize(String filename) {
        return doNormalize(filename, SYSTEM_SEPARATOR, true);
    }
    /**
     * Normalizes a path, removing double and single dot path steps.
     *

     * This method normalizes a path to a standard format.
     * The input may contain separators in either Unix or Windows format.
     * The output will contain separators in the format specified.
     *

     * A trailing slash will be retained.
     * A double slash will be merged to a single slash (but UNC names are handled).
     * A single dot path segment will be removed.
     * A double dot will cause that path segment and the one before to be removed.
     * If the double dot has no parent path segment to work with, {@code null}
     * is returned.
     *

     * The output will be the same on both Unix and Windows except
     * for the separator character.
     *

     * /foo//               -->   /foo/
     * /foo/./              -->   /foo/
     * /foo/../bar          -->   /bar
     * /foo/../bar/         -->   /bar/
     * /foo/../bar/../baz   -->   /baz
     * //foo//./bar         -->   /foo/bar
     * /../                 -->   null
     * ../foo               -->   null
     * foo/bar/..           -->   foo/
     * foo/../../bar        -->   null
     * foo/../bar           -->   bar
     * //server/foo/../bar  -->   //server/bar
     * //server/../bar      -->   null
     * C:\foo\..\bar        -->   C:\bar
     * C:\..\bar            -->   null
     * ~/foo/../bar/        -->   ~/bar/
     * ~/../bar             -->   null
     *

     * The output will be the same on both Unix and Windows including
     * the separator character.
     *
     * @param filename  the filename to normalize, null returns null
     * @param unixSeparator {@code true} if a unix separator should
     * be used or {@code false} if a windows separator should be used.
     * @return the normalized filename, or null if invalid
     * @since 2.0
     */
    public static String normalize(String filename, boolean unixSeparator) {
        char separator = unixSeparator ? UNIX_SEPARATOR : WINDOWS_SEPARATOR;
        return doNormalize(filename, separator, true);
    }

    //-----------------------------------------------------------------------
    /**
     * Normalizes a path, removing double and single dot path steps,
     * and removing any final directory separator.
     *

     * This method normalizes a path to a standard format.
     * The input may contain separators in either Unix or Windows format.
     * The output will contain separators in the format of the system.
     *

     * A trailing slash will be removed.
     * A double slash will be merged to a single slash (but UNC names are handled).
     * A single dot path segment will be removed.
     * A double dot will cause that path segment and the one before to be removed.
     * If the double dot has no parent path segment to work with, {@code null}
     * is returned.
     *

     * The output will be the same on both Unix and Windows except
     * for the separator character.
     *

     * /foo//               -->   /foo
     * /foo/./              -->   /foo
     * /foo/../bar          -->   /bar
     * /foo/../bar/         -->   /bar
     * /foo/../bar/../baz   -->   /baz
     * //foo//./bar         -->   /foo/bar
     * /../                 -->   null
     * ../foo               -->   null
     * foo/bar/..           -->   foo
     * foo/../../bar        -->   null
     * foo/../bar           -->   bar
     * //server/foo/../bar  -->   //server/bar
     * //server/../bar      -->   null
     * C:\foo\..\bar        -->   C:\bar
     * C:\..\bar            -->   null
     * ~/foo/../bar/        -->   ~/bar
     * ~/../bar             -->   null
     *

     * (Note the file separator returned will be correct for Windows/Unix)
     *
     * @param filename  the filename to normalize, null returns null
     * @return the normalized filename, or null if invalid
     */
    public static String normalizeNoEndSeparator(String filename) {
        return doNormalize(filename, SYSTEM_SEPARATOR, false);
    }

    /**
     * Normalizes a path, removing double and single dot path steps,
     * and removing any final directory separator.
     *

     * This method normalizes a path to a standard format.
     * The input may contain separators in either Unix or Windows format.
     * The output will contain separators in the format specified.
     *

     * A trailing slash will be removed.
     * A double slash will be merged to a single slash (but UNC names are handled).
     * A single dot path segment will be removed.
     * A double dot will cause that path segment and the one before to be removed.
     * If the double dot has no parent path segment to work with, {@code null}
     * is returned.
     *

     * The output will be the same on both Unix and Windows including
     * the separator character.
     *

     * /foo//               -->   /foo
     * /foo/./              -->   /foo
     * /foo/../bar          -->   /bar
     * /foo/../bar/         -->   /bar
     * /foo/../bar/../baz   -->   /baz
     * //foo//./bar         -->   /foo/bar
     * /../                 -->   null
     * ../foo               -->   null
     * foo/bar/..           -->   foo
     * foo/../../bar        -->   null
     * foo/../bar           -->   bar
     * //server/foo/../bar  -->   //server/bar
     * //server/../bar      -->   null
     * C:\foo\..\bar        -->   C:\bar
     * C:\..\bar            -->   null
     * ~/foo/../bar/        -->   ~/bar
     * ~/../bar             -->   null
     *

     *
     * @param filename  the filename to normalize, null returns null
     * @param unixSeparator {@code true} if a unix separator should
     * be used or {@code false} if a windows separtor should be used.
     * @return the normalized filename, or null if invalid
     * @since 2.0
     */
    public static String normalizeNoEndSeparator(String filename, boolean unixSeparator) {
         char separator = unixSeparator ? UNIX_SEPARATOR : WINDOWS_SEPARATOR;
        return doNormalize(filename, separator, false);
    }

    /**
     * Internal method to perform the normalization.
     *
     * @param filename  the filename
     * @param separator The separator character to use
     * @param keepSeparator  true to keep the final separator
     * @return the normalized filename
     */
    private static String doNormalize(String filename, char separator, boolean keepSeparator) {
        if (filename == null) {
            return null;
        }
        int size = filename.length();
        if (size == 0) {
            return filename;
        }
        int prefix = getPrefixLength(filename);
        if (prefix < 0) {
            return null;
        }

        char[] array = new char[size + 2];  // +1 for possible extra slash, +2 for arraycopy
        filename.getChars(0, filename.length(), array, 0);

        // fix separators throughout
        char otherSeparator = separator == SYSTEM_SEPARATOR ? OTHER_SEPARATOR : SYSTEM_SEPARATOR;
        for (int i = 0; i < array.length; i++) {
            if (array[i] == otherSeparator) {
                array[i] = separator;
            }
        }

        // add extra separator on the end to simplify code below
        boolean lastIsDirectory = true;
        if (array[size - 1] != separator) {
            array[size++] = separator;
            lastIsDirectory = false;
        }

        // adjoining slashes
        for (int i = prefix + 1; i < size; i++) {
            if (array[i] == separator && array[i - 1] == separator) {
                System.arraycopy(array, i, array, i - 1, size - i);
                size--;
                i--;
            }
        }

        // dot slash
        for (int i = prefix + 1; i < size; i++) {
            if (array[i] == separator && array[i - 1] == '.' &&
                    (i == prefix + 1 || array[i - 2] == separator)) {
                if (i == size - 1) {
                    lastIsDirectory = true;
                }
                System.arraycopy(array, i + 1, array, i - 1, size - i);
                size -=2;
                i--;
            }
        }

        // double dot slash
        outer:
        for (int i = prefix + 2; i < size; i++) {
            if (array[i] == separator && array[i - 1] == '.' && array[i - 2] == '.' &&
                    (i == prefix + 2 || array[i - 3] == separator)) {
                if (i == prefix + 2) {
                    return null;
                }
                if (i == size - 1) {
                    lastIsDirectory = true;
                }
                int j;
                for (j = i - 4 ; j >= prefix; j--) {
                    if (array[j] == separator) {
                        // remove b/../ from a/b/../c
                        System.arraycopy(array, i + 1, array, j + 1, size - i);
                        size -= i - j;
                        i = j + 1;
                        continue outer;
                    }
                }
                // remove a/../ from a/../c
                System.arraycopy(array, i + 1, array, prefix, size - i);
                size -= i + 1 - prefix;
                i = prefix + 1;
            }
        }

        if (size <= 0) {  // should never be less than 0
            return "";
        }
        if (size <= prefix) {  // should never be less than prefix
            return new String(array, 0, size);
        }
        if (lastIsDirectory && keepSeparator) {
            return new String(array, 0, size);  // keep trailing separator
        }
        return new String(array, 0, size - 1);  // lose trailing separator
    }

    //-----------------------------------------------------------------------
    /**
     * Concatenates a filename to a base path using normal command line style rules.
     *

     * The effect is equivalent to resultant directory after changing
     * directory to the first argument, followed by changing directory to
     * the second argument.
     *

     * The first argument is the base path, the second is the path to concatenate.
     * The returned path is always normalized via {@link #normalize(String)},
     * thus .. is handled.
     *

     * If pathToAdd is absolute (has an absolute prefix), then
     * it will be normalized and returned.
     * Otherwise, the paths will be joined, normalized and returned.
     *

     * The output will be the same on both Unix and Windows except
     * for the separator character.
     *

     * /foo/ + bar          -->   /foo/bar
     * /foo + bar           -->   /foo/bar
     * /foo + /bar          -->   /bar
     * /foo + C:/bar        -->   C:/bar
     * /foo + C:bar         -->   C:bar (*)
     * /foo/a/ + ../bar     -->   foo/bar
     * /foo/ + ../../bar    -->   null
     * /foo/ + /bar         -->   /bar
     * /foo/.. + /bar       -->   /bar
     * /foo + bar/c.txt     -->   /foo/bar/c.txt
     * /foo/c.txt + bar     -->   /foo/c.txt/bar (!)
     *

     * (*) Note that the Windows relative drive prefix is unreliable when
     * used with this method.
     * (!) Note that the first parameter must be a path. If it ends with a name, then
     * the name will be built into the concatenated path. If this might be a problem,
     * use {@link #getFullPath(String)} on the base path argument.
     *
     * @param basePath  the base path to attach to, always treated as a path
     * @param fullFilenameToAdd  the filename (or path) to attach to the base
     * @return the concatenated path, or null if invalid
     */
    public static String concat(String basePath, String fullFilenameToAdd) {
        int prefix = getPrefixLength(fullFilenameToAdd);
        if (prefix < 0) {
            return null;
        }
        if (prefix > 0) {
            return normalize(fullFilenameToAdd);
        }
        if (basePath == null) {
            return null;
        }
        int len = basePath.length();
        if (len == 0) {
            return normalize(fullFilenameToAdd);
        }
        char ch = basePath.charAt(len - 1);
        if (isSeparator(ch)) {
            return normalize(basePath + fullFilenameToAdd);
        } else {
            return normalize(basePath + '/' + fullFilenameToAdd);
        }
    }

    /**
     * Determines whether the {@code parent} directory contains the {@code child} element (a file or directory).
     *

     * The files names are expected to be normalized.
     *

     *
     * Edge cases:
     *

     *
A {@code directory} must not be null: if null, throw IllegalArgumentException

     *
A directory does not contain itself: return false

     *
A null child file is not contained in any parent: return false

     *

     *
     * @param canonicalParent
     *            the file to consider as the parent.
     * @param canonicalChild
     *            the file to consider as the child.
     * @return true is the candidate leaf is under by the specified composite. False otherwise.
     * @throws IOException
     *             if an IO error occurs while checking the files.
     * @since 2.2
     */
    public static boolean directoryContains(final String canonicalParent, final String canonicalChild)
            throws IOException {

        // Fail fast against NullPointerException
        if (canonicalParent == null) {
            throw new IllegalArgumentException("Directory must not be null");
        }

        if (canonicalChild == null) {
            return false;
        }

        if (IOCase.SYSTEM.checkEquals(canonicalParent, canonicalChild)) {
            return false;
        }

        return IOCase.SYSTEM.checkStartsWith(canonicalChild, canonicalParent);
    }

    //-----------------------------------------------------------------------
    /**
     * Converts all separators to the Unix separator of forward slash.
     *
     * @param path  the path to be changed, null ignored
     * @return the updated path
     */
    public static String separatorsToUnix(String path) {
        if (path == null || path.indexOf(WINDOWS_SEPARATOR) == -1) {
            return path;
        }
        return path.replace(WINDOWS_SEPARATOR, UNIX_SEPARATOR);
    }

    /**
     * Converts all separators to the Windows separator of backslash.
     *
     * @param path  the path to be changed, null ignored
     * @return the updated path
     */
    public static String separatorsToWindows(String path) {
        if (path == null || path.indexOf(UNIX_SEPARATOR) == -1) {
            return path;
        }
        return path.replace(UNIX_SEPARATOR, WINDOWS_SEPARATOR);
    }

    /**
     * Converts all separators to the system separator.
     *
     * @param path  the path to be changed, null ignored
     * @return the updated path
     */
    public static String separatorsToSystem(String path) {
        if (path == null) {
            return null;
        }
        if (isSystemWindows()) {
            return separatorsToWindows(path);
        } else {
            return separatorsToUnix(path);
        }
    }

    //-----------------------------------------------------------------------
    /**
     * Returns the length of the filename prefix, such as C:/ or ~/.
     *

     * This method will handle a file in either Unix or Windows format.
     *

     * The prefix length includes the first slash in the full filename
     * if applicable. Thus, it is possible that the length returned is greater
     * than the length of the input string.
     *

     * Windows:
     * a\b\c.txt           --> ""          --> relative
     * \a\b\c.txt          --> "\"         --> current drive absolute
     * C:a\b\c.txt         --> "C:"        --> drive relative
     * C:\a\b\c.txt        --> "C:\"       --> absolute
     * \\server\a\b\c.txt  --> "\\server\" --> UNC
     *
     * Unix:
     * a/b/c.txt           --> ""          --> relative
     * /a/b/c.txt          --> "/"         --> absolute
     * ~/a/b/c.txt         --> "~/"        --> current user
     * ~                   --> "~/"        --> current user (slash added)
     * ~user/a/b/c.txt     --> "~user/"    --> named user
     * ~user               --> "~user/"    --> named user (slash added)
     *

     *

     * The output will be the same irrespective of the machine that the code is running on.
     * ie. both Unix and Windows prefixes are matched regardless.
     *
     * @param filename  the filename to find the prefix in, null returns -1
     * @return the length of the prefix, -1 if invalid or null
     */
    public static int getPrefixLength(String filename) {
        if (filename == null) {
            return -1;
        }
        int len = filename.length();
        if (len == 0) {
            return 0;
        }
        char ch0 = filename.charAt(0);
        if (ch0 == ':') {
            return -1;
        }
        if (len == 1) {
            if (ch0 == '~') {
                return 2;  // return a length greater than the input
            }
            return isSeparator(ch0) ? 1 : 0;
        } else {
            if (ch0 == '~') {
                int posUnix = filename.indexOf(UNIX_SEPARATOR, 1);
                int posWin = filename.indexOf(WINDOWS_SEPARATOR, 1);
                if (posUnix == -1 && posWin == -1) {
                    return len + 1;  // return a length greater than the input
                }
                posUnix = posUnix == -1 ? posWin : posUnix;
                posWin = posWin == -1 ? posUnix : posWin;
                return Math.min(posUnix, posWin) + 1;
            }
            char ch1 = filename.charAt(1);
            if (ch1 == ':') {
                ch0 = Character.toUpperCase(ch0);
                if (ch0 >= 'A' && ch0 <= 'Z') {
                    if (len == 2 || isSeparator(filename.charAt(2)) == false) {
                        return 2;
                    }
                    return 3;
                }
                return -1;

            } else if (isSeparator(ch0) && isSeparator(ch1)) {
                int posUnix = filename.indexOf(UNIX_SEPARATOR, 2);
                int posWin = filename.indexOf(WINDOWS_SEPARATOR, 2);
                if (posUnix == -1 && posWin == -1 || posUnix == 2 || posWin == 2) {
                    return -1;
                }
                posUnix = posUnix == -1 ? posWin : posUnix;
                posWin = posWin == -1 ? posUnix : posWin;
                return Math.min(posUnix, posWin) + 1;
            } else {
                return isSeparator(ch0) ? 1 : 0;
            }
        }
    }

    /**
     * Returns the index of the last directory separator character.
     *

     * This method will handle a file in either Unix or Windows format.
     * The position of the last forward or backslash is returned.
     *

     * The output will be the same irrespective of the machine that the code is running on.
     *
     * @param filename  the filename to find the last path separator in, null returns -1
     * @return the index of the last separator character, or -1 if there
     * is no such character
     */
    public static int indexOfLastSeparator(String filename) {
        if (filename == null) {
            return -1;
        }
        int lastUnixPos = filename.lastIndexOf(UNIX_SEPARATOR);
        int lastWindowsPos = filename.lastIndexOf(WINDOWS_SEPARATOR);
        return Math.max(lastUnixPos, lastWindowsPos);
    }

    /**
     * Returns the index of the last extension separator character, which is a dot.
     *

     * This method also checks that there is no directory separator after the last dot.
     * To do this it uses {@link #indexOfLastSeparator(String)} which will
     * handle a file in either Unix or Windows format.
     *

     * The output will be the same irrespective of the machine that the code is running on.
     *
     * @param filename  the filename to find the last path separator in, null returns -1
     * @return the index of the last separator character, or -1 if there
     * is no such character
     */
    public static int indexOfExtension(String filename) {
        if (filename == null) {
            return -1;
        }
        int extensionPos = filename.lastIndexOf(EXTENSION_SEPARATOR);
        int lastSeparator = indexOfLastSeparator(filename);
        return lastSeparator > extensionPos ? -1 : extensionPos;
    }

    //-----------------------------------------------------------------------
    /**
     * Gets the prefix from a full filename, such as C:/
     * or ~/.
     *

     * This method will handle a file in either Unix or Windows format.
     * The prefix includes the first slash in the full filename where applicable.
     *

     * Windows:
     * a\b\c.txt           --> ""          --> relative
     * \a\b\c.txt          --> "\"         --> current drive absolute
     * C:a\b\c.txt         --> "C:"        --> drive relative
     * C:\a\b\c.txt        --> "C:\"       --> absolute
     * \\server\a\b\c.txt  --> "\\server\" --> UNC
     *
     * Unix:
     * a/b/c.txt           --> ""          --> relative
     * /a/b/c.txt          --> "/"         --> absolute
     * ~/a/b/c.txt         --> "~/"        --> current user
     * ~                   --> "~/"        --> current user (slash added)
     * ~user/a/b/c.txt     --> "~user/"    --> named user
     * ~user               --> "~user/"    --> named user (slash added)
     *

     *

     * The output will be the same irrespective of the machine that the code is running on.
     * ie. both Unix and Windows prefixes are matched regardless.
     *
     * @param filename  the filename to query, null returns null
     * @return the prefix of the file, null if invalid
     */
    public static String getPrefix(String filename) {
        if (filename == null) {
            return null;
        }
        int len = getPrefixLength(filename);
        if (len < 0) {
            return null;
        }
        if (len > filename.length()) {
            return filename + UNIX_SEPARATOR;  // we know this only happens for unix
        }
        return filename.substring(0, len);
    }

    /**
     * Gets the path from a full filename, which excludes the prefix.
     *

     * This method will handle a file in either Unix or Windows format.
     * The method is entirely text based, and returns the text before and
     * including the last forward or backslash.
     *

     * C:\a\b\c.txt --> a\b\
     * ~/a/b/c.txt  --> a/b/
     * a.txt        --> ""
     * a/b/c        --> a/b/
     * a/b/c/       --> a/b/c/
     *

     *

     * The output will be the same irrespective of the machine that the code is running on.
     *

     * This method drops the prefix from the result.
     * See {@link #getFullPath(String)} for the method that retains the prefix.
     *
     * @param filename  the filename to query, null returns null
     * @return the path of the file, an empty string if none exists, null if invalid
     */
    public static String getPath(String filename) {
        return doGetPath(filename, 1);
    }

    /**
     * Gets the path from a full filename, which excludes the prefix, and
     * also excluding the final directory separator.
     *

     * This method will handle a file in either Unix or Windows format.
     * The method is entirely text based, and returns the text before the
     * last forward or backslash.
     *

     * C:\a\b\c.txt --> a\b
     * ~/a/b/c.txt  --> a/b
     * a.txt        --> ""
     * a/b/c        --> a/b
     * a/b/c/       --> a/b/c
     *

     *

     * The output will be the same irrespective of the machine that the code is running on.
     *

     * This method drops the prefix from the result.
     * See {@link #getFullPathNoEndSeparator(String)} for the method that retains the prefix.
     *
     * @param filename  the filename to query, null returns null
     * @return the path of the file, an empty string if none exists, null if invalid
     */
    public static String getPathNoEndSeparator(String filename) {
        return doGetPath(filename, 0);
    }

    /**
     * Does the work of getting the path.
     *
     * @param filename  the filename
     * @param separatorAdd  0 to omit the end separator, 1 to return it
     * @return the path
     */
    private static String doGetPath(String filename, int separatorAdd) {
        if (filename == null) {
            return null;
        }
        int prefix = getPrefixLength(filename);
        if (prefix < 0) {
            return null;
        }
        int index = indexOfLastSeparator(filename);
        int endIndex = index+separatorAdd;
        if (prefix >= filename.length() || index < 0 || prefix >= endIndex) {
            return "";
        }
        return filename.substring(prefix, endIndex);
    }

    /**
     * Gets the full path from a full filename, which is the prefix + path.
     *

     * This method will handle a file in either Unix or Windows format.
     * The method is entirely text based, and returns the text before and
     * including the last forward or backslash.
     *

     * C:\a\b\c.txt --> C:\a\b\
     * ~/a/b/c.txt  --> ~/a/b/
     * a.txt        --> ""
     * a/b/c        --> a/b/
     * a/b/c/       --> a/b/c/
     * C:           --> C:
     * C:\          --> C:\
     * ~            --> ~/
     * ~/           --> ~/
     * ~user        --> ~user/
     * ~user/       --> ~user/
     *

     *

     * The output will be the same irrespective of the machine that the code is running on.
     *
     * @param filename  the filename to query, null returns null
     * @return the path of the file, an empty string if none exists, null if invalid
     */
    public static String getFullPath(String filename) {
        return doGetFullPath(filename, true);
    }

    /**
     * Gets the full path from a full filename, which is the prefix + path,
     * and also excluding the final directory separator.
     *

     * This method will handle a file in either Unix or Windows format.
     * The method is entirely text based, and returns the text before the
     * last forward or backslash.
     *

     * C:\a\b\c.txt --> C:\a\b
     * ~/a/b/c.txt  --> ~/a/b
     * a.txt        --> ""
     * a/b/c        --> a/b
     * a/b/c/       --> a/b/c
     * C:           --> C:
     * C:\          --> C:\
     * ~            --> ~
     * ~/           --> ~
     * ~user        --> ~user
     * ~user/       --> ~user
     *

     *

     * The output will be the same irrespective of the machine that the code is running on.
     *
     * @param filename  the filename to query, null returns null
     * @return the path of the file, an empty string if none exists, null if invalid
     */
    public static String getFullPathNoEndSeparator(String filename) {
        return doGetFullPath(filename, false);
    }

    /**
     * Does the work of getting the path.
     *
     * @param filename  the filename
     * @param includeSeparator  true to include the end separator
     * @return the path
     */
    private static String doGetFullPath(String filename, boolean includeSeparator) {
        if (filename == null) {
            return null;
        }
        int prefix = getPrefixLength(filename);
        if (prefix < 0) {
            return null;
        }
        if (prefix >= filename.length()) {
            if (includeSeparator) {
                return getPrefix(filename);  // add end slash if necessary
            } else {
                return filename;
            }
        }
        int index = indexOfLastSeparator(filename);
        if (index < 0) {
            return filename.substring(0, prefix);
        }
        int end = index + (includeSeparator ?  1 : 0);
        if (end == 0) {
            end++;
        }
        return filename.substring(0, end);
    }

    /**
     * Gets the name minus the path from a full filename.
     *

     * This method will handle a file in either Unix or Windows format.
     * The text after the last forward or backslash is returned.
     *

     * a/b/c.txt --> c.txt
     * a.txt     --> a.txt
     * a/b/c     --> c
     * a/b/c/    --> ""
     *

     *

     * The output will be the same irrespective of the machine that the code is running on.
     *
     * @param filename  the filename to query, null returns null
     * @return the name of the file without the path, or an empty string if none exists
     */
    public static String getName(String filename) {
        if (filename == null) {
            return null;
        }
        int index = indexOfLastSeparator(filename);
        return filename.substring(index + 1);
    }

    /**
     * Gets the base name, minus the full path and extension, from a full filename.
     *

     * This method will handle a file in either Unix or Windows format.
     * The text after the last forward or backslash and before the last dot is returned.
     *

     * a/b/c.txt --> c
     * a.txt     --> a
     * a/b/c     --> c
     * a/b/c/    --> ""
     *

     *

     * The output will be the same irrespective of the machine that the code is running on.
     *
     * @param filename  the filename to query, null returns null
     * @return the name of the file without the path, or an empty string if none exists
     */
    public static String getBaseName(String filename) {
        return removeExtension(getName(filename));
    }

    /**
     * Gets the extension of a filename.
     *

     * This method returns the textual part of the filename after the last dot.
     * There must be no directory separator after the dot.
     *

     * foo.txt      --> "txt"
     * a/b/c.jpg    --> "jpg"
     * a/b.txt/c    --> ""
     * a/b/c        --> ""
     *

     *

     * The output will be the same irrespective of the machine that the code is running on.
     *
     * @param filename the filename to retrieve the extension of.
     * @return the extension of the file or an empty string if none exists or {@code null}
     * if the filename is {@code null}.
     */
    public static String getExtension(String filename) {
        if (filename == null) {
            return null;
        }
        int index = indexOfExtension(filename);
        if (index == -1) {
            return "";
        } else {
            return filename.substring(index + 1);
        }
    }

    //-----------------------------------------------------------------------
    /**
     * Removes the extension from a filename.
     *

     * This method returns the textual part of the filename before the last dot.
     * There must be no directory separator after the dot.
     *

     * foo.txt    --> foo
     * a\b\c.jpg  --> a\b\c
     * a\b\c      --> a\b\c
     * a.b\c      --> a.b\c
     *

     *

     * The output will be the same irrespective of the machine that the code is running on.
     *
     * @param filename  the filename to query, null returns null
     * @return the filename minus the extension
     */
    public static String removeExtension(String filename) {
        if (filename == null) {
            return null;
        }
        int index = indexOfExtension(filename);
        if (index == -1) {
            return filename;
        } else {
            return filename.substring(0, index);
        }
    }

    //-----------------------------------------------------------------------
    /**
     * Checks whether two filenames are equal exactly.
     *

     * No processing is performed on the filenames other than comparison,
     * thus this is merely a null-safe case-sensitive equals.
     *
     * @param filename1  the first filename to query, may be null
     * @param filename2  the second filename to query, may be null
     * @return true if the filenames are equal, null equals null
     * @see IOCase#SENSITIVE
     */
    public static boolean equals(String filename1, String filename2) {
        return equals(filename1, filename2, false, IOCase.SENSITIVE);
    }

    /**
     * Checks whether two filenames are equal using the case rules of the system.
     *

     * No processing is performed on the filenames other than comparison.
     * The check is case-sensitive on Unix and case-insensitive on Windows.
     *
     * @param filename1  the first filename to query, may be null
     * @param filename2  the second filename to query, may be null
     * @return true if the filenames are equal, null equals null
     * @see IOCase#SYSTEM
     */
    public static boolean equalsOnSystem(String filename1, String filename2) {
        return equals(filename1, filename2, false, IOCase.SYSTEM);
    }

    //-----------------------------------------------------------------------
    /**
     * Checks whether two filenames are equal after both have been normalized.
     *

     * Both filenames are first passed to {@link #normalize(String)}.
     * The check is then performed in a case-sensitive manner.
     *
     * @param filename1  the first filename to query, may be null
     * @param filename2  the second filename to query, may be null
     * @return true if the filenames are equal, null equals null
     * @see IOCase#SENSITIVE
     */
    public static boolean equalsNormalized(String filename1, String filename2) {
        return equals(filename1, filename2, true, IOCase.SENSITIVE);
    }

    /**
     * Checks whether two filenames are equal after both have been normalized
     * and using the case rules of the system.
     *

     * Both filenames are first passed to {@link #normalize(String)}.
     * The check is then performed case-sensitive on Unix and
     * case-insensitive on Windows.
     *
     * @param filename1  the first filename to query, may be null
     * @param filename2  the second filename to query, may be null
     * @return true if the filenames are equal, null equals null
     * @see IOCase#SYSTEM
     */
    public static boolean equalsNormalizedOnSystem(String filename1, String filename2) {
        return equals(filename1, filename2, true, IOCase.SYSTEM);
    }

    /**
     * Checks whether two filenames are equal, optionally normalizing and providing
     * control over the case-sensitivity.
     *
     * @param filename1  the first filename to query, may be null
     * @param filename2  the second filename to query, may be null
     * @param normalized  whether to normalize the filenames
     * @param caseSensitivity  what case sensitivity rule to use, null means case-sensitive
     * @return true if the filenames are equal, null equals null
     * @since 1.3
     */
    public static boolean equals(
            String filename1, String filename2,
            boolean normalized, IOCase caseSensitivity) {

        if (filename1 == null || filename2 == null) {
            return filename1 == null && filename2 == null;
        }
        if (normalized) {
            filename1 = normalize(filename1);
            filename2 = normalize(filename2);
            if (filename1 == null || filename2 == null) {
                throw new NullPointerException(
                    "Error normalizing one or both of the file names");
            }
        }
        if (caseSensitivity == null) {
            caseSensitivity = IOCase.SENSITIVE;
        }
        return caseSensitivity.checkEquals(filename1, filename2);
    }

    //-----------------------------------------------------------------------
    /**
     * Checks whether the extension of the filename is that specified.
     *

     * This method obtains the extension as the textual part of the filename
     * after the last dot. There must be no directory separator after the dot.
     * The extension check is case-sensitive on all platforms.
     *
     * @param filename  the filename to query, null returns false
     * @param extension  the extension to check for, null or empty checks for no extension
     * @return true if the filename has the specified extension
     */
    public static boolean isExtension(String filename, String extension) {
        if (filename == null) {
            return false;
        }
        if (extension == null || extension.length() == 0) {
            return indexOfExtension(filename) == -1;
        }
        String fileExt = getExtension(filename);
        return fileExt.equals(extension);
    }

    /**
     * Checks whether the extension of the filename is one of those specified.
     *

     * This method obtains the extension as the textual part of the filename
     * after the last dot. There must be no directory separator after the dot.
     * The extension check is case-sensitive on all platforms.
     *
     * @param filename  the filename to query, null returns false
     * @param extensions  the extensions to check for, null checks for no extension
     * @return true if the filename is one of the extensions
     */
    public static boolean isExtension(String filename, String[] extensions) {
        if (filename == null) {
            return false;
        }
        if (extensions == null || extensions.length == 0) {
            return indexOfExtension(filename) == -1;
        }
        String fileExt = getExtension(filename);
        for (String extension : extensions) {
            if (fileExt.equals(extension)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Checks whether the extension of the filename is one of those specified.
     *

     * This method obtains the extension as the textual part of the filename
     * after the last dot. There must be no directory separator after the dot.
     * The extension check is case-sensitive on all platforms.
     *
     * @param filename  the filename to query, null returns false
     * @param extensions  the extensions to check for, null checks for no extension
     * @return true if the filename is one of the extensions
     */
    public static boolean isExtension(String filename, Collection<String> extensions) {
        if (filename == null) {
            return false;
        }
        if (extensions == null || extensions.isEmpty()) {
            return indexOfExtension(filename) == -1;
        }
        String fileExt = getExtension(filename);
        for (String extension : extensions) {
            if (fileExt.equals(extension)) {
                return true;
            }
        }
        return false;
    }

    //-----------------------------------------------------------------------
    /**
     * Checks a filename to see if it matches the specified wildcard matcher,
     * always testing case-sensitive.
     *

     * The wildcard matcher uses the characters '?' and '*' to represent a
     * single or multiple (zero or more) wildcard characters.
     * This is the same as often found on Dos/Unix command lines.
     * The check is case-sensitive always.
     *

     * wildcardMatch("c.txt", "*.txt")      --> true
     * wildcardMatch("c.txt", "*.jpg")      --> false
     * wildcardMatch("a/b/c.txt", "a/b/*")  --> true
     * wildcardMatch("c.txt", "*.???")      --> true
     * wildcardMatch("c.txt", "*.????")     --> false
     *

     * N.B. the sequence "*?" does not work properly at present in match strings.
     *
     * @param filename  the filename to match on
     * @param wildcardMatcher  the wildcard string to match against
     * @return true if the filename matches the wilcard string
     * @see IOCase#SENSITIVE
     */
    public static boolean wildcardMatch(String filename, String wildcardMatcher) {
        return wildcardMatch(filename, wildcardMatcher, IOCase.SENSITIVE);
    }

    /**
     * Checks a filename to see if it matches the specified wildcard matcher
     * using the case rules of the system.
     *

     * The wildcard matcher uses the characters '?' and '*' to represent a
     * single or multiple (zero or more) wildcard characters.
     * This is the same as often found on Dos/Unix command lines.
     * The check is case-sensitive on Unix and case-insensitive on Windows.
     *

     * wildcardMatch("c.txt", "*.txt")      --> true
     * wildcardMatch("c.txt", "*.jpg")      --> false
     * wildcardMatch("a/b/c.txt", "a/b/*")  --> true
     * wildcardMatch("c.txt", "*.???")      --> true
     * wildcardMatch("c.txt", "*.????")     --> false
     *

     * N.B. the sequence "*?" does not work properly at present in match strings.
     *
     * @param filename  the filename to match on
     * @param wildcardMatcher  the wildcard string to match against
     * @return true if the filename matches the wilcard string
     * @see IOCase#SYSTEM
     */
    public static boolean wildcardMatchOnSystem(String filename, String wildcardMatcher) {
        return wildcardMatch(filename, wildcardMatcher, IOCase.SYSTEM);
    }

    /**
     * Checks a filename to see if it matches the specified wildcard matcher
     * allowing control over case-sensitivity.
     *

     * The wildcard matcher uses the characters '?' and '*' to represent a
     * single or multiple (zero or more) wildcard characters.
     * N.B. the sequence "*?" does not work properly at present in match strings.
     *
     * @param filename  the filename to match on
     * @param wildcardMatcher  the wildcard string to match against
     * @param caseSensitivity  what case sensitivity rule to use, null means case-sensitive
     * @return true if the filename matches the wilcard string
     * @since 1.3
     */
    public static boolean wildcardMatch(String filename, String wildcardMatcher, IOCase caseSensitivity) {
        if (filename == null && wildcardMatcher == null) {
            return true;
        }
        if (filename == null || wildcardMatcher == null) {
            return false;
        }
        if (caseSensitivity == null) {
            caseSensitivity = IOCase.SENSITIVE;
        }
        String[] wcs = splitOnTokens(wildcardMatcher);
        boolean anyChars = false;
        int textIdx = 0;
        int wcsIdx = 0;
        Stack<int[]> backtrack = new Stack<int[]>();

        // loop around a backtrack stack, to handle complex * matching
        do {
            if (backtrack.size() > 0) {
                int[] array = backtrack.pop();
                wcsIdx = array[0];
                textIdx = array[1];
                anyChars = true;
            }

            // loop whilst tokens and text left to process
            while (wcsIdx < wcs.length) {

                if (wcs[wcsIdx].equals("?")) {
                    // ? so move to next text char
                    textIdx++;
                    if (textIdx > filename.length()) {
                        break;
                    }
                    anyChars = false;

                } else if (wcs[wcsIdx].equals("*")) {
                    // set any chars status
                    anyChars = true;
                    if (wcsIdx == wcs.length - 1) {
                        textIdx = filename.length();
                    }

                } else {
                    // matching text token
                    if (anyChars) {
                        // any chars then try to locate text token
                        textIdx = caseSensitivity.checkIndexOf(filename, textIdx, wcs[wcsIdx]);
                        if (textIdx == -1) {
                            // token not found
                            break;
                        }
                        int repeat = caseSensitivity.checkIndexOf(filename, textIdx + 1, wcs[wcsIdx]);
                        if (repeat >= 0) {
                            backtrack.push(new int[] {wcsIdx, repeat});
                        }
                    } else {
                        // matching from current position
                        if (!caseSensitivity.checkRegionMatches(filename, textIdx, wcs[wcsIdx])) {
                            // couldnt match token
                            break;
                        }
                    }

                    // matched text token, move text index to end of matched token
                    textIdx += wcs[wcsIdx].length();
                    anyChars = false;
                }

                wcsIdx++;
            }

            // full match
            if (wcsIdx == wcs.length && textIdx == filename.length()) {
                return true;
            }

        } while (backtrack.size() > 0);

        return false;
    }

    /**
     * Splits a string into a number of tokens.
     * The text is split by '?' and '*'.
     * Where multiple '*' occur consecutively they are collapsed into a single '*'.
     *
     * @param text  the text to split
     * @return the array of tokens, never null
     */
    static String[] splitOnTokens(String text) {
        // used by wildcardMatch
        // package level so a unit test may run on this

        if (text.indexOf('?') == -1 && text.indexOf('*') == -1) {
            return new String[] { text };
        }

        char[] array = text.toCharArray();
        ArrayList<String> list = new ArrayList<String>();
        StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < array.length; i++) {
            if (array[i] == '?' || array[i] == '*') {
                if (buffer.length() != 0) {
                    list.add(buffer.toString());
                    buffer.setLength(0);
                }
                if (array[i] == '?') {
                    list.add("?");
                } else if (list.isEmpty() ||
                        i > 0 && list.get(list.size() - 1).equals("*") == false) {
                    list.add("*");
                }
            } else {
                buffer.append(array[i]);
            }
        }
        if (buffer.length() != 0) {
            list.add(buffer.toString());
        }

        return list.toArray( new String[ list.size() ] );
    }

}


/*
 * Copyright (C) 2015-2018 Emanuel Moecklin
 *
 * 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.onegravity.rteditor.effects;

import android.text.Spannable;

import com.onegravity.rteditor.spans.RTSpan;
import com.onegravity.rteditor.utils.Selection;

import java.lang.reflect.Array;
import java.util.List;

/**
 * Spanned.getSpans(int, int, Class) unfortunately doesn't respect the mark/point flags
 * (SPAN_EXCLUSIVE_EXCLUSIVE, SPAN_INCLUSIVE_EXCLUSIVE etc.).
 *
 * Android finds spans that precede or follow a selection (adjacent spans).
 *
 * - if the span is a point (start == end) --> every adjacent selection (cursor, range = selected text) will match:
 *   01234[]|56789     point selection after point span   --> getSpans returns span
 *   01234|[]56789     point selection before point span  --> getSpans returns span
 *   01234[]|56|789    range selection after point span   --> getSpans returns span
 *   012|34|[]56789    range selection before point span  --> getSpans returns span
 *
 * - if the span is a range (start < end) --> only point selections (cursors) will match:
 *   01[234]|56789     point selection after range span  --> getSpans returns span
 *   01234|[567]89     point selection before range span --> getSpans returns span
 *   01[234]|56|789    range selection after range span  --> getSpans returns nothing
 *   012|34|[567]89    range selection before range span --> getSpans returns nothing
 *
 * The span flags (SPAN_EXCLUSIVE_INCLUSIVE etc.) have no impact!
 *
 * (exception SPAN_EXCLUSIVE_EXCLUSIVE for point spans because those can't have a length of 0 and
 *  will be removed automatically:
 *  http://developer.android.com/reference/android/text/Spanned.html#SPAN_EXCLUSIVE_EXCLUSIVE)
 *
 * Sometimes we need to find or ignore adjacent spans depending on the span flags, the position of a
 * span, the selection (last line, empty lines...) and the type of span (character, paragraph).
 *
 * This class allows us to implement different getSpan methods that honor the span flags.
 *
 * @param <V> the Effect's configuration information.
 */
abstract class SpanCollector<V> {

    private Class<? extends RTSpan<V>> mSpanClazz;

    protected SpanCollector(Class<? extends RTSpan<V>> spanClazz) {
        mSpanClazz = spanClazz;
    }

    /**
     * Equivalent to the Spanned.getSpans(int, int, Class<T>) method.
     * Return the markup objects (spans) attached to the specified slice of a Spannable.
     * The type of the spans is defined in the SpanCollector.
     *
     * @param str The Spannable to search for spans.
     * @param selection The selection within the Spannable to search for spans.
     * @param mode details see SpanCollectMode.
     *
     * @return the list of spans in this Spannable/Selection, never Null
     */
    protected abstract List<RTSpan<V>> getSpans(Spannable str, Selection selection, SpanCollectMode mode);

    /**
     * Return an array of the markup objects attached to the specified slice of a Spannable and whose
     * type is the specified type or a subclass of it (see Spanned.getSpans(int, int, Class<T>)).
     */
    final protected RTSpan<V>[] getSpansAndroid(Spannable str, int selStart, int selEnd) {
        RTSpan<V>[] spans = str.getSpans(selStart, selEnd, mSpanClazz);
        return spans == null ? (RTSpan<V>[]) Array.newInstance(mSpanClazz) : spans;
    }

    /**
     * @return True if the flags contain at least one of the values, False otherwise.
     */
    final protected boolean isOneFlagSet(int flags, int...value) {
        for (int flag : value) {
            if ((flags & flag) == flag) {
                return true;
            }
        }
        return false;
    }

}


/*
 * Copyright (C) 2007 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.onegravity.rteditor.media.crop;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;

import java.util.ArrayList;

class CropImageView extends ImageViewTouchBase {

    ArrayList<HighlightView> mHighlightViews = new ArrayList<HighlightView>();
    HighlightView mMotionHighlightView = null;
    float mLastX, mLastY;
    int mMotionEdge;

    private Context mContext;

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (mBitmapDisplayed.getBitmap() != null) {
            for (HighlightView hv : mHighlightViews) {
                hv.mMatrix.set(getImageMatrix());
                hv.invalidate();
                if (hv.mIsFocused) {
                    centerBasedOnHighlightView(hv);
                }
            }
        }
    }

    public CropImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
    }

    @Override
    protected void zoomTo(float scale, float centerX, float centerY) {
        super.zoomTo(scale, centerX, centerY);
        for (HighlightView hv : mHighlightViews) {
            hv.mMatrix.set(getImageMatrix());
            hv.invalidate();
        }
    }

    @Override
    protected void zoomIn() {
        super.zoomIn();
        for (HighlightView hv : mHighlightViews) {
            hv.mMatrix.set(getImageMatrix());
            hv.invalidate();
        }
    }

    @Override
    protected void zoomOut() {
        super.zoomOut();
        for (HighlightView hv : mHighlightViews) {
            hv.mMatrix.set(getImageMatrix());
            hv.invalidate();
        }
    }

    @Override
    protected void postTranslate(float deltaX, float deltaY) {
        super.postTranslate(deltaX, deltaY);
        for (int i = 0; i < mHighlightViews.size(); i++) {
            HighlightView hv = mHighlightViews.get(i);
            hv.mMatrix.postTranslate(deltaX, deltaY);
            hv.invalidate();
        }
    }

    // According to the event's position, change the focus to the first
    // hitting cropping rectangle.
    private void recomputeFocus(MotionEvent event) {
        for (int i = 0; i < mHighlightViews.size(); i++) {
            HighlightView hv = mHighlightViews.get(i);
            hv.setFocus(false);
            hv.invalidate();
        }

        for (int i = 0; i < mHighlightViews.size(); i++) {
            HighlightView hv = mHighlightViews.get(i);
            int edge = hv.getHit(event.getX(), event.getY());
            if (edge != HighlightView.GROW_NONE) {
                if (!hv.hasFocus()) {
                    hv.setFocus(true);
                    hv.invalidate();
                }
                break;
            }
        }
        invalidate();
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        CropImageActivity cropImage = (CropImageActivity) mContext;
        if (cropImage.mSaving) {
            return false;
        }

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (cropImage.mWaitingToPick) {
                    recomputeFocus(event);
                } else {
                    for (int i = 0; i < mHighlightViews.size(); i++) {
                        HighlightView hv = mHighlightViews.get(i);
                        int edge = hv.getHit(event.getX(), event.getY());
                        if (edge != HighlightView.GROW_NONE) {
                            mMotionEdge = edge;
                            mMotionHighlightView = hv;
                            mLastX = event.getX();
                            mLastY = event.getY();
                            mMotionHighlightView
                                    .setMode((edge == HighlightView.MOVE) ? HighlightView.ModifyMode.Move
                                            : HighlightView.ModifyMode.Grow);
                            break;
                        }
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                if (cropImage.mWaitingToPick) {
                    for (int i = 0; i < mHighlightViews.size(); i++) {
                        HighlightView hv = mHighlightViews.get(i);
                        if (hv.hasFocus()) {
                            cropImage.mCrop = hv;
                            for (int j = 0; j < mHighlightViews.size(); j++) {
                                if (j == i) {
                                    continue;
                                }
                                mHighlightViews.get(j).setHidden(true);
                            }
                            centerBasedOnHighlightView(hv);
                            ((CropImageActivity) mContext).mWaitingToPick = false;
                            return true;
                        }
                    }
                } else if (mMotionHighlightView != null) {
                    centerBasedOnHighlightView(mMotionHighlightView);
                    mMotionHighlightView.setMode(HighlightView.ModifyMode.None);
                }
                mMotionHighlightView = null;
                break;
            case MotionEvent.ACTION_MOVE:
                if (cropImage.mWaitingToPick) {
                    recomputeFocus(event);
                } else if (mMotionHighlightView != null) {
                    mMotionHighlightView.handleMotion(mMotionEdge, event.getX()
                            - mLastX, event.getY() - mLastY);
                    mLastX = event.getX();
                    mLastY = event.getY();

                    if (true) {
                        // This section of code is optional. It has some user
                        // benefit in that moving the crop rectangle against
                        // the edge of the screen causes scrolling but it means
                        // that the crop rectangle is no longer fixed under
                        // the user's finger.
                        ensureVisible(mMotionHighlightView);
                    }
                }
                break;
        }

        switch (event.getAction()) {
            case MotionEvent.ACTION_UP:
                center(true, true);
                break;
            case MotionEvent.ACTION_MOVE:
                // if we're not zoomed then there's no point in even allowing
                // the user to move the image around. This call to center puts
                // it back to the normalized location (with false meaning don't
                // animate).
                if (getScale() == 1F) {
                    center(true, true);
                }
                break;
        }

        return true;
    }

    // Pan the displayed image to make sure the cropping rectangle is visible.
    private void ensureVisible(HighlightView hv) {
        Rect r = hv.mDrawRect;

        int panDeltaX1 = Math.max(0, mLeft - r.left);
        int panDeltaX2 = Math.min(0, mRight - r.right);

        int panDeltaY1 = Math.max(0, mTop - r.top);
        int panDeltaY2 = Math.min(0, mBottom - r.bottom);

        int panDeltaX = panDeltaX1 != 0 ? panDeltaX1 : panDeltaX2;
        int panDeltaY = panDeltaY1 != 0 ? panDeltaY1 : panDeltaY2;

        if (panDeltaX != 0 || panDeltaY != 0) {
            panBy(panDeltaX, panDeltaY);
        }
    }

    // If the cropping rectangle's size changed significantly, change the
    // view's center and scale according to the cropping rectangle.
    private void centerBasedOnHighlightView(HighlightView hv) {
        Rect drawRect = hv.mDrawRect;

        float width = drawRect.width();
        float height = drawRect.height();

        float thisWidth = getWidth();
        float thisHeight = getHeight();

        float z1 = thisWidth / width * .8F;
        float z2 = thisHeight / height * .8F;

        float zoom = Math.min(z1, z2);
        zoom = zoom * this.getScale();
        zoom = Math.max(1F, zoom);
        if ((Math.abs(zoom - getScale()) / zoom) > .1) {
            float[] coordinates = new float[]{hv.mCropRect.centerX(), hv.mCropRect.centerY()};
            getImageMatrix().mapPoints(coordinates);
            zoomTo(zoom, coordinates[0], coordinates[1], 300F);
        }

        ensureVisible(hv);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for (int i = 0; i < mHighlightViews.size(); i++) {
            mHighlightViews.get(i).draw(canvas);
        }
    }

    public void add(HighlightView hv) {
        mHighlightViews.add(hv);
        invalidate();
    }
}


// This file is part of TagSoup and is Copyright 2002-2008 by John Cowan.
//
// TagSoup is licensed under the Apache License,
// Version 2.0.  You may obtain a copy of this license at
// http://www.apache.org/licenses/LICENSE-2.0 .  You may also have
// additional legal rights not granted by this license.
//
// TagSoup is distributed in the hope that it will be useful, but
// unless required by applicable law or agreed to in writing, TagSoup
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, either express or implied; not even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
//

package com.onegravity.rteditor.converter.tagsoup;

import java.io.*;

import org.xml.sax.SAXException;
import org.xml.sax.Locator;

/**
 * This class implements a table-driven scanner for HTML, allowing for lots of
 * defects. It implements the Scanner interface, which accepts a Reader object
 * to fetch characters from and a ScanHandler object to report lexical events
 * to.
 */

public class HTMLScanner implements Scanner, Locator {

    // Start of state table
    private static final int S_ANAME = 1;
    private static final int S_APOS = 2;
    private static final int S_AVAL = 3;
    private static final int S_BB = 4;
    private static final int S_BBC = 5;
    private static final int S_BBCD = 6;
    private static final int S_BBCDA = 7;
    private static final int S_BBCDAT = 8;
    private static final int S_BBCDATA = 9;
    private static final int S_CDATA = 10;
    private static final int S_CDATA2 = 11;
    private static final int S_CDSECT = 12;
    private static final int S_CDSECT1 = 13;
    private static final int S_CDSECT2 = 14;
    private static final int S_COM = 15;
    private static final int S_COM2 = 16;
    private static final int S_COM3 = 17;
    private static final int S_COM4 = 18;
    private static final int S_DECL = 19;
    private static final int S_DECL2 = 20;
    private static final int S_DONE = 21;
    private static final int S_EMPTYTAG = 22;
    private static final int S_ENT = 23;
    private static final int S_EQ = 24;
    private static final int S_ETAG = 25;
    private static final int S_GI = 26;
    private static final int S_NCR = 27;
    private static final int S_PCDATA = 28;
    private static final int S_PI = 29;
    private static final int S_PITARGET = 30;
    private static final int S_QUOT = 31;
    private static final int S_STAGC = 32;
    private static final int S_TAG = 33;
    private static final int S_TAGWS = 34;
    private static final int S_XNCR = 35;
    private static final int A_ADUP = 1;
    private static final int A_ADUP_SAVE = 2;
    private static final int A_ADUP_STAGC = 3;
    private static final int A_ANAME = 4;
    private static final int A_ANAME_ADUP = 5;
    private static final int A_ANAME_ADUP_STAGC = 6;
    private static final int A_AVAL = 7;
    private static final int A_AVAL_STAGC = 8;
    private static final int A_CDATA = 9;
    private static final int A_CMNT = 10;
    private static final int A_DECL = 11;
    private static final int A_EMPTYTAG = 12;
    private static final int A_ENTITY = 13;
    private static final int A_ENTITY_START = 14;
    private static final int A_ETAG = 15;
    private static final int A_GI = 16;
    private static final int A_GI_STAGC = 17;
    private static final int A_LT = 18;
    private static final int A_LT_PCDATA = 19;
    private static final int A_MINUS = 20;
    private static final int A_MINUS2 = 21;
    private static final int A_MINUS3 = 22;
    private static final int A_PCDATA = 23;
    private static final int A_PI = 24;
    private static final int A_PITARGET = 25;
    private static final int A_PITARGET_PI = 26;
    private static final int A_SAVE = 27;
    private static final int A_SKIP = 28;
    private static final int A_SP = 29;
    private static final int A_STAGC = 30;
    private static final int A_UNGET = 31;
    private static final int A_UNSAVE_PCDATA = 32;
    private static int[] statetable = {S_ANAME, '/', A_ANAME_ADUP, S_EMPTYTAG,
            S_ANAME, '=', A_ANAME, S_AVAL, S_ANAME, '>', A_ANAME_ADUP_STAGC,
            S_PCDATA, S_ANAME, 0, A_SAVE, S_ANAME, S_ANAME, -1,
            A_ANAME_ADUP_STAGC, S_DONE, S_ANAME, ' ', A_ANAME, S_EQ, S_ANAME,
            '\n', A_ANAME, S_EQ, S_ANAME, '\t', A_ANAME, S_EQ, S_APOS, '\'',
            A_AVAL, S_TAGWS, S_APOS, 0, A_SAVE, S_APOS, S_APOS, -1,
            A_AVAL_STAGC, S_DONE, S_APOS, ' ', A_SP, S_APOS, S_APOS, '\n',
            A_SP, S_APOS, S_APOS, '\t', A_SP, S_APOS, S_AVAL, '\'', A_SKIP,
            S_APOS, S_AVAL, '"', A_SKIP, S_QUOT, S_AVAL, '>', A_AVAL_STAGC,
            S_PCDATA, S_AVAL, 0, A_SAVE, S_STAGC, S_AVAL, -1, A_AVAL_STAGC,
            S_DONE, S_AVAL, ' ', A_SKIP, S_AVAL, S_AVAL, '\n', A_SKIP, S_AVAL,
            S_AVAL, '\t', A_SKIP, S_AVAL, S_BB, 'C', A_SKIP, S_BBC, S_BB, 0,
            A_SKIP, S_DECL, S_BB, -1, A_SKIP, S_DONE, S_BBC, 'D', A_SKIP,
            S_BBCD, S_BBC, 0, A_SKIP, S_DECL, S_BBC, -1, A_SKIP, S_DONE,
            S_BBCD, 'A', A_SKIP, S_BBCDA, S_BBCD, 0, A_SKIP, S_DECL, S_BBCD,
            -1, A_SKIP, S_DONE, S_BBCDA, 'T', A_SKIP, S_BBCDAT, S_BBCDA, 0,
            A_SKIP, S_DECL, S_BBCDA, -1, A_SKIP, S_DONE, S_BBCDAT, 'A', A_SKIP,
            S_BBCDATA, S_BBCDAT, 0, A_SKIP, S_DECL, S_BBCDAT, -1, A_SKIP,
            S_DONE, S_BBCDATA, '[', A_SKIP, S_CDSECT, S_BBCDATA, 0, A_SKIP,
            S_DECL, S_BBCDATA, -1, A_SKIP, S_DONE, S_CDATA, '<', A_SAVE,
            S_CDATA2, S_CDATA, 0, A_SAVE, S_CDATA, S_CDATA, -1, A_PCDATA,
            S_DONE, S_CDATA2, '/', A_UNSAVE_PCDATA, S_ETAG, S_CDATA2, 0,
            A_SAVE, S_CDATA, S_CDATA2, -1, A_UNSAVE_PCDATA, S_DONE, S_CDSECT,
            ']', A_SAVE, S_CDSECT1, S_CDSECT, 0, A_SAVE, S_CDSECT, S_CDSECT,
            -1, A_SKIP, S_DONE, S_CDSECT1, ']', A_SAVE, S_CDSECT2, S_CDSECT1,
            0, A_SAVE, S_CDSECT, S_CDSECT1, -1, A_SKIP, S_DONE, S_CDSECT2, '>',
            A_CDATA, S_PCDATA, S_CDSECT2, 0, A_SAVE, S_CDSECT, S_CDSECT2, -1,
            A_SKIP, S_DONE, S_COM, '-', A_SKIP, S_COM2, S_COM, 0, A_SAVE,
            S_COM2, S_COM, -1, A_CMNT, S_DONE, S_COM2, '-', A_SKIP, S_COM3,
            S_COM2, 0, A_SAVE, S_COM2, S_COM2, -1, A_CMNT, S_DONE, S_COM3, '-',
            A_SKIP, S_COM4, S_COM3, 0, A_MINUS, S_COM2, S_COM3, -1, A_CMNT,
            S_DONE, S_COM4, '-', A_MINUS3, S_COM4, S_COM4, '>', A_CMNT,
            S_PCDATA, S_COM4, 0, A_MINUS2, S_COM2, S_COM4, -1, A_CMNT, S_DONE,
            S_DECL, '-', A_SKIP, S_COM, S_DECL, '[', A_SKIP, S_BB, S_DECL, '>',
            A_SKIP, S_PCDATA, S_DECL, 0, A_SAVE, S_DECL2, S_DECL, -1, A_SKIP,
            S_DONE, S_DECL2, '>', A_DECL, S_PCDATA, S_DECL2, 0, A_SAVE,
            S_DECL2, S_DECL2, -1, A_SKIP, S_DONE, S_EMPTYTAG, '>', A_EMPTYTAG,
            S_PCDATA, S_EMPTYTAG, 0, A_SAVE, S_ANAME, S_EMPTYTAG, ' ', A_SKIP,
            S_TAGWS, S_EMPTYTAG, '\n', A_SKIP, S_TAGWS, S_EMPTYTAG, '\t',
            A_SKIP, S_TAGWS, S_ENT, 0, A_ENTITY, S_ENT, S_ENT, -1, A_ENTITY,
            S_DONE, S_EQ, '=', A_SKIP, S_AVAL, S_EQ, '>', A_ADUP_STAGC,
            S_PCDATA, S_EQ, 0, A_ADUP_SAVE, S_ANAME, S_EQ, -1, A_ADUP_STAGC,
            S_DONE, S_EQ, ' ', A_SKIP, S_EQ, S_EQ, '\n', A_SKIP, S_EQ, S_EQ,
            '\t', A_SKIP, S_EQ, S_ETAG, '>', A_ETAG, S_PCDATA, S_ETAG, 0,
            A_SAVE, S_ETAG, S_ETAG, -1, A_ETAG, S_DONE, S_ETAG, ' ', A_SKIP,
            S_ETAG, S_ETAG, '\n', A_SKIP, S_ETAG, S_ETAG, '\t', A_SKIP, S_ETAG,
            S_GI, '/', A_SKIP, S_EMPTYTAG, S_GI, '>', A_GI_STAGC, S_PCDATA,
            S_GI, 0, A_SAVE, S_GI, S_GI, -1, A_SKIP, S_DONE, S_GI, ' ', A_GI,
            S_TAGWS, S_GI, '\n', A_GI, S_TAGWS, S_GI, '\t', A_GI, S_TAGWS,
            S_NCR, 0, A_ENTITY, S_NCR, S_NCR, -1, A_ENTITY, S_DONE, S_PCDATA,
            '&', A_ENTITY_START, S_ENT, S_PCDATA, '<', A_PCDATA, S_TAG,
            S_PCDATA, 0, A_SAVE, S_PCDATA, S_PCDATA, -1, A_PCDATA, S_DONE,
            S_PI, '>', A_PI, S_PCDATA, S_PI, 0, A_SAVE, S_PI, S_PI, -1, A_PI,
            S_DONE, S_PITARGET, '>', A_PITARGET_PI, S_PCDATA, S_PITARGET, 0,
            A_SAVE, S_PITARGET, S_PITARGET, -1, A_PITARGET_PI, S_DONE,
            S_PITARGET, ' ', A_PITARGET, S_PI, S_PITARGET, '\n', A_PITARGET,
            S_PI, S_PITARGET, '\t', A_PITARGET, S_PI, S_QUOT, '"', A_AVAL,
            S_TAGWS, S_QUOT, 0, A_SAVE, S_QUOT, S_QUOT, -1, A_AVAL_STAGC,
            S_DONE, S_QUOT, ' ', A_SP, S_QUOT, S_QUOT, '\n', A_SP, S_QUOT,
            S_QUOT, '\t', A_SP, S_QUOT, S_STAGC, '>', A_AVAL_STAGC, S_PCDATA,
            S_STAGC, 0, A_SAVE, S_STAGC, S_STAGC, -1, A_AVAL_STAGC, S_DONE,
            S_STAGC, ' ', A_AVAL, S_TAGWS, S_STAGC, '\n', A_AVAL, S_TAGWS,
            S_STAGC, '\t', A_AVAL, S_TAGWS, S_TAG, '!', A_SKIP, S_DECL, S_TAG,
            '?', A_SKIP, S_PITARGET, S_TAG, '/', A_SKIP, S_ETAG, S_TAG, '<',
            A_SAVE, S_TAG, S_TAG, 0, A_SAVE, S_GI, S_TAG, -1, A_LT_PCDATA,
            S_DONE, S_TAG, ' ', A_LT, S_PCDATA, S_TAG, '\n', A_LT, S_PCDATA,
            S_TAG, '\t', A_LT, S_PCDATA, S_TAGWS, '/', A_SKIP, S_EMPTYTAG,
            S_TAGWS, '>', A_STAGC, S_PCDATA, S_TAGWS, 0, A_SAVE, S_ANAME,
            S_TAGWS, -1, A_STAGC, S_DONE, S_TAGWS, ' ', A_SKIP, S_TAGWS,
            S_TAGWS, '\n', A_SKIP, S_TAGWS, S_TAGWS, '\t', A_SKIP, S_TAGWS,
            S_XNCR, 0, A_ENTITY, S_XNCR, S_XNCR, -1, A_ENTITY, S_DONE,

    };

    // End of state table

    private String thePublicid; // Locator state
    private String theSystemid;
    private int theLastLine;
    private int theLastColumn;
    private int theCurrentLine;
    private int theCurrentColumn;

    int theState; // Current state
    int theNextState; // Next state
    char[] theOutputBuffer = new char[200]; // Output buffer
    int theSize; // Current buffer size
    int[] theWinMap = { // Windows chars map
            0x20AC, 0xFFFD, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6,
            0x2030, 0x0160, 0x2039, 0x0152, 0xFFFD, 0x017D, 0xFFFD, 0xFFFD,
            0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC,
            0x2122, 0x0161, 0x203A, 0x0153, 0xFFFD, 0x017E, 0x0178};

    // Compensate for bug in PushbackReader that allows
    // pushing back EOF.
    private void unread(PushbackReader r, int c) throws IOException {
        if (c != -1)
            r.unread(c);
    }

    // Locator implementation

    public int getLineNumber() {
        return theLastLine;
    }

    public int getColumnNumber() {
        return theLastColumn;
    }

    public String getPublicId() {
        return thePublicid;
    }

    public String getSystemId() {
        return theSystemid;
    }

    // Scanner implementation

    /**
     * Reset document locator, supplying systemid and publicid.
     *
     * @param systemid System id
     * @param publicid Public id
     */

    public void resetDocumentLocator(String publicid, String systemid) {
        thePublicid = publicid;
        theSystemid = systemid;
        theLastLine = theLastColumn = theCurrentLine = theCurrentColumn = 0;
    }

    /**
     * Scan HTML source, reporting lexical events.
     *
     * @param r0 Reader that provides characters
     * @param h  ScanHandler that accepts lexical events.
     */
    public void scan(Reader r0, ScanHandler h) throws IOException, SAXException {
        theState = S_PCDATA;
        PushbackReader r;
        if (r0 instanceof PushbackReader) {
            r = (PushbackReader) r0;
        } else if (r0 instanceof BufferedReader) {
            r = new PushbackReader(r0);
        } else {
            r = new PushbackReader(new BufferedReader(r0, 200));
        }

        int firstChar = r.read(); // Remove any leading BOM
        if (firstChar != '\uFEFF')
            unread(r, firstChar);

        while (theState != S_DONE) {
            int c1 = r.read();
            char c = (char) c1;
            boolean is32BitChar = Character.isHighSurrogate(c);
            int c2 = is32BitChar ? r.read() : -1;
            String s = is32BitChar ? new StringBuffer().append(c).append((char) c2).toString() : null;

            // Process control characters
            if (!is32BitChar && c1 >= 0x80 && c1 <= 0x9F)
                c1 = theWinMap[c1 - 0x80];

            if (!is32BitChar && c1 == '\r') {
                c1 = r.read(); // expect LF next
                if (c1 != '\n') {
                    unread(r, c1); // nope
                    c1 = '\n';
                }
            }

            if (!is32BitChar && c1 == '\n') {
                theCurrentLine++;
                theCurrentColumn = 0;
            } else {
                theCurrentColumn++;
            }

            if (!!is32BitChar && !(c1 >= 0x20 || c1 == '\n' || c1 == '\t' || c1 == -1))
                continue;

            // Search state table
            int action = 0;
            for (int i = 0; i < statetable.length; i += 4) {
                if (theState != statetable[i]) {
                    if (action != 0)
                        break;
                    continue;
                }
                if (statetable[i + 1] == 0) {
                    action = statetable[i + 2];
                    theNextState = statetable[i + 3];
                } else if (!is32BitChar && statetable[i + 1] == c1) {
                    action = statetable[i + 2];
                    theNextState = statetable[i + 3];
                    break;
                }
            }
            switch (action) {
                case 0:
                    throw new Error("HTMLScanner can't cope with " + Integer.toString(c1) + " in state " + Integer.toString(theState));
                case A_ADUP:
                    h.adup(theOutputBuffer, 0, theSize);
                    theSize = 0;
                    break;
                case A_ADUP_SAVE:
                    h.adup(theOutputBuffer, 0, theSize);
                    theSize = 0;
                    if (s != null)
                        save(s, c1, h);
                    break;
                case A_ADUP_STAGC:
                    h.adup(theOutputBuffer, 0, theSize);
                    theSize = 0;
                    h.stagc(theOutputBuffer, 0, theSize);
                    break;
                case A_ANAME:
                    h.aname(theOutputBuffer, 0, theSize);
                    theSize = 0;
                    break;
                case A_ANAME_ADUP:
                    h.aname(theOutputBuffer, 0, theSize);
                    theSize = 0;
                    h.adup(theOutputBuffer, 0, theSize);
                    break;
                case A_ANAME_ADUP_STAGC:
                    h.aname(theOutputBuffer, 0, theSize);
                    theSize = 0;
                    h.adup(theOutputBuffer, 0, theSize);
                    h.stagc(theOutputBuffer, 0, theSize);
                    break;
                case A_AVAL:
                    h.aval(theOutputBuffer, 0, theSize);
                    theSize = 0;
                    break;
                case A_AVAL_STAGC:
                    h.aval(theOutputBuffer, 0, theSize);
                    theSize = 0;
                    h.stagc(theOutputBuffer, 0, theSize);
                    break;
                case A_CDATA:
                    mark();
                    // suppress the final "]]" in the buffer
                    if (theSize > 1)
                        theSize -= 2;
                    h.pcdata(theOutputBuffer, 0, theSize);
                    theSize = 0;
                    break;
                case A_ENTITY_START:
                    h.pcdata(theOutputBuffer, 0, theSize);
                    theSize = 0;
                    save(s, c1, h);
                    break;
                case A_ENTITY:
                    mark();
                    if (theState == S_ENT && c == '#') {
                        theNextState = S_NCR;
                        save(s, c1, h);
                        break;
                    } else if (theState == S_NCR && (c == 'x' || c == 'X')) {
                        theNextState = S_XNCR;
                        save(s, c1, h);
                        break;
                    } else if (theState == S_ENT && Character.isLetterOrDigit(c)) {
                        save(s, c1, h);
                        break;
                    } else if (theState == S_NCR && Character.isDigit(c)) {
                        save(s, c1, h);
                        break;
                    } else if (theState == S_XNCR && (Character.isDigit(c) || "abcdefABCDEF".indexOf(c) != -1)) {
                        save(s, c1, h);
                        break;
                    }

                    // The whole entity reference has been collected
                    h.entity(theOutputBuffer, 1, theSize - 1);
                    int ent = h.getEntity();
                    if (ent != 0) {
                        theSize = 0;
                        if (ent >= 0x80 && ent <= 0x9F) {
                            ent = theWinMap[ent - 0x80];
                        }
                        if (ent < 0x20) {
                            // Control becomes space
                            ent = 0x20;
                        } else if (ent >= 0xD800 && ent <= 0xDFFF) {
                            // Surrogates get dropped
                            ent = 0;
                        } else if (ent <= 0xFFFF) {
                            // BMP character
                            save(ent, h);
                        } else {
                            // Astral converted to two surrogates
                            ent -= 0x10000;
                            save((ent >> 10) + 0xD800, h);
                            save((ent & 0x3FF) + 0xDC00, h);
                        }
                        if (is32BitChar || c1 != ';') {
                            if (is32BitChar) {
                                unread(r, c2);
                                theCurrentColumn--;
                            }
                            unread(r, c1);
                            theCurrentColumn--;
                        }
                    } else {
                        if (is32BitChar) {
                            unread(r, c2);
                            theCurrentColumn--;
                        }
                        unread(r, c1);
                        theCurrentColumn--;
                    }
                    theNextState = S_PCDATA;
                    break;
                case A_ETAG:
                    h.etag(theOutputBuffer, 0, theSize);
                    theSize = 0;
                    break;
                case A_DECL:
                    h.decl(theOutputBuffer, 0, theSize);
                    theSize = 0;
                    break;
                case A_GI:
                    h.gi(theOutputBuffer, 0, theSize);
                    theSize = 0;
                    break;
                case A_GI_STAGC:
                    h.gi(theOutputBuffer, 0, theSize);
                    theSize = 0;
                    h.stagc(theOutputBuffer, 0, theSize);
                    break;
                case A_LT:
                    mark();
                    save('<', h);
                    save(s, c1, h);
                    break;
                case A_LT_PCDATA:
                    mark();
                    save('<', h);
                    h.pcdata(theOutputBuffer, 0, theSize);
                    theSize = 0;
                    break;
                case A_PCDATA:
                    mark();
                    h.pcdata(theOutputBuffer, 0, theSize);
                    theSize = 0;
                    break;
                case A_CMNT:
                    mark();
                    h.cmnt(theOutputBuffer, 0, theSize);
                    theSize = 0;
                    break;
                case A_MINUS3:
                    save('-', h);
                    save(' ', h);
                    break;
                case A_MINUS2:
                    save('-', h);
                    save(' ', h);
                    // fall through into A_MINUS
                case A_MINUS:
                    save('-', h);
                    save(s, c1, h);
                    break;
                case A_PI:
                    mark();
                    h.pi(theOutputBuffer, 0, theSize);
                    theSize = 0;
                    break;
                case A_PITARGET:
                    h.pitarget(theOutputBuffer, 0, theSize);
                    theSize = 0;
                    break;
                case A_PITARGET_PI:
                    h.pitarget(theOutputBuffer, 0, theSize);
                    theSize = 0;
                    h.pi(theOutputBuffer, 0, theSize);
                    break;
                case A_SAVE:
                    save(s, c1, h);
                    break;
                case A_SKIP:
                    break;
                case A_SP:
                    save(' ', h);
                    break;
                case A_STAGC:
                    h.stagc(theOutputBuffer, 0, theSize);
                    theSize = 0;
                    break;
                case A_EMPTYTAG:
                    mark();
                    if (theSize > 0)
                        h.gi(theOutputBuffer, 0, theSize);
                    theSize = 0;
                    h.stage(theOutputBuffer, 0, theSize);
                    break;
                case A_UNGET:
                    unread(r, c1);
                    theCurrentColumn--;
                    break;
                case A_UNSAVE_PCDATA:
                    if (theSize > 0)
                        theSize--;
                    h.pcdata(theOutputBuffer, 0, theSize);
                    theSize = 0;
                    break;
                default:
                    throw new Error("Can't process state " + action);
            }
            theState = theNextState;
        }
        h.eof(theOutputBuffer, 0, 0);
    }

    /**
     * Mark the current scan position as a "point of interest" - start of a tag,
     * cdata, processing instruction etc.
     */

    private void mark() {
        theLastColumn = theCurrentColumn;
        theLastLine = theCurrentLine;
    }

    /**
     * A callback for the ScanHandler that allows it to force the lexer state to
     * CDATA content (no markup is recognized except the end of element.
     */

    public void startCDATA() {
        theNextState = S_CDATA;
    }

    private void save(int ch, ScanHandler h) throws IOException, SAXException {
        save(h);
        theOutputBuffer[theSize++] = (char) ch;
    }

    private void save(String s, int ch, ScanHandler h) throws IOException, SAXException {
        if (s == null) {
            save(ch, h);
        } else {
            save(h);
            for (int i = 0, len = s.length(); i < len; i++) {
                theOutputBuffer[theSize++] = s.charAt(i);
            }
        }
    }

    private void save(ScanHandler h) throws IOException, SAXException {
        if (theSize >= theOutputBuffer.length - 20) {
            if (theState == S_PCDATA || theState == S_CDATA) {
                // Return a buffer-sized chunk of PCDATA
                h.pcdata(theOutputBuffer, 0, theSize);
                theSize = 0;
            } else {
                // Grow the buffer size
                char[] newOutputBuffer = new char[theOutputBuffer.length * 2];
                System.arraycopy(theOutputBuffer, 0, newOutputBuffer, 0, theSize + 1);
                theOutputBuffer = newOutputBuffer;
            }
        }
    }
}


/*
 * 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 com.onegravity.rteditor.utils.validator;

import java.io.Serializable;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

/**
 * Regular Expression validation (using JDK 1.4+ regex support).
 *

 * Construct the validator either for a single regular expression or a set (array) of
 * regular expressions. By default validation is case sensitive but constructors
 * are provided to allow  case in-sensitive validation. For example to create
 * a validator which does case in-sensitive validation for a set of regular
 * expressions:
 *

 *

 *
 * String[] regexs = new String[] {...};
 * RegexValidator validator = new RegexValidator(regexs, false);
 *
 *

 *
 *

 *
Validate true or false:

 *

 *

 *
boolean valid = validator.isValid(value);

 *

 *

 *
Validate returning an aggregated String of the matched groups:

 *

 *

 *
String result = validator.validate(value);

 *

 *

 *
Validate returning the matched groups:

 *

 *

 *
String[] result = validator.match(value);

 *

 *

 *

 *
 *

 * Cached instances pre-compile and re-use {@link Pattern}(s) - which according
 * to the {@link Pattern} API are safe to use in a multi-threaded environment.
 *

 *
 * @version $Revision: 1649191 $
 * @since Validator 1.4
 */
public class RegexValidator implements Serializable {

    private static final long serialVersionUID = -8832409930574867162L;

    private final Pattern[] patterns;

    /**
     * Construct a case sensitive validator for a single
     * regular expression.
     *
     * @param regex The regular expression this validator will
     * validate against
     */
    public RegexValidator(String regex) {
        this(regex, true);
    }

    /**
     * Construct a validator for a single regular expression
     * with the specified case sensitivity.
     *
     * @param regex The regular expression this validator will
     * validate against
     * @param caseSensitive when true matching is case
     * sensitive, otherwise matching is case in-sensitive
     */
    public RegexValidator(String regex, boolean caseSensitive) {
        this(new String[] {regex}, caseSensitive);
    }

    /**
     * Construct a case sensitive validator that matches any one
     * of the set of regular expressions.
     *
     * @param regexs The set of regular expressions this validator will
     * validate against
     */
    public RegexValidator(String[] regexs) {
        this(regexs, true);
    }

    /**
     * Construct a validator that matches any one of the set of regular
     * expressions with the specified case sensitivity.
     *
     * @param regexs The set of regular expressions this validator will
     * validate against
     * @param caseSensitive when true matching is case
     * sensitive, otherwise matching is case in-sensitive
     */
    public RegexValidator(String[] regexs, boolean caseSensitive) {
        if (regexs == null || regexs.length == 0) {
            throw new IllegalArgumentException("Regular expressions are missing");
        }
        patterns = new Pattern[regexs.length];
        int flags =  (caseSensitive ? 0: Pattern.CASE_INSENSITIVE);
        for (int i = 0; i < regexs.length; i++) {
            if (regexs[i] == null || regexs[i].length() == 0) {
                throw new IllegalArgumentException("Regular expression[" + i + "] is missing");
            }
            patterns[i] =  Pattern.compile(regexs[i], flags);
        }
    }

    /**
     * Validate a value against the set of regular expressions.
     *
     * @param value The value to validate.
     * @return true if the value is valid
     * otherwise false.
     */
    public boolean isValid(String value) {
        if (value == null) {
            return false;
        }
        for (int i = 0; i < patterns.length; i++) {
            if (patterns[i].matcher(value).matches()) {
                return true;
            }
        }
        return false;
    }

    /**
     * Validate a value against the set of regular expressions
     * returning the array of matched groups.
     *
     * @param value The value to validate.
     * @return String array of the groups matched if
     * valid or null if invalid
     */
    public String[] match(String value) {
        if (value == null) {
            return null;
        }
        for (int i = 0; i < patterns.length; i++) {
            Matcher matcher = patterns[i].matcher(value);
            if (matcher.matches()) {
                int count = matcher.groupCount();
                String[] groups = new String[count];
                for (int j = 0; j < count; j++) {
                    groups[j] = matcher.group(j+1);
                }
                return groups;
            }
        }
        return null;
    }

    /**
     * Validate a value against the set of regular expressions
     * returning a String value of the aggregated groups.
     *
     * @param value The value to validate.
     * @return Aggregated String value comprised of the
     * groups matched if valid or null if invalid
     */
    public String validate(String value) {
        if (value == null) {
            return null;
        }
        for (int i = 0; i < patterns.length; i++) {
            Matcher matcher = patterns[i].matcher(value);
            if (matcher.matches()) {
                int count = matcher.groupCount();
                if (count == 1) {
                    return matcher.group(1);
                }
                StringBuffer buffer = new StringBuffer();
                for (int j = 0; j < count; j++) {
                    String component = matcher.group(j+1);
                    if (component != null) {
                        buffer.append(component);
                    }
                }
                return buffer.toString();
            }
        }
        return null;
    }

    /**
     * Provide a String representation of this validator.
     * @return A String representation of this validator
     */
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append("RegexValidator{");
        for (int i = 0; i < patterns.length; i++) {
            if (i > 0) {
                buffer.append(",");
            }
            buffer.append(patterns[i].pattern());
        }
        buffer.append("}");
        return buffer.toString();
    }

}


/*
 * Copyright (C) 2015-2018 Emanuel Moecklin
 *
 * 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.onegravity.rteditor.utils;

/**
 * A Paragraph is a Selection but represents a whole text paragraph.
 */
public class Paragraph extends Selection {
    private static final long serialVersionUID = 2475227150049924994L;

    final private boolean mIsFirst;
    final private boolean mIsLast;

    public Paragraph(int start, int end, boolean isFirst, boolean isLast) {
        super(start, end);
        mIsFirst = isFirst;
        mIsLast = isLast;
    }

    /**
     * @return True if this is the first paragraph in the editor, False otherwise
     */
    public boolean isFirst() {
        return mIsFirst;
    }

    /**
     * @return True if this is the last paragraph in the editor, False otherwise
     */
    public boolean isLast() {
        return mIsLast;
    }

    /**
     * The paragraph is selected by the Selection if:
     * <p>
     * - they have at least one character in common
     * - the selection is a point within the paragraph ("01\n" -> 0 till 2 intersects while the span is [0, 3])
     * - the selection is a point within or at the end of the LAST paragraph ("01" -> 0 till 2 intersects while the span is [0, 2]),
     * e.g. [10, 10] will intersect the paragraph [0, 10] only if it's the last paragraph
     */
    public boolean isSelected(Selection sel) {
        if (sel == null) {
            return false;
        }
        if (sel.isEmpty()) {
            // selection is a point
            boolean isCompletelyWithin = sel.start() >= start() && sel.end() < end();  // selection is completely within paragraph (not at the end)
            boolean isWithin = sel.start() >= start() && sel.end() <= end();           // selection is within or at the end of the paragraph
            return isCompletelyWithin || (isWithin && mIsLast);
        } else {
            // selection is a range --> at least one character in common
            int start = Math.max(start(), sel.start());
            int end = Math.min(end(), sel.end());
            return start < end;
        }
    }

}