Full Code of Nilhcem/hosts-editor-android for AI

master 837e40f9958c cached
59 files
125.4 KB
30.6k tokens
205 symbols
1 requests
Download .txt
Repository: Nilhcem/hosts-editor-android
Branch: master
Commit: 837e40f9958c
Files: 59
Total size: 125.4 KB

Directory structure:
gitextract_bdv5001x/

├── .gitignore
├── LICENSE.txt
├── README.md
├── app/
│   ├── build.gradle
│   ├── libs/
│   │   └── RootTools-4.2.jar
│   └── src/
│       └── main/
│           ├── AndroidManifest.xml
│           ├── java/
│           │   └── com/
│           │       └── nilhcem/
│           │           └── hostseditor/
│           │               ├── HostsEditorApplication.java
│           │               ├── core/
│           │               │   ├── Host.java
│           │               │   ├── HostsManager.java
│           │               │   ├── dagger/
│           │               │   │   ├── HostsEditorComponent.java
│           │               │   │   └── HostsEditorModule.java
│           │               │   ├── log/
│           │               │   │   └── ReleaseTree.java
│           │               │   └── util/
│           │               │       ├── Compatibility.java
│           │               │       ├── InetAddresses.java
│           │               │       └── ThreadPreconditions.java
│           │               ├── event/
│           │               │   ├── CreatedHostEvent.java
│           │               │   ├── LoadingEvent.java
│           │               │   ├── RefreshHostsEvent.java
│           │               │   ├── StartAddEditActivityEvent.java
│           │               │   └── TaskCompletedEvent.java
│           │               ├── task/
│           │               │   ├── AddEditHostAsync.java
│           │               │   ├── GenericTaskAsync.java
│           │               │   ├── ListHostsAsync.java
│           │               │   ├── RemoveHostsAsync.java
│           │               │   └── ToggleHostsAsync.java
│           │               └── ui/
│           │                   ├── BaseActivity.java
│           │                   ├── BaseFragment.java
│           │                   ├── about/
│           │                   │   └── AboutDialogFragment.java
│           │                   ├── addedit/
│           │                   │   ├── AddEditHostActivity.java
│           │                   │   └── AddEditHostFragment.java
│           │                   ├── list/
│           │                   │   ├── ListHostsActivity.java
│           │                   │   ├── ListHostsAdapter.java
│           │                   │   ├── ListHostsFragment.java
│           │                   │   └── ListHostsSearchFilter.java
│           │                   └── widget/
│           │                       ├── CheckableHostItem.java
│           │                       ├── InertCheckBox.java
│           │                       ├── TypefacedButton.java
│           │                       └── TypefacedTextView.java
│           └── res/
│               ├── layout/
│               │   ├── about_dialog.xml
│               │   ├── add_edit_host_layout.xml
│               │   ├── checkable_host_item.xml
│               │   ├── list_hosts_empty.xml
│               │   ├── list_hosts_fragment.xml
│               │   └── list_hosts_layout.xml
│               ├── menu/
│               │   ├── add_edit_menu.xml
│               │   ├── list_contextual_actions.xml
│               │   └── list_menu.xml
│               ├── values/
│               │   ├── attrs.xml
│               │   ├── colors.xml
│               │   ├── dimens.xml
│               │   ├── strings.xml
│               │   └── styles.xml
│               └── values-sw720dp-land/
│                   └── dimens.xml
├── build.gradle
├── gradle/
│   └── wrapper/
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
# Temporary files
*~
\#*
tmp/

# Build directory
build/

# Eclipse files
.metadata
.pmd
.apt_generated/

# IntelliJ files
.idea
*.iml

# Android built application files
*.apk
*.ap_

# Files for the dex VM
*.dex

# Java class files
*.class

# Generated files
bin/
gen/

# Local configuration file (sdk path, etc)
local.properties

# OSX files
.DS_Store

# Windows files
Thumbs.db

# Gradle
.gradle


================================================
FILE: LICENSE.txt
================================================

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.


================================================
FILE: README.md
================================================
# Hosts Editor for Android

This repository contains the source code for the Hosts-editor Android app.

It is available from [Google Play][] and [F-Droid][].

![Hosts Editor for Android screenshots][]

This application, **for root devices only**, lets you modify easily your Android `/etc/hosts` file.

You might need to reboot to clear your DNS cache after any change.


## Features

* Android 2.2 and above
* Insert, Remove, Toggle (comment/uncomment) and Modify host entries
* Holo theme
* Fast search engine
* 100% free/libre, gratis, no ads


## Building the app

The Android SDK for API level 19 is required to build the app. Then launch:

    ./gradlew clean build


## Acknowledgements

This project uses many great open-source libraries, such as:

* [ActionBarSherlock][]
* [Butterknife][]
* [Dagger][]
* [Commons IO][]
* [Otto][]
* [RootTools][]


## License

<pre>

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
</pre>


[Google Play]: https://play.google.com/store/apps/details?id=com.nilhcem.hostseditor
[F-Droid]: https://f-droid.org/repository/browse/?fdid=com.nilhcem.hostseditor
[Hosts Editor for Android screenshots]: https://raw.githubusercontent.com/Nilhcem/hosts-editor-android/master/screenshot.png
[ActionBarSherlock]: http://actionbarsherlock.com/
[Butterknife]: http://jakewharton.github.com/butterknife/
[Dagger]: http://square.github.com/dagger/
[Commons IO]: http://commons.apache.org/proper/commons-io/
[Otto]: http://square.github.com/otto/
[RootTools]: https://code.google.com/p/roottools/


================================================
FILE: app/build.gradle
================================================
apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'

android {
    compileSdkVersion 22
    buildToolsVersion '22.0.1'

    defaultConfig {
        applicationId 'com.nilhcem.hostseditor'
        minSdkVersion 8
        targetSdkVersion 22
        versionCode 5
        versionName '1.4'
        resConfig 'en'
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }

    buildTypes {
        release {
            minifyEnabled false
        }
    }

    packagingOptions {
        exclude 'META-INF/LICENSE.txt'
    }

    lintOptions {
        abortOnError false
    }
}

dependencies {
    // Commons IO
    compile 'commons-io:commons-io:2.4'

    // Dagger
    compile 'com.google.dagger:dagger:2.0.1'
    apt 'com.google.dagger:dagger-compiler:2.0.1'
    compile 'javax.annotation:javax.annotation-api:1.2'

    // ActionBarSherlock + Support library
    compile 'com.actionbarsherlock:actionbarsherlock:4.4.0@aar'
    compile 'com.android.support:support-v4:22.2.0'

    // Butterknife
    compile 'com.jakewharton:butterknife:7.0.1'

    // Logging
    compile 'com.jakewharton.timber:timber:3.1.0'

    // Otto
    compile 'com.squareup:otto:1.3.8'

    // Other jars (RootTools)
    compile fileTree(dir: 'libs', include: '*.jar')
}


================================================
FILE: app/src/main/AndroidManifest.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.nilhcem.hostseditor"
    android:installLocation="preferExternal">

    <uses-permission android:name="android.permission.ACCESS_SUPERUSER" />

    <application
        android:name="com.nilhcem.hostseditor.HostsEditorApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:theme="@style/AppTheme">

        <activity android:name="com.nilhcem.hostseditor.ui.list.ListHostsActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name="com.nilhcem.hostseditor.ui.addedit.AddEditHostActivity" />
    </application>
</manifest>


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/HostsEditorApplication.java
================================================
package com.nilhcem.hostseditor;

import android.app.Application;
import android.content.Context;

import com.nilhcem.hostseditor.core.dagger.DaggerHostsEditorComponent;
import com.nilhcem.hostseditor.core.dagger.HostsEditorComponent;
import com.nilhcem.hostseditor.core.dagger.HostsEditorModule;
import com.nilhcem.hostseditor.core.log.ReleaseTree;

import timber.log.Timber;

public class HostsEditorApplication extends Application {

    private HostsEditorComponent mComponent;

    public static HostsEditorApplication get(Context context) {
        return (HostsEditorApplication) context.getApplicationContext();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        initLogger();
        initGraph();
    }

    public HostsEditorComponent component() {
        return mComponent;
    }

