Compare commits

..

30 Commits

Author SHA1 Message Date
Jason A. Donenfeld e5f6c24174 Bump version
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-04 07:16:10 +02:00
Jason A. Donenfeld 4cad06b7ce app: disable proguard
It's mostly a hindrance to debugging.

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-04 07:16:10 +02:00
Jason A. Donenfeld c4e32328fc TunnelManager: disable dangerous intents for now
We need to think about how to allow this securely. It's not okay for all
apps to be allowed to twiddle with VPN settings.

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-04 07:06:28 +02:00
Jason A. Donenfeld a2ccbf003c TunnelManager: new intents
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-04 07:06:28 +02:00
Jason A. Donenfeld 10ca2c8681 Preferences: don't use round icon
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-03 16:15:30 +02:00
Harsh Shandilya fd63e496e5 Preferences: Move version pref to top and add icon
Signed-off-by: Harsh Shandilya <me@msfjarvis.dev>
2018-06-02 19:35:11 +02:00
Jason A. Donenfeld 567503abc7 Backends: print versions somewhere in log
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-02 19:26:33 +02:00
Harsh Shandilya 4671f59c67 android: Cleanup classes
- Use final modifer wherever possible
- Use try-with-resources for input/output streams

Signed-off-by: Harsh Shandilya <me@msfjarvis.dev>
2018-06-02 19:14:56 +02:00
Harsh Shandilya 4986d92f3d crypto: KeyEncoding: Fix style
- Replace python style variable names with camel case
- Don't declare multiple variables in the same line

Signed-off-by: Harsh Shandilya <me@msfjarvis.dev>
2018-06-02 19:12:30 +02:00
Jason A. Donenfeld 0b1c7cc35f Topic: John does things differently
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-02 18:44:35 +02:00
Jason A. Donenfeld 9e278c88e6 ExporterPreferences: disable control immediately
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-02 18:38:56 +02:00
Jason A. Donenfeld c3246060f5 Preferences: add log exporter
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-02 18:35:09 +02:00
Jason A. Donenfeld b7e025e381 libwg-go: fix style
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-01 18:27:30 +02:00
Jason A. Donenfeld 858ec4c0ab Version bump
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-01 18:01:25 +02:00
Jason A. Donenfeld 65292aaa79 Topic: make reentrant
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-01 17:34:59 +02:00
Jason A. Donenfeld 3d57eb633e BaseActivity: flush themed icon cache on theme change
The most terrible hack you have ever seen.

The drawable cache isn't properly flushed when changing the theme -- a
frameworks bug, evidently -- so we work around it by digging deep into
the mud.

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-01 16:48:08 +02:00
Jason A. Donenfeld 1e45898d70 Settings: add version
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-01 16:06:56 +02:00
Jason A. Donenfeld 61431fb579 colors: final touches
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-01 15:18:23 +02:00
Harsh Shandilya 00d48e867b ui: Use better list colors in night mode
Signed-off-by: Harsh Shandilya <me@msfjarvis.dev>
2018-06-01 18:42:20 +05:30
Harsh Shandilya d5df0c10ab TunnelListFragment: Dejank action mode title
When unselecting items, the toolbar briefly says
'0 items selected' before it reverts back to the
non-action mode toolbar which feels janky at best.

To mitigate this, just set a blank title to the action
mode toolbar when item count is 0, to facilitate the
smoothness of the transition to non-action mode toolbar.

Signed-off-by: Harsh Shandilya <me@msfjarvis.dev>
2018-06-01 18:42:20 +05:30
Harsh Shandilya af814951f3 fab: Make label responsive to night mode
Signed-off-by: Harsh Shandilya <me@msfjarvis.dev>
2018-06-01 18:42:20 +05:30
Harsh Shandilya a54a03aa2f FloatingActionButton: Cleanup declaration of TranslucentLayerDrawable class
Signed-off-by: Harsh Shandilya <me@msfjarvis.dev>
2018-06-01 18:42:20 +05:30
Harsh Shandilya 4edfdd8f3b FloatingActionButton: Make attribute grabbing not be terrible
Signed-off-by: Harsh Shandilya <me@msfjarvis.dev>
2018-06-01 18:42:19 +05:30
Jason A. Donenfeld 32d669a661 theme: add dark theme with toggle
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-01 14:57:25 +02:00
Jason A. Donenfeld 918076a670 global: fix theme situation and clean up cruft while adding more cruft
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-06-01 14:57:25 +02:00
Harsh Shandilya 752e61d1c7 fab: default to app theme colors
Signed-off-by: Harsh Shandilya <me@msfjarvis.dev>
2018-06-01 03:19:26 +02:00
Harsh Shandilya 125f725a03 fab: use AppCompatTextView for label
Signed-off-by: Harsh Shandilya <me@msfjarvis.dev>
2018-06-01 03:17:29 +02:00
Harsh Shandilya 3c84b48f08 fab: cleanup
Signed-off-by: Harsh Shandilya <me@msfjarvis.dev>
2018-06-01 03:16:32 +02:00
Jason A. Donenfeld 8c32c32c2b wg-quick: don't break push notifications
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-05-31 16:40:50 +02:00
Jason A. Donenfeld e664a05d4b KeyEncoding: more constant time
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2018-05-30 23:31:20 +02:00
43 changed files with 733 additions and 212 deletions
+2 -8
View File
@@ -2,12 +2,6 @@ apply plugin: 'com.android.application'
android {
buildToolsVersion '27.0.3'
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
@@ -20,8 +14,8 @@ android {
applicationId 'com.wireguard.android'
minSdkVersion 21
targetSdkVersion 27
versionCode 419
versionName '0.0.20180529'
versionCode 421
versionName '0.0.20180604'
}
externalNativeBuild {
cmake {
-26
View File
@@ -1,26 +0,0 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /opt/android-sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
-dontwarn sun.misc.Unsafe
+13 -2
View File
@@ -8,6 +8,13 @@
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<permission
android:name="com.wireguard.android.permission.CONTROL_TUNNELS"
android:protectionLevel="dangerous"
android:icon="@mipmap/ic_launcher"
android:label="@string/permission_label"
android:description="@string/permission_description" />
<application
android:name=".Application"
android:allowBackup="false"
@@ -50,9 +57,13 @@
</intent-filter>
</receiver>
<receiver android:name=".backend.WgQuickBackend$WgQuickChangeReceiver">
<receiver
android:name=".model.TunnelManager$IntentReceiver"
android:permission="com.wireguard.android.permission.CONTROL_TUNNELS">
<intent-filter>
<action android:name="com.wireguard.android.WGQUICK_CHANGE" />
<action android:name="com.wireguard.android.action.REFRESH_TUNNEL_STATES" />
<action android:name="com.wireguard.android.action.SET_TUNNEL_UP" />
<action android:name="com.wireguard.android.action.SET_TUNNEL_DOWN" />
</intent-filter>
</receiver>
@@ -12,6 +12,7 @@ import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatDelegate;
import com.wireguard.android.backend.Backend;
import com.wireguard.android.backend.GoBackend;
@@ -22,6 +23,7 @@ import com.wireguard.android.model.TunnelManager;
import com.wireguard.android.util.AsyncWorker;
import com.wireguard.android.util.RootShell;
import com.wireguard.android.util.ToolsInstaller;
import com.wireguard.android.util.Topic;
import java.io.File;
import java.util.concurrent.Executor;
@@ -66,6 +68,8 @@ public class Application extends android.app.Application {
ToolsInstaller getToolsInstaller();
TunnelManager getTunnelManager();
Topic getThemeChangeTopic();
}
@Qualifier
@@ -86,6 +90,10 @@ public class Application extends android.app.Application {
private ApplicationModule(final Application application) {
context = application.getApplicationContext();
AppCompatDelegate.setDefaultNightMode(
getPreferences(context).getBoolean("dark_theme", false) ?
AppCompatDelegate.MODE_NIGHT_YES : AppCompatDelegate.MODE_NIGHT_NO);
}
@ApplicationScope
@@ -111,6 +119,12 @@ public class Application extends android.app.Application {
return new FileConfigStore(context);
}
@ApplicationScope
@Provides
public static Topic getThemeChangeTopic() {
return new Topic();
}
@ApplicationScope
@Provides
@@ -11,19 +11,24 @@ import android.databinding.CallbackRegistry;
import android.databinding.CallbackRegistry.NotifierCallback;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.wireguard.android.Application;
import com.wireguard.android.backend.GoBackend;
import com.wireguard.android.model.Tunnel;
import com.wireguard.android.model.TunnelManager;
import com.wireguard.android.util.Topic;
import java.lang.reflect.Field;
import java.util.Objects;
/**
* Base class for activities that need to remember the currently-selected tunnel.
*/
public abstract class BaseActivity extends AppCompatActivity {
public abstract class BaseActivity extends AppCompatActivity implements Topic.Subscriber {
private static final String TAG = "WireGuard/" + BaseActivity.class.getSimpleName();
private static final String KEY_SELECTED_TUNNEL = "selected_tunnel";
private final SelectionChangeRegistry selectionChangeRegistry = new SelectionChangeRegistry();
@@ -40,6 +45,8 @@ public abstract class BaseActivity extends AppCompatActivity {
@Override
protected void onCreate(final Bundle savedInstanceState) {
subscribeTopics();
// Restore the saved tunnel if there is one; otherwise grab it from the arguments.
String savedTunnelName = null;
if (savedInstanceState != null)
@@ -62,6 +69,12 @@ public abstract class BaseActivity extends AppCompatActivity {
}
}
@Override
protected void onDestroy() {
unsubscribeTopics();
super.onDestroy();
}
@Override
protected void onSaveInstanceState(final Bundle outState) {
if (selectedTunnel != null)
@@ -105,4 +118,28 @@ public abstract class BaseActivity extends AppCompatActivity {
super(new SelectionChangeNotifier());
}
}
@Override
public void onTopicPublished(Topic topic) {
try {
Field f = getResources().getClass().getDeclaredField("mResourcesImpl");
f.setAccessible(true);
Object o = f.get(getResources());
f = o.getClass().getDeclaredField("mDrawableCache");
f.setAccessible(true);
o = f.get(o);
f = o.getClass().getSuperclass().getDeclaredField("mThemedEntries");
f.setAccessible(true);
o = f.get(o);
o.getClass().getMethod("clear").invoke(o);
} catch (Exception e) {
Log.e(TAG, "Failed to flush icon cache", e);
}
recreate();
}
@Override
public Topic[] getSubscription() {
return new Topic[] { Application.getComponent().getThemeChangeTopic() };
}
}
@@ -6,12 +6,14 @@
package com.wireguard.android.activity;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceFragmentCompat;
import android.view.MenuItem;
@@ -19,6 +21,7 @@ import android.view.MenuItem;
import com.wireguard.android.Application;
import com.wireguard.android.R;
import com.wireguard.android.backend.WgQuickBackend;
import com.wireguard.android.util.Topic;
import java.util.ArrayList;
import java.util.Arrays;
@@ -30,7 +33,7 @@ import java.util.Map;
* Interface for changing application-global persistent settings.
*/
public class SettingsActivity extends AppCompatActivity {
public class SettingsActivity extends AppCompatActivity implements Topic.Subscriber {
private final Map<Integer, PermissionRequestCallback> permissionRequestCallbacks = new HashMap<>();
private int permissionRequestCounter;
@@ -56,6 +59,7 @@ public class SettingsActivity extends AppCompatActivity {
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
subscribeTopics();
if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) {
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, new SettingsFragment())
@@ -63,6 +67,12 @@ public class SettingsActivity extends AppCompatActivity {
}
}
@Override
protected void onDestroy() {
unsubscribeTopics();
super.onDestroy();
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
@@ -89,7 +99,17 @@ public class SettingsActivity extends AppCompatActivity {
void done(String[] permissions, int[] grantResults);
}
public static class SettingsFragment extends PreferenceFragmentCompat {
@Override
public void onTopicPublished(final Topic topic) {
recreate();
}
@Override
public Topic[] getSubscription() {
return new Topic[] { Application.getComponent().getThemeChangeTopic() };
}
public static class SettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener {
@Override
public void onCreatePreferences(final Bundle savedInstanceState, final String key) {
addPreferencesFromResource(R.xml.preferences);
@@ -100,5 +120,26 @@ public class SettingsActivity extends AppCompatActivity {
getPreferenceScreen().removePreference(pref);
}
}
@Override
public void onResume() {
super.onResume();
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onPause() {
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}
@Override
public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, final String key) {
if ("dark_theme".equals(key)) {
AppCompatDelegate.setDefaultNightMode(
sharedPreferences.getBoolean(key, false) ? AppCompatDelegate.MODE_NIGHT_YES : AppCompatDelegate.MODE_NIGHT_NO);
Application.getComponent().getThemeChangeTopic().publish(false);
}
}
}
}
@@ -56,6 +56,10 @@ public final class GoBackend implements Backend {
private static native int wgTurnOn(String ifName, int tunFd, String settings);
private static native String wgVersion();
public static String getVersion() { return wgVersion(); }
@Override
public Config applyConfig(final Tunnel tunnel, final Config config) throws Exception {
if (tunnel.getState() == State.UP) {
@@ -133,7 +137,7 @@ public final class GoBackend implements Backend {
// Build config
final Interface iface = config.getInterface();
final String goConfig;
try (Formatter fmt = new Formatter(new StringBuilder())) {
try (final Formatter fmt = new Formatter(new StringBuilder())) {
fmt.format("replace_peers=true\n");
if (iface.getPrivateKey() != null)
fmt.format("private_key=%s\n", KeyEncoding.keyToHex(KeyEncoding.keyFromBase64(iface.getPrivateKey())));
@@ -180,11 +184,12 @@ public final class GoBackend implements Backend {
builder.setMtu(mtu);
builder.setBlocking(true);
final ParcelFileDescriptor tun = builder.establish();
if (tun == null)
throw new Exception("Unable to create tun device");
currentTunnelHandle = wgTurnOn(tunnel.getName(), tun.detachFd(), goConfig);
try (final ParcelFileDescriptor tun = builder.establish()) {
if (tun == null)
throw new Exception("Unable to create tun device");
Log.d(TAG, "Go backend v" + wgVersion());
currentTunnelHandle = wgTurnOn(tunnel.getName(), tun.detachFd(), goConfig);
}
if (currentTunnelHandle < 0)
throw new Exception("Unable to turn tunnel on (wgTurnOn return " + currentTunnelHandle + ')');
@@ -233,7 +238,7 @@ public final class GoBackend implements Backend {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
public int onStartCommand(final Intent intent, final int flags, final int startId) {
vpnService.complete(this);
if (intent == null || intent.getComponent() == null || !intent.getComponent().getPackageName().equals(getPackageName())) {
Log.d(TAG, "Service started by Always-on VPN feature");
@@ -6,12 +6,9 @@
package com.wireguard.android.backend;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.wireguard.android.Application;
import com.wireguard.android.model.Tunnel;
import com.wireguard.android.model.Tunnel.State;
import com.wireguard.android.model.Tunnel.Statistics;
@@ -106,23 +103,17 @@ public final class WgQuickBackend implements Backend {
private void setStateInternal(final Tunnel tunnel, final Config config, final State state)
throws Exception {
final File tempFile = new File(localTemporaryDir, tunnel.getName() + ".conf");
try (FileOutputStream stream = new FileOutputStream(tempFile, false)) {
try (final FileOutputStream stream = new FileOutputStream(tempFile, false)) {
stream.write(config.toString().getBytes(StandardCharsets.UTF_8));
}
final String command = String.format("wg-quick %s '%s'",
String command = String.format("wg-quick %s '%s'",
state.toString().toLowerCase(), tempFile.getAbsolutePath());
if (state == State.UP)
command = "cat /sys/module/wireguard/version && " + command;
final int result = rootShell.run(null, command);
// noinspection ResultOfMethodCallIgnored
tempFile.delete();
if (result != 0)
throw new Exception("Unable to configure tunnel (wg-quick returned " + result + ')');
}
public static final class WgQuickChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
Log.d(TAG, "Refreshing tunnel states");
Application.getComponent().getTunnelManager().refreshTunnelStates();
}
}
}
@@ -42,7 +42,7 @@ public final class FileConfigStore implements ConfigStore {
final File file = fileFor(name);
if (!file.createNewFile())
throw new IOException("Configuration file " + file.getName() + " already exists");
try (FileOutputStream stream = new FileOutputStream(file, false)) {
try (final FileOutputStream stream = new FileOutputStream(file, false)) {
stream.write(config.toString().getBytes(StandardCharsets.UTF_8));
}
return config;
@@ -70,7 +70,7 @@ public final class FileConfigStore implements ConfigStore {
@Override
public Config load(final String name) throws IOException {
try (FileInputStream stream = new FileInputStream(fileFor(name))) {
try (final FileInputStream stream = new FileInputStream(fileFor(name))) {
return Config.from(stream);
}
}
@@ -95,7 +95,7 @@ public final class FileConfigStore implements ConfigStore {
final File file = fileFor(name);
if (!file.isFile())
throw new FileNotFoundException("Configuration file " + file.getName() + " not found");
try (FileOutputStream stream = new FileOutputStream(file, false)) {
try (final FileOutputStream stream = new FileOutputStream(file, false)) {
stream.write(config.toString().getBytes(StandardCharsets.UTF_8));
}
return config;
@@ -343,7 +343,11 @@ public class TunnelListFragment extends BaseFragment {
private void updateTitle(final ActionMode mode) {
final int count = (int) getCheckedPositions().count();
mode.setTitle(resources.getQuantityString(R.plurals.delete_title, count, count));
if (count == 0) {
mode.setTitle("");
} else {
mode.setTitle(resources.getQuantityString(R.plurals.delete_title, count, count));
}
}
}
@@ -6,11 +6,15 @@
package com.wireguard.android.model;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.databinding.BaseObservable;
import android.databinding.Bindable;
import android.support.annotation.NonNull;
import com.wireguard.android.Application;
import com.wireguard.android.Application.ApplicationScope;
import com.wireguard.android.BR;
import com.wireguard.android.backend.Backend;
@@ -57,7 +61,7 @@ public final class TunnelManager extends BaseObservable {
new ObservableSortedKeyedArrayList<>(COMPARATOR);
private Tunnel lastUsedTunnel;
private boolean haveLoaded;
private ArrayList<CompletableFuture<Void>> delayedLoadRestoreTunnels = new ArrayList<>();
private final ArrayList<CompletableFuture<Void>> delayedLoadRestoreTunnels = new ArrayList<>();
@Inject
public TunnelManager(final AsyncWorker asyncWorker, final Backend backend,
@@ -150,7 +154,7 @@ public final class TunnelManager extends BaseObservable {
final String lastUsedName = preferences.getString(KEY_LAST_USED_TUNNEL, null);
if (lastUsedName != null)
setLastUsedTunnel(tunnels.get(lastUsedName));
CompletableFuture<Void> toComplete[];
final CompletableFuture<Void>[] toComplete;
synchronized (delayedLoadRestoreTunnels) {
haveLoaded = true;
toComplete = delayedLoadRestoreTunnels.toArray(new CompletableFuture[delayedLoadRestoreTunnels.size()]);
@@ -175,12 +179,12 @@ public final class TunnelManager extends BaseObservable {
.whenComplete(ExceptionLoggers.E);
}
public CompletionStage<Void> restoreState(boolean force) {
public CompletionStage<Void> restoreState(final boolean force) {
if (!force && !preferences.getBoolean(KEY_RESTORE_ON_BOOT, false))
return CompletableFuture.completedFuture(null);
synchronized (delayedLoadRestoreTunnels) {
if (!haveLoaded) {
CompletableFuture<Void> f = new CompletableFuture<>();
final CompletableFuture<Void> f = new CompletableFuture<>();
delayedLoadRestoreTunnels.add(f);
return f;
}
@@ -264,4 +268,43 @@ public final class TunnelManager extends BaseObservable {
saveState();
});
}
public static final class IntentReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
final TunnelManager manager = Application.getComponent().getTunnelManager();
if (intent == null)
return;
final String action = intent.getAction();
if (action == null)
return;
if ("com.wireguard.android.action.REFRESH_TUNNEL_STATES".equals(action)) {
manager.refreshTunnelStates();
return;
}
/* We disable the below, for now, as the security model of allowing this
* might take a bit more consideration.
*/
if (true)
return;
final State state;
if ("com.wireguard.android.action.SET_TUNNEL_UP".equals(action))
state = State.UP;
else if ("com.wireguard.android.action.SET_TUNNEL_DOWN".equals(action))
state = State.DOWN;
else
return;
final String tunnelName = intent.getStringExtra("tunnel");
if (tunnelName == null)
return;
final Tunnel tunnel = manager.getTunnels().get(tunnelName);
if (tunnel == null)
return;
manager.setTunnelState(tunnel, state);
}
}
}
@@ -0,0 +1,126 @@
/*
* Copyright © 2018 Samuel Holland <samuel@sholland.org>
* Copyright © 2018 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
* SPDX-License-Identifier: GPL-2.0-or-later
*/
package com.wireguard.android.preference;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.design.widget.Snackbar;
import android.support.v7.preference.Preference;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ContextThemeWrapper;
import com.wireguard.android.Application;
import com.wireguard.android.R;
import com.wireguard.android.activity.SettingsActivity;
import com.wireguard.android.util.ExceptionLoggers;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Preference implementing a button that asynchronously exports logs.
*/
public class LogExporterPreference extends Preference {
private static final String TAG = "WireGuard/" + LogExporterPreference.class.getSimpleName();
private String exportedFilePath;
public LogExporterPreference(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
private static SettingsActivity getPrefActivity(final Preference preference) {
final Context context = preference.getContext();
if (context instanceof ContextThemeWrapper) {
if (((ContextThemeWrapper) context).getBaseContext() instanceof SettingsActivity) {
return ((SettingsActivity) ((ContextThemeWrapper) context).getBaseContext());
}
}
return null;
}
private void exportLog() {
Application.getComponent().getAsyncWorker().supplyAsync(() -> {
final File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
final File file = new File(path, "wireguard-log.txt");
if (!path.isDirectory() && !path.mkdirs())
throw new IOException("Cannot create output directory");
/* We would like to simply run `builder.redirectOutput(file);`, but this is API 26.
* Instead we have to do this dance, since logcat appends.
*/
new FileOutputStream(file).close();
try {
final Process process = Runtime.getRuntime().exec(new String[]{
"logcat", "-b", "all", "-d", "-v", "threadtime", "--pid", Integer.toString(android.os.Process.myPid()), "-f", file.getAbsolutePath(), "*:V"});
if (process.waitFor() != 0) {
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
final StringBuilder errors = new StringBuilder();
errors.append("Unable to run logcat: ");
String line;
while ((line = reader.readLine()) != null)
errors.append(line);
throw new Exception(errors.toString());
}
}
} catch (final Exception e) {
// noinspection ResultOfMethodCallIgnored
file.delete();
throw e;
}
return file.getAbsolutePath();
}).whenComplete(this::exportLogComplete);
}
private void exportLogComplete(final String filePath, final Throwable throwable) {
if (throwable != null) {
final String error = ExceptionLoggers.unwrapMessage(throwable);
final String message = getContext().getString(R.string.log_export_error, error);
Log.e(TAG, message, throwable);
Snackbar.make(
getPrefActivity(this).findViewById(android.R.id.content),
message, Snackbar.LENGTH_LONG).show();
setEnabled(true);
} else {
exportedFilePath = filePath;
notifyChanged();
}
}
@Override
public CharSequence getSummary() {
return exportedFilePath == null ?
getContext().getString(R.string.log_export_summary) :
getContext().getString(R.string.log_export_success, exportedFilePath);
}
@Override
public CharSequence getTitle() {
return getContext().getString(R.string.log_exporter_title);
}
@Override
protected void onClick() {
getPrefActivity(this).ensurePermissions(
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
(permissions, granted) -> {
if (granted.length > 0 && granted[0] == PackageManager.PERMISSION_GRANTED) {
setEnabled(false);
exportLog();
}
});
}
}
@@ -0,0 +1,55 @@
/*
* Copyright © 2018 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
* SPDX-License-Identifier: GPL-2.0-or-later
*/
package com.wireguard.android.preference;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.preference.Preference;
import android.util.AttributeSet;
import com.wireguard.android.Application;
import com.wireguard.android.BuildConfig;
import com.wireguard.android.R;
import com.wireguard.android.backend.GoBackend;
import com.wireguard.android.backend.WgQuickBackend;
public class VersionPreference extends Preference {
private String versionSummary;
public VersionPreference(final Context context, final AttributeSet attrs) {
super(context, attrs);
if (Application.getComponent().getBackendType() == GoBackend.class) {
versionSummary = getContext().getString(R.string.version_userspace_summary, GoBackend.getVersion());
} else if (Application.getComponent().getBackendType() == WgQuickBackend.class) {
Application.getComponent().getToolsInstaller().getVersion().whenComplete((version, exception) -> {
versionSummary = exception == null
? getContext().getString(R.string.version_kernel_summary, version)
: getContext().getString(R.string.version_kernel_unknown_summary);
notifyChanged();
});
}
}
@Override
public CharSequence getSummary() {
return versionSummary;
}
@Override
public CharSequence getTitle() {
return getContext().getString(R.string.version_title, BuildConfig.VERSION_NAME);
}
@Override
protected void onClick() {
final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://www.wireguard.com/"));
getContext().startActivity(intent);
}
}
@@ -17,12 +17,9 @@ import android.util.Log;
import android.view.ContextThemeWrapper;
import com.wireguard.android.Application;
import com.wireguard.android.Application.ApplicationComponent;
import com.wireguard.android.R;
import com.wireguard.android.activity.SettingsActivity;
import com.wireguard.android.model.Tunnel;
import com.wireguard.android.model.TunnelManager;
import com.wireguard.android.util.AsyncWorker;
import com.wireguard.android.util.ExceptionLoggers;
import com.wireguard.config.Config;
@@ -44,16 +41,10 @@ import java9.util.concurrent.CompletableFuture;
public class ZipExporterPreference extends Preference {
private static final String TAG = "WireGuard/" + ZipExporterPreference.class.getSimpleName();
private final AsyncWorker asyncWorker;
private final TunnelManager tunnelManager;
private String exportedFilePath;
@SuppressWarnings({"SameParameterValue", "WeakerAccess"})
public ZipExporterPreference(final Context context, final AttributeSet attrs) {
super(context, attrs);
final ApplicationComponent applicationComponent = Application.getComponent();
asyncWorker = applicationComponent.getAsyncWorker();
tunnelManager = applicationComponent.getTunnelManager();
}
private static SettingsActivity getPrefActivity(final Preference preference) {
@@ -67,7 +58,7 @@ public class ZipExporterPreference extends Preference {
}
private void exportZip() {
final List<Tunnel> tunnels = new ArrayList<>(tunnelManager.getTunnels());
final List<Tunnel> tunnels = new ArrayList<>(Application.getComponent().getTunnelManager().getTunnels());
final List<CompletableFuture<Config>> futureConfigs = new ArrayList<>(tunnels.size());
for (final Tunnel tunnel : tunnels)
futureConfigs.add(tunnel.getConfigAsync().toCompletableFuture());
@@ -76,7 +67,7 @@ public class ZipExporterPreference extends Preference {
return;
}
CompletableFuture.allOf(futureConfigs.toArray(new CompletableFuture[futureConfigs.size()]))
.whenComplete((ignored1, exception) -> asyncWorker.supplyAsync(() -> {
.whenComplete((ignored1, exception) -> Application.getComponent().getAsyncWorker().supplyAsync(() -> {
if (exception != null)
throw exception;
final File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
@@ -90,8 +81,7 @@ public class ZipExporterPreference extends Preference {
toString().getBytes(StandardCharsets.UTF_8));
}
zip.closeEntry();
zip.close();
} catch (Exception e) {
} catch (final Exception e) {
// noinspection ResultOfMethodCallIgnored
file.delete();
throw e;
@@ -103,14 +93,14 @@ public class ZipExporterPreference extends Preference {
private void exportZipComplete(final String filePath, final Throwable throwable) {
if (throwable != null) {
final String error = ExceptionLoggers.unwrapMessage(throwable);
final String message = getContext().getString(R.string.export_error, error);
final String message = getContext().getString(R.string.zip_export_error, error);
Log.e(TAG, message, throwable);
Snackbar.make(
getPrefActivity(this).findViewById(android.R.id.content),
message, Snackbar.LENGTH_LONG).show();
setEnabled(true);
} else {
exportedFilePath = filePath;
setEnabled(false);
notifyChanged();
}
}
@@ -118,8 +108,8 @@ public class ZipExporterPreference extends Preference {
@Override
public CharSequence getSummary() {
return exportedFilePath == null ?
getContext().getString(R.string.export_summary) :
getContext().getString(R.string.export_success, exportedFilePath);
getContext().getString(R.string.zip_export_summary) :
getContext().getString(R.string.zip_export_success, exportedFilePath);
}
@Override
@@ -132,8 +122,10 @@ public class ZipExporterPreference extends Preference {
getPrefActivity(this).ensurePermissions(
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
(permissions, granted) -> {
if (granted.length > 0 && granted[0] == PackageManager.PERMISSION_GRANTED)
if (granted.length > 0 && granted[0] == PackageManager.PERMISSION_GRANTED) {
setEnabled(false);
exportZip();
}
});
}
@@ -22,7 +22,7 @@ public final class SharedLibraryLoader {
private SharedLibraryLoader() {
}
public static final void loadSharedLibrary(final Context context, final String libName) {
public static void loadSharedLibrary(final Context context, final String libName) {
Throwable noAbiException;
try {
System.loadLibrary(libName);
@@ -35,12 +35,12 @@ public final class SharedLibraryLoader {
final ZipFile zipFile;
try {
zipFile = new ZipFile(new File(context.getApplicationInfo().sourceDir), ZipFile.OPEN_READ);
} catch (IOException e) {
} catch (final IOException e) {
throw new RuntimeException(e);
}
final String mappedLibName = System.mapLibraryName(libName);
byte buffer[] = new byte[1024 * 32];
final byte[] buffer = new byte[1024 * 32];
for (final String abi : Build.SUPPORTED_ABIS) {
final String libZipPath = "lib" + File.separatorChar + abi + File.separatorChar + mappedLibName;
final ZipEntry zipEntry = zipFile.getEntry(libZipPath);
@@ -50,13 +50,13 @@ public final class SharedLibraryLoader {
try {
f = File.createTempFile("lib", ".so", context.getCacheDir());
Log.d(TAG, "Extracting apk:/" + libZipPath + " to " + f.getAbsolutePath() + " and loading");
FileOutputStream out = new FileOutputStream(f);
InputStream in = zipFile.getInputStream(zipEntry);
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
try (final FileOutputStream out = new FileOutputStream(f);
final InputStream in = zipFile.getInputStream(zipEntry)) {
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
}
out.close();
System.load(f.getAbsolutePath());
return;
} catch (Exception e) {
@@ -64,6 +64,7 @@ public final class SharedLibraryLoader {
noAbiException = e;
} finally {
if (f != null)
// noinspection ResultOfMethodCallIgnored
f.delete();
}
}
@@ -10,6 +10,7 @@ import android.content.Context;
import android.system.OsConstants;
import android.util.Log;
import com.wireguard.android.Application;
import com.wireguard.android.Application.ApplicationContext;
import com.wireguard.android.Application.ApplicationScope;
import com.wireguard.android.util.RootShell.NoRootException;
@@ -17,11 +18,14 @@ import com.wireguard.android.util.RootShell.NoRootException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.inject.Inject;
import java9.util.concurrent.CompletionStage;
/**
* Helper to install WireGuard tools to the system partition.
*/
@@ -52,14 +56,24 @@ public final class ToolsInstaller {
this.rootShell = rootShell;
}
public CompletionStage<String> getVersion() {
return Application.getComponent().getAsyncWorker().supplyAsync(() -> {
final List<String> output = new ArrayList<>();
if (rootShell.run(output, "cat /sys/module/wireguard/version") != 0 || output.isEmpty())
throw new RuntimeException("Unable to determine kernel module version");
return output.get(0);
});
}
private static File getInstallDir() {
final String path = System.getenv("PATH");
if (path == null)
return INSTALL_DIRS[0];
final List<String> paths = Arrays.asList(path.split(":"));
for (final File dir : INSTALL_DIRS)
for (final File dir : INSTALL_DIRS) {
if (paths.contains(dir.getPath()) && dir.isDirectory())
return dir;
}
return null;
}
@@ -0,0 +1,109 @@
/*
* Copyright © 2017 John Wu <topjohnwu@gmail.com>
* SPDX-License-Identifier: GPL-2.0-or-later
*/
package com.wireguard.android.util;
import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
public class Topic {
private static final int NON_INIT = 0;
private static final int PENDING = 1;
private static final int PUBLISHED = 2;
private int state = NON_INIT;
private List<WeakReference<Subscriber>> subscribers;
private Object[] results;
public Topic() {
subscribers = new SyncArrayList<>();
}
public synchronized void subscribe(final Subscriber sub) {
subscribers.add(new WeakReference<>(sub));
}
public synchronized void unsubscribe() {
subscribers = new SyncArrayList<>();
}
public synchronized void unsubscribe(final Subscriber sub) {
List<WeakReference<Subscriber>> subs = subscribers;
subscribers = new ArrayList<>();
for (final WeakReference<Subscriber> subscriber : subs) {
if (subscriber.get() != null && subscriber.get() != sub)
subscribers.add(subscriber);
}
}
public void reset() {
state = NON_INIT;
results = null;
}
public boolean isPublished() {
return state == PUBLISHED;
}
public void publish() {
publish(true);
}
public void publish(boolean record, Object... results) {
if (record)
state = PUBLISHED;
this.results = results;
// Snapshot
List<WeakReference<Subscriber>> subs = subscribers;
for (final WeakReference<Subscriber> subscriber : subs) {
if (subscriber != null && subscriber.get() != null)
subscriber.get().onTopicPublished(this);
}
}
public Object[] getResults() {
return results;
}
public boolean isPending() {
return state == PENDING;
}
public void setPending() {
state = PENDING;
}
public interface Subscriber {
default void subscribeTopics() {
for (final Topic topic : getSubscription()) {
if (topic.isPublished()) {
onTopicPublished(topic);
}
topic.subscribe(this);
}
}
default void unsubscribeTopics() {
for (final Topic event : getSubscription()) {
event.unsubscribe(this);
}
}
void onTopicPublished(Topic topic);
Topic[] getSubscription();
}
private static class SyncArrayList<E> extends ArrayList<E> {
@Override
public synchronized boolean add(final E e) {
return super.add(e);
}
}
}
@@ -16,6 +16,7 @@ import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.Shape;
import android.support.annotation.ColorRes;
import android.support.annotation.DrawableRes;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import com.wireguard.android.R;
@@ -38,7 +39,7 @@ public class AddFloatingActionButton extends FloatingActionButton {
@Override
void init(final Context context, final AttributeSet attributeSet) {
final TypedArray attr = context.obtainStyledAttributes(attributeSet, R.styleable.AddFloatingActionButton, 0, 0);
mPlusColor = attr.getColor(R.styleable.AddFloatingActionButton_fab_plusIconColor, getColor(android.R.color.white));
mPlusColor = attr.getColor(R.styleable.AddFloatingActionButton_fab_plusIconColor, FloatingActionButton.getColorFromTheme(context, android.R.attr.colorBackground, android.R.color.white));
attr.recycle();
super.init(context, attributeSet);
@@ -58,8 +59,8 @@ public class AddFloatingActionButton extends FloatingActionButton {
}
}
public void setPlusColorResId(@ColorRes int plusColor) {
setPlusColor(getColor(plusColor));
public void setPlusColorResId(@ColorRes final int plusColor) {
setPlusColor(ContextCompat.getColor(getContext(), plusColor));
}
@Override
@@ -7,6 +7,7 @@
package com.wireguard.android.widget.fab;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.*;
import android.graphics.Paint.Style;
@@ -15,8 +16,10 @@ import android.graphics.drawable.*;
import android.graphics.drawable.ShapeDrawable.ShaderFactory;
import android.graphics.drawable.shapes.OvalShape;
import android.support.annotation.*;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatImageButton;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;
import com.wireguard.android.R;
@@ -51,16 +54,29 @@ public class FloatingActionButton extends AppCompatImageButton {
init(context, attrs);
}
public FloatingActionButton(Context context, AttributeSet attrs, int defStyle) {
public FloatingActionButton(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
public static int getColorFromTheme(final Context context, final int themeResource, @ColorRes final int fallback) {
final TypedValue typedValue = new TypedValue();
final Resources.Theme theme = context.getTheme();
theme.resolveAttribute(themeResource, typedValue, true);
@ColorInt final int color = typedValue.data;
return color == 0 ? fallback : color;
}
void init(final Context context, final AttributeSet attributeSet) {
final TypedArray attr = context.obtainStyledAttributes(attributeSet, R.styleable.FloatingActionButton, 0, 0);
mColorNormal = attr.getColor(R.styleable.FloatingActionButton_fab_colorNormal, getColor(android.R.color.holo_blue_dark));
mColorPressed = attr.getColor(R.styleable.FloatingActionButton_fab_colorPressed, getColor(android.R.color.holo_blue_light));
mColorDisabled = attr.getColor(R.styleable.FloatingActionButton_fab_colorDisabled, getColor(android.R.color.darker_gray));
final TypedArray attr = context.obtainStyledAttributes(attributeSet,
R.styleable.FloatingActionButton, 0, 0);
mColorNormal = attr.getColor(R.styleable.FloatingActionButton_fab_colorNormal,
getColorFromTheme(context, android.R.attr.colorAccent, android.R.color.holo_blue_bright));
mColorPressed = attr.getColor(R.styleable.FloatingActionButton_fab_colorPressed,
darkenOrLightenColor(mColorNormal)); //TODO(msf): use getColorForState on the accent color from theme instead to get darker states
mColorDisabled = attr.getColor(R.styleable.FloatingActionButton_fab_colorDisabled,
ContextCompat.getColor(context, android.R.color.darker_gray)); //TODO(msf): load from theme
mSize = attr.getInt(R.styleable.FloatingActionButton_fab_size, SIZE_NORMAL);
mIcon = attr.getResourceId(R.styleable.FloatingActionButton_fab_icon, 0);
mTitle = attr.getString(R.styleable.FloatingActionButton_fab_title);
@@ -124,7 +140,7 @@ public class FloatingActionButton extends AppCompatImageButton {
}
public void setColorNormalResId(@ColorRes final int colorNormal) {
setColorNormal(getColor(colorNormal));
setColorNormal(ContextCompat.getColor(getContext(), colorNormal));
}
/**
@@ -142,7 +158,7 @@ public class FloatingActionButton extends AppCompatImageButton {
}
public void setColorPressedResId(@ColorRes final int colorPressed) {
setColorPressed(getColor(colorPressed));
setColorPressed(ContextCompat.getColor(getContext(), colorPressed));
}
/**
@@ -160,7 +176,7 @@ public class FloatingActionButton extends AppCompatImageButton {
}
public void setColorDisabledResId(@ColorRes final int colorDisabled) {
setColorDisabled(getColor(colorDisabled));
setColorDisabled(ContextCompat.getColor(getContext(), colorDisabled));
}
public boolean isStrokeVisible() {
@@ -174,10 +190,6 @@ public class FloatingActionButton extends AppCompatImageButton {
}
}
int getColor(@ColorRes final int id) {
return getResources().getColor(id);
}
float getDimension(@DimenRes final int id) {
return getResources().getDimension(id);
}
@@ -247,7 +259,7 @@ public class FloatingActionButton extends AppCompatImageButton {
if (mIconDrawable != null) {
return mIconDrawable;
} else if (mIcon != 0) {
return getResources().getDrawable(mIcon, null);
return ContextCompat.getDrawable(getContext(), mIcon);
} else {
return new ColorDrawable(Color.TRANSPARENT);
}
@@ -294,7 +306,7 @@ public class FloatingActionButton extends AppCompatImageButton {
return drawable;
}
private Drawable createOuterStrokeDrawable(final float strokeWidth) {
private static Drawable createOuterStrokeDrawable(final float strokeWidth) {
final ShapeDrawable shapeDrawable = new ShapeDrawable(new OvalShape());
final Paint paint = shapeDrawable.getPaint();
@@ -307,19 +319,32 @@ public class FloatingActionButton extends AppCompatImageButton {
return shapeDrawable;
}
private int opacityToAlpha(final float opacity) {
private static int opacityToAlpha(final float opacity) {
return (int) (255f * opacity);
}
private int darkenColor(final int argb) {
private static int darkenColor(final int argb) {
return adjustColorBrightness(argb, 0.9f);
}
private int lightenColor(final int argb) {
private static int lightenColor(final int argb) {
return adjustColorBrightness(argb, 1.1f);
}
private int adjustColorBrightness(final int argb, final float factor) {
public static int darkenOrLightenColor(final int argb) {
final float[] hsv = new float[3];
Color.colorToHSV(argb, hsv);
final float factor;
if (hsv[2] < 0.2)
factor = 1.2f;
else
factor = 0.8f;
hsv[2] = Math.min(hsv[2] * factor, 1f);
return Color.HSVToColor(Color.alpha(argb), hsv);
}
private static int adjustColorBrightness(final int argb, final float factor) {
final float[] hsv = new float[3];
Color.colorToHSV(argb, hsv);
@@ -328,7 +353,7 @@ public class FloatingActionButton extends AppCompatImageButton {
return Color.HSVToColor(Color.alpha(argb), hsv);
}
private int halfTransparent(final int argb) {
private static int halfTransparent(final int argb) {
return Color.argb(
Color.alpha(argb) / 2,
Color.red(argb),
@@ -337,7 +362,7 @@ public class FloatingActionButton extends AppCompatImageButton {
);
}
private int opaque(final int argb) {
private static int opaque(final int argb) {
return Color.rgb(
Color.red(argb),
Color.green(argb),
@@ -390,10 +415,10 @@ public class FloatingActionButton extends AppCompatImageButton {
public @interface FAB_SIZE {
}
private static class TranslucentLayerDrawable extends LayerDrawable {
private static final class TranslucentLayerDrawable extends LayerDrawable {
private final int mAlpha;
public TranslucentLayerDrawable(final int alpha, final Drawable... layers) {
private TranslucentLayerDrawable(final int alpha, final Drawable... layers) {
super(layers);
mAlpha = alpha;
}
@@ -10,28 +10,33 @@ import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.TimeInterpolator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.ColorRes;
import android.support.annotation.Keep;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;
import android.view.ContextThemeWrapper;
import android.view.TouchDelegate;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.OvershootInterpolator;
import android.widget.TextView;
import com.wireguard.android.R;
@SuppressWarnings("ReturnOfInnerClass")
public class FloatingActionsMenu extends ViewGroup {
public static final int EXPAND_UP = 0;
public static final int EXPAND_DOWN = 1;
@@ -44,9 +49,9 @@ public class FloatingActionsMenu extends ViewGroup {
private static final int ANIMATION_DURATION = 300;
private static final float COLLAPSED_PLUS_ROTATION = 0f;
private static final float EXPANDED_PLUS_ROTATION = 90f + 45f;
private static final Interpolator sExpandInterpolator = new OvershootInterpolator();
private static final Interpolator sCollapseInterpolator = new DecelerateInterpolator(3f);
private static final Interpolator sAlphaExpandInterpolator = new DecelerateInterpolator();
private static final TimeInterpolator EXPAND_INTERPOLATOR = new OvershootInterpolator();
private static final TimeInterpolator COLLAPSE_INTERPOLATOR = new DecelerateInterpolator(3f);
private static final TimeInterpolator ALPHA_EXPAND_INTERPOLATOR = new DecelerateInterpolator();
private int mAddButtonPlusColor;
private int mAddButtonColorNormal;
private int mAddButtonColorPressed;
@@ -74,7 +79,7 @@ public class FloatingActionsMenu extends ViewGroup {
this(context, null);
}
public FloatingActionsMenu(final Context context, AttributeSet attrs) {
public FloatingActionsMenu(final Context context, final AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
@@ -93,9 +98,12 @@ public class FloatingActionsMenu extends ViewGroup {
setTouchDelegate(mTouchDelegateGroup);
final TypedArray attr = context.obtainStyledAttributes(attributeSet, R.styleable.FloatingActionsMenu, 0, 0);
mAddButtonPlusColor = attr.getColor(R.styleable.FloatingActionsMenu_fab_addButtonPlusIconColor, getColor(android.R.color.white));
mAddButtonColorNormal = attr.getColor(R.styleable.FloatingActionsMenu_fab_addButtonColorNormal, getColor(android.R.color.holo_blue_dark));
mAddButtonColorPressed = attr.getColor(R.styleable.FloatingActionsMenu_fab_addButtonColorPressed, getColor(android.R.color.holo_blue_light));
mAddButtonPlusColor = attr.getColor(R.styleable.FloatingActionsMenu_fab_addButtonPlusIconColor,
FloatingActionButton.getColorFromTheme(context, android.R.attr.colorBackground, android.R.color.white));
mAddButtonColorNormal = attr.getColor(R.styleable.FloatingActionsMenu_fab_addButtonColorNormal,
FloatingActionButton.getColorFromTheme(context, android.R.attr.colorAccent, android.R.color.holo_blue_bright));
mAddButtonColorPressed = attr.getColor(R.styleable.FloatingActionsMenu_fab_addButtonColorPressed,
FloatingActionButton.darkenOrLightenColor(mAddButtonColorNormal)); //TODO(msf): use getColorForState on the accent color from theme instead to get darker states
mAddButtonSize = attr.getInt(R.styleable.FloatingActionsMenu_fab_addButtonSize, FloatingActionButton.SIZE_NORMAL);
mAddButtonStrokeVisible = attr.getBoolean(R.styleable.FloatingActionsMenu_fab_addButtonStrokeVisible, true);
mExpandDirection = attr.getInt(R.styleable.FloatingActionsMenu_fab_expandDirection, EXPAND_UP);
@@ -134,7 +142,7 @@ public class FloatingActionsMenu extends ViewGroup {
final RotatingDrawable rotatingDrawable = new RotatingDrawable(super.getIconDrawable());
mRotatingDrawable = rotatingDrawable;
final OvershootInterpolator interpolator = new OvershootInterpolator();
final TimeInterpolator interpolator = new OvershootInterpolator();
final ObjectAnimator collapseAnimator = ObjectAnimator.ofFloat(rotatingDrawable, "rotation", EXPANDED_PLUS_ROTATION, COLLAPSED_PLUS_ROTATION);
final ObjectAnimator expandAnimator = ObjectAnimator.ofFloat(rotatingDrawable, "rotation", COLLAPSED_PLUS_ROTATION, EXPANDED_PLUS_ROTATION);
@@ -151,12 +159,7 @@ public class FloatingActionsMenu extends ViewGroup {
mAddButton.setId(R.id.fab_expand_menu_button);
mAddButton.setSize(mAddButtonSize);
mAddButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
toggle();
}
});
mAddButton.setOnClickListener(v -> toggle());
addView(mAddButton, super.generateDefaultLayoutParams());
mButtonsCount++;
@@ -178,10 +181,6 @@ public class FloatingActionsMenu extends ViewGroup {
mButtonsCount--;
}
private int getColor(@ColorRes final int id) {
return getResources().getColor(id);
}
@Override
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
measureChildren(widthMeasureSpec, heightMeasureSpec);
@@ -194,7 +193,7 @@ public class FloatingActionsMenu extends ViewGroup {
int maxLabelWidth = 0;
for (int i = 0; i < mButtonsCount; i++) {
View child = getChildAt(i);
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
@@ -214,17 +213,17 @@ public class FloatingActionsMenu extends ViewGroup {
}
if (!expandsHorizontally()) {
TextView label = (TextView) child.getTag(R.id.fab_label);
final TextView label = (TextView) child.getTag(R.id.fab_label);
if (label != null) {
maxLabelWidth = Math.max(maxLabelWidth, label.getMeasuredWidth());
}
}
}
if (!expandsHorizontally()) {
width = mMaxButtonWidth + (maxLabelWidth > 0 ? maxLabelWidth + mLabelsMargin : 0);
} else {
if (expandsHorizontally()) {
height = mMaxButtonHeight;
} else {
width = mMaxButtonWidth + (maxLabelWidth > 0 ? maxLabelWidth + mLabelsMargin : 0);
}
switch (mExpandDirection) {
@@ -243,7 +242,7 @@ public class FloatingActionsMenu extends ViewGroup {
setMeasuredDimension(width, height);
}
private int adjustForOvershoot(final int dimension) {
private static int adjustForOvershoot(final int dimension) {
return dimension * 12 / 10;
}
@@ -290,7 +289,7 @@ public class FloatingActionsMenu extends ViewGroup {
child.setTranslationY(mExpanded ? expandedTranslation : collapsedTranslation);
child.setAlpha(mExpanded ? 1f : 0f);
LayoutParams params = (LayoutParams) child.getLayoutParams();
final LayoutParams params = (LayoutParams) child.getLayoutParams();
params.mCollapseDir.setFloatValues(expandedTranslation, collapsedTranslation);
params.mExpandDir.setFloatValues(collapsedTranslation, expandedTranslation);
params.setAnimationsTarget(child);
@@ -322,7 +321,7 @@ public class FloatingActionsMenu extends ViewGroup {
label.setTranslationY(mExpanded ? expandedTranslation : collapsedTranslation);
label.setAlpha(mExpanded ? 1f : 0f);
LayoutParams labelParams = (LayoutParams) label.getLayoutParams();
final LayoutParams labelParams = (LayoutParams) label.getLayoutParams();
labelParams.mCollapseDir.setFloatValues(expandedTranslation, collapsedTranslation);
labelParams.mExpandDir.setFloatValues(collapsedTranslation, expandedTranslation);
labelParams.setAnimationsTarget(label);
@@ -418,8 +417,8 @@ public class FloatingActionsMenu extends ViewGroup {
if (button == mAddButton || title == null ||
button.getTag(R.id.fab_label) != null) continue;
final TextView label = new TextView(context);
label.setTextAppearance(context, mLabelsStyle);
final AppCompatTextView label = new AppCompatTextView(context);
label.setTextAppearance(getContext(), mLabelsStyle);
label.setText(button.getTitle());
addView(label);
@@ -525,6 +524,7 @@ public class FloatingActionsMenu extends ViewGroup {
return mRotation;
}
@Keep
@SuppressWarnings("UnusedDeclaration")
public void setRotation(final float rotation) {
mRotation = rotation;
@@ -544,12 +544,12 @@ public class FloatingActionsMenu extends ViewGroup {
public static final Creator<SavedState> CREATOR = new Creator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel in) {
public SavedState createFromParcel(final Parcel in) {
return new SavedState(in);
}
@Override
public SavedState[] newArray(int size) {
public SavedState[] newArray(final int size) {
return new SavedState[size];
}
};
@@ -582,10 +582,10 @@ public class FloatingActionsMenu extends ViewGroup {
LayoutParams(final ViewGroup.LayoutParams source) {
super(source);
mExpandDir.setInterpolator(sExpandInterpolator);
mExpandAlpha.setInterpolator(sAlphaExpandInterpolator);
mCollapseDir.setInterpolator(sCollapseInterpolator);
mCollapseAlpha.setInterpolator(sCollapseInterpolator);
mExpandDir.setInterpolator(EXPAND_INTERPOLATOR);
mExpandAlpha.setInterpolator(ALPHA_EXPAND_INTERPOLATOR);
mCollapseDir.setInterpolator(COLLAPSE_INTERPOLATOR);
mCollapseAlpha.setInterpolator(COLLAPSE_INTERPOLATOR);
mCollapseAlpha.setProperty(View.ALPHA);
mCollapseAlpha.setFloatValues(1f, 0f);
@@ -25,10 +25,10 @@ public final class KeyEncoding {
// Prevent instantiation.
}
private static int decodeBase64(final char[] src, final int src_offset) {
private static int decodeBase64(final char[] src, final int srcOffset) {
int val = 0;
for (int i = 0; i < 4; ++i) {
final char c = src[i + src_offset];
final char c = src[i + srcOffset];
val |= (-1
+ ((((('A' - 1) - c) & (c - ('Z' + 1))) >>> 8) & (c - 64))
+ ((((('a' - 1) - c) & (c - ('z' + 1))) >>> 8) & (c - 70))
@@ -40,16 +40,16 @@ public final class KeyEncoding {
return val;
}
private static void encodeBase64(final byte[] src, final int src_offset,
final char[] dest, final int dest_offset) {
private static void encodeBase64(final byte[] src, final int srcOffset,
final char[] dest, final int destOffset) {
final byte[] input = {
(byte) ((src[src_offset] >>> 2) & 63),
(byte) ((src[src_offset] << 4 | ((src[1 + src_offset] & 0xff) >>> 4)) & 63),
(byte) ((src[1 + src_offset] << 2 | ((src[2 + src_offset] & 0xff) >>> 6)) & 63),
(byte) ((src[2 + src_offset]) & 63),
(byte) ((src[srcOffset] >>> 2) & 63),
(byte) ((src[srcOffset] << 4 | ((src[1 + srcOffset] & 0xff) >>> 4)) & 63),
(byte) ((src[1 + srcOffset] << 2 | ((src[2 + srcOffset] & 0xff) >>> 6)) & 63),
(byte) ((src[2 + srcOffset]) & 63),
};
for (int i = 0; i < 4; ++i) {
dest[i + dest_offset] = (char) (input[i] + 'A'
dest[i + destOffset] = (char) (input[i] + 'A'
+ (((25 - input[i]) >>> 8) & 6)
- (((51 - input[i]) >>> 8) & 75)
- (((61 - input[i]) >>> 8) & 15)
@@ -63,10 +63,10 @@ public final class KeyEncoding {
if (input.length != KEY_LENGTH_BASE64 || input[KEY_LENGTH_BASE64 - 1] != '=')
throw new IllegalArgumentException(KEY_LENGTH_BASE64_EXCEPTION_MESSAGE);
int i;
int ret = 0;
for (i = 0; i < KEY_LENGTH / 3; ++i) {
final int val = decodeBase64(input, i * 4);
if (val < 0)
throw new IllegalArgumentException(KEY_LENGTH_BASE64_EXCEPTION_MESSAGE);
ret |= val >>> 31;
key[i * 3] = (byte) ((val >>> 16) & 0xff);
key[i * 3 + 1] = (byte) ((val >>> 8) & 0xff);
key[i * 3 + 2] = (byte) (val & 0xff);
@@ -78,10 +78,12 @@ public final class KeyEncoding {
'A',
};
final int val = decodeBase64(endSegment, 0);
if (val < 0 || (val & 0xff) != 0)
throw new IllegalArgumentException(KEY_LENGTH_BASE64_EXCEPTION_MESSAGE);
ret |= (val >>> 31) | (val & 0xff);
key[i * 3] = (byte) ((val >>> 16) & 0xff);
key[i * 3 + 1] = (byte) ((val >>> 8) & 0xff);
if (ret != 0)
throw new IllegalArgumentException(KEY_LENGTH_BASE64_EXCEPTION_MESSAGE);
return key;
}
@@ -90,25 +92,37 @@ public final class KeyEncoding {
final byte[] key = new byte[KEY_LENGTH];
if (input.length != KEY_LENGTH_HEX)
throw new IllegalArgumentException(KEY_LENGTH_HEX_EXCEPTION_MESSAGE);
int ret = 0;
int c_acc = 0;
int state = 0;
for (int i = 0; i < KEY_LENGTH_HEX; i += 2) {
int c;
int cNum;
int cNum0;
int cAlpha;
int cAlpha0;
int cVal;
final int cAcc;
for (int i = 0; i < KEY_LENGTH_HEX; ++i) {
final int c = input[i];
final int c_num = c ^ 48;
final int c_num0 = (c_num - 10) >> 8;
final int c_alpha = (c & ~32) - 55;
final int c_alpha0 = ((c_alpha - 10) ^ (c_alpha - 16)) >> 8;
if ((c_num0 | c_alpha0) == 0)
throw new IllegalArgumentException(KEY_LENGTH_HEX_EXCEPTION_MESSAGE);
final int c_val = (c_num0 & c_num) | (c_alpha0 & c_alpha);
if (state == 0)
c_acc = c_val * 16;
else
key[i / 2] = (byte) (c_acc | c_val);
state = ~state;
c = input[i];
cNum = c ^ 48;
cNum0 = ((cNum - 10) >>> 8) & 0xff;
cAlpha = (c & ~32) - 55;
cAlpha0 = (((cAlpha - 10) ^ (cAlpha - 16)) >>> 8) & 0xff;
ret |= ((cNum0 | cAlpha0) - 1) >>> 8;
cVal = (cNum0 & cNum) | (cAlpha0 & cAlpha);
cAcc = cVal * 16;
c = input[i + 1];
cNum = c ^ 48;
cNum0 = ((cNum - 10) >>> 8) & 0xff;
cAlpha = (c & ~32) - 55;
cAlpha0 = (((cAlpha - 10) ^ (cAlpha - 16)) >>> 8) & 0xff;
ret |= ((cNum0 | cAlpha0) - 1) >>> 8;
cVal = (cNum0 & cNum) | (cAlpha0 & cAlpha);
key[i / 2] = (byte) (cAcc | cVal);
}
if (ret != 0)
throw new IllegalArgumentException(KEY_LENGTH_HEX_EXCEPTION_MESSAGE);
return key;
}
@@ -6,5 +6,5 @@
android:left="8dp"
android:right="8dp"
android:top="4dp" />
<solid android:color="?android:attr/colorPrimary" />
<solid android:color="@color/fab_label_background_color" />
</shape>
@@ -4,6 +4,6 @@
android:viewportHeight="24"
android:viewportWidth="24">
<path
android:fillColor="#FFFFFF"
android:fillColor="?android:attr/colorForeground"
android:pathData="M6,19c0,1.1 0.9,2 2,2h8c1.1,0 2,-0.9 2,-2V7H6v12zM19,4h-3.5l-1,-1h-5l-1,1H5v2h14V4z" />
</vector>
@@ -1,9 +0,0 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportHeight="24"
android:viewportWidth="24">
<path
android:fillColor="#000000"
android:pathData="M6,19c0,1.1 0.9,2 2,2h8c1.1,0 2,-0.9 2,-2V7H6v12zM19,4h-3.5l-1,-1h-5l-1,1H5v2h14V4z" />
</vector>
+1 -1
View File
@@ -4,6 +4,6 @@
android:viewportHeight="24"
android:viewportWidth="24">
<path
android:fillColor="#FFFFFF"
android:fillColor="?android:attr/colorForeground"
android:pathData="M3,17.25V21h3.75L17.81,9.94l-3.75,-3.75L3,17.25zM20.71,7.04c0.39,-0.39 0.39,-1.02 0,-1.41l-2.34,-2.34c-0.39,-0.39 -1.02,-0.39 -1.41,0l-1.83,1.83 3.75,3.75 1.83,-1.83z" />
</vector>
@@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportHeight="24"
android:viewportWidth="24">
<path
android:fillColor="?android:attr/colorBackground"
android:pathData="M3,17.25V21h3.75L17.81,9.94l-3.75,-3.75L3,17.25zM20.71,7.04c0.39,-0.39 0.39,-1.02 0,-1.41l-2.34,-2.34c-0.39,-0.39 -1.02,-0.39 -1.41,0l-1.83,1.83 3.75,3.75 1.83,-1.83z" />
</vector>
+1 -1
View File
@@ -4,6 +4,6 @@
android:viewportHeight="24"
android:viewportWidth="24">
<path
android:fillColor="#FFFFFF"
android:fillColor="?android:attr/colorForeground"
android:pathData="M6,2c-1.1,0 -1.99,0.9 -1.99,2L4,20c0,1.1 0.89,2 1.99,2L18,22c1.1,0 2,-0.9 2,-2L20,8l-6,-6L6,2zM13,9L13,3.5L18.5,9L13,9z" />
</vector>
@@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportHeight="24"
android:viewportWidth="24">
<path
android:fillColor="?android:attr/colorBackground"
android:pathData="M6,2c-1.1,0 -1.99,0.9 -1.99,2L4,20c0,1.1 0.89,2 1.99,2L18,22c1.1,0 2,-0.9 2,-2L20,8l-6,-6L6,2zM13,9L13,3.5L18.5,9L13,9z" />
</vector>
+1 -1
View File
@@ -5,6 +5,6 @@
android:viewportHeight="24"
android:viewportWidth="24">
<path
android:fillColor="#FFFFFF"
android:fillColor="?android:attr/colorForeground"
android:pathData="M17,3L5,3c-1.11,0 -2,0.9 -2,2v14c0,1.1 0.89,2 2,2h14c1.1,0 2,-0.9 2,-2L21,7l-4,-4zM12,19c-1.66,0 -3,-1.34 -3,-3s1.34,-3 3,-3 3,1.34 3,3 -1.34,3 -3,3zM15,9L5,9L5,5h10v4z" />
</vector>
+1 -1
View File
@@ -4,6 +4,6 @@
android:viewportHeight="24"
android:viewportWidth="24">
<path
android:fillColor="#FFFFFF"
android:fillColor="?android:attr/colorForeground"
android:pathData="M19.43,12.98c0.04,-0.32 0.07,-0.64 0.07,-0.98s-0.03,-0.66 -0.07,-0.98l2.11,-1.65c0.19,-0.15 0.24,-0.42 0.12,-0.64l-2,-3.46c-0.12,-0.22 -0.39,-0.3 -0.61,-0.22l-2.49,1c-0.52,-0.4 -1.08,-0.73 -1.69,-0.98l-0.38,-2.65C14.46,2.18 14.25,2 14,2h-4c-0.25,0 -0.46,0.18 -0.49,0.42l-0.38,2.65c-0.61,0.25 -1.17,0.59 -1.69,0.98l-2.49,-1c-0.23,-0.09 -0.49,0 -0.61,0.22l-2,3.46c-0.13,0.22 -0.07,0.49 0.12,0.64l2.11,1.65c-0.04,0.32 -0.07,0.65 -0.07,0.98s0.03,0.66 0.07,0.98l-2.11,1.65c-0.19,0.15 -0.24,0.42 -0.12,0.64l2,3.46c0.12,0.22 0.39,0.3 0.61,0.22l2.49,-1c0.52,0.4 1.08,0.73 1.69,0.98l0.38,2.65c0.03,0.24 0.24,0.42 0.49,0.42h4c0.25,0 0.46,-0.18 0.49,-0.42l0.38,-2.65c0.61,-0.25 1.17,-0.59 1.69,-0.98l2.49,1c0.23,0.09 0.49,0 0.61,-0.22l2,-3.46c0.12,-0.22 0.07,-0.49 -0.12,-0.64l-2.11,-1.65zM12,15.5c-1.93,0 -3.5,-1.57 -3.5,-3.5s1.57,-3.5 3.5,-3.5 3.5,1.57 3.5,3.5 -1.57,3.5 -3.5,3.5z" />
</vector>
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/list_item_activated" android:state_activated="true" />
<item android:drawable="@android:color/transparent" />
<item android:drawable="@color/list_item_activated" android:state_activated="true" /> <!-- TODO(msf): themeify this -->
<item android:drawable="@android:color/transparent" /> <!-- TODO(msf): themeify this -->
</selector>
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/list_item_ripple">
android:color="@color/list_item_ripple"> <!-- TODO(msf): themeify this -->
<item android:drawable="@drawable/list_item_background" />
</ripple>
@@ -51,7 +51,7 @@
android:background="@null"
android:contentDescription="@string/delete"
android:onClick="@{() -> collection.remove(item)}"
android:src="@drawable/ic_action_delete_black" />
android:src="@drawable/ic_action_delete" />
<TextView
android:id="@+id/public_key_label"
@@ -44,7 +44,7 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="@{fragment::onRequestCreateConfig}"
app:fab_icon="@drawable/ic_action_edit"
app:fab_icon="@drawable/ic_action_edit_inverse"
app:fab_size="mini"
app:fab_title="@string/create_empty" />
@@ -53,7 +53,7 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="@{fragment::onRequestImportConfig}"
app:fab_icon="@drawable/ic_action_open"
app:fab_icon="@drawable/ic_action_open_inverse"
app:fab_size="mini"
app:fab_title="@string/create_from_file" />
</com.wireguard.android.widget.fab.FloatingActionsMenu>
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- TODO(msf): remove these 4 hard-coded colors and replace with theme colors -->
<color name="list_item_activated">#64cfd8dc</color>
<color name="list_item_ripple">#a0808e95</color>
<color name="fab_label_text_color">#000000</color>
<color name="fab_label_background_color">#bbbbbb</color>
<color name="accent">#BBDEFB</color>
</resources>
+5
View File
@@ -1,5 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- TODO(msf): remove these 4 hard-coded colors and replace with theme colors -->
<color name="list_item_activated">#cfd8dc</color> <!-- Blue Grey 200 -->
<color name="list_item_ripple">#808e95</color> <!-- Blue Grey 200 dark -->
<color name="fab_label_text_color">#ffffff</color>
<color name="fab_label_background_color">#444444</color>
<color name="accent">#2196F3</color>
</resources>
+16 -3
View File
@@ -29,6 +29,9 @@
<string name="create_activity_title">Create WireGuard Tunnel</string>
<string name="create_empty">Create from scratch</string>
<string name="create_from_file">Create from file or archive</string>
<string name="dark_theme_title">Use dark theme</string>
<string name="dark_theme_summary_on">Currently using dark night theme</string>
<string name="dark_theme_summary_off">Currently using light day theme</string>
<string name="delete">Delete</string>
<string name="dns_servers">DNS servers</string>
<string name="edit">Edit</string>
@@ -36,9 +39,6 @@
<string name="error_down">Error bringing down tunnel: %s</string>
<string name="error_root">Please obtain root access and try again</string>
<string name="error_up">Error bringing up tunnel: %s</string>
<string name="export_error">Unable to export tunnels: %s</string>
<string name="export_success">Saved to %s</string>
<string name="export_summary">Zip file will be saved to downloads folder</string>
<string name="generate">Generate</string>
<string name="hint_automatic">(auto)</string>
<string name="hint_generated">(generated)</string>
@@ -48,9 +48,15 @@
<string name="import_success">Imported “%s”</string>
<string name="interface_title">Interface</string>
<string name="listen_port">Listen port</string>
<string name="log_exporter_title">Export log file</string>
<string name="log_export_error">Unable to export log: %s</string>
<string name="log_export_success">Saved to %s</string>
<string name="log_export_summary">Log file will be saved to downloads folder</string>
<string name="mtu">MTU</string>
<string name="name">Name</string>
<string name="peer">Peer</string>
<string name="permission_label">control WireGuard tunnels</string>
<string name="permission_description">Allows an app to control WireGuard tunnels. Apps with this permission may enable and disable WireGuard tunnels at will, potentially misdirecting Internet traffic.</string>
<string name="persistent_keepalive">Persistent keepalive</string>
<string name="pre_shared_key">Pre-shared key</string>
<string name="private_key">Private key</string>
@@ -71,5 +77,12 @@
<string name="tunnel_create_success">Successfully created tunnel “%s”</string>
<string name="tunnel_rename_error">Unable to rename tunnel: %s</string>
<string name="tunnel_rename_success">Successfully renamed tunnel to “%s”</string>
<string name="version_title">WireGuard for Android v%s"</string>
<string name="version_kernel_summary">Kernel module backend v%s</string>
<string name="version_kernel_unknown_summary">Unknown kernel module version</string>
<string name="version_userspace_summary">Go userspace backend v%s</string>
<string name="zip_exporter_title">Export tunnels to zip file</string>
<string name="zip_export_error">Unable to export tunnels: %s</string>
<string name="zip_export_success">Saved to %s</string>
<string name="zip_export_summary">Zip file will be saved to downloads folder</string>
</resources>
+4 -1
View File
@@ -1,7 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar" />
<style name="AppTheme" parent="Theme.AppCompat.DayNight.DarkActionBar">
<item name="colorAccent">@color/accent</item>
</style>
<style name="SettingsTheme" parent="AppTheme">
<item name="preferenceTheme">@style/PreferenceThemeOverlay.v14.Material</item>
@@ -9,6 +11,7 @@
<style name="fab_label" parent="android:TextAppearance.DeviceDefault.Inverse">
<item name="android:background">@drawable/fab_label_background</item>
<item name="android:textColor">@color/fab_label_text_color</item>
</style>
</resources>
+9 -1
View File
@@ -1,10 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<com.wireguard.android.preference.VersionPreference android:icon="@mipmap/ic_launcher" />
<CheckBoxPreference
android:defaultValue="false"
android:key="restore_on_boot"
android:summary="@string/restore_on_boot_summary"
android:title="@string/restore_on_boot_title" />
<com.wireguard.android.preference.ToolsInstallerPreference android:key="tools_installer" />
<com.wireguard.android.preference.ZipExporterPreference android:key="zip_exporter" />
<com.wireguard.android.preference.ZipExporterPreference />
<com.wireguard.android.preference.LogExporterPreference />
<CheckBoxPreference
android:defaultValue="false"
android:key="dark_theme"
android:summaryOn="@string/dark_theme_summary_on"
android:summaryOff="@string/dark_theme_summary_off"
android:title="@string/dark_theme_title" />
</PreferenceScreen>
@@ -160,4 +160,9 @@ func wgGetSocketV6(tunnelHandle int32) int32 {
return fd
}
//export wgVersion
func wgVersion() string {
return WireGuardGoVersion
}
func main() {}
@@ -4,12 +4,15 @@
*/
#include <jni.h>
#include <stdlib.h>
#include <string.h>
struct go_string { const char *str; long n; };
extern int wgTurnOn(struct go_string ifname, int tun_fd, struct go_string settings);
extern void wgTurnOff(int handle);
extern int wgGetSocketV4(int handle);
extern int wgGetSocketV6(int handle);
extern struct go_string wgVersion();
JNIEXPORT jint JNICALL Java_com_wireguard_android_backend_GoBackend_wgTurnOn(JNIEnv *env, jclass c, jstring ifname, jint tun_fd, jstring settings)
{
@@ -43,3 +46,17 @@ JNIEXPORT jint JNICALL Java_com_wireguard_android_backend_GoBackend_wgGetSocketV
{
return wgGetSocketV6(handle);
}
JNIEXPORT jstring JNICALL Java_com_wireguard_android_backend_GoBackend_wgVersion(JNIEnv *env, jclass c)
{
jstring ret;
struct go_string s = wgVersion();
char *cstr = malloc(s.n + 1);
if (!cstr)
return NULL;
memcpy(cstr, s.str, s.n);
cstr[s.n] = '\0';
ret = (*env)->NewStringUTF(env, cstr);
free(cstr);
return ret;
}