diff --git a/docs/Makefile b/docs/Makefile index d4bb2cbb..d0c3cbf1 100644 --- a/docs/Makefile +++ b/docs/Makefile @@ -5,8 +5,8 @@ # from the environment for the first two. SPHINXOPTS ?= SPHINXBUILD ?= sphinx-build -SOURCEDIR = . -BUILDDIR = _build +SOURCEDIR = source +BUILDDIR = build # Put it first so that "make" without argument is like "make help". help: diff --git a/docs/build/doctrees/cli.doctree b/docs/build/doctrees/cli.doctree new file mode 100644 index 00000000..8c589b7c Binary files /dev/null and b/docs/build/doctrees/cli.doctree differ diff --git a/docs/build/doctrees/environment.pickle b/docs/build/doctrees/environment.pickle new file mode 100644 index 00000000..3c36d2e1 Binary files /dev/null and b/docs/build/doctrees/environment.pickle differ diff --git a/docs/build/doctrees/index.doctree b/docs/build/doctrees/index.doctree new file mode 100644 index 00000000..5cfe191a Binary files /dev/null and b/docs/build/doctrees/index.doctree differ diff --git a/docs/build/doctrees/modules.doctree b/docs/build/doctrees/modules.doctree new file mode 100644 index 00000000..cf3c71c9 Binary files /dev/null and b/docs/build/doctrees/modules.doctree differ diff --git a/docs/build/doctrees/reference.doctree b/docs/build/doctrees/reference.doctree new file mode 100644 index 00000000..ca6a59ab Binary files /dev/null and b/docs/build/doctrees/reference.doctree differ diff --git a/docs/build/html/.buildinfo b/docs/build/html/.buildinfo new file mode 100644 index 00000000..b96c5bdb --- /dev/null +++ b/docs/build/html/.buildinfo @@ -0,0 +1,4 @@ +# Sphinx build info version 1 +# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. +config: 547179dc83846d861e5f79c600fa9301 +tags: 645f666f9bcd5a90fca523b33c5a78b7 diff --git a/docs/build/html/_modules/index.html b/docs/build/html/_modules/index.html new file mode 100644 index 00000000..e6ae3db5 --- /dev/null +++ b/docs/build/html/_modules/index.html @@ -0,0 +1,105 @@ + + + + + + + + Overview: module code — osxphotos 0.40.4 documentation + + + + + + + + + + + + + + + + + +
+
+ +
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/build/html/_modules/osxphotos/photoinfo/_photoinfo_exifinfo.html b/docs/build/html/_modules/osxphotos/photoinfo/_photoinfo_exifinfo.html new file mode 100644 index 00000000..7ce03cbd --- /dev/null +++ b/docs/build/html/_modules/osxphotos/photoinfo/_photoinfo_exifinfo.html @@ -0,0 +1,195 @@ + + + + + + + + osxphotos.photoinfo._photoinfo_exifinfo — osxphotos 0.40.4 documentation + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Source code for osxphotos.photoinfo._photoinfo_exifinfo

+""" PhotoInfo methods to expose EXIF info from the library """
+
+import logging
+from dataclasses import dataclass
+
+from .._constants import _PHOTOS_4_VERSION
+
+
+@dataclass(frozen=True)
+class ExifInfo:
+    """ EXIF info associated with a photo from the Photos library """
+
+    flash_fired: bool
+    iso: int
+    metering_mode: int
+    sample_rate: int
+    track_format: int
+    white_balance: int
+    aperture: float
+    bit_rate: float
+    duration: float
+    exposure_bias: float
+    focal_length: float
+    fps: float
+    latitude: float
+    longitude: float
+    shutter_speed: float
+    camera_make: str
+    camera_model: str
+    codec: str
+    lens_model: str
+
+
+@property
+def exif_info(self):
+    """ Returns an ExifInfo object with the EXIF data for photo
+        Note: the returned EXIF data is the data Photos stores in the database on import;
+        ExifInfo does not provide access to the EXIF info in the actual image file
+        Some or all of the fields may be None
+        Only valid for Photos 5; on earlier database returns None
+        """
+
+    if self._db._db_version <= _PHOTOS_4_VERSION:
+        logging.debug(f"exif_info not implemented for this database version")
+        return None
+
+    try:
+        exif = self._db._db_exifinfo_uuid[self.uuid]
+        exif_info = ExifInfo(
+            iso=exif["ZISO"],
+            flash_fired=True if exif["ZFLASHFIRED"] == 1 else False,
+            metering_mode=exif["ZMETERINGMODE"],
+            sample_rate=exif["ZSAMPLERATE"],
+            track_format=exif["ZTRACKFORMAT"],
+            white_balance=exif["ZWHITEBALANCE"],
+            aperture=exif["ZAPERTURE"],
+            bit_rate=exif["ZBITRATE"],
+            duration=exif["ZDURATION"],
+            exposure_bias=exif["ZEXPOSUREBIAS"],
+            focal_length=exif["ZFOCALLENGTH"],
+            fps=exif["ZFPS"],
+            latitude=exif["ZLATITUDE"],
+            longitude=exif["ZLONGITUDE"],
+            shutter_speed=exif["ZSHUTTERSPEED"],
+            camera_make=exif["ZCAMERAMAKE"],
+            camera_model=exif["ZCAMERAMODEL"],
+            codec=exif["ZCODEC"],
+            lens_model=exif["ZLENSMODEL"],
+        )
+    except KeyError:
+        logging.debug(f"Could not find exif record for uuid {self.uuid}")
+        exif_info = ExifInfo(
+            iso=None,
+            flash_fired=None,
+            metering_mode=None,
+            sample_rate=None,
+            track_format=None,
+            white_balance=None,
+            aperture=None,
+            bit_rate=None,
+            duration=None,
+            exposure_bias=None,
+            focal_length=None,
+            fps=None,
+            latitude=None,
+            longitude=None,
+            shutter_speed=None,
+            camera_make=None,
+            camera_model=None,
+            codec=None,
+            lens_model=None,
+        )
+
+    return exif_info
+
+ +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/build/html/_modules/osxphotos/photoinfo/_photoinfo_export.html b/docs/build/html/_modules/osxphotos/photoinfo/_photoinfo_export.html new file mode 100644 index 00000000..1b65faf3 --- /dev/null +++ b/docs/build/html/_modules/osxphotos/photoinfo/_photoinfo_export.html @@ -0,0 +1,1935 @@ + + + + + + + + osxphotos.photoinfo._photoinfo_export — osxphotos 0.40.4 documentation + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Source code for osxphotos.photoinfo._photoinfo_export

+""" Export methods for PhotoInfo 
+    The following methods are defined and must be imported into PhotoInfo as instance methods:
+    export
+    export2
+    _export_photo
+    _write_exif_data
+    _exiftool_json_sidecar
+    _get_exif_keywords
+    _get_exif_persons
+    _exiftool_dict
+    _xmp_sidecar
+    _write_sidecar
+    """
+
+# TODO: should this be its own PhotoExporter class?
+# TODO: the various sidecar_json, sidecar_xmp, etc args should all be collapsed to a sidecar param using a bit mask
+
+import glob
+import hashlib
+import json
+import logging
+import os
+import pathlib
+import re
+import tempfile
+from collections import namedtuple  # pylint: disable=syntax-error
+
+import photoscript
+from mako.template import Template
+
+# from .._applescript import AppleScript
+from .._constants import (
+    _MAX_IPTC_KEYWORD_LEN,
+    _OSXPHOTOS_NONE_SENTINEL,
+    _TEMPLATE_DIR,
+    _UNKNOWN_PERSON,
+    _XMP_TEMPLATE_NAME,
+    _XMP_TEMPLATE_NAME_BETA,
+    SIDECAR_EXIFTOOL,
+    SIDECAR_JSON,
+    SIDECAR_XMP,
+)
+from .._version import __version__
+from ..datetime_utils import datetime_tz_to_utc
+from ..exiftool import ExifTool
+from ..export_db import ExportDBNoOp
+from ..fileutil import FileUtil
+from ..photokit import (
+    PHOTOS_VERSION_CURRENT,
+    PHOTOS_VERSION_ORIGINAL,
+    PhotoKitFetchFailed,
+    PhotoLibrary,
+)
+from ..utils import findfiles, get_preferred_uti_extension, lineno, noop
+
+# retry if use_photos_export fails the first time (which sometimes it does)
+MAX_PHOTOSCRIPT_RETRIES = 3
+
+
+class ExportError(Exception):
+    """ error during export """
+
+    pass
+
+
+class ExportResults:
+    """ holds export results for export2 """
+
+    def __init__(
+        self,
+        exported=None,
+        new=None,
+        updated=None,
+        skipped=None,
+        exif_updated=None,
+        touched=None,
+        converted_to_jpeg=None,
+        sidecar_json_written=None,
+        sidecar_json_skipped=None,
+        sidecar_exiftool_written=None,
+        sidecar_exiftool_skipped=None,
+        sidecar_xmp_written=None,
+        sidecar_xmp_skipped=None,
+        missing=None,
+        error=None,
+        exiftool_warning=None,
+        exiftool_error=None,
+        xattr_written=None,
+        xattr_skipped=None,
+    ):
+        self.exported = exported or []
+        self.new = new or []
+        self.updated = updated or []
+        self.skipped = skipped or []
+        self.exif_updated = exif_updated or []
+        self.touched = touched or []
+        self.converted_to_jpeg = converted_to_jpeg or []
+        self.sidecar_json_written = sidecar_json_written or []
+        self.sidecar_json_skipped = sidecar_json_skipped or []
+        self.sidecar_exiftool_written = sidecar_exiftool_written or []
+        self.sidecar_exiftool_skipped = sidecar_exiftool_skipped or []
+        self.sidecar_xmp_written = sidecar_xmp_written or []
+        self.sidecar_xmp_skipped = sidecar_xmp_skipped or []
+        self.missing = missing or []
+        self.error = error or []
+        self.exiftool_warning = exiftool_warning or []
+        self.exiftool_error = exiftool_error or []
+        self.xattr_written = xattr_written or []
+        self.xattr_skipped = xattr_skipped or []
+
+    def all_files(self):
+        """ return all filenames contained in results """
+        files = (
+            self.exported
+            + self.new
+            + self.updated
+            + self.skipped
+            + self.exif_updated
+            + self.touched
+            + self.converted_to_jpeg
+            + self.sidecar_json_written
+            + self.sidecar_json_skipped
+            + self.sidecar_exiftool_written
+            + self.sidecar_exiftool_skipped
+            + self.sidecar_xmp_written
+            + self.sidecar_xmp_skipped
+            + self.missing
+        )
+        files += [x[0] for x in self.exiftool_warning]
+        files += [x[0] for x in self.exiftool_error]
+        files += [x[0] for x in self.error]
+
+        files = list(set(files))
+        return files
+
+    def __iadd__(self, other):
+        self.exported += other.exported
+        self.new += other.new
+        self.updated += other.updated
+        self.skipped += other.skipped
+        self.exif_updated += other.exif_updated
+        self.touched += other.touched
+        self.converted_to_jpeg += other.converted_to_jpeg
+        self.sidecar_json_written += other.sidecar_json_written
+        self.sidecar_json_skipped += other.sidecar_json_skipped
+        self.sidecar_exiftool_written += other.sidecar_exiftool_written
+        self.sidecar_exiftool_skipped += other.sidecar_exiftool_skipped
+        self.sidecar_xmp_written += other.sidecar_xmp_written
+        self.sidecar_xmp_skipped += other.sidecar_xmp_skipped
+        self.missing += other.missing
+        self.error += other.error
+        self.exiftool_warning += other.exiftool_warning
+        self.exiftool_error += other.exiftool_error
+        return self
+
+    def __str__(self):
+        return (
+            "ExportResults("
+            + f"exported={self.exported}"
+            + f",new={self.new}"
+            + f",updated={self.updated}"
+            + f",skipped={self.skipped}"
+            + f",exif_updated={self.exif_updated}"
+            + f",touched={self.touched}"
+            + f",converted_to_jpeg={self.converted_to_jpeg}"
+            + f",sidecar_json_written={self.sidecar_json_written}"
+            + f",sidecar_json_skipped={self.sidecar_json_skipped}"
+            + f",sidecar_exiftool_written={self.sidecar_exiftool_written}"
+            + f",sidecar_exiftool_skipped={self.sidecar_exiftool_skipped}"
+            + f",sidecar_xmp_written={self.sidecar_xmp_written}"
+            + f",sidecar_xmp_skipped={self.sidecar_xmp_skipped}"
+            + f",missing={self.missing}"
+            + f",error={self.error}"
+            + f",exiftool_warning={self.exiftool_warning}"
+            + f",exiftool_error={self.exiftool_error}"
+            + ")"
+        )
+
+
+# hexdigest is not a class method, don't import this into PhotoInfo
+def hexdigest(strval):
+    """ hexdigest of a string, using blake2b """
+    h = hashlib.blake2b(digest_size=20)
+    h.update(bytes(strval, "utf-8"))
+    return h.hexdigest()
+
+
+# _export_photo_uuid_applescript is not a class method, don't import this into PhotoInfo
+def _export_photo_uuid_applescript(
+    uuid,
+    dest,
+    filestem=None,
+    original=True,
+    edited=False,
+    live_photo=False,
+    timeout=120,
+    burst=False,
+    dry_run=False,
+):
+    """Export photo to dest path using applescript to control Photos
+    If photo is a live photo, exports both the photo and associated .mov file
+
+    Args:
+        uuid: UUID of photo to export
+        dest: destination path to export to
+        filestem: (string) if provided, exported filename will be named stem.ext
+                where ext is extension of the file exported by photos (e.g. .jpeg, .mov, etc)
+                If not provided, file will be named with whatever name Photos uses
+                If filestem.ext exists, it wil be overwritten
+        original: (boolean) if True, export original image; default = True
+        edited: (boolean) if True, export edited photo; default = False
+                If photo not edited and edited=True, will still export the original image
+                caller must verify image has been edited
+        *Note*: must be called with either edited or original but not both,
+                will raise error if called with both edited and original = True
+        live_photo: (boolean) if True, export associated .mov live photo; default = False
+        timeout: timeout value in seconds; export will fail if applescript run time exceeds timeout
+        burst: (boolean) set to True if file is a burst image to avoid Photos export error
+        dry_run: (boolean) set to True to run in "dry run" mode which will download file but not actually copy to destination
+
+    Returns: list of paths to exported file(s) or None if export failed
+
+    Raises: ExportError if error during export
+
+    Note: For Live Photos, if edited=True, will export a jpeg but not the movie, even if photo
+          has not been edited. This is due to how Photos Applescript interface works.
+    """
+
+    dest = pathlib.Path(dest)
+    if not dest.is_dir():
+        raise ValueError(f"dest {dest} must be a directory")
+
+    if not original ^ edited:
+        raise ValueError(f"edited or original must be True but not both")
+
+    tmpdir = tempfile.TemporaryDirectory(prefix="osxphotos_")
+
+    exported_files = []
+    filename = None
+    try:
+        # I've seen intermittent failures with the PhotoScript export so retry if
+        # export doesn't return anything
+        retries = 0
+        while not exported_files and retries < MAX_PHOTOSCRIPT_RETRIES:
+            photo = photoscript.Photo(uuid)
+            filename = photo.filename
+            exported_files = photo.export(
+                tmpdir.name, original=original, timeout=timeout
+            )
+            retries += 1
+    except Exception as e:
+        raise ExportError(e)
+
+    if not exported_files or not filename:
+        # nothing got exported
+        raise ExportError(f"Could not export photo {uuid}")
+
+    # need to find actual filename as sometimes Photos renames JPG to jpeg on export
+    # may be more than one file exported (e.g. if Live Photo, Photos exports both .jpeg and .mov)
+    # TemporaryDirectory will cleanup on return
+    filename_stem = pathlib.Path(filename).stem
+    exported_paths = []
+    for fname in exported_files:
+        path = pathlib.Path(tmpdir.name) / fname
+        if len(exported_files) > 1 and not live_photo and path.suffix.lower() == ".mov":
+            # it's the .mov part of live photo but not requested, so don't export
+            continue
+        if len(exported_files) > 1 and burst and path.stem != filename_stem:
+            # skip any burst photo that's not the one we asked for
+            continue
+        if filestem:
+            # rename the file based on filestem, keeping original extension
+            dest_new = dest / f"{filestem}{path.suffix}"
+        else:
+            # use the name Photos provided
+            dest_new = dest / path.name
+        if not dry_run:
+            FileUtil.copy(str(path), str(dest_new))
+        exported_paths.append(str(dest_new))
+    return exported_paths
+
+
+# _check_export_suffix is not a class method, don't import this into PhotoInfo
+def _check_export_suffix(src, dest, edited):
+    """Helper function for exporting photos to check file extensions of destination path.
+
+    Checks that dst file extension is appropriate for the src.
+    If edited=True, will use src file extension of ".jpeg" if None provided for src.
+
+    Args:
+        src: path to source file or None.
+        dest: path to destination file.
+        edited: set to True if exporting an edited photo.
+
+    Returns:
+        True if src and dest extensions are OK, else False.
+
+    Raises:
+        ValueError if edited is False and src is None
+    """
+
+    # check extension of destination
+    if src is not None:
+        # use suffix from edited file
+        actual_suffix = pathlib.Path(src).suffix
+    elif edited:
+        # use .jpeg as that's probably correct
+        actual_suffix = ".jpeg"
+    else:
+        raise ValueError("src must not be None if edited=False")
+
+    # Photo's often converts .JPG to .jpeg or .tif to .tiff on import
+    dest_ext = dest.suffix.lower()
+    actual_ext = actual_suffix.lower()
+    suffixes = sorted([dest_ext, actual_ext])
+    return (
+        dest_ext == actual_ext
+        or suffixes == [".jpeg", ".jpg"]
+        or suffixes == [".tif", ".tiff"]
+    )
+
+
+# not a class method, don't import into PhotoInfo
+def rename_jpeg_files(files, jpeg_ext, fileutil):
+    """ rename any jpeg files in files so that extension matches jpeg_ext
+
+    Args:
+        files: list of file paths
+        jpeg_ext: extension to use for jpeg files found in files, e.g. "jpg"
+        fileutil: a FileUtil object
+    
+    Returns:
+        list of files with updated names
+
+    Note: If non-jpeg files found, they will be ignore and returned in the return list
+    """
+    jpeg_ext = "." + jpeg_ext
+    jpegs = [".jpeg", ".jpg"]
+    new_files = []
+    for file in files:
+        path = pathlib.Path(file)
+        if path.suffix.lower() in jpegs and path.suffix != jpeg_ext:
+            new_file = path.parent / (path.stem + jpeg_ext)
+            fileutil.rename(file, new_file)
+            new_files.append(new_file)
+        else:
+            new_files.append(file)
+    return new_files
+
+
+def export(
+    self,
+    dest,
+    *filename,
+    edited=False,
+    live_photo=False,
+    raw_photo=False,
+    export_as_hardlink=False,
+    overwrite=False,
+    increment=True,
+    sidecar_json=False,
+    sidecar_exiftool=False,
+    sidecar_xmp=False,
+    use_photos_export=False,
+    timeout=120,
+    exiftool=False,
+    use_albums_as_keywords=False,
+    use_persons_as_keywords=False,
+    keyword_template=None,
+    description_template=None,
+):
+    """export photo
+    dest: must be valid destination path (or exception raised)
+    filename: (optional): name of exported picture; if not provided, will use current filename
+                **NOTE**: if provided, user must ensure file extension (suffix) is correct.
+                For example, if photo is .CR2 file, edited image may be .jpeg.
+                If you provide an extension different than what the actual file is,
+                export will print a warning but will export the photo using the
+                incorrect file extension (unless use_photos_export is true, in which case export will
+                use the extension provided by Photos upon export; in this case, an incorrect extension is
+                silently ignored).
+                e.g. to get the extension of the edited photo,
+                reference PhotoInfo.path_edited
+    edited: (boolean, default=False); if True will export the edited version of the photo
+            (or raise exception if no edited version)
+    live_photo: (boolean, default=False); if True, will also export the associted .mov for live photos
+    raw_photo: (boolean, default=False); if True, will also export the associted RAW photo
+    export_as_hardlink: (boolean, default=False); if True, will hardlink files instead of copying them
+    overwrite: (boolean, default=False); if True will overwrite files if they alreay exist
+    increment: (boolean, default=True); if True, will increment file name until a non-existant name is found
+                if overwrite=False and increment=False, export will fail if destination file already exists
+    sidecar_json: if set will write a json sidecar with data in format readable by exiftool
+                sidecar filename will be dest/filename.json; includes exiftool tag group names (e.g. `exiftool -G -j`)
+    sidecar_exiftool: if set will write a json sidecar with data in format readable by exiftool
+                sidecar filename will be dest/filename.json; does not include exiftool tag group names (e.g. `exiftool -j`)
+    sidecar_xmp: if set will write an XMP sidecar with IPTC data
+                sidecar filename will be dest/filename.xmp           
+    use_photos_export: (boolean, default=False); if True will attempt to export photo via applescript interaction with Photos
+    timeout: (int, default=120) timeout in seconds used with use_photos_export
+    exiftool: (boolean, default = False); if True, will use exiftool to write metadata to export file
+    returns list of full paths to the exported files
+    use_albums_as_keywords: (boolean, default = False); if True, will include album names in keywords
+    when exporting metadata with exiftool or sidecar
+    use_persons_as_keywords: (boolean, default = False); if True, will include person names in keywords
+    when exporting metadata with exiftool or sidecar
+    keyword_template: (list of strings); list of template strings that will be rendered as used as keywords
+    description_template: string; optional template string that will be rendered for use as photo description
+    
+    Returns: list of photos exported
+    """
+
+    # Implementation note: calls export2 to actually do the work
+
+    sidecar = 0
+    if sidecar_json:
+        sidecar |= SIDECAR_JSON
+    if sidecar_exiftool:
+        sidecar |= SIDECAR_EXIFTOOL
+    if sidecar_xmp:
+        sidecar |= SIDECAR_XMP
+
+    results = self.export2(
+        dest,
+        *filename,
+        edited=edited,
+        live_photo=live_photo,
+        raw_photo=raw_photo,
+        export_as_hardlink=export_as_hardlink,
+        overwrite=overwrite,
+        increment=increment,
+        sidecar=sidecar,
+        use_photos_export=use_photos_export,
+        timeout=timeout,
+        exiftool=exiftool,
+        use_albums_as_keywords=use_albums_as_keywords,
+        use_persons_as_keywords=use_persons_as_keywords,
+        keyword_template=keyword_template,
+        description_template=description_template,
+    )
+
+    return results.exported
+
+
+def export2(
+    self,
+    dest,
+    *filename,
+    edited=False,
+    live_photo=False,
+    raw_photo=False,
+    export_as_hardlink=False,
+    overwrite=False,
+    increment=True,
+    sidecar=0,
+    sidecar_drop_ext=False,
+    use_photos_export=False,
+    timeout=120,
+    exiftool=False,
+    use_albums_as_keywords=False,
+    use_persons_as_keywords=False,
+    keyword_template=None,
+    description_template=None,
+    update=False,
+    ignore_signature=False,
+    export_db=None,
+    fileutil=FileUtil,
+    dry_run=False,
+    touch_file=False,
+    convert_to_jpeg=False,
+    jpeg_quality=1.0,
+    ignore_date_modified=False,
+    use_photokit=False,
+    verbose=None,
+    exiftool_flags=None,
+    merge_exif_keywords=False,
+    merge_exif_persons=False,
+    jpeg_ext=None,
+):
+    """export photo, like export but with update and dry_run options
+    dest: must be valid destination path or exception raised
+    filename: (optional): name of exported picture; if not provided, will use current filename
+                **NOTE**: if provided, user must ensure file extension (suffix) is correct.
+                For example, if photo is .CR2 file, edited image may be .jpeg.
+                If you provide an extension different than what the actual file is,
+                will export the photo using the incorrect file extension (unless use_photos_export is true,
+                in which case export will use the extension provided by Photos upon export.
+                e.g. to get the extension of the edited photo,
+                reference PhotoInfo.path_edited
+    edited: (boolean, default=False); if True will export the edited version of the photo
+            (or raise exception if no edited version)
+    live_photo: (boolean, default=False); if True, will also export the associted .mov for live photos
+    raw_photo: (boolean, default=False); if True, will also export the associted RAW photo
+    export_as_hardlink: (boolean, default=False); if True, will hardlink files instead of copying them
+    overwrite: (boolean, default=False); if True will overwrite files if they alreay exist
+    increment: (boolean, default=True); if True, will increment file name until a non-existant name is found
+                if overwrite=False and increment=False, export will fail if destination file already exists
+    sidecar: bit field: set to one or more of SIDECAR_XMP, SIDECAR_JSON, SIDECAR_EXIFTOOL
+             SIDECAR_JSON: if set will write a json sidecar with data in format readable by exiftool
+                sidecar filename will be dest/filename.json; includes exiftool tag group names (e.g. `exiftool -G -j`)
+             SIDECAR_EXIFTOOL: if set will write a json sidecar with data in format readable by exiftool
+                sidecar filename will be dest/filename.json; does not include exiftool tag group names (e.g. `exiftool -j`)
+             SIDECAR_XMP: if set will write an XMP sidecar with IPTC data
+                sidecar filename will be dest/filename.xmp
+    sidecar_drop_ext: (boolean, default=False); if True, drops the photo's extension from sidecar filename (e.g. 'IMG_1234.json' instead of 'IMG_1234.JPG.json')
+    use_photos_export: (boolean, default=False); if True will attempt to export photo via applescript interaction with Photos
+    timeout: (int, default=120) timeout in seconds used with use_photos_export
+    exiftool: (boolean, default = False); if True, will use exiftool to write metadata to export file
+    use_albums_as_keywords: (boolean, default = False); if True, will include album names in keywords
+    when exporting metadata with exiftool or sidecar
+    use_persons_as_keywords: (boolean, default = False); if True, will include person names in keywords
+    when exporting metadata with exiftool or sidecar
+    keyword_template: (list of strings); list of template strings that will be rendered as used as keywords
+    description_template: string; optional template string that will be rendered for use as photo description
+    update: (boolean, default=False); if True export will run in update mode, that is, it will
+            not export the photo if the current version already exists in the destination
+    ignore_signature: (bool, default=False), ignore file signature when used with update (look only at filename)
+    export_db: (ExportDB_ABC); instance of a class that conforms to ExportDB_ABC with methods
+            for getting/setting data related to exported files to compare update state
+    fileutil: (FileUtilABC); class that conforms to FileUtilABC with various file utilities
+    dry_run: (boolean, default=False); set to True to run in "dry run" mode
+    touch_file: (boolean, default=False); if True, sets file's modification time upon photo date
+    convert_to_jpeg: boolean; if True, converts non-jpeg images to jpeg
+    jpeg_quality: float in range 0.0 <= jpeg_quality <= 1.0.  A value of 1.0 specifies use best quality, a value of 0.0 specifies use maximum compression.
+    ignore_date_modified: for use with sidecar and exiftool; if True, sets EXIF:ModifyDate to EXIF:DateTimeOriginal even if date_modified is set
+    verbose: optional callable function to use for printing verbose text during processing; if None (default), does not print output.
+    exiftool_flags: optional list of flags to pass to exiftool when using exiftool option, e.g ["-m", "-F"]
+    merge_exif_keywords: boolean; if True, merged keywords found in file's exif data (requires exiftool)
+    merge_exif_persons: boolean; if True, merged persons found in file's exif data (requires exiftool)
+    jpeg_ext: if set, will use this value for extension on jpegs converted to jpeg with convert_to_jpeg; if not set, uses jpeg; do not include the leading "."
+
+    Returns: ExportResults class 
+        ExportResults has attributes: 
+        "exported",
+        "new",
+        "updated",
+        "skipped",
+        "exif_updated",
+        "touched",
+        "converted_to_jpeg",
+        "sidecar_json_written",
+        "sidecar_json_skipped",
+        "sidecar_exiftool_written",
+        "sidecar_exiftool_skipped",
+        "sidecar_xmp_written",
+        "sidecar_xmp_skipped",
+        "missing",
+        "error",
+        "error_str",
+        "exiftool_warning",
+        "exiftool_error",
+
+ 
+    Note: to use dry run mode, you must set dry_run=True and also pass in memory version of export_db,
+          and no-op fileutil (e.g. ExportDBInMemory and FileUtilNoOp)
+    """
+
+    # NOTE: This function is very complex and does a lot of things.
+    # Don't modify this code if you don't fully understand everything it does.
+    # TODO: This is a good candidate for refactoring.
+
+    # when called from export(), won't get an export_db, so use no-op version
+    if export_db is None:
+        export_db = ExportDBNoOp()
+
+    if verbose is None:
+        verbose = noop
+    elif not callable(verbose):
+        raise TypeError("verbose must be callable")
+    self._verbose = verbose
+
+    # suffix to add to edited files
+    # e.g. name will be filename_edited.jpg
+    edited_identifier = "_edited"
+
+    # check edited and raise exception trying to export edited version of
+    # photo that hasn't been edited
+    if edited and not self.hasadjustments:
+        raise ValueError(
+            "Photo does not have adjustments, cannot export edited version"
+        )
+
+    # check arguments and get destination path and filename (if provided)
+    if filename and len(filename) > 2:
+        raise TypeError(
+            "Too many positional arguments.  Should be at most two: destination, filename."
+        )
+
+    # verify destination is a valid path
+    if dest is None:
+        raise ValueError("Destination must not be None")
+    elif not dry_run and not os.path.isdir(dest):
+        raise FileNotFoundError("Invalid path passed to export")
+
+    if filename and len(filename) == 1:
+        # if filename passed, use it
+        fname = filename[0]
+    else:
+        # no filename provided so use the default
+        # if edited file requested, use filename but add _edited
+        # need to use file extension from edited file as Photos saves a jpeg once edited
+        if edited and not use_photos_export:
+            # verify we have a valid path_edited and use that to get filename
+            if not self.path_edited:
+                raise FileNotFoundError(
+                    "edited=True but path_edited is none; hasadjustments: "
+                    f" {self.hasadjustments}"
+                )
+            edited_name = pathlib.Path(self.path_edited).name
+            edited_suffix = pathlib.Path(edited_name).suffix
+            fname = pathlib.Path(self.filename).stem + edited_identifier + edited_suffix
+        else:
+            fname = self.filename
+
+    uti = self.uti if edited else self.uti_original
+    if convert_to_jpeg and self.isphoto and uti != "public.jpeg":
+        # not a jpeg but will convert to jpeg upon export so fix file extension
+        fname_new = pathlib.Path(fname)
+        ext = "." + jpeg_ext if jpeg_ext else ".jpeg"
+        fname = str(fname_new.parent / f"{fname_new.stem}{ext}")
+    else:
+        # nothing to convert
+        convert_to_jpeg = False
+
+    # check destination path
+    dest = pathlib.Path(dest)
+    fname = pathlib.Path(fname)
+    dest = dest / fname
+
+    # check to see if file exists and if so, add (1), (2), etc until we find one that works
+    # Photos checks the stem and adds (1), (2), etc which avoids collision with sidecars
+    # e.g. exporting sidecar for file1.png and file1.jpeg
+    # if file1.png exists and exporting file1.jpeg,
+    # dest will be file1 (1).jpeg even though file1.jpeg doesn't exist to prevent sidecar collision
+    if not update and increment and not overwrite:
+        count = 1
+        dest_files = findfiles(f"{dest.stem}*", str(dest.parent))
+        dest_files = [pathlib.Path(f).stem.lower() for f in dest_files]
+        dest_new = dest.stem
+        while dest_new.lower() in dest_files:
+            dest_new = f"{dest.stem} ({count})"
+            count += 1
+        dest = dest.parent / f"{dest_new}{dest.suffix}"
+
+    # if overwrite==False and #increment==False, export should fail if file exists
+    if dest.exists() and not update and not overwrite and not increment:
+        raise FileExistsError(
+            f"destination exists ({dest}); overwrite={overwrite}, increment={increment}"
+        )
+
+    all_results = ExportResults()
+    if not use_photos_export:
+        # find the source file on disk and export
+        # get path to source file and verify it's not None and is valid file
+        # TODO: how to handle ismissing or not hasadjustments and edited=True cases?
+        if edited:
+            if self.path_edited is not None:
+                src = self.path_edited
+            else:
+                raise FileNotFoundError(
+                    f"Cannot export edited photo if path_edited is None"
+                )
+        else:
+            if self.path is not None:
+                src = self.path
+            else:
+                raise FileNotFoundError("Cannot export photo if path is None")
+
+        if not os.path.isfile(src):
+            raise FileNotFoundError(f"{src} does not appear to exist")
+
+        # found source now try to find right destination
+        if update and dest.exists():
+            # destination exists, check to see if destination is the right UUID
+            dest_uuid = export_db.get_uuid_for_file(dest)
+            if dest_uuid is None and fileutil.cmp(src, dest):
+                # might be exporting into a pre-ExportDB folder or the DB got deleted
+                dest_uuid = self.uuid
+                export_db.set_data(
+                    filename=dest,
+                    uuid=self.uuid,
+                    orig_stat=fileutil.file_sig(dest),
+                    exif_stat=(None, None, None),
+                    converted_stat=(None, None, None),
+                    edited_stat=(None, None, None),
+                    info_json=self.json(),
+                    exif_json=None,
+                )
+            if dest_uuid != self.uuid:
+                # not the right file, find the right one
+                count = 1
+                glob_str = str(dest.parent / f"{dest.stem} (*{dest.suffix}")
+                dest_files = glob.glob(glob_str)
+                found_match = False
+                for file_ in dest_files:
+                    dest_uuid = export_db.get_uuid_for_file(file_)
+                    if dest_uuid == self.uuid:
+                        dest = pathlib.Path(file_)
+                        found_match = True
+                        break
+                    elif dest_uuid is None and fileutil.cmp(src, file_):
+                        # files match, update the UUID
+                        dest = pathlib.Path(file_)
+                        found_match = True
+                        export_db.set_data(
+                            filename=dest,
+                            uuid=self.uuid,
+                            orig_stat=fileutil.file_sig(dest),
+                            exif_stat=(None, None, None),
+                            converted_stat=(None, None, None),
+                            edited_stat=(None, None, None),
+                            info_json=self.json(),
+                            exif_json=None,
+                        )
+                        break
+
+                if not found_match:
+                    # increment the destination file
+                    count = 1
+                    glob_str = str(dest.parent / f"{dest.stem}*")
+                    dest_files = glob.glob(glob_str)
+                    dest_files = [pathlib.Path(f).stem for f in dest_files]
+                    dest_new = dest.stem
+                    while dest_new in dest_files:
+                        dest_new = f"{dest.stem} ({count})"
+                        count += 1
+                    dest = dest.parent / f"{dest_new}{dest.suffix}"
+
+        # export the dest file
+        results = self._export_photo(
+            src,
+            dest,
+            update,
+            export_db,
+            overwrite,
+            export_as_hardlink,
+            exiftool,
+            touch_file,
+            convert_to_jpeg,
+            fileutil=fileutil,
+            edited=edited,
+            jpeg_quality=jpeg_quality,
+            ignore_signature=ignore_signature,
+        )
+        all_results += results
+
+        # copy live photo associated .mov if requested
+        if live_photo and self.live_photo:
+            live_name = dest.parent / f"{dest.stem}.mov"
+            src_live = self.path_live_photo
+
+            if src_live is not None:
+                results = self._export_photo(
+                    src_live,
+                    live_name,
+                    update,
+                    export_db,
+                    overwrite,
+                    export_as_hardlink,
+                    exiftool,
+                    touch_file,
+                    False,
+                    fileutil=fileutil,
+                    ignore_signature=ignore_signature,
+                )
+                all_results += results
+
+        # copy associated RAW image if requested
+        if raw_photo and self.has_raw:
+            raw_path = pathlib.Path(self.path_raw)
+            raw_ext = raw_path.suffix
+            raw_name = dest.parent / f"{dest.stem}{raw_ext}"
+            if raw_path is not None:
+                results = self._export_photo(
+                    raw_path,
+                    raw_name,
+                    update,
+                    export_db,
+                    overwrite,
+                    export_as_hardlink,
+                    exiftool,
+                    touch_file,
+                    convert_to_jpeg,
+                    fileutil=fileutil,
+                    jpeg_quality=jpeg_quality,
+                    ignore_signature=ignore_signature,
+                )
+                all_results += results
+    else:
+        # TODO: move this big if/else block to separate functions
+        # e.g. _export_with_photos_export or such
+        # use_photo_export
+        # export live_photo .mov file?
+        live_photo = True if live_photo and self.live_photo else False
+        if edited or self.shared:
+            # exported edited version and not original
+            # shared photos (in shared albums) show up as not having adjustments (not edited)
+            # but Photos is unable to export the "original" as only a jpeg copy is shared in iCloud
+            # so tell Photos to export the current version in this case
+            if filename:
+                # use filename stem provided
+                filestem = dest.stem
+            else:
+                # didn't get passed a filename, add _edited
+                filestem = f"{dest.stem}{edited_identifier}"
+                uti = self.uti_edited if edited and self.uti_edited else self.uti
+                ext = get_preferred_uti_extension(uti)
+                dest = dest.parent / f"{filestem}{ext}"
+
+            if use_photokit:
+                photolib = PhotoLibrary()
+                photo = None
+                try:
+                    photo = photolib.fetch_uuid(self.uuid)
+                except PhotoKitFetchFailed as e:
+                    # if failed to find UUID, might be a burst photo
+                    if self.burst and self._info["burstUUID"]:
+                        bursts = photolib.fetch_burst_uuid(
+                            self._info["burstUUID"], all=True
+                        )
+                        # PhotoKit UUIDs may contain "/L0/001" so only look at beginning
+                        photo = [p for p in bursts if p.uuid.startswith(self.uuid)]
+                        photo = photo[0] if photo else None
+                    if not photo:
+                        all_results.error.append(
+                            (
+                                str(dest),
+                                f"PhotoKitFetchFailed exception exporting photo {self.uuid}: {e} ({lineno(__file__)})",
+                            )
+                        )
+                if photo:
+                    if not dry_run:
+                        try:
+                            exported = photo.export(
+                                dest.parent, dest.name, version=PHOTOS_VERSION_CURRENT
+                            )
+                            all_results.exported.extend(exported)
+                        except Exception as e:
+                            all_results.error.append(
+                                (str(dest), f"{e} ({lineno(__file__)})")
+                            )
+                    else:
+                        # dry_run, don't actually export
+                        all_results.exported.append(str(dest))
+            else:
+                try:
+                    exported = _export_photo_uuid_applescript(
+                        self.uuid,
+                        dest.parent,
+                        filestem=filestem,
+                        original=False,
+                        edited=True,
+                        live_photo=live_photo,
+                        timeout=timeout,
+                        burst=self.burst,
+                        dry_run=dry_run,
+                    )
+                    all_results.exported.extend(exported)
+                except ExportError as e:
+                    all_results.error.append((str(dest), f"{e} ({lineno(__file__)})"))
+        else:
+            # export original version and not edited
+            filestem = dest.stem
+            if use_photokit:
+                photolib = PhotoLibrary()
+                photo = None
+                try:
+                    photo = photolib.fetch_uuid(self.uuid)
+                except PhotoKitFetchFailed:
+                    # if failed to find UUID, might be a burst photo
+                    if self.burst and self._info["burstUUID"]:
+                        bursts = photolib.fetch_burst_uuid(
+                            self._info["burstUUID"], all=True
+                        )
+                        # PhotoKit UUIDs may contain "/L0/001" so only look at beginning
+                        photo = [p for p in bursts if p.uuid.startswith(self.uuid)]
+                        photo = photo[0] if photo else None
+                if photo:
+                    if not dry_run:
+                        try:
+                            exported = photo.export(
+                                dest.parent, dest.name, version=PHOTOS_VERSION_ORIGINAL
+                            )
+                            all_results.exported.extend(exported)
+                        except Exception as e:
+                            all_results.error.append(
+                                (str(dest), f"{e} ({lineno(__file__)})")
+                            )
+                    else:
+                        # dry_run, don't actually export
+                        all_results.exported.append(str(dest))
+            else:
+                try:
+                    exported = _export_photo_uuid_applescript(
+                        self.uuid,
+                        dest.parent,
+                        filestem=filestem,
+                        original=True,
+                        edited=False,
+                        live_photo=live_photo,
+                        timeout=timeout,
+                        burst=self.burst,
+                        dry_run=dry_run,
+                    )
+                    all_results.exported.extend(exported)
+                except ExportError as e:
+                    all_results.error.append((str(dest), f"{e} ({lineno(__file__)})"))
+        if all_results.exported:
+            if jpeg_ext:
+                # use_photos_export (both PhotoKit and AppleScript) don't use the
+                # file extension provided (instead they use extension for UTI)
+                # so if jpeg_ext is set, rename any non-conforming jpegs
+                all_results.exported = rename_jpeg_files(
+                    all_results.exported, jpeg_ext, fileutil
+                )
+            if touch_file:
+                for exported_file in all_results.exported:
+                    all_results.touched.append(exported_file)
+                    ts = int(self.date.timestamp())
+                    fileutil.utime(exported_file, (ts, ts))
+            if update:
+                all_results.new.extend(all_results.exported)
+
+    # export metadata
+    sidecars = []
+    sidecar_json_files_skipped = []
+    sidecar_json_files_written = []
+    sidecar_exiftool_files_skipped = []
+    sidecar_exiftool_files_written = []
+    sidecar_xmp_files_skipped = []
+    sidecar_xmp_files_written = []
+
+    dest_suffix = "" if sidecar_drop_ext else dest.suffix
+    if sidecar & SIDECAR_JSON:
+        sidecar_filename = dest.parent / pathlib.Path(f"{dest.stem}{dest_suffix}.json")
+        sidecar_str = self._exiftool_json_sidecar(
+            use_albums_as_keywords=use_albums_as_keywords,
+            use_persons_as_keywords=use_persons_as_keywords,
+            keyword_template=keyword_template,
+            description_template=description_template,
+            ignore_date_modified=ignore_date_modified,
+            merge_exif_keywords=merge_exif_keywords,
+            merge_exif_persons=merge_exif_persons,
+            filename=dest.name,
+        )
+        sidecars.append(
+            (
+                sidecar_filename,
+                sidecar_str,
+                sidecar_json_files_written,
+                sidecar_json_files_skipped,
+                "JSON",
+            )
+        )
+
+    if sidecar & SIDECAR_EXIFTOOL:
+        sidecar_filename = dest.parent / pathlib.Path(f"{dest.stem}{dest_suffix}.json")
+        sidecar_str = self._exiftool_json_sidecar(
+            use_albums_as_keywords=use_albums_as_keywords,
+            use_persons_as_keywords=use_persons_as_keywords,
+            keyword_template=keyword_template,
+            description_template=description_template,
+            ignore_date_modified=ignore_date_modified,
+            tag_groups=False,
+            merge_exif_keywords=merge_exif_keywords,
+            merge_exif_persons=merge_exif_persons,
+            filename=dest.name,
+        )
+        sidecars.append(
+            (
+                sidecar_filename,
+                sidecar_str,
+                sidecar_exiftool_files_written,
+                sidecar_exiftool_files_skipped,
+                "exiftool",
+            )
+        )
+
+    if sidecar & SIDECAR_XMP:
+        sidecar_filename = dest.parent / pathlib.Path(f"{dest.stem}{dest_suffix}.xmp")
+        sidecar_str = self._xmp_sidecar(
+            use_albums_as_keywords=use_albums_as_keywords,
+            use_persons_as_keywords=use_persons_as_keywords,
+            keyword_template=keyword_template,
+            description_template=description_template,
+            extension=dest.suffix[1:] if dest.suffix else None,
+        )
+        sidecars.append(
+            (
+                sidecar_filename,
+                sidecar_str,
+                sidecar_xmp_files_written,
+                sidecar_xmp_files_skipped,
+                "XMP",
+            )
+        )
+
+    for data in sidecars:
+        sidecar_filename = data[0]
+        sidecar_str = data[1]
+        files_written = data[2]
+        files_skipped = data[3]
+        sidecar_type = data[4]
+
+        sidecar_digest = hexdigest(sidecar_str)
+        old_sidecar_digest, sidecar_sig = export_db.get_sidecar_for_file(
+            sidecar_filename
+        )
+        write_sidecar = (
+            not update
+            or (update and not sidecar_filename.exists())
+            or (
+                update
+                and (sidecar_digest != old_sidecar_digest)
+                or not fileutil.cmp_file_sig(sidecar_filename, sidecar_sig)
+            )
+        )
+        if write_sidecar:
+            verbose(f"Writing {sidecar_type} sidecar {sidecar_filename}")
+            files_written.append(str(sidecar_filename))
+            if not dry_run:
+                self._write_sidecar(sidecar_filename, sidecar_str)
+                export_db.set_sidecar_for_file(
+                    sidecar_filename,
+                    sidecar_digest,
+                    fileutil.file_sig(sidecar_filename),
+                )
+        else:
+            verbose(f"Skipped up to date {sidecar_type} sidecar {sidecar_filename}")
+            files_skipped.append(str(sidecar_filename))
+
+    # if exiftool, write the metadata
+    if update:
+        exif_files = all_results.new + all_results.updated + all_results.skipped
+    else:
+        exif_files = all_results.exported
+
+    # TODO: remove duplicative code from below
+    if exiftool and update and exif_files:
+        for exported_file in exif_files:
+            files_are_different = False
+            old_data = export_db.get_exifdata_for_file(exported_file)
+            if old_data is not None:
+                old_data = json.loads(old_data)[0]
+                current_data = json.loads(
+                    self._exiftool_json_sidecar(
+                        use_albums_as_keywords=use_albums_as_keywords,
+                        use_persons_as_keywords=use_persons_as_keywords,
+                        keyword_template=keyword_template,
+                        description_template=description_template,
+                        ignore_date_modified=ignore_date_modified,
+                        merge_exif_keywords=merge_exif_keywords,
+                        merge_exif_persons=merge_exif_persons,
+                    )
+                )[0]
+                if old_data != current_data:
+                    files_are_different = True
+
+            if old_data is None or files_are_different:
+                # didn't have old data, assume we need to write it
+                # or files were different
+                verbose(f"Writing metadata with exiftool for {exported_file}")
+                if not dry_run:
+                    warning_, error_ = self._write_exif_data(
+                        exported_file,
+                        use_albums_as_keywords=use_albums_as_keywords,
+                        use_persons_as_keywords=use_persons_as_keywords,
+                        keyword_template=keyword_template,
+                        description_template=description_template,
+                        ignore_date_modified=ignore_date_modified,
+                        flags=exiftool_flags,
+                        merge_exif_keywords=merge_exif_keywords,
+                        merge_exif_persons=merge_exif_persons,
+                    )
+                    if warning_:
+                        all_results.exiftool_warning.append((exported_file, warning_))
+                    if error_:
+                        all_results.exiftool_error.append((exported_file, error_))
+                        all_results.error.append((exported_file, error_))
+
+                export_db.set_exifdata_for_file(
+                    exported_file,
+                    self._exiftool_json_sidecar(
+                        use_albums_as_keywords=use_albums_as_keywords,
+                        use_persons_as_keywords=use_persons_as_keywords,
+                        keyword_template=keyword_template,
+                        description_template=description_template,
+                        ignore_date_modified=ignore_date_modified,
+                        merge_exif_keywords=merge_exif_keywords,
+                        merge_exif_persons=merge_exif_persons,
+                    ),
+                )
+                export_db.set_stat_exif_for_file(
+                    exported_file, fileutil.file_sig(exported_file)
+                )
+                all_results.exif_updated.append(exported_file)
+            else:
+                verbose(f"Skipped up to date exiftool metadata for {exported_file}")
+    elif exiftool and exif_files:
+        for exported_file in exif_files:
+            verbose(f"Writing metadata with exiftool for {exported_file}")
+            if not dry_run:
+                warning_, error_ = self._write_exif_data(
+                    exported_file,
+                    use_albums_as_keywords=use_albums_as_keywords,
+                    use_persons_as_keywords=use_persons_as_keywords,
+                    keyword_template=keyword_template,
+                    description_template=description_template,
+                    ignore_date_modified=ignore_date_modified,
+                    flags=exiftool_flags,
+                    merge_exif_keywords=merge_exif_keywords,
+                    merge_exif_persons=merge_exif_persons,
+                )
+                if warning_:
+                    all_results.exiftool_warning.append((exported_file, warning_))
+                if error_:
+                    all_results.exiftool_error.append((exported_file, error_))
+                    all_results.error.append((exported_file, error_))
+
+            export_db.set_exifdata_for_file(
+                exported_file,
+                self._exiftool_json_sidecar(
+                    use_albums_as_keywords=use_albums_as_keywords,
+                    use_persons_as_keywords=use_persons_as_keywords,
+                    keyword_template=keyword_template,
+                    description_template=description_template,
+                    ignore_date_modified=ignore_date_modified,
+                    merge_exif_keywords=merge_exif_keywords,
+                    merge_exif_persons=merge_exif_persons,
+                ),
+            )
+            export_db.set_stat_exif_for_file(
+                exported_file, fileutil.file_sig(exported_file)
+            )
+            all_results.exif_updated.append(exported_file)
+
+    if touch_file:
+        for exif_file in all_results.exif_updated:
+            verbose(f"Updating file modification time for {exif_file}")
+            all_results.touched.append(exif_file)
+            ts = int(self.date.timestamp())
+            fileutil.utime(exif_file, (ts, ts))
+
+    all_results.touched = list(set(all_results.touched))
+
+    all_results.sidecar_json_written = sidecar_json_files_written
+    all_results.sidecar_json_skipped = sidecar_json_files_skipped
+    all_results.sidecar_exiftool_written = sidecar_exiftool_files_written
+    all_results.sidecar_exiftool_skipped = sidecar_exiftool_files_skipped
+    all_results.sidecar_xmp_written = sidecar_xmp_files_written
+    all_results.sidecar_xmp_skipped = sidecar_xmp_files_skipped
+
+    return all_results
+
+
+def _export_photo(
+    self,
+    src,
+    dest,
+    update,
+    export_db,
+    overwrite,
+    export_as_hardlink,
+    exiftool,
+    touch_file,
+    convert_to_jpeg,
+    fileutil=FileUtil,
+    edited=False,
+    jpeg_quality=1.0,
+    ignore_signature=None,
+):
+    """Helper function for export()
+        Does the actual copy or hardlink taking the appropriate
+        action depending on update, overwrite, export_as_hardlink
+        Assumes destination is the right destination (e.g. UUID matches)
+        sets UUID and JSON info foo exported file using set_uuid_for_file, set_inf_for_uuido
+
+    Args:
+        src: src path (string)
+        dest: dest path (pathlib.Path)
+        update: bool
+        export_db: instance of ExportDB that conforms to ExportDB_ABC interface
+        overwrite: bool
+        export_as_hardlink: bool
+        exiftool: bool
+        touch_file: bool
+        convert_to_jpeg: bool; if True, convert file to jpeg on export
+        fileutil: FileUtil class that conforms to fileutil.FileUtilABC
+        edited: bool; set to True if exporting edited version of photo
+        jpeg_quality: float in range 0.0 <= jpeg_quality <= 1.0.  A value of 1.0 specifies use best quality, a value of 0.0 specifies use maximum compression.
+        ignore_signature: bool, ignore file signature when used with update (look only at filename)
+
+    Returns:
+        ExportResults
+
+    Raises:
+        ValueError if export_as_hardlink and convert_to_jpeg both True
+    """
+
+    if export_as_hardlink and convert_to_jpeg:
+        raise ValueError("export_as_hardlink and convert_to_jpeg cannot both be True")
+
+    exported_files = []
+    update_updated_files = []
+    update_new_files = []
+    update_skipped_files = []
+    touched_files = []
+    converted_to_jpeg_files = []
+
+    dest_str = str(dest)
+    dest_exists = dest.exists()
+
+    if update:  # updating
+        cmp_touch, cmp_orig = False, False
+        if dest_exists:
+            # update, destination exists, but we might not need to replace it...
+            if ignore_signature:
+                cmp_orig = True
+                cmp_touch = fileutil.cmp(src, dest, mtime1=int(self.date.timestamp()))
+            elif exiftool:
+                sig_exif = export_db.get_stat_exif_for_file(dest_str)
+                cmp_orig = fileutil.cmp_file_sig(dest_str, sig_exif)
+                sig_exif = (sig_exif[0], sig_exif[1], int(self.date.timestamp()))
+                cmp_touch = fileutil.cmp_file_sig(dest_str, sig_exif)
+            elif convert_to_jpeg:
+                sig_converted = export_db.get_stat_converted_for_file(dest_str)
+                cmp_orig = fileutil.cmp_file_sig(dest_str, sig_converted)
+                sig_converted = (
+                    sig_converted[0],
+                    sig_converted[1],
+                    int(self.date.timestamp()),
+                )
+                cmp_touch = fileutil.cmp_file_sig(dest_str, sig_converted)
+            else:
+                cmp_orig = fileutil.cmp(src, dest)
+                cmp_touch = fileutil.cmp(src, dest, mtime1=int(self.date.timestamp()))
+
+            sig_cmp = cmp_touch if touch_file else cmp_orig
+
+            if edited:
+                # requested edited version of photo
+                # need to see if edited version in Photos library has changed
+                # (e.g. it's been edited again)
+                sig_edited = export_db.get_stat_edited_for_file(dest_str)
+                cmp_edited = (
+                    fileutil.cmp_file_sig(src, sig_edited)
+                    if sig_edited != (None, None, None)
+                    else False
+                )
+                sig_cmp = sig_cmp and cmp_edited
+
+            if (export_as_hardlink and dest.samefile(src)) or (
+                not export_as_hardlink and not dest.samefile(src) and sig_cmp
+            ):
+                # destination exists and signatures match, skip it
+                update_skipped_files.append(dest_str)
+            else:
+                # destination exists but signature is different
+                if touch_file and cmp_orig and not cmp_touch:
+                    # destination exists, signature matches original but does not match expected touch time
+                    # skip exporting but update touch time
+                    update_skipped_files.append(dest_str)
+                    touched_files.append(dest_str)
+                elif not touch_file and cmp_touch and not cmp_orig:
+                    # destination exists, signature matches expected touch but not original
+                    # user likely exported with touch_file and is now exporting without touch_file
+                    # don't update the file because it's same but leave touch time
+                    update_skipped_files.append(dest_str)
+                else:
+                    # destination exists but is different
+                    update_updated_files.append(dest_str)
+                    if touch_file:
+                        touched_files.append(dest_str)
+
+        else:
+            # update, destination doesn't exist (new file)
+            update_new_files.append(dest_str)
+            if touch_file:
+                touched_files.append(dest_str)
+    else:
+        # not update, export the file
+        exported_files.append(dest_str)
+        if touch_file:
+            sig = fileutil.file_sig(src)
+            sig = (sig[0], sig[1], int(self.date.timestamp()))
+            if not fileutil.cmp_file_sig(src, sig):
+                touched_files.append(dest_str)
+    if not update_skipped_files:
+        converted_stat = (None, None, None)
+        edited_stat = fileutil.file_sig(src) if edited else (None, None, None)
+        if dest_exists and (update or overwrite):
+            # need to remove the destination first
+            fileutil.unlink(dest)
+        if export_as_hardlink:
+            fileutil.hardlink(src, dest)
+        elif convert_to_jpeg:
+            # use convert_to_jpeg to export the file
+            fileutil.convert_to_jpeg(src, dest_str, compression_quality=jpeg_quality)
+            converted_stat = fileutil.file_sig(dest_str)
+            converted_to_jpeg_files.append(dest_str)
+        else:
+            fileutil.copy(src, dest_str)
+
+        export_db.set_data(
+            filename=dest_str,
+            uuid=self.uuid,
+            orig_stat=fileutil.file_sig(dest_str),
+            exif_stat=(None, None, None),
+            converted_stat=converted_stat,
+            edited_stat=edited_stat,
+            info_json=self.json(),
+            exif_json=None,
+        )
+
+    if touched_files:
+        ts = int(self.date.timestamp())
+        fileutil.utime(dest, (ts, ts))
+
+    return ExportResults(
+        exported=exported_files + update_new_files + update_updated_files,
+        new=update_new_files,
+        updated=update_updated_files,
+        skipped=update_skipped_files,
+        exif_updated=[],
+        touched=touched_files,
+        converted_to_jpeg=converted_to_jpeg_files,
+        sidecar_json_written=[],
+        sidecar_json_skipped=[],
+        sidecar_exiftool_written=[],
+        sidecar_exiftool_skipped=[],
+        sidecar_xmp_written=[],
+        sidecar_xmp_skipped=[],
+        missing=[],
+        error=[],
+    )
+
+
+def _write_exif_data(
+    self,
+    filepath,
+    use_albums_as_keywords=False,
+    use_persons_as_keywords=False,
+    keyword_template=None,
+    description_template=None,
+    ignore_date_modified=False,
+    flags=None,
+    merge_exif_keywords=False,
+    merge_exif_persons=False,
+):
+    """write exif data to image file at filepath
+
+    Args:
+        filepath: full path to the image file
+        use_albums_as_keywords: treat album names as keywords
+        use_persons_as_keywords: treat person names as keywords
+        keyword_template: (list of strings); list of template strings to render as keywords
+        ignore_date_modified: if True, sets EXIF:ModifyDate to EXIF:DateTimeOriginal even if date_modified is set
+        flags: optional list of exiftool flags to prepend to exiftool command when writing metadata (e.g. -m or -F)
+
+    Returns:
+        (warning, error) of warning and error strings if exiftool produces warnings or errors
+    """
+    if not os.path.exists(filepath):
+        raise FileNotFoundError(f"Could not find file {filepath}")
+    exif_info = self._exiftool_dict(
+        use_albums_as_keywords=use_albums_as_keywords,
+        use_persons_as_keywords=use_persons_as_keywords,
+        keyword_template=keyword_template,
+        description_template=description_template,
+        ignore_date_modified=ignore_date_modified,
+        merge_exif_keywords=merge_exif_keywords,
+        merge_exif_persons=merge_exif_persons,
+    )
+
+    with ExifTool(filepath, flags=flags, exiftool=self._db._exiftool_path) as exiftool:
+        for exiftag, val in exif_info.items():
+            if type(val) == list:
+                for v in val:
+                    exiftool.setvalue(exiftag, v)
+            else:
+                exiftool.setvalue(exiftag, val)
+    return exiftool.warning, exiftool.error
+
+
+def _exiftool_dict(
+    self,
+    use_albums_as_keywords=False,
+    use_persons_as_keywords=False,
+    keyword_template=None,
+    description_template=None,
+    ignore_date_modified=False,
+    merge_exif_keywords=False,
+    merge_exif_persons=False,
+    filename=None,
+):
+    """Return dict of EXIF details for building exiftool JSON sidecar or sending commands to ExifTool.
+        Does not include all the EXIF fields as those are likely already in the image.
+
+    Args:
+        filename: name of source image file (without path); if not None, exiftool JSON signature will be included; if None, signature will not be included
+        use_albums_as_keywords: treat album names as keywords
+        use_persons_as_keywords: treat person names as keywords
+        keyword_template: (list of strings); list of template strings to render as keywords
+        description_template: (list of strings); list of template strings to render for the description
+        ignore_date_modified: if True, sets EXIF:ModifyDate to EXIF:DateTimeOriginal even if date_modified is set
+        merge_exif_keywords: merge keywords in the file's exif metadata (requires exiftool)
+        merge_exif_persons: merge persons in the file's exif metadata (requires exiftool)
+
+    Returns: dict with exiftool tags / values
+
+    Exports the following:
+        EXIF:ImageDescription (may include template)
+        XMP:Description (may include template)
+        XMP:Title
+        XMP:TagsList (may include album name, person name, or template)
+        IPTC:Keywords (may include album name, person name, or template)
+        XMP:Subject (set to keywords + persons)
+        XMP:PersonInImage
+        EXIF:GPSLatitudeRef, EXIF:GPSLongitudeRef
+        EXIF:GPSLatitude, EXIF:GPSLongitude
+        EXIF:GPSPosition
+        EXIF:DateTimeOriginal
+        EXIF:OffsetTimeOriginal
+        EXIF:ModifyDate
+        IPTC:DateCreated
+        IPTC:TimeCreated
+        QuickTime:CreationDate
+        QuickTime:CreateDate (UTC)
+        QuickTime:ModifyDate (UTC)
+        QuickTime:GPSCoordinates
+        UserData:GPSCoordinates
+    """
+
+    exif = (
+        {
+            "SourceFile": filename,
+            "ExifTool:ExifToolVersion": "12.00",
+            "File:FileName": filename,
+        }
+        if filename is not None
+        else {}
+    )
+
+    if description_template is not None:
+        rendered = self.render_template(
+            description_template, expand_inplace=True, inplace_sep=", "
+        )[0]
+        description = " ".join(rendered) if rendered else ""
+        exif["EXIF:ImageDescription"] = description
+        exif["XMP:Description"] = description
+    elif self.description:
+        exif["EXIF:ImageDescription"] = self.description
+        exif["XMP:Description"] = self.description
+
+    if self.title:
+        exif["XMP:Title"] = self.title
+
+    keyword_list = []
+    if merge_exif_keywords:
+        keyword_list.extend(self._get_exif_keywords())
+
+    if self.keywords:
+        keyword_list.extend(self.keywords)
+
+    person_list = []
+    if merge_exif_persons:
+        person_list.extend(self._get_exif_persons())
+
+    if self.persons:
+        # filter out _UNKNOWN_PERSON
+        person_list.extend([p for p in self.persons if p != _UNKNOWN_PERSON])
+
+    if use_persons_as_keywords and person_list:
+        keyword_list.extend(person_list)
+
+    if use_albums_as_keywords and self.albums:
+        keyword_list.extend(self.albums)
+
+    if keyword_template:
+        rendered_keywords = []
+        for template_str in keyword_template:
+            rendered, unmatched = self.render_template(
+                template_str, none_str=_OSXPHOTOS_NONE_SENTINEL, path_sep="/"
+            )
+            if unmatched:
+                logging.warning(
+                    f"Unmatched template substitution for template: {template_str} {unmatched}"
+                )
+            rendered_keywords.extend(rendered)
+
+        # filter out any template values that didn't match by looking for sentinel
+        rendered_keywords = [
+            keyword
+            for keyword in sorted(rendered_keywords)
+            if _OSXPHOTOS_NONE_SENTINEL not in keyword
+        ]
+
+        # check to see if any keywords too long
+        long_keywords = [
+            long_str
+            for long_str in rendered_keywords
+            if len(long_str) > _MAX_IPTC_KEYWORD_LEN
+        ]
+        if long_keywords:
+            logging.warning(
+                f"Some keywords exceed max IPTC Keyword length of {_MAX_IPTC_KEYWORD_LEN}: {long_keywords}"
+            )
+
+        keyword_list.extend(rendered_keywords)
+
+    if keyword_list:
+        # remove duplicates
+        keyword_list = sorted(list(set([str(keyword) for keyword in keyword_list])))
+        exif["IPTC:Keywords"] = keyword_list.copy()
+        exif["XMP:Subject"] = keyword_list.copy()
+        exif["XMP:TagsList"] = keyword_list.copy()
+
+    if person_list:
+        person_list = sorted(list(set(person_list)))
+        exif["XMP:PersonInImage"] = person_list.copy()
+
+    # if self.favorite():
+    #     exif["Rating"] = 5
+
+    (lat, lon) = self.location
+    if lat is not None and lon is not None:
+        if self.isphoto:
+            exif["EXIF:GPSLatitude"] = lat
+            exif["EXIF:GPSLongitude"] = lon
+            lat_ref = "N" if lat >= 0 else "S"
+            lon_ref = "E" if lon >= 0 else "W"
+            exif["EXIF:GPSLatitudeRef"] = lat_ref
+            exif["EXIF:GPSLongitudeRef"] = lon_ref
+        elif self.ismovie:
+            exif["Keys:GPSCoordinates"] = f"{lat} {lon}"
+            exif["UserData:GPSCoordinates"] = f"{lat} {lon}"
+
+    # process date/time and timezone offset
+    # Photos exports the following fields and sets modify date to creation date
+    # [EXIF]    Modify Date             : 2020:10:30 00:00:00
+    # [EXIF]    Date/Time Original      : 2020:10:30 00:00:00
+    # [EXIF]    Create Date             : 2020:10:30 00:00:00
+    # [IPTC]    Digital Creation Date   : 2020:10:30
+    # [IPTC]    Date Created            : 2020:10:30
+    #
+    # for videos:
+    # [QuickTime]     CreateDate                      : 2020:12:11 06:10:10
+    # [QuickTime]     ModifyDate                      : 2020:12:11 06:10:10
+    # [Keys]          CreationDate                    : 2020:12:10 22:10:10-08:00
+    # This code deviates from Photos in one regard:
+    # if photo has modification date, use it otherwise use creation date
+
+    date = self.date
+    offsettime = date.strftime("%z")
+    # find timezone offset in format "-04:00"
+    offset = re.findall(r"([+-]?)([\d]{2})([\d]{2})", offsettime)
+    offset = offset[0]  # findall returns list of tuples
+    offsettime = f"{offset[0]}{offset[1]}:{offset[2]}"
+
+    # exiftool expects format to "2015:01:18 12:00:00"
+    datetimeoriginal = date.strftime("%Y:%m:%d %H:%M:%S")
+
+    if self.isphoto:
+        exif["EXIF:DateTimeOriginal"] = datetimeoriginal
+        exif["EXIF:CreateDate"] = datetimeoriginal
+        exif["EXIF:OffsetTimeOriginal"] = offsettime
+
+        dateoriginal = date.strftime("%Y:%m:%d")
+        exif["IPTC:DateCreated"] = dateoriginal
+
+        timeoriginal = date.strftime(f"%H:%M:%S{offsettime}")
+        exif["IPTC:TimeCreated"] = timeoriginal
+
+        if self.date_modified is not None and not ignore_date_modified:
+            exif["EXIF:ModifyDate"] = self.date_modified.strftime("%Y:%m:%d %H:%M:%S")
+        else:
+            exif["EXIF:ModifyDate"] = self.date.strftime("%Y:%m:%d %H:%M:%S")
+    elif self.ismovie:
+        # QuickTime spec specifies times in UTC
+        # QuickTime:CreateDate and ModifyDate are in UTC w/ no timezone
+        # QuickTime:CreationDate must include time offset or Photos shows invalid values
+        # reference: https://exiftool.org/TagNames/QuickTime.html#Keys
+        #            https://exiftool.org/forum/index.php?topic=11927.msg64369#msg64369
+        exif["QuickTime:CreationDate"] = f"{datetimeoriginal}{offsettime}"
+
+        date_utc = datetime_tz_to_utc(date)
+        creationdate = date_utc.strftime("%Y:%m:%d %H:%M:%S")
+        exif["QuickTime:CreateDate"] = creationdate
+        if self.date_modified is None or ignore_date_modified:
+            exif["QuickTime:ModifyDate"] = creationdate
+        else:
+            exif["QuickTime:ModifyDate"] = datetime_tz_to_utc(
+                self.date_modified
+            ).strftime("%Y:%m:%d %H:%M:%S")
+    return exif
+
+
+def _get_exif_keywords(self):
+    """ returns list of keywords found in the file's exif metadata """
+    keywords = []
+    exif = self.exiftool
+    if exif:
+        exifdict = exif.asdict()
+        for field in ["IPTC:Keywords", "XMP:TagsList", "XMP:Subject"]:
+            try:
+                kw = exifdict[field]
+                if kw and type(kw) != list:
+                    kw = [kw]
+                kw = [str(k) for k in kw]
+                keywords.extend(kw)
+            except KeyError:
+                pass
+    return keywords
+
+
+def _get_exif_persons(self):
+    """ returns list of persons found in the file's exif metadata """
+    persons = []
+    exif = self.exiftool
+    if exif:
+        exifdict = exif.asdict()
+        try:
+            p = exifdict["XMP:PersonInImage"]
+            if p and type(p) != list:
+                p = [p]
+            p = [str(p_) for p_ in p]
+            persons.extend(p)
+        except KeyError:
+            pass
+    return persons
+
+
+def _exiftool_json_sidecar(
+    self,
+    use_albums_as_keywords=False,
+    use_persons_as_keywords=False,
+    keyword_template=None,
+    description_template=None,
+    ignore_date_modified=False,
+    tag_groups=True,
+    merge_exif_keywords=False,
+    merge_exif_persons=False,
+    filename=None,
+):
+    """Return dict of EXIF details for building exiftool JSON sidecar or sending commands to ExifTool.
+        Does not include all the EXIF fields as those are likely already in the image.
+
+    Args:
+        use_albums_as_keywords: treat album names as keywords
+        use_persons_as_keywords: treat person names as keywords
+        keyword_template: (list of strings); list of template strings to render as keywords
+        description_template: (list of strings); list of template strings to render for the description
+        ignore_date_modified: if True, sets EXIF:ModifyDate to EXIF:DateTimeOriginal even if date_modified is set
+        tag_groups: if True, tags are in form Group:TagName, e.g. IPTC:Keywords, otherwise group name is omitted, e.g. Keywords
+        merge_exif_keywords: boolean; if True, merged keywords found in file's exif data (requires exiftool)
+        merge_exif_persons: boolean; if True, merged persons found in file's exif data (requires exiftool)
+        filename: filename of the destination image file for including in exiftool signature in JSON sidecar
+
+    Returns: dict with exiftool tags / values
+
+    Exports the following:
+        EXIF:ImageDescription
+        XMP:Description (may include template)
+        XMP:Title
+        XMP:TagsList
+        IPTC:Keywords (may include album name, person name, or template)
+        XMP:Subject (set to keywords + person)
+        XMP:PersonInImage
+        EXIF:GPSLatitudeRef, EXIF:GPSLongitudeRef
+        EXIF:GPSLatitude, EXIF:GPSLongitude
+        EXIF:GPSPosition
+        EXIF:DateTimeOriginal
+        EXIF:OffsetTimeOriginal
+        EXIF:ModifyDate
+        IPTC:DigitalCreationDate
+        IPTC:DateCreated
+        QuickTime:CreationDate
+        QuickTime:CreateDate (UTC)
+        QuickTime:ModifyDate (UTC)
+        QuickTime:GPSCoordinates
+        UserData:GPSCoordinates
+    """
+    exif = self._exiftool_dict(
+        use_albums_as_keywords=use_albums_as_keywords,
+        use_persons_as_keywords=use_persons_as_keywords,
+        keyword_template=keyword_template,
+        description_template=description_template,
+        ignore_date_modified=ignore_date_modified,
+        merge_exif_keywords=merge_exif_keywords,
+        merge_exif_persons=merge_exif_persons,
+        filename=filename,
+    )
+
+    if not tag_groups:
+        # strip tag groups
+        exif_new = {}
+        for k, v in exif.items():
+            k = re.sub(r".*:", "", k)
+            exif_new[k] = v
+        exif = exif_new
+
+    return json.dumps([exif])
+
+
+def _xmp_sidecar(
+    self,
+    use_albums_as_keywords=False,
+    use_persons_as_keywords=False,
+    keyword_template=None,
+    description_template=None,
+    extension=None,
+    merge_exif_keywords=False,
+    merge_exif_persons=False,
+):
+    """returns string for XMP sidecar
+    use_albums_as_keywords: treat album names as keywords
+    use_persons_as_keywords: treat person names as keywords
+    keyword_template: (list of strings); list of template strings to render as keywords
+    description_template: string; optional template string that will be rendered for use as photo description
+    extension: which extension to use for SidecarForExtension property
+    merge_exif_keywords: boolean; if True, merged keywords found in file's exif data (requires exiftool)
+    merge_exif_persons: boolean; if True, merged persons found in file's exif data (requires exiftool)
+    """
+
+    xmp_template_file = (
+        _XMP_TEMPLATE_NAME if not self._db._beta else _XMP_TEMPLATE_NAME_BETA
+    )
+    xmp_template = Template(filename=os.path.join(_TEMPLATE_DIR, xmp_template_file))
+
+    if extension is None:
+        extension = pathlib.Path(self.original_filename)
+        extension = extension.suffix[1:] if extension.suffix else None
+
+    if description_template is not None:
+        rendered = self.render_template(
+            description_template, expand_inplace=True, inplace_sep=", "
+        )[0]
+        description = " ".join(rendered) if rendered else ""
+    else:
+        description = self.description if self.description is not None else ""
+
+    keyword_list = []
+    if merge_exif_keywords:
+        keyword_list.extend(self._get_exif_keywords())
+
+    if self.keywords:
+        keyword_list.extend(self.keywords)
+
+    # TODO: keyword handling in this and _exiftool_json_sidecar is
+    # good candidate for pulling out in a function
+
+    person_list = []
+    if merge_exif_persons:
+        person_list.extend(self._get_exif_persons())
+
+    if self.persons:
+        # filter out _UNKNOWN_PERSON
+        person_list.extend([p for p in self.persons if p != _UNKNOWN_PERSON])
+
+    if use_persons_as_keywords and person_list:
+        keyword_list.extend(person_list)
+
+    if use_albums_as_keywords and self.albums:
+        keyword_list.extend(self.albums)
+
+    if keyword_template:
+        rendered_keywords = []
+        for template_str in keyword_template:
+            rendered, unmatched = self.render_template(
+                template_str, none_str=_OSXPHOTOS_NONE_SENTINEL, path_sep="/"
+            )
+            if unmatched:
+                logging.warning(
+                    f"Unmatched template substitution for template: {template_str} {unmatched}"
+                )
+            rendered_keywords.extend(rendered)
+
+        # filter out any template values that didn't match by looking for sentinel
+        rendered_keywords = [
+            keyword
+            for keyword in rendered_keywords
+            if _OSXPHOTOS_NONE_SENTINEL not in keyword
+        ]
+
+        # check to see if any keywords too long
+        long_keywords = [
+            long_str
+            for long_str in rendered_keywords
+            if len(long_str) > _MAX_IPTC_KEYWORD_LEN
+        ]
+        if long_keywords:
+            logging.warning(
+                f"Some keywords exceed max IPTC Keyword length of {_MAX_IPTC_KEYWORD_LEN}: {long_keywords}"
+            )
+
+        keyword_list.extend(rendered_keywords)
+
+    # remove duplicates
+    # sorted mainly to make testing the XMP file easier
+    if keyword_list:
+        keyword_list = sorted(list(set(keyword_list)))
+    if person_list:
+        person_list = sorted(list(set(person_list)))
+
+    subject_list = keyword_list
+
+    xmp_str = xmp_template.render(
+        photo=self,
+        description=description,
+        keywords=keyword_list,
+        persons=person_list,
+        subjects=subject_list,
+        extension=extension,
+        version=__version__,
+    )
+
+    # remove extra lines that mako inserts from template
+    xmp_str = "\n".join(line for line in xmp_str.split("\n") if line.strip() != "")
+    return xmp_str
+
+
+def _write_sidecar(self, filename, sidecar_str):
+    """write sidecar_str to filename
+    used for exporting sidecar info"""
+    if not (filename or sidecar_str):
+        raise (
+            ValueError(
+                f"filename {filename} and sidecar_str {sidecar_str} must not be None"
+            )
+        )
+
+    # TODO: catch exception?
+    f = open(filename, "w")
+    f.write(sidecar_str)
+    f.close()
+
+ +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/build/html/_modules/osxphotos/photoinfo/_photoinfo_scoreinfo.html b/docs/build/html/_modules/osxphotos/photoinfo/_photoinfo_scoreinfo.html new file mode 100644 index 00000000..689858c2 --- /dev/null +++ b/docs/build/html/_modules/osxphotos/photoinfo/_photoinfo_scoreinfo.html @@ -0,0 +1,220 @@ + + + + + + + + osxphotos.photoinfo._photoinfo_scoreinfo — osxphotos 0.40.4 documentation + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Source code for osxphotos.photoinfo._photoinfo_scoreinfo

+""" PhotoInfo methods to expose computed score info from the library """
+
+import logging
+from dataclasses import dataclass
+
+from .._constants import _PHOTOS_4_VERSION
+
+
+@dataclass(frozen=True)
+class ScoreInfo:
+    """ Computed photo score info associated with a photo from the Photos library """
+
+    overall: float
+    curation: float
+    promotion: float
+    highlight_visibility: float
+    behavioral: float
+    failure: float
+    harmonious_color: float
+    immersiveness: float
+    interaction: float
+    interesting_subject: float
+    intrusive_object_presence: float
+    lively_color: float
+    low_light: float
+    noise: float
+    pleasant_camera_tilt: float
+    pleasant_composition: float
+    pleasant_lighting: float
+    pleasant_pattern: float
+    pleasant_perspective: float
+    pleasant_post_processing: float
+    pleasant_reflection: float
+    pleasant_symmetry: float
+    sharply_focused_subject: float
+    tastefully_blurred: float
+    well_chosen_subject: float
+    well_framed_subject: float
+    well_timed_shot: float
+
+
+@property
+def score(self):
+    """ Computed score information for a photo
+
+    Returns:
+        ScoreInfo instance
+    """
+
+    if self._db._db_version <= _PHOTOS_4_VERSION:
+        logging.debug(f"score not implemented for this database version")
+        return None
+
+    try:
+        return self._scoreinfo  # pylint: disable=access-member-before-definition
+    except AttributeError:
+        try:
+            scores = self._db._db_scoreinfo_uuid[self.uuid]
+            self._scoreinfo = ScoreInfo(
+                overall=scores["overall_aesthetic"],
+                curation=scores["curation"],
+                promotion=scores["promotion"],
+                highlight_visibility=scores["highlight_visibility"],
+                behavioral=scores["behavioral"],
+                failure=scores["failure"],
+                harmonious_color=scores["harmonious_color"],
+                immersiveness=scores["immersiveness"],
+                interaction=scores["interaction"],
+                interesting_subject=scores["interesting_subject"],
+                intrusive_object_presence=scores["intrusive_object_presence"],
+                lively_color=scores["lively_color"],
+                low_light=scores["low_light"],
+                noise=scores["noise"],
+                pleasant_camera_tilt=scores["pleasant_camera_tilt"],
+                pleasant_composition=scores["pleasant_composition"],
+                pleasant_lighting=scores["pleasant_lighting"],
+                pleasant_pattern=scores["pleasant_pattern"],
+                pleasant_perspective=scores["pleasant_perspective"],
+                pleasant_post_processing=scores["pleasant_post_processing"],
+                pleasant_reflection=scores["pleasant_reflection"],
+                pleasant_symmetry=scores["pleasant_symmetry"],
+                sharply_focused_subject=scores["sharply_focused_subject"],
+                tastefully_blurred=scores["tastefully_blurred"],
+                well_chosen_subject=scores["well_chosen_subject"],
+                well_framed_subject=scores["well_framed_subject"],
+                well_timed_shot=scores["well_timed_shot"],
+            )
+            return self._scoreinfo
+        except KeyError:
+            self._scoreinfo = ScoreInfo(
+                overall=0.0,
+                curation=0.0,
+                promotion=0.0,
+                highlight_visibility=0.0,
+                behavioral=0.0,
+                failure=0.0,
+                harmonious_color=0.0,
+                immersiveness=0.0,
+                interaction=0.0,
+                interesting_subject=0.0,
+                intrusive_object_presence=0.0,
+                lively_color=0.0,
+                low_light=0.0,
+                noise=0.0,
+                pleasant_camera_tilt=0.0,
+                pleasant_composition=0.0,
+                pleasant_lighting=0.0,
+                pleasant_pattern=0.0,
+                pleasant_perspective=0.0,
+                pleasant_post_processing=0.0,
+                pleasant_reflection=0.0,
+                pleasant_symmetry=0.0,
+                sharply_focused_subject=0.0,
+                tastefully_blurred=0.0,
+                well_chosen_subject=0.0,
+                well_framed_subject=0.0,
+                well_timed_shot=0.0,
+            )
+            return self._scoreinfo
+
+ +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/build/html/_modules/osxphotos/photoinfo/_photoinfo_searchinfo.html b/docs/build/html/_modules/osxphotos/photoinfo/_photoinfo_searchinfo.html new file mode 100644 index 00000000..399d3aa3 --- /dev/null +++ b/docs/build/html/_modules/osxphotos/photoinfo/_photoinfo_searchinfo.html @@ -0,0 +1,378 @@ + + + + + + + + osxphotos.photoinfo._photoinfo_searchinfo — osxphotos 0.40.4 documentation + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Source code for osxphotos.photoinfo._photoinfo_searchinfo

+""" Methods and class for PhotoInfo exposing SearchInfo data such as labels 
+    Adds the following properties to PhotoInfo (valid only for Photos 5):
+        search_info: returns a SearchInfo object
+        search_info_normalized: returns a SearchInfo object with properties that produce normalized results
+        labels: returns list of labels
+        labels_normalized: returns list of normalized labels
+"""
+
+from .._constants import (
+    _PHOTOS_4_VERSION,
+    SEARCH_CATEGORY_CITY,
+    SEARCH_CATEGORY_LABEL,
+    SEARCH_CATEGORY_NEIGHBORHOOD,
+    SEARCH_CATEGORY_PLACE_NAME,
+    SEARCH_CATEGORY_STREET,
+    SEARCH_CATEGORY_ALL_LOCALITY,
+    SEARCH_CATEGORY_COUNTRY,
+    SEARCH_CATEGORY_STATE,
+    SEARCH_CATEGORY_STATE_ABBREVIATION,
+    SEARCH_CATEGORY_BODY_OF_WATER,
+    SEARCH_CATEGORY_MONTH,
+    SEARCH_CATEGORY_YEAR,
+    SEARCH_CATEGORY_HOLIDAY,
+    SEARCH_CATEGORY_ACTIVITY,
+    SEARCH_CATEGORY_SEASON,
+    SEARCH_CATEGORY_VENUE,
+    SEARCH_CATEGORY_VENUE_TYPE,
+    SEARCH_CATEGORY_MEDIA_TYPES,
+)
+
+
+@property
+def search_info(self):
+    """ returns SearchInfo object for photo 
+        only valid on Photos 5, on older libraries, returns None
+    """
+    if self._db._db_version <= _PHOTOS_4_VERSION:
+        return None
+
+    # memoize SearchInfo object
+    try:
+        return self._search_info
+    except AttributeError:
+        self._search_info = SearchInfo(self)
+        return self._search_info
+
+
+@property
+def search_info_normalized(self):
+    """ returns SearchInfo object for photo that produces normalized results
+        only valid on Photos 5, on older libraries, returns None
+    """
+    if self._db._db_version <= _PHOTOS_4_VERSION:
+        return None
+
+    # memoize SearchInfo object
+    try:
+        return self._search_info_normalized
+    except AttributeError:
+        self._search_info_normalized = SearchInfo(self, normalized=True)
+        return self._search_info_normalized
+
+
+@property
+def labels(self):
+    """ returns list of labels applied to photo by Photos image categorization
+        only valid on Photos 5, on older libraries returns empty list 
+    """
+    if self._db._db_version <= _PHOTOS_4_VERSION:
+        return []
+
+    return self.search_info.labels
+
+
+@property
+def labels_normalized(self):
+    """ returns normalized list of labels applied to photo by Photos image categorization
+        only valid on Photos 5, on older libraries returns empty list 
+    """
+    if self._db._db_version <= _PHOTOS_4_VERSION:
+        return []
+
+    return self.search_info_normalized.labels
+
+
+class SearchInfo:
+    """ Info about search terms such as machine learning labels that Photos knows about a photo """
+
+    def __init__(self, photo, normalized=False):
+        """ photo: PhotoInfo object
+            normalized: if True, all properties return normalized (lower case) results """
+
+        if photo._db._db_version <= _PHOTOS_4_VERSION:
+            raise NotImplementedError(
+                f"search info not implemented for this database version"
+            )
+
+        self._photo = photo
+        self._normalized = normalized
+        self.uuid = photo.uuid
+        try:
+            # get search info for this UUID
+            # there might not be any search info data (e.g. if Photo was missing or photoanalysisd not run yet)
+            self._db_searchinfo = photo._db._db_searchinfo_uuid[self.uuid]
+        except KeyError:
+            self._db_searchinfo = None
+
+    @property
+    def labels(self):
+        """ return list of labels associated with Photo """
+        return self._get_text_for_category(SEARCH_CATEGORY_LABEL)
+
+    @property
+    def place_names(self):
+        """ returns list of place names """
+        return self._get_text_for_category(SEARCH_CATEGORY_PLACE_NAME)
+
+    @property
+    def streets(self):
+        """ returns list of street names """
+        return self._get_text_for_category(SEARCH_CATEGORY_STREET)
+
+    @property
+    def neighborhoods(self):
+        """ returns list of neighborhoods """
+        return self._get_text_for_category(SEARCH_CATEGORY_NEIGHBORHOOD)
+
+    @property
+    def locality_names(self):
+        """ returns list of other locality names """
+        locality = []
+        for category in SEARCH_CATEGORY_ALL_LOCALITY:
+            locality += self._get_text_for_category(category)
+        return locality
+
+    @property
+    def city(self):
+        """ returns city/town """
+        city = self._get_text_for_category(SEARCH_CATEGORY_CITY)
+        return city[0] if city else ""
+
+    @property
+    def state(self):
+        """ returns state name """
+        state = self._get_text_for_category(SEARCH_CATEGORY_STATE)
+        return state[0] if state else ""
+
+    @property
+    def state_abbreviation(self):
+        """ returns state abbreviation """
+        abbrev = self._get_text_for_category(SEARCH_CATEGORY_STATE_ABBREVIATION)
+        return abbrev[0] if abbrev else ""
+
+    @property
+    def country(self):
+        """ returns country name """
+        country = self._get_text_for_category(SEARCH_CATEGORY_COUNTRY)
+        return country[0] if country else ""
+
+    @property
+    def month(self):
+        """ returns month name """
+        month = self._get_text_for_category(SEARCH_CATEGORY_MONTH)
+        return month[0] if month else ""
+
+    @property
+    def year(self):
+        """ returns year """
+        year = self._get_text_for_category(SEARCH_CATEGORY_YEAR)
+        return year[0] if year else ""
+
+    @property
+    def bodies_of_water(self):
+        """ returns list of body of water names """
+        return self._get_text_for_category(SEARCH_CATEGORY_BODY_OF_WATER)
+
+    @property
+    def holidays(self):
+        """ returns list of holiday names """
+        return self._get_text_for_category(SEARCH_CATEGORY_HOLIDAY)
+
+    @property
+    def activities(self):
+        """ returns list of activity names """
+        return self._get_text_for_category(SEARCH_CATEGORY_ACTIVITY)
+
+    @property
+    def season(self):
+        """ returns season name """
+        season = self._get_text_for_category(SEARCH_CATEGORY_SEASON)
+        return season[0] if season else ""
+
+    @property
+    def venues(self):
+        """ returns list of venue names """
+        return self._get_text_for_category(SEARCH_CATEGORY_VENUE)
+
+    @property
+    def venue_types(self):
+        """ returns list of venue types """
+        return self._get_text_for_category(SEARCH_CATEGORY_VENUE_TYPE)
+
+    @property
+    def media_types(self):
+        """ returns list of media types (photo, video, panorama, etc) """
+        types = []
+        for category in SEARCH_CATEGORY_MEDIA_TYPES:
+            types += self._get_text_for_category(category)
+        return types
+
+    @property
+    def all(self):
+        """ return all search info properties in a single list """
+        all = (
+            self.labels
+            + self.place_names
+            + self.streets
+            + self.neighborhoods
+            + self.locality_names
+            + self.bodies_of_water
+            + self.holidays
+            + self.activities
+            + self.venues
+            + self.venue_types
+            + self.media_types
+        )
+        if self.city:
+            all += [self.city]
+        if self.state:
+            all += [self.state]
+        if self.state_abbreviation:
+            all += [self.state_abbreviation]
+        if self.country:
+            all += [self.country]
+        if self.month:
+            all += [self.month]
+        if self.year:
+            all += [self.year]
+        if self.season:
+            all += [self.season]
+
+        return all
+
+    def asdict(self):
+        """ return dict of search info """
+        return {
+            "labels": self.labels,
+            "place_names": self.place_names,
+            "streets": self.streets,
+            "neighborhoods": self.neighborhoods,
+            "city": self.city,
+            "locality_names": self.locality_names,
+            "state": self.state,
+            "state_abbreviation": self.state_abbreviation,
+            "country": self.country,
+            "bodies_of_water": self.bodies_of_water,
+            "month": self.month,
+            "year": self.year,
+            "holidays": self.holidays,
+            "activities": self.activities,
+            "season": self.season,
+            "venues": self.venues,
+            "venue_types": self.venue_types,
+            "media_types": self.media_types,
+        }
+
+    def _get_text_for_category(self, category):
+        """ return list of text for a specified category ID """
+        if self._db_searchinfo:
+            content = "normalized_string" if self._normalized else "content_string"
+            return [
+                rec[content]
+                for rec in self._db_searchinfo
+                if rec["category"] == category
+            ]
+        else:
+            return []
+
+ +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/build/html/_modules/osxphotos/photoinfo/photoinfo.html b/docs/build/html/_modules/osxphotos/photoinfo/photoinfo.html new file mode 100644 index 00000000..a3bf7d1e --- /dev/null +++ b/docs/build/html/_modules/osxphotos/photoinfo/photoinfo.html @@ -0,0 +1,1196 @@ + + + + + + + + osxphotos.photoinfo.photoinfo — osxphotos 0.40.4 documentation + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Source code for osxphotos.photoinfo.photoinfo

+"""
+PhotoInfo class
+Represents a single photo in the Photos library and provides access to the photo's attributes
+PhotosDB.photos() returns a list of PhotoInfo objects
+"""
+
+import dataclasses
+import datetime
+import json
+import logging
+import os
+import os.path
+import pathlib
+from datetime import timedelta, timezone
+
+import yaml
+
+from .._constants import (
+    _MOVIE_TYPE,
+    _PHOTO_TYPE,
+    _PHOTOS_4_ALBUM_KIND,
+    _PHOTOS_4_ROOT_FOLDER,
+    _PHOTOS_4_VERSION,
+    _PHOTOS_5_ALBUM_KIND,
+    _PHOTOS_5_IMPORT_SESSION_ALBUM_KIND,
+    _PHOTOS_5_SHARED_ALBUM_KIND,
+    _PHOTOS_5_SHARED_PHOTO_PATH,
+    _PHOTOS_5_VERSION,
+)
+from ..albuminfo import AlbumInfo, ImportInfo
+from ..personinfo import FaceInfo, PersonInfo
+from ..phototemplate import PhotoTemplate
+from ..placeinfo import PlaceInfo4, PlaceInfo5
+from ..utils import _debug, _get_resource_loc, findfiles, get_preferred_uti_extension
+
+
+
[docs]class PhotoInfo: + """ + Info about a specific photo, contains all the details about the photo + including keywords, persons, albums, uuid, path, etc. + """ + + # import additional methods + from ._photoinfo_searchinfo import ( + search_info, + search_info_normalized, + labels, + labels_normalized, + SearchInfo, + ) + from ._photoinfo_exifinfo import exif_info, ExifInfo + from ._photoinfo_exiftool import exiftool + from ._photoinfo_export import ( + export, + export2, + _export_photo, + _exiftool_dict, + _exiftool_json_sidecar, + _get_exif_keywords, + _get_exif_persons, + _write_exif_data, + _write_sidecar, + _xmp_sidecar, + ExportResults, + ) + from ._photoinfo_scoreinfo import score, ScoreInfo + from ._photoinfo_comments import comments, likes + + def __init__(self, db=None, uuid=None, info=None): + self._uuid = uuid + self._info = info + self._db = db + + @property + def filename(self): + """ filename of the picture """ + if ( + self._db._db_version <= _PHOTOS_4_VERSION + and self.has_raw + and self.raw_original + ): + # return the JPEG version as that's what Photos 5+ does + return self._info["raw_pair_info"]["filename"] + else: + return self._info["filename"] + + @property + def original_filename(self): + """original filename of the picture + Photos 5 mangles filenames upon import""" + if ( + self._db._db_version <= _PHOTOS_4_VERSION + and self.has_raw + and self.raw_original + ): + # return the JPEG version as that's what Photos 5+ does + original_name = self._info["raw_pair_info"]["originalFilename"] + else: + original_name = self._info["originalFilename"] + return original_name or self.filename + + @property + def date(self): + """ image creation date as timezone aware datetime object """ + return self._info["imageDate"] + + @property + def date_modified(self): + """image modification date as timezone aware datetime object + or None if no modification date set""" + + # Photos <= 4 provides no way to get date of adjustment and will update + # lastmodifieddate anytime photo database record is updated (e.g. adding tags) + # only report lastmodified date for Photos <=4 if photo is edited; + # even in this case, the date could be incorrect + if not self.hasadjustments and self._db._db_version <= _PHOTOS_4_VERSION: + return None + + imagedate = self._info["lastmodifieddate"] + if imagedate: + seconds = self._info["imageTimeZoneOffsetSeconds"] or 0 + delta = timedelta(seconds=seconds) + tz = timezone(delta) + return imagedate.astimezone(tz=tz) + else: + return None + + @property + def tzoffset(self): + """ timezone offset from UTC in seconds """ + return self._info["imageTimeZoneOffsetSeconds"] + + @property + def path(self): + """ absolute path on disk of the original picture """ + try: + return self._path + except AttributeError: + self._path = None + photopath = None + # TODO: should path try to return path even if ismissing? + if self._info["isMissing"] == 1: + return photopath # path would be meaningless until downloaded + + if self._db._db_version <= _PHOTOS_4_VERSION: + if self._info["has_raw"]: + # return the path to JPEG even if RAW is original + vol = ( + self._db._dbvolumes[self._info["raw_pair_info"]["volumeId"]] + if self._info["raw_pair_info"]["volumeId"] is not None + else None + ) + if vol is not None: + photopath = os.path.join( + "/Volumes", vol, self._info["raw_pair_info"]["imagePath"] + ) + else: + photopath = os.path.join( + self._db._masters_path, + self._info["raw_pair_info"]["imagePath"], + ) + else: + vol = self._info["volume"] + if vol is not None: + photopath = os.path.join( + "/Volumes", vol, self._info["imagePath"] + ) + else: + photopath = os.path.join( + self._db._masters_path, self._info["imagePath"] + ) + if not os.path.isfile(photopath): + photopath = None + self._path = photopath + return photopath + + if self._info["shared"]: + # shared photo + photopath = os.path.join( + self._db._library_path, + _PHOTOS_5_SHARED_PHOTO_PATH, + self._info["directory"], + self._info["filename"], + ) + if not os.path.isfile(photopath): + photopath = None + self._path = photopath + return photopath + + if self._info["directory"].startswith("/"): + photopath = os.path.join( + self._info["directory"], self._info["filename"] + ) + else: + photopath = os.path.join( + self._db._masters_path, + self._info["directory"], + self._info["filename"], + ) + if not os.path.isfile(photopath): + photopath = None + self._path = photopath + return photopath + + @property + def path_edited(self): + """ absolute path on disk of the edited picture """ + """ None if photo has not been edited """ + + try: + return self._path_edited + except AttributeError: + if self._db._db_version <= _PHOTOS_4_VERSION: + self._path_edited = self._path_edited_4() + else: + self._path_edited = self._path_edited_5() + + return self._path_edited + + def _path_edited_5(self): + """ return path_edited for Photos >= 5 """ + # In Photos 5.0 / Catalina / MacOS 10.15: + # edited photos appear to always be converted to .jpeg and stored in + # library_name/resources/renders/X/UUID_1_201_a.jpeg + # where X = first letter of UUID + # and UUID = UUID of image + # this seems to be true even for photos not copied to Photos library and + # where original format was not jpg/jpeg + # if more than one edit, previous edit is stored as UUID_p.jpeg + # + # In Photos 6.0 / Big Sur, the edited image is a .heic if the photo isn't a jpeg, + # otherwise it's a jpeg. It could also be a jpeg if photo library upgraded from earlier + # version. + + if self._db._db_version < _PHOTOS_5_VERSION: + raise RuntimeError("Wrong database format!") + + if self._info["hasAdjustments"]: + library = self._db._library_path + directory = self._uuid[0] # first char of uuid + filename = None + if self._info["type"] == _PHOTO_TYPE: + # it's a photo + if self._db._photos_ver == 5: + filename = f"{self._uuid}_1_201_a.jpeg" + else: + # could be a heic or a jpeg + if self.uti == "public.heic": + filename = f"{self._uuid}_1_201_a.heic" + else: + filename = f"{self._uuid}_1_201_a.jpeg" + elif self._info["type"] == _MOVIE_TYPE: + # it's a movie + filename = f"{self._uuid}_2_0_a.mov" + else: + # don't know what it is! + logging.debug(f"WARNING: unknown type {self._info['type']}") + return None + + photopath = os.path.join( + library, "resources", "renders", directory, filename + ) + + if not os.path.isfile(photopath): + logging.debug( + f"edited file for UUID {self._uuid} should be at {photopath} but does not appear to exist" + ) + photopath = None + else: + photopath = None + + # TODO: might be possible for original/master to be missing but edit to still be there + # if self._info["isMissing"] == 1: + # photopath = None # path would be meaningless until downloaded + + return photopath + + def _path_edited_4(self): + """ return path_edited for Photos <= 4 """ + + if self._db._db_version > _PHOTOS_4_VERSION: + raise RuntimeError("Wrong database format!") + + photopath = None + if self._info["hasAdjustments"]: + edit_id = self._info["edit_resource_id"] + if edit_id is not None: + library = self._db._library_path + folder_id, file_id = _get_resource_loc(edit_id) + # todo: is this always true or do we need to search file file_id under folder_id + # figure out what kind it is and build filename + filename = None + if self._info["type"] == _PHOTO_TYPE: + # it's a photo + filename = f"fullsizeoutput_{file_id}.jpeg" + elif self._info["type"] == _MOVIE_TYPE: + # it's a movie + filename = f"fullsizeoutput_{file_id}.mov" + else: + # don't know what it is! + logging.debug(f"WARNING: unknown type {self._info['type']}") + return None + + # photopath appears to usually be in "00" subfolder but + # could be elsewhere--I haven't figured out this logic yet + # first see if it's in 00 + photopath = os.path.join( + library, "resources", "media", "version", folder_id, "00", filename + ) + + if not os.path.isfile(photopath): + rootdir = os.path.join( + library, "resources", "media", "version", folder_id + ) + + for dirname, _, filelist in os.walk(rootdir): + if filename in filelist: + photopath = os.path.join(dirname, filename) + break + + # check again to see if we found a valid file + if not os.path.isfile(photopath): + logging.debug( + f"MISSING PATH: edited file for UUID {self._uuid} should be at {photopath} but does not appear to exist" + ) + photopath = None + else: + logging.debug( + f"{self.uuid} hasAdjustments but edit_resource_id is None" + ) + photopath = None + else: + photopath = None + + return photopath + + @property + def path_raw(self): + """ absolute path of associated RAW image or None if there is not one """ + + # In Photos 5, raw is in same folder as original but with _4.ext + # Unless "Copy Items to the Photos Library" is not checked + # then RAW image is not renamed but has same name is jpeg buth with raw extension + # Current implementation uses findfiles to find images with the correct raw UTI extension + # in same folder as the original and with same stem as original in form: original_stem*.raw_ext + # TODO: I don't like this -- would prefer a more deterministic approach but until I have more + # data on how Photos stores and retrieves RAW images, this seems to be working + + if self._info["isMissing"] == 1: + return None # path would be meaningless until downloaded + + if not self.has_raw: + return None # no raw image to get path for + + # if self._info["shared"]: + # # shared photo + # photopath = os.path.join( + # self._db._library_path, + # _PHOTOS_5_SHARED_PHOTO_PATH, + # self._info["directory"], + # self._info["filename"], + # ) + # return photopath + + if self._db._db_version <= _PHOTOS_4_VERSION: + vol = self._info["raw_info"]["volume"] + if vol is not None: + photopath = os.path.join( + "/Volumes", vol, self._info["raw_info"]["imagePath"] + ) + else: + photopath = os.path.join( + self._db._masters_path, self._info["raw_info"]["imagePath"] + ) + if not os.path.isfile(photopath): + logging.debug( + f"MISSING PATH: RAW photo for UUID {self._uuid} should be at {photopath} but does not appear to exist" + ) + photopath = None + else: + filestem = pathlib.Path(self._info["filename"]).stem + raw_ext = get_preferred_uti_extension(self._info["UTI_raw"]) + + if self._info["directory"].startswith("/"): + filepath = self._info["directory"] + else: + filepath = os.path.join(self._db._masters_path, self._info["directory"]) + + glob_str = f"{filestem}*.{raw_ext}" + raw_file = findfiles(glob_str, filepath) + if len(raw_file) != 1: + # Note: In Photos Version 5.0 (141.19.150), images not copied to Photos Library + # that are missing do not always trigger is_missing = True as happens + # in earlier version so it's possible for this check to fail, if so, return None + logging.debug(f"Error getting path to RAW file: {filepath}/{glob_str}") + photopath = None + else: + photopath = os.path.join(filepath, raw_file[0]) + if not os.path.isfile(photopath): + logging.debug( + f"MISSING PATH: RAW photo for UUID {self._uuid} should be at {photopath} but does not appear to exist" + ) + photopath = None + + return photopath + + @property + def description(self): + """ long / extended description of picture """ + return self._info["extendedDescription"] + + @property + def persons(self): + """ list of persons in picture """ + return [self._db._dbpersons_pk[pk]["fullname"] for pk in self._info["persons"]] + + @property + def person_info(self): + """ list of PersonInfo objects for person in picture """ + try: + return self._personinfo + except AttributeError: + self._personinfo = [ + PersonInfo(db=self._db, pk=pk) for pk in self._info["persons"] + ] + return self._personinfo + + @property + def face_info(self): + """ list of FaceInfo objects for faces in picture """ + try: + return self._faceinfo + except AttributeError: + try: + faces = self._db._db_faceinfo_uuid[self._uuid] + self._faceinfo = [FaceInfo(db=self._db, pk=pk) for pk in faces] + except KeyError: + # no faces + self._faceinfo = [] + return self._faceinfo + + @property + def albums(self): + """ list of albums picture is contained in """ + try: + return self._albums + except AttributeError: + album_uuids = self._get_album_uuids() + self._albums = list( + {self._db._dbalbum_details[album]["title"] for album in album_uuids} + ) + return self._albums + + @property + def album_info(self): + """ list of AlbumInfo objects representing albums the photos is contained in """ + try: + return self._album_info + except AttributeError: + album_uuids = self._get_album_uuids() + self._album_info = [ + AlbumInfo(db=self._db, uuid=album) for album in album_uuids + ] + return self._album_info + + @property + def import_info(self): + """ ImportInfo object representing import session for the photo or None if no import session """ + try: + return self._import_info + except AttributeError: + self._import_info = ( + ImportInfo(db=self._db, uuid=self._info["import_uuid"]) + if self._info["import_uuid"] is not None + else None + ) + return self._import_info + + @property + def keywords(self): + """ list of keywords for picture """ + return self._info["keywords"] + + @property + def title(self): + """ name / title of picture """ + return self._info["name"] + + @property + def uuid(self): + """ UUID of picture """ + return self._uuid + + @property + def ismissing(self): + """returns true if photo is missing from disk (which means it's not been downloaded from iCloud) + NOTE: the photos.db database uses an asynchrounous write-ahead log so changes in Photos + do not immediately get written to disk. In particular, I've noticed that downloading + an image from the cloud does not force the database to be updated until something else + e.g. an edit, keyword, etc. occurs forcing a database synch + The exact process / timing is a mystery to be but be aware that if some photos were recently + downloaded from cloud to local storate their status in the database might still show + isMissing = 1 + """ + return self._info["isMissing"] == 1 + + @property + def hasadjustments(self): + """ True if picture has adjustments / edits """ + return self._info["hasAdjustments"] == 1 + + @property + def external_edit(self): + """ Returns True if picture was edited outside of Photos using external editor """ + return self._info["adjustmentFormatID"] == "com.apple.Photos.externalEdit" + + @property + def favorite(self): + """ True if picture is marked as favorite """ + return self._info["favorite"] == 1 + + @property + def hidden(self): + """ True if picture is hidden """ + return self._info["hidden"] == 1 + + @property + def visible(self): + """ True if picture is visble """ + return self._info["visible"] + + @property + def intrash(self): + """ True if picture is in trash ('Recently Deleted' folder)""" + return self._info["intrash"] + + @property + def date_trashed(self): + """ Date asset was placed in the trash or None """ + # TODO: add add_timezone(dt, offset_seconds) to datetime_utils + # also update date_modified + trasheddate = self._info["trasheddate"] + if trasheddate: + seconds = self._info["imageTimeZoneOffsetSeconds"] or 0 + delta = timedelta(seconds=seconds) + tz = timezone(delta) + return trasheddate.astimezone(tz=tz) + else: + return None + + @property + def location(self): + """ returns (latitude, longitude) as float in degrees or None """ + return (self._latitude, self._longitude) + + @property + def shared(self): + """returns True if photos is in a shared iCloud album otherwise false + Only valid on Photos 5; returns None on older versions""" + if self._db._db_version > _PHOTOS_4_VERSION: + return self._info["shared"] + else: + return None + + @property + def uti(self): + """Returns Uniform Type Identifier (UTI) for the image + for example: public.jpeg or com.apple.quicktime-movie + """ + if self._db._db_version <= _PHOTOS_4_VERSION and self.hasadjustments: + return self._info["UTI_edited"] + elif ( + self._db._db_version <= _PHOTOS_4_VERSION + and self.has_raw + and self.raw_original + ): + # return UTI of the non-raw image to match Photos 5+ behavior + return self._info["raw_pair_info"]["UTI"] + else: + return self._info["UTI"] + + @property + def uti_original(self): + """Returns Uniform Type Identifier (UTI) for the original image + for example: public.jpeg or com.apple.quicktime-movie + """ + if self._db._db_version <= _PHOTOS_4_VERSION and self._info["has_raw"]: + return self._info["raw_pair_info"]["UTI"] + elif self.shared: + # TODO: need reliable way to get original UTI for shared + return self.uti + else: + return self._info["UTI_original"] + + @property + def uti_edited(self): + """Returns Uniform Type Identifier (UTI) for the edited image + if the photo has been edited, otherwise None; + for example: public.jpeg + """ + if self._db._db_version >= _PHOTOS_5_VERSION: + return self.uti if self.hasadjustments else None + else: + return self._info["UTI_edited"] + + @property + def uti_raw(self): + """Returns Uniform Type Identifier (UTI) for the RAW image if there is one + for example: com.canon.cr2-raw-image + Returns None if no associated RAW image + """ + return self._info["UTI_raw"] + + @property + def ismovie(self): + """Returns True if file is a movie, otherwise False""" + return self._info["type"] == _MOVIE_TYPE + + @property + def isphoto(self): + """Returns True if file is an image, otherwise False""" + return self._info["type"] == _PHOTO_TYPE + + @property + def incloud(self): + """Returns True if photo is cloud asset and is synched to cloud + False if photo is cloud asset and not yet synched to cloud + None if photo is not cloud asset + """ + return self._info["incloud"] + + @property + def iscloudasset(self): + """Returns True if photo is a cloud asset (in an iCloud library), + otherwise False + """ + if self._db._db_version <= _PHOTOS_4_VERSION: + return ( + True + if self._info["cloudLibraryState"] is not None + and self._info["cloudLibraryState"] != 0 + else False + ) + else: + return True if self._info["cloudAssetGUID"] is not None else False + + @property + def isreference(self): + """ Returns True if photo is a reference (not copied to the Photos library), otherwise False """ + return self._info["isreference"] + + @property + def burst(self): + """ Returns True if photo is part of a Burst photo set, otherwise False """ + return self._info["burst"] + + @property + def burst_photos(self): + """If photo is a burst photo, returns list of PhotoInfo objects + that are part of the same burst photo set; otherwise returns empty list. + self is not included in the returned list""" + if self._info["burst"]: + burst_uuid = self._info["burstUUID"] + return [ + PhotoInfo(db=self._db, uuid=u, info=self._db._dbphotos[u]) + for u in self._db._dbphotos_burst[burst_uuid] + if u != self._uuid + ] + else: + return [] + + @property + def live_photo(self): + """ Returns True if photo is a live photo, otherwise False """ + return self._info["live_photo"] + + @property + def path_live_photo(self): + """Returns path to the associated video file for a live photo + If photo is not a live photo, returns None + If photo is missing, returns None""" + + photopath = None + if self._db._db_version <= _PHOTOS_4_VERSION: + if self.live_photo and not self.ismissing: + live_model_id = self._info["live_model_id"] + if live_model_id == None: + logging.debug(f"missing live_model_id: {self._uuid}") + photopath = None + else: + folder_id, file_id = _get_resource_loc(live_model_id) + library_path = self._db.library_path + photopath = os.path.join( + library_path, + "resources", + "media", + "master", + folder_id, + "00", + f"jpegvideocomplement_{file_id}.mov", + ) + if not os.path.isfile(photopath): + # In testing, I've seen occasional missing movie for live photo + # These appear to be valid -- e.g. live component hasn't been downloaded from iCloud + # photos 4 has "isOnDisk" column we could check + # or could do the actual check with "isfile" + # TODO: should this be a warning or debug? + logging.debug( + f"MISSING PATH: live photo path for UUID {self._uuid} should be at {photopath} but does not appear to exist" + ) + photopath = None + else: + photopath = None + else: + # Photos 5 + if self.live_photo and not self.ismissing: + filename = pathlib.Path(self.path) + photopath = filename.parent.joinpath(f"{filename.stem}_3.mov") + photopath = str(photopath) + if not os.path.isfile(photopath): + # In testing, I've seen occasional missing movie for live photo + # these appear to be valid -- e.g. video component not yet downloaded from iCloud + # TODO: should this be a warning or debug? + logging.debug( + f"MISSING PATH: live photo path for UUID {self._uuid} should be at {photopath} but does not appear to exist" + ) + photopath = None + else: + photopath = None + + return photopath + + @property + def panorama(self): + """ Returns True if photo is a panorama, otherwise False """ + return self._info["panorama"] + + @property + def slow_mo(self): + """ Returns True if photo is a slow motion video, otherwise False """ + return self._info["slow_mo"] + + @property + def time_lapse(self): + """ Returns True if photo is a time lapse video, otherwise False """ + return self._info["time_lapse"] + + @property + def hdr(self): + """ Returns True if photo is an HDR photo, otherwise False """ + return self._info["hdr"] + + @property + def screenshot(self): + """ Returns True if photo is an HDR photo, otherwise False """ + return self._info["screenshot"] + + @property + def portrait(self): + """ Returns True if photo is a portrait, otherwise False """ + return self._info["portrait"] + + @property + def selfie(self): + """ Returns True if photo is a selfie (front facing camera), otherwise False """ + return self._info["selfie"] + + @property + def place(self): + """ Returns PlaceInfo object containing reverse geolocation info """ + + # implementation note: doesn't create the PlaceInfo object until requested + # then memoizes the object in self._place to avoid recreating the object + + if self._db._db_version <= _PHOTOS_4_VERSION: + try: + return self._place # pylint: disable=access-member-before-definition + except AttributeError: + if self._info["placeNames"]: + self._place = PlaceInfo4( + self._info["placeNames"], self._info["countryCode"] + ) + else: + self._place = None + return self._place + else: + try: + return self._place # pylint: disable=access-member-before-definition + except AttributeError: + if self._info["reverse_geolocation"]: + self._place = PlaceInfo5(self._info["reverse_geolocation"]) + else: + self._place = None + return self._place + + @property + def has_raw(self): + """ returns True if photo has an associated raw image (that is, it's a RAW+JPEG pair), otherwise False """ + return self._info["has_raw"] + + @property + def israw(self): + """ returns True if photo is a raw image. For images with an associated RAW+JPEG pair, see has_raw """ + return "raw-image" in self.uti_original + + @property + def raw_original(self): + """returns True if associated raw image and the raw image is selected in Photos + via "Use RAW as Original " + otherwise returns False""" + return self._info["raw_is_original"] + + @property + def height(self): + """ returns height of the current photo version in pixels """ + return self._info["height"] + + @property + def width(self): + """ returns width of the current photo version in pixels """ + return self._info["width"] + + @property + def orientation(self): + """ returns EXIF orientation of the current photo version as int """ + return self._info["orientation"] + + @property + def original_height(self): + """ returns height of the original photo version in pixels """ + return self._info["original_height"] + + @property + def original_width(self): + """ returns width of the original photo version in pixels """ + return self._info["original_width"] + + @property + def original_orientation(self): + """ returns EXIF orientation of the original photo version as int """ + return self._info["original_orientation"] + + @property + def original_filesize(self): + """ returns filesize of original photo in bytes as int """ + return self._info["original_filesize"] + +
[docs] def render_template( + self, + template_str, + none_str="_", + path_sep=None, + expand_inplace=False, + inplace_sep=None, + filename=False, + dirname=False, + strip=False, + ): + """Renders a template string for PhotoInfo instance using PhotoTemplate + + Args: + template_str: a template string with fields to render + none_str: a str to use if template field renders to None, default is "_". + path_sep: a single character str to use as path separator when joining + fields like folder_album; if not provided, defaults to os.path.sep + expand_inplace: expand multi-valued substitutions in-place as a single string + instead of returning individual strings + inplace_sep: optional string to use as separator between multi-valued keywords + with expand_inplace; default is ',' + filename: if True, template output will be sanitized to produce valid file name + dirname: if True, template output will be sanitized to produce valid directory name + strip: if True, strips leading/trailing white space from resulting template + + Returns: + ([rendered_strings], [unmatched]): tuple of list of rendered strings and list of unmatched template values + """ + template = PhotoTemplate(self, exiftool_path=self._db._exiftool_path) + return template.render( + template_str, + none_str=none_str, + path_sep=path_sep, + expand_inplace=expand_inplace, + inplace_sep=inplace_sep, + filename=filename, + dirname=dirname, + strip=strip, + )
+ + @property + def _longitude(self): + """ Returns longitude, in degrees """ + return self._info["longitude"] + + @property + def _latitude(self): + """ Returns latitude, in degrees """ + return self._info["latitude"] + + def _get_album_uuids(self): + """Return list of album UUIDs this photo is found in + + Filters out albums in the trash and any special album types + + Returns: list of album UUIDs + """ + if self._db._db_version <= _PHOTOS_4_VERSION: + version4 = True + album_kind = [_PHOTOS_4_ALBUM_KIND] + else: + version4 = False + album_kind = [_PHOTOS_5_SHARED_ALBUM_KIND, _PHOTOS_5_ALBUM_KIND] + + album_list = [] + for album in self._info["albums"]: + detail = self._db._dbalbum_details[album] + if ( + detail["kind"] in album_kind + and not detail["intrash"] + and ( + not version4 + # in Photos <= 4, special albums like "printAlbum" have kind _PHOTOS_4_ALBUM_KIND + # but should not be listed here; they can be distinguished by looking + # for folderUuid of _PHOTOS_4_ROOT_FOLDER as opposed to _PHOTOS_4_TOP_LEVEL_ALBUM + or (version4 and detail["folderUuid"] != _PHOTOS_4_ROOT_FOLDER) + ) + ): + album_list.append(album) + return album_list + + def __repr__(self): + return f"osxphotos.{self.__class__.__name__}(db={self._db}, uuid='{self._uuid}', info={self._info})" + + def __str__(self): + """ string representation of PhotoInfo object """ + + date_iso = self.date.isoformat() + date_modified_iso = ( + self.date_modified.isoformat() if self.date_modified else None + ) + exif = str(self.exif_info) if self.exif_info else None + score = str(self.score) if self.score else None + + info = { + "uuid": self.uuid, + "filename": self.filename, + "original_filename": self.original_filename, + "date": date_iso, + "description": self.description, + "title": self.title, + "keywords": self.keywords, + "albums": self.albums, + "persons": self.persons, + "path": self.path, + "ismissing": self.ismissing, + "hasadjustments": self.hasadjustments, + "external_edit": self.external_edit, + "favorite": self.favorite, + "hidden": self.hidden, + "latitude": self._latitude, + "longitude": self._longitude, + "path_edited": self.path_edited, + "shared": self.shared, + "isphoto": self.isphoto, + "ismovie": self.ismovie, + "uti": self.uti, + "burst": self.burst, + "live_photo": self.live_photo, + "path_live_photo": self.path_live_photo, + "iscloudasset": self.iscloudasset, + "incloud": self.incloud, + "date_modified": date_modified_iso, + "portrait": self.portrait, + "screenshot": self.screenshot, + "slow_mo": self.slow_mo, + "time_lapse": self.time_lapse, + "hdr": self.hdr, + "selfie": self.selfie, + "panorama": self.panorama, + "has_raw": self.has_raw, + "uti_raw": self.uti_raw, + "path_raw": self.path_raw, + "place": self.place, + "exif": exif, + "score": score, + "intrash": self.intrash, + "height": self.height, + "width": self.width, + "orientation": self.orientation, + "original_height": self.original_height, + "original_width": self.original_width, + "original_orientation": self.original_orientation, + "original_filesize": self.original_filesize, + } + return yaml.dump(info, sort_keys=False) + +
[docs] def asdict(self): + """ return dict representation """ + + folders = {album.title: album.folder_names for album in self.album_info} + exif = dataclasses.asdict(self.exif_info) if self.exif_info else {} + place = self.place.asdict() if self.place else {} + score = dataclasses.asdict(self.score) if self.score else {} + comments = [comment.asdict() for comment in self.comments] + likes = [like.asdict() for like in self.likes] + faces = [face.asdict() for face in self.face_info] + search_info = self.search_info.asdict() if self.search_info else {} + + return { + "library": self._db._library_path, + "uuid": self.uuid, + "filename": self.filename, + "original_filename": self.original_filename, + "date": self.date, + "description": self.description, + "title": self.title, + "keywords": self.keywords, + "labels": self.labels, + "keywords": self.keywords, + "albums": self.albums, + "folders": folders, + "persons": self.persons, + "faces": faces, + "path": self.path, + "ismissing": self.ismissing, + "hasadjustments": self.hasadjustments, + "external_edit": self.external_edit, + "favorite": self.favorite, + "hidden": self.hidden, + "latitude": self._latitude, + "longitude": self._longitude, + "path_edited": self.path_edited, + "shared": self.shared, + "isphoto": self.isphoto, + "ismovie": self.ismovie, + "uti": self.uti, + "uti_original": self.uti_original, + "burst": self.burst, + "live_photo": self.live_photo, + "path_live_photo": self.path_live_photo, + "iscloudasset": self.iscloudasset, + "incloud": self.incloud, + "isreference": self.isreference, + "date_modified": self.date_modified, + "portrait": self.portrait, + "screenshot": self.screenshot, + "slow_mo": self.slow_mo, + "time_lapse": self.time_lapse, + "hdr": self.hdr, + "selfie": self.selfie, + "panorama": self.panorama, + "has_raw": self.has_raw, + "israw": self.israw, + "raw_original": self.raw_original, + "uti_raw": self.uti_raw, + "path_raw": self.path_raw, + "place": place, + "exif": exif, + "score": score, + "intrash": self.intrash, + "height": self.height, + "width": self.width, + "orientation": self.orientation, + "original_height": self.original_height, + "original_width": self.original_width, + "original_orientation": self.original_orientation, + "original_filesize": self.original_filesize, + "comments": comments, + "likes": likes, + "search_info": search_info, + }
+ +
[docs] def json(self): + """ Return JSON representation """ + + def default(o): + if isinstance(o, (datetime.date, datetime.datetime)): + return o.isoformat() + + return json.dumps(self.asdict(), sort_keys=True, default=default)
+ + def __eq__(self, other): + """ Compare two PhotoInfo objects for equality """ + # Can't just compare the two __dicts__ because some methods (like albums) + # memoize their value once called in an instance variable (e.g. self._albums) + if isinstance(other, self.__class__): + return ( + self._db.db_path == other._db.db_path + and self.uuid == other.uuid + and self._info == other._info + ) + return False + + def __ne__(self, other): + """ Compare two PhotoInfo objects for inequality """ + return not self.__eq__(other)
+
+ +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/build/html/_modules/osxphotos/photosdb/photosdb.html b/docs/build/html/_modules/osxphotos/photosdb/photosdb.html new file mode 100644 index 00000000..a7608f22 --- /dev/null +++ b/docs/build/html/_modules/osxphotos/photosdb/photosdb.html @@ -0,0 +1,2963 @@ + + + + + + + + osxphotos.photosdb.photosdb — osxphotos 0.40.4 documentation + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Source code for osxphotos.photosdb.photosdb

+"""
+PhotosDB class
+Processes a Photos.app library database to extract information about photos
+"""
+
+import logging
+import os
+import os.path
+import pathlib
+import platform
+import sys
+import tempfile
+from datetime import datetime, timedelta, timezone
+from pprint import pformat
+
+from .._constants import (
+    _DB_TABLE_NAMES,
+    _MOVIE_TYPE,
+    _PHOTO_TYPE,
+    _PHOTOS_3_VERSION,
+    _PHOTOS_4_ALBUM_KIND,
+    _PHOTOS_4_ROOT_FOLDER,
+    _PHOTOS_4_TOP_LEVEL_ALBUM,
+    _PHOTOS_4_VERSION,
+    _PHOTOS_5_ALBUM_KIND,
+    _PHOTOS_5_FOLDER_KIND,
+    _PHOTOS_5_IMPORT_SESSION_ALBUM_KIND,
+    _PHOTOS_5_ROOT_FOLDER_KIND,
+    _PHOTOS_5_SHARED_ALBUM_KIND,
+    _TESTED_OS_VERSIONS,
+    _UNKNOWN_PERSON,
+    TIME_DELTA,
+)
+from .._version import __version__
+from ..albuminfo import AlbumInfo, FolderInfo, ImportInfo
+from ..datetime_utils import datetime_has_tz, datetime_naive_to_local
+from ..fileutil import FileUtil
+from ..personinfo import PersonInfo
+from ..photoinfo import PhotoInfo
+from ..utils import (
+    _check_file_exists,
+    _db_is_locked,
+    _debug,
+    _get_os_version,
+    _open_sql_file,
+    get_last_library_path,
+    noop,
+    normalize_unicode,
+)
+from .photosdb_utils import get_db_model_version, get_db_version
+
+# TODO: Add test for imageTimeZoneOffsetSeconds = None
+# TODO: Add test for __str__
+# TODO: Add special albums and magic albums
+
+
+
[docs]class PhotosDB: + """ Processes a Photos.app library database to extract information about photos """ + + # import additional methods + from ._photosdb_process_exif import _process_exifinfo + from ._photosdb_process_faceinfo import _process_faceinfo + from ._photosdb_process_searchinfo import ( + _process_searchinfo, + labels, + labels_normalized, + labels_as_dict, + labels_normalized_as_dict, + ) + from ._photosdb_process_scoreinfo import _process_scoreinfo + from ._photosdb_process_comments import _process_comments + + def __init__(self, dbfile=None, verbose=None, exiftool=None): + """ Create a new PhotosDB object. + + Args: + dbfile: specify full path to photos library or photos.db; if None, will attempt to locate last library opened by Photos. + verbose: optional callable function to use for printing verbose text during processing; if None (default), does not print output. + exiftool: optional path to exiftool for methods that require this (e.g. PhotoInfo.exiftool); if not provided, will search PATH + + Raises: + FileNotFoundError if dbfile is not a valid Photos library. + TypeError if verbose is not None and not callable. + """ + + # Check OS version + system = platform.system() + (ver, major, _) = _get_os_version() + if system != "Darwin" or ((ver, major) not in _TESTED_OS_VERSIONS): + logging.warning( + f"WARNING: This module has only been tested with macOS versions " + f"[{', '.join(f'{v}.{m}' for (v, m) in _TESTED_OS_VERSIONS)}]: " + f"you have {system}, OS version: {ver}.{major}" + ) + + if verbose is None: + verbose = noop + elif not callable(verbose): + raise TypeError("verbose must be callable") + self._verbose = verbose + + # enable beta features + self._beta = False + + self._exiftool_path = exiftool + + # create a temporary directory + # tempfile.TemporaryDirectory gets cleaned up when the object does + self._tempdir = tempfile.TemporaryDirectory(prefix="osxphotos_") + self._tempdir_name = self._tempdir.name + + # set up the data structures used to store all the Photo database info + + # TODO: I don't think these keywords flags are actually used + # if True, will treat persons as keywords when exporting metadata + self.use_persons_as_keywords = False + + # if True, will treat albums as keywords when exporting metadata + self.use_albums_as_keywords = False + + # Path to the Photos library database file + # photos.db in the photos library database/ directory + self._dbfile = None + + # the actual file with library data + # in Photos 5 this is Photos.sqlite instead of photos.db + self._dbfile_actual = None + + # Dict with information about all photos by uuid + # This is the "master" data structure, built by process_database + # key is a photo UUID, value is a dictionary with all the information + # known about a photo + # this is built by joining data from multiple queries against the photos database + # several of the keys in the info dictionary point to other data structures described below + # e.g. self._dbphotos[uuid]["keywords"] = self._dbkeywords_uuid[uuid] + # self._dbphotos[uuid]["persons"] = self._dbfaces_uuid[uuid] + # self._dbphotos[uuid]["albums"] = self._dbalbums_uuid[uuid] + self._dbphotos = {} + + # Dict with information about all burst photos by burst uuid + # key is UUID of the burst set, value is a set of photo UUIDs in the burst set + # e.g. {'BD94B7C0-2EB8-43DB-98B4-3B8E9653C255': {'8B386814-CA8A-42AA-BCA8-97C1AA746D8A', '52B95550-DE4A-44DD-9E67-89E979F2E97F'}} + self._dbphotos_burst = {} + + # Dict with additional information from RKMaster + # key is UUID from RKMaster, value is dict with info related to each master + # currently used to get information on RAW images + self._dbphotos_master = {} + + # Dict with information about all persons by person PK + # key is person PK, value is dict with info about each person + # e.g. {3: {"pk": 3, "fullname": "Maria Smith"...}} + self._dbpersons_pk = {} + + # Dict with information about all persons by person fullname + # key is person PK, value is list of person PKs with fullname + # there may be more than one person PK with the same fullname + # e.g. {"Maria Smith": [1, 2]} + self._dbpersons_fullname = {} + + # Dict with information about all persons/photos by uuid + # key is photo UUID, value is list of person primary keys of persons in the photo + # Note: Photos 5 identifies faces even if not given a name + # and those are labeled by process_database as _UNKNOWN_ + # e.g. {'1EB2B765-0765-43BA-A90C-0D0580E6172C': [1, 3, 5]} + self._dbfaces_uuid = {} + + # Dict with information about detected faces by person primary key + # key is person pk, value is list of photo UUIDs + # e.g. {3: ['E9BC5C36-7CD1-40A1-A72B-8B8FAC227D51']} + self._dbfaces_pk = {} + + # Dict with information about all keywords/photos by uuid + # key is photo uuid and value is list of keywords + # e.g. {'1EB2B765-0765-43BA-A90C-0D0580E6172C': ['Kids']} + self._dbkeywords_uuid = {} + + # Dict with information about all keywords/photos by keyword + # key is keyword and value is list of photo UUIDs that have that keyword + # e.g. {'England': ['DC99FBDD-7A52-4100-A5BB-344131646C30']} + self._dbkeywords_keyword = {} + + # Dict with information about all albums/photos by uuid + # key is photo UUID, value is list of album UUIDs the photo is contained in + # e.g. {'1EB2B765-0765-43BA-A90C-0D0580E6172C': ['0C514A98-7B77-4E4F-801B-364B7B65EAFA']} + self._dbalbums_uuid = {} + + # Dict with information about all albums/photos by primary key in the album database + # key is album pk, value is album uuid + # e.g. {'43': '0C514A98-7B77-4E4F-801B-364B7B65EAFA'} + # specific to Photos versions >= 5 + self._dbalbums_pk = {} + + # Dict with information about all albums/photos by album + # key is album UUID, value is list of tuples of (photo UUID, sort order) contained in that album + # e.g. {'0C514A98-7B77-4E4F-801B-364B7B65EAFA': [('1EB2B765-0765-43BA-A90C-0D0580E6172C', 1024)]} + self._dbalbums_album = {} + + # Dict with information about album details + # key is album UUID, value is a dict with some additional details + # (mostly about cloud status) of the album + # e.g. {'0C514A98-7B77-4E4F-801B-364B7B65EAFA': {'cloudidentifier': None, + # 'cloudlibrarystate': None, 'cloudlocalstate': 0, 'cloudownderlastname': None, + # 'cloudownerfirstname': None, 'cloudownerhashedpersonid': None, 'title': 'Pumpkin Farm'}} + self._dbalbum_details = {} + + # Dict with information about album titles + # key is title of album, value is list of album UUIDs with that title + # (It's possible to have more than one album with the same title) + # e.g. {'Pumpkin Farm': ['0C514A98-7B77-4E4F-801B-364B7B65EAFA']} + self._dbalbum_titles = {} + + # Dict with information about all the file system volumes/photos by uuid + # key is volume UUID, value is name of file system volume + # e.g. {'8A0B2944-7B09-4D06-9AC3-4B0BF3F363F1': 'MacBook Mojave'} + # Used to find path of photos imported but not copied to the Photos library + self._dbvolumes = {} + + # Dict with information about parent folders for folders and albums + # key is album or folder UUID and value is list of UUIDs of parent folder + # e.g. {'0C514A98-7B77-4E4F-801B-364B7B65EAFA': ['92D68107-B6C7-453B-96D2-97B0F26D5B8B'],} + self._dbalbum_parent_folders = {} + + # Dict with information about folder hierarchy for each album / folder + # key is uuid of album / folder, value is dict with uuid of descendant folder / album + # structure is recursive as a descendant may itself have descendants + # e.g. {'AA4145F5-098C-496E-9197-B7584958FF9B': {'99D24D3E-59E7-465F-B386-A48A94B00BC1': {'F2246D82-1A12-4994-9654-3DC6FE38A7A8': None}}, } + self._dbalbum_folders = {} + + # Dict with information about folders + self._dbfolder_details = {} + + # Will hold the primary key of root folder + self._folder_root_pk = None + + if _debug(): + logging.debug(f"dbfile = {dbfile}") + + if dbfile is None: + dbfile = get_last_library_path() + if dbfile is None: + # get_last_library_path must have failed to find library + raise FileNotFoundError("Could not get path to photo library database") + + if os.path.isdir(dbfile): + # passed a directory, assume it's a photoslibrary + dbfile = os.path.join(dbfile, "database/photos.db") + + # if get here, should have a dbfile path; make sure it exists + if not _check_file_exists(dbfile): + raise FileNotFoundError(f"dbfile {dbfile} does not exist", dbfile) + + if _debug(): + logging.debug(f"dbfile = {dbfile}") + + # init database names + # _tmp_db is the file that will processed by _process_database4/5 + # assume _tmp_db will be _dbfile or _dbfile_actual based on Photos version + # unless DB is locked, in which case _tmp_db will point to a temporary copy + # if Photos <=4, _dbfile = _dbfile_actual = photos.db + # if Photos >= 5, _dbfile = photos.db, from which we get DB version but the actual + # photos data is in Photos.sqlite + # In either case, a temporary copy will be made if the DB is locked by Photos + # or photosanalysisd + self._dbfile = self._dbfile_actual = self._tmp_db = os.path.abspath(dbfile) + + verbose(f"Processing database {self._dbfile}") + + # if database is exclusively locked, make a copy of it and use the copy + # Photos maintains an exclusive lock on the database file while Photos is open + # photoanalysisd sometimes maintains this lock even after Photos is closed + # In those cases, make a temp copy of the file for sqlite3 to read + if _db_is_locked(self._dbfile): + verbose(f"Database locked, creating temporary copy.") + self._tmp_db = self._copy_db_file(self._dbfile) + + self._db_version = get_db_version(self._tmp_db) + + # If Photos >= 5, actual data isn't in photos.db but in Photos.sqlite + if int(self._db_version) > int(_PHOTOS_4_VERSION): + dbpath = pathlib.Path(self._dbfile).parent + dbfile = dbpath / "Photos.sqlite" + if not _check_file_exists(dbfile): + raise FileNotFoundError(f"dbfile {dbfile} does not exist", dbfile) + else: + self._dbfile_actual = self._tmp_db = dbfile + verbose(f"Processing database {self._dbfile_actual}") + # if database is exclusively locked, make a copy of it and use the copy + if _db_is_locked(self._dbfile_actual): + verbose(f"Database locked, creating temporary copy.") + self._tmp_db = self._copy_db_file(self._dbfile_actual) + + if _debug(): + logging.debug( + f"_dbfile = {self._dbfile}, _dbfile_actual = {self._dbfile_actual}" + ) + + library_path = os.path.dirname(os.path.abspath(dbfile)) + (library_path, _) = os.path.split(library_path) # drop /database from path + self._library_path = library_path + if int(self._db_version) <= int(_PHOTOS_4_VERSION): + masters_path = os.path.join(library_path, "Masters") + self._masters_path = masters_path + else: + masters_path = os.path.join(library_path, "originals") + self._masters_path = masters_path + + if _debug(): + logging.debug(f"library = {library_path}, masters = {masters_path}") + + if int(self._db_version) <= int(_PHOTOS_4_VERSION): + self._process_database4() + else: + self._process_database5() + + @property + def keywords_as_dict(self): + """ return keywords as dict of keyword, count in reverse sorted order (descending) """ + keywords = { + k: len(self._dbkeywords_keyword[k]) for k in self._dbkeywords_keyword.keys() + } + + keywords = dict(sorted(keywords.items(), key=lambda kv: kv[1], reverse=True)) + return keywords + + @property + def persons_as_dict(self): + """ return persons as dict of person, count in reverse sorted order (descending) """ + persons = {} + for pk in self._dbfaces_pk: + fullname = self._dbpersons_pk[pk]["fullname"] + try: + persons[fullname] += len(self._dbfaces_pk[pk]) + except KeyError: + persons[fullname] = len(self._dbfaces_pk[pk]) + persons = dict(sorted(persons.items(), key=lambda kv: kv[1], reverse=True)) + return persons + + @property + def albums_as_dict(self): + """ return albums as dict of albums, count in reverse sorted order (descending) """ + albums = {} + album_keys = self._get_album_uuids(shared=False) + for album in album_keys: + title = self._dbalbum_details[album]["title"] + if album in self._dbalbums_album: + try: + albums[title] += len(self._dbalbums_album[album]) + except KeyError: + albums[title] = len(self._dbalbums_album[album]) + else: + albums[title] = 0 # empty album + albums = dict(sorted(albums.items(), key=lambda kv: kv[1], reverse=True)) + return albums + + @property + def albums_shared_as_dict(self): + """ returns shared albums as dict of albums, count in reverse sorted order (descending) + valid only on Photos 5; on Photos <= 4, prints warning and returns empty dict """ + + albums = {} + album_keys = self._get_album_uuids(shared=True) + for album in album_keys: + title = self._dbalbum_details[album]["title"] + if album in self._dbalbums_album: + try: + albums[title] += len(self._dbalbums_album[album]) + except KeyError: + albums[title] = len(self._dbalbums_album[album]) + else: + albums[title] = 0 # empty album + albums = dict(sorted(albums.items(), key=lambda kv: kv[1], reverse=True)) + return albums + + @property + def keywords(self): + """ return list of keywords found in photos database """ + keywords = self._dbkeywords_keyword.keys() + return list(keywords) + + @property + def persons(self): + """ return list of persons found in photos database """ + persons = {self._dbpersons_pk[k]["fullname"] for k in self._dbfaces_pk} + return list(persons) + + @property + def person_info(self): + """ return list of PersonInfo objects for each person in the photos database """ + try: + return self._person_info + except AttributeError: + self._person_info = [ + PersonInfo(db=self, pk=pk) for pk in self._dbpersons_pk + ] + return self._person_info + + @property + def folder_info(self): + """ return list FolderInfo objects representing top-level folders in the photos database """ + if self._db_version <= _PHOTOS_4_VERSION: + folders = [ + FolderInfo(db=self, uuid=folder) + for folder, detail in self._dbfolder_details.items() + if not detail["intrash"] + and not detail["isMagic"] + and detail["parentFolderUuid"] == _PHOTOS_4_TOP_LEVEL_ALBUM + ] + else: + folders = [ + FolderInfo(db=self, uuid=album) + for album, detail in self._dbalbum_details.items() + if not detail["intrash"] + and detail["kind"] == _PHOTOS_5_FOLDER_KIND + and detail["parentfolder"] == self._folder_root_pk + ] + return folders + + @property + def folders(self): + """ return list of top-level folder names in the photos database """ + if self._db_version <= _PHOTOS_4_VERSION: + folder_names = [ + folder["name"] + for folder in self._dbfolder_details.values() + if not folder["intrash"] + and not folder["isMagic"] + and folder["parentFolderUuid"] == _PHOTOS_4_TOP_LEVEL_ALBUM + ] + else: + folder_names = [ + detail["title"] + for detail in self._dbalbum_details.values() + if not detail["intrash"] + and detail["kind"] == _PHOTOS_5_FOLDER_KIND + and detail["parentfolder"] == self._folder_root_pk + ] + return folder_names + + @property + def album_info(self): + """ return list of AlbumInfo objects for each album in the photos database """ + try: + return self._album_info + except AttributeError: + self._album_info = [ + AlbumInfo(db=self, uuid=album) + for album in self._get_album_uuids(shared=False) + ] + return self._album_info + + @property + def album_info_shared(self): + """ return list of AlbumInfo objects for each shared album in the photos database + only valid for Photos 5; on Photos <= 4, prints warning and returns empty list """ + # if _dbalbum_details[key]["cloudownerhashedpersonid"] is not None, then it's a shared album + try: + return self._album_info_shared + except AttributeError: + self._album_info_shared = [ + AlbumInfo(db=self, uuid=album) + for album in self._get_album_uuids(shared=True) + ] + return self._album_info_shared + + @property + def albums(self): + """ return list of albums found in photos database """ + + # Could be more than one album with same name + # Right now, they are treated as same album and photos are combined from albums with same name + + try: + return self._albums + except AttributeError: + self._albums = self._get_albums(shared=False) + return self._albums + + @property + def albums_shared(self): + """ return list of shared albums found in photos database + only valid for Photos 5; on Photos <= 4, prints warning and returns empty list """ + + # Could be more than one album with same name + # Right now, they are treated as same album and photos are combined from albums with same name + + # if _dbalbum_details[key]["cloudownerhashedpersonid"] is not None, then it's a shared album + + try: + return self._albums_shared + except AttributeError: + self._albums_shared = self._get_albums(shared=True) + return self._albums_shared + + @property + def import_info(self): + """ return list of ImportInfo objects for each import session in the database """ + try: + return self._import_info + except AttributeError: + self._import_info = [ + ImportInfo(db=self, uuid=album) + for album in self._get_album_uuids(import_session=True) + ] + return self._import_info + + @property + def db_version(self): + """ return the database version as stored in LiGlobals table """ + return self._db_version + + @property + def db_path(self): + """ returns path to the Photos library database PhotosDB was initialized with """ + return os.path.abspath(self._dbfile) + + @property + def library_path(self): + """ returns path to the Photos library PhotosDB was initialized with """ + return self._library_path + +
[docs] def get_db_connection(self): + """ Get connection to the working copy of the Photos database + + Returns: + tuple of (connection, cursor) to sqlite3 database + """ + return _open_sql_file(self._tmp_db)
+ + def _copy_db_file(self, fname): + """ copies the sqlite database file to a temp file """ + """ returns the name of the temp file """ + """ If sqlite shared memory and write-ahead log files exist, those are copied too """ + # required because python's sqlite3 implementation can't read a locked file + # _, suffix = os.path.splitext(fname) + dest_name = dest_path = "" + try: + dest_name = pathlib.Path(fname).name + dest_path = os.path.join(self._tempdir_name, dest_name) + FileUtil.copy(fname, dest_path) + # copy write-ahead log and shared memory files (-wal and -shm) files if they exist + if os.path.exists(f"{fname}-wal"): + FileUtil.copy(f"{fname}-wal", f"{dest_path}-wal") + if os.path.exists(f"{fname}-shm"): + FileUtil.copy(f"{fname}-shm", f"{dest_path}-shm") + except: + print(f"Error copying{fname} to {dest_path}", file=sys.stderr) + raise Exception + + if _debug(): + logging.debug(dest_path) + + return dest_path + + # NOTE: This method seems to cause problems with applescript + # Bummer...would'be been nice to avoid copying the DB + # def _link_db_file(self, fname): + # """ links the sqlite database file to a temp file """ + # """ returns the name of the temp file """ + # """ If sqlite shared memory and write-ahead log files exist, those are copied too """ + # # required because python's sqlite3 implementation can't read a locked file + # # _, suffix = os.path.splitext(fname) + # dest_name = dest_path = "" + # try: + # dest_name = pathlib.Path(fname).name + # dest_path = os.path.join(self._tempdir_name, dest_name) + # FileUtil.hardlink(fname, dest_path) + # # link write-ahead log and shared memory files (-wal and -shm) files if they exist + # if os.path.exists(f"{fname}-wal"): + # FileUtil.hardlink(f"{fname}-wal", f"{dest_path}-wal") + # if os.path.exists(f"{fname}-shm"): + # FileUtil.hardlink(f"{fname}-shm", f"{dest_path}-shm") + # except: + # print("Error linking " + fname + " to " + dest_path, file=sys.stderr) + # raise Exception + + # if _debug(): + # logging.debug(dest_path) + + # return dest_path + + def _process_database4(self): + """ process the Photos database to extract info + works on Photos version <= 4.0 """ + + verbose = self._verbose + verbose("Processing database.") + verbose(f"Database version: {self._db_version}.") + + (conn, c) = _open_sql_file(self._tmp_db) + + # get info to associate persons with photos + # then get detected faces in each photo and link to persons + verbose("Processing persons in photos.") + c.execute( + """ SELECT + RKPerson.modelID, + RKPerson.uuid, + RKPerson.name, + RKPerson.faceCount, + RKPerson.displayName, + RKPerson.representativeFaceId + FROM RKPerson + """ + ) + + # 0 RKPerson.modelID, + # 1 RKPerson.uuid, + # 2 RKPerson.name, + # 3 RKPerson.faceCount, + # 4 RKPerson.displayName + # 5 RKPerson.representativeFaceId + + for person in c: + pk = person[0] + fullname = person[2] if person[2] is not None else _UNKNOWN_PERSON + self._dbpersons_pk[pk] = { + "pk": pk, + "uuid": person[1], + "fullname": fullname, + "facecount": person[3], + "keyface": person[5], + "displayname": person[4], + "photo_uuid": None, + "keyface_uuid": None, + } + try: + self._dbpersons_fullname[fullname].append(pk) + except KeyError: + self._dbpersons_fullname[fullname] = [pk] + + # get info on key face + c.execute( + """ SELECT + RKPerson.modelID, + RKPerson.representativeFaceId, + RKVersion.uuid, + RKFace.uuid + FROM RKPerson, RKFace, RKVersion + WHERE + RKFace.modelId = RKPerson.representativeFaceId AND + RKVersion.modelId = RKFace.ImageModelId + """ + ) + + # 0 RKPerson.modelID, + # 1 RKPerson.representativeFaceId + # 2 RKVersion.uuid, + # 3 RKFace.uuid + + for person in c: + pk = person[0] + try: + self._dbpersons_pk[pk]["photo_uuid"] = person[2] + self._dbpersons_pk[pk]["keyface_uuid"] = person[3] + except KeyError: + logging.debug(f"Unexpected KeyError _dbpersons_pk[{pk}]") + + # get information on detected faces + verbose("Processing detected faces in photos.") + c.execute( + """ SELECT + RKPerson.modelID, + RKVersion.uuid + FROM + RKFace, RKPerson, RKVersion, RKMaster + WHERE + RKFace.personID = RKperson.modelID AND + RKVersion.modelId = RKFace.ImageModelId AND + RKVersion.masterUuid = RKMaster.uuid + """ + ) + + # 0 RKPerson.modelID + # 1 RKVersion.uuid + + for face in c: + pk = face[0] + uuid = face[1] + try: + self._dbfaces_uuid[uuid].append(pk) + except KeyError: + self._dbfaces_uuid[uuid] = [pk] + + try: + self._dbfaces_pk[pk].append(uuid) + except KeyError: + self._dbfaces_pk[pk] = [uuid] + + if _debug(): + logging.debug(f"Finished walking through persons") + logging.debug(pformat(self._dbpersons_pk)) + logging.debug(pformat(self._dbpersons_fullname)) + logging.debug(pformat(self._dbfaces_pk)) + logging.debug(pformat(self._dbfaces_uuid)) + + # Get info on albums + verbose("Processing albums.") + c.execute( + """ SELECT + RKAlbum.uuid, + RKVersion.uuid, + RKCustomSortOrder.orderNumber + FROM RKVersion + JOIN RKCustomSortOrder on RKCustomSortOrder.objectUuid = RKVersion.uuid + JOIN RKAlbum on RKAlbum.uuid = RKCustomSortOrder.containerUuid + """ + ) + + # 0 RKAlbum.uuid, + # 1 RKVersion.uuid, + # 2 RKCustomSortOrder.orderNumber + + for album in c: + # store by uuid in _dbalbums_uuid and by album in _dbalbums_album + album_uuid = album[0] + photo_uuid = album[1] + sort_order = album[2] + try: + self._dbalbums_uuid[photo_uuid].append(album_uuid) + except KeyError: + self._dbalbums_uuid[photo_uuid] = [album_uuid] + + try: + self._dbalbums_album[album_uuid].append((photo_uuid, sort_order)) + except KeyError: + self._dbalbums_album[album_uuid] = [(photo_uuid, sort_order)] + + # now get additional details about albums + c.execute( + """ SELECT + uuid, + name, + cloudLibraryState, + cloudIdentifier, + isInTrash, + folderUuid, + albumType, + albumSubclass, + createDate + FROM RKAlbum """ + ) + + # Order of results + # 0: uuid + # 1: name + # 2: cloudLibraryState + # 3: cloudIdentifier + # 4: isInTrash + # 5: folderUuid + # 6: albumType + # 7: albumSubclass -- if 3, normal user album + # 8: createDate + + for album in c: + self._dbalbum_details[album[0]] = { + "_uuid": album[0], + "title": normalize_unicode(album[1]), + "cloudlibrarystate": album[2], + "cloudidentifier": album[3], + "intrash": False if album[4] == 0 else True, + "cloudlocalstate": None, # Photos 5 + "cloudownerfirstname": None, # Photos 5 + "cloudownderlastname": None, # Photos 5 + "cloudownerhashedpersonid": None, # Photos 5 + "folderUuid": album[5], + "albumType": album[6], + "albumSubclass": album[7], + # for compatability with Photos 5 where album kind is ZKIND + "kind": album[7], + "creation_date": album[8], + "start_date": None, # Photos 5 only + "end_date": None, # Photos 5 only + } + + # get details about folders + c.execute( + """ SELECT + uuid, + modelId, + name, + isMagic, + isInTrash, + folderType, + parentFolderUuid, + folderPath + FROM RKFolder """ + ) + + # Order of results + # 0 uuid, + # 1 modelId, + # 2 name, + # 3 isMagic, + # 4 isInTrash, + # 5 folderType, + # 6 parentFolderUuid, + # 7 folderPath + + for row in c: + uuid = row[0] + self._dbfolder_details[uuid] = { + "_uuid": row[0], + "modelId": row[1], + "name": normalize_unicode(row[2]), + "isMagic": row[3], + "intrash": row[4], + "folderType": row[5], + "parentFolderUuid": row[6], + "folderPath": row[7], + } + + # build _dbalbum_folders in form uuid: [parent uuid] to be consistent with _process_database5 + for album, details in self._dbalbum_details.items(): + # album can be in a single folder + parent = details["folderUuid"] + self._dbalbum_parent_folders[album] = [parent] + + # build folder hierarchy + for album, details in self._dbalbum_details.items(): + parent_folder = details["folderUuid"] + if details[ + "albumSubclass" + ] == _PHOTOS_4_ALBUM_KIND and parent_folder not in [ + _PHOTOS_4_TOP_LEVEL_ALBUM + ]: + folder_hierarchy = self._build_album_folder_hierarchy_4(parent_folder) + self._dbalbum_folders[album] = folder_hierarchy + else: + self._dbalbum_folders[album] = {} + + if _debug(): + logging.debug(f"Finished walking through albums") + logging.debug(pformat(self._dbalbums_album)) + logging.debug(pformat(self._dbalbums_uuid)) + logging.debug(pformat(self._dbalbum_details)) + logging.debug(pformat(self._dbalbum_folders)) + logging.debug(pformat(self._dbfolder_details)) + + # Get info on keywords + verbose("Processing keywords.") + c.execute( + """ SELECT + RKKeyword.name, + RKVersion.uuid, + RKMaster.uuid + FROM + RKKeyword, RKKeywordForVersion, RKVersion, RKMaster + WHERE + RKKeyword.modelId = RKKeyWordForVersion.keywordID AND + RKVersion.modelID = RKKeywordForVersion.versionID AND + RKMaster.uuid = RKVersion.masterUuid + """ + ) + for keyword in c: + if not keyword[1] in self._dbkeywords_uuid: + self._dbkeywords_uuid[keyword[1]] = [] + if not keyword[0] in self._dbkeywords_keyword: + self._dbkeywords_keyword[keyword[0]] = [] + self._dbkeywords_uuid[keyword[1]].append(keyword[0]) + self._dbkeywords_keyword[keyword[0]].append(keyword[1]) + + # Get info on disk volumes + c.execute("select RKVolume.modelId, RKVolume.name from RKVolume") + for vol in c: + self._dbvolumes[vol[0]] = vol[1] + + # Get photo details + verbose("Processing photo details.") + if self._db_version < _PHOTOS_3_VERSION: + # Photos < 3.0 doesn't have RKVersion.selfPortrait (selfie) + c.execute( + """ SELECT RKVersion.uuid, RKVersion.modelId, RKVersion.masterUuid, RKVersion.filename, + RKVersion.lastmodifieddate, RKVersion.imageDate, RKVersion.mainRating, + RKVersion.hasAdjustments, RKVersion.hasKeywords, RKVersion.imageTimeZoneOffsetSeconds, + RKMaster.volumeId, RKMaster.imagePath, RKVersion.extendedDescription, RKVersion.name, + RKMaster.isMissing, RKMaster.originalFileName, RKVersion.isFavorite, RKVersion.isHidden, + RKVersion.latitude, RKVersion.longitude, + RKVersion.adjustmentUuid, RKVersion.type, RKMaster.UTI, + RKVersion.burstUuid, RKVersion.burstPickType, + RKVersion.specialType, RKMaster.modelID, null, RKVersion.momentUuid, + RKVersion.rawMasterUuid, + RKVersion.nonRawMasterUuid, + RKMaster.alternateMasterUuid, + RKVersion.isInTrash, + RKVersion.processedHeight, + RKVersion.processedWidth, + RKVersion.orientation, + RKMaster.height, + RKMaster.width, + RKMaster.orientation, + RKMaster.fileSize, + RKVersion.subType, + RKVersion.inTrashDate, + RKVersion.showInLibrary, + RKMaster.fileIsReference + FROM RKVersion, RKMaster + WHERE RKVersion.masterUuid = RKMaster.uuid""" + ) + else: + c.execute( + """ SELECT RKVersion.uuid, RKVersion.modelId, RKVersion.masterUuid, RKVersion.filename, + RKVersion.lastmodifieddate, RKVersion.imageDate, RKVersion.mainRating, + RKVersion.hasAdjustments, RKVersion.hasKeywords, RKVersion.imageTimeZoneOffsetSeconds, + RKMaster.volumeId, RKMaster.imagePath, RKVersion.extendedDescription, RKVersion.name, + RKMaster.isMissing, RKMaster.originalFileName, RKVersion.isFavorite, RKVersion.isHidden, + RKVersion.latitude, RKVersion.longitude, + RKVersion.adjustmentUuid, RKVersion.type, RKMaster.UTI, + RKVersion.burstUuid, RKVersion.burstPickType, + RKVersion.specialType, RKMaster.modelID, + RKVersion.selfPortrait, + RKVersion.momentUuid, + RKVersion.rawMasterUuid, + RKVersion.nonRawMasterUuid, + RKMaster.alternateMasterUuid, + RKVersion.isInTrash, + RKVersion.processedHeight, + RKVersion.processedWidth, + RKVersion.orientation, + RKMaster.height, + RKMaster.width, + RKMaster.orientation, + RKMaster.originalFileSize, + RKVersion.subType, + RKVersion.inTrashDate, + RKVersion.showInLibrary, + RKMaster.fileIsReference + FROM RKVersion, RKMaster + WHERE RKVersion.masterUuid = RKMaster.uuid""" + ) + + # order of results + # 0 RKVersion.uuid + # 1 RKVersion.modelId + # 2 RKVersion.masterUuid + # 3 RKVersion.filename + # 4 RKVersion.lastmodifieddate + # 5 RKVersion.imageDate + # 6 RKVersion.mainRating + # 7 RKVersion.hasAdjustments + # 8 RKVersion.hasKeywords + # 9 RKVersion.imageTimeZoneOffsetSeconds + # 10 RKMaster.volumeId + # 11 RKMaster.imagePath + # 12 RKVersion.extendedDescription + # 13 RKVersion.name + # 14 RKMaster.isMissing + # 15 RKMaster.originalFileName + # 16 RKVersion.isFavorite + # 17 RKVersion.isHidden + # 18 RKVersion.latitude + # 19 RKVersion.longitude + # 20 RKVersion.adjustmentUuid + # 21 RKVersion.type + # 22 RKMaster.UTI + # 23 RKVersion.burstUuid + # 24 RKVersion.burstPickType + # 25 RKVersion.specialType + # 26 RKMaster.modelID + # 27 RKVersion.selfPortrait -- 1 if selfie, Photos >= 3, not present for Photos < 3 + # 28 RKVersion.momentID (# 27 for Photos < 3) + # 29 RKVersion.rawMasterUuid, -- UUID of RAW master + # 30 RKVersion.nonRawMasterUuid, -- UUID of non-RAW master + # 31 RKMaster.alternateMasterUuid -- UUID of alternate master (will be RAW master for JPEG and JPEG master for RAW) + # 32 RKVersion.isInTrash + # 33 RKVersion.processedHeight, + # 34 RKVersion.processedWidth, + # 35 RKVersion.orientation, + # 36 RKMaster.height, + # 37 RKMaster.width, + # 38 RKMaster.orientation, + # 39 RKMaster.originalFileSize + # 40 RKVersion.subType + # 41 RKVersion.inTrashDate + # 42 RKVersion.showInLibrary -- is item visible in library (e.g. non-selected burst images are not visible) + # 43 RKMaster.fileIsReference -- file is reference (imported without copying to Photos library) + + for row in c: + uuid = row[0] + if _debug(): + logging.debug(f"uuid = '{uuid}, master = '{row[2]}") + self._dbphotos[uuid] = {} + self._dbphotos[uuid]["_uuid"] = uuid # stored here for easier debugging + self._dbphotos[uuid]["modelID"] = row[1] + self._dbphotos[uuid]["masterUuid"] = row[2] + self._dbphotos[uuid]["filename"] = row[3] + + # There are sometimes negative values for lastmodifieddate in the database + # I don't know what these mean but they will raise exception in datetime if + # not accounted for + self._dbphotos[uuid]["lastmodifieddate_timestamp"] = row[4] + try: + self._dbphotos[uuid]["lastmodifieddate"] = datetime.fromtimestamp( + row[4] + TIME_DELTA + ) + except ValueError: + self._dbphotos[uuid]["lastmodifieddate"] = None + except TypeError: + self._dbphotos[uuid]["lastmodifieddate"] = None + + self._dbphotos[uuid]["imageTimeZoneOffsetSeconds"] = row[9] + self._dbphotos[uuid]["imageDate_timestamp"] = row[5] + + try: + imagedate = datetime.fromtimestamp(row[5] + TIME_DELTA) + seconds = self._dbphotos[uuid]["imageTimeZoneOffsetSeconds"] or 0 + delta = timedelta(seconds=seconds) + tz = timezone(delta) + self._dbphotos[uuid]["imageDate"] = imagedate.astimezone(tz=tz) + except ValueError: + # sometimes imageDate is invalid so use 1 Jan 1970 in UTC as image date + imagedate = datetime(1970, 1, 1) + tz = timezone(timedelta(0)) + self._dbphotos[uuid]["imageDate"] = imagedate.astimezone(tz=tz) + + self._dbphotos[uuid]["mainRating"] = row[6] + self._dbphotos[uuid]["hasAdjustments"] = row[7] + self._dbphotos[uuid]["hasKeywords"] = row[8] + self._dbphotos[uuid]["volumeId"] = row[10] + self._dbphotos[uuid]["imagePath"] = row[11] + self._dbphotos[uuid]["extendedDescription"] = row[12] + self._dbphotos[uuid]["name"] = normalize_unicode(row[13]) + self._dbphotos[uuid]["isMissing"] = row[14] + self._dbphotos[uuid]["originalFilename"] = row[15] + self._dbphotos[uuid]["favorite"] = row[16] + self._dbphotos[uuid]["hidden"] = row[17] + self._dbphotos[uuid]["latitude"] = row[18] + self._dbphotos[uuid]["longitude"] = row[19] + self._dbphotos[uuid]["adjustmentUuid"] = row[20] + self._dbphotos[uuid]["adjustmentFormatID"] = None + + # find type and UTI + if row[21] == 2: + # photo + self._dbphotos[uuid]["type"] = _PHOTO_TYPE + elif row[21] == 8: + # movie + self._dbphotos[uuid]["type"] = _MOVIE_TYPE + else: + # unknown + if _debug(): + logging.debug(f"WARNING: {uuid} found unknown type {row[21]}") + self._dbphotos[uuid]["type"] = None + + self._dbphotos[uuid]["UTI"] = row[22] + + # The UTI in RKMaster will always be UTI of the original + # Unlike Photos 5 which changes the UTI to match latest edit + self._dbphotos[uuid]["UTI_original"] = row[22] + + # UTI edited will be read from RKModelResource + self._dbphotos[uuid]["UTI_edited"] = None + + # handle burst photos + # if burst photo, determine whether or not it's a selected burst photo + self._dbphotos[uuid]["burstUUID"] = row[23] + self._dbphotos[uuid]["burstPickType"] = row[24] + if row[23] is not None: + # it's a burst photo + self._dbphotos[uuid]["burst"] = True + burst_uuid = row[23] + if burst_uuid not in self._dbphotos_burst: + self._dbphotos_burst[burst_uuid] = set() + self._dbphotos_burst[burst_uuid].add(uuid) + if row[24] != 2 and row[24] != 4: + self._dbphotos[uuid][ + "burst_key" + ] = True # it's a key photo (selected from the burst) + else: + self._dbphotos[uuid][ + "burst_key" + ] = False # it's a burst photo but not one that's selected + else: + # not a burst photo + self._dbphotos[uuid]["burst"] = False + self._dbphotos[uuid]["burst_key"] = None + + # RKVersion.specialType + # 1 == panorama + # 2 == slow-mo movie + # 3 == time-lapse movie + # 4 == HDR + # 5 == live photo + # 6 == screenshot + # 7 == JPEG/RAW pair + # 8 == HDR live photo + # 9 = portrait + + # get info on special types + self._dbphotos[uuid]["specialType"] = row[25] + self._dbphotos[uuid]["masterModelID"] = row[26] + self._dbphotos[uuid]["panorama"] = True if row[25] == 1 else False + self._dbphotos[uuid]["slow_mo"] = True if row[25] == 2 else False + self._dbphotos[uuid]["time_lapse"] = True if row[25] == 3 else False + self._dbphotos[uuid]["hdr"] = ( + True if (row[25] == 4 or row[25] == 8) else False + ) + self._dbphotos[uuid]["live_photo"] = ( + True if (row[25] == 5 or row[25] == 8) else False + ) + self._dbphotos[uuid]["screenshot"] = True if row[25] == 6 else False + self._dbphotos[uuid]["portrait"] = True if row[25] == 9 else False + + # selfies (front facing camera, RKVersion.selfPortrait == 1) + if row[27] is not None: + self._dbphotos[uuid]["selfie"] = True if row[27] == 1 else False + else: + self._dbphotos[uuid]["selfie"] = None + + self._dbphotos[uuid]["momentID"] = row[28] + + # Init cloud details that will be filled in later if cloud asset + self._dbphotos[uuid]["cloudAssetGUID"] = None # Photos 5 + self._dbphotos[uuid]["cloudLocalState"] = None # Photos 5 + self._dbphotos[uuid]["cloudLibraryState"] = None + self._dbphotos[uuid]["cloudStatus"] = None + self._dbphotos[uuid]["cloudAvailable"] = None + self._dbphotos[uuid]["incloud"] = None + + # associated RAW image info + self._dbphotos[uuid]["has_raw"] = True if row[25] == 7 else False + self._dbphotos[uuid]["UTI_raw"] = None + self._dbphotos[uuid]["raw_data_length"] = None + self._dbphotos[uuid]["raw_info"] = None + self._dbphotos[uuid]["resource_type"] = None # Photos 5 + self._dbphotos[uuid]["datastore_subtype"] = None # Photos 5 + self._dbphotos[uuid]["raw_master_uuid"] = row[29] + self._dbphotos[uuid]["non_raw_master_uuid"] = row[30] + self._dbphotos[uuid]["alt_master_uuid"] = row[31] + + # original resource choice (e.g. RAW or jpeg) + # In Photos 5+, original_resource_choice set from: + # ZADDITIONALASSETATTRIBUTES.ZORIGINALRESOURCECHOICE + # = 0 if jpeg is selected as "original" in Photos (the default) + # = 1 if RAW is selected as "original" in Photos + # RKVersion.subType, RAW always appears to be 16 + # 4 = mov + # 16 = RAW + # 32 = JPEG + # 64 = TIFF + # 2048 = PNG + # 32768 = HIEC + self._dbphotos[uuid]["original_resource_choice"] = ( + 1 if row[40] == 16 and self._dbphotos[uuid]["has_raw"] else 0 + ) + self._dbphotos[uuid]["raw_is_original"] = bool( + self._dbphotos[uuid]["original_resource_choice"] + ) + + # recently deleted items + self._dbphotos[uuid]["intrash"] = row[32] == 1 + self._dbphotos[uuid]["trasheddate_timestamp"] = row[41] + try: + self._dbphotos[uuid]["trasheddate"] = datetime.fromtimestamp( + row[41] + TIME_DELTA + ) + except (ValueError, TypeError): + self._dbphotos[uuid]["trasheddate"] = None + + # height/width/orientation + self._dbphotos[uuid]["height"] = row[33] + self._dbphotos[uuid]["width"] = row[34] + self._dbphotos[uuid]["orientation"] = row[35] + self._dbphotos[uuid]["original_height"] = row[36] + self._dbphotos[uuid]["original_width"] = row[37] + self._dbphotos[uuid]["original_orientation"] = row[38] + self._dbphotos[uuid]["original_filesize"] = row[39] + + # visibility state + self._dbphotos[uuid]["visibility_state"] = row[42] + self._dbphotos[uuid]["visible"] = row[42] == 1 + + # file is reference (not copied into Photos library) + self._dbphotos[uuid]["isreference"] = row[43] == 1 + self._dbphotos[uuid]["saved_asset_type"] = None # Photos 5+ + + # import session not yet handled for Photos 4 + self._dbphotos[uuid]["import_session"] = None + self._dbphotos[uuid]["import_uuid"] = None + self._dbphotos[uuid]["fok_import_session"] = None + + # get additional details from RKMaster, needed for RAW processing + verbose("Processing additional photo details.") + c.execute( + """ SELECT + RKMaster.uuid, + RKMaster.volumeId, + RKMaster.imagePath, + RKMaster.isMissing, + RKMaster.originalFileName, + RKMaster.UTI, + RKMaster.modelID, + RKMaster.fileSize, + RKMaster.isTrulyRaw, + RKMaster.alternateMasterUuid, + RKMaster.filename + FROM RKMaster + """ + ) + + # Order of results: + # 0 RKMaster.uuid, + # 1 RKMaster.volumeId, + # 2 RKMaster.imagePath, + # 3 RKMaster.isMissing, + # 4 RKMaster.originalFileName, + # 5 RKMaster.UTI, + # 6 RKMaster.modelID, + # 7 RKMaster.fileSize, + # 8 RKMaster.isTrulyRaw, + # 9 RKMaster.alternateMasterUuid + # 10 RKMaster.filename + + for row in c: + uuid = row[0] + info = {} + info["_uuid"] = uuid + info["volumeId"] = row[1] + info["imagePath"] = row[2] + info["isMissing"] = row[3] + info["originalFilename"] = row[4] + info["UTI"] = row[5] + info["modelID"] = row[6] + info["fileSize"] = row[7] + info["isTrulyRAW"] = row[8] + info["alternateMasterUuid"] = row[9] + info["filename"] = row[10] + self._dbphotos_master[uuid] = info + + # get details needed to find path of the edited photos + c.execute( + """ SELECT RKVersion.uuid, RKVersion.adjustmentUuid, RKModelResource.modelId, + RKModelResource.resourceTag, RKModelResource.UTI, RKVersion.specialType, + RKModelResource.attachedModelType, RKModelResource.resourceType + FROM RKVersion + JOIN RKModelResource on RKModelResource.attachedModelId = RKVersion.modelId """ + ) + + # Order of results: + # 0 RKVersion.uuid + # 1 RKVersion.adjustmentUuid + # 2 RKModelResource.modelId + # 3 RKModelResource.resourceTag + # 4 RKModelResource.UTI + # 5 RKVersion.specialType + # 6 RKModelResource.attachedModelType + # 7 RKModelResource.resourceType + + for row in c: + uuid = row[0] + if uuid in self._dbphotos: + # get info on adjustments (edits) + if self._dbphotos[uuid]["adjustmentUuid"] == row[3]: + if ( + row[1] != "UNADJUSTEDNONRAW" + and row[1] != "UNADJUSTED" + and row[6] == 2 + ): + if "edit_resource_id" in self._dbphotos[uuid]: + if _debug(): + logging.debug( + f"WARNING: found more than one edit_resource_id for " + f"UUID {row[0]},adjustmentUUID {row[1]}, modelID {row[2]}" + ) + # TODO: I think there should never be more than one edit but + # I've seen this once in my library + # should we return all edits or just most recent one? + # For now, return most recent edit + self._dbphotos[uuid]["edit_resource_id"] = row[2] + self._dbphotos[uuid]["UTI_edited"] = row[4] + + # get details on external edits + c.execute( + """ SELECT RKVersion.uuid, + RKVersion.adjustmentUuid, + RKAdjustmentData.originator, + RKAdjustmentData.format + FROM RKVersion, RKAdjustmentData + WHERE RKVersion.adjustmentUuid = RKAdjustmentData.uuid """ + ) + + for row in c: + uuid = row[0] + if uuid in self._dbphotos: + self._dbphotos[uuid]["adjustmentFormatID"] = row[3] + + # get details to find path of live photos + c.execute( + """ SELECT + RKVersion.uuid, + RKModelResource.modelId, + RKModelResource.UTI, + RKVersion.specialType, + RKModelResource.attachedModelType, + RKModelResource.resourceType, + RKModelResource.isOnDisk + FROM RKVersion + INNER JOIN RKMaster on RKVersion.masterUuid = RKMaster.uuid + INNER JOIN RKModelResource on RKMaster.modelId = RKModelResource.attachedModelId + WHERE RKModelResource.UTI = 'com.apple.quicktime-movie' + """ + ) + + # Order of results + # 0 RKVersion.uuid, + # 1 RKModelResource.modelId, + # 2 RKModelResource.UTI, + # 3 RKVersion.specialType, + # 4 RKModelResource.attachedModelType, + # 5 RKModelResource.resourceType + # 6 RKModelResource.isOnDisk + + # TODO: don't think we need most of these fields, remove from SQL query? + for row in c: + uuid = row[0] + if uuid in self._dbphotos: + self._dbphotos[uuid]["live_model_id"] = row[1] + self._dbphotos[uuid]["modeResourceIsOnDisk"] = ( + True if row[6] == 1 else False + ) + + # init any uuids that had no edits or live photos + for uuid in self._dbphotos: + if "edit_resource_id" not in self._dbphotos[uuid]: + self._dbphotos[uuid]["edit_resource_id"] = None + if "live_model_id" not in self._dbphotos[uuid]: + self._dbphotos[uuid]["live_model_id"] = None + self._dbphotos[uuid]["modeResourceIsOnDisk"] = None + + # get cloud details + c.execute( + """ SELECT + RKVersion.uuid, + RKMaster.cloudLibraryState, + RKCloudResource.available, + RKCloudResource.status + FROM RKCloudResource + INNER JOIN RKMaster ON RKMaster.fingerprint = RKCloudResource.fingerprint + INNER JOIN RKVersion ON RKVersion.masterUuid = RKMaster.uuid """ + ) + + # Order of results + # 0 RKVersion.uuid, + # 1 RKMaster.cloudLibraryState, + # 2 RKCloudResource.available, + # 3 RKCloudResource.status + + for row in c: + uuid = row[0] + if uuid in self._dbphotos: + self._dbphotos[uuid]["cloudLibraryState"] = row[1] + self._dbphotos[uuid]["cloudAvailable"] = row[2] + self._dbphotos[uuid]["cloudStatus"] = row[3] + self._dbphotos[uuid]["incloud"] = True if row[2] == 1 else False + + # get location data + verbose("Processing location data.") + # get the country codes + country_codes = c.execute( + "SELECT modelID, countryCode " + "FROM RKPlace " + "WHERE countryCode IS NOT NULL " + ).fetchall() + countries = {code[0]: code[1] for code in country_codes} + self._db_countries = countries + + # get the place data + place_data = c.execute( + "SELECT modelID, defaultName, type, area " "FROM RKPlace " + ).fetchall() + places = {p[0]: p for p in place_data} + self._db_places = places + + for uuid in self._dbphotos: + # get placeId which is then used to lookup defaultName + place_ids_query = c.execute( + "SELECT placeId " + "FROM RKPlaceForVersion " + f"WHERE versionId = '{self._dbphotos[uuid]['modelID']}'" + ) + + place_ids = [id[0] for id in place_ids_query.fetchall()] + self._dbphotos[uuid]["placeIDs"] = place_ids + country_code = [countries[x] for x in place_ids if x in countries] + if len(country_code) > 1: + logging.warning(f"Found more than one country code for uuid: {uuid}") + + if country_code: + self._dbphotos[uuid]["countryCode"] = country_code[0] + else: + self._dbphotos[uuid]["countryCode"] = None + + # get the place info that matches the RKPlace modelIDs for this photo + # (place_ids), sort by area (element 3 of the place_data tuple in places) + # area could be None so assume 0 if it is (issue #230) + place_names = [ + pname + for pname in sorted( + [places[p] for p in places if p in place_ids], + key=lambda place: place[3] if place[3] is not None else 0, + ) + ] + + self._dbphotos[uuid]["placeNames"] = place_names + self._dbphotos[uuid]["reverse_geolocation"] = None # Photos 5 + + # build album_titles dictionary + for album_id in self._dbalbum_details: + title = self._dbalbum_details[album_id]["title"] + if title in self._dbalbum_titles: + self._dbalbum_titles[title].append(album_id) + else: + self._dbalbum_titles[title] = [album_id] + + # add volume name to _dbphotos_master + for info in self._dbphotos_master.values(): + # issue 230: have seen bad volumeID values + try: + info["volume"] = ( + self._dbvolumes[info["volumeId"]] + if info["volumeId"] is not None + else None + ) + except KeyError: + info["volume"] = None + + # add data on RAW images + for info in self._dbphotos.values(): + if info["has_raw"]: + raw_uuid = info["raw_master_uuid"] + info["raw_info"] = self._dbphotos_master[raw_uuid] + info["UTI_raw"] = self._dbphotos_master[raw_uuid]["UTI"] + non_raw_uuid = info["non_raw_master_uuid"] + info["raw_pair_info"] = self._dbphotos_master[non_raw_uuid] + else: + info["raw_info"] = None + info["UTI_raw"] = None + info["raw_pair_info"] = None + + # done with the database connection + conn.close() + + # process faces + verbose("Processing face details.") + self._process_faceinfo() + + # add faces and keywords to photo data + for uuid in self._dbphotos: + # keywords + if self._dbphotos[uuid]["hasKeywords"] == 1: + self._dbphotos[uuid]["keywords"] = self._dbkeywords_uuid[uuid] + else: + self._dbphotos[uuid]["keywords"] = [] + + if uuid in self._dbfaces_uuid: + self._dbphotos[uuid]["hasPersons"] = 1 + self._dbphotos[uuid]["persons"] = self._dbfaces_uuid[uuid] + else: + self._dbphotos[uuid]["hasPersons"] = 0 + self._dbphotos[uuid]["persons"] = [] + + if uuid in self._dbalbums_uuid: + self._dbphotos[uuid]["albums"] = self._dbalbums_uuid[uuid] + self._dbphotos[uuid]["hasAlbums"] = 1 + else: + self._dbphotos[uuid]["albums"] = [] + self._dbphotos[uuid]["hasAlbums"] = 0 + + if self._dbphotos[uuid]["volumeId"] is not None: + # issue 230: have seen bad volumeID values + try: + self._dbphotos[uuid]["volume"] = self._dbvolumes[ + self._dbphotos[uuid]["volumeId"] + ] + except KeyError: + self._dbphotos[uuid]["volume"] = None + else: + self._dbphotos[uuid]["volume"] = None + + # done processing, dump debug data if requested + verbose("Done processing details from Photos library.") + if _debug(): + logging.debug("Faces (_dbfaces_uuid):") + logging.debug(pformat(self._dbfaces_uuid)) + + logging.debug("Persons (_dbpersons_pk):") + logging.debug(pformat(self._dbpersons_pk)) + + logging.debug("Keywords by uuid (_dbkeywords_uuid):") + logging.debug(pformat(self._dbkeywords_uuid)) + + logging.debug("Keywords by keyword (_dbkeywords_keywords):") + logging.debug(pformat(self._dbkeywords_keyword)) + + logging.debug("Albums by uuid (_dbalbums_uuid):") + logging.debug(pformat(self._dbalbums_uuid)) + + logging.debug("Albums by album (_dbalbums_albums):") + logging.debug(pformat(self._dbalbums_album)) + + logging.debug("Album details (_dbalbum_details):") + logging.debug(pformat(self._dbalbum_details)) + + logging.debug("Album titles (_dbalbum_titles):") + logging.debug(pformat(self._dbalbum_titles)) + + logging.debug("Volumes (_dbvolumes):") + logging.debug(pformat(self._dbvolumes)) + + logging.debug("Photos (_dbphotos):") + logging.debug(pformat(self._dbphotos)) + + logging.debug("Burst Photos (dbphotos_burst:") + logging.debug(pformat(self._dbphotos_burst)) + + def _build_album_folder_hierarchy_4(self, uuid, folders=None): + """ recursively build folder/album hierarchy + uuid: parent uuid of the album being processed + (parent uuid is a folder in RKFolders) + folders: dict holding the folder hierarchy + NOTE: This implementation is different than _build_album_folder_hierarchy_5 + which takes the uuid of the album being processed. Here uuid is the parent uuid + of the parent folder album because in Photos <=4, folders are in RKFolders and + albums in RKAlbums. In Photos 5, folders are just special albums + with kind = _PHOTOS_5_FOLDER_KIND """ + + parent_uuid = self._dbfolder_details[uuid]["parentFolderUuid"] + + if parent_uuid is None: + return folders + + if parent_uuid == _PHOTOS_4_TOP_LEVEL_ALBUM: + if not folders: + # this is a top-level folder with no sub-folders + folders = {uuid: None} + # at top of hierarchy, we're done + return folders + + # recurse to keep building + if not folders: + # first time building + folders = {uuid: None} + folders = {parent_uuid: folders} + folders = self._build_album_folder_hierarchy_4(parent_uuid, folders=folders) + return folders + + def _process_database5(self): + """ process the Photos database to extract info + works on Photos version 5 and version 6 + + This is a big hairy 700 line function that should probably be refactored + but it works so don't touch it. + """ + + if _debug(): + logging.debug(f"_process_database5") + verbose = self._verbose + verbose(f"Processing database.") + (conn, c) = _open_sql_file(self._tmp_db) + + # some of the tables/columns have different names in different versions of Photos + photos_ver = get_db_model_version(self._tmp_db) + self._photos_ver = photos_ver + verbose(f"Database version: {self._db_version}, {photos_ver}.") + asset_table = _DB_TABLE_NAMES[photos_ver]["ASSET"] + keyword_join = _DB_TABLE_NAMES[photos_ver]["KEYWORD_JOIN"] + album_join = _DB_TABLE_NAMES[photos_ver]["ALBUM_JOIN"] + album_sort = _DB_TABLE_NAMES[photos_ver]["ALBUM_SORT_ORDER"] + import_fok = _DB_TABLE_NAMES[photos_ver]["IMPORT_FOK"] + depth_state = _DB_TABLE_NAMES[photos_ver]["DEPTH_STATE"] + + # Look for all combinations of persons and pictures + if _debug(): + logging.debug(f"Getting information about persons") + + # get info to associate persons with photos + # then get detected faces in each photo and link to persons + verbose("Processing persons in photos.") + c.execute( + """ SELECT + ZPERSON.Z_PK, + ZPERSON.ZPERSONUUID, + ZPERSON.ZFULLNAME, + ZPERSON.ZFACECOUNT, + ZPERSON.ZKEYFACE, + ZPERSON.ZDISPLAYNAME + FROM ZPERSON + """ + ) + + # 0 ZPERSON.Z_PK, + # 1 ZPERSON.ZPERSONUUID, + # 2 ZPERSON.ZFULLNAME, + # 3 ZPERSON.ZFACECOUNT, + # 4 ZPERSON.ZKEYFACE, + # 5 ZPERSON.ZDISPLAYNAME + + for person in c: + pk = person[0] + fullname = person[2] if person[2] != "" else _UNKNOWN_PERSON + self._dbpersons_pk[pk] = { + "pk": pk, + "uuid": person[1], + "fullname": fullname, + "facecount": person[3], + "keyface": person[4], + "displayname": person[5], + "photo_uuid": None, + "keyface_uuid": None, + } + try: + self._dbpersons_fullname[fullname].append(pk) + except KeyError: + self._dbpersons_fullname[fullname] = [pk] + + # get info on keyface -- some photos have null keyface so can't do a single query + # (at least not with my SQL skills) + c.execute( + f""" SELECT + ZPERSON.Z_PK, + ZPERSON.ZKEYFACE, + {asset_table}.ZUUID, + ZDETECTEDFACE.ZUUID + FROM ZPERSON, ZDETECTEDFACE, {asset_table} + WHERE ZDETECTEDFACE.Z_PK = ZPERSON.ZKEYFACE AND + ZDETECTEDFACE.ZASSET = {asset_table}.Z_PK + """ + ) + + # 0 ZPERSON.Z_PK, + # 1 ZPERSON.ZKEYFACE, + # 2 ZGENERICASSET.ZUUID, + # 3 ZDETECTEDFACE.ZUUID + + for person in c: + pk = person[0] + try: + self._dbpersons_pk[pk]["photo_uuid"] = person[2] + self._dbpersons_pk[pk]["keyface_uuid"] = person[3] + except KeyError: + logging.debug(f"Unexpected KeyError _dbpersons_pk[{pk}]") + + # get information on detected faces + verbose("Processing detected faces in photos.") + c.execute( + f""" SELECT + ZPERSON.Z_PK, + {asset_table}.ZUUID + FROM ZPERSON, ZDETECTEDFACE, {asset_table} + WHERE ZDETECTEDFACE.ZPERSON = ZPERSON.Z_PK AND + ZDETECTEDFACE.ZASSET = {asset_table}.Z_PK + """ + ) + + # 0 ZPERSON.Z_PK, + # 1 ZGENERICASSET.ZUUID, + + for face in c: + pk = face[0] + uuid = face[1] + try: + self._dbfaces_uuid[uuid].append(pk) + except KeyError: + self._dbfaces_uuid[uuid] = [pk] + + try: + self._dbfaces_pk[pk].append(uuid) + except KeyError: + self._dbfaces_pk[pk] = [uuid] + + if _debug(): + logging.debug(f"Finished walking through persons") + logging.debug(pformat(self._dbpersons_pk)) + logging.debug(pformat(self._dbpersons_fullname)) + logging.debug(pformat(self._dbfaces_pk)) + logging.debug(pformat(self._dbfaces_uuid)) + + # get details about albums + verbose("Processing albums.") + c.execute( + f""" SELECT + ZGENERICALBUM.ZUUID, + {asset_table}.ZUUID, + {album_sort} + FROM {asset_table} + JOIN Z_26ASSETS ON {album_join} = {asset_table}.Z_PK + JOIN ZGENERICALBUM ON ZGENERICALBUM.Z_PK = Z_26ASSETS.Z_26ALBUMS + """ + ) + + # 0 ZGENERICALBUM.ZUUID, + # 1 ZGENERICASSET.ZUUID, + # 2 Z_26ASSETS.Z_FOK_34ASSETS + + for album in c: + # store by uuid in _dbalbums_uuid and by album in _dbalbums_album + album_uuid = album[0] + photo_uuid = album[1] + sort_order = album[2] + try: + self._dbalbums_uuid[photo_uuid].append(album_uuid) + except KeyError: + self._dbalbums_uuid[photo_uuid] = [album_uuid] + + try: + self._dbalbums_album[album_uuid].append((photo_uuid, sort_order)) + except KeyError: + self._dbalbums_album[album_uuid] = [(photo_uuid, sort_order)] + + # now get additional details about albums + c.execute( + "SELECT " + "ZUUID, " # 0 + "ZTITLE, " # 1 + "ZCLOUDLOCALSTATE, " # 2 + "ZCLOUDOWNERFIRSTNAME, " # 3 + "ZCLOUDOWNERLASTNAME, " # 4 + "ZCLOUDOWNERHASHEDPERSONID, " # 5 + "ZKIND, " # 6 + "ZPARENTFOLDER, " # 7 + "Z_PK, " # 8 + "ZTRASHEDSTATE, " # 9 + "ZCREATIONDATE, " # 10 + "ZSTARTDATE, " # 11 + "ZENDDATE " # 12 + "FROM ZGENERICALBUM " + ) + for album in c: + self._dbalbum_details[album[0]] = { + "_uuid": album[0], + "title": normalize_unicode(album[1]), + "cloudlocalstate": album[2], + "cloudownerfirstname": album[3], + "cloudownderlastname": album[4], + "cloudownerhashedpersonid": album[5], + "cloudlibrarystate": None, # Photos 4 + "cloudidentifier": None, # Photos 4 + "kind": album[6], + "parentfolder": album[7], + "pk": album[8], + "intrash": False if album[9] == 0 else True, + "creation_date": album[10], + "start_date": album[11], + "end_date": album[12], + } + + # add cross-reference by pk to uuid + # needed to extract folder hierarchy + # in Photos >= 5, folders are special albums + self._dbalbums_pk[album[8]] = album[0] + + # get pk of root folder + root_uuid = [ + album + for album, details in self._dbalbum_details.items() + if details["kind"] == _PHOTOS_5_ROOT_FOLDER_KIND + ] + if len(root_uuid) != 1: + raise ValueError(f"Error finding root folder: {root_uuid}") + else: + self._folder_root_pk = self._dbalbum_details[root_uuid[0]]["pk"] + + # build _dbalbum_folders which is in form uuid: [list of parent uuids] + # TODO: look at this code...it works but I think I album can only be in a single folder + # which means there's a code path that will never get executed + for album, details in self._dbalbum_details.items(): + pk_parent = details["parentfolder"] + if pk_parent is None: + continue + + try: + parent = self._dbalbums_pk[pk_parent] + except KeyError: + raise ValueError(f"Did not find uuid for album {album} pk {pk_parent}") + + try: + self._dbalbum_parent_folders[album].append(parent) + except KeyError: + self._dbalbum_parent_folders[album] = [parent] + + for album, details in self._dbalbum_details.items(): + # if details["kind"] in [_PHOTOS_5_ALBUM_KIND, _PHOTOS_5_FOLDER_KIND]: + if details["kind"] == _PHOTOS_5_ALBUM_KIND: + folder_hierarchy = self._build_album_folder_hierarchy_5(album) + self._dbalbum_folders[album] = folder_hierarchy + elif details["kind"] == _PHOTOS_5_SHARED_ALBUM_KIND: + # shared albums can't be in folders + self._dbalbum_folders[album] = [] + + if _debug(): + logging.debug(f"Finished walking through albums") + logging.debug(pformat(self._dbalbums_album)) + logging.debug(pformat(self._dbalbums_uuid)) + logging.debug(pformat(self._dbalbum_details)) + logging.debug(pformat(self._dbalbum_folders)) + + # get details on keywords + verbose("Processing keywords.") + c.execute( + f"""SELECT ZKEYWORD.ZTITLE, {asset_table}.ZUUID + FROM {asset_table} + JOIN ZADDITIONALASSETATTRIBUTES ON ZADDITIONALASSETATTRIBUTES.ZASSET = {asset_table}.Z_PK + JOIN Z_1KEYWORDS ON Z_1KEYWORDS.Z_1ASSETATTRIBUTES = ZADDITIONALASSETATTRIBUTES.Z_PK + JOIN ZKEYWORD ON ZKEYWORD.Z_PK = {keyword_join} """ + ) + for keyword in c: + keyword_title = normalize_unicode(keyword[0]) + if not keyword[1] in self._dbkeywords_uuid: + self._dbkeywords_uuid[keyword[1]] = [] + if not keyword_title in self._dbkeywords_keyword: + self._dbkeywords_keyword[keyword_title] = [] + self._dbkeywords_uuid[keyword[1]].append(keyword[0]) + self._dbkeywords_keyword[keyword_title].append(keyword[1]) + + if _debug(): + logging.debug(f"Finished walking through keywords") + logging.debug(pformat(self._dbkeywords_keyword)) + logging.debug(pformat(self._dbkeywords_uuid)) + + # get details on disk volumes + c.execute("SELECT ZUUID, ZNAME from ZFILESYSTEMVOLUME") + for vol in c: + self._dbvolumes[vol[0]] = vol[1] + + if _debug(): + logging.debug(f"Finished walking through volumes") + logging.debug(self._dbvolumes) + + # get details about photos + verbose("Processing photo details.") + logging.debug(f"Getting information about photos") + c.execute( + f"""SELECT {asset_table}.ZUUID, + ZADDITIONALASSETATTRIBUTES.ZMASTERFINGERPRINT, + ZADDITIONALASSETATTRIBUTES.ZTITLE, + ZADDITIONALASSETATTRIBUTES.ZORIGINALFILENAME, + {asset_table}.ZMODIFICATIONDATE, + {asset_table}.ZDATECREATED, + ZADDITIONALASSETATTRIBUTES.ZTIMEZONEOFFSET, + ZADDITIONALASSETATTRIBUTES.ZINFERREDTIMEZONEOFFSET, + ZADDITIONALASSETATTRIBUTES.ZTIMEZONENAME, + {asset_table}.ZHIDDEN, + {asset_table}.ZFAVORITE, + {asset_table}.ZDIRECTORY, + {asset_table}.ZFILENAME, + {asset_table}.ZLATITUDE, + {asset_table}.ZLONGITUDE, + {asset_table}.ZHASADJUSTMENTS, + {asset_table}.ZCLOUDBATCHPUBLISHDATE, + {asset_table}.ZKIND, + {asset_table}.ZUNIFORMTYPEIDENTIFIER, + {asset_table}.ZAVALANCHEUUID, + {asset_table}.ZAVALANCHEPICKTYPE, + {asset_table}.ZKINDSUBTYPE, + {asset_table}.ZCUSTOMRENDEREDVALUE, + ZADDITIONALASSETATTRIBUTES.ZCAMERACAPTUREDEVICE, + {asset_table}.ZCLOUDASSETGUID, + ZADDITIONALASSETATTRIBUTES.ZREVERSELOCATIONDATA, + {asset_table}.ZMOMENT, + ZADDITIONALASSETATTRIBUTES.ZORIGINALRESOURCECHOICE, + {asset_table}.ZTRASHEDSTATE, + {asset_table}.ZHEIGHT, + {asset_table}.ZWIDTH, + {asset_table}.ZORIENTATION, + ZADDITIONALASSETATTRIBUTES.ZORIGINALHEIGHT, + ZADDITIONALASSETATTRIBUTES.ZORIGINALWIDTH, + ZADDITIONALASSETATTRIBUTES.ZORIGINALORIENTATION, + ZADDITIONALASSETATTRIBUTES.ZORIGINALFILESIZE, + {depth_state}, + {asset_table}.ZADJUSTMENTTIMESTAMP, + {asset_table}.ZVISIBILITYSTATE, + {asset_table}.ZTRASHEDDATE, + {asset_table}.ZSAVEDASSETTYPE + FROM {asset_table} + JOIN ZADDITIONALASSETATTRIBUTES ON ZADDITIONALASSETATTRIBUTES.ZASSET = {asset_table}.Z_PK + ORDER BY {asset_table}.ZUUID """ + ) + # Order of results + # 0 SELECT ZGENERICASSET.ZUUID, + # 1 ZADDITIONALASSETATTRIBUTES.ZMASTERFINGERPRINT, + # 2 ZADDITIONALASSETATTRIBUTES.ZTITLE, + # 3 ZADDITIONALASSETATTRIBUTES.ZORIGINALFILENAME, + # 4 ZGENERICASSET.ZMODIFICATIONDATE, + # 5 ZGENERICASSET.ZDATECREATED, + # 6 ZADDITIONALASSETATTRIBUTES.ZTIMEZONEOFFSET, + # 7 ZADDITIONALASSETATTRIBUTES.ZINFERREDTIMEZONEOFFSET, + # 8 ZADDITIONALASSETATTRIBUTES.ZTIMEZONENAME, + # 9 ZGENERICASSET.ZHIDDEN, + # 10 ZGENERICASSET.ZFAVORITE, + # 11 ZGENERICASSET.ZDIRECTORY, + # 12 ZGENERICASSET.ZFILENAME, + # 13 ZGENERICASSET.ZLATITUDE, + # 14 ZGENERICASSET.ZLONGITUDE, + # 15 ZGENERICASSET.ZHASADJUSTMENTS + # 16 ZCLOUDBATCHPUBLISHDATE -- If not null, indicates a shared photo + # 17 ZKIND, -- 0 = photo, 1 = movie + # 18 ZUNIFORMTYPEIDENTIFIER -- UTI + # 19 ZGENERICASSET.ZAVALANCHEUUID, -- if not NULL, is burst photo + # 20 ZGENERICASSET.ZAVALANCHEPICKTYPE -- if not 2, is a selected burst photo + # 21 ZGENERICASSET.ZKINDSUBTYPE -- determine if live photos, etc + # 22 ZGENERICASSET.ZCUSTOMRENDEREDVALUE -- determine if HDR photo + # 23 ZADDITIONALASSETATTRIBUTES.ZCAMERACAPTUREDEVICE -- 1 if selfie (front facing camera) + # 24 ZGENERICASSET.ZCLOUDASSETGUID -- not null if asset is cloud asset + # (e.g. user has "iCloud Photos" checked in Photos preferences) + # 25 ZADDITIONALASSETATTRIBUTES.ZREVERSELOCATIONDATA -- reverse geolocation data + # 26 ZGENERICASSET.ZMOMENT -- FK for ZMOMENT.Z_PK + # 27 ZADDITIONALASSETATTRIBUTES.ZORIGINALRESOURCECHOICE -- 1 if associated RAW image is original else 0 + # 28 ZGENERICASSET.ZTRASHEDSTATE -- 0 if not in trash, 1 if in trash + # 29 ZGENERICASSET.ZHEIGHT, + # 30 ZGENERICASSET.ZWIDTH, + # 31 ZGENERICASSET.ZORIENTATION, + # 32 ZADDITIONALASSETATTRIBUTES.ZORIGINALHEIGHT, + # 33 ZADDITIONALASSETATTRIBUTES.ZORIGINALWIDTH, + # 34 ZADDITIONALASSETATTRIBUTES.ZORIGINALORIENTATION, + # 35 ZADDITIONALASSETATTRIBUTES.ZORIGINALFILESIZE + # 36 ZGENERICASSET.ZDEPTHSTATES / ZASSET.ZDEPTHTYPE + # 37 ZGENERICASSET.ZADJUSTMENTTIMESTAMP -- when was photo edited? + # 38 ZGENERICASSET.ZVISIBILITYSTATE -- 0 if visible, 2 if not (e.g. a burst image) + # 39 ZGENERICASSET.ZTRASHEDDATE -- date item placed in the trash or null if not in trash + # 40 ZGENERICASSET.ZSAVEDASSETTYPE -- how item imported + + for row in c: + uuid = row[0] + info = {} + info["_uuid"] = uuid # stored here for easier debugging + info["modelID"] = None + info["masterUuid"] = None + info["masterFingerprint"] = row[1] + info["name"] = normalize_unicode(row[2]) + + # There are sometimes negative values for lastmodifieddate in the database + # I don't know what these mean but they will raise exception in datetime if + # not accounted for + info["lastmodifieddate_timestamp"] = row[37] + try: + info["lastmodifieddate"] = datetime.fromtimestamp(row[37] + TIME_DELTA) + except (ValueError, TypeError): + info["lastmodifieddate"] = None + + info["imageTimeZoneOffsetSeconds"] = row[6] + info["imageDate_timestamp"] = row[5] + + try: + imagedate = datetime.fromtimestamp(row[5] + TIME_DELTA) + seconds = info["imageTimeZoneOffsetSeconds"] or 0 + delta = timedelta(seconds=seconds) + tz = timezone(delta) + info["imageDate"] = imagedate.astimezone(tz=tz) + except ValueError: + # sometimes imageDate is invalid so use 1 Jan 1970 in UTC as image date + imagedate = datetime(1970, 1, 1) + tz = timezone(timedelta(0)) + info["imageDate"] = imagedate.astimezone(tz=tz) + + info["hidden"] = row[9] + info["favorite"] = row[10] + info["originalFilename"] = row[3] + info["filename"] = row[12] + info["directory"] = row[11] + + # set latitude and longitude + # if both latitude and longitude = -180.0, then they are NULL + if row[13] == -180.0 and row[14] == -180.0: + info["latitude"] = None + info["longitude"] = None + else: + info["latitude"] = row[13] + info["longitude"] = row[14] + + info["hasAdjustments"] = row[15] + + info["cloudbatchpublishdate"] = row[16] + info["shared"] = True if row[16] is not None else False + + # these will get filled in later + # init to avoid key errors + info["extendedDescription"] = None # fill this in later + info["localAvailability"] = None + info["remoteAvailability"] = None + info["isMissing"] = None + info["adjustmentUuid"] = None + info["adjustmentFormatID"] = None + + # find type + if row[17] == 0: + info["type"] = _PHOTO_TYPE + elif row[17] == 1: + info["type"] = _MOVIE_TYPE + else: + if _debug(): + logging.debug(f"WARNING: {uuid} found unknown type {row[17]}") + info["type"] = None + + info["UTI"] = row[18] + info["UTI_original"] = None # filled in later + + # handle burst photos + # if burst photo, determine whether or not it's a selected burst photo + # in Photos 5, burstUUID is called avalancheUUID + info["burstUUID"] = row[19] # avalancheUUID + info["burstPickType"] = row[20] # avalanchePickType + if row[19] is not None: + # it's a burst photo + info["burst"] = True + burst_uuid = row[19] + if burst_uuid not in self._dbphotos_burst: + self._dbphotos_burst[burst_uuid] = set() + self._dbphotos_burst[burst_uuid].add(uuid) + if row[20] != 2 and row[20] != 4: + info[ + "burst_key" + ] = True # it's a key photo (selected from the burst) + else: + info[ + "burst_key" + ] = False # it's a burst photo but not one that's selected + else: + # not a burst photo + info["burst"] = False + info["burst_key"] = None + + # Info on sub-type (live photo, panorama, etc) + # ZGENERICASSET.ZKINDSUBTYPE + # 1 == panorama + # 2 == live photo + # 10 = screenshot + # 100 = shared movie (MP4) ?? + # 101 = slow-motion video + # 102 = Time lapse video + info["subtype"] = row[21] + info["live_photo"] = True if row[21] == 2 else False + info["screenshot"] = True if row[21] == 10 else False + info["slow_mo"] = True if row[21] == 101 else False + info["time_lapse"] = True if row[21] == 102 else False + + # Handle HDR photos and portraits + # ZGENERICASSET.ZCUSTOMRENDEREDVALUE + # 3 = HDR photo + # 4 = non-HDR version of the photo + # 6 = panorama + # > 6 = portrait (sometimes, see ZDEPTHSTATE/ZDEPTHTYPE) + info["customRenderedValue"] = row[22] + info["hdr"] = True if row[22] == 3 else False + info["portrait"] = True if row[36] != 0 else False + + # Set panorama from either KindSubType or RenderedValue + info["panorama"] = True if row[21] == 1 or row[22] == 6 else False + + # Handle selfies (front facing camera, ZCAMERACAPTUREDEVICE=1) + info["selfie"] = True if row[23] == 1 else False + + # Determine if photo is part of cloud library (ZGENERICASSET.ZCLOUDASSETGUID not NULL) + # Initialize cloud fields that will filled in later + info["cloudAssetGUID"] = row[24] + info["cloudLocalState"] = None + info["incloud"] = None + info["cloudLibraryState"] = None # Photos 4 + info["cloudStatus"] = None # Photos 4 + info["cloudAvailable"] = None # Photos 4 + + # reverse geolocation info + info["reverse_geolocation"] = row[25] + info["placeIDs"] = None # Photos 4 + info["placeNames"] = None # Photos 4 + info["countryCode"] = None # Photos 4 + + # moment info + info["momentID"] = row[26] + + # original resource choice (e.g. RAW or jpeg) + # for images part of a RAW/jpeg pair, + # ZADDITIONALASSETATTRIBUTES.ZORIGINALRESOURCECHOICE + # = 0 if jpeg is selected as "original" in Photos (the default) + # = 1 if RAW is selected as "original" in Photos + info["original_resource_choice"] = row[27] + info["raw_is_original"] = True if row[27] == 1 else False + + # recently deleted items + info["intrash"] = True if row[28] == 1 else False + info["trasheddate_timestamp"] = row[39] + try: + info["trasheddate"] = datetime.fromtimestamp(row[39] + TIME_DELTA) + except (ValueError, TypeError): + info["trasheddate"] = None + + # height/width/orientation + info["height"] = row[29] + info["width"] = row[30] + info["orientation"] = row[31] + info["original_height"] = row[32] + info["original_width"] = row[33] + info["original_orientation"] = row[34] + info["original_filesize"] = row[35] + + # visibility state, visible (True) if 0, otherwise not visible (False) + # only values I've seen are 0 for visible, 2 for not-visible + info["visibility_state"] = row[38] + info["visible"] = row[38] == 0 + + # ZSAVEDASSETTYPE Values: + # 3: imported by copying to Photos library + # 4: shared iCloud photo + # 6: imported by iCloud (e.g. from iPhone) + # 10: referenced file (not copied to Photos library) + info["saved_asset_type"] = row[40] + info["isreference"] = row[40] == 10 + + # initialize import session info which will be filled in later + # not every photo has an import session so initialize all records now + info["import_session"] = None + info["fok_import_session"] = None + info["import_uuid"] = None + + # associated RAW image info + # will be filled in later + info["has_raw"] = False + info["raw_data_length"] = None + info["UTI_raw"] = None + info["datastore_subtype"] = None + info["resource_type"] = None + info["raw_master_uuid"] = None # Photos 4 + info["non_raw_master_uuid"] = None # Photos 4 + info["alt_master_uuid"] = None # Photos 4 + info["raw_info"] = None # Photos 4 + + self._dbphotos[uuid] = info + + # # if row[19] is not None and ((row[20] == 2) or (row[20] == 4)): + # # burst photo + # if row[19] is not None: + # # burst photo, add to _dbphotos_burst + # info["burst"] = True + # burst_uuid = row[19] + # if burst_uuid not in self._dbphotos_burst: + # self._dbphotos_burst[burst_uuid] = {} + # self._dbphotos_burst[burst_uuid][uuid] = info + # else: + # info["burst"] = False + + # get info on import sessions + # 0 ZGENERICASSET.ZUUID + # 1 ZGENERICASSET.ZIMPORTSESSION + # 2 ZGENERICASSET.Z_FOK_IMPORTSESSION + # 3 ZGENERICALBUM.ZUUID, + verbose("Processing import sessions.") + c.execute( + f"""SELECT + {asset_table}.ZUUID, + {asset_table}.ZIMPORTSESSION, + {import_fok}, + ZGENERICALBUM.ZUUID + FROM + {asset_table} + JOIN ZGENERICALBUM ON ZGENERICALBUM.Z_PK = {asset_table}.ZIMPORTSESSION + """ + ) + + for row in c: + uuid = row[0] + try: + self._dbphotos[uuid]["import_session"] = row[1] + self._dbphotos[uuid]["fok_import_session"] = row[2] + self._dbphotos[uuid]["import_uuid"] = row[3] + except KeyError: + logging.debug(f"No info record for uuid {uuid} for import session") + + # Get extended description + verbose("Processing additional photo details.") + c.execute( + f"""SELECT {asset_table}.ZUUID, + ZASSETDESCRIPTION.ZLONGDESCRIPTION + FROM {asset_table} + JOIN ZADDITIONALASSETATTRIBUTES ON ZADDITIONALASSETATTRIBUTES.ZASSET = {asset_table}.Z_PK + JOIN ZASSETDESCRIPTION ON ZASSETDESCRIPTION.Z_PK = ZADDITIONALASSETATTRIBUTES.ZASSETDESCRIPTION + ORDER BY {asset_table}.ZUUID """ + ) + for row in c: + uuid = row[0] + if uuid in self._dbphotos: + self._dbphotos[uuid]["extendedDescription"] = normalize_unicode(row[1]) + else: + if _debug(): + logging.debug( + f"WARNING: found description {row[1]} but no photo for {uuid}" + ) + + # get information about adjusted/edited photos + c.execute( + f"""SELECT {asset_table}.ZUUID, + {asset_table}.ZHASADJUSTMENTS, + ZUNMANAGEDADJUSTMENT.ZADJUSTMENTFORMATIDENTIFIER + FROM {asset_table}, ZUNMANAGEDADJUSTMENT + JOIN ZADDITIONALASSETATTRIBUTES ON ZADDITIONALASSETATTRIBUTES.ZASSET = {asset_table}.Z_PK + WHERE ZADDITIONALASSETATTRIBUTES.ZUNMANAGEDADJUSTMENT = ZUNMANAGEDADJUSTMENT.Z_PK """ + ) + for row in c: + uuid = row[0] + if uuid in self._dbphotos: + self._dbphotos[uuid]["adjustmentFormatID"] = row[2] + else: + if _debug(): + logging.debug( + f"WARNING: found adjustmentformatidentifier {row[2]} but no photo for uuid {row[0]}" + ) + + # Find missing photos + # TODO: this code is very kludgy and I had to make lots of assumptions + # it's probably wrong and needs to be re-worked once I figure out how to reliably + # determine if a photo is missing in Photos 5 + + # Get info on remote/local availability for photos in shared albums + # Also get UTI of original image (zdatastoresubtype = 1) + c.execute( + f""" SELECT + {asset_table}.ZUUID, + ZINTERNALRESOURCE.ZLOCALAVAILABILITY, + ZINTERNALRESOURCE.ZREMOTEAVAILABILITY, + ZINTERNALRESOURCE.ZDATASTORESUBTYPE, + ZINTERNALRESOURCE.ZUNIFORMTYPEIDENTIFIER, + ZUNIFORMTYPEIDENTIFIER.ZIDENTIFIER + FROM {asset_table} + JOIN ZADDITIONALASSETATTRIBUTES ON ZADDITIONALASSETATTRIBUTES.ZASSET = {asset_table}.Z_PK + JOIN ZINTERNALRESOURCE ON ZINTERNALRESOURCE.ZASSET = ZADDITIONALASSETATTRIBUTES.ZASSET + JOIN ZUNIFORMTYPEIDENTIFIER ON ZUNIFORMTYPEIDENTIFIER.Z_PK = ZINTERNALRESOURCE.ZUNIFORMTYPEIDENTIFIER + WHERE ZDATASTORESUBTYPE = 1 OR ZDATASTORESUBTYPE = 3 """ + ) + + # Order of results: + # 0 {asset_table}.ZUUID, + # 1 ZINTERNALRESOURCE.ZLOCALAVAILABILITY, + # 2 ZINTERNALRESOURCE.ZREMOTEAVAILABILITY, + # 3 ZINTERNALRESOURCE.ZDATASTORESUBTYPE, + # 4 ZINTERNALRESOURCE.ZUNIFORMTYPEIDENTIFIER, + # 5 ZUNIFORMTYPEIDENTIFIER.ZIDENTIFIER + + for row in c: + uuid = row[0] + if uuid in self._dbphotos: + self._dbphotos[uuid]["localAvailability"] = row[1] + self._dbphotos[uuid]["remoteAvailability"] = row[2] + if row[3] == 1: + self._dbphotos[uuid]["UTI_original"] = row[5] + + if row[1] != 1: + self._dbphotos[uuid]["isMissing"] = 1 + else: + self._dbphotos[uuid]["isMissing"] = 0 + + # get information on local/remote availability + c.execute( + f""" SELECT {asset_table}.ZUUID, + ZINTERNALRESOURCE.ZLOCALAVAILABILITY, + ZINTERNALRESOURCE.ZREMOTEAVAILABILITY + FROM {asset_table} + JOIN ZADDITIONALASSETATTRIBUTES ON ZADDITIONALASSETATTRIBUTES.ZASSET = {asset_table}.Z_PK + JOIN ZINTERNALRESOURCE ON ZINTERNALRESOURCE.ZFINGERPRINT = ZADDITIONALASSETATTRIBUTES.ZMASTERFINGERPRINT """ + ) + + for row in c: + uuid = row[0] + if uuid in self._dbphotos: + self._dbphotos[uuid]["localAvailability"] = row[1] + self._dbphotos[uuid]["remoteAvailability"] = row[2] + + if row[1] != 1: + self._dbphotos[uuid]["isMissing"] = 1 + else: + self._dbphotos[uuid]["isMissing"] = 0 + + # get information about cloud sync state + c.execute( + f""" SELECT + {asset_table}.ZUUID, + ZCLOUDMASTER.ZCLOUDLOCALSTATE + FROM ZCLOUDMASTER, {asset_table} + WHERE {asset_table}.ZMASTER = ZCLOUDMASTER.Z_PK """ + ) + for row in c: + uuid = row[0] + if uuid in self._dbphotos: + self._dbphotos[uuid]["cloudLocalState"] = row[1] + self._dbphotos[uuid]["incloud"] = True if row[1] == 3 else False + + # get information about associted RAW images + # RAW images have ZDATASTORESUBTYPE = 17 + c.execute( + f""" SELECT + {asset_table}.ZUUID, + ZINTERNALRESOURCE.ZDATALENGTH, + ZUNIFORMTYPEIDENTIFIER.ZIDENTIFIER, + ZINTERNALRESOURCE.ZDATASTORESUBTYPE, + ZINTERNALRESOURCE.ZRESOURCETYPE + FROM {asset_table} + JOIN ZINTERNALRESOURCE ON ZINTERNALRESOURCE.ZASSET = ZADDITIONALASSETATTRIBUTES.ZASSET + JOIN ZADDITIONALASSETATTRIBUTES ON ZADDITIONALASSETATTRIBUTES.ZASSET = {asset_table}.Z_PK + JOIN ZUNIFORMTYPEIDENTIFIER ON ZUNIFORMTYPEIDENTIFIER.Z_PK = ZINTERNALRESOURCE.ZUNIFORMTYPEIDENTIFIER + WHERE ZINTERNALRESOURCE.ZDATASTORESUBTYPE = 17 + """ + ) + for row in c: + uuid = row[0] + if uuid in self._dbphotos: + self._dbphotos[uuid]["has_raw"] = True + self._dbphotos[uuid]["raw_data_length"] = row[1] + self._dbphotos[uuid]["UTI_raw"] = row[2] + self._dbphotos[uuid]["datastore_subtype"] = row[3] + self._dbphotos[uuid]["resource_type"] = row[4] + + # add faces and keywords to photo data + for uuid in self._dbphotos: + # keywords + if uuid in self._dbkeywords_uuid: + self._dbphotos[uuid]["hasKeywords"] = 1 + self._dbphotos[uuid]["keywords"] = self._dbkeywords_uuid[uuid] + else: + self._dbphotos[uuid]["hasKeywords"] = 0 + self._dbphotos[uuid]["keywords"] = [] + + if uuid in self._dbfaces_uuid: + self._dbphotos[uuid]["hasPersons"] = 1 + self._dbphotos[uuid]["persons"] = self._dbfaces_uuid[uuid] + else: + self._dbphotos[uuid]["hasPersons"] = 0 + self._dbphotos[uuid]["persons"] = [] + + if uuid in self._dbalbums_uuid: + self._dbphotos[uuid]["albums"] = self._dbalbums_uuid[uuid] + self._dbphotos[uuid]["hasAlbums"] = 1 + else: + self._dbphotos[uuid]["albums"] = [] + self._dbphotos[uuid]["hasAlbums"] = 0 + + # build album_titles dictionary + for album_id in self._dbalbum_details: + title = self._dbalbum_details[album_id]["title"] + if title in self._dbalbum_titles: + self._dbalbum_titles[title].append(album_id) + else: + self._dbalbum_titles[title] = [album_id] + + # country codes (only used in Photos <=4) + self._db_countries = None + + # close connection and remove temporary files + conn.close() + + # process face info + verbose("Processing face details.") + self._process_faceinfo() + + # process search info + verbose("Processing photo labels.") + self._process_searchinfo() + + # process exif info + verbose("Processing EXIF details.") + self._process_exifinfo() + + # process computed scores + verbose("Processing computed aesthetic scores.") + self._process_scoreinfo() + + # process shared comments/likes + verbose("Processing comments and likes for shared photos.") + self._process_comments() + + # done processing, dump debug data if requested + verbose("Done processing details from Photos library.") + if _debug(): + logging.debug("Faces (_dbfaces_uuid):") + logging.debug(pformat(self._dbfaces_uuid)) + + logging.debug("Persons (_dbpersons_pk):") + logging.debug(pformat(self._dbpersons_pk)) + + logging.debug("Keywords by uuid (_dbkeywords_uuid):") + logging.debug(pformat(self._dbkeywords_uuid)) + + logging.debug("Keywords by keyword (_dbkeywords_keywords):") + logging.debug(pformat(self._dbkeywords_keyword)) + + logging.debug("Albums by uuid (_dbalbums_uuid):") + logging.debug(pformat(self._dbalbums_uuid)) + + logging.debug("Albums by album (_dbalbums_albums):") + logging.debug(pformat(self._dbalbums_album)) + + logging.debug("Album details (_dbalbum_details):") + logging.debug(pformat(self._dbalbum_details)) + + logging.debug("Album titles (_dbalbum_titles):") + logging.debug(pformat(self._dbalbum_titles)) + + logging.debug("Album folders (_dbalbum_folders):") + logging.debug(pformat(self._dbalbum_folders)) + + logging.debug("Album parent folders (_dbalbum_parent_folders):") + logging.debug(pformat(self._dbalbum_parent_folders)) + + logging.debug("Albums pk (_dbalbums_pk):") + logging.debug(pformat(self._dbalbums_pk)) + + logging.debug("Volumes (_dbvolumes):") + logging.debug(pformat(self._dbvolumes)) + + logging.debug("Photos (_dbphotos):") + logging.debug(pformat(self._dbphotos)) + + logging.debug("Burst Photos (dbphotos_burst:") + logging.debug(pformat(self._dbphotos_burst)) + + def _build_album_folder_hierarchy_5(self, uuid, folders=None): + """ recursively build folder/album hierarchy + uuid: uuid of the album/folder being processed + folders: dict holding the folder hierarchy """ + + # get parent uuid + parent = self._dbalbum_details[uuid]["parentfolder"] + + if parent is not None: + parent_uuid = self._dbalbums_pk[parent] + else: + # folder with no parent (e.g. shared iCloud folders) + return folders + + if self._db_version > _PHOTOS_4_VERSION and parent == self._folder_root_pk: + # at the top of the folder hierarchy, we're done + return folders + + # recurse to keep building + folders = {parent_uuid: folders} + folders = self._build_album_folder_hierarchy_5(parent_uuid, folders=folders) + return folders + + def _album_folder_hierarchy_list(self, album_uuid): + """ return appropriate album_folder_hierarchy_list for the _db_version """ + if self._db_version <= _PHOTOS_4_VERSION: + return self._album_folder_hierarchy_list_4(album_uuid) + else: + return self._album_folder_hierarchy_list_5(album_uuid) + + def _album_folder_hierarchy_list_4(self, album_uuid): + """ return hierarchical list of folder names album_uuid is contained in + the folder list is in form: + ["Top level folder", "sub folder 1", "sub folder 2"] + returns empty list of album is not in any folders """ + try: + folders = self._dbalbum_folders[album_uuid] + except KeyError: + logging.debug(f"Caught _dbalbum_folders KeyError for album: {album_uuid}") + return [] + + def _recurse_folder_hierarchy(folders, hierarchy=[]): + """ recursively walk the folders dict to build list of folder hierarchy """ + if not folders: + # empty folder dict (album has no folder hierarchy) + return [] + + if len(folders) != 1: + raise ValueError("Expected only a single key in folders dict") + + folder_uuid = list(folders)[0] # first and only key of dict + + parent_title = self._dbfolder_details[folder_uuid]["name"] + hierarchy.append(parent_title) + + folders = folders[folder_uuid] + if folders: + # still have elements left to recurse + hierarchy = _recurse_folder_hierarchy(folders, hierarchy=hierarchy) + return hierarchy + + # no elements left to recurse + return hierarchy + + hierarchy = _recurse_folder_hierarchy(folders) + return hierarchy + + def _album_folder_hierarchy_list_5(self, album_uuid): + """ return hierarchical list of folder names album_uuid is contained in + the folder list is in form: + ["Top level folder", "sub folder 1", "sub folder 2"] + returns empty list of album is not in any folders """ + try: + folders = self._dbalbum_folders[album_uuid] + except KeyError: + logging.debug(f"Caught _dbalbum_folders KeyError for album: {album_uuid}") + return [] + + def _recurse_folder_hierarchy(folders, hierarchy=[]): + """ recursively walk the folders dict to build list of folder hierarchy """ + + if not folders: + # empty folder dict (album has no folder hierarchy) + return [] + + if len(folders) != 1: + raise ValueError("Expected only a single key in folders dict") + + folder_uuid = list(folders)[0] # first and only key of dict + parent_title = self._dbalbum_details[folder_uuid]["title"] + hierarchy.append(parent_title) + + folders = folders[folder_uuid] + if folders: + # still have elements left to recurse + hierarchy = _recurse_folder_hierarchy(folders, hierarchy=hierarchy) + return hierarchy + + # no elements left to recurse + return hierarchy + + hierarchy = _recurse_folder_hierarchy(folders) + return hierarchy + + def _album_folder_hierarchy_folderinfo(self, album_uuid): + if self._db_version <= _PHOTOS_4_VERSION: + return self._album_folder_hierarchy_folderinfo_4(album_uuid) + else: + return self._album_folder_hierarchy_folderinfo_5(album_uuid) + + def _album_folder_hierarchy_folderinfo_4(self, album_uuid): + """ return hierarchical list of FolderInfo objects album_uuid is contained in + ["Top level folder", "sub folder 1", "sub folder 2"] + returns empty list of album is not in any folders """ + # title = photosdb._dbalbum_details[album_uuid]["title"] + folders = self._dbalbum_folders[album_uuid] + # logging.warning(f"uuid = {album_uuid}, folder = {folders}") + + def _recurse_folder_hierarchy(folders, hierarchy=[]): + """ recursively walk the folders dict to build list of folder hierarchy """ + # logging.warning(f"folders={folders},hierarchy = {hierarchy}") + if not folders: + # empty folder dict (album has no folder hierarchy) + return [] + + if len(folders) != 1: + raise ValueError("Expected only a single key in folders dict") + + folder_uuid = list(folders)[0] # first and only key of dict + hierarchy.append(FolderInfo(db=self, uuid=folder_uuid)) + + folders = folders[folder_uuid] + if folders: + # still have elements left to recurse + hierarchy = _recurse_folder_hierarchy(folders, hierarchy=hierarchy) + return hierarchy + + # no elements left to recurse + return hierarchy + + hierarchy = _recurse_folder_hierarchy(folders) + # logging.warning(f"hierarchy = {hierarchy}") + return hierarchy + + def _album_folder_hierarchy_folderinfo_5(self, album_uuid): + """ return hierarchical list of FolderInfo objects album_uuid is contained in + ["Top level folder", "sub folder 1", "sub folder 2"] + returns empty list of album is not in any folders """ + # title = photosdb._dbalbum_details[album_uuid]["title"] + folders = self._dbalbum_folders[album_uuid] + + def _recurse_folder_hierarchy(folders, hierarchy=[]): + """ recursively walk the folders dict to build list of folder hierarchy """ + + if not folders: + # empty folder dict (album has no folder hierarchy) + return [] + + if len(folders) != 1: + raise ValueError("Expected only a single key in folders dict") + + folder_uuid = list(folders)[0] # first and only key of dict + hierarchy.append(FolderInfo(db=self, uuid=folder_uuid)) + + folders = folders[folder_uuid] + if folders: + # still have elements left to recurse + hierarchy = _recurse_folder_hierarchy(folders, hierarchy=hierarchy) + return hierarchy + + # no elements left to recurse + return hierarchy + + hierarchy = _recurse_folder_hierarchy(folders) + return hierarchy + + def _get_album_uuids(self, shared=False, import_session=False): + """ Return list of album UUIDs found in photos database + + Filters out albums in the trash and any special album types + + Args: + shared: boolean; if True, returns shared albums, else normal albums + import_session: boolean, if True, returns import session albums, else normal or shared albums + Note: flags (shared, import_session) are mutually exclusive + + Raises: + ValueError: raised if mutually exclusive flags passed + + Returns: list of album UUIDs + """ + if shared and import_session: + raise ValueError( + "flags are mutually exclusive: pass zero or one of shared, import_session" + ) + + if self._db_version <= _PHOTOS_4_VERSION: + version4 = True + if shared: + logging.warning( + f"Shared albums not implemented for Photos library version {self._db_version}" + ) + return [] # not implemented for _PHOTOS_4_VERSION + elif import_session: + logging.warning( + f"Import sessions not implemented for Photos library version {self._db_version}" + ) + return [] # not implemented for _PHOTOS_4_VERSION + else: + album_kind = _PHOTOS_4_ALBUM_KIND + else: + version4 = False + if shared: + album_kind = _PHOTOS_5_SHARED_ALBUM_KIND + elif import_session: + album_kind = _PHOTOS_5_IMPORT_SESSION_ALBUM_KIND + else: + album_kind = _PHOTOS_5_ALBUM_KIND + + album_list = [] + # look through _dbalbum_details because _dbalbums_album won't have empty albums it + for album, detail in self._dbalbum_details.items(): + if ( + detail["kind"] == album_kind + and not detail["intrash"] + and ( + (shared and detail["cloudownerhashedpersonid"] is not None) + or (not shared and detail["cloudownerhashedpersonid"] is None) + ) + and ( + not version4 + # in Photos 4, special albums like "printAlbum" have kind _PHOTOS_4_ALBUM_KIND + # but should not be listed here; they can be distinguished by looking + # for folderUuid of _PHOTOS_4_ROOT_FOLDER as opposed to _PHOTOS_4_TOP_LEVEL_ALBUM + or (version4 and detail["folderUuid"] != _PHOTOS_4_ROOT_FOLDER) + ) + ): + album_list.append(album) + return album_list + + def _get_albums(self, shared=False): + """ Return list of album titles found in photos database + Albums may have duplicate titles -- these will be treated as a single album. + + Filters out albums in the trash and any special album types + + Args: + shared: boolean; if True, returns shared albums, else normal albums + + Returns: list of album names + """ + + album_uuids = self._get_album_uuids(shared=shared) + return list({self._dbalbum_details[album]["title"] for album in album_uuids}) + +
[docs] def photos( + self, + keywords=None, + uuid=None, + persons=None, + albums=None, + images=True, + movies=True, + from_date=None, + to_date=None, + intrash=False, + ): + """ Return a list of PhotoInfo objects + If called with no args, returns the entire database of photos + If called with args, returns photos matching the args (e.g. keywords, persons, etc.) + If more than one arg, returns photos matching all the criteria (e.g. keywords AND persons) + If more than one keyword, uuid, persons, albums is passed, they are treated as "OR" criteria + e.g. keywords=["wedding","vacation"] returns photos matching either keyword + from_date and to_date may be either naive or timezone-aware datetime.datetime objects. + If naive, timezone will be assumed to be local timezone. + + Args: + keywords: list of keywords to search for + uuid: list of UUIDs to search for + persons: list of persons to search for + albums: list of album names to search for + images: if True, returns image files, if False, does not return images; default is True + movies: if True, returns movie files, if False, does not return movies; default is True + from_date: return photos with creation date >= from_date (datetime.datetime object, default None) + to_date: return photos with creation date <= to_date (datetime.datetime object, default None) + intrash: if True, returns only images in "Recently deleted items" folder, + if False returns only photos that aren't deleted; default is False + + Returns: + list of PhotoInfo objects + """ + + # implementation is a bit kludgy but it works + # build a set of each search argument then compute the intersection of the sets + # use results to build a list of PhotoInfo objects + + photos_sets = [] # list of photo sets to perform intersection of + if intrash: + photos_sets.append( + {p for p in self._dbphotos if self._dbphotos[p]["intrash"]} + ) + else: + photos_sets.append( + {p for p in self._dbphotos if not self._dbphotos[p]["intrash"]} + ) + + if not any([keywords, uuid, persons, albums, from_date, to_date]): + # return all the photos, filtering for images and movies + # append keys of all photos as a single set to photos_sets + photos_sets.append(set(self._dbphotos.keys())) + else: + if albums: + album_set = set() + for album in albums: + # glob together albums with same name + if album in self._dbalbum_titles: + title_set = set() + for album_id in self._dbalbum_titles[album]: + try: + # _dbalbums_album value is list of tuples: [(uuid, sort order)] + uuid_in_album, _ = zip(*self._dbalbums_album[album_id]) + title_set.update(uuid_in_album) + except KeyError: + # an empty album will be in _dbalbum_titles but not _dbalbums_album + pass + album_set.update(title_set) + else: + logging.debug(f"Could not find album '{album}' in database") + photos_sets.append(album_set) + + if uuid: + uuid_set = set() + for u in uuid: + if u in self._dbphotos: + uuid_set.update([u]) + else: + logging.debug(f"Could not find uuid '{u}' in database") + photos_sets.append(uuid_set) + + if keywords: + keyword_set = set() + for keyword in keywords: + if keyword in self._dbkeywords_keyword: + keyword_set.update(self._dbkeywords_keyword[keyword]) + else: + logging.debug(f"Could not find keyword '{keyword}' in database") + photos_sets.append(keyword_set) + + if persons: + person_set = set() + for person in persons: + if person in self._dbpersons_fullname: + for pk in self._dbpersons_fullname[person]: + try: + person_set.update(self._dbfaces_pk[pk]) + except KeyError: + # some persons have zero photos so they won't be in _dbfaces_pk + pass + else: + logging.debug(f"Could not find person '{person}' in database") + photos_sets.append(person_set) + + if from_date or to_date: # sourcery off + dsel = self._dbphotos + if from_date: + if not datetime_has_tz(from_date): + from_date = datetime_naive_to_local(from_date) + dsel = { + k: v for k, v in dsel.items() if v["imageDate"] >= from_date + } + logging.debug( + f"Found %i items with from_date {from_date}" % len(dsel) + ) + if to_date: + if not datetime_has_tz(to_date): + to_date = datetime_naive_to_local(to_date) + dsel = {k: v for k, v in dsel.items() if v["imageDate"] <= to_date} + logging.debug(f"Found %i items with to_date {to_date}" % len(dsel)) + photos_sets.append(set(dsel.keys())) + + photoinfo = [] + if photos_sets: # found some photos + # get the intersection of each argument/search criteria + for p in set.intersection(*photos_sets): + # filter for non-selected burst photos + if self._dbphotos[p]["burst"] and not self._dbphotos[p]["burst_key"]: + # not a key/selected burst photo, don't include in returned results + continue + + # filter for images and/or movies + if (images and self._dbphotos[p]["type"] == _PHOTO_TYPE) or ( + movies and self._dbphotos[p]["type"] == _MOVIE_TYPE + ): + info = PhotoInfo(db=self, uuid=p, info=self._dbphotos[p]) + photoinfo.append(info) + if _debug: + logging.debug(f"photoinfo: {pformat(photoinfo)}") + + return photoinfo
+ +
[docs] def get_photo(self, uuid): + """ Returns a single photo matching uuid + + Arguments: + uuid: the UUID of photo to get + + Returns: + PhotoInfo instance for photo with UUID matching uuid or None if no match + """ + try: + return PhotoInfo(db=self, uuid=uuid, info=self._dbphotos[uuid]) + except KeyError: + return None
+ + # TODO: add to docs and test +
[docs] def photos_by_uuid(self, uuids): + """ Returns a list of photos with UUID in uuids. + Does not generate error if invalid or missing UUID passed. + This is faster than using PhotosDB.photos if you have list of UUIDs. + Returns photos regardless of intrash state. + + Arguments: + uuid: list of UUIDs of photos to get + + Returns: + list of PhotoInfo instance for photo with UUID matching uuid or [] if no match + """ + photos = [] + for uuid in uuids: + try: + photos.append(PhotoInfo(db=self, uuid=uuid, info=self._dbphotos[uuid])) + except KeyError: + # ignore missing/invlaid UUID + pass + return photos
+ + def __repr__(self): + return f"osxphotos.{self.__class__.__name__}(dbfile='{self.db_path}')" + + # compare two PhotosDB objects for equality + def __eq__(self, other): + if isinstance(other, self.__class__): + return self.__dict__ == other.__dict__ + + return False + + def __len__(self): + """ Returns number of photos in the database + Includes recently deleted photos and non-selected burst images + """ + return len(self._dbphotos)
+
+ +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/cli.rst b/docs/build/html/_sources/cli.rst.txt similarity index 100% rename from docs/cli.rst rename to docs/build/html/_sources/cli.rst.txt diff --git a/docs/build/html/_sources/index.rst.txt b/docs/build/html/_sources/index.rst.txt new file mode 100644 index 00000000..5e14cd04 --- /dev/null +++ b/docs/build/html/_sources/index.rst.txt @@ -0,0 +1,23 @@ +.. osxphotos documentation master file, created by + sphinx-quickstart on Sat Jan 23 13:27:27 2021. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to osxphotos's documentation! +===================================== + +.. include:: ../../README.rst + +.. toctree:: + :maxdepth: 4 + + cli + reference + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/docs/modules.rst b/docs/build/html/_sources/modules.rst.txt similarity index 100% rename from docs/modules.rst rename to docs/build/html/_sources/modules.rst.txt diff --git a/docs/reference.rst b/docs/build/html/_sources/reference.rst.txt similarity index 100% rename from docs/reference.rst rename to docs/build/html/_sources/reference.rst.txt diff --git a/docs/build/html/_static/alabaster.css b/docs/build/html/_static/alabaster.css new file mode 100644 index 00000000..0eddaeb0 --- /dev/null +++ b/docs/build/html/_static/alabaster.css @@ -0,0 +1,701 @@ +@import url("basic.css"); + +/* -- page layout ----------------------------------------------------------- */ + +body { + font-family: Georgia, serif; + font-size: 17px; + background-color: #fff; + color: #000; + margin: 0; + padding: 0; +} + + +div.document { + width: 940px; + margin: 30px auto 0 auto; +} + +div.documentwrapper { + float: left; + width: 100%; +} + +div.bodywrapper { + margin: 0 0 0 220px; +} + +div.sphinxsidebar { + width: 220px; + font-size: 14px; + line-height: 1.5; +} + +hr { + border: 1px solid #B1B4B6; +} + +div.body { + background-color: #fff; + color: #3E4349; + padding: 0 30px 0 30px; +} + +div.body > .section { + text-align: left; +} + +div.footer { + width: 940px; + margin: 20px auto 30px auto; + font-size: 14px; + color: #888; + text-align: right; +} + +div.footer a { + color: #888; +} + +p.caption { + font-family: inherit; + font-size: inherit; +} + + +div.relations { + display: none; +} + + +div.sphinxsidebar a { + color: #444; + text-decoration: none; + border-bottom: 1px dotted #999; +} + +div.sphinxsidebar a:hover { + border-bottom: 1px solid #999; +} + +div.sphinxsidebarwrapper { + padding: 18px 10px; +} + +div.sphinxsidebarwrapper p.logo { + padding: 0; + margin: -10px 0 0 0px; + text-align: center; +} + +div.sphinxsidebarwrapper h1.logo { + margin-top: -10px; + text-align: center; + margin-bottom: 5px; + text-align: left; +} + +div.sphinxsidebarwrapper h1.logo-name { + margin-top: 0px; +} + +div.sphinxsidebarwrapper p.blurb { + margin-top: 0; + font-style: normal; +} + +div.sphinxsidebar h3, +div.sphinxsidebar h4 { + font-family: Georgia, serif; + color: #444; + font-size: 24px; + font-weight: normal; + margin: 0 0 5px 0; + padding: 0; +} + +div.sphinxsidebar h4 { + font-size: 20px; +} + +div.sphinxsidebar h3 a { + color: #444; +} + +div.sphinxsidebar p.logo a, +div.sphinxsidebar h3 a, +div.sphinxsidebar p.logo a:hover, +div.sphinxsidebar h3 a:hover { + border: none; +} + +div.sphinxsidebar p { + color: #555; + margin: 10px 0; +} + +div.sphinxsidebar ul { + margin: 10px 0; + padding: 0; + color: #000; +} + +div.sphinxsidebar ul li.toctree-l1 > a { + font-size: 120%; +} + +div.sphinxsidebar ul li.toctree-l2 > a { + font-size: 110%; +} + +div.sphinxsidebar input { + border: 1px solid #CCC; + font-family: Georgia, serif; + font-size: 1em; +} + +div.sphinxsidebar hr { + border: none; + height: 1px; + color: #AAA; + background: #AAA; + + text-align: left; + margin-left: 0; + width: 50%; +} + +div.sphinxsidebar .badge { + border-bottom: none; +} + +div.sphinxsidebar .badge:hover { + border-bottom: none; +} + +/* To address an issue with donation coming after search */ +div.sphinxsidebar h3.donation { + margin-top: 10px; +} + +/* -- body styles ----------------------------------------------------------- */ + +a { + color: #004B6B; + text-decoration: underline; +} + +a:hover { + color: #6D4100; + text-decoration: underline; +} + +div.body h1, +div.body h2, +div.body h3, +div.body h4, +div.body h5, +div.body h6 { + font-family: Georgia, serif; + font-weight: normal; + margin: 30px 0px 10px 0px; + padding: 0; +} + +div.body h1 { margin-top: 0; padding-top: 0; font-size: 240%; } +div.body h2 { font-size: 180%; } +div.body h3 { font-size: 150%; } +div.body h4 { font-size: 130%; } +div.body h5 { font-size: 100%; } +div.body h6 { font-size: 100%; } + +a.headerlink { + color: #DDD; + padding: 0 4px; + text-decoration: none; +} + +a.headerlink:hover { + color: #444; + background: #EAEAEA; +} + +div.body p, div.body dd, div.body li { + line-height: 1.4em; +} + +div.admonition { + margin: 20px 0px; + padding: 10px 30px; + background-color: #EEE; + border: 1px solid #CCC; +} + +div.admonition tt.xref, div.admonition code.xref, div.admonition a tt { + background-color: #FBFBFB; + border-bottom: 1px solid #fafafa; +} + +div.admonition p.admonition-title { + font-family: Georgia, serif; + font-weight: normal; + font-size: 24px; + margin: 0 0 10px 0; + padding: 0; + line-height: 1; +} + +div.admonition p.last { + margin-bottom: 0; +} + +div.highlight { + background-color: #fff; +} + +dt:target, .highlight { + background: #FAF3E8; +} + +div.warning { + background-color: #FCC; + border: 1px solid #FAA; +} + +div.danger { + background-color: #FCC; + border: 1px solid #FAA; + -moz-box-shadow: 2px 2px 4px #D52C2C; + -webkit-box-shadow: 2px 2px 4px #D52C2C; + box-shadow: 2px 2px 4px #D52C2C; +} + +div.error { + background-color: #FCC; + border: 1px solid #FAA; + -moz-box-shadow: 2px 2px 4px #D52C2C; + -webkit-box-shadow: 2px 2px 4px #D52C2C; + box-shadow: 2px 2px 4px #D52C2C; +} + +div.caution { + background-color: #FCC; + border: 1px solid #FAA; +} + +div.attention { + background-color: #FCC; + border: 1px solid #FAA; +} + +div.important { + background-color: #EEE; + border: 1px solid #CCC; +} + +div.note { + background-color: #EEE; + border: 1px solid #CCC; +} + +div.tip { + background-color: #EEE; + border: 1px solid #CCC; +} + +div.hint { + background-color: #EEE; + border: 1px solid #CCC; +} + +div.seealso { + background-color: #EEE; + border: 1px solid #CCC; +} + +div.topic { + background-color: #EEE; +} + +p.admonition-title { + display: inline; +} + +p.admonition-title:after { + content: ":"; +} + +pre, tt, code { + font-family: 'Consolas', 'Menlo', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', monospace; + font-size: 0.9em; +} + +.hll { + background-color: #FFC; + margin: 0 -12px; + padding: 0 12px; + display: block; +} + +img.screenshot { +} + +tt.descname, tt.descclassname, code.descname, code.descclassname { + font-size: 0.95em; +} + +tt.descname, code.descname { + padding-right: 0.08em; +} + +img.screenshot { + -moz-box-shadow: 2px 2px 4px #EEE; + -webkit-box-shadow: 2px 2px 4px #EEE; + box-shadow: 2px 2px 4px #EEE; +} + +table.docutils { + border: 1px solid #888; + -moz-box-shadow: 2px 2px 4px #EEE; + -webkit-box-shadow: 2px 2px 4px #EEE; + box-shadow: 2px 2px 4px #EEE; +} + +table.docutils td, table.docutils th { + border: 1px solid #888; + padding: 0.25em 0.7em; +} + +table.field-list, table.footnote { + border: none; + -moz-box-shadow: none; + -webkit-box-shadow: none; + box-shadow: none; +} + +table.footnote { + margin: 15px 0; + width: 100%; + border: 1px solid #EEE; + background: #FDFDFD; + font-size: 0.9em; +} + +table.footnote + table.footnote { + margin-top: -15px; + border-top: none; +} + +table.field-list th { + padding: 0 0.8em 0 0; +} + +table.field-list td { + padding: 0; +} + +table.field-list p { + margin-bottom: 0.8em; +} + +/* Cloned from + * https://github.com/sphinx-doc/sphinx/commit/ef60dbfce09286b20b7385333d63a60321784e68 + */ +.field-name { + -moz-hyphens: manual; + -ms-hyphens: manual; + -webkit-hyphens: manual; + hyphens: manual; +} + +table.footnote td.label { + width: .1px; + padding: 0.3em 0 0.3em 0.5em; +} + +table.footnote td { + padding: 0.3em 0.5em; +} + +dl { + margin: 0; + padding: 0; +} + +dl dd { + margin-left: 30px; +} + +blockquote { + margin: 0 0 0 30px; + padding: 0; +} + +ul, ol { + /* Matches the 30px from the narrow-screen "li > ul" selector below */ + margin: 10px 0 10px 30px; + padding: 0; +} + +pre { + background: #EEE; + padding: 7px 30px; + margin: 15px 0px; + line-height: 1.3em; +} + +div.viewcode-block:target { + background: #ffd; +} + +dl pre, blockquote pre, li pre { + margin-left: 0; + padding-left: 30px; +} + +tt, code { + background-color: #ecf0f3; + color: #222; + /* padding: 1px 2px; */ +} + +tt.xref, code.xref, a tt { + background-color: #FBFBFB; + border-bottom: 1px solid #fff; +} + +a.reference { + text-decoration: none; + border-bottom: 1px dotted #004B6B; +} + +/* Don't put an underline on images */ +a.image-reference, a.image-reference:hover { + border-bottom: none; +} + +a.reference:hover { + border-bottom: 1px solid #6D4100; +} + +a.footnote-reference { + text-decoration: none; + font-size: 0.7em; + vertical-align: top; + border-bottom: 1px dotted #004B6B; +} + +a.footnote-reference:hover { + border-bottom: 1px solid #6D4100; +} + +a:hover tt, a:hover code { + background: #EEE; +} + + +@media screen and (max-width: 870px) { + + div.sphinxsidebar { + display: none; + } + + div.document { + width: 100%; + + } + + div.documentwrapper { + margin-left: 0; + margin-top: 0; + margin-right: 0; + margin-bottom: 0; + } + + div.bodywrapper { + margin-top: 0; + margin-right: 0; + margin-bottom: 0; + margin-left: 0; + } + + ul { + margin-left: 0; + } + + li > ul { + /* Matches the 30px from the "ul, ol" selector above */ + margin-left: 30px; + } + + .document { + width: auto; + } + + .footer { + width: auto; + } + + .bodywrapper { + margin: 0; + } + + .footer { + width: auto; + } + + .github { + display: none; + } + + + +} + + + +@media screen and (max-width: 875px) { + + body { + margin: 0; + padding: 20px 30px; + } + + div.documentwrapper { + float: none; + background: #fff; + } + + div.sphinxsidebar { + display: block; + float: none; + width: 102.5%; + margin: 50px -30px -20px -30px; + padding: 10px 20px; + background: #333; + color: #FFF; + } + + div.sphinxsidebar h3, div.sphinxsidebar h4, div.sphinxsidebar p, + div.sphinxsidebar h3 a { + color: #fff; + } + + div.sphinxsidebar a { + color: #AAA; + } + + div.sphinxsidebar p.logo { + display: none; + } + + div.document { + width: 100%; + margin: 0; + } + + div.footer { + display: none; + } + + div.bodywrapper { + margin: 0; + } + + div.body { + min-height: 0; + padding: 0; + } + + .rtd_doc_footer { + display: none; + } + + .document { + width: auto; + } + + .footer { + width: auto; + } + + .footer { + width: auto; + } + + .github { + display: none; + } +} + + +/* misc. */ + +.revsys-inline { + display: none!important; +} + +/* Make nested-list/multi-paragraph items look better in Releases changelog + * pages. Without this, docutils' magical list fuckery causes inconsistent + * formatting between different release sub-lists. + */ +div#changelog > div.section > ul > li > p:only-child { + margin-bottom: 0; +} + +/* Hide fugly table cell borders in ..bibliography:: directive output */ +table.docutils.citation, table.docutils.citation td, table.docutils.citation th { + border: none; + /* Below needed in some edge cases; if not applied, bottom shadows appear */ + -moz-box-shadow: none; + -webkit-box-shadow: none; + box-shadow: none; +} + + +/* relbar */ + +.related { + line-height: 30px; + width: 100%; + font-size: 0.9rem; +} + +.related.top { + border-bottom: 1px solid #EEE; + margin-bottom: 20px; +} + +.related.bottom { + border-top: 1px solid #EEE; +} + +.related ul { + padding: 0; + margin: 0; + list-style: none; +} + +.related li { + display: inline; +} + +nav#rellinks { + float: right; +} + +nav#rellinks li+li:before { + content: "|"; +} + +nav#breadcrumbs li+li:before { + content: "\00BB"; +} + +/* Hide certain items when printing */ +@media print { + div.related { + display: none; + } +} \ No newline at end of file diff --git a/docs/build/html/_static/basic.css b/docs/build/html/_static/basic.css new file mode 100644 index 00000000..be19270e --- /dev/null +++ b/docs/build/html/_static/basic.css @@ -0,0 +1,856 @@ +/* + * basic.css + * ~~~~~~~~~ + * + * Sphinx stylesheet -- basic theme. + * + * :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +/* -- main layout ----------------------------------------------------------- */ + +div.clearer { + clear: both; +} + +div.section::after { + display: block; + content: ''; + clear: left; +} + +/* -- relbar ---------------------------------------------------------------- */ + +div.related { + width: 100%; + font-size: 90%; +} + +div.related h3 { + display: none; +} + +div.related ul { + margin: 0; + padding: 0 0 0 10px; + list-style: none; +} + +div.related li { + display: inline; +} + +div.related li.right { + float: right; + margin-right: 5px; +} + +/* -- sidebar --------------------------------------------------------------- */ + +div.sphinxsidebarwrapper { + padding: 10px 5px 0 10px; +} + +div.sphinxsidebar { + float: left; + width: 230px; + margin-left: -100%; + font-size: 90%; + word-wrap: break-word; + overflow-wrap : break-word; +} + +div.sphinxsidebar ul { + list-style: none; +} + +div.sphinxsidebar ul ul, +div.sphinxsidebar ul.want-points { + margin-left: 20px; + list-style: square; +} + +div.sphinxsidebar ul ul { + margin-top: 0; + margin-bottom: 0; +} + +div.sphinxsidebar form { + margin-top: 10px; +} + +div.sphinxsidebar input { + border: 1px solid #98dbcc; + font-family: sans-serif; + font-size: 1em; +} + +div.sphinxsidebar #searchbox form.search { + overflow: hidden; +} + +div.sphinxsidebar #searchbox input[type="text"] { + float: left; + width: 80%; + padding: 0.25em; + box-sizing: border-box; +} + +div.sphinxsidebar #searchbox input[type="submit"] { + float: left; + width: 20%; + border-left: none; + padding: 0.25em; + box-sizing: border-box; +} + + +img { + border: 0; + max-width: 100%; +} + +/* -- search page ----------------------------------------------------------- */ + +ul.search { + margin: 10px 0 0 20px; + padding: 0; +} + +ul.search li { + padding: 5px 0 5px 20px; + background-image: url(file.png); + background-repeat: no-repeat; + background-position: 0 7px; +} + +ul.search li a { + font-weight: bold; +} + +ul.search li div.context { + color: #888; + margin: 2px 0 0 30px; + text-align: left; +} + +ul.keywordmatches li.goodmatch a { + font-weight: bold; +} + +/* -- index page ------------------------------------------------------------ */ + +table.contentstable { + width: 90%; + margin-left: auto; + margin-right: auto; +} + +table.contentstable p.biglink { + line-height: 150%; +} + +a.biglink { + font-size: 1.3em; +} + +span.linkdescr { + font-style: italic; + padding-top: 5px; + font-size: 90%; +} + +/* -- general index --------------------------------------------------------- */ + +table.indextable { + width: 100%; +} + +table.indextable td { + text-align: left; + vertical-align: top; +} + +table.indextable ul { + margin-top: 0; + margin-bottom: 0; + list-style-type: none; +} + +table.indextable > tbody > tr > td > ul { + padding-left: 0em; +} + +table.indextable tr.pcap { + height: 10px; +} + +table.indextable tr.cap { + margin-top: 10px; + background-color: #f2f2f2; +} + +img.toggler { + margin-right: 3px; + margin-top: 3px; + cursor: pointer; +} + +div.modindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +div.genindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +/* -- domain module index --------------------------------------------------- */ + +table.modindextable td { + padding: 2px; + border-collapse: collapse; +} + +/* -- general body styles --------------------------------------------------- */ + +div.body { + min-width: 450px; + max-width: 800px; +} + +div.body p, div.body dd, div.body li, div.body blockquote { + -moz-hyphens: auto; + -ms-hyphens: auto; + -webkit-hyphens: auto; + hyphens: auto; +} + +a.headerlink { + visibility: hidden; +} + +a.brackets:before, +span.brackets > a:before{ + content: "["; +} + +a.brackets:after, +span.brackets > a:after { + content: "]"; +} + +h1:hover > a.headerlink, +h2:hover > a.headerlink, +h3:hover > a.headerlink, +h4:hover > a.headerlink, +h5:hover > a.headerlink, +h6:hover > a.headerlink, +dt:hover > a.headerlink, +caption:hover > a.headerlink, +p.caption:hover > a.headerlink, +div.code-block-caption:hover > a.headerlink { + visibility: visible; +} + +div.body p.caption { + text-align: inherit; +} + +div.body td { + text-align: left; +} + +.first { + margin-top: 0 !important; +} + +p.rubric { + margin-top: 30px; + font-weight: bold; +} + +img.align-left, .figure.align-left, object.align-left { + clear: left; + float: left; + margin-right: 1em; +} + +img.align-right, .figure.align-right, object.align-right { + clear: right; + float: right; + margin-left: 1em; +} + +img.align-center, .figure.align-center, object.align-center { + display: block; + margin-left: auto; + margin-right: auto; +} + +img.align-default, .figure.align-default { + display: block; + margin-left: auto; + margin-right: auto; +} + +.align-left { + text-align: left; +} + +.align-center { + text-align: center; +} + +.align-default { + text-align: center; +} + +.align-right { + text-align: right; +} + +/* -- sidebars -------------------------------------------------------------- */ + +div.sidebar { + margin: 0 0 0.5em 1em; + border: 1px solid #ddb; + padding: 7px; + background-color: #ffe; + width: 40%; + float: right; + clear: right; + overflow-x: auto; +} + +p.sidebar-title { + font-weight: bold; +} + +div.admonition, div.topic, blockquote { + clear: left; +} + +/* -- topics ---------------------------------------------------------------- */ + +div.topic { + border: 1px solid #ccc; + padding: 7px; + margin: 10px 0 10px 0; +} + +p.topic-title { + font-size: 1.1em; + font-weight: bold; + margin-top: 10px; +} + +/* -- admonitions ----------------------------------------------------------- */ + +div.admonition { + margin-top: 10px; + margin-bottom: 10px; + padding: 7px; +} + +div.admonition dt { + font-weight: bold; +} + +p.admonition-title { + margin: 0px 10px 5px 0px; + font-weight: bold; +} + +div.body p.centered { + text-align: center; + margin-top: 25px; +} + +/* -- content of sidebars/topics/admonitions -------------------------------- */ + +div.sidebar > :last-child, +div.topic > :last-child, +div.admonition > :last-child { + margin-bottom: 0; +} + +div.sidebar::after, +div.topic::after, +div.admonition::after, +blockquote::after { + display: block; + content: ''; + clear: both; +} + +/* -- tables ---------------------------------------------------------------- */ + +table.docutils { + margin-top: 10px; + margin-bottom: 10px; + border: 0; + border-collapse: collapse; +} + +table.align-center { + margin-left: auto; + margin-right: auto; +} + +table.align-default { + margin-left: auto; + margin-right: auto; +} + +table caption span.caption-number { + font-style: italic; +} + +table caption span.caption-text { +} + +table.docutils td, table.docutils th { + padding: 1px 8px 1px 5px; + border-top: 0; + border-left: 0; + border-right: 0; + border-bottom: 1px solid #aaa; +} + +table.footnote td, table.footnote th { + border: 0 !important; +} + +th { + text-align: left; + padding-right: 5px; +} + +table.citation { + border-left: solid 1px gray; + margin-left: 1px; +} + +table.citation td { + border-bottom: none; +} + +th > :first-child, +td > :first-child { + margin-top: 0px; +} + +th > :last-child, +td > :last-child { + margin-bottom: 0px; +} + +/* -- figures --------------------------------------------------------------- */ + +div.figure { + margin: 0.5em; + padding: 0.5em; +} + +div.figure p.caption { + padding: 0.3em; +} + +div.figure p.caption span.caption-number { + font-style: italic; +} + +div.figure p.caption span.caption-text { +} + +/* -- field list styles ----------------------------------------------------- */ + +table.field-list td, table.field-list th { + border: 0 !important; +} + +.field-list ul { + margin: 0; + padding-left: 1em; +} + +.field-list p { + margin: 0; +} + +.field-name { + -moz-hyphens: manual; + -ms-hyphens: manual; + -webkit-hyphens: manual; + hyphens: manual; +} + +/* -- hlist styles ---------------------------------------------------------- */ + +table.hlist { + margin: 1em 0; +} + +table.hlist td { + vertical-align: top; +} + + +/* -- other body styles ----------------------------------------------------- */ + +ol.arabic { + list-style: decimal; +} + +ol.loweralpha { + list-style: lower-alpha; +} + +ol.upperalpha { + list-style: upper-alpha; +} + +ol.lowerroman { + list-style: lower-roman; +} + +ol.upperroman { + list-style: upper-roman; +} + +:not(li) > ol > li:first-child > :first-child, +:not(li) > ul > li:first-child > :first-child { + margin-top: 0px; +} + +:not(li) > ol > li:last-child > :last-child, +:not(li) > ul > li:last-child > :last-child { + margin-bottom: 0px; +} + +ol.simple ol p, +ol.simple ul p, +ul.simple ol p, +ul.simple ul p { + margin-top: 0; +} + +ol.simple > li:not(:first-child) > p, +ul.simple > li:not(:first-child) > p { + margin-top: 0; +} + +ol.simple p, +ul.simple p { + margin-bottom: 0; +} + +dl.footnote > dt, +dl.citation > dt { + float: left; + margin-right: 0.5em; +} + +dl.footnote > dd, +dl.citation > dd { + margin-bottom: 0em; +} + +dl.footnote > dd:after, +dl.citation > dd:after { + content: ""; + clear: both; +} + +dl.field-list { + display: grid; + grid-template-columns: fit-content(30%) auto; +} + +dl.field-list > dt { + font-weight: bold; + word-break: break-word; + padding-left: 0.5em; + padding-right: 5px; +} + +dl.field-list > dt:after { + content: ":"; +} + +dl.field-list > dd { + padding-left: 0.5em; + margin-top: 0em; + margin-left: 0em; + margin-bottom: 0em; +} + +dl { + margin-bottom: 15px; +} + +dd > :first-child { + margin-top: 0px; +} + +dd ul, dd table { + margin-bottom: 10px; +} + +dd { + margin-top: 3px; + margin-bottom: 10px; + margin-left: 30px; +} + +dl > dd:last-child, +dl > dd:last-child > :last-child { + margin-bottom: 0; +} + +dt:target, span.highlighted { + background-color: #fbe54e; +} + +rect.highlighted { + fill: #fbe54e; +} + +dl.glossary dt { + font-weight: bold; + font-size: 1.1em; +} + +.optional { + font-size: 1.3em; +} + +.sig-paren { + font-size: larger; +} + +.versionmodified { + font-style: italic; +} + +.system-message { + background-color: #fda; + padding: 5px; + border: 3px solid red; +} + +.footnote:target { + background-color: #ffa; +} + +.line-block { + display: block; + margin-top: 1em; + margin-bottom: 1em; +} + +.line-block .line-block { + margin-top: 0; + margin-bottom: 0; + margin-left: 1.5em; +} + +.guilabel, .menuselection { + font-family: sans-serif; +} + +.accelerator { + text-decoration: underline; +} + +.classifier { + font-style: oblique; +} + +.classifier:before { + font-style: normal; + margin: 0.5em; + content: ":"; +} + +abbr, acronym { + border-bottom: dotted 1px; + cursor: help; +} + +/* -- code displays --------------------------------------------------------- */ + +pre { + overflow: auto; + overflow-y: hidden; /* fixes display issues on Chrome browsers */ +} + +pre, div[class*="highlight-"] { + clear: both; +} + +span.pre { + -moz-hyphens: none; + -ms-hyphens: none; + -webkit-hyphens: none; + hyphens: none; +} + +div[class*="highlight-"] { + margin: 1em 0; +} + +td.linenos pre { + border: 0; + background-color: transparent; + color: #aaa; +} + +table.highlighttable { + display: block; +} + +table.highlighttable tbody { + display: block; +} + +table.highlighttable tr { + display: flex; +} + +table.highlighttable td { + margin: 0; + padding: 0; +} + +table.highlighttable td.linenos { + padding-right: 0.5em; +} + +table.highlighttable td.code { + flex: 1; + overflow: hidden; +} + +.highlight .hll { + display: block; +} + +div.highlight pre, +table.highlighttable pre { + margin: 0; +} + +div.code-block-caption + div { + margin-top: 0; +} + +div.code-block-caption { + margin-top: 1em; + padding: 2px 5px; + font-size: small; +} + +div.code-block-caption code { + background-color: transparent; +} + +table.highlighttable td.linenos, +span.linenos, +div.doctest > div.highlight span.gp { /* gp: Generic.Prompt */ + user-select: none; +} + +div.code-block-caption span.caption-number { + padding: 0.1em 0.3em; + font-style: italic; +} + +div.code-block-caption span.caption-text { +} + +div.literal-block-wrapper { + margin: 1em 0; +} + +code.descname { + background-color: transparent; + font-weight: bold; + font-size: 1.2em; +} + +code.descclassname { + background-color: transparent; +} + +code.xref, a code { + background-color: transparent; + font-weight: bold; +} + +h1 code, h2 code, h3 code, h4 code, h5 code, h6 code { + background-color: transparent; +} + +.viewcode-link { + float: right; +} + +.viewcode-back { + float: right; + font-family: sans-serif; +} + +div.viewcode-block:target { + margin: -1px -10px; + padding: 0 10px; +} + +/* -- math display ---------------------------------------------------------- */ + +img.math { + vertical-align: middle; +} + +div.body div.math p { + text-align: center; +} + +span.eqno { + float: right; +} + +span.eqno a.headerlink { + position: absolute; + z-index: 1; +} + +div.math:hover a.headerlink { + visibility: visible; +} + +/* -- printout stylesheet --------------------------------------------------- */ + +@media print { + div.document, + div.documentwrapper, + div.bodywrapper { + margin: 0 !important; + width: 100%; + } + + div.sphinxsidebar, + div.related, + div.footer, + #top-link { + display: none; + } +} \ No newline at end of file diff --git a/docs/build/html/_static/custom.css b/docs/build/html/_static/custom.css new file mode 100644 index 00000000..2a924f1d --- /dev/null +++ b/docs/build/html/_static/custom.css @@ -0,0 +1 @@ +/* This file intentionally left blank. */ diff --git a/docs/build/html/_static/doctools.js b/docs/build/html/_static/doctools.js new file mode 100644 index 00000000..144884ea --- /dev/null +++ b/docs/build/html/_static/doctools.js @@ -0,0 +1,316 @@ +/* + * doctools.js + * ~~~~~~~~~~~ + * + * Sphinx JavaScript utilities for all documentation. + * + * :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +/** + * select a different prefix for underscore + */ +$u = _.noConflict(); + +/** + * make the code below compatible with browsers without + * an installed firebug like debugger +if (!window.console || !console.firebug) { + var names = ["log", "debug", "info", "warn", "error", "assert", "dir", + "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", + "profile", "profileEnd"]; + window.console = {}; + for (var i = 0; i < names.length; ++i) + window.console[names[i]] = function() {}; +} + */ + +/** + * small helper function to urldecode strings + */ +jQuery.urldecode = function(x) { + return decodeURIComponent(x).replace(/\+/g, ' '); +}; + +/** + * small helper function to urlencode strings + */ +jQuery.urlencode = encodeURIComponent; + +/** + * This function returns the parsed url parameters of the + * current request. Multiple values per key are supported, + * it will always return arrays of strings for the value parts. + */ +jQuery.getQueryParameters = function(s) { + if (typeof s === 'undefined') + s = document.location.search; + var parts = s.substr(s.indexOf('?') + 1).split('&'); + var result = {}; + for (var i = 0; i < parts.length; i++) { + var tmp = parts[i].split('=', 2); + var key = jQuery.urldecode(tmp[0]); + var value = jQuery.urldecode(tmp[1]); + if (key in result) + result[key].push(value); + else + result[key] = [value]; + } + return result; +}; + +/** + * highlight a given string on a jquery object by wrapping it in + * span elements with the given class name. + */ +jQuery.fn.highlightText = function(text, className) { + function highlight(node, addItems) { + if (node.nodeType === 3) { + var val = node.nodeValue; + var pos = val.toLowerCase().indexOf(text); + if (pos >= 0 && + !jQuery(node.parentNode).hasClass(className) && + !jQuery(node.parentNode).hasClass("nohighlight")) { + var span; + var isInSVG = jQuery(node).closest("body, svg, foreignObject").is("svg"); + if (isInSVG) { + span = document.createElementNS("http://www.w3.org/2000/svg", "tspan"); + } else { + span = document.createElement("span"); + span.className = className; + } + span.appendChild(document.createTextNode(val.substr(pos, text.length))); + node.parentNode.insertBefore(span, node.parentNode.insertBefore( + document.createTextNode(val.substr(pos + text.length)), + node.nextSibling)); + node.nodeValue = val.substr(0, pos); + if (isInSVG) { + var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect"); + var bbox = node.parentElement.getBBox(); + rect.x.baseVal.value = bbox.x; + rect.y.baseVal.value = bbox.y; + rect.width.baseVal.value = bbox.width; + rect.height.baseVal.value = bbox.height; + rect.setAttribute('class', className); + addItems.push({ + "parent": node.parentNode, + "target": rect}); + } + } + } + else if (!jQuery(node).is("button, select, textarea")) { + jQuery.each(node.childNodes, function() { + highlight(this, addItems); + }); + } + } + var addItems = []; + var result = this.each(function() { + highlight(this, addItems); + }); + for (var i = 0; i < addItems.length; ++i) { + jQuery(addItems[i].parent).before(addItems[i].target); + } + return result; +}; + +/* + * backward compatibility for jQuery.browser + * This will be supported until firefox bug is fixed. + */ +if (!jQuery.browser) { + jQuery.uaMatch = function(ua) { + ua = ua.toLowerCase(); + + var match = /(chrome)[ \/]([\w.]+)/.exec(ua) || + /(webkit)[ \/]([\w.]+)/.exec(ua) || + /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || + /(msie) ([\w.]+)/.exec(ua) || + ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || + []; + + return { + browser: match[ 1 ] || "", + version: match[ 2 ] || "0" + }; + }; + jQuery.browser = {}; + jQuery.browser[jQuery.uaMatch(navigator.userAgent).browser] = true; +} + +/** + * Small JavaScript module for the documentation. + */ +var Documentation = { + + init : function() { + this.fixFirefoxAnchorBug(); + this.highlightSearchWords(); + this.initIndexTable(); + if (DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) { + this.initOnKeyListeners(); + } + }, + + /** + * i18n support + */ + TRANSLATIONS : {}, + PLURAL_EXPR : function(n) { return n === 1 ? 0 : 1; }, + LOCALE : 'unknown', + + // gettext and ngettext don't access this so that the functions + // can safely bound to a different name (_ = Documentation.gettext) + gettext : function(string) { + var translated = Documentation.TRANSLATIONS[string]; + if (typeof translated === 'undefined') + return string; + return (typeof translated === 'string') ? translated : translated[0]; + }, + + ngettext : function(singular, plural, n) { + var translated = Documentation.TRANSLATIONS[singular]; + if (typeof translated === 'undefined') + return (n == 1) ? singular : plural; + return translated[Documentation.PLURALEXPR(n)]; + }, + + addTranslations : function(catalog) { + for (var key in catalog.messages) + this.TRANSLATIONS[key] = catalog.messages[key]; + this.PLURAL_EXPR = new Function('n', 'return +(' + catalog.plural_expr + ')'); + this.LOCALE = catalog.locale; + }, + + /** + * add context elements like header anchor links + */ + addContextElements : function() { + $('div[id] > :header:first').each(function() { + $('\u00B6'). + attr('href', '#' + this.id). + attr('title', _('Permalink to this headline')). + appendTo(this); + }); + $('dt[id]').each(function() { + $('\u00B6'). + attr('href', '#' + this.id). + attr('title', _('Permalink to this definition')). + appendTo(this); + }); + }, + + /** + * workaround a firefox stupidity + * see: https://bugzilla.mozilla.org/show_bug.cgi?id=645075 + */ + fixFirefoxAnchorBug : function() { + if (document.location.hash && $.browser.mozilla) + window.setTimeout(function() { + document.location.href += ''; + }, 10); + }, + + /** + * highlight the search words provided in the url in the text + */ + highlightSearchWords : function() { + var params = $.getQueryParameters(); + var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : []; + if (terms.length) { + var body = $('div.body'); + if (!body.length) { + body = $('body'); + } + window.setTimeout(function() { + $.each(terms, function() { + body.highlightText(this.toLowerCase(), 'highlighted'); + }); + }, 10); + $('') + .appendTo($('#searchbox')); + } + }, + + /** + * init the domain index toggle buttons + */ + initIndexTable : function() { + var togglers = $('img.toggler').click(function() { + var src = $(this).attr('src'); + var idnum = $(this).attr('id').substr(7); + $('tr.cg-' + idnum).toggle(); + if (src.substr(-9) === 'minus.png') + $(this).attr('src', src.substr(0, src.length-9) + 'plus.png'); + else + $(this).attr('src', src.substr(0, src.length-8) + 'minus.png'); + }).css('display', ''); + if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) { + togglers.click(); + } + }, + + /** + * helper function to hide the search marks again + */ + hideSearchWords : function() { + $('#searchbox .highlight-link').fadeOut(300); + $('span.highlighted').removeClass('highlighted'); + }, + + /** + * make the url absolute + */ + makeURL : function(relativeURL) { + return DOCUMENTATION_OPTIONS.URL_ROOT + '/' + relativeURL; + }, + + /** + * get the current relative url + */ + getCurrentURL : function() { + var path = document.location.pathname; + var parts = path.split(/\//); + $.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() { + if (this === '..') + parts.pop(); + }); + var url = parts.join('/'); + return path.substring(url.lastIndexOf('/') + 1, path.length - 1); + }, + + initOnKeyListeners: function() { + $(document).keydown(function(event) { + var activeElementType = document.activeElement.tagName; + // don't navigate when in search box, textarea, dropdown or button + if (activeElementType !== 'TEXTAREA' && activeElementType !== 'INPUT' && activeElementType !== 'SELECT' + && activeElementType !== 'BUTTON' && !event.altKey && !event.ctrlKey && !event.metaKey + && !event.shiftKey) { + switch (event.keyCode) { + case 37: // left + var prevHref = $('link[rel="prev"]').prop('href'); + if (prevHref) { + window.location.href = prevHref; + return false; + } + case 39: // right + var nextHref = $('link[rel="next"]').prop('href'); + if (nextHref) { + window.location.href = nextHref; + return false; + } + } + } + }); + } +}; + +// quick alias for translations +_ = Documentation.gettext; + +$(document).ready(function() { + Documentation.init(); +}); diff --git a/docs/build/html/_static/documentation_options.js b/docs/build/html/_static/documentation_options.js new file mode 100644 index 00000000..6b1b68b6 --- /dev/null +++ b/docs/build/html/_static/documentation_options.js @@ -0,0 +1,12 @@ +var DOCUMENTATION_OPTIONS = { + URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'), + VERSION: '0.40.4', + LANGUAGE: 'None', + COLLAPSE_INDEX: false, + BUILDER: 'html', + FILE_SUFFIX: '.html', + LINK_SUFFIX: '.html', + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt', + NAVIGATION_WITH_KEYS: false +}; \ No newline at end of file diff --git a/docs/build/html/_static/file.png b/docs/build/html/_static/file.png new file mode 100644 index 00000000..a858a410 Binary files /dev/null and b/docs/build/html/_static/file.png differ diff --git a/docs/build/html/_static/jquery-3.5.1.js b/docs/build/html/_static/jquery-3.5.1.js new file mode 100644 index 00000000..50937333 --- /dev/null +++ b/docs/build/html/_static/jquery-3.5.1.js @@ -0,0 +1,10872 @@ +/*! + * jQuery JavaScript Library v3.5.1 + * https://jquery.com/ + * + * Includes Sizzle.js + * https://sizzlejs.com/ + * + * Copyright JS Foundation and other contributors + * Released under the MIT license + * https://jquery.org/license + * + * Date: 2020-05-04T22:49Z + */ +( function( global, factory ) { + + "use strict"; + + if ( typeof module === "object" && typeof module.exports === "object" ) { + + // For CommonJS and CommonJS-like environments where a proper `window` + // is present, execute the factory and get jQuery. + // For environments that do not have a `window` with a `document` + // (such as Node.js), expose a factory as module.exports. + // This accentuates the need for the creation of a real `window`. + // e.g. var jQuery = require("jquery")(window); + // See ticket #14549 for more info. + module.exports = global.document ? + factory( global, true ) : + function( w ) { + if ( !w.document ) { + throw new Error( "jQuery requires a window with a document" ); + } + return factory( w ); + }; + } else { + factory( global ); + } + +// Pass this if window is not defined yet +} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { + +// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 +// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode +// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common +// enough that all such attempts are guarded in a try block. +"use strict"; + +var arr = []; + +var getProto = Object.getPrototypeOf; + +var slice = arr.slice; + +var flat = arr.flat ? function( array ) { + return arr.flat.call( array ); +} : function( array ) { + return arr.concat.apply( [], array ); +}; + + +var push = arr.push; + +var indexOf = arr.indexOf; + +var class2type = {}; + +var toString = class2type.toString; + +var hasOwn = class2type.hasOwnProperty; + +var fnToString = hasOwn.toString; + +var ObjectFunctionString = fnToString.call( Object ); + +var support = {}; + +var isFunction = function isFunction( obj ) { + + // Support: Chrome <=57, Firefox <=52 + // In some browsers, typeof returns "function" for HTML elements + // (i.e., `typeof document.createElement( "object" ) === "function"`). + // We don't want to classify *any* DOM node as a function. + return typeof obj === "function" && typeof obj.nodeType !== "number"; + }; + + +var isWindow = function isWindow( obj ) { + return obj != null && obj === obj.window; + }; + + +var document = window.document; + + + + var preservedScriptAttributes = { + type: true, + src: true, + nonce: true, + noModule: true + }; + + function DOMEval( code, node, doc ) { + doc = doc || document; + + var i, val, + script = doc.createElement( "script" ); + + script.text = code; + if ( node ) { + for ( i in preservedScriptAttributes ) { + + // Support: Firefox 64+, Edge 18+ + // Some browsers don't support the "nonce" property on scripts. + // On the other hand, just using `getAttribute` is not enough as + // the `nonce` attribute is reset to an empty string whenever it + // becomes browsing-context connected. + // See https://github.com/whatwg/html/issues/2369 + // See https://html.spec.whatwg.org/#nonce-attributes + // The `node.getAttribute` check was added for the sake of + // `jQuery.globalEval` so that it can fake a nonce-containing node + // via an object. + val = node[ i ] || node.getAttribute && node.getAttribute( i ); + if ( val ) { + script.setAttribute( i, val ); + } + } + } + doc.head.appendChild( script ).parentNode.removeChild( script ); + } + + +function toType( obj ) { + if ( obj == null ) { + return obj + ""; + } + + // Support: Android <=2.3 only (functionish RegExp) + return typeof obj === "object" || typeof obj === "function" ? + class2type[ toString.call( obj ) ] || "object" : + typeof obj; +} +/* global Symbol */ +// Defining this global in .eslintrc.json would create a danger of using the global +// unguarded in another place, it seems safer to define global only for this module + + + +var + version = "3.5.1", + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + + // The jQuery object is actually just the init constructor 'enhanced' + // Need init if jQuery is called (just allow error to be thrown if not included) + return new jQuery.fn.init( selector, context ); + }; + +jQuery.fn = jQuery.prototype = { + + // The current version of jQuery being used + jquery: version, + + constructor: jQuery, + + // The default length of a jQuery object is 0 + length: 0, + + toArray: function() { + return slice.call( this ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + + // Return all the elements in a clean array + if ( num == null ) { + return slice.call( this ); + } + + // Return just the one element from the set + return num < 0 ? this[ num + this.length ] : this[ num ]; + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems ) { + + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + each: function( callback ) { + return jQuery.each( this, callback ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map( this, function( elem, i ) { + return callback.call( elem, i, elem ); + } ) ); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ) ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + even: function() { + return this.pushStack( jQuery.grep( this, function( _elem, i ) { + return ( i + 1 ) % 2; + } ) ); + }, + + odd: function() { + return this.pushStack( jQuery.grep( this, function( _elem, i ) { + return i % 2; + } ) ); + }, + + eq: function( i ) { + var len = this.length, + j = +i + ( i < 0 ? len : 0 ); + return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); + }, + + end: function() { + return this.prevObject || this.constructor(); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: arr.sort, + splice: arr.splice +}; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[ 0 ] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + + // Skip the boolean and the target + target = arguments[ i ] || {}; + i++; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !isFunction( target ) ) { + target = {}; + } + + // Extend jQuery itself if only one argument is passed + if ( i === length ) { + target = this; + i--; + } + + for ( ; i < length; i++ ) { + + // Only deal with non-null/undefined values + if ( ( options = arguments[ i ] ) != null ) { + + // Extend the base object + for ( name in options ) { + copy = options[ name ]; + + // Prevent Object.prototype pollution + // Prevent never-ending loop + if ( name === "__proto__" || target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject( copy ) || + ( copyIsArray = Array.isArray( copy ) ) ) ) { + src = target[ name ]; + + // Ensure proper type for the source value + if ( copyIsArray && !Array.isArray( src ) ) { + clone = []; + } else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) { + clone = {}; + } else { + clone = src; + } + copyIsArray = false; + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend( { + + // Unique for each copy of jQuery on the page + expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), + + // Assume jQuery is ready without the ready module + isReady: true, + + error: function( msg ) { + throw new Error( msg ); + }, + + noop: function() {}, + + isPlainObject: function( obj ) { + var proto, Ctor; + + // Detect obvious negatives + // Use toString instead of jQuery.type to catch host objects + if ( !obj || toString.call( obj ) !== "[object Object]" ) { + return false; + } + + proto = getProto( obj ); + + // Objects with no prototype (e.g., `Object.create( null )`) are plain + if ( !proto ) { + return true; + } + + // Objects with prototype are plain iff they were constructed by a global Object function + Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; + return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; + }, + + isEmptyObject: function( obj ) { + var name; + + for ( name in obj ) { + return false; + } + return true; + }, + + // Evaluates a script in a provided context; falls back to the global one + // if not specified. + globalEval: function( code, options, doc ) { + DOMEval( code, { nonce: options && options.nonce }, doc ); + }, + + each: function( obj, callback ) { + var length, i = 0; + + if ( isArrayLike( obj ) ) { + length = obj.length; + for ( ; i < length; i++ ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } else { + for ( i in obj ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } + + return obj; + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var ret = results || []; + + if ( arr != null ) { + if ( isArrayLike( Object( arr ) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); + } else { + push.call( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + return arr == null ? -1 : indexOf.call( arr, elem, i ); + }, + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + merge: function( first, second ) { + var len = +second.length, + j = 0, + i = first.length; + + for ( ; j < len; j++ ) { + first[ i++ ] = second[ j ]; + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, invert ) { + var callbackInverse, + matches = [], + i = 0, + length = elems.length, + callbackExpect = !invert; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + callbackInverse = !callback( elems[ i ], i ); + if ( callbackInverse !== callbackExpect ) { + matches.push( elems[ i ] ); + } + } + + return matches; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var length, value, + i = 0, + ret = []; + + // Go through the array, translating each of the items to their new values + if ( isArrayLike( elems ) ) { + length = elems.length; + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + + // Go through every key on the object, + } else { + for ( i in elems ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + } + + // Flatten any nested arrays + return flat( ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // jQuery.support is not used in Core but other projects attach their + // properties to it so it needs to exist. + support: support +} ); + +if ( typeof Symbol === "function" ) { + jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; +} + +// Populate the class2type map +jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), +function( _i, name ) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +} ); + +function isArrayLike( obj ) { + + // Support: real iOS 8.2 only (not reproducible in simulator) + // `in` check used to prevent JIT error (gh-2145) + // hasOwn isn't used here due to false negatives + // regarding Nodelist length in IE + var length = !!obj && "length" in obj && obj.length, + type = toType( obj ); + + if ( isFunction( obj ) || isWindow( obj ) ) { + return false; + } + + return type === "array" || length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj; +} +var Sizzle = +/*! + * Sizzle CSS Selector Engine v2.3.5 + * https://sizzlejs.com/ + * + * Copyright JS Foundation and other contributors + * Released under the MIT license + * https://js.foundation/ + * + * Date: 2020-03-14 + */ +( function( window ) { +var i, + support, + Expr, + getText, + isXML, + tokenize, + compile, + select, + outermostContext, + sortInput, + hasDuplicate, + + // Local document vars + setDocument, + document, + docElem, + documentIsHTML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + + // Instance-specific data + expando = "sizzle" + 1 * new Date(), + preferredDoc = window.document, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + nonnativeSelectorCache = createCache(), + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + } + return 0; + }, + + // Instance methods + hasOwn = ( {} ).hasOwnProperty, + arr = [], + pop = arr.pop, + pushNative = arr.push, + push = arr.push, + slice = arr.slice, + + // Use a stripped-down indexOf as it's faster than native + // https://jsperf.com/thor-indexof-vs-for/5 + indexOf = function( list, elem ) { + var i = 0, + len = list.length; + for ( ; i < len; i++ ) { + if ( list[ i ] === elem ) { + return i; + } + } + return -1; + }, + + booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|" + + "ismap|loop|multiple|open|readonly|required|scoped", + + // Regular expressions + + // http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + + // https://www.w3.org/TR/css-syntax-3/#ident-token-diagram + identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace + + "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+", + + // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors + attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + + + // Operator (capture 2) + "*([*^$|!~]?=)" + whitespace + + + // "Attribute values must be CSS identifiers [capture 5] + // or strings [capture 3 or capture 4]" + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + + whitespace + "*\\]", + + pseudos = ":(" + identifier + ")(?:\\((" + + + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: + // 1. quoted (capture 3; capture 4 or capture 5) + "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + + + // 2. simple (capture 6) + "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + + + // 3. anything else (capture 2) + ".*" + + ")\\)|)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rwhitespace = new RegExp( whitespace + "+", "g" ), + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + + "*" ), + rdescend = new RegExp( whitespace + "|>" ), + + rpseudo = new RegExp( pseudos ), + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = { + "ID": new RegExp( "^#(" + identifier + ")" ), + "CLASS": new RegExp( "^\\.(" + identifier + ")" ), + "TAG": new RegExp( "^(" + identifier + "|[*])" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), + + // For use in libraries implementing .is() + // We use this for POS matching in `select` + "needsContext": new RegExp( "^" + whitespace + + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) + }, + + rhtml = /HTML$/i, + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + + rnative = /^[^{]+\{\s*\[native \w/, + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + + rsibling = /[+~]/, + + // CSS escapes + // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = new RegExp( "\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g" ), + funescape = function( escape, nonHex ) { + var high = "0x" + escape.slice( 1 ) - 0x10000; + + return nonHex ? + + // Strip the backslash prefix from a non-hex escape sequence + nonHex : + + // Replace a hexadecimal escape sequence with the encoded Unicode code point + // Support: IE <=11+ + // For values outside the Basic Multilingual Plane (BMP), manually construct a + // surrogate pair + high < 0 ? + String.fromCharCode( high + 0x10000 ) : + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }, + + // CSS string/identifier serialization + // https://drafts.csswg.org/cssom/#common-serializing-idioms + rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, + fcssescape = function( ch, asCodePoint ) { + if ( asCodePoint ) { + + // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER + if ( ch === "\0" ) { + return "\uFFFD"; + } + + // Control characters and (dependent upon position) numbers get escaped as code points + return ch.slice( 0, -1 ) + "\\" + + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; + } + + // Other potentially-special ASCII characters get backslash-escaped + return "\\" + ch; + }, + + // Used for iframes + // See setDocument() + // Removing the function wrapper causes a "Permission Denied" + // error in IE + unloadHandler = function() { + setDocument(); + }, + + inDisabledFieldset = addCombinator( + function( elem ) { + return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset"; + }, + { dir: "parentNode", next: "legend" } + ); + +// Optimize for push.apply( _, NodeList ) +try { + push.apply( + ( arr = slice.call( preferredDoc.childNodes ) ), + preferredDoc.childNodes + ); + + // Support: Android<4.0 + // Detect silently failing push.apply + // eslint-disable-next-line no-unused-expressions + arr[ preferredDoc.childNodes.length ].nodeType; +} catch ( e ) { + push = { apply: arr.length ? + + // Leverage slice if possible + function( target, els ) { + pushNative.apply( target, slice.call( els ) ); + } : + + // Support: IE<9 + // Otherwise append directly + function( target, els ) { + var j = target.length, + i = 0; + + // Can't trust NodeList.length + while ( ( target[ j++ ] = els[ i++ ] ) ) {} + target.length = j - 1; + } + }; +} + +function Sizzle( selector, context, results, seed ) { + var m, i, elem, nid, match, groups, newSelector, + newContext = context && context.ownerDocument, + + // nodeType defaults to 9, since context defaults to document + nodeType = context ? context.nodeType : 9; + + results = results || []; + + // Return early from calls with invalid selector or context + if ( typeof selector !== "string" || !selector || + nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { + + return results; + } + + // Try to shortcut find operations (as opposed to filters) in HTML documents + if ( !seed ) { + setDocument( context ); + context = context || document; + + if ( documentIsHTML ) { + + // If the selector is sufficiently simple, try using a "get*By*" DOM method + // (excepting DocumentFragment context, where the methods don't exist) + if ( nodeType !== 11 && ( match = rquickExpr.exec( selector ) ) ) { + + // ID selector + if ( ( m = match[ 1 ] ) ) { + + // Document context + if ( nodeType === 9 ) { + if ( ( elem = context.getElementById( m ) ) ) { + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + + // Element context + } else { + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( newContext && ( elem = newContext.getElementById( m ) ) && + contains( context, elem ) && + elem.id === m ) { + + results.push( elem ); + return results; + } + } + + // Type selector + } else if ( match[ 2 ] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; + + // Class selector + } else if ( ( m = match[ 3 ] ) && support.getElementsByClassName && + context.getElementsByClassName ) { + + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } + } + + // Take advantage of querySelectorAll + if ( support.qsa && + !nonnativeSelectorCache[ selector + " " ] && + ( !rbuggyQSA || !rbuggyQSA.test( selector ) ) && + + // Support: IE 8 only + // Exclude object elements + ( nodeType !== 1 || context.nodeName.toLowerCase() !== "object" ) ) { + + newSelector = selector; + newContext = context; + + // qSA considers elements outside a scoping root when evaluating child or + // descendant combinators, which is not what we want. + // In such cases, we work around the behavior by prefixing every selector in the + // list with an ID selector referencing the scope context. + // The technique has to be used as well when a leading combinator is used + // as such selectors are not recognized by querySelectorAll. + // Thanks to Andrew Dupont for this technique. + if ( nodeType === 1 && + ( rdescend.test( selector ) || rcombinators.test( selector ) ) ) { + + // Expand context for sibling selectors + newContext = rsibling.test( selector ) && testContext( context.parentNode ) || + context; + + // We can use :scope instead of the ID hack if the browser + // supports it & if we're not changing the context. + if ( newContext !== context || !support.scope ) { + + // Capture the context ID, setting it first if necessary + if ( ( nid = context.getAttribute( "id" ) ) ) { + nid = nid.replace( rcssescape, fcssescape ); + } else { + context.setAttribute( "id", ( nid = expando ) ); + } + } + + // Prefix every selector in the list + groups = tokenize( selector ); + i = groups.length; + while ( i-- ) { + groups[ i ] = ( nid ? "#" + nid : ":scope" ) + " " + + toSelector( groups[ i ] ); + } + newSelector = groups.join( "," ); + } + + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch ( qsaError ) { + nonnativeSelectorCache( selector, true ); + } finally { + if ( nid === expando ) { + context.removeAttribute( "id" ); + } + } + } + } + } + + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed ); +} + +/** + * Create key-value caches of limited size + * @returns {function(string, object)} Returns the Object data after storing it on itself with + * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + * deleting the oldest entry + */ +function createCache() { + var keys = []; + + function cache( key, value ) { + + // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) + if ( keys.push( key + " " ) > Expr.cacheLength ) { + + // Only keep the most recent entries + delete cache[ keys.shift() ]; + } + return ( cache[ key + " " ] = value ); + } + return cache; +} + +/** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ expando ] = true; + return fn; +} + +/** + * Support testing using an element + * @param {Function} fn Passed the created element and returns a boolean result + */ +function assert( fn ) { + var el = document.createElement( "fieldset" ); + + try { + return !!fn( el ); + } catch ( e ) { + return false; + } finally { + + // Remove from its parent by default + if ( el.parentNode ) { + el.parentNode.removeChild( el ); + } + + // release memory in IE + el = null; + } +} + +/** + * Adds the same handler for all of the specified attrs + * @param {String} attrs Pipe-separated list of attributes + * @param {Function} handler The method that will be applied + */ +function addHandle( attrs, handler ) { + var arr = attrs.split( "|" ), + i = arr.length; + + while ( i-- ) { + Expr.attrHandle[ arr[ i ] ] = handler; + } +} + +/** + * Checks document order of two siblings + * @param {Element} a + * @param {Element} b + * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b + */ +function siblingCheck( a, b ) { + var cur = b && a, + diff = cur && a.nodeType === 1 && b.nodeType === 1 && + a.sourceIndex - b.sourceIndex; + + // Use IE sourceIndex if available on both nodes + if ( diff ) { + return diff; + } + + // Check if b follows a + if ( cur ) { + while ( ( cur = cur.nextSibling ) ) { + if ( cur === b ) { + return -1; + } + } + } + + return a ? 1 : -1; +} + +/** + * Returns a function to use in pseudos for input types + * @param {String} type + */ +function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for buttons + * @param {String} type + */ +function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return ( name === "input" || name === "button" ) && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for :enabled/:disabled + * @param {Boolean} disabled true for :disabled; false for :enabled + */ +function createDisabledPseudo( disabled ) { + + // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable + return function( elem ) { + + // Only certain elements can match :enabled or :disabled + // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled + // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled + if ( "form" in elem ) { + + // Check for inherited disabledness on relevant non-disabled elements: + // * listed form-associated elements in a disabled fieldset + // https://html.spec.whatwg.org/multipage/forms.html#category-listed + // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled + // * option elements in a disabled optgroup + // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled + // All such elements have a "form" property. + if ( elem.parentNode && elem.disabled === false ) { + + // Option elements defer to a parent optgroup if present + if ( "label" in elem ) { + if ( "label" in elem.parentNode ) { + return elem.parentNode.disabled === disabled; + } else { + return elem.disabled === disabled; + } + } + + // Support: IE 6 - 11 + // Use the isDisabled shortcut property to check for disabled fieldset ancestors + return elem.isDisabled === disabled || + + // Where there is no isDisabled, check manually + /* jshint -W018 */ + elem.isDisabled !== !disabled && + inDisabledFieldset( elem ) === disabled; + } + + return elem.disabled === disabled; + + // Try to winnow out elements that can't be disabled before trusting the disabled property. + // Some victims get caught in our net (label, legend, menu, track), but it shouldn't + // even exist on them, let alone have a boolean value. + } else if ( "label" in elem ) { + return elem.disabled === disabled; + } + + // Remaining elements are neither :enabled nor :disabled + return false; + }; +} + +/** + * Returns a function to use in pseudos for positionals + * @param {Function} fn + */ +function createPositionalPseudo( fn ) { + return markFunction( function( argument ) { + argument = +argument; + return markFunction( function( seed, matches ) { + var j, + matchIndexes = fn( [], seed.length, argument ), + i = matchIndexes.length; + + // Match elements found at the specified indexes + while ( i-- ) { + if ( seed[ ( j = matchIndexes[ i ] ) ] ) { + seed[ j ] = !( matches[ j ] = seed[ j ] ); + } + } + } ); + } ); +} + +/** + * Checks a node for validity as a Sizzle context + * @param {Element|Object=} context + * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value + */ +function testContext( context ) { + return context && typeof context.getElementsByTagName !== "undefined" && context; +} + +// Expose support vars for convenience +support = Sizzle.support = {}; + +/** + * Detects XML nodes + * @param {Element|Object} elem An element or a document + * @returns {Boolean} True iff elem is a non-HTML XML node + */ +isXML = Sizzle.isXML = function( elem ) { + var namespace = elem.namespaceURI, + docElem = ( elem.ownerDocument || elem ).documentElement; + + // Support: IE <=8 + // Assume HTML when documentElement doesn't yet exist, such as inside loading iframes + // https://bugs.jquery.com/ticket/4833 + return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" ); +}; + +/** + * Sets document-related variables once based on the current document + * @param {Element|Object} [doc] An element or document object to use to set the document + * @returns {Object} Returns the current document + */ +setDocument = Sizzle.setDocument = function( node ) { + var hasCompare, subWindow, + doc = node ? node.ownerDocument || node : preferredDoc; + + // Return early if doc is invalid or already selected + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( doc == document || doc.nodeType !== 9 || !doc.documentElement ) { + return document; + } + + // Update global variables + document = doc; + docElem = document.documentElement; + documentIsHTML = !isXML( document ); + + // Support: IE 9 - 11+, Edge 12 - 18+ + // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( preferredDoc != document && + ( subWindow = document.defaultView ) && subWindow.top !== subWindow ) { + + // Support: IE 11, Edge + if ( subWindow.addEventListener ) { + subWindow.addEventListener( "unload", unloadHandler, false ); + + // Support: IE 9 - 10 only + } else if ( subWindow.attachEvent ) { + subWindow.attachEvent( "onunload", unloadHandler ); + } + } + + // Support: IE 8 - 11+, Edge 12 - 18+, Chrome <=16 - 25 only, Firefox <=3.6 - 31 only, + // Safari 4 - 5 only, Opera <=11.6 - 12.x only + // IE/Edge & older browsers don't support the :scope pseudo-class. + // Support: Safari 6.0 only + // Safari 6.0 supports :scope but it's an alias of :root there. + support.scope = assert( function( el ) { + docElem.appendChild( el ).appendChild( document.createElement( "div" ) ); + return typeof el.querySelectorAll !== "undefined" && + !el.querySelectorAll( ":scope fieldset div" ).length; + } ); + + /* Attributes + ---------------------------------------------------------------------- */ + + // Support: IE<8 + // Verify that getAttribute really returns attributes and not properties + // (excepting IE8 booleans) + support.attributes = assert( function( el ) { + el.className = "i"; + return !el.getAttribute( "className" ); + } ); + + /* getElement(s)By* + ---------------------------------------------------------------------- */ + + // Check if getElementsByTagName("*") returns only elements + support.getElementsByTagName = assert( function( el ) { + el.appendChild( document.createComment( "" ) ); + return !el.getElementsByTagName( "*" ).length; + } ); + + // Support: IE<9 + support.getElementsByClassName = rnative.test( document.getElementsByClassName ); + + // Support: IE<10 + // Check if getElementById returns elements by name + // The broken getElementById methods don't pick up programmatically-set names, + // so use a roundabout getElementsByName test + support.getById = assert( function( el ) { + docElem.appendChild( el ).id = expando; + return !document.getElementsByName || !document.getElementsByName( expando ).length; + } ); + + // ID filter and find + if ( support.getById ) { + Expr.filter[ "ID" ] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + return elem.getAttribute( "id" ) === attrId; + }; + }; + Expr.find[ "ID" ] = function( id, context ) { + if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { + var elem = context.getElementById( id ); + return elem ? [ elem ] : []; + } + }; + } else { + Expr.filter[ "ID" ] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== "undefined" && + elem.getAttributeNode( "id" ); + return node && node.value === attrId; + }; + }; + + // Support: IE 6 - 7 only + // getElementById is not reliable as a find shortcut + Expr.find[ "ID" ] = function( id, context ) { + if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { + var node, i, elems, + elem = context.getElementById( id ); + + if ( elem ) { + + // Verify the id attribute + node = elem.getAttributeNode( "id" ); + if ( node && node.value === id ) { + return [ elem ]; + } + + // Fall back on getElementsByName + elems = context.getElementsByName( id ); + i = 0; + while ( ( elem = elems[ i++ ] ) ) { + node = elem.getAttributeNode( "id" ); + if ( node && node.value === id ) { + return [ elem ]; + } + } + } + + return []; + } + }; + } + + // Tag + Expr.find[ "TAG" ] = support.getElementsByTagName ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== "undefined" ) { + return context.getElementsByTagName( tag ); + + // DocumentFragment nodes don't have gEBTN + } else if ( support.qsa ) { + return context.querySelectorAll( tag ); + } + } : + + function( tag, context ) { + var elem, + tmp = [], + i = 0, + + // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too + results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + while ( ( elem = results[ i++ ] ) ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } + + return tmp; + } + return results; + }; + + // Class + Expr.find[ "CLASS" ] = support.getElementsByClassName && function( className, context ) { + if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { + return context.getElementsByClassName( className ); + } + }; + + /* QSA/matchesSelector + ---------------------------------------------------------------------- */ + + // QSA and matchesSelector support + + // matchesSelector(:active) reports false when true (IE9/Opera 11.5) + rbuggyMatches = []; + + // qSa(:focus) reports false when true (Chrome 21) + // We allow this because of a bug in IE8/9 that throws an error + // whenever `document.activeElement` is accessed on an iframe + // So, we allow :focus to pass through QSA all the time to avoid the IE error + // See https://bugs.jquery.com/ticket/13378 + rbuggyQSA = []; + + if ( ( support.qsa = rnative.test( document.querySelectorAll ) ) ) { + + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert( function( el ) { + + var input; + + // Select is set to empty string on purpose + // This is to test IE's treatment of not explicitly + // setting a boolean content attribute, + // since its presence should be enough + // https://bugs.jquery.com/ticket/12359 + docElem.appendChild( el ).innerHTML = "" + + ""; + + // Support: IE8, Opera 11-12.16 + // Nothing should be selected when empty strings follow ^= or $= or *= + // The test attribute must be unknown in Opera but "safe" for WinRT + // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section + if ( el.querySelectorAll( "[msallowcapture^='']" ).length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); + } + + // Support: IE8 + // Boolean attributes and "value" are not treated correctly + if ( !el.querySelectorAll( "[selected]" ).length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); + } + + // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ + if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { + rbuggyQSA.push( "~=" ); + } + + // Support: IE 11+, Edge 15 - 18+ + // IE 11/Edge don't find elements on a `[name='']` query in some cases. + // Adding a temporary attribute to the document before the selection works + // around the issue. + // Interestingly, IE 10 & older don't seem to have the issue. + input = document.createElement( "input" ); + input.setAttribute( "name", "" ); + el.appendChild( input ); + if ( !el.querySelectorAll( "[name='']" ).length ) { + rbuggyQSA.push( "\\[" + whitespace + "*name" + whitespace + "*=" + + whitespace + "*(?:''|\"\")" ); + } + + // Webkit/Opera - :checked should return selected option elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + // IE8 throws error here and will not see later tests + if ( !el.querySelectorAll( ":checked" ).length ) { + rbuggyQSA.push( ":checked" ); + } + + // Support: Safari 8+, iOS 8+ + // https://bugs.webkit.org/show_bug.cgi?id=136851 + // In-page `selector#id sibling-combinator selector` fails + if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { + rbuggyQSA.push( ".#.+[+~]" ); + } + + // Support: Firefox <=3.6 - 5 only + // Old Firefox doesn't throw on a badly-escaped identifier. + el.querySelectorAll( "\\\f" ); + rbuggyQSA.push( "[\\r\\n\\f]" ); + } ); + + assert( function( el ) { + el.innerHTML = "" + + ""; + + // Support: Windows 8 Native Apps + // The type and name attributes are restricted during .innerHTML assignment + var input = document.createElement( "input" ); + input.setAttribute( "type", "hidden" ); + el.appendChild( input ).setAttribute( "name", "D" ); + + // Support: IE8 + // Enforce case-sensitivity of name attribute + if ( el.querySelectorAll( "[name=d]" ).length ) { + rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); + } + + // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) + // IE8 throws error here and will not see later tests + if ( el.querySelectorAll( ":enabled" ).length !== 2 ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Support: IE9-11+ + // IE's :disabled selector does not pick up the children of disabled fieldsets + docElem.appendChild( el ).disabled = true; + if ( el.querySelectorAll( ":disabled" ).length !== 2 ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Support: Opera 10 - 11 only + // Opera 10-11 does not throw on post-comma invalid pseudos + el.querySelectorAll( "*,:x" ); + rbuggyQSA.push( ",.*:" ); + } ); + } + + if ( ( support.matchesSelector = rnative.test( ( matches = docElem.matches || + docElem.webkitMatchesSelector || + docElem.mozMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector ) ) ) ) { + + assert( function( el ) { + + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + support.disconnectedMatch = matches.call( el, "*" ); + + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( el, "[s!='']:x" ); + rbuggyMatches.push( "!=", pseudos ); + } ); + } + + rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join( "|" ) ); + rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join( "|" ) ); + + /* Contains + ---------------------------------------------------------------------- */ + hasCompare = rnative.test( docElem.compareDocumentPosition ); + + // Element contains another + // Purposefully self-exclusive + // As in, an element does not contain itself + contains = hasCompare || rnative.test( docElem.contains ) ? + function( a, b ) { + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b && b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && ( + adown.contains ? + adown.contains( bup ) : + a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 + ) ); + } : + function( a, b ) { + if ( b ) { + while ( ( b = b.parentNode ) ) { + if ( b === a ) { + return true; + } + } + } + return false; + }; + + /* Sorting + ---------------------------------------------------------------------- */ + + // Document order sorting + sortOrder = hasCompare ? + function( a, b ) { + + // Flag for duplicate removal + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + // Sort on method existence if only one input has compareDocumentPosition + var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; + if ( compare ) { + return compare; + } + + // Calculate position if both inputs belong to the same document + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + compare = ( a.ownerDocument || a ) == ( b.ownerDocument || b ) ? + a.compareDocumentPosition( b ) : + + // Otherwise we know they are disconnected + 1; + + // Disconnected nodes + if ( compare & 1 || + ( !support.sortDetached && b.compareDocumentPosition( a ) === compare ) ) { + + // Choose the first element that is related to our preferred document + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( a == document || a.ownerDocument == preferredDoc && + contains( preferredDoc, a ) ) { + return -1; + } + + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( b == document || b.ownerDocument == preferredDoc && + contains( preferredDoc, b ) ) { + return 1; + } + + // Maintain original order + return sortInput ? + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + 0; + } + + return compare & 4 ? -1 : 1; + } : + function( a, b ) { + + // Exit early if the nodes are identical + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + var cur, + i = 0, + aup = a.parentNode, + bup = b.parentNode, + ap = [ a ], + bp = [ b ]; + + // Parentless nodes are either documents or disconnected + if ( !aup || !bup ) { + + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + /* eslint-disable eqeqeq */ + return a == document ? -1 : + b == document ? 1 : + /* eslint-enable eqeqeq */ + aup ? -1 : + bup ? 1 : + sortInput ? + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + 0; + + // If the nodes are siblings, we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + } + + // Otherwise we need full lists of their ancestors for comparison + cur = a; + while ( ( cur = cur.parentNode ) ) { + ap.unshift( cur ); + } + cur = b; + while ( ( cur = cur.parentNode ) ) { + bp.unshift( cur ); + } + + // Walk down the tree looking for a discrepancy + while ( ap[ i ] === bp[ i ] ) { + i++; + } + + return i ? + + // Do a sibling check if the nodes have a common ancestor + siblingCheck( ap[ i ], bp[ i ] ) : + + // Otherwise nodes in our document sort first + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + /* eslint-disable eqeqeq */ + ap[ i ] == preferredDoc ? -1 : + bp[ i ] == preferredDoc ? 1 : + /* eslint-enable eqeqeq */ + 0; + }; + + return document; +}; + +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); +}; + +Sizzle.matchesSelector = function( elem, expr ) { + setDocument( elem ); + + if ( support.matchesSelector && documentIsHTML && + !nonnativeSelectorCache[ expr + " " ] && + ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && + ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { + + try { + var ret = matches.call( elem, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || support.disconnectedMatch || + + // As well, disconnected nodes are said to be in a document + // fragment in IE 9 + elem.document && elem.document.nodeType !== 11 ) { + return ret; + } + } catch ( e ) { + nonnativeSelectorCache( expr, true ); + } + } + + return Sizzle( expr, document, null, [ elem ] ).length > 0; +}; + +Sizzle.contains = function( context, elem ) { + + // Set document vars if needed + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( ( context.ownerDocument || context ) != document ) { + setDocument( context ); + } + return contains( context, elem ); +}; + +Sizzle.attr = function( elem, name ) { + + // Set document vars if needed + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( ( elem.ownerDocument || elem ) != document ) { + setDocument( elem ); + } + + var fn = Expr.attrHandle[ name.toLowerCase() ], + + // Don't get fooled by Object.prototype properties (jQuery #13807) + val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? + fn( elem, name, !documentIsHTML ) : + undefined; + + return val !== undefined ? + val : + support.attributes || !documentIsHTML ? + elem.getAttribute( name ) : + ( val = elem.getAttributeNode( name ) ) && val.specified ? + val.value : + null; +}; + +Sizzle.escape = function( sel ) { + return ( sel + "" ).replace( rcssescape, fcssescape ); +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +/** + * Document sorting and removing duplicates + * @param {ArrayLike} results + */ +Sizzle.uniqueSort = function( results ) { + var elem, + duplicates = [], + j = 0, + i = 0; + + // Unless we *know* we can detect duplicates, assume their presence + hasDuplicate = !support.detectDuplicates; + sortInput = !support.sortStable && results.slice( 0 ); + results.sort( sortOrder ); + + if ( hasDuplicate ) { + while ( ( elem = results[ i++ ] ) ) { + if ( elem === results[ i ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } + + // Clear input after sorting to release objects + // See https://github.com/jquery/sizzle/pull/225 + sortInput = null; + + return results; +}; + +/** + * Utility function for retrieving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +getText = Sizzle.getText = function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( !nodeType ) { + + // If no nodeType, this is expected to be an array + while ( ( node = elem[ i++ ] ) ) { + + // Do not traverse comment nodes + ret += getText( node ); + } + } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + + // Use textContent for elements + // innerText usage removed for consistency of new lines (jQuery #11153) + if ( typeof elem.textContent === "string" ) { + return elem.textContent; + } else { + + // Traverse its children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + + // Do not include comment or processing instruction nodes + + return ret; +}; + +Expr = Sizzle.selectors = { + + // Can be adjusted by the user + cacheLength: 50, + + createPseudo: markFunction, + + match: matchExpr, + + attrHandle: {}, + + find: {}, + + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, + + preFilter: { + "ATTR": function( match ) { + match[ 1 ] = match[ 1 ].replace( runescape, funescape ); + + // Move the given value to match[3] whether quoted or unquoted + match[ 3 ] = ( match[ 3 ] || match[ 4 ] || + match[ 5 ] || "" ).replace( runescape, funescape ); + + if ( match[ 2 ] === "~=" ) { + match[ 3 ] = " " + match[ 3 ] + " "; + } + + return match.slice( 0, 4 ); + }, + + "CHILD": function( match ) { + + /* matches from matchExpr["CHILD"] + 1 type (only|nth|...) + 2 what (child|of-type) + 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 4 xn-component of xn+y argument ([+-]?\d*n|) + 5 sign of xn-component + 6 x of xn-component + 7 sign of y-component + 8 y of y-component + */ + match[ 1 ] = match[ 1 ].toLowerCase(); + + if ( match[ 1 ].slice( 0, 3 ) === "nth" ) { + + // nth-* requires argument + if ( !match[ 3 ] ) { + Sizzle.error( match[ 0 ] ); + } + + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[ 4 ] = +( match[ 4 ] ? + match[ 5 ] + ( match[ 6 ] || 1 ) : + 2 * ( match[ 3 ] === "even" || match[ 3 ] === "odd" ) ); + match[ 5 ] = +( ( match[ 7 ] + match[ 8 ] ) || match[ 3 ] === "odd" ); + + // other types prohibit arguments + } else if ( match[ 3 ] ) { + Sizzle.error( match[ 0 ] ); + } + + return match; + }, + + "PSEUDO": function( match ) { + var excess, + unquoted = !match[ 6 ] && match[ 2 ]; + + if ( matchExpr[ "CHILD" ].test( match[ 0 ] ) ) { + return null; + } + + // Accept quoted arguments as-is + if ( match[ 3 ] ) { + match[ 2 ] = match[ 4 ] || match[ 5 ] || ""; + + // Strip excess characters from unquoted arguments + } else if ( unquoted && rpseudo.test( unquoted ) && + + // Get excess from tokenize (recursively) + ( excess = tokenize( unquoted, true ) ) && + + // advance to the next closing parenthesis + ( excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length ) ) { + + // excess is a negative index + match[ 0 ] = match[ 0 ].slice( 0, excess ); + match[ 2 ] = unquoted.slice( 0, excess ); + } + + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); + } + }, + + filter: { + + "TAG": function( nodeNameSelector ) { + var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); + return nodeNameSelector === "*" ? + function() { + return true; + } : + function( elem ) { + return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + }; + }, + + "CLASS": function( className ) { + var pattern = classCache[ className + " " ]; + + return pattern || + ( pattern = new RegExp( "(^|" + whitespace + + ")" + className + "(" + whitespace + "|$)" ) ) && classCache( + className, function( elem ) { + return pattern.test( + typeof elem.className === "string" && elem.className || + typeof elem.getAttribute !== "undefined" && + elem.getAttribute( "class" ) || + "" + ); + } ); + }, + + "ATTR": function( name, operator, check ) { + return function( elem ) { + var result = Sizzle.attr( elem, name ); + + if ( result == null ) { + return operator === "!="; + } + if ( !operator ) { + return true; + } + + result += ""; + + /* eslint-disable max-len */ + + return operator === "=" ? result === check : + operator === "!=" ? result !== check : + operator === "^=" ? check && result.indexOf( check ) === 0 : + operator === "*=" ? check && result.indexOf( check ) > -1 : + operator === "$=" ? check && result.slice( -check.length ) === check : + operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : + false; + /* eslint-enable max-len */ + + }; + }, + + "CHILD": function( type, what, _argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, _context, xml ) { + var cache, uniqueCache, outerCache, node, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType, + diff = false; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( ( node = node[ dir ] ) ) { + if ( ofType ? + node.nodeName.toLowerCase() === name : + node.nodeType === 1 ) { + + return false; + } + } + + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; + } + + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + + // Seek `elem` from a previously-cached index + + // ...in a gzip-friendly way + node = parent; + outerCache = node[ expando ] || ( node[ expando ] = {} ); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + ( outerCache[ node.uniqueID ] = {} ); + + cache = uniqueCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex && cache[ 2 ]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( ( node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + ( diff = nodeIndex = 0 ) || start.pop() ) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + } else { + + // Use previously-cached element index if available + if ( useCache ) { + + // ...in a gzip-friendly way + node = elem; + outerCache = node[ expando ] || ( node[ expando ] = {} ); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + ( outerCache[ node.uniqueID ] = {} ); + + cache = uniqueCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex; + } + + // xml :nth-child(...) + // or :nth-last-child(...) or :nth(-last)?-of-type(...) + if ( diff === false ) { + + // Use the same loop as above to seek `elem` from the start + while ( ( node = ++nodeIndex && node && node[ dir ] || + ( diff = nodeIndex = 0 ) || start.pop() ) ) { + + if ( ( ofType ? + node.nodeName.toLowerCase() === name : + node.nodeType === 1 ) && + ++diff ) { + + // Cache the index of each encountered element + if ( useCache ) { + outerCache = node[ expando ] || + ( node[ expando ] = {} ); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + ( outerCache[ node.uniqueID ] = {} ); + + uniqueCache[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } + } + } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction( function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf( seed, matched[ i ] ); + seed[ idx ] = !( matches[ idx ] = matched[ i ] ); + } + } ) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; + } + }, + + pseudos: { + + // Potentially complex pseudos + "not": markFunction( function( selector ) { + + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction( function( seed, matches, _context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( ( elem = unmatched[ i ] ) ) { + seed[ i ] = !( matches[ i ] = elem ); + } + } + } ) : + function( elem, _context, xml ) { + input[ 0 ] = elem; + matcher( input, null, xml, results ); + + // Don't keep the element (issue #299) + input[ 0 ] = null; + return !results.pop(); + }; + } ), + + "has": markFunction( function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + } ), + + "contains": markFunction( function( text ) { + text = text.replace( runescape, funescape ); + return function( elem ) { + return ( elem.textContent || getText( elem ) ).indexOf( text ) > -1; + }; + } ), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // http://www.w3.org/TR/selectors/#lang-pseudo + "lang": markFunction( function( lang ) { + + // lang value must be a valid identifier + if ( !ridentifier.test( lang || "" ) ) { + Sizzle.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( ( elemLang = documentIsHTML ? + elem.lang : + elem.getAttribute( "xml:lang" ) || elem.getAttribute( "lang" ) ) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( ( elem = elem.parentNode ) && elem.nodeType === 1 ); + return false; + }; + } ), + + // Miscellaneous + "target": function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + "root": function( elem ) { + return elem === docElem; + }, + + "focus": function( elem ) { + return elem === document.activeElement && + ( !document.hasFocus || document.hasFocus() ) && + !!( elem.type || elem.href || ~elem.tabIndex ); + }, + + // Boolean properties + "enabled": createDisabledPseudo( false ), + "disabled": createDisabledPseudo( true ), + + "checked": function( elem ) { + + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return ( nodeName === "input" && !!elem.checked ) || + ( nodeName === "option" && !!elem.selected ); + }, + + "selected": function( elem ) { + + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + // eslint-disable-next-line no-unused-expressions + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + // Contents + "empty": function( elem ) { + + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), + // but not by others (comment: 8; processing instruction: 7; etc.) + // nodeType < 6 works because attributes (2) do not appear as children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeType < 6 ) { + return false; + } + } + return true; + }, + + "parent": function( elem ) { + return !Expr.pseudos[ "empty" ]( elem ); + }, + + // Element/input types + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "text": function( elem ) { + var attr; + return elem.nodeName.toLowerCase() === "input" && + elem.type === "text" && + + // Support: IE<8 + // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" + ( ( attr = elem.getAttribute( "type" ) ) == null || + attr.toLowerCase() === "text" ); + }, + + // Position-in-collection + "first": createPositionalPseudo( function() { + return [ 0 ]; + } ), + + "last": createPositionalPseudo( function( _matchIndexes, length ) { + return [ length - 1 ]; + } ), + + "eq": createPositionalPseudo( function( _matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + } ), + + "even": createPositionalPseudo( function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + } ), + + "odd": createPositionalPseudo( function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + } ), + + "lt": createPositionalPseudo( function( matchIndexes, length, argument ) { + var i = argument < 0 ? + argument + length : + argument > length ? + length : + argument; + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + } ), + + "gt": createPositionalPseudo( function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + } ) + } +}; + +Expr.pseudos[ "nth" ] = Expr.pseudos[ "eq" ]; + +// Add button/input type pseudos +for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { + Expr.pseudos[ i ] = createInputPseudo( i ); +} +for ( i in { submit: true, reset: true } ) { + Expr.pseudos[ i ] = createButtonPseudo( i ); +} + +// Easy API for creating new setFilters +function setFilters() {} +setFilters.prototype = Expr.filters = Expr.pseudos; +Expr.setFilters = new setFilters(); + +tokenize = Sizzle.tokenize = function( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ selector + " " ]; + + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); + } + + soFar = selector; + groups = []; + preFilters = Expr.preFilter; + + while ( soFar ) { + + // Comma and first run + if ( !matched || ( match = rcomma.exec( soFar ) ) ) { + if ( match ) { + + // Don't consume trailing commas as valid + soFar = soFar.slice( match[ 0 ].length ) || soFar; + } + groups.push( ( tokens = [] ) ); + } + + matched = false; + + // Combinators + if ( ( match = rcombinators.exec( soFar ) ) ) { + matched = match.shift(); + tokens.push( { + value: matched, + + // Cast descendant combinators to space + type: match[ 0 ].replace( rtrim, " " ) + } ); + soFar = soFar.slice( matched.length ); + } + + // Filters + for ( type in Expr.filter ) { + if ( ( match = matchExpr[ type ].exec( soFar ) ) && ( !preFilters[ type ] || + ( match = preFilters[ type ]( match ) ) ) ) { + matched = match.shift(); + tokens.push( { + value: matched, + type: type, + matches: match + } ); + soFar = soFar.slice( matched.length ); + } + } + + if ( !matched ) { + break; + } + } + + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + return parseOnly ? + soFar.length : + soFar ? + Sizzle.error( selector ) : + + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); +}; + +function toSelector( tokens ) { + var i = 0, + len = tokens.length, + selector = ""; + for ( ; i < len; i++ ) { + selector += tokens[ i ].value; + } + return selector; +} + +function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + skip = combinator.next, + key = skip || dir, + checkNonElements = base && key === "parentNode", + doneName = done++; + + return combinator.first ? + + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( ( elem = elem[ dir ] ) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + return matcher( elem, context, xml ); + } + } + return false; + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + var oldCache, uniqueCache, outerCache, + newCache = [ dirruns, doneName ]; + + // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching + if ( xml ) { + while ( ( elem = elem[ dir ] ) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + if ( matcher( elem, context, xml ) ) { + return true; + } + } + } + } else { + while ( ( elem = elem[ dir ] ) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + outerCache = elem[ expando ] || ( elem[ expando ] = {} ); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ elem.uniqueID ] || + ( outerCache[ elem.uniqueID ] = {} ); + + if ( skip && skip === elem.nodeName.toLowerCase() ) { + elem = elem[ dir ] || elem; + } else if ( ( oldCache = uniqueCache[ key ] ) && + oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { + + // Assign to newCache so results back-propagate to previous elements + return ( newCache[ 2 ] = oldCache[ 2 ] ); + } else { + + // Reuse newcache so results back-propagate to previous elements + uniqueCache[ key ] = newCache; + + // A match means we're done; a fail means we have to keep checking + if ( ( newCache[ 2 ] = matcher( elem, context, xml ) ) ) { + return true; + } + } + } + } + } + return false; + }; +} + +function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[ i ]( elem, context, xml ) ) { + return false; + } + } + return true; + } : + matchers[ 0 ]; +} + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[ i ], results ); + } + return results; +} + +function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; + + for ( ; i < len; i++ ) { + if ( ( elem = unmatched[ i ] ) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); + } + } + } + } + + return newUnmatched; +} + +function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ expando ] ) { + postFilter = setMatcher( postFilter ); + } + if ( postFinder && !postFinder[ expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction( function( seed, results, context, xml ) { + var temp, i, elem, + preMap = [], + postMap = [], + preexisting = results.length, + + // Get initial elements from seed or context + elems = seed || multipleContexts( + selector || "*", + context.nodeType ? [ context ] : context, + [] + ), + + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems, + + matcherOut = matcher ? + + // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, + postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + + // ...intermediate processing is necessary + [] : + + // ...otherwise use results directly + results : + matcherIn; + + // Find primary matches + if ( matcher ) { + matcher( matcherIn, matcherOut, context, xml ); + } + + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( ( elem = temp[ i ] ) ) { + matcherOut[ postMap[ i ] ] = !( matcherIn[ postMap[ i ] ] = elem ); + } + } + } + + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( ( elem = matcherOut[ i ] ) ) { + + // Restore matcherIn since elem is not yet a final match + temp.push( ( matcherIn[ i ] = elem ) ); + } + } + postFinder( null, ( matcherOut = [] ), temp, xml ); + } + + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( ( elem = matcherOut[ i ] ) && + ( temp = postFinder ? indexOf( seed, elem ) : preMap[ i ] ) > -1 ) { + + seed[ temp ] = !( results[ temp ] = elem ); + } + } + } + + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } + } + } ); +} + +function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = Expr.relative[ tokens[ 0 ].type ], + implicitRelative = leadingRelative || Expr.relative[ " " ], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + ( checkContext = context ).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + + // Avoid hanging onto element (issue #299) + checkContext = null; + return ret; + } ]; + + for ( ; i < len; i++ ) { + if ( ( matcher = Expr.relative[ tokens[ i ].type ] ) ) { + matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ]; + } else { + matcher = Expr.filter[ tokens[ i ].type ].apply( null, tokens[ i ].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ expando ] ) { + + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( Expr.relative[ tokens[ j ].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && toSelector( + + // If the preceding token was a descendant combinator, insert an implicit any-element `*` + tokens + .slice( 0, i - 1 ) + .concat( { value: tokens[ i - 2 ].type === " " ? "*" : "" } ) + ).replace( rtrim, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( ( tokens = tokens.slice( j ) ) ), + j < len && toSelector( tokens ) + ); + } + matchers.push( matcher ); + } + } + + return elementMatcher( matchers ); +} + +function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + var bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, outermost ) { + var elem, j, matcher, + matchedCount = 0, + i = "0", + unmatched = seed && [], + setMatched = [], + contextBackup = outermostContext, + + // We must always have either seed elements or outermost context + elems = seed || byElement && Expr.find[ "TAG" ]( "*", outermost ), + + // Use integer dirruns iff this is the outermost matcher + dirrunsUnique = ( dirruns += contextBackup == null ? 1 : Math.random() || 0.1 ), + len = elems.length; + + if ( outermost ) { + + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + outermostContext = context == document || context || outermost; + } + + // Add elements passing elementMatchers directly to results + // Support: IE<9, Safari + // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id + for ( ; i !== len && ( elem = elems[ i ] ) != null; i++ ) { + if ( byElement && elem ) { + j = 0; + + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( !context && elem.ownerDocument != document ) { + setDocument( elem ); + xml = !documentIsHTML; + } + while ( ( matcher = elementMatchers[ j++ ] ) ) { + if ( matcher( elem, context || document, xml ) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + + // They will have gone through all possible matchers + if ( ( elem = !matcher && elem ) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // `i` is now the count of elements visited above, and adding it to `matchedCount` + // makes the latter nonnegative. + matchedCount += i; + + // Apply set filters to unmatched elements + // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` + // equals `i`), unless we didn't visit _any_ elements in the above loop because we have + // no element matchers and no seed. + // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that + // case, which will result in a "00" `matchedCount` that differs from `i` but is also + // numerically zero. + if ( bySet && i !== matchedCount ) { + j = 0; + while ( ( matcher = setMatchers[ j++ ] ) ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !( unmatched[ i ] || setMatched[ i ] ) ) { + setMatched[ i ] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + Sizzle.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; + + if ( !cached ) { + + // Generate a function of recursive functions that can be used to check each element + if ( !match ) { + match = tokenize( selector ); + } + i = match.length; + while ( i-- ) { + cached = matcherFromTokens( match[ i ] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( + selector, + matcherFromGroupMatchers( elementMatchers, setMatchers ) + ); + + // Save selector and tokenization + cached.selector = selector; + } + return cached; +}; + +/** + * A low-level selection function that works with Sizzle's compiled + * selector functions + * @param {String|Function} selector A selector or a pre-compiled + * selector function built with Sizzle.compile + * @param {Element} context + * @param {Array} [results] + * @param {Array} [seed] A set of elements to match against + */ +select = Sizzle.select = function( selector, context, results, seed ) { + var i, tokens, token, type, find, + compiled = typeof selector === "function" && selector, + match = !seed && tokenize( ( selector = compiled.selector || selector ) ); + + results = results || []; + + // Try to minimize operations if there is only one selector in the list and no seed + // (the latter of which guarantees us context) + if ( match.length === 1 ) { + + // Reduce context if the leading compound selector is an ID + tokens = match[ 0 ] = match[ 0 ].slice( 0 ); + if ( tokens.length > 2 && ( token = tokens[ 0 ] ).type === "ID" && + context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[ 1 ].type ] ) { + + context = ( Expr.find[ "ID" ]( token.matches[ 0 ] + .replace( runescape, funescape ), context ) || [] )[ 0 ]; + if ( !context ) { + return results; + + // Precompiled matchers will still verify ancestry, so step up a level + } else if ( compiled ) { + context = context.parentNode; + } + + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + i = matchExpr[ "needsContext" ].test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[ i ]; + + // Abort if we hit a combinator + if ( Expr.relative[ ( type = token.type ) ] ) { + break; + } + if ( ( find = Expr.find[ type ] ) ) { + + // Search, expanding context for leading sibling combinators + if ( ( seed = find( + token.matches[ 0 ].replace( runescape, funescape ), + rsibling.test( tokens[ 0 ].type ) && testContext( context.parentNode ) || + context + ) ) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, seed ); + return results; + } + + break; + } + } + } + } + + // Compile and execute a filtering function if one is not provided + // Provide `match` to avoid retokenization if we modified the selector above + ( compiled || compile( selector, match ) )( + seed, + context, + !documentIsHTML, + results, + !context || rsibling.test( selector ) && testContext( context.parentNode ) || context + ); + return results; +}; + +// One-time assignments + +// Sort stability +support.sortStable = expando.split( "" ).sort( sortOrder ).join( "" ) === expando; + +// Support: Chrome 14-35+ +// Always assume duplicates if they aren't passed to the comparison function +support.detectDuplicates = !!hasDuplicate; + +// Initialize against the default document +setDocument(); + +// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) +// Detached nodes confoundingly follow *each other* +support.sortDetached = assert( function( el ) { + + // Should return 1, but returns 4 (following) + return el.compareDocumentPosition( document.createElement( "fieldset" ) ) & 1; +} ); + +// Support: IE<8 +// Prevent attribute/property "interpolation" +// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx +if ( !assert( function( el ) { + el.innerHTML = ""; + return el.firstChild.getAttribute( "href" ) === "#"; +} ) ) { + addHandle( "type|href|height|width", function( elem, name, isXML ) { + if ( !isXML ) { + return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); + } + } ); +} + +// Support: IE<9 +// Use defaultValue in place of getAttribute("value") +if ( !support.attributes || !assert( function( el ) { + el.innerHTML = ""; + el.firstChild.setAttribute( "value", "" ); + return el.firstChild.getAttribute( "value" ) === ""; +} ) ) { + addHandle( "value", function( elem, _name, isXML ) { + if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { + return elem.defaultValue; + } + } ); +} + +// Support: IE<9 +// Use getAttributeNode to fetch booleans when getAttribute lies +if ( !assert( function( el ) { + return el.getAttribute( "disabled" ) == null; +} ) ) { + addHandle( booleans, function( elem, name, isXML ) { + var val; + if ( !isXML ) { + return elem[ name ] === true ? name.toLowerCase() : + ( val = elem.getAttributeNode( name ) ) && val.specified ? + val.value : + null; + } + } ); +} + +return Sizzle; + +} )( window ); + + + +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; + +// Deprecated +jQuery.expr[ ":" ] = jQuery.expr.pseudos; +jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; +jQuery.escapeSelector = Sizzle.escape; + + + + +var dir = function( elem, dir, until ) { + var matched = [], + truncate = until !== undefined; + + while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { + if ( elem.nodeType === 1 ) { + if ( truncate && jQuery( elem ).is( until ) ) { + break; + } + matched.push( elem ); + } + } + return matched; +}; + + +var siblings = function( n, elem ) { + var matched = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + matched.push( n ); + } + } + + return matched; +}; + + +var rneedsContext = jQuery.expr.match.needsContext; + + + +function nodeName( elem, name ) { + + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + +}; +var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); + + + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, not ) { + if ( isFunction( qualifier ) ) { + return jQuery.grep( elements, function( elem, i ) { + return !!qualifier.call( elem, i, elem ) !== not; + } ); + } + + // Single element + if ( qualifier.nodeType ) { + return jQuery.grep( elements, function( elem ) { + return ( elem === qualifier ) !== not; + } ); + } + + // Arraylike of elements (jQuery, arguments, Array) + if ( typeof qualifier !== "string" ) { + return jQuery.grep( elements, function( elem ) { + return ( indexOf.call( qualifier, elem ) > -1 ) !== not; + } ); + } + + // Filtered directly for both simple and complex selectors + return jQuery.filter( qualifier, elements, not ); +} + +jQuery.filter = function( expr, elems, not ) { + var elem = elems[ 0 ]; + + if ( not ) { + expr = ":not(" + expr + ")"; + } + + if ( elems.length === 1 && elem.nodeType === 1 ) { + return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : []; + } + + return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { + return elem.nodeType === 1; + } ) ); +}; + +jQuery.fn.extend( { + find: function( selector ) { + var i, ret, + len = this.length, + self = this; + + if ( typeof selector !== "string" ) { + return this.pushStack( jQuery( selector ).filter( function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + } ) ); + } + + ret = this.pushStack( [] ); + + for ( i = 0; i < len; i++ ) { + jQuery.find( selector, self[ i ], ret ); + } + + return len > 1 ? jQuery.uniqueSort( ret ) : ret; + }, + filter: function( selector ) { + return this.pushStack( winnow( this, selector || [], false ) ); + }, + not: function( selector ) { + return this.pushStack( winnow( this, selector || [], true ) ); + }, + is: function( selector ) { + return !!winnow( + this, + + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + typeof selector === "string" && rneedsContext.test( selector ) ? + jQuery( selector ) : + selector || [], + false + ).length; + } +} ); + + +// Initialize a jQuery object + + +// A central reference to the root jQuery(document) +var rootjQuery, + + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + // Strict HTML recognition (#11290: must start with <) + // Shortcut simple #id case for speed + rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, + + init = jQuery.fn.init = function( selector, context, root ) { + var match, elem; + + // HANDLE: $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Method init() accepts an alternate rootjQuery + // so migrate can support jQuery.sub (gh-2101) + root = root || rootjQuery; + + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector[ 0 ] === "<" && + selector[ selector.length - 1 ] === ">" && + selector.length >= 3 ) { + + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = rquickExpr.exec( selector ); + } + + // Match html or make sure no context is specified for #id + if ( match && ( match[ 1 ] || !context ) ) { + + // HANDLE: $(html) -> $(array) + if ( match[ 1 ] ) { + context = context instanceof jQuery ? context[ 0 ] : context; + + // Option to run scripts is true for back-compat + // Intentionally let the error be thrown if parseHTML is not present + jQuery.merge( this, jQuery.parseHTML( + match[ 1 ], + context && context.nodeType ? context.ownerDocument || context : document, + true + ) ); + + // HANDLE: $(html, props) + if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { + for ( match in context ) { + + // Properties of context are called as methods if possible + if ( isFunction( this[ match ] ) ) { + this[ match ]( context[ match ] ); + + // ...and otherwise set as attributes + } else { + this.attr( match, context[ match ] ); + } + } + } + + return this; + + // HANDLE: $(#id) + } else { + elem = document.getElementById( match[ 2 ] ); + + if ( elem ) { + + // Inject the element directly into the jQuery object + this[ 0 ] = elem; + this.length = 1; + } + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || root ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(DOMElement) + } else if ( selector.nodeType ) { + this[ 0 ] = selector; + this.length = 1; + return this; + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( isFunction( selector ) ) { + return root.ready !== undefined ? + root.ready( selector ) : + + // Execute immediately if ready is not present + selector( jQuery ); + } + + return jQuery.makeArray( selector, this ); + }; + +// Give the init function the jQuery prototype for later instantiation +init.prototype = jQuery.fn; + +// Initialize central reference +rootjQuery = jQuery( document ); + + +var rparentsprev = /^(?:parents|prev(?:Until|All))/, + + // Methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend( { + has: function( target ) { + var targets = jQuery( target, this ), + l = targets.length; + + return this.filter( function() { + var i = 0; + for ( ; i < l; i++ ) { + if ( jQuery.contains( this, targets[ i ] ) ) { + return true; + } + } + } ); + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + matched = [], + targets = typeof selectors !== "string" && jQuery( selectors ); + + // Positional selectors never match, since there's no _selection_ context + if ( !rneedsContext.test( selectors ) ) { + for ( ; i < l; i++ ) { + for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { + + // Always skip document fragments + if ( cur.nodeType < 11 && ( targets ? + targets.index( cur ) > -1 : + + // Don't pass non-elements to Sizzle + cur.nodeType === 1 && + jQuery.find.matchesSelector( cur, selectors ) ) ) { + + matched.push( cur ); + break; + } + } + } + } + + return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); + }, + + // Determine the position of an element within the set + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; + } + + // Index in selector + if ( typeof elem === "string" ) { + return indexOf.call( jQuery( elem ), this[ 0 ] ); + } + + // Locate the position of the desired element + return indexOf.call( this, + + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[ 0 ] : elem + ); + }, + + add: function( selector, context ) { + return this.pushStack( + jQuery.uniqueSort( + jQuery.merge( this.get(), jQuery( selector, context ) ) + ) + ); + }, + + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter( selector ) + ); + } +} ); + +function sibling( cur, dir ) { + while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} + return cur; +} + +jQuery.each( { + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, _i, until ) { + return dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, _i, until ) { + return dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, _i, until ) { + return dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return siblings( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return siblings( elem.firstChild ); + }, + contents: function( elem ) { + if ( elem.contentDocument != null && + + // Support: IE 11+ + // elements with no `data` attribute has an object + // `contentDocument` with a `null` prototype. + getProto( elem.contentDocument ) ) { + + return elem.contentDocument; + } + + // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only + // Treat the template element as a regular one in browsers that + // don't support it. + if ( nodeName( elem, "template" ) ) { + elem = elem.content || elem; + } + + return jQuery.merge( [], elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var matched = jQuery.map( this, fn, until ); + + if ( name.slice( -5 ) !== "Until" ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + matched = jQuery.filter( selector, matched ); + } + + if ( this.length > 1 ) { + + // Remove duplicates + if ( !guaranteedUnique[ name ] ) { + jQuery.uniqueSort( matched ); + } + + // Reverse order for parents* and prev-derivatives + if ( rparentsprev.test( name ) ) { + matched.reverse(); + } + } + + return this.pushStack( matched ); + }; +} ); +var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g ); + + + +// Convert String-formatted options into Object-formatted ones +function createOptions( options ) { + var object = {}; + jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) { + object[ flag ] = true; + } ); + return object; +} + +/* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( options ) { + + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + createOptions( options ) : + jQuery.extend( {}, options ); + + var // Flag to know if list is currently firing + firing, + + // Last fire value for non-forgettable lists + memory, + + // Flag to know if list was already fired + fired, + + // Flag to prevent firing + locked, + + // Actual callback list + list = [], + + // Queue of execution data for repeatable lists + queue = [], + + // Index of currently firing callback (modified by add/remove as needed) + firingIndex = -1, + + // Fire callbacks + fire = function() { + + // Enforce single-firing + locked = locked || options.once; + + // Execute callbacks for all pending executions, + // respecting firingIndex overrides and runtime changes + fired = firing = true; + for ( ; queue.length; firingIndex = -1 ) { + memory = queue.shift(); + while ( ++firingIndex < list.length ) { + + // Run callback and check for early termination + if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && + options.stopOnFalse ) { + + // Jump to end and forget the data so .add doesn't re-fire + firingIndex = list.length; + memory = false; + } + } + } + + // Forget the data if we're done with it + if ( !options.memory ) { + memory = false; + } + + firing = false; + + // Clean up if we're done firing for good + if ( locked ) { + + // Keep an empty list if we have data for future add calls + if ( memory ) { + list = []; + + // Otherwise, this object is spent + } else { + list = ""; + } + } + }, + + // Actual Callbacks object + self = { + + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + + // If we have memory from a past run, we should fire after adding + if ( memory && !firing ) { + firingIndex = list.length - 1; + queue.push( memory ); + } + + ( function add( args ) { + jQuery.each( args, function( _, arg ) { + if ( isFunction( arg ) ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && toType( arg ) !== "string" ) { + + // Inspect recursively + add( arg ); + } + } ); + } )( arguments ); + + if ( memory && !firing ) { + fire(); + } + } + return this; + }, + + // Remove a callback from the list + remove: function() { + jQuery.each( arguments, function( _, arg ) { + var index; + while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + + // Handle firing indexes + if ( index <= firingIndex ) { + firingIndex--; + } + } + } ); + return this; + }, + + // Check if a given callback is in the list. + // If no argument is given, return whether or not list has callbacks attached. + has: function( fn ) { + return fn ? + jQuery.inArray( fn, list ) > -1 : + list.length > 0; + }, + + // Remove all callbacks from the list + empty: function() { + if ( list ) { + list = []; + } + return this; + }, + + // Disable .fire and .add + // Abort any current/pending executions + // Clear all callbacks and values + disable: function() { + locked = queue = []; + list = memory = ""; + return this; + }, + disabled: function() { + return !list; + }, + + // Disable .fire + // Also disable .add unless we have memory (since it would have no effect) + // Abort any pending executions + lock: function() { + locked = queue = []; + if ( !memory && !firing ) { + list = memory = ""; + } + return this; + }, + locked: function() { + return !!locked; + }, + + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( !locked ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + queue.push( args ); + if ( !firing ) { + fire(); + } + } + return this; + }, + + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; + + return self; +}; + + +function Identity( v ) { + return v; +} +function Thrower( ex ) { + throw ex; +} + +function adoptValue( value, resolve, reject, noValue ) { + var method; + + try { + + // Check for promise aspect first to privilege synchronous behavior + if ( value && isFunction( ( method = value.promise ) ) ) { + method.call( value ).done( resolve ).fail( reject ); + + // Other thenables + } else if ( value && isFunction( ( method = value.then ) ) ) { + method.call( value, resolve, reject ); + + // Other non-thenables + } else { + + // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer: + // * false: [ value ].slice( 0 ) => resolve( value ) + // * true: [ value ].slice( 1 ) => resolve() + resolve.apply( undefined, [ value ].slice( noValue ) ); + } + + // For Promises/A+, convert exceptions into rejections + // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in + // Deferred#then to conditionally suppress rejection. + } catch ( value ) { + + // Support: Android 4.0 only + // Strict mode functions invoked without .call/.apply get global-object context + reject.apply( undefined, [ value ] ); + } +} + +jQuery.extend( { + + Deferred: function( func ) { + var tuples = [ + + // action, add listener, callbacks, + // ... .then handlers, argument index, [final state] + [ "notify", "progress", jQuery.Callbacks( "memory" ), + jQuery.Callbacks( "memory" ), 2 ], + [ "resolve", "done", jQuery.Callbacks( "once memory" ), + jQuery.Callbacks( "once memory" ), 0, "resolved" ], + [ "reject", "fail", jQuery.Callbacks( "once memory" ), + jQuery.Callbacks( "once memory" ), 1, "rejected" ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + "catch": function( fn ) { + return promise.then( null, fn ); + }, + + // Keep pipe for back-compat + pipe: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + + return jQuery.Deferred( function( newDefer ) { + jQuery.each( tuples, function( _i, tuple ) { + + // Map tuples (progress, done, fail) to arguments (done, fail, progress) + var fn = isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ]; + + // deferred.progress(function() { bind to newDefer or newDefer.notify }) + // deferred.done(function() { bind to newDefer or newDefer.resolve }) + // deferred.fail(function() { bind to newDefer or newDefer.reject }) + deferred[ tuple[ 1 ] ]( function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && isFunction( returned.promise ) ) { + returned.promise() + .progress( newDefer.notify ) + .done( newDefer.resolve ) + .fail( newDefer.reject ); + } else { + newDefer[ tuple[ 0 ] + "With" ]( + this, + fn ? [ returned ] : arguments + ); + } + } ); + } ); + fns = null; + } ).promise(); + }, + then: function( onFulfilled, onRejected, onProgress ) { + var maxDepth = 0; + function resolve( depth, deferred, handler, special ) { + return function() { + var that = this, + args = arguments, + mightThrow = function() { + var returned, then; + + // Support: Promises/A+ section 2.3.3.3.3 + // https://promisesaplus.com/#point-59 + // Ignore double-resolution attempts + if ( depth < maxDepth ) { + return; + } + + returned = handler.apply( that, args ); + + // Support: Promises/A+ section 2.3.1 + // https://promisesaplus.com/#point-48 + if ( returned === deferred.promise() ) { + throw new TypeError( "Thenable self-resolution" ); + } + + // Support: Promises/A+ sections 2.3.3.1, 3.5 + // https://promisesaplus.com/#point-54 + // https://promisesaplus.com/#point-75 + // Retrieve `then` only once + then = returned && + + // Support: Promises/A+ section 2.3.4 + // https://promisesaplus.com/#point-64 + // Only check objects and functions for thenability + ( typeof returned === "object" || + typeof returned === "function" ) && + returned.then; + + // Handle a returned thenable + if ( isFunction( then ) ) { + + // Special processors (notify) just wait for resolution + if ( special ) { + then.call( + returned, + resolve( maxDepth, deferred, Identity, special ), + resolve( maxDepth, deferred, Thrower, special ) + ); + + // Normal processors (resolve) also hook into progress + } else { + + // ...and disregard older resolution values + maxDepth++; + + then.call( + returned, + resolve( maxDepth, deferred, Identity, special ), + resolve( maxDepth, deferred, Thrower, special ), + resolve( maxDepth, deferred, Identity, + deferred.notifyWith ) + ); + } + + // Handle all other returned values + } else { + + // Only substitute handlers pass on context + // and multiple values (non-spec behavior) + if ( handler !== Identity ) { + that = undefined; + args = [ returned ]; + } + + // Process the value(s) + // Default process is resolve + ( special || deferred.resolveWith )( that, args ); + } + }, + + // Only normal processors (resolve) catch and reject exceptions + process = special ? + mightThrow : + function() { + try { + mightThrow(); + } catch ( e ) { + + if ( jQuery.Deferred.exceptionHook ) { + jQuery.Deferred.exceptionHook( e, + process.stackTrace ); + } + + // Support: Promises/A+ section 2.3.3.3.4.1 + // https://promisesaplus.com/#point-61 + // Ignore post-resolution exceptions + if ( depth + 1 >= maxDepth ) { + + // Only substitute handlers pass on context + // and multiple values (non-spec behavior) + if ( handler !== Thrower ) { + that = undefined; + args = [ e ]; + } + + deferred.rejectWith( that, args ); + } + } + }; + + // Support: Promises/A+ section 2.3.3.3.1 + // https://promisesaplus.com/#point-57 + // Re-resolve promises immediately to dodge false rejection from + // subsequent errors + if ( depth ) { + process(); + } else { + + // Call an optional hook to record the stack, in case of exception + // since it's otherwise lost when execution goes async + if ( jQuery.Deferred.getStackHook ) { + process.stackTrace = jQuery.Deferred.getStackHook(); + } + window.setTimeout( process ); + } + }; + } + + return jQuery.Deferred( function( newDefer ) { + + // progress_handlers.add( ... ) + tuples[ 0 ][ 3 ].add( + resolve( + 0, + newDefer, + isFunction( onProgress ) ? + onProgress : + Identity, + newDefer.notifyWith + ) + ); + + // fulfilled_handlers.add( ... ) + tuples[ 1 ][ 3 ].add( + resolve( + 0, + newDefer, + isFunction( onFulfilled ) ? + onFulfilled : + Identity + ) + ); + + // rejected_handlers.add( ... ) + tuples[ 2 ][ 3 ].add( + resolve( + 0, + newDefer, + isFunction( onRejected ) ? + onRejected : + Thrower + ) + ); + } ).promise(); + }, + + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } + }, + deferred = {}; + + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 5 ]; + + // promise.progress = list.add + // promise.done = list.add + // promise.fail = list.add + promise[ tuple[ 1 ] ] = list.add; + + // Handle state + if ( stateString ) { + list.add( + function() { + + // state = "resolved" (i.e., fulfilled) + // state = "rejected" + state = stateString; + }, + + // rejected_callbacks.disable + // fulfilled_callbacks.disable + tuples[ 3 - i ][ 2 ].disable, + + // rejected_handlers.disable + // fulfilled_handlers.disable + tuples[ 3 - i ][ 3 ].disable, + + // progress_callbacks.lock + tuples[ 0 ][ 2 ].lock, + + // progress_handlers.lock + tuples[ 0 ][ 3 ].lock + ); + } + + // progress_handlers.fire + // fulfilled_handlers.fire + // rejected_handlers.fire + list.add( tuple[ 3 ].fire ); + + // deferred.notify = function() { deferred.notifyWith(...) } + // deferred.resolve = function() { deferred.resolveWith(...) } + // deferred.reject = function() { deferred.rejectWith(...) } + deferred[ tuple[ 0 ] ] = function() { + deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments ); + return this; + }; + + // deferred.notifyWith = list.fireWith + // deferred.resolveWith = list.fireWith + // deferred.rejectWith = list.fireWith + deferred[ tuple[ 0 ] + "With" ] = list.fireWith; + } ); + + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( singleValue ) { + var + + // count of uncompleted subordinates + remaining = arguments.length, + + // count of unprocessed arguments + i = remaining, + + // subordinate fulfillment data + resolveContexts = Array( i ), + resolveValues = slice.call( arguments ), + + // the master Deferred + master = jQuery.Deferred(), + + // subordinate callback factory + updateFunc = function( i ) { + return function( value ) { + resolveContexts[ i ] = this; + resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; + if ( !( --remaining ) ) { + master.resolveWith( resolveContexts, resolveValues ); + } + }; + }; + + // Single- and empty arguments are adopted like Promise.resolve + if ( remaining <= 1 ) { + adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject, + !remaining ); + + // Use .then() to unwrap secondary thenables (cf. gh-3000) + if ( master.state() === "pending" || + isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { + + return master.then(); + } + } + + // Multiple arguments are aggregated like Promise.all array elements + while ( i-- ) { + adoptValue( resolveValues[ i ], updateFunc( i ), master.reject ); + } + + return master.promise(); + } +} ); + + +// These usually indicate a programmer mistake during development, +// warn about them ASAP rather than swallowing them by default. +var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; + +jQuery.Deferred.exceptionHook = function( error, stack ) { + + // Support: IE 8 - 9 only + // Console exists when dev tools are open, which can happen at any time + if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) { + window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack ); + } +}; + + + + +jQuery.readyException = function( error ) { + window.setTimeout( function() { + throw error; + } ); +}; + + + + +// The deferred used on DOM ready +var readyList = jQuery.Deferred(); + +jQuery.fn.ready = function( fn ) { + + readyList + .then( fn ) + + // Wrap jQuery.readyException in a function so that the lookup + // happens at the time of error handling instead of callback + // registration. + .catch( function( error ) { + jQuery.readyException( error ); + } ); + + return this; +}; + +jQuery.extend( { + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + } +} ); + +jQuery.ready.then = readyList.then; + +// The ready event handler and self cleanup method +function completed() { + document.removeEventListener( "DOMContentLoaded", completed ); + window.removeEventListener( "load", completed ); + jQuery.ready(); +} + +// Catch cases where $(document).ready() is called +// after the browser event has already occurred. +// Support: IE <=9 - 10 only +// Older IE sometimes signals "interactive" too soon +if ( document.readyState === "complete" || + ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { + + // Handle it asynchronously to allow scripts the opportunity to delay ready + window.setTimeout( jQuery.ready ); + +} else { + + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed ); +} + + + + +// Multifunctional method to get and set values of a collection +// The value/s can optionally be executed if it's a function +var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + len = elems.length, + bulk = key == null; + + // Sets many values + if ( toType( key ) === "object" ) { + chainable = true; + for ( i in key ) { + access( elems, fn, i, key[ i ], true, emptyGet, raw ); + } + + // Sets one value + } else if ( value !== undefined ) { + chainable = true; + + if ( !isFunction( value ) ) { + raw = true; + } + + if ( bulk ) { + + // Bulk operations run against the entire set + if ( raw ) { + fn.call( elems, value ); + fn = null; + + // ...except when executing function values + } else { + bulk = fn; + fn = function( elem, _key, value ) { + return bulk.call( jQuery( elem ), value ); + }; + } + } + + if ( fn ) { + for ( ; i < len; i++ ) { + fn( + elems[ i ], key, raw ? + value : + value.call( elems[ i ], i, fn( elems[ i ], key ) ) + ); + } + } + } + + if ( chainable ) { + return elems; + } + + // Gets + if ( bulk ) { + return fn.call( elems ); + } + + return len ? fn( elems[ 0 ], key ) : emptyGet; +}; + + +// Matches dashed string for camelizing +var rmsPrefix = /^-ms-/, + rdashAlpha = /-([a-z])/g; + +// Used by camelCase as callback to replace() +function fcamelCase( _all, letter ) { + return letter.toUpperCase(); +} + +// Convert dashed to camelCase; used by the css and data modules +// Support: IE <=9 - 11, Edge 12 - 15 +// Microsoft forgot to hump their vendor prefix (#9572) +function camelCase( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); +} +var acceptData = function( owner ) { + + // Accepts only: + // - Node + // - Node.ELEMENT_NODE + // - Node.DOCUMENT_NODE + // - Object + // - Any + return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); +}; + + + + +function Data() { + this.expando = jQuery.expando + Data.uid++; +} + +Data.uid = 1; + +Data.prototype = { + + cache: function( owner ) { + + // Check if the owner object already has a cache + var value = owner[ this.expando ]; + + // If not, create one + if ( !value ) { + value = {}; + + // We can accept data for non-element nodes in modern browsers, + // but we should not, see #8335. + // Always return an empty object. + if ( acceptData( owner ) ) { + + // If it is a node unlikely to be stringify-ed or looped over + // use plain assignment + if ( owner.nodeType ) { + owner[ this.expando ] = value; + + // Otherwise secure it in a non-enumerable property + // configurable must be true to allow the property to be + // deleted when data is removed + } else { + Object.defineProperty( owner, this.expando, { + value: value, + configurable: true + } ); + } + } + } + + return value; + }, + set: function( owner, data, value ) { + var prop, + cache = this.cache( owner ); + + // Handle: [ owner, key, value ] args + // Always use camelCase key (gh-2257) + if ( typeof data === "string" ) { + cache[ camelCase( data ) ] = value; + + // Handle: [ owner, { properties } ] args + } else { + + // Copy the properties one-by-one to the cache object + for ( prop in data ) { + cache[ camelCase( prop ) ] = data[ prop ]; + } + } + return cache; + }, + get: function( owner, key ) { + return key === undefined ? + this.cache( owner ) : + + // Always use camelCase key (gh-2257) + owner[ this.expando ] && owner[ this.expando ][ camelCase( key ) ]; + }, + access: function( owner, key, value ) { + + // In cases where either: + // + // 1. No key was specified + // 2. A string key was specified, but no value provided + // + // Take the "read" path and allow the get method to determine + // which value to return, respectively either: + // + // 1. The entire cache object + // 2. The data stored at the key + // + if ( key === undefined || + ( ( key && typeof key === "string" ) && value === undefined ) ) { + + return this.get( owner, key ); + } + + // When the key is not a string, or both a key and value + // are specified, set or extend (existing objects) with either: + // + // 1. An object of properties + // 2. A key and value + // + this.set( owner, key, value ); + + // Since the "set" path can have two possible entry points + // return the expected data based on which path was taken[*] + return value !== undefined ? value : key; + }, + remove: function( owner, key ) { + var i, + cache = owner[ this.expando ]; + + if ( cache === undefined ) { + return; + } + + if ( key !== undefined ) { + + // Support array or space separated string of keys + if ( Array.isArray( key ) ) { + + // If key is an array of keys... + // We always set camelCase keys, so remove that. + key = key.map( camelCase ); + } else { + key = camelCase( key ); + + // If a key with the spaces exists, use it. + // Otherwise, create an array by matching non-whitespace + key = key in cache ? + [ key ] : + ( key.match( rnothtmlwhite ) || [] ); + } + + i = key.length; + + while ( i-- ) { + delete cache[ key[ i ] ]; + } + } + + // Remove the expando if there's no more data + if ( key === undefined || jQuery.isEmptyObject( cache ) ) { + + // Support: Chrome <=35 - 45 + // Webkit & Blink performance suffers when deleting properties + // from DOM nodes, so set to undefined instead + // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) + if ( owner.nodeType ) { + owner[ this.expando ] = undefined; + } else { + delete owner[ this.expando ]; + } + } + }, + hasData: function( owner ) { + var cache = owner[ this.expando ]; + return cache !== undefined && !jQuery.isEmptyObject( cache ); + } +}; +var dataPriv = new Data(); + +var dataUser = new Data(); + + + +// Implementation Summary +// +// 1. Enforce API surface and semantic compatibility with 1.9.x branch +// 2. Improve the module's maintainability by reducing the storage +// paths to a single mechanism. +// 3. Use the same single mechanism to support "private" and "user" data. +// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) +// 5. Avoid exposing implementation details on user objects (eg. expando properties) +// 6. Provide a clear path for implementation upgrade to WeakMap in 2014 + +var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, + rmultiDash = /[A-Z]/g; + +function getData( data ) { + if ( data === "true" ) { + return true; + } + + if ( data === "false" ) { + return false; + } + + if ( data === "null" ) { + return null; + } + + // Only convert to a number if it doesn't change the string + if ( data === +data + "" ) { + return +data; + } + + if ( rbrace.test( data ) ) { + return JSON.parse( data ); + } + + return data; +} + +function dataAttr( elem, key, data ) { + var name; + + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = getData( data ); + } catch ( e ) {} + + // Make sure we set the data so it isn't changed later + dataUser.set( elem, key, data ); + } else { + data = undefined; + } + } + return data; +} + +jQuery.extend( { + hasData: function( elem ) { + return dataUser.hasData( elem ) || dataPriv.hasData( elem ); + }, + + data: function( elem, name, data ) { + return dataUser.access( elem, name, data ); + }, + + removeData: function( elem, name ) { + dataUser.remove( elem, name ); + }, + + // TODO: Now that all calls to _data and _removeData have been replaced + // with direct calls to dataPriv methods, these can be deprecated. + _data: function( elem, name, data ) { + return dataPriv.access( elem, name, data ); + }, + + _removeData: function( elem, name ) { + dataPriv.remove( elem, name ); + } +} ); + +jQuery.fn.extend( { + data: function( key, value ) { + var i, name, data, + elem = this[ 0 ], + attrs = elem && elem.attributes; + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = dataUser.get( elem ); + + if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { + i = attrs.length; + while ( i-- ) { + + // Support: IE 11 only + // The attrs elements can be null (#14894) + if ( attrs[ i ] ) { + name = attrs[ i ].name; + if ( name.indexOf( "data-" ) === 0 ) { + name = camelCase( name.slice( 5 ) ); + dataAttr( elem, name, data[ name ] ); + } + } + } + dataPriv.set( elem, "hasDataAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each( function() { + dataUser.set( this, key ); + } ); + } + + return access( this, function( value ) { + var data; + + // The calling jQuery object (element matches) is not empty + // (and therefore has an element appears at this[ 0 ]) and the + // `value` parameter was not undefined. An empty jQuery object + // will result in `undefined` for elem = this[ 0 ] which will + // throw an exception if an attempt to read a data cache is made. + if ( elem && value === undefined ) { + + // Attempt to get data from the cache + // The key will always be camelCased in Data + data = dataUser.get( elem, key ); + if ( data !== undefined ) { + return data; + } + + // Attempt to "discover" the data in + // HTML5 custom data-* attrs + data = dataAttr( elem, key ); + if ( data !== undefined ) { + return data; + } + + // We tried really hard, but the data doesn't exist. + return; + } + + // Set the data... + this.each( function() { + + // We always store the camelCased key + dataUser.set( this, key, value ); + } ); + }, null, value, arguments.length > 1, null, true ); + }, + + removeData: function( key ) { + return this.each( function() { + dataUser.remove( this, key ); + } ); + } +} ); + + +jQuery.extend( { + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = dataPriv.get( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || Array.isArray( data ) ) { + queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); + } else { + queue.push( data ); + } + } + return queue || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; + } + + if ( fn ) { + + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + // Clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); + } + + if ( !startLength && hooks ) { + hooks.empty.fire(); + } + }, + + // Not public - generate a queueHooks object, or return the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { + empty: jQuery.Callbacks( "once memory" ).add( function() { + dataPriv.remove( elem, [ type + "queue", key ] ); + } ) + } ); + } +} ); + +jQuery.fn.extend( { + queue: function( type, data ) { + var setter = 2; + + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } + + if ( arguments.length < setter ) { + return jQuery.queue( this[ 0 ], type ); + } + + return data === undefined ? + this : + this.each( function() { + var queue = jQuery.queue( this, type, data ); + + // Ensure a hooks for this queue + jQuery._queueHooks( this, type ); + + if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + } ); + }, + dequeue: function( type ) { + return this.each( function() { + jQuery.dequeue( this, type ); + } ); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + }; + + if ( typeof type !== "string" ) { + obj = type; + type = undefined; + } + type = type || "fx"; + + while ( i-- ) { + tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } + } + resolve(); + return defer.promise( obj ); + } +} ); +var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; + +var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); + + +var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; + +var documentElement = document.documentElement; + + + + var isAttached = function( elem ) { + return jQuery.contains( elem.ownerDocument, elem ); + }, + composed = { composed: true }; + + // Support: IE 9 - 11+, Edge 12 - 18+, iOS 10.0 - 10.2 only + // Check attachment across shadow DOM boundaries when possible (gh-3504) + // Support: iOS 10.0-10.2 only + // Early iOS 10 versions support `attachShadow` but not `getRootNode`, + // leading to errors. We need to check for `getRootNode`. + if ( documentElement.getRootNode ) { + isAttached = function( elem ) { + return jQuery.contains( elem.ownerDocument, elem ) || + elem.getRootNode( composed ) === elem.ownerDocument; + }; + } +var isHiddenWithinTree = function( elem, el ) { + + // isHiddenWithinTree might be called from jQuery#filter function; + // in that case, element will be second argument + elem = el || elem; + + // Inline style trumps all + return elem.style.display === "none" || + elem.style.display === "" && + + // Otherwise, check computed style + // Support: Firefox <=43 - 45 + // Disconnected elements can have computed display: none, so first confirm that elem is + // in the document. + isAttached( elem ) && + + jQuery.css( elem, "display" ) === "none"; + }; + + + +function adjustCSS( elem, prop, valueParts, tween ) { + var adjusted, scale, + maxIterations = 20, + currentValue = tween ? + function() { + return tween.cur(); + } : + function() { + return jQuery.css( elem, prop, "" ); + }, + initial = currentValue(), + unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), + + // Starting value computation is required for potential unit mismatches + initialInUnit = elem.nodeType && + ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && + rcssNum.exec( jQuery.css( elem, prop ) ); + + if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { + + // Support: Firefox <=54 + // Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144) + initial = initial / 2; + + // Trust units reported by jQuery.css + unit = unit || initialInUnit[ 3 ]; + + // Iteratively approximate from a nonzero starting point + initialInUnit = +initial || 1; + + while ( maxIterations-- ) { + + // Evaluate and update our best guess (doubling guesses that zero out). + // Finish if the scale equals or crosses 1 (making the old*new product non-positive). + jQuery.style( elem, prop, initialInUnit + unit ); + if ( ( 1 - scale ) * ( 1 - ( scale = currentValue() / initial || 0.5 ) ) <= 0 ) { + maxIterations = 0; + } + initialInUnit = initialInUnit / scale; + + } + + initialInUnit = initialInUnit * 2; + jQuery.style( elem, prop, initialInUnit + unit ); + + // Make sure we update the tween properties later on + valueParts = valueParts || []; + } + + if ( valueParts ) { + initialInUnit = +initialInUnit || +initial || 0; + + // Apply relative offset (+=/-=) if specified + adjusted = valueParts[ 1 ] ? + initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : + +valueParts[ 2 ]; + if ( tween ) { + tween.unit = unit; + tween.start = initialInUnit; + tween.end = adjusted; + } + } + return adjusted; +} + + +var defaultDisplayMap = {}; + +function getDefaultDisplay( elem ) { + var temp, + doc = elem.ownerDocument, + nodeName = elem.nodeName, + display = defaultDisplayMap[ nodeName ]; + + if ( display ) { + return display; + } + + temp = doc.body.appendChild( doc.createElement( nodeName ) ); + display = jQuery.css( temp, "display" ); + + temp.parentNode.removeChild( temp ); + + if ( display === "none" ) { + display = "block"; + } + defaultDisplayMap[ nodeName ] = display; + + return display; +} + +function showHide( elements, show ) { + var display, elem, + values = [], + index = 0, + length = elements.length; + + // Determine new display value for elements that need to change + for ( ; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + + display = elem.style.display; + if ( show ) { + + // Since we force visibility upon cascade-hidden elements, an immediate (and slow) + // check is required in this first loop unless we have a nonempty display value (either + // inline or about-to-be-restored) + if ( display === "none" ) { + values[ index ] = dataPriv.get( elem, "display" ) || null; + if ( !values[ index ] ) { + elem.style.display = ""; + } + } + if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) { + values[ index ] = getDefaultDisplay( elem ); + } + } else { + if ( display !== "none" ) { + values[ index ] = "none"; + + // Remember what we're overwriting + dataPriv.set( elem, "display", display ); + } + } + } + + // Set the display of the elements in a second loop to avoid constant reflow + for ( index = 0; index < length; index++ ) { + if ( values[ index ] != null ) { + elements[ index ].style.display = values[ index ]; + } + } + + return elements; +} + +jQuery.fn.extend( { + show: function() { + return showHide( this, true ); + }, + hide: function() { + return showHide( this ); + }, + toggle: function( state ) { + if ( typeof state === "boolean" ) { + return state ? this.show() : this.hide(); + } + + return this.each( function() { + if ( isHiddenWithinTree( this ) ) { + jQuery( this ).show(); + } else { + jQuery( this ).hide(); + } + } ); + } +} ); +var rcheckableType = ( /^(?:checkbox|radio)$/i ); + +var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]*)/i ); + +var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i ); + + + +( function() { + var fragment = document.createDocumentFragment(), + div = fragment.appendChild( document.createElement( "div" ) ), + input = document.createElement( "input" ); + + // Support: Android 4.0 - 4.3 only + // Check state lost if the name is set (#11217) + // Support: Windows Web Apps (WWA) + // `name` and `type` must use .setAttribute for WWA (#14901) + input.setAttribute( "type", "radio" ); + input.setAttribute( "checked", "checked" ); + input.setAttribute( "name", "t" ); + + div.appendChild( input ); + + // Support: Android <=4.1 only + // Older WebKit doesn't clone checked state correctly in fragments + support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Support: IE <=11 only + // Make sure textarea (and checkbox) defaultValue is properly cloned + div.innerHTML = ""; + support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; + + // Support: IE <=9 only + // IE <=9 replaces "; + support.option = !!div.lastChild; +} )(); + + +// We have to close these tags to support XHTML (#13200) +var wrapMap = { + + // XHTML parsers do not magically insert elements in the + // same way that tag soup parsers do. So we cannot shorten + // this by omitting or other required elements. + thead: [ 1, "", "
" ], + col: [ 2, "", "
" ], + tr: [ 2, "", "
" ], + td: [ 3, "", "
" ], + + _default: [ 0, "", "" ] +}; + +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +// Support: IE <=9 only +if ( !support.option ) { + wrapMap.optgroup = wrapMap.option = [ 1, "" ]; +} + + +function getAll( context, tag ) { + + // Support: IE <=9 - 11 only + // Use typeof to avoid zero-argument method invocation on host objects (#15151) + var ret; + + if ( typeof context.getElementsByTagName !== "undefined" ) { + ret = context.getElementsByTagName( tag || "*" ); + + } else if ( typeof context.querySelectorAll !== "undefined" ) { + ret = context.querySelectorAll( tag || "*" ); + + } else { + ret = []; + } + + if ( tag === undefined || tag && nodeName( context, tag ) ) { + return jQuery.merge( [ context ], ret ); + } + + return ret; +} + + +// Mark scripts as having already been evaluated +function setGlobalEval( elems, refElements ) { + var i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + dataPriv.set( + elems[ i ], + "globalEval", + !refElements || dataPriv.get( refElements[ i ], "globalEval" ) + ); + } +} + + +var rhtml = /<|&#?\w+;/; + +function buildFragment( elems, context, scripts, selection, ignored ) { + var elem, tmp, tag, wrap, attached, j, + fragment = context.createDocumentFragment(), + nodes = [], + i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + elem = elems[ i ]; + + if ( elem || elem === 0 ) { + + // Add nodes directly + if ( toType( elem ) === "object" ) { + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); + + // Convert non-html into a text node + } else if ( !rhtml.test( elem ) ) { + nodes.push( context.createTextNode( elem ) ); + + // Convert html into DOM nodes + } else { + tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); + + // Deserialize a standard representation + tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; + + // Descend through wrappers to the right content + j = wrap[ 0 ]; + while ( j-- ) { + tmp = tmp.lastChild; + } + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, tmp.childNodes ); + + // Remember the top-level container + tmp = fragment.firstChild; + + // Ensure the created nodes are orphaned (#12392) + tmp.textContent = ""; + } + } + } + + // Remove wrapper from fragment + fragment.textContent = ""; + + i = 0; + while ( ( elem = nodes[ i++ ] ) ) { + + // Skip elements already in the context collection (trac-4087) + if ( selection && jQuery.inArray( elem, selection ) > -1 ) { + if ( ignored ) { + ignored.push( elem ); + } + continue; + } + + attached = isAttached( elem ); + + // Append to fragment + tmp = getAll( fragment.appendChild( elem ), "script" ); + + // Preserve script evaluation history + if ( attached ) { + setGlobalEval( tmp ); + } + + // Capture executables + if ( scripts ) { + j = 0; + while ( ( elem = tmp[ j++ ] ) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } + } + + return fragment; +} + + +var + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, + rtypenamespace = /^([^.]*)(?:\.(.+)|)/; + +function returnTrue() { + return true; +} + +function returnFalse() { + return false; +} + +// Support: IE <=9 - 11+ +// focus() and blur() are asynchronous, except when they are no-op. +// So expect focus to be synchronous when the element is already active, +// and blur to be synchronous when the element is not already active. +// (focus and blur are always synchronous in other supported browsers, +// this just defines when we can count on it). +function expectSync( elem, type ) { + return ( elem === safeActiveElement() ) === ( type === "focus" ); +} + +// Support: IE <=9 only +// Accessing document.activeElement can throw unexpectedly +// https://bugs.jquery.com/ticket/13393 +function safeActiveElement() { + try { + return document.activeElement; + } catch ( err ) { } +} + +function on( elem, types, selector, data, fn, one ) { + var origFn, type; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + on( elem, type, selector, data, types[ type ], one ); + } + return elem; + } + + if ( data == null && fn == null ) { + + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return elem; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return elem.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + } ); +} + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + global: {}, + + add: function( elem, types, handler, data, selector ) { + + var handleObjIn, eventHandle, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.get( elem ); + + // Only attach events to objects that accept data + if ( !acceptData( elem ) ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // Ensure that invalid selectors throw exceptions at attach time + // Evaluate against documentElement in case elem is a non-element node (e.g., document) + if ( selector ) { + jQuery.find.matchesSelector( documentElement, selector ); + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + if ( !( events = elemData.events ) ) { + events = elemData.events = Object.create( null ); + } + if ( !( eventHandle = elemData.handle ) ) { + eventHandle = elemData.handle = function( e ) { + + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? + jQuery.event.dispatch.apply( elem, arguments ) : undefined; + }; + } + + // Handle multiple events separated by a space + types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); + + // There *must* be a type, no attaching namespace-only handlers + if ( !type ) { + continue; + } + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend( { + type: type, + origType: origType, + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join( "." ) + }, handleObjIn ); + + // Init the event handler queue if we're the first + if ( !( handlers = events[ type ] ) ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener if the special events handler returns false + if ( !special.setup || + special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + }, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + + var j, origCount, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); + + if ( !elemData || !( events = elemData.events ) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + handlers = events[ type ] || []; + tmp = tmp[ 2 ] && + new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); + + // Remove matching events + origCount = j = handlers.length; + while ( j-- ) { + handleObj = handlers[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !tmp || tmp.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || + selector === "**" && handleObj.selector ) ) { + handlers.splice( j, 1 ); + + if ( handleObj.selector ) { + handlers.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( origCount && !handlers.length ) { + if ( !special.teardown || + special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove data and the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + dataPriv.remove( elem, "handle events" ); + } + }, + + dispatch: function( nativeEvent ) { + + var i, j, ret, matched, handleObj, handlerQueue, + args = new Array( arguments.length ), + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( nativeEvent ), + + handlers = ( + dataPriv.get( this, "events" ) || Object.create( null ) + )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[ 0 ] = event; + + for ( i = 1; i < arguments.length; i++ ) { + args[ i ] = arguments[ i ]; + } + + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } + + // Determine handlers + handlerQueue = jQuery.event.handlers.call( this, event, handlers ); + + // Run delegates first; they may want to stop propagation beneath us + i = 0; + while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { + event.currentTarget = matched.elem; + + j = 0; + while ( ( handleObj = matched.handlers[ j++ ] ) && + !event.isImmediatePropagationStopped() ) { + + // If the event is namespaced, then each handler is only invoked if it is + // specially universal or its namespaces are a superset of the event's. + if ( !event.rnamespace || handleObj.namespace === false || + event.rnamespace.test( handleObj.namespace ) ) { + + event.handleObj = handleObj; + event.data = handleObj.data; + + ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || + handleObj.handler ).apply( matched.elem, args ); + + if ( ret !== undefined ) { + if ( ( event.result = ret ) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + handlers: function( event, handlers ) { + var i, handleObj, sel, matchedHandlers, matchedSelectors, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Find delegate handlers + if ( delegateCount && + + // Support: IE <=9 + // Black-hole SVG instance trees (trac-13180) + cur.nodeType && + + // Support: Firefox <=42 + // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861) + // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click + // Support: IE 11 only + // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343) + !( event.type === "click" && event.button >= 1 ) ) { + + for ( ; cur !== this; cur = cur.parentNode || this ) { + + // Don't check non-elements (#13208) + // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) { + matchedHandlers = []; + matchedSelectors = {}; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + + // Don't conflict with Object.prototype properties (#13203) + sel = handleObj.selector + " "; + + if ( matchedSelectors[ sel ] === undefined ) { + matchedSelectors[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) > -1 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( matchedSelectors[ sel ] ) { + matchedHandlers.push( handleObj ); + } + } + if ( matchedHandlers.length ) { + handlerQueue.push( { elem: cur, handlers: matchedHandlers } ); + } + } + } + } + + // Add the remaining (directly-bound) handlers + cur = this; + if ( delegateCount < handlers.length ) { + handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } ); + } + + return handlerQueue; + }, + + addProp: function( name, hook ) { + Object.defineProperty( jQuery.Event.prototype, name, { + enumerable: true, + configurable: true, + + get: isFunction( hook ) ? + function() { + if ( this.originalEvent ) { + return hook( this.originalEvent ); + } + } : + function() { + if ( this.originalEvent ) { + return this.originalEvent[ name ]; + } + }, + + set: function( value ) { + Object.defineProperty( this, name, { + enumerable: true, + configurable: true, + writable: true, + value: value + } ); + } + } ); + }, + + fix: function( originalEvent ) { + return originalEvent[ jQuery.expando ] ? + originalEvent : + new jQuery.Event( originalEvent ); + }, + + special: { + load: { + + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + click: { + + // Utilize native event to ensure correct state for checkable inputs + setup: function( data ) { + + // For mutual compressibility with _default, replace `this` access with a local var. + // `|| data` is dead code meant only to preserve the variable through minification. + var el = this || data; + + // Claim the first handler + if ( rcheckableType.test( el.type ) && + el.click && nodeName( el, "input" ) ) { + + // dataPriv.set( el, "click", ... ) + leverageNative( el, "click", returnTrue ); + } + + // Return false to allow normal processing in the caller + return false; + }, + trigger: function( data ) { + + // For mutual compressibility with _default, replace `this` access with a local var. + // `|| data` is dead code meant only to preserve the variable through minification. + var el = this || data; + + // Force setup before triggering a click + if ( rcheckableType.test( el.type ) && + el.click && nodeName( el, "input" ) ) { + + leverageNative( el, "click" ); + } + + // Return non-false to allow normal event-path propagation + return true; + }, + + // For cross-browser consistency, suppress native .click() on links + // Also prevent it if we're currently inside a leveraged native-event stack + _default: function( event ) { + var target = event.target; + return rcheckableType.test( target.type ) && + target.click && nodeName( target, "input" ) && + dataPriv.get( target, "click" ) || + nodeName( target, "a" ); + } + }, + + beforeunload: { + postDispatch: function( event ) { + + // Support: Firefox 20+ + // Firefox doesn't alert if the returnValue field is not set. + if ( event.result !== undefined && event.originalEvent ) { + event.originalEvent.returnValue = event.result; + } + } + } + } +}; + +// Ensure the presence of an event listener that handles manually-triggered +// synthetic events by interrupting progress until reinvoked in response to +// *native* events that it fires directly, ensuring that state changes have +// already occurred before other listeners are invoked. +function leverageNative( el, type, expectSync ) { + + // Missing expectSync indicates a trigger call, which must force setup through jQuery.event.add + if ( !expectSync ) { + if ( dataPriv.get( el, type ) === undefined ) { + jQuery.event.add( el, type, returnTrue ); + } + return; + } + + // Register the controller as a special universal handler for all event namespaces + dataPriv.set( el, type, false ); + jQuery.event.add( el, type, { + namespace: false, + handler: function( event ) { + var notAsync, result, + saved = dataPriv.get( this, type ); + + if ( ( event.isTrigger & 1 ) && this[ type ] ) { + + // Interrupt processing of the outer synthetic .trigger()ed event + // Saved data should be false in such cases, but might be a leftover capture object + // from an async native handler (gh-4350) + if ( !saved.length ) { + + // Store arguments for use when handling the inner native event + // There will always be at least one argument (an event object), so this array + // will not be confused with a leftover capture object. + saved = slice.call( arguments ); + dataPriv.set( this, type, saved ); + + // Trigger the native event and capture its result + // Support: IE <=9 - 11+ + // focus() and blur() are asynchronous + notAsync = expectSync( this, type ); + this[ type ](); + result = dataPriv.get( this, type ); + if ( saved !== result || notAsync ) { + dataPriv.set( this, type, false ); + } else { + result = {}; + } + if ( saved !== result ) { + + // Cancel the outer synthetic event + event.stopImmediatePropagation(); + event.preventDefault(); + return result.value; + } + + // If this is an inner synthetic event for an event with a bubbling surrogate + // (focus or blur), assume that the surrogate already propagated from triggering the + // native event and prevent that from happening again here. + // This technically gets the ordering wrong w.r.t. to `.trigger()` (in which the + // bubbling surrogate propagates *after* the non-bubbling base), but that seems + // less bad than duplication. + } else if ( ( jQuery.event.special[ type ] || {} ).delegateType ) { + event.stopPropagation(); + } + + // If this is a native event triggered above, everything is now in order + // Fire an inner synthetic event with the original arguments + } else if ( saved.length ) { + + // ...and capture the result + dataPriv.set( this, type, { + value: jQuery.event.trigger( + + // Support: IE <=9 - 11+ + // Extend with the prototype to reset the above stopImmediatePropagation() + jQuery.extend( saved[ 0 ], jQuery.Event.prototype ), + saved.slice( 1 ), + this + ) + } ); + + // Abort handling of the native event + event.stopImmediatePropagation(); + } + } + } ); +} + +jQuery.removeEvent = function( elem, type, handle ) { + + // This "if" is needed for plain objects + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle ); + } +}; + +jQuery.Event = function( src, props ) { + + // Allow instantiation without the 'new' keyword + if ( !( this instanceof jQuery.Event ) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = src.defaultPrevented || + src.defaultPrevented === undefined && + + // Support: Android <=2.3 only + src.returnValue === false ? + returnTrue : + returnFalse; + + // Create target properties + // Support: Safari <=6 - 7 only + // Target should not be a text node (#504, #13143) + this.target = ( src.target && src.target.nodeType === 3 ) ? + src.target.parentNode : + src.target; + + this.currentTarget = src.currentTarget; + this.relatedTarget = src.relatedTarget; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || Date.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + constructor: jQuery.Event, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, + isSimulated: false, + + preventDefault: function() { + var e = this.originalEvent; + + this.isDefaultPrevented = returnTrue; + + if ( e && !this.isSimulated ) { + e.preventDefault(); + } + }, + stopPropagation: function() { + var e = this.originalEvent; + + this.isPropagationStopped = returnTrue; + + if ( e && !this.isSimulated ) { + e.stopPropagation(); + } + }, + stopImmediatePropagation: function() { + var e = this.originalEvent; + + this.isImmediatePropagationStopped = returnTrue; + + if ( e && !this.isSimulated ) { + e.stopImmediatePropagation(); + } + + this.stopPropagation(); + } +}; + +// Includes all common event props including KeyEvent and MouseEvent specific props +jQuery.each( { + altKey: true, + bubbles: true, + cancelable: true, + changedTouches: true, + ctrlKey: true, + detail: true, + eventPhase: true, + metaKey: true, + pageX: true, + pageY: true, + shiftKey: true, + view: true, + "char": true, + code: true, + charCode: true, + key: true, + keyCode: true, + button: true, + buttons: true, + clientX: true, + clientY: true, + offsetX: true, + offsetY: true, + pointerId: true, + pointerType: true, + screenX: true, + screenY: true, + targetTouches: true, + toElement: true, + touches: true, + + which: function( event ) { + var button = event.button; + + // Add which for key events + if ( event.which == null && rkeyEvent.test( event.type ) ) { + return event.charCode != null ? event.charCode : event.keyCode; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) { + if ( button & 1 ) { + return 1; + } + + if ( button & 2 ) { + return 3; + } + + if ( button & 4 ) { + return 2; + } + + return 0; + } + + return event.which; + } +}, jQuery.event.addProp ); + +jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateType ) { + jQuery.event.special[ type ] = { + + // Utilize native event if possible so blur/focus sequence is correct + setup: function() { + + // Claim the first handler + // dataPriv.set( this, "focus", ... ) + // dataPriv.set( this, "blur", ... ) + leverageNative( this, type, expectSync ); + + // Return false to allow normal processing in the caller + return false; + }, + trigger: function() { + + // Force setup before trigger + leverageNative( this, type ); + + // Return non-false to allow normal event-path propagation + return true; + }, + + delegateType: delegateType + }; +} ); + +// Create mouseenter/leave events using mouseover/out and event-time checks +// so that event delegation works in jQuery. +// Do the same for pointerenter/pointerleave and pointerover/pointerout +// +// Support: Safari 7 only +// Safari sends mouseenter too often; see: +// https://bugs.chromium.org/p/chromium/issues/detail?id=470258 +// for the description of the bug (it existed in older Chrome versions as well). +jQuery.each( { + mouseenter: "mouseover", + mouseleave: "mouseout", + pointerenter: "pointerover", + pointerleave: "pointerout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj; + + // For mouseenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +} ); + +jQuery.fn.extend( { + + on: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn ); + }, + one: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? + handleObj.origType + "." + handleObj.namespace : + handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each( function() { + jQuery.event.remove( this, types, fn, selector ); + } ); + } +} ); + + +var + + // Support: IE <=10 - 11, Edge 12 - 13 only + // In IE/Edge using regex groups here causes severe slowdowns. + // See https://connect.microsoft.com/IE/feedback/details/1736512/ + rnoInnerhtml = /\s*$/g; + +// Prefer a tbody over its parent table for containing new rows +function manipulationTarget( elem, content ) { + if ( nodeName( elem, "table" ) && + nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { + + return jQuery( elem ).children( "tbody" )[ 0 ] || elem; + } + + return elem; +} + +// Replace/restore the type attribute of script elements for safe DOM manipulation +function disableScript( elem ) { + elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; + return elem; +} +function restoreScript( elem ) { + if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) { + elem.type = elem.type.slice( 5 ); + } else { + elem.removeAttribute( "type" ); + } + + return elem; +} + +function cloneCopyEvent( src, dest ) { + var i, l, type, pdataOld, udataOld, udataCur, events; + + if ( dest.nodeType !== 1 ) { + return; + } + + // 1. Copy private data: events, handlers, etc. + if ( dataPriv.hasData( src ) ) { + pdataOld = dataPriv.get( src ); + events = pdataOld.events; + + if ( events ) { + dataPriv.remove( dest, "handle events" ); + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + } + + // 2. Copy user data + if ( dataUser.hasData( src ) ) { + udataOld = dataUser.access( src ); + udataCur = jQuery.extend( {}, udataOld ); + + dataUser.set( dest, udataCur ); + } +} + +// Fix IE bugs, see support tests +function fixInput( src, dest ) { + var nodeName = dest.nodeName.toLowerCase(); + + // Fails to persist the checked state of a cloned checkbox or radio button. + if ( nodeName === "input" && rcheckableType.test( src.type ) ) { + dest.checked = src.checked; + + // Fails to return the selected option to the default selected state when cloning options + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + } +} + +function domManip( collection, args, callback, ignored ) { + + // Flatten any nested arrays + args = flat( args ); + + var fragment, first, scripts, hasScripts, node, doc, + i = 0, + l = collection.length, + iNoClone = l - 1, + value = args[ 0 ], + valueIsFunction = isFunction( value ); + + // We can't cloneNode fragments that contain checked, in WebKit + if ( valueIsFunction || + ( l > 1 && typeof value === "string" && + !support.checkClone && rchecked.test( value ) ) ) { + return collection.each( function( index ) { + var self = collection.eq( index ); + if ( valueIsFunction ) { + args[ 0 ] = value.call( this, index, self.html() ); + } + domManip( self, args, callback, ignored ); + } ); + } + + if ( l ) { + fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + // Require either new content or an interest in ignored elements to invoke the callback + if ( first || ignored ) { + scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); + hasScripts = scripts.length; + + // Use the original fragment for the last item + // instead of the first because it can end up + // being emptied incorrectly in certain situations (#8070). + for ( ; i < l; i++ ) { + node = fragment; + + if ( i !== iNoClone ) { + node = jQuery.clone( node, true, true ); + + // Keep references to cloned scripts for later restoration + if ( hasScripts ) { + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( scripts, getAll( node, "script" ) ); + } + } + + callback.call( collection[ i ], node, i ); + } + + if ( hasScripts ) { + doc = scripts[ scripts.length - 1 ].ownerDocument; + + // Reenable scripts + jQuery.map( scripts, restoreScript ); + + // Evaluate executable scripts on first document insertion + for ( i = 0; i < hasScripts; i++ ) { + node = scripts[ i ]; + if ( rscriptType.test( node.type || "" ) && + !dataPriv.access( node, "globalEval" ) && + jQuery.contains( doc, node ) ) { + + if ( node.src && ( node.type || "" ).toLowerCase() !== "module" ) { + + // Optional AJAX dependency, but won't run scripts if not present + if ( jQuery._evalUrl && !node.noModule ) { + jQuery._evalUrl( node.src, { + nonce: node.nonce || node.getAttribute( "nonce" ) + }, doc ); + } + } else { + DOMEval( node.textContent.replace( rcleanScript, "" ), node, doc ); + } + } + } + } + } + } + + return collection; +} + +function remove( elem, selector, keepData ) { + var node, + nodes = selector ? jQuery.filter( selector, elem ) : elem, + i = 0; + + for ( ; ( node = nodes[ i ] ) != null; i++ ) { + if ( !keepData && node.nodeType === 1 ) { + jQuery.cleanData( getAll( node ) ); + } + + if ( node.parentNode ) { + if ( keepData && isAttached( node ) ) { + setGlobalEval( getAll( node, "script" ) ); + } + node.parentNode.removeChild( node ); + } + } + + return elem; +} + +jQuery.extend( { + htmlPrefilter: function( html ) { + return html; + }, + + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var i, l, srcElements, destElements, + clone = elem.cloneNode( true ), + inPage = isAttached( elem ); + + // Fix IE cloning issues + if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && + !jQuery.isXMLDoc( elem ) ) { + + // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2 + destElements = getAll( clone ); + srcElements = getAll( elem ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + fixInput( srcElements[ i ], destElements[ i ] ); + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + if ( deepDataAndEvents ) { + srcElements = srcElements || getAll( elem ); + destElements = destElements || getAll( clone ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + cloneCopyEvent( srcElements[ i ], destElements[ i ] ); + } + } else { + cloneCopyEvent( elem, clone ); + } + } + + // Preserve script evaluation history + destElements = getAll( clone, "script" ); + if ( destElements.length > 0 ) { + setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); + } + + // Return the cloned set + return clone; + }, + + cleanData: function( elems ) { + var data, elem, type, + special = jQuery.event.special, + i = 0; + + for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { + if ( acceptData( elem ) ) { + if ( ( data = elem[ dataPriv.expando ] ) ) { + if ( data.events ) { + for ( type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + } + + // Support: Chrome <=35 - 45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataPriv.expando ] = undefined; + } + if ( elem[ dataUser.expando ] ) { + + // Support: Chrome <=35 - 45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataUser.expando ] = undefined; + } + } + } + } +} ); + +jQuery.fn.extend( { + detach: function( selector ) { + return remove( this, selector, true ); + }, + + remove: function( selector ) { + return remove( this, selector ); + }, + + text: function( value ) { + return access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().each( function() { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + this.textContent = value; + } + } ); + }, null, value, arguments.length ); + }, + + append: function() { + return domManip( this, arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.appendChild( elem ); + } + } ); + }, + + prepend: function() { + return domManip( this, arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.insertBefore( elem, target.firstChild ); + } + } ); + }, + + before: function() { + return domManip( this, arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this ); + } + } ); + }, + + after: function() { + return domManip( this, arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + } + } ); + }, + + empty: function() { + var elem, + i = 0; + + for ( ; ( elem = this[ i ] ) != null; i++ ) { + if ( elem.nodeType === 1 ) { + + // Prevent memory leaks + jQuery.cleanData( getAll( elem, false ) ); + + // Remove any remaining nodes + elem.textContent = ""; + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? false : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map( function() { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + } ); + }, + + html: function( value ) { + return access( this, function( value ) { + var elem = this[ 0 ] || {}, + i = 0, + l = this.length; + + if ( value === undefined && elem.nodeType === 1 ) { + return elem.innerHTML; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { + + value = jQuery.htmlPrefilter( value ); + + try { + for ( ; i < l; i++ ) { + elem = this[ i ] || {}; + + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + elem.innerHTML = value; + } + } + + elem = 0; + + // If using innerHTML throws an exception, use the fallback method + } catch ( e ) {} + } + + if ( elem ) { + this.empty().append( value ); + } + }, null, value, arguments.length ); + }, + + replaceWith: function() { + var ignored = []; + + // Make the changes, replacing each non-ignored context element with the new content + return domManip( this, arguments, function( elem ) { + var parent = this.parentNode; + + if ( jQuery.inArray( this, ignored ) < 0 ) { + jQuery.cleanData( getAll( this ) ); + if ( parent ) { + parent.replaceChild( elem, this ); + } + } + + // Force callback invocation + }, ignored ); + } +} ); + +jQuery.each( { + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + ret = [], + insert = jQuery( selector ), + last = insert.length - 1, + i = 0; + + for ( ; i <= last; i++ ) { + elems = i === last ? this : this.clone( true ); + jQuery( insert[ i ] )[ original ]( elems ); + + // Support: Android <=4.0 only, PhantomJS 1 only + // .get() because push.apply(_, arraylike) throws on ancient WebKit + push.apply( ret, elems.get() ); + } + + return this.pushStack( ret ); + }; +} ); +var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); + +var getStyles = function( elem ) { + + // Support: IE <=11 only, Firefox <=30 (#15098, #14150) + // IE throws on elements created in popups + // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" + var view = elem.ownerDocument.defaultView; + + if ( !view || !view.opener ) { + view = window; + } + + return view.getComputedStyle( elem ); + }; + +var swap = function( elem, options, callback ) { + var ret, name, + old = {}; + + // Remember the old values, and insert the new ones + for ( name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } + + ret = callback.call( elem ); + + // Revert the old values + for ( name in options ) { + elem.style[ name ] = old[ name ]; + } + + return ret; +}; + + +var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" ); + + + +( function() { + + // Executing both pixelPosition & boxSizingReliable tests require only one layout + // so they're executed at the same time to save the second computation. + function computeStyleTests() { + + // This is a singleton, we need to execute it only once + if ( !div ) { + return; + } + + container.style.cssText = "position:absolute;left:-11111px;width:60px;" + + "margin-top:1px;padding:0;border:0"; + div.style.cssText = + "position:relative;display:block;box-sizing:border-box;overflow:scroll;" + + "margin:auto;border:1px;padding:1px;" + + "width:60%;top:1%"; + documentElement.appendChild( container ).appendChild( div ); + + var divStyle = window.getComputedStyle( div ); + pixelPositionVal = divStyle.top !== "1%"; + + // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 + reliableMarginLeftVal = roundPixelMeasures( divStyle.marginLeft ) === 12; + + // Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3 + // Some styles come back with percentage values, even though they shouldn't + div.style.right = "60%"; + pixelBoxStylesVal = roundPixelMeasures( divStyle.right ) === 36; + + // Support: IE 9 - 11 only + // Detect misreporting of content dimensions for box-sizing:border-box elements + boxSizingReliableVal = roundPixelMeasures( divStyle.width ) === 36; + + // Support: IE 9 only + // Detect overflow:scroll screwiness (gh-3699) + // Support: Chrome <=64 + // Don't get tricked when zoom affects offsetWidth (gh-4029) + div.style.position = "absolute"; + scrollboxSizeVal = roundPixelMeasures( div.offsetWidth / 3 ) === 12; + + documentElement.removeChild( container ); + + // Nullify the div so it wouldn't be stored in the memory and + // it will also be a sign that checks already performed + div = null; + } + + function roundPixelMeasures( measure ) { + return Math.round( parseFloat( measure ) ); + } + + var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal, + reliableTrDimensionsVal, reliableMarginLeftVal, + container = document.createElement( "div" ), + div = document.createElement( "div" ); + + // Finish early in limited (non-browser) environments + if ( !div.style ) { + return; + } + + // Support: IE <=9 - 11 only + // Style of cloned element affects source element cloned (#8908) + div.style.backgroundClip = "content-box"; + div.cloneNode( true ).style.backgroundClip = ""; + support.clearCloneStyle = div.style.backgroundClip === "content-box"; + + jQuery.extend( support, { + boxSizingReliable: function() { + computeStyleTests(); + return boxSizingReliableVal; + }, + pixelBoxStyles: function() { + computeStyleTests(); + return pixelBoxStylesVal; + }, + pixelPosition: function() { + computeStyleTests(); + return pixelPositionVal; + }, + reliableMarginLeft: function() { + computeStyleTests(); + return reliableMarginLeftVal; + }, + scrollboxSize: function() { + computeStyleTests(); + return scrollboxSizeVal; + }, + + // Support: IE 9 - 11+, Edge 15 - 18+ + // IE/Edge misreport `getComputedStyle` of table rows with width/height + // set in CSS while `offset*` properties report correct values. + // Behavior in IE 9 is more subtle than in newer versions & it passes + // some versions of this test; make sure not to make it pass there! + reliableTrDimensions: function() { + var table, tr, trChild, trStyle; + if ( reliableTrDimensionsVal == null ) { + table = document.createElement( "table" ); + tr = document.createElement( "tr" ); + trChild = document.createElement( "div" ); + + table.style.cssText = "position:absolute;left:-11111px"; + tr.style.height = "1px"; + trChild.style.height = "9px"; + + documentElement + .appendChild( table ) + .appendChild( tr ) + .appendChild( trChild ); + + trStyle = window.getComputedStyle( tr ); + reliableTrDimensionsVal = parseInt( trStyle.height ) > 3; + + documentElement.removeChild( table ); + } + return reliableTrDimensionsVal; + } + } ); +} )(); + + +function curCSS( elem, name, computed ) { + var width, minWidth, maxWidth, ret, + + // Support: Firefox 51+ + // Retrieving style before computed somehow + // fixes an issue with getting wrong values + // on detached elements + style = elem.style; + + computed = computed || getStyles( elem ); + + // getPropertyValue is needed for: + // .css('filter') (IE 9 only, #12537) + // .css('--customProperty) (#3144) + if ( computed ) { + ret = computed.getPropertyValue( name ) || computed[ name ]; + + if ( ret === "" && !isAttached( elem ) ) { + ret = jQuery.style( elem, name ); + } + + // A tribute to the "awesome hack by Dean Edwards" + // Android Browser returns percentage for some values, + // but width seems to be reliably pixels. + // This is against the CSSOM draft spec: + // https://drafts.csswg.org/cssom/#resolved-values + if ( !support.pixelBoxStyles() && rnumnonpx.test( ret ) && rboxStyle.test( name ) ) { + + // Remember the original values + width = style.width; + minWidth = style.minWidth; + maxWidth = style.maxWidth; + + // Put in the new values to get a computed value out + style.minWidth = style.maxWidth = style.width = ret; + ret = computed.width; + + // Revert the changed values + style.width = width; + style.minWidth = minWidth; + style.maxWidth = maxWidth; + } + } + + return ret !== undefined ? + + // Support: IE <=9 - 11 only + // IE returns zIndex value as an integer. + ret + "" : + ret; +} + + +function addGetHookIf( conditionFn, hookFn ) { + + // Define the hook, we'll check on the first run if it's really needed. + return { + get: function() { + if ( conditionFn() ) { + + // Hook not needed (or it's not possible to use it due + // to missing dependency), remove it. + delete this.get; + return; + } + + // Hook needed; redefine it so that the support test is not executed again. + return ( this.get = hookFn ).apply( this, arguments ); + } + }; +} + + +var cssPrefixes = [ "Webkit", "Moz", "ms" ], + emptyStyle = document.createElement( "div" ).style, + vendorProps = {}; + +// Return a vendor-prefixed property or undefined +function vendorPropName( name ) { + + // Check for vendor prefixed names + var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), + i = cssPrefixes.length; + + while ( i-- ) { + name = cssPrefixes[ i ] + capName; + if ( name in emptyStyle ) { + return name; + } + } +} + +// Return a potentially-mapped jQuery.cssProps or vendor prefixed property +function finalPropName( name ) { + var final = jQuery.cssProps[ name ] || vendorProps[ name ]; + + if ( final ) { + return final; + } + if ( name in emptyStyle ) { + return name; + } + return vendorProps[ name ] = vendorPropName( name ) || name; +} + + +var + + // Swappable if display is none or starts with table + // except "table", "table-cell", or "table-caption" + // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display + rdisplayswap = /^(none|table(?!-c[ea]).+)/, + rcustomProp = /^--/, + cssShow = { position: "absolute", visibility: "hidden", display: "block" }, + cssNormalTransform = { + letterSpacing: "0", + fontWeight: "400" + }; + +function setPositiveNumber( _elem, value, subtract ) { + + // Any relative (+/-) values have already been + // normalized at this point + var matches = rcssNum.exec( value ); + return matches ? + + // Guard against undefined "subtract", e.g., when used as in cssHooks + Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : + value; +} + +function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) { + var i = dimension === "width" ? 1 : 0, + extra = 0, + delta = 0; + + // Adjustment may not be necessary + if ( box === ( isBorderBox ? "border" : "content" ) ) { + return 0; + } + + for ( ; i < 4; i += 2 ) { + + // Both box models exclude margin + if ( box === "margin" ) { + delta += jQuery.css( elem, box + cssExpand[ i ], true, styles ); + } + + // If we get here with a content-box, we're seeking "padding" or "border" or "margin" + if ( !isBorderBox ) { + + // Add padding + delta += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + + // For "border" or "margin", add border + if ( box !== "padding" ) { + delta += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + + // But still keep track of it otherwise + } else { + extra += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + + // If we get here with a border-box (content + padding + border), we're seeking "content" or + // "padding" or "margin" + } else { + + // For "content", subtract padding + if ( box === "content" ) { + delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + } + + // For "content" or "padding", subtract border + if ( box !== "margin" ) { + delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + } + } + + // Account for positive content-box scroll gutter when requested by providing computedVal + if ( !isBorderBox && computedVal >= 0 ) { + + // offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border + // Assuming integer scroll gutter, subtract the rest and round down + delta += Math.max( 0, Math.ceil( + elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - + computedVal - + delta - + extra - + 0.5 + + // If offsetWidth/offsetHeight is unknown, then we can't determine content-box scroll gutter + // Use an explicit zero to avoid NaN (gh-3964) + ) ) || 0; + } + + return delta; +} + +function getWidthOrHeight( elem, dimension, extra ) { + + // Start with computed style + var styles = getStyles( elem ), + + // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-4322). + // Fake content-box until we know it's needed to know the true value. + boxSizingNeeded = !support.boxSizingReliable() || extra, + isBorderBox = boxSizingNeeded && + jQuery.css( elem, "boxSizing", false, styles ) === "border-box", + valueIsBorderBox = isBorderBox, + + val = curCSS( elem, dimension, styles ), + offsetProp = "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ); + + // Support: Firefox <=54 + // Return a confounding non-pixel value or feign ignorance, as appropriate. + if ( rnumnonpx.test( val ) ) { + if ( !extra ) { + return val; + } + val = "auto"; + } + + + // Support: IE 9 - 11 only + // Use offsetWidth/offsetHeight for when box sizing is unreliable. + // In those cases, the computed value can be trusted to be border-box. + if ( ( !support.boxSizingReliable() && isBorderBox || + + // Support: IE 10 - 11+, Edge 15 - 18+ + // IE/Edge misreport `getComputedStyle` of table rows with width/height + // set in CSS while `offset*` properties report correct values. + // Interestingly, in some cases IE 9 doesn't suffer from this issue. + !support.reliableTrDimensions() && nodeName( elem, "tr" ) || + + // Fall back to offsetWidth/offsetHeight when value is "auto" + // This happens for inline elements with no explicit setting (gh-3571) + val === "auto" || + + // Support: Android <=4.1 - 4.3 only + // Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602) + !parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) && + + // Make sure the element is visible & connected + elem.getClientRects().length ) { + + isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; + + // Where available, offsetWidth/offsetHeight approximate border box dimensions. + // Where not available (e.g., SVG), assume unreliable box-sizing and interpret the + // retrieved value as a content box dimension. + valueIsBorderBox = offsetProp in elem; + if ( valueIsBorderBox ) { + val = elem[ offsetProp ]; + } + } + + // Normalize "" and auto + val = parseFloat( val ) || 0; + + // Adjust for the element's box model + return ( val + + boxModelAdjustment( + elem, + dimension, + extra || ( isBorderBox ? "border" : "content" ), + valueIsBorderBox, + styles, + + // Provide the current computed size to request scroll gutter calculation (gh-3589) + val + ) + ) + "px"; +} + +jQuery.extend( { + + // Add in style property hooks for overriding the default + // behavior of getting and setting a style property + cssHooks: { + opacity: { + get: function( elem, computed ) { + if ( computed ) { + + // We should always get a number back from opacity + var ret = curCSS( elem, "opacity" ); + return ret === "" ? "1" : ret; + } + } + } + }, + + // Don't automatically add "px" to these possibly-unitless properties + cssNumber: { + "animationIterationCount": true, + "columnCount": true, + "fillOpacity": true, + "flexGrow": true, + "flexShrink": true, + "fontWeight": true, + "gridArea": true, + "gridColumn": true, + "gridColumnEnd": true, + "gridColumnStart": true, + "gridRow": true, + "gridRowEnd": true, + "gridRowStart": true, + "lineHeight": true, + "opacity": true, + "order": true, + "orphans": true, + "widows": true, + "zIndex": true, + "zoom": true + }, + + // Add in properties whose names you wish to fix before + // setting or getting the value + cssProps: {}, + + // Get and set the style property on a DOM Node + style: function( elem, name, value, extra ) { + + // Don't set styles on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { + return; + } + + // Make sure that we're working with the right name + var ret, type, hooks, + origName = camelCase( name ), + isCustomProp = rcustomProp.test( name ), + style = elem.style; + + // Make sure that we're working with the right name. We don't + // want to query the value if it is a CSS custom property + // since they are user-defined. + if ( !isCustomProp ) { + name = finalPropName( origName ); + } + + // Gets hook for the prefixed version, then unprefixed version + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // Check if we're setting a value + if ( value !== undefined ) { + type = typeof value; + + // Convert "+=" or "-=" to relative numbers (#7345) + if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { + value = adjustCSS( elem, name, ret ); + + // Fixes bug #9237 + type = "number"; + } + + // Make sure that null and NaN values aren't set (#7116) + if ( value == null || value !== value ) { + return; + } + + // If a number was passed in, add the unit (except for certain CSS properties) + // The isCustomProp check can be removed in jQuery 4.0 when we only auto-append + // "px" to a few hardcoded values. + if ( type === "number" && !isCustomProp ) { + value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); + } + + // background-* props affect original clone's values + if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { + style[ name ] = "inherit"; + } + + // If a hook was provided, use that value, otherwise just set the specified value + if ( !hooks || !( "set" in hooks ) || + ( value = hooks.set( elem, value, extra ) ) !== undefined ) { + + if ( isCustomProp ) { + style.setProperty( name, value ); + } else { + style[ name ] = value; + } + } + + } else { + + // If a hook was provided get the non-computed value from there + if ( hooks && "get" in hooks && + ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { + + return ret; + } + + // Otherwise just get the value from the style object + return style[ name ]; + } + }, + + css: function( elem, name, extra, styles ) { + var val, num, hooks, + origName = camelCase( name ), + isCustomProp = rcustomProp.test( name ); + + // Make sure that we're working with the right name. We don't + // want to modify the value if it is a CSS custom property + // since they are user-defined. + if ( !isCustomProp ) { + name = finalPropName( origName ); + } + + // Try prefixed name followed by the unprefixed name + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // If a hook was provided get the computed value from there + if ( hooks && "get" in hooks ) { + val = hooks.get( elem, true, extra ); + } + + // Otherwise, if a way to get the computed value exists, use that + if ( val === undefined ) { + val = curCSS( elem, name, styles ); + } + + // Convert "normal" to computed value + if ( val === "normal" && name in cssNormalTransform ) { + val = cssNormalTransform[ name ]; + } + + // Make numeric if forced or a qualifier was provided and val looks numeric + if ( extra === "" || extra ) { + num = parseFloat( val ); + return extra === true || isFinite( num ) ? num || 0 : val; + } + + return val; + } +} ); + +jQuery.each( [ "height", "width" ], function( _i, dimension ) { + jQuery.cssHooks[ dimension ] = { + get: function( elem, computed, extra ) { + if ( computed ) { + + // Certain elements can have dimension info if we invisibly show them + // but it must have a current display style that would benefit + return rdisplayswap.test( jQuery.css( elem, "display" ) ) && + + // Support: Safari 8+ + // Table columns in Safari have non-zero offsetWidth & zero + // getBoundingClientRect().width unless display is changed. + // Support: IE <=11 only + // Running getBoundingClientRect on a disconnected node + // in IE throws an error. + ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? + swap( elem, cssShow, function() { + return getWidthOrHeight( elem, dimension, extra ); + } ) : + getWidthOrHeight( elem, dimension, extra ); + } + }, + + set: function( elem, value, extra ) { + var matches, + styles = getStyles( elem ), + + // Only read styles.position if the test has a chance to fail + // to avoid forcing a reflow. + scrollboxSizeBuggy = !support.scrollboxSize() && + styles.position === "absolute", + + // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-3991) + boxSizingNeeded = scrollboxSizeBuggy || extra, + isBorderBox = boxSizingNeeded && + jQuery.css( elem, "boxSizing", false, styles ) === "border-box", + subtract = extra ? + boxModelAdjustment( + elem, + dimension, + extra, + isBorderBox, + styles + ) : + 0; + + // Account for unreliable border-box dimensions by comparing offset* to computed and + // faking a content-box to get border and padding (gh-3699) + if ( isBorderBox && scrollboxSizeBuggy ) { + subtract -= Math.ceil( + elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - + parseFloat( styles[ dimension ] ) - + boxModelAdjustment( elem, dimension, "border", false, styles ) - + 0.5 + ); + } + + // Convert to pixels if value adjustment is needed + if ( subtract && ( matches = rcssNum.exec( value ) ) && + ( matches[ 3 ] || "px" ) !== "px" ) { + + elem.style[ dimension ] = value; + value = jQuery.css( elem, dimension ); + } + + return setPositiveNumber( elem, value, subtract ); + } + }; +} ); + +jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, + function( elem, computed ) { + if ( computed ) { + return ( parseFloat( curCSS( elem, "marginLeft" ) ) || + elem.getBoundingClientRect().left - + swap( elem, { marginLeft: 0 }, function() { + return elem.getBoundingClientRect().left; + } ) + ) + "px"; + } + } +); + +// These hooks are used by animate to expand properties +jQuery.each( { + margin: "", + padding: "", + border: "Width" +}, function( prefix, suffix ) { + jQuery.cssHooks[ prefix + suffix ] = { + expand: function( value ) { + var i = 0, + expanded = {}, + + // Assumes a single number if not a string + parts = typeof value === "string" ? value.split( " " ) : [ value ]; + + for ( ; i < 4; i++ ) { + expanded[ prefix + cssExpand[ i ] + suffix ] = + parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; + } + + return expanded; + } + }; + + if ( prefix !== "margin" ) { + jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; + } +} ); + +jQuery.fn.extend( { + css: function( name, value ) { + return access( this, function( elem, name, value ) { + var styles, len, + map = {}, + i = 0; + + if ( Array.isArray( name ) ) { + styles = getStyles( elem ); + len = name.length; + + for ( ; i < len; i++ ) { + map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); + } + + return map; + } + + return value !== undefined ? + jQuery.style( elem, name, value ) : + jQuery.css( elem, name ); + }, name, value, arguments.length > 1 ); + } +} ); + + +function Tween( elem, options, prop, end, easing ) { + return new Tween.prototype.init( elem, options, prop, end, easing ); +} +jQuery.Tween = Tween; + +Tween.prototype = { + constructor: Tween, + init: function( elem, options, prop, end, easing, unit ) { + this.elem = elem; + this.prop = prop; + this.easing = easing || jQuery.easing._default; + this.options = options; + this.start = this.now = this.cur(); + this.end = end; + this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); + }, + cur: function() { + var hooks = Tween.propHooks[ this.prop ]; + + return hooks && hooks.get ? + hooks.get( this ) : + Tween.propHooks._default.get( this ); + }, + run: function( percent ) { + var eased, + hooks = Tween.propHooks[ this.prop ]; + + if ( this.options.duration ) { + this.pos = eased = jQuery.easing[ this.easing ]( + percent, this.options.duration * percent, 0, 1, this.options.duration + ); + } else { + this.pos = eased = percent; + } + this.now = ( this.end - this.start ) * eased + this.start; + + if ( this.options.step ) { + this.options.step.call( this.elem, this.now, this ); + } + + if ( hooks && hooks.set ) { + hooks.set( this ); + } else { + Tween.propHooks._default.set( this ); + } + return this; + } +}; + +Tween.prototype.init.prototype = Tween.prototype; + +Tween.propHooks = { + _default: { + get: function( tween ) { + var result; + + // Use a property on the element directly when it is not a DOM element, + // or when there is no matching style property that exists. + if ( tween.elem.nodeType !== 1 || + tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { + return tween.elem[ tween.prop ]; + } + + // Passing an empty string as a 3rd parameter to .css will automatically + // attempt a parseFloat and fallback to a string if the parse fails. + // Simple values such as "10px" are parsed to Float; + // complex values such as "rotate(1rad)" are returned as-is. + result = jQuery.css( tween.elem, tween.prop, "" ); + + // Empty strings, null, undefined and "auto" are converted to 0. + return !result || result === "auto" ? 0 : result; + }, + set: function( tween ) { + + // Use step hook for back compat. + // Use cssHook if its there. + // Use .style if available and use plain properties where available. + if ( jQuery.fx.step[ tween.prop ] ) { + jQuery.fx.step[ tween.prop ]( tween ); + } else if ( tween.elem.nodeType === 1 && ( + jQuery.cssHooks[ tween.prop ] || + tween.elem.style[ finalPropName( tween.prop ) ] != null ) ) { + jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); + } else { + tween.elem[ tween.prop ] = tween.now; + } + } + } +}; + +// Support: IE <=9 only +// Panic based approach to setting things on disconnected nodes +Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { + set: function( tween ) { + if ( tween.elem.nodeType && tween.elem.parentNode ) { + tween.elem[ tween.prop ] = tween.now; + } + } +}; + +jQuery.easing = { + linear: function( p ) { + return p; + }, + swing: function( p ) { + return 0.5 - Math.cos( p * Math.PI ) / 2; + }, + _default: "swing" +}; + +jQuery.fx = Tween.prototype.init; + +// Back compat <1.8 extension point +jQuery.fx.step = {}; + + + + +var + fxNow, inProgress, + rfxtypes = /^(?:toggle|show|hide)$/, + rrun = /queueHooks$/; + +function schedule() { + if ( inProgress ) { + if ( document.hidden === false && window.requestAnimationFrame ) { + window.requestAnimationFrame( schedule ); + } else { + window.setTimeout( schedule, jQuery.fx.interval ); + } + + jQuery.fx.tick(); + } +} + +// Animations created synchronously will run synchronously +function createFxNow() { + window.setTimeout( function() { + fxNow = undefined; + } ); + return ( fxNow = Date.now() ); +} + +// Generate parameters to create a standard animation +function genFx( type, includeWidth ) { + var which, + i = 0, + attrs = { height: type }; + + // If we include width, step value is 1 to do all cssExpand values, + // otherwise step value is 2 to skip over Left and Right + includeWidth = includeWidth ? 1 : 0; + for ( ; i < 4; i += 2 - includeWidth ) { + which = cssExpand[ i ]; + attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; + } + + if ( includeWidth ) { + attrs.opacity = attrs.width = type; + } + + return attrs; +} + +function createTween( value, prop, animation ) { + var tween, + collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), + index = 0, + length = collection.length; + for ( ; index < length; index++ ) { + if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { + + // We're done with this property + return tween; + } + } +} + +function defaultPrefilter( elem, props, opts ) { + var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, + isBox = "width" in props || "height" in props, + anim = this, + orig = {}, + style = elem.style, + hidden = elem.nodeType && isHiddenWithinTree( elem ), + dataShow = dataPriv.get( elem, "fxshow" ); + + // Queue-skipping animations hijack the fx hooks + if ( !opts.queue ) { + hooks = jQuery._queueHooks( elem, "fx" ); + if ( hooks.unqueued == null ) { + hooks.unqueued = 0; + oldfire = hooks.empty.fire; + hooks.empty.fire = function() { + if ( !hooks.unqueued ) { + oldfire(); + } + }; + } + hooks.unqueued++; + + anim.always( function() { + + // Ensure the complete handler is called before this completes + anim.always( function() { + hooks.unqueued--; + if ( !jQuery.queue( elem, "fx" ).length ) { + hooks.empty.fire(); + } + } ); + } ); + } + + // Detect show/hide animations + for ( prop in props ) { + value = props[ prop ]; + if ( rfxtypes.test( value ) ) { + delete props[ prop ]; + toggle = toggle || value === "toggle"; + if ( value === ( hidden ? "hide" : "show" ) ) { + + // Pretend to be hidden if this is a "show" and + // there is still data from a stopped show/hide + if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { + hidden = true; + + // Ignore all other no-op show/hide data + } else { + continue; + } + } + orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); + } + } + + // Bail out if this is a no-op like .hide().hide() + propTween = !jQuery.isEmptyObject( props ); + if ( !propTween && jQuery.isEmptyObject( orig ) ) { + return; + } + + // Restrict "overflow" and "display" styles during box animations + if ( isBox && elem.nodeType === 1 ) { + + // Support: IE <=9 - 11, Edge 12 - 15 + // Record all 3 overflow attributes because IE does not infer the shorthand + // from identically-valued overflowX and overflowY and Edge just mirrors + // the overflowX value there. + opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; + + // Identify a display type, preferring old show/hide data over the CSS cascade + restoreDisplay = dataShow && dataShow.display; + if ( restoreDisplay == null ) { + restoreDisplay = dataPriv.get( elem, "display" ); + } + display = jQuery.css( elem, "display" ); + if ( display === "none" ) { + if ( restoreDisplay ) { + display = restoreDisplay; + } else { + + // Get nonempty value(s) by temporarily forcing visibility + showHide( [ elem ], true ); + restoreDisplay = elem.style.display || restoreDisplay; + display = jQuery.css( elem, "display" ); + showHide( [ elem ] ); + } + } + + // Animate inline elements as inline-block + if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) { + if ( jQuery.css( elem, "float" ) === "none" ) { + + // Restore the original display value at the end of pure show/hide animations + if ( !propTween ) { + anim.done( function() { + style.display = restoreDisplay; + } ); + if ( restoreDisplay == null ) { + display = style.display; + restoreDisplay = display === "none" ? "" : display; + } + } + style.display = "inline-block"; + } + } + } + + if ( opts.overflow ) { + style.overflow = "hidden"; + anim.always( function() { + style.overflow = opts.overflow[ 0 ]; + style.overflowX = opts.overflow[ 1 ]; + style.overflowY = opts.overflow[ 2 ]; + } ); + } + + // Implement show/hide animations + propTween = false; + for ( prop in orig ) { + + // General show/hide setup for this element animation + if ( !propTween ) { + if ( dataShow ) { + if ( "hidden" in dataShow ) { + hidden = dataShow.hidden; + } + } else { + dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } ); + } + + // Store hidden/visible for toggle so `.stop().toggle()` "reverses" + if ( toggle ) { + dataShow.hidden = !hidden; + } + + // Show elements before animating them + if ( hidden ) { + showHide( [ elem ], true ); + } + + /* eslint-disable no-loop-func */ + + anim.done( function() { + + /* eslint-enable no-loop-func */ + + // The final step of a "hide" animation is actually hiding the element + if ( !hidden ) { + showHide( [ elem ] ); + } + dataPriv.remove( elem, "fxshow" ); + for ( prop in orig ) { + jQuery.style( elem, prop, orig[ prop ] ); + } + } ); + } + + // Per-property setup + propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); + if ( !( prop in dataShow ) ) { + dataShow[ prop ] = propTween.start; + if ( hidden ) { + propTween.end = propTween.start; + propTween.start = 0; + } + } + } +} + +function propFilter( props, specialEasing ) { + var index, name, easing, value, hooks; + + // camelCase, specialEasing and expand cssHook pass + for ( index in props ) { + name = camelCase( index ); + easing = specialEasing[ name ]; + value = props[ index ]; + if ( Array.isArray( value ) ) { + easing = value[ 1 ]; + value = props[ index ] = value[ 0 ]; + } + + if ( index !== name ) { + props[ name ] = value; + delete props[ index ]; + } + + hooks = jQuery.cssHooks[ name ]; + if ( hooks && "expand" in hooks ) { + value = hooks.expand( value ); + delete props[ name ]; + + // Not quite $.extend, this won't overwrite existing keys. + // Reusing 'index' because we have the correct "name" + for ( index in value ) { + if ( !( index in props ) ) { + props[ index ] = value[ index ]; + specialEasing[ index ] = easing; + } + } + } else { + specialEasing[ name ] = easing; + } + } +} + +function Animation( elem, properties, options ) { + var result, + stopped, + index = 0, + length = Animation.prefilters.length, + deferred = jQuery.Deferred().always( function() { + + // Don't match elem in the :animated selector + delete tick.elem; + } ), + tick = function() { + if ( stopped ) { + return false; + } + var currentTime = fxNow || createFxNow(), + remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), + + // Support: Android 2.3 only + // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) + temp = remaining / animation.duration || 0, + percent = 1 - temp, + index = 0, + length = animation.tweens.length; + + for ( ; index < length; index++ ) { + animation.tweens[ index ].run( percent ); + } + + deferred.notifyWith( elem, [ animation, percent, remaining ] ); + + // If there's more to do, yield + if ( percent < 1 && length ) { + return remaining; + } + + // If this was an empty animation, synthesize a final progress notification + if ( !length ) { + deferred.notifyWith( elem, [ animation, 1, 0 ] ); + } + + // Resolve the animation and report its conclusion + deferred.resolveWith( elem, [ animation ] ); + return false; + }, + animation = deferred.promise( { + elem: elem, + props: jQuery.extend( {}, properties ), + opts: jQuery.extend( true, { + specialEasing: {}, + easing: jQuery.easing._default + }, options ), + originalProperties: properties, + originalOptions: options, + startTime: fxNow || createFxNow(), + duration: options.duration, + tweens: [], + createTween: function( prop, end ) { + var tween = jQuery.Tween( elem, animation.opts, prop, end, + animation.opts.specialEasing[ prop ] || animation.opts.easing ); + animation.tweens.push( tween ); + return tween; + }, + stop: function( gotoEnd ) { + var index = 0, + + // If we are going to the end, we want to run all the tweens + // otherwise we skip this part + length = gotoEnd ? animation.tweens.length : 0; + if ( stopped ) { + return this; + } + stopped = true; + for ( ; index < length; index++ ) { + animation.tweens[ index ].run( 1 ); + } + + // Resolve when we played the last frame; otherwise, reject + if ( gotoEnd ) { + deferred.notifyWith( elem, [ animation, 1, 0 ] ); + deferred.resolveWith( elem, [ animation, gotoEnd ] ); + } else { + deferred.rejectWith( elem, [ animation, gotoEnd ] ); + } + return this; + } + } ), + props = animation.props; + + propFilter( props, animation.opts.specialEasing ); + + for ( ; index < length; index++ ) { + result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); + if ( result ) { + if ( isFunction( result.stop ) ) { + jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = + result.stop.bind( result ); + } + return result; + } + } + + jQuery.map( props, createTween, animation ); + + if ( isFunction( animation.opts.start ) ) { + animation.opts.start.call( elem, animation ); + } + + // Attach callbacks from options + animation + .progress( animation.opts.progress ) + .done( animation.opts.done, animation.opts.complete ) + .fail( animation.opts.fail ) + .always( animation.opts.always ); + + jQuery.fx.timer( + jQuery.extend( tick, { + elem: elem, + anim: animation, + queue: animation.opts.queue + } ) + ); + + return animation; +} + +jQuery.Animation = jQuery.extend( Animation, { + + tweeners: { + "*": [ function( prop, value ) { + var tween = this.createTween( prop, value ); + adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); + return tween; + } ] + }, + + tweener: function( props, callback ) { + if ( isFunction( props ) ) { + callback = props; + props = [ "*" ]; + } else { + props = props.match( rnothtmlwhite ); + } + + var prop, + index = 0, + length = props.length; + + for ( ; index < length; index++ ) { + prop = props[ index ]; + Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; + Animation.tweeners[ prop ].unshift( callback ); + } + }, + + prefilters: [ defaultPrefilter ], + + prefilter: function( callback, prepend ) { + if ( prepend ) { + Animation.prefilters.unshift( callback ); + } else { + Animation.prefilters.push( callback ); + } + } +} ); + +jQuery.speed = function( speed, easing, fn ) { + var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { + complete: fn || !fn && easing || + isFunction( speed ) && speed, + duration: speed, + easing: fn && easing || easing && !isFunction( easing ) && easing + }; + + // Go to the end state if fx are off + if ( jQuery.fx.off ) { + opt.duration = 0; + + } else { + if ( typeof opt.duration !== "number" ) { + if ( opt.duration in jQuery.fx.speeds ) { + opt.duration = jQuery.fx.speeds[ opt.duration ]; + + } else { + opt.duration = jQuery.fx.speeds._default; + } + } + } + + // Normalize opt.queue - true/undefined/null -> "fx" + if ( opt.queue == null || opt.queue === true ) { + opt.queue = "fx"; + } + + // Queueing + opt.old = opt.complete; + + opt.complete = function() { + if ( isFunction( opt.old ) ) { + opt.old.call( this ); + } + + if ( opt.queue ) { + jQuery.dequeue( this, opt.queue ); + } + }; + + return opt; +}; + +jQuery.fn.extend( { + fadeTo: function( speed, to, easing, callback ) { + + // Show any hidden elements after setting opacity to 0 + return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show() + + // Animate to the value specified + .end().animate( { opacity: to }, speed, easing, callback ); + }, + animate: function( prop, speed, easing, callback ) { + var empty = jQuery.isEmptyObject( prop ), + optall = jQuery.speed( speed, easing, callback ), + doAnimation = function() { + + // Operate on a copy of prop so per-property easing won't be lost + var anim = Animation( this, jQuery.extend( {}, prop ), optall ); + + // Empty animations, or finishing resolves immediately + if ( empty || dataPriv.get( this, "finish" ) ) { + anim.stop( true ); + } + }; + doAnimation.finish = doAnimation; + + return empty || optall.queue === false ? + this.each( doAnimation ) : + this.queue( optall.queue, doAnimation ); + }, + stop: function( type, clearQueue, gotoEnd ) { + var stopQueue = function( hooks ) { + var stop = hooks.stop; + delete hooks.stop; + stop( gotoEnd ); + }; + + if ( typeof type !== "string" ) { + gotoEnd = clearQueue; + clearQueue = type; + type = undefined; + } + if ( clearQueue ) { + this.queue( type || "fx", [] ); + } + + return this.each( function() { + var dequeue = true, + index = type != null && type + "queueHooks", + timers = jQuery.timers, + data = dataPriv.get( this ); + + if ( index ) { + if ( data[ index ] && data[ index ].stop ) { + stopQueue( data[ index ] ); + } + } else { + for ( index in data ) { + if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { + stopQueue( data[ index ] ); + } + } + } + + for ( index = timers.length; index--; ) { + if ( timers[ index ].elem === this && + ( type == null || timers[ index ].queue === type ) ) { + + timers[ index ].anim.stop( gotoEnd ); + dequeue = false; + timers.splice( index, 1 ); + } + } + + // Start the next in the queue if the last step wasn't forced. + // Timers currently will call their complete callbacks, which + // will dequeue but only if they were gotoEnd. + if ( dequeue || !gotoEnd ) { + jQuery.dequeue( this, type ); + } + } ); + }, + finish: function( type ) { + if ( type !== false ) { + type = type || "fx"; + } + return this.each( function() { + var index, + data = dataPriv.get( this ), + queue = data[ type + "queue" ], + hooks = data[ type + "queueHooks" ], + timers = jQuery.timers, + length = queue ? queue.length : 0; + + // Enable finishing flag on private data + data.finish = true; + + // Empty the queue first + jQuery.queue( this, type, [] ); + + if ( hooks && hooks.stop ) { + hooks.stop.call( this, true ); + } + + // Look for any active animations, and finish them + for ( index = timers.length; index--; ) { + if ( timers[ index ].elem === this && timers[ index ].queue === type ) { + timers[ index ].anim.stop( true ); + timers.splice( index, 1 ); + } + } + + // Look for any animations in the old queue and finish them + for ( index = 0; index < length; index++ ) { + if ( queue[ index ] && queue[ index ].finish ) { + queue[ index ].finish.call( this ); + } + } + + // Turn off finishing flag + delete data.finish; + } ); + } +} ); + +jQuery.each( [ "toggle", "show", "hide" ], function( _i, name ) { + var cssFn = jQuery.fn[ name ]; + jQuery.fn[ name ] = function( speed, easing, callback ) { + return speed == null || typeof speed === "boolean" ? + cssFn.apply( this, arguments ) : + this.animate( genFx( name, true ), speed, easing, callback ); + }; +} ); + +// Generate shortcuts for custom animations +jQuery.each( { + slideDown: genFx( "show" ), + slideUp: genFx( "hide" ), + slideToggle: genFx( "toggle" ), + fadeIn: { opacity: "show" }, + fadeOut: { opacity: "hide" }, + fadeToggle: { opacity: "toggle" } +}, function( name, props ) { + jQuery.fn[ name ] = function( speed, easing, callback ) { + return this.animate( props, speed, easing, callback ); + }; +} ); + +jQuery.timers = []; +jQuery.fx.tick = function() { + var timer, + i = 0, + timers = jQuery.timers; + + fxNow = Date.now(); + + for ( ; i < timers.length; i++ ) { + timer = timers[ i ]; + + // Run the timer and safely remove it when done (allowing for external removal) + if ( !timer() && timers[ i ] === timer ) { + timers.splice( i--, 1 ); + } + } + + if ( !timers.length ) { + jQuery.fx.stop(); + } + fxNow = undefined; +}; + +jQuery.fx.timer = function( timer ) { + jQuery.timers.push( timer ); + jQuery.fx.start(); +}; + +jQuery.fx.interval = 13; +jQuery.fx.start = function() { + if ( inProgress ) { + return; + } + + inProgress = true; + schedule(); +}; + +jQuery.fx.stop = function() { + inProgress = null; +}; + +jQuery.fx.speeds = { + slow: 600, + fast: 200, + + // Default speed + _default: 400 +}; + + +// Based off of the plugin by Clint Helfers, with permission. +// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/ +jQuery.fn.delay = function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; + type = type || "fx"; + + return this.queue( type, function( next, hooks ) { + var timeout = window.setTimeout( next, time ); + hooks.stop = function() { + window.clearTimeout( timeout ); + }; + } ); +}; + + +( function() { + var input = document.createElement( "input" ), + select = document.createElement( "select" ), + opt = select.appendChild( document.createElement( "option" ) ); + + input.type = "checkbox"; + + // Support: Android <=4.3 only + // Default value for a checkbox should be "on" + support.checkOn = input.value !== ""; + + // Support: IE <=11 only + // Must access selectedIndex to make default options select + support.optSelected = opt.selected; + + // Support: IE <=11 only + // An input loses its value after becoming a radio + input = document.createElement( "input" ); + input.value = "t"; + input.type = "radio"; + support.radioValue = input.value === "t"; +} )(); + + +var boolHook, + attrHandle = jQuery.expr.attrHandle; + +jQuery.fn.extend( { + attr: function( name, value ) { + return access( this, jQuery.attr, name, value, arguments.length > 1 ); + }, + + removeAttr: function( name ) { + return this.each( function() { + jQuery.removeAttr( this, name ); + } ); + } +} ); + +jQuery.extend( { + attr: function( elem, name, value ) { + var ret, hooks, + nType = elem.nodeType; + + // Don't get/set attributes on text, comment and attribute nodes + if ( nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === "undefined" ) { + return jQuery.prop( elem, name, value ); + } + + // Attribute hooks are determined by the lowercase version + // Grab necessary hook if one is defined + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + hooks = jQuery.attrHooks[ name.toLowerCase() ] || + ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); + } + + if ( value !== undefined ) { + if ( value === null ) { + jQuery.removeAttr( elem, name ); + return; + } + + if ( hooks && "set" in hooks && + ( ret = hooks.set( elem, value, name ) ) !== undefined ) { + return ret; + } + + elem.setAttribute( name, value + "" ); + return value; + } + + if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { + return ret; + } + + ret = jQuery.find.attr( elem, name ); + + // Non-existent attributes return null, we normalize to undefined + return ret == null ? undefined : ret; + }, + + attrHooks: { + type: { + set: function( elem, value ) { + if ( !support.radioValue && value === "radio" && + nodeName( elem, "input" ) ) { + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + } + }, + + removeAttr: function( elem, value ) { + var name, + i = 0, + + // Attribute names can contain non-HTML whitespace characters + // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 + attrNames = value && value.match( rnothtmlwhite ); + + if ( attrNames && elem.nodeType === 1 ) { + while ( ( name = attrNames[ i++ ] ) ) { + elem.removeAttribute( name ); + } + } + } +} ); + +// Hooks for boolean attributes +boolHook = { + set: function( elem, value, name ) { + if ( value === false ) { + + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else { + elem.setAttribute( name, name ); + } + return name; + } +}; + +jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( _i, name ) { + var getter = attrHandle[ name ] || jQuery.find.attr; + + attrHandle[ name ] = function( elem, name, isXML ) { + var ret, handle, + lowercaseName = name.toLowerCase(); + + if ( !isXML ) { + + // Avoid an infinite loop by temporarily removing this function from the getter + handle = attrHandle[ lowercaseName ]; + attrHandle[ lowercaseName ] = ret; + ret = getter( elem, name, isXML ) != null ? + lowercaseName : + null; + attrHandle[ lowercaseName ] = handle; + } + return ret; + }; +} ); + + + + +var rfocusable = /^(?:input|select|textarea|button)$/i, + rclickable = /^(?:a|area)$/i; + +jQuery.fn.extend( { + prop: function( name, value ) { + return access( this, jQuery.prop, name, value, arguments.length > 1 ); + }, + + removeProp: function( name ) { + return this.each( function() { + delete this[ jQuery.propFix[ name ] || name ]; + } ); + } +} ); + +jQuery.extend( { + prop: function( elem, name, value ) { + var ret, hooks, + nType = elem.nodeType; + + // Don't get/set properties on text, comment and attribute nodes + if ( nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + if ( hooks && "set" in hooks && + ( ret = hooks.set( elem, value, name ) ) !== undefined ) { + return ret; + } + + return ( elem[ name ] = value ); + } + + if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { + return ret; + } + + return elem[ name ]; + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + + // Support: IE <=9 - 11 only + // elem.tabIndex doesn't always return the + // correct value when it hasn't been explicitly set + // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + // Use proper attribute retrieval(#12072) + var tabindex = jQuery.find.attr( elem, "tabindex" ); + + if ( tabindex ) { + return parseInt( tabindex, 10 ); + } + + if ( + rfocusable.test( elem.nodeName ) || + rclickable.test( elem.nodeName ) && + elem.href + ) { + return 0; + } + + return -1; + } + } + }, + + propFix: { + "for": "htmlFor", + "class": "className" + } +} ); + +// Support: IE <=11 only +// Accessing the selectedIndex property +// forces the browser to respect setting selected +// on the option +// The getter ensures a default option is selected +// when in an optgroup +// eslint rule "no-unused-expressions" is disabled for this code +// since it considers such accessions noop +if ( !support.optSelected ) { + jQuery.propHooks.selected = { + get: function( elem ) { + + /* eslint no-unused-expressions: "off" */ + + var parent = elem.parentNode; + if ( parent && parent.parentNode ) { + parent.parentNode.selectedIndex; + } + return null; + }, + set: function( elem ) { + + /* eslint no-unused-expressions: "off" */ + + var parent = elem.parentNode; + if ( parent ) { + parent.selectedIndex; + + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + } + }; +} + +jQuery.each( [ + "tabIndex", + "readOnly", + "maxLength", + "cellSpacing", + "cellPadding", + "rowSpan", + "colSpan", + "useMap", + "frameBorder", + "contentEditable" +], function() { + jQuery.propFix[ this.toLowerCase() ] = this; +} ); + + + + + // Strip and collapse whitespace according to HTML spec + // https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace + function stripAndCollapse( value ) { + var tokens = value.match( rnothtmlwhite ) || []; + return tokens.join( " " ); + } + + +function getClass( elem ) { + return elem.getAttribute && elem.getAttribute( "class" ) || ""; +} + +function classesToArray( value ) { + if ( Array.isArray( value ) ) { + return value; + } + if ( typeof value === "string" ) { + return value.match( rnothtmlwhite ) || []; + } + return []; +} + +jQuery.fn.extend( { + addClass: function( value ) { + var classes, elem, cur, curValue, clazz, j, finalValue, + i = 0; + + if ( isFunction( value ) ) { + return this.each( function( j ) { + jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); + } ); + } + + classes = classesToArray( value ); + + if ( classes.length ) { + while ( ( elem = this[ i++ ] ) ) { + curValue = getClass( elem ); + cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); + + if ( cur ) { + j = 0; + while ( ( clazz = classes[ j++ ] ) ) { + if ( cur.indexOf( " " + clazz + " " ) < 0 ) { + cur += clazz + " "; + } + } + + // Only assign if different to avoid unneeded rendering. + finalValue = stripAndCollapse( cur ); + if ( curValue !== finalValue ) { + elem.setAttribute( "class", finalValue ); + } + } + } + } + + return this; + }, + + removeClass: function( value ) { + var classes, elem, cur, curValue, clazz, j, finalValue, + i = 0; + + if ( isFunction( value ) ) { + return this.each( function( j ) { + jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); + } ); + } + + if ( !arguments.length ) { + return this.attr( "class", "" ); + } + + classes = classesToArray( value ); + + if ( classes.length ) { + while ( ( elem = this[ i++ ] ) ) { + curValue = getClass( elem ); + + // This expression is here for better compressibility (see addClass) + cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); + + if ( cur ) { + j = 0; + while ( ( clazz = classes[ j++ ] ) ) { + + // Remove *all* instances + while ( cur.indexOf( " " + clazz + " " ) > -1 ) { + cur = cur.replace( " " + clazz + " ", " " ); + } + } + + // Only assign if different to avoid unneeded rendering. + finalValue = stripAndCollapse( cur ); + if ( curValue !== finalValue ) { + elem.setAttribute( "class", finalValue ); + } + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value, + isValidValue = type === "string" || Array.isArray( value ); + + if ( typeof stateVal === "boolean" && isValidValue ) { + return stateVal ? this.addClass( value ) : this.removeClass( value ); + } + + if ( isFunction( value ) ) { + return this.each( function( i ) { + jQuery( this ).toggleClass( + value.call( this, i, getClass( this ), stateVal ), + stateVal + ); + } ); + } + + return this.each( function() { + var className, i, self, classNames; + + if ( isValidValue ) { + + // Toggle individual class names + i = 0; + self = jQuery( this ); + classNames = classesToArray( value ); + + while ( ( className = classNames[ i++ ] ) ) { + + // Check each className given, space separated list + if ( self.hasClass( className ) ) { + self.removeClass( className ); + } else { + self.addClass( className ); + } + } + + // Toggle whole class name + } else if ( value === undefined || type === "boolean" ) { + className = getClass( this ); + if ( className ) { + + // Store className if set + dataPriv.set( this, "__className__", className ); + } + + // If the element has a class name or if we're passed `false`, + // then remove the whole classname (if there was one, the above saved it). + // Otherwise bring back whatever was previously saved (if anything), + // falling back to the empty string if nothing was stored. + if ( this.setAttribute ) { + this.setAttribute( "class", + className || value === false ? + "" : + dataPriv.get( this, "__className__" ) || "" + ); + } + } + } ); + }, + + hasClass: function( selector ) { + var className, elem, + i = 0; + + className = " " + selector + " "; + while ( ( elem = this[ i++ ] ) ) { + if ( elem.nodeType === 1 && + ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) { + return true; + } + } + + return false; + } +} ); + + + + +var rreturn = /\r/g; + +jQuery.fn.extend( { + val: function( value ) { + var hooks, ret, valueIsFunction, + elem = this[ 0 ]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.type ] || + jQuery.valHooks[ elem.nodeName.toLowerCase() ]; + + if ( hooks && + "get" in hooks && + ( ret = hooks.get( elem, "value" ) ) !== undefined + ) { + return ret; + } + + ret = elem.value; + + // Handle most common string cases + if ( typeof ret === "string" ) { + return ret.replace( rreturn, "" ); + } + + // Handle cases where value is null/undef or number + return ret == null ? "" : ret; + } + + return; + } + + valueIsFunction = isFunction( value ); + + return this.each( function( i ) { + var val; + + if ( this.nodeType !== 1 ) { + return; + } + + if ( valueIsFunction ) { + val = value.call( this, i, jQuery( this ).val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + + } else if ( typeof val === "number" ) { + val += ""; + + } else if ( Array.isArray( val ) ) { + val = jQuery.map( val, function( value ) { + return value == null ? "" : value + ""; + } ); + } + + hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + } ); + } +} ); + +jQuery.extend( { + valHooks: { + option: { + get: function( elem ) { + + var val = jQuery.find.attr( elem, "value" ); + return val != null ? + val : + + // Support: IE <=10 - 11 only + // option.text throws exceptions (#14686, #14858) + // Strip and collapse whitespace + // https://html.spec.whatwg.org/#strip-and-collapse-whitespace + stripAndCollapse( jQuery.text( elem ) ); + } + }, + select: { + get: function( elem ) { + var value, option, i, + options = elem.options, + index = elem.selectedIndex, + one = elem.type === "select-one", + values = one ? null : [], + max = one ? index + 1 : options.length; + + if ( index < 0 ) { + i = max; + + } else { + i = one ? index : 0; + } + + // Loop through all the selected options + for ( ; i < max; i++ ) { + option = options[ i ]; + + // Support: IE <=9 only + // IE8-9 doesn't update selected after form reset (#2551) + if ( ( option.selected || i === index ) && + + // Don't return options that are disabled or in a disabled optgroup + !option.disabled && + ( !option.parentNode.disabled || + !nodeName( option.parentNode, "optgroup" ) ) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + return values; + }, + + set: function( elem, value ) { + var optionSet, option, + options = elem.options, + values = jQuery.makeArray( value ), + i = options.length; + + while ( i-- ) { + option = options[ i ]; + + /* eslint-disable no-cond-assign */ + + if ( option.selected = + jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 + ) { + optionSet = true; + } + + /* eslint-enable no-cond-assign */ + } + + // Force browsers to behave consistently when non-matching value is set + if ( !optionSet ) { + elem.selectedIndex = -1; + } + return values; + } + } + } +} ); + +// Radios and checkboxes getter/setter +jQuery.each( [ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + set: function( elem, value ) { + if ( Array.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); + } + } + }; + if ( !support.checkOn ) { + jQuery.valHooks[ this ].get = function( elem ) { + return elem.getAttribute( "value" ) === null ? "on" : elem.value; + }; + } +} ); + + + + +// Return jQuery for attributes-only inclusion + + +support.focusin = "onfocusin" in window; + + +var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + stopPropagationCallback = function( e ) { + e.stopPropagation(); + }; + +jQuery.extend( jQuery.event, { + + trigger: function( event, data, elem, onlyHandlers ) { + + var i, cur, tmp, bubbleType, ontype, handle, special, lastElement, + eventPath = [ elem || document ], + type = hasOwn.call( event, "type" ) ? event.type : event, + namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; + + cur = lastElement = tmp = elem = elem || document; + + // Don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf( "." ) > -1 ) { + + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split( "." ); + type = namespaces.shift(); + namespaces.sort(); + } + ontype = type.indexOf( ":" ) < 0 && "on" + type; + + // Caller can pass in a jQuery.Event object, Object, or just an event type string + event = event[ jQuery.expando ] ? + event : + new jQuery.Event( type, typeof event === "object" && event ); + + // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) + event.isTrigger = onlyHandlers ? 2 : 3; + event.namespace = namespaces.join( "." ); + event.rnamespace = event.namespace ? + new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : + null; + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data == null ? + [ event ] : + jQuery.makeArray( data, [ event ] ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + if ( !onlyHandlers && !special.noBubble && !isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + if ( !rfocusMorph.test( bubbleType + type ) ) { + cur = cur.parentNode; + } + for ( ; cur; cur = cur.parentNode ) { + eventPath.push( cur ); + tmp = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( tmp === ( elem.ownerDocument || document ) ) { + eventPath.push( tmp.defaultView || tmp.parentWindow || window ); + } + } + + // Fire handlers on the event path + i = 0; + while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { + lastElement = cur; + event.type = i > 1 ? + bubbleType : + special.bindType || type; + + // jQuery handler + handle = ( + dataPriv.get( cur, "events" ) || Object.create( null ) + )[ event.type ] && + dataPriv.get( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + + // Native handler + handle = ontype && cur[ ontype ]; + if ( handle && handle.apply && acceptData( cur ) ) { + event.result = handle.apply( cur, data ); + if ( event.result === false ) { + event.preventDefault(); + } + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( ( !special._default || + special._default.apply( eventPath.pop(), data ) === false ) && + acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name as the event. + // Don't do default actions on window, that's where global variables be (#6170) + if ( ontype && isFunction( elem[ type ] ) && !isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + tmp = elem[ ontype ]; + + if ( tmp ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + + if ( event.isPropagationStopped() ) { + lastElement.addEventListener( type, stopPropagationCallback ); + } + + elem[ type ](); + + if ( event.isPropagationStopped() ) { + lastElement.removeEventListener( type, stopPropagationCallback ); + } + + jQuery.event.triggered = undefined; + + if ( tmp ) { + elem[ ontype ] = tmp; + } + } + } + } + + return event.result; + }, + + // Piggyback on a donor event to simulate a different one + // Used only for `focus(in | out)` events + simulate: function( type, elem, event ) { + var e = jQuery.extend( + new jQuery.Event(), + event, + { + type: type, + isSimulated: true + } + ); + + jQuery.event.trigger( e, null, elem ); + } + +} ); + +jQuery.fn.extend( { + + trigger: function( type, data ) { + return this.each( function() { + jQuery.event.trigger( type, data, this ); + } ); + }, + triggerHandler: function( type, data ) { + var elem = this[ 0 ]; + if ( elem ) { + return jQuery.event.trigger( type, data, elem, true ); + } + } +} ); + + +// Support: Firefox <=44 +// Firefox doesn't have focus(in | out) events +// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 +// +// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 +// focus(in | out) events fire after focus & blur events, +// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order +// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 +if ( !support.focusin ) { + jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler on the document while someone wants focusin/focusout + var handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + + // Handle: regular nodes (via `this.ownerDocument`), window + // (via `this.document`) & document (via `this`). + var doc = this.ownerDocument || this.document || this, + attaches = dataPriv.access( doc, fix ); + + if ( !attaches ) { + doc.addEventListener( orig, handler, true ); + } + dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); + }, + teardown: function() { + var doc = this.ownerDocument || this.document || this, + attaches = dataPriv.access( doc, fix ) - 1; + + if ( !attaches ) { + doc.removeEventListener( orig, handler, true ); + dataPriv.remove( doc, fix ); + + } else { + dataPriv.access( doc, fix, attaches ); + } + } + }; + } ); +} +var location = window.location; + +var nonce = { guid: Date.now() }; + +var rquery = ( /\?/ ); + + + +// Cross-browser xml parsing +jQuery.parseXML = function( data ) { + var xml; + if ( !data || typeof data !== "string" ) { + return null; + } + + // Support: IE 9 - 11 only + // IE throws on parseFromString with invalid input. + try { + xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); + } catch ( e ) { + xml = undefined; + } + + if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { + jQuery.error( "Invalid XML: " + data ); + } + return xml; +}; + + +var + rbracket = /\[\]$/, + rCRLF = /\r?\n/g, + rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, + rsubmittable = /^(?:input|select|textarea|keygen)/i; + +function buildParams( prefix, obj, traditional, add ) { + var name; + + if ( Array.isArray( obj ) ) { + + // Serialize array item. + jQuery.each( obj, function( i, v ) { + if ( traditional || rbracket.test( prefix ) ) { + + // Treat each array item as a scalar. + add( prefix, v ); + + } else { + + // Item is non-scalar (array or object), encode its numeric index. + buildParams( + prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", + v, + traditional, + add + ); + } + } ); + + } else if ( !traditional && toType( obj ) === "object" ) { + + // Serialize object item. + for ( name in obj ) { + buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); + } + + } else { + + // Serialize scalar item. + add( prefix, obj ); + } +} + +// Serialize an array of form elements or a set of +// key/values into a query string +jQuery.param = function( a, traditional ) { + var prefix, + s = [], + add = function( key, valueOrFunction ) { + + // If value is a function, invoke it and use its return value + var value = isFunction( valueOrFunction ) ? + valueOrFunction() : + valueOrFunction; + + s[ s.length ] = encodeURIComponent( key ) + "=" + + encodeURIComponent( value == null ? "" : value ); + }; + + if ( a == null ) { + return ""; + } + + // If an array was passed in, assume that it is an array of form elements. + if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { + + // Serialize the form elements + jQuery.each( a, function() { + add( this.name, this.value ); + } ); + + } else { + + // If traditional, encode the "old" way (the way 1.3.2 or older + // did it), otherwise encode params recursively. + for ( prefix in a ) { + buildParams( prefix, a[ prefix ], traditional, add ); + } + } + + // Return the resulting serialization + return s.join( "&" ); +}; + +jQuery.fn.extend( { + serialize: function() { + return jQuery.param( this.serializeArray() ); + }, + serializeArray: function() { + return this.map( function() { + + // Can add propHook for "elements" to filter or add form elements + var elements = jQuery.prop( this, "elements" ); + return elements ? jQuery.makeArray( elements ) : this; + } ) + .filter( function() { + var type = this.type; + + // Use .is( ":disabled" ) so that fieldset[disabled] works + return this.name && !jQuery( this ).is( ":disabled" ) && + rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && + ( this.checked || !rcheckableType.test( type ) ); + } ) + .map( function( _i, elem ) { + var val = jQuery( this ).val(); + + if ( val == null ) { + return null; + } + + if ( Array.isArray( val ) ) { + return jQuery.map( val, function( val ) { + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + } ); + } + + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + } ).get(); + } +} ); + + +var + r20 = /%20/g, + rhash = /#.*$/, + rantiCache = /([?&])_=[^&]*/, + rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, + + // #7653, #8125, #8152: local protocol detection + rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, + rnoContent = /^(?:GET|HEAD)$/, + rprotocol = /^\/\//, + + /* Prefilters + * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) + * 2) These are called: + * - BEFORE asking for a transport + * - AFTER param serialization (s.data is a string if s.processData is true) + * 3) key is the dataType + * 4) the catchall symbol "*" can be used + * 5) execution will start with transport dataType and THEN continue down to "*" if needed + */ + prefilters = {}, + + /* Transports bindings + * 1) key is the dataType + * 2) the catchall symbol "*" can be used + * 3) selection will start with transport dataType and THEN go to "*" if needed + */ + transports = {}, + + // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression + allTypes = "*/".concat( "*" ), + + // Anchor tag for parsing the document origin + originAnchor = document.createElement( "a" ); + originAnchor.href = location.href; + +// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport +function addToPrefiltersOrTransports( structure ) { + + // dataTypeExpression is optional and defaults to "*" + return function( dataTypeExpression, func ) { + + if ( typeof dataTypeExpression !== "string" ) { + func = dataTypeExpression; + dataTypeExpression = "*"; + } + + var dataType, + i = 0, + dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || []; + + if ( isFunction( func ) ) { + + // For each dataType in the dataTypeExpression + while ( ( dataType = dataTypes[ i++ ] ) ) { + + // Prepend if requested + if ( dataType[ 0 ] === "+" ) { + dataType = dataType.slice( 1 ) || "*"; + ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); + + // Otherwise append + } else { + ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); + } + } + } + }; +} + +// Base inspection function for prefilters and transports +function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { + + var inspected = {}, + seekingTransport = ( structure === transports ); + + function inspect( dataType ) { + var selected; + inspected[ dataType ] = true; + jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { + var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); + if ( typeof dataTypeOrTransport === "string" && + !seekingTransport && !inspected[ dataTypeOrTransport ] ) { + + options.dataTypes.unshift( dataTypeOrTransport ); + inspect( dataTypeOrTransport ); + return false; + } else if ( seekingTransport ) { + return !( selected = dataTypeOrTransport ); + } + } ); + return selected; + } + + return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); +} + +// A special extend for ajax options +// that takes "flat" options (not to be deep extended) +// Fixes #9887 +function ajaxExtend( target, src ) { + var key, deep, + flatOptions = jQuery.ajaxSettings.flatOptions || {}; + + for ( key in src ) { + if ( src[ key ] !== undefined ) { + ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; + } + } + if ( deep ) { + jQuery.extend( true, target, deep ); + } + + return target; +} + +/* Handles responses to an ajax request: + * - finds the right dataType (mediates between content-type and expected dataType) + * - returns the corresponding response + */ +function ajaxHandleResponses( s, jqXHR, responses ) { + + var ct, type, finalDataType, firstDataType, + contents = s.contents, + dataTypes = s.dataTypes; + + // Remove auto dataType and get content-type in the process + while ( dataTypes[ 0 ] === "*" ) { + dataTypes.shift(); + if ( ct === undefined ) { + ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); + } + } + + // Check if we're dealing with a known content-type + if ( ct ) { + for ( type in contents ) { + if ( contents[ type ] && contents[ type ].test( ct ) ) { + dataTypes.unshift( type ); + break; + } + } + } + + // Check to see if we have a response for the expected dataType + if ( dataTypes[ 0 ] in responses ) { + finalDataType = dataTypes[ 0 ]; + } else { + + // Try convertible dataTypes + for ( type in responses ) { + if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { + finalDataType = type; + break; + } + if ( !firstDataType ) { + firstDataType = type; + } + } + + // Or just use first one + finalDataType = finalDataType || firstDataType; + } + + // If we found a dataType + // We add the dataType to the list if needed + // and return the corresponding response + if ( finalDataType ) { + if ( finalDataType !== dataTypes[ 0 ] ) { + dataTypes.unshift( finalDataType ); + } + return responses[ finalDataType ]; + } +} + +/* Chain conversions given the request and the original response + * Also sets the responseXXX fields on the jqXHR instance + */ +function ajaxConvert( s, response, jqXHR, isSuccess ) { + var conv2, current, conv, tmp, prev, + converters = {}, + + // Work with a copy of dataTypes in case we need to modify it for conversion + dataTypes = s.dataTypes.slice(); + + // Create converters map with lowercased keys + if ( dataTypes[ 1 ] ) { + for ( conv in s.converters ) { + converters[ conv.toLowerCase() ] = s.converters[ conv ]; + } + } + + current = dataTypes.shift(); + + // Convert to each sequential dataType + while ( current ) { + + if ( s.responseFields[ current ] ) { + jqXHR[ s.responseFields[ current ] ] = response; + } + + // Apply the dataFilter if provided + if ( !prev && isSuccess && s.dataFilter ) { + response = s.dataFilter( response, s.dataType ); + } + + prev = current; + current = dataTypes.shift(); + + if ( current ) { + + // There's only work to do if current dataType is non-auto + if ( current === "*" ) { + + current = prev; + + // Convert response if prev dataType is non-auto and differs from current + } else if ( prev !== "*" && prev !== current ) { + + // Seek a direct converter + conv = converters[ prev + " " + current ] || converters[ "* " + current ]; + + // If none found, seek a pair + if ( !conv ) { + for ( conv2 in converters ) { + + // If conv2 outputs current + tmp = conv2.split( " " ); + if ( tmp[ 1 ] === current ) { + + // If prev can be converted to accepted input + conv = converters[ prev + " " + tmp[ 0 ] ] || + converters[ "* " + tmp[ 0 ] ]; + if ( conv ) { + + // Condense equivalence converters + if ( conv === true ) { + conv = converters[ conv2 ]; + + // Otherwise, insert the intermediate dataType + } else if ( converters[ conv2 ] !== true ) { + current = tmp[ 0 ]; + dataTypes.unshift( tmp[ 1 ] ); + } + break; + } + } + } + } + + // Apply converter (if not an equivalence) + if ( conv !== true ) { + + // Unless errors are allowed to bubble, catch and return them + if ( conv && s.throws ) { + response = conv( response ); + } else { + try { + response = conv( response ); + } catch ( e ) { + return { + state: "parsererror", + error: conv ? e : "No conversion from " + prev + " to " + current + }; + } + } + } + } + } + } + + return { state: "success", data: response }; +} + +jQuery.extend( { + + // Counter for holding the number of active queries + active: 0, + + // Last-Modified header cache for next request + lastModified: {}, + etag: {}, + + ajaxSettings: { + url: location.href, + type: "GET", + isLocal: rlocalProtocol.test( location.protocol ), + global: true, + processData: true, + async: true, + contentType: "application/x-www-form-urlencoded; charset=UTF-8", + + /* + timeout: 0, + data: null, + dataType: null, + username: null, + password: null, + cache: null, + throws: false, + traditional: false, + headers: {}, + */ + + accepts: { + "*": allTypes, + text: "text/plain", + html: "text/html", + xml: "application/xml, text/xml", + json: "application/json, text/javascript" + }, + + contents: { + xml: /\bxml\b/, + html: /\bhtml/, + json: /\bjson\b/ + }, + + responseFields: { + xml: "responseXML", + text: "responseText", + json: "responseJSON" + }, + + // Data converters + // Keys separate source (or catchall "*") and destination types with a single space + converters: { + + // Convert anything to text + "* text": String, + + // Text to html (true = no transformation) + "text html": true, + + // Evaluate text as a json expression + "text json": JSON.parse, + + // Parse text as xml + "text xml": jQuery.parseXML + }, + + // For options that shouldn't be deep extended: + // you can add your own custom options here if + // and when you create one that shouldn't be + // deep extended (see ajaxExtend) + flatOptions: { + url: true, + context: true + } + }, + + // Creates a full fledged settings object into target + // with both ajaxSettings and settings fields. + // If target is omitted, writes into ajaxSettings. + ajaxSetup: function( target, settings ) { + return settings ? + + // Building a settings object + ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : + + // Extending ajaxSettings + ajaxExtend( jQuery.ajaxSettings, target ); + }, + + ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), + ajaxTransport: addToPrefiltersOrTransports( transports ), + + // Main method + ajax: function( url, options ) { + + // If url is an object, simulate pre-1.5 signature + if ( typeof url === "object" ) { + options = url; + url = undefined; + } + + // Force options to be an object + options = options || {}; + + var transport, + + // URL without anti-cache param + cacheURL, + + // Response headers + responseHeadersString, + responseHeaders, + + // timeout handle + timeoutTimer, + + // Url cleanup var + urlAnchor, + + // Request state (becomes false upon send and true upon completion) + completed, + + // To know if global events are to be dispatched + fireGlobals, + + // Loop variable + i, + + // uncached part of the url + uncached, + + // Create the final options object + s = jQuery.ajaxSetup( {}, options ), + + // Callbacks context + callbackContext = s.context || s, + + // Context for global events is callbackContext if it is a DOM node or jQuery collection + globalEventContext = s.context && + ( callbackContext.nodeType || callbackContext.jquery ) ? + jQuery( callbackContext ) : + jQuery.event, + + // Deferreds + deferred = jQuery.Deferred(), + completeDeferred = jQuery.Callbacks( "once memory" ), + + // Status-dependent callbacks + statusCode = s.statusCode || {}, + + // Headers (they are sent all at once) + requestHeaders = {}, + requestHeadersNames = {}, + + // Default abort message + strAbort = "canceled", + + // Fake xhr + jqXHR = { + readyState: 0, + + // Builds headers hashtable if needed + getResponseHeader: function( key ) { + var match; + if ( completed ) { + if ( !responseHeaders ) { + responseHeaders = {}; + while ( ( match = rheaders.exec( responseHeadersString ) ) ) { + responseHeaders[ match[ 1 ].toLowerCase() + " " ] = + ( responseHeaders[ match[ 1 ].toLowerCase() + " " ] || [] ) + .concat( match[ 2 ] ); + } + } + match = responseHeaders[ key.toLowerCase() + " " ]; + } + return match == null ? null : match.join( ", " ); + }, + + // Raw string + getAllResponseHeaders: function() { + return completed ? responseHeadersString : null; + }, + + // Caches the header + setRequestHeader: function( name, value ) { + if ( completed == null ) { + name = requestHeadersNames[ name.toLowerCase() ] = + requestHeadersNames[ name.toLowerCase() ] || name; + requestHeaders[ name ] = value; + } + return this; + }, + + // Overrides response content-type header + overrideMimeType: function( type ) { + if ( completed == null ) { + s.mimeType = type; + } + return this; + }, + + // Status-dependent callbacks + statusCode: function( map ) { + var code; + if ( map ) { + if ( completed ) { + + // Execute the appropriate callbacks + jqXHR.always( map[ jqXHR.status ] ); + } else { + + // Lazy-add the new callbacks in a way that preserves old ones + for ( code in map ) { + statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; + } + } + } + return this; + }, + + // Cancel the request + abort: function( statusText ) { + var finalText = statusText || strAbort; + if ( transport ) { + transport.abort( finalText ); + } + done( 0, finalText ); + return this; + } + }; + + // Attach deferreds + deferred.promise( jqXHR ); + + // Add protocol if not provided (prefilters might expect it) + // Handle falsy url in the settings object (#10093: consistency with old signature) + // We also use the url parameter if available + s.url = ( ( url || s.url || location.href ) + "" ) + .replace( rprotocol, location.protocol + "//" ); + + // Alias method option to type as per ticket #12004 + s.type = options.method || options.type || s.method || s.type; + + // Extract dataTypes list + s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ]; + + // A cross-domain request is in order when the origin doesn't match the current origin. + if ( s.crossDomain == null ) { + urlAnchor = document.createElement( "a" ); + + // Support: IE <=8 - 11, Edge 12 - 15 + // IE throws exception on accessing the href property if url is malformed, + // e.g. http://example.com:80x/ + try { + urlAnchor.href = s.url; + + // Support: IE <=8 - 11 only + // Anchor's host property isn't correctly set when s.url is relative + urlAnchor.href = urlAnchor.href; + s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== + urlAnchor.protocol + "//" + urlAnchor.host; + } catch ( e ) { + + // If there is an error parsing the URL, assume it is crossDomain, + // it can be rejected by the transport if it is invalid + s.crossDomain = true; + } + } + + // Convert data if not already a string + if ( s.data && s.processData && typeof s.data !== "string" ) { + s.data = jQuery.param( s.data, s.traditional ); + } + + // Apply prefilters + inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); + + // If request was aborted inside a prefilter, stop there + if ( completed ) { + return jqXHR; + } + + // We can fire global events as of now if asked to + // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) + fireGlobals = jQuery.event && s.global; + + // Watch for a new set of requests + if ( fireGlobals && jQuery.active++ === 0 ) { + jQuery.event.trigger( "ajaxStart" ); + } + + // Uppercase the type + s.type = s.type.toUpperCase(); + + // Determine if request has content + s.hasContent = !rnoContent.test( s.type ); + + // Save the URL in case we're toying with the If-Modified-Since + // and/or If-None-Match header later on + // Remove hash to simplify url manipulation + cacheURL = s.url.replace( rhash, "" ); + + // More options handling for requests with no content + if ( !s.hasContent ) { + + // Remember the hash so we can put it back + uncached = s.url.slice( cacheURL.length ); + + // If data is available and should be processed, append data to url + if ( s.data && ( s.processData || typeof s.data === "string" ) ) { + cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; + + // #9682: remove data so that it's not used in an eventual retry + delete s.data; + } + + // Add or update anti-cache param if needed + if ( s.cache === false ) { + cacheURL = cacheURL.replace( rantiCache, "$1" ); + uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce.guid++ ) + + uncached; + } + + // Put hash and anti-cache on the URL that will be requested (gh-1732) + s.url = cacheURL + uncached; + + // Change '%20' to '+' if this is encoded form body content (gh-2658) + } else if ( s.data && s.processData && + ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) { + s.data = s.data.replace( r20, "+" ); + } + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + if ( jQuery.lastModified[ cacheURL ] ) { + jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); + } + if ( jQuery.etag[ cacheURL ] ) { + jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); + } + } + + // Set the correct header, if data is being sent + if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { + jqXHR.setRequestHeader( "Content-Type", s.contentType ); + } + + // Set the Accepts header for the server, depending on the dataType + jqXHR.setRequestHeader( + "Accept", + s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? + s.accepts[ s.dataTypes[ 0 ] ] + + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : + s.accepts[ "*" ] + ); + + // Check for headers option + for ( i in s.headers ) { + jqXHR.setRequestHeader( i, s.headers[ i ] ); + } + + // Allow custom headers/mimetypes and early abort + if ( s.beforeSend && + ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) { + + // Abort if not done already and return + return jqXHR.abort(); + } + + // Aborting is no longer a cancellation + strAbort = "abort"; + + // Install callbacks on deferreds + completeDeferred.add( s.complete ); + jqXHR.done( s.success ); + jqXHR.fail( s.error ); + + // Get transport + transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); + + // If no transport, we auto-abort + if ( !transport ) { + done( -1, "No Transport" ); + } else { + jqXHR.readyState = 1; + + // Send global event + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); + } + + // If request was aborted inside ajaxSend, stop there + if ( completed ) { + return jqXHR; + } + + // Timeout + if ( s.async && s.timeout > 0 ) { + timeoutTimer = window.setTimeout( function() { + jqXHR.abort( "timeout" ); + }, s.timeout ); + } + + try { + completed = false; + transport.send( requestHeaders, done ); + } catch ( e ) { + + // Rethrow post-completion exceptions + if ( completed ) { + throw e; + } + + // Propagate others as results + done( -1, e ); + } + } + + // Callback for when everything is done + function done( status, nativeStatusText, responses, headers ) { + var isSuccess, success, error, response, modified, + statusText = nativeStatusText; + + // Ignore repeat invocations + if ( completed ) { + return; + } + + completed = true; + + // Clear timeout if it exists + if ( timeoutTimer ) { + window.clearTimeout( timeoutTimer ); + } + + // Dereference transport for early garbage collection + // (no matter how long the jqXHR object will be used) + transport = undefined; + + // Cache response headers + responseHeadersString = headers || ""; + + // Set readyState + jqXHR.readyState = status > 0 ? 4 : 0; + + // Determine if successful + isSuccess = status >= 200 && status < 300 || status === 304; + + // Get response data + if ( responses ) { + response = ajaxHandleResponses( s, jqXHR, responses ); + } + + // Use a noop converter for missing script + if ( !isSuccess && jQuery.inArray( "script", s.dataTypes ) > -1 ) { + s.converters[ "text script" ] = function() {}; + } + + // Convert no matter what (that way responseXXX fields are always set) + response = ajaxConvert( s, response, jqXHR, isSuccess ); + + // If successful, handle type chaining + if ( isSuccess ) { + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + modified = jqXHR.getResponseHeader( "Last-Modified" ); + if ( modified ) { + jQuery.lastModified[ cacheURL ] = modified; + } + modified = jqXHR.getResponseHeader( "etag" ); + if ( modified ) { + jQuery.etag[ cacheURL ] = modified; + } + } + + // if no content + if ( status === 204 || s.type === "HEAD" ) { + statusText = "nocontent"; + + // if not modified + } else if ( status === 304 ) { + statusText = "notmodified"; + + // If we have data, let's convert it + } else { + statusText = response.state; + success = response.data; + error = response.error; + isSuccess = !error; + } + } else { + + // Extract error from statusText and normalize for non-aborts + error = statusText; + if ( status || !statusText ) { + statusText = "error"; + if ( status < 0 ) { + status = 0; + } + } + } + + // Set data for the fake xhr object + jqXHR.status = status; + jqXHR.statusText = ( nativeStatusText || statusText ) + ""; + + // Success/Error + if ( isSuccess ) { + deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); + } else { + deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); + } + + // Status-dependent callbacks + jqXHR.statusCode( statusCode ); + statusCode = undefined; + + if ( fireGlobals ) { + globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", + [ jqXHR, s, isSuccess ? success : error ] ); + } + + // Complete + completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); + + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); + + // Handle the global AJAX counter + if ( !( --jQuery.active ) ) { + jQuery.event.trigger( "ajaxStop" ); + } + } + } + + return jqXHR; + }, + + getJSON: function( url, data, callback ) { + return jQuery.get( url, data, callback, "json" ); + }, + + getScript: function( url, callback ) { + return jQuery.get( url, undefined, callback, "script" ); + } +} ); + +jQuery.each( [ "get", "post" ], function( _i, method ) { + jQuery[ method ] = function( url, data, callback, type ) { + + // Shift arguments if data argument was omitted + if ( isFunction( data ) ) { + type = type || callback; + callback = data; + data = undefined; + } + + // The url can be an options object (which then must have .url) + return jQuery.ajax( jQuery.extend( { + url: url, + type: method, + dataType: type, + data: data, + success: callback + }, jQuery.isPlainObject( url ) && url ) ); + }; +} ); + +jQuery.ajaxPrefilter( function( s ) { + var i; + for ( i in s.headers ) { + if ( i.toLowerCase() === "content-type" ) { + s.contentType = s.headers[ i ] || ""; + } + } +} ); + + +jQuery._evalUrl = function( url, options, doc ) { + return jQuery.ajax( { + url: url, + + // Make this explicit, since user can override this through ajaxSetup (#11264) + type: "GET", + dataType: "script", + cache: true, + async: false, + global: false, + + // Only evaluate the response if it is successful (gh-4126) + // dataFilter is not invoked for failure responses, so using it instead + // of the default converter is kludgy but it works. + converters: { + "text script": function() {} + }, + dataFilter: function( response ) { + jQuery.globalEval( response, options, doc ); + } + } ); +}; + + +jQuery.fn.extend( { + wrapAll: function( html ) { + var wrap; + + if ( this[ 0 ] ) { + if ( isFunction( html ) ) { + html = html.call( this[ 0 ] ); + } + + // The elements to wrap the target around + wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); + + if ( this[ 0 ].parentNode ) { + wrap.insertBefore( this[ 0 ] ); + } + + wrap.map( function() { + var elem = this; + + while ( elem.firstElementChild ) { + elem = elem.firstElementChild; + } + + return elem; + } ).append( this ); + } + + return this; + }, + + wrapInner: function( html ) { + if ( isFunction( html ) ) { + return this.each( function( i ) { + jQuery( this ).wrapInner( html.call( this, i ) ); + } ); + } + + return this.each( function() { + var self = jQuery( this ), + contents = self.contents(); + + if ( contents.length ) { + contents.wrapAll( html ); + + } else { + self.append( html ); + } + } ); + }, + + wrap: function( html ) { + var htmlIsFunction = isFunction( html ); + + return this.each( function( i ) { + jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html ); + } ); + }, + + unwrap: function( selector ) { + this.parent( selector ).not( "body" ).each( function() { + jQuery( this ).replaceWith( this.childNodes ); + } ); + return this; + } +} ); + + +jQuery.expr.pseudos.hidden = function( elem ) { + return !jQuery.expr.pseudos.visible( elem ); +}; +jQuery.expr.pseudos.visible = function( elem ) { + return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); +}; + + + + +jQuery.ajaxSettings.xhr = function() { + try { + return new window.XMLHttpRequest(); + } catch ( e ) {} +}; + +var xhrSuccessStatus = { + + // File protocol always yields status code 0, assume 200 + 0: 200, + + // Support: IE <=9 only + // #1450: sometimes IE returns 1223 when it should be 204 + 1223: 204 + }, + xhrSupported = jQuery.ajaxSettings.xhr(); + +support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); +support.ajax = xhrSupported = !!xhrSupported; + +jQuery.ajaxTransport( function( options ) { + var callback, errorCallback; + + // Cross domain only allowed if supported through XMLHttpRequest + if ( support.cors || xhrSupported && !options.crossDomain ) { + return { + send: function( headers, complete ) { + var i, + xhr = options.xhr(); + + xhr.open( + options.type, + options.url, + options.async, + options.username, + options.password + ); + + // Apply custom fields if provided + if ( options.xhrFields ) { + for ( i in options.xhrFields ) { + xhr[ i ] = options.xhrFields[ i ]; + } + } + + // Override mime type if needed + if ( options.mimeType && xhr.overrideMimeType ) { + xhr.overrideMimeType( options.mimeType ); + } + + // X-Requested-With header + // For cross-domain requests, seeing as conditions for a preflight are + // akin to a jigsaw puzzle, we simply never set it to be sure. + // (it can always be set on a per-request basis or even using ajaxSetup) + // For same-domain requests, won't change header if already provided. + if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { + headers[ "X-Requested-With" ] = "XMLHttpRequest"; + } + + // Set headers + for ( i in headers ) { + xhr.setRequestHeader( i, headers[ i ] ); + } + + // Callback + callback = function( type ) { + return function() { + if ( callback ) { + callback = errorCallback = xhr.onload = + xhr.onerror = xhr.onabort = xhr.ontimeout = + xhr.onreadystatechange = null; + + if ( type === "abort" ) { + xhr.abort(); + } else if ( type === "error" ) { + + // Support: IE <=9 only + // On a manual native abort, IE9 throws + // errors on any property access that is not readyState + if ( typeof xhr.status !== "number" ) { + complete( 0, "error" ); + } else { + complete( + + // File: protocol always yields status 0; see #8605, #14207 + xhr.status, + xhr.statusText + ); + } + } else { + complete( + xhrSuccessStatus[ xhr.status ] || xhr.status, + xhr.statusText, + + // Support: IE <=9 only + // IE9 has no XHR2 but throws on binary (trac-11426) + // For XHR2 non-text, let the caller handle it (gh-2498) + ( xhr.responseType || "text" ) !== "text" || + typeof xhr.responseText !== "string" ? + { binary: xhr.response } : + { text: xhr.responseText }, + xhr.getAllResponseHeaders() + ); + } + } + }; + }; + + // Listen to events + xhr.onload = callback(); + errorCallback = xhr.onerror = xhr.ontimeout = callback( "error" ); + + // Support: IE 9 only + // Use onreadystatechange to replace onabort + // to handle uncaught aborts + if ( xhr.onabort !== undefined ) { + xhr.onabort = errorCallback; + } else { + xhr.onreadystatechange = function() { + + // Check readyState before timeout as it changes + if ( xhr.readyState === 4 ) { + + // Allow onerror to be called first, + // but that will not handle a native abort + // Also, save errorCallback to a variable + // as xhr.onerror cannot be accessed + window.setTimeout( function() { + if ( callback ) { + errorCallback(); + } + } ); + } + }; + } + + // Create the abort callback + callback = callback( "abort" ); + + try { + + // Do send the request (this may raise an exception) + xhr.send( options.hasContent && options.data || null ); + } catch ( e ) { + + // #14683: Only rethrow if this hasn't been notified as an error yet + if ( callback ) { + throw e; + } + } + }, + + abort: function() { + if ( callback ) { + callback(); + } + } + }; + } +} ); + + + + +// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432) +jQuery.ajaxPrefilter( function( s ) { + if ( s.crossDomain ) { + s.contents.script = false; + } +} ); + +// Install script dataType +jQuery.ajaxSetup( { + accepts: { + script: "text/javascript, application/javascript, " + + "application/ecmascript, application/x-ecmascript" + }, + contents: { + script: /\b(?:java|ecma)script\b/ + }, + converters: { + "text script": function( text ) { + jQuery.globalEval( text ); + return text; + } + } +} ); + +// Handle cache's special case and crossDomain +jQuery.ajaxPrefilter( "script", function( s ) { + if ( s.cache === undefined ) { + s.cache = false; + } + if ( s.crossDomain ) { + s.type = "GET"; + } +} ); + +// Bind script tag hack transport +jQuery.ajaxTransport( "script", function( s ) { + + // This transport only deals with cross domain or forced-by-attrs requests + if ( s.crossDomain || s.scriptAttrs ) { + var script, callback; + return { + send: function( _, complete ) { + script = jQuery( " + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

osxphotos command line interface (CLI)

+
+

osxphotos

+
osxphotos [OPTIONS] COMMAND [ARGS]...
+
+
+

Options

+
+
+--db <Photos database path>
+

Specify Photos database path. Path to Photos library/database can be specified using either –db or directly as PHOTOS_LIBRARY positional argument. If neither –db or PHOTOS_LIBRARY provided, will attempt to find the library to use in the following order: 1. last opened library, 2. system library, 3. ~/Pictures/Photos Library.photoslibrary

+
+ +
+
+--json
+

Print output in JSON format.

+
+ +
+
+-v, --version
+

Show the version and exit.

+
+ +
+

about

+

Print information about osxphotos including license.

+
osxphotos about [OPTIONS]
+
+
+
+
+

albums

+

Print out albums found in the Photos library.

+
osxphotos albums [OPTIONS] [PHOTOS_LIBRARY]...
+
+
+

Options

+
+
+--db <Photos database path>
+

Specify Photos database path. Path to Photos library/database can be specified using either –db or directly as PHOTOS_LIBRARY positional argument. If neither –db or PHOTOS_LIBRARY provided, will attempt to find the library to use in the following order: 1. last opened library, 2. system library, 3. ~/Pictures/Photos Library.photoslibrary

+
+ +
+
+--json
+

Print output in JSON format.

+
+ +

Arguments

+
+
+PHOTOS_LIBRARY
+

Optional argument(s)

+
+ +
+
+

dump

+

Print list of all photos & associated info from the Photos library.

+
osxphotos dump [OPTIONS] [PHOTOS_LIBRARY]...
+
+
+

Options

+
+
+--db <Photos database path>
+

Specify Photos database path. Path to Photos library/database can be specified using either –db or directly as PHOTOS_LIBRARY positional argument. If neither –db or PHOTOS_LIBRARY provided, will attempt to find the library to use in the following order: 1. last opened library, 2. system library, 3. ~/Pictures/Photos Library.photoslibrary

+
+ +
+
+--json
+

Print output in JSON format.

+
+ +
+
+--deleted
+

Include photos from the ‘Recently Deleted’ folder.

+
+ +
+
+--deleted-only
+

Include only photos from the ‘Recently Deleted’ folder.

+
+ +

Arguments

+
+
+PHOTOS_LIBRARY
+

Optional argument(s)

+
+ +
+
+

export

+

Export photos from the Photos database. +Export path DEST is required. +Optionally, query the Photos database using 1 or more search options; +if more than one option is provided, they are treated as “AND” +(e.g. search for photos matching all options). +If no query options are provided, all photos will be exported. +By default, all versions of all photos will be exported including edited +versions, live photo movies, burst photos, and associated raw images. +See –skip-edited, –skip-live, –skip-bursts, and –skip-raw options +to modify this behavior.

+
osxphotos export [OPTIONS] [PHOTOS_LIBRARY]... DEST
+
+
+

Options

+
+
+--db <Photos database path>
+

Specify Photos database path. Path to Photos library/database can be specified using either –db or directly as PHOTOS_LIBRARY positional argument. If neither –db or PHOTOS_LIBRARY provided, will attempt to find the library to use in the following order: 1. last opened library, 2. system library, 3. ~/Pictures/Photos Library.photoslibrary

+
+ +
+
+-V, --verbose
+

Print verbose output.

+
+ +
+
+--keyword <KEYWORD>
+

Search for photos with keyword KEYWORD. If more than one keyword, treated as “OR”, e.g. find photos matching any keyword

+
+ +
+
+--person <PERSON>
+

Search for photos with person PERSON. If more than one person, treated as “OR”, e.g. find photos matching any person

+
+ +
+
+--album <ALBUM>
+

Search for photos in album ALBUM. If more than one album, treated as “OR”, e.g. find photos matching any album

+
+ +
+
+--folder <FOLDER>
+

Search for photos in an album in folder FOLDER. If more than one folder, treated as “OR”, e.g. find photos in any FOLDER. Only searches top level folders (e.g. does not look at subfolders)

+
+ +
+
+--uuid <UUID>
+

Search for photos with UUID(s).

+
+ +
+
+--uuid-from-file <FILE>
+

Search for photos with UUID(s) loaded from FILE. Format is a single UUID per line. Lines preceeded with # are ignored.

+
+ +
+
+--title <TITLE>
+

Search for TITLE in title of photo.

+
+ +
+
+--no-title
+

Search for photos with no title.

+
+ +
+
+--description <DESC>
+

Search for DESC in description of photo.

+
+ +
+
+--no-description
+

Search for photos with no description.

+
+ +
+
+--place <PLACE>
+

Search for PLACE in photo’s reverse geolocation info

+
+ +
+
+--no-place
+

Search for photos with no associated place name info (no reverse geolocation info)

+
+ +
+
+--label <LABEL>
+

Search for photos with image classification label LABEL (Photos 5 only). If more than one label, treated as “OR”, e.g. find photos matching any label

+
+ +
+
+--uti <UTI>
+

Search for photos whose uniform type identifier (UTI) matches UTI

+
+ +
+
+-i, --ignore-case
+

Case insensitive search for title, description, place, keyword, person, or album.

+
+ +
+
+--edited
+

Search for photos that have been edited.

+
+ +
+
+--external-edit
+

Search for photos edited in external editor.

+
+ +
+
+--favorite
+

Search for photos marked favorite.

+
+ +
+
+--not-favorite
+

Search for photos not marked favorite.

+
+ +
+
+--hidden
+

Search for photos marked hidden.

+
+ +
+
+--not-hidden
+

Search for photos not marked hidden.

+
+ +
+
+--shared
+

Search for photos in shared iCloud album (Photos 5 only).

+
+ +
+
+--not-shared
+

Search for photos not in shared iCloud album (Photos 5 only).

+
+ +
+
+--burst
+

Search for photos that were taken in a burst.

+
+ +
+
+--not-burst
+

Search for photos that are not part of a burst.

+
+ +
+
+--live
+

Search for Apple live photos

+
+ +
+
+--not-live
+

Search for photos that are not Apple live photos.

+
+ +
+
+--portrait
+

Search for Apple portrait mode photos.

+
+ +
+
+--not-portrait
+

Search for photos that are not Apple portrait mode photos.

+
+ +
+
+--screenshot
+

Search for screenshot photos.

+
+ +
+
+--not-screenshot
+

Search for photos that are not screenshot photos.

+
+ +
+
+--slow-mo
+

Search for slow motion videos.

+
+ +
+
+--not-slow-mo
+

Search for photos that are not slow motion videos.

+
+ +
+
+--time-lapse
+

Search for time lapse videos.

+
+ +
+
+--not-time-lapse
+

Search for photos that are not time lapse videos.

+
+ +
+
+--hdr
+

Search for high dynamic range (HDR) photos.

+
+ +
+
+--not-hdr
+

Search for photos that are not HDR photos.

+
+ +
+
+--selfie
+

Search for selfies (photos taken with front-facing cameras).

+
+ +
+
+--not-selfie
+

Search for photos that are not selfies.

+
+ +
+
+--panorama
+

Search for panorama photos.

+
+ +
+
+--not-panorama
+

Search for photos that are not panoramas.

+
+ +
+
+--has-raw
+

Search for photos with both a jpeg and raw version

+
+ +
+
+--only-movies
+

Search only for movies (default searches both images and movies).

+
+ +
+
+--only-photos
+

Search only for photos/images (default searches both images and movies).

+
+ +
+
+--from-date <from_date>
+

Search by start item date, e.g. 2000-01-12T12:00:00, 2001-01-12T12:00:00-07:00, or 2000-12-31 (ISO 8601).

+
+ +
+
+--to-date <to_date>
+

Search by end item date, e.g. 2000-01-12T12:00:00, 2001-01-12T12:00:00-07:00, or 2000-12-31 (ISO 8601).

+
+ +
+
+--has-comment
+

Search for photos that have comments.

+
+ +
+
+--no-comment
+

Search for photos with no comments.

+
+ +
+
+--has-likes
+

Search for photos that have likes.

+
+ +
+
+--no-likes
+

Search for photos with no likes.

+
+ +
+
+--is-reference
+

Search for photos that were imported as referenced files (not copied into Photos library).

+
+ +
+
+--missing
+

Export only photos missing from the Photos library; must be used with –download-missing.

+
+ +
+
+--deleted
+

Include photos from the ‘Recently Deleted’ folder.

+
+ +
+
+--deleted-only
+

Include only photos from the ‘Recently Deleted’ folder.

+
+ +
+
+--update
+

Only export new or updated files. See notes below on export and –update.

+
+ +
+
+--ignore-signature
+

When used with –update, ignores file signature when updating files. This is useful if you have processed or edited exported photos changing the file signature (size & modification date). In this case, –update would normally re-export the processed files but with –ignore-signature, files which exist in the export directory will not be re-exported.

+
+ +
+
+--dry-run
+

Dry run (test) the export but don’t actually export any files; most useful with –verbose.

+
+ +
+ +

Hardlink files instead of copying them. Cannot be used with –exiftool which creates copies of the files with embedded EXIF data. Note: on APFS volumes, files are cloned when exporting giving many of the same advantages as hardlinks without having to use –export-as-hardlink.

+
+ +
+
+--touch-file
+

Sets the file’s modification time to match photo date.

+
+ +
+
+--overwrite
+

Overwrite existing files. Default behavior is to add (1), (2), etc to filename if file already exists. Use this with caution as it may create name collisions on export. (e.g. if two files happen to have the same name)

+
+ +
+
+--export-by-date
+

Automatically create output folders to organize photos by date created (e.g. DEST/2019/12/20/photoname.jpg).

+
+ +
+
+--skip-edited
+

Do not export edited version of photo if an edited version exists.

+
+ +
+
+--skip-original-if-edited
+

Do not export original if there is an edited version (exports only the edited version).

+
+ +
+
+--skip-bursts
+

Do not export all associated burst images in the library if a photo is a burst photo.

+
+ +
+
+--skip-live
+

Do not export the associated live video component of a live photo.

+
+ +
+
+--skip-raw
+

Do not export associated raw images of a RAW+JPEG pair. Note: this does not skip raw photos if the raw photo does not have an associated jpeg image (e.g. the raw file was imported to Photos without a jpeg preview).

+
+ +
+
+--current-name
+

Use photo’s current filename instead of original filename for export. Note: Starting with Photos 5, all photos are renamed upon import. By default, photos are exported with the the original name they had before import.

+
+ +
+
+--convert-to-jpeg
+

Convert all non-jpeg images (e.g. raw, HEIC, PNG, etc) to JPEG upon export. Only works if your Mac has a GPU.

+
+ +
+
+--jpeg-quality <jpeg_quality>
+

Value in range 0.0 to 1.0 to use with –convert-to-jpeg. A value of 1.0 specifies best quality, a value of 0.0 specifies maximum compression. Defaults to 1.0

+
+ +
+
+--download-missing
+

Attempt to download missing photos from iCloud. The current implementation uses Applescript to interact with Photos to export the photo which will force Photos to download from iCloud if the photo does not exist on disk. This will be slow and will require internet connection. This obviously only works if the Photos library is synched to iCloud. Note: –download-missing does not currently export all burst images; only the primary photo will be exported–associated burst images will be skipped.

+
+ +
+
+--sidecar <FORMAT>
+

Create sidecar for each photo exported; valid FORMAT values: xmp, json, exiftool; –sidecar xmp: create XMP sidecar used by Digikam, Adobe Lightroom, etc. The sidecar file is named in format photoname.ext.xmp The XMP sidecar exports the following tags: Description, Title, Keywords/Tags, Subject (set to Keywords + PersonInImage), PersonInImage, CreateDate, ModifyDate, GPSLongitude, Face Regions (Metadata Working Group and Microsoft Photo). +–sidecar json: create JSON sidecar useable by exiftool (https://exiftool.org/) The sidecar file can be used to apply metadata to the file with exiftool, for example: “exiftool -j=photoname.jpg.json photoname.jpg” The sidecar file is named in format photoname.ext.json; format includes tag groups (equivalent to running ‘exiftool -G -j’). +–sidecar exiftool: create JSON sidecar compatible with output of ‘exiftool -j’. Unlike ‘–sidecar json’, ‘–sidecar exiftool’ does not export tag groups. Sidecar filename is in format photoname.ext.json; For a list of tags exported in the JSON and exiftool sidecar, see ‘–exiftool’.

+
+
Options
+

xmp|json|exiftool

+
+
+
+ +
+
+--sidecar-drop-ext
+

Drop the photo’s extension when naming sidecar files. By default, sidecar files are named in format ‘photo_filename.photo_ext.sidecar_ext’, e.g. ‘IMG_1234.JPG.xmp’. Use ‘–sidecar-drop-ext’ to ignore the photo extension. Resulting sidecar files will have name in format ‘IMG_1234.xmp’. Warning: this may result in sidecar filename collisions if there are files of different types but the same name in the output directory, e.g. ‘IMG_1234.JPG’ and ‘IMG_1234.MOV’.

+
+ +
+
+--exiftool
+

Use exiftool to write metadata directly to exported photos. To use this option, exiftool must be installed and in the path. exiftool may be installed from https://exiftool.org/. Cannot be used with –export-as-hardlink. Writes the following metadata: EXIF:ImageDescription, XMP:Description (see also –description-template); XMP:Title; XMP:TagsList, IPTC:Keywords, XMP:Subject (see also –keyword-template, –person-keyword, –album-keyword); XMP:PersonInImage; EXIF:GPSLatitudeRef; EXIF:GPSLongitudeRef; EXIF:GPSLatitude; EXIF:GPSLongitude; EXIF:GPSPosition; EXIF:DateTimeOriginal; EXIF:OffsetTimeOriginal; EXIF:ModifyDate (see –ignore-date-modified); IPTC:DateCreated; IPTC:TimeCreated; (video files only): QuickTime:CreationDate; QuickTime:CreateDate; QuickTime:ModifyDate (see also –ignore-date-modified); QuickTime:GPSCoordinates; UserData:GPSCoordinates.

+
+ +
+
+--exiftool-path <EXIFTOOL_PATH>
+

Optionally specify path to exiftool; if not provided, will look for exiftool in $PATH.

+
+ +
+
+--exiftool-option <OPTION>
+

Optional flag/option to pass to exiftool when using –exiftool. For example, –exiftool-option ‘-m’ to ignore minor warnings. Specify these as you would on the exiftool command line. See exiftool docs at https://exiftool.org/exiftool_pod.html for full list of options. More than one option may be specified by repeating the option, e.g. –exiftool-option ‘-m’ –exiftool-option ‘-F’.

+
+ +
+
+--exiftool-merge-keywords
+

Merge any keywords found in the original file with keywords used for ‘–exiftool’ and ‘–sidecar’.

+
+ +
+
+--exiftool-merge-persons
+

Merge any persons found in the original file with persons used for ‘–exiftool’ and ‘–sidecar’.

+
+ +
+
+--ignore-date-modified
+

If used with –exiftool or –sidecar, will ignore the photo modification date and set EXIF:ModifyDate to EXIF:DateTimeOriginal; this is consistent with how Photos handles the EXIF:ModifyDate tag.

+
+ +
+
+--person-keyword
+

Use person in image as keyword/tag when exporting metadata.

+
+ +
+
+--album-keyword
+

Use album name as keyword/tag when exporting metadata.

+
+ +
+
+--keyword-template <TEMPLATE>
+

For use with –exiftool, –sidecar; specify a template string to use as keyword in the form ‘{name,DEFAULT}’ This is the same format as –directory. For example, if you wanted to add the full path to the folder and album photo is contained in as a keyword when exporting you could specify –keyword-template “{folder_album}” You may specify more than one template, for example –keyword-template “{folder_album}” –keyword-template “{created.year}” See Templating System below.

+
+ +
+
+--description-template <TEMPLATE>
+

For use with –exiftool, –sidecar; specify a template string to use as description in the form ‘{name,DEFAULT}’ This is the same format as –directory. For example, if you wanted to append ‘exported with osxphotos on [today’s date]’ to the description, you could specify –description-template “{descr} exported with osxphotos on {today.date}” See Templating System below.

+
+ +
+
+--finder-tag-template <TEMPLATE>
+

Set MacOS Finder tags to TEMPLATE. These tags can be searched in the Finder or Spotlight with ‘tag:tagname’ format. For example, ‘–finder-tag-template “{label}”’ to set Finder tags to photo labels. You may specify multiple TEMPLATE values by using ‘–finder-tag-template’ multiple times. See also ‘–finder-tag-keywords and Extended Attributes below.’.

+
+ +
+
+--finder-tag-keywords
+

Set MacOS Finder tags to keywords; any keywords specified via ‘–keyword-template’, ‘–person-keyword’, etc. will also be used as Finder tags. See also ‘–finder-tag-template and Extended Attributes below.’.

+
+ +
+
+--xattr-template <ATTRIBUTE TEMPLATE>
+

Set extended attribute ATTRIBUTE to TEMPLATE value. Valid attributes are: ‘authors’, ‘comment’, ‘copyright’, ‘description’, ‘findercomment’, ‘headline’, ‘keywords’. For example, to set Finder comment to the photo’s title and description: ‘–xattr-template findercomment “{title}; {descr}” See Extended Attributes below for additional details on this option.

+
+ +
+
+--directory <DIRECTORY>
+

Optional template for specifying name of output directory in the form ‘{name,DEFAULT}’. See below for additional details on templating system.

+
+ +
+
+--filename <FILENAME>
+

Optional template for specifying name of output file in the form ‘{name,DEFAULT}’. File extension will be added automatically–do not include an extension in the FILENAME template. See below for additional details on templating system.

+
+ +
+
+--jpeg-ext <EXTENSION>
+

Specify file extension for JPEG files. Photos uses .jpeg for edited images but many images are imported with .jpg or .JPG which can result in multiple different extensions used for JPEG files upon export. Use –jpg-ext to specify a single extension to use for all exported JPEG images. Valid values are jpeg, jpg, JPEG, JPG; e.g. ‘–jpg-ext jpg’ to use ‘.jpg’ for all JPEGs.

+
+
Options
+

jpeg|jpg|JPEG|JPG

+
+
+
+ +
+
+--strip
+

Optionally strip leading and trailing whitespace from any rendered templates. For example, if –filename template is “{title,} {original_name}” and image has no title, resulting file would have a leading space but if used with –strip, this will be removed.

+
+ +
+
+--edited-suffix <SUFFIX>
+

Optional suffix template for naming edited photos. Default name for edited photos is in form ‘photoname_edited.ext’. For example, with ‘–edited-suffix _bearbeiten’, the edited photo would be named ‘photoname_bearbeiten.ext’. The default suffix is ‘_edited’. Multi-value templates (see Templating System) are not permitted with –edited-suffix.

+
+ +
+
+--original-suffix <SUFFIX>
+

Optional suffix template for naming original photos. Default name for original photos is in form ‘filename.ext’. For example, with ‘–original-suffix _original’, the original photo would be named ‘filename_original.ext’. The default suffix is ‘’ (no suffix). Multi-value templates (see Templating System) are not permitted with –original-suffix.

+
+ +
+
+--use-photos-export
+

Force the use of AppleScript or PhotoKit to export even if not missing (see also ‘–download-missing’ and ‘–use-photokit’).

+
+ +
+
+--use-photokit
+

Use with ‘–download-missing’ or ‘–use-photos-export’ to use direct Photos interface instead of AppleScript to export. Highly experimental alpha feature; does not work with iTerm2 (use with Terminal.app). This is faster and more reliable than the default AppleScript interface.

+
+ +
+
+--report <path to export report>
+

Write a CSV formatted report of all files that were exported.

+
+ +
+
+--cleanup
+

Cleanup export directory by deleting any files which were not included in this export set. For example, photos which had previously been exported and were subsequently deleted in Photos.

+
+ +
+
+--exportdb <EXPORTDB_FILE>
+

Specify alternate name for database file which stores state information for export and –update. If –exportdb is not specified, export database will be saved to ‘.osxphotos_export.db’ in the export directory. Must be specified as filename only, not a path, as export database will be saved in export directory.

+
+ +
+
+--load-config <config file path>
+

Load options from file as written with –save-config. This allows you to save a complex export command to file for later reuse. For example: ‘osxphotos export <lots of options here> –save-config osxphotos.toml’ then ‘osxphotos export /path/to/export –load-config osxphotos.toml’. If any other command line options are used in conjunction with –load-config, they will override the corresponding values in the config file.

+
+ +
+
+--save-config <config file path>
+

Save options to file for use with –load-config. File format is TOML.

+
+ +

Arguments

+
+
+PHOTOS_LIBRARY
+

Optional argument(s)

+
+ +
+
+DEST
+

Required argument

+
+ +
+
+

help

+

Print help; for help on commands: help <command>.

+
osxphotos help [OPTIONS] [TOPIC]
+
+
+

Arguments

+
+
+TOPIC
+

Optional argument

+
+ +
+
+

info

+

Print out descriptive info of the Photos library database.

+
osxphotos info [OPTIONS] [PHOTOS_LIBRARY]...
+
+
+

Options

+
+
+--db <Photos database path>
+

Specify Photos database path. Path to Photos library/database can be specified using either –db or directly as PHOTOS_LIBRARY positional argument. If neither –db or PHOTOS_LIBRARY provided, will attempt to find the library to use in the following order: 1. last opened library, 2. system library, 3. ~/Pictures/Photos Library.photoslibrary

+
+ +
+
+--json
+

Print output in JSON format.

+
+ +

Arguments

+
+
+PHOTOS_LIBRARY
+

Optional argument(s)

+
+ +
+
+

keywords

+

Print out keywords found in the Photos library.

+
osxphotos keywords [OPTIONS] [PHOTOS_LIBRARY]...
+
+
+

Options

+
+
+--db <Photos database path>
+

Specify Photos database path. Path to Photos library/database can be specified using either –db or directly as PHOTOS_LIBRARY positional argument. If neither –db or PHOTOS_LIBRARY provided, will attempt to find the library to use in the following order: 1. last opened library, 2. system library, 3. ~/Pictures/Photos Library.photoslibrary

+
+ +
+
+--json
+

Print output in JSON format.

+
+ +

Arguments

+
+
+PHOTOS_LIBRARY
+

Optional argument(s)

+
+ +
+
+

labels

+

Print out image classification labels found in the Photos library.

+
osxphotos labels [OPTIONS] [PHOTOS_LIBRARY]...
+
+
+

Options

+
+
+--db <Photos database path>
+

Specify Photos database path. Path to Photos library/database can be specified using either –db or directly as PHOTOS_LIBRARY positional argument. If neither –db or PHOTOS_LIBRARY provided, will attempt to find the library to use in the following order: 1. last opened library, 2. system library, 3. ~/Pictures/Photos Library.photoslibrary

+
+ +
+
+--json
+

Print output in JSON format.

+
+ +

Arguments

+
+
+PHOTOS_LIBRARY
+

Optional argument(s)

+
+ +
+
+

list

+

Print list of Photos libraries found on the system.

+
osxphotos list [OPTIONS]
+
+
+

Options

+
+
+--json
+

Print output in JSON format.

+
+ +
+
+

persons

+

Print out persons (faces) found in the Photos library.

+
osxphotos persons [OPTIONS] [PHOTOS_LIBRARY]...
+
+
+

Options

+
+
+--db <Photos database path>
+

Specify Photos database path. Path to Photos library/database can be specified using either –db or directly as PHOTOS_LIBRARY positional argument. If neither –db or PHOTOS_LIBRARY provided, will attempt to find the library to use in the following order: 1. last opened library, 2. system library, 3. ~/Pictures/Photos Library.photoslibrary

+
+ +
+
+--json
+

Print output in JSON format.

+
+ +

Arguments

+
+
+PHOTOS_LIBRARY
+

Optional argument(s)

+
+ +
+
+

places

+

Print out places found in the Photos library.

+
osxphotos places [OPTIONS] [PHOTOS_LIBRARY]...
+
+
+

Options

+
+
+--db <Photos database path>
+

Specify Photos database path. Path to Photos library/database can be specified using either –db or directly as PHOTOS_LIBRARY positional argument. If neither –db or PHOTOS_LIBRARY provided, will attempt to find the library to use in the following order: 1. last opened library, 2. system library, 3. ~/Pictures/Photos Library.photoslibrary

+
+ +
+
+--json
+

Print output in JSON format.

+
+ +

Arguments

+
+
+PHOTOS_LIBRARY
+

Optional argument(s)

+
+ +
+
+

query

+

Query the Photos database using 1 or more search options; +if more than one option is provided, they are treated as “AND” +(e.g. search for photos matching all options).

+
osxphotos query [OPTIONS] [PHOTOS_LIBRARY]...
+
+
+

Options

+
+
+--db <Photos database path>
+

Specify Photos database path. Path to Photos library/database can be specified using either –db or directly as PHOTOS_LIBRARY positional argument. If neither –db or PHOTOS_LIBRARY provided, will attempt to find the library to use in the following order: 1. last opened library, 2. system library, 3. ~/Pictures/Photos Library.photoslibrary

+
+ +
+
+--json
+

Print output in JSON format.

+
+ +
+
+--keyword <KEYWORD>
+

Search for photos with keyword KEYWORD. If more than one keyword, treated as “OR”, e.g. find photos matching any keyword

+
+ +
+
+--person <PERSON>
+

Search for photos with person PERSON. If more than one person, treated as “OR”, e.g. find photos matching any person

+
+ +
+
+--album <ALBUM>
+

Search for photos in album ALBUM. If more than one album, treated as “OR”, e.g. find photos matching any album

+
+ +
+
+--folder <FOLDER>
+

Search for photos in an album in folder FOLDER. If more than one folder, treated as “OR”, e.g. find photos in any FOLDER. Only searches top level folders (e.g. does not look at subfolders)

+
+ +
+
+--uuid <UUID>
+

Search for photos with UUID(s).

+
+ +
+
+--uuid-from-file <FILE>
+

Search for photos with UUID(s) loaded from FILE. Format is a single UUID per line. Lines preceeded with # are ignored.

+
+ +
+
+--title <TITLE>
+

Search for TITLE in title of photo.

+
+ +
+
+--no-title
+

Search for photos with no title.

+
+ +
+
+--description <DESC>
+

Search for DESC in description of photo.

+
+ +
+
+--no-description
+

Search for photos with no description.

+
+ +
+
+--place <PLACE>
+

Search for PLACE in photo’s reverse geolocation info

+
+ +
+
+--no-place
+

Search for photos with no associated place name info (no reverse geolocation info)

+
+ +
+
+--label <LABEL>
+

Search for photos with image classification label LABEL (Photos 5 only). If more than one label, treated as “OR”, e.g. find photos matching any label

+
+ +
+
+--uti <UTI>
+

Search for photos whose uniform type identifier (UTI) matches UTI

+
+ +
+
+-i, --ignore-case
+

Case insensitive search for title, description, place, keyword, person, or album.

+
+ +
+
+--edited
+

Search for photos that have been edited.

+
+ +
+
+--external-edit
+

Search for photos edited in external editor.

+
+ +
+
+--favorite
+

Search for photos marked favorite.

+
+ +
+
+--not-favorite
+

Search for photos not marked favorite.

+
+ +
+
+--hidden
+

Search for photos marked hidden.

+
+ +
+
+--not-hidden
+

Search for photos not marked hidden.

+
+ +
+
+--shared
+

Search for photos in shared iCloud album (Photos 5 only).

+
+ +
+
+--not-shared
+

Search for photos not in shared iCloud album (Photos 5 only).

+
+ +
+
+--burst
+

Search for photos that were taken in a burst.

+
+ +
+
+--not-burst
+

Search for photos that are not part of a burst.

+
+ +
+
+--live
+

Search for Apple live photos

+
+ +
+
+--not-live
+

Search for photos that are not Apple live photos.

+
+ +
+
+--portrait
+

Search for Apple portrait mode photos.

+
+ +
+
+--not-portrait
+

Search for photos that are not Apple portrait mode photos.

+
+ +
+
+--screenshot
+

Search for screenshot photos.

+
+ +
+
+--not-screenshot
+

Search for photos that are not screenshot photos.

+
+ +
+
+--slow-mo
+

Search for slow motion videos.

+
+ +
+
+--not-slow-mo
+

Search for photos that are not slow motion videos.

+
+ +
+
+--time-lapse
+

Search for time lapse videos.

+
+ +
+
+--not-time-lapse
+

Search for photos that are not time lapse videos.

+
+ +
+
+--hdr
+

Search for high dynamic range (HDR) photos.

+
+ +
+
+--not-hdr
+

Search for photos that are not HDR photos.

+
+ +
+
+--selfie
+

Search for selfies (photos taken with front-facing cameras).

+
+ +
+
+--not-selfie
+

Search for photos that are not selfies.

+
+ +
+
+--panorama
+

Search for panorama photos.

+
+ +
+
+--not-panorama
+

Search for photos that are not panoramas.

+
+ +
+
+--has-raw
+

Search for photos with both a jpeg and raw version

+
+ +
+
+--only-movies
+

Search only for movies (default searches both images and movies).

+
+ +
+
+--only-photos
+

Search only for photos/images (default searches both images and movies).

+
+ +
+
+--from-date <from_date>
+

Search by start item date, e.g. 2000-01-12T12:00:00, 2001-01-12T12:00:00-07:00, or 2000-12-31 (ISO 8601).

+
+ +
+
+--to-date <to_date>
+

Search by end item date, e.g. 2000-01-12T12:00:00, 2001-01-12T12:00:00-07:00, or 2000-12-31 (ISO 8601).

+
+ +
+
+--has-comment
+

Search for photos that have comments.

+
+ +
+
+--no-comment
+

Search for photos with no comments.

+
+ +
+
+--has-likes
+

Search for photos that have likes.

+
+ +
+
+--no-likes
+

Search for photos with no likes.

+
+ +
+
+--is-reference
+

Search for photos that were imported as referenced files (not copied into Photos library).

+
+ +
+
+--deleted
+

Include photos from the ‘Recently Deleted’ folder.

+
+ +
+
+--deleted-only
+

Include only photos from the ‘Recently Deleted’ folder.

+
+ +
+
+--missing
+

Search for photos missing from disk.

+
+ +
+
+--not-missing
+

Search for photos present on disk (e.g. not missing).

+
+ +
+
+--cloudasset
+

Search for photos that are part of an iCloud library

+
+ +
+
+--not-cloudasset
+

Search for photos that are not part of an iCloud library

+
+ +
+
+--incloud
+

Search for photos that are in iCloud (have been synched)

+
+ +
+
+--not-incloud
+

Search for photos that are not in iCloud (have not been synched)

+
+ +

Arguments

+
+
+PHOTOS_LIBRARY
+

Optional argument(s)

+
+ +
+
+
+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/build/html/genindex.html b/docs/build/html/genindex.html new file mode 100644 index 00000000..56d2d1d0 --- /dev/null +++ b/docs/build/html/genindex.html @@ -0,0 +1,2085 @@ + + + + + + + + Index — osxphotos 0.40.4 documentation + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ + +

Index

+ +
+ Symbols + | A + | B + | C + | D + | E + | F + | G + | H + | I + | J + | K + | L + | M + | N + | O + | P + | R + | S + | T + | U + | V + | W + | Y + +
+

Symbols

+ + + +
+ +

A

+ + + +
+ +

B

+ + + +
+ +

C

+ + + +
+ +

D

+ + + +
+ +

E

+ + + +
+ +

F

+ + + +
+ +

G

+ + + +
+ +

H

+ + + +
+ +

I

+ + + +
+ +

J

+ + +
+ +

K

+ + + +
+ +

L

+ + + +
+ +

M

+ + + +
+ +

N

+ + + +
+ +

O

+ + + +
+ +

P

+ + + +
+ +

R

+ + + +
+ +

S

+ + + +
+ +

T

+ + + +
+ +

U

+ + + +
+ +

V

+ + + +
+ +

W

+ + + +
+ +

Y

+ + +
+ + + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/build/html/index.html b/docs/build/html/index.html new file mode 100644 index 00000000..8105574e --- /dev/null +++ b/docs/build/html/index.html @@ -0,0 +1,380 @@ + + + + + + + + Welcome to osxphotos’s documentation! — osxphotos 0.40.4 documentation + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

Welcome to osxphotos’s documentation!

+
+
+

OSXPhotos

+
+

What is osxphotos?

+

OSXPhotos provides both the ability to interact with and query Apple’s Photos.app library on macOS directly from your python code +as well as a very flexible command line interface (CLI) app for exporting photos. +You can query the Photos library database – for example, file name, file path, and metadata such as keywords/tags, persons/faces, albums, etc. +You can also easily export both the original and edited photos.

+
+
+

Supported operating systems

+

Only works on macOS (aka Mac OS X). Tested on macOS Sierra (10.12.6) until macOS Catalina (10.15.7). +Beta support for macOS Big Sur (10.16.01/11.01).

+

This package will read Photos databases for any supported version on any supported macOS version. +E.g. you can read a database created with Photos 5.0 on MacOS 10.15 on a machine running macOS 10.12 and vice versa.

+

Requires python >= 3.7.

+
+
+

Installation

+

If you are new to python and just want to use the command line application, I recommend you to install using pipx. See other advanced options below.

+
+

Installation using pipx

+

If you aren’t familiar with installing python applications, I recommend you install osxphotos with pipx. If you use pipx, you will not need to create a virtual environment as pipx takes care of this. The easiest way to do this on a Mac is to use homebrew:

+
    +
  • Open Terminal (search for Terminal in Spotlight or look in Applications/Utilities)

  • +
  • Install homebrew according to instructions at https://brew.sh/

  • +
  • Type the following into Terminal: brew install pipx

  • +
  • Then type this: pipx install osxphotos

  • +
  • Now you should be able to run osxphotos by typing: osxphotos

  • +
+
+
+

Installation using pip

+

You can also install directly from pypi:

+
pip install osxphotos
+
+
+
+
+

Installation from git repository

+

OSXPhotos uses setuptools, thus simply run:

+
git clone https://github.com/RhetTbull/osxphotos.git
+cd osxphotos
+python3 setup.py install
+
+
+

I recommend you create a virtual environment before installing osxphotos.

+

WARNING The git repo for this project is very large (> 1GB) because it contains multiple Photos libraries used for testing +on different versions of macOS. If you just want to use the osxphotos package in your own code, +I recommend you install the latest version from PyPI which does not include all the test +libraries. If you just want to use the command line utility, you can download a pre-built executable of the latest +release or you can install via pip which also installs the command line app. +If you aren’t comfortable with running python on your Mac, start with the pre-built executable or pipx as described above.

+
+
+
+

Command Line Usage

+

This package will install a command line utility called osxphotos that allows you to query the Photos database and export photos. +Alternatively, you can also run the command line utility like this: python3 -m osxphotos

+
> osxphotos
+Usage: osxphotos [OPTIONS] COMMAND [ARGS]...
+
+Options:
+  --db <Photos database path>  Specify Photos database path. Path to Photos
+                               library/database can be specified using either
+                               --db or directly as PHOTOS_LIBRARY positional
+                               argument. If neither --db or PHOTOS_LIBRARY
+                               provided, will attempt to find the library to
+                               use in the following order: 1. last opened
+                               library, 2. system library, 3.
+                               ~/Pictures/Photos Library.photoslibrary
+  --json                       Print output in JSON format.
+  -v, --version                Show the version and exit.
+  -h, --help                   Show this message and exit.
+
+Commands:
+  about     Print information about osxphotos including license.
+  albums    Print out albums found in the Photos library.
+  dump      Print list of all photos & associated info from the Photos...
+  export    Export photos from the Photos database.
+  help      Print help; for help on commands: help <command>.
+  info      Print out descriptive info of the Photos library database.
+  keywords  Print out keywords found in the Photos library.
+  labels    Print out image classification labels found in the Photos...
+  list      Print list of Photos libraries found on the system.
+  persons   Print out persons (faces) found in the Photos library.
+  places    Print out places found in the Photos library.
+  query     Query the Photos database using 1 or more search options; if...
+
+
+

To get help on a specific command, use osxphotos help <command_name>

+
+

Command line examples

+
+

export all photos to ~/Desktop/export group in folders by date created

+

osxphotos export --export-by-date ~/Pictures/Photos\ Library.photoslibrary ~/Desktop/export

+

Note: Photos library/database path can also be specified using --db option:

+

osxphotos export --export-by-date --db ~/Pictures/Photos\ Library.photoslibrary ~/Desktop/export

+
+
+

find all photos with keyword “Kids” and output results to json file named results.json:

+

osxphotos query --keyword Kids --json ~/Pictures/Photos\ Library.photoslibrary >results.json

+
+
+

export photos to file structure based on 4-digit year and full name of month of photo’s creation date:

+

osxphotos export ~/Desktop/export --directory "{created.year}/{created.month}"

+

(by default, it will attempt to use the system library)

+
+
+

export photos to file structure based on 4-digit year of photo’s creation date and add keywords for media type and labels (labels are only awailable on Photos 5 and higher):

+

osxphotos export ~/Desktop/export --directory "{created.year}" --keyword-template "{label}" --keyword-template "{media_type}"

+
+
+

export default library using ‘country name/year’ as output directory (but use “NoCountry/year” if country not specified), add persons, album names, and year as keywords, write exif metadata to files when exporting, update only changed files, print verbose ouput

+

osxphotos export ~/Desktop/export --directory "{place.name.country,NoCountry}/{created.year}"  --person-keyword --album-keyword --keyword-template "{created.year}" --exiftool --update --verbose

+
+
+
+
+

Example uses of the package

+
""" Simple usage of the package """
+import osxphotos
+
+def main():
+    photosdb = osxphotos.PhotosDB()
+    print(photosdb.keywords)
+    print(photosdb.persons)
+    print(photosdb.album_names)
+
+    print(photosdb.keywords_as_dict)
+    print(photosdb.persons_as_dict)
+    print(photosdb.albums_as_dict)
+
+    # find all photos with Keyword = Foo and containing John Smith
+    photos = photosdb.photos(keywords=["Foo"],persons=["John Smith"])
+
+    # find all photos that include Alice Smith but do not contain the keyword Bar
+    photos = [p for p in photosdb.photos(persons=["Alice Smith"])
+                if p not in photosdb.photos(keywords=["Bar"]) ]
+    for p in photos:
+        print(
+            p.uuid,
+            p.filename,
+            p.original_filename,
+            p.date,
+            p.description,
+            p.title,
+            p.keywords,
+            p.albums,
+            p.persons,
+            p.path,
+        )
+
+if __name__ == "__main__":
+    main()
+
+
+
""" Export all photos to specified directory using album names as folders
+    If file has been edited, also export the edited version,
+    otherwise, export the original version
+    This will result in duplicate photos if photo is in more than album """
+
+import os.path
+import pathlib
+import sys
+
+import click
+from pathvalidate import is_valid_filepath, sanitize_filepath
+
+import osxphotos
+
+
+@click.command()
+@click.argument("export_path", type=click.Path(exists=True))
+@click.option(
+    "--default-album",
+    help="Default folder for photos with no album. Defaults to 'unfiled'",
+    default="unfiled",
+)
+@click.option(
+    "--library-path",
+    help="Path to Photos library, default to last used library",
+    default=None,
+)
+def export(export_path, default_album, library_path):
+    export_path = os.path.expanduser(export_path)
+    library_path = os.path.expanduser(library_path) if library_path else None
+
+    if library_path is not None:
+        photosdb = osxphotos.PhotosDB(library_path)
+    else:
+        photosdb = osxphotos.PhotosDB()
+
+    photos = photosdb.photos()
+
+    for p in photos:
+        if not p.ismissing:
+            albums = p.albums
+            if not albums:
+                albums = [default_album]
+            for album in albums:
+                click.echo(f"exporting {p.filename} in album {album}")
+
+                # make sure no invalid characters in destination path (could be in album name)
+                album_name = sanitize_filepath(album, platform="auto")
+
+                # create destination folder, if necessary, based on album name
+                dest_dir = os.path.join(export_path, album_name)
+
+                # verify path is a valid path
+                if not is_valid_filepath(dest_dir, platform="auto"):
+                    sys.exit(f"Invalid filepath {dest_dir}")
+
+                # create destination dir if needed
+                if not os.path.isdir(dest_dir):
+                    os.makedirs(dest_dir)
+
+                # export the photo
+                if p.hasadjustments:
+                    # export edited version
+                    exported = p.export(dest_dir, edited=True)
+                    edited_name = pathlib.Path(p.path_edited).name
+                    click.echo(f"Exported {edited_name} to {exported}")
+                # export unedited version
+                exported = p.export(dest_dir)
+                click.echo(f"Exported {p.filename} to {exported}")
+        else:
+            click.echo(f"Skipping missing photo: {p.filename}")
+
+
+if __name__ == "__main__":
+    export()  # pylint: disable=no-value-for-parameter
+
+
+
+
+

Package Interface

+

Reference full documentation on GitHub

+ +
+
+
+

Indices and tables

+ +
+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/build/html/modules.html b/docs/build/html/modules.html new file mode 100644 index 00000000..cb007e24 --- /dev/null +++ b/docs/build/html/modules.html @@ -0,0 +1,107 @@ + + + + + + + + osxphotos — osxphotos 0.40.4 documentation + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

osxphotos

+
+
+
+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/build/html/objects.inv b/docs/build/html/objects.inv new file mode 100644 index 00000000..35b7e09c Binary files /dev/null and b/docs/build/html/objects.inv differ diff --git a/docs/build/html/reference.html b/docs/build/html/reference.html new file mode 100644 index 00000000..37212656 --- /dev/null +++ b/docs/build/html/reference.html @@ -0,0 +1,1357 @@ + + + + + + + + osxphotos package — osxphotos 0.40.4 documentation + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
+

osxphotos package

+
+

osxphotos module

+
+
+class osxphotos.PhotosDB(dbfile=None, verbose=None, exiftool=None)[source]
+

Processes a Photos.app library database to extract information about photos

+
+
+property album_info
+

return list of AlbumInfo objects for each album in the photos database

+
+ +
+
+property album_info_shared
+

return list of AlbumInfo objects for each shared album in the photos database +only valid for Photos 5; on Photos <= 4, prints warning and returns empty list

+
+ +
+
+property albums
+

return list of albums found in photos database

+
+ +
+
+property albums_as_dict
+

return albums as dict of albums, count in reverse sorted order (descending)

+
+ +
+
+property albums_shared
+

return list of shared albums found in photos database +only valid for Photos 5; on Photos <= 4, prints warning and returns empty list

+
+ +
+
+property albums_shared_as_dict
+

returns shared albums as dict of albums, count in reverse sorted order (descending) +valid only on Photos 5; on Photos <= 4, prints warning and returns empty dict

+
+ +
+
+property db_path
+

returns path to the Photos library database PhotosDB was initialized with

+
+ +
+
+property db_version
+

return the database version as stored in LiGlobals table

+
+ +
+
+property folder_info
+

return list FolderInfo objects representing top-level folders in the photos database

+
+ +
+
+property folders
+

return list of top-level folder names in the photos database

+
+ +
+
+get_db_connection()[source]
+

Get connection to the working copy of the Photos database

+
+
Returns
+

tuple of (connection, cursor) to sqlite3 database

+
+
+
+ +
+
+get_photo(uuid)[source]
+

Returns a single photo matching uuid

+
+
Parameters
+

uuid – the UUID of photo to get

+
+
Returns
+

PhotoInfo instance for photo with UUID matching uuid or None if no match

+
+
+
+ +
+
+property import_info
+

return list of ImportInfo objects for each import session in the database

+
+ +
+
+property keywords
+

return list of keywords found in photos database

+
+ +
+
+property keywords_as_dict
+

return keywords as dict of keyword, count in reverse sorted order (descending)

+
+ +
+
+property labels
+

return list of all search info labels found in the library

+
+ +
+
+property labels_as_dict
+

count in reverse sorted order (descending)

+
+
Type
+

return labels as dict of label

+
+
+
+ +
+
+property labels_normalized
+

return list of all normalized search info labels found in the library

+
+ +
+
+property labels_normalized_as_dict
+

count in reverse sorted order (descending)

+
+
Type
+

return normalized labels as dict of label

+
+
+
+ +
+
+property library_path
+

returns path to the Photos library PhotosDB was initialized with

+
+ +
+
+property person_info
+

return list of PersonInfo objects for each person in the photos database

+
+ +
+
+property persons
+

return list of persons found in photos database

+
+ +
+
+property persons_as_dict
+

return persons as dict of person, count in reverse sorted order (descending)

+
+ +
+
+photos(keywords=None, uuid=None, persons=None, albums=None, images=True, movies=True, from_date=None, to_date=None, intrash=False)[source]
+

Return a list of PhotoInfo objects +If called with no args, returns the entire database of photos +If called with args, returns photos matching the args (e.g. keywords, persons, etc.) +If more than one arg, returns photos matching all the criteria (e.g. keywords AND persons) +If more than one keyword, uuid, persons, albums is passed, they are treated as “OR” criteria +e.g. keywords=[“wedding”,”vacation”] returns photos matching either keyword +from_date and to_date may be either naive or timezone-aware datetime.datetime objects. +If naive, timezone will be assumed to be local timezone.

+
+
Parameters
+
    +
  • keywords – list of keywords to search for

  • +
  • uuid – list of UUIDs to search for

  • +
  • persons – list of persons to search for

  • +
  • albums – list of album names to search for

  • +
  • images – if True, returns image files, if False, does not return images; default is True

  • +
  • movies – if True, returns movie files, if False, does not return movies; default is True

  • +
  • from_date – return photos with creation date >= from_date (datetime.datetime object, default None)

  • +
  • to_date – return photos with creation date <= to_date (datetime.datetime object, default None)

  • +
  • intrash – if True, returns only images in “Recently deleted items” folder, +if False returns only photos that aren’t deleted; default is False

  • +
+
+
Returns
+

list of PhotoInfo objects

+
+
+
+ +
+
+photos_by_uuid(uuids)[source]
+
+
Returns a list of photos with UUID in uuids.

Does not generate error if invalid or missing UUID passed. +This is faster than using PhotosDB.photos if you have list of UUIDs. +Returns photos regardless of intrash state.

+
+
+
+
Parameters
+

uuid – list of UUIDs of photos to get

+
+
Returns
+

list of PhotoInfo instance for photo with UUID matching uuid or [] if no match

+
+
+
+ +
+ +
+
+class osxphotos.PhotoInfo(db=None, uuid=None, info=None)[source]
+

Info about a specific photo, contains all the details about the photo +including keywords, persons, albums, uuid, path, etc.

+
+
+class ExifInfo(flash_fired: bool, iso: int, metering_mode: int, sample_rate: int, track_format: int, white_balance: int, aperture: float, bit_rate: float, duration: float, exposure_bias: float, focal_length: float, fps: float, latitude: float, longitude: float, shutter_speed: float, camera_make: str, camera_model: str, codec: str, lens_model: str)
+

EXIF info associated with a photo from the Photos library

+
+
+aperture: float
+
+ +
+
+bit_rate: float
+
+ +
+
+camera_make: str
+
+ +
+
+camera_model: str
+
+ +
+
+codec: str
+
+ +
+
+duration: float
+
+ +
+
+exposure_bias: float
+
+ +
+
+flash_fired: bool
+
+ +
+
+focal_length: float
+
+ +
+
+fps: float
+
+ +
+
+iso: int
+
+ +
+
+latitude: float
+
+ +
+
+lens_model: str
+
+ +
+
+longitude: float
+
+ +
+
+metering_mode: int
+
+ +
+
+sample_rate: int
+
+ +
+
+shutter_speed: float
+
+ +
+
+track_format: int
+
+ +
+
+white_balance: int
+
+ +
+ +
+
+class ExportResults(exported=None, new=None, updated=None, skipped=None, exif_updated=None, touched=None, converted_to_jpeg=None, sidecar_json_written=None, sidecar_json_skipped=None, sidecar_exiftool_written=None, sidecar_exiftool_skipped=None, sidecar_xmp_written=None, sidecar_xmp_skipped=None, missing=None, error=None, exiftool_warning=None, exiftool_error=None, xattr_written=None, xattr_skipped=None)
+

holds export results for export2

+
+
+all_files()
+

return all filenames contained in results

+
+ +
+ +
+
+class ScoreInfo(overall: float, curation: float, promotion: float, highlight_visibility: float, behavioral: float, failure: float, harmonious_color: float, immersiveness: float, interaction: float, interesting_subject: float, intrusive_object_presence: float, lively_color: float, low_light: float, noise: float, pleasant_camera_tilt: float, pleasant_composition: float, pleasant_lighting: float, pleasant_pattern: float, pleasant_perspective: float, pleasant_post_processing: float, pleasant_reflection: float, pleasant_symmetry: float, sharply_focused_subject: float, tastefully_blurred: float, well_chosen_subject: float, well_framed_subject: float, well_timed_shot: float)
+

Computed photo score info associated with a photo from the Photos library

+
+
+behavioral: float
+
+ +
+
+curation: float
+
+ +
+
+failure: float
+
+ +
+
+harmonious_color: float
+
+ +
+
+highlight_visibility: float
+
+ +
+
+immersiveness: float
+
+ +
+
+interaction: float
+
+ +
+
+interesting_subject: float
+
+ +
+
+intrusive_object_presence: float
+
+ +
+
+lively_color: float
+
+ +
+
+low_light: float
+
+ +
+
+noise: float
+
+ +
+
+overall: float
+
+ +
+
+pleasant_camera_tilt: float
+
+ +
+
+pleasant_composition: float
+
+ +
+
+pleasant_lighting: float
+
+ +
+
+pleasant_pattern: float
+
+ +
+
+pleasant_perspective: float
+
+ +
+
+pleasant_post_processing: float
+
+ +
+
+pleasant_reflection: float
+
+ +
+
+pleasant_symmetry: float
+
+ +
+
+promotion: float
+
+ +
+
+sharply_focused_subject: float
+
+ +
+
+tastefully_blurred: float
+
+ +
+
+well_chosen_subject: float
+
+ +
+
+well_framed_subject: float
+
+ +
+
+well_timed_shot: float
+
+ +
+ +
+
+class SearchInfo(photo, normalized=False)
+

Info about search terms such as machine learning labels that Photos knows about a photo

+
+
+property activities
+

returns list of activity names

+
+ +
+
+property all
+

return all search info properties in a single list

+
+ +
+
+asdict()
+

return dict of search info

+
+ +
+
+property bodies_of_water
+

returns list of body of water names

+
+ +
+
+property city
+

returns city/town

+
+ +
+
+property country
+

returns country name

+
+ +
+
+property holidays
+

returns list of holiday names

+
+ +
+
+property labels
+

return list of labels associated with Photo

+
+ +
+
+property locality_names
+

returns list of other locality names

+
+ +
+
+property media_types
+

returns list of media types (photo, video, panorama, etc)

+
+ +
+
+property month
+

returns month name

+
+ +
+
+property neighborhoods
+

returns list of neighborhoods

+
+ +
+
+property place_names
+

returns list of place names

+
+ +
+
+property season
+

returns season name

+
+ +
+
+property state
+

returns state name

+
+ +
+
+property state_abbreviation
+

returns state abbreviation

+
+ +
+
+property streets
+

returns list of street names

+
+ +
+
+property venue_types
+

returns list of venue types

+
+ +
+
+property venues
+

returns list of venue names

+
+ +
+
+property year
+

returns year

+
+ +
+ +
+
+property album_info
+

list of AlbumInfo objects representing albums the photos is contained in

+
+ +
+
+property albums
+

list of albums picture is contained in

+
+ +
+
+asdict()[source]
+

return dict representation

+
+ +
+
+property burst
+

Returns True if photo is part of a Burst photo set, otherwise False

+
+ +
+
+property burst_photos
+

If photo is a burst photo, returns list of PhotoInfo objects +that are part of the same burst photo set; otherwise returns empty list. +self is not included in the returned list

+
+ +
+
+property comments
+

Returns list of Comment objects for any comments on the photo (sorted by date)

+
+ +
+
+property date
+

image creation date as timezone aware datetime object

+
+ +
+
+property date_modified
+

image modification date as timezone aware datetime object +or None if no modification date set

+
+ +
+
+property date_trashed
+

Date asset was placed in the trash or None

+
+ +
+
+property description
+

long / extended description of picture

+
+ +
+
+property exif_info
+

Returns an ExifInfo object with the EXIF data for photo +Note: the returned EXIF data is the data Photos stores in the database on import; +ExifInfo does not provide access to the EXIF info in the actual image file +Some or all of the fields may be None +Only valid for Photos 5; on earlier database returns None

+
+ +
+
+property exiftool
+

Returns an ExifTool object for the photo +requires that exiftool (https://exiftool.org/) be installed +If exiftool not installed, logs warning and returns None +If photo path is missing, returns None

+
+ +
+
+export(dest, *filename, edited=False, live_photo=False, raw_photo=False, export_as_hardlink=False, overwrite=False, increment=True, sidecar_json=False, sidecar_exiftool=False, sidecar_xmp=False, use_photos_export=False, timeout=120, exiftool=False, use_albums_as_keywords=False, use_persons_as_keywords=False, keyword_template=None, description_template=None)
+

export photo +dest: must be valid destination path (or exception raised) +filename: (optional): name of exported picture; if not provided, will use current filename

+
+

NOTE: if provided, user must ensure file extension (suffix) is correct. +For example, if photo is .CR2 file, edited image may be .jpeg. +If you provide an extension different than what the actual file is, +export will print a warning but will export the photo using the +incorrect file extension (unless use_photos_export is true, in which case export will +use the extension provided by Photos upon export; in this case, an incorrect extension is +silently ignored). +e.g. to get the extension of the edited photo, +reference PhotoInfo.path_edited

+
+
+
edited: (boolean, default=False); if True will export the edited version of the photo

(or raise exception if no edited version)

+
+
+

live_photo: (boolean, default=False); if True, will also export the associted .mov for live photos +raw_photo: (boolean, default=False); if True, will also export the associted RAW photo +export_as_hardlink: (boolean, default=False); if True, will hardlink files instead of copying them +overwrite: (boolean, default=False); if True will overwrite files if they alreay exist +increment: (boolean, default=True); if True, will increment file name until a non-existant name is found

+
+

if overwrite=False and increment=False, export will fail if destination file already exists

+
+
+
sidecar_json: if set will write a json sidecar with data in format readable by exiftool

sidecar filename will be dest/filename.json; includes exiftool tag group names (e.g. exiftool -G -j)

+
+
sidecar_exiftool: if set will write a json sidecar with data in format readable by exiftool

sidecar filename will be dest/filename.json; does not include exiftool tag group names (e.g. exiftool -j)

+
+
sidecar_xmp: if set will write an XMP sidecar with IPTC data

sidecar filename will be dest/filename.xmp

+
+
+

use_photos_export: (boolean, default=False); if True will attempt to export photo via applescript interaction with Photos +timeout: (int, default=120) timeout in seconds used with use_photos_export +exiftool: (boolean, default = False); if True, will use exiftool to write metadata to export file +returns list of full paths to the exported files +use_albums_as_keywords: (boolean, default = False); if True, will include album names in keywords +when exporting metadata with exiftool or sidecar +use_persons_as_keywords: (boolean, default = False); if True, will include person names in keywords +when exporting metadata with exiftool or sidecar +keyword_template: (list of strings); list of template strings that will be rendered as used as keywords +description_template: string; optional template string that will be rendered for use as photo description

+

Returns: list of photos exported

+
+ +
+
+export2(dest, *filename, edited=False, live_photo=False, raw_photo=False, export_as_hardlink=False, overwrite=False, increment=True, sidecar=0, sidecar_drop_ext=False, use_photos_export=False, timeout=120, exiftool=False, use_albums_as_keywords=False, use_persons_as_keywords=False, keyword_template=None, description_template=None, update=False, ignore_signature=False, export_db=None, fileutil=<class 'osxphotos.fileutil.FileUtil'>, dry_run=False, touch_file=False, convert_to_jpeg=False, jpeg_quality=1.0, ignore_date_modified=False, use_photokit=False, verbose=None, exiftool_flags=None, merge_exif_keywords=False, merge_exif_persons=False, jpeg_ext=None)
+

export photo, like export but with update and dry_run options +dest: must be valid destination path or exception raised +filename: (optional): name of exported picture; if not provided, will use current filename

+
+

NOTE: if provided, user must ensure file extension (suffix) is correct. +For example, if photo is .CR2 file, edited image may be .jpeg. +If you provide an extension different than what the actual file is, +will export the photo using the incorrect file extension (unless use_photos_export is true, +in which case export will use the extension provided by Photos upon export. +e.g. to get the extension of the edited photo, +reference PhotoInfo.path_edited

+
+
+
edited: (boolean, default=False); if True will export the edited version of the photo

(or raise exception if no edited version)

+
+
+

live_photo: (boolean, default=False); if True, will also export the associted .mov for live photos +raw_photo: (boolean, default=False); if True, will also export the associted RAW photo +export_as_hardlink: (boolean, default=False); if True, will hardlink files instead of copying them +overwrite: (boolean, default=False); if True will overwrite files if they alreay exist +increment: (boolean, default=True); if True, will increment file name until a non-existant name is found

+
+

if overwrite=False and increment=False, export will fail if destination file already exists

+
+
+
sidecar: bit field: set to one or more of SIDECAR_XMP, SIDECAR_JSON, SIDECAR_EXIFTOOL
+
SIDECAR_JSON: if set will write a json sidecar with data in format readable by exiftool

sidecar filename will be dest/filename.json; includes exiftool tag group names (e.g. exiftool -G -j)

+
+
SIDECAR_EXIFTOOL: if set will write a json sidecar with data in format readable by exiftool

sidecar filename will be dest/filename.json; does not include exiftool tag group names (e.g. exiftool -j)

+
+
SIDECAR_XMP: if set will write an XMP sidecar with IPTC data

sidecar filename will be dest/filename.xmp

+
+
+
+
+

sidecar_drop_ext: (boolean, default=False); if True, drops the photo’s extension from sidecar filename (e.g. ‘IMG_1234.json’ instead of ‘IMG_1234.JPG.json’) +use_photos_export: (boolean, default=False); if True will attempt to export photo via applescript interaction with Photos +timeout: (int, default=120) timeout in seconds used with use_photos_export +exiftool: (boolean, default = False); if True, will use exiftool to write metadata to export file +use_albums_as_keywords: (boolean, default = False); if True, will include album names in keywords +when exporting metadata with exiftool or sidecar +use_persons_as_keywords: (boolean, default = False); if True, will include person names in keywords +when exporting metadata with exiftool or sidecar +keyword_template: (list of strings); list of template strings that will be rendered as used as keywords +description_template: string; optional template string that will be rendered for use as photo description +update: (boolean, default=False); if True export will run in update mode, that is, it will

+
+

not export the photo if the current version already exists in the destination

+
+

ignore_signature: (bool, default=False), ignore file signature when used with update (look only at filename) +export_db: (ExportDB_ABC); instance of a class that conforms to ExportDB_ABC with methods

+
+

for getting/setting data related to exported files to compare update state

+
+

fileutil: (FileUtilABC); class that conforms to FileUtilABC with various file utilities +dry_run: (boolean, default=False); set to True to run in “dry run” mode +touch_file: (boolean, default=False); if True, sets file’s modification time upon photo date +convert_to_jpeg: boolean; if True, converts non-jpeg images to jpeg +jpeg_quality: float in range 0.0 <= jpeg_quality <= 1.0. A value of 1.0 specifies use best quality, a value of 0.0 specifies use maximum compression. +ignore_date_modified: for use with sidecar and exiftool; if True, sets EXIF:ModifyDate to EXIF:DateTimeOriginal even if date_modified is set +verbose: optional callable function to use for printing verbose text during processing; if None (default), does not print output. +exiftool_flags: optional list of flags to pass to exiftool when using exiftool option, e.g [“-m”, “-F”] +merge_exif_keywords: boolean; if True, merged keywords found in file’s exif data (requires exiftool) +merge_exif_persons: boolean; if True, merged persons found in file’s exif data (requires exiftool) +jpeg_ext: if set, will use this value for extension on jpegs converted to jpeg with convert_to_jpeg; if not set, uses jpeg; do not include the leading “.”

+
+
Returns: ExportResults class

ExportResults has attributes: +“exported”, +“new”, +“updated”, +“skipped”, +“exif_updated”, +“touched”, +“converted_to_jpeg”, +“sidecar_json_written”, +“sidecar_json_skipped”, +“sidecar_exiftool_written”, +“sidecar_exiftool_skipped”, +“sidecar_xmp_written”, +“sidecar_xmp_skipped”, +“missing”, +“error”, +“error_str”, +“exiftool_warning”, +“exiftool_error”,

+
+
Note: to use dry run mode, you must set dry_run=True and also pass in memory version of export_db,

and no-op fileutil (e.g. ExportDBInMemory and FileUtilNoOp)

+
+
+
+ +
+
+property external_edit
+

Returns True if picture was edited outside of Photos using external editor

+
+ +
+
+property face_info
+

list of FaceInfo objects for faces in picture

+
+ +
+
+property favorite
+

True if picture is marked as favorite

+
+ +
+
+property filename
+

filename of the picture

+
+ +
+
+property has_raw
+

returns True if photo has an associated raw image (that is, it’s a RAW+JPEG pair), otherwise False

+
+ +
+
+property hasadjustments
+

True if picture has adjustments / edits

+
+ +
+
+property hdr
+

Returns True if photo is an HDR photo, otherwise False

+
+ +
+
+property height
+

returns height of the current photo version in pixels

+
+ +
+
+property hidden
+

True if picture is hidden

+
+ +
+
+property import_info
+

ImportInfo object representing import session for the photo or None if no import session

+
+ +
+
+property incloud
+

Returns True if photo is cloud asset and is synched to cloud +False if photo is cloud asset and not yet synched to cloud +None if photo is not cloud asset

+
+ +
+
+property intrash
+

True if picture is in trash (‘Recently Deleted’ folder)

+
+ +
+
+property iscloudasset
+

Returns True if photo is a cloud asset (in an iCloud library), +otherwise False

+
+ +
+
+property ismissing
+

returns true if photo is missing from disk (which means it’s not been downloaded from iCloud) +NOTE: the photos.db database uses an asynchrounous write-ahead log so changes in Photos

+
+

do not immediately get written to disk. In particular, I’ve noticed that downloading +an image from the cloud does not force the database to be updated until something else +e.g. an edit, keyword, etc. occurs forcing a database synch +The exact process / timing is a mystery to be but be aware that if some photos were recently +downloaded from cloud to local storate their status in the database might still show +isMissing = 1

+
+
+ +
+
+property ismovie
+

Returns True if file is a movie, otherwise False

+
+ +
+
+property isphoto
+

Returns True if file is an image, otherwise False

+
+ +
+
+property israw
+

returns True if photo is a raw image. For images with an associated RAW+JPEG pair, see has_raw

+
+ +
+
+property isreference
+

Returns True if photo is a reference (not copied to the Photos library), otherwise False

+
+ +
+
+json()[source]
+

Return JSON representation

+
+ +
+
+property keywords
+

list of keywords for picture

+
+ +
+
+property labels
+

returns list of labels applied to photo by Photos image categorization +only valid on Photos 5, on older libraries returns empty list

+
+ +
+
+property labels_normalized
+

returns normalized list of labels applied to photo by Photos image categorization +only valid on Photos 5, on older libraries returns empty list

+
+ +
+
+property likes
+

Returns list of Like objects for any likes on the photo (sorted by date)

+
+ +
+
+property live_photo
+

Returns True if photo is a live photo, otherwise False

+
+ +
+
+property location
+

returns (latitude, longitude) as float in degrees or None

+
+ +
+
+property orientation
+

returns EXIF orientation of the current photo version as int

+
+ +
+
+property original_filename
+

original filename of the picture +Photos 5 mangles filenames upon import

+
+ +
+
+property original_filesize
+

returns filesize of original photo in bytes as int

+
+ +
+
+property original_height
+

returns height of the original photo version in pixels

+
+ +
+
+property original_orientation
+

returns EXIF orientation of the original photo version as int

+
+ +
+
+property original_width
+

returns width of the original photo version in pixels

+
+ +
+
+property panorama
+

Returns True if photo is a panorama, otherwise False

+
+ +
+
+property path
+

absolute path on disk of the original picture

+
+ +
+
+property path_edited
+

absolute path on disk of the edited picture

+
+ +
+
+property path_live_photo
+

Returns path to the associated video file for a live photo +If photo is not a live photo, returns None +If photo is missing, returns None

+
+ +
+
+property path_raw
+

absolute path of associated RAW image or None if there is not one

+
+ +
+
+property person_info
+

list of PersonInfo objects for person in picture

+
+ +
+
+property persons
+

list of persons in picture

+
+ +
+
+property place
+

Returns PlaceInfo object containing reverse geolocation info

+
+ +
+
+property portrait
+

Returns True if photo is a portrait, otherwise False

+
+ +
+
+property raw_original
+

returns True if associated raw image and the raw image is selected in Photos +via “Use RAW as Original ” +otherwise returns False

+
+ +
+
+render_template(template_str, none_str='_', path_sep=None, expand_inplace=False, inplace_sep=None, filename=False, dirname=False, strip=False)[source]
+

Renders a template string for PhotoInfo instance using PhotoTemplate

+
+
Parameters
+
    +
  • template_str – a template string with fields to render

  • +
  • none_str – a str to use if template field renders to None, default is “_”.

  • +
  • path_sep – a single character str to use as path separator when joining +fields like folder_album; if not provided, defaults to os.path.sep

  • +
  • expand_inplace – expand multi-valued substitutions in-place as a single string +instead of returning individual strings

  • +
  • inplace_sep – optional string to use as separator between multi-valued keywords +with expand_inplace; default is ‘,’

  • +
  • filename – if True, template output will be sanitized to produce valid file name

  • +
  • dirname – if True, template output will be sanitized to produce valid directory name

  • +
  • strip – if True, strips leading/trailing white space from resulting template

  • +
+
+
Returns
+

tuple of list of rendered strings and list of unmatched template values

+
+
Return type
+

([rendered_strings], [unmatched])

+
+
+
+ +
+
+property score
+

Computed score information for a photo

+
+
Returns
+

ScoreInfo instance

+
+
+
+ +
+
+property screenshot
+

Returns True if photo is an HDR photo, otherwise False

+
+ +
+
+property search_info
+

returns SearchInfo object for photo +only valid on Photos 5, on older libraries, returns None

+
+ +
+
+property search_info_normalized
+

returns SearchInfo object for photo that produces normalized results +only valid on Photos 5, on older libraries, returns None

+
+ +
+
+property selfie
+

Returns True if photo is a selfie (front facing camera), otherwise False

+
+ +
+
+property shared
+

returns True if photos is in a shared iCloud album otherwise false +Only valid on Photos 5; returns None on older versions

+
+ +
+
+property slow_mo
+

Returns True if photo is a slow motion video, otherwise False

+
+ +
+
+property time_lapse
+

Returns True if photo is a time lapse video, otherwise False

+
+ +
+
+property title
+

name / title of picture

+
+ +
+
+property tzoffset
+

timezone offset from UTC in seconds

+
+ +
+
+property uti
+

Returns Uniform Type Identifier (UTI) for the image +for example: public.jpeg or com.apple.quicktime-movie

+
+ +
+
+property uti_edited
+

Returns Uniform Type Identifier (UTI) for the edited image +if the photo has been edited, otherwise None; +for example: public.jpeg

+
+ +
+
+property uti_original
+

Returns Uniform Type Identifier (UTI) for the original image +for example: public.jpeg or com.apple.quicktime-movie

+
+ +
+
+property uti_raw
+

Returns Uniform Type Identifier (UTI) for the RAW image if there is one +for example: com.canon.cr2-raw-image +Returns None if no associated RAW image

+
+ +
+
+property uuid
+

UUID of picture

+
+ +
+
+property visible
+

True if picture is visble

+
+ +
+
+property width
+

returns width of the current photo version in pixels

+
+ +
+ +
+
+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/build/html/search.html b/docs/build/html/search.html new file mode 100644 index 00000000..39c1eec5 --- /dev/null +++ b/docs/build/html/search.html @@ -0,0 +1,114 @@ + + + + + + + + Search — osxphotos 0.40.4 documentation + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Search

+
+ +

+ Please activate JavaScript to enable the search + functionality. +

+
+

+ Searching for multiple words only shows matches that contain + all words. +

+
+ + + +
+ +
+ +
+ +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/build/html/searchindex.js b/docs/build/html/searchindex.js new file mode 100644 index 00000000..4bc49183 --- /dev/null +++ b/docs/build/html/searchindex.js @@ -0,0 +1 @@ +Search.setIndex({docnames:["cli","index","modules","reference"],envversion:{"sphinx.domains.c":2,"sphinx.domains.changeset":1,"sphinx.domains.citation":1,"sphinx.domains.cpp":3,"sphinx.domains.index":1,"sphinx.domains.javascript":2,"sphinx.domains.math":2,"sphinx.domains.python":2,"sphinx.domains.rst":2,"sphinx.domains.std":1,"sphinx.ext.intersphinx":1,"sphinx.ext.viewcode":1,sphinx:56},filenames:["cli.rst","index.rst","modules.rst","reference.rst"],objects:{"osxphotos-albums":{"--db":[0,3,1,"cmdoption-osxphotos-albums-db"],"--json":[0,3,1,"cmdoption-osxphotos-albums-json"],PHOTOS_LIBRARY:[0,3,1,"cmdoption-osxphotos-albums-arg-PHOTOS_LIBRARY"]},"osxphotos-dump":{"--db":[0,3,1,"cmdoption-osxphotos-dump-db"],"--deleted":[0,3,1,"cmdoption-osxphotos-dump-deleted"],"--deleted-only":[0,3,1,"cmdoption-osxphotos-dump-deleted-only"],"--json":[0,3,1,"cmdoption-osxphotos-dump-json"],PHOTOS_LIBRARY:[0,3,1,"cmdoption-osxphotos-dump-arg-PHOTOS_LIBRARY"]},"osxphotos-export":{"--album":[0,3,1,"cmdoption-osxphotos-export-album"],"--album-keyword":[0,3,1,"cmdoption-osxphotos-export-album-keyword"],"--burst":[0,3,1,"cmdoption-osxphotos-export-burst"],"--cleanup":[0,3,1,"cmdoption-osxphotos-export-cleanup"],"--convert-to-jpeg":[0,3,1,"cmdoption-osxphotos-export-convert-to-jpeg"],"--current-name":[0,3,1,"cmdoption-osxphotos-export-current-name"],"--db":[0,3,1,"cmdoption-osxphotos-export-db"],"--deleted":[0,3,1,"cmdoption-osxphotos-export-deleted"],"--deleted-only":[0,3,1,"cmdoption-osxphotos-export-deleted-only"],"--description":[0,3,1,"cmdoption-osxphotos-export-description"],"--description-template":[0,3,1,"cmdoption-osxphotos-export-description-template"],"--directory":[0,3,1,"cmdoption-osxphotos-export-directory"],"--download-missing":[0,3,1,"cmdoption-osxphotos-export-download-missing"],"--dry-run":[0,3,1,"cmdoption-osxphotos-export-dry-run"],"--edited":[0,3,1,"cmdoption-osxphotos-export-edited"],"--edited-suffix":[0,3,1,"cmdoption-osxphotos-export-edited-suffix"],"--exiftool":[0,3,1,"cmdoption-osxphotos-export-exiftool"],"--exiftool-merge-keywords":[0,3,1,"cmdoption-osxphotos-export-exiftool-merge-keywords"],"--exiftool-merge-persons":[0,3,1,"cmdoption-osxphotos-export-exiftool-merge-persons"],"--exiftool-option":[0,3,1,"cmdoption-osxphotos-export-exiftool-option"],"--exiftool-path":[0,3,1,"cmdoption-osxphotos-export-exiftool-path"],"--export-as-hardlink":[0,3,1,"cmdoption-osxphotos-export-export-as-hardlink"],"--export-by-date":[0,3,1,"cmdoption-osxphotos-export-export-by-date"],"--exportdb":[0,3,1,"cmdoption-osxphotos-export-exportdb"],"--external-edit":[0,3,1,"cmdoption-osxphotos-export-external-edit"],"--favorite":[0,3,1,"cmdoption-osxphotos-export-favorite"],"--filename":[0,3,1,"cmdoption-osxphotos-export-filename"],"--finder-tag-keywords":[0,3,1,"cmdoption-osxphotos-export-finder-tag-keywords"],"--finder-tag-template":[0,3,1,"cmdoption-osxphotos-export-finder-tag-template"],"--folder":[0,3,1,"cmdoption-osxphotos-export-folder"],"--from-date":[0,3,1,"cmdoption-osxphotos-export-from-date"],"--has-comment":[0,3,1,"cmdoption-osxphotos-export-has-comment"],"--has-likes":[0,3,1,"cmdoption-osxphotos-export-has-likes"],"--has-raw":[0,3,1,"cmdoption-osxphotos-export-has-raw"],"--hdr":[0,3,1,"cmdoption-osxphotos-export-hdr"],"--hidden":[0,3,1,"cmdoption-osxphotos-export-hidden"],"--ignore-case":[0,3,1,"cmdoption-osxphotos-export-i"],"--ignore-date-modified":[0,3,1,"cmdoption-osxphotos-export-ignore-date-modified"],"--ignore-signature":[0,3,1,"cmdoption-osxphotos-export-ignore-signature"],"--is-reference":[0,3,1,"cmdoption-osxphotos-export-is-reference"],"--jpeg-ext":[0,3,1,"cmdoption-osxphotos-export-jpeg-ext"],"--jpeg-quality":[0,3,1,"cmdoption-osxphotos-export-jpeg-quality"],"--keyword":[0,3,1,"cmdoption-osxphotos-export-keyword"],"--keyword-template":[0,3,1,"cmdoption-osxphotos-export-keyword-template"],"--label":[0,3,1,"cmdoption-osxphotos-export-label"],"--live":[0,3,1,"cmdoption-osxphotos-export-live"],"--load-config":[0,3,1,"cmdoption-osxphotos-export-load-config"],"--missing":[0,3,1,"cmdoption-osxphotos-export-missing"],"--no-comment":[0,3,1,"cmdoption-osxphotos-export-no-comment"],"--no-description":[0,3,1,"cmdoption-osxphotos-export-no-description"],"--no-likes":[0,3,1,"cmdoption-osxphotos-export-no-likes"],"--no-place":[0,3,1,"cmdoption-osxphotos-export-no-place"],"--no-title":[0,3,1,"cmdoption-osxphotos-export-no-title"],"--not-burst":[0,3,1,"cmdoption-osxphotos-export-not-burst"],"--not-favorite":[0,3,1,"cmdoption-osxphotos-export-not-favorite"],"--not-hdr":[0,3,1,"cmdoption-osxphotos-export-not-hdr"],"--not-hidden":[0,3,1,"cmdoption-osxphotos-export-not-hidden"],"--not-live":[0,3,1,"cmdoption-osxphotos-export-not-live"],"--not-panorama":[0,3,1,"cmdoption-osxphotos-export-not-panorama"],"--not-portrait":[0,3,1,"cmdoption-osxphotos-export-not-portrait"],"--not-screenshot":[0,3,1,"cmdoption-osxphotos-export-not-screenshot"],"--not-selfie":[0,3,1,"cmdoption-osxphotos-export-not-selfie"],"--not-shared":[0,3,1,"cmdoption-osxphotos-export-not-shared"],"--not-slow-mo":[0,3,1,"cmdoption-osxphotos-export-not-slow-mo"],"--not-time-lapse":[0,3,1,"cmdoption-osxphotos-export-not-time-lapse"],"--only-movies":[0,3,1,"cmdoption-osxphotos-export-only-movies"],"--only-photos":[0,3,1,"cmdoption-osxphotos-export-only-photos"],"--original-suffix":[0,3,1,"cmdoption-osxphotos-export-original-suffix"],"--overwrite":[0,3,1,"cmdoption-osxphotos-export-overwrite"],"--panorama":[0,3,1,"cmdoption-osxphotos-export-panorama"],"--person":[0,3,1,"cmdoption-osxphotos-export-person"],"--person-keyword":[0,3,1,"cmdoption-osxphotos-export-person-keyword"],"--place":[0,3,1,"cmdoption-osxphotos-export-place"],"--portrait":[0,3,1,"cmdoption-osxphotos-export-portrait"],"--report":[0,3,1,"cmdoption-osxphotos-export-report"],"--save-config":[0,3,1,"cmdoption-osxphotos-export-save-config"],"--screenshot":[0,3,1,"cmdoption-osxphotos-export-screenshot"],"--selfie":[0,3,1,"cmdoption-osxphotos-export-selfie"],"--shared":[0,3,1,"cmdoption-osxphotos-export-shared"],"--sidecar":[0,3,1,"cmdoption-osxphotos-export-sidecar"],"--sidecar-drop-ext":[0,3,1,"cmdoption-osxphotos-export-sidecar-drop-ext"],"--skip-bursts":[0,3,1,"cmdoption-osxphotos-export-skip-bursts"],"--skip-edited":[0,3,1,"cmdoption-osxphotos-export-skip-edited"],"--skip-live":[0,3,1,"cmdoption-osxphotos-export-skip-live"],"--skip-original-if-edited":[0,3,1,"cmdoption-osxphotos-export-skip-original-if-edited"],"--skip-raw":[0,3,1,"cmdoption-osxphotos-export-skip-raw"],"--slow-mo":[0,3,1,"cmdoption-osxphotos-export-slow-mo"],"--strip":[0,3,1,"cmdoption-osxphotos-export-strip"],"--time-lapse":[0,3,1,"cmdoption-osxphotos-export-time-lapse"],"--title":[0,3,1,"cmdoption-osxphotos-export-title"],"--to-date":[0,3,1,"cmdoption-osxphotos-export-to-date"],"--touch-file":[0,3,1,"cmdoption-osxphotos-export-touch-file"],"--update":[0,3,1,"cmdoption-osxphotos-export-update"],"--use-photokit":[0,3,1,"cmdoption-osxphotos-export-use-photokit"],"--use-photos-export":[0,3,1,"cmdoption-osxphotos-export-use-photos-export"],"--uti":[0,3,1,"cmdoption-osxphotos-export-uti"],"--uuid":[0,3,1,"cmdoption-osxphotos-export-uuid"],"--uuid-from-file":[0,3,1,"cmdoption-osxphotos-export-uuid-from-file"],"--verbose":[0,3,1,"cmdoption-osxphotos-export-V"],"--xattr-template":[0,3,1,"cmdoption-osxphotos-export-xattr-template"],"-V":[0,3,1,"cmdoption-osxphotos-export-V"],"-i":[0,3,1,"cmdoption-osxphotos-export-i"],DEST:[0,3,1,"cmdoption-osxphotos-export-arg-DEST"],PHOTOS_LIBRARY:[0,3,1,"cmdoption-osxphotos-export-arg-PHOTOS_LIBRARY"]},"osxphotos-help":{TOPIC:[0,3,1,"cmdoption-osxphotos-help-arg-TOPIC"]},"osxphotos-info":{"--db":[0,3,1,"cmdoption-osxphotos-info-db"],"--json":[0,3,1,"cmdoption-osxphotos-info-json"],PHOTOS_LIBRARY:[0,3,1,"cmdoption-osxphotos-info-arg-PHOTOS_LIBRARY"]},"osxphotos-keywords":{"--db":[0,3,1,"cmdoption-osxphotos-keywords-db"],"--json":[0,3,1,"cmdoption-osxphotos-keywords-json"],PHOTOS_LIBRARY:[0,3,1,"cmdoption-osxphotos-keywords-arg-PHOTOS_LIBRARY"]},"osxphotos-labels":{"--db":[0,3,1,"cmdoption-osxphotos-labels-db"],"--json":[0,3,1,"cmdoption-osxphotos-labels-json"],PHOTOS_LIBRARY:[0,3,1,"cmdoption-osxphotos-labels-arg-PHOTOS_LIBRARY"]},"osxphotos-list":{"--json":[0,3,1,"cmdoption-osxphotos-list-json"]},"osxphotos-persons":{"--db":[0,3,1,"cmdoption-osxphotos-persons-db"],"--json":[0,3,1,"cmdoption-osxphotos-persons-json"],PHOTOS_LIBRARY:[0,3,1,"cmdoption-osxphotos-persons-arg-PHOTOS_LIBRARY"]},"osxphotos-places":{"--db":[0,3,1,"cmdoption-osxphotos-places-db"],"--json":[0,3,1,"cmdoption-osxphotos-places-json"],PHOTOS_LIBRARY:[0,3,1,"cmdoption-osxphotos-places-arg-PHOTOS_LIBRARY"]},"osxphotos-query":{"--album":[0,3,1,"cmdoption-osxphotos-query-album"],"--burst":[0,3,1,"cmdoption-osxphotos-query-burst"],"--cloudasset":[0,3,1,"cmdoption-osxphotos-query-cloudasset"],"--db":[0,3,1,"cmdoption-osxphotos-query-db"],"--deleted":[0,3,1,"cmdoption-osxphotos-query-deleted"],"--deleted-only":[0,3,1,"cmdoption-osxphotos-query-deleted-only"],"--description":[0,3,1,"cmdoption-osxphotos-query-description"],"--edited":[0,3,1,"cmdoption-osxphotos-query-edited"],"--external-edit":[0,3,1,"cmdoption-osxphotos-query-external-edit"],"--favorite":[0,3,1,"cmdoption-osxphotos-query-favorite"],"--folder":[0,3,1,"cmdoption-osxphotos-query-folder"],"--from-date":[0,3,1,"cmdoption-osxphotos-query-from-date"],"--has-comment":[0,3,1,"cmdoption-osxphotos-query-has-comment"],"--has-likes":[0,3,1,"cmdoption-osxphotos-query-has-likes"],"--has-raw":[0,3,1,"cmdoption-osxphotos-query-has-raw"],"--hdr":[0,3,1,"cmdoption-osxphotos-query-hdr"],"--hidden":[0,3,1,"cmdoption-osxphotos-query-hidden"],"--ignore-case":[0,3,1,"cmdoption-osxphotos-query-i"],"--incloud":[0,3,1,"cmdoption-osxphotos-query-incloud"],"--is-reference":[0,3,1,"cmdoption-osxphotos-query-is-reference"],"--json":[0,3,1,"cmdoption-osxphotos-query-json"],"--keyword":[0,3,1,"cmdoption-osxphotos-query-keyword"],"--label":[0,3,1,"cmdoption-osxphotos-query-label"],"--live":[0,3,1,"cmdoption-osxphotos-query-live"],"--missing":[0,3,1,"cmdoption-osxphotos-query-missing"],"--no-comment":[0,3,1,"cmdoption-osxphotos-query-no-comment"],"--no-description":[0,3,1,"cmdoption-osxphotos-query-no-description"],"--no-likes":[0,3,1,"cmdoption-osxphotos-query-no-likes"],"--no-place":[0,3,1,"cmdoption-osxphotos-query-no-place"],"--no-title":[0,3,1,"cmdoption-osxphotos-query-no-title"],"--not-burst":[0,3,1,"cmdoption-osxphotos-query-not-burst"],"--not-cloudasset":[0,3,1,"cmdoption-osxphotos-query-not-cloudasset"],"--not-favorite":[0,3,1,"cmdoption-osxphotos-query-not-favorite"],"--not-hdr":[0,3,1,"cmdoption-osxphotos-query-not-hdr"],"--not-hidden":[0,3,1,"cmdoption-osxphotos-query-not-hidden"],"--not-incloud":[0,3,1,"cmdoption-osxphotos-query-not-incloud"],"--not-live":[0,3,1,"cmdoption-osxphotos-query-not-live"],"--not-missing":[0,3,1,"cmdoption-osxphotos-query-not-missing"],"--not-panorama":[0,3,1,"cmdoption-osxphotos-query-not-panorama"],"--not-portrait":[0,3,1,"cmdoption-osxphotos-query-not-portrait"],"--not-screenshot":[0,3,1,"cmdoption-osxphotos-query-not-screenshot"],"--not-selfie":[0,3,1,"cmdoption-osxphotos-query-not-selfie"],"--not-shared":[0,3,1,"cmdoption-osxphotos-query-not-shared"],"--not-slow-mo":[0,3,1,"cmdoption-osxphotos-query-not-slow-mo"],"--not-time-lapse":[0,3,1,"cmdoption-osxphotos-query-not-time-lapse"],"--only-movies":[0,3,1,"cmdoption-osxphotos-query-only-movies"],"--only-photos":[0,3,1,"cmdoption-osxphotos-query-only-photos"],"--panorama":[0,3,1,"cmdoption-osxphotos-query-panorama"],"--person":[0,3,1,"cmdoption-osxphotos-query-person"],"--place":[0,3,1,"cmdoption-osxphotos-query-place"],"--portrait":[0,3,1,"cmdoption-osxphotos-query-portrait"],"--screenshot":[0,3,1,"cmdoption-osxphotos-query-screenshot"],"--selfie":[0,3,1,"cmdoption-osxphotos-query-selfie"],"--shared":[0,3,1,"cmdoption-osxphotos-query-shared"],"--slow-mo":[0,3,1,"cmdoption-osxphotos-query-slow-mo"],"--time-lapse":[0,3,1,"cmdoption-osxphotos-query-time-lapse"],"--title":[0,3,1,"cmdoption-osxphotos-query-title"],"--to-date":[0,3,1,"cmdoption-osxphotos-query-to-date"],"--uti":[0,3,1,"cmdoption-osxphotos-query-uti"],"--uuid":[0,3,1,"cmdoption-osxphotos-query-uuid"],"--uuid-from-file":[0,3,1,"cmdoption-osxphotos-query-uuid-from-file"],"-i":[0,3,1,"cmdoption-osxphotos-query-i"],PHOTOS_LIBRARY:[0,3,1,"cmdoption-osxphotos-query-arg-PHOTOS_LIBRARY"]},"osxphotos.PhotoInfo":{"export":[3,2,1,""],ExifInfo:[3,0,1,""],ExportResults:[3,0,1,""],ScoreInfo:[3,0,1,""],SearchInfo:[3,0,1,""],album_info:[3,2,1,""],albums:[3,2,1,""],asdict:[3,2,1,""],burst:[3,2,1,""],burst_photos:[3,2,1,""],comments:[3,2,1,""],date:[3,2,1,""],date_modified:[3,2,1,""],date_trashed:[3,2,1,""],description:[3,2,1,""],exif_info:[3,2,1,""],exiftool:[3,2,1,""],export2:[3,2,1,""],external_edit:[3,2,1,""],face_info:[3,2,1,""],favorite:[3,2,1,""],filename:[3,2,1,""],has_raw:[3,2,1,""],hasadjustments:[3,2,1,""],hdr:[3,2,1,""],height:[3,2,1,""],hidden:[3,2,1,""],import_info:[3,2,1,""],incloud:[3,2,1,""],intrash:[3,2,1,""],iscloudasset:[3,2,1,""],ismissing:[3,2,1,""],ismovie:[3,2,1,""],isphoto:[3,2,1,""],israw:[3,2,1,""],isreference:[3,2,1,""],json:[3,2,1,""],keywords:[3,2,1,""],labels:[3,2,1,""],labels_normalized:[3,2,1,""],likes:[3,2,1,""],live_photo:[3,2,1,""],location:[3,2,1,""],orientation:[3,2,1,""],original_filename:[3,2,1,""],original_filesize:[3,2,1,""],original_height:[3,2,1,""],original_orientation:[3,2,1,""],original_width:[3,2,1,""],panorama:[3,2,1,""],path:[3,2,1,""],path_edited:[3,2,1,""],path_live_photo:[3,2,1,""],path_raw:[3,2,1,""],person_info:[3,2,1,""],persons:[3,2,1,""],place:[3,2,1,""],portrait:[3,2,1,""],raw_original:[3,2,1,""],render_template:[3,2,1,""],score:[3,2,1,""],screenshot:[3,2,1,""],search_info:[3,2,1,""],search_info_normalized:[3,2,1,""],selfie:[3,2,1,""],shared:[3,2,1,""],slow_mo:[3,2,1,""],time_lapse:[3,2,1,""],title:[3,2,1,""],tzoffset:[3,2,1,""],uti:[3,2,1,""],uti_edited:[3,2,1,""],uti_original:[3,2,1,""],uti_raw:[3,2,1,""],uuid:[3,2,1,""],visible:[3,2,1,""],width:[3,2,1,""]},"osxphotos.PhotoInfo.ExifInfo":{aperture:[3,1,1,""],bit_rate:[3,1,1,""],camera_make:[3,1,1,""],camera_model:[3,1,1,""],codec:[3,1,1,""],duration:[3,1,1,""],exposure_bias:[3,1,1,""],flash_fired:[3,1,1,""],focal_length:[3,1,1,""],fps:[3,1,1,""],iso:[3,1,1,""],latitude:[3,1,1,""],lens_model:[3,1,1,""],longitude:[3,1,1,""],metering_mode:[3,1,1,""],sample_rate:[3,1,1,""],shutter_speed:[3,1,1,""],track_format:[3,1,1,""],white_balance:[3,1,1,""]},"osxphotos.PhotoInfo.ExportResults":{all_files:[3,2,1,""]},"osxphotos.PhotoInfo.ScoreInfo":{behavioral:[3,1,1,""],curation:[3,1,1,""],failure:[3,1,1,""],harmonious_color:[3,1,1,""],highlight_visibility:[3,1,1,""],immersiveness:[3,1,1,""],interaction:[3,1,1,""],interesting_subject:[3,1,1,""],intrusive_object_presence:[3,1,1,""],lively_color:[3,1,1,""],low_light:[3,1,1,""],noise:[3,1,1,""],overall:[3,1,1,""],pleasant_camera_tilt:[3,1,1,""],pleasant_composition:[3,1,1,""],pleasant_lighting:[3,1,1,""],pleasant_pattern:[3,1,1,""],pleasant_perspective:[3,1,1,""],pleasant_post_processing:[3,1,1,""],pleasant_reflection:[3,1,1,""],pleasant_symmetry:[3,1,1,""],promotion:[3,1,1,""],sharply_focused_subject:[3,1,1,""],tastefully_blurred:[3,1,1,""],well_chosen_subject:[3,1,1,""],well_framed_subject:[3,1,1,""],well_timed_shot:[3,1,1,""]},"osxphotos.PhotoInfo.SearchInfo":{activities:[3,2,1,""],all:[3,2,1,""],asdict:[3,2,1,""],bodies_of_water:[3,2,1,""],city:[3,2,1,""],country:[3,2,1,""],holidays:[3,2,1,""],labels:[3,2,1,""],locality_names:[3,2,1,""],media_types:[3,2,1,""],month:[3,2,1,""],neighborhoods:[3,2,1,""],place_names:[3,2,1,""],season:[3,2,1,""],state:[3,2,1,""],state_abbreviation:[3,2,1,""],streets:[3,2,1,""],venue_types:[3,2,1,""],venues:[3,2,1,""],year:[3,2,1,""]},"osxphotos.PhotosDB":{album_info:[3,2,1,""],album_info_shared:[3,2,1,""],albums:[3,2,1,""],albums_as_dict:[3,2,1,""],albums_shared:[3,2,1,""],albums_shared_as_dict:[3,2,1,""],db_path:[3,2,1,""],db_version:[3,2,1,""],folder_info:[3,2,1,""],folders:[3,2,1,""],get_db_connection:[3,2,1,""],get_photo:[3,2,1,""],import_info:[3,2,1,""],keywords:[3,2,1,""],keywords_as_dict:[3,2,1,""],labels:[3,2,1,""],labels_as_dict:[3,2,1,""],labels_normalized:[3,2,1,""],labels_normalized_as_dict:[3,2,1,""],library_path:[3,2,1,""],person_info:[3,2,1,""],persons:[3,2,1,""],persons_as_dict:[3,2,1,""],photos:[3,2,1,""],photos_by_uuid:[3,2,1,""]},osxphotos:{"--db":[0,3,1,"cmdoption-osxphotos-db"],"--json":[0,3,1,"cmdoption-osxphotos-json"],"--version":[0,3,1,"cmdoption-osxphotos-v"],"-v":[0,3,1,"cmdoption-osxphotos-v"],PhotoInfo:[3,0,1,""],PhotosDB:[3,0,1,""]}},objnames:{"0":["py","class","Python class"],"1":["py","attribute","Python attribute"],"2":["py","method","Python method"],"3":["std","cmdoption","program option"]},objtypes:{"0":"py:class","1":"py:attribute","2":"py:method","3":"std:cmdoption"},terms:{"120":3,"12t12":0,"1gb":1,"2000":0,"2001":0,"2019":0,"8601":0,"boolean":3,"byte":3,"case":[0,3],"class":3,"default":[0,3],"export":3,"float":3,"function":3,"import":[0,1,3],"int":3,"long":3,"new":[0,1,3],"public":3,"return":3,"true":[1,3],AND:[0,3],For:[0,3],The:[0,1,3],Then:1,These:0,Use:[0,3],__main__:1,__name__:1,_bearbeiten:0,_edit:0,_origin:0,abbrevi:3,abil:1,abl:1,about:[1,3],abov:1,absolut:3,access:3,accord:1,activ:3,actual:[0,3],add:0,added:0,addit:0,adjust:3,adob:0,advanc:1,advantag:0,ahead:3,aka:1,album:3,album_info:3,album_info_shar:3,album_nam:1,albuminfo:3,albums_as_dict:[1,3],albums_shar:3,albums_shared_as_dict:3,alic:1,all:[0,3],all_fil:3,allow:[0,1],alpha:0,alreadi:[0,3],alreai:3,also:[0,1,3],altern:[0,1],ani:[0,1,3],apertur:3,apf:0,app:[0,1,3],append:0,appl:[0,1,3],applescript:[0,3],appli:[0,3],applic:1,aren:[1,3],arg:[0,1,3],argument:[0,1],asdict:3,asset:3,associ:[0,1,3],associt:3,assum:3,asynchroun:3,attempt:[0,1,3],attribut:[0,3],author:0,auto:1,automat:0,awar:3,bar:1,becaus:1,been:[0,1,3],befor:[0,1],behavior:[0,3],below:[0,1],best:[0,3],beta:1,between:3,big:1,bit:3,bit_rat:3,bodi:3,bodies_of_wat:3,bool:3,both:[0,1],brew:1,built:1,burst:[0,3],burst_photo:3,call:[1,3],callabl:3,camera:[0,3],camera_mak:3,camera_model:3,can:[0,1],cannot:0,canon:3,care:1,catalina:1,categor:3,caution:0,chang:[0,3],charact:[1,3],citi:3,classif:[0,1],cleanup:0,cli:1,click:1,clone:[0,1],cloud:3,cloudasset:0,code:1,codec:3,collis:0,com:[1,3],comfort:1,command:[],command_nam:1,comment:[0,3],compar:3,compat:0,complex:0,compon:0,compress:[0,3],comput:3,config:0,conform:3,conjunct:0,connect:[0,3],consist:0,contain:[0,1,3],content:[],convert:[0,3],convert_to_jpeg:3,converted_to_jpeg:3,copi:[0,3],copyright:0,correct:3,correspond:0,could:[0,1],count:3,countri:3,cr2:3,creat:0,created:0,creation:3,creationd:0,criteria:3,csv:0,curat:3,current:[0,3],cursor:3,data:[0,3],databas:[0,1,3],date:[0,3],date_modifi:3,date_trash:3,datecr:0,datetim:3,datetimeorigin:[0,3],db_path:3,db_version:3,dbfile:3,def:1,default_album:1,degre:3,delet:[0,3],desc:0,descend:3,descr:0,describ:1,descript:[0,1,3],description_templ:3,dest:[0,3],dest_dir:1,destin:[1,3],detail:[0,3],dict:3,differ:[0,1,3],digikam:0,dir:1,direct:0,directli:[0,1],directori:[0,3],dirnam:3,disabl:1,disk:[0,3],doc:0,doe:[0,1,3],don:0,download:[0,1,3],drop:[0,3],dry:[0,3],dry_run:3,dump:1,duplic:1,durat:3,dure:3,dynam:0,each:[0,3],earlier:3,easiest:1,easili:1,echo:1,edit:[0,1,3],edited_nam:1,editor:[0,3],either:[0,1,3],els:[1,3],embed:0,empti:3,end:0,ensur:3,entir:3,environ:1,equival:0,error:3,error_str:3,etc:[0,1,3],even:[0,3],exact:3,exampl:[0,3],except:3,execut:1,exif:[0,3],exif_info:3,exif_upd:3,exifinfo:3,exiftool:[0,1,3],exiftool_error:3,exiftool_flag:3,exiftool_path:0,exiftool_pod:0,exiftool_warn:3,exist:[0,1,3],exit:[0,1],expand:3,expand_inplac:3,expandus:1,experiment:0,export2:3,export_as_hardlink:3,export_db:3,export_path:1,exportdb:0,exportdb_abc:3,exportdb_fil:0,exportdbinmemori:3,exportresult:3,exposure_bia:3,ext:0,extend:[0,3],extens:[0,3],extern:[0,3],external_edit:3,extract:3,face:[0,1,3],face_info:3,faceinfo:3,fail:3,failur:3,fals:3,familiar:1,faster:[0,3],favorit:[0,3],featur:0,field:3,file:[0,3],filenam:[0,1,3],filename_origin:0,filepath:1,files:3,fileutil:3,fileutilabc:3,fileutilnoop:3,find:0,finder:0,findercom:0,flag:[0,3],flash_fir:3,flexibl:1,focal_length:3,folder:[0,3],folder_album:[0,3],folder_info:3,folderinfo:3,follow:[0,1],foo:1,forc:[0,3],form:0,format:[0,1,3],found:[0,1,3],fps:3,from:[0,3],from_dat:[0,3],front:[0,3],full:[0,3],gener:3,geoloc:[0,3],get:[1,3],get_db_connect:3,get_photo:3,github:1,give:0,gpscoordin:0,gpslatitud:0,gpslatituderef:0,gpslongitud:0,gpslongituderef:0,gpsposit:0,gpu:0,group:[0,3],had:0,handl:0,happen:0,hardlink:[0,3],harmonious_color:3,has:[0,1,3],has_raw:3,hasadjust:[1,3],have:[0,3],hdr:[0,3],headlin:0,heic:0,height:3,help:1,here:0,hidden:[0,3],high:0,highli:0,highlight_vis:3,hold:3,holidai:3,homebrew:1,how:0,html:0,http:[0,1,3],icloud:[0,3],identifi:[0,3],ignor:[0,3],ignore_date_modifi:3,ignore_signatur:3,imag:[0,1,3],imagedescript:0,img_1234:[0,3],immedi:3,immers:3,implement:0,import_info:3,importinfo:3,incloud:[0,3],includ:[0,1,3],incorrect:3,increment:3,index:1,individu:3,info:[1,3],inform:[0,1,3],initi:3,inplace_sep:3,insensit:0,instal:[0,3],instanc:3,instead:[0,3],instruct:1,interact:[0,1,3],interesting_subject:3,interfac:[],internet:0,intrash:3,intrusive_object_pres:3,invalid:[1,3],iptc:[0,3],is_valid_filepath:1,iscloudasset:3,isdir:1,ismiss:[1,3],ismovi:3,iso:[0,3],isphoto:3,israw:3,isrefer:3,item:[0,3],iterm2:0,john:1,join:[1,3],jpeg:[0,3],jpeg_ext:3,jpeg_qual:[0,3],jpg:[0,3],json:[0,3],just:1,keyword:3,keyword_templ:3,keywords_as_dict:[1,3],know:3,label:3,labels_as_dict:3,labels_norm:3,labels_normalized_as_dict:3,laps:[0,3],larg:1,last:[0,1],later:0,latest:1,latitud:3,lead:[0,3],learn:3,lens_model:3,level:[0,3],librari:[0,3],library_path:[1,3],licens:[0,1],lightroom:0,liglob:3,like:[0,1,3],line:[],list:[1,3],live:[0,3],live_photo:3,lively_color:3,load:0,local:3,locality_nam:3,locat:3,log:3,longitud:3,look:[0,1,3],lot:0,low_light:3,mac:[0,1],machin:[1,3],maco:[0,1],mai:[0,3],main:1,make:1,makedir:1,mangl:3,mani:0,mark:[0,3],match:[0,3],maximum:[0,3],mean:3,media:3,media_typ:[1,3],memori:3,merg:[0,3],merge_exif_keyword:3,merge_exif_person:3,messag:1,metadata:[0,3],metering_mod:3,method:3,microsoft:0,might:3,minor:0,miss:[0,1,3],mode:[0,3],modif:[0,3],modifi:0,modifyd:[0,3],modul:1,month:3,more:[0,1,3],most:0,motion:[0,3],mov:[0,3],movi:[0,3],multi:[0,3],multipl:[0,1],must:[0,3],mysteri:3,naiv:3,name:[0,3],necessari:1,need:1,neighborhood:3,neither:[0,1],nois:3,non:[0,3],none:[1,3],none_str:3,normal:[0,3],note:[0,1,3],notic:3,now:1,object:3,obvious:0,occur:3,offset:3,offsettimeorigin:0,older:3,one:[0,3],onli:[0,3],open:[0,1],option:[0,1,3],order:[0,1,3],org:[0,3],organ:0,orient:3,origin:[0,1,3],original_filenam:[1,3],original_files:3,original_height:3,original_nam:0,original_orient:3,original_width:3,osxphotos_export:0,other:[0,1,3],otherwis:[1,3],out:[0,1],output:[0,3],outsid:3,overal:3,overrid:0,overwrit:[0,3],own:1,packag:[],page:1,pair:[0,3],panorama:[0,3],paramet:[1,3],part:[0,3],particular:3,pass:[0,3],path:[0,1,3],path_edit:[1,3],path_live_photo:3,path_raw:3,path_sep:3,pathlib:1,pathvalid:1,per:0,permit:0,person:3,person_info:3,personinfo:3,personinimag:0,persons_as_dict:[1,3],photo:[0,3],photo_ext:0,photo_filenam:0,photoinfo:3,photokit:0,photonam:0,photoname_bearbeiten:0,photoname_edit:0,photos_by_uuid:3,photos_librari:[0,1],photosdb:[1,3],photoslibrari:[0,1],phototempl:3,pictur:[0,1,3],pixel:3,place:[1,3],place_nam:3,placeinfo:3,platform:1,pleasant_camera_tilt:3,pleasant_composit:3,pleasant_light:3,pleasant_pattern:3,pleasant_perspect:3,pleasant_post_process:3,pleasant_reflect:3,pleasant_symmetri:3,png:0,portrait:[0,3],posit:[0,1],pre:1,preceed:0,present:0,preview:0,previous:0,primari:0,print:[0,3],process:[0,3],produc:3,project:1,promot:3,properti:3,provid:[0,1,3],pylint:1,pypi:1,python3:1,python:1,qualiti:[0,3],queri:1,quicktim:[0,3],rais:3,rang:[0,3],raw:[0,3],raw_origin:3,raw_photo:3,read:1,readabl:3,recent:[0,3],recommend:1,refer:[0,1,3],referenc:0,regardless:3,region:0,relat:3,releas:1,reliabl:0,remov:0,renam:0,render:[0,3],render_templ:3,rendered_str:3,repeat:0,repo:1,report:0,repres:3,represent:3,requir:[0,1,3],result:[0,3],reus:0,revers:[0,3],rhettbul:1,run:[0,1,3],same:[0,3],sample_r:3,sanit:3,sanitize_filepath:1,save:0,score:3,scoreinfo:3,screenshot:[0,3],search:[0,1,3],search_info:3,search_info_norm:3,searchinfo:3,season:3,second:3,see:[0,1,3],select:3,self:3,selfi:[0,3],sep:3,separ:3,session:3,set:[0,3],setup:1,setuptool:1,share:[0,3],sharply_focused_subject:3,should:1,show:[0,1,3],shutter_spe:3,sidecar:[0,3],sidecar_drop_ext:3,sidecar_exiftool:3,sidecar_exiftool_skip:3,sidecar_exiftool_written:3,sidecar_ext:0,sidecar_json:3,sidecar_json_skip:3,sidecar_json_written:3,sidecar_xmp:3,sidecar_xmp_skip:3,sidecar_xmp_written:3,sierra:1,signatur:[0,3],silent:3,simpl:1,simpli:1,singl:[0,3],size:0,skip:[0,1,3],slow:[0,3],slow_mo:3,smith:1,some:3,someth:3,sort:3,sourc:3,space:[0,3],specif:[1,3],specifi:[0,3],spotlight:[0,1],sqlite3:3,start:[0,1],state:[0,3],state_abbrevi:3,statu:3,still:3,storat:3,store:[0,3],str:3,street:3,string:[0,3],strip:[0,3],subfold:0,subject:0,subsequ:0,substitut:3,suffix:[0,3],sur:1,sure:1,synch:[0,3],sys:1,system:0,tabl:3,tag:[0,1,3],tagnam:0,tagslist:0,take:1,taken:0,tastefully_blur:3,templat:[0,1,3],template_str:3,term:3,termin:[0,1],test:[0,1],text:3,than:[0,1,3],thei:[0,3],them:[0,3],thi:[0,1,3],thu:1,time:[0,3],time_laps:3,timecr:0,timeout:3,timezon:3,titl:[0,1,3],to_dat:[0,3],todai:0,toml:0,top:[0,3],topic:0,touch:[0,3],touch_fil:3,town:3,track_format:3,trail:[0,3],trash:3,treat:[0,3],tupl:3,two:0,type:[0,3],tzoffset:3,unedit:1,unfil:1,uniform:[0,3],unless:3,unlik:0,unmatch:3,until:[1,3],updat:[0,3],upon:[0,3],use:[0,3],use_albums_as_keyword:3,use_persons_as_keyword:3,use_photokit:3,use_photos_export:3,useabl:0,used:[0,1,3],useful:0,user:3,userdata:0,uses:[0,3],using:[0,3],utc:3,uti:[0,3],uti_edit:3,uti_origin:3,uti_raw:3,util:[1,3],uuid:[0,1,3],vacat:3,valid:[0,1,3],valu:[0,1,3],variou:3,venu:3,venue_typ:3,verbos:[0,3],veri:1,verifi:1,versa:1,version:[0,1,3],via:[0,1,3],vice:1,video:[0,3],virtual:1,visbl:3,visibl:3,volum:0,wai:1,want:[0,1],warn:[0,1,3],water:3,wed:3,well:1,well_chosen_subject:3,well_framed_subject:3,well_timed_shot:3,were:[0,3],what:3,when:[0,3],which:[0,1,3],white:3,white_bal:3,whitespac:0,whose:0,width:3,without:0,work:[0,1,3],would:0,write:[0,3],written:[0,3],xattr:0,xattr_skip:3,xattr_written:3,xmp:[0,3],year:[0,3],yet:3,you:[0,1,3],your:[0,1]},titles:["osxphotos command line interface (CLI)","Welcome to osxphotos\u2019s documentation!","osxphotos","osxphotos package"],titleterms:{"default":1,"export":[0,1],about:0,add:1,album:[0,1],all:1,awail:1,base:1,chang:1,cli:0,command:[0,1],countri:1,creat:1,creation:1,date:1,desktop:1,digit:1,directori:1,document:1,dump:0,exampl:1,exif:1,file:1,find:1,folder:1,from:1,full:1,git:1,group:1,help:0,higher:1,indic:1,info:0,instal:1,interfac:[0,1],json:1,keyword:[0,1],kid:1,label:[0,1],librari:1,line:[0,1],list:0,media:1,metadata:1,modul:3,month:1,name:1,nocountri:1,onli:1,oper:1,osxphoto:[0,1,2,3],ouput:1,output:1,packag:[1,3],person:[0,1],photo:1,pip:1,pipx:1,place:0,print:1,queri:0,repositori:1,result:1,specifi:1,structur:1,support:1,system:1,tabl:1,type:1,updat:1,usag:1,use:1,uses:1,using:1,verbos:1,welcom:1,what:1,when:1,write:1,year:1}}) \ No newline at end of file diff --git a/docs/source/cli.rst b/docs/source/cli.rst new file mode 100644 index 00000000..b63dfe3a --- /dev/null +++ b/docs/source/cli.rst @@ -0,0 +1,6 @@ +osxphotos command line interface (CLI) +====================================== + +.. click:: osxphotos.cli:cli + :prog: osxphotos + :nested: full \ No newline at end of file diff --git a/docs/conf.py b/docs/source/conf.py similarity index 96% rename from docs/conf.py rename to docs/source/conf.py index 2d0ce941..b620f586 100644 --- a/docs/conf.py +++ b/docs/source/conf.py @@ -28,7 +28,7 @@ author = "Rhet Turnbull" # holds config info read from disk about = {} this_directory = pathlib.Path(__file__).parent -version_file = this_directory.parent / "osxphotos" / "_version.py" +version_file = this_directory.parent.parent / "osxphotos" / "_version.py" # get version info from _version with open( version_file, mode="r", encoding="utf-8" diff --git a/docs/index.rst b/docs/source/index.rst similarity index 89% rename from docs/index.rst rename to docs/source/index.rst index c05f4535..5e14cd04 100644 --- a/docs/index.rst +++ b/docs/source/index.rst @@ -6,15 +6,15 @@ Welcome to osxphotos's documentation! ===================================== -.. include:: ../README.rst +.. include:: ../../README.rst .. toctree:: :maxdepth: 4 - :caption: Contents: cli reference + Indices and tables ================== diff --git a/docs/source/modules.rst b/docs/source/modules.rst new file mode 100644 index 00000000..3867ec04 --- /dev/null +++ b/docs/source/modules.rst @@ -0,0 +1,5 @@ +osxphotos +=========== + +.. toctree:: + :maxdepth: 4 diff --git a/docs/source/reference.rst b/docs/source/reference.rst new file mode 100644 index 00000000..0aa546ff --- /dev/null +++ b/docs/source/reference.rst @@ -0,0 +1,13 @@ +osxphotos package +=================== + +osxphotos module +------------------------------ + +.. autoclass:: osxphotos.PhotosDB + :members: + :undoc-members: + +.. autoclass:: osxphotos.PhotoInfo + :members: + :undoc-members: