[
  {
    "path": ".gitignore",
    "content": ".gradle\n/local.properties\n/.idea/workspace.xml\n/.idea/libraries\n.DS_Store\n/build\n"
  },
  {
    "path": ".idea/.name",
    "content": "WeixinNineGridLayout"
  },
  {
    "path": ".idea/compiler.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project version=\"4\">\n  <component name=\"CompilerConfiguration\">\n    <option name=\"DEFAULT_COMPILER\" value=\"Javac\" />\n    <resourceExtensions />\n    <wildcardResourcePatterns>\n      <entry name=\"!?*.java\" />\n      <entry name=\"!?*.form\" />\n      <entry name=\"!?*.class\" />\n      <entry name=\"!?*.groovy\" />\n      <entry name=\"!?*.scala\" />\n      <entry name=\"!?*.flex\" />\n      <entry name=\"!?*.kt\" />\n      <entry name=\"!?*.clj\" />\n    </wildcardResourcePatterns>\n    <annotationProcessing>\n      <profile default=\"true\" name=\"Default\" enabled=\"false\">\n        <processorPath useClasspath=\"true\" />\n      </profile>\n    </annotationProcessing>\n  </component>\n</project>\n\n"
  },
  {
    "path": ".idea/copyright/profiles_settings.xml",
    "content": "<component name=\"CopyrightManager\">\n  <settings default=\"\" />\n</component>"
  },
  {
    "path": ".idea/encodings.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project version=\"4\">\n  <component name=\"Encoding\" useUTFGuessing=\"true\" native2AsciiForPropertiesFiles=\"false\" />\n</project>\n\n"
  },
  {
    "path": ".idea/gradle.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project version=\"4\">\n  <component name=\"GradleSettings\">\n    <option name=\"linkedExternalProjectsSettings\">\n      <GradleProjectSettings>\n        <option name=\"distributionType\" value=\"LOCAL\" />\n        <option name=\"externalProjectPath\" value=\"$PROJECT_DIR$\" />\n        <option name=\"gradleHome\" value=\"D:/常用软件/gradle-2.2.1\" />\n        <option name=\"modules\">\n          <set>\n            <option value=\"$PROJECT_DIR$\" />\n            <option value=\"$PROJECT_DIR$/app\" />\n          </set>\n        </option>\n      </GradleProjectSettings>\n    </option>\n  </component>\n</project>\n\n"
  },
  {
    "path": ".idea/misc.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project version=\"4\">\n  <component name=\"DaemonCodeAnalyzer\">\n    <disable_hints />\n  </component>\n  <component name=\"ProjectLevelVcsManager\" settingsEditedManually=\"false\">\n    <OptionsSetting value=\"true\" id=\"Add\" />\n    <OptionsSetting value=\"true\" id=\"Remove\" />\n    <OptionsSetting value=\"true\" id=\"Checkout\" />\n    <OptionsSetting value=\"true\" id=\"Update\" />\n    <OptionsSetting value=\"true\" id=\"Status\" />\n    <OptionsSetting value=\"true\" id=\"Edit\" />\n    <ConfirmationsSetting value=\"0\" id=\"Add\" />\n    <ConfirmationsSetting value=\"0\" id=\"Remove\" />\n  </component>\n  <component name=\"ProjectRootManager\" version=\"2\" languageLevel=\"JDK_1_6\" assert-keyword=\"true\" jdk-15=\"true\">\n    <output url=\"file://$PROJECT_DIR$/build/classes\" />\n  </component>\n  <component name=\"RunManager\">\n    <configuration default=\"true\" type=\"Remote\" factoryName=\"Remote\">\n      <option name=\"USE_SOCKET_TRANSPORT\" value=\"true\" />\n      <option name=\"SERVER_MODE\" value=\"false\" />\n      <option name=\"SHMEM_ADDRESS\" value=\"javadebug\" />\n      <option name=\"HOST\" value=\"localhost\" />\n      <option name=\"PORT\" value=\"5005\" />\n      <method />\n    </configuration>\n    <configuration default=\"true\" type=\"JUnit\" factoryName=\"JUnit\">\n      <module name=\"\" />\n      <option name=\"ALTERNATIVE_JRE_PATH_ENABLED\" value=\"false\" />\n      <option name=\"ALTERNATIVE_JRE_PATH\" />\n      <option name=\"PACKAGE_NAME\" />\n      <option name=\"MAIN_CLASS_NAME\" />\n      <option name=\"METHOD_NAME\" />\n      <option name=\"TEST_OBJECT\" value=\"class\" />\n      <option name=\"VM_PARAMETERS\" value=\"-ea\" />\n      <option name=\"PARAMETERS\" />\n      <option name=\"WORKING_DIRECTORY\" value=\"$PROJECT_DIR$\" />\n      <option name=\"ENV_VARIABLES\" />\n      <option name=\"PASS_PARENT_ENVS\" value=\"true\" />\n      <option name=\"TEST_SEARCH_SCOPE\">\n        <value defaultName=\"moduleWithDependencies\" />\n      </option>\n      <envs />\n      <patterns />\n      <method />\n    </configuration>\n    <configuration default=\"true\" type=\"TestNG\" factoryName=\"TestNG\">\n      <module name=\"\" />\n      <option name=\"ALTERNATIVE_JRE_PATH_ENABLED\" value=\"false\" />\n      <option name=\"ALTERNATIVE_JRE_PATH\" />\n      <option name=\"SUITE_NAME\" />\n      <option name=\"PACKAGE_NAME\" />\n      <option name=\"MAIN_CLASS_NAME\" />\n      <option name=\"METHOD_NAME\" />\n      <option name=\"GROUP_NAME\" />\n      <option name=\"TEST_OBJECT\" value=\"CLASS\" />\n      <option name=\"VM_PARAMETERS\" value=\"-ea\" />\n      <option name=\"PARAMETERS\" />\n      <option name=\"WORKING_DIRECTORY\" value=\"$PROJECT_DIR$\" />\n      <option name=\"OUTPUT_DIRECTORY\" />\n      <option name=\"ANNOTATION_TYPE\" />\n      <option name=\"ENV_VARIABLES\" />\n      <option name=\"PASS_PARENT_ENVS\" value=\"true\" />\n      <option name=\"TEST_SEARCH_SCOPE\">\n        <value defaultName=\"moduleWithDependencies\" />\n      </option>\n      <option name=\"USE_DEFAULT_REPORTERS\" value=\"false\" />\n      <option name=\"PROPERTIES_FILE\" />\n      <envs />\n      <properties />\n      <listeners />\n      <method />\n    </configuration>\n    <configuration default=\"true\" type=\"Application\" factoryName=\"Application\">\n      <option name=\"MAIN_CLASS_NAME\" />\n      <option name=\"VM_PARAMETERS\" />\n      <option name=\"PROGRAM_PARAMETERS\" />\n      <option name=\"WORKING_DIRECTORY\" value=\"$PROJECT_DIR$\" />\n      <option name=\"ALTERNATIVE_JRE_PATH_ENABLED\" value=\"false\" />\n      <option name=\"ALTERNATIVE_JRE_PATH\" />\n      <option name=\"ENABLE_SWING_INSPECTOR\" value=\"false\" />\n      <option name=\"ENV_VARIABLES\" />\n      <option name=\"PASS_PARENT_ENVS\" value=\"true\" />\n      <module name=\"\" />\n      <envs />\n      <method />\n    </configuration>\n    <list size=\"0\" />\n    <configuration name=\"&lt;template&gt;\" type=\"#org.jetbrains.idea.devkit.run.PluginConfigurationType\" default=\"true\" selected=\"false\">\n      <option name=\"VM_PARAMETERS\" value=\"-Xmx512m -Xms256m -XX:MaxPermSize=250m -ea\" />\n    </configuration>\n    <configuration name=\"&lt;template&gt;\" type=\"WebApp\" default=\"true\" selected=\"false\">\n      <Host>localhost</Host>\n      <Port>5050</Port>\n    </configuration>\n  </component>\n  <component name=\"SvnBranchConfigurationManager\">\n    <option name=\"mySupportsUserInfoFilter\" value=\"true\" />\n  </component>\n</project>\n\n"
  },
  {
    "path": ".idea/modules.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project version=\"4\">\n  <component name=\"ProjectModuleManager\">\n    <modules>\n      <module fileurl=\"file://$PROJECT_DIR$/WeixinNineGridLayout.iml\" filepath=\"$PROJECT_DIR$/WeixinNineGridLayout.iml\" />\n    </modules>\n  </component>\n</project>\n\n"
  },
  {
    "path": ".idea/scopes/scope_settings.xml",
    "content": "<component name=\"DependencyValidationManager\">\n  <state>\n    <option name=\"SKIP_IMPORT_STATEMENTS\" value=\"false\" />\n  </state>\n</component>"
  },
  {
    "path": ".idea/vcs.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project version=\"4\">\n  <component name=\"VcsDirectoryMappings\">\n    <mapping directory=\"\" vcs=\"svn\" />\n  </component>\n</project>\n\n"
  },
  {
    "path": "README.md",
    "content": "NineGridLayout\n--------------\n\n 1. 简介\n\n  这是一个用于实现像微信朋友圈和微博的类似的九宫格图片展示控件，通过自定义viewgroup实现，是用方便，只需要很简单的就可嵌入到项目中去。\n  \n  \n\n\n----------\n\n\n 2. 使用方法\n 在项目的layout文件中添加如下xml即可加入到布局文件\n\n                <com.weixinninegridlayout.NineGridlayout\n                android:layout_marginTop=\"8dp\"\n                android:id=\"@+id/iv_ngrid_layout\"\n                android:layout_height=\"wrap_content\"\n                android:layout_width=\"match_parent\" />\n\n  因为大部分这类控件都是在listview里面用的，所以针对Listview的复用有针对性的优化，只需要在项目中调用NineGridlayout.setImagesData就可以实现图片的加载和显示。同时为了解耦合和，重写了一个CustomImageView嵌入了picasso图片加载库来加载图片。\n\n\n----------\n\n\n 3. 效果展示\n 由于我用markdown嵌入图片发现大小不能调整，所以如果想要看跟多详情，可以去我的CSDN博客，地址：[自定义九宫格控件NineGridLayout ,实现微信朋友圈图片九宫格显示][1]\n\n\n\n  ![效果1][2]\n  ![效果2][3]\n   \n  [1]: http://blog.csdn.net/u012650948/article/details/43638427\n\n  \n  [3]: http://img.blog.csdn.net/20150208195246244?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMjY1MDk0OA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center\n\n\n  \n----------\n\n\n 4. 协议\n\n>  /*\n * Copyright (C) 2015 panyihong\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n"
  },
  {
    "path": "WeixinNineGridLayout.iml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<module external.linked.project.path=\"$MODULE_DIR$\" external.root.project.path=\"$MODULE_DIR$\" external.system.id=\"GRADLE\" type=\"JAVA_MODULE\" version=\"4\">\n  <component name=\"FacetManager\">\n    <facet type=\"java-gradle\" name=\"Java-Gradle\">\n      <configuration>\n        <option name=\"BUILD_FOLDER_PATH\" value=\"$MODULE_DIR$/build\" />\n      </configuration>\n    </facet>\n    <facet type=\"android-gradle\" name=\"Android-Gradle\">\n      <configuration>\n        <option name=\"GRADLE_PROJECT_PATH\" value=\":\" />\n      </configuration>\n    </facet>\n    <facet type=\"android\" name=\"Android\">\n      <configuration>\n        <option name=\"ALLOW_USER_CONFIGURATION\" value=\"false\" />\n      </configuration>\n    </facet>\n  </component>\n  <component name=\"NewModuleRootManager\" inherit-compiler-output=\"false\">\n    <output url=\"file://$MODULE_DIR$/build/classes/main\" />\n    <output-test url=\"file://$MODULE_DIR$/build/classes/test\" />\n    <exclude-output />\n    <content url=\"file://$MODULE_DIR$\">\n      <excludeFolder url=\"file://$MODULE_DIR$/.gradle\" />\n    </content>\n    <orderEntry type=\"inheritedJdk\" />\n    <orderEntry type=\"sourceFolder\" forTests=\"false\" />\n  </component>\n</module>\n\n"
  },
  {
    "path": "app/.gitignore",
    "content": "/build\n"
  },
  {
    "path": "app/app.iml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<module external.linked.project.path=\"$MODULE_DIR$\" external.root.project.path=\"$MODULE_DIR$/..\" external.system.id=\"GRADLE\" type=\"JAVA_MODULE\" version=\"4\">\n  <component name=\"FacetManager\">\n    <facet type=\"android-gradle\" name=\"Android-Gradle\">\n      <configuration>\n        <option name=\"GRADLE_PROJECT_PATH\" value=\":app\" />\n      </configuration>\n    </facet>\n    <facet type=\"android\" name=\"Android\">\n      <configuration>\n        <option name=\"SELECTED_BUILD_VARIANT\" value=\"debug\" />\n        <option name=\"ASSEMBLE_TASK_NAME\" value=\"assembleDebug\" />\n        <option name=\"COMPILE_JAVA_TASK_NAME\" value=\"compileDebugSources\" />\n        <option name=\"ASSEMBLE_TEST_TASK_NAME\" value=\"assembleDebugTest\" />\n        <option name=\"SOURCE_GEN_TASK_NAME\" value=\"generateDebugSources\" />\n        <option name=\"TEST_SOURCE_GEN_TASK_NAME\" value=\"generateDebugTestSources\" />\n        <option name=\"ALLOW_USER_CONFIGURATION\" value=\"false\" />\n        <option name=\"MANIFEST_FILE_RELATIVE_PATH\" value=\"/src/main/AndroidManifest.xml\" />\n        <option name=\"RES_FOLDER_RELATIVE_PATH\" value=\"/src/main/res\" />\n        <option name=\"RES_FOLDERS_RELATIVE_PATH\" value=\"file://$MODULE_DIR$/src/main/res\" />\n        <option name=\"ASSETS_FOLDER_RELATIVE_PATH\" value=\"/src/main/assets\" />\n      </configuration>\n    </facet>\n  </component>\n  <component name=\"NewModuleRootManager\" inherit-compiler-output=\"false\">\n    <output url=\"file://$MODULE_DIR$/build/intermediates/classes/debug\" />\n    <exclude-output />\n    <content url=\"file://$MODULE_DIR$\">\n      <sourceFolder url=\"file://$MODULE_DIR$/build/generated/source/r/debug\" isTestSource=\"false\" generated=\"true\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/build/generated/source/aidl/debug\" isTestSource=\"false\" generated=\"true\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/build/generated/source/buildConfig/debug\" isTestSource=\"false\" generated=\"true\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/build/generated/source/rs/debug\" isTestSource=\"false\" generated=\"true\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/build/generated/res/rs/debug\" type=\"java-resource\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/build/generated/res/generated/debug\" type=\"java-resource\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/build/generated/source/r/test/debug\" isTestSource=\"true\" generated=\"true\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/build/generated/source/aidl/test/debug\" isTestSource=\"true\" generated=\"true\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/build/generated/source/buildConfig/test/debug\" isTestSource=\"true\" generated=\"true\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/build/generated/source/rs/test/debug\" isTestSource=\"true\" generated=\"true\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/build/generated/res/rs/test/debug\" type=\"java-test-resource\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/build/generated/res/generated/test/debug\" type=\"java-test-resource\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/src/debug/res\" type=\"java-resource\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/src/debug/resources\" type=\"java-resource\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/src/debug/assets\" type=\"java-resource\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/src/debug/aidl\" isTestSource=\"false\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/src/debug/java\" isTestSource=\"false\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/src/debug/jni\" isTestSource=\"false\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/src/debug/rs\" isTestSource=\"false\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/src/main/res\" type=\"java-resource\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/src/main/resources\" type=\"java-resource\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/src/main/assets\" type=\"java-resource\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/src/main/aidl\" isTestSource=\"false\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/src/main/java\" isTestSource=\"false\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/src/main/jni\" isTestSource=\"false\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/src/main/rs\" isTestSource=\"false\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/src/androidTest/res\" type=\"java-test-resource\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/src/androidTest/resources\" type=\"java-test-resource\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/src/androidTest/assets\" type=\"java-test-resource\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/src/androidTest/aidl\" isTestSource=\"true\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/src/androidTest/java\" isTestSource=\"true\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/src/androidTest/jni\" isTestSource=\"true\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/src/androidTest/rs\" isTestSource=\"true\" />\n      <excludeFolder url=\"file://$MODULE_DIR$/build/intermediates/assets\" />\n      <excludeFolder url=\"file://$MODULE_DIR$/build/intermediates/bundles\" />\n      <excludeFolder url=\"file://$MODULE_DIR$/build/intermediates/classes\" />\n      <excludeFolder url=\"file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes\" />\n      <excludeFolder url=\"file://$MODULE_DIR$/build/intermediates/dependency-cache\" />\n      <excludeFolder url=\"file://$MODULE_DIR$/build/intermediates/dex\" />\n      <excludeFolder url=\"file://$MODULE_DIR$/build/intermediates/dex-cache\" />\n      <excludeFolder url=\"file://$MODULE_DIR$/build/intermediates/incremental\" />\n      <excludeFolder url=\"file://$MODULE_DIR$/build/intermediates/jacoco\" />\n      <excludeFolder url=\"file://$MODULE_DIR$/build/intermediates/javaResources\" />\n      <excludeFolder url=\"file://$MODULE_DIR$/build/intermediates/libs\" />\n      <excludeFolder url=\"file://$MODULE_DIR$/build/intermediates/lint\" />\n      <excludeFolder url=\"file://$MODULE_DIR$/build/intermediates/manifests\" />\n      <excludeFolder url=\"file://$MODULE_DIR$/build/intermediates/ndk\" />\n      <excludeFolder url=\"file://$MODULE_DIR$/build/intermediates/pre-dexed\" />\n      <excludeFolder url=\"file://$MODULE_DIR$/build/intermediates/proguard\" />\n      <excludeFolder url=\"file://$MODULE_DIR$/build/intermediates/res\" />\n      <excludeFolder url=\"file://$MODULE_DIR$/build/intermediates/rs\" />\n      <excludeFolder url=\"file://$MODULE_DIR$/build/intermediates/symbols\" />\n      <excludeFolder url=\"file://$MODULE_DIR$/build/outputs\" />\n      <excludeFolder url=\"file://$MODULE_DIR$/build/tmp\" />\n    </content>\n    <orderEntry type=\"jdk\" jdkName=\"Android API 21 Platform\" jdkType=\"Android SDK\" />\n    <orderEntry type=\"sourceFolder\" forTests=\"false\" />\n    <orderEntry type=\"library\" exported=\"\" name=\"support-annotations-21.0.0\" level=\"project\" />\n    <orderEntry type=\"library\" exported=\"\" name=\"picasso-2.3.4\" level=\"project\" />\n    <orderEntry type=\"library\" exported=\"\" name=\"support-v4-21.0.0\" level=\"project\" />\n    <orderEntry type=\"library\" exported=\"\" name=\"appcompat-v7-21.0.0\" level=\"project\" />\n  </component>\n</module>\n\n"
  },
  {
    "path": "app/build.gradle",
    "content": "apply plugin: 'com.android.application'\n\nandroid {\n    compileSdkVersion 21\n    buildToolsVersion \"21.1.0\"\n\n    defaultConfig {\n        applicationId \"com.weixinninegridlayout\"\n        minSdkVersion 9\n        targetSdkVersion 21\n        versionCode 1\n        versionName \"1.0\"\n    }\n    buildTypes {\n        release {\n            minifyEnabled false\n            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n        }\n    }\n}\n\ndependencies {\n    compile fileTree(dir: 'libs', include: ['*.jar'])\n    compile 'com.android.support:appcompat-v7:21.0.0'\n    compile files('libs/picasso-2.3.4.jar')\n}\n"
  },
  {
    "path": "app/proguard-rules.pro",
    "content": "# Add project specific ProGuard rules here.\n# By default, the flags in this file are appended to flags specified\n# in D:\\android statio\\sdk/tools/proguard/proguard-android.txt\n# You can edit the include path and order by changing the proguardFiles\n# directive in build.gradle.\n#\n# For more details, see\n#   http://developer.android.com/guide/developing/tools/proguard.html\n\n# Add any project specific keep options here:\n\n# If your project uses WebView with JS, uncomment the following\n# and specify the fully qualified class name to the JavaScript interface\n# class:\n#-keepclassmembers class fqcn.of.javascript.interface.for.webview {\n#   public *;\n#}\n"
  },
  {
    "path": "app/src/androidTest/java/com/example/administrator/weixinninegridlayout/ApplicationTest.java",
    "content": "package com.example.administrator.weixinninegridlayout;\n\nimport android.app.Application;\nimport android.test.ApplicationTestCase;\n\n/**\n * <a href=\"http://d.android.com/tools/testing/testing_android.html\">Testing Fundamentals</a>\n */\npublic class ApplicationTest extends ApplicationTestCase<Application> {\n    public ApplicationTest() {\n        super(Application.class);\n    }\n}"
  },
  {
    "path": "app/src/main/AndroidManifest.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    package=\"com.weixinninegridlayout\">\n\n    <uses-permission android:name=\"android.permission.INTERNET\" />\n    <uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\" />\n    <uses-permission android:name=\"android.permission.READ_EXTERNAL_STORAGE\"/>\n\n    <application\n        android:allowBackup=\"true\"\n        android:icon=\"@drawable/ic_launcher\"\n        android:label=\"@string/app_name\"\n        android:theme=\"@style/AppTheme\">\n        <activity\n            android:name=\"com.weixinninegridlayout.MainActivity\"\n            android:label=\"@string/app_name\">\n            <intent-filter>\n                <action android:name=\"android.intent.action.MAIN\" />\n\n                <category android:name=\"android.intent.category.LAUNCHER\" />\n            </intent-filter>\n        </activity>\n    </application>\n\n</manifest>\n"
  },
  {
    "path": "app/src/main/java/com/weixinninegridlayout/CustomImageView.java",
    "content": "package com.weixinninegridlayout;\n\nimport android.content.Context;\nimport android.graphics.Color;\nimport android.graphics.PorterDuff;\nimport android.graphics.drawable.ColorDrawable;\nimport android.graphics.drawable.Drawable;\nimport android.text.TextUtils;\nimport android.util.AttributeSet;\nimport android.view.MotionEvent;\nimport android.widget.ImageView;\n\nimport com.squareup.picasso.Picasso;\n\n\n/**\n * Created by Pan_ on 2015/2/2.\n */\npublic class CustomImageView extends ImageView {\n    private String url;\n    private boolean isAttachedToWindow;\n\n    public CustomImageView(Context context, AttributeSet attrs) {\n        super(context, attrs);\n    }\n\n    public CustomImageView(Context context) {\n        super(context);\n    }\n\n\n    @Override\n    public boolean onTouchEvent(MotionEvent event) {\n\n        switch (event.getAction()) {\n            case MotionEvent.ACTION_DOWN:\n                Drawable drawable=getDrawable();\n                if(drawable!=null) {\n                    drawable.mutate().setColorFilter(Color.GRAY,\n                            PorterDuff.Mode.MULTIPLY);\n                }\n                break;\n            case MotionEvent.ACTION_MOVE:\n                break;\n            case MotionEvent.ACTION_CANCEL:\n            case MotionEvent.ACTION_UP:\n                Drawable drawableUp=getDrawable();\n                if(drawableUp!=null) {\n                    drawableUp.mutate().clearColorFilter();\n                }\n                break;\n        }\n\n        return super.onTouchEvent(event);\n    }\n\n    @Override\n    public void onAttachedToWindow() {\n        isAttachedToWindow = true;\n        setImageUrl(url);\n        super.onAttachedToWindow();\n    }\n\n    @Override\n    public void onDetachedFromWindow() {\n        Picasso.with(getContext()).cancelRequest(this);\n        isAttachedToWindow = false;\n        setImageBitmap(null);\n        super.onDetachedFromWindow();\n    }\n\n\n    public void setImageUrl(String url) {\n        if (!TextUtils.isEmpty(url)) {\n            this.url = url;\n            if (isAttachedToWindow) {\n                Picasso.with(getContext()).load(url).placeholder(new ColorDrawable(Color.parseColor(\"#f5f5f5\"))).into(this);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "app/src/main/java/com/weixinninegridlayout/Image.java",
    "content": "package com.weixinninegridlayout;\n\n/**\n * Created by Pan_ on 2015/2/3.\n */\npublic class Image {\n    private String url;\n    private int width;\n    private int height;\n\n    public Image(String url, int width, int height) {\n        this.url = url;\n        this.width = width;\n        this.height = height;\n        L.i(toString());\n    }\n\n    public String getUrl() {\n        return url;\n    }\n\n    public void setUrl(String url) {\n        this.url = url;\n    }\n\n    public int getWidth() {\n        return width;\n    }\n\n    public void setWidth(int width) {\n        this.width = width;\n    }\n\n    public int getHeight() {\n        return height;\n    }\n\n    public void setHeight(int height) {\n        this.height = height;\n    }\n\n    @Override\n    public String toString() {\n\n        return \"image---->>url=\"+url+\"width=\"+width+\"height\"+height;\n    }\n}\n"
  },
  {
    "path": "app/src/main/java/com/weixinninegridlayout/L.java",
    "content": "package com.weixinninegridlayout;\n\nimport android.util.Log;\n\n\npublic final class L {\n\tprivate L() {\n\t}\n\n\n\tpublic static void v(Throwable t) {\n\t\tlog(Log.VERBOSE, t, null);\n\t}\n\n\tpublic static void v(Object format, Object... args) {\n\t\tlog(Log.VERBOSE, null, format, args);\n\t}\n\n\tpublic static void v(Throwable t, Object format, Object... args) {\n\t\tlog(Log.VERBOSE, t, format, args);\n\t}\n\n\tpublic static void d(Throwable t) {\n\t\tlog(Log.DEBUG, t, null);\n\t}\n\n\tpublic static void d(Object format, Object... args) {\n\t\tlog(Log.DEBUG, null, format, args);\n\t}\n\n\tpublic static void d(Throwable t, Object format, Object... args) {\n\t\tlog(Log.DEBUG, t, format, args);\n\t}\n\n\tpublic static void i(Throwable t) {\n\t\tlog(Log.INFO, t, null);\n\t}\n\n\tpublic static void i(Object format, Object... args) {\n\t\tlog(Log.INFO, null, format, args);\n\t}\n\n\tpublic static void i(Throwable t, Object format, Object... args) {\n\t\tlog(Log.INFO, t, format, args);\n\t}\n\n\tpublic static void w(Throwable t) {\n\t\tlog(Log.WARN, t, null);\n\t}\n\n\tpublic static void w(Object format, Object... args) {\n\t\tlog(Log.WARN, null, format, args);\n\t}\n\n\tpublic static void w(Throwable t, Object format, Object... args) {\n\t\tlog(Log.WARN, t, format, args);\n\t}\n\n\tpublic static void e(Throwable t) {\n\t\tlog(Log.ERROR, t, null);\n\t}\n\n\tpublic static void e(Object format, Object... args) {\n\t\tlog(Log.ERROR, null, format, args);\n\t}\n\n\tpublic static void e(Throwable t, Object format, Object... args) {\n\t\tlog(Log.ERROR, t, format, args);\n\t}\n\n\tprivate static void log(final int pType, final Throwable t, final Object format,\n\t\t\tfinal Object... args) {\n\t\tfinal StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[4];\n\n\t\tfinal String fullClassName = stackTraceElement.getClassName();\n\t\tfinal String className = fullClassName.substring(fullClassName.lastIndexOf(\".\") + 1);\n\t\tfinal int lineNumber = stackTraceElement.getLineNumber();\n\t\tfinal String method = stackTraceElement.getMethodName();\n\n\t\tfinal String tag = new StringBuilder(\"[\").append(Thread.currentThread().getId()).append(\"]\")\n\t\t\t\t.append(className).append(\"<\").append(lineNumber).append(\">\").toString();\n\n\t\tfinal StringBuilder stringBuilder = new StringBuilder();\n\t\tstringBuilder.append(method);\n\t\tstringBuilder.append(\"(): \");\n\n\t\tif (format != null) {\n\t\t\ttry {\n\t\t\t\tfinal String message = (args == null) ? format.toString() : String.format(\n\t\t\t\t\t\t(String) format, args);\n\t\t\t\tstringBuilder.append(message);\n\t\t\t} catch (Exception e) {\n\t\t\t\tstringBuilder.append(\"日志格式化异常：\");\n\t\t\t\tstringBuilder.append(format.toString());\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\n\t\tswitch (pType) {\n\t\tcase Log.VERBOSE:\n\t\t\tif (t != null) {\n\t\t\t\tLog.v(tag, stringBuilder.toString(), t);\n\t\t\t} else {\n\t\t\t\tLog.v(tag, stringBuilder.toString());\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase Log.DEBUG:\n\t\t\tif (t != null) {\n\t\t\t\tLog.d(tag, stringBuilder.toString(), t);\n\t\t\t} else {\n\t\t\t\tLog.d(tag, stringBuilder.toString());\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase Log.INFO:\n\t\t\tif (t != null) {\n\t\t\t\tLog.i(tag, stringBuilder.toString(), t);\n\t\t\t} else {\n\t\t\t\tLog.i(tag, stringBuilder.toString());\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase Log.WARN:\n\t\t\tif (t != null) {\n\t\t\t\tLog.w(tag, stringBuilder.toString(), t);\n\t\t\t} else {\n\t\t\t\tLog.w(tag, stringBuilder.toString());\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase Log.ERROR:\n\t\t\tif (t != null) {\n\t\t\t\tLog.e(tag, stringBuilder.toString(), t);\n\t\t\t} else {\n\t\t\t\tLog.e(tag, stringBuilder.toString());\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\t// }\n\t}\n}\n"
  },
  {
    "path": "app/src/main/java/com/weixinninegridlayout/MainActivity.java",
    "content": "package com.weixinninegridlayout;\n\nimport android.support.v7.app.ActionBarActivity;\nimport android.os.Bundle;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.widget.ListView;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n\npublic class MainActivity extends ActionBarActivity {\n    private ListView listView;\n    private List<List<Image>> imagesList;\n\n    private String[][] images=new String[][]{{\n             \"http://img4.duitang.com/uploads/item/201209/25/20120925201555_eUHEU.jpeg\",\"640\",\"960\"}\n            ,{\"file:///android_asset/img2.jpg\",\"250\",\"250\"}\n            ,{\"file:///android_asset/img3.jpg\",\"250\",\"250\"}\n            ,{\"file:///android_asset/img4.jpg\",\"250\",\"250\"}\n            ,{\"file:///android_asset/img5.jpg\",\"250\",\"250\"}\n            ,{\"file:///android_asset/img6.jpg\",\"250\",\"250\"}\n            ,{\"file:///android_asset/img7.jpg\",\"250\",\"250\"}\n            ,{\"file:///android_asset/img8.jpg\",\"250\",\"250\"}\n            ,{\"http://img3.douban.com/view/photo/raw/public/p1708880537.jpg\",\"1280\",\"800\"}\n    };\n\n    @Override\n    protected void onCreate(Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.activity_main);\n\n        listView= (ListView) findViewById(R.id.lv_main);\n        initData();\n        listView.setAdapter(new MainAdapter(MainActivity.this,imagesList));\n\n    }\n\n    private void initData() {\n        imagesList=new ArrayList<>();\n       //这里单独添加一条单条的测试数据，用来测试单张的时候横竖图片的效果\n        ArrayList<Image> singleList=new ArrayList<>();\n        singleList.add(new Image(images[8][0],Integer.parseInt(images[8][1]),Integer.parseInt(images[8][2])));\n        imagesList.add(singleList);\n        //从一到9生成9条朋友圈内容，分别是1~9张图片\n        for(int i=0;i<9;i++){\n            ArrayList<Image> itemList=new ArrayList<>();\n             for(int j=0;j<=i;j++){\n                 itemList.add(new Image(images[j][0],Integer.parseInt(images[j][1]),Integer.parseInt(images[j][2])));\n             }\n            imagesList.add(itemList);\n        }\n    }\n\n}\n"
  },
  {
    "path": "app/src/main/java/com/weixinninegridlayout/MainAdapter.java",
    "content": "package com.weixinninegridlayout;\n\nimport android.content.Context;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.BaseAdapter;\n\nimport java.util.List;\n\n/**\n * Created by Pan_ on 2015/2/3.\n */\npublic class MainAdapter extends BaseAdapter {\n    private Context context;\n    private List<List<Image>> datalist;\n\n    public MainAdapter(Context context, List<List<Image>> datalist) {\n        this.context = context;\n        this.datalist = datalist;\n    }\n\n    @Override\n    public int getCount() {\n        return datalist.size();\n    }\n\n    @Override\n    public Object getItem(int position) {\n        return datalist.get(position);\n    }\n\n    @Override\n    public long getItemId(int position) {\n        return position;\n    }\n\n    @Override\n    public View getView(int position, View convertView, ViewGroup parent) {\n        ViewHolder viewHolder;\n        List<Image> itemList = datalist.get(position);\n        if (convertView == null) {\n            convertView = LayoutInflater.from(context).inflate(R.layout.item_ninegridlayout, parent, false);\n            viewHolder = new ViewHolder();\n            viewHolder.ivMore = (NineGridlayout) convertView.findViewById(R.id.iv_ngrid_layout);\n            viewHolder.ivOne = (CustomImageView) convertView.findViewById(R.id.iv_oneimage);\n\n            convertView.setTag(viewHolder);\n        } else {\n            viewHolder = (ViewHolder) convertView.getTag();\n        }\n        if (itemList.isEmpty() || itemList.isEmpty()) {\n            viewHolder.ivMore.setVisibility(View.GONE);\n            viewHolder.ivOne.setVisibility(View.GONE);\n        } else if (itemList.size() == 1) {\n            viewHolder.ivMore.setVisibility(View.GONE);\n            viewHolder.ivOne.setVisibility(View.VISIBLE);\n\n            handlerOneImage(viewHolder, itemList.get(0));\n        } else {\n            viewHolder.ivMore.setVisibility(View.VISIBLE);\n            viewHolder.ivOne.setVisibility(View.GONE);\n\n            viewHolder.ivMore.setImagesData(itemList);\n        }\n\n        return convertView;\n    }\n\n    private void handlerOneImage(ViewHolder viewHolder, Image image) {\n        int totalWidth;\n        int imageWidth;\n        int imageHeight;\n        ScreenTools screentools = ScreenTools.instance(context);\n        totalWidth = screentools.getScreenWidth() - screentools.dip2px(80);\n        imageWidth = screentools.dip2px(image.getWidth());\n        imageHeight = screentools.dip2px(image.getHeight());\n        if (image.getWidth() <= image.getHeight()) {\n            if (imageHeight > totalWidth) {\n                imageHeight = totalWidth;\n                imageWidth = (imageHeight * image.getWidth()) / image.getHeight();\n            }\n        } else {\n            if (imageWidth > totalWidth) {\n                imageWidth = totalWidth;\n                imageHeight = (imageWidth * image.getHeight()) / image.getWidth();\n            }\n        }\n        ViewGroup.LayoutParams layoutparams = viewHolder.ivOne.getLayoutParams();\n        layoutparams.height = imageHeight;\n        layoutparams.width = imageWidth;\n        viewHolder.ivOne.setLayoutParams(layoutparams);\n        viewHolder.ivOne.setClickable(true);\n        viewHolder.ivOne.setScaleType(android.widget.ImageView.ScaleType.FIT_XY);\n        viewHolder.ivOne.setImageUrl(image.getUrl());\n\n    }\n\n\n    class ViewHolder {\n        public NineGridlayout ivMore;\n        public CustomImageView ivOne;\n    }\n}\n"
  },
  {
    "path": "app/src/main/java/com/weixinninegridlayout/NineGridlayout.java",
    "content": "package com.weixinninegridlayout;\n\nimport android.content.Context;\nimport android.graphics.Color;\nimport android.graphics.drawable.ColorDrawable;\nimport android.util.AttributeSet;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ImageView;\n\nimport java.util.List;\n\n\n/**\n * Created by Pan_ on 2015/2/2.\n */\npublic class NineGridlayout extends ViewGroup {\n\n    /**\n     * 图片之间的间隔\n     */\n    private int gap = 5;\n    private int columns;//\n    private int rows;//\n    private List listData;\n    private int totalWidth;\n\n    public NineGridlayout(Context context) {\n        super(context);\n    }\n\n    public NineGridlayout(Context context, AttributeSet attrs) {\n        super(context, attrs);\n        ScreenTools screenTools=ScreenTools.instance(getContext());\n        totalWidth=screenTools.getScreenWidth()-screenTools.dip2px(80);\n    }\n\n    @Override\n    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n        super.onMeasure(widthMeasureSpec, heightMeasureSpec);\n    }\n\n    @Override\n    protected void onLayout(boolean changed, int l, int t, int r, int b) {\n\n    }\n    private void layoutChildrenView(){\n        int childrenCount = listData.size();\n\n        int singleWidth = (totalWidth - gap * (3 - 1)) / 3;\n        int singleHeight = singleWidth;\n\n        //根据子view数量确定高度\n        ViewGroup.LayoutParams params = getLayoutParams();\n        params.height = singleHeight * rows + gap * (rows - 1);\n        setLayoutParams(params);\n\n        for (int i = 0; i < childrenCount; i++) {\n            CustomImageView childrenView = (CustomImageView) getChildAt(i);\n            childrenView.setImageUrl(((Image) listData.get(i)).getUrl());\n            int[] position = findPosition(i);\n            int left = (singleWidth + gap) * position[1];\n            int top = (singleHeight + gap) * position[0];\n            int right = left + singleWidth;\n            int bottom = top + singleHeight;\n\n            childrenView.layout(left, top, right, bottom);\n        }\n\n    }\n\n\n    private int[] findPosition(int childNum) {\n        int[] position = new int[2];\n        for (int i = 0; i < rows; i++) {\n            for (int j = 0; j < columns; j++) {\n                if ((i * columns + j) == childNum) {\n                    position[0] = i;//行\n                    position[1] = j;//列\n                    break;\n                }\n            }\n        }\n        return position;\n    }\n\n    public int getGap() {\n        return gap;\n    }\n\n    public void setGap(int gap) {\n        this.gap = gap;\n    }\n\n\n    public void setImagesData(List<Image> lists) {\n        if (lists == null || lists.isEmpty()) {\n            return;\n        }\n        //初始化布局\n        generateChildrenLayout(lists.size());\n        //这里做一个重用view的处理\n        if (listData == null) {\n            int i = 0;\n            while (i < lists.size()) {\n                CustomImageView iv = generateImageView();\n                addView(iv,generateDefaultLayoutParams());\n                i++;\n            }\n        } else {\n            int oldViewCount = listData.size();\n            int newViewCount = lists.size();\n            if (oldViewCount > newViewCount) {\n                removeViews(newViewCount - 1, oldViewCount - newViewCount);\n            } else if (oldViewCount < newViewCount) {\n                for (int i = 0; i < newViewCount - oldViewCount; i++) {\n                    CustomImageView iv = generateImageView();\n                    addView(iv,generateDefaultLayoutParams());\n                }\n            }\n        }\n        listData = lists;\n        layoutChildrenView();\n    }\n\n\n    /**\n     * 根据图片个数确定行列数量\n     * 对应关系如下\n     * num\trow\tcolumn\n     * 1\t   1\t1\n     * 2\t   1\t2\n     * 3\t   1\t3\n     * 4\t   2\t2\n     * 5\t   2\t3\n     * 6\t   2\t3\n     * 7\t   3\t3\n     * 8\t   3\t3\n     * 9\t   3\t3\n     *\n     * @param length\n     */\n    private void generateChildrenLayout(int length) {\n        if (length <= 3) {\n            rows = 1;\n            columns = length;\n        } else if (length <= 6) {\n            rows = 2;\n            columns = 3;\n            if (length == 4) {\n                columns = 2;\n            }\n        } else {\n            rows = 3;\n            columns = 3;\n        }\n    }\n\n    private CustomImageView generateImageView() {\n        CustomImageView iv = new CustomImageView(getContext());\n        iv.setScaleType(ImageView.ScaleType.CENTER_CROP);\n        iv.setOnClickListener(new OnClickListener() {\n            @Override\n            public void onClick(View v) {\n\n            }\n        });\n        iv.setBackgroundColor(Color.parseColor(\"#f5f5f5\"));\n        return iv;\n    }\n\n\n}\n"
  },
  {
    "path": "app/src/main/java/com/weixinninegridlayout/ScreenTools.java",
    "content": "\npackage com.weixinninegridlayout;\n\nimport android.content.Context;\n\npublic class ScreenTools {\n\n    private static ScreenTools mScreenTools;\n    private Context context;\n\n    private ScreenTools(Context context) {\n        this.context = context.getApplicationContext();\n    }\n\n    public static ScreenTools instance(Context context) {\n        if (mScreenTools == null)\n            mScreenTools = new ScreenTools(context);\n        return mScreenTools;\n    }\n\n    public int dip2px(float f) {\n        return (int) (0.5D + (double) (f * getDensity(context)));\n    }\n\n    public int dip2px(int i) {\n        return (int) (0.5D + (double) (getDensity(context) * (float) i));\n    }\n\n    public int get480Height(int i) {\n        return (i * getScreenWidth()) / 480;\n    }\n\n    public float getDensity(Context context) {\n        return context.getResources().getDisplayMetrics().density;\n    }\n\n    public int getScal() {\n        return (100 * getScreenWidth()) / 480;\n    }\n\n    public int getScreenDensityDpi() {\n        return context.getResources().getDisplayMetrics().densityDpi;\n    }\n\n    public int getScreenHeight() {\n        return context.getResources().getDisplayMetrics().heightPixels;\n    }\n\n    public int getScreenWidth() {\n        return context.getResources().getDisplayMetrics().widthPixels;\n    }\n\n\n    public float getXdpi() {\n        return context.getResources().getDisplayMetrics().xdpi;\n    }\n\n    public float getYdpi() {\n        return context.getResources().getDisplayMetrics().ydpi;\n    }\n\n    public int px2dip(float f) {\n        float f1 = getDensity(context);\n        return (int) (((double) f - 0.5D) / (double) f1);\n    }\n\n    public int px2dip(int i) {\n        float f = getDensity(context);\n        return (int) (((double) i - 0.5D) / (double) f);\n    }\n\n}\n"
  },
  {
    "path": "app/src/main/res/layout/activity_main.xml",
    "content": "    <LinearLayout\n        xmlns:android=\"http://schemas.android.com/apk/res/android\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"match_parent\"\n        android:orientation=\"vertical\"\n       >\n\n     <ListView android:layout_width=\"fill_parent\"\n         android:layout_height=\"fill_parent\"\n         android:listSelector=\"@android:color/transparent\"\n         android:id=\"@+id/lv_main\"\n         />\n\n    </LinearLayout>\n"
  },
  {
    "path": "app/src/main/res/layout/item_ninegridlayout.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<FrameLayout\n    android:layout_height=\"fill_parent\"\n    android:layout_width=\"fill_parent\"\n    xmlns:android=\"http://schemas.android.com/apk/res/android\">\n\n    <LinearLayout\n        android:layout_marginTop=\"10dp\"\n        android:layout_marginBottom=\"10dp\"\n        android:orientation=\"horizontal\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"match_parent\">\n\n        <ImageView\n            android:layout_width=\"50dp\"\n            android:background=\"@drawable/ic_launcher\"\n            android:layout_height=\"50dp\" />\n\n        <LinearLayout\n            android:layout_marginLeft=\"5dp\"\n            android:layout_width=\"fill_parent\"\n            android:orientation=\"vertical\"\n            android:layout_height=\"wrap_content\">\n\n            <TextView\n                android:text=\"小明\"\n                android:layout_width=\"wrap_content\"\n                android:layout_height=\"wrap_content\" />\n\n            <TextView\n                android:layout_marginTop=\"5dp\"\n                android:text=\"今天天气真好，好开心！！！！！！！！！！！！！！！！！\"\n                android:layout_width=\"wrap_content\"\n                android:layout_height=\"wrap_content\" />\n\n            <com.weixinninegridlayout.NineGridlayout\n                android:layout_marginTop=\"8dp\"\n                android:id=\"@+id/iv_ngrid_layout\"\n                android:layout_height=\"wrap_content\"\n                android:layout_width=\"match_parent\" />\n\n            <com.weixinninegridlayout.CustomImageView\n                android:layout_marginTop=\"8dp\"\n                android:id=\"@+id/iv_oneimage\"\n                android:layout_width=\"fill_parent\"\n                android:layout_height=\"wrap_content\" />\n\n            <TextView\n                android:layout_marginTop=\"8dp\"\n                android:text=\"3分钟前\"\n                android:layout_width=\"wrap_content\"\n                android:layout_height=\"wrap_content\" />\n        </LinearLayout>\n    </LinearLayout>\n</FrameLayout>"
  },
  {
    "path": "app/src/main/res/menu/menu_main.xml",
    "content": "<menu xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n    xmlns:tools=\"http://schemas.android.com/tools\" tools:context=\".MainActivity\">\n    <item android:id=\"@+id/action_settings\" android:title=\"@string/action_settings\"\n        android:orderInCategory=\"100\" app:showAsAction=\"never\" />\n</menu>\n"
  },
  {
    "path": "app/src/main/res/values/dimens.xml",
    "content": "<resources>\n    <!-- Default screen margins, per the Android Design guidelines. -->\n    <dimen name=\"activity_horizontal_margin\">16dp</dimen>\n    <dimen name=\"activity_vertical_margin\">16dp</dimen>\n</resources>\n"
  },
  {
    "path": "app/src/main/res/values/strings.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n\n    <string name=\"app_name\">WeixinNineGridLayout</string>\n    <string name=\"hello_world\">Hello world!</string>\n    <string name=\"action_settings\">Settings</string>\n\n</resources>\n"
  },
  {
    "path": "app/src/main/res/values/styles.xml",
    "content": "<resources>\n\n    <!-- Base application theme. -->\n    <style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.DarkActionBar\">\n        <!-- Customize your theme here. -->\n    </style>\n\n</resources>\n"
  },
  {
    "path": "app/src/main/res/values-w820dp/dimens.xml",
    "content": "<resources>\n    <!-- Example customization of dimensions originally defined in res/values/dimens.xml\n         (such as screen margins) for screens with more than 820dp of available width. This\n         would include 7\" and 10\" devices in landscape (~960dp and ~1280dp respectively). -->\n    <dimen name=\"activity_horizontal_margin\">64dp</dimen>\n</resources>\n"
  },
  {
    "path": "build.gradle",
    "content": "// Top-level build file where you can add configuration options common to all sub-projects/modules.\n\nbuildscript {\n    repositories {\n        jcenter()\n    }\n    dependencies {\n        classpath 'com.android.tools.build:gradle:1.0.0'\n\n        // NOTE: Do not place your application dependencies here; they belong\n        // in the individual module build.gradle files\n    }\n}\n\nallprojects {\n    repositories {\n        jcenter()\n    }\n}\n"
  },
  {
    "path": "gradle/wrapper/gradle-wrapper.properties",
    "content": "#Wed Apr 10 15:27:10 PDT 2013\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-2.2.1-all.zip\n"
  },
  {
    "path": "gradle.properties",
    "content": "# Project-wide Gradle settings.\n\n# IDE (e.g. Android Studio) users:\n# Gradle settings configured through the IDE *will override*\n# any settings specified in this file.\n\n# For more details on how to configure your build environment visit\n# http://www.gradle.org/docs/current/userguide/build_environment.html\n\n# Specifies the JVM arguments used for the daemon process.\n# The setting is particularly useful for tweaking memory settings.\n# Default value: -Xmx10248m -XX:MaxPermSize=256m\n# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8\n\n# When configured, Gradle will run in incubating parallel mode.\n# This option should only be used with decoupled projects. More details, visit\n# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects\n# org.gradle.parallel=true"
  },
  {
    "path": "gradlew",
    "content": "#!/usr/bin/env bash\n\n##############################################################################\n##\n##  Gradle start up script for UN*X\n##\n##############################################################################\n\n# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\nDEFAULT_JVM_OPTS=\"\"\n\nAPP_NAME=\"Gradle\"\nAPP_BASE_NAME=`basename \"$0\"`\n\n# Use the maximum available, or set MAX_FD != -1 to use that value.\nMAX_FD=\"maximum\"\n\nwarn ( ) {\n    echo \"$*\"\n}\n\ndie ( ) {\n    echo\n    echo \"$*\"\n    echo\n    exit 1\n}\n\n# OS specific support (must be 'true' or 'false').\ncygwin=false\nmsys=false\ndarwin=false\ncase \"`uname`\" in\n  CYGWIN* )\n    cygwin=true\n    ;;\n  Darwin* )\n    darwin=true\n    ;;\n  MINGW* )\n    msys=true\n    ;;\nesac\n\n# For Cygwin, ensure paths are in UNIX format before anything is touched.\nif $cygwin ; then\n    [ -n \"$JAVA_HOME\" ] && JAVA_HOME=`cygpath --unix \"$JAVA_HOME\"`\nfi\n\n# Attempt to set APP_HOME\n# Resolve links: $0 may be a link\nPRG=\"$0\"\n# Need this for relative symlinks.\nwhile [ -h \"$PRG\" ] ; do\n    ls=`ls -ld \"$PRG\"`\n    link=`expr \"$ls\" : '.*-> \\(.*\\)$'`\n    if expr \"$link\" : '/.*' > /dev/null; then\n        PRG=\"$link\"\n    else\n        PRG=`dirname \"$PRG\"`\"/$link\"\n    fi\ndone\nSAVED=\"`pwd`\"\ncd \"`dirname \\\"$PRG\\\"`/\" >&-\nAPP_HOME=\"`pwd -P`\"\ncd \"$SAVED\" >&-\n\nCLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar\n\n# Determine the Java command to use to start the JVM.\nif [ -n \"$JAVA_HOME\" ] ; then\n    if [ -x \"$JAVA_HOME/jre/sh/java\" ] ; then\n        # IBM's JDK on AIX uses strange locations for the executables\n        JAVACMD=\"$JAVA_HOME/jre/sh/java\"\n    else\n        JAVACMD=\"$JAVA_HOME/bin/java\"\n    fi\n    if [ ! -x \"$JAVACMD\" ] ; then\n        die \"ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\n    fi\nelse\n    JAVACMD=\"java\"\n    which java >/dev/null 2>&1 || die \"ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\nfi\n\n# Increase the maximum file descriptors if we can.\nif [ \"$cygwin\" = \"false\" -a \"$darwin\" = \"false\" ] ; then\n    MAX_FD_LIMIT=`ulimit -H -n`\n    if [ $? -eq 0 ] ; then\n        if [ \"$MAX_FD\" = \"maximum\" -o \"$MAX_FD\" = \"max\" ] ; then\n            MAX_FD=\"$MAX_FD_LIMIT\"\n        fi\n        ulimit -n $MAX_FD\n        if [ $? -ne 0 ] ; then\n            warn \"Could not set maximum file descriptor limit: $MAX_FD\"\n        fi\n    else\n        warn \"Could not query maximum file descriptor limit: $MAX_FD_LIMIT\"\n    fi\nfi\n\n# For Darwin, add options to specify how the application appears in the dock\nif $darwin; then\n    GRADLE_OPTS=\"$GRADLE_OPTS \\\"-Xdock:name=$APP_NAME\\\" \\\"-Xdock:icon=$APP_HOME/media/gradle.icns\\\"\"\nfi\n\n# For Cygwin, switch paths to Windows format before running java\nif $cygwin ; then\n    APP_HOME=`cygpath --path --mixed \"$APP_HOME\"`\n    CLASSPATH=`cygpath --path --mixed \"$CLASSPATH\"`\n\n    # We build the pattern for arguments to be converted via cygpath\n    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`\n    SEP=\"\"\n    for dir in $ROOTDIRSRAW ; do\n        ROOTDIRS=\"$ROOTDIRS$SEP$dir\"\n        SEP=\"|\"\n    done\n    OURCYGPATTERN=\"(^($ROOTDIRS))\"\n    # Add a user-defined pattern to the cygpath arguments\n    if [ \"$GRADLE_CYGPATTERN\" != \"\" ] ; then\n        OURCYGPATTERN=\"$OURCYGPATTERN|($GRADLE_CYGPATTERN)\"\n    fi\n    # Now convert the arguments - kludge to limit ourselves to /bin/sh\n    i=0\n    for arg in \"$@\" ; do\n        CHECK=`echo \"$arg\"|egrep -c \"$OURCYGPATTERN\" -`\n        CHECK2=`echo \"$arg\"|egrep -c \"^-\"`                                 ### Determine if an option\n\n        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition\n            eval `echo args$i`=`cygpath --path --ignore --mixed \"$arg\"`\n        else\n            eval `echo args$i`=\"\\\"$arg\\\"\"\n        fi\n        i=$((i+1))\n    done\n    case $i in\n        (0) set -- ;;\n        (1) set -- \"$args0\" ;;\n        (2) set -- \"$args0\" \"$args1\" ;;\n        (3) set -- \"$args0\" \"$args1\" \"$args2\" ;;\n        (4) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" ;;\n        (5) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" ;;\n        (6) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" ;;\n        (7) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" ;;\n        (8) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" \"$args7\" ;;\n        (9) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" \"$args7\" \"$args8\" ;;\n    esac\nfi\n\n# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules\nfunction splitJvmOpts() {\n    JVM_OPTS=(\"$@\")\n}\neval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS\nJVM_OPTS[${#JVM_OPTS[*]}]=\"-Dorg.gradle.appname=$APP_BASE_NAME\"\n\nexec \"$JAVACMD\" \"${JVM_OPTS[@]}\" -classpath \"$CLASSPATH\" org.gradle.wrapper.GradleWrapperMain \"$@\"\n"
  },
  {
    "path": "gradlew.bat",
    "content": "@if \"%DEBUG%\" == \"\" @echo off\n@rem ##########################################################################\n@rem\n@rem  Gradle startup script for Windows\n@rem\n@rem ##########################################################################\n\n@rem Set local scope for the variables with windows NT shell\nif \"%OS%\"==\"Windows_NT\" setlocal\n\n@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\nset DEFAULT_JVM_OPTS=\n\nset DIRNAME=%~dp0\nif \"%DIRNAME%\" == \"\" set DIRNAME=.\nset APP_BASE_NAME=%~n0\nset APP_HOME=%DIRNAME%\n\n@rem Find java.exe\nif defined JAVA_HOME goto findJavaFromJavaHome\n\nset JAVA_EXE=java.exe\n%JAVA_EXE% -version >NUL 2>&1\nif \"%ERRORLEVEL%\" == \"0\" goto init\n\necho.\necho ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\necho.\necho Please set the JAVA_HOME variable in your environment to match the\necho location of your Java installation.\n\ngoto fail\n\n:findJavaFromJavaHome\nset JAVA_HOME=%JAVA_HOME:\"=%\nset JAVA_EXE=%JAVA_HOME%/bin/java.exe\n\nif exist \"%JAVA_EXE%\" goto init\n\necho.\necho ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%\necho.\necho Please set the JAVA_HOME variable in your environment to match the\necho location of your Java installation.\n\ngoto fail\n\n:init\n@rem Get command-line arguments, handling Windowz variants\n\nif not \"%OS%\" == \"Windows_NT\" goto win9xME_args\nif \"%@eval[2+2]\" == \"4\" goto 4NT_args\n\n:win9xME_args\n@rem Slurp the command line arguments.\nset CMD_LINE_ARGS=\nset _SKIP=2\n\n:win9xME_args_slurp\nif \"x%~1\" == \"x\" goto execute\n\nset CMD_LINE_ARGS=%*\ngoto execute\n\n:4NT_args\n@rem Get arguments from the 4NT Shell from JP Software\nset CMD_LINE_ARGS=%$\n\n:execute\n@rem Setup the command line\n\nset CLASSPATH=%APP_HOME%\\gradle\\wrapper\\gradle-wrapper.jar\n\n@rem Execute Gradle\n\"%JAVA_EXE%\" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% \"-Dorg.gradle.appname=%APP_BASE_NAME%\" -classpath \"%CLASSPATH%\" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%\n\n:end\n@rem End local scope for the variables with windows NT shell\nif \"%ERRORLEVEL%\"==\"0\" goto mainEnd\n\n:fail\nrem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of\nrem the _cmd.exe /c_ return code!\nif  not \"\" == \"%GRADLE_EXIT_CONSOLE%\" exit 1\nexit /b 1\n\n:mainEnd\nif \"%OS%\"==\"Windows_NT\" endlocal\n\n:omega\n"
  },
  {
    "path": "picasso/Action.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.graphics.Bitmap;\nimport android.graphics.drawable.Drawable;\nimport java.lang.ref.ReferenceQueue;\nimport java.lang.ref.WeakReference;\n\nabstract class Action<T> {\n  static class RequestWeakReference<T> extends WeakReference<T> {\n    final Action action;\n\n    public RequestWeakReference(Action action, T referent, ReferenceQueue<? super T> q) {\n      super(referent, q);\n      this.action = action;\n    }\n  }\n\n  final Picasso picasso;\n  final Request request;\n  final WeakReference<T> target;\n  final boolean skipCache;\n  final boolean noFade;\n  final int errorResId;\n  final Drawable errorDrawable;\n  final String key;\n\n  boolean willReplay;\n  boolean cancelled;\n\n  Action(Picasso picasso, T target, Request request, boolean skipCache, boolean noFade,\n      int errorResId, Drawable errorDrawable, String key) {\n    this.picasso = picasso;\n    this.request = request;\n    this.target = new RequestWeakReference<T>(this, target, picasso.referenceQueue);\n    this.skipCache = skipCache;\n    this.noFade = noFade;\n    this.errorResId = errorResId;\n    this.errorDrawable = errorDrawable;\n    this.key = key;\n  }\n\n  abstract void complete(Bitmap result, Picasso.LoadedFrom from);\n\n  abstract void error();\n\n  void cancel() {\n    cancelled = true;\n  }\n\n  Request getRequest() {\n    return request;\n  }\n\n  T getTarget() {\n    return target.get();\n  }\n\n  String getKey() {\n    return key;\n  }\n\n  boolean isCancelled() {\n    return cancelled;\n  }\n\n  boolean willReplay() {\n    return willReplay;\n  }\n\n  Picasso getPicasso() {\n    return picasso;\n  }\n}\n"
  },
  {
    "path": "picasso/AssetRequestHandler.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.content.Context;\nimport android.content.res.AssetManager;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.net.Uri;\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport static android.content.ContentResolver.SCHEME_FILE;\nimport static com.squareup.picasso.Picasso.LoadedFrom.DISK;\n\nclass AssetRequestHandler extends RequestHandler {\n  protected static final String ANDROID_ASSET = \"android_asset\";\n  private static final int ASSET_PREFIX_LENGTH =\n      (SCHEME_FILE + \":///\" + ANDROID_ASSET + \"/\").length();\n\n  private final AssetManager assetManager;\n\n  public AssetRequestHandler(Context context) {\n    assetManager = context.getAssets();\n  }\n\n  @Override public boolean canHandleRequest(Request data) {\n    Uri uri = data.uri;\n    return (SCHEME_FILE.equals(uri.getScheme())\n        && !uri.getPathSegments().isEmpty() && ANDROID_ASSET.equals(uri.getPathSegments().get(0)));\n  }\n\n  @Override public Result load(Request data) throws IOException {\n    String filePath = data.uri.toString().substring(ASSET_PREFIX_LENGTH);\n    return new Result(decodeAsset(data, filePath), DISK);\n  }\n\n  Bitmap decodeAsset(Request data, String filePath) throws IOException {\n    final BitmapFactory.Options options = createBitmapOptions(data);\n    if (requiresInSampleSize(options)) {\n      InputStream is = null;\n      try {\n        is = assetManager.open(filePath);\n        BitmapFactory.decodeStream(is, null, options);\n      } finally {\n        Utils.closeQuietly(is);\n      }\n      calculateInSampleSize(data.targetWidth, data.targetHeight, options);\n    }\n    InputStream is = assetManager.open(filePath);\n    try {\n      return BitmapFactory.decodeStream(is, null, options);\n    } finally {\n      Utils.closeQuietly(is);\n    }\n  }\n}\n"
  },
  {
    "path": "picasso/BitmapHunter.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.graphics.Bitmap;\nimport android.graphics.Matrix;\nimport android.net.NetworkInfo;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.io.StringWriter;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.Future;\n\nimport static com.squareup.picasso.Picasso.LoadedFrom.MEMORY;\nimport static com.squareup.picasso.Utils.OWNER_HUNTER;\nimport static com.squareup.picasso.Utils.VERB_DECODED;\nimport static com.squareup.picasso.Utils.VERB_EXECUTING;\nimport static com.squareup.picasso.Utils.VERB_JOINED;\nimport static com.squareup.picasso.Utils.VERB_REMOVED;\nimport static com.squareup.picasso.Utils.VERB_TRANSFORMED;\nimport static com.squareup.picasso.Utils.getLogIdsForHunter;\nimport static com.squareup.picasso.Utils.log;\n\nclass BitmapHunter implements Runnable {\n  /**\n   * Global lock for bitmap decoding to ensure that we are only are decoding one at a time. Since\n   * this will only ever happen in background threads we help avoid excessive memory thrashing as\n   * well as potential OOMs. Shamelessly stolen from Volley.\n   */\n  private static final Object DECODE_LOCK = new Object();\n\n  private static final ThreadLocal<StringBuilder> NAME_BUILDER = new ThreadLocal<StringBuilder>() {\n    @Override protected StringBuilder initialValue() {\n      return new StringBuilder(Utils.THREAD_PREFIX);\n    }\n  };\n\n  final Picasso picasso;\n  final Dispatcher dispatcher;\n  final Cache cache;\n  final Stats stats;\n  final String key;\n  final Request data;\n  final boolean skipMemoryCache;\n  final RequestHandler requestHandler;\n\n  Action action;\n  List<Action> actions;\n  Bitmap result;\n  Future<?> future;\n  Picasso.LoadedFrom loadedFrom;\n  Exception exception;\n  int exifRotation; // Determined during decoding of original resource.\n  int retryCount;\n\n  BitmapHunter(Picasso picasso, Dispatcher dispatcher, Cache cache, Stats stats, Action action,\n               RequestHandler requestHandler) {\n    this.picasso = picasso;\n    this.dispatcher = dispatcher;\n    this.cache = cache;\n    this.stats = stats;\n    this.key = action.getKey();\n    this.data = action.getRequest();\n    this.skipMemoryCache = action.skipCache;\n    this.requestHandler = requestHandler;\n    this.retryCount = requestHandler.getRetryCount();\n    this.action = action;\n  }\n\n  @Override public void run() {\n    try {\n      updateThreadName(data);\n\n      if (picasso.loggingEnabled) {\n        log(OWNER_HUNTER, VERB_EXECUTING, getLogIdsForHunter(this));\n      }\n\n      result = hunt();\n\n      if (result == null) {\n        dispatcher.dispatchFailed(this);\n      } else {\n        dispatcher.dispatchComplete(this);\n      }\n    } catch (Downloader.ResponseException e) {\n      exception = e;\n      dispatcher.dispatchFailed(this);\n    } catch (IOException e) {\n      exception = e;\n      dispatcher.dispatchRetry(this);\n    } catch (OutOfMemoryError e) {\n      StringWriter writer = new StringWriter();\n      stats.createSnapshot().dump(new PrintWriter(writer));\n      exception = new RuntimeException(writer.toString(), e);\n      dispatcher.dispatchFailed(this);\n    } catch (Exception e) {\n      exception = e;\n      dispatcher.dispatchFailed(this);\n    } finally {\n      Thread.currentThread().setName(Utils.THREAD_IDLE_NAME);\n    }\n  }\n\n  Bitmap hunt() throws IOException {\n    Bitmap bitmap = null;\n\n    if (!skipMemoryCache) {\n      bitmap = cache.get(key);\n      if (bitmap != null) {\n        stats.dispatchCacheHit();\n        loadedFrom = MEMORY;\n        if (picasso.loggingEnabled) {\n          log(OWNER_HUNTER, VERB_DECODED, data.logId(), \"from cache\");\n        }\n        return bitmap;\n      }\n    }\n\n    data.loadFromLocalCacheOnly = (retryCount == 0);\n    RequestHandler.Result result = requestHandler.load(data);\n    if (result != null) {\n      bitmap = result.getBitmap();\n      loadedFrom = result.getLoadedFrom();\n      exifRotation = result.getExifOrientation();\n    }\n\n    if (bitmap != null) {\n      if (picasso.loggingEnabled) {\n        log(OWNER_HUNTER, VERB_DECODED, data.logId());\n      }\n      stats.dispatchBitmapDecoded(bitmap);\n      if (data.needsTransformation() || exifRotation != 0) {\n        synchronized (DECODE_LOCK) {\n          if (data.needsMatrixTransform() || exifRotation != 0) {\n            bitmap = transformResult(data, bitmap, exifRotation);\n            if (picasso.loggingEnabled) {\n              log(OWNER_HUNTER, VERB_TRANSFORMED, data.logId());\n            }\n          }\n          if (data.hasCustomTransformations()) {\n            bitmap = applyCustomTransformations(data.transformations, bitmap);\n            if (picasso.loggingEnabled) {\n              log(OWNER_HUNTER, VERB_TRANSFORMED, data.logId(), \"from custom transformations\");\n            }\n          }\n        }\n        if (bitmap != null) {\n          stats.dispatchBitmapTransformed(bitmap);\n        }\n      }\n    }\n\n    return bitmap;\n  }\n\n  void attach(Action action) {\n    boolean loggingEnabled = picasso.loggingEnabled;\n    Request request = action.request;\n\n    if (this.action == null) {\n      this.action = action;\n      if (loggingEnabled) {\n        if (actions == null || actions.isEmpty()) {\n          log(OWNER_HUNTER, VERB_JOINED, request.logId(), \"to empty hunter\");\n        } else {\n          log(OWNER_HUNTER, VERB_JOINED, request.logId(), getLogIdsForHunter(this, \"to \"));\n        }\n      }\n      return;\n    }\n\n    if (actions == null) {\n      actions = new ArrayList<Action>(3);\n    }\n\n    actions.add(action);\n\n    if (loggingEnabled) {\n      log(OWNER_HUNTER, VERB_JOINED, request.logId(), getLogIdsForHunter(this, \"to \"));\n    }\n  }\n\n  void detach(Action action) {\n    if (this.action == action) {\n      this.action = null;\n    } else if (actions != null) {\n      actions.remove(action);\n    }\n\n    if (picasso.loggingEnabled) {\n      log(OWNER_HUNTER, VERB_REMOVED, action.request.logId(), getLogIdsForHunter(this, \"from \"));\n    }\n  }\n\n  boolean cancel() {\n    return action == null\n        && (actions == null || actions.isEmpty())\n        && future != null\n        && future.cancel(false);\n  }\n\n  boolean isCancelled() {\n    return future != null && future.isCancelled();\n  }\n\n  boolean shouldSkipMemoryCache() {\n    return skipMemoryCache;\n  }\n\n  boolean shouldRetry(boolean airplaneMode, NetworkInfo info) {\n    boolean hasRetries = retryCount > 0;\n    if (!hasRetries) {\n      return false;\n    }\n    retryCount--;\n    return requestHandler.shouldRetry(airplaneMode, info);\n  }\n\n  boolean supportsReplay() {\n    return requestHandler.supportsReplay();\n  }\n\n  Bitmap getResult() {\n    return result;\n  }\n\n  String getKey() {\n    return key;\n  }\n\n  Request getData() {\n    return data;\n  }\n\n  Action getAction() {\n    return action;\n  }\n\n  Picasso getPicasso() {\n    return picasso;\n  }\n\n  List<Action> getActions() {\n    return actions;\n  }\n\n  Exception getException() {\n    return exception;\n  }\n\n  Picasso.LoadedFrom getLoadedFrom() {\n    return loadedFrom;\n  }\n\n  static void updateThreadName(Request data) {\n    String name = data.getName();\n\n    StringBuilder builder = NAME_BUILDER.get();\n    builder.ensureCapacity(Utils.THREAD_PREFIX.length() + name.length());\n    builder.replace(Utils.THREAD_PREFIX.length(), builder.length(), name);\n\n    Thread.currentThread().setName(builder.toString());\n  }\n\n  static BitmapHunter forRequest(Picasso picasso, Dispatcher dispatcher,\n      Cache cache, Stats stats, Action action) {\n    Request request = action.getRequest();\n\n    List<RequestHandler> requestHandlers = picasso.getRequestHandlers();\n    final int count = requestHandlers.size();\n    for (int i = 0; i < count; i++) {\n      RequestHandler requestHandler = requestHandlers.get(i);\n      if (requestHandler.canHandleRequest(request)) {\n        return new BitmapHunter(picasso, dispatcher, cache, stats, action, requestHandler);\n      }\n    }\n\n    throw new IllegalStateException(\"Unrecognized type of request: \" + request);\n  }\n\n  static Bitmap applyCustomTransformations(List<Transformation> transformations, Bitmap result) {\n    for (int i = 0, count = transformations.size(); i < count; i++) {\n      final Transformation transformation = transformations.get(i);\n      Bitmap newResult = transformation.transform(result);\n\n      if (newResult == null) {\n        final StringBuilder builder = new StringBuilder() //\n            .append(\"Transformation \")\n            .append(transformation.key())\n            .append(\" returned null after \")\n            .append(i)\n            .append(\" previous transformation(s).\\n\\nTransformation list:\\n\");\n        for (Transformation t : transformations) {\n          builder.append(t.key()).append('\\n');\n        }\n        Picasso.HANDLER.post(new Runnable() {\n          @Override public void run() {\n            throw new NullPointerException(builder.toString());\n          }\n        });\n        return null;\n      }\n\n      if (newResult == result && result.isRecycled()) {\n        Picasso.HANDLER.post(new Runnable() {\n          @Override public void run() {\n            throw new IllegalStateException(\"Transformation \"\n                + transformation.key()\n                + \" returned input Bitmap but recycled it.\");\n          }\n        });\n        return null;\n      }\n\n      // If the transformation returned a new bitmap ensure they recycled the original.\n      if (newResult != result && !result.isRecycled()) {\n        Picasso.HANDLER.post(new Runnable() {\n          @Override public void run() {\n            throw new IllegalStateException(\"Transformation \"\n                + transformation.key()\n                + \" mutated input Bitmap but failed to recycle the original.\");\n          }\n        });\n        return null;\n      }\n\n      result = newResult;\n    }\n    return result;\n  }\n\n  static Bitmap transformResult(Request data, Bitmap result, int exifRotation) {\n    int inWidth = result.getWidth();\n    int inHeight = result.getHeight();\n\n    int drawX = 0;\n    int drawY = 0;\n    int drawWidth = inWidth;\n    int drawHeight = inHeight;\n\n    Matrix matrix = new Matrix();\n\n    if (data.needsMatrixTransform()) {\n      int targetWidth = data.targetWidth;\n      int targetHeight = data.targetHeight;\n\n      float targetRotation = data.rotationDegrees;\n      if (targetRotation != 0) {\n        if (data.hasRotationPivot) {\n          matrix.setRotate(targetRotation, data.rotationPivotX, data.rotationPivotY);\n        } else {\n          matrix.setRotate(targetRotation);\n        }\n      }\n\n      if (data.centerCrop) {\n        float widthRatio = targetWidth / (float) inWidth;\n        float heightRatio = targetHeight / (float) inHeight;\n        float scale;\n        if (widthRatio > heightRatio) {\n          scale = widthRatio;\n          int newSize = (int) Math.ceil(inHeight * (heightRatio / widthRatio));\n          drawY = (inHeight - newSize) / 2;\n          drawHeight = newSize;\n        } else {\n          scale = heightRatio;\n          int newSize = (int) Math.ceil(inWidth * (widthRatio / heightRatio));\n          drawX = (inWidth - newSize) / 2;\n          drawWidth = newSize;\n        }\n        matrix.preScale(scale, scale);\n      } else if (data.centerInside) {\n        float widthRatio = targetWidth / (float) inWidth;\n        float heightRatio = targetHeight / (float) inHeight;\n        float scale = widthRatio < heightRatio ? widthRatio : heightRatio;\n        matrix.preScale(scale, scale);\n      } else if (targetWidth != 0 && targetHeight != 0 //\n          && (targetWidth != inWidth || targetHeight != inHeight)) {\n        // If an explicit target size has been specified and they do not match the results bounds,\n        // pre-scale the existing matrix appropriately.\n        float sx = targetWidth / (float) inWidth;\n        float sy = targetHeight / (float) inHeight;\n        matrix.preScale(sx, sy);\n      }\n    }\n\n    if (exifRotation != 0) {\n      matrix.preRotate(exifRotation);\n    }\n\n    Bitmap newResult =\n        Bitmap.createBitmap(result, drawX, drawY, drawWidth, drawHeight, matrix, true);\n    if (newResult != result) {\n      result.recycle();\n      result = newResult;\n    }\n\n    return result;\n  }\n}\n"
  },
  {
    "path": "picasso/Cache.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.graphics.Bitmap;\n\n/**\n * A memory cache for storing the most recently used images.\n * <p>\n * <em>Note:</em> The {@link com.squareup.picasso.Cache} is accessed by multiple threads. You must ensure\n * your {@link com.squareup.picasso.Cache} implementation is thread safe when {@link com.squareup.picasso.Cache#get(String)} or {@link\n * com.squareup.picasso.Cache#set(String, android.graphics.Bitmap)} is called.\n */\npublic interface Cache {\n  /** Retrieve an image for the specified {@code key} or {@code null}. */\n  Bitmap get(String key);\n\n  /** Store an image in the cache for the specified {@code key}. */\n  void set(String key, Bitmap bitmap);\n\n  /** Returns the current size of the cache in bytes. */\n  int size();\n\n  /** Returns the maximum size in bytes that the cache can hold. */\n  int maxSize();\n\n  /** Clears the cache. */\n  void clear();\n\n  /** A cache which does not store any values. */\n  Cache NONE = new Cache() {\n    @Override public Bitmap get(String key) {\n      return null;\n    }\n\n    @Override public void set(String key, Bitmap bitmap) {\n      // Ignore.\n    }\n\n    @Override public int size() {\n      return 0;\n    }\n\n    @Override public int maxSize() {\n      return 0;\n    }\n\n    @Override public void clear() {\n    }\n  };\n}\n"
  },
  {
    "path": "picasso/Callback.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\npublic interface Callback {\n  void onSuccess();\n\n  void onError();\n\n  public static class EmptyCallback implements Callback {\n\n    @Override public void onSuccess() {\n    }\n\n    @Override public void onError() {\n    }\n  }\n}\n"
  },
  {
    "path": "picasso/ContactsPhotoRequestHandler.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.annotation.TargetApi;\nimport android.content.ContentResolver;\nimport android.content.Context;\nimport android.content.UriMatcher;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.net.Uri;\nimport android.provider.ContactsContract;\n\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport static android.content.ContentResolver.SCHEME_CONTENT;\nimport static android.os.Build.VERSION.SDK_INT;\nimport static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;\nimport static android.provider.ContactsContract.Contacts.openContactPhotoInputStream;\nimport static com.squareup.picasso.Picasso.LoadedFrom.DISK;\n\nclass ContactsPhotoRequestHandler extends RequestHandler {\n  /** A lookup uri (e.g. content://com.android.contacts/contacts/lookup/3570i61d948d30808e537) */\n  private static final int ID_LOOKUP = 1;\n  /** A contact thumbnail uri (e.g. content://com.android.contacts/contacts/38/photo) */\n  private static final int ID_THUMBNAIL = 2;\n  /** A contact uri (e.g. content://com.android.contacts/contacts/38) */\n  private static final int ID_CONTACT = 3;\n  /**\n   * A contact display photo (high resolution) uri\n   * (e.g. content://com.android.contacts/display_photo/5)\n   */\n  private static final int ID_DISPLAY_PHOTO = 4;\n\n  private static final UriMatcher matcher;\n\n  static {\n    matcher = new UriMatcher(UriMatcher.NO_MATCH);\n    matcher.addURI(ContactsContract.AUTHORITY, \"contacts/lookup/*/#\", ID_LOOKUP);\n    matcher.addURI(ContactsContract.AUTHORITY, \"contacts/lookup/*\", ID_LOOKUP);\n    matcher.addURI(ContactsContract.AUTHORITY, \"contacts/#/photo\", ID_THUMBNAIL);\n    matcher.addURI(ContactsContract.AUTHORITY, \"contacts/#\", ID_CONTACT);\n    matcher.addURI(ContactsContract.AUTHORITY, \"display_photo/#\", ID_DISPLAY_PHOTO);\n  }\n\n  final Context context;\n\n  ContactsPhotoRequestHandler(Context context) {\n    this.context = context;\n  }\n\n  @Override public boolean canHandleRequest(Request data) {\n    final Uri uri = data.uri;\n    return (SCHEME_CONTENT.equals(uri.getScheme())\n        && ContactsContract.Contacts.CONTENT_URI.getHost().equals(uri.getHost())\n        && !uri.getPathSegments().contains(ContactsContract.Contacts.Photo.CONTENT_DIRECTORY));\n  }\n\n  @Override public Result load(Request data) throws IOException {\n    InputStream is = null;\n    try {\n      is = getInputStream(data);\n      return new Result(decodeStream(is, data), DISK);\n    } finally {\n      Utils.closeQuietly(is);\n    }\n  }\n\n  private InputStream getInputStream(Request data) throws IOException {\n    ContentResolver contentResolver = context.getContentResolver();\n    Uri uri = data.uri;\n    switch (matcher.match(uri)) {\n      case ID_LOOKUP:\n        uri = ContactsContract.Contacts.lookupContact(contentResolver, uri);\n        if (uri == null) {\n          return null;\n        }\n        // Resolved the uri to a contact uri, intentionally fall through to process the resolved uri\n      case ID_CONTACT:\n        if (SDK_INT < ICE_CREAM_SANDWICH) {\n          return openContactPhotoInputStream(contentResolver, uri);\n        } else {\n          return ContactPhotoStreamIcs.get(contentResolver, uri);\n        }\n      case ID_THUMBNAIL:\n      case ID_DISPLAY_PHOTO:\n        return contentResolver.openInputStream(uri);\n      default:\n        throw new IllegalStateException(\"Invalid uri: \" + uri);\n    }\n  }\n\n  private Bitmap decodeStream(InputStream stream, Request data) throws IOException {\n    if (stream == null) {\n      return null;\n    }\n    final BitmapFactory.Options options = createBitmapOptions(data);\n    if (requiresInSampleSize(options)) {\n      InputStream is = getInputStream(data);\n      try {\n        BitmapFactory.decodeStream(is, null, options);\n      } finally {\n        Utils.closeQuietly(is);\n      }\n      calculateInSampleSize(data.targetWidth, data.targetHeight, options);\n    }\n    return BitmapFactory.decodeStream(stream, null, options);\n  }\n\n  @TargetApi(ICE_CREAM_SANDWICH)\n  private static class ContactPhotoStreamIcs {\n    static InputStream get(ContentResolver contentResolver, Uri uri) {\n      return openContactPhotoInputStream(contentResolver, uri, true);\n    }\n  }\n}\n"
  },
  {
    "path": "picasso/ContentStreamRequestHandler.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.content.ContentResolver;\nimport android.content.Context;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport static android.content.ContentResolver.SCHEME_CONTENT;\nimport static com.squareup.picasso.Picasso.LoadedFrom.DISK;\n\nclass ContentStreamRequestHandler extends RequestHandler {\n  final Context context;\n\n  ContentStreamRequestHandler(Context context) {\n    this.context = context;\n  }\n\n  @Override public boolean canHandleRequest(Request data) {\n    return SCHEME_CONTENT.equals(data.uri.getScheme());\n  }\n\n  @Override public Result load(Request data) throws IOException {\n    return new Result(decodeContentStream(data), DISK);\n  }\n\n  protected Bitmap decodeContentStream(Request data) throws IOException {\n    ContentResolver contentResolver = context.getContentResolver();\n    final BitmapFactory.Options options = createBitmapOptions(data);\n    if (requiresInSampleSize(options)) {\n      InputStream is = null;\n      try {\n        is = contentResolver.openInputStream(data.uri);\n        BitmapFactory.decodeStream(is, null, options);\n      } finally {\n        Utils.closeQuietly(is);\n      }\n      calculateInSampleSize(data.targetWidth, data.targetHeight, options);\n    }\n    InputStream is = contentResolver.openInputStream(data.uri);\n    try {\n      return BitmapFactory.decodeStream(is, null, options);\n    } finally {\n      Utils.closeQuietly(is);\n    }\n  }\n}\n"
  },
  {
    "path": "picasso/DeferredRequestCreator.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.view.ViewTreeObserver;\nimport android.widget.ImageView;\nimport java.lang.ref.WeakReference;\n\nclass DeferredRequestCreator implements ViewTreeObserver.OnPreDrawListener {\n\n  final RequestCreator creator;\n  final WeakReference<ImageView> target;\n  Callback callback;\n\nDeferredRequestCreator(RequestCreator creator, ImageView target) {\n    this(creator, target, null);\n  }\n\n  DeferredRequestCreator(RequestCreator creator, ImageView target, Callback callback) {\n    this.creator = creator;\n    this.target = new WeakReference<ImageView>(target);\n    this.callback = callback;\n    target.getViewTreeObserver().addOnPreDrawListener(this);\n  }\n\n  @Override public boolean onPreDraw() {\n    ImageView target = this.target.get();\n    if (target == null) {\n      return true;\n    }\n    ViewTreeObserver vto = target.getViewTreeObserver();\n    if (!vto.isAlive()) {\n      return true;\n    }\n\n    int width = target.getWidth();\n    int height = target.getHeight();\n\n    if (width <= 0 || height <= 0) {\n      return true;\n    }\n\n    vto.removeOnPreDrawListener(this);\n\n    this.creator.unfit().resize(width, height).into(target, callback);\n    return true;\n  }\n\n  void cancel() {\n    callback = null;\n    ImageView target = this.target.get();\n    if (target == null) {\n      return;\n    }\n    ViewTreeObserver vto = target.getViewTreeObserver();\n    if (!vto.isAlive()) {\n      return;\n    }\n    vto.removeOnPreDrawListener(this);\n  }\n}\n"
  },
  {
    "path": "picasso/Dispatcher.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.Manifest;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.net.ConnectivityManager;\nimport android.net.NetworkInfo;\nimport android.os.Handler;\nimport android.os.HandlerThread;\nimport android.os.Looper;\nimport android.os.Message;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.WeakHashMap;\nimport java.util.concurrent.ExecutorService;\n\nimport static android.content.Context.CONNECTIVITY_SERVICE;\nimport static android.content.Intent.ACTION_AIRPLANE_MODE_CHANGED;\nimport static android.net.ConnectivityManager.CONNECTIVITY_ACTION;\nimport static android.os.Process.THREAD_PRIORITY_BACKGROUND;\nimport static com.squareup.picasso.BitmapHunter.forRequest;\nimport static com.squareup.picasso.Utils.OWNER_DISPATCHER;\nimport static com.squareup.picasso.Utils.VERB_BATCHED;\nimport static com.squareup.picasso.Utils.VERB_CANCELED;\nimport static com.squareup.picasso.Utils.VERB_DELIVERED;\nimport static com.squareup.picasso.Utils.VERB_ENQUEUED;\nimport static com.squareup.picasso.Utils.VERB_IGNORED;\nimport static com.squareup.picasso.Utils.VERB_REPLAYING;\nimport static com.squareup.picasso.Utils.VERB_RETRYING;\nimport static com.squareup.picasso.Utils.getLogIdsForHunter;\nimport static com.squareup.picasso.Utils.getService;\nimport static com.squareup.picasso.Utils.hasPermission;\nimport static com.squareup.picasso.Utils.log;\n\nclass Dispatcher {\n  private static final int RETRY_DELAY = 500;\n  private static final int AIRPLANE_MODE_ON = 1;\n  private static final int AIRPLANE_MODE_OFF = 0;\n\n  static final int REQUEST_SUBMIT = 1;\n  static final int REQUEST_CANCEL = 2;\n  static final int REQUEST_GCED = 3;\n  static final int HUNTER_COMPLETE = 4;\n  static final int HUNTER_RETRY = 5;\n  static final int HUNTER_DECODE_FAILED = 6;\n  static final int HUNTER_DELAY_NEXT_BATCH = 7;\n  static final int HUNTER_BATCH_COMPLETE = 8;\n  static final int NETWORK_STATE_CHANGE = 9;\n  static final int AIRPLANE_MODE_CHANGE = 10;\n\n  private static final String DISPATCHER_THREAD_NAME = \"Dispatcher\";\n  private static final int BATCH_DELAY = 200; // ms\n\n  final DispatcherThread dispatcherThread;\n  final Context context;\n  final ExecutorService service;\n  final Downloader downloader;\n  final Map<String, BitmapHunter> hunterMap;\n  final Map<Object, Action> failedActions;\n  final Handler handler;\n  final Handler mainThreadHandler;\n  final Cache cache;\n  final Stats stats;\n  final List<BitmapHunter> batch;\n  final NetworkBroadcastReceiver receiver;\n  final boolean scansNetworkChanges;\n\n  boolean airplaneMode;\n\n  Dispatcher(Context context, ExecutorService service, Handler mainThreadHandler,\n      Downloader downloader, Cache cache, Stats stats) {\n    this.dispatcherThread = new DispatcherThread();\n    this.dispatcherThread.start();\n    this.context = context;\n    this.service = service;\n    this.hunterMap = new LinkedHashMap<String, BitmapHunter>();\n    this.failedActions = new WeakHashMap<Object, Action>();\n    this.handler = new DispatcherHandler(dispatcherThread.getLooper(), this);\n    this.downloader = downloader;\n    this.mainThreadHandler = mainThreadHandler;\n    this.cache = cache;\n    this.stats = stats;\n    this.batch = new ArrayList<BitmapHunter>(4);\n    this.airplaneMode = Utils.isAirplaneModeOn(this.context);\n    this.scansNetworkChanges = hasPermission(context, Manifest.permission.ACCESS_NETWORK_STATE);\n    this.receiver = new NetworkBroadcastReceiver(this);\n    receiver.register();\n  }\n\n  void shutdown() {\n    service.shutdown();\n    dispatcherThread.quit();\n    receiver.unregister();\n  }\n\n  void dispatchSubmit(Action action) {\n    handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action));\n  }\n\n  void dispatchCancel(Action action) {\n    handler.sendMessage(handler.obtainMessage(REQUEST_CANCEL, action));\n  }\n\n  void dispatchComplete(BitmapHunter hunter) {\n    handler.sendMessage(handler.obtainMessage(HUNTER_COMPLETE, hunter));\n  }\n\n  void dispatchRetry(BitmapHunter hunter) {\n    handler.sendMessageDelayed(handler.obtainMessage(HUNTER_RETRY, hunter), RETRY_DELAY);\n  }\n\n  void dispatchFailed(BitmapHunter hunter) {\n    handler.sendMessage(handler.obtainMessage(HUNTER_DECODE_FAILED, hunter));\n  }\n\n  void dispatchNetworkStateChange(NetworkInfo info) {\n    handler.sendMessage(handler.obtainMessage(NETWORK_STATE_CHANGE, info));\n  }\n\n  void dispatchAirplaneModeChange(boolean airplaneMode) {\n    handler.sendMessage(handler.obtainMessage(AIRPLANE_MODE_CHANGE,\n        airplaneMode ? AIRPLANE_MODE_ON : AIRPLANE_MODE_OFF, 0));\n  }\n\n  void performSubmit(Action action) {\n    BitmapHunter hunter = hunterMap.get(action.getKey());\n    if (hunter != null) {\n      hunter.attach(action);\n      return;\n    }\n\n    if (service.isShutdown()) {\n      if (action.getPicasso().loggingEnabled) {\n        log(OWNER_DISPATCHER, VERB_IGNORED, action.request.logId(), \"because shut down\");\n      }\n      return;\n    }\n\n    hunter = forRequest(action.getPicasso(), this, cache, stats, action);\n    hunter.future = service.submit(hunter);\n    hunterMap.put(action.getKey(), hunter);\n    failedActions.remove(action.getTarget());\n\n    if (action.getPicasso().loggingEnabled) {\n      log(OWNER_DISPATCHER, VERB_ENQUEUED, action.request.logId());\n    }\n  }\n\n  void performCancel(Action action) {\n    String key = action.getKey();\n    BitmapHunter hunter = hunterMap.get(key);\n    if (hunter != null) {\n      hunter.detach(action);\n      if (hunter.cancel()) {\n        hunterMap.remove(key);\n        if (action.getPicasso().loggingEnabled) {\n          log(OWNER_DISPATCHER, VERB_CANCELED, action.getRequest().logId());\n        }\n      }\n    }\n    Action remove = failedActions.remove(action.getTarget());\n    if (remove != null && remove.getPicasso().loggingEnabled) {\n      log(OWNER_DISPATCHER, VERB_CANCELED, remove.getRequest().logId(), \"from replaying\");\n    }\n  }\n\n  void performRetry(BitmapHunter hunter) {\n    if (hunter.isCancelled()) return;\n\n    if (service.isShutdown()) {\n      performError(hunter, false);\n      return;\n    }\n\n    NetworkInfo networkInfo = null;\n    if (scansNetworkChanges) {\n      ConnectivityManager connectivityManager = getService(context, CONNECTIVITY_SERVICE);\n      networkInfo = connectivityManager.getActiveNetworkInfo();\n    }\n\n    boolean hasConnectivity = networkInfo != null && networkInfo.isConnected();\n    boolean shouldRetryHunter = hunter.shouldRetry(airplaneMode, networkInfo);\n    boolean supportsReplay = hunter.supportsReplay();\n\n    if (!shouldRetryHunter) {\n      // Mark for replay only if we observe network info changes and support replay.\n      boolean willReplay = scansNetworkChanges && supportsReplay;\n      performError(hunter, willReplay);\n      if (willReplay) {\n        markForReplay(hunter);\n      }\n      return;\n    }\n\n    // If we don't scan for network changes (missing permission) or if we have connectivity, retry.\n    if (!scansNetworkChanges || hasConnectivity) {\n      if (hunter.getPicasso().loggingEnabled) {\n        log(OWNER_DISPATCHER, VERB_RETRYING, getLogIdsForHunter(hunter));\n      }\n      hunter.future = service.submit(hunter);\n      return;\n    }\n\n    performError(hunter, supportsReplay);\n\n    if (supportsReplay) {\n      markForReplay(hunter);\n    }\n  }\n\n  void performComplete(BitmapHunter hunter) {\n    if (!hunter.shouldSkipMemoryCache()) {\n      cache.set(hunter.getKey(), hunter.getResult());\n    }\n    hunterMap.remove(hunter.getKey());\n    batch(hunter);\n    if (hunter.getPicasso().loggingEnabled) {\n      log(OWNER_DISPATCHER, VERB_BATCHED, getLogIdsForHunter(hunter), \"for completion\");\n    }\n  }\n\n  void performBatchComplete() {\n    List<BitmapHunter> copy = new ArrayList<BitmapHunter>(batch);\n    batch.clear();\n    mainThreadHandler.sendMessage(mainThreadHandler.obtainMessage(HUNTER_BATCH_COMPLETE, copy));\n    logBatch(copy);\n  }\n\n  void performError(BitmapHunter hunter, boolean willReplay) {\n    if (hunter.getPicasso().loggingEnabled) {\n      log(OWNER_DISPATCHER, VERB_BATCHED, getLogIdsForHunter(hunter),\n          \"for error\" + (willReplay ? \" (will replay)\" : \"\"));\n    }\n    hunterMap.remove(hunter.getKey());\n    batch(hunter);\n  }\n\n  void performAirplaneModeChange(boolean airplaneMode) {\n    this.airplaneMode = airplaneMode;\n  }\n\n  void performNetworkStateChange(NetworkInfo info) {\n    if (service instanceof PicassoExecutorService) {\n      ((PicassoExecutorService) service).adjustThreadCount(info);\n    }\n    // Intentionally check only if isConnected() here before we flush out failed actions.\n    if (info != null && info.isConnected()) {\n      flushFailedActions();\n    }\n  }\n\n  private void flushFailedActions() {\n    if (!failedActions.isEmpty()) {\n      Iterator<Action> iterator = failedActions.values().iterator();\n      while (iterator.hasNext()) {\n        Action action = iterator.next();\n        iterator.remove();\n        if (action.getPicasso().loggingEnabled) {\n          log(OWNER_DISPATCHER, VERB_REPLAYING, action.getRequest().logId());\n        }\n        performSubmit(action);\n      }\n    }\n  }\n\n  private void markForReplay(BitmapHunter hunter) {\n    Action action = hunter.getAction();\n    if (action != null) {\n      markForReplay(action);\n    }\n    List<Action> joined = hunter.getActions();\n    if (joined != null) {\n      //noinspection ForLoopReplaceableByForEach\n      for (int i = 0, n = joined.size(); i < n; i++) {\n        Action join = joined.get(i);\n        markForReplay(join);\n      }\n    }\n  }\n\n  private void markForReplay(Action action) {\n    Object target = action.getTarget();\n    if (target != null) {\n      action.willReplay = true;\n      failedActions.put(target, action);\n    }\n  }\n\n  private void batch(BitmapHunter hunter) {\n    if (hunter.isCancelled()) {\n      return;\n    }\n    batch.add(hunter);\n    if (!handler.hasMessages(HUNTER_DELAY_NEXT_BATCH)) {\n      handler.sendEmptyMessageDelayed(HUNTER_DELAY_NEXT_BATCH, BATCH_DELAY);\n    }\n  }\n\n  private void logBatch(List<BitmapHunter> copy) {\n    if (copy == null || copy.isEmpty()) return;\n    BitmapHunter hunter = copy.get(0);\n    Picasso picasso = hunter.getPicasso();\n    if (picasso.loggingEnabled) {\n      StringBuilder builder = new StringBuilder();\n      for (BitmapHunter bitmapHunter : copy) {\n        if (builder.length() > 0) builder.append(\", \");\n        builder.append(Utils.getLogIdsForHunter(bitmapHunter));\n      }\n      log(OWNER_DISPATCHER, VERB_DELIVERED, builder.toString());\n    }\n  }\n\n  private static class DispatcherHandler extends Handler {\n    private final Dispatcher dispatcher;\n\n    public DispatcherHandler(Looper looper, Dispatcher dispatcher) {\n      super(looper);\n      this.dispatcher = dispatcher;\n    }\n\n    @Override public void handleMessage(final Message msg) {\n      switch (msg.what) {\n        case REQUEST_SUBMIT: {\n          Action action = (Action) msg.obj;\n          dispatcher.performSubmit(action);\n          break;\n        }\n        case REQUEST_CANCEL: {\n          Action action = (Action) msg.obj;\n          dispatcher.performCancel(action);\n          break;\n        }\n        case HUNTER_COMPLETE: {\n          BitmapHunter hunter = (BitmapHunter) msg.obj;\n          dispatcher.performComplete(hunter);\n          break;\n        }\n        case HUNTER_RETRY: {\n          BitmapHunter hunter = (BitmapHunter) msg.obj;\n          dispatcher.performRetry(hunter);\n          break;\n        }\n        case HUNTER_DECODE_FAILED: {\n          BitmapHunter hunter = (BitmapHunter) msg.obj;\n          dispatcher.performError(hunter, false);\n          break;\n        }\n        case HUNTER_DELAY_NEXT_BATCH: {\n          dispatcher.performBatchComplete();\n          break;\n        }\n        case NETWORK_STATE_CHANGE: {\n          NetworkInfo info = (NetworkInfo) msg.obj;\n          dispatcher.performNetworkStateChange(info);\n          break;\n        }\n        case AIRPLANE_MODE_CHANGE: {\n          dispatcher.performAirplaneModeChange(msg.arg1 == AIRPLANE_MODE_ON);\n          break;\n        }\n        default:\n          Picasso.HANDLER.post(new Runnable() {\n            @Override public void run() {\n              throw new AssertionError(\"Unknown handler message received: \" + msg.what);\n            }\n          });\n      }\n    }\n  }\n\n  static class DispatcherThread extends HandlerThread {\n    DispatcherThread() {\n      super(Utils.THREAD_PREFIX + DISPATCHER_THREAD_NAME, THREAD_PRIORITY_BACKGROUND);\n    }\n  }\n\n  static class NetworkBroadcastReceiver extends BroadcastReceiver {\n    static final String EXTRA_AIRPLANE_STATE = \"state\";\n\n    private final Dispatcher dispatcher;\n\n    NetworkBroadcastReceiver(Dispatcher dispatcher) {\n      this.dispatcher = dispatcher;\n    }\n\n    void register() {\n      IntentFilter filter = new IntentFilter();\n      filter.addAction(ACTION_AIRPLANE_MODE_CHANGED);\n      if (dispatcher.scansNetworkChanges) {\n        filter.addAction(CONNECTIVITY_ACTION);\n      }\n      dispatcher.context.registerReceiver(this, filter);\n    }\n\n    void unregister() {\n      dispatcher.context.unregisterReceiver(this);\n    }\n\n    @Override public void onReceive(Context context, Intent intent) {\n      // On some versions of Android this may be called with a null Intent,\n      // also without extras (getExtras() == null), in such case we use defaults.\n      if (intent == null) {\n        return;\n      }\n      final String action = intent.getAction();\n      if (ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {\n        if (!intent.hasExtra(EXTRA_AIRPLANE_STATE)) {\n          return; // No airplane state, ignore it. Should we query Utils.isAirplaneModeOn?\n        }\n        dispatcher.dispatchAirplaneModeChange(intent.getBooleanExtra(EXTRA_AIRPLANE_STATE, false));\n      } else if (CONNECTIVITY_ACTION.equals(action)) {\n        ConnectivityManager connectivityManager = getService(context, CONNECTIVITY_SERVICE);\n        dispatcher.dispatchNetworkStateChange(connectivityManager.getActiveNetworkInfo());\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "picasso/Downloader.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.graphics.Bitmap;\nimport android.net.Uri;\nimport java.io.IOException;\nimport java.io.InputStream;\n\n/** A mechanism to load images from external resources such as a disk cache and/or the internet. */\npublic interface Downloader {\n  /**\n   * Download the specified image {@code url} from the internet.\n   *\n   * @param uri Remote image URL.\n   * @param localCacheOnly If {@code true} the URL should only be loaded if available in a local\n   * disk cache.\n   * @return {@link com.squareup.picasso.Downloader.Response} containing either a {@link android.graphics.Bitmap} representation of the request or an\n   * {@link java.io.InputStream} for the image data. {@code null} can be returned to indicate a problem\n   * loading the bitmap.\n   * @throws java.io.IOException if the requested URL cannot successfully be loaded.\n   */\n  Response load(Uri uri, boolean localCacheOnly) throws IOException;\n\n  /** Thrown for non-2XX responses. */\n  class ResponseException extends IOException {\n    public ResponseException(String message) {\n      super(message);\n    }\n  }\n\n  /** Response stream or bitmap and info. */\n  class Response {\n    final InputStream stream;\n    final Bitmap bitmap;\n    final boolean cached;\n    final long contentLength;\n\n    /**\n     * Response image and info.\n     *\n     * @param bitmap Image.\n     * @param loadedFromCache {@code true} if the source of the image is from a local disk cache.\n     * @deprecated Use {@link com.squareup.picasso.Downloader.Response#Response(android.graphics.Bitmap, boolean, long)} instead.\n     */\n    @Deprecated @SuppressWarnings(\"UnusedDeclaration\")\n    public Response(Bitmap bitmap, boolean loadedFromCache) {\n      this(bitmap, loadedFromCache, -1);\n    }\n\n    /**\n     * Response stream and info.\n     *\n     * @param stream Image data stream.\n     * @param loadedFromCache {@code true} if the source of the stream is from a local disk cache.\n     * @deprecated Use {@link com.squareup.picasso.Downloader.Response#Response(java.io.InputStream, boolean, long)} instead.\n     */\n    @Deprecated @SuppressWarnings(\"UnusedDeclaration\")\n    public Response(InputStream stream, boolean loadedFromCache) {\n      this(stream, loadedFromCache, -1);\n    }\n\n    /**\n     * Response image and info.\n     *\n     * @param bitmap Image.\n     * @param loadedFromCache {@code true} if the source of the image is from a local disk cache.\n     * @param contentLength The content length of the response, typically derived by the\n     * {@code Content-Length} HTTP header.\n     */\n    public Response(Bitmap bitmap, boolean loadedFromCache, long contentLength) {\n      if (bitmap == null) {\n        throw new IllegalArgumentException(\"Bitmap may not be null.\");\n      }\n      this.stream = null;\n      this.bitmap = bitmap;\n      this.cached = loadedFromCache;\n      this.contentLength = contentLength;\n    }\n\n    /**\n     * Response stream and info.\n     *\n     * @param stream Image data stream.\n     * @param loadedFromCache {@code true} if the source of the stream is from a local disk cache.\n     * @param contentLength The content length of the response, typically derived by the\n     * {@code Content-Length} HTTP header.\n     */\n    public Response(InputStream stream, boolean loadedFromCache, long contentLength) {\n      if (stream == null) {\n        throw new IllegalArgumentException(\"Stream may not be null.\");\n      }\n      this.stream = stream;\n      this.bitmap = null;\n      this.cached = loadedFromCache;\n      this.contentLength = contentLength;\n    }\n\n    /**\n     * Input stream containing image data.\n     * <p>\n     * If this returns {@code null}, image data will be available via {@link #getBitmap()}.\n     */\n    public InputStream getInputStream() {\n      return stream;\n    }\n\n    /**\n     * Bitmap representing the image.\n     * <p>\n     * If this returns {@code null}, image data will be available via {@link #getInputStream()}.\n     */\n    public Bitmap getBitmap() {\n      return bitmap;\n    }\n\n    /** Content length of the response. */\n    public long getContentLength() {\n      return contentLength;\n    }\n  }\n}\n"
  },
  {
    "path": "picasso/FetchAction.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.graphics.Bitmap;\n\nclass FetchAction extends Action<Void> {\n  FetchAction(Picasso picasso, Request data, boolean skipCache, String key) {\n    super(picasso, null, data, skipCache, false, 0, null, key);\n  }\n\n  @Override void complete(Bitmap result, Picasso.LoadedFrom from) {\n  }\n\n  @Override public void error() {\n  }\n}\n"
  },
  {
    "path": "picasso/FileRequestHandler.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.content.Context;\nimport android.media.ExifInterface;\nimport android.net.Uri;\nimport java.io.IOException;\n\nimport static android.content.ContentResolver.SCHEME_FILE;\nimport static android.media.ExifInterface.ORIENTATION_NORMAL;\nimport static android.media.ExifInterface.ORIENTATION_ROTATE_180;\nimport static android.media.ExifInterface.ORIENTATION_ROTATE_270;\nimport static android.media.ExifInterface.ORIENTATION_ROTATE_90;\nimport static android.media.ExifInterface.TAG_ORIENTATION;\nimport static com.squareup.picasso.Picasso.LoadedFrom.DISK;\n\nclass FileRequestHandler extends ContentStreamRequestHandler {\n\n  FileRequestHandler(Context context) {\n    super(context);\n  }\n\n  @Override public boolean canHandleRequest(Request data) {\n    return SCHEME_FILE.equals(data.uri.getScheme());\n  }\n\n  @Override public Result load(Request data) throws IOException {\n    return new Result(decodeContentStream(data), DISK, getFileExifRotation(data.uri));\n  }\n\n  static int getFileExifRotation(Uri uri) throws IOException {\n    ExifInterface exifInterface = new ExifInterface(uri.getPath());\n    int orientation = exifInterface.getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL);\n    switch (orientation) {\n      case ORIENTATION_ROTATE_90:\n        return 90;\n      case ORIENTATION_ROTATE_180:\n        return 180;\n      case ORIENTATION_ROTATE_270:\n        return 270;\n      default:\n        return 0;\n    }\n  }\n}\n"
  },
  {
    "path": "picasso/GetAction.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.graphics.Bitmap;\n\nclass GetAction extends Action<Void> {\n  GetAction(Picasso picasso, Request data, boolean skipCache, String key) {\n    super(picasso, null, data, skipCache, false, 0, null, key);\n  }\n\n  @Override void complete(Bitmap result, Picasso.LoadedFrom from) {\n  }\n\n  @Override public void error() {\n  }\n}\n"
  },
  {
    "path": "picasso/ImageViewAction.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.content.Context;\nimport android.graphics.Bitmap;\nimport android.graphics.drawable.Drawable;\nimport android.widget.ImageView;\n\nclass ImageViewAction extends Action<ImageView> {\n\n  Callback callback;\n\n  ImageViewAction(Picasso picasso, ImageView imageView, Request data, boolean skipCache,\n      boolean noFade, int errorResId, Drawable errorDrawable, String key, Callback callback) {\n    super(picasso, imageView, data, skipCache, noFade, errorResId, errorDrawable, key);\n    this.callback = callback;\n  }\n\n  @Override public void complete(Bitmap result, Picasso.LoadedFrom from) {\n    if (result == null) {\n      throw new AssertionError(\n          String.format(\"Attempted to complete action with no result!\\n%s\", this));\n    }\n\n    ImageView target = this.target.get();\n    if (target == null) {\n      return;\n    }\n\n    Context context = picasso.context;\n    boolean indicatorsEnabled = picasso.indicatorsEnabled;\n    PicassoDrawable.setBitmap(target, context, result, from, noFade, indicatorsEnabled);\n\n    if (callback != null) {\n      callback.onSuccess();\n    }\n  }\n\n  @Override public void error() {\n    ImageView target = this.target.get();\n    if (target == null) {\n      return;\n    }\n    if (errorResId != 0) {\n      target.setImageResource(errorResId);\n    } else if (errorDrawable != null) {\n      target.setImageDrawable(errorDrawable);\n    }\n\n    if (callback != null) {\n      callback.onError();\n    }\n  }\n\n  @Override void cancel() {\n    super.cancel();\n    if (callback != null) {\n      callback = null;\n    }\n  }\n}\n"
  },
  {
    "path": "picasso/LruCache.java",
    "content": "/*\n * Copyright (C) 2011 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.content.Context;\nimport android.graphics.Bitmap;\nimport java.util.LinkedHashMap;\nimport java.util.Map;\n\n/** A memory cache which uses a least-recently used eviction policy. */\npublic class LruCache implements Cache {\n  final LinkedHashMap<String, Bitmap> map;\n  private final int maxSize;\n\n  private int size;\n  private int putCount;\n  private int evictionCount;\n  private int hitCount;\n  private int missCount;\n\n  /** Create a cache using an appropriate portion of the available RAM as the maximum size. */\n  public LruCache(Context context) {\n    this(Utils.calculateMemoryCacheSize(context));\n  }\n\n  /** Create a cache with a given maximum size in bytes. */\n  public LruCache(int maxSize) {\n    if (maxSize <= 0) {\n      throw new IllegalArgumentException(\"Max size must be positive.\");\n    }\n    this.maxSize = maxSize;\n    this.map = new LinkedHashMap<String, Bitmap>(0, 0.75f, true);\n  }\n\n  @Override public Bitmap get(String key) {\n    if (key == null) {\n      throw new NullPointerException(\"key == null\");\n    }\n\n    Bitmap mapValue;\n    synchronized (this) {\n      mapValue = map.get(key);\n      if (mapValue != null) {\n        hitCount++;\n        return mapValue;\n      }\n      missCount++;\n    }\n\n    return null;\n  }\n\n  @Override public void set(String key, Bitmap bitmap) {\n    if (key == null || bitmap == null) {\n      throw new NullPointerException(\"key == null || bitmap == null\");\n    }\n\n    Bitmap previous;\n    synchronized (this) {\n      putCount++;\n      size += Utils.getBitmapBytes(bitmap);\n      previous = map.put(key, bitmap);\n      if (previous != null) {\n        size -= Utils.getBitmapBytes(previous);\n      }\n    }\n\n    trimToSize(maxSize);\n  }\n\n  private void trimToSize(int maxSize) {\n    while (true) {\n      String key;\n      Bitmap value;\n      synchronized (this) {\n        if (size < 0 || (map.isEmpty() && size != 0)) {\n          throw new IllegalStateException(\n              getClass().getName() + \".sizeOf() is reporting inconsistent results!\");\n        }\n\n        if (size <= maxSize || map.isEmpty()) {\n          break;\n        }\n\n        Map.Entry<String, Bitmap> toEvict = map.entrySet().iterator().next();\n        key = toEvict.getKey();\n        value = toEvict.getValue();\n        map.remove(key);\n        size -= Utils.getBitmapBytes(value);\n        evictionCount++;\n      }\n    }\n  }\n\n  /** Clear the cache. */\n  public final void evictAll() {\n    trimToSize(-1); // -1 will evict 0-sized elements\n  }\n\n  /** Returns the sum of the sizes of the entries in this cache. */\n  public final synchronized int size() {\n    return size;\n  }\n\n  /** Returns the maximum sum of the sizes of the entries in this cache. */\n  public final synchronized int maxSize() {\n    return maxSize;\n  }\n\n  public final synchronized void clear() {\n    evictAll();\n  }\n\n  /** Returns the number of times {@link #get} returned a value. */\n  public final synchronized int hitCount() {\n    return hitCount;\n  }\n\n  /** Returns the number of times {@link #get} returned {@code null}. */\n  public final synchronized int missCount() {\n    return missCount;\n  }\n\n  /** Returns the number of times {@link #set(String, android.graphics.Bitmap)} was called. */\n  public final synchronized int putCount() {\n    return putCount;\n  }\n\n  /** Returns the number of values that have been evicted. */\n  public final synchronized int evictionCount() {\n    return evictionCount;\n  }\n}\n"
  },
  {
    "path": "picasso/MarkableInputStream.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport java.io.BufferedInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\n\n/**\n * An input stream wrapper that supports unlimited independent cursors for\n * marking and resetting. Each cursor is a token, and it's the caller's\n * responsibility to keep track of these.\n */\nfinal class MarkableInputStream extends InputStream {\n  private static final int DEFAULT_BUFFER_SIZE = 4096;\n\n  private final InputStream in;\n\n  private long offset;\n  private long reset;\n  private long limit;\n  private long defaultMark = -1;\n\n  public MarkableInputStream(InputStream in) {\n    this(in, DEFAULT_BUFFER_SIZE);\n  }\n\n  public MarkableInputStream(InputStream in, int size) {\n    if (!in.markSupported()) {\n      in = new BufferedInputStream(in, size);\n    }\n    this.in = in;\n  }\n\n  /** Marks this place in the stream so we can reset back to it later. */\n  @Override public void mark(int readLimit) {\n    defaultMark = savePosition(readLimit);\n  }\n\n  /**\n   * Returns an opaque token representing the current position in the stream.\n   * Call {@link #reset(long)} to return to this position in the stream later.\n   * It is an error to call {@link #reset(long)} after consuming more than\n   * {@code readLimit} bytes from this stream.\n   */\n  public long savePosition(int readLimit) {\n    long offsetLimit = offset + readLimit;\n    if (limit < offsetLimit) {\n      setLimit(offsetLimit);\n    }\n    return offset;\n  }\n\n  /**\n   * Makes sure that the underlying stream can backtrack the full range from\n   * {@code reset} thru {@code limit}. Since we can't call {@code mark()}\n   * without also adjusting the reset-to-position on the underlying stream this\n   * method resets first and then marks the union of the two byte ranges. On\n   * buffered streams this additional cursor motion shouldn't result in any\n   * additional I/O.\n   */\n  private void setLimit(long limit) {\n    try {\n      if (reset < offset && offset <= this.limit) {\n        in.reset();\n        in.mark((int) (limit - reset));\n        skip(reset, offset);\n      } else {\n        reset = offset;\n        in.mark((int) (limit - offset));\n      }\n      this.limit = limit;\n    } catch (IOException e) {\n      throw new IllegalStateException(\"Unable to mark: \" + e);\n    }\n  }\n\n  /** Resets the stream to the most recent {@link #mark mark}. */\n  @Override public void reset() throws IOException {\n    reset(defaultMark);\n  }\n\n  /** Resets the stream to the position recorded by {@code token}. */\n  public void reset(long token) throws IOException {\n    if (offset > limit || token < reset) {\n      throw new IOException(\"Cannot reset\");\n    }\n    in.reset();\n    skip(reset, token);\n    offset = token;\n  }\n\n  /** Skips {@code target - current} bytes and returns. */\n  private void skip(long current, long target) throws IOException {\n    while (current < target) {\n      long skipped = in.skip(target - current);\n      if (skipped == 0) {\n        if (read() == -1) {\n          break; // EOF\n        } else {\n          skipped = 1;\n        }\n      }\n      current += skipped;\n    }\n  }\n\n  @Override public int read() throws IOException {\n    int result = in.read();\n    if (result != -1) {\n      offset++;\n    }\n    return result;\n  }\n\n  @Override public int read(byte[] buffer) throws IOException {\n    int count = in.read(buffer);\n    if (count != -1) {\n      offset += count;\n    }\n    return count;\n  }\n\n  @Override public int read(byte[] buffer, int offset, int length) throws IOException {\n    int count = in.read(buffer, offset, length);\n    if (count != -1) {\n      this.offset += count;\n    }\n    return count;\n  }\n\n  @Override public long skip(long byteCount) throws IOException {\n    long skipped = in.skip(byteCount);\n    offset += skipped;\n    return skipped;\n  }\n\n  @Override public int available() throws IOException {\n    return in.available();\n  }\n\n  @Override public void close() throws IOException {\n    in.close();\n  }\n\n  @Override public boolean markSupported() {\n    return in.markSupported();\n  }\n}\n"
  },
  {
    "path": "picasso/MediaStoreRequestHandler.java",
    "content": "/*\n * Copyright (C) 2014 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.content.ContentResolver;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.net.Uri;\nimport android.provider.MediaStore;\nimport java.io.IOException;\n\nimport static android.content.ContentResolver.SCHEME_CONTENT;\nimport static android.content.ContentUris.parseId;\nimport static android.provider.MediaStore.Images;\nimport static android.provider.MediaStore.Video;\nimport static android.provider.MediaStore.Images.Thumbnails.FULL_SCREEN_KIND;\nimport static android.provider.MediaStore.Images.Thumbnails.MICRO_KIND;\nimport static android.provider.MediaStore.Images.Thumbnails.MINI_KIND;\nimport static com.squareup.picasso.MediaStoreRequestHandler.PicassoKind.FULL;\nimport static com.squareup.picasso.MediaStoreRequestHandler.PicassoKind.MICRO;\nimport static com.squareup.picasso.MediaStoreRequestHandler.PicassoKind.MINI;\nimport static com.squareup.picasso.Picasso.LoadedFrom.DISK;\n\nclass MediaStoreRequestHandler extends ContentStreamRequestHandler {\n  private static final String[] CONTENT_ORIENTATION = new String[] {\n      Images.ImageColumns.ORIENTATION\n  };\n\n  MediaStoreRequestHandler(Context context) {\n    super(context);\n  }\n\n  @Override public boolean canHandleRequest(Request data) {\n    final Uri uri = data.uri;\n    return (SCHEME_CONTENT.equals(uri.getScheme())\n            && MediaStore.AUTHORITY.equals(uri.getAuthority()));\n  }\n\n  @Override public Result load(Request data) throws IOException {\n    ContentResolver contentResolver = context.getContentResolver();\n    int exifOrientation = getExifOrientation(contentResolver, data.uri);\n\n    String mimeType = contentResolver.getType(data.uri);\n    boolean isVideo = mimeType != null && mimeType.startsWith(\"video/\");\n\n    if (data.hasSize()) {\n      PicassoKind picassoKind = getPicassoKind(data.targetWidth, data.targetHeight);\n      if (!isVideo && picassoKind == FULL) {\n        return new Result(decodeContentStream(data), DISK, exifOrientation);\n      }\n\n      long id = parseId(data.uri);\n\n      BitmapFactory.Options options = createBitmapOptions(data);\n      options.inJustDecodeBounds = true;\n\n      calculateInSampleSize(data.targetWidth, data.targetHeight, picassoKind.width,\n              picassoKind.height, options);\n\n      Bitmap bitmap;\n\n      if (isVideo) {\n        // Since MediaStore doesn't provide the full screen kind thumbnail, we use the mini kind\n        // instead which is the largest thumbnail size can be fetched from MediaStore.\n        int kind = (picassoKind == FULL) ? Video.Thumbnails.MINI_KIND : picassoKind.androidKind;\n        bitmap = Video.Thumbnails.getThumbnail(contentResolver, id, kind, options);\n      } else {\n        bitmap =\n            Images.Thumbnails.getThumbnail(contentResolver, id, picassoKind.androidKind, options);\n      }\n\n      if (bitmap != null) {\n        return new Result(bitmap, DISK, exifOrientation);\n      }\n    }\n\n    return new Result(decodeContentStream(data), DISK, exifOrientation);\n  }\n\n  static PicassoKind getPicassoKind(int targetWidth, int targetHeight) {\n    if (targetWidth <= MICRO.width && targetHeight <= MICRO.height) {\n      return MICRO;\n    } else if (targetWidth <= MINI.width && targetHeight <= MINI.height) {\n      return MINI;\n    }\n    return FULL;\n  }\n\n  static int getExifOrientation(ContentResolver contentResolver, Uri uri) {\n    Cursor cursor = null;\n    try {\n      cursor = contentResolver.query(uri, CONTENT_ORIENTATION, null, null, null);\n      if (cursor == null || !cursor.moveToFirst()) {\n        return 0;\n      }\n      return cursor.getInt(0);\n    } catch (RuntimeException ignored) {\n      // If the orientation column doesn't exist, assume no rotation.\n      return 0;\n    } finally {\n      if (cursor != null) {\n        cursor.close();\n      }\n    }\n  }\n\n  enum PicassoKind {\n    MICRO(MICRO_KIND, 96, 96),\n    MINI(MINI_KIND, 512, 384),\n    FULL(FULL_SCREEN_KIND, -1, -1);\n\n    final int androidKind;\n    final int width;\n    final int height;\n\n    PicassoKind(int androidKind, int width, int height) {\n      this.androidKind = androidKind;\n      this.width = width;\n      this.height = height;\n    }\n  }\n}\n"
  },
  {
    "path": "picasso/NetworkRequestHandler.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.net.NetworkInfo;\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport static com.squareup.picasso.Downloader.Response;\nimport static com.squareup.picasso.Picasso.LoadedFrom.DISK;\nimport static com.squareup.picasso.Picasso.LoadedFrom.NETWORK;\n\nclass NetworkRequestHandler extends RequestHandler {\n  static final int RETRY_COUNT = 2;\n  private static final int MARKER = 65536;\n\n  private static final String SCHEME_HTTP = \"http\";\n  private static final String SCHEME_HTTPS = \"https\";\n\n  private final Downloader downloader;\n  private final Stats stats;\n\n  public NetworkRequestHandler(Downloader downloader, Stats stats) {\n    this.downloader = downloader;\n    this.stats = stats;\n  }\n\n  @Override public boolean canHandleRequest(Request data) {\n    String scheme = data.uri.getScheme();\n    return (SCHEME_HTTP.equals(scheme) || SCHEME_HTTPS.equals(scheme));\n  }\n\n  @Override public Result load(Request data) throws IOException {\n    Response response = downloader.load(data.uri, data.loadFromLocalCacheOnly);\n    if (response == null) {\n      return null;\n    }\n\n    Picasso.LoadedFrom loadedFrom = response.cached ? DISK : NETWORK;\n\n    Bitmap bitmap = response.getBitmap();\n    if (bitmap != null) {\n      return new Result(bitmap, loadedFrom);\n    }\n\n    InputStream is = response.getInputStream();\n    if (is == null) {\n      return null;\n    }\n    // Sometimes response content length is zero when requests are being replayed. Haven't found\n    // root cause to this but retrying the request seems safe to do so.\n    if (response.getContentLength() == 0) {\n      Utils.closeQuietly(is);\n      throw new IOException(\"Received response with 0 content-length header.\");\n    }\n    if (loadedFrom == NETWORK && response.getContentLength() > 0) {\n      stats.dispatchDownloadFinished(response.getContentLength());\n    }\n    try {\n      return new Result(decodeStream(is, data), loadedFrom);\n    } finally {\n      Utils.closeQuietly(is);\n    }\n  }\n\n  @Override int getRetryCount() {\n    return RETRY_COUNT;\n  }\n\n  @Override boolean shouldRetry(boolean airplaneMode, NetworkInfo info) {\n    return info == null || info.isConnected();\n  }\n\n  @Override boolean supportsReplay() {\n    return true;\n  }\n\n  private Bitmap decodeStream(InputStream stream, Request data) throws IOException {\n    MarkableInputStream markStream = new MarkableInputStream(stream);\n    stream = markStream;\n\n    long mark = markStream.savePosition(MARKER);\n\n    final BitmapFactory.Options options = createBitmapOptions(data);\n    final boolean calculateSize = requiresInSampleSize(options);\n\n    boolean isWebPFile = Utils.isWebPFile(stream);\n    markStream.reset(mark);\n    // When decode WebP network stream, BitmapFactory throw JNI Exception and make app crash.\n    // Decode byte array instead\n    if (isWebPFile) {\n      byte[] bytes = Utils.toByteArray(stream);\n      if (calculateSize) {\n        BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);\n        calculateInSampleSize(data.targetWidth, data.targetHeight, options);\n      }\n      return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);\n    } else {\n      if (calculateSize) {\n        BitmapFactory.decodeStream(stream, null, options);\n        calculateInSampleSize(data.targetWidth, data.targetHeight, options);\n\n        markStream.reset(mark);\n      }\n      Bitmap bitmap = BitmapFactory.decodeStream(stream, null, options);\n      if (bitmap == null) {\n        // Treat null as an IO exception, we will eventually retry.\n        throw new IOException(\"Failed to decode stream.\");\n      }\n      return bitmap;\n    }\n  }\n}\n"
  },
  {
    "path": "picasso/Picasso.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.content.Context;\nimport android.graphics.Bitmap;\nimport android.graphics.Color;\nimport android.net.Uri;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.os.Message;\nimport android.os.Process;\nimport android.widget.ImageView;\nimport android.widget.RemoteViews;\nimport java.io.File;\nimport java.lang.ref.ReferenceQueue;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.WeakHashMap;\nimport java.util.concurrent.ExecutorService;\n\nimport static android.os.Process.THREAD_PRIORITY_BACKGROUND;\nimport static com.squareup.picasso.Action.RequestWeakReference;\nimport static com.squareup.picasso.Dispatcher.HUNTER_BATCH_COMPLETE;\nimport static com.squareup.picasso.Dispatcher.REQUEST_GCED;\nimport static com.squareup.picasso.Utils.OWNER_MAIN;\nimport static com.squareup.picasso.Utils.THREAD_PREFIX;\nimport static com.squareup.picasso.Utils.VERB_COMPLETED;\nimport static com.squareup.picasso.Utils.VERB_ERRORED;\nimport static com.squareup.picasso.Utils.checkMain;\nimport static com.squareup.picasso.Utils.log;\n\n/**\n * Image downloading, transformation, and caching manager.\n * <p>\n * Use {@link #with(android.content.Context)} for the global singleton instance or construct your\n * own instance with {@link com.squareup.picasso.Picasso.Builder}.\n */\npublic class Picasso {\n\n  /** Callbacks for Picasso events. */\n  public interface Listener {\n    /**\n     * Invoked when an image has failed to load. This is useful for reporting image failures to a\n     * remote analytics service, for example.\n     */\n    void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception);\n  }\n\n  /**\n   * A transformer that is called immediately before every request is submitted. This can be used to\n   * modify any information about a request.\n   * <p>\n   * For example, if you use a CDN you can change the hostname for the image based on the current\n   * location of the user in order to get faster download speeds.\n   * <p>\n   * <b>NOTE:</b> This is a beta feature. The API is subject to change in a backwards incompatible\n   * way at any time.\n   */\n  public interface RequestTransformer {\n    /**\n     * Transform a request before it is submitted to be processed.\n     *\n     * @return The original request or a new request to replace it. Must not be null.\n     */\n    Request transformRequest(Request request);\n\n    /** A {@link com.squareup.picasso.Picasso.RequestTransformer} which returns the original request. */\n    RequestTransformer IDENTITY = new RequestTransformer() {\n      @Override public Request transformRequest(Request request) {\n        return request;\n      }\n    };\n  }\n\n  static final String TAG = \"Picasso\";\n  static final Handler HANDLER = new Handler(Looper.getMainLooper()) {\n    @Override public void handleMessage(Message msg) {\n      switch (msg.what) {\n        case HUNTER_BATCH_COMPLETE: {\n          @SuppressWarnings(\"unchecked\") List<BitmapHunter> batch = (List<BitmapHunter>) msg.obj;\n          //noinspection ForLoopReplaceableByForEach\n          for (int i = 0, n = batch.size(); i < n; i++) {\n            BitmapHunter hunter = batch.get(i);\n            hunter.picasso.complete(hunter);\n          }\n          break;\n        }\n        case REQUEST_GCED: {\n          Action action = (Action) msg.obj;\n          action.picasso.cancelExistingRequest(action.getTarget());\n          break;\n        }\n        default:\n          throw new AssertionError(\"Unknown handler message received: \" + msg.what);\n      }\n    }\n  };\n\n  static Picasso singleton = null;\n\n  private final Listener listener;\n  private final RequestTransformer requestTransformer;\n  private final CleanupThread cleanupThread;\n  private final List<RequestHandler> requestHandlers;\n\n  final Context context;\n  final Dispatcher dispatcher;\n  final Cache cache;\n  final Stats stats;\n  final Map<Object, Action> targetToAction;\n  final Map<ImageView, DeferredRequestCreator> targetToDeferredRequestCreator;\n  final ReferenceQueue<Object> referenceQueue;\n\n  boolean indicatorsEnabled;\n  volatile boolean loggingEnabled;\n\n  boolean shutdown;\n\n  Picasso(Context context, Dispatcher dispatcher, Cache cache, Listener listener,\n      RequestTransformer requestTransformer, List<RequestHandler> extraRequestHandlers,\n      Stats stats, boolean indicatorsEnabled, boolean loggingEnabled) {\n    this.context = context;\n    this.dispatcher = dispatcher;\n    this.cache = cache;\n    this.listener = listener;\n    this.requestTransformer = requestTransformer;\n\n    final int extraCount = (extraRequestHandlers != null ? extraRequestHandlers.size() : 0);\n    final List<RequestHandler> allRequestHandlers = new ArrayList<RequestHandler>(7 + extraCount);\n    // ResourceRequestHandler needs to be the first in the list to avoid\n    // forcing other RequestHandlers to perform null checks on request.uri\n    // to cover the (request.resourceId != 0) case.\n    allRequestHandlers.add(new ResourceRequestHandler(context));\n    if (extraRequestHandlers != null) {\n      allRequestHandlers.addAll(extraRequestHandlers);\n    }\n    allRequestHandlers.add(new ContactsPhotoRequestHandler(context));\n    allRequestHandlers.add(new MediaStoreRequestHandler(context));\n    allRequestHandlers.add(new ContentStreamRequestHandler(context));\n    allRequestHandlers.add(new AssetRequestHandler(context));\n    allRequestHandlers.add(new FileRequestHandler(context));\n    allRequestHandlers.add(new NetworkRequestHandler(dispatcher.downloader, stats));\n    requestHandlers = Collections.unmodifiableList(allRequestHandlers);\n\n    this.stats = stats;\n    this.targetToAction = new WeakHashMap<Object, Action>();\n    this.targetToDeferredRequestCreator = new WeakHashMap<ImageView, DeferredRequestCreator>();\n    this.indicatorsEnabled = indicatorsEnabled;\n    this.loggingEnabled = loggingEnabled;\n    this.referenceQueue = new ReferenceQueue<Object>();\n    this.cleanupThread = new CleanupThread(referenceQueue, HANDLER);\n    this.cleanupThread.start();\n  }\n\n  /** Cancel any existing requests for the specified target {@link android.widget.ImageView}. */\n  public void cancelRequest(ImageView view) {\n    cancelExistingRequest(view);\n  }\n\n  /** Cancel any existing requests for the specified {@link com.squareup.picasso.Target} instance. */\n  public void cancelRequest(Target target) {\n    cancelExistingRequest(target);\n  }\n\n  /**\n   * Cancel any existing requests for the specified {@link android.widget.RemoteViews} target with the given {@code\n   * viewId}.\n   */\n  public void cancelRequest(RemoteViews remoteViews, int viewId) {\n    cancelExistingRequest(new RemoteViewsAction.RemoteViewsTarget(remoteViews, viewId));\n  }\n\n  /**\n   * Start an image request using the specified URI.\n   * <p>\n   * Passing {@code null} as a {@code uri} will not trigger any request but will set a placeholder,\n   * if one is specified.\n   *\n   * @see #load(java.io.File)\n   * @see #load(String)\n   * @see #load(int)\n   */\n  public RequestCreator load(Uri uri) {\n    return new RequestCreator(this, uri, 0);\n  }\n\n  /**\n   * Start an image request using the specified path. This is a convenience method for calling\n   * {@link #load(android.net.Uri)}.\n   * <p>\n   * This path may be a remote URL, file resource (prefixed with {@code file:}), content resource\n   * (prefixed with {@code content:}), or android resource (prefixed with {@code\n   * android.resource:}.\n   * <p>\n   * Passing {@code null} as a {@code path} will not trigger any request but will set a\n   * placeholder, if one is specified.\n   *\n   * @see #load(android.net.Uri)\n   * @see #load(java.io.File)\n   * @see #load(int)\n   * @throws IllegalArgumentException if {@code path} is empty or blank string.\n   */\n  public RequestCreator load(String path) {\n    if (path == null) {\n      return new RequestCreator(this, null, 0);\n    }\n    if (path.trim().length() == 0) {\n      throw new IllegalArgumentException(\"Path must not be empty.\");\n    }\n    return load(Uri.parse(path));\n  }\n\n  /**\n   * Start an image request using the specified image file. This is a convenience method for\n   * calling {@link #load(android.net.Uri)}.\n   * <p>\n   * Passing {@code null} as a {@code file} will not trigger any request but will set a\n   * placeholder, if one is specified.\n   * <p>\n   * Equivalent to calling {@link #load(android.net.Uri) load(Uri.fromFile(file))}.\n   *\n   * @see #load(android.net.Uri)\n   * @see #load(String)\n   * @see #load(int)\n   */\n  public RequestCreator load(File file) {\n    if (file == null) {\n      return new RequestCreator(this, null, 0);\n    }\n    return load(Uri.fromFile(file));\n  }\n\n  /**\n   * Start an image request using the specified drawable resource ID.\n   *\n   * @see #load(android.net.Uri)\n   * @see #load(String)\n   * @see #load(java.io.File)\n   */\n  public RequestCreator load(int resourceId) {\n    if (resourceId == 0) {\n      throw new IllegalArgumentException(\"Resource ID must not be zero.\");\n    }\n    return new RequestCreator(this, null, resourceId);\n  }\n\n  /**\n   * {@code true} if debug display, logging, and statistics are enabled.\n   * <p>\n   * @deprecated Use {@link #areIndicatorsEnabled()} and {@link #isLoggingEnabled()} instead.\n   */\n  @SuppressWarnings(\"UnusedDeclaration\") @Deprecated public boolean isDebugging() {\n    return areIndicatorsEnabled() && isLoggingEnabled();\n  }\n\n  /**\n   * Toggle whether debug display, logging, and statistics are enabled.\n   * <p>\n   * @deprecated Use {@link #setIndicatorsEnabled(boolean)} and {@link #setLoggingEnabled(boolean)}\n   * instead.\n   */\n  @SuppressWarnings(\"UnusedDeclaration\") @Deprecated public void setDebugging(boolean debugging) {\n    setIndicatorsEnabled(debugging);\n  }\n\n  /** Toggle whether to display debug indicators on images. */\n  @SuppressWarnings(\"UnusedDeclaration\") public void setIndicatorsEnabled(boolean enabled) {\n    indicatorsEnabled = enabled;\n  }\n\n  /** {@code true} if debug indicators should are displayed on images. */\n  @SuppressWarnings(\"UnusedDeclaration\") public boolean areIndicatorsEnabled() {\n    return indicatorsEnabled;\n  }\n\n  /**\n   * Toggle whether debug logging is enabled.\n   * <p>\n   * <b>WARNING:</b> Enabling this will result in excessive object allocation. This should be only\n   * be used for debugging Picasso behavior. Do NOT pass {@code BuildConfig.DEBUG}.\n   */\n  public void setLoggingEnabled(boolean enabled) {\n    loggingEnabled = enabled;\n  }\n\n  /** {@code true} if debug logging is enabled. */\n  public boolean isLoggingEnabled() {\n    return loggingEnabled;\n  }\n\n  /**\n   * Creates a {@link com.squareup.picasso.StatsSnapshot} of the current stats for this instance.\n   * <p>\n   * <b>NOTE:</b> The snapshot may not always be completely up-to-date if requests are still in\n   * progress.\n   */\n  @SuppressWarnings(\"UnusedDeclaration\") public StatsSnapshot getSnapshot() {\n    return stats.createSnapshot();\n  }\n\n  /** Stops this instance from accepting further requests. */\n  public void shutdown() {\n    if (this == singleton) {\n      throw new UnsupportedOperationException(\"Default singleton instance cannot be shutdown.\");\n    }\n    if (shutdown) {\n      return;\n    }\n    cache.clear();\n    cleanupThread.shutdown();\n    stats.shutdown();\n    dispatcher.shutdown();\n    for (DeferredRequestCreator deferredRequestCreator : targetToDeferredRequestCreator.values()) {\n      deferredRequestCreator.cancel();\n    }\n    targetToDeferredRequestCreator.clear();\n    shutdown = true;\n  }\n\n  List<RequestHandler> getRequestHandlers() {\n    return requestHandlers;\n  }\n\n  Request transformRequest(Request request) {\n    Request transformed = requestTransformer.transformRequest(request);\n    if (transformed == null) {\n      throw new IllegalStateException(\"Request transformer \"\n          + requestTransformer.getClass().getCanonicalName()\n          + \" returned null for \"\n          + request);\n    }\n    return transformed;\n  }\n\n  void defer(ImageView view, DeferredRequestCreator request) {\n    targetToDeferredRequestCreator.put(view, request);\n  }\n\n  void enqueueAndSubmit(Action action) {\n    Object target = action.getTarget();\n    if (target != null) {\n      // This will also check we are on the main thread.\n      cancelExistingRequest(target);\n      targetToAction.put(target, action);\n    }\n    submit(action);\n  }\n\n  void submit(Action action) {\n    dispatcher.dispatchSubmit(action);\n  }\n\n  Bitmap quickMemoryCacheCheck(String key) {\n    Bitmap cached = cache.get(key);\n    if (cached != null) {\n      stats.dispatchCacheHit();\n    } else {\n      stats.dispatchCacheMiss();\n    }\n    return cached;\n  }\n\n  void complete(BitmapHunter hunter) {\n    Action single = hunter.getAction();\n    List<Action> joined = hunter.getActions();\n\n    boolean hasMultiple = joined != null && !joined.isEmpty();\n    boolean shouldDeliver = single != null || hasMultiple;\n\n    if (!shouldDeliver) {\n      return;\n    }\n\n    Uri uri = hunter.getData().uri;\n    Exception exception = hunter.getException();\n    Bitmap result = hunter.getResult();\n    LoadedFrom from = hunter.getLoadedFrom();\n\n    if (single != null) {\n      deliverAction(result, from, single);\n    }\n\n    if (hasMultiple) {\n      //noinspection ForLoopReplaceableByForEach\n      for (int i = 0, n = joined.size(); i < n; i++) {\n        Action join = joined.get(i);\n        deliverAction(result, from, join);\n      }\n    }\n\n    if (listener != null && exception != null) {\n      listener.onImageLoadFailed(this, uri, exception);\n    }\n  }\n\n  private void deliverAction(Bitmap result, LoadedFrom from, Action action) {\n    if (action.isCancelled()) {\n      return;\n    }\n    if (!action.willReplay()) {\n      targetToAction.remove(action.getTarget());\n    }\n    if (result != null) {\n      if (from == null) {\n        throw new AssertionError(\"LoadedFrom cannot be null.\");\n      }\n      action.complete(result, from);\n      if (loggingEnabled) {\n        log(OWNER_MAIN, VERB_COMPLETED, action.request.logId(), \"from \" + from);\n      }\n    } else {\n      action.error();\n      if (loggingEnabled) {\n        log(OWNER_MAIN, VERB_ERRORED, action.request.logId());\n      }\n    }\n  }\n\n  private void cancelExistingRequest(Object target) {\n    checkMain();\n    Action action = targetToAction.remove(target);\n    if (action != null) {\n      action.cancel();\n      dispatcher.dispatchCancel(action);\n    }\n    if (target instanceof ImageView) {\n      ImageView targetImageView = (ImageView) target;\n      DeferredRequestCreator deferredRequestCreator =\n          targetToDeferredRequestCreator.remove(targetImageView);\n      if (deferredRequestCreator != null) {\n        deferredRequestCreator.cancel();\n      }\n    }\n  }\n\n  private static class CleanupThread extends Thread {\n    private final ReferenceQueue<?> referenceQueue;\n    private final Handler handler;\n\n    CleanupThread(ReferenceQueue<?> referenceQueue, Handler handler) {\n      this.referenceQueue = referenceQueue;\n      this.handler = handler;\n      setDaemon(true);\n      setName(THREAD_PREFIX + \"refQueue\");\n    }\n\n    @Override public void run() {\n      Process.setThreadPriority(THREAD_PRIORITY_BACKGROUND);\n      while (true) {\n        try {\n          RequestWeakReference<?> remove = (RequestWeakReference<?>) referenceQueue.remove();\n          handler.sendMessage(handler.obtainMessage(REQUEST_GCED, remove.action));\n        } catch (InterruptedException e) {\n          break;\n        } catch (final Exception e) {\n          handler.post(new Runnable() {\n            @Override public void run() {\n              throw new RuntimeException(e);\n            }\n          });\n          break;\n        }\n      }\n    }\n\n    void shutdown() {\n      interrupt();\n    }\n  }\n\n  /**\n   * The global default {@link com.squareup.picasso.Picasso} instance.\n   * <p>\n   * This instance is automatically initialized with defaults that are suitable to most\n   * implementations.\n   * <ul>\n   * <li>LRU memory cache of 15% the available application RAM</li>\n   * <li>Disk cache of 2% storage space up to 50MB but no less than 5MB. (Note: this is only\n   * available on API 14+ <em>or</em> if you are using a standalone library that provides a disk\n   * cache on all API levels like OkHttp)</li>\n   * <li>Three download threads for disk and network access.</li>\n   * </ul>\n   * <p>\n   * If these settings do not meet the requirements of your application you can construct your own\n   * instance with full control over the configuration by using {@link com.squareup.picasso.Picasso.Builder}.\n   */\n  public static Picasso with(Context context) {\n    if (singleton == null) {\n      synchronized (Picasso.class) {\n        if (singleton == null) {\n          singleton = new Builder(context).build();\n        }\n      }\n    }\n    return singleton;\n  }\n\n  /** Fluent API for creating {@link com.squareup.picasso.Picasso} instances. */\n  @SuppressWarnings(\"UnusedDeclaration\") // Public API.\n  public static class Builder {\n    private final Context context;\n    private Downloader downloader;\n    private ExecutorService service;\n    private Cache cache;\n    private Listener listener;\n    private RequestTransformer transformer;\n    private List<RequestHandler> requestHandlers;\n\n    private boolean indicatorsEnabled;\n    private boolean loggingEnabled;\n\n    /** Start building a new {@link com.squareup.picasso.Picasso} instance. */\n    public Builder(Context context) {\n      if (context == null) {\n        throw new IllegalArgumentException(\"Context must not be null.\");\n      }\n      this.context = context.getApplicationContext();\n    }\n\n    /** Specify the {@link com.squareup.picasso.Downloader} that will be used for downloading images. */\n    public Builder downloader(Downloader downloader) {\n      if (downloader == null) {\n        throw new IllegalArgumentException(\"Downloader must not be null.\");\n      }\n      if (this.downloader != null) {\n        throw new IllegalStateException(\"Downloader already set.\");\n      }\n      this.downloader = downloader;\n      return this;\n    }\n\n    /** Specify the executor service for loading images in the background. */\n    public Builder executor(ExecutorService executorService) {\n      if (executorService == null) {\n        throw new IllegalArgumentException(\"Executor service must not be null.\");\n      }\n      if (this.service != null) {\n        throw new IllegalStateException(\"Executor service already set.\");\n      }\n      this.service = executorService;\n      return this;\n    }\n\n    /** Specify the memory cache used for the most recent images. */\n    public Builder memoryCache(Cache memoryCache) {\n      if (memoryCache == null) {\n        throw new IllegalArgumentException(\"Memory cache must not be null.\");\n      }\n      if (this.cache != null) {\n        throw new IllegalStateException(\"Memory cache already set.\");\n      }\n      this.cache = memoryCache;\n      return this;\n    }\n\n    /** Specify a listener for interesting events. */\n    public Builder listener(Listener listener) {\n      if (listener == null) {\n        throw new IllegalArgumentException(\"Listener must not be null.\");\n      }\n      if (this.listener != null) {\n        throw new IllegalStateException(\"Listener already set.\");\n      }\n      this.listener = listener;\n      return this;\n    }\n\n    /**\n     * Specify a transformer for all incoming requests.\n     * <p>\n     * <b>NOTE:</b> This is a beta feature. The API is subject to change in a backwards incompatible\n     * way at any time.\n     */\n    public Builder requestTransformer(RequestTransformer transformer) {\n      if (transformer == null) {\n        throw new IllegalArgumentException(\"Transformer must not be null.\");\n      }\n      if (this.transformer != null) {\n        throw new IllegalStateException(\"Transformer already set.\");\n      }\n      this.transformer = transformer;\n      return this;\n    }\n\n    /** Register a {@link RequestHandler}. */\n    public Builder addRequestHandler(RequestHandler requestHandler) {\n      if (requestHandler == null) {\n        throw new IllegalArgumentException(\"RequestHandler must not be null.\");\n      }\n      if (requestHandlers == null) {\n        requestHandlers = new ArrayList<RequestHandler>();\n      }\n      if (requestHandlers.contains(requestHandler)) {\n        throw new IllegalStateException(\"RequestHandler already registered.\");\n      }\n      requestHandlers.add(requestHandler);\n      return this;\n    }\n\n    /**\n     * @deprecated Use {@link #indicatorsEnabled(boolean)} instead.\n     * Whether debugging is enabled or not.\n     */\n    @Deprecated public Builder debugging(boolean debugging) {\n      return indicatorsEnabled(debugging);\n    }\n\n    /** Toggle whether to display debug indicators on images. */\n    public Builder indicatorsEnabled(boolean enabled) {\n      this.indicatorsEnabled = enabled;\n      return this;\n    }\n\n    /**\n     * Toggle whether debug logging is enabled.\n     * <p>\n     * <b>WARNING:</b> Enabling this will result in excessive object allocation. This should be only\n     * be used for debugging purposes. Do NOT pass {@code BuildConfig.DEBUG}.\n     */\n    public Builder loggingEnabled(boolean enabled) {\n      this.loggingEnabled = enabled;\n      return this;\n    }\n\n    /** Create the {@link com.squareup.picasso.Picasso} instance. */\n    public Picasso build() {\n      Context context = this.context;\n\n      if (downloader == null) {\n        downloader = Utils.createDefaultDownloader(context);\n      }\n      if (cache == null) {\n        cache = new LruCache(context);\n      }\n      if (service == null) {\n        service = new PicassoExecutorService();\n      }\n      if (transformer == null) {\n        transformer = RequestTransformer.IDENTITY;\n      }\n\n      Stats stats = new Stats(cache);\n\n      Dispatcher dispatcher = new Dispatcher(context, service, HANDLER, downloader, cache, stats);\n\n      return new Picasso(context, dispatcher, cache, listener, transformer,\n          requestHandlers, stats, indicatorsEnabled, loggingEnabled);\n    }\n  }\n\n  /** Describes where the image was loaded from. */\n  public enum LoadedFrom {\n    MEMORY(Color.GREEN),\n    DISK(Color.YELLOW),\n    NETWORK(Color.RED);\n\n    final int debugColor;\n\n    private LoadedFrom(int debugColor) {\n      this.debugColor = debugColor;\n    }\n  }\n}\n"
  },
  {
    "path": "picasso/PicassoDrawable.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.content.Context;\nimport android.graphics.Bitmap;\nimport android.graphics.Canvas;\nimport android.graphics.ColorFilter;\nimport android.graphics.Paint;\nimport android.graphics.Path;\nimport android.graphics.Point;\nimport android.graphics.Rect;\nimport android.graphics.drawable.AnimationDrawable;\nimport android.graphics.drawable.BitmapDrawable;\nimport android.graphics.drawable.Drawable;\nimport android.os.Build;\nimport android.os.SystemClock;\nimport android.widget.ImageView;\n\nimport static android.graphics.Color.WHITE;\nimport static com.squareup.picasso.Picasso.LoadedFrom.MEMORY;\n\nfinal class PicassoDrawable extends BitmapDrawable {\n  // Only accessed from main thread.\n  private static final Paint DEBUG_PAINT = new Paint();\n  private static final float FADE_DURATION = 200f; //ms\n\n  /**\n   * Create or update the drawable on the target {@link android.widget.ImageView} to display the supplied bitmap\n   * image.\n   */\n  static void setBitmap(ImageView target, Context context, Bitmap bitmap,\n      Picasso.LoadedFrom loadedFrom, boolean noFade, boolean debugging) {\n    Drawable placeholder = target.getDrawable();\n    if (placeholder instanceof AnimationDrawable) {\n      ((AnimationDrawable) placeholder).stop();\n    }\n    PicassoDrawable drawable =\n        new PicassoDrawable(context, bitmap, placeholder, loadedFrom, noFade, debugging);\n    target.setImageDrawable(drawable);\n  }\n\n  /**\n   * Create or update the drawable on the target {@link android.widget.ImageView} to display the supplied\n   * placeholder image.\n   */\n  static void setPlaceholder(ImageView target, int placeholderResId, Drawable placeholderDrawable) {\n    if (placeholderResId != 0) {\n      target.setImageResource(placeholderResId);\n    } else {\n      target.setImageDrawable(placeholderDrawable);\n    }\n    if (target.getDrawable() instanceof AnimationDrawable) {\n      ((AnimationDrawable) target.getDrawable()).start();\n    }\n  }\n\n  private final boolean debugging;\n  private final float density;\n  private final Picasso.LoadedFrom loadedFrom;\n\n  Drawable placeholder;\n\n  long startTimeMillis;\n  boolean animating;\n  int alpha = 0xFF;\n\n  PicassoDrawable(Context context, Bitmap bitmap, Drawable placeholder,\n      Picasso.LoadedFrom loadedFrom, boolean noFade, boolean debugging) {\n    super(context.getResources(), bitmap);\n\n    this.debugging = debugging;\n    this.density = context.getResources().getDisplayMetrics().density;\n\n    this.loadedFrom = loadedFrom;\n\n    boolean fade = loadedFrom != MEMORY && !noFade;\n    if (fade) {\n      this.placeholder = placeholder;\n      animating = true;\n      startTimeMillis = SystemClock.uptimeMillis();\n    }\n  }\n\n  @Override public void draw(Canvas canvas) {\n    if (!animating) {\n      super.draw(canvas);\n    } else {\n      float normalized = (SystemClock.uptimeMillis() - startTimeMillis) / FADE_DURATION;\n      if (normalized >= 1f) {\n        animating = false;\n        placeholder = null;\n        super.draw(canvas);\n      } else {\n        if (placeholder != null) {\n          placeholder.draw(canvas);\n        }\n\n        int partialAlpha = (int) (alpha * normalized);\n        super.setAlpha(partialAlpha);\n        super.draw(canvas);\n        super.setAlpha(alpha);\n        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {\n          invalidateSelf();\n        }\n      }\n    }\n\n    if (debugging) {\n      drawDebugIndicator(canvas);\n    }\n  }\n\n  @Override public void setAlpha(int alpha) {\n    this.alpha = alpha;\n    if (placeholder != null) {\n      placeholder.setAlpha(alpha);\n    }\n    super.setAlpha(alpha);\n  }\n\n  @Override public void setColorFilter(ColorFilter cf) {\n    if (placeholder != null) {\n      placeholder.setColorFilter(cf);\n    }\n    super.setColorFilter(cf);\n  }\n\n  @Override protected void onBoundsChange(Rect bounds) {\n    if (placeholder != null) {\n      placeholder.setBounds(bounds);\n    }\n    super.onBoundsChange(bounds);\n  }\n\n  private void drawDebugIndicator(Canvas canvas) {\n    DEBUG_PAINT.setColor(WHITE);\n    Path path = getTrianglePath(new Point(0, 0), (int) (16 * density));\n    canvas.drawPath(path, DEBUG_PAINT);\n\n    DEBUG_PAINT.setColor(loadedFrom.debugColor);\n    path = getTrianglePath(new Point(0, 0), (int) (15 * density));\n    canvas.drawPath(path, DEBUG_PAINT);\n  }\n\n  private static Path getTrianglePath(Point p1, int width) {\n    Point p2 = new Point(p1.x + width, p1.y);\n    Point p3 = new Point(p1.x, p1.y + width);\n\n    Path path = new Path();\n    path.moveTo(p1.x, p1.y);\n    path.lineTo(p2.x, p2.y);\n    path.lineTo(p3.x, p3.y);\n\n    return path;\n  }\n}\n"
  },
  {
    "path": "picasso/PicassoExecutorService.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.net.ConnectivityManager;\nimport android.net.NetworkInfo;\nimport android.telephony.TelephonyManager;\nimport java.util.concurrent.LinkedBlockingQueue;\nimport java.util.concurrent.ThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\n/**\n * The default {@link java.util.concurrent.ExecutorService} used for new {@link com.squareup.picasso.Picasso} instances.\n * <p>\n * Exists as a custom type so that we can differentiate the use of defaults versus a user-supplied\n * instance.\n */\nclass PicassoExecutorService extends ThreadPoolExecutor {\n  private static final int DEFAULT_THREAD_COUNT = 3;\n\n  PicassoExecutorService() {\n    super(DEFAULT_THREAD_COUNT, DEFAULT_THREAD_COUNT, 0, TimeUnit.MILLISECONDS,\n        new LinkedBlockingQueue<Runnable>(), new Utils.PicassoThreadFactory());\n  }\n\n  void adjustThreadCount(NetworkInfo info) {\n    if (info == null || !info.isConnectedOrConnecting()) {\n      setThreadCount(DEFAULT_THREAD_COUNT);\n      return;\n    }\n    switch (info.getType()) {\n      case ConnectivityManager.TYPE_WIFI:\n      case ConnectivityManager.TYPE_WIMAX:\n      case ConnectivityManager.TYPE_ETHERNET:\n        setThreadCount(4);\n        break;\n      case ConnectivityManager.TYPE_MOBILE:\n        switch (info.getSubtype()) {\n          case TelephonyManager.NETWORK_TYPE_LTE:  // 4G\n          case TelephonyManager.NETWORK_TYPE_HSPAP:\n          case TelephonyManager.NETWORK_TYPE_EHRPD:\n            setThreadCount(3);\n            break;\n          case TelephonyManager.NETWORK_TYPE_UMTS: // 3G\n          case TelephonyManager.NETWORK_TYPE_CDMA:\n          case TelephonyManager.NETWORK_TYPE_EVDO_0:\n          case TelephonyManager.NETWORK_TYPE_EVDO_A:\n          case TelephonyManager.NETWORK_TYPE_EVDO_B:\n            setThreadCount(2);\n            break;\n          case TelephonyManager.NETWORK_TYPE_GPRS: // 2G\n          case TelephonyManager.NETWORK_TYPE_EDGE:\n            setThreadCount(1);\n            break;\n          default:\n            setThreadCount(DEFAULT_THREAD_COUNT);\n        }\n        break;\n      default:\n        setThreadCount(DEFAULT_THREAD_COUNT);\n    }\n  }\n\n  private void setThreadCount(int threadCount) {\n    setCorePoolSize(threadCount);\n    setMaximumPoolSize(threadCount);\n  }\n}\n"
  },
  {
    "path": "picasso/RemoteViewsAction.java",
    "content": "/*\n * Copyright (C) 2014 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.app.Notification;\nimport android.app.NotificationManager;\nimport android.appwidget.AppWidgetManager;\nimport android.graphics.Bitmap;\nimport android.widget.RemoteViews;\n\nimport static android.content.Context.NOTIFICATION_SERVICE;\nimport static com.squareup.picasso.Utils.getService;\n\nabstract class RemoteViewsAction extends Action<RemoteViewsAction.RemoteViewsTarget> {\n  final RemoteViews remoteViews;\n  final int viewId;\n\n  RemoteViewsAction(Picasso picasso, Request data, RemoteViews remoteViews, int viewId,\n      int errorResId, boolean skipCache, String key) {\n    super(picasso, new RemoteViewsTarget(remoteViews, viewId), data, skipCache, false, errorResId,\n        null, key);\n    this.remoteViews = remoteViews;\n    this.viewId = viewId;\n  }\n\n  @Override void complete(Bitmap result, Picasso.LoadedFrom from) {\n    remoteViews.setImageViewBitmap(viewId, result);\n    update();\n  }\n\n  @Override public void error() {\n    if (errorResId != 0) {\n      setImageResource(errorResId);\n    }\n  }\n\n  void setImageResource(int resId) {\n    remoteViews.setImageViewResource(viewId, resId);\n    update();\n  }\n\n  abstract void update();\n\n  static class RemoteViewsTarget {\n    final RemoteViews remoteViews;\n    final int viewId;\n\n    RemoteViewsTarget(RemoteViews remoteViews, int viewId) {\n      this.remoteViews = remoteViews;\n      this.viewId = viewId;\n    }\n\n    @Override public boolean equals(Object o) {\n      if (this == o) return true;\n      if (o == null || getClass() != o.getClass()) return false;\n      RemoteViewsTarget remoteViewsTarget = (RemoteViewsTarget) o;\n      return viewId == remoteViewsTarget.viewId && remoteViews.equals(\n          remoteViewsTarget.remoteViews);\n    }\n\n    @Override public int hashCode() {\n      return 31 * remoteViews.hashCode() + viewId;\n    }\n  }\n\n  static class AppWidgetAction extends RemoteViewsAction {\n    private final int[] appWidgetIds;\n\n    AppWidgetAction(Picasso picasso, Request data, RemoteViews remoteViews, int viewId,\n        int[] appWidgetIds, boolean skipCache, int errorResId, String key) {\n      super(picasso, data, remoteViews, viewId, errorResId, skipCache, key);\n      this.appWidgetIds = appWidgetIds;\n    }\n\n    @Override void update() {\n      AppWidgetManager manager = AppWidgetManager.getInstance(picasso.context);\n      manager.updateAppWidget(appWidgetIds, remoteViews);\n    }\n  }\n\n  static class NotificationAction extends RemoteViewsAction {\n    private final int notificationId;\n    private final Notification notification;\n\n    NotificationAction(Picasso picasso, Request data, RemoteViews remoteViews, int viewId,\n        int notificationId, Notification notification, boolean skipCache, int errorResId,\n        String key) {\n      super(picasso, data, remoteViews, viewId, errorResId, skipCache, key);\n      this.notificationId = notificationId;\n      this.notification = notification;\n    }\n\n    @Override void update() {\n      NotificationManager manager = getService(picasso.context, NOTIFICATION_SERVICE);\n      manager.notify(notificationId, notification);\n    }\n  }\n}\n"
  },
  {
    "path": "picasso/Request.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.graphics.Bitmap;\nimport android.net.Uri;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.TimeUnit;\n\nimport static java.util.Collections.unmodifiableList;\n\n/** Immutable data about an image and the transformations that will be applied to it. */\npublic final class Request {\n  private static final long TOO_LONG_LOG = TimeUnit.SECONDS.toNanos(5);\n\n  /** A unique ID for the request. */\n  int id;\n  /** The time that the request was first submitted (in nanos). */\n  long started;\n  /** Whether or not this request should only load from local cache. */\n  boolean loadFromLocalCacheOnly;\n\n  /**\n   * The image URI.\n   * <p>\n   * This is mutually exclusive with {@link #resourceId}.\n   */\n  public final Uri uri;\n  /**\n   * The image resource ID.\n   * <p>\n   * This is mutually exclusive with {@link #uri}.\n   */\n  public final int resourceId;\n  /** List of custom transformations to be applied after the built-in transformations. */\n  public final List<Transformation> transformations;\n  /** Target image width for resizing. */\n  public final int targetWidth;\n  /** Target image height for resizing. */\n  public final int targetHeight;\n  /**\n   * True if the final image should use the 'centerCrop' scale technique.\n   * <p>\n   * This is mutually exclusive with {@link #centerInside}.\n   */\n  public final boolean centerCrop;\n  /**\n   * True if the final image should use the 'centerInside' scale technique.\n   * <p>\n   * This is mutually exclusive with {@link #centerCrop}.\n   */\n  public final boolean centerInside;\n  /** Amount to rotate the image in degrees. */\n  public final float rotationDegrees;\n  /** Rotation pivot on the X axis. */\n  public final float rotationPivotX;\n  /** Rotation pivot on the Y axis. */\n  public final float rotationPivotY;\n  /** Whether or not {@link #rotationPivotX} and {@link #rotationPivotY} are set. */\n  public final boolean hasRotationPivot;\n  /** Target image config for decoding. */\n  public final Bitmap.Config config;\n\n  private Request(Uri uri, int resourceId, List<Transformation> transformations, int targetWidth,\n      int targetHeight, boolean centerCrop, boolean centerInside, float rotationDegrees,\n      float rotationPivotX, float rotationPivotY, boolean hasRotationPivot, Bitmap.Config config) {\n    this.uri = uri;\n    this.resourceId = resourceId;\n    if (transformations == null) {\n      this.transformations = null;\n    } else {\n      this.transformations = unmodifiableList(transformations);\n    }\n    this.targetWidth = targetWidth;\n    this.targetHeight = targetHeight;\n    this.centerCrop = centerCrop;\n    this.centerInside = centerInside;\n    this.rotationDegrees = rotationDegrees;\n    this.rotationPivotX = rotationPivotX;\n    this.rotationPivotY = rotationPivotY;\n    this.hasRotationPivot = hasRotationPivot;\n    this.config = config;\n  }\n\n  @Override public String toString() {\n    final StringBuilder sb = new StringBuilder(\"Request{\");\n    if (resourceId > 0) {\n      sb.append(resourceId);\n    } else {\n      sb.append(uri);\n    }\n    if (transformations != null && !transformations.isEmpty()) {\n      for (Transformation transformation : transformations) {\n        sb.append(' ').append(transformation.key());\n      }\n    }\n    if (targetWidth > 0) {\n      sb.append(\" resize(\").append(targetWidth).append(',').append(targetHeight).append(')');\n    }\n    if (centerCrop) {\n      sb.append(\" centerCrop\");\n    }\n    if (centerInside) {\n      sb.append(\" centerInside\");\n    }\n    if (rotationDegrees != 0) {\n      sb.append(\" rotation(\").append(rotationDegrees);\n      if (hasRotationPivot) {\n        sb.append(\" @ \").append(rotationPivotX).append(',').append(rotationPivotY);\n      }\n      sb.append(')');\n    }\n    if (config != null) {\n      sb.append(' ').append(config);\n    }\n    sb.append('}');\n\n    return sb.toString();\n  }\n\n  String logId() {\n    long delta = System.nanoTime() - started;\n    if (delta > TOO_LONG_LOG) {\n      return plainId() + '+' + TimeUnit.NANOSECONDS.toSeconds(delta) + 's';\n    }\n    return plainId() + '+' + TimeUnit.NANOSECONDS.toMillis(delta) + \"ms\";\n  }\n\n  String plainId() {\n    return \"[R\" + id + ']';\n  }\n\n  String getName() {\n    if (uri != null) {\n      return String.valueOf(uri.getPath());\n    }\n    return Integer.toHexString(resourceId);\n  }\n\n  public boolean hasSize() {\n    return targetWidth != 0;\n  }\n\n  boolean needsTransformation() {\n    return needsMatrixTransform() || hasCustomTransformations();\n  }\n\n  boolean needsMatrixTransform() {\n    return targetWidth != 0 || rotationDegrees != 0;\n  }\n\n  boolean hasCustomTransformations() {\n    return transformations != null;\n  }\n\n  public Builder buildUpon() {\n    return new Builder(this);\n  }\n\n  /** Builder for creating {@link com.squareup.picasso.Request} instances. */\n  public static final class Builder {\n    private Uri uri;\n    private int resourceId;\n    private int targetWidth;\n    private int targetHeight;\n    private boolean centerCrop;\n    private boolean centerInside;\n    private float rotationDegrees;\n    private float rotationPivotX;\n    private float rotationPivotY;\n    private boolean hasRotationPivot;\n    private List<Transformation> transformations;\n    private Bitmap.Config config;\n\n    /** Start building a request using the specified {@link android.net.Uri}. */\n    public Builder(Uri uri) {\n      setUri(uri);\n    }\n\n    /** Start building a request using the specified resource ID. */\n    public Builder(int resourceId) {\n      setResourceId(resourceId);\n    }\n\n    Builder(Uri uri, int resourceId) {\n      this.uri = uri;\n      this.resourceId = resourceId;\n    }\n\n    private Builder(Request request) {\n      uri = request.uri;\n      resourceId = request.resourceId;\n      targetWidth = request.targetWidth;\n      targetHeight = request.targetHeight;\n      centerCrop = request.centerCrop;\n      centerInside = request.centerInside;\n      rotationDegrees = request.rotationDegrees;\n      rotationPivotX = request.rotationPivotX;\n      rotationPivotY = request.rotationPivotY;\n      hasRotationPivot = request.hasRotationPivot;\n      if (request.transformations != null) {\n        transformations = new ArrayList<Transformation>(request.transformations);\n      }\n      config = request.config;\n    }\n\n    boolean hasImage() {\n      return uri != null || resourceId != 0;\n    }\n\n    boolean hasSize() {\n      return targetWidth != 0;\n    }\n\n    /**\n     * Set the target image Uri.\n     * <p>\n     * This will clear an image resource ID if one is set.\n     */\n    public Builder setUri(Uri uri) {\n      if (uri == null) {\n        throw new IllegalArgumentException(\"Image URI may not be null.\");\n      }\n      this.uri = uri;\n      this.resourceId = 0;\n      return this;\n    }\n\n    /**\n     * Set the target image resource ID.\n     * <p>\n     * This will clear an image Uri if one is set.\n     */\n    public Builder setResourceId(int resourceId) {\n      if (resourceId == 0) {\n        throw new IllegalArgumentException(\"Image resource ID may not be 0.\");\n      }\n      this.resourceId = resourceId;\n      this.uri = null;\n      return this;\n    }\n\n    /** Resize the image to the specified size in pixels. */\n    public Builder resize(int targetWidth, int targetHeight) {\n      if (targetWidth <= 0) {\n        throw new IllegalArgumentException(\"Width must be positive number.\");\n      }\n      if (targetHeight <= 0) {\n        throw new IllegalArgumentException(\"Height must be positive number.\");\n      }\n      this.targetWidth = targetWidth;\n      this.targetHeight = targetHeight;\n      return this;\n    }\n\n    /** Clear the resize transformation, if any. This will also clear center crop/inside if set. */\n    public Builder clearResize() {\n      targetWidth = 0;\n      targetHeight = 0;\n      centerCrop = false;\n      centerInside = false;\n      return this;\n    }\n\n    /**\n     * Crops an image inside of the bounds specified by {@link #resize(int, int)} rather than\n     * distorting the aspect ratio. This cropping technique scales the image so that it fills the\n     * requested bounds and then crops the extra.\n     */\n    public Builder centerCrop() {\n      if (centerInside) {\n        throw new IllegalStateException(\"Center crop can not be used after calling centerInside\");\n      }\n      centerCrop = true;\n      return this;\n    }\n\n    /** Clear the center crop transformation flag, if set. */\n    public Builder clearCenterCrop() {\n      centerCrop = false;\n      return this;\n    }\n\n    /**\n     * Centers an image inside of the bounds specified by {@link #resize(int, int)}. This scales\n     * the image so that both dimensions are equal to or less than the requested bounds.\n     */\n    public Builder centerInside() {\n      if (centerCrop) {\n        throw new IllegalStateException(\"Center inside can not be used after calling centerCrop\");\n      }\n      centerInside = true;\n      return this;\n    }\n\n    /** Clear the center inside transformation flag, if set. */\n    public Builder clearCenterInside() {\n      centerInside = false;\n      return this;\n    }\n\n    /** Rotate the image by the specified degrees. */\n    public Builder rotate(float degrees) {\n      rotationDegrees = degrees;\n      return this;\n    }\n\n    /** Rotate the image by the specified degrees around a pivot point. */\n    public Builder rotate(float degrees, float pivotX, float pivotY) {\n      rotationDegrees = degrees;\n      rotationPivotX = pivotX;\n      rotationPivotY = pivotY;\n      hasRotationPivot = true;\n      return this;\n    }\n\n    /** Clear the rotation transformation, if any. */\n    public Builder clearRotation() {\n      rotationDegrees = 0;\n      rotationPivotX = 0;\n      rotationPivotY = 0;\n      hasRotationPivot = false;\n      return this;\n    }\n\n    /** Decode the image using the specified config. */\n    public Builder config(Bitmap.Config config) {\n      this.config = config;\n      return this;\n    }\n\n    /**\n     * Add a custom transformation to be applied to the image.\n     * <p>\n     * Custom transformations will always be run after the built-in transformations.\n     */\n    public Builder transform(Transformation transformation) {\n      if (transformation == null) {\n        throw new IllegalArgumentException(\"Transformation must not be null.\");\n      }\n      if (transformations == null) {\n        transformations = new ArrayList<Transformation>(2);\n      }\n      transformations.add(transformation);\n      return this;\n    }\n\n    /** Create the immutable {@link com.squareup.picasso.Request} object. */\n    public Request build() {\n      if (centerInside && centerCrop) {\n        throw new IllegalStateException(\"Center crop and center inside can not be used together.\");\n      }\n      if (centerCrop && targetWidth == 0) {\n        throw new IllegalStateException(\"Center crop requires calling resize.\");\n      }\n      if (centerInside && targetWidth == 0) {\n        throw new IllegalStateException(\"Center inside requires calling resize.\");\n      }\n      return new Request(uri, resourceId, transformations, targetWidth, targetHeight, centerCrop,\n          centerInside, rotationDegrees, rotationPivotX, rotationPivotY, hasRotationPivot, config);\n    }\n  }\n}\n"
  },
  {
    "path": "picasso/RequestCreator.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.app.Notification;\nimport android.content.res.Resources;\nimport android.graphics.Bitmap;\nimport android.graphics.drawable.Drawable;\nimport android.net.Uri;\nimport android.widget.ImageView;\nimport android.widget.RemoteViews;\nimport java.io.IOException;\nimport java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport static com.squareup.picasso.BitmapHunter.forRequest;\nimport static com.squareup.picasso.Picasso.LoadedFrom.MEMORY;\nimport static com.squareup.picasso.PicassoDrawable.setBitmap;\nimport static com.squareup.picasso.PicassoDrawable.setPlaceholder;\nimport static com.squareup.picasso.RemoteViewsAction.AppWidgetAction;\nimport static com.squareup.picasso.RemoteViewsAction.NotificationAction;\nimport static com.squareup.picasso.Utils.OWNER_MAIN;\nimport static com.squareup.picasso.Utils.VERB_CHANGED;\nimport static com.squareup.picasso.Utils.VERB_COMPLETED;\nimport static com.squareup.picasso.Utils.VERB_CREATED;\nimport static com.squareup.picasso.Utils.checkMain;\nimport static com.squareup.picasso.Utils.checkNotMain;\nimport static com.squareup.picasso.Utils.createKey;\nimport static com.squareup.picasso.Utils.isMain;\nimport static com.squareup.picasso.Utils.log;\n\n/** Fluent API for building an image download request. */\n@SuppressWarnings(\"UnusedDeclaration\") // Public API.\npublic class RequestCreator {\n  private static int nextId = 0;\n\n  private static int getRequestId() {\n    if (isMain()) {\n      return nextId++;\n    }\n\n    final CountDownLatch latch = new CountDownLatch(1);\n    final AtomicInteger id = new AtomicInteger();\n    Picasso.HANDLER.post(new Runnable() {\n      @Override public void run() {\n        id.set(getRequestId());\n        latch.countDown();\n      }\n    });\n    try {\n      latch.await();\n    } catch (final InterruptedException e) {\n      Picasso.HANDLER.post(new Runnable() {\n        @Override public void run() {\n          throw new RuntimeException(e);\n        }\n      });\n    }\n    return id.get();\n  }\n\n  private final Picasso picasso;\n  private final Request.Builder data;\n\n  private boolean skipMemoryCache;\n  private boolean noFade;\n  private boolean deferred;\n  private int placeholderResId;\n  private int errorResId;\n  private Drawable placeholderDrawable;\n  private Drawable errorDrawable;\n\n  RequestCreator(Picasso picasso, Uri uri, int resourceId) {\n    if (picasso.shutdown) {\n      throw new IllegalStateException(\n          \"Picasso instance already shut down. Cannot submit new requests.\");\n    }\n    this.picasso = picasso;\n    this.data = new Request.Builder(uri, resourceId);\n  }\n\n   RequestCreator() {\n    this.picasso = null;\n    this.data = new Request.Builder(null, 0);\n  }\n\n  /**\n   * A placeholder drawable to be used while the image is being loaded. If the requested image is\n   * not immediately available in the memory cache then this resource will be set on the target\n   * {@link android.widget.ImageView}.\n   */\n  public RequestCreator placeholder(int placeholderResId) {\n    if (placeholderResId == 0) {\n      throw new IllegalArgumentException(\"Placeholder image resource invalid.\");\n    }\n    if (placeholderDrawable != null) {\n      throw new IllegalStateException(\"Placeholder image already set.\");\n    }\n    this.placeholderResId = placeholderResId;\n    return this;\n  }\n\n  /**\n   * A placeholder drawable to be used while the image is being loaded. If the requested image is\n   * not immediately available in the memory cache then this resource will be set on the target\n   * {@link android.widget.ImageView}.\n   * <p>\n   * If you are not using a placeholder image but want to clear an existing image (such as when\n   * used in an {@link android.widget.Adapter adapter}), pass in {@code null}.\n   */\n  public RequestCreator placeholder(Drawable placeholderDrawable) {\n    if (placeholderResId != 0) {\n      throw new IllegalStateException(\"Placeholder image already set.\");\n    }\n    this.placeholderDrawable = placeholderDrawable;\n    return this;\n  }\n\n  /** An error drawable to be used if the request image could not be loaded. */\n  public RequestCreator error(int errorResId) {\n    if (errorResId == 0) {\n      throw new IllegalArgumentException(\"Error image resource invalid.\");\n    }\n    if (errorDrawable != null) {\n      throw new IllegalStateException(\"Error image already set.\");\n    }\n    this.errorResId = errorResId;\n    return this;\n  }\n\n  /** An error drawable to be used if the request image could not be loaded. */\n  public RequestCreator error(Drawable errorDrawable) {\n    if (errorDrawable == null) {\n      throw new IllegalArgumentException(\"Error image may not be null.\");\n    }\n    if (errorResId != 0) {\n      throw new IllegalStateException(\"Error image already set.\");\n    }\n    this.errorDrawable = errorDrawable;\n    return this;\n  }\n\n  /**\n   * Attempt to resize the image to fit exactly into the target {@link android.widget.ImageView}'s bounds. This\n   * will result in delayed execution of the request until the {@link android.widget.ImageView} has been laid out.\n   * <p>\n   * <em>Note:</em> This method works only when your target is an {@link android.widget.ImageView}.\n   */\n  public RequestCreator fit() {\n    deferred = true;\n    return this;\n  }\n\n  /** Internal use only. Used by {@link com.squareup.picasso.DeferredRequestCreator}. */\n  RequestCreator unfit() {\n    deferred = false;\n    return this;\n  }\n\n  /** Resize the image to the specified dimension size. */\n  public RequestCreator resizeDimen(int targetWidthResId, int targetHeightResId) {\n    Resources resources = picasso.context.getResources();\n    int targetWidth = resources.getDimensionPixelSize(targetWidthResId);\n    int targetHeight = resources.getDimensionPixelSize(targetHeightResId);\n    return resize(targetWidth, targetHeight);\n  }\n\n  /** Resize the image to the specified size in pixels. */\n  public RequestCreator resize(int targetWidth, int targetHeight) {\n    data.resize(targetWidth, targetHeight);\n    return this;\n  }\n\n  /**\n   * Crops an image inside of the bounds specified by {@link #resize(int, int)} rather than\n   * distorting the aspect ratio. This cropping technique scales the image so that it fills the\n   * requested bounds and then crops the extra.\n   */\n  public RequestCreator centerCrop() {\n    data.centerCrop();\n    return this;\n  }\n\n  /**\n   * Centers an image inside of the bounds specified by {@link #resize(int, int)}. This scales\n   * the image so that both dimensions are equal to or less than the requested bounds.\n   */\n  public RequestCreator centerInside() {\n    data.centerInside();\n    return this;\n  }\n\n  /** Rotate the image by the specified degrees. */\n  public RequestCreator rotate(float degrees) {\n    data.rotate(degrees);\n    return this;\n  }\n\n  /** Rotate the image by the specified degrees around a pivot point. */\n  public RequestCreator rotate(float degrees, float pivotX, float pivotY) {\n    data.rotate(degrees, pivotX, pivotY);\n    return this;\n  }\n\n  /**\n   * Attempt to decode the image using the specified config.\n   * <p>\n   * Note: This value may be ignored by {@link android.graphics.BitmapFactory}. See\n   * {@link android.graphics.BitmapFactory.Options#inPreferredConfig its documentation} for more details.\n   */\n  public RequestCreator config(Bitmap.Config config) {\n    data.config(config);\n    return this;\n  }\n\n  /**\n   * Add a custom transformation to be applied to the image.\n   * <p>\n   * Custom transformations will always be run after the built-in transformations.\n   */\n  // TODO show example of calling resize after a transform in the javadoc\n  public RequestCreator transform(Transformation transformation) {\n    data.transform(transformation);\n    return this;\n  }\n\n  /**\n   * Indicate that this action should not use the memory cache for attempting to load or save the\n   * image. This can be useful when you know an image will only ever be used once (e.g., loading\n   * an image from the filesystem and uploading to a remote server).\n   */\n  public RequestCreator skipMemoryCache() {\n    skipMemoryCache = true;\n    return this;\n  }\n\n  /** Disable brief fade in of images loaded from the disk cache or network. */\n  public RequestCreator noFade() {\n    noFade = true;\n    return this;\n  }\n\n  /**\n   * Synchronously fulfill this request. Must not be called from the main thread.\n   * <p>\n   * <em>Note</em>: The result of this operation is not cached in memory because the underlying\n   * {@link com.squareup.picasso.Cache} implementation is not guaranteed to be thread-safe.\n   */\n  public Bitmap get() throws IOException {\n    long started = System.nanoTime();\n    checkNotMain();\n\n    if (deferred) {\n      throw new IllegalStateException(\"Fit cannot be used with get.\");\n    }\n    if (!data.hasImage()) {\n      return null;\n    }\n\n    Request finalData = createRequest(started);\n    String key = createKey(finalData, new StringBuilder());\n\n    Action action = new GetAction(picasso, finalData, skipMemoryCache, key);\n    return forRequest(picasso, picasso.dispatcher, picasso.cache, picasso.stats, action).hunt();\n  }\n\n  /**\n   * Asynchronously fulfills the request without a {@link android.widget.ImageView} or {@link com.squareup.picasso.Target}. This is\n   * useful when you want to warm up the cache with an image.\n   * <p>\n   * <em>Note:</em> It is safe to invoke this method from any thread.\n   */\n  public void fetch() {\n    long started = System.nanoTime();\n\n    if (deferred) {\n      throw new IllegalStateException(\"Fit cannot be used with fetch.\");\n    }\n    if (data.hasImage()) {\n      Request request = createRequest(started);\n      String key = createKey(request, new StringBuilder());\n\n      Action action = new FetchAction(picasso, request, skipMemoryCache, key);\n      picasso.submit(action);\n    }\n  }\n\n  /**\n   * Asynchronously fulfills the request into the specified {@link com.squareup.picasso.Target}. In most cases, you\n   * should use this when you are dealing with a custom {@link android.view.View View} or view\n   * holder which should implement the {@link com.squareup.picasso.Target} interface.\n   * <p>\n   * Implementing on a {@link android.view.View View}:\n   * <blockquote><pre>\n   * public class ProfileView extends FrameLayout implements Target {\n   *   {@literal @}Override public void onBitmapLoaded(Bitmap bitmap, LoadedFrom from) {\n   *     setBackgroundDrawable(new BitmapDrawable(bitmap));\n   *   }\n   *\n   *   {@literal @}Override public void onBitmapFailed() {\n   *     setBackgroundResource(R.drawable.profile_error);\n   *   }\n   *\n   *   {@literal @}Override public void onPrepareLoad(Drawable placeHolderDrawable) {\n   *     frame.setBackgroundDrawable(placeHolderDrawable);\n   *   }\n   * }\n   * </pre></blockquote>\n   * Implementing on a view holder object for use inside of an adapter:\n   * <blockquote><pre>\n   * public class ViewHolder implements Target {\n   *   public FrameLayout frame;\n   *   public TextView name;\n   *\n   *   {@literal @}Override public void onBitmapLoaded(Bitmap bitmap, LoadedFrom from) {\n   *     frame.setBackgroundDrawable(new BitmapDrawable(bitmap));\n   *   }\n   *\n   *   {@literal @}Override public void onBitmapFailed() {\n   *     frame.setBackgroundResource(R.drawable.profile_error);\n   *   }\n   *\n   *   {@literal @}Override public void onPrepareLoad(Drawable placeHolderDrawable) {\n   *     frame.setBackgroundDrawable(placeHolderDrawable);\n   *   }\n   * }\n   * </pre></blockquote>\n   * <p>\n   * <em>Note:</em> This method keeps a weak reference to the {@link com.squareup.picasso.Target} instance and will be\n   * garbage collected if you do not keep a strong reference to it. To receive callbacks when an\n   * image is loaded use {@link #into(android.widget.ImageView, com.squareup.picasso.Callback)}.\n   */\n  public void into(Target target) {\n    long started = System.nanoTime();\n    checkMain();\n\n    if (target == null) {\n      throw new IllegalArgumentException(\"Target must not be null.\");\n    }\n    if (deferred) {\n      throw new IllegalStateException(\"Fit cannot be used with a Target.\");\n    }\n\n    Drawable drawable =\n        placeholderResId != 0 ? picasso.context.getResources().getDrawable(placeholderResId)\n            : placeholderDrawable;\n\n    if (!data.hasImage()) {\n      picasso.cancelRequest(target);\n      target.onPrepareLoad(drawable);\n      return;\n    }\n\n    Request request = createRequest(started);\n    String requestKey = createKey(request);\n\n    if (!skipMemoryCache) {\n      Bitmap bitmap = picasso.quickMemoryCacheCheck(requestKey);\n      if (bitmap != null) {\n        picasso.cancelRequest(target);\n        target.onBitmapLoaded(bitmap, MEMORY);\n        return;\n      }\n    }\n\n    target.onPrepareLoad(drawable);\n\n    Action action =\n        new TargetAction(picasso, target, request, skipMemoryCache, errorResId, errorDrawable,\n            requestKey);\n    picasso.enqueueAndSubmit(action);\n  }\n\n  /**\n   * Asynchronously fulfills the request into the specified {@link android.widget.RemoteViews} object with the\n   * given {@code viewId}. This is used for loading bitmaps into a {@link android.app.Notification}.\n   */\n  public void into(RemoteViews remoteViews, int viewId, int notificationId,\n      Notification notification) {\n    long started = System.nanoTime();\n    checkMain();\n\n    if (remoteViews == null) {\n      throw new IllegalArgumentException(\"RemoteViews must not be null.\");\n    }\n    if (notification == null) {\n      throw new IllegalArgumentException(\"Notification must not be null.\");\n    }\n    if (deferred) {\n      throw new IllegalStateException(\"Fit cannot be used with RemoteViews.\");\n    }\n    if (placeholderDrawable != null || errorDrawable != null) {\n      throw new IllegalArgumentException(\n          \"Cannot use placeholder or error drawables with remote views.\");\n    }\n\n    Request request = createRequest(started);\n    String key = createKey(request);\n\n    RemoteViewsAction action =\n        new NotificationAction(picasso, request, remoteViews, viewId, notificationId, notification,\n            skipMemoryCache, errorResId, key);\n\n    performRemoteViewInto(action);\n  }\n\n  /**\n   * Asynchronously fulfills the request into the specified {@link android.widget.RemoteViews} object with the\n   * given {@code viewId}. This is used for loading bitmaps into all instances of a widget.\n   */\n  public void into(RemoteViews remoteViews, int viewId, int[] appWidgetIds) {\n    long started = System.nanoTime();\n    checkMain();\n\n    if (remoteViews == null) {\n      throw new IllegalArgumentException(\"remoteViews must not be null.\");\n    }\n    if (appWidgetIds == null) {\n      throw new IllegalArgumentException(\"appWidgetIds must not be null.\");\n    }\n    if (deferred) {\n      throw new IllegalStateException(\"Fit cannot be used with remote views.\");\n    }\n    if (placeholderDrawable != null || errorDrawable != null) {\n      throw new IllegalArgumentException(\n          \"Cannot use placeholder or error drawables with remote views.\");\n    }\n\n    Request request = createRequest(started);\n    String key = createKey(request);\n\n    RemoteViewsAction action =\n        new AppWidgetAction(picasso, request, remoteViews, viewId, appWidgetIds, skipMemoryCache,\n            errorResId, key);\n\n    performRemoteViewInto(action);\n  }\n\n  /**\n   * Asynchronously fulfills the request into the specified {@link android.widget.ImageView}.\n   * <p>\n   * <em>Note:</em> This method keeps a weak reference to the {@link android.widget.ImageView} instance and will\n   * automatically support object recycling.\n   */\n  public void into(ImageView target) {\n    into(target, null);\n  }\n\n  /**\n   * Asynchronously fulfills the request into the specified {@link android.widget.ImageView} and invokes the\n   * target {@link com.squareup.picasso.Callback} if it's not {@code null}.\n   * <p>\n   * <em>Note:</em> The {@link com.squareup.picasso.Callback} param is a strong reference and will prevent your\n   * {@link android.app.Activity} or {@link android.app.Fragment} from being garbage collected. If\n   * you use this method, it is <b>strongly</b> recommended you invoke an adjacent\n   * {@link com.squareup.picasso.Picasso#cancelRequest(android.widget.ImageView)} call to prevent temporary leaking.\n   */\n  public void into(ImageView target, Callback callback) {\n    long started = System.nanoTime();\n    checkMain();\n\n    if (target == null) {\n      throw new IllegalArgumentException(\"Target must not be null.\");\n    }\n\n    if (!data.hasImage()) {\n      picasso.cancelRequest(target);\n      setPlaceholder(target, placeholderResId, placeholderDrawable);\n      return;\n    }\n\n    if (deferred) {\n      if (data.hasSize()) {\n        throw new IllegalStateException(\"Fit cannot be used with resize.\");\n      }\n      int width = target.getWidth();\n      int height = target.getHeight();\n      if (width == 0 || height == 0) {\n        setPlaceholder(target, placeholderResId, placeholderDrawable);\n        picasso.defer(target, new DeferredRequestCreator(this, target, callback));\n        return;\n      }\n      data.resize(width, height);\n    }\n\n    Request request = createRequest(started);\n    String requestKey = createKey(request);\n\n    if (!skipMemoryCache) {\n      Bitmap bitmap = picasso.quickMemoryCacheCheck(requestKey);\n      if (bitmap != null) {\n        picasso.cancelRequest(target);\n        setBitmap(target, picasso.context, bitmap, MEMORY, noFade, picasso.indicatorsEnabled);\n        if (picasso.loggingEnabled) {\n          log(OWNER_MAIN, VERB_COMPLETED, request.plainId(), \"from \" + MEMORY);\n        }\n        if (callback != null) {\n          callback.onSuccess();\n        }\n        return;\n      }\n    }\n\n    setPlaceholder(target, placeholderResId, placeholderDrawable);\n\n    Action action =\n        new ImageViewAction(picasso, target, request, skipMemoryCache, noFade, errorResId,\n            errorDrawable, requestKey, callback);\n\n    picasso.enqueueAndSubmit(action);\n  }\n\n  /** Create the request optionally passing it through the request transformer. */\n  private Request createRequest(long started) {\n    int id = getRequestId();\n\n    Request request = data.build();\n    request.id = id;\n    request.started = started;\n\n    boolean loggingEnabled = picasso.loggingEnabled;\n    if (loggingEnabled) {\n      log(OWNER_MAIN, VERB_CREATED, request.plainId(), request.toString());\n    }\n\n    Request transformed = picasso.transformRequest(request);\n    if (transformed != request) {\n      // If the request was changed, copy over the id and timestamp from the original.\n      transformed.id = id;\n      transformed.started = started;\n\n      if (loggingEnabled) {\n        log(OWNER_MAIN, VERB_CHANGED, transformed.logId(), \"into \" + transformed);\n      }\n    }\n\n    return transformed;\n  }\n\n  private void performRemoteViewInto(RemoteViewsAction action) {\n    if (!skipMemoryCache) {\n      Bitmap bitmap = picasso.quickMemoryCacheCheck(action.getKey());\n      if (bitmap != null) {\n        action.complete(bitmap, MEMORY);\n        return;\n      }\n    }\n\n    if (placeholderResId != 0) {\n      action.setImageResource(placeholderResId);\n    }\n\n    picasso.enqueueAndSubmit(action);\n  }\n}\n"
  },
  {
    "path": "picasso/RequestHandler.java",
    "content": "/*\n * Copyright (C) 2014 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.net.NetworkInfo;\n\nimport java.io.IOException;\n\n/**\n * {@link com.squareup.picasso.RequestHandler} allows you to extend Picasso to load images\n * in ways that are not supported by default in the library.\n * <p>\n * <h2>Usage</h2>\n * <p>{@link com.squareup.picasso.RequestHandler} must be subclassed to be used. You will have to\n * override two methods ({@link #canHandleRequest(com.squareup.picasso.Request)} and\n * {@link #load(com.squareup.picasso.Request)}) with your custom logic to load images.</p>\n *\n * <p>You should then register your {@link com.squareup.picasso.RequestHandler} using\n * {@link com.squareup.picasso.Picasso.Builder#addRequestHandler(com.squareup.picasso.RequestHandler)}</p>\n *\n * <b>NOTE:</b> This is a beta feature. The API is subject to change in a backwards\n * incompatible way at any time.\n *\n * @see com.squareup.picasso.Picasso.Builder#addRequestHandler(com.squareup.picasso.RequestHandler)\n */\npublic abstract class RequestHandler {\n  /**\n   * {@link com.squareup.picasso.RequestHandler.Result} represents the result of a {@link #load(com.squareup.picasso.Request)} call in a\n   * {@link com.squareup.picasso.RequestHandler}.\n   *\n   * @see com.squareup.picasso.RequestHandler\n   * @see #load(com.squareup.picasso.Request)\n   */\n  public static final class Result {\n    private final Picasso.LoadedFrom loadedFrom;\n    private final Bitmap bitmap;\n    private final int exifOrientation;\n\n    public Result(Bitmap bitmap, Picasso.LoadedFrom loadedFrom) {\n      this(bitmap, loadedFrom, 0);\n    }\n\n    Result(Bitmap bitmap, Picasso.LoadedFrom loadedFrom, int exifOrientation) {\n      this.bitmap = bitmap;\n      this.loadedFrom = loadedFrom;\n      this.exifOrientation = exifOrientation;\n    }\n\n    /**\n     * Returns the resulting {@link android.graphics.Bitmap} generated\n     * from a {@link #load(com.squareup.picasso.Request)} call.\n     */\n    public Bitmap getBitmap() {\n      return bitmap;\n    }\n\n    /**\n     * Returns the resulting {@link com.squareup.picasso.Picasso.LoadedFrom} generated\n     * from a {@link #load(com.squareup.picasso.Request)} call.\n     */\n    public Picasso.LoadedFrom getLoadedFrom() {\n      return loadedFrom;\n    }\n\n    /**\n     * Returns the resulting EXIF orientation generated\n     * from a {@link #load(com.squareup.picasso.Request)} call. This is only accessible\n     * to built-in RequestHandlers.\n     */\n    int getExifOrientation() {\n      return exifOrientation;\n    }\n  }\n\n  /**\n   * Whether or not this {@link com.squareup.picasso.RequestHandler} can handle a request with the\n   * given {@link com.squareup.picasso.Request}.\n   */\n  public abstract boolean canHandleRequest(Request data);\n\n  /**\n   * Loads an image for the given {@link com.squareup.picasso.Request}.\n   *\n   * @param data the {@link android.net.Uri} to load the image from.\n   * @return A {@link com.squareup.picasso.RequestHandler.Result} instance representing the result.\n   */\n  public abstract Result load(Request data) throws IOException;\n\n  int getRetryCount() {\n    return 0;\n  }\n\n  boolean shouldRetry(boolean airplaneMode, NetworkInfo info) {\n    return false;\n  }\n\n  boolean supportsReplay() {\n    return false;\n  }\n\n  /**\n   * Lazily create {@link android.graphics.BitmapFactory.Options} based in given\n   * {@link com.squareup.picasso.Request}, only instantiating them if needed.\n   */\n  static BitmapFactory.Options createBitmapOptions(Request data) {\n    final boolean justBounds = data.hasSize();\n    final boolean hasConfig = data.config != null;\n    BitmapFactory.Options options = null;\n    if (justBounds || hasConfig) {\n      options = new BitmapFactory.Options();\n      options.inJustDecodeBounds = justBounds;\n      if (hasConfig) {\n        options.inPreferredConfig = data.config;\n      }\n    }\n    return options;\n  }\n\n  static boolean requiresInSampleSize(BitmapFactory.Options options) {\n    return options != null && options.inJustDecodeBounds;\n  }\n\n  static void calculateInSampleSize(int reqWidth, int reqHeight, BitmapFactory.Options options) {\n    calculateInSampleSize(reqWidth, reqHeight, options.outWidth, options.outHeight, options);\n  }\n\n  static void calculateInSampleSize(int reqWidth, int reqHeight, int width, int height,\n                                    BitmapFactory.Options options) {\n    int sampleSize = 1;\n    if (height > reqHeight || width > reqWidth) {\n      final int heightRatio = (int) Math.floor((float) height / (float) reqHeight);\n      final int widthRatio = (int) Math.floor((float) width / (float) reqWidth);\n      sampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;\n    }\n    options.inSampleSize = sampleSize;\n    options.inJustDecodeBounds = false;\n  }\n}\n"
  },
  {
    "path": "picasso/ResourceRequestHandler.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport java.io.IOException;\n\nimport static android.content.ContentResolver.SCHEME_ANDROID_RESOURCE;\nimport static com.squareup.picasso.Picasso.LoadedFrom.DISK;\n\nclass ResourceRequestHandler extends RequestHandler {\n  private final Context context;\n\n  ResourceRequestHandler(Context context) {\n    this.context = context;\n  }\n\n  @Override public boolean canHandleRequest(Request data) {\n    if (data.resourceId != 0) {\n      return true;\n    }\n\n    return SCHEME_ANDROID_RESOURCE.equals(data.uri.getScheme());\n  }\n\n  @Override public Result load(Request data) throws IOException {\n    Resources res = Utils.getResources(context, data);\n    int id = Utils.getResourceId(res, data);\n    return new Result(decodeResource(res, id, data), DISK);\n  }\n\n  private static Bitmap decodeResource(Resources resources, int id, Request data) {\n    final BitmapFactory.Options options = createBitmapOptions(data);\n    if (requiresInSampleSize(options)) {\n      BitmapFactory.decodeResource(resources, id, options);\n      calculateInSampleSize(data.targetWidth, data.targetHeight, options);\n    }\n    return BitmapFactory.decodeResource(resources, id, options);\n  }\n}\n"
  },
  {
    "path": "picasso/Stats.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.graphics.Bitmap;\nimport android.os.Handler;\nimport android.os.HandlerThread;\nimport android.os.Looper;\nimport android.os.Message;\n\nimport static android.os.Process.THREAD_PRIORITY_BACKGROUND;\n\nclass Stats {\n  private static final int CACHE_HIT = 0;\n  private static final int CACHE_MISS = 1;\n  private static final int BITMAP_DECODE_FINISHED = 2;\n  private static final int BITMAP_TRANSFORMED_FINISHED = 3;\n  private static final int DOWNLOAD_FINISHED = 4;\n\n  private static final String STATS_THREAD_NAME = Utils.THREAD_PREFIX + \"Stats\";\n\n  final HandlerThread statsThread;\n  final Cache cache;\n  final Handler handler;\n\n  long cacheHits;\n  long cacheMisses;\n  long totalDownloadSize;\n  long totalOriginalBitmapSize;\n  long totalTransformedBitmapSize;\n  long averageDownloadSize;\n  long averageOriginalBitmapSize;\n  long averageTransformedBitmapSize;\n  int downloadCount;\n  int originalBitmapCount;\n  int transformedBitmapCount;\n\n  Stats(Cache cache) {\n    this.cache = cache;\n    this.statsThread = new HandlerThread(STATS_THREAD_NAME, THREAD_PRIORITY_BACKGROUND);\n    this.statsThread.start();\n    this.handler = new StatsHandler(statsThread.getLooper(), this);\n  }\n\n  void dispatchBitmapDecoded(Bitmap bitmap) {\n    processBitmap(bitmap, BITMAP_DECODE_FINISHED);\n  }\n\n  void dispatchBitmapTransformed(Bitmap bitmap) {\n    processBitmap(bitmap, BITMAP_TRANSFORMED_FINISHED);\n  }\n\n  void dispatchDownloadFinished(long size) {\n    handler.sendMessage(handler.obtainMessage(DOWNLOAD_FINISHED, size));\n  }\n\n  void dispatchCacheHit() {\n    handler.sendEmptyMessage(CACHE_HIT);\n  }\n\n  void dispatchCacheMiss() {\n    handler.sendEmptyMessage(CACHE_MISS);\n  }\n\n  void shutdown() {\n    statsThread.quit();\n  }\n\n  void performCacheHit() {\n    cacheHits++;\n  }\n\n  void performCacheMiss() {\n    cacheMisses++;\n  }\n\n  void performDownloadFinished(Long size) {\n    downloadCount++;\n    totalDownloadSize += size;\n    averageDownloadSize = getAverage(downloadCount, totalDownloadSize);\n  }\n\n  void performBitmapDecoded(long size) {\n    originalBitmapCount++;\n    totalOriginalBitmapSize += size;\n    averageOriginalBitmapSize = getAverage(originalBitmapCount, totalOriginalBitmapSize);\n  }\n\n  void performBitmapTransformed(long size) {\n    transformedBitmapCount++;\n    totalTransformedBitmapSize += size;\n    averageTransformedBitmapSize = getAverage(originalBitmapCount, totalTransformedBitmapSize);\n  }\n\n  StatsSnapshot createSnapshot() {\n    return new StatsSnapshot(cache.maxSize(), cache.size(), cacheHits, cacheMisses,\n        totalDownloadSize, totalOriginalBitmapSize, totalTransformedBitmapSize, averageDownloadSize,\n        averageOriginalBitmapSize, averageTransformedBitmapSize, downloadCount, originalBitmapCount,\n        transformedBitmapCount, System.currentTimeMillis());\n  }\n\n  private void processBitmap(Bitmap bitmap, int what) {\n    // Never send bitmaps to the handler as they could be recycled before we process them.\n    int bitmapSize = Utils.getBitmapBytes(bitmap);\n    handler.sendMessage(handler.obtainMessage(what, bitmapSize, 0));\n  }\n\n  private static long getAverage(int count, long totalSize) {\n    return totalSize / count;\n  }\n\n  private static class StatsHandler extends Handler {\n\n    private final Stats stats;\n\n    public StatsHandler(Looper looper, Stats stats) {\n      super(looper);\n      this.stats = stats;\n    }\n\n    @Override public void handleMessage(final Message msg) {\n      switch (msg.what) {\n        case CACHE_HIT:\n          stats.performCacheHit();\n          break;\n        case CACHE_MISS:\n          stats.performCacheMiss();\n          break;\n        case BITMAP_DECODE_FINISHED:\n          stats.performBitmapDecoded(msg.arg1);\n          break;\n        case BITMAP_TRANSFORMED_FINISHED:\n          stats.performBitmapTransformed(msg.arg1);\n          break;\n        case DOWNLOAD_FINISHED:\n          stats.performDownloadFinished((Long) msg.obj);\n          break;\n        default:\n          Picasso.HANDLER.post(new Runnable() {\n            @Override public void run() {\n              throw new AssertionError(\"Unhandled stats message.\" + msg.what);\n            }\n          });\n      }\n    }\n  }\n}"
  },
  {
    "path": "picasso/StatsSnapshot.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.util.Log;\nimport java.io.PrintWriter;\nimport java.io.StringWriter;\n\nimport static com.squareup.picasso.Picasso.TAG;\n\n/** Represents all stats for a {@link com.squareup.picasso.Picasso} instance at a single point in time. */\npublic class StatsSnapshot {\n  public final int maxSize;\n  public final int size;\n  public final long cacheHits;\n  public final long cacheMisses;\n  public final long totalDownloadSize;\n  public final long totalOriginalBitmapSize;\n  public final long totalTransformedBitmapSize;\n  public final long averageDownloadSize;\n  public final long averageOriginalBitmapSize;\n  public final long averageTransformedBitmapSize;\n  public final int downloadCount;\n  public final int originalBitmapCount;\n  public final int transformedBitmapCount;\n\n  public final long timeStamp;\n\n  public StatsSnapshot(int maxSize, int size, long cacheHits, long cacheMisses,\n      long totalDownloadSize, long totalOriginalBitmapSize, long totalTransformedBitmapSize,\n      long averageDownloadSize, long averageOriginalBitmapSize, long averageTransformedBitmapSize,\n      int downloadCount, int originalBitmapCount, int transformedBitmapCount, long timeStamp) {\n    this.maxSize = maxSize;\n    this.size = size;\n    this.cacheHits = cacheHits;\n    this.cacheMisses = cacheMisses;\n    this.totalDownloadSize = totalDownloadSize;\n    this.totalOriginalBitmapSize = totalOriginalBitmapSize;\n    this.totalTransformedBitmapSize = totalTransformedBitmapSize;\n    this.averageDownloadSize = averageDownloadSize;\n    this.averageOriginalBitmapSize = averageOriginalBitmapSize;\n    this.averageTransformedBitmapSize = averageTransformedBitmapSize;\n    this.downloadCount = downloadCount;\n    this.originalBitmapCount = originalBitmapCount;\n    this.transformedBitmapCount = transformedBitmapCount;\n    this.timeStamp = timeStamp;\n  }\n\n  /** Prints out this {@link com.squareup.picasso.StatsSnapshot} into log. */\n  @SuppressWarnings(\"UnusedDeclaration\") public void dump() {\n    StringWriter logWriter = new StringWriter();\n    dump(new PrintWriter(logWriter));\n    Log.i(TAG, logWriter.toString());\n  }\n\n  /** Prints out this {@link com.squareup.picasso.StatsSnapshot} with the the provided {@link java.io.PrintWriter}. */\n  public void dump(PrintWriter writer) {\n    writer.println(\"===============BEGIN PICASSO STATS ===============\");\n    writer.println(\"Memory Cache Stats\");\n    writer.print(\"  Max Cache Size: \");\n    writer.println(maxSize);\n    writer.print(\"  Cache Size: \");\n    writer.println(size);\n    writer.print(\"  Cache % Full: \");\n    writer.println((int) Math.ceil((float) size / maxSize * 100));\n    writer.print(\"  Cache Hits: \");\n    writer.println(cacheHits);\n    writer.print(\"  Cache Misses: \");\n    writer.println(cacheMisses);\n    writer.println(\"Network Stats\");\n    writer.print(\"  Download Count: \");\n    writer.println(downloadCount);\n    writer.print(\"  Total Download Size: \");\n    writer.println(totalDownloadSize);\n    writer.print(\"  Average Download Size: \");\n    writer.println(averageDownloadSize);\n    writer.println(\"Bitmap Stats\");\n    writer.print(\"  Total Bitmaps Decoded: \");\n    writer.println(originalBitmapCount);\n    writer.print(\"  Total Bitmap Size: \");\n    writer.println(totalOriginalBitmapSize);\n    writer.print(\"  Total Transformed Bitmaps: \");\n    writer.println(transformedBitmapCount);\n    writer.print(\"  Total Transformed Bitmap Size: \");\n    writer.println(totalTransformedBitmapSize);\n    writer.print(\"  Average Bitmap Size: \");\n    writer.println(averageOriginalBitmapSize);\n    writer.print(\"  Average Transformed Bitmap Size: \");\n    writer.println(averageTransformedBitmapSize);\n    writer.println(\"===============END PICASSO STATS ===============\");\n    writer.flush();\n  }\n\n  @Override public String toString() {\n    return \"StatsSnapshot{\"\n        + \"maxSize=\"\n        + maxSize\n        + \", size=\"\n        + size\n        + \", cacheHits=\"\n        + cacheHits\n        + \", cacheMisses=\"\n        + cacheMisses\n        + \", downloadCount=\"\n        + downloadCount\n        + \", totalDownloadSize=\"\n        + totalDownloadSize\n        + \", averageDownloadSize=\"\n        + averageDownloadSize\n        + \", totalOriginalBitmapSize=\"\n        + totalOriginalBitmapSize\n        + \", totalTransformedBitmapSize=\"\n        + totalTransformedBitmapSize\n        + \", averageOriginalBitmapSize=\"\n        + averageOriginalBitmapSize\n        + \", averageTransformedBitmapSize=\"\n        + averageTransformedBitmapSize\n        + \", originalBitmapCount=\"\n        + originalBitmapCount\n        + \", transformedBitmapCount=\"\n        + transformedBitmapCount\n        + \", timeStamp=\"\n        + timeStamp\n        + '}';\n  }\n}\n"
  },
  {
    "path": "picasso/Target.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.graphics.Bitmap;\nimport android.graphics.drawable.Drawable;\n\nimport static com.squareup.picasso.Picasso.LoadedFrom;\n\n/**\n * Represents an arbitrary listener for image loading.\n * <p>\n * Objects implementing this class <strong>must</strong> have a working implementation of\n * {@link Object#equals(Object)} and {@link Object#hashCode()} for proper storage internally.\n * Instances of this interface will also be compared to determine if view recycling is occurring.\n * It is recommended that you add this interface directly on to a custom view type when using in an\n * adapter to ensure correct recycling behavior.\n */\npublic interface Target {\n  /**\n   * Callback when an image has been successfully loaded.\n   * <p>\n   * <strong>Note:</strong> You must not recycle the bitmap.\n   */\n  void onBitmapLoaded(Bitmap bitmap, LoadedFrom from);\n\n  /**\n   * Callback indicating the image could not be successfully loaded.\n   * <p>\n   * <strong>Note:</strong> The passed {@link android.graphics.drawable.Drawable} may be {@code null} if none has been\n   * specified via {@link com.squareup.picasso.RequestCreator#error(android.graphics.drawable.Drawable)}\n   * or {@link com.squareup.picasso.RequestCreator#error(int)}.\n   */\n  void onBitmapFailed(Drawable errorDrawable);\n\n  /**\n   * Callback invoked right before your request is submitted.\n   * <p>\n   * <strong>Note:</strong> The passed {@link android.graphics.drawable.Drawable} may be {@code null} if none has been\n   * specified via {@link com.squareup.picasso.RequestCreator#placeholder(android.graphics.drawable.Drawable)}\n   * or {@link com.squareup.picasso.RequestCreator#placeholder(int)}.\n   */\n  void onPrepareLoad(Drawable placeHolderDrawable);\n}\n"
  },
  {
    "path": "picasso/TargetAction.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.graphics.Bitmap;\nimport android.graphics.drawable.Drawable;\n\nfinal class TargetAction extends Action<Target> {\n\n  TargetAction(Picasso picasso, Target target, Request data, boolean skipCache,\n        int errorResId, Drawable errorDrawable, String key) {\n    super(picasso, target, data, skipCache, false, errorResId, errorDrawable, key);\n  }\n\n  @Override void complete(Bitmap result, Picasso.LoadedFrom from) {\n    if (result == null) {\n      throw new AssertionError(\n          String.format(\"Attempted to complete action with no result!\\n%s\", this));\n    }\n    Target target = getTarget();\n    if (target != null) {\n      target.onBitmapLoaded(result, from);\n      if (result.isRecycled()) {\n        throw new IllegalStateException(\"Target callback must not recycle bitmap!\");\n      }\n    }\n  }\n\n  @Override void error() {\n    Target target = getTarget();\n    if (target != null) {\n      if (errorResId != 0) {\n        target.onBitmapFailed(picasso.context.getResources().getDrawable(errorResId));\n      } else {\n        target.onBitmapFailed(errorDrawable);\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "picasso/Transformation.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.graphics.Bitmap;\n\n/** Image transformation. */\npublic interface Transformation {\n  /**\n   * Transform the source bitmap into a new bitmap. If you create a new bitmap instance, you must\n   * call {@link android.graphics.Bitmap#recycle()} on {@code source}. You may return the original\n   * if no transformation is required.\n   */\n  Bitmap transform(Bitmap source);\n\n  /**\n   * Returns a unique key for the transformation, used for caching purposes. If the transformation\n   * has parameters (e.g. size, scale factor, etc) then these should be part of the key.\n   */\n  String key();\n}\n"
  },
  {
    "path": "picasso/UrlConnectionDownloader.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.net.http.HttpResponseCache;\nimport android.os.Build;\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\n\nimport static com.squareup.picasso.Utils.parseResponseSourceHeader;\n\n/**\n * A {@link com.squareup.picasso.Downloader} which uses {@link java.net.HttpURLConnection} to download images. A disk cache of 2%\n * of the total available space will be used (capped at 50MB) will automatically be installed in the\n * application's cache directory, when available.\n */\npublic class UrlConnectionDownloader implements Downloader {\n  static final String RESPONSE_SOURCE = \"X-Android-Response-Source\";\n\n  private static final Object lock = new Object();\n  static volatile Object cache;\n\n  private final Context context;\n\n  public UrlConnectionDownloader(Context context) {\n    this.context = context.getApplicationContext();\n  }\n\n  protected HttpURLConnection openConnection(Uri path) throws IOException {\n    HttpURLConnection connection = (HttpURLConnection) new URL(path.toString()).openConnection();\n    connection.setConnectTimeout(Utils.DEFAULT_CONNECT_TIMEOUT);\n    connection.setReadTimeout(Utils.DEFAULT_READ_TIMEOUT);\n    return connection;\n  }\n\n  @Override public Response load(Uri uri, boolean localCacheOnly) throws IOException {\n    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {\n      installCacheIfNeeded(context);\n    }\n\n    HttpURLConnection connection = openConnection(uri);\n    connection.setUseCaches(true);\n    if (localCacheOnly) {\n      connection.setRequestProperty(\"Cache-Control\", \"only-if-cached,max-age=\" + Integer.MAX_VALUE);\n    }\n\n    int responseCode = connection.getResponseCode();\n    if (responseCode >= 300) {\n      connection.disconnect();\n      throw new ResponseException(responseCode + \" \" + connection.getResponseMessage());\n    }\n\n    long contentLength = connection.getHeaderFieldInt(\"Content-Length\", -1);\n    boolean fromCache = parseResponseSourceHeader(connection.getHeaderField(RESPONSE_SOURCE));\n\n    return new Response(connection.getInputStream(), fromCache, contentLength);\n  }\n\n  private static void installCacheIfNeeded(Context context) {\n    // DCL + volatile should be safe after Java 5.\n    if (cache == null) {\n      try {\n        synchronized (lock) {\n          if (cache == null) {\n            cache = ResponseCacheIcs.install(context);\n          }\n        }\n      } catch (IOException ignored) {\n      }\n    }\n  }\n\n  private static class ResponseCacheIcs {\n    static Object install(Context context) throws IOException {\n      File cacheDir = Utils.createDefaultCacheDir(context);\n      HttpResponseCache cache = HttpResponseCache.getInstalled();\n      if (cache == null) {\n        long maxSize = Utils.calculateDiskCacheSize(cacheDir);\n        cache = HttpResponseCache.install(cacheDir, maxSize);\n      }\n      return cache;\n    }\n  }\n}\n"
  },
  {
    "path": "picasso/Utils.java",
    "content": "/*\n * Copyright (C) 2013 Square, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.squareup.picasso;\n\nimport android.annotation.TargetApi;\nimport android.app.ActivityManager;\nimport android.content.ContentResolver;\nimport android.content.Context;\nimport android.content.pm.PackageManager;\nimport android.content.res.Resources;\nimport android.graphics.Bitmap;\nimport android.os.Looper;\nimport android.os.Process;\nimport android.os.StatFs;\nimport android.provider.Settings;\nimport android.util.Log;\nimport java.io.ByteArrayOutputStream;\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.List;\nimport java.util.concurrent.ThreadFactory;\n\nimport static android.content.Context.ACTIVITY_SERVICE;\nimport static android.content.pm.ApplicationInfo.FLAG_LARGE_HEAP;\nimport static android.os.Build.VERSION.SDK_INT;\nimport static android.os.Build.VERSION_CODES.HONEYCOMB;\nimport static android.os.Build.VERSION_CODES.HONEYCOMB_MR1;\nimport static android.os.Process.THREAD_PRIORITY_BACKGROUND;\nimport static android.provider.Settings.System.AIRPLANE_MODE_ON;\nimport static com.squareup.picasso.Picasso.TAG;\nimport static java.lang.String.format;\n\nfinal class Utils {\n  static final String THREAD_PREFIX = \"Picasso-\";\n  static final String THREAD_IDLE_NAME = THREAD_PREFIX + \"Idle\";\n  static final int DEFAULT_READ_TIMEOUT = 20 * 1000; // 20s\n  static final int DEFAULT_CONNECT_TIMEOUT = 15 * 1000; // 15s\n  private static final String PICASSO_CACHE = \"picasso-cache\";\n  private static final int KEY_PADDING = 50; // Determined by exact science.\n  private static final int MIN_DISK_CACHE_SIZE = 5 * 1024 * 1024; // 5MB\n  private static final int MAX_DISK_CACHE_SIZE = 50 * 1024 * 1024; // 50MB\n\n  /** Thread confined to main thread for key creation. */\n  static final StringBuilder MAIN_THREAD_KEY_BUILDER = new StringBuilder();\n\n  /** Logging */\n  static final String OWNER_MAIN = \"Main\";\n  static final String OWNER_DISPATCHER = \"Dispatcher\";\n  static final String OWNER_HUNTER = \"Hunter\";\n  static final String VERB_CREATED = \"created\";\n  static final String VERB_CHANGED = \"changed\";\n  static final String VERB_IGNORED = \"ignored\";\n  static final String VERB_ENQUEUED = \"enqueued\";\n  static final String VERB_CANCELED = \"canceled\";\n  static final String VERB_BATCHED = \"batched\";\n  static final String VERB_RETRYING = \"retrying\";\n  static final String VERB_EXECUTING = \"executing\";\n  static final String VERB_DECODED = \"decoded\";\n  static final String VERB_TRANSFORMED = \"transformed\";\n  static final String VERB_JOINED = \"joined\";\n  static final String VERB_REMOVED = \"removed\";\n  static final String VERB_DELIVERED = \"delivered\";\n  static final String VERB_REPLAYING = \"replaying\";\n  static final String VERB_COMPLETED = \"completed\";\n  static final String VERB_ERRORED = \"errored\";\n\n  /* WebP file header\n     0                   1                   2                   3\n     0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n    |      'R'      |      'I'      |      'F'      |      'F'      |\n    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n    |                           File Size                           |\n    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n    |      'W'      |      'E'      |      'B'      |      'P'      |\n    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n  */\n  private static final int WEBP_FILE_HEADER_SIZE = 12;\n  private static final String WEBP_FILE_HEADER_RIFF = \"RIFF\";\n  private static final String WEBP_FILE_HEADER_WEBP = \"WEBP\";\n\n  private Utils() {\n    // No instances.\n  }\n\n  static int getBitmapBytes(Bitmap bitmap) {\n    int result;\n    if (SDK_INT >= HONEYCOMB_MR1) {\n      result = BitmapHoneycombMR1.getByteCount(bitmap);\n    } else {\n      result = bitmap.getRowBytes() * bitmap.getHeight();\n    }\n    if (result < 0) {\n      throw new IllegalStateException(\"Negative size: \" + bitmap);\n    }\n    return result;\n  }\n\n  static void checkNotMain() {\n    if (isMain()) {\n      throw new IllegalStateException(\"Method call should not happen from the main thread.\");\n    }\n  }\n\n  static void checkMain() {\n    if (!isMain()) {\n      throw new IllegalStateException(\"Method call should happen from the main thread.\");\n    }\n  }\n\n  static boolean isMain() {\n    return Looper.getMainLooper().getThread() == Thread.currentThread();\n  }\n\n  static String getLogIdsForHunter(BitmapHunter hunter) {\n    return getLogIdsForHunter(hunter, \"\");\n  }\n\n  static String getLogIdsForHunter(BitmapHunter hunter, String prefix) {\n    StringBuilder builder = new StringBuilder(prefix);\n    Action action = hunter.getAction();\n    if (action != null) {\n      builder.append(action.request.logId());\n    }\n    List<Action> actions = hunter.getActions();\n    if (actions != null) {\n      for (int i = 0, count = actions.size(); i < count; i++) {\n        if (i > 0 || action != null) builder.append(\", \");\n        builder.append(actions.get(i).request.logId());\n      }\n    }\n    return builder.toString();\n  }\n\n  static void log(String owner, String verb, String logId) {\n    log(owner, verb, logId, \"\");\n  }\n\n  static void log(String owner, String verb, String logId, String extras) {\n    Log.d(TAG, format(\"%1$-11s %2$-12s %3$s %4$s\", owner, verb, logId, extras));\n  }\n\n  static String createKey(Request data) {\n    String result = createKey(data, MAIN_THREAD_KEY_BUILDER);\n    MAIN_THREAD_KEY_BUILDER.setLength(0);\n    return result;\n  }\n\n  static String createKey(Request data, StringBuilder builder) {\n    if (data.uri != null) {\n      String path = data.uri.toString();\n      builder.ensureCapacity(path.length() + KEY_PADDING);\n      builder.append(path);\n    } else {\n      builder.ensureCapacity(KEY_PADDING);\n      builder.append(data.resourceId);\n    }\n    builder.append('\\n');\n\n    if (data.rotationDegrees != 0) {\n      builder.append(\"rotation:\").append(data.rotationDegrees);\n      if (data.hasRotationPivot) {\n        builder.append('@').append(data.rotationPivotX).append('x').append(data.rotationPivotY);\n      }\n      builder.append('\\n');\n    }\n    if (data.targetWidth != 0) {\n      builder.append(\"resize:\").append(data.targetWidth).append('x').append(data.targetHeight);\n      builder.append('\\n');\n    }\n    if (data.centerCrop) {\n      builder.append(\"centerCrop\\n\");\n    } else if (data.centerInside) {\n      builder.append(\"centerInside\\n\");\n    }\n\n    if (data.transformations != null) {\n      //noinspection ForLoopReplaceableByForEach\n      for (int i = 0, count = data.transformations.size(); i < count; i++) {\n        builder.append(data.transformations.get(i).key());\n        builder.append('\\n');\n      }\n    }\n\n    return builder.toString();\n  }\n\n  static void closeQuietly(InputStream is) {\n    if (is == null) return;\n    try {\n      is.close();\n    } catch (IOException ignored) {\n    }\n  }\n\n  /** Returns {@code true} if header indicates the response body was loaded from the disk cache. */\n  static boolean parseResponseSourceHeader(String header) {\n    if (header == null) {\n      return false;\n    }\n    String[] parts = header.split(\" \", 2);\n    if (\"CACHE\".equals(parts[0])) {\n      return true;\n    }\n    if (parts.length == 1) {\n      return false;\n    }\n    try {\n      return \"CONDITIONAL_CACHE\".equals(parts[0]) && Integer.parseInt(parts[1]) == 304;\n    } catch (NumberFormatException e) {\n      return false;\n    }\n  }\n\n  static Downloader createDefaultDownloader(Context context) {\n    boolean okUrlFactory = false;\n    try {\n      Class.forName(\"com.squareup.okhttp.OkUrlFactory\");\n      okUrlFactory = true;\n    } catch (ClassNotFoundException ignored) {\n    }\n\n    boolean okHttpClient = false;\n    try {\n      Class.forName(\"com.squareup.okhttp.OkHttpClient\");\n      okHttpClient = true;\n    } catch (ClassNotFoundException ignored) {\n    }\n\n    if (okHttpClient != okUrlFactory) {\n      throw new RuntimeException(\"\"\n          + \"Picasso detected an unsupported OkHttp on the classpath.\\n\"\n          + \"To use OkHttp with this version of Picasso, you'll need:\\n\"\n          + \"1. com.squareup.okhttp:okhttp:1.6.0 (or newer)\\n\"\n          + \"2. com.squareup.okhttp:okhttp-urlconnection:1.6.0 (or newer)\\n\"\n          + \"Note that OkHttp 2.0.0+ is supported!\");\n    }\n\n    return okHttpClient\n        ? OkHttpLoaderCreator.create(context)\n        : new UrlConnectionDownloader(context);\n  }\n\n  static File createDefaultCacheDir(Context context) {\n    File cache = new File(context.getApplicationContext().getCacheDir(), PICASSO_CACHE);\n    if (!cache.exists()) {\n      //noinspection ResultOfMethodCallIgnored\n      cache.mkdirs();\n    }\n    return cache;\n  }\n\n  static long calculateDiskCacheSize(File dir) {\n    long size = MIN_DISK_CACHE_SIZE;\n\n    try {\n      StatFs statFs = new StatFs(dir.getAbsolutePath());\n      long available = ((long) statFs.getBlockCount()) * statFs.getBlockSize();\n      // Target 2% of the total space.\n      size = available / 50;\n    } catch (IllegalArgumentException ignored) {\n    }\n\n    // Bound inside min/max size for disk cache.\n    return Math.max(Math.min(size, MAX_DISK_CACHE_SIZE), MIN_DISK_CACHE_SIZE);\n  }\n\n  static int calculateMemoryCacheSize(Context context) {\n    ActivityManager am = getService(context, ACTIVITY_SERVICE);\n    boolean largeHeap = (context.getApplicationInfo().flags & FLAG_LARGE_HEAP) != 0;\n    int memoryClass = am.getMemoryClass();\n    if (largeHeap && SDK_INT >= HONEYCOMB) {\n      memoryClass = ActivityManagerHoneycomb.getLargeMemoryClass(am);\n    }\n    // Target ~15% of the available heap.\n    return 1024 * 1024 * memoryClass / 7;\n  }\n\n  static boolean isAirplaneModeOn(Context context) {\n    ContentResolver contentResolver = context.getContentResolver();\n    return Settings.System.getInt(contentResolver, AIRPLANE_MODE_ON, 0) != 0;\n  }\n\n  @SuppressWarnings(\"unchecked\")\n  static <T> T getService(Context context, String service) {\n    return (T) context.getSystemService(service);\n  }\n\n  static boolean hasPermission(Context context, String permission) {\n    return context.checkCallingOrSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;\n  }\n\n  static byte[] toByteArray(InputStream input) throws IOException {\n    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();\n    byte[] buffer = new byte[1024 * 4];\n    int n;\n    while (-1 != (n = input.read(buffer))) {\n      byteArrayOutputStream.write(buffer, 0, n);\n    }\n    return byteArrayOutputStream.toByteArray();\n  }\n\n  static boolean isWebPFile(InputStream stream) throws IOException {\n    byte[] fileHeaderBytes = new byte[WEBP_FILE_HEADER_SIZE];\n    boolean isWebPFile = false;\n    if (stream.read(fileHeaderBytes, 0, WEBP_FILE_HEADER_SIZE) == WEBP_FILE_HEADER_SIZE) {\n      // If a file's header starts with RIFF and end with WEBP, the file is a WebP file\n      isWebPFile = WEBP_FILE_HEADER_RIFF.equals(new String(fileHeaderBytes, 0, 4, \"US-ASCII\"))\n          && WEBP_FILE_HEADER_WEBP.equals(new String(fileHeaderBytes, 8, 4, \"US-ASCII\"));\n    }\n    return isWebPFile;\n  }\n\n  static int getResourceId(Resources resources, Request data) throws FileNotFoundException {\n    if (data.resourceId != 0 || data.uri == null) {\n      return data.resourceId;\n    }\n\n    String pkg = data.uri.getAuthority();\n    if (pkg == null) throw new FileNotFoundException(\"No package provided: \" + data.uri);\n\n    int id;\n    List<String> segments = data.uri.getPathSegments();\n    if (segments == null || segments.isEmpty()) {\n      throw new FileNotFoundException(\"No path segments: \" + data.uri);\n    } else if (segments.size() == 1) {\n      try {\n        id = Integer.parseInt(segments.get(0));\n      } catch (NumberFormatException e) {\n        throw new FileNotFoundException(\"Last path segment is not a resource ID: \" + data.uri);\n      }\n    } else if (segments.size() == 2) {\n      String type = segments.get(0);\n      String name = segments.get(1);\n\n      id = resources.getIdentifier(name, type, pkg);\n    } else {\n      throw new FileNotFoundException(\"More than two path segments: \" + data.uri);\n    }\n    return id;\n  }\n\n  static Resources getResources(Context context, Request data) throws FileNotFoundException {\n    if (data.resourceId != 0 || data.uri == null) {\n      return context.getResources();\n    }\n\n    String pkg = data.uri.getAuthority();\n    if (pkg == null) throw new FileNotFoundException(\"No package provided: \" + data.uri);\n    try {\n      PackageManager pm = context.getPackageManager();\n      return pm.getResourcesForApplication(pkg);\n    } catch (PackageManager.NameNotFoundException e) {\n      throw new FileNotFoundException(\"Unable to obtain resources for package: \" + data.uri);\n    }\n  }\n\n  @TargetApi(HONEYCOMB)\n  private static class ActivityManagerHoneycomb {\n    static int getLargeMemoryClass(ActivityManager activityManager) {\n      return activityManager.getLargeMemoryClass();\n    }\n  }\n\n  static class PicassoThreadFactory implements ThreadFactory {\n    @SuppressWarnings(\"NullableProblems\")\n    public Thread newThread(Runnable r) {\n      return new PicassoThread(r);\n    }\n  }\n\n  private static class PicassoThread extends Thread {\n    public PicassoThread(Runnable r) {\n      super(r);\n    }\n\n    @Override public void run() {\n      Process.setThreadPriority(THREAD_PRIORITY_BACKGROUND);\n      super.run();\n    }\n  }\n\n  @TargetApi(HONEYCOMB_MR1)\n  private static class BitmapHoneycombMR1 {\n    static int getByteCount(Bitmap bitmap) {\n      return bitmap.getByteCount();\n    }\n  }\n\n  private static class OkHttpLoaderCreator {\n    static Downloader create(Context context) {\n      return new OkHttpDownloader(context);\n    }\n  }\n}\n"
  },
  {
    "path": "settings.gradle",
    "content": "include ':app'\n"
  }
]