forked from shadowsocks/shadowsocks-android
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMainActivity.kt
273 lines (250 loc) · 11.9 KB
/
MainActivity.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
/*******************************************************************************
* *
* Copyright (C) 2017 by Max Lv <[email protected]> *
* Copyright (C) 2017 by Mygod Studio <[email protected]> *
* *
* 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/>. *
* *
*******************************************************************************/
package com.github.shadowsocks
import android.app.Activity
import android.app.backup.BackupManager
import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.VpnService
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.RemoteException
import android.view.*
import androidx.appcompat.app.AppCompatActivity
import androidx.browser.customtabs.CustomTabColorSchemeParams
import androidx.browser.customtabs.CustomTabsIntent
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import androidx.core.view.GravityCompat
import androidx.core.view.updateLayoutParams
import androidx.drawerlayout.widget.DrawerLayout
import androidx.preference.PreferenceDataStore
import com.github.shadowsocks.acl.CustomRulesFragment
import com.github.shadowsocks.aidl.IShadowsocksService
import com.github.shadowsocks.aidl.ShadowsocksConnection
import com.github.shadowsocks.aidl.TrafficStats
import com.github.shadowsocks.bg.BaseService
import com.github.shadowsocks.preference.DataStore
import com.github.shadowsocks.preference.OnPreferenceDataStoreChangeListener
import com.github.shadowsocks.subscription.SubscriptionFragment
import com.github.shadowsocks.utils.Key
import com.github.shadowsocks.utils.SingleInstanceActivity
import com.github.shadowsocks.widget.ListHolderListener
import com.github.shadowsocks.widget.ServiceButton
import com.github.shadowsocks.widget.StatsBar
import com.google.android.material.navigation.NavigationView
import com.google.android.material.snackbar.Snackbar
import com.google.firebase.analytics.ktx.analytics
import com.google.firebase.analytics.ktx.logEvent
import com.google.firebase.ktx.Firebase
import timber.log.Timber
class MainActivity : AppCompatActivity(), ShadowsocksConnection.Callback, OnPreferenceDataStoreChangeListener,
NavigationView.OnNavigationItemSelectedListener {
companion object {
private const val REQUEST_CONNECT = 1
var stateListener: ((BaseService.State) -> Unit)? = null
}
// UI
private lateinit var fab: ServiceButton
private lateinit var stats: StatsBar
internal lateinit var drawer: DrawerLayout
private lateinit var navigation: NavigationView
lateinit var snackbar: CoordinatorLayout private set
fun snackbar(text: CharSequence = "") = Snackbar.make(snackbar, text, Snackbar.LENGTH_LONG).apply {
anchorView = fab
}
private val customTabsIntent by lazy {
CustomTabsIntent.Builder().apply {
setColorScheme(CustomTabsIntent.COLOR_SCHEME_SYSTEM)
setColorSchemeParams(CustomTabsIntent.COLOR_SCHEME_LIGHT, CustomTabColorSchemeParams.Builder().apply {
setToolbarColor(ContextCompat.getColor(this@MainActivity, R.color.light_color_primary))
}.build())
setColorSchemeParams(CustomTabsIntent.COLOR_SCHEME_DARK, CustomTabColorSchemeParams.Builder().apply {
setToolbarColor(ContextCompat.getColor(this@MainActivity, R.color.dark_color_primary))
}.build())
}.build()
}
fun launchUrl(uri: String) = try {
customTabsIntent.launchUrl(this, uri.toUri())
} catch (_: ActivityNotFoundException) {
snackbar(uri).show()
}
// service
var state = BaseService.State.Idle
override fun stateChanged(state: BaseService.State, profileName: String?, msg: String?) =
changeState(state, msg, true)
override fun trafficUpdated(profileId: Long, stats: TrafficStats) {
if (profileId == 0L) [email protected](
stats.txRate, stats.rxRate, stats.txTotal, stats.rxTotal)
if (state != BaseService.State.Stopping) {
(supportFragmentManager.findFragmentById(R.id.fragment_holder) as? ProfilesFragment)
?.onTrafficUpdated(profileId, stats)
}
}
override fun trafficPersisted(profileId: Long) {
ProfilesFragment.instance?.onTrafficPersisted(profileId)
}
private fun changeState(state: BaseService.State, msg: String? = null, animate: Boolean = false) {
fab.changeState(state, this.state, animate)
stats.changeState(state)
if (msg != null) snackbar(getString(R.string.vpn_error, msg)).show()
this.state = state
ProfilesFragment.instance?.profilesAdapter?.notifyDataSetChanged() // refresh button enabled state
stateListener?.invoke(state)
}
private fun toggle() = when {
state.canStop -> Core.stopService()
DataStore.serviceMode == Key.modeVpn -> {
val intent = VpnService.prepare(this)
if (intent != null) startActivityForResult(intent, REQUEST_CONNECT)
else onActivityResult(REQUEST_CONNECT, Activity.RESULT_OK, null)
}
else -> Core.startService()
}
private val handler = Handler(Looper.getMainLooper())
private val connection = ShadowsocksConnection(handler, true)
override fun onServiceConnected(service: IShadowsocksService) = changeState(try {
BaseService.State.values()[service.state]
} catch (_: RemoteException) {
BaseService.State.Idle
})
override fun onServiceDisconnected() = changeState(BaseService.State.Idle)
override fun onBinderDied() {
connection.disconnect(this)
connection.connect(this, this)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when {
requestCode != REQUEST_CONNECT -> super.onActivityResult(requestCode, resultCode, data)
resultCode == Activity.RESULT_OK -> Core.startService()
else -> {
snackbar().setText(R.string.vpn_permission_denied).show()
Timber.e("Failed to start VpnService from onActivityResult: $data")
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
SingleInstanceActivity.register(this) ?: return
setContentView(R.layout.layout_main)
snackbar = findViewById(R.id.snackbar)
snackbar.setOnApplyWindowInsetsListener(ListHolderListener)
stats = findViewById(R.id.stats)
stats.setOnClickListener { if (state == BaseService.State.Connected) stats.testConnection() }
drawer = findViewById(R.id.drawer)
drawer.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
navigation = findViewById(R.id.navigation)
navigation.setNavigationItemSelectedListener(this)
if (savedInstanceState == null) {
navigation.menu.findItem(R.id.profiles).isChecked = true
displayFragment(ProfilesFragment())
}
fab = findViewById(R.id.fab)
fab.setOnClickListener { toggle() }
fab.setOnApplyWindowInsetsListener { view, insets ->
view.updateLayoutParams<ViewGroup.MarginLayoutParams> {
bottomMargin = insets.systemWindowInsetBottom +
resources.getDimensionPixelOffset(R.dimen.mtrl_bottomappbar_fab_bottom_margin)
}
insets
}
changeState(BaseService.State.Idle) // reset everything to init state
connection.connect(this, this)
DataStore.publicStore.registerChangeListener(this)
}
override fun onPreferenceDataStoreChanged(store: PreferenceDataStore, key: String) {
when (key) {
Key.serviceMode -> handler.post {
connection.disconnect(this)
connection.connect(this, this)
}
}
}
private fun displayFragment(fragment: ToolbarFragment) {
supportFragmentManager.beginTransaction().replace(R.id.fragment_holder, fragment).commitAllowingStateLoss()
drawer.closeDrawers()
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
if (item.isChecked) drawer.closeDrawers() else {
when (item.itemId) {
R.id.profiles -> {
displayFragment(ProfilesFragment())
connection.bandwidthTimeout = connection.bandwidthTimeout // request stats update
}
R.id.globalSettings -> displayFragment(GlobalSettingsFragment())
R.id.about -> {
Firebase.analytics.logEvent("about") { }
displayFragment(AboutFragment())
}
R.id.faq -> {
launchUrl(getString(R.string.faq_url))
return true
}
R.id.customRules -> displayFragment(CustomRulesFragment())
R.id.subscriptions -> displayFragment(SubscriptionFragment())
else -> return false
}
item.isChecked = true
}
return true
}
override fun onStart() {
super.onStart()
connection.bandwidthTimeout = 500
}
override fun onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) drawer.closeDrawers() else {
val currentFragment = supportFragmentManager.findFragmentById(R.id.fragment_holder) as ToolbarFragment
if (!currentFragment.onBackPressed()) {
if (currentFragment is ProfilesFragment) super.onBackPressed() else {
navigation.menu.findItem(R.id.profiles).isChecked = true
displayFragment(ProfilesFragment())
}
}
}
}
override fun onKeyShortcut(keyCode: Int, event: KeyEvent) = when {
keyCode == KeyEvent.KEYCODE_G && event.hasModifiers(KeyEvent.META_CTRL_ON) -> {
toggle()
true
}
keyCode == KeyEvent.KEYCODE_T && event.hasModifiers(KeyEvent.META_CTRL_ON) -> {
stats.testConnection()
true
}
else -> (supportFragmentManager.findFragmentById(R.id.fragment_holder) as ToolbarFragment).toolbar.menu.let {
it.setQwertyMode(KeyCharacterMap.load(event.deviceId).keyboardType != KeyCharacterMap.NUMERIC)
it.performShortcut(keyCode, event, 0)
}
}
override fun onStop() {
connection.bandwidthTimeout = 0
super.onStop()
}
override fun onDestroy() {
super.onDestroy()
DataStore.publicStore.unregisterChangeListener(this)
connection.disconnect(this)
BackupManager(this).dataChanged()
handler.removeCallbacksAndMessages(null)
}
}