Compare commits

..
108 Commits
Author SHA1 Message Date
Max Lv c842f7fd41 Bump version 2016-10-03 19:47:53 +08:00
Max Lv c2f02994f8 Refine DNS server with China List 2016-10-02 19:36:53 +08:00
Max Lv 54247d6b2b Update DNS 2016-09-30 20:48:20 +08:00
Max Lv e7fbfd668d Update config name 2016-09-30 19:43:30 +08:00
Max Lv b6d0af1ec3 Fix #910 2016-09-30 19:28:03 +08:00
Max Lv f58301b80b Bump version 2016-09-30 13:49:16 +08:00
Max Lv 792870b289 Update ACL 2016-09-29 11:53:40 +08:00
Max Lv 3b6eff6d9d Fix #905 2016-09-28 14:36:36 +08:00
Max Lv 528fea136d Clean up 2016-09-28 10:40:16 +08:00
Mygod 5d7e88310b Update dependencies 2016-09-26 19:51:38 +08:00
Max Lv 8c4508843b Refine DNS resolution 2016-09-26 13:54:34 +08:00
Max Lv 79acf14069 Reduce the timeout of default DNS server 2016-09-26 09:48:42 +08:00
Max Lv 5f43500b9f Fix auto-start again 2016-09-26 07:51:54 +08:00
Max Lv 8b4a8a92f2 Bump version 2016-09-25 18:29:41 +08:00
Max Lv 7887d18f6f Clean up 2016-09-25 17:40:53 +08:00
Max Lv fb960d0664 Fix #900 2016-09-25 17:32:16 +08:00
Max Lv 9ed320d33b Fix #901 2016-09-25 17:29:27 +08:00
Max Lv 2599e88a81 Add fake demographics 2016-09-24 11:34:08 +08:00
Max Lv ac0a8c7600 Bump version 2016-09-24 10:59:24 +08:00
Max Lv 63fc69f495 Update shadowsocks-libev 2016-09-23 12:26:38 +08:00
Mygod 5761962754 Fix russian translation 2016-09-23 00:44:02 +08:00
Mygod 20506eeda8 Migrate to preference support library
Fix #875. Step 1 for #762.

Note: This will make main UI very different on 4.4.
2016-09-23 00:30:39 +08:00
Mygod dd63bda2cd Don't suppress log in debug builds 2016-09-22 21:18:02 +08:00
Mygod e6d7a0855d Suggest different local ports automatically in MU mode
Refine #885
2016-09-22 20:38:33 +08:00
Mygod 4da89cd18e Add support for ROM with TFO enabled as default 2016-09-22 20:16:22 +08:00
Mygod 66250eb66b Update GMS 2016-09-22 20:16:14 +08:00
Max Lv 005c3443ae Remove :bg from RunnerService 2016-09-22 10:13:04 +08:00
Max Lv 6b60f276b2 Enable UDP forwarding in ss-tunnel by default 2016-09-22 09:36:30 +08:00
Max Lv 0edbe01237 Fix #894 2016-09-22 09:34:35 +08:00
Max Lv c87882e5d4 Fully disable IPv6 resolving in IPv4 mode, #890 2016-09-21 15:30:34 +08:00
Max Lv 8f80fbfd4a Bump version 2016-09-21 14:08:49 +08:00
Max Lv 6ec8117e1c Update shadowsocks-libev 2016-09-20 18:01:10 +08:00
Max Lv 3c68a26794 Update DNS forwarding 2016-09-20 08:40:13 +08:00
Max Lv fda89933d0 Disable DNS forwarding in GFWList/ChinaList mode 2016-09-19 17:18:39 +08:00
Max Lv d8f721db3b Refine DNS resolve of GFWList and ChinaList, #887 2016-09-19 09:58:36 +08:00
Max Lv 28339ce7c1 Update DNS 2016-09-19 09:10:47 +08:00
Max Lv edda3179dd Add China List, close #886 2016-09-18 18:56:04 +08:00
Mygod 1d79990656 Remove workaround for libsuperuser#55 2016-09-15 12:22:21 +08:00
Mygod 2a47362195 Fix profile name not updated in ShadowsocksTileService 2016-09-15 00:11:37 +08:00
Mygod 02d5951f8b Auto reset when downgrading
While it's theoretically impossible to downgrade without reinstalling the app, there are ways to bypass this mechanism. And don't forget users can restore their app data as well.
2016-09-14 22:37:26 +08:00
Mygod b126c62365 Fix a crash in AppManager 2016-09-14 18:16:44 +08:00
Mygod bbaf1779ea Add missing translation for Russian 2016-09-14 17:18:10 +08:00
Max Lv 65ddd6f5d8 Bump version 2016-09-14 14:57:02 +08:00
Max Lv 772bc18eb8 Bump version 2016-09-12 10:28:25 +08:00
Max Lv d503818169 Add missing translation 2016-09-12 10:27:55 +08:00
Max Lv b209e73386 Bump version 2016-09-12 10:11:16 +08:00
Max Lv 6c381b0ecc Fix a crash reported by Goolge Play 2016-09-12 09:49:17 +08:00
Max Lv e3f0fa6756 Fix #871 2016-09-09 22:13:51 +08:00
Max Lv 35cb273592 SuppressLint 2016-09-09 16:47:47 +08:00
Max Lv b76f410c34 Refine header parser 2016-09-09 10:30:22 +08:00
Max Lv d3678531b7 Bump version 2016-09-08 19:23:50 +08:00
Max Lv 122ca599de Add GFWList support 2016-09-08 18:36:39 +08:00
Max Lv 96fcec788c Add issue template 2016-09-05 16:24:51 +08:00
Max Lv 1c67b39a3e Bump version 2016-09-04 10:31:33 +08:00
Max Lv 30fea4a705 Merge branch 'master' of github.com:shadowsocks/shadowsocks-android 2016-09-04 10:19:15 +08:00
Max Lv 7c0763c78a Fix #848 2016-09-01 14:00:23 +08:00
Mygod b8c593b110 Fix crash in GuardedProcess 2016-08-29 13:57:25 +08:00
Mygod 782af959a0 Fix #844 2016-08-29 12:54:55 +08:00
Max Lv 6df227d231 Update kcptun 2016-08-28 18:11:29 +08:00
Max Lv 5b1432e4e8 Handle stdout/stderr of GuardedProcess properly 2016-08-28 17:42:19 +08:00
Max Lv 7ca4e4ec74 Enable android log for kcptun 2016-08-28 08:00:35 +08:00
Mygod 655ef1eed6 Refine TFO 2016-08-27 23:39:06 +08:00
Mygod 04be60577a Revert "Revert "Fix #839 #838""
This reverts commit 264b177b38.
2016-08-27 23:32:13 +08:00
Mygod 63d2ec7b02 Revert "Fix #838 #839"
This reverts commit 32f4d6af47.