    private void initLogger() {
        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
        } else {
            Timber.plant(new ReleaseTree());
        }
    }

    private void initGraph() {
        mComponent = DaggerHostsEditorComponent.builder()
                .hostsEditorModule(new HostsEditorModule())
                .build();
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/core/Host.java
================================================
package com.nilhcem.hostseditor.core;

import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;

import com.nilhcem.hostseditor.core.util.InetAddresses;

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

public class Host implements Parcelable {

    public static final String STR_COMMENT = "#";
    private static final String STR_SEPARATOR = " ";
    private static final String HOST_PATTERN_STR = "^\\s*(" + STR_COMMENT + "?)\\s*(\\S*)\\s*([^" + STR_COMMENT + "]*)" + STR_COMMENT + "?(.*)$";
    private static final Pattern HOST_PATTERN = Pattern.compile(HOST_PATTERN_STR);

    private String mIp;
    private String mHostName;
    private String mComment; // When host entry has a comment at the end, eg: "::1 localhost #myhome"
    private boolean mIsCommented; // When host entry starts with #, eg: "#::1 localhost"
    private boolean mIsValid; // When host entry has a valid IP + hostname

    public Host(String ip, String hostName, String comment, boolean isCommented, boolean isValid) {
        mIp = ip;
        mHostName = hostName;
        mComment = comment;
        mIsCommented = isCommented;
        mIsValid = isValid;
    }

    public void merge(Host src) {
        mIp = src.getIp();
        mHostName = src.getHostName();
        mComment = src.getComment();
        mIsCommented = src.isCommented();
        mIsValid = src.isValid();
    }

    public String getIp() {
        return mIp;
    }

    public String getHostName() {
        return mHostName;
    }

    public String getComment() {
        return mComment;
    }

    public boolean isValid() {
        return mIsValid;
    }

    public boolean isCommented() {
        return mIsCommented;
    }

    public void toggleComment() {
        mIsCommented = !mIsCommented;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();

        if (mIsCommented) {
            sb.append(STR_COMMENT);
        }
        if (mIp != null) {
            sb.append(mIp).append(STR_SEPARATOR);
        }
        if (mHostName != null) {
            sb.append(mHostName);
        }
        if (!TextUtils.isEmpty(mComment)) {
            sb.append(STR_SEPARATOR).append(STR_COMMENT).append(mComment);
        }
        return sb.toString();
    }

    public static Host fromString(String line) {
        Matcher matcher = HOST_PATTERN.matcher(line);
        String ip = null;
        String hostname = null;
        String comment = null;
        boolean isCommented = false;
        boolean isValid = false;

        if (matcher.find()) {
            isCommented = !TextUtils.isEmpty(matcher.group(1));
            ip = matcher.group(2);
            hostname = matcher.group(3).trim();
            comment = matcher.group(4).trim();
            if (TextUtils.isEmpty(comment)) {
                comment = null;
            }

            isValid = !TextUtils.isEmpty(ip) && !TextUtils.isEmpty(hostname)
                    && InetAddresses.isInetAddress(ip);
        }
        return new Host(ip, hostname, comment, isCommented, isValid);
    }

    public static final Parcelable.Creator<Host> CREATOR = new Parcelable.Creator<Host>() {

        @Override
        public Host createFromParcel(Parcel source) {
            return new Host(source);
        }

        @Override
        public Host[] newArray(int size) {
            return new Host[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(mIp);
        dest.writeString(mHostName);
        dest.writeString(mComment);
        dest.writeByte((byte) (mIsCommented ? 1 : 0));
        dest.writeByte((byte) (mIsValid ? 1 : 0));
    }

    private Host(Parcel in) {
        mIp = in.readString();
        mHostName = in.readString();
        mComment = in.readString();
        mIsCommented = in.readByte() == 1;
        mIsValid = in.readByte() == 1;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((mComment == null) ? 0 : mComment.hashCode());
        result = prime * result + ((mHostName == null) ? 0 : mHostName.hashCode());
        result = prime * result + ((mIp == null) ? 0 : mIp.hashCode());
        result = prime * result + (mIsCommented ? 1231 : 1237);
        result = prime * result + (mIsValid ? 1231 : 1237);
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        Host other = (Host) obj;
        if (mComment == null) {
            if (other.mComment != null) {
                return false;
            }
        } else if (!mComment.equals(other.mComment)) {
            return false;
        }
        if (mHostName == null) {
            if (other.mHostName != null) {
                return false;
            }
        } else if (!mHostName.equals(other.mHostName)) {
            return false;
        }
        if (mIp == null) {
            if (other.mIp != null) {
                return false;
            }
        } else if (!mIp.equals(other.mIp)) {
            return false;
        }
        if (mIsCommented != other.mIsCommented) {
            return false;
        }
        if (mIsValid != other.mIsValid) {
            return false;
        }
        return true;
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/core/HostsManager.java
================================================
package com.nilhcem.hostseditor.core;

import android.content.Context;

import com.stericson.RootShell.RootShell;
import com.stericson.RootShell.exceptions.RootDeniedException;
import com.stericson.RootShell.execution.Command;
import com.stericson.RootTools.RootTools;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeoutException;

import javax.inject.Inject;
import javax.inject.Singleton;

import timber.log.Timber;

@Singleton
public class HostsManager {

    private static final String UTF_8 = "UTF-8";
    private static final String HOSTS_FILE_NAME = "hosts";
    private static final String HOSTS_FILE_PATH = "/system/etc/" + HOSTS_FILE_NAME;

    private static final String LINE_SEPARATOR = System.getProperty("line.separator", "\n");
    private static final String MOUNT_TYPE_RO = "ro";
    private static final String MOUNT_TYPE_RW = "rw";
    private static final String COMMAND_RM = "rm -f";
    private static final String COMMAND_CHOWN = "chown 0:0";
    private static final String COMMAND_CHMOD_644 = "chmod 644";

    // Do not access this field directly even in the same class, use getAllHosts() instead.
    private List<Host> mHosts;

    @Inject
    public HostsManager() {
    }

    /**
     * Gets all host entries from hosts file.
     * <p><b>Must be in an async call.</b></p>
     *
     * @param forceRefresh if we want to force using the hosts file (not the cache)
     * @return a list of host entries
     */
    public synchronized List<Host> getHosts(boolean forceRefresh) {
        if (mHosts == null || forceRefresh) {
            mHosts = Collections.synchronizedList(new ArrayList<Host>());

            LineIterator it = null;
            try {
                it = FileUtils.lineIterator(new File(HOSTS_FILE_PATH), UTF_8);
                while (it.hasNext()) {
                    Host host = Host.fromString(it.nextLine());
                    if (host != null) {
                        mHosts.add(host);
                    }
                }
            } catch (IOException e) {
                Timber.e(e, "I/O error while opening hosts file");
            } finally {
                if (it != null) {
                    LineIterator.closeQuietly(it);
                }
            }
        }
        return mHosts;
    }

    /**
     * Saves new hosts file and creates a backup of previous file.
     * <p><b>Must be in an async call.</b></p>
     *
     * @param appContext application context
     * @return {@code true} if everything was working as expected, or {@code false} otherwise
     */
    public synchronized boolean saveHosts(Context appContext) {
        if (!RootTools.isAccessGiven()) {
            Timber.w("Can't get root access");
            return false;
        }

        // Step 1: Create temporary hosts file in /data/data/project_package/files/hosts
        if (!createTempHostsFile(appContext)) {
            Timber.w("Can't create temporary hosts file");
            return false;
        }

        String tmpFile = String.format(Locale.US, "%s/%s", appContext.getFilesDir().getAbsolutePath(), HOSTS_FILE_NAME);
        String backupFile = String.format(Locale.US, "%s.bak", tmpFile);

        // Step 2: Get canonical path for /etc/hosts (it could be a symbolic link)
        String hostsFilePath = HOSTS_FILE_PATH;
        File hostsFile = new File(HOSTS_FILE_PATH);
        if (hostsFile.exists()) {
            try {
                if (FileUtils.isSymlink(hostsFile)) {
                    hostsFilePath = hostsFile.getCanonicalPath();
                }
            } catch (IOException e1) {
                Timber.e(e1, "Can't find hosts file");
            }
        } else {
            Timber.w("Hosts file was not found in filesystem");
        }

        try {
            // Step 3: Create backup of current hosts file (if any)
            RootTools.remount(hostsFilePath, MOUNT_TYPE_RW);
            runRootCommand(COMMAND_RM, backupFile);
            RootTools.copyFile(hostsFilePath, backupFile, false, true);

            // Step 4: Replace hosts file with generated file
            runRootCommand(COMMAND_RM, hostsFilePath);
            RootTools.copyFile(tmpFile, hostsFilePath, false, true);

            // Step 5: Give proper rights
            runRootCommand(COMMAND_CHOWN, hostsFilePath);
            runRootCommand(COMMAND_CHMOD_644, hostsFilePath);

            // Step 6: Delete local file
            appContext.deleteFile(HOSTS_FILE_NAME);
        } catch (Exception e) {
            Timber.e(e, "Failed running root command");
            return false;
        } finally {
            RootTools.remount(hostsFilePath, MOUNT_TYPE_RO);
        }
        return true;
    }

    /**
     * Returns a list of hosts matching the constraint parameter.
     */
    public List<Host> filterHosts(CharSequence constraint) {
        List<Host> all = getHosts(false);
        List<Host> hosts = new ArrayList<>();

        for (Host host : all) {
            if (host.isValid()) {
                if (host.getIp().contains(constraint)
                        || host.getHostName().contains(constraint)
                        || (host.getComment() != null && host.getComment().contains(constraint))) {
                    hosts.add(host);
                }
            }
        }
        return hosts;
    }

    /**
     * Creates a temporary hosts file in {@code /data/data/project_package/files/hosts}.
     * <p><b>Must be in an async call.</b></p>
     *
     * @param appContext application context
     * @return {@code true} if the temp file was created, or {@code false} otherwise
     */
    private boolean createTempHostsFile(Context appContext) {
        OutputStreamWriter writer = null;
        try {
            FileOutputStream out = appContext.openFileOutput(HOSTS_FILE_NAME, Context.MODE_PRIVATE);
            writer = new OutputStreamWriter(out);

            for (Host host : getHosts(false)) {
                writer.append(host.toString()).append(LINE_SEPARATOR);
            }
            writer.flush();
        } catch (IOException e) {
            Timber.e(e, "Error creating temporary hosts file");
            return false;
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    Timber.e(e, "Error while closing writer");
                }
            }
        }
        return true;
    }

    /**
     * Executes a single argument root command.
     * <p><b>Must be in an async call.</b></p>
     *
     * @param command   a command, ie {@code "rm -f"}, {@code "chmod 644"}...
     * @param uniqueArg the unique argument for the command, usually the file name
     */
    private void runRootCommand(String command, String uniqueArg) throws IOException, TimeoutException, RootDeniedException {
        Command cmd = new Command(0, false, String.format(Locale.US, "%s %s", command, uniqueArg));
        RootShell.getShell(true).add(cmd);
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/core/dagger/HostsEditorComponent.java
================================================
package com.nilhcem.hostseditor.core.dagger;

import com.nilhcem.hostseditor.task.GenericTaskAsync;
import com.nilhcem.hostseditor.task.ListHostsAsync;
import com.nilhcem.hostseditor.ui.BaseActivity;
import com.nilhcem.hostseditor.ui.addedit.AddEditHostFragment;
import com.nilhcem.hostseditor.ui.list.ListHostsFragment;

import javax.inject.Singleton;

import dagger.Component;

@Singleton
@Component(
        modules = {
                HostsEditorModule.class
        }
)
public interface HostsEditorComponent {

    void inject(BaseActivity activity);

    void inject(GenericTaskAsync async);

    void inject(AddEditHostFragment fragment);

    void inject(ListHostsAsync async);

    void inject(ListHostsFragment fragment);
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/core/dagger/HostsEditorModule.java
================================================
package com.nilhcem.hostseditor.core.dagger;

import com.squareup.otto.Bus;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;

@Module
public class HostsEditorModule {

    @Provides @Singleton Bus provideBus() {
        return new Bus();
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/core/log/ReleaseTree.java
================================================
package com.nilhcem.hostseditor.core.log;

import android.util.Log;

import timber.log.Timber;

public class ReleaseTree extends Timber.Tree {

    @Override
    protected void log(int priority, String tag, String message, Throwable t) {
        // Only log ERROR, and WTF.
        if (priority > Log.WARN) {
            Log.println(priority, tag, message);
        }
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/core/util/Compatibility.java
================================================
package com.nilhcem.hostseditor.core.util;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Point;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;

public class Compatibility {

    private Compatibility() {
        throw new UnsupportedOperationException();
    }

    /**
     * Checks if current SDK is compatible with the desired API level.
     *
     * @param apiLevel the required API level.
     * @return {@code true} if current OS is compatible.
     */
    private static boolean isCompatible(int apiLevel) {
        return android.os.Build.VERSION.SDK_INT >= apiLevel;
    }

    @SuppressWarnings("deprecation")
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    public static Point getScreenDimensions(Context context) {
        Point size = new Point();

        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        if (Compatibility.isCompatible(Build.VERSION_CODES.HONEYCOMB_MR2)) {
            display.getSize(size);
        } else {
            size.set(display.getWidth(), display.getHeight());
        }
        return size;
    }

    /**
     * This method converts dp unit to equivalent device specific value in pixels.
     *
     * @param dp      A value in dp (Device independent pixels) unit. Which we need to convert into pixels.
     * @param context Context to get resources and device specific display metrics.
     * @return A float value to represent Pixels equivalent to dp according to device.
     */
    public static float convertDpToPixel(float dp, Context context) {
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        return dp * (metrics.densityDpi / 160f);
    }

    public static int convertDpToIntPixel(float dp, Context context) {
        return Math.round(convertDpToPixel(dp, context));
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/core/util/InetAddresses.java
================================================
/*
 * Copyright (C) 2008 The Guava Authors
 *
 * NOTICE: THIS FILE WAS MODIFIED (removed all not required for the project)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.nilhcem.hostseditor.core.util;

import java.net.InetAddress;
import java.nio.ByteBuffer;

/**
 * Static utility methods pertaining to {@link InetAddress} instances.
 */
public final class InetAddresses {

    private static final int IPV4_PART_COUNT = 4;
    private static final int IPV6_PART_COUNT = 8;

    private InetAddresses() {
    }

    /**
     * Returns {@code true} if the supplied string is a valid IP string literal,
     * {@code false} otherwise.
     *
     * @param ipString {@code String} to evaluated as an IP string literal
     * @return {@code true} if the argument is a valid IP string literal
     */
    public static boolean isInetAddress(String ipString) {
        return ipStringToBytes(ipString) != null;
    }

    private static byte[] ipStringToBytes(String ipString) {
        // Make a first pass to categorize the characters in this string.
        boolean hasColon = false;
        boolean hasDot = false;
        for (int i = 0; i < ipString.length(); i++) {
            char c = ipString.charAt(i);
            if (c == '.') {
                hasDot = true;
            } else if (c == ':') {
                if (hasDot) {
                    return null; // Colons must not appear after dots.
                }
                hasColon = true;
            } else if (Character.digit(c, 16) == -1) {
                return null; // Everything else must be a decimal or hex digit.
            }
        }

        // Now decide which address family to parse.
        if (hasColon) {
            if (hasDot) {
                ipString = convertDottedQuadToHex(ipString);
                if (ipString == null) {
                    return null;
                }
            }
            return textToNumericFormatV6(ipString);
        } else if (hasDot) {
            return textToNumericFormatV4(ipString);
        }
        return null;
    }

    private static byte[] textToNumericFormatV4(String ipString) {
        String[] address = ipString.split("\\.", IPV4_PART_COUNT + 1);
        if (address.length != IPV4_PART_COUNT) {
            return null;
        }

        byte[] bytes = new byte[IPV4_PART_COUNT];
        try {
            for (int i = 0; i < bytes.length; i++) {
                bytes[i] = parseOctet(address[i]);
            }
        } catch (NumberFormatException ex) {
            return null;
        }

        return bytes;
    }

    private static byte[] textToNumericFormatV6(String ipString) {
        // An address can have [2..8] colons, and N colons make N+1 parts.
        String[] parts = ipString.split(":", IPV6_PART_COUNT + 2);
        if (parts.length < 3 || parts.length > IPV6_PART_COUNT + 1) {
            return null;
        }

        // Disregarding the endpoints, find "::" with nothing in between.
        // This indicates that a run of zeroes has been skipped.
        int skipIndex = -1;
        for (int i = 1; i < parts.length - 1; i++) {
            if (parts[i].length() == 0) {
                if (skipIndex >= 0) {
                    return null; // Can't have more than one ::
                }
                skipIndex = i;
            }
        }

        int partsHi; // Number of parts to copy from above/before the "::"
        int partsLo; // Number of parts to copy from below/after the "::"
        if (skipIndex >= 0) {
            // If we found a "::", then check if it also covers the endpoints.
            partsHi = skipIndex;
            partsLo = parts.length - skipIndex - 1;
            if (parts[0].length() == 0 && --partsHi != 0) {
                return null; // ^: requires ^::
            }
            if (parts[parts.length - 1].length() == 0 && --partsLo != 0) {
                return null; // :$ requires ::$
            }
        } else {
            // Otherwise, allocate the entire address to partsHi. The endpoints
            // could still be empty, but parseHextet() will check for that.
            partsHi = parts.length;
            partsLo = 0;
        }

        // If we found a ::, then we must have skipped at least one part.
        // Otherwise, we must have exactly the right number of parts.
        int partsSkipped = IPV6_PART_COUNT - (partsHi + partsLo);
        if (!(skipIndex >= 0 ? partsSkipped >= 1 : partsSkipped == 0)) {
            return null;
        }

        // Now parse the hextets into a byte array.
        ByteBuffer rawBytes = ByteBuffer.allocate(2 * IPV6_PART_COUNT);
        try {
            for (int i = 0; i < partsHi; i++) {
                rawBytes.putShort(parseHextet(parts[i]));
            }
            for (int i = 0; i < partsSkipped; i++) {
                rawBytes.putShort((short) 0);
            }
            for (int i = partsLo; i > 0; i--) {
                rawBytes.putShort(parseHextet(parts[parts.length - i]));
            }
        } catch (NumberFormatException ex) {
            return null;
        }
        return rawBytes.array();
    }

    private static String convertDottedQuadToHex(String ipString) {
        int lastColon = ipString.lastIndexOf(':');
        String initialPart = ipString.substring(0, lastColon + 1);
        String dottedQuad = ipString.substring(lastColon + 1);
        byte[] quad = textToNumericFormatV4(dottedQuad);
        if (quad == null) {
            return null;
        }
        String penultimate = Integer.toHexString(((quad[0] & 0xff) << 8)
                | (quad[1] & 0xff));
        String ultimate = Integer.toHexString(((quad[2] & 0xff) << 8)
                | (quad[3] & 0xff));
        return initialPart + penultimate + ":" + ultimate;
    }

    private static byte parseOctet(String ipPart) {
        // Note: we already verified that this string contains only hex digits.
        int octet = Integer.parseInt(ipPart);
        // Disallow leading zeroes, because no clear standard exists on
        // whether these should be interpreted as decimal or octal.
        if (octet > 255 || (ipPart.startsWith("0") && ipPart.length() > 1)) {
            throw new NumberFormatException();
        }
        return (byte) octet;
    }

    private static short parseHextet(String ipPart) {
        // Note: we already verified that this string contains only hex digits.
        int hextet = Integer.parseInt(ipPart, 16);
        if (hextet > 0xffff) {
            throw new NumberFormatException();
        }
        return (short) hextet;
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/core/util/ThreadPreconditions.java
================================================
package com.nilhcem.hostseditor.core.util;

import android.os.Looper;

import com.nilhcem.hostseditor.BuildConfig;

public final class ThreadPreconditions {

    private ThreadPreconditions() {
        throw new UnsupportedOperationException();
    }

    public static void checkOnMainThread() {
        if (BuildConfig.DEBUG) {
            if (Thread.currentThread() != Looper.getMainLooper().getThread()) {
                throw new IllegalStateException("This method should be called from the Main Thread");
            }
        }
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/event/CreatedHostEvent.java
================================================
package com.nilhcem.hostseditor.event;

import com.nilhcem.hostseditor.core.Host;

public class CreatedHostEvent {

    /**
     * Host (add mode), or the modified version of the Host entry (edit mode).
     */
    public final Host editedHost;

    /**
     * Original version of the Host entry (edit mode) or {@code null} (add mode).
     */
    public final Host originalHost;

    public CreatedHostEvent(Host original, Host edited) {
        originalHost = original;
        editedHost = edited;
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/event/LoadingEvent.java
================================================
package com.nilhcem.hostseditor.event;

import android.content.Context;

public class LoadingEvent {

    private final boolean mIsLoading;
    private final int mMessageRes;
    private final String mMessage;

    public LoadingEvent() {
        this(false, "");
    }

    public LoadingEvent(boolean isLoading, int messageRes) {
        mIsLoading = isLoading;
        mMessageRes = messageRes;
        mMessage = null;
    }

    public LoadingEvent(boolean isLoading, String message) {
        mIsLoading = isLoading;
        mMessage = message;
        mMessageRes = 0;
    }

    public boolean isLoading() {
        return mIsLoading;
    }

    public String getMessage(Context context) {
        if (mMessage == null) {
            return context.getString(mMessageRes);
        }
        return mMessage;
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/event/RefreshHostsEvent.java
================================================
package com.nilhcem.hostseditor.event;

import com.nilhcem.hostseditor.core.Host;

import java.util.List;

/**
 * Sent to the bus when hosts need to be refreshed.
 */
public class RefreshHostsEvent {

    public final List<Host> hosts;

    public RefreshHostsEvent(List<Host> refreshedHosts) {
        hosts = refreshedHosts;
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/event/StartAddEditActivityEvent.java
================================================
package com.nilhcem.hostseditor.event;

import com.nilhcem.hostseditor.core.Host;

public class StartAddEditActivityEvent {

    /**
     * The Host entry to modify (edit mode), or {@code null} (add mode).
     */
    public final Host host;

    public StartAddEditActivityEvent(Host addEditHost) {
        host = addEditHost;
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/event/TaskCompletedEvent.java
================================================
package com.nilhcem.hostseditor.event;

public class TaskCompletedEvent {

    public final String tag;
    public final boolean isSuccessful;

    public TaskCompletedEvent(String pTag, boolean pIsSuccessful) {
        tag = pTag;
        isSuccessful = pIsSuccessful;
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/task/AddEditHostAsync.java
================================================
package com.nilhcem.hostseditor.task;

import android.content.Context;

import com.nilhcem.hostseditor.R;
import com.nilhcem.hostseditor.core.Host;

import java.util.List;

import timber.log.Timber;

/**
 * AsyncTask that inserts or edits an host entry and triggers a {@code TaskCompletedEvent} event.
 */
public class AddEditHostAsync extends GenericTaskAsync {

    public AddEditHostAsync(Context appContext, boolean flagMsg) {
        super(appContext, flagMsg);
    }

    @Override
    protected void process(Host... params) {
        Timber.d("Add/Edit host");
        Host host = params[0];
        Host original = params[1];

        List<Host> hosts = mHostsManager.getHosts(false);
        if (original == null) {
            hosts.add(host);
        } else {
            hosts.get(hosts.indexOf(original)).merge(host);
        }
    }

    @Override
    protected int getLoadingMsgRes() {
        return mFlagLoadingMsg ? R.string.loading_add : R.string.loading_edit;
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/task/GenericTaskAsync.java
================================================
package com.nilhcem.hostseditor.task;

import android.content.Context;
import android.os.AsyncTask;

import com.nilhcem.hostseditor.HostsEditorApplication;
import com.nilhcem.hostseditor.core.Host;
import com.nilhcem.hostseditor.core.HostsManager;
import com.nilhcem.hostseditor.event.LoadingEvent;
import com.nilhcem.hostseditor.event.TaskCompletedEvent;
import com.squareup.otto.Bus;

import javax.inject.Inject;

import timber.log.Timber;

public abstract class GenericTaskAsync extends AsyncTask<Host, Void, Void> {

    @Inject Bus mBus;
    @Inject HostsManager mHostsManager;

    private Context mAppContext;
    protected boolean mFlagLoadingMsg; // which loading message (between 2) to display: (singular/plural) - (add/edit).

    public GenericTaskAsync(Context appContext, boolean flagMsg) {
        mAppContext = appContext;
        mFlagLoadingMsg = flagMsg;
        HostsEditorApplication.get(appContext).component().inject(this);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mBus.post(new LoadingEvent(true, getLoadingMsgRes()));
    }

    @Override
    protected Void doInBackground(Host... params) {
        process(params);
        if (!mHostsManager.saveHosts(mAppContext)) {
            cancel(false);
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        Timber.d("Task fully executed");
        mBus.post(new TaskCompletedEvent(getClass().getSimpleName(), true));
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
        Timber.w("Task cancelled");
        mBus.post(new TaskCompletedEvent(getClass().getSimpleName(), false));
    }

    /**
     * This method should edit the main {@code List<Host>}.
     *
     * @param params selected Hosts from the main ListView.
     */
    protected abstract void process(Host... params);

    protected abstract int getLoadingMsgRes();
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/task/ListHostsAsync.java
================================================
package com.nilhcem.hostseditor.task;

import android.content.Context;
import android.os.AsyncTask;

import com.nilhcem.hostseditor.HostsEditorApplication;
import com.nilhcem.hostseditor.R;
import com.nilhcem.hostseditor.core.Host;
import com.nilhcem.hostseditor.core.HostsManager;
import com.nilhcem.hostseditor.event.LoadingEvent;
import com.nilhcem.hostseditor.event.RefreshHostsEvent;
import com.squareup.otto.Bus;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * AsyncTask that gets all valid hosts and triggers a {@code RefreshHostEvent} event.
 */
public class ListHostsAsync extends AsyncTask<Boolean, Void, List<Host>> {

    @Inject Bus mBus;
    @Inject HostsManager mHostsManager;

    public ListHostsAsync(Context context) {
        HostsEditorApplication.get(context).component().inject(this);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mBus.post(new LoadingEvent(true, R.string.loading_hosts));
    }

    @Override
    protected List<Host> doInBackground(Boolean... params) {
        Boolean forceRefresh = params[0];
        if (forceRefresh == null) {
            forceRefresh = false;
        }

        List<Host> allHosts = mHostsManager.getHosts(forceRefresh);

        // Filter to get only valid hosts
        List<Host> validHosts = new ArrayList<>();
        for (Host host : allHosts) {
            if (host.isValid()) {
                validHosts.add(host);
            }
        }
        return validHosts;
    }

    @Override
    protected void onPostExecute(List<Host> result) {
        super.onPostExecute(result);
        mBus.post(new RefreshHostsEvent(result));
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/task/RemoveHostsAsync.java
================================================
package com.nilhcem.hostseditor.task;

import android.content.Context;

import com.nilhcem.hostseditor.R;
import com.nilhcem.hostseditor.core.Host;

import java.util.List;

import timber.log.Timber;

/**
 * AsyncTask that removes one or many host entries and triggers a {@code TaskCompletedEvent} event.
 */
public class RemoveHostsAsync extends GenericTaskAsync {

    public RemoveHostsAsync(Context appContext, boolean flagMsg) {
        super(appContext, flagMsg);
    }

    @Override
    protected void process(Host... params) {
        Timber.d("Remove hosts");

        List<Host> hosts = mHostsManager.getHosts(false);
        for (Host host : params) {
            hosts.remove(host);
        }
    }

    @Override
    protected int getLoadingMsgRes() {
        return mFlagLoadingMsg ? R.string.loading_remove_single : R.string.loading_remove_multiple;
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/task/ToggleHostsAsync.java
================================================
package com.nilhcem.hostseditor.task;

import android.content.Context;

import com.nilhcem.hostseditor.R;
import com.nilhcem.hostseditor.core.Host;

import timber.log.Timber;

/**
 * AsyncTask that toggles one or many host entries and triggers a {@code TaskCompletedEvent} event.
 */
public class ToggleHostsAsync extends GenericTaskAsync {

    public ToggleHostsAsync(Context appContext, boolean flagMsg) {
        super(appContext, flagMsg);
    }

    @Override
    protected void process(Host... params) {
        Timber.d("Toggle hosts");

        for (Host host : params) {
            host.toggleComment();
        }
    }

    @Override
    protected int getLoadingMsgRes() {
        return mFlagLoadingMsg ? R.string.loading_toggle_single : R.string.loading_toggle_multiple;
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/ui/BaseActivity.java
================================================
package com.nilhcem.hostseditor.ui;

import android.os.Bundle;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.nilhcem.hostseditor.HostsEditorApplication;
import com.squareup.otto.Bus;

import javax.inject.Inject;

/**
 * All activities should extend this for dependency injection.
 */
public abstract class BaseActivity extends SherlockFragmentActivity {

    @Inject protected Bus mBus;
    protected HostsEditorApplication mApp;

    @Override
    protected void onCreate(Bundle state) {
        super.onCreate(state);
        mApp = HostsEditorApplication.get(this);
        mApp.component().inject(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mBus.register(this);
    }

    @Override
    protected void onPause() {
        mBus.unregister(this);
        super.onPause();
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/ui/BaseFragment.java
================================================
package com.nilhcem.hostseditor.ui;

import android.app.Activity;
import android.os.Bundle;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.nilhcem.hostseditor.BuildConfig;
import com.nilhcem.hostseditor.HostsEditorApplication;
import com.squareup.otto.Bus;

import javax.inject.Inject;

/**
 * All fragments should extend this for dependency injection.
 */
public class BaseFragment extends SherlockFragment {

    @Inject protected Bus mBus;

    protected HostsEditorApplication mApp;
    protected SherlockFragmentActivity mActivity;

    @Override
    public void onAttach(Activity activity) {
        if (BuildConfig.DEBUG && !(activity instanceof SherlockFragmentActivity)) {
            throw new UnsupportedOperationException("Activity must be a SherlockFragmentActivity");
        }

        super.onAttach(activity);
        mApp = HostsEditorApplication.get(activity);
        mActivity = (SherlockFragmentActivity) activity;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Override
    public void onResume() {
        super.onResume();
        mBus.register(this);
    }

    @Override
    public void onPause() {
        mBus.unregister(this);
        super.onPause();
    }

    @Override
    public void onDetach() {
        mApp = null;
        mActivity = null;
        super.onDetach();
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/ui/about/AboutDialogFragment.java
================================================
package com.nilhcem.hostseditor.ui.about;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.actionbarsherlock.app.SherlockDialogFragment;
import com.nilhcem.hostseditor.R;

import butterknife.ButterKnife;
import butterknife.OnClick;

public class AboutDialogFragment extends SherlockDialogFragment {

    public static final String TAG = AboutDialogFragment.class.getSimpleName();
    private static final String GITHUB_URL = "https://github.com/Nilhcem/hosts-editor-android";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.about_dialog, container, false);
        ButterKnife.bind(this, view);
        getDialog().setTitle(R.string.about_title);
        return view;
    }

    @Override
    public void onDestroyView() {
        ButterKnife.unbind(this);
        super.onDestroyView();
    }

    @OnClick(R.id.aboutGitHub)
    void openGitHubUrl() {
        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(GITHUB_URL));
        startActivity(browserIntent);
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/ui/addedit/AddEditHostActivity.java
================================================
package com.nilhcem.hostseditor.ui.addedit;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.nilhcem.hostseditor.R;
import com.nilhcem.hostseditor.core.Host;
import com.nilhcem.hostseditor.event.CreatedHostEvent;
import com.nilhcem.hostseditor.ui.BaseActivity;
import com.nilhcem.hostseditor.ui.list.ListHostsActivity;
import com.squareup.otto.Subscribe;

public class AddEditHostActivity extends BaseActivity {

    public static final String EXTRA_HOST_ORIGINAL = "hostOriginal"; // useful in Edit mode, this is the original Host entry before being edited.
    public static final String EXTRA_HOST_MODIFIED = "hostModified"; // the new Host entry, after having been edited.

    private AddEditHostFragment mFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Host hostToEdit = getHostFromIntent();
        initActionBar(hostToEdit);

        // Add fragment
        FragmentManager fm = getSupportFragmentManager();
        mFragment = (AddEditHostFragment) fm.findFragmentByTag(AddEditHostFragment.TAG);
        if (mFragment == null) {
            mFragment = AddEditHostFragment.newInstance(hostToEdit);
            FragmentTransaction ft = fm.beginTransaction();
            ft.replace(android.R.id.content, mFragment, AddEditHostFragment.TAG);
            ft.commit();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getSupportMenuInflater().inflate(R.menu.add_edit_menu, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        MenuItem item = menu.findItem(R.id.action_add_rm_comment);
        if (mFragment.hasComment()) {
            item.setTitle(R.string.action_remove_comment);
        } else {
            item.setTitle(R.string.action_add_comment);
        }
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                Intent intent = new Intent(this, ListHostsActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                return true;
            case R.id.action_add_rm_comment:
                mFragment.toggleCommentVisibility();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Subscribe
    public void onHostCreatedFromFragment(CreatedHostEvent event) {
        Intent returnIntent = new Intent();
        returnIntent.putExtra(EXTRA_HOST_ORIGINAL, event.originalHost);
        returnIntent.putExtra(EXTRA_HOST_MODIFIED, event.editedHost);
        setResult(RESULT_OK, returnIntent);
        finish();
    }

    private Host getHostFromIntent() {
        Host host = null;

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            host = bundle.getParcelable(EXTRA_HOST_ORIGINAL);
        }
        return host;
    }

    private void initActionBar(Host hostToEdit) {
        int titleRes;
        if (hostToEdit == null) {
            titleRes = R.string.add_host_title;
        } else {
            titleRes = R.string.edit_host_title;
        }

        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(titleRes);
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/ui/addedit/AddEditHostFragment.java
================================================
package com.nilhcem.hostseditor.ui.addedit;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.nilhcem.hostseditor.R;
import com.nilhcem.hostseditor.core.Host;
import com.nilhcem.hostseditor.core.util.InetAddresses;
import com.nilhcem.hostseditor.event.CreatedHostEvent;
import com.nilhcem.hostseditor.ui.BaseFragment;

import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AddEditHostFragment extends BaseFragment {

    public static final String TAG = AddEditHostFragment.class.getSimpleName();

    private static final String ARG_HOST = "mInitialHost";
    private static final Pattern HOSTNAME_INVALID_CHARS_PATTERN = Pattern.compile("^.*[#'\",\\\\]+.*$");

    private Host mInitialHost; // "edit mode" only - null for "add mode"
    private AlertDialog mErrorAlert;

    @Bind(R.id.addEditHostIp) EditText mIp;
    @Bind(R.id.addEditHostName) EditText mHostName;
    @Bind(R.id.addEditComment) EditText mComment;
    @Bind(R.id.addEditCommentLabel) TextView mCommentLabel;
    @Bind(R.id.addEditHostButton) Button mButton;

    public static AddEditHostFragment newInstance(Host hostToEdit) {
        AddEditHostFragment fragment = new AddEditHostFragment();

        if (hostToEdit != null) {
            Bundle args = new Bundle();
            args.putParcelable(ARG_HOST, hostToEdit);
            fragment.setArguments(args);
        }
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mApp.component().inject(this);
        Bundle arguments = getArguments();
        if (arguments != null) {
            mInitialHost = arguments.getParcelable(ARG_HOST);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.add_edit_host_layout, container, false);
        ButterKnife.bind(this, view);

        if (mInitialHost == null) {
            mButton.setText(R.string.add_host_title);
        } else {
            mIp.setText(mInitialHost.getIp());
            mHostName.setText(mInitialHost.getHostName());
            mButton.setText(R.string.edit_host_title);

            String comment = mInitialHost.getComment();
            if (!TextUtils.isEmpty(comment)) {
                mComment.setText(comment);
                toggleCommentVisibility();
            }
        }
        return view;
    }

    @Override
    public void onStop() {
        if (mErrorAlert != null) {
            mErrorAlert.dismiss();
        }
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        ButterKnife.unbind(this);
        super.onDestroyView();
    }

    @OnClick(R.id.addEditHostButton)
    void onAddEditHostButtonClicked(Button button) {
        if (button.getId() == R.id.addEditHostButton) {
            String ip = mIp.getText().toString();
            String hostname = mHostName.getText().toString();
            String comment = mComment.getText().toString();
            if (TextUtils.isEmpty(comment)) {
                comment = null;
            }
            int error = checkFormErrors(ip, hostname);

            if (error == 0) {
                Host edited = new Host(ip, hostname, comment, false, true);
                mBus.post(new CreatedHostEvent(mInitialHost, edited));
            } else {
                mErrorAlert = new AlertDialog.Builder(mActivity)
                        .setTitle(R.string.add_edit_error_title)
                        .setMessage(error)
                        .setCancelable(true)
                        .setNeutralButton(R.string.add_edit_error_ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // Do nothing
                            }
                        })
                        .create();
                mErrorAlert.show();
            }
        }
    }

    public boolean hasComment() {
        return mComment.getVisibility() == View.VISIBLE;
    }

    public void toggleCommentVisibility() {
        int visibility;
        if (hasComment()) {
            visibility = View.GONE;
            mComment.setText("");
        } else {
            visibility = View.VISIBLE;
        }

        mComment.setVisibility(visibility);
        mCommentLabel.setVisibility(visibility);
    }

    private int checkFormErrors(String ip, String hostname) {
        int error = 0;

        if (TextUtils.isEmpty(hostname) || HOSTNAME_INVALID_CHARS_PATTERN.matcher(hostname).matches()) {
            error = R.string.add_edit_error_hostname;
        }
        if (TextUtils.isEmpty(ip) || !InetAddresses.isInetAddress(ip)) {
            error = R.string.add_edit_error_ip;
        }
        return error;
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/ui/list/ListHostsActivity.java
================================================
package com.nilhcem.hostseditor.ui.list;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.widget.SearchView;
import com.nilhcem.hostseditor.R;
import com.nilhcem.hostseditor.core.Host;
import com.nilhcem.hostseditor.event.LoadingEvent;
import com.nilhcem.hostseditor.event.StartAddEditActivityEvent;
import com.nilhcem.hostseditor.ui.BaseActivity;
import com.nilhcem.hostseditor.ui.about.AboutDialogFragment;
import com.nilhcem.hostseditor.ui.addedit.AddEditHostActivity;
import com.squareup.otto.Subscribe;

import butterknife.Bind;
import butterknife.ButterKnife;
import timber.log.Timber;

public class ListHostsActivity extends BaseActivity {

    private static final int REQUESTCODE_ADDEDIT_ACTIVITY = 1;
    private static final String STR_EMPTY = "";
    private static final String INSTANCE_STATE_LOADING = "loading";
    private static final String INSTANCE_STATE_LOADING_MESSAGE = "loadingMessage";
    private static final String INSTANCE_STATE_SEARCH = "search";

    @Bind(R.id.listLoading) ProgressBar mProgressBar;
    @Bind(R.id.listLoadingMsg) TextView mLoadingMsg;

    private ListHostsFragment mFragment;
    private String mSearchQuery = STR_EMPTY;
    private MenuItem mSearchItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_hosts_layout);
        ButterKnife.bind(this);

        FragmentManager fm = getSupportFragmentManager();
        mFragment = (ListHostsFragment) fm.findFragmentById(R.id.listHostsFragment);

        if (savedInstanceState == null) {
            onLoadingEvent(new LoadingEvent(true, R.string.loading_hosts));
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getSupportMenuInflater().inflate(R.menu.list_menu, menu);

        // Init search
        mSearchItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) mSearchItem.getActionView();
        if (searchView != null) {
            searchView.setQueryHint(getString(R.string.action_search));
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    mSearchItem.collapseActionView();
                    return true;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    Timber.d("Search query: %s", newText);
                    setSearchQuery(newText);
                    mFragment.filterList(newText);
                    return true;
                }
            });
        }
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mFragment.filterList(mSearchQuery);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (!TextUtils.isEmpty(mSearchQuery)) {
                    // Revert search
                    setSearchQuery(STR_EMPTY);
                    mFragment.filterList(mSearchQuery);
                    return true;
                }
                break;
            case KeyEvent.KEYCODE_SEARCH:
                mSearchItem.expandActionView();
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_add_host:
                mBus.post(new StartAddEditActivityEvent(null));
                return true;
            case R.id.action_reload_hosts:
                mFragment.refreshHosts(true);
                return true;
            case R.id.action_select_all:
                mFragment.selectAll();
                return true;
            case R.id.action_about:
                displayAboutDialog();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Timber.d("Activity result received");
        if (requestCode == REQUESTCODE_ADDEDIT_ACTIVITY) {
            if (resultCode == RESULT_OK) {
                Host modified = data.getParcelableExtra(AddEditHostActivity.EXTRA_HOST_MODIFIED);
                Host original = data.getParcelableExtra(AddEditHostActivity.EXTRA_HOST_ORIGINAL);

                boolean addMode = (original == null);
                onLoadingEvent(new LoadingEvent(true, addMode ? R.string.loading_add : R.string.loading_edit));
                mFragment.addEditHost(addMode, new Host[]{modified, original});
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(INSTANCE_STATE_LOADING, mProgressBar.getVisibility() == View.VISIBLE);
        outState.putString(INSTANCE_STATE_LOADING_MESSAGE, mLoadingMsg.getText().toString());
        outState.putString(INSTANCE_STATE_SEARCH, mSearchQuery);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        boolean isLoading = savedInstanceState.getBoolean(INSTANCE_STATE_LOADING, true);

        if (isLoading) {
            String loadingMsg = savedInstanceState.getString(INSTANCE_STATE_LOADING_MESSAGE);
            if (loadingMsg == null) {
                loadingMsg = STR_EMPTY;
            }
            onLoadingEvent(new LoadingEvent(true, loadingMsg));
        }
        setSearchQuery(savedInstanceState.getString(INSTANCE_STATE_SEARCH));
    }

    @Override
    protected void onDestroy() {
        ButterKnife.unbind(this);
        super.onDestroy();
    }

    @Subscribe
    public void onStartAddEditActivityEvent(StartAddEditActivityEvent event) {
        Timber.d("Ready to start AddEditActivity");
        Intent intent = new Intent(this, AddEditHostActivity.class);
        intent.putExtra(AddEditHostActivity.EXTRA_HOST_ORIGINAL, event.host);
        startActivityForResult(intent, REQUESTCODE_ADDEDIT_ACTIVITY);
    }

    @Subscribe
    public void onLoadingEvent(LoadingEvent event) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

        mLoadingMsg.setText(event.getMessage(this));
        if (event.isLoading()) {
            Timber.d("Start loading");
            if (mSearchItem != null) {
                setSearchQuery(STR_EMPTY);
                mSearchItem.collapseActionView();
            }

            mProgressBar.setVisibility(View.VISIBLE);
            mLoadingMsg.setVisibility(View.VISIBLE);
            ft.hide(mFragment);
        } else {
            Timber.d("Stop loading");
            mProgressBar.setVisibility(View.GONE);
            mLoadingMsg.setVisibility(View.GONE);
            ft.show(mFragment);
        }
        ft.commitAllowingStateLoss();
    }

    private void setSearchQuery(String searchQuery) {
        mSearchQuery = searchQuery;
        setActionBarTitle();
    }

    private void setActionBarTitle() {
        int titleRes;

        if (TextUtils.isEmpty(mSearchQuery)) {
            titleRes = R.string.app_name;
        } else {
            titleRes = R.string.action_search_results;
        }
        getSupportActionBar().setTitle(titleRes);
    }

    private void displayAboutDialog() {
        FragmentManager fm = getSupportFragmentManager();
        AboutDialogFragment dialog = new AboutDialogFragment();
        dialog.show(fm, AboutDialogFragment.TAG);
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/ui/list/ListHostsAdapter.java
================================================
package com.nilhcem.hostseditor.ui.list;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;

import com.nilhcem.hostseditor.core.Host;
import com.nilhcem.hostseditor.core.util.Compatibility;
import com.nilhcem.hostseditor.core.util.ThreadPreconditions;
import com.nilhcem.hostseditor.ui.widget.CheckableHostItem;

import java.util.Collections;
import java.util.List;

import javax.inject.Inject;

import timber.log.Timber;

public class ListHostsAdapter extends BaseAdapter implements Filterable {

    private final ListHostsSearchFilter mSearchFilter;

    private List<Host> mHosts = Collections.emptyList();
    private Context mAppContext;

    private int mIpMinWidth;
    private int mIpMaxWidth;

    @Inject public ListHostsAdapter(ListHostsSearchFilter searchFilter) {
        mSearchFilter = searchFilter;
    }

    public void init(Context appContext) {
        mAppContext = appContext;
    }

    public void updateHosts(List<Host> hosts) {
        ThreadPreconditions.checkOnMainThread();
        if (hosts == null) {
            mHosts = Collections.emptyList();
        } else {
            mHosts = hosts;
        }
        notifyDataSetChanged();
    }

    public void computeViewWidths(Context context) {
        // The IP column can be very large, especially when it holds ipv6 with 39 chars.
        // Its size has to be generated programmatically, as it should fit with the device's width.
        // A tablet can afford having a large column but not a phone.

        int screenWidth = Compatibility.getScreenDimensions(context).x;
        Timber.d("Screen width: %d", screenWidth);

        // 1: Compute minimum width.
        // Min width must be between [100dp, 160dp]. If possible, 30% of screen width.
        int minWidth = screenWidth * 30 / 100;
        int minRange = Compatibility.convertDpToIntPixel(100f, context);
        int maxRange = Compatibility.convertDpToIntPixel(160f, context);

        if (minWidth < minRange) {
            minWidth = minRange;
        }
        if (minWidth > maxRange) {
            minWidth = maxRange;
        }

        // 2: Compute maximum width, usually 35% of screen width.
        int maxWidth = screenWidth * 35 / 100;
        if (maxWidth < minWidth) {
            maxWidth = minWidth;
        }

        Timber.d("Min width: %d - Max width: %d", minWidth, maxWidth);
        mIpMinWidth = minWidth;
        mIpMaxWidth = maxWidth;
    }

    @Override
    public int getCount() {
        return mHosts.size();
    }

    @Override
    public Host getItem(int position) {
        return mHosts.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        CheckableHostItem view;

        if (convertView == null) {
            view = new CheckableHostItem(mAppContext);
        } else {
            view = (CheckableHostItem) convertView;
        }

        Host host = getItem(position);
        view.init(host, mIpMinWidth, mIpMaxWidth);
        return view;
    }

    @Override
    public Filter getFilter() {
        return mSearchFilter;
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/ui/list/ListHostsFragment.java
================================================
package com.nilhcem.hostseditor.ui.list;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;

import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.nilhcem.hostseditor.R;
import com.nilhcem.hostseditor.core.Host;
import com.nilhcem.hostseditor.event.LoadingEvent;
import com.nilhcem.hostseditor.event.RefreshHostsEvent;
import com.nilhcem.hostseditor.event.StartAddEditActivityEvent;
import com.nilhcem.hostseditor.event.TaskCompletedEvent;
import com.nilhcem.hostseditor.task.AddEditHostAsync;
import com.nilhcem.hostseditor.task.ListHostsAsync;
import com.nilhcem.hostseditor.task.RemoveHostsAsync;
import com.nilhcem.hostseditor.task.ToggleHostsAsync;
import com.nilhcem.hostseditor.ui.BaseFragment;
import com.squareup.otto.Subscribe;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.ButterKnife;
import timber.log.Timber;

public class ListHostsFragment extends BaseFragment implements OnItemClickListener, OnItemLongClickListener {

    @Inject ListHostsAdapter mAdapter;

    @Bind(R.id.listHosts) ListView mListView;

    private ActionMode mMode;
    private MenuItem mEditMenuItem;
    private Dialog mDisplayedDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mApp.component().inject(this);
        mAdapter.init(mApp);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        boolean firstCall = (mListView == null);

        View view = inflater.inflate(R.layout.list_hosts_fragment, container, false);
        ButterKnife.bind(this, view);

        mListView.setAdapter(mAdapter);
        mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        mListView.setFastScrollEnabled(true);
        mListView.setItemsCanFocus(false);
        mListView.setOnItemClickListener(this);
        mListView.setOnItemLongClickListener(this);

        View emptyLayout = view.findViewById(R.id.listEmptyLayout);
        if (emptyLayout != null) {
            mListView.setEmptyView(emptyLayout);
        }

        mAdapter.computeViewWidths(mActivity);

        if (firstCall) {
            refreshHosts(false);
        }
        return view;
    }

    @Override
    public void onPause() {
        finishActionMode();
        if (mDisplayedDialog != null) {
            mDisplayedDialog.dismiss();
            mDisplayedDialog = null;
        }
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        ButterKnife.unbind(this);
        super.onDestroyView();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        int nbCheckedElements = 0;
        SparseBooleanArray checked = mListView.getCheckedItemPositions();
        for (int i = 0; i < checked.size(); i++) {
            if (checked.valueAt(i)) {
                nbCheckedElements++;
            }
        }
        displayActionMode(nbCheckedElements);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        if (mMode == null) {
            Host host = mAdapter.getItem(position);
            mBus.post(new StartAddEditActivityEvent(host));
            return true;
        }
        return false;
    }

    @Subscribe
    public void onTaskFinished(TaskCompletedEvent task) {
        Timber.d("Task %s finished", task.tag);
        if (task.isSuccessful) {
            refreshHosts(false);
        } else {
            displayErrorDialog();
        }
    }

    @Subscribe
    public void onHostsRefreshed(RefreshHostsEvent hosts) {
        Timber.d("Refreshing listview");
        finishActionMode();
        mAdapter.updateHosts(hosts.hosts);
        mBus.post(new LoadingEvent());
    }

    public void addEditHost(boolean addMode, Host[] hosts) {
        new AddEditHostAsync(mApp, addMode).execute(hosts);
    }

    public void refreshHosts(boolean forceRefresh) {
        new ListHostsAsync(mApp).execute(forceRefresh);
    }

    public void selectAll() {
        int nbElem = mAdapter.getCount();

        if (nbElem > 0) {
            for (int i = 0; i < nbElem; i++) {
                mListView.setItemChecked(i, true);
            }
            displayActionMode(nbElem);
        }
    }

    public void filterList(String filter) {
        mAdapter.getFilter().filter(filter);
    }

    private void displayActionMode(int nbCheckedElements) {
        if (nbCheckedElements > 0) {
            if (mMode == null) {
                mMode = mActivity.startActionMode(new ModeCallback());
            }

            if (mEditMenuItem != null) {
                mEditMenuItem.setVisible(nbCheckedElements == 1);
            }
            mMode.setTitle(String.format(Locale.US, getString(R.string.list_menu_selected), nbCheckedElements));
        } else {
            finishActionMode();
        }
    }

    private final class ModeCallback implements ActionMode.Callback {

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            MenuInflater inflater = mActivity.getSupportMenuInflater();
            inflater.inflate(R.menu.list_contextual_actions, menu);
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            mEditMenuItem = menu.findItem(R.id.cab_action_edit);
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            for (int i = 0; i < mListView.getAdapter().getCount(); i++) {
                mListView.setItemChecked(i, false);
            }
            mMode = null;
            mEditMenuItem = null;
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            Host[] selectedItems = getSelectedItems();

            switch (item.getItemId()) {
                case R.id.cab_action_edit:
                    mBus.post(new StartAddEditActivityEvent(selectedItems[0]));
                    break;
                case R.id.cab_action_delete:
                    displayDeleteConfirmationDialog(selectedItems);
                    break;
                case R.id.cab_action_toggle:
                    new ToggleHostsAsync(mApp, selectedItems.length == 1).execute(selectedItems);
                    break;
                default:
                    return false;
            }
            mode.finish();
            return true;
        }

        private Host[] getSelectedItems() {
            List<Host> items = new ArrayList<>();

            int len = mListView.getCount();
            SparseBooleanArray checked = mListView.getCheckedItemPositions();
            for (int i = 0; i < len; i++) {
                if (checked.get(i)) {
                    items.add(mAdapter.getItem(i));
                }
            }
            return items.toArray(new Host[items.size()]);
        }
    }

    private void displayDeleteConfirmationDialog(final Host[] selectedItems) {
        mDisplayedDialog = new AlertDialog.Builder(mActivity)
                .setTitle(R.string.delete_dialog_title)
                .setMessage(getResources().getQuantityText(R.plurals.delete_dialog_content, selectedItems.length))
                .setPositiveButton(R.string.delete_dialog_delete, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        new RemoveHostsAsync(mApp, selectedItems.length == 1).execute(selectedItems);
                    }
                })
                .setNegativeButton(R.string.delete_dialog_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // Do nothing
                    }
                })
                .create();
        mDisplayedDialog.show();
    }

    private void displayErrorDialog() {
        mBus.post(new LoadingEvent());
        mDisplayedDialog = new AlertDialog.Builder(mActivity)
                .setTitle(R.string.list_error_title)
                .setMessage(R.string.list_error_content)
                .setNeutralButton(R.string.list_error_ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        refreshHosts(true);
                    }
                })
                .setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        refreshHosts(true);
                    }
                })
                .create();
        mDisplayedDialog.show();
    }

    private void finishActionMode() {
        if (mMode != null) {
            mMode.finish();
        }
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/ui/list/ListHostsSearchFilter.java
================================================
package com.nilhcem.hostseditor.ui.list;

import android.text.TextUtils;
import android.widget.Filter;

import com.nilhcem.hostseditor.core.Host;
import com.nilhcem.hostseditor.core.HostsManager;
import com.nilhcem.hostseditor.event.RefreshHostsEvent;
import com.squareup.otto.Bus;

import java.util.List;

import javax.inject.Inject;

import timber.log.Timber;

public class ListHostsSearchFilter extends Filter {

    private final Bus mBus;
    private final HostsManager mHostsManager;

    @Inject public ListHostsSearchFilter(Bus bus, HostsManager hostsManager) {
        mBus = bus;
        mHostsManager = hostsManager;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        if (!TextUtils.isEmpty(constraint)) {
            Timber.d("Publishing result for: %s", constraint);
        }
        mBus.post(new RefreshHostsEvent((List<Host>) results.values));
    }

    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        if (!TextUtils.isEmpty(constraint)) {
            Timber.d("Perform filtering for: %s", constraint);
        }
        FilterResults results = new FilterResults();
        results.values = mHostsManager.filterHosts(constraint);
        return results;
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/ui/widget/CheckableHostItem.java
================================================
package com.nilhcem.hostseditor.ui.widget;

import android.content.Context;
import android.content.res.Resources;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Checkable;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nilhcem.hostseditor.R;
import com.nilhcem.hostseditor.core.Host;

import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Custom component that implements the Checkable interface.
 *
 * @see "http://www.marvinlabs.com/2010/10/29/custom-listview-ability-check-items/"
 */
public class CheckableHostItem extends RelativeLayout implements Checkable {

    @Bind(R.id.hostItemIp) TextView mIp;
    @Bind(R.id.hostItemHostname) TextView mHostname;
    @Bind(R.id.hostItemComment) TextView mComment;
    @Bind(R.id.hostItemCheckbox) InertCheckBox mCheckbox;

    private int mTextColor;
    private int mCommentColor;

    public CheckableHostItem(Context context) {
        super(context);
        initLayout(context);
    }

    private void initLayout(Context context) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.checkable_host_item, this, true);
        ButterKnife.bind(this, view);

        Resources res = context.getResources();
        mTextColor = res.getColor(R.color.list_hosts_entry);
        mCommentColor = res.getColor(R.color.list_hosts_comment);
    }

    public void init(Host host, int ipMinWidth, int ipMaxWidth) {
        String ip = String.format(Locale.US, "%s%s", (host.isCommented() ? Host.STR_COMMENT : ""), host.getIp());

        int textColor;
        if (host.isCommented()) {
            textColor = mCommentColor;
        } else {
            textColor = mTextColor;
        }

        mIp.setText(ip);
        mIp.setTextColor(textColor);
        mIp.setMinimumWidth(ipMinWidth);
        mIp.setMaxWidth(ipMaxWidth);
        mHostname.setText(host.getHostName());
        mHostname.setTextColor(textColor);
        mCheckbox.setChecked(false);

        String comment = host.getComment();
        if (TextUtils.isEmpty(comment)) {
            mComment.setVisibility(View.GONE);
        } else {
            mComment.setText(String.format(Locale.US, "%s%s", Host.STR_COMMENT, comment));
            mComment.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public boolean isChecked() {
        return mCheckbox.isChecked();
    }

    @Override
    public void setChecked(boolean checked) {
        mCheckbox.setChecked(checked);
    }

    @Override
    public void toggle() {
        mCheckbox.toggle();
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/ui/widget/InertCheckBox.java
================================================
package com.nilhcem.hostseditor.ui.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.CheckBox;

/**
 * CheckBox that does not react to any user event in order to let the container handle them.
 */
public class InertCheckBox extends CheckBox {

    public InertCheckBox(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public InertCheckBox(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public InertCheckBox(Context context) {
        super(context);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return false;
    }

    @Override
    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
        return false;
    }

    @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        return false;
    }

    @Override
    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
        return false;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        return false;
    }

    @Override
    public boolean onTrackballEvent(MotionEvent event) {
        return false;
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/ui/widget/TypefacedButton.java
================================================
package com.nilhcem.hostseditor.ui.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;

/**
 * Button using a custom font.
 *
 * @see TypefacedTextView
 */
public final class TypefacedButton extends Button {

    public TypefacedButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypefacedTextView.applyFont(context, attrs, this);
    }
}


================================================
FILE: app/src/main/java/com/nilhcem/hostseditor/ui/widget/TypefacedTextView.java
================================================
package com.nilhcem.hostseditor.ui.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;

import com.nilhcem.hostseditor.R;

/**
 * TextView using a custom font.
 *
 * @see "http://stackoverflow.com/questions/4395309/android-want-to-set-custom-fonts-for-whole-application-not-runtime/9199258#9199258"
 */
public final class TypefacedTextView extends TextView {

    public TypefacedTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

        // Typeface.createFromAsset doesn't work in the layout editor. Skipping...
        if (isInEditMode()) {
            return;
        }

        TypefacedTextView.applyFont(context, attrs, this);
    }

    static void applyFont(Context context, AttributeSet attrs, TextView view) {
        TypedArray styledAttrs = context.obtainStyledAttributes(attrs, R.styleable.TypefacedTextView);
        if (styledAttrs != null) {
            String fontName = styledAttrs.getString(R.styleable.TypefacedTextView_typeface);
            styledAttrs.recycle();

            if (fontName != null) {
                Typeface typeface = Typeface.createFromAsset(context.getAssets(), fontName);
                view.setTypeface(typeface);
            }
        }
    }
}


================================================
FILE: app/src/main/res/layout/about_dialog.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="10dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="10dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <!-- Content -->
        <com.nilhcem.hostseditor.ui.widget.TypefacedTextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/about_text"
            android:textSize="16sp"
            app:typeface="fonts/Roboto-Regular.ttf"/>

        <!-- GitHub button -->
        <com.nilhcem.hostseditor.ui.widget.TypefacedButton
            android:id="@+id/aboutGitHub"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="12dp"
            android:layout_marginTop="12dp"
            android:text="@string/about_github_button"
            app:typeface="fonts/Roboto-Regular.ttf"/>

        <!-- Date - Author -->
        <com.nilhcem.hostseditor.ui.widget.TypefacedTextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:autoLink="web"
            android:gravity="center"
            android:text="@string/about_author"
            app:typeface="fonts/Roboto-Italic.ttf"/>
    </LinearLayout>
</ScrollView>


================================================
FILE: app/src/main/res/layout/add_edit_host_layout.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <!-- IP (label) -->
        <com.nilhcem.hostseditor.ui.widget.TypefacedTextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/add_edit_ip"
            android:textSize="@dimen/add_edit_label_size"
            app:typeface="fonts/Roboto-Regular.ttf"/>

        <!-- IP (input) -->
        <EditText
            android:id="@+id/addEditHostIp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/add_edit_form_margin"
            android:digits="0123456789abcdefABCDEF.:"
            android:ems="10"
            android:inputType="textNoSuggestions">

            <requestFocus/>
        </EditText>

        <!-- Hostname (label) -->
        <com.nilhcem.hostseditor.ui.widget.TypefacedTextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/add_edit_name"
            android:textSize="@dimen/add_edit_label_size"
            app:typeface="fonts/Roboto-Regular.ttf"/>

        <!-- Hostname (input) -->
        <EditText
            android:id="@+id/addEditHostName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/add_edit_form_margin"
            android:ems="10"
            android:inputType="textNoSuggestions"/>

        <!-- Comment (label) - hidden by default -->
        <com.nilhcem.hostseditor.ui.widget.TypefacedTextView
            android:id="@+id/addEditCommentLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/add_edit_comment"
            android:textSize="@dimen/add_edit_label_size"
            android:visibility="gone"
            app:typeface="fonts/Roboto-Regular.ttf"
            tools:visibility="visible"/>

        <!-- Comment (input) - hidden by default -->
        <EditText
            android:id="@+id/addEditComment"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/add_edit_form_margin"
            android:ems="10"
            android:inputType="text"
            android:visibility="gone"
            tools:visibility="visible"/>

        <!-- "Add/Edit Host" Button -->
        <com.nilhcem.hostseditor.ui.widget.TypefacedButton
            android:id="@+id/addEditHostButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="10dp"
            android:drawableLeft="@drawable/ic_action_add_dark"
            android:drawablePadding="8dp"
            app:typeface="fonts/Roboto-Light.ttf"
            tools:text="@string/add_host_title"/>
    </LinearLayout>
</ScrollView>


================================================
FILE: app/src/main/res/layout/checkable_host_item.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingBottom="4dp"
    android:paddingTop="4dp">

    <!-- Left part (IP) -->
    <TextView
        android:id="@+id/hostItemIp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:focusable="false"
        android:paddingLeft="8dp"
        android:paddingRight="18dp"
        android:textIsSelectable="false"
        android:textSize="16sp"
        tools:text="127.0.0.1"/>

    <!-- Middle part (hostname/comment) -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toLeftOf="@+id/hostItemCheckbox"
        android:layout_toRightOf="@+id/hostItemIp"
        android:focusable="false"
        android:orientation="vertical">

        <!-- Hostname -->
        <TextView
            android:id="@+id/hostItemHostname"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:focusable="false"
            android:textIsSelectable="false"
            android:textSize="16sp"
            tools:text="localhost"/>

        <!-- Comment -->
        <TextView
            android:id="@+id/hostItemComment"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:focusable="false"
            android:textColor="@color/list_hosts_comment"
            android:textSize="12sp"
            android:visibility="gone"
            tools:text="#comment"
            tools:visibility="visible"/>
    </LinearLayout>

    <!-- Right part (checkbox) -->
    <com.nilhcem.hostseditor.ui.widget.InertCheckBox
        android:id="@+id/hostItemCheckbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:focusable="false"/>
</RelativeLayout>


================================================
FILE: app/src/main/res/layout/list_hosts_empty.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="vertical">

        <com.nilhcem.hostseditor.ui.widget.TypefacedTextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:text="@string/list_empty"
            android:textSize="24sp"
            app:typeface="fonts/Roboto-Regular.ttf"/>

        <com.nilhcem.hostseditor.ui.widget.TypefacedTextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:text="@string/list_empty_desc"
            android:textSize="12sp"
            app:typeface="fonts/Roboto-Italic.ttf"/>
    </LinearLayout>
</ScrollView>


================================================
FILE: app/src/main/res/layout/list_hosts_fragment.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- Hosts list -->
    <ListView
        android:id="@+id/listHosts"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:listitem="@layout/checkable_host_item"/>

    <!-- Empty layout -->
    <ViewStub
        android:id="@+id/listEmptyLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout="@layout/list_hosts_empty"
        android:visibility="gone"/>
</FrameLayout>


================================================
FILE: app/src/main/res/layout/list_hosts_layout.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <!-- Hosts list -->
    <fragment
        android:id="@+id/listHostsFragment"
        android:name="com.nilhcem.hostseditor.ui.list.ListHostsFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout="@layout/list_hosts_fragment"/>

    <!-- Loading (progress bar) -->
    <ProgressBar
        android:id="@+id/listLoading"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"/>

    <!-- Loading (message) -->
    <com.nilhcem.hostseditor.ui.widget.TypefacedTextView
        android:id="@+id/listLoadingMsg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:paddingTop="12dp"
        android:textSize="18sp"
        android:visibility="gone"
        app:typeface="fonts/Roboto-Regular.ttf"/>
</LinearLayout>


================================================
FILE: app/src/main/res/menu/add_edit_menu.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Add / Remove comment -->
    <item
        android:id="@+id/action_add_rm_comment"
        android:showAsAction="never|withText"
        android:title="@string/action_add_comment"/>
</menu>


================================================
FILE: app/src/main/res/menu/list_contextual_actions.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Edit (visible when only one element is selected) -->
    <item
        android:id="@+id/cab_action_edit"
        android:icon="@drawable/ic_action_edit"
        android:orderInCategory="1"
        android:showAsAction="ifRoom|withText"
        android:title="@string/list_menu_edit"
        android:visible="false"/>

    <!-- Toggle (comment/uncomment) -->
    <item
        android:id="@+id/cab_action_toggle"
        android:icon="@drawable/ic_action_toggle"
        android:orderInCategory="2"
        android:showAsAction="ifRoom|withText"
        android:title="@string/list_menu_toggle"/>

    <!-- Delete -->
    <item
        android:id="@+id/cab_action_delete"
        android:icon="@drawable/ic_action_delete"
        android:orderInCategory="3"
        android:showAsAction="ifRoom|withText"
        android:title="@string/list_menu_delete"/>
</menu>


================================================
FILE: app/src/main/res/menu/list_menu.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Search -->
    <item
        android:id="@+id/action_search"
        android:actionViewClass="com.actionbarsherlock.widget.SearchView"
        android:icon="@drawable/ic_action_search"
        android:showAsAction="ifRoom|withText|collapseActionView"
        android:title="@string/action_search"/>

    <!-- Add host -->
    <item
        android:id="@+id/action_add_host"
        android:icon="@drawable/ic_action_add_dark"
        android:showAsAction="ifRoom|withText"
        android:title="@string/action_add_host"/>

    <!-- Reload -->
    <item
        android:id="@+id/action_reload_hosts"
        android:icon="@drawable/ic_menu_refresh"
        android:showAsAction="never|withText"
        android:title="@string/action_reload"/>

    <!-- Select all -->
    <item
        android:id="@+id/action_select_all"
        android:icon="@drawable/ic_menu_mark"
        android:showAsAction="never|withText"
        android:title="@string/action_select_all"/>

    <!-- About -->
    <item
        android:id="@+id/action_about"
        android:icon="@drawable/ic_menu_info_details"
        android:showAsAction="never|withText"
        android:title="@string/action_about"/>
</menu>


================================================
FILE: app/src/main/res/values/attrs.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="TypefacedTextView">
        <attr name="typeface" format="string"/>
    </declare-styleable>
</resources>


================================================
FILE: app/src/main/res/values/colors.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="list_hosts_entry">#fff3f3f3</color>
    <color name="list_hosts_comment">#ff909090</color>
</resources>


================================================
FILE: app/src/main/res/values/dimens.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- Default screen margins, per the Android Design guidelines -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>

    <!-- Add/Edit host -->
    <dimen name="add_edit_form_margin">20dp</dimen>
    <dimen name="add_edit_label_size">16sp</dimen>
</resources>


================================================
FILE: app/src/main/res/values/strings.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Hosts Editor</string>

    <!-- Action bar menu -->
    <string name="action_search">Search</string>
    <string name="action_search_results">Search results</string>
    <string name="action_add_host">Add Host</string>
    <string name="action_reload">Reload host entries</string>
    <string name="action_select_all">Select all hosts</string>
    <string name="action_about">About</string>

    <!-- Add/Edit host -->
    <string name="add_host_title">Add Hostname</string>
    <string name="edit_host_title">Edit Hostname</string>
    <string name="add_edit_ip">IP Address:</string>
    <string name="add_edit_name">Hostname:</string>
    <string name="add_edit_comment">Comment:</string>
    <string name="add_edit_error_title">Error</string>
    <string name="add_edit_error_ip">IP address is invalid</string>
    <string name="add_edit_error_hostname">Hostname is invalid</string>
    <string name="add_edit_error_ok">OK</string>

    <!-- Add/Edit host menu -->
    <string name="action_add_comment">Add comment</string>
    <string name="action_remove_comment">Remove comment</string>

    <!-- List hosts (empty layout) -->
    <string name="list_empty">No \'hosts\' records found.</string>
    <string name="list_empty_desc">We couldn\'t find any host entry.\nFeel free to add some!</string>

    <!-- List hosts (contextual menu) -->
    <string name="list_menu_selected">%d selected</string>
    <string name="list_menu_edit">Edit</string>
    <string name="list_menu_delete">Delete</string>
    <string name="list_menu_toggle">Toggle</string>

    <!-- List hosts error dialog -->
    <string name="list_error_title">Error</string>
    <string name="list_error_content">Can\'t edit hosts file, make sure you have root/SuperUser rights.\nThe app should be allowed to request super user access.</string>
    <string name="list_error_ok">OK</string>

    <!-- Delete confirmation dialog -->
    <string name="delete_dialog_title">Delete</string>
    <plurals name="delete_dialog_content">
        <item quantity="one">Delete selected host?</item>
        <item quantity="other">Delete selected hosts?</item>
    </plurals>
    <string name="delete_dialog_cancel">Cancel</string>
    <string name="delete_dialog_delete">Delete</string>

    <!-- Loading messages -->
    <string name="loading_hosts">Loading host entries</string>
    <string name="loading_add">Adding entry</string>
    <string name="loading_edit">Editing entry</string>
    <string name="loading_remove_single">Removing entry</string>
    <string name="loading_remove_multiple">Removing entries</string>
    <string name="loading_toggle_single">Toggling entry</string>
    <string name="loading_toggle_multiple">Toggling entries</string>

    <!-- About -->
    <string name="about_title">About Hosts Editor</string>
    <string name="about_text">This app lets you modify your /etc/hosts file on Android.\nYou might need to reboot to clear your DNS cache after any change.</string>
    <string name="about_author">2013 &#8211; 2015\n<a href="http://www.nilhcem.com">http://www.nilhcem.com</a></string>
    <string name="about_github_button">GitHub</string>
</resources>


================================================
FILE: app/src/main/res/values/styles.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!--
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
    -->
    <style name="AppBaseTheme" parent="@style/Theme.Sherlock">
        <!--
            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.
        -->
    </style>

    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    </style>
</resources>


================================================
FILE: app/src/main/res/values-sw720dp-land/dimens.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!--
         Customize dimensions originally defined in res/values/dimens.xml (such as
         screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here.
    -->
    <dimen name="activity_horizontal_margin">128dp</dimen>
</resources>


================================================
FILE: build.gradle
================================================
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.2.3'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}


================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
#Mon Jul 13 13:14:00 GMT 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-all.zip


================================================
FILE: gradlew
================================================
#!/usr/bin/env bash

##############################################################################
##
##  Gradle start up script for UN*X
##
##############################################################################

# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""

APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`

# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"

warn ( ) {
    echo "$*"
}

die ( ) {
    echo
    echo "$*"
    echo
    exit 1
}

# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
  CYGWIN* )
    cygwin=true
    ;;
  Darwin* )
    darwin=true
    ;;
  MINGW* )
    msys=true
    ;;
esac

# For Cygwin, ensure paths are in UNIX format before anything is touched.
if $cygwin ; then
    [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
fi

# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
    ls=`ls -ld "$PRG"`
    link=`expr "$ls" : '.*-> \(.*\)$'`
    if expr "$link" : '/.*' > /dev/null; then
        PRG="$link"
    else
        PRG=`dirname "$PRG"`"/$link"
    fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >&-
APP_HOME="`pwd -P`"
cd "$SAVED" >&-

CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar

# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
        # IBM's JDK on AIX uses strange locations for the executables
        JAVACMD="$JAVA_HOME/jre/sh/java"
    else
        JAVACMD="$JAVA_HOME/bin/java"
    fi
    if [ ! -x "$JAVACMD" ] ; then
        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
    fi
else
    JAVACMD="java"
    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi

# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
    MAX_FD_LIMIT=`ulimit -H -n`
    if [ $? -eq 0 ] ; then
        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
            MAX_FD="$MAX_FD_LIMIT"
        fi
        ulimit -n $MAX_FD
        if [ $? -ne 0 ] ; then
            warn "Could not set maximum file descriptor limit: $MAX_FD"
        fi
    else
        warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
    fi
fi

# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
    GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi

# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
    APP_HOME=`cygpath --path --mixed "$APP_HOME"`
    CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`

    # We build the pattern for arguments to be converted via cygpath
    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
    SEP=""
    for dir in $ROOTDIRSRAW ; do
        ROOTDIRS="$ROOTDIRS$SEP$dir"
        SEP="|"
    done
    OURCYGPATTERN="(^($ROOTDIRS))"
    # Add a user-defined pattern to the cygpath arguments
    if [ "$GRADLE_CYGPATTERN" != "" ] ; then
        OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
    fi
    # Now convert the arguments - kludge to limit ourselves to /bin/sh
    i=0
    for arg in "$@" ; do
        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
        CHECK2=`echo "$arg"|egrep -c "^-"`                                 ### Determine if an option

        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition
            eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
        else
            eval `echo args$i`="\"$arg\""
        fi
        i=$((i+1))
    done
    case $i in
        (0) set -- ;;
        (1) set -- "$args0" ;;
        (2) set -- "$args0" "$args1" ;;
        (3) set -- "$args0" "$args1" "$args2" ;;
        (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
        (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
        (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
        (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
        (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
        (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
    esac
fi

# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
    JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"

exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"


================================================
FILE: gradlew.bat
================================================
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem  Gradle startup script for Windows
@rem
@rem ##########################################################################

@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal

@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=

set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%

@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome

set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init

echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.

goto fail

:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe

if exist "%JAVA_EXE%" goto init

echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.

goto fail

:init
@rem Get command-line arguments, handling Windowz variants

if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args

:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2

:win9xME_args_slurp
if "x%~1" == "x" goto execute

set CMD_LINE_ARGS=%*
goto execute

:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$

:execute
@rem Setup the command line

set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar

@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%

:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd

:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if  not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1

:mainEnd
if "%OS%"=="Windows_NT" endlocal

:omega


================================================
FILE: settings.gradle
================================================
include ':app'
Download .txt
gitextract_bdv5001x/

├── .gitignore
├── LICENSE.txt
├── README.md
├── app/
│   ├── build.gradle
│   ├── libs/
│   │   └── RootTools-4.2.jar
│   └── src/
│       └── main/
│           ├── AndroidManifest.xml
│           ├── java/
│           │   └── com/
│           │       └── nilhcem/
│           │           └── hostseditor/
│           │               ├── HostsEditorApplication.java
│           │               ├── core/
│           │               │   ├── Host.java
│           │               │   ├── HostsManager.java
│           │               │   ├── dagger/
│           │               │   │   ├── HostsEditorComponent.java
│           │               │   │   └── HostsEditorModule.java
│           │               │   ├── log/
│           │               │   │   └── ReleaseTree.java
│           │               │   └── util/
│           │               │       ├── Compatibility.java
│           │               │       ├── InetAddresses.java
│           │               │       └── ThreadPreconditions.java
│           │               ├── event/
│           │               │   ├── CreatedHostEvent.java
│           │               │   ├── LoadingEvent.java
│           │               │   ├── RefreshHostsEvent.java
│           │               │   ├── StartAddEditActivityEvent.java
│           │               │   └── TaskCompletedEvent.java
│           │               ├── task/
│           │               │   ├── AddEditHostAsync.java
│           │               │   ├── GenericTaskAsync.java
│           │               │   ├── ListHostsAsync.java
│           │               │   ├── RemoveHostsAsync.java
│           │               │   └── ToggleHostsAsync.java
│           │               └── ui/
│           │                   ├── BaseActivity.java
│           │                   ├── BaseFragment.java
│           │                   ├── about/
│           │                   │   └── AboutDialogFragment.java
│           │                   ├── addedit/
│           │                   │   ├── AddEditHostActivity.java
│           │                   │   └── AddEditHostFragment.java
│           │                   ├── list/
│           │                   │   ├── ListHostsActivity.java
│           │                   │   ├── ListHostsAdapter.java
│           │                   │   ├── ListHostsFragment.java
│           │                   │   └── ListHostsSearchFilter.java
│           │                   └── widget/
│           │                       ├── CheckableHostItem.java
│           │                       ├── InertCheckBox.java
│           │                       ├── TypefacedButton.java
│           │                       └── TypefacedTextView.java
│           └── res/
│               ├── layout/
│               │   ├── about_dialog.xml
│               │   ├── add_edit_host_layout.xml
│               │   ├── checkable_host_item.xml
│               │   ├── list_hosts_empty.xml
│               │   ├── list_hosts_fragment.xml
│               │   └── list_hosts_layout.xml
│               ├── menu/
│               │   ├── add_edit_menu.xml
│               │   ├── list_contextual_actions.xml
│               │   └── list_menu.xml
│               ├── values/
│               │   ├── attrs.xml
│               │   ├── colors.xml
│               │   ├── dimens.xml
│               │   ├── strings.xml
│               │   └── styles.xml
│               └── values-sw720dp-land/
│                   └── dimens.xml
├── build.gradle
├── gradle/
│   └── wrapper/
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle
Download .txt
SYMBOL INDEX (205 symbols across 32 files)

FILE: app/src/main/java/com/nilhcem/hostseditor/HostsEditorApplication.java
  class HostsEditorApplication (line 13) | public class HostsEditorApplication extends Application {
    method get (line 17) | public static HostsEditorApplication get(Context context) {
    method onCreate (line 21) | @Override
    method component (line 28) | public HostsEditorComponent component() {
    method initLogger (line 32) | private void initLogger() {
    method initGraph (line 40) | private void initGraph() {

FILE: app/src/main/java/com/nilhcem/hostseditor/core/Host.java
  class Host (line 12) | public class Host implements Parcelable {
    method Host (line 25) | public Host(String ip, String hostName, String comment, boolean isComm...
    method merge (line 33) | public void merge(Host src) {
    method getIp (line 41) | public String getIp() {
    method getHostName (line 45) | public String getHostName() {
    method getComment (line 49) | public String getComment() {
    method isValid (line 53) | public boolean isValid() {
    method isCommented (line 57) | public boolean isCommented() {
    method toggleComment (line 61) | public void toggleComment() {
    method toString (line 65) | @Override
    method fromString (line 84) | public static Host fromString(String line) {
    method createFromParcel (line 109) | @Override
    method newArray (line 114) | @Override
    method describeContents (line 120) | @Override
    method writeToParcel (line 125) | @Override
    method Host (line 134) | private Host(Parcel in) {
    method hashCode (line 142) | @Override
    method equals (line 154) | @Override

FILE: app/src/main/java/com/nilhcem/hostseditor/core/HostsManager.java
  class HostsManager (line 28) | @Singleton
    method HostsManager (line 45) | @Inject
    method getHosts (line 56) | public synchronized List<Host> getHosts(boolean forceRefresh) {
    method saveHosts (line 87) | public synchronized boolean saveHosts(Context appContext) {
    method filterHosts (line 145) | public List<Host> filterHosts(CharSequence constraint) {
    method createTempHostsFile (line 168) | private boolean createTempHostsFile(Context appContext) {
    method runRootCommand (line 200) | private void runRootCommand(String command, String uniqueArg) throws I...

FILE: app/src/main/java/com/nilhcem/hostseditor/core/dagger/HostsEditorComponent.java
  type HostsEditorComponent (line 13) | @Singleton
    method inject (line 21) | void inject(BaseActivity activity);
    method inject (line 23) | void inject(GenericTaskAsync async);
    method inject (line 25) | void inject(AddEditHostFragment fragment);
    method inject (line 27) | void inject(ListHostsAsync async);
    method inject (line 29) | void inject(ListHostsFragment fragment);

FILE: app/src/main/java/com/nilhcem/hostseditor/core/dagger/HostsEditorModule.java
  class HostsEditorModule (line 10) | @Module
    method provideBus (line 13) | @Provides @Singleton Bus provideBus() {

FILE: app/src/main/java/com/nilhcem/hostseditor/core/log/ReleaseTree.java
  class ReleaseTree (line 7) | public class ReleaseTree extends Timber.Tree {
    method log (line 9) | @Override

FILE: app/src/main/java/com/nilhcem/hostseditor/core/util/Compatibility.java
  class Compatibility (line 12) | public class Compatibility {
    method Compatibility (line 14) | private Compatibility() {
    method isCompatible (line 24) | private static boolean isCompatible(int apiLevel) {
    method getScreenDimensions (line 28) | @SuppressWarnings("deprecation")
    method convertDpToPixel (line 50) | public static float convertDpToPixel(float dp, Context context) {
    method convertDpToIntPixel (line 56) | public static int convertDpToIntPixel(float dp, Context context) {

FILE: app/src/main/java/com/nilhcem/hostseditor/core/util/InetAddresses.java
  class InetAddresses (line 26) | public final class InetAddresses {
    method InetAddresses (line 31) | private InetAddresses() {
    method isInetAddress (line 41) | public static boolean isInetAddress(String ipString) {
    method ipStringToBytes (line 45) | private static byte[] ipStringToBytes(String ipString) {
    method textToNumericFormatV4 (line 78) | private static byte[] textToNumericFormatV4(String ipString) {
    method textToNumericFormatV6 (line 96) | private static byte[] textToNumericFormatV6(String ipString) {
    method convertDottedQuadToHex (line 159) | private static String convertDottedQuadToHex(String ipString) {
    method parseOctet (line 174) | private static byte parseOctet(String ipPart) {
    method parseHextet (line 185) | private static short parseHextet(String ipPart) {

FILE: app/src/main/java/com/nilhcem/hostseditor/core/util/ThreadPreconditions.java
  class ThreadPreconditions (line 7) | public final class ThreadPreconditions {
    method ThreadPreconditions (line 9) | private ThreadPreconditions() {
    method checkOnMainThread (line 13) | public static void checkOnMainThread() {

FILE: app/src/main/java/com/nilhcem/hostseditor/event/CreatedHostEvent.java
  class CreatedHostEvent (line 5) | public class CreatedHostEvent {
    method CreatedHostEvent (line 17) | public CreatedHostEvent(Host original, Host edited) {

FILE: app/src/main/java/com/nilhcem/hostseditor/event/LoadingEvent.java
  class LoadingEvent (line 5) | public class LoadingEvent {
    method LoadingEvent (line 11) | public LoadingEvent() {
    method LoadingEvent (line 15) | public LoadingEvent(boolean isLoading, int messageRes) {
    method LoadingEvent (line 21) | public LoadingEvent(boolean isLoading, String message) {
    method isLoading (line 27) | public boolean isLoading() {
    method getMessage (line 31) | public String getMessage(Context context) {

FILE: app/src/main/java/com/nilhcem/hostseditor/event/RefreshHostsEvent.java
  class RefreshHostsEvent (line 10) | public class RefreshHostsEvent {
    method RefreshHostsEvent (line 14) | public RefreshHostsEvent(List<Host> refreshedHosts) {

FILE: app/src/main/java/com/nilhcem/hostseditor/event/StartAddEditActivityEvent.java
  class StartAddEditActivityEvent (line 5) | public class StartAddEditActivityEvent {
    method StartAddEditActivityEvent (line 12) | public StartAddEditActivityEvent(Host addEditHost) {

FILE: app/src/main/java/com/nilhcem/hostseditor/event/TaskCompletedEvent.java
  class TaskCompletedEvent (line 3) | public class TaskCompletedEvent {
    method TaskCompletedEvent (line 8) | public TaskCompletedEvent(String pTag, boolean pIsSuccessful) {

FILE: app/src/main/java/com/nilhcem/hostseditor/task/AddEditHostAsync.java
  class AddEditHostAsync (line 15) | public class AddEditHostAsync extends GenericTaskAsync {
    method AddEditHostAsync (line 17) | public AddEditHostAsync(Context appContext, boolean flagMsg) {
    method process (line 21) | @Override
    method getLoadingMsgRes (line 35) | @Override

FILE: app/src/main/java/com/nilhcem/hostseditor/task/GenericTaskAsync.java
  class GenericTaskAsync (line 17) | public abstract class GenericTaskAsync extends AsyncTask<Host, Void, Voi...
    method GenericTaskAsync (line 25) | public GenericTaskAsync(Context appContext, boolean flagMsg) {
    method onPreExecute (line 31) | @Override
    method doInBackground (line 37) | @Override
    method onPostExecute (line 46) | @Override
    method onCancelled (line 53) | @Override
    method process (line 65) | protected abstract void process(Host... params);
    method getLoadingMsgRes (line 67) | protected abstract int getLoadingMsgRes();

FILE: app/src/main/java/com/nilhcem/hostseditor/task/ListHostsAsync.java
  class ListHostsAsync (line 22) | public class ListHostsAsync extends AsyncTask<Boolean, Void, List<Host>> {
    method ListHostsAsync (line 27) | public ListHostsAsync(Context context) {
    method onPreExecute (line 31) | @Override
    method doInBackground (line 37) | @Override
    method onPostExecute (line 56) | @Override

FILE: app/src/main/java/com/nilhcem/hostseditor/task/RemoveHostsAsync.java
  class RemoveHostsAsync (line 15) | public class RemoveHostsAsync extends GenericTaskAsync {
    method RemoveHostsAsync (line 17) | public RemoveHostsAsync(Context appContext, boolean flagMsg) {
    method process (line 21) | @Override
    method getLoadingMsgRes (line 31) | @Override

FILE: app/src/main/java/com/nilhcem/hostseditor/task/ToggleHostsAsync.java
  class ToggleHostsAsync (line 13) | public class ToggleHostsAsync extends GenericTaskAsync {
    method ToggleHostsAsync (line 15) | public ToggleHostsAsync(Context appContext, boolean flagMsg) {
    method process (line 19) | @Override
    method getLoadingMsgRes (line 28) | @Override

FILE: app/src/main/java/com/nilhcem/hostseditor/ui/BaseActivity.java
  class BaseActivity (line 14) | public abstract class BaseActivity extends SherlockFragmentActivity {
    method onCreate (line 19) | @Override
    method onResume (line 26) | @Override
    method onPause (line 32) | @Override

FILE: app/src/main/java/com/nilhcem/hostseditor/ui/BaseFragment.java
  class BaseFragment (line 17) | public class BaseFragment extends SherlockFragment {
    method onAttach (line 24) | @Override
    method onCreate (line 35) | @Override
    method onResume (line 41) | @Override
    method onPause (line 47) | @Override
    method onDetach (line 53) | @Override

FILE: app/src/main/java/com/nilhcem/hostseditor/ui/about/AboutDialogFragment.java
  class AboutDialogFragment (line 16) | public class AboutDialogFragment extends SherlockDialogFragment {
    method onCreateView (line 21) | @Override
    method onDestroyView (line 29) | @Override
    method openGitHubUrl (line 35) | @OnClick(R.id.aboutGitHub)

FILE: app/src/main/java/com/nilhcem/hostseditor/ui/addedit/AddEditHostActivity.java
  class AddEditHostActivity (line 18) | public class AddEditHostActivity extends BaseActivity {
    method onCreate (line 25) | @Override
    method onCreateOptionsMenu (line 43) | @Override
    method onPrepareOptionsMenu (line 49) | @Override
    method onOptionsItemSelected (line 60) | @Override
    method onHostCreatedFromFragment (line 76) | @Subscribe
    method getHostFromIntent (line 85) | private Host getHostFromIntent() {
    method initActionBar (line 95) | private void initActionBar(Host hostToEdit) {

FILE: app/src/main/java/com/nilhcem/hostseditor/ui/addedit/AddEditHostFragment.java
  class AddEditHostFragment (line 26) | public class AddEditHostFragment extends BaseFragment {
    method newInstance (line 42) | public static AddEditHostFragment newInstance(Host hostToEdit) {
    method onCreate (line 53) | @Override
    method onCreateView (line 63) | @Override
    method onStop (line 84) | @Override
    method onDestroyView (line 92) | @Override
    method onAddEditHostButtonClicked (line 98) | @OnClick(R.id.addEditHostButton)
    method hasComment (line 129) | public boolean hasComment() {
    method toggleCommentVisibility (line 133) | public void toggleCommentVisibility() {
    method checkFormErrors (line 146) | private int checkFormErrors(String ip, String hostname) {

FILE: app/src/main/java/com/nilhcem/hostseditor/ui/list/ListHostsActivity.java
  class ListHostsActivity (line 29) | public class ListHostsActivity extends BaseActivity {
    method onCreate (line 44) | @Override
    method onCreateOptionsMenu (line 58) | @Override
    method onResume (line 86) | @Override
    method onKeyDown (line 92) | @Override
    method onOptionsItemSelected (line 110) | @Override
    method onActivityResult (line 130) | @Override
    method onSaveInstanceState (line 147) | @Override
    method onRestoreInstanceState (line 155) | @Override
    method onDestroy (line 170) | @Override
    method onStartAddEditActivityEvent (line 176) | @Subscribe
    method onLoadingEvent (line 184) | @Subscribe
    method setSearchQuery (line 208) | private void setSearchQuery(String searchQuery) {
    method setActionBarTitle (line 213) | private void setActionBarTitle() {
    method displayAboutDialog (line 224) | private void displayAboutDialog() {

FILE: app/src/main/java/com/nilhcem/hostseditor/ui/list/ListHostsAdapter.java
  class ListHostsAdapter (line 23) | public class ListHostsAdapter extends BaseAdapter implements Filterable {
    method ListHostsAdapter (line 33) | @Inject public ListHostsAdapter(ListHostsSearchFilter searchFilter) {
    method init (line 37) | public void init(Context appContext) {
    method updateHosts (line 41) | public void updateHosts(List<Host> hosts) {
    method computeViewWidths (line 51) | public void computeViewWidths(Context context) {
    method getCount (line 83) | @Override
    method getItem (line 88) | @Override
    method getItemId (line 93) | @Override
    method getView (line 98) | @Override
    method getFilter (line 113) | @Override

FILE: app/src/main/java/com/nilhcem/hostseditor/ui/list/ListHostsFragment.java
  class ListHostsFragment (line 43) | public class ListHostsFragment extends BaseFragment implements OnItemCli...
    method onCreate (line 53) | @Override
    method onCreateView (line 60) | @Override
    method onPause (line 87) | @Override
    method onDestroyView (line 97) | @Override
    method onItemClick (line 103) | @Override
    method onItemLongClick (line 115) | @Override
    method onTaskFinished (line 125) | @Subscribe
    method onHostsRefreshed (line 135) | @Subscribe
    method addEditHost (line 143) | public void addEditHost(boolean addMode, Host[] hosts) {
    method refreshHosts (line 147) | public void refreshHosts(boolean forceRefresh) {
    method selectAll (line 151) | public void selectAll() {
    method filterList (line 162) | public void filterList(String filter) {
    method displayActionMode (line 166) | private void displayActionMode(int nbCheckedElements) {
    class ModeCallback (line 181) | private final class ModeCallback implements ActionMode.Callback {
      method onCreateActionMode (line 183) | @Override
      method onPrepareActionMode (line 190) | @Override
      method onDestroyActionMode (line 196) | @Override
      method onActionItemClicked (line 205) | @Override
      method getSelectedItems (line 226) | private Host[] getSelectedItems() {
    method displayDeleteConfirmationDialog (line 240) | private void displayDeleteConfirmationDialog(final Host[] selectedItem...
    method displayErrorDialog (line 260) | private void displayErrorDialog() {
    method finishActionMode (line 281) | private void finishActionMode() {

FILE: app/src/main/java/com/nilhcem/hostseditor/ui/list/ListHostsSearchFilter.java
  class ListHostsSearchFilter (line 17) | public class ListHostsSearchFilter extends Filter {
    method ListHostsSearchFilter (line 22) | @Inject public ListHostsSearchFilter(Bus bus, HostsManager hostsManage...
    method publishResults (line 27) | @SuppressWarnings("unchecked")
    method performFiltering (line 36) | @Override

FILE: app/src/main/java/com/nilhcem/hostseditor/ui/widget/CheckableHostItem.java
  class CheckableHostItem (line 25) | public class CheckableHostItem extends RelativeLayout implements Checkab...
    method CheckableHostItem (line 35) | public CheckableHostItem(Context context) {
    method initLayout (line 40) | private void initLayout(Context context) {
    method init (line 50) | public void init(Host host, int ipMinWidth, int ipMaxWidth) {
    method isChecked (line 78) | @Override
    method setChecked (line 83) | @Override
    method toggle (line 88) | @Override

FILE: app/src/main/java/com/nilhcem/hostseditor/ui/widget/InertCheckBox.java
  class InertCheckBox (line 12) | public class InertCheckBox extends CheckBox {
    method InertCheckBox (line 14) | public InertCheckBox(Context context, AttributeSet attrs, int defStyle) {
    method InertCheckBox (line 18) | public InertCheckBox(Context context, AttributeSet attrs) {
    method InertCheckBox (line 22) | public InertCheckBox(Context context) {
    method onTouchEvent (line 26) | @Override
    method onKeyDown (line 31) | @Override
    method onKeyMultiple (line 36) | @Override
    method onKeyPreIme (line 41) | @Override
    method onKeyShortcut (line 46) | @Override
    method onKeyUp (line 51) | @Override
    method onTrackballEvent (line 56) | @Override

FILE: app/src/main/java/com/nilhcem/hostseditor/ui/widget/TypefacedButton.java
  class TypefacedButton (line 12) | public final class TypefacedButton extends Button {
    method TypefacedButton (line 14) | public TypefacedButton(Context context, AttributeSet attrs) {

FILE: app/src/main/java/com/nilhcem/hostseditor/ui/widget/TypefacedTextView.java
  class TypefacedTextView (line 16) | public final class TypefacedTextView extends TextView {
    method TypefacedTextView (line 18) | public TypefacedTextView(Context context, AttributeSet attrs) {
    method applyFont (line 29) | static void applyFont(Context context, AttributeSet attrs, TextView vi...
Condensed preview — 59 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (138K chars).
[
  {
    "path": ".gitignore",
    "chars": 397,
    "preview": "# Temporary files\n*~\n\\#*\ntmp/\n\n# Build directory\nbuild/\n\n# Eclipse files\n.metadata\n.pmd\n.apt_generated/\n\n# IntelliJ file"
  },
  {
    "path": "LICENSE.txt",
    "chars": 11358,
    "preview": "\n                                 Apache License\n                           Version 2.0, January 2004\n                  "
  },
  {
    "path": "README.md",
    "chars": 12832,
    "preview": "# Hosts Editor for Android\n\nThis repository contains the source code for the Hosts-editor Android app.\n\nIt is available "
  },
  {
    "path": "app/build.gradle",
    "chars": 1358,
    "preview": "apply plugin: 'com.android.application'\napply plugin: 'com.neenbedankt.android-apt'\n\nandroid {\n    compileSdkVersion 22\n"
  },
  {
    "path": "app/src/main/AndroidManifest.xml",
    "chars": 982,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    package="
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/HostsEditorApplication.java",
    "chars": 1203,
    "preview": "package com.nilhcem.hostseditor;\n\nimport android.app.Application;\nimport android.content.Context;\n\nimport com.nilhcem.ho"
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/core/Host.java",
    "chars": 5607,
    "preview": "package com.nilhcem.hostseditor.core;\n\nimport android.os.Parcel;\nimport android.os.Parcelable;\nimport android.text.TextU"
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/core/HostsManager.java",
    "chars": 7293,
    "preview": "package com.nilhcem.hostseditor.core;\n\nimport android.content.Context;\n\nimport com.stericson.RootShell.RootShell;\nimport"
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/core/dagger/HostsEditorComponent.java",
    "chars": 734,
    "preview": "package com.nilhcem.hostseditor.core.dagger;\n\nimport com.nilhcem.hostseditor.task.GenericTaskAsync;\nimport com.nilhcem.h"
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/core/dagger/HostsEditorModule.java",
    "chars": 276,
    "preview": "package com.nilhcem.hostseditor.core.dagger;\n\nimport com.squareup.otto.Bus;\n\nimport javax.inject.Singleton;\n\nimport dagg"
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/core/log/ReleaseTree.java",
    "chars": 376,
    "preview": "package com.nilhcem.hostseditor.core.log;\n\nimport android.util.Log;\n\nimport timber.log.Timber;\n\npublic class ReleaseTree"
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/core/util/Compatibility.java",
    "chars": 2072,
    "preview": "package com.nilhcem.hostseditor.core.util;\n\nimport android.annotation.TargetApi;\nimport android.content.Context;\nimport "
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/core/util/InetAddresses.java",
    "chars": 7091,
    "preview": "/*\n * Copyright (C) 2008 The Guava Authors\n *\n * NOTICE: THIS FILE WAS MODIFIED (removed all not required for the projec"
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/core/util/ThreadPreconditions.java",
    "chars": 544,
    "preview": "package com.nilhcem.hostseditor.core.util;\n\nimport android.os.Looper;\n\nimport com.nilhcem.hostseditor.BuildConfig;\n\npubl"
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/event/CreatedHostEvent.java",
    "chars": 509,
    "preview": "package com.nilhcem.hostseditor.event;\n\nimport com.nilhcem.hostseditor.core.Host;\n\npublic class CreatedHostEvent {\n\n    "
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/event/LoadingEvent.java",
    "chars": 824,
    "preview": "package com.nilhcem.hostseditor.event;\n\nimport android.content.Context;\n\npublic class LoadingEvent {\n\n    private final "
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/event/RefreshHostsEvent.java",
    "chars": 335,
    "preview": "package com.nilhcem.hostseditor.event;\n\nimport com.nilhcem.hostseditor.core.Host;\n\nimport java.util.List;\n\n/**\n * Sent t"
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/event/StartAddEditActivityEvent.java",
    "chars": 336,
    "preview": "package com.nilhcem.hostseditor.event;\n\nimport com.nilhcem.hostseditor.core.Host;\n\npublic class StartAddEditActivityEven"
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/event/TaskCompletedEvent.java",
    "chars": 278,
    "preview": "package com.nilhcem.hostseditor.event;\n\npublic class TaskCompletedEvent {\n\n    public final String tag;\n    public final"
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/task/AddEditHostAsync.java",
    "chars": 988,
    "preview": "package com.nilhcem.hostseditor.task;\n\nimport android.content.Context;\n\nimport com.nilhcem.hostseditor.R;\nimport com.nil"
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/task/GenericTaskAsync.java",
    "chars": 1982,
    "preview": "package com.nilhcem.hostseditor.task;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.nilhcem."
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/task/ListHostsAsync.java",
    "chars": 1700,
    "preview": "package com.nilhcem.hostseditor.task;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.nilhcem."
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/task/RemoveHostsAsync.java",
    "chars": 873,
    "preview": "package com.nilhcem.hostseditor.task;\n\nimport android.content.Context;\n\nimport com.nilhcem.hostseditor.R;\nimport com.nil"
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/task/ToggleHostsAsync.java",
    "chars": 793,
    "preview": "package com.nilhcem.hostseditor.task;\n\nimport android.content.Context;\n\nimport com.nilhcem.hostseditor.R;\nimport com.nil"
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/ui/BaseActivity.java",
    "chars": 857,
    "preview": "package com.nilhcem.hostseditor.ui;\n\nimport android.os.Bundle;\n\nimport com.actionbarsherlock.app.SherlockFragmentActivit"
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/ui/BaseFragment.java",
    "chars": 1505,
    "preview": "package com.nilhcem.hostseditor.ui;\n\nimport android.app.Activity;\nimport android.os.Bundle;\n\nimport com.actionbarsherloc"
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/ui/about/AboutDialogFragment.java",
    "chars": 1240,
    "preview": "package com.nilhcem.hostseditor.ui.about;\n\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Bund"
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/ui/addedit/AddEditHostActivity.java",
    "chars": 3750,
    "preview": "package com.nilhcem.hostseditor.ui.addedit;\n\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.sup"
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/ui/addedit/AddEditHostFragment.java",
    "chars": 5234,
    "preview": "package com.nilhcem.hostseditor.ui.addedit;\n\nimport android.app.AlertDialog;\nimport android.content.DialogInterface;\nimp"
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/ui/list/ListHostsActivity.java",
    "chars": 8165,
    "preview": "package com.nilhcem.hostseditor.ui.list;\n\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.suppor"
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/ui/list/ListHostsAdapter.java",
    "chars": 3366,
    "preview": "package com.nilhcem.hostseditor.ui.list;\n\nimport android.content.Context;\nimport android.view.View;\nimport android.view."
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/ui/list/ListHostsFragment.java",
    "chars": 9593,
    "preview": "package com.nilhcem.hostseditor.ui.list;\n\nimport android.app.AlertDialog;\nimport android.app.Dialog;\nimport android.cont"
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/ui/list/ListHostsSearchFilter.java",
    "chars": 1319,
    "preview": "package com.nilhcem.hostseditor.ui.list;\n\nimport android.text.TextUtils;\nimport android.widget.Filter;\n\nimport com.nilhc"
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/ui/widget/CheckableHostItem.java",
    "chars": 2729,
    "preview": "package com.nilhcem.hostseditor.ui.widget;\n\nimport android.content.Context;\nimport android.content.res.Resources;\nimport"
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/ui/widget/InertCheckBox.java",
    "chars": 1394,
    "preview": "package com.nilhcem.hostseditor.ui.widget;\n\nimport android.content.Context;\nimport android.util.AttributeSet;\nimport and"
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/ui/widget/TypefacedButton.java",
    "chars": 426,
    "preview": "package com.nilhcem.hostseditor.ui.widget;\n\nimport android.content.Context;\nimport android.util.AttributeSet;\nimport and"
  },
  {
    "path": "app/src/main/java/com/nilhcem/hostseditor/ui/widget/TypefacedTextView.java",
    "chars": 1350,
    "preview": "package com.nilhcem.hostseditor.ui.widget;\n\nimport android.content.Context;\nimport android.content.res.TypedArray;\nimpor"
  },
  {
    "path": "app/src/main/res/layout/about_dialog.xml",
    "chars": 1673,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<ScrollView\n    xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xm"
  },
  {
    "path": "app/src/main/res/layout/add_edit_host_layout.xml",
    "chars": 3693,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<ScrollView\n    xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xm"
  },
  {
    "path": "app/src/main/res/layout/checkable_host_item.xml",
    "chars": 2324,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n    xmlns:android=\"http://schemas.android.com/apk/res/android\"\n  "
  },
  {
    "path": "app/src/main/res/layout/list_hosts_empty.xml",
    "chars": 1223,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<ScrollView\n    xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xm"
  },
  {
    "path": "app/src/main/res/layout/list_hosts_fragment.xml",
    "chars": 780,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<FrameLayout\n    xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    x"
  },
  {
    "path": "app/src/main/res/layout/list_hosts_layout.xml",
    "chars": 1354,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout\n    xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    "
  },
  {
    "path": "app/src/main/res/menu/add_edit_menu.xml",
    "chars": 305,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<menu xmlns:android=\"http://schemas.android.com/apk/res/android\">\n\n    <!-- Add /"
  },
  {
    "path": "app/src/main/res/menu/list_contextual_actions.xml",
    "chars": 978,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<menu xmlns:android=\"http://schemas.android.com/apk/res/android\">\n\n    <!-- Edit "
  },
  {
    "path": "app/src/main/res/menu/list_menu.xml",
    "chars": 1305,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<menu xmlns:android=\"http://schemas.android.com/apk/res/android\">\n\n    <!-- Searc"
  },
  {
    "path": "app/src/main/res/values/attrs.xml",
    "chars": 186,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n    <declare-styleable name=\"TypefacedTextView\">\n        <attr name=\""
  },
  {
    "path": "app/src/main/res/values/colors.xml",
    "chars": 172,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n    <color name=\"list_hosts_entry\">#fff3f3f3</color>\n    <color name="
  },
  {
    "path": "app/src/main/res/values/dimens.xml",
    "chars": 380,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n    <!-- Default screen margins, per the Android Design guidelines --"
  },
  {
    "path": "app/src/main/res/values/strings.xml",
    "chars": 3225,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n    <string name=\"app_name\">Hosts Editor</string>\n\n    <!-- Action ba"
  },
  {
    "path": "app/src/main/res/values/styles.xml",
    "chars": 719,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n    <!--\n        Base application theme, dependent on API level. This"
  },
  {
    "path": "app/src/main/res/values-sw720dp-land/dimens.xml",
    "chars": 306,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n    <!--\n         Customize dimensions originally defined in res/valu"
  },
  {
    "path": "build.gradle",
    "chars": 369,
    "preview": "// Top-level build file where you can add configuration options common to all sub-projects/modules.\n\nbuildscript {\n    r"
  },
  {
    "path": "gradle/wrapper/gradle-wrapper.properties",
    "chars": 230,
    "preview": "#Mon Jul 13 13:14:00 GMT 2015\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_"
  },
  {
    "path": "gradlew",
    "chars": 5080,
    "preview": "#!/usr/bin/env bash\n\n##############################################################################\n##\n##  Gradle start "
  },
  {
    "path": "gradlew.bat",
    "chars": 2404,
    "preview": "@if \"%DEBUG%\" == \"\" @echo off\r\n@rem ##########################################################################\r\n@rem\r\n@r"
  },
  {
    "path": "settings.gradle",
    "chars": 15,
    "preview": "include ':app'\n"
  }
]

// ... and 2 more files (download for full content)

About this extraction

This page contains the full source code of the Nilhcem/hosts-editor-android GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 59 files (125.4 KB), approximately 30.6k tokens, and a symbol index with 205 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!