Never mind then! I changed my mind.
2016-08-27 23:31:50 +08:00
Mygod 06b6afd557 Update sbt-android 2016-08-27 23:23:58 +08:00
Mygod 32f4d6af47 Fix #838 #839 2016-08-27 23:23:08 +08:00
Mygod 264b177b38 Revert "Fix #839 #838"
This reverts commit 069cc152ca.
2016-08-27 23:15:25 +08:00
Syrone Wong 67a1c5460a Drop redundant rule (#840)
[info] Android NDK: WARNING:jni/Android.mk:mbedtls: LOCAL_LDLIBS is always ignored for static libraries
2016-08-27 20:42:16 +08:00
Max Lv a20b7821f2 Bump version 2016-08-27 17:11:05 +08:00
Max Lv 069cc152ca Fix #839 #838 2016-08-27 17:10:12 +08:00
Max Lv 7b57be669c Bump version 2016-08-27 07:56:10 +08:00
Max Lv 2f051e9eed Update kcptun 2016-08-23 13:52:48 +08:00
Mygod 8d1d018fe1 Remove boot script to disable fast open
Fix #828.
2016-08-23 13:48:05 +08:00
Mygod 3c5bc27750 Refine mount command
Fix #826.
2016-08-22 21:10:41 +08:00
Mygod 6c047eca8e Add error message if failed 2016-08-22 21:10:33 +08:00
Max Lv a31e753841 Update golang 2016-08-21 11:14:09 +08:00
Max Lv c94c509931 KCP with session ID (#823)
* Add sid support

* Update kcptun
2016-08-20 14:09:22 +08:00
Mygod 41417a7546 Refine regex in KcpCliPreference 2016-08-19 19:52:34 +08:00
Mygod 25cfb1623a Remove all the extravagant styles
These styles are either introduced by @AnyOfYou, or exist because of a bug in Android support library. Anyway they can be removed now.
2016-08-19 19:49:43 +08:00
Max Lv c9ce515cca Bump version 2016-08-19 17:57:53 +08:00
Mygod 7802a50603 Fix Travis dependency problem once and for all 2016-08-19 15:53:59 +08:00
Mygod 680a6594f6 Drop compatibility RTL support for Jelly Bean 2016-08-19 15:39:03 +08:00
Mygod b7367835b0 Update support lib 2016-08-19 15:32:02 +08:00
Mygod 25bd5347eb Refine #816 and error handling in startRunner 2016-08-19 15:23:43 +08:00
Max Lv d2a527ed0e Fix #816 2016-08-18 17:49:48 +08:00
Mygod 07ab938719 Prevent createProfile returns null 2016-08-17 12:52:21 +08:00
Mygod b6bfd5bfa0 Fix navigations in ProfileManagerActivity 2016-08-17 12:37:32 +08:00
Mygod f9194df55d Fix accessibility issue for stat and fab 2016-08-17 12:32:27 +08:00
Mygod 958d387b8c Fix su detection 2016-08-17 12:29:17 +08:00
Mygod eee89774df Refine kcpcli help again 2016-08-17 11:50:40 +08:00
Mygod 8454975a13 Fix NAT notifications on Android 4.4 2016-08-17 11:44:22 +08:00
Max Lv 69cb86a7c5 Format the help output of kcptun 2016-08-17 09:09:30 +08:00
Max Lv 45ea903323 Enable fast-open only with ss-local 2016-08-17 08:30:22 +08:00
Mygod f7303e1564 Revert "Promote default settings to kcptun"
This reverts commit 99ff47bd5f.

See discussion at: https://github.com/shadowsocks/kcptun/pull/1
2016-08-16 22:36:18 +08:00
Mygod 99ff47bd5f Promote default settings to kcptun 2016-08-16 22:16:25 +08:00
Mygod 820d71fb07 Add help for kcpcli (#811)
* Add help for kcpcli

* Filter useless parameters
2016-08-16 22:07:01 +08:00
Mygod a9a6e1c1a6 Track caught exceptions (#810) 2016-08-16 21:26:10 +08:00
Mygod 364d873eba Update to AutoCloseable in Java 1.7 2016-08-16 20:51:47 +08:00
Mygod a722257aba Set tcp_fastopen with echo instead of sysctl 2016-08-16 14:48:30 +08:00
Mygod 80d93a84bd Add support for TCP Fast Open (#809)
* Add support for TCP Fast Open

* Remove useless echo done line

* Check return values before proceeding in TcpFastOpen.enabled
2016-08-16 14:37:21 +08:00
Mygod 9b07239ced Refine default kcpcli 2016-08-16 14:02:16 +08:00
Mygod 5c7174fc5e Add default kcpcli 2016-08-16 11:49:14 +08:00
Mygod 536fe92c83 Refine #806 2016-08-16 11:23:21 +08:00
Mygod 29e6deabd0 Update sbt-android 2016-08-16 11:15:14 +08:00
Mygod e6b39444e8 Update to Java 1.7 2016-08-16 10:57:07 +08:00
Mygod 1b480b0163 Order libraryDependencies in alphabetical order
Putting support library after its dependencies could cause build failures on some rare cases.
2016-08-16 10:56:55 +08:00
Mygod c7fc4095ff Remove compatibility code for Jelly Bean 2016-08-16 10:26:52 +08:00
Max Lv 41d585ae22 Drop the support of Android 4.3 and below 2016-08-14 11:40:26 +08:00
93 changed files with 26339 additions and 5445 deletions
+18
View File
@@ -0,0 +1,18 @@
Please answer these questions before submitting your issue. Thanks!
### What version of Shadowsocks are you using?
### What Android OS version and device are you using?
### What did you do?
### What did you expect to see?
### What did you see instead?
### What is your config in detail (with all sensitive info masked)?
+1
View File
@@ -15,6 +15,7 @@ gen_*
*.o
local.sbt
.deps
/proguard-sbt.txt
#Intellij IDEA
*.iml
+3
View File
@@ -30,3 +30,6 @@
[submodule "src/main/jni/mbedtls"]
path = src/main/jni/mbedtls
url = https://github.com/ARMmbed/mbedtls
[submodule "src/main/jni/pcre"]
path = src/main/jni/pcre
url = https://android.googlesource.com/platform/external/pcre
+1
View File
@@ -28,6 +28,7 @@ android:
components:
- tools
- build-tools-24.0.1
- extra-android-m2repository
- extra-google-m2repository
install:
+1 -1
View File
@@ -15,7 +15,7 @@ A [shadowsocks](http://shadowsocks.org) client for Android, written in Scala.
* Go 1.4+
* Android SDK
- Build Tools 24+ (as required by [`sbt-android`](https://github.com/scala-android/sbt-android))
- Google Repository (see `build.sbt` for version)
- Android Support Repository and Google Repository (see `build.sbt` for version)
* Android NDK r12b+
### BUILD
+14 -14
View File
@@ -10,9 +10,9 @@ scalaVersion := "2.11.8"
compileOrder in Compile := CompileOrder.JavaThenScala
javacOptions ++= Seq("-source", "1.6", "-target", "1.6")
javacOptions ++= Seq("-source", "1.7", "-target", "1.7")
scalacOptions ++= Seq("-target:jvm-1.6", "-Xexperimental")
scalacOptions ++= Seq("-target:jvm-1.7", "-Xexperimental")
ndkJavah in Android := List()
@@ -31,23 +31,23 @@ resolvers += Resolver.jcenterRepo
useSupportVectors
libraryDependencies ++= Seq(
"dnsjava" % "dnsjava" % "2.1.7",
"com.github.kevinsawicki" % "http-request" % "6.0",
"eu.chainfire" % "libsuperuser" % "1.0.0.201607041850",
"net.glxn.qrgen" % "android" % "2.0",
"com.google.android.gms" % "play-services-ads" % "9.4.0",
"com.google.android.gms" % "play-services-analytics" % "9.4.0",
"com.android.support" % "design" % "24.1.1",
"com.android.support" % "gridlayout-v7" % "24.1.1",
"com.android.support" % "cardview-v7" % "24.1.1",
"com.android.support" % "design" % "24.2.1",
"com.android.support" % "gridlayout-v7" % "24.2.1",
"com.android.support" % "preference-v14" % "24.2.1",
"com.github.clans" % "fab" % "1.6.4",
"com.github.jorgecastilloprz" % "fabprogresscircle" % "1.01",
"com.github.kevinsawicki" % "http-request" % "6.0",
"com.google.android.gms" % "play-services-ads" % "9.6.1",
"com.google.android.gms" % "play-services-analytics" % "9.6.1",
"com.j256.ormlite" % "ormlite-android" % "5.0",
"com.twofortyfouram" % "android-plugin-api-for-locale" % "1.0.2",
"com.github.clans" % "fab" % "1.6.4",
"me.dm7.barcodescanner" % "zxing" % "1.9"
"dnsjava" % "dnsjava" % "2.1.7",
"eu.chainfire" % "libsuperuser" % "1.0.0.201608240809",
"me.dm7.barcodescanner" % "zxing" % "1.9",
"net.glxn.qrgen" % "android" % "2.0"
)
proguardVersion in Android := "5.2.1"
proguardVersion in Android := "5.3"
proguardCache in Android := Seq()
+1
View File
@@ -52,6 +52,7 @@ pushd kcptun/client
echo "Get dependences for kcptun"
go get -u github.com/xtaci/kcp-go
go get -u github.com/xtaci/smux
go get
echo "Cross compile kcptun for arm"
+1 -1
View File
@@ -1,4 +1,4 @@
addSbtPlugin("org.scala-android" % "sbt-android" % "1.6.12")
addSbtPlugin("org.scala-android" % "sbt-android" % "1.6.18")
addSbtPlugin("com.timushev.sbt" % "sbt-updates" % "0.1.10")
+4 -4
View File
@@ -1,7 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" package="com.github.shadowsocks"
android:versionCode="146"
android:versionName="3.0.4">
android:versionCode="163"
android:versionName="3.2.3">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
@@ -19,7 +19,7 @@
android:required="false"/>
<uses-sdk
android:minSdkVersion="16"
android:minSdkVersion="19"
android:targetSdkVersion="24"/>
<application
@@ -109,7 +109,7 @@
android:launchMode="singleInstance"
android:excludeFromRecents="true"
android:taskAffinity=""
android:theme="@style/PopupTheme.QuickSwitch">
android:theme="@style/Theme.Material.Dialog">
<intent-filter>
<action android:name="com.github.shadowsocks.QUICK_SWITCH" />
<category android:name="android.intent.category.DEFAULT"/>
@@ -4,6 +4,7 @@ import com.github.shadowsocks.aidl.IShadowsocksServiceCallback;
interface IShadowsocksService {
int getState();
String getProfileName();
oneway void registerCallback(IShadowsocksServiceCallback cb);
oneway void unregisterCallback(IShadowsocksServiceCallback cb);
@@ -1,6 +1,6 @@
package com.github.shadowsocks.aidl;
interface IShadowsocksServiceCallback {
oneway void stateChanged(int state, String msg);
oneway void stateChanged(int state, String profileName, String msg);
oneway void trafficUpdated(long txRate, long rxRate, long txTotal, long rxTotal);
}
File diff suppressed because it is too large Load Diff
+14
View File
@@ -0,0 +1,14 @@
0.0.0.0/8
10.0.0.0/8
100.64.0.0/10
127.0.0.0/8
169.254.0.0/16
172.16.0.0/12
192.0.0.0/29
192.0.2.0/24
192.88.99.0/24
192.168.0.0/16
198.18.0.0/15
198.51.100.0/24
203.0.113.0/24
224.0.0.0/3
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+53 -9
View File
@@ -371,7 +371,9 @@ PDNSD_SOURCES := $(wildcard $(LOCAL_PATH)/pdnsd/src/*.c)
LOCAL_MODULE := pdnsd
LOCAL_SRC_FILES := $(PDNSD_SOURCES:$(LOCAL_PATH)/%=%)
LOCAL_CFLAGS := -DANDROID -Wall -O2 -I$(LOCAL_PATH)/pdnsd \
-I$(LOCAL_PATH)/include/pdnsd
-I$(LOCAL_PATH)/include/pdnsd -I$(LOCAL_PATH)/libancillary
LOCAL_STATIC_LIBRARIES := libancillary
LOCAL_LDLIBS := -llog
include $(BUILD_EXECUTABLE)
@@ -381,25 +383,29 @@ include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
SHADOWSOCKS_SOURCES := local.c cache.c udprelay.c encrypt.c utils.c netutils.c json.c jconf.c acl.c android.c
SHADOWSOCKS_SOURCES := local.c cache.c udprelay.c encrypt.c \
utils.c netutils.c json.c jconf.c acl.c http.c tls.c rule.c \
android.c
LOCAL_MODULE := ss-local
LOCAL_SRC_FILES := $(addprefix shadowsocks-libev/src/, $(SHADOWSOCKS_SOURCES))
LOCAL_CFLAGS := -Wall -O2 -fno-strict-aliasing -DMODULE_LOCAL \
-DUSE_CRYPTO_MBEDTLS -DANDROID -DHAVE_CONFIG_H \
-DCONNECT_IN_PROGRESS=EINPROGRESS \
-I$(LOCAL_PATH)/include/shadowsocks-libev \
-I$(LOCAL_PATH)/include \
-I$(LOCAL_PATH)/libancillary \
-I$(LOCAL_PATH)/mbedtls/include \
-I$(LOCAL_PATH)/pcre \
-I$(LOCAL_PATH)/shadowsocks-libev/libudns \
-I$(LOCAL_PATH)/shadowsocks-libev/libcork/include \
-I$(LOCAL_PATH)/shadowsocks-libev/libsodium/src/libsodium/include \
-I$(LOCAL_PATH)/shadowsocks-libev/libsodium/src/libsodium/include/sodium \
-I$(LOCAL_PATH)/shadowsocks-libev/libipset/include \
-I$(LOCAL_PATH)/shadowsocks-libev/libev \
-I$(LOCAL_PATH)/include/shadowsocks-libev
-I$(LOCAL_PATH)/shadowsocks-libev/libev
LOCAL_STATIC_LIBRARIES := libev libmbedtls libipset libcork libudns libsodium libancillary
LOCAL_STATIC_LIBRARIES := libev libmbedtls libipset libcork libudns \
libsodium libancillary libpcre
LOCAL_LDLIBS := -llog
@@ -551,17 +557,55 @@ include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
LOCAL_MODULE:= mbedtls
LOCAL_MODULE := mbedtls
LOCAL_C_INCLUDES:= $(LOCAL_PATH)/mbedtls/include
LOCAL_C_INCLUDES := $(LOCAL_PATH)/mbedtls/include
MBEDTLS_SOURCES := $(wildcard $(LOCAL_PATH)/mbedtls/library/*.c)
MBEDTLS_SOURCES := $(wildcard $(LOCAL_PATH)/mbedtls/library/*.c)
LOCAL_SRC_FILES := $(MBEDTLS_SOURCES:$(LOCAL_PATH)/%=%)
LOCAL_LDLIBS := -ldl -llog
include $(BUILD_STATIC_LIBRARY)
########################################################
## pcre
########################################################
include $(CLEAR_VARS)
LOCAL_MODULE := pcre
LOCAL_CFLAGS += -DHAVE_CONFIG_H
LOCAL_C_INCLUDES := $(LOCAL_PATH)/pcre/dist $(LOCAL_PATH)/pcre
libpcre_src_files := \
pcre_chartables.c \
dist/pcre_byte_order.c \
dist/pcre_compile.c \
dist/pcre_config.c \
dist/pcre_dfa_exec.c \
dist/pcre_exec.c \
dist/pcre_fullinfo.c \
dist/pcre_get.c \
dist/pcre_globals.c \
dist/pcre_jit_compile.c \
dist/pcre_maketables.c \
dist/pcre_newline.c \
dist/pcre_ord2utf8.c \
dist/pcre_refcount.c \
dist/pcre_string_utils.c \
dist/pcre_study.c \
dist/pcre_tables.c \
dist/pcre_ucd.c \
dist/pcre_valid_utf8.c \
dist/pcre_version.c \
dist/pcre_xclass.c
LOCAL_SRC_FILES := $(addprefix pcre/, $(libpcre_src_files))
include $(BUILD_STATIC_LIBRARY)
# Import cpufeatures
$(call import-module,android/cpufeatures)
+1 -1
View File
@@ -1,4 +1,4 @@
APP_ABI := armeabi-v7a x86
APP_PLATFORM := android-16
APP_STL := stlport_static
NDK_TOOLCHAIN_VERSION := 4.9
NDK_TOOLCHAIN_VERSION := clang
@@ -417,3 +417,9 @@
/* Define as `fork' if `vfork' does not work. */
/* #undef vfork */
/* Define to 1 if you have the <pcre.h> header file. */
#define HAVE_PCRE_H 1
/* Define to 1 if you have the <pcre/pcre.h> header file. */
/* #undef HAVE_PCRE_PCRE_H */
+1
Submodule src/main/jni/pcre added at 222bbf4b3f
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="?android:colorControlHighlight">
<item>
<color android:color="@color/material_accent_300"/>
<color android:color="@color/material_primary_300"/>
</item>
</ripple>
+1 -1
View File
@@ -1,2 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<color xmlns:android="http://schemas.android.com/apk/res/android" android:color="@color/material_accent_300"/>
<color xmlns:android="http://schemas.android.com/apk/res/android" android:color="@color/material_primary_300"/>
@@ -1,3 +1,4 @@
<!--suppress NewApi -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
+1
View File
@@ -1,3 +1,4 @@
<!--suppress NewApi -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
@@ -1,3 +1,4 @@
<!--suppress NewApi -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
@@ -1,3 +1,4 @@
<!--suppress NewApi -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
@@ -1,3 +1,4 @@
<!--suppress NewApi -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
+1
View File
@@ -1,3 +1,4 @@
<!--suppress NewApi -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
+1
View File
@@ -1,3 +1,4 @@
<!--suppress NewApi -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
@@ -1,3 +1,4 @@
<!--suppress NewApi -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
@@ -1,3 +1,4 @@
<!--suppress NewApi -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
+2 -1
View File
@@ -1,4 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<!--suppress NewApi -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
@@ -11,4 +12,4 @@
<path
android:fillColor="#fff"
android:pathData="M 9.45 17.56 L 9.46 22 L 12.09 18.41 L 9.45 17.56 L 9.45 17.56 Z" />
</vector>
</vector>
+2 -1
View File
@@ -1,4 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<!--suppress NewApi -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
@@ -11,4 +12,4 @@
<path
android:fillColor="#fff"
android:pathData="M 9.45 17.56 L 12.09 18.41 L 9.46 22 L 9.45 17.56 Z" />
</vector>
</vector>
+2 -1
View File
@@ -1,4 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<!--suppress NewApi -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
@@ -22,4 +23,4 @@
<path
android:fillColor="#fff"
android:pathData="M8.56,8.56L0,12.8l6.83,2.57,4.64-3.9ZM6.44,13.08L5,12.55l5-2.47Z" />
</vector>
</vector>
+4 -4
View File
@@ -18,8 +18,8 @@
android:text="@string/on"
android:textSize="18sp"
android:textColor="?android:attr/textColorSecondary"
android:paddingLeft="60dp"
android:paddingRight="8dp"
android:paddingStart="60dp"
android:paddingEnd="8dp"
android:paddingTop="12dp"
android:paddingBottom="12dp"
android:layout_width="match_parent"
@@ -30,8 +30,8 @@
android:text="@string/bypass_apps"
android:textSize="18sp"
android:textColor="?android:attr/textColorSecondary"
android:paddingLeft="60dp"
android:paddingRight="8dp"
android:paddingStart="60dp"
android:paddingEnd="8dp"
android:paddingTop="12dp"
android:paddingBottom="12dp"
android:layout_width="match_parent"
+3 -4
View File
@@ -11,8 +11,8 @@
android:layout_width="60dp"
android:layout_height="48dp"
android:scaleType="fitCenter"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:paddingStart="8dp"
android:paddingEnd="8dp"
android:paddingTop="2dp"
android:paddingBottom="2dp"/>
@@ -28,7 +28,6 @@
android:focusable="false"
android:focusableInTouchMode="false"
android:clickable="false"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"/>
android:layout_marginEnd="8dp"/>
</LinearLayout>
+6 -7
View File
@@ -11,9 +11,9 @@
android:layout_width="match_parent" android:layout_height="wrap_content"
android:minHeight="?android:attr/listPreferredItemHeight" android:gravity="center_vertical"
android:paddingStart="16dip" android:paddingEnd="16dip" android:focusable="true"
android:paddingLeft="16dip" android:paddingRight="16dip"
android:paddingTop="16dip" android:paddingBottom="16dip"
android:background="@drawable/background_stat" android:orientation="vertical">
android:background="@drawable/background_stat" android:orientation="vertical"
android:nextFocusRight="@+id/fab">
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:text="@string/stat"
@@ -33,12 +33,12 @@
<android.support.v7.widget.GridLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingEnd="72dip"
android:paddingRight="72dip"
app:columnCount="4">
<TextView app:layout_column="0" style="@style/TextAppearance.AppCompat.Body2"
android:ellipsize="marquee" android:text="@string/sent"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginRight="24dp" android:layout_marginEnd="24dp" android:gravity="end"/>
android:layout_marginEnd="24dp"
android:gravity="end"/>
<TextView app:layout_column="1" android:id="@+id/tx" android:textSize="14sp"
android:textColor="?android:attr/textColorSecondary" android:ellipsize="marquee"
android:layout_width="0dp" android:layout_height="wrap_content"
@@ -53,7 +53,8 @@
app:layout_gravity="fill_horizontal" android:gravity="end"/>
<TextView app:layout_row="1" app:layout_column="0" style="@style/TextAppearance.AppCompat.Body2"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginRight="24dp" android:layout_marginEnd="24dp" android:gravity="end"
android:layout_marginEnd="24dp"
android:gravity="end"
android:ellipsize="marquee" android:text="@string/received"/>
<TextView app:layout_row="1" app:layout_column="1" android:id="@+id/rx" android:textSize="14sp"
android:textColor="?android:attr/textColorSecondary" android:ellipsize="marquee"
@@ -76,9 +77,7 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:elevation="6dp"
android:layout_alignBottom="@+id/title_bar"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="@dimen/fab_margin_bottom">
<android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content"
+10 -11
View File
@@ -16,10 +16,9 @@
android:layout_height="match_parent"
android:layout_gravity="bottom|end"
android:layout_marginBottom="16dp"
android:layout_marginRight="16dp"
android:layout_marginEnd="16dp"
app:menu_colorNormal="@color/material_accent_500"
app:menu_colorPressed="@color/material_accent_700"
app:menu_colorNormal="@color/material_primary_500"
app:menu_colorPressed="@color/material_primary_700"
app:fab_colorRipple="@android:color/white"
app:layout_behavior="com.github.shadowsocks.widget.FloatingActionMenuBehavior">
@@ -27,8 +26,8 @@
android:id="@+id/fab_manual_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:fab_colorNormal="@color/material_accent_500"
app:fab_colorPressed="@color/material_accent_700"
app:fab_colorNormal="@color/material_primary_500"
app:fab_colorPressed="@color/material_primary_700"
app:fab_colorRipple="@android:color/white"
app:fab_size="mini"
app:fab_label="@string/add_profile_methods_manual_settings"
@@ -37,8 +36,8 @@
android:id="@+id/fab_qrcode_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:fab_colorNormal="@color/material_accent_500"
app:fab_colorPressed="@color/material_accent_700"
app:fab_colorNormal="@color/material_primary_500"
app:fab_colorPressed="@color/material_primary_700"
app:fab_colorRipple="@android:color/white"
app:fab_size="mini"
app:fab_label="@string/add_profile_methods_scan_qr_code"
@@ -47,8 +46,8 @@
android:id="@+id/fab_nfc_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:fab_colorNormal="@color/material_accent_500"
app:fab_colorPressed="@color/material_accent_700"
app:fab_colorNormal="@color/material_primary_500"
app:fab_colorPressed="@color/material_primary_700"
app:fab_colorRipple="@android:color/white"
app:fab_size="mini"
app:fab_label="NFC"
@@ -57,8 +56,8 @@
android:id="@+id/fab_import_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:fab_colorNormal="@color/material_accent_500"
app:fab_colorPressed="@color/material_accent_700"
app:fab_colorNormal="@color/material_primary_500"
app:fab_colorPressed="@color/material_primary_700"
app:fab_colorRipple="@android:color/white"
app:fab_size="mini"
app:fab_label="@string/action_import"
@@ -8,8 +8,6 @@
android:background="?android:attr/selectableItemBackground"
android:paddingStart="20dp"
android:paddingEnd="?attr/dialogPreferredPadding"
android:paddingLeft="20dp"
android:paddingRight="?attr/dialogPreferredPadding"
android:focusable="true"
android:nextFocusRight="@+id/share">
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
@@ -23,7 +21,6 @@
android:textColor="?android:attr/textColorAlertDialogListItem"
android:gravity="center_vertical"
android:drawableStart="?android:attr/listChoiceIndicatorSingle"
android:drawableLeft="?android:attr/listChoiceIndicatorSingle"
android:drawablePadding="20dp"
android:maxLines="4"
android:scrollHorizontally="false" />
+9 -19
View File
@@ -1,24 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_margin="8dp"
android:layout_gravity="center_vertical"
app:cardElevation="5dp"
app:cardBackgroundColor="#EEEEEE">
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
<include layout="@layout/toolbar_light_dark"/>
<android.support.v7.widget.RecyclerView
android:id="@+id/profilesList"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<include layout="@layout/toolbar_light_dark"/>
<android.support.v7.widget.RecyclerView
android:id="@+id/profilesList"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</android.support.v7.widget.CardView>
android:layout_height="wrap_content"/>
</LinearLayout>
+11 -7
View File
@@ -24,13 +24,9 @@
<string name="proxy_cat">Настройки Сервера</string>
<string name="profile_name">Имя Профиля</string>
<string name="proxy">Сервер</string>
<string name="proxy_summary">Имя или IP удалённого сервера</string>
<string name="remote_port">Удалённый порт</string>
<string name="remote_port_summary">%d (номер порта удалённого сервера)</string>
<string name="port">Локальный порт</string>
<string name="port_summary">%d (номер порта локального сервера)</string>
<string name="sitekey">Пароль</string>
<string name="sitekey_summary">Пароль удалённого сервера</string>
<string name="enc_method">Метод Шифрования</string>
<!-- feature category -->
@@ -46,6 +42,14 @@
<string name="auto_set_gfwlist">CHN Маршрут</string>
<string name="auto_set_gfwlist_summary">Игнорировать все сайты находящиеся в Китае</string>
<string name="route_list">Маршрут</string>
<string-array name="route_entry">
<item>Все</item>
<item>Обход LAN</item>
<item>Обходной Китай</item>
<item>Обход LAN и Китай</item>
<item>Список GFW</item>
<item>Список Китай</item>
</string-array>
<string name="proxied_apps">Прокси для выбранных приложений</string>
<string name="proxied_apps_summary">Установить прокси для выбранных приложений, требует режим NAT под Android 4.x</string>
<string name="on">Вкл</string>
@@ -53,6 +57,8 @@
<string name="bypass_apps_summary">Включите эту опцию для работы выбранных приложений в обход прокси</string>
<string name="auto_connect">Авто Подключение</string>
<string name="auto_connect_summary">Запускать Shadowsocks при включении</string>
<string name="tcp_fastopen_summary">Переключение требует наличия ROOT прав</string>
<string name="tcp_fastopen_summary_unsupported">Неподдерживаемая версия ядра: %s &lt; 3.7.1</string>
<string name="udp_dns">Проброс UDP</string>
<string name="udp_dns_summary">Пробрасывать UDP пакеты на удалённый сервер</string>
@@ -92,8 +98,7 @@
<string name="share_message_nfc_disabled">Сканировать QR код\nAndroid Beam отключен</string>
<string name="turn_on_nfc">Включить NFC &amp; Android Beam</string>
<string name="flush_dnscache">Очистить кэш DNS</string>
<string name="flush_dnscache_summary">Работает только в режиме NAT</string>
<string name="flush_dnscache_summary_root">Работает только в режиме NAT. Требует наличия ROOT прав.</string>
<string name="flush_dnscache_summary">Работает только в режиме NAT. Требует наличия ROOT прав.</string>
<string name="flush_dnscache_no_root">Очистка кэша DNS не работает без налиичя ROOT прав</string>
<string name="flushing">Очистка</string>
<string name="add_profile">Добавить Профиль</string>
@@ -140,5 +145,4 @@
<string name="kcp_port">KCP порт</string>
<string name="kcp_port_summary">%d (KCPTUN омер порта удалённого сервера)</string>
<string name="kcpcli">KCP параметры</string>
<string name="kcpcli_summary">Командная строка KCPTUN</string>
</resources>
+1 -5
View File
@@ -1,8 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.Material.Dialog" parent="Theme.Material.DialogBase"/>
<style name="Theme.Material.Dialog.Alert" parent="Theme.Material.Dialog.AlertBase"/>
<style name="Theme.Material" parent="Theme.MaterialBase"/>
</resources>
+5 -7
View File
@@ -9,13 +9,9 @@
<string name="profile">配置文件</string>
<string name="profile_summary">新建或切换到其他配置文件</string>
<string name="proxy">服务器</string>
<string name="proxy_summary">远程服务器的地址</string>
<string name="remote_port">远程端口</string>
<string name="remote_port_summary">%d(远程服务器的端口号)</string>
<string name="port">本地端口</string>
<string name="port_summary">%d(本地客户端的端口号)</string>
<string name="sitekey">密码</string>
<string name="sitekey_summary">远程服务器的密码</string>
<string name="enc_method">加密方法</string>
<string name="feature_cat">功能设置</string>
<string name="http_proxy">HTTP 代理服务器</string>
@@ -32,6 +28,8 @@
<string name="bypass_apps_summary">启用该选项,以使所选应用程序的流量不经过代理</string>
<string name="auto_connect">自动连接</string>
<string name="auto_connect_summary">随系统启动后台服务</string>
<string name="tcp_fastopen_summary">切换需要 ROOT 权限</string>
<string name="tcp_fastopen_summary_unsupported">不支持的内核版本:%s &lt; 3.7.1</string>
<string name="forward_success">后台服务已开始运行。</string>
<string name="service_failed">无法连接远程服务器</string>
<string name="invalid_server">服务器名无效</string>
@@ -58,8 +56,7 @@
<string name="about">关于</string>
<string name="about_title">影梭(shadowsocks)%s</string>
<string name="flush_dnscache">刷新 DNS 缓存</string>
<string name="flush_dnscache_summary">只需在 NAT 模式下使用</string>
<string name="flush_dnscache_summary_root">只需在 NAT 模式下使用,需要 ROOT 权限</string>
<string name="flush_dnscache_summary">只需在 NAT 模式下使用,需要 ROOT 权限</string>
<string name="flush_dnscache_no_root">在没有 ROOT 权限的情况下无法刷新 DNS 缓存</string>
<string name="flushing">刷新中……</string>
<string name="share">分享</string>
@@ -109,6 +106,8 @@
<item>绕过局域网地址</item>
<item>绕过中国大陆地址</item>
<item>绕过局域网及中国大陆地址</item>
<item>仅代理中国大陆无法访问的地址</item>
<item>仅代理中国大陆地址</item>
</string-array>
<string name="action_apply_all">应用设置到所有配置文件</string>
@@ -139,6 +138,5 @@
<string name="kcp_port">KCP 端口</string>
<string name="kcp_port_summary">%d(远端 KCPTUN 服务器的端口号)</string>
<string name="kcpcli">KCP 参数</string>
<string name="kcpcli_summary">KCPTUN 的命令行参数</string>
</resources>
+5 -7
View File
@@ -10,13 +10,9 @@
<string name="profile">設定檔</string>
<string name="profile_summary">切換至其他設定檔或新增新設定檔</string>
<string name="proxy">伺服器</string>
<string name="proxy_summary">遠端伺服器的 IP 位址或主機名稱</string>
<string name="remote_port">遠端連接埠</string>
<string name="remote_port_summary">%d(遠端伺服器的連接埠號碼)</string>
<string name="port">連接埠號碼</string>
<string name="port_summary">%d(本機伺服器的連接埠號碼)</string>
<string name="sitekey">密碼</string>
<string name="sitekey_summary">遠端伺服器的密碼</string>
<string name="enc_method">加密方法</string>
<string name="feature_cat">功能設定</string>
<string name="http_proxy">HTTP Proxy</string>
@@ -33,6 +29,8 @@
<string name="bypass_apps_summary">啟用此選項,會略過已選擇的應用程式</string>
<string name="auto_connect">自動連線</string>
<string name="auto_connect_summary">在裝置啟動時啟用 Shadowsocks</string>
<string name="tcp_fastopen_summary">切換需要 ROOT 權限</string>
<string name="tcp_fastopen_summary_unsupported">不支持的內核版本:%s &lt; 3.7.1</string>
<string name="forward_success">Shadowsocks 已啟動。</string>
<string name="service_failed">連線至遠端伺服器失敗</string>
<string name="invalid_server">伺服器名稱無效</string>
@@ -59,8 +57,7 @@
<string name="about">關於</string>
<string name="about_title">Shadowsocks %s</string>
<string name="flush_dnscache">清除 DNS 快取</string>
<string name="flush_dnscache_summary">僅在 NAT 模式可用</string>
<string name="flush_dnscache_summary_root">僅在 NAT 模式可用,需要 ROOT 權限</string>
<string name="flush_dnscache_summary">僅在 NAT 模式可用,需要 ROOT 權限</string>
<string name="flush_dnscache_no_root">在無 ROOT 權限時清除 DNS 快取無法進行</string>
<string name="flushing">清除中……</string>
<string name="share">分享</string>
@@ -111,6 +108,8 @@
<item>略過區域網路位址</item>
<item>略過中國大陸位址</item>
<item>略過區域網路及中國大陸位址</item>
<item>僅代理大陸屏蔽位址</item>
<item>僅代理大陸位址</item>
</string-array>
<string name="action_apply_all">應用設置到所有配置文件</string>
@@ -141,6 +140,5 @@
<string name="kcp_port">KCP 連接埠</string>
<string name="kcp_port_summary">%d(遠端 KCPTUN 伺服器的連接埠號碼)</string>
<string name="kcpcli">KCP 參數</string>
<string name="kcpcli_summary">KCPTUN 的命令行參數</string>
</resources>
+8 -117
View File
@@ -38,35 +38,22 @@
<item>chacha20-ietf</item>
</string-array>
<string-array name="route_entry">
<item>All</item>
<item>Bypass LAN</item>
<item>Bypass China</item>
<item>Bypass LAN &amp; China</item>
</string-array>
<string-array name="route_value">
<item>all</item>
<item>bypass-lan</item>
<item>bypass-china</item>
<item>bypass-lan-china</item>
<item>gfwlist</item>
<item>china-list</item>
</string-array>
<string-array name="private_route">
<item>0.0.0.0/8</item>
<item>10.0.0.0/8</item>
<item>100.64.0.0/10</item>
<item>127.0.0.0/8</item>
<item>169.254.0.0/16</item>
<item>172.16.0.0/12</item>
<item>192.0.0.0/29</item>
<item>192.0.2.0/24</item>
<item>192.88.99.0/24</item>
<item>192.168.0.0/16</item>
<item>198.18.0.0/15</item>
<item>198.51.100.0/24</item>
<item>203.0.113.0/24</item>
<item>224.0.0.0/3</item>
</string-array>
<string-array name="bypass_private_route">
@@ -79,47 +66,8 @@
<item>16.0.0.0/4</item>
<item>32.0.0.0/3</item>
<item>64.0.0.0/3</item>
<item>96.0.0.0/6</item>
<item>100.0.0.0/10</item>
<item>100.128.0.0/9</item>
<item>101.0.0.0/8</item>
<item>102.0.0.0/7</item>
<item>104.0.0.0/5</item>
<item>112.0.0.0/10</item>
<item>112.64.0.0/11</item>
<item>112.96.0.0/12</item>
<item>112.112.0.0/13</item>
<item>112.120.0.0/14</item>
<item>112.124.0.0/19</item>
<item>112.124.32.0/21</item>
<item>112.124.40.0/22</item>
<item>112.124.44.0/23</item>
<item>112.124.46.0/24</item>
<item>112.124.48.0/20</item>
<item>112.124.64.0/18</item>
<item>112.124.128.0/17</item>
<item>112.125.0.0/16</item>
<item>112.126.0.0/15</item>
<item>112.128.0.0/9</item>
<item>113.0.0.0/8</item>
<item>114.0.0.0/10</item>
<item>114.64.0.0/11</item>
<item>114.96.0.0/12</item>
<item>114.112.0.0/15</item>
<item>114.114.0.0/18</item>
<item>114.114.64.0/19</item>
<item>114.114.96.0/20</item>
<item>114.114.112.0/23</item>
<item>114.114.115.0/24</item>
<item>114.114.116.0/22</item>
<item>114.114.120.0/21</item>
<item>114.114.128.0/17</item>
<item>114.115.0.0/16</item>
<item>114.116.0.0/14</item>
<item>114.120.0.0/13</item>
<item>114.128.0.0/9</item>
<item>115.0.0.0/8</item>
<item>116.0.0.0/6</item>
<item>96.0.0.0/4</item>
<item>112.0.0.0/5</item>
<item>120.0.0.0/6</item>
<item>124.0.0.0/7</item>
<item>126.0.0.0/8</item>
@@ -161,69 +109,12 @@
<item>192.8.0.0/13</item>
<item>192.16.0.0/12</item>
<item>192.32.0.0/11</item>
<item>192.64.0.0/12</item>
<item>192.80.0.0/13</item>
<item>192.88.0.0/18</item>
<item>192.88.64.0/19</item>
<item>192.88.96.0/23</item>
<item>192.88.98.0/24</item>
<item>192.88.100.0/22</item>
<item>192.88.104.0/21</item>
<item>192.88.112.0/20</item>
<item>192.88.128.0/17</item>
<item>192.89.0.0/16</item>
<item>192.90.0.0/15</item>
<item>192.92.0.0/14</item>
<item>192.96.0.0/11</item>
<item>192.128.0.0/11</item>
<item>192.160.0.0/13</item>
<item>192.169.0.0/16</item>
<item>192.170.0.0/15</item>
<item>192.172.0.0/14</item>
<item>192.176.0.0/12</item>
<item>192.192.0.0/10</item>
<item>192.64.0.0/10</item>
<item>192.128.0.0/9</item>
<item>193.0.0.0/8</item>
<item>194.0.0.0/7</item>
<item>196.0.0.0/7</item>
<item>198.0.0.0/12</item>
<item>198.16.0.0/15</item>
<item>198.20.0.0/14</item>
<item>198.24.0.0/13</item>
<item>198.32.0.0/12</item>
<item>198.48.0.0/15</item>
<item>198.50.0.0/16</item>
<item>198.51.0.0/18</item>
<item>198.51.64.0/19</item>
<item>198.51.96.0/22</item>
<item>198.51.101.0/24</item>
<item>198.51.102.0/23</item>
<item>198.51.104.0/21</item>
<item>198.51.112.0/20</item>
<item>198.51.128.0/17</item>
<item>198.52.0.0/14</item>
<item>198.56.0.0/13</item>
<item>198.64.0.0/10</item>
<item>198.128.0.0/9</item>
<item>199.0.0.0/8</item>
<item>200.0.0.0/7</item>
<item>202.0.0.0/8</item>
<item>203.0.0.0/18</item>
<item>203.0.64.0/19</item>
<item>203.0.96.0/20</item>
<item>203.0.112.0/24</item>
<item>203.0.114.0/23</item>
<item>203.0.116.0/22</item>
<item>203.0.120.0/21</item>
<item>203.0.128.0/17</item>
<item>203.1.0.0/16</item>
<item>203.2.0.0/15</item>
<item>203.4.0.0/14</item>
<item>203.8.0.0/13</item>
<item>203.16.0.0/12</item>
<item>203.32.0.0/11</item>
<item>203.64.0.0/10</item>
<item>203.128.0.0/9</item>
<item>204.0.0.0/6</item>
<item>196.0.0.0/6</item>
<item>200.0.0.0/5</item>
<item>208.0.0.0/4</item>
</string-array>
</resources>
-4
View File
@@ -1,9 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="DropDownPreference">
<attr name="android:entries" />
<attr name="android:entryValues" />
</declare-styleable>
<declare-styleable name="NumberPickerPreference">
<attr name="max" format="integer" />
<attr name="min" format="integer" />
File diff suppressed because it is too large Load Diff
+4 -3
View File
@@ -6,8 +6,9 @@
<color name="material_blue_grey_300">#90A4AE</color>
<color name="material_blue_grey_500">#607D8B</color>
<color name="material_blue_grey_700">#455A64</color>
<color name="material_accent_300">@color/material_blue_grey_300</color>
<color name="material_accent_500">@color/material_blue_grey_500</color>
<color name="material_accent_700">@color/material_blue_grey_700</color>
<color name="material_primary_300">@color/material_blue_grey_300</color>
<color name="material_primary_500">@color/material_blue_grey_500</color>
<color name="material_primary_700">@color/material_blue_grey_700</color>
<color name="material_accent_200">@color/material_blue_grey_500</color>
</resources>
File diff suppressed because one or more lines are too long
+11 -7
View File
@@ -29,13 +29,9 @@
<string name="proxy_cat">Server Settings</string>
<string name="profile_name">Profile Name</string>
<string name="proxy">Server</string>
<string name="proxy_summary">Hostname or IP of the remote server</string>
<string name="remote_port">Remote Port</string>
<string name="remote_port_summary">%d (port number of the remote server)</string>
<string name="port">Local Port</string>
<string name="port_summary">%d (port number of the local server)</string>
<string name="sitekey">Password</string>
<string name="sitekey_summary">Password of the remote server</string>
<string name="enc_method">Encrypt Method</string>
<!-- feature category -->
@@ -52,6 +48,14 @@
<string name="auto_set_gfwlist_summary">Bypass all sites located in China
</string>
<string name="route_list">Route</string>
<string-array name="route_entry">
<item>All</item>
<item>Bypass LAN</item>
<item>Bypass China</item>
<item>Bypass LAN &amp; China</item>
<item>GFW List</item>
<item>China List</item>
</string-array>
<string name="proxied_apps">Per-App Proxy</string>
<string name="proxied_apps_summary">Set proxy for selected apps, requires NAT mode under Android 4.x</string>
<string name="on">On</string>
@@ -59,6 +63,8 @@
<string name="bypass_apps_summary">Enable this option to bypass selected apps</string>
<string name="auto_connect">Auto Connect</string>
<string name="auto_connect_summary">Enable Shadowsocks on startup</string>
<string name="tcp_fastopen_summary">Toggling requires ROOT permission</string>
<string name="tcp_fastopen_summary_unsupported">Unsupported kernel version: %s &lt; 3.7.1</string>
<string name="udp_dns">UDP Forwarding</string>
<string name="udp_dns_summary">Forward UDP packets to remote</string>
@@ -98,8 +104,7 @@
<string name="share_message_nfc_disabled">Scan QR code\nAndroid Beam is disabled</string>
<string name="turn_on_nfc">Turn on NFC &amp; Android Beam</string>
<string name="flush_dnscache">Flush DNS cache</string>
<string name="flush_dnscache_summary">Only useful in NAT mode</string>
<string name="flush_dnscache_summary_root">Only useful in NAT mode. Requires ROOT permission.</string>
<string name="flush_dnscache_summary">Only useful in NAT mode. Requires ROOT permission.</string>
<string name="flush_dnscache_no_root">Flush DNS cache cannot proceed without ROOT permission</string>
<string name="flushing">Flushing</string>
<string name="add_profile">Add Profile</string>
@@ -146,5 +151,4 @@
<string name="kcp_port">KCP Port</string>
<string name="kcp_port_summary">%d (port number of the remote KCPTUN server)</string>
<string name="kcpcli">KCP Parameters (CLI)</string>
<string name="kcpcli_summary">The command line of KCPTUN</string>
</resources>
+34 -39
View File
@@ -6,48 +6,43 @@
<item name="android:textSize">24sp</item>
</style>
<style name="Theme.Material" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:alertDialogTheme">@style/Theme.Material.Dialog.Alert</item>
<item name="android:dialogTheme">@style/Theme.Material.Dialog</item>
<item name="android:navigationBarColor">@color/material_accent_700</item>
<item name="colorAccent">@color/material_accent_500</item>
<item name="colorButtonNormal">@color/material_accent_500</item>
<item name="colorPrimary">@color/material_accent_500</item>
<item name="colorPrimaryDark">@color/material_accent_700</item>
<style name="Theme.MaterialBase" parent="Theme.AppCompat.Light.NoActionBar">
<!--suppress NewApi -->
<item name="android:navigationBarColor">@color/material_primary_700</item>
<item name="colorAccent">@color/material_primary_500</item>
<item name="colorButtonNormal">@color/material_primary_500</item>
<item name="colorPrimary">@color/material_primary_500</item>
<item name="colorPrimaryDark">@color/material_primary_700</item>
<item name="preferenceTheme">@style/Theme.Material.PreferenceThemeOverlay</item>
</style>
<style name="Theme.Material.DialogBase" parent="Theme.AppCompat.Light.Dialog">
<item name="colorAccent">@color/material_accent_500</item>
<item name="colorPrimary">@color/material_accent_500</item>
<item name="colorPrimaryDark">@color/material_accent_700</item>
</style>
<style name="Theme.Material.Dialog.AlertBase" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="colorAccent">@color/material_accent_500</item>
<item name="colorPrimary">@color/material_accent_500</item>
<item name="colorPrimaryDark">@color/material_accent_700</item>
</style>
<style name="Theme.Material.Dialog" parent="Theme.Material.DialogBase">
<item name="android:windowBackground">@android:color/transparent</item>
</style>
<style name="Theme.Material.Dialog.Alert" parent="Theme.Material.Dialog.AlertBase">
<item name="android:windowBackground">@android:color/transparent</item>
</style>
<style name="PopupTheme" parent="Theme.Material.Dialog">
<item name="android:windowNoTitle">true</item>
<item name="android:windowSoftInputMode">stateAlwaysHidden</item>
<item name="android:colorBackgroundCacheHint">@null</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
</style>
<style name="PopupTheme.QuickSwitch" parent="PopupTheme">
<style name="Theme.Material.Dialog" parent="Theme.AppCompat.Light.Dialog">
<item name="colorAccent">@color/material_primary_500</item>
<item name="colorButtonNormal">@color/material_accent_200</item>
<item name="colorPrimary">@color/material_primary_500</item>
<item name="colorPrimaryDark">@color/material_primary_700</item>
<item name="preferenceTheme">@style/Theme.Material.PreferenceThemeOverlay</item>
<item name="windowNoTitle">true</item>
<item name="android:windowActionBar">false</item>
<item name="android:windowAnimationStyle">@android:style/Animation.Translucent</item>
</style>
<!-- Fix for wrong padding on v17-v20 based on: https://github.com/Gericop/Android-Support-Preference-V7-Fix/blob/a6082cb/preference-v7/src/main/res/values-v17/styles.xml -->
<style name="Theme.Material" parent="Theme.MaterialBase">
<item name="android:listPreferredItemPaddingStart">16dp</item>
<item name="android:listPreferredItemPaddingEnd">16dp</item>
</style>
<!-- This is needed because the default PreferenceCategory appearance doesn't use bold text style -->
<style name="Preference_TextAppearanceMaterialBody2">
<item name="android:textSize">14sp</item>
<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">bold</item>
<item name="android:textColor">?android:attr/textColorPrimary</item>
</style>
<style name="Theme.Material.PreferenceThemeOverlay" parent="@style/PreferenceThemeOverlay.v14.Material">
<item name="preferenceFragmentListStyle">@style/Theme.Material.PreferenceFragmentList</item>
</style>
<style name="Theme.Material.PreferenceFragmentList" parent="@style/PreferenceFragmentList.Material">
<item name="android:fadeScrollbars">true</item>
<item name="android:scrollbars">vertical</item>
</style>
</resources>
+29 -23
View File
@@ -2,39 +2,40 @@
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/com.github.shadowsocks">
<PreferenceCategory
<tk.mygod.preference.PreferenceCategory
android:title="@string/proxy_cat">
<com.github.shadowsocks.preferences.SummaryEditTextPreference
<tk.mygod.preference.EditTextPreference
android:key="profileName"
android:persistent="false"
android:summary="%s"
android:title="@string/profile_name"/>
<com.github.shadowsocks.preferences.SummaryEditTextPreference
<tk.mygod.preference.EditTextPreference
android:key="proxy"
android:persistent="false"
android:summary="@string/proxy_summary"
android:summary="%s"
android:title="@string/proxy"/>
<com.github.shadowsocks.preferences.NumberPickerPreference
<tk.mygod.preference.NumberPickerPreference
app:min="1"
app:max="65535"
android:key="remotePortNum"
android:persistent="false"
android:summary="@string/remote_port_summary"
android:summary="%d"
android:title="@string/remote_port"/>
<com.github.shadowsocks.preferences.NumberPickerPreference
<tk.mygod.preference.NumberPickerPreference
app:min="1025"
app:max="65535"
android:key="localPortNum"
android:persistent="false"
android:summary="@string/port_summary"
android:summary="%d"
android:title="@string/port"/>
<com.github.shadowsocks.preferences.PasswordEditTextPreference
<tk.mygod.preference.EditTextPreference
android:inputType="textPassword"
android:key="sitekey"
android:persistent="false"
android:summary="@string/sitekey_summary"
android:summary="%s"
android:title="@string/sitekey"/>
<com.github.shadowsocks.preferences.DropDownPreference
<android.support.v7.preference.DropDownPreference
android:key="encMethod"
android:persistent="false"
android:entries="@array/enc_method_entry"
@@ -47,12 +48,12 @@
android:summary="@string/onetime_auth_summary"
android:title="@string/onetime_auth"/>
</PreferenceCategory>
</tk.mygod.preference.PreferenceCategory>
<PreferenceCategory
<tk.mygod.preference.PreferenceCategory
android:title="@string/feature_cat">
<com.github.shadowsocks.preferences.DropDownPreference
<android.support.v7.preference.DropDownPreference
android:key="route"
android:persistent="false"
android:entries="@array/route_entry"
@@ -75,9 +76,9 @@
android:summary="@string/udp_dns_summary"
android:title="@string/udp_dns"/>
</PreferenceCategory>
</tk.mygod.preference.PreferenceCategory>
<PreferenceCategory
<tk.mygod.preference.PreferenceCategory
android:title="@string/kcp">
<SwitchPreference
@@ -86,7 +87,7 @@
android:summary="@string/kcp_summary"
android:title="@string/kcp"/>
<com.github.shadowsocks.preferences.NumberPickerPreference
<tk.mygod.preference.NumberPickerPreference
app:min="1"
app:max="65535"
android:key="kcpPort"
@@ -94,15 +95,15 @@
android:summary="@string/kcp_port_summary"
android:title="@string/kcp_port"/>
<com.github.shadowsocks.preferences.SummaryEditTextPreference
<tk.mygod.preference.EditTextPreference
android:key="kcpcli"
android:persistent="false"
android:summary="@string/kcpcli_summary"
android:summary="%s"
android:title="@string/kcpcli"/>
</PreferenceCategory>
</tk.mygod.preference.PreferenceCategory>
<PreferenceCategory android:title="@string/misc_cat">
<tk.mygod.preference.PreferenceCategory android:title="@string/misc_cat">
<SwitchPreference
android:key="isAutoConnect"
@@ -110,6 +111,11 @@
android:summary="@string/auto_connect_summary"
android:title="@string/auto_connect"/>
<SwitchPreference
android:key="tcp_fastopen"
android:summary="@string/tcp_fastopen_summary"
android:title="TCP Fast Open"/>
<SwitchPreference android:key="isNAT"
android:title="@string/nat"
android:summary="@string/nat_summary"/>
@@ -117,10 +123,10 @@
android:summary="@string/recovery_summary"/>
<Preference android:key="flush_dnscache"
android:title="@string/flush_dnscache"
android:summary="@string/flush_dnscache_summary_root"/>
android:summary="@string/flush_dnscache_summary"/>
<Preference android:key="about" android:title="@string/about"/>
</PreferenceCategory>
</tk.mygod.preference.PreferenceCategory>
</PreferenceScreen>
@@ -46,14 +46,13 @@ import android.content._
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.os.{Bundle, Handler}
import android.preference.PreferenceManager
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar.OnMenuItemClickListener
import android.support.v7.widget.{DefaultItemAnimator, LinearLayoutManager, RecyclerView, Toolbar}
import android.view._
import android.widget._
import com.github.shadowsocks.utils.{Key, Utils}
import com.github.shadowsocks.ShadowsocksApplication.app
import com.github.shadowsocks.utils.{Key, Utils}
import scala.collection.JavaConversions._
import scala.collection.mutable
@@ -143,7 +142,7 @@ class AppManager extends AppCompatActivity with OnMenuItemClickListener {
private var loadingView: View = _
private val appsLoading = new AtomicBoolean
private var handler: Handler = _
private val profile = app.currentProfile.get
private val profile = app.currentProfile.orNull
private def initProxiedApps(str: String = profile.individual) = proxiedApps = str.split('\n').to[mutable.HashSet]
@@ -213,6 +212,8 @@ class AppManager extends AppCompatActivity with OnMenuItemClickListener {
protected override def onCreate(savedInstanceState: Bundle) {
super.onCreate(savedInstanceState)
if (profile == null) finish()
handler = new Handler()
this.setContentView(R.layout.layout_apps)
@@ -39,6 +39,7 @@
package com.github.shadowsocks
import java.io.IOException
import java.util.{Timer, TimerTask}
import android.app.Service
@@ -48,7 +49,6 @@ import android.os.{Handler, RemoteCallbackList}
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import com.github.kevinsawicki.http.HttpRequest
import com.github.shadowsocks.aidl.{IShadowsocksService, IShadowsocksServiceCallback}
import com.github.shadowsocks.utils._
@@ -60,12 +60,17 @@ trait BaseService extends Service {
@volatile private var state = State.STOPPED
@volatile protected var profile: Profile = _
case class NameNotResolvedException() extends IOException
case class KcpcliParseException(cause: Throwable) extends Exception(cause)
var timer: Timer = _
var trafficMonitorThread: TrafficMonitorThread = _
final val callbacks = new RemoteCallbackList[IShadowsocksServiceCallback]
var callbacksCount: Int = _
lazy val handler = new Handler(getMainLooper)
lazy val restartHanlder = new Handler(getMainLooper)
lazy val protectPath = getApplicationInfo.dataDir + "/protect_path"
private val closeReceiver: BroadcastReceiver = (context: Context, intent: Intent) => {
Toast.makeText(context, R.string.stopping, Toast.LENGTH_SHORT).show()
@@ -79,7 +84,10 @@ trait BaseService extends Service {
val activeNetwork = cm.getActiveNetworkInfo()
val isConnected = activeNetwork != null && activeNetwork.isConnected()
if (isConnected && profile.kcp && kcptunProcess != null) kcptunProcess.restart()
if (isConnected && profile.kcp && kcptunProcess != null) {
restartHanlder.removeCallbacks(null)
restartHanlder.postDelayed(() => kcptunProcess.restart(), 2000)
}
}
var networkReceiverRegistered: Boolean = _
@@ -88,6 +96,8 @@ trait BaseService extends Service {
state
}
override def getProfileName: String = if (profile == null) null else profile.name
override def unregisterCallback(cb: IShadowsocksServiceCallback) {
if (cb != null && callbacks.unregister(cb)) {
callbacksCount -= 1
@@ -136,7 +146,7 @@ trait BaseService extends Service {
false
} else true
def connect() = if (profile.host == "198.199.101.152") try {
def connect() = if (profile.host == "198.199.101.152") {
val holder = app.containerHolder
val container = holder.getContainer
val url = container.getString("proxy_url")
@@ -153,8 +163,6 @@ trait BaseService extends Service {
profile.remotePort = proxy(1).trim.toInt
profile.password = proxy(2).trim
profile.method = proxy(3).trim
} catch {
case ex: Exception => stopRunner(true, getString(R.string.service_failed))
}
def startRunner(profile: Profile) {
@@ -188,7 +196,15 @@ trait BaseService extends Service {
if (profile.isMethodUnsafe) handler.post(() => Toast.makeText(this, R.string.method_unsafe, Toast.LENGTH_LONG).show)
Utils.ThrowableFuture(connect)
Utils.ThrowableFuture(try connect catch {
case _: NameNotResolvedException => stopRunner(true, getString(R.string.invalid_server))
case exc: KcpcliParseException =>
stopRunner(true, getString(R.string.service_failed) + ": " + exc.cause.getMessage)
case exc: Throwable =>
stopRunner(true, getString(R.string.service_failed) + ": " + exc.getMessage)
exc.printStackTrace()
app.track(exc)
})
}
def stopRunner(stopService: Boolean, msg: String = null) {
@@ -273,7 +289,7 @@ trait BaseService extends Service {
val n = callbacks.beginBroadcast()
for (i <- 0 until n) {
try {
callbacks.getBroadcastItem(i).stateChanged(s, msg)
callbacks.getBroadcastItem(i).stateChanged(s, binder.getProfileName, msg)
} catch {
case _: Exception => // Ignore
}
@@ -288,10 +304,11 @@ trait BaseService extends Service {
val default = getString(R.string.black_list)
try {
val container = app.containerHolder.getContainer
val update = container.getString("black_list")
if (update == null || update.isEmpty) default else update
val update = container.getString("black_list_lite")
val list = if (update == null || update.isEmpty) default else update
"exclude = " + list + ";"
} catch {
case ex: Exception => default
case ex: Exception => "exclude = " + default + ";"
}
}
}
@@ -53,5 +53,7 @@ object BootReceiver {
}
class BootReceiver extends BroadcastReceiver {
def onReceive(context: Context, intent: Intent) = Utils.startSsService(context)
def onReceive(context: Context, intent: Intent) = {
Utils.startSsService(context)
}
}
@@ -39,18 +39,35 @@
package com.github.shadowsocks
import java.io.{IOException, InputStream, OutputStream}
import java.io._
import java.lang.System.currentTimeMillis
import java.util.concurrent.Semaphore
import android.util.Log
import scala.collection.JavaConversions._
import scala.collection.immutable.Stream
import scala.util.control.Exception._
class StreamLogger(is: InputStream, tag: String) extends Thread {
def withCloseable[T <: Closeable, R](t: T)(f: T => R): R = {
allCatch.andFinally{t.close} apply { f(t) }
}
override def run() {
withCloseable(new BufferedReader(new InputStreamReader(is))) {
br => try Stream.continually(br.readLine()).takeWhile(_ != null).foreach(Log.i(tag, _)) catch {
case ignore: IOException =>
}
}
}
}
/**
* @author ayanamist@gmail.com
*/
class GuardedProcess(cmd: Seq[String]) extends Process {
class GuardedProcess(cmd: Seq[String]) {
private val TAG = classOf[GuardedProcess].getSimpleName
@volatile private var guardThread: Thread = _
@@ -72,19 +89,25 @@ class GuardedProcess(cmd: Seq[String]) extends Process {
process = new ProcessBuilder(cmd).redirectErrorStream(true).start
val is = process.getInputStream
new StreamLogger(is, TAG).start
if (callback == null) callback = onRestartCallback else callback()
semaphore.release
process.waitFor
if (isRestart) {
isRestart = false
} else {
if (currentTimeMillis - startTime < 1000) {
Log.w(TAG, "process exit too fast, stop guard: " + cmd)
isDestroyed = true
this.synchronized {
if (isRestart) {
isRestart = false
} else {
if (currentTimeMillis - startTime < 1000) {
Log.w(TAG, "process exit too fast, stop guard: " + cmd)
isDestroyed = true
}
}
}
}
} catch {
case ignored: InterruptedException =>
@@ -114,15 +137,12 @@ class GuardedProcess(cmd: Seq[String]) extends Process {
}
def restart() {
isRestart = true
process.destroy()
this.synchronized {
isRestart = true
process.destroy()
}
}
def exitValue: Int = throw new UnsupportedOperationException
def getErrorStream: InputStream = throw new UnsupportedOperationException
def getInputStream: InputStream = throw new UnsupportedOperationException
def getOutputStream: OutputStream = throw new UnsupportedOperationException
@throws(classOf[InterruptedException])
def waitFor = {
guardThread.join()
@@ -114,12 +114,14 @@ final class ProfileManagerActivity extends AppCompatActivity with OnMenuItemClic
finish
}
def onKey(v: View, keyCode: Int, event: KeyEvent) = if (event.getAction == KeyEvent.ACTION_UP) keyCode match {
def onKey(v: View, keyCode: Int, event: KeyEvent) = if (event.getAction == KeyEvent.ACTION_DOWN) keyCode match {
case KeyEvent.KEYCODE_DPAD_LEFT =>
val index = getAdapterPosition
profilesAdapter.remove(index)
undoManager.remove(index, item)
true
if (index >= 0) {
profilesAdapter.remove(index)
undoManager.remove(index, item)
true
} else false
case _ => false
} else false
}
@@ -233,7 +235,7 @@ final class ProfileManagerActivity extends AppCompatActivity with OnMenuItemClic
}).attachToRecyclerView(profilesList)
attachService(new IShadowsocksServiceCallback.Stub {
def stateChanged(state: Int, msg: String) = () // ignore
def stateChanged(state: Int, profileName: String, msg: String) = () // ignore
def trafficUpdated(txRate: Long, rxRate: Long, txTotal: Long, rxTotal: Long) =
if (selectedItem != null) selectedItem.updateText(txTotal, rxTotal)
})
@@ -274,7 +276,7 @@ final class ProfileManagerActivity extends AppCompatActivity with OnMenuItemClic
updateNfcState()
}
override def onNewIntent(intent: Intent): Unit ={
override def onNewIntent(intent: Intent) {
super.onNewIntent(intent)
handleShareIntent(intent)
}
@@ -1,6 +1,5 @@
package com.github.shadowsocks
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
@@ -48,13 +47,13 @@ class ScannerActivity extends AppCompatActivity with ZXingScannerView.ResultHand
override def onResume() {
super.onResume()
val permissionCheck = ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA)
android.Manifest.permission.CAMERA)
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
scannerView.setResultHandler(this) // Register ourselves as a handler for scan results.
scannerView.startCamera() // Start camera on resume
} else {
ActivityCompat.requestPermissions(this,
Array(Manifest.permission.CAMERA), MY_PERMISSIONS_REQUEST_CAMERA)
Array(android.Manifest.permission.CAMERA), MY_PERMISSIONS_REQUEST_CAMERA)
}
}
@@ -41,7 +41,8 @@ package com.github.shadowsocks
import java.io.{FileOutputStream, IOException, InputStream, OutputStream}
import java.lang.System.currentTimeMillis
import java.net.{HttpURLConnection, URL}
import java.util
import java.util.Date
import java.util.Hashtable
import java.util.Locale
import android.app.backup.BackupManager
@@ -59,15 +60,16 @@ import android.util.Log
import android.view.{View, ViewGroup}
import android.widget._
import com.github.jorgecastilloprz.FABProgressCircle
import com.github.shadowsocks.ShadowsocksApplication.app
import com.github.shadowsocks.aidl.IShadowsocksServiceCallback
import com.github.shadowsocks.database._
import com.github.shadowsocks.utils.CloseUtils._
import com.github.shadowsocks.utils._
import com.github.shadowsocks.ShadowsocksApplication.app
import com.google.android.gms.ads.{AdRequest, AdSize, AdView}
import eu.chainfire.libsuperuser.Shell
import scala.collection.mutable.ArrayBuffer
import scala.util.Random
object Typefaces {
def get(c: Context, assetPath: String): Typeface = {
@@ -78,6 +80,7 @@ object Typefaces {
} catch {
case e: Exception =>
Log.e(TAG, "Could not get typeface '" + assetPath + "' because " + e.getMessage)
app.track(e)
return null
}
}
@@ -86,7 +89,7 @@ object Typefaces {
}
private final val TAG = "Typefaces"
private final val cache = new util.Hashtable[String, Typeface]
private final val cache = new Hashtable[String, Typeface]
}
object Shadowsocks {
@@ -110,7 +113,7 @@ class Shadowsocks extends AppCompatActivity with ServiceBoundContext {
// Services
private val callback = new IShadowsocksServiceCallback.Stub {
def stateChanged(s: Int, m: String) {
def stateChanged(s: Int, profileName: String, m: String) {
handler.post(() => {
s match {
case State.CONNECTING =>
@@ -185,8 +188,8 @@ class Shadowsocks extends AppCompatActivity with ServiceBoundContext {
snackbar.show
}
if (!app.settings.getBoolean(app.getVersionName, false)) {
app.editor.putBoolean(app.getVersionName, true).apply()
if (app.settings.getInt(Key.currentVersionCode, -1) != BuildConfig.VERSION_CODE) {
app.editor.putInt(Key.currentVersionCode, BuildConfig.VERSION_CODE).apply()
recovery()
@@ -246,6 +249,7 @@ class Shadowsocks extends AppCompatActivity with ServiceBoundContext {
} catch {
case e: IOException =>
Log.e(TAG, e.getMessage)
app.track(e)
}
if (files != null) {
for (file <- files) {
@@ -267,6 +271,7 @@ class Shadowsocks extends AppCompatActivity with ServiceBoundContext {
} catch {
case ex: Exception =>
Log.e(TAG, ex.getMessage)
app.track(ex)
}
}
}
@@ -484,7 +489,18 @@ class Shadowsocks extends AppCompatActivity with ServiceBoundContext {
adView.setAdUnitId("ca-app-pub-9097031975646651/7760346322")
adView.setAdSize(AdSize.SMART_BANNER)
preferences.getView.asInstanceOf[ViewGroup].addView(adView, 1)
adView.loadAd(new AdRequest.Builder().build())
// Demographics
val random = new Random()
val adBuilder = new AdRequest.Builder()
adBuilder.setGender(AdRequest.GENDER_MALE)
val year = 1975 + random.nextInt(40)
val month = 1 + random.nextInt(12)
val day = random.nextInt(28)
adBuilder.setBirthday(new Date(year, month, day))
// Load Ad
adView.loadAd(adBuilder.build())
} else adView.setVisibility(View.VISIBLE) else if (adView != null) adView.setVisibility(View.GONE)
preferences.setProfile(profile)
@@ -500,11 +516,8 @@ class Shadowsocks extends AppCompatActivity with ServiceBoundContext {
clearDialog()
}
private var _isDestroyed: Boolean = _
override def isDestroyed = if (Build.VERSION.SDK_INT >= 17) super.isDestroyed else _isDestroyed
override def onDestroy() {
super.onDestroy()
_isDestroyed = true
detachService()
new BackupManager(this).dataChanged()
handler.removeCallbacksAndMessages(null)
@@ -514,6 +527,7 @@ class Shadowsocks extends AppCompatActivity with ServiceBoundContext {
crashRecovery()
copyAssets(System.getABI)
copyAssets("acl")
val ab = new ArrayBuffer[String]
for (executable <- EXECUTABLES) {
@@ -43,12 +43,11 @@ import java.util
import java.util.concurrent.TimeUnit
import android.app.Application
import android.content.pm.PackageManager
import android.preference.PreferenceManager
import android.support.v7.app.AppCompatDelegate
import com.github.shadowsocks.database.{DBHelper, ProfileManager}
import com.github.shadowsocks.utils.{Key, Utils}
import com.google.android.gms.analytics.{GoogleAnalytics, HitBuilders}
import com.github.shadowsocks.utils.{Key, Utils, TcpFastOpen}
import com.google.android.gms.analytics.{GoogleAnalytics, HitBuilders, StandardExceptionParser}
import com.google.android.gms.common.api.ResultCallback
import com.google.android.gms.tagmanager.{ContainerHolder, TagManager}
import com.j256.ormlite.logger.LocalLog
@@ -70,17 +69,14 @@ class ShadowsocksApplication extends Application {
def isNatEnabled = settings.getBoolean(Key.isNAT, false)
def isVpnEnabled = !isNatEnabled
def getVersionName = try {
getPackageManager.getPackageInfo(getPackageName, 0).versionName
} catch {
case _: PackageManager.NameNotFoundException => "Package name not found"
case _: Throwable => null
}
// send event
def track(category: String, action: String) = tracker.send(new HitBuilders.EventBuilder()
.setAction(action)
.setLabel(getVersionName)
.setLabel(BuildConfig.VERSION_NAME)
.build())
def track(t: Throwable) = tracker.send(new HitBuilders.ExceptionBuilder()
.setDescription(new StandardExceptionParser(this, null).getDescription(Thread.currentThread.getName, t))
.setFatal(false)
.build())
def profileId = settings.getInt(Key.id, -1)
@@ -93,7 +89,7 @@ class ShadowsocksApplication extends Application {
}
override def onCreate() {
java.lang.System.setProperty(LocalLog.LOCAL_LOG_LEVEL_PROPERTY, "ERROR")
if (!BuildConfig.DEBUG) java.lang.System.setProperty(LocalLog.LOCAL_LOG_LEVEL_PROPERTY, "ERROR")
app = this
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
val tm = TagManager.getInstance(this)
@@ -115,6 +111,8 @@ class ShadowsocksApplication extends Application {
}
}
pending.setResultCallback(callback, 2, TimeUnit.SECONDS)
TcpFastOpen.enabled(settings.getBoolean(Key.tfo, TcpFastOpen.sendEnabled))
}
def refreshContainerHolder {
@@ -40,7 +40,6 @@
package com.github.shadowsocks
import java.io.File
import java.lang.Process
import java.net.{Inet6Address, InetAddress}
import java.util.Locale
@@ -65,25 +64,13 @@ class ShadowsocksNatService extends BaseService {
private var notification: ShadowsocksNotification = _
val myUid = android.os.Process.myUid()
var sslocalProcess: Process = _
var sstunnelProcess: Process = _
var redsocksProcess: Process = _
var pdnsdProcess: Process = _
var sslocalProcess: GuardedProcess = _
var sstunnelProcess: GuardedProcess = _
var redsocksProcess: GuardedProcess = _
var pdnsdProcess: GuardedProcess = _
var su: Shell.Interactive = _
def startShadowsocksDaemon() {
if (profile.route != Route.ALL) {
val acl: Array[Array[String]] = profile.route match {
case Route.BYPASS_LAN => Array(getResources.getStringArray(R.array.private_route))
case Route.BYPASS_CHN => Array(getResources.getStringArray(R.array.chn_route))
case Route.BYPASS_LAN_CHN =>
Array(getResources.getStringArray(R.array.private_route), getResources.getStringArray(R.array.chn_route))
}
Utils.printToFile(new File(getApplicationInfo.dataDir + "/acl.list"))(p => {
acl.flatten.foreach(p.println)
})
}
val conf = if (profile.kcp) {
ConfigUtils
.SHADOWSOCKS.formatLocal(Locale.ENGLISH, "127.0.0.1", profile.localPort + 90, profile.localPort,
@@ -97,8 +84,7 @@ class ShadowsocksNatService extends BaseService {
p.println(conf)
})
val cmd = new ArrayBuffer[String]
cmd += (getApplicationInfo.dataDir + "/ss-local"
val cmd = ArrayBuffer[String](getApplicationInfo.dataDir + "/ss-local"
, "-b" , "127.0.0.1"
, "-t" , "600"
, "-P", getApplicationInfo.dataDir
@@ -106,9 +92,17 @@ class ShadowsocksNatService extends BaseService {
if (profile.auth) cmd += "-A"
if (TcpFastOpen.sendEnabled) cmd += "--fast-open"
if (profile.route != Route.ALL) {
cmd += "--acl"
cmd += (getApplicationInfo.dataDir + "/acl.list")
profile.route match {
case Route.BYPASS_LAN => cmd += (getApplicationInfo.dataDir + "/bypass_lan.acl")
case Route.BYPASS_CHN => cmd += (getApplicationInfo.dataDir + "/bypass_chn.acl")
case Route.BYPASS_LAN_CHN => cmd += (getApplicationInfo.dataDir + "/bypass_lan_chn.acl")
case Route.GFWLIST => cmd += (getApplicationInfo.dataDir + "/gfwlist.acl")
case Route.CHINALIST => cmd += (getApplicationInfo.dataDir + "/chinalist.acl")
}
}
if (BuildConfig.DEBUG) Log.d(TAG, cmd.mkString(" "))
@@ -118,15 +112,16 @@ class ShadowsocksNatService extends BaseService {
def startKcptunDaemon() {
if (profile.kcpcli == null) profile.kcpcli = ""
val cmd = new ArrayBuffer[String]
cmd += (getApplicationInfo.dataDir + "/kcptun"
val cmd = ArrayBuffer[String](getApplicationInfo.dataDir + "/kcptun"
, "-r", profile.host + ":" + profile.kcpPort
, "-l", "127.0.0.1:" + (profile.localPort + 90)
, profile.kcpcli.trim.replaceAll("[\"']", ""))
, "-l", "127.0.0.1:" + (profile.localPort + 90))
try cmd ++= Utils.translateCommandline(profile.kcpcli) catch {
case exc: Exception => throw KcpcliParseException(exc)
}
if (BuildConfig.DEBUG) Log.d(TAG, cmd.mkString(" "))
kcptunProcess = new GuardedProcess(cmd.mkString(" ").split(" ").toSeq).start()
kcptunProcess = new GuardedProcess(cmd).start()
}
def startDNSTunnel() {
@@ -137,16 +132,20 @@ class ShadowsocksNatService extends BaseService {
Utils.printToFile(new File(getApplicationInfo.dataDir + "/ss-tunnel-nat.conf"))(p => {
p.println(conf)
})
val cmd = new ArrayBuffer[String]
cmd += (getApplicationInfo.dataDir + "/ss-tunnel"
val cmd = ArrayBuffer[String](getApplicationInfo.dataDir + "/ss-tunnel"
, "-u"
, "-t" , "10"
, "-b" , "127.0.0.1"
, "-L" , "8.8.8.8:53"
, "-l" , (profile.localPort + 53).toString
, "-P" , getApplicationInfo.dataDir
, "-c" , getApplicationInfo.dataDir + "/ss-tunnel-nat.conf")
cmd += "-L"
if (profile.route == Route.CHINALIST)
cmd += "114.114.114.114:53"
else
cmd += "8.8.8.8:53"
if (profile.auth) cmd += "-A"
if (BuildConfig.DEBUG) Log.d(TAG, cmd.mkString(" "))
@@ -166,8 +165,7 @@ class ShadowsocksNatService extends BaseService {
Utils.printToFile(new File(getApplicationInfo.dataDir + "/ss-tunnel-nat.conf"))(p => {
p.println(conf)
})
val cmdBuf = new ArrayBuffer[String]
cmdBuf += (getApplicationInfo.dataDir + "/ss-tunnel"
val cmdBuf = ArrayBuffer[String](getApplicationInfo.dataDir + "/ss-tunnel"
, "-t" , "10"
, "-b" , "127.0.0.1"
, "-l" , (profile.localPort + 63).toString
@@ -185,38 +183,48 @@ class ShadowsocksNatService extends BaseService {
def startDnsDaemon() {
val conf = if (profile.route == Route.BYPASS_CHN || profile.route == Route.BYPASS_LAN_CHN) {
ConfigUtils.PDNSD_DIRECT.formatLocal(Locale.ENGLISH, getApplicationInfo.dataDir,
"127.0.0.1", profile.localPort + 53, getBlackList, profile.localPort + 63, "")
} else {
ConfigUtils.PDNSD_LOCAL.formatLocal(Locale.ENGLISH, getApplicationInfo.dataDir,
"127.0.0.1", profile.localPort + 53, profile.localPort + 63, "")
val reject = if (profile.ipv6) "224.0.0.0/3" else "224.0.0.0/3, ::/0"
val conf = profile.route match {
case Route.BYPASS_CHN | Route.BYPASS_LAN_CHN | Route.GFWLIST => {
ConfigUtils.PDNSD_DIRECT.formatLocal(Locale.ENGLISH, "", getApplicationInfo.dataDir,
"127.0.0.1", profile.localPort + 53, "1.2.4.8, 114.114.114.114",
getBlackList, reject, profile.localPort + 63, reject)
}
case Route.CHINALIST => {
ConfigUtils.PDNSD_DIRECT.formatLocal(Locale.ENGLISH, "", getApplicationInfo.dataDir,
"127.0.0.1", profile.localPort + 53, "8.8.8.8, 208.67.222.222",
"", reject, profile.localPort + 63, reject)
}
case _ => {
ConfigUtils.PDNSD_LOCAL.formatLocal(Locale.ENGLISH, "", getApplicationInfo.dataDir,
"127.0.0.1", profile.localPort + 53, profile.localPort + 63, reject)
}
}
Utils.printToFile(new File(getApplicationInfo.dataDir + "/pdnsd-nat.conf"))(p => {
p.println(conf)
})
val cmd = getApplicationInfo.dataDir + "/pdnsd -c " + getApplicationInfo.dataDir + "/pdnsd-nat.conf"
val cmd = Array(getApplicationInfo.dataDir + "/pdnsd", "-c", getApplicationInfo.dataDir + "/pdnsd-nat.conf")
if (BuildConfig.DEBUG) Log.d(TAG, cmd)
if (BuildConfig.DEBUG) Log.d(TAG, cmd.mkString(" "))
pdnsdProcess = new GuardedProcess(cmd.split(" ").toSeq).start()
pdnsdProcess = new GuardedProcess(cmd).start()
}
def startRedsocksDaemon() {
val conf = ConfigUtils.REDSOCKS.formatLocal(Locale.ENGLISH, profile.localPort)
val cmd = "%s/redsocks -c %s/redsocks-nat.conf"
.formatLocal(Locale.ENGLISH, getApplicationInfo.dataDir, getApplicationInfo.dataDir)
val cmd = Array(getApplicationInfo.dataDir + "/redsocks", "-c", getApplicationInfo.dataDir + "/redsocks-nat.conf")
Utils.printToFile(new File(getApplicationInfo.dataDir + "/redsocks-nat.conf"))(p => {
p.println(conf)
})
if (BuildConfig.DEBUG) Log.d(TAG, cmd)
redsocksProcess = new GuardedProcess(cmd.split(" ").toSeq).start()
if (BuildConfig.DEBUG) Log.d(TAG, cmd.mkString(" "))
redsocksProcess = new GuardedProcess(cmd).start()
}
/** Called when the activity is first created. */
def handleConnection {
def handleConnection() {
startDNSTunnel()
startRedsocksDaemon()
@@ -300,50 +308,32 @@ class ShadowsocksNatService extends BaseService {
su.addCommand((init_sb ++ http_sb).toArray)
}
override def startRunner(profile: Profile) = if (su == null) {
override def startRunner(profile: Profile) = if (su == null)
su = new Shell.Builder().useSU().setWantSTDERR(true).setWatchdogTimeout(10).open((_, exitCode, _) =>
if (exitCode == 0) super.startRunner(profile) else {
Log.wtf(TAG, "libsuperuser#55 has been fixed. Please remove the redundant code.")
su.close()
su = null
if (su != null) {
su.close()
su = null
}
super.stopRunner(true, getString(R.string.nat_no_root))
})
su.waitForIdle()
if (!su.isRunning) {
su.close()
su = null
super.stopRunner(true, getString(R.string.nat_no_root))
}
}
override def connect() {
super.connect()
if (profile != null) {
// Clean up
killProcesses()
// Clean up
killProcesses()
var resolved = false
if (!Utils.isNumeric(profile.host)) {
Utils.resolve(profile.host, enableIPv6 = true) match {
case Some(a) =>
profile.host = a
resolved = true
case None => resolved = false
}
} else {
resolved = true
}
if (!resolved) stopRunner(true, getString(R.string.invalid_server)) else {
handleConnection
// Set DNS
su.addCommand(Utils.FLUSH_DNS)
changeState(State.CONNECTED)
notification = new ShadowsocksNotification(this, profile.name, true)
}
if (!Utils.isNumeric(profile.host)) Utils.resolve(profile.host, enableIPv6 = true) match {
case Some(a) => profile.host = a
case None => throw NameNotResolvedException()
}
handleConnection()
// Set DNS
su.addCommand(Utils.FLUSH_DNS)
changeState(State.CONNECTED)
notification = new ShadowsocksNotification(this, profile.name, true)
}
override def stopRunner(stopService: Boolean, msg: String = null) {
@@ -19,7 +19,7 @@ class ShadowsocksNotification(private val service: BaseService, profileName: Str
private val keyGuard = service.getSystemService(Context.KEYGUARD_SERVICE).asInstanceOf[KeyguardManager]
private lazy val nm = service.getSystemService(Context.NOTIFICATION_SERVICE).asInstanceOf[NotificationManager]
private lazy val callback = new Stub {
override def stateChanged(state: Int, msg: String) = () // ignore
override def stateChanged(state: Int, profileName: String, msg: String) = () // ignore
override def trafficUpdated(txRate: Long, rxRate: Long, txTotal: Long, rxTotal: Long) {
val txr = TrafficMonitor.formatTraffic(txRate)
val rxr = TrafficMonitor.formatTraffic(rxRate)
@@ -34,7 +34,7 @@ class ShadowsocksNotification(private val service: BaseService, profileName: Str
private val builder = new NotificationCompat.Builder(service)
.setWhen(0)
.setColor(ContextCompat.getColor(service, R.color.material_accent_500))
.setColor(ContextCompat.getColor(service, R.color.material_primary_500))
.setTicker(service.getString(R.string.forward_success))
.setContentTitle(profileName)
.setContentIntent(PendingIntent.getActivity(service, 0, new Intent(service, classOf[Shadowsocks])
@@ -49,7 +49,6 @@ class ShadowsocksNotification(private val service: BaseService, profileName: Str
case _ =>
}
private lazy val style = new BigTextStyle(builder)
private val showOnUnlock = visible && Utils.isLollipopOrAbove
private var isVisible = true
update(if (service.getSystemService(Context.POWER_SERVICE).asInstanceOf[PowerManager].isScreenOn)
Intent.ACTION_SCREEN_ON else Intent.ACTION_SCREEN_OFF, true)
@@ -57,19 +56,19 @@ class ShadowsocksNotification(private val service: BaseService, profileName: Str
val screenFilter = new IntentFilter()
screenFilter.addAction(Intent.ACTION_SCREEN_ON)
screenFilter.addAction(Intent.ACTION_SCREEN_OFF)
if (showOnUnlock) screenFilter.addAction(Intent.ACTION_USER_PRESENT)
if (visible && Utils.isLollipopOrAbove) screenFilter.addAction(Intent.ACTION_USER_PRESENT)
service.registerReceiver(lockReceiver, screenFilter)
private def update(action: String, forceShow: Boolean = false) =
if (forceShow || service.getState == State.CONNECTED) action match {
case Intent.ACTION_SCREEN_OFF =>
setVisible(false, forceShow)
setVisible(visible && !Utils.isLollipopOrAbove, forceShow)
unregisterCallback // unregister callback to save battery
case Intent.ACTION_SCREEN_ON =>
setVisible(showOnUnlock && !keyGuard.inKeyguardRestrictedInputMode, forceShow)
setVisible(visible && Utils.isLollipopOrAbove && !keyGuard.inKeyguardRestrictedInputMode, forceShow)
service.binder.registerCallback(callback)
callbackRegistered = true
case Intent.ACTION_USER_PRESENT => setVisible(showOnUnlock, forceShow)
case Intent.ACTION_USER_PRESENT => setVisible(true, forceShow)
}
private def unregisterCallback = if (callbackRegistered) {
@@ -68,7 +68,7 @@ class ShadowsocksQuickSwitchActivity extends AppCompatActivity {
profilesList.setItemAnimator(new DefaultItemAnimator)
profilesList.setAdapter(profilesAdapter)
if (app.profileId >= 0) lm.scrollToPosition(profilesAdapter.profiles.zipWithIndex.collectFirst {
case (profile, i) if profile.id == app.profileId => i + 1
case (profile, i) if profile.id == app.profileId => i
}.getOrElse(0))
}
}
@@ -54,10 +54,12 @@ class ShadowsocksRunnerService extends Service with ServiceBoundContext {
}
override def onServiceConnected() {
handler.postDelayed(() => if (bgService != null) {
if (app.isNatEnabled) startBackgroundService()
else if (VpnService.prepare(ShadowsocksRunnerService.this) == null) startBackgroundService()
stopSelf()
handler.postDelayed(() => {
if (bgService != null) {
if (app.isNatEnabled) startBackgroundService()
else if (VpnService.prepare(ShadowsocksRunnerService.this) == null) startBackgroundService()
handler.postDelayed(() => stopSelf(), 10000)
}
}, 1000)
}
@@ -5,14 +5,17 @@ import java.util.Locale
import android.content.SharedPreferences.OnSharedPreferenceChangeListener
import android.content.{Intent, SharedPreferences}
import android.net.Uri
import android.os.{Build, Bundle}
import android.preference.{Preference, PreferenceFragment, SwitchPreference}
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v14.preference.SwitchPreference
import android.support.v7.app.AlertDialog
import android.support.v7.preference.{DropDownPreference, Preference}
import android.webkit.{WebView, WebViewClient}
import com.github.shadowsocks.ShadowsocksApplication.app
import com.github.shadowsocks.database.Profile
import com.github.shadowsocks.preferences._
import com.github.shadowsocks.utils.{Key, Utils}
import com.github.shadowsocks.preferences.KcpCliPreferenceDialogFragment
import com.github.shadowsocks.utils.{Key, TcpFastOpen, Utils}
import tk.mygod.preference._
object ShadowsocksSettings {
// Constants
@@ -26,31 +29,25 @@ object ShadowsocksSettings {
pref.asInstanceOf[DropDownPreference].setValue(value)
}
def updatePasswordEditTextPreference(pref: Preference, value: String) {
pref.setSummary(value)
pref.asInstanceOf[PasswordEditTextPreference].setText(value)
def updateEditTextPreference(pref: Preference, value: String) {
pref.asInstanceOf[EditTextPreference].setText(value)
}
def updateNumberPickerPreference(pref: Preference, value: Int) {
pref.asInstanceOf[NumberPickerPreference].setValue(value)
}
def updateSummaryEditTextPreference(pref: Preference, value: String) {
pref.setSummary(value)
pref.asInstanceOf[SummaryEditTextPreference].setText(value)
}
def updateSwitchPreference(pref: Preference, value: Boolean) {
pref.asInstanceOf[SwitchPreference].setChecked(value)
}
def updatePreference(pref: Preference, name: String, profile: Profile) {
name match {
case Key.name => updateSummaryEditTextPreference(pref, profile.name)
case Key.host => updateSummaryEditTextPreference(pref, profile.host)
case Key.name => updateEditTextPreference(pref, profile.name)
case Key.host => updateEditTextPreference(pref, profile.host)
case Key.remotePort => updateNumberPickerPreference(pref, profile.remotePort)
case Key.localPort => updateNumberPickerPreference(pref, profile.localPort)
case Key.password => updatePasswordEditTextPreference(pref, profile.password)
case Key.password => updateEditTextPreference(pref, profile.password)
case Key.method => updateDropDownPreference(pref, profile.method)
case Key.route => updateDropDownPreference(pref, profile.route)
case Key.proxyApps => updateSwitchPreference(pref, profile.proxyApps)
@@ -59,7 +56,7 @@ object ShadowsocksSettings {
case Key.ipv6 => updateSwitchPreference(pref, profile.ipv6)
case Key.kcp => updateSwitchPreference(pref, profile.kcp)
case Key.kcpPort => updateNumberPickerPreference(pref, profile.kcpPort)
case Key.kcpcli => updateSummaryEditTextPreference(pref, profile.kcpcli)
case Key.kcpcli => updateEditTextPreference(pref, profile.kcpcli)
}
}
}
@@ -72,8 +69,7 @@ class ShadowsocksSettings extends PreferenceFragment with OnSharedPreferenceChan
private var isProxyApps: SwitchPreference = _
override def onCreate(savedInstanceState: Bundle) {
super.onCreate(savedInstanceState)
override def onCreatePreferences(bundle: Bundle, key: String) {
addPreferencesFromResource(R.xml.pref_all)
getPreferenceManager.getSharedPreferences.registerOnSharedPreferenceChangeListener(this)
@@ -154,15 +150,27 @@ class ShadowsocksSettings extends PreferenceFragment with OnSharedPreferenceChan
}
switch.setChecked(BootReceiver.getEnabled(activity))
val tfo = findPreference(Key.tfo).asInstanceOf[SwitchPreference]
tfo.setChecked(TcpFastOpen.sendEnabled)
tfo.setOnPreferenceChangeListener((_, v) => {
val value = v.asInstanceOf[Boolean]
val result = TcpFastOpen.enabled(value)
if (result != null && result != "Success.")
Snackbar.make(activity.findViewById(android.R.id.content), result, Snackbar.LENGTH_LONG).show()
value == TcpFastOpen.sendEnabled
})
if (!TcpFastOpen.supported) {
tfo.setEnabled(false)
tfo.setSummary(getString(R.string.tcp_fastopen_summary_unsupported, java.lang.System.getProperty("os.version")))
}
findPreference("recovery").setOnPreferenceClickListener((preference: Preference) => {
app.track(TAG, "reset")
activity.recovery()
true
})
val flush = findPreference("flush_dnscache")
if (Build.VERSION.SDK_INT < 17) flush.setSummary(R.string.flush_dnscache_summary)
flush.setOnPreferenceClickListener(_ => {
findPreference("flush_dnscache").setOnPreferenceClickListener(_ => {
app.track(TAG, "flush_dnscache")
activity.flushDnsCache()
true
@@ -184,7 +192,7 @@ class ShadowsocksSettings extends PreferenceFragment with OnSharedPreferenceChan
})
new AlertDialog.Builder(activity)
.setTitle(getString(R.string.about_title).formatLocal(Locale.ENGLISH, app.getVersionName))
.setTitle(getString(R.string.about_title).formatLocal(Locale.ENGLISH, BuildConfig.VERSION_NAME))
.setNegativeButton(getString(android.R.string.ok), null)
.setView(web)
.create()
@@ -193,8 +201,29 @@ class ShadowsocksSettings extends PreferenceFragment with OnSharedPreferenceChan
})
}
override def onDisplayPreferenceDialog(preference: Preference) = preference match {
case _: EditTextPreference => displayPreferenceDialog(preference.getKey,
if (preference.getKey == Key.kcpcli) new KcpCliPreferenceDialogFragment()
else new EditTextPreferenceDialogFragment())
case _: NumberPickerPreference =>
displayPreferenceDialog(preference.getKey, new NumberPickerPreferenceDialogFragment())
case _ => super.onDisplayPreferenceDialog(preference)
}
def refreshProfile() {
profile = app.currentProfile.get
profile = app.currentProfile match {
case Some(p) => p
case None =>
app.profileManager.getFirstProfile match {
case Some(p) =>
app.profileId(p.id)
p
case None =>
val default = app.profileManager.createDefault()
app.profileId(default.id)
default
}
}
isProxyApps.setChecked(profile.proxyApps)
}
@@ -5,7 +5,6 @@ import android.graphics.drawable.Icon
import android.service.quicksettings.{Tile, TileService}
import com.github.shadowsocks.aidl.IShadowsocksServiceCallback
import com.github.shadowsocks.utils.{State, Utils}
import com.github.shadowsocks.ShadowsocksApplication.app
/**
* @author Mygod
@@ -23,7 +22,7 @@ final class ShadowsocksTileService extends TileService with ServiceBoundContext
private lazy val iconConnected = Icon.createWithResource(this, R.drawable.ic_start_connected)
private lazy val callback = new IShadowsocksServiceCallback.Stub {
def trafficUpdated(txRate: Long, rxRate: Long, txTotal: Long, rxTotal: Long) = ()
def stateChanged(state: Int, msg: String) {
def stateChanged(state: Int, profileName: String, msg: String) {
val tile = getQsTile
if (tile != null) {
state match {
@@ -33,10 +32,7 @@ final class ShadowsocksTileService extends TileService with ServiceBoundContext
tile.setState(Tile.STATE_INACTIVE)
case State.CONNECTED =>
tile.setIcon(iconConnected)
tile.setLabel(app.currentProfile match {
case Some(profile) => profile.name
case None => getString(R.string.app_name)
})
tile.setLabel(if (profileName == null) getString(R.string.app_name) else profileName)
tile.setState(Tile.STATE_ACTIVE)
case _ =>
tile.setIcon(iconBusy)
@@ -48,7 +44,7 @@ final class ShadowsocksTileService extends TileService with ServiceBoundContext
}
}
override def onServiceConnected() = callback.stateChanged(bgService.getState, null)
override def onServiceConnected() = callback.stateChanged(bgService.getState, bgService.getProfileName, null)
override def onCreate {
super.onCreate
@@ -40,17 +40,17 @@
package com.github.shadowsocks
import java.io.File
import java.lang.Process
import java.util.Locale
import android.annotation.SuppressLint
import android.content._
import android.content.pm.PackageManager.NameNotFoundException
import android.net.VpnService
import android.os._
import android.util.Log
import com.github.shadowsocks.utils._
import com.github.shadowsocks.ShadowsocksApplication.app
import com.github.shadowsocks.database.Profile
import com.github.shadowsocks.utils._
import scala.collection.mutable.ArrayBuffer
@@ -63,10 +63,10 @@ class ShadowsocksVpnService extends VpnService with BaseService {
var vpnThread: ShadowsocksVpnThread = _
private var notification: ShadowsocksNotification = _
var sslocalProcess: Process = _
var sstunnelProcess: Process = _
var pdnsdProcess: Process = _
var tun2socksProcess: Process = _
var sslocalProcess: GuardedProcess = _
var sstunnelProcess: GuardedProcess = _
var pdnsdProcess: GuardedProcess = _
var tun2socksProcess: GuardedProcess = _
override def onBind(intent: Intent): IBinder = {
val action = intent.getAction
@@ -148,42 +148,28 @@ class ShadowsocksVpnService extends VpnService with BaseService {
override def connect() = {
super.connect()
if (profile != null) {
vpnThread = new ShadowsocksVpnThread(this)
vpnThread.start()
vpnThread = new ShadowsocksVpnThread(this)
vpnThread.start()
// reset the context
killProcesses()
// reset the context
killProcesses()
// Resolve the server address
var resolved: Boolean = false
if (!Utils.isNumeric(profile.host)) {
Utils.resolve(profile.host, enableIPv6 = true) match {
case Some(addr) =>
profile.host = addr
resolved = true
case None => resolved = false
}
} else {
resolved = true
}
if (!resolved) stopRunner(true, getString(R.string.invalid_server)) else if (handleConnection) {
changeState(State.CONNECTED)
notification = new ShadowsocksNotification(this, profile.name)
} else {
changeState(State.STOPPED, getString(R.string.service_failed))
stopRunner(true)
}
// Resolve the server address
if (!Utils.isNumeric(profile.host)) Utils.resolve(profile.host, enableIPv6 = true) match {
case Some(addr) => profile.host = addr
case None => throw NameNotResolvedException()
}
handleConnection()
changeState(State.CONNECTED)
notification = new ShadowsocksNotification(this, profile.name)
}
/** Called when the activity is first created. */
def handleConnection: Boolean = {
def handleConnection() {
val fd = startVpn()
if (!sendFd(fd)) return false
if (!sendFd(fd)) throw new Exception("sendFd failed")
if (profile.kcp) {
startKcptunDaemon()
@@ -199,24 +185,23 @@ class ShadowsocksVpnService extends VpnService with BaseService {
startDnsDaemon()
startDnsTunnel()
}
true
}
def startKcptunDaemon() {
if (profile.kcpcli == null) profile.kcpcli = ""
val cmd = new ArrayBuffer[String]
cmd += (getApplicationInfo.dataDir + "/kcptun"
val cmd = ArrayBuffer(getApplicationInfo.dataDir + "/kcptun"
, "-r", profile.host + ":" + profile.kcpPort
, "-l", "127.0.0.1:" + (profile.localPort + 90)
, "--path", getApplicationInfo.dataDir + "/protect_path"
, profile.kcpcli.trim.replaceAll("[\"']", ""))
, "--path", protectPath)
try cmd ++= Utils.translateCommandline(profile.kcpcli) catch {
case exc: Exception => throw KcpcliParseException(exc)
}
if (BuildConfig.DEBUG)
Log.d(TAG, cmd.mkString(" "))
kcptunProcess = new GuardedProcess(cmd.mkString(" ").split(" ").toSeq).start()
kcptunProcess = new GuardedProcess(cmd).start()
}
def startShadowsocksUDPDaemon() {
@@ -227,8 +212,7 @@ class ShadowsocksVpnService extends VpnService with BaseService {
p.println(conf)
})
val cmd = new ArrayBuffer[String]
cmd += (getApplicationInfo.dataDir + "/ss-local", "-V", "-U"
val cmd = ArrayBuffer[String](getApplicationInfo.dataDir + "/ss-local", "-V", "-U"
, "-b", "127.0.0.1"
, "-t", "600"
, "-P", getApplicationInfo.dataDir
@@ -242,18 +226,6 @@ class ShadowsocksVpnService extends VpnService with BaseService {
}
def startShadowsocksDaemon() {
if (profile.route != Route.ALL) {
val acl: Array[Array[String]] = profile.route match {
case Route.BYPASS_LAN => Array(getResources.getStringArray(R.array.private_route))
case Route.BYPASS_CHN => Array(getResources.getStringArray(R.array.chn_route))
case Route.BYPASS_LAN_CHN =>
Array(getResources.getStringArray(R.array.private_route), getResources.getStringArray(R.array.chn_route))
}
Utils.printToFile(new File(getApplicationInfo.dataDir + "/acl.list"))(p => {
acl.flatten.foreach(p.println)
})
}
val conf = if (profile.kcp) {
ConfigUtils
.SHADOWSOCKS.formatLocal(Locale.ENGLISH, "127.0.0.1", profile.localPort + 90, profile.localPort,
@@ -267,8 +239,7 @@ class ShadowsocksVpnService extends VpnService with BaseService {
p.println(conf)
})
val cmd = new ArrayBuffer[String]
cmd += (getApplicationInfo.dataDir + "/ss-local", "-V"
val cmd = ArrayBuffer[String](getApplicationInfo.dataDir + "/ss-local", "-V"
, "-b", "127.0.0.1"
, "-t", "600"
, "-P", getApplicationInfo.dataDir
@@ -280,9 +251,17 @@ class ShadowsocksVpnService extends VpnService with BaseService {
if (profile.route != Route.ALL) {
cmd += "--acl"
cmd += (getApplicationInfo.dataDir + "/acl.list")
profile.route match {
case Route.BYPASS_LAN => cmd += (getApplicationInfo.dataDir + "/bypass_lan.acl")
case Route.BYPASS_CHN => cmd += (getApplicationInfo.dataDir + "/bypass_chn.acl")
case Route.BYPASS_LAN_CHN => cmd += (getApplicationInfo.dataDir + "/bypass_lan_chn.acl")
case Route.GFWLIST => cmd += (getApplicationInfo.dataDir + "/gfwlist.acl")
case Route.CHINALIST => cmd += (getApplicationInfo.dataDir + "/chinalist.acl")
}
}
if (TcpFastOpen.sendEnabled) cmd += "--fast-open"
if (BuildConfig.DEBUG) Log.d(TAG, cmd.mkString(" "))
sslocalProcess = new GuardedProcess(cmd).start()
@@ -301,15 +280,19 @@ class ShadowsocksVpnService extends VpnService with BaseService {
Utils.printToFile(new File(getApplicationInfo.dataDir + "/ss-tunnel-vpn.conf"))(p => {
p.println(conf)
})
val cmd = new ArrayBuffer[String]
cmd += (getApplicationInfo.dataDir + "/ss-tunnel"
val cmd = ArrayBuffer[String](getApplicationInfo.dataDir + "/ss-tunnel"
, "-V"
, "-t", "10"
, "-b", "127.0.0.1"
, "-L", "8.8.8.8:53"
, "-P", getApplicationInfo.dataDir
, "-c", getApplicationInfo.dataDir + "/ss-tunnel-vpn.conf")
cmd += "-L"
if (profile.route == Route.CHINALIST)
cmd += "114.114.114.114:53"
else
cmd += "8.8.8.8:53"
if (profile.auth) cmd += "-A"
if (BuildConfig.DEBUG) Log.d(TAG, cmd.mkString(" "))
@@ -318,26 +301,35 @@ class ShadowsocksVpnService extends VpnService with BaseService {
}
def startDnsDaemon() {
val ipv6 = if (profile.ipv6) "" else "reject = ::/0;"
val conf = {
if (profile.route == Route.BYPASS_CHN || profile.route == Route.BYPASS_LAN_CHN) {
ConfigUtils.PDNSD_DIRECT.formatLocal(Locale.ENGLISH, getApplicationInfo.dataDir,
"0.0.0.0", profile.localPort + 53, getBlackList, profile.localPort + 63, ipv6)
} else {
ConfigUtils.PDNSD_LOCAL.formatLocal(Locale.ENGLISH, getApplicationInfo.dataDir,
"0.0.0.0", profile.localPort + 53, profile.localPort + 63, ipv6)
val reject = if (profile.ipv6) "224.0.0.0/3" else "224.0.0.0/3, ::/0"
val protect = "protect = \"" + protectPath +"\";"
val conf = profile.route match {
case Route.BYPASS_CHN | Route.BYPASS_LAN_CHN | Route.GFWLIST => {
ConfigUtils.PDNSD_DIRECT.formatLocal(Locale.ENGLISH, protect, getApplicationInfo.dataDir,
"0.0.0.0", profile.localPort + 53, "114.114.114.114, 119.29.29.29, 1.2.4.8",
getBlackList, reject, profile.localPort + 63, reject)
}
case Route.CHINALIST => {
ConfigUtils.PDNSD_DIRECT.formatLocal(Locale.ENGLISH, protect, getApplicationInfo.dataDir,
"0.0.0.0", profile.localPort + 53, "8.8.8.8, 8.8.4.4, 208.67.222.222",
"", reject, profile.localPort + 63, reject)
}
case _ => {
ConfigUtils.PDNSD_LOCAL.formatLocal(Locale.ENGLISH, protect, getApplicationInfo.dataDir,
"0.0.0.0", profile.localPort + 53, profile.localPort + 63, reject)
}
}
Utils.printToFile(new File(getApplicationInfo.dataDir + "/pdnsd-vpn.conf"))(p => {
p.println(conf)
})
val cmd = getApplicationInfo.dataDir + "/pdnsd -c " + getApplicationInfo.dataDir + "/pdnsd-vpn.conf"
val cmd = Array(getApplicationInfo.dataDir + "/pdnsd", "-c", getApplicationInfo.dataDir + "/pdnsd-vpn.conf")
if (BuildConfig.DEBUG) Log.d(TAG, cmd)
if (BuildConfig.DEBUG) Log.d(TAG, cmd.mkString(" "))
pdnsdProcess = new GuardedProcess(cmd.split(" ").toSeq).start()
pdnsdProcess = new GuardedProcess(cmd).start()
}
@SuppressLint(Array("NewApi"))
def startVpn(): Int = {
val builder = new Builder()
@@ -345,7 +337,8 @@ class ShadowsocksVpnService extends VpnService with BaseService {
.setSession(profile.name)
.setMtu(VPN_MTU)
.addAddress(PRIVATE_VLAN.formatLocal(Locale.ENGLISH, "1"), 24)
.addDnsServer("8.8.8.8")
builder.addDnsServer("8.8.8.8")
if (profile.ipv6) {
builder.addAddress(PRIVATE_VLAN6.formatLocal(Locale.ENGLISH, "1"), 126)
@@ -364,7 +357,7 @@ class ShadowsocksVpnService extends VpnService with BaseService {
}
} catch {
case ex: NameNotFoundException =>
Log.e(TAG, "Invalid package name", ex);
Log.e(TAG, "Invalid package name", ex)
}
}
}
@@ -386,45 +379,36 @@ class ShadowsocksVpnService extends VpnService with BaseService {
conn = builder.establish()
if (conn == null) changeState(State.STOPPED, getString(R.string.reboot_required))
} catch {
case ex: IllegalStateException =>
changeState(State.STOPPED, ex.getMessage)
conn = null
case ex: Exception =>
ex.printStackTrace()
conn = null
}
if (conn == null) {
stopRunner(true)
return -1
app.track(ex)
stopRunner(true, ex.getMessage)
return -1
}
val fd = conn.getFd
var cmd = (getApplicationInfo.dataDir +
"/tun2socks --netif-ipaddr %s "
+ "--netif-netmask 255.255.255.0 "
+ "--socks-server-addr 127.0.0.1:%d "
+ "--tunfd %d "
+ "--tunmtu %d "
+ "--sock-path %s "
+ "--loglevel 3")
.formatLocal(Locale.ENGLISH,
PRIVATE_VLAN.formatLocal(Locale.ENGLISH, "2"),
profile.localPort, fd, VPN_MTU, getApplicationInfo.dataDir + "/sock_path")
var cmd = ArrayBuffer[String](getApplicationInfo.dataDir + "/tun2socks",
"--netif-ipaddr", PRIVATE_VLAN.formatLocal(Locale.ENGLISH, "2"),
"--netif-netmask", "255.255.255.0",
"--socks-server-addr", "127.0.0.1:" + profile.localPort,
"--tunfd", fd.toString,
"--tunmtu", VPN_MTU.toString,
"--sock-path", getApplicationInfo.dataDir + "/sock_path",
"--loglevel", "3")
if (profile.ipv6)
cmd += " --netif-ip6addr " + PRIVATE_VLAN6.formatLocal(Locale.ENGLISH, "2")
cmd += ("--netif-ip6addr", PRIVATE_VLAN6.formatLocal(Locale.ENGLISH, "2"))
if (profile.udpdns)
cmd += " --enable-udprelay"
cmd += "--enable-udprelay"
else
cmd += " --dnsgw %s:%d".formatLocal(Locale.ENGLISH, PRIVATE_VLAN.formatLocal(Locale.ENGLISH, "1"),
profile.localPort + 53)
cmd += ("--dnsgw", "%s:%d".formatLocal(Locale.ENGLISH, PRIVATE_VLAN.formatLocal(Locale.ENGLISH, "1"),
profile.localPort + 53))
if (BuildConfig.DEBUG) Log.d(TAG, cmd)
if (BuildConfig.DEBUG) Log.d(TAG, cmd.mkString(" "))
tun2socksProcess = new GuardedProcess(cmd.split(" ").toSeq).start(() => sendFd(fd))
tun2socksProcess = new GuardedProcess(cmd).start(() => sendFd(fd))
fd
}
@@ -44,6 +44,7 @@ import java.util.concurrent.Executors
import android.net.{LocalServerSocket, LocalSocket, LocalSocketAddress}
import android.util.Log
import com.github.shadowsocks.ShadowsocksApplication.app
object ShadowsocksVpnThread {
val getInt = classOf[FileDescriptor].getDeclaredMethod("getInt$")
@@ -56,7 +57,7 @@ class ShadowsocksVpnThread(vpnService: ShadowsocksVpnService) extends Thread {
lazy val PATH = vpnService.getApplicationInfo.dataDir + "/protect_path"
@volatile var isRunning: Boolean = true
@volatile var serverSocket: LocalServerSocket = null
@volatile var serverSocket: LocalServerSocket = _
def closeServerSocket() {
if (serverSocket != null) {
@@ -76,11 +77,7 @@ class ShadowsocksVpnThread(vpnService: ShadowsocksVpnService) extends Thread {
override def run() {
try {
new File(PATH).delete()
} catch {
case _: Exception => // ignore
}
new File(PATH).delete()
try {
val localSocket = new LocalSocket
@@ -89,6 +86,7 @@ class ShadowsocksVpnThread(vpnService: ShadowsocksVpnService) extends Thread {
} catch {
case e: IOException =>
Log.e(TAG, "unable to bind", e)
app.track(e)
return
}
@@ -127,6 +125,7 @@ class ShadowsocksVpnThread(vpnService: ShadowsocksVpnService) extends Thread {
} catch {
case e: Exception =>
Log.e(TAG, "Error when protect socket", e)
app.track(e)
}
// close socket
@@ -140,6 +139,7 @@ class ShadowsocksVpnThread(vpnService: ShadowsocksVpnService) extends Thread {
} catch {
case e: IOException =>
Log.e(TAG, "Error when accept socket", e)
app.track(e)
return
}
}
@@ -64,7 +64,7 @@ object DBHelper {
}
class DBHelper(val context: Context)
extends OrmLiteSqliteOpenHelper(context, DBHelper.PROFILE, null, 19) {
extends OrmLiteSqliteOpenHelper(context, DBHelper.PROFILE, null, 20) {
import DBHelper._
lazy val profileDao: Dao[Profile, Int] = getDao(classOf[Profile])
@@ -129,7 +129,11 @@ class DBHelper(val context: Context)
if (oldVersion < 17) {
profileDao.executeRawNoArgs("ALTER TABLE `profile` ADD COLUMN kcp SMALLINT;")
profileDao.executeRawNoArgs("ALTER TABLE `profile` ADD COLUMN kcpcli VARCHAR DEFAULT '';")
profileDao.executeRawNoArgs("ALTER TABLE `profile` ADD COLUMN kcpcli VARCHAR DEFAULT " +
"'--crypt none --mode normal --mtu 1200 --nocomp --dscp 46 --parityshard 0';")
} else if (oldVersion < 20) {
profileDao.executeRawNoArgs("UPDATE `profile` SET kcpcli = '--crypt none --mode normal --mtu 1200 --nocomp " +
"--dscp 46 --parityshard 0' WHERE kcpcli IS NULL;")
}
if (oldVersion < 18) {
@@ -41,6 +41,7 @@ package com.github.shadowsocks.database
import java.util.Locale
import android.os.Binder
import android.util.Base64
import com.j256.ormlite.field.{DataType, DatabaseField}
@@ -54,8 +55,9 @@ class Profile {
@DatabaseField
var host: String = ""
// hopefully hashCode = mHandle doesn't change, currently this is true from KitKat to Nougat
@DatabaseField
var localPort: Int = 1080
var localPort: Int = 1080 + Binder.getCallingUserHandle.hashCode
@DatabaseField
var remotePort: Int = 8388
@@ -106,7 +108,7 @@ class Profile {
var kcpPort: Int = 8399
@DatabaseField
var kcpcli: String = ""
var kcpcli: String = "--crypt none --mode normal --mtu 1200 --nocomp --dscp 46 --parityshard 0"
override def toString = "ss://" + Base64.encodeToString("%s%s:%s@%s:%d".formatLocal(Locale.ENGLISH,
method, if (auth) "-auth" else "", password, host, remotePort).getBytes, Base64.NO_PADDING | Base64.NO_WRAP)
@@ -53,9 +53,9 @@ class ProfileManager(dbHelper: DBHelper) {
def setProfileAddedListener(listener: Profile => Any) = this.profileAddedListener = listener
def createProfile(p: Profile = null): Profile = {
val profile = if (p == null) new Profile else p
profile.id = 0
try {
val profile = if (p == null) new Profile else p
profile.id = 0
app.currentProfile match {
case Some(oldProfile) =>
// Copy Feature Settings from old profile
@@ -72,12 +72,12 @@ class ProfileManager(dbHelper: DBHelper) {
if (last != null && last.length == 1 && last(0) != null) profile.userOrder = last(0).toInt + 1
dbHelper.profileDao.createOrUpdate(profile)
if (profileAddedListener != null) profileAddedListener(profile)
profile
} catch {
case ex: Exception =>
Log.e(TAG, "addProfile", ex)
p
app.track(ex)
}
profile
}
def updateProfile(profile: Profile): Boolean = {
@@ -87,6 +87,7 @@ class ProfileManager(dbHelper: DBHelper) {
} catch {
case ex: Exception =>
Log.e(TAG, "updateProfile", ex)
app.track(ex)
false
}
}
@@ -100,6 +101,7 @@ class ProfileManager(dbHelper: DBHelper) {
} catch {
case ex: Exception =>
Log.e(TAG, "getProfile", ex)
app.track(ex)
None
}
}
@@ -111,6 +113,7 @@ class ProfileManager(dbHelper: DBHelper) {
} catch {
case ex: Exception =>
Log.e(TAG, "delProfile", ex)
app.track(ex)
false
}
}
@@ -122,6 +125,7 @@ class ProfileManager(dbHelper: DBHelper) {
} catch {
case ex: Exception =>
Log.e(TAG, "getAllProfiles", ex)
app.track(ex)
None
}
}
@@ -133,6 +137,7 @@ class ProfileManager(dbHelper: DBHelper) {
} catch {
case ex: Exception =>
Log.e(TAG, "getAllProfiles", ex)
app.track(ex)
None
}
}
@@ -1,169 +0,0 @@
package com.github.shadowsocks.preferences
import android.content.Context
import android.content.res.TypedArray
import android.preference.Preference
import android.support.annotation.{ArrayRes, NonNull}
import android.support.v7.widget.AppCompatSpinner
import android.util.AttributeSet
import android.view.{View, ViewGroup}
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.{AdapterView, ArrayAdapter}
import com.github.shadowsocks.R
/**
* @author Mygod
*/
final class DropDownPreference(private val mContext: Context, attrs: AttributeSet = null)
extends Preference(mContext, attrs) with SummaryPreference {
private val mAdapter = new ArrayAdapter[String](mContext, android.R.layout.simple_spinner_dropdown_item)
private val mSpinner = new AppCompatSpinner(mContext)
private var mEntries: Array[CharSequence] = _
private var mEntryValues: Array[CharSequence] = _
private var mSelectedIndex: Int = -1
mSpinner.setVisibility(View.INVISIBLE)
mSpinner.setAdapter(mAdapter)
mSpinner.setOnItemSelectedListener(new OnItemSelectedListener {
def onNothingSelected(parent: AdapterView[_]) { }
def onItemSelected(parent: AdapterView[_], view: View, position: Int, id: Long) = {
val value = getValue(position)
if (position != mSelectedIndex && callChangeListener(value)) setValue(position, value)
}
})
setOnPreferenceClickListener((preference: Preference) => {
// TODO: not working with scrolling
// mSpinner.setDropDownVerticalOffset(Utils.dpToPx(getContext, -48 * mSelectedIndex).toInt)
mSpinner.performClick
true
})
val a: TypedArray = mContext.obtainStyledAttributes(attrs, R.styleable.DropDownPreference)
setEntries(a.getTextArray(R.styleable.DropDownPreference_android_entries))
setEntryValues(a.getTextArray(R.styleable.DropDownPreference_android_entryValues))
a.recycle
protected override def getSummaryValue = getEntry
/**
* Sets the human-readable entries to be shown in the list. This will be shown in subsequent dialogs.
*
* Each entry must have a corresponding index in [[setEntryValues(CharSequence[])]].
*
* @param entries The entries.
* @see [[setEntryValues(CharSequence[])]]
*/
def setEntries(entries: Array[CharSequence]) {
mEntries = entries
mAdapter.clear
if (entries != null) for (entry <- entries) mAdapter.add(entry.toString)
}
/**
* @see #setEntries(CharSequence[])
* @param entriesResId The entries array as a resource.
*/
def setEntries(@ArrayRes entriesResId: Int): Unit = setEntries(getContext.getResources.getTextArray(entriesResId))
/**
* The list of entries to be shown in the list in subsequent dialogs.
*
* @return The list as an array.
*/
def getEntries = mEntries
/**
* The array to find the value to save for a preference when an entry from
* entries is selected. If a user clicks on the second item in entries, the
* second item in this array will be saved to the preference.
*
* @param entryValues The array to be used as values to save for the preference.
*/
def setEntryValues(entryValues: Array[CharSequence]) = mEntryValues = entryValues
/**
* @see #setEntryValues(CharSequence[])
* @param entryValuesResId The entry values array as a resource.
*/
def setEntryValues(@ArrayRes entryValuesResId: Int): Unit =
setEntryValues(getContext.getResources.getTextArray(entryValuesResId))
/**
* Returns the array of values to be saved for the preference.
*
* @return The array of values.
*/
def getEntryValues: Array[CharSequence] = mEntryValues
private def getValue(index: Int) = (if (mEntryValues == null) index else mEntryValues(index)).toString
/**
* Sets the value of the key. This should be one of the entries in [[getEntryValues]].
*
* @param value The value to set for the key.
*/
def setValue(value: String): Unit = setValue(findIndexOfValue(value), value)
/**
* Sets the value to the given index from the entry values.
*
* @param index The index of the value to set.
*/
def setValueIndex(index: Int) = setValue(index, getValue(index))
private def setValue(index: Int, value: String) {
persistString(value)
mSelectedIndex = index
mSpinner.setSelection(index)
notifyChanged
}
/**
* Returns the value of the key. This should be one of the entries in [[getEntryValues]].
*
* @return The value of the key.
*/
def getValue = if (mEntryValues == null || mSelectedIndex < 0) null else mEntryValues(mSelectedIndex).toString
/**
* Returns the entry corresponding to the current value.
*
* @return The entry corresponding to the current value, or null.
*/
def getEntry = {
val index = getValueIndex
if (index >= 0 && mEntries != null) mEntries(index) else null
}
/**
* Returns the index of the given value (in the entry values array).
*
* @param value The value whose index should be returned.
* @return The index of the value, or -1 if not found.
*/
def findIndexOfValue(value: String): Int = {
if (value != null && mEntryValues != null) {
var i = mEntryValues.length - 1
while (i >= 0) {
if (mEntryValues(i) == value) return i
i -= 1
}
}
-1
}
def getValueIndex = mSelectedIndex
protected override def onGetDefaultValue(a: TypedArray, index: Int) = a.getString(index)
protected override def onSetInitialValue (restoreValue: Boolean, defaultValue: AnyRef) =
setValue(if (restoreValue) getPersistedString(getValue) else defaultValue.asInstanceOf[String])
def setDropDownWidth(dimenResId: Int) =
mSpinner.setDropDownWidth(mContext.getResources.getDimensionPixelSize(dimenResId))
protected override def onBindView(@NonNull view: View) {
super.onBindView(view)
val parent = mSpinner.getParent.asInstanceOf[ViewGroup]
if (view eq parent) return
if (parent != null) parent.removeView(mSpinner)
view.asInstanceOf[ViewGroup].addView(mSpinner, 0)
val lp = mSpinner.getLayoutParams
lp.width = 0
mSpinner.setLayoutParams(lp)
}
}
@@ -0,0 +1,34 @@
package com.github.shadowsocks.preferences
import android.app.AlertDialog
import android.content.DialogInterface
import eu.chainfire.libsuperuser.Shell
import tk.mygod.preference.EditTextPreferenceDialogFragment
import scala.collection.JavaConverters._
/**
* @author Mygod
*/
class KcpCliPreferenceDialogFragment extends EditTextPreferenceDialogFragment {
override def onPrepareDialogBuilder(builder: AlertDialog.Builder) {
super.onPrepareDialogBuilder(builder)
builder.setNeutralButton("?", ((_, _) => new AlertDialog.Builder(builder.getContext)
.setTitle("?")
.setMessage(Shell.SH.run(builder.getContext.getApplicationInfo.dataDir + "/kcptun --help")
.asScala
.dropWhile(line => line != "GLOBAL OPTIONS:")
.drop(1)
.takeWhile(line => line.length() > 3)
.filter(line =>
!line.startsWith(" --localaddr ") &&
!line.startsWith(" --remoteaddr ") &&
!line.startsWith(" --path ") &&
!line.startsWith(" --help,") &&
!line.startsWith(" --version,"))
.mkString("\n")
.replaceAll(" {2,}", "\n")
.substring(1)) // remove 1st \n
.show()): DialogInterface.OnClickListener)
}
}
@@ -1,68 +0,0 @@
/*
* Shadowsocks - A shadowsocks client for Android
* Copyright (C) 2013 <max.c.lv@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* ___====-_ _-====___
* _--^^^#####// \\#####^^^--_
* _-^##########// ( ) \\##########^-_
* -############// |\^^/| \\############-
* _/############// (@::@) \\############\_
* /#############(( \\// ))#############\
* -###############\\ (oo) //###############-
* -#################\\ / VV \ //#################-
* -###################\\/ \//###################-
* _#/|##########/\######( /\ )######/\##########|\#_
* |/ |#/\#/\#/\/ \#/\##\ | | /##/\#/ \/\#/\#/\#| \|
* ` |/ V V ` V \#\| | | |/#/ V ' V V \| '
* ` ` ` ` / | | | | \ ' ' ' '
* ( | | | | )
* __\ | | | | /__
* (vvv(VVV)(VVV)vvv)
*
* HERE BE DRAGONS
*
*/
package com.github.shadowsocks.preferences
import android.content.Context
import android.preference.EditTextPreference
import android.util.AttributeSet
class PasswordEditTextPreference(context: Context, attrs: AttributeSet, defStyle: Int)
extends EditTextPreference(context, attrs, defStyle) {
def this(context: Context, attrs: AttributeSet) = {
this(context, attrs, android.R.attr.editTextPreferenceStyle)
mDefaultSummary = getSummary
}
override def setText(text: String) {
super.setText(text)
setSummary(text)
}
override def setSummary(summary: CharSequence) {
if (summary.toString.isEmpty) {
super.setSummary(mDefaultSummary)
} else {
super.setSummary(summary.toString.map(c => "*").mkString)
}
}
private var mDefaultSummary: CharSequence = getSummary
}
@@ -1,69 +0,0 @@
/*
* Shadowsocks - A shadowsocks client for Android
* Copyright (C) 2013 <max.c.lv@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* ___====-_ _-====___
* _--^^^#####// \\#####^^^--_
* _-^##########// ( ) \\##########^-_
* -############// |\^^/| \\############-
* _/############// (@::@) \\############\_
* /#############(( \\// ))#############\
* -###############\\ (oo) //###############-
* -#################\\ / VV \ //#################-
* -###################\\/ \//###################-
* _#/|##########/\######( /\ )######/\##########|\#_
* |/ |#/\#/\#/\/ \#/\##\ | | /##/\#/ \/\#/\#/\#| \|
* ` |/ V V ` V \#\| | | |/#/ V ' V V \| '
* ` ` ` ` / | | | | \ ' ' ' '
* ( | | | | )
* __\ | | | | /__
* (vvv(VVV)(VVV)vvv)
*
* HERE BE DRAGONS
*
*/
package com.github.shadowsocks.preferences
import android.content.Context
import android.preference.EditTextPreference
import android.text.TextUtils
import android.util.AttributeSet
class SummaryEditTextPreference(context: Context, attrs: AttributeSet, defStyle: Int)
extends EditTextPreference(context, attrs, defStyle) {
def this(context: Context, attrs: AttributeSet) = {
this(context, attrs, android.R.attr.editTextPreferenceStyle)
mDefaultSummary = getSummary
}
override def setText(text: String) {
super.setText(text)
setSummary(text)
}
override def setSummary(summary: CharSequence) {
if (TextUtils.isEmpty(summary)) {
super.setSummary(mDefaultSummary)
} else {
super.setSummary(summary)
}
}
private var mDefaultSummary: CharSequence = getSummary
}
@@ -1,21 +0,0 @@
package com.github.shadowsocks.preferences
import java.util.Locale
import android.preference.Preference
/**
* Make your preference support %s in summary. Override getSummaryValue to customize what to put in.
* @author Mygod
*/
trait SummaryPreference extends Preference {
protected def getSummaryValue: AnyRef
/**
* Returns the summary of this SummaryPreference. If the summary has a String formatting marker in it
* (i.e. "%s" or "%1$s"), then the current entry value will be substituted in its place.
*
* @return the summary with appropriate string substitution
*/
override def getSummary = super.getSummary.toString.formatLocal(Locale.ENGLISH, getSummaryValue)
}
@@ -4,14 +4,11 @@ package com.github.shadowsocks.utils
* @author Mygod
*/
object CloseUtils {
type Closeable = {
def close()
}
type Disconnectable = {
def disconnect()
}
def autoClose[A <: Closeable, B](x: => A)(block: A => B): B = {
def autoClose[A <: AutoCloseable, B](x: => A)(block: A => B): B = {
var a: Option[A] = None
try {
a = Some(x)
@@ -69,11 +69,11 @@ object ConfigUtils {
"""
|global {
| perm_cache = 2048;
| %s
| cache_dir = "%s";
| server_ip = %s;
| server_port = %d;
| query_method = tcp_only;
| run_ipv4 = on;
| min_ttl = 15m;
| max_ttl = 1w;
| timeout = 10;
@@ -84,10 +84,9 @@ object ConfigUtils {
| label = "local";
| ip = 127.0.0.1;
| port = %d;
| %s
| reject = %s;
| reject_policy = negate;
| reject_recursively = on;
| timeout = 5;
|}
|
|rr {
@@ -103,32 +102,36 @@ object ConfigUtils {
"""
|global {
| perm_cache = 2048;
| %s
| cache_dir = "%s";
| server_ip = %s;
| server_port = %d;
| query_method = tcp_only;
| run_ipv4 = on;
| query_method = udp_only;
| min_ttl = 15m;
| max_ttl = 1w;
| timeout = 10;
| daemon = off;
| par_queries = 4;
|}
|
|server {
| label = "china-servers";
| ip = 114.114.114.114, 112.124.47.27;
| timeout = 4;
| exclude = %s;
| label = "remote-servers";
| ip = %s;
| timeout = 3;
| query_method = udp_only;
| %s
| policy = included;
| uptest = none;
| preset = on;
| reject = %s;
| reject_policy = fail;
| reject_recursively = on;
|}
|
|server {
| label = "local-server";
| ip = 127.0.0.1;
| query_method = tcp_only;
| port = %d;
| %s
| reject = %s;
| reject_policy = negate;
| reject_recursively = on;
|}
@@ -171,6 +174,9 @@ object Key {
val kcp = "kcp"
val kcpPort = "kcpPort"
val kcpcli = "kcpcli"
val tfo = "tcp_fastopen"
val currentVersionCode = "currentVersionCode"
}
object State {
@@ -192,4 +198,6 @@ object Route {
val BYPASS_LAN = "bypass-lan"
val BYPASS_CHN = "bypass-china"
val BYPASS_LAN_CHN = "bypass-lan-china"
val GFWLIST = "gfwlist"
val CHINALIST = "china-list"
}
@@ -0,0 +1,40 @@
package com.github.shadowsocks.utils
import java.io.File
import eu.chainfire.libsuperuser.Shell
import scala.collection.JavaConverters._
/**
* @author Mygod
*/
object TcpFastOpen {
/**
* Is kernel version >= 3.7.1.
*/
lazy val supported = "^(\\d+)\\.(\\d+)\\.(\\d+)".r.findFirstMatchIn(System.getProperty("os.version")) match {
case Some(m) =>
val kernel = m.group(1).toInt
if (kernel < 3) false else if (kernel > 3) true else {
val major = m.group(2).toInt
if (major < 7) false else if (major > 7) true else m.group(3).toInt >= 1
}
case _ => false
}
def sendEnabled = {
val file = new File("/proc/sys/net/ipv4/tcp_fastopen")
file.canRead && (Utils.readAllLines(file).toInt & 1) > 0
}
def enabled(value: Boolean): String = if (sendEnabled != value) {
val res = Shell.run("su", Array(
"if echo " + (if (value) 3 else 0) + " > /proc/sys/net/ipv4/tcp_fastopen; then",
" echo Success.",
"else",
" echo Failed.",
"fi"), null, true)
if (res != null) res.asScala.mkString("\n") else null
} else null
}
@@ -46,13 +46,14 @@ import java.util.concurrent.Executors
import android.content.Context
import android.net.{LocalServerSocket, LocalSocket, LocalSocketAddress}
import android.util.Log
import com.github.shadowsocks.ShadowsocksApplication.app
class TrafficMonitorThread(context: Context) extends Thread {
val TAG = "TrafficMonitorThread"
lazy val PATH = context.getApplicationInfo.dataDir + "/stat_path"
@volatile var serverSocket: LocalServerSocket = null
@volatile var serverSocket: LocalServerSocket = _
@volatile var isRunning: Boolean = true
def closeServerSocket() {
@@ -73,11 +74,7 @@ class TrafficMonitorThread(context: Context) extends Thread {
override def run() {
try {
new File(PATH).delete()
} catch {
case _: Exception => // ignore
}
new File(PATH).delete()
try {
val localSocket = new LocalSocket
@@ -113,6 +110,7 @@ class TrafficMonitorThread(context: Context) extends Thread {
} catch {
case e: Exception =>
Log.e(TAG, "Error when recv traffic stat", e)
app.track(e)
}
// close socket
@@ -126,6 +124,7 @@ class TrafficMonitorThread(context: Context) extends Thread {
} catch {
case e: IOException =>
Log.e(TAG, "Error when accept socket", e)
app.track(e)
return
}
}
@@ -38,15 +38,16 @@
*/
package com.github.shadowsocks.utils
import java.io.File
import java.net._
import java.security.MessageDigest
import java.util.{Scanner, StringTokenizer}
import android.animation.{Animator, AnimatorListenerAdapter}
import android.content.pm.PackageManager
import android.content.{Context, Intent}
import android.graphics._
import android.os.Build
import android.provider.Settings
import android.util.{Base64, DisplayMetrics, Log}
import android.view.View.MeasureSpec
import android.view.{Gravity, View, Window}
@@ -56,6 +57,8 @@ import com.github.shadowsocks.{BuildConfig, ShadowsocksRunnerService}
import eu.chainfire.libsuperuser.Shell
import org.xbill.DNS._
import scala.collection.JavaConversions._
import scala.collection.mutable.ArrayBuffer
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.util.{Failure, Try}
@@ -109,6 +112,13 @@ object Utils {
})
}
def readAllLines(f: File) = {
val scanner = new Scanner(f)
try {
scanner.useDelimiter("\\Z")
scanner.next()
} finally scanner.close()
}
def printToFile(f: java.io.File)(op: java.io.PrintWriter => Unit) {
val p = new java.io.PrintWriter(f)
try {
@@ -118,6 +128,48 @@ object Utils {
}
}
/**
* Crack a command line.
* Based on: https://github.com/apache/ant/blob/588ce1f/src/main/org/apache/tools/ant/types/Commandline.java#L471
* @param toProcess the command line to process.
* @return the command line broken into strings.
* An empty or null toProcess parameter results in a zero sized ArrayBuffer.
*/
def translateCommandline(toProcess: String): ArrayBuffer[String] = {
if (toProcess == null || toProcess.length == 0) return ArrayBuffer[String]()
val tok = new StringTokenizer(toProcess, "\"' ", true)
val result = ArrayBuffer[String]()
val current = new StringBuilder()
var quote = ' '
var last = " "
while (tok.hasMoreTokens) {
val nextTok = tok.nextToken
quote match {
case '\'' => nextTok match {
case "'" => quote = ' '
case _ => current.append(nextTok)
}
case '"' => nextTok match {
case "\"" => quote = ' '
case _ => current.append(nextTok)
}
case _ => nextTok match {
case "'" => quote = '\''
case "\"" => quote = '"'
case " " => if (last != " ") {
result.append(current.toString)
current.setLength(0)
}
case _ => current.append(nextTok)
}
}
last = nextTok
}
if (current.nonEmpty) result.append(current.toString)
if (quote == '\'' || quote == '"') throw new Exception("Unbalanced quotes in " + toProcess)
result
}
// Because /sys/class/net/* isn't accessible since API level 24
final val FLUSH_DNS = "for if in /sys/class/net/*; do " +
"if [ \"down\" != $(cat $if/operstate) ]; then " + // up or unknown
@@ -128,25 +180,7 @@ object Utils {
// Blocked > 3 seconds
def toggleAirplaneMode(context: Context) = {
val result = Shell.SU.run(FLUSH_DNS)
if (result != null && !result.isEmpty) true else if (Build.VERSION.SDK_INT < 17) {
toggleBelowApiLevel17(context)
true
} else false
}
//noinspection ScalaDeprecation
private def toggleBelowApiLevel17(context: Context) {
// Android 4.2 below
Settings.System.putInt(context.getContentResolver, Settings.System.AIRPLANE_MODE_ON, 1)
val enableIntent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED)
enableIntent.putExtra("state", true)
context.sendBroadcast(enableIntent)
Thread.sleep(3000)
Settings.System.putInt(context.getContentResolver, Settings.System.AIRPLANE_MODE_ON, 0)
val disableIntent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED)
disableIntent.putExtra("state", false)
context.sendBroadcast(disableIntent)
result != null && !result.isEmpty
}
def resolve(host: String, addrType: Int): Option[String] = {
@@ -210,29 +244,22 @@ object Utils {
*/
def isIPv6Support: Boolean = {
try {
val interfaces = NetworkInterface.getNetworkInterfaces
while (interfaces.hasMoreElements) {
val intf = interfaces.nextElement()
val addrs = intf.getInetAddresses
while (addrs.hasMoreElements) {
val addr = addrs.nextElement()
if (!addr.isLoopbackAddress && !addr.isLinkLocalAddress) {
if (addr.isInstanceOf[Inet6Address]) {
if (BuildConfig.DEBUG) Log.d(TAG, "IPv6 address detected")
return true
}
for (intf <- enumerationAsScalaIterator(NetworkInterface.getNetworkInterfaces))
for (addr <- enumerationAsScalaIterator(intf.getInetAddresses))
if (addr.isInstanceOf[Inet6Address] && !addr.isLoopbackAddress && !addr.isLinkLocalAddress) {
if (BuildConfig.DEBUG) Log.d(TAG, "IPv6 address detected")
return true
}
}
}
} catch {
case ex: Exception =>
Log.e(TAG, "Failed to get interfaces' addresses.", ex)
app.track(ex)
}
false
}
def startSsService(context: Context) {
val isInstalled: Boolean = app.settings.getBoolean(app.getVersionName, false)
val isInstalled = app.settings.getInt(Key.currentVersionCode, -1) == BuildConfig.VERSION_CODE
if (!isInstalled) return
val intent = new Intent(context, classOf[ShadowsocksRunnerService])
@@ -245,7 +272,9 @@ object Utils {
}
private val handleFailure: Try[_] => Unit = {
case Failure(e) => e.printStackTrace()
case Failure(e) =>
e.printStackTrace()
app.track(e)
case _ =>
}
@@ -0,0 +1,32 @@
package tk.mygod.preference
import android.content.Context
import android.support.v7.preference.{EditTextPreference => Parent}
import android.support.v7.widget.AppCompatEditText
import android.text.InputType
import android.util.AttributeSet
/**
* Fixed EditTextPreference + SummaryPreference with password support!
* Based on: https://github.com/Gericop/Android-Support-Preference-V7-Fix/tree/master/app/src/main/java/android/support/v7/preference
*/
class EditTextPreference(context: Context, attrs: AttributeSet = null) extends Parent(context, attrs)
with SummaryPreference {
val editText = new AppCompatEditText(context, attrs)
editText.setId(android.R.id.edit)
override protected def getSummaryValue = {
var text = getText
if (text == null) text = ""
val inputType = editText.getInputType
if (inputType == (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD) ||
inputType == (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD) ||
inputType == (InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD))
"\u2022" * text.length else text
}
override def setText(text: String) = {
super.setText(text)
notifyChanged
}
}
@@ -0,0 +1,30 @@
package tk.mygod.preference
import android.content.Context
import android.support.v14.preference.PreferenceDialogFragment
import android.view.{View, ViewGroup}
class EditTextPreferenceDialogFragment extends PreferenceDialogFragment {
private lazy val preference = getPreference.asInstanceOf[EditTextPreference]
private lazy val editText = preference.editText
override protected def onCreateDialogView(context: Context) = {
val parent = editText.getParent.asInstanceOf[ViewGroup]
if (parent != null) parent.removeView(editText)
editText
}
override protected def onBindDialogView(view: View) {
super.onBindDialogView(view)
editText.setText(preference.getText)
val text = editText.getText
if (text != null) editText.setSelection(0, text.length)
}
override protected def needInputMethod = true
def onDialogClosed(positiveResult: Boolean) = if (positiveResult) {
val value = editText.getText.toString
if (preference.callChangeListener(value)) preference.setText(value)
}
}
@@ -1,20 +1,40 @@
package com.github.shadowsocks.preferences
package tk.mygod.preference
import android.content.Context
import android.content.res.TypedArray
import android.os.Bundle
import android.preference.DialogPreference
import android.support.v7.preference.DialogPreference
import android.util.AttributeSet
import android.view.{ViewGroup, WindowManager}
import android.view.View
import android.view.ViewGroup.LayoutParams
import android.widget.NumberPicker
import android.widget.EditText
import com.github.shadowsocks.R
/**
* @author Mygod
*/
final class NumberPickerPreference(context: Context, attrs: AttributeSet = null)
class MyNumberPicker(private val context: Context, attrs: AttributeSet = null)
extends NumberPicker(context, attrs) {
override def addView(child: View) {
super.addView(child)
updateView(child)
}
override def addView(child: View, params: LayoutParams) {
super.addView(child, params)
updateView(child)
}
override def addView(child: View, index: Int, params: LayoutParams) {
super.addView(child, index, params)
updateView(child)
}
def updateView(child: View) {
if (child.isInstanceOf[EditText]) {
child.asInstanceOf[EditText].setTextSize(dp2px(6))
}
}
def dp2px(dp: Float): Int = (dp*getResources().getDisplayMetrics().density).toInt
}
class NumberPickerPreference(private val context: Context, attrs: AttributeSet = null)
extends DialogPreference(context, attrs) with SummaryPreference {
private val picker = new NumberPicker(context)
private[preference] val picker = new MyNumberPicker(context)
private var value: Int = _
{
@@ -28,7 +48,7 @@ final class NumberPickerPreference(context: Context, attrs: AttributeSet = null)
def getMin = if (picker == null) 0 else picker.getMinValue
def getMax = picker.getMaxValue
def setValue(i: Int) {
if (i == getValue) return
if (i == value) return
picker.setValue(i)
value = picker.getValue
persistInt(value)
@@ -37,28 +57,8 @@ final class NumberPickerPreference(context: Context, attrs: AttributeSet = null)
def setMin(value: Int) = picker.setMinValue(value)
def setMax(value: Int) = picker.setMaxValue(value)
override protected def showDialog(state: Bundle) {
super.showDialog(state)
getDialog.getWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
}
override protected def onCreateDialogView = {
val parent = picker.getParent.asInstanceOf[ViewGroup]
if (parent != null) parent.removeView(picker)
picker
}
override protected def onDialogClosed(positiveResult: Boolean) {
picker.clearFocus // commit changes
super.onDialogClosed(positiveResult) // forward compatibility
if (positiveResult) {
val value = picker.getValue
if (callChangeListener(value)) {
setValue(value)
return
}
}
picker.setValue(value)
}
override protected def onGetDefaultValue(a: TypedArray, index: Int) = a.getInt(index, getMin).asInstanceOf[AnyRef]
override protected def onGetDefaultValue(a: TypedArray, index: Int): AnyRef =
a.getInt(index, getMin).asInstanceOf[AnyRef]
override protected def onSetInitialValue(restorePersistedValue: Boolean, defaultValue: Any) {
val default = defaultValue.asInstanceOf[Int]
setValue(if (restorePersistedValue) getPersistedInt(default) else default)
@@ -0,0 +1,36 @@
package tk.mygod.preference
import android.content.Context
import android.support.v14.preference.PreferenceDialogFragment
import android.view.inputmethod.InputMethodManager
import android.view.{View, ViewGroup}
class NumberPickerPreferenceDialogFragment extends PreferenceDialogFragment {
private lazy val preference = getPreference.asInstanceOf[NumberPickerPreference]
private lazy val picker = preference.picker
private lazy val inputMethodManager =
getActivity.getSystemService(Context.INPUT_METHOD_SERVICE).asInstanceOf[InputMethodManager]
override protected def onCreateDialogView(context: Context) = {
val parent = picker.getParent.asInstanceOf[ViewGroup]
if (parent != null) parent.removeView(picker)
picker
}
override protected def onBindDialogView(view: View) {
super.onBindDialogView(view)
picker.setValue(preference.getValue)
}
override protected def needInputMethod = true
def onDialogClosed(positiveResult: Boolean) {
picker.clearFocus // commit changes
if (positiveResult) {
val value = picker.getValue
if (preference.callChangeListener(value)) preference.setValue(value)
}
inputMethodManager.hideSoftInputFromWindow(getActivity.getCurrentFocus.getWindowToken,
InputMethodManager.HIDE_NOT_ALWAYS)
}
}
@@ -0,0 +1,18 @@
package tk.mygod.preference
import android.content.Context
import android.support.v7.preference.{PreferenceViewHolder, PreferenceCategory => Base}
import android.util.AttributeSet
import android.view.ViewGroup.MarginLayoutParams
/**
* Based on: https://github.com/Gericop/Android-Support-Preference-V7-Fix/blob/4c2bb2896895dbedb37b659b36bd2a96b33c1605/preference-v7/src/main/java/com/takisoft/fix/support/v7/preference/PreferenceCategory.java
*
* @author Mygod
*/
class PreferenceCategory(context: Context, attrs: AttributeSet = null) extends Base(context, attrs) {
override def onBindViewHolder(holder: PreferenceViewHolder) {
super.onBindViewHolder(holder)
holder.findViewById(android.R.id.title).getLayoutParams.asInstanceOf[MarginLayoutParams].bottomMargin = 0
}
}
@@ -0,0 +1,27 @@
package tk.mygod.preference
import android.app.DialogFragment
import android.os.Bundle
import android.support.v14.preference.{PreferenceFragment => Base}
import android.support.v7.preference.PreferenceScreen
import android.view.{LayoutInflater, ViewGroup}
abstract class PreferenceFragment extends Base {
override def onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle) =
super.onCreateView(inflater, container, savedInstanceState)
protected final def displayPreferenceDialog(key: String, fragment: DialogFragment) {
val bundle = new Bundle(1)
bundle.putString("key", key)
fragment.setArguments(bundle)
fragment.setTargetFragment(this, 0)
fragment.show(getFragmentManager, "android.support.v14.preference.PreferenceFragment.DIALOG")
}
override protected def onCreateAdapter(screen: PreferenceScreen) = new PreferenceGroupAdapter(screen)
override def onResume {
super.onResume
getListView.scrollBy(0, 0)
}
}
@@ -0,0 +1,65 @@
package tk.mygod.preference
import java.lang.reflect.Field
import java.util.List
import android.os.Build
import android.support.v4.content.ContextCompat
import android.support.v4.view.ViewCompat
import android.support.v7.preference.{PreferenceGroup, PreferenceViewHolder, PreferenceGroupAdapter => Old}
import android.view.{LayoutInflater, View, ViewGroup}
import com.github.shadowsocks.R
/**
* Fix by: https://github.com/Gericop/Android-Support-Preference-V7-Fix/commit/7de016b007e28a264001a8bb353f110a7f64bb69
*
* @author Mygod
*/
object PreferenceGroupAdapter {
private var preferenceLayoutsField: Field = _
private var fieldResId: Field = _
private var fieldWidgetResId: Field = _
private val preferenceViewHolderConstructor = classOf[PreferenceViewHolder].getDeclaredConstructor(classOf[View])
{
val oldClass = classOf[Old]
preferenceLayoutsField = oldClass.getDeclaredField("mPreferenceLayouts")
preferenceLayoutsField.setAccessible(true)
val c = oldClass.getDeclaredClasses.filter(c => c.getSimpleName == "PreferenceLayout").head
fieldResId = c.getDeclaredField("resId")
fieldResId.setAccessible(true)
fieldWidgetResId = c.getDeclaredField("widgetResId")
fieldWidgetResId.setAccessible(true)
preferenceViewHolderConstructor.setAccessible(true)
}
}
class PreferenceGroupAdapter(group: PreferenceGroup) extends Old(group) {
import PreferenceGroupAdapter._
protected lazy val preferenceLayouts = preferenceLayoutsField.get(this).asInstanceOf[List[AnyRef]]
override def onCreateViewHolder(parent: ViewGroup, viewType: Int) = if (Build.VERSION.SDK_INT < 21) {
val context = parent.getContext
val inflater = LayoutInflater.from(context)
val pl = preferenceLayouts.get(viewType)
val view = inflater.inflate(fieldResId.get(pl).asInstanceOf[Int], parent, false)
if (view.getBackground == null) {
val array = context.obtainStyledAttributes(null, R.styleable.BackgroundStyle)
var background = array.getDrawable(R.styleable.BackgroundStyle_android_selectableItemBackground)
if (background == null)
background = ContextCompat.getDrawable(context, android.R.drawable.list_selector_background)
array.recycle
val (s, t, e, b) = (ViewCompat.getPaddingStart(view), view.getPaddingTop,
ViewCompat.getPaddingEnd(view), view.getPaddingBottom)
view.setBackground(background)
ViewCompat.setPaddingRelative(view, s, t, e, b)
}
val widgetFrame = view.findViewById(android.R.id.widget_frame).asInstanceOf[ViewGroup]
if (widgetFrame != null) {
val widgetResId = fieldWidgetResId.get(pl).asInstanceOf[Int]
if (widgetResId != 0) inflater.inflate(widgetResId, widgetFrame) else widgetFrame.setVisibility(View.GONE)
}
preferenceViewHolderConstructor.newInstance(view)
} else super.onCreateViewHolder(parent, viewType)
}
+25
View File
@@ -0,0 +1,25 @@
package tk.mygod.preference
import android.support.v7.preference.Preference
/**
* Make your preference support %s in summary. Override getSummaryValue to customize what to put in.
* Based on:
* https://github.com/android/platform_frameworks_base/blob/master/core/java/android/preference/ListPreference.java
*
* @author Mygod
*/
trait SummaryPreference extends Preference {
protected def getSummaryValue: AnyRef
/**
* Returns the summary of this SummaryPreference. If the summary has a String formatting marker in it
* (i.e. "%s" or "%1$s"), then the current entry value will be substituted in its place.
*
* @return the summary with appropriate string substitution
*/
override def getSummary = {
val summary = super.getSummary
if (summary == null) null else String.format(summary.toString, getSummaryValue)
}
}