Compare commits

..
4 Commits
Author SHA1 Message Date
gmp fdb655c671 Tweak SelButton. 2019-10-10 17:07:39 -04:00
gmp 0f984918ea Remove page timing debug information. 2019-10-10 11:36:27 -04:00
gmp 49ebf55b15 Fix performance bug in list.Layout(...) 2019-10-10 11:35:11 -04:00
gmp 455a8960e5 Update gio version. 2019-10-08 10:58:42 -04:00
24 changed files with 395 additions and 1699 deletions
+1 -2
View File
@@ -2,5 +2,4 @@ cmd/passgo/passgo
cmd/passgo-gui/passgo-gui cmd/passgo-gui/passgo-gui
nohup.out nohup.out
*.apk *.apk
*.idsig cpuprofile
/passgo-gui
BIN
View File
Binary file not shown.
-91
View File
@@ -1,91 +0,0 @@
package st.wow.git.passgo;
import java.lang.Runnable;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.content.Context;
import android.util.Log;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.Manifest;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.view.View;
// Requests the storage permissions the app needs to read the password
// store in shared storage. On Android 11+ (API 30+) the
// MANAGE_EXTERNAL_STORAGE ("All files access") permission cannot be
// requested with a dialog; the user must toggle it in the system
// settings, so we launch that settings screen directly for this app.
public class Permissions extends Fragment {
Context ctx;
Handler handler;
final int PERMISSIONS_REQUEST = 1;
public Permissions(View view) {
Log.d("passgo", "Permissions()");
this.ctx = view.getContext();
this.handler = new Handler(this.ctx.getMainLooper());
Permissions inst = this;
handler.post(new Runnable() {
public void run() {
Activity act = (Activity)ctx;
FragmentTransaction ft = act.getFragmentManager().beginTransaction();
ft.add(inst, "Permissions");
ft.commitNow();
}
});
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
Log.d("passgo", "Permissions onAttach()");
if (!(context instanceof Activity)) {
Log.w("passgo", "Context is not an Activity");
return;
}
Activity activity = (Activity) context;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
if (context.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
PERMISSIONS_REQUEST
);
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R
&& !Environment.isExternalStorageManager()) {
Log.d("passgo", "Requesting all files access");
Intent intent = new Intent(
Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION,
Uri.parse("package:" + activity.getPackageName())
);
if (intent.resolveActivity(activity.getPackageManager()) != null) {
startActivity(intent);
} else {
Intent fallback = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
if (fallback.resolveActivity(activity.getPackageManager()) != null) {
startActivity(fallback);
} else {
Log.e("passgo", "No activity found for all files access settings");
}
}
}
}
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("passgo", "Permissions onActivityResult(" + requestCode + "): " + resultCode);
super.onActivityResult(requestCode, resultCode, data);
}
}
BIN
View File
Binary file not shown.
-375
View File
@@ -1,375 +0,0 @@
package st.wow.git.passgo;
import java.lang.Runnable;
import java.lang.String;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import android.os.Handler;
import android.os.IBinder;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import org.openintents.openpgp.IOpenPgpService2;
import org.openintents.openpgp.OpenPgpError;
import org.openintents.openpgp.OpenPgpSignatureResult;
import org.openintents.openpgp.util.OpenPgpApi;
import android.content.ComponentName;
import android.content.ServiceConnection;
import android.content.Context;
import android.content.ClipboardManager;
import android.content.ClipData;
import android.content.Intent;
import android.util.Log;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.PendingIntent;
import android.content.IntentSender;
import android.content.IntentSender.OnFinished;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.Manifest;
import android.content.pm.PackageManager;
import android.content.Context;
import android.view.View;
public class PgpConnect extends Fragment {
Context ctx;
Handler handler;
ClipboardManager cb;
IOpenPgpService2 mService;
final int PERMISSIONS_REQUEST = 1;
// The OpenPgpApi in openpgp-api.jar calls through the IOpenPgpService2
// AIDL interface, so we must bind the service that implements that
// descriptor: org.openintents.openpgp.IOpenPgpService2 (Keychain >= 11 /
// standalone 5.x-6.x). The v1 action (IOpenPgpService) does not implement
// the v2 descriptor and dies with a SecurityException; the very old
// org.openintents.openpgp.api.OpenPgpService action (used by
// OpenPgpServiceConnection) no longer exists. Try in that order.
static final String[] SERVICE_ACTIONS = {
"org.openintents.openpgp.IOpenPgpService2",
"org.openintents.openpgp.IOpenPgpService",
"org.openintents.openpgp.api.OpenPgpService",
};
final ServiceConnection mConnection = new ServiceConnection() {
@Override public void onServiceConnected(ComponentName name, IBinder service) {
mService = IOpenPgpService2.Stub.asInterface(service);
Log.d("gio", "OpenPGP service connected: " + name);
}
@Override public void onServiceDisconnected(ComponentName name) {
mService = null;
Log.d("gio", "OpenPGP service disconnected");
}
};
private void bindOpenPgp() {
Intent bindIntent = null;
for (String action : SERVICE_ACTIONS) {
Intent i = new Intent(action);
i.setPackage("org.sufficientlysecure.keychain");
if (ctx.getPackageManager().resolveService(i, 0) != null) {
bindIntent = i;
break;
}
}
if (bindIntent == null) {
Log.e("gio", "No OpenPGP service found in org.sufficientlysecure.keychain");
return;
}
Log.d("gio", "Binding OpenPGP service: " + bindIntent.getAction());
ctx.bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE);
}
// executeApi needs a live service; the bind is asynchronous, so if the
// service is not connected yet, retry on the main looper (up to ~10 s)
// instead of calling into a null service.
private void runWhenConnected(final int chint, final Runnable task, final int attempt) {
if (mService != null) {
task.run();
return;
}
if (attempt > 33) {
Log.e("gio", "OpenPGP service never connected");
stringResult(chint, null);
return;
}
handler.postDelayed(new Runnable() {
public void run() {
runWhenConnected(chint, task, attempt + 1);
}
}, 300);
}
public PgpConnect(View view) {
Log.d("gio", "PgpConnect()");
this.ctx = view.getContext();
this.handler = new Handler(this.ctx.getMainLooper());
PgpConnect inst = this;
handler.post(new Runnable() {
public void run() {
Activity act = (Activity)ctx;
FragmentTransaction ft = act.getFragmentManager().beginTransaction();
ft.add(inst, "PgpConnect");
ft.commitNow();
}
});
}
@Override public void onAttach(Context ctx) {
super.onAttach(ctx);
Log.d("gio", "onAttach()");
if (ctx instanceof Activity) {
Log.d("gio", "It's an Activity!");
}
bindOpenPgp();
cb = (ClipboardManager) ctx.getSystemService(Context.CLIPBOARD_SERVICE);
if (ctx.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ctx.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST);
}
System.loadLibrary("gio");
installComplete(this);
}
//For debugging:
/*private void printExtras(Intent data) {
Bundle bundle = data.getExtras();
if (bundle != null) {
for (String k : bundle.keySet()) {
Log.d("gio", "extra:" + k);
}
}
}*/
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("gio", "onActivityResult(" + requestCode + "): " + resultCode);
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) {
Log.d("gio", "onActivityResult: not OK");
stringResult(requestCode, null);
return;
}
switch (data.getAction()) {
case OpenPgpApi.ACTION_DECRYPT_VERIFY: {
Log.d("gio", "action decrypt");
_decrypt(data, requestCode);
break;
}
case OpenPgpApi.ACTION_ENCRYPT: {
Log.d("gio", "action encrypt");
_encrypt(data, requestCode);
break;
}
case OpenPgpApi.ACTION_GET_KEY_IDS:
Log.d("gio", "action getid");
String[] ids = data.getStringArrayExtra("user_ids");
if (ids != null && ids.length > 0) {
Log.d("gio", "got some IDs");
stringResult(requestCode, ids[0]);
} else {
Log.d("gio", "no ids");
stringResult(requestCode, null);
}
break;
default: {
Log.d("gio", "some other action");
}
}
}
public void Clip(byte []dat) {
ClipData clip = ClipData.newPlainText("PgpConnect", new String(dat));
cb.setPrimaryClip(clip);
}
public void GetId(int chint) {
if (handler == null) {
stringResult(chint, null);
return;
}
Log.d("gio", "GetId()");
handler.post(new Runnable() {
public void run() {
Intent data = new Intent();
data.setAction(OpenPgpApi.ACTION_GET_KEY_IDS);
//data.setAction(OpenPgpApi.ACTION_ENCRYPT);
data.putExtra(OpenPgpApi.EXTRA_USER_IDS, new String[]{" "});
_getid(data, chint);
}
});
}
public void Decrypt(byte []dat, int chint) {
if (handler == null) {
stringResult(chint, null);
return;
}
handler.post(new Runnable() {
public void run() {
Intent data = new Intent();
data.setAction(OpenPgpApi.ACTION_DECRYPT_VERIFY);
data.putExtra("DATA", dat);
_decrypt(data, chint);
}
});
}
private void _getid(Intent data, int chint) {
Log.d("gio","_getid");
runWhenConnected(chint, new Runnable() {
public void run() { doGetid(data, chint); }
}, 0);
}
private void doGetid(Intent data, int chint) {
InputStream is = null;
ByteArrayOutputStream os = new ByteArrayOutputStream();
OpenPgpApi api = new OpenPgpApi(this.ctx, mService);
Intent result = api.executeApi(data, is, os);
switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR)) {
case OpenPgpApi.RESULT_CODE_SUCCESS: {
Log.d("gio","_getid: success");
try {
String ret = os.toString("UTF-8");
//Log.d(OpenPgpApi.TAG, "output: " + ret);
stringResult(chint, ret);
} catch (UnsupportedEncodingException e) {
Log.e("gio", "UnsupportedEncodingException", e);
stringResult(chint, null);
}
break;
}
case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED: {
Log.d("gio","_getid: interaction required");
PendingIntent pi = result.getParcelableExtra(OpenPgpApi.RESULT_INTENT);
try {
startIntentSenderForResult(pi.getIntentSender(), chint, null, 0, 0, 0, null);
} catch (IntentSender.SendIntentException e) {
Log.e("gio", "SendIntentException", e);
stringResult(chint, null);
}
break;
}
case OpenPgpApi.RESULT_CODE_ERROR: {
Log.d("gio","_getid: error");
OpenPgpError error = result.getParcelableExtra(OpenPgpApi.RESULT_ERROR);
stringResult(chint, null);
}
}
}
private void _decrypt(Intent data, int chint) {
Log.d("gio","_decrypt");
runWhenConnected(chint, new Runnable() {
public void run() { doDecrypt(data, chint); }
}, 0);
}
private void doDecrypt(Intent data, int chint) {
byte []dat = data.getByteArrayExtra("DATA");
InputStream is = new ByteArrayInputStream(dat);
ByteArrayOutputStream os = new ByteArrayOutputStream();
OpenPgpApi api = new OpenPgpApi(this.ctx, mService);
Intent result = api.executeApi(data, is, os);
switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR)) {
case OpenPgpApi.RESULT_CODE_SUCCESS: {
try {
String ret = os.toString("UTF-8");
//Log.d(OpenPgpApi.TAG, "output: " + ret);
stringResult(chint, ret);
} catch (UnsupportedEncodingException e) {
Log.e("gio", "UnsupportedEncodingException", e);
stringResult(chint, null);
}
break;
}
case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED: {
PendingIntent pi = result.getParcelableExtra(OpenPgpApi.RESULT_INTENT);
try {
startIntentSenderForResult(pi.getIntentSender(), chint, null, 0, 0, 0, null);
} catch (IntentSender.SendIntentException e) {
Log.e("gio", "SendIntentException", e);
stringResult(chint, null);
}
break;
}
case OpenPgpApi.RESULT_CODE_ERROR: {
OpenPgpError error = result.getParcelableExtra(OpenPgpApi.RESULT_ERROR);
stringResult(chint, null);
}
}
}
public void Encrypt(byte[] id, byte[] dat, int chint) {
if (handler == null) {
stringResult(chint, null);
return;
}
handler.post(new Runnable() {
public void run() {
Intent data = new Intent();
data.setAction(OpenPgpApi.ACTION_ENCRYPT);
data.putExtra(OpenPgpApi.EXTRA_USER_IDS, new String[]{new String(id)});
data.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true);
data.putExtra("DATA", dat);
_encrypt(data, chint);
}
});
}
private void _encrypt(Intent data, int chint) {
Log.d("gio","_encrypt");
runWhenConnected(chint, new Runnable() {
public void run() { doEncrypt(data, chint); }
}, 0);
}
private void doEncrypt(Intent data, int chint) {
byte []dat = data.getByteArrayExtra("DATA");
InputStream is = new ByteArrayInputStream(dat);
ByteArrayOutputStream os = new ByteArrayOutputStream();
OpenPgpApi api = new OpenPgpApi(this.ctx, mService);
Intent result = api.executeApi(data, is, os);
switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR)) {
case OpenPgpApi.RESULT_CODE_SUCCESS: {
try {
String ret = os.toString("UTF-8");
//Log.d(OpenPgpApi.TAG, "output: " + ret);
stringResult(chint, ret);
} catch (UnsupportedEncodingException e) {
Log.e("gio", "UnsupportedEncodingException", e);
stringResult(chint, null);
}
if (result.hasExtra(OpenPgpApi.RESULT_SIGNATURE)) {
OpenPgpSignatureResult sigResult
= result.getParcelableExtra(OpenPgpApi.RESULT_SIGNATURE);
}
break;
}
case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED: {
PendingIntent pi = result.getParcelableExtra(OpenPgpApi.RESULT_INTENT);
try {
IntentSender sender = pi.getIntentSender();
//Log.d("PgpConnect", "IntentSender:" + sender.toString());
startIntentSenderForResult(sender, chint, null, 0, 0, 0, null);
} catch (IntentSender.SendIntentException e) {
Log.e("gio", "SendIntentException", e);
stringResult(chint, null);
}
break;
}
case OpenPgpApi.RESULT_CODE_ERROR: {
OpenPgpError error = result.getParcelableExtra(OpenPgpApi.RESULT_ERROR);
stringResult(chint, null);
break;
}
}
}
static private native void installComplete(PgpConnect p);
static private native void stringResult(int requestCode, String result);
}
+4 -33
View File
@@ -4,9 +4,8 @@ This repository includes Go code to interact with pass, the Unix password
manager. Library code is provided to open a password store, list manager. Library code is provided to open a password store, list
saved passwords, and decrypt specified passwords. The library provides saved passwords, and decrypt specified passwords. The library provides
a simple passphrase input function, or, if gpg-agent is running (on MacOS), a simple passphrase input function, or, if gpg-agent is running (on MacOS),
it will connect automatically to request your GPG passphrase. On Android, it will connect automatically to request your GPG passphrase. MacOS users
`passgo` connects to OpenKeychain. MacOS and Android users can also ask passgo can also ask passgo to copy a password directly to the clipboard.
to copy a password directly to the clipboard.
```go ```go
store := passgo.Store{} store := passgo.Store{}
@@ -30,33 +29,5 @@ p, err := store.Decrypt("myPass")
... ...
``` ```
Also included is a simple GUI front-end using [Gio](https://gioui.org) Also included is a simple GUI front-end using [Gio](https://gioui.org). See
that works on MacOS and Android. See `cmd/passgo-gui`. `cmd/passgo-gui`.
## Building the Android APK
Use `scripts/build.sh` — do not build by hand:
```sh
./scripts/build.sh phone # build + install on the phone
./scripts/build.sh phone --no-install
./scripts/build.sh emu # emulator build (amd64)
```
It outputs `cmd/passgo-gui/passgo-gui.apk` (APKs are git-ignored and
regenerated by the script). The script, in order:
1. `gogio -target android -targetsdk 34` (from `~/go/bin`; packages the
Go code plus the `*.jar` JNI classes found in `cmd/passgo-gui/`),
2. apktool decode → inject `MANAGE_EXTERNAL_STORAGE` into the manifest
(gogio's hardcoded permission table lacks it, and without it the
system "All files access" toggle is grayed out on Android 11+) →
apktool rebuild,
3. sign with the debug keystore (`~/.android/debug.keystore`),
4. `adb install -r`.
Prereqs: JDK, Go + gogio, Android SDK at `~/android-sdk`
(platform-tools + build-tools 35.0.0). apktool v3.0.3 is auto-downloaded
to `~/android-sdk/tools/apktool.jar` if missing. The script checks each
prereq and says what is missing. The phone is reached via adb over the
WireGuard address (see the global AGENTS.md).
+11 -44
View File
@@ -1,64 +1,31 @@
//go:build android //+build !darwin
package main package main
import ( import (
"os" "os"
"gioui.org/app" "golang.org/x/image/font/gofont/goregular"
"gioui.org/io/event" "golang.org/x/image/font/sfnt"
"git.wow.st/gmp/passgo"
)
var (
noidLabelText = "Enter a GPG key ID above"
) )
func init() { func init() {
log(Info, "Android start") log(Info, "Android start")
// Use a larger font on Android var err error
fontSize = 24 regular, err = sfnt.Parse(goregular.TTF)
}
func handleEvent(e event.Event) {
switch e := e.(type) {
case app.AndroidViewEvent:
// A zero View means the view is detached (e.g. the activity going
// away on a recents-wipe); there is nothing to register for a
// detached view. A re-attach arrives as a fresh event with a live
// view.
if e.View != 0 {
initPgp(e.View)
initPermissions(e.View)
}
}
}
func initPgp(view uintptr) {
passgo.InitPgp(view)
}
func initPermissions(view uintptr) {
passgo.InitPermissions(view)
}
func getConfDir() (string, error) {
ret, err := app.DataDir()
if err != nil { if err != nil {
log(Error, "Cannot get data directory:", err) log(Fatal, "Cannot parse default font: ", err)
return "", err
} }
if _, err := os.Stat(ret); os.IsNotExist(err) { confDir = app.DataDir()
err = os.MkdirAll(ret, 0700) if _, err := os.Stat(confDir); os.IsNotExist(err) {
err = os.MkdirAll(confDir, 0700)
if err != nil { if err != nil {
log(Error, "Cannot create configuration directory ", ret) log(Info, "Cannot create configuration directory ", confDir)
return "", err log(Fatal, err)
} else { } else {
log(Info, "Configuration directory created") log(Info, "Configuration directory created")
return ret, nil
} }
} else { } else {
log(Info, "Configuration directory found") log(Info, "Configuration directory found")
return ret, nil
} }
} }
+25 -32
View File
@@ -1,63 +1,56 @@
//go:build darwin //+build darwin
package main package main
import ( import (
"io"
"os" "os"
"os/user" "os/user"
"path" "path"
"gioui.org/font/opentype" "golang.org/x/image/font/gofont/goregular"
) "golang.org/x/image/font/sfnt"
var (
noidLabelText = "No GPG ids available. Please create a private key or enter a key ID above"
) )
func setFont() error { func setFont() error {
f, err := os.Open("/System/Library/Fonts/AppleSDGothicNeo.ttc") f, err := os.Open("/System/Library/Fonts/AppleSDGothicNeo.ttc")
if err != nil { if err != nil {
log(Info, "Cannot open system font collection") log(Info, "Cannot open system font.")
return err return err
} }
defer f.Close() collection, err := sfnt.ParseCollectionReaderAt(f)
data, err := io.ReadAll(f)
if err != nil { if err != nil {
log(Info, "Cannot read system font collection") log(Info, "Cannot parse system font.")
return err return err
} }
fnts, err := opentype.ParseCollection(data) regular, err = collection.Font(0)
if err != nil { if err != nil {
log(Info, "Cannot parse font collection") log(Info, "Cannot access first font in collection.")
return err return err
} }
collection = append(collection, fnts...)
return nil return nil
} }
func init() { func init() {
fontSize = 16 err := setFont()
setFont()
}
func getConfDir() (string, error) {
usr, err := user.Current()
if err != nil { if err != nil {
log(Error, "Cannot get current user: ", err) regular, err = sfnt.Parse(goregular.TTF)
return "", err
}
ret := path.Join(usr.HomeDir, ".config/passgo")
if _, err := os.Stat(ret); os.IsNotExist(err) {
err = os.MkdirAll(ret, 0700)
if err != nil { if err != nil {
log(Info, "Cannot create configuration directory ", confDir) log(Fatal, "Cannot parse default font: ", err)
return "", err }
} else { }
log(Info, "Configuration directory created") usr, err := user.Current()
return ret, nil if err != nil {
log(Fatal, "Cannot get current user: ", err)
}
confDir = path.Join(usr.HomeDir, ".config/passgo")
if _, err := os.Stat(confDir); os.IsNotExist(err) {
err = os.MkdirAll(confDir, 0700)
if err != nil {
log(Info, "Cannot create configuration directory ", confDir)
log(Fatal, err)
} else {
log(Info, "Configuration directory created")
} }
} }
return ret, nil
} }
-33
View File
@@ -1,33 +0,0 @@
//go:build linux && !android
package main
import (
"os"
"gioui.org/app"
)
var (
noidLabelText = "No GPG ids available"
)
func init() {
fontSize = 16
}
func getConfDir() (string, error) {
ret, err := app.DataDir()
if err != nil {
log(Error, "Cannot get data directory:", err)
return "", err
}
if _, err := os.Stat(ret); os.IsNotExist(err) {
err = os.MkdirAll(ret, 0700)
if err != nil {
log(Error, "Cannot create configuration directory ", ret)
return "", err
}
}
return ret, nil
}
-10
View File
@@ -1,10 +0,0 @@
//go:build !android
package main
import (
"gioui.org/io/event"
)
func handleEvent(e event.Event) {
}
+230 -443
View File
File diff suppressed because it is too large Load Diff
+75 -64
View File
@@ -4,118 +4,129 @@ import (
"image" "image"
"image/color" "image/color"
"gioui.org/f32"
"gioui.org/gesture" "gioui.org/gesture"
"gioui.org/io/event" "gioui.org/io/pointer"
"gioui.org/layout" "gioui.org/layout"
"gioui.org/op/clip" "gioui.org/op"
"gioui.org/op/paint" "gioui.org/op/paint"
"gioui.org/text" "gioui.org/text"
"gioui.org/unit" "gioui.org/unit"
"gioui.org/widget/material"
) )
var ( var (
black = color.NRGBA{A: 0xff, R: 0, G: 0, B: 0} black = color.RGBA{A: 0xff, R: 0, G: 0, B: 0}
white = color.NRGBA{A: 0xff, R: 0xff, G: 0xff, B: 0xff} white = color.RGBA{A: 0xff, R: 0xff, G: 0xff, B: 0xff}
gray = color.NRGBA{A: 0xff, R: 0xf0, G: 0xf0, B: 0xf0} gray = color.RGBA{A: 0xff, R: 0xf0, G: 0xf0, B: 0xf0}
darkgray = color.NRGBA{A: 0xff, R: 0xa0, G: 0xa0, B: 0xa0} darkgray = color.RGBA{A: 0xff, R: 0xa0, G: 0xa0, B: 0xa0}
) )
type Overlay struct { type Overlay struct {
Size unit.Sp Size unit.Value
Text string Text string
Click gesture.Click Click gesture.Click
Color color.NRGBA Color color.RGBA
Background color.NRGBA Background color.RGBA
Alignment text.Alignment Alignment text.Alignment
} }
func (b *Overlay) Layout(gtx C) D { func (b *Overlay) Layout(gtx *layout.Context, family text.Family) {
ins := layout.UniformInset(unit.Dp(1)) ins := layout.UniformInset(unit.Dp(1))
return ins.Layout(gtx, func(gtx C) D { ins.Layout(gtx, func() {
st := layout.Stack{} st := layout.Stack{}
c2 := layout.Stacked(func(gtx C) D { c2 := st.Rigid(gtx, func() {
l := material.Label(th, b.Size, b.Text) l := text.Label{
Size: b.Size,
Text: b.Text,
Alignment: b.Alignment,
}
ins := layout.UniformInset(unit.Dp(4)) ins := layout.UniformInset(unit.Dp(4))
l.Color = b.Color l.Material.Record(gtx.Ops)
return ins.Layout(gtx, func(gtx C) D { paint.ColorOp{Color: b.Color}.Add(gtx.Ops)
return l.Layout(gtx) l.Material.Stop()
ins.Layout(gtx, func() {
l.Layout(gtx, family)
}) })
pointer.RectAreaOp{image.Rect(0, 0, gtx.Dimensions.Size.X, gtx.Dimensions.Size.Y)}.Add(gtx.Ops)
}) })
c1 := layout.Expanded(func(gtx C) D { c1 := st.Expand(gtx, func() {
return layoutRRect(b.Background, gtx) layoutRRect(b.Background, gtx)
}) })
return st.Layout(gtx, c1, c2) st.Layout(gtx, c1, c2)
}) })
} }
type SelButton struct { type SelButton struct {
Button Button
SelColor color.NRGBA SelColor color.RGBA
Selected bool Selected bool
} }
type Button struct { type Button struct {
Size unit.Sp Size unit.Value
Label string Label string
Click gesture.Click Click gesture.Click
Color color.NRGBA Color color.RGBA
Background color.NRGBA Background color.RGBA
Alignment text.Alignment Alignment text.Alignment
clicked bool clicked bool
} }
func layoutRRect(col color.NRGBA, gtx C) D { func layoutRRect(col color.RGBA, gtx *layout.Context) {
r := gtx.Dp(4) r := float32(gtx.Config.Px(unit.Dp(4)))
sz := image.Point{X: gtx.Constraints.Min.X, Y: gtx.Constraints.Min.Y} sz := image.Point{X: gtx.Constraints.Width.Min, Y: gtx.Constraints.Height.Min}
// Push the rounded-rect clip, paint, then restore the previous clip. w, h := float32(sz.X), float32(sz.Y)
stk := clip.UniformRRect(image.Rectangle{Max: sz}, r).Push(gtx.Ops) rrect(gtx.Ops, w, h, r, r, r, r)
paint.ColorOp{Color: col}.Add(gtx.Ops) paint.ColorOp{Color: col}.Add(gtx.Ops)
paint.PaintOp{}.Add(gtx.Ops) paint.PaintOp{Rect: f32.Rectangle{Max: f32.Point{X: w, Y: h}}}.Add(gtx.Ops)
stk.Pop() gtx.Dimensions = layout.Dimensions{Size: sz}
return layout.Dimensions{Size: sz}
} }
func (b *Button) Layout(gtx C) D { // https://pomax.github.io/bezierinfo/#circles_cubic.
mwidth := gtx.Constraints.Min.X func rrect(ops *op.Ops, width, height, se, sw, nw, ne float32) {
w, h := float32(width), float32(height)
const c = 0.55228475 // 4*(sqrt(2)-1)/3
var b paint.Path
b.Begin(ops)
b.Move(f32.Point{X: w, Y: h - se})
b.Cube(f32.Point{X: 0, Y: se * c}, f32.Point{X: -se + se*c, Y: se}, f32.Point{X: -se, Y: se}) // SE
b.Line(f32.Point{X: sw - w + se, Y: 0})
b.Cube(f32.Point{X: -sw * c, Y: 0}, f32.Point{X: -sw, Y: -sw + sw*c}, f32.Point{X: -sw, Y: -sw}) // SW
b.Line(f32.Point{X: 0, Y: nw - h + sw})
b.Cube(f32.Point{X: 0, Y: -nw * c}, f32.Point{X: nw - nw*c, Y: -nw}, f32.Point{X: nw, Y: -nw}) // NW
b.Line(f32.Point{X: w - ne - nw, Y: 0})
b.Cube(f32.Point{X: ne * c, Y: 0}, f32.Point{X: ne, Y: ne - ne*c}, f32.Point{X: ne, Y: ne}) // NE
b.End()
}
func (b *Button) Layout(gtx *layout.Context, family text.Family) {
b.clicked = false b.clicked = false
for _, ev := range b.Click.Events(gtx) {
if ev.Type == gesture.TypeClick {
b.clicked = true
}
}
ins := layout.UniformInset(unit.Dp(1)) ins := layout.UniformInset(unit.Dp(1))
return ins.Layout(gtx, func(gtx C) D { ins.Layout(gtx, func() {
st := layout.Stack{} st := layout.Stack{}
c2 := layout.Stacked(func(gtx C) D { c2 := st.Rigid(gtx, func() {
l := material.Label(th, b.Size, b.Label) l := text.Label{
l.Color = b.Color Size: b.Size,
Text: b.Label,
Alignment: b.Alignment,
}
ins := layout.UniformInset(unit.Dp(4)) ins := layout.UniformInset(unit.Dp(4))
ret := ins.Layout(gtx, func(gtx C) D { //paint.ColorOp{Color: b.Color}.Add(ops)
return l.Layout(gtx) ins.Layout(gtx, func() {
l.Layout(gtx, family)
}) })
// Register the click handler for the whole button area, not pointer.RectAreaOp{image.Rect(0, 0, gtx.Dimensions.Size.X, gtx.Dimensions.Size.Y)}.Add(gtx.Ops)
// just the label: otherwise buttons with short labels (in
// full-width rows, for example) have a tiny tap target.
hit := ret.Size
if hit.X < gtx.Constraints.Max.X {
hit.X = gtx.Constraints.Max.X
}
stk := clip.Rect(image.Rectangle{Max: hit}).Push(gtx.Ops)
event.Op(gtx.Ops, b)
b.Click.Add(gtx.Ops) b.Click.Add(gtx.Ops)
stk.Pop()
for {
ev, ok := b.Click.Update(gtx.Source)
if !ok {
break
}
if ev.Kind == gesture.KindClick {
b.clicked = true
}
}
return ret
}) })
c1 := layout.Expanded(func(gtx C) D { c1 := st.Expand(gtx, func() {
gtx.Constraints.Min.X = mwidth layoutRRect(b.Background, gtx)
return layoutRRect(b.Background, gtx)
}) })
return st.Layout(gtx, c1, c2) st.Layout(gtx, c1, c2)
}) })
} }
+6 -15
View File
@@ -1,23 +1,14 @@
module git.wow.st/gmp/passgo module git.wow.st/gmp/passgo
go 1.24.0 go 1.12
require ( require (
gioui.org v0.10.2 gioui.org v0.0.0-20191008122509-6bc55d66c2fe
git.wow.st/gmp/clip v0.0.0-20191001134149-1458ba6a7cf5 git.wow.st/gmp/clip v0.0.0-20191001134149-1458ba6a7cf5
git.wow.st/gmp/rand v0.0.0-20191001220155-a81bebfaf8b0 git.wow.st/gmp/rand v0.0.0-20191001220155-a81bebfaf8b0
github.com/fsnotify/fsnotify v1.8.0 github.com/fsnotify/fsnotify v1.4.7
github.com/jcmdev0/gpgagent v0.0.0-20180509014935-5601b32d936c github.com/jcmdev0/gpgagent v0.0.0-20180509014935-5601b32d936c
golang.org/x/crypto v0.46.0 golang.org/x/crypto v0.0.0-20190911031432-227b76d455e7
gopkg.in/yaml.v2 v2.2.7 golang.org/x/image v0.0.0-20190910094157-69e4b8554b2a
) gopkg.in/yaml.v2 v2.2.2
require (
gioui.org/shader v1.0.9 // indirect
github.com/go-text/typesetting v0.3.4 // indirect
golang.org/x/exp/shiny v0.0.0-20250408133849-7e4ce0ab07d0 // indirect
golang.org/x/image v0.26.0 // indirect
golang.org/x/net v0.48.0 // indirect
golang.org/x/sys v0.39.0 // indirect
golang.org/x/text v0.32.0 // indirect
) )
+32 -32
View File
@@ -1,40 +1,40 @@
eliasnaur.com/font v0.0.0-20230308162249-dd43949cb42d h1:ARo7NCVvN2NdhLlJE9xAbKweuI9L6UgfTbYb0YwPacY= gioui.org v0.0.0-20191002081212-2a1c203863c3 h1:4ROVjhDrWa/J/O4KbtbCItYHhWnFWbmTyHPrfBeeG0w=
eliasnaur.com/font v0.0.0-20230308162249-dd43949cb42d/go.mod h1:OYVuxibdk9OSLX8vAqydtRPP87PyTFcT9uH3MlEGBQA= gioui.org v0.0.0-20191002081212-2a1c203863c3/go.mod h1:+CEjc9B//HrBfWsQOVxjCyih7HGIj3Pww1xFHVDZyyk=
gioui.org v0.10.2 h1:bZU5CORROwc51sNha0zYdE2qWVaDncOp5EjV5nrZQZ8= gioui.org v0.0.0-20191002205528-32bda106e7ff h1:pLleCPnIUzrPrjM+kad+jVhU31lzoEfINETZkLcTMRQ=
gioui.org v0.10.2/go.mod h1:iKILKNq6+LHMWhP/HjGDW/wDidUzRnb7B6c7ZD9y1Mg= gioui.org v0.0.0-20191002205528-32bda106e7ff/go.mod h1:+CEjc9B//HrBfWsQOVxjCyih7HGIj3Pww1xFHVDZyyk=
gioui.org/cpu v0.0.0-20210808092351-bfe733dd3334/go.mod h1:A8M0Cn5o+vY5LTMlnRoK3O5kG+rH0kWfJjeKd9QpBmQ= gioui.org v0.0.0-20191002212946-96d3d74cb33a h1:+VTwpWGLLyLXICY3wn4LQlSLXpwX06PenIutOxYqe+M=
gioui.org/shader v1.0.9 h1:XxnqIfmClWpN49kizxH2W0JcCFrrEP4q3jZmNYaltbs= gioui.org v0.0.0-20191002212946-96d3d74cb33a/go.mod h1:+CEjc9B//HrBfWsQOVxjCyih7HGIj3Pww1xFHVDZyyk=
gioui.org/shader v1.0.9/go.mod h1:mWdiME581d/kV7/iEhLmUgUK5iZ09XR5XpduXzbePVM= gioui.org v0.0.0-20191008122509-6bc55d66c2fe h1:N29sMDb1EoJNXSTxGWWb1i+3GymQXbbwLiRc7bEW450=
gioui.org v0.0.0-20191008122509-6bc55d66c2fe/go.mod h1:+CEjc9B//HrBfWsQOVxjCyih7HGIj3Pww1xFHVDZyyk=
gioui.org/ui v0.0.0-20190918172808-816f0e901fc6 h1:LvHEYxyOW7g+PhOiAm8Delc3AUv9EH219oDvaUMeKBw=
gioui.org/ui v0.0.0-20190918172808-816f0e901fc6/go.mod h1:PssKPKlqVIeyaed+0w492Xc2NgX5M3n6oZKOAj5rxoE=
gioui.org/ui v0.0.0-20190926171558-ce74bc0cbaea h1:rv21Wx1Inf27NY453rrrP6tuEG65PyWPhnP2Jx+Qb8k=
gioui.org/ui v0.0.0-20190926171558-ce74bc0cbaea/go.mod h1:PssKPKlqVIeyaed+0w492Xc2NgX5M3n6oZKOAj5rxoE=
git.wow.st/gmp/clip v0.0.0-20191001134149-1458ba6a7cf5 h1:OKeTjZST+/TKvtdA258NXJH+/gIx/xwyZxKrAezNFvk= git.wow.st/gmp/clip v0.0.0-20191001134149-1458ba6a7cf5 h1:OKeTjZST+/TKvtdA258NXJH+/gIx/xwyZxKrAezNFvk=
git.wow.st/gmp/clip v0.0.0-20191001134149-1458ba6a7cf5/go.mod h1:NLdpaBoMQNFqncwP8OVRNWUDw1Kt9XWm3snfT7cXu24= git.wow.st/gmp/clip v0.0.0-20191001134149-1458ba6a7cf5/go.mod h1:NLdpaBoMQNFqncwP8OVRNWUDw1Kt9XWm3snfT7cXu24=
git.wow.st/gmp/rand v0.0.0-20191001220006-66bfa936ad6b h1:yu3SnygEUgkNJ3xBXLkWHws7tki5qveZ6Kk7ybWj1GQ=
git.wow.st/gmp/rand v0.0.0-20191001220006-66bfa936ad6b/go.mod h1:8+2Gwnrpc5yuk8Wp6cBhxvGcNLumYiPbQ7n0SQ8h29A=
git.wow.st/gmp/rand v0.0.0-20191001220155-a81bebfaf8b0 h1:08wP00wvbDINsct1fzKV1xGGLvvtNsSb2X4CtIdpBzM= git.wow.st/gmp/rand v0.0.0-20191001220155-a81bebfaf8b0 h1:08wP00wvbDINsct1fzKV1xGGLvvtNsSb2X4CtIdpBzM=
git.wow.st/gmp/rand v0.0.0-20191001220155-a81bebfaf8b0/go.mod h1:8+2Gwnrpc5yuk8Wp6cBhxvGcNLumYiPbQ7n0SQ8h29A= git.wow.st/gmp/rand v0.0.0-20191001220155-a81bebfaf8b0/go.mod h1:8+2Gwnrpc5yuk8Wp6cBhxvGcNLumYiPbQ7n0SQ8h29A=
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M=
github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/go-text/typesetting v0.3.4 h1:YYurUOtEb9kGSOz4uE3k4OpBGsp1dDL8+fjCeaFamAU=
github.com/go-text/typesetting v0.3.4/go.mod h1:4qZCQphq4KSgGTAeI0uMEkVbROgfah8BuyF5LRYr7XY=
github.com/go-text/typesetting-utils v0.0.0-20260223113751-2d88ac90dae3 h1:drBZzMgdYPbmyXqOto4YhhJGrFIQCX94FpR4MzTCsos=
github.com/go-text/typesetting-utils v0.0.0-20260223113751-2d88ac90dae3/go.mod h1:3/62I4La/HBRX9TcTpBj4eipLiwzf+vhI+7whTc9V7o=
github.com/jcmdev0/gpgagent v0.0.0-20180509014935-5601b32d936c h1:DCnjNrPDSEslcqqBgcZBxlLUIhk2elQVyf2V+HkyxJI= github.com/jcmdev0/gpgagent v0.0.0-20180509014935-5601b32d936c h1:DCnjNrPDSEslcqqBgcZBxlLUIhk2elQVyf2V+HkyxJI=
github.com/jcmdev0/gpgagent v0.0.0-20180509014935-5601b32d936c/go.mod h1:vdJ2op9pzpbH8CbpYKYBD6zjURqDY13PmnVn2I/uYBs= github.com/jcmdev0/gpgagent v0.0.0-20180509014935-5601b32d936c/go.mod h1:vdJ2op9pzpbH8CbpYKYBD6zjURqDY13PmnVn2I/uYBs=
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0= golang.org/x/crypto v0.0.0-20190911031432-227b76d455e7 h1:0hQKqeLdqlt5iIwVOBErRisrHJAN57yOiPRQItI20fU=
golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0 h1:R84qjqJb5nVJMxqWYb3np9L5ZsaDtB+a39EqjV0JSUM= golang.org/x/crypto v0.0.0-20190911031432-227b76d455e7/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0/go.mod h1:S9Xr4PYopiDyqSyp5NjCrhFrqg6A5zA2E/iPHPhqnS8= golang.org/x/image v0.0.0-20190703141733-d6a02ce849c9/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/exp/shiny v0.0.0-20250408133849-7e4ce0ab07d0 h1:tMSqXTK+AQdW3LpCbfatHSRPHeW6+2WuxaVQuHftn80= golang.org/x/image v0.0.0-20190910094157-69e4b8554b2a h1:gHevYm0pO4QUbwy8Dmdr01R5r1BuKtfYqRqF0h/Cbh0=
golang.org/x/exp/shiny v0.0.0-20250408133849-7e4ce0ab07d0/go.mod h1:ygj7T6vSGhhm/9yTpOQQNvuAUFziTH7RUiH74EoE2C8= golang.org/x/image v0.0.0-20190910094157-69e4b8554b2a/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.26.0 h1:4XjIFEZWQmCZi6Wv8BoxsDhRU3RVnLX04dToTDAEPlY= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/image v0.26.0/go.mod h1:lcxbMFAovzpnJxzXS3nyL83K27tmqtKzIJpctK8YO5c= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU= golang.org/x/sys v0.0.0-20190412213103-97732733099d h1:+R4KGOnez64A81RvjARKc4UT5/tI9ujCIVX+P5KiHuI=
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a h1:aYOabOQFp6Vj6W1F80affTUvO9UxmJRx8K0gsfABByQ=
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.7 h1:VUgggvou5XRW9mHwD/yXxIYSMtY0zoKQf/v226p2nyo= gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
+6 -97
View File
@@ -1,115 +1,24 @@
//go:build android //+build android
// +build android
// Regenerate PgpConnect.jar and Permissions.jar (gogio dexes every *.jar in
// the repo root; the two classes must stay in separate jars). ANDROID_HOME
// must be set. Note: go generate skips this file on non-android hosts.
//go:generate sh -c 'mkdir -p classes && javac -nowarn -classpath "$ANDROID_HOME/platforms/android-35/android.jar:openpgp-api.jar" -d classes PgpConnect.java Permissions.java && (cd classes && jar cf ../../PgpConnect.jar st/wow/git/passgo/PgpConnect* && jar cf ../../Permissions.jar st/wow/git/passgo/Permissions*) && rm -rf classes'
package passgo package passgo
/*
#import <jni.h>
#import "jni_android.h"
*/
import "C"
import ( import (
"fmt" "fmt"
"io/ioutil"
"log"
"path"
"strings"
"sync"
"unsafe"
"gioui.org/app"
_ "gioui.org/app/permission/storage"
//"git.wow.st/gmp/jni"
) )
var ( //Clip copies a string to the clipboard
jvm uintptr
waitch chan struct{}
//w *app.Window
pgp PGP
installCompleteOnce sync.Once
)
func init() {
waitch = make(chan struct{})
}
//export Java_st_wow_git_passgo_PgpConnect_installComplete
func Java_st_wow_git_passgo_PgpConnect_installComplete(env *C.JNIEnv, class C.jclass, p C.jobject) {
log.Printf("InstallComplete()")
pgp = PGP(C.NewGlobalRef(env, p))
installCompleteOnce.Do(func() {
close(waitch)
})
}
func InitPgp(view uintptr) {
log.Printf("InitPgp()")
if view == 0 {
return // detach signal; nothing to register
}
jvm = app.JavaVM()
SetJVM(jvm) // why?
RunInJVM(func(env *JNIEnv) {
C.registerFragment(env, (C.jobject)(unsafe.Pointer(view)))
})
}
// InitPermissions registers the Permissions fragment, which requests the
// storage permissions (launching the system "All files access" settings
// screen on Android 11+) so the app can read the store in shared storage.
func InitPermissions(view uintptr) {
log.Printf("InitPermissions()")
if view == 0 {
return // detach signal; nothing to register
}
RunInJVM(func(env *JNIEnv) {
C.registerPermissionsFragment(env, (C.jobject)(unsafe.Pointer(view)))
})
}
func stopPgp() {
waitch = make(chan struct{})
}
func connect() {
<-waitch
}
// Clip copies a string to the clipboard
func Clip(x string) { func Clip(x string) {
pgp.Clip(x) fmt.Println("Clipboard not implemented for this platform")
} }
func (s *Store) nativeDecrypt(name string) (string, error) { func (s *Store) nativeDecrypt(name string) (string, error) {
connect() return "", fmt.Errorf("NOT IMPLEMENTED")
data, err := ioutil.ReadFile(path.Join(s.Dir, strings.Join([]string{name, ".gpg"}, "")))
if err != nil {
return "", fmt.Errorf("Error reading file: %s", err)
}
ret, err := pgp.Decrypt(string(data))
return ret, err
} }
func (s *Store) nativeEncrypt(pw string) ([]byte, error) { func (s *Store) nativeEncrypt(pw string) ([]byte, error) {
connect() return nil, fmt.Errorf("NOT IMPLEMENTED")
ret, err := pgp.Encrypt(s.Id, pw)
return []byte(ret), err
} }
func nativeIdentities() ([]string, error) { func nativeIdentities() ([]string, error) {
//NOT IMPLEMENTED ON ANDROID return nil, fmt.Errorf("NOT IMPLEMENTED")
return []string{}, nil
log.Printf("nativeIdentities()")
connect()
log.Printf("calling pgp.GetId()")
id, err := pgp.GetId()
log.Printf("pgp.GetId() returned")
return []string{id}, err
} }
+2 -3
View File
@@ -1,5 +1,4 @@
//go:build darwin //+build darwin
// +build darwin
package passgo package passgo
@@ -120,7 +119,7 @@ func init() {
setAgentInfo() setAgentInfo()
} }
// Clip copies a string to the clipboard //Clip copies a string to the clipboard
func Clip(x string) { func Clip(x string) {
clip.Set(x) clip.Set(x)
} }
+2 -3
View File
@@ -1,5 +1,4 @@
//go:build !android && linux //+build !android,linux
// +build !android,linux
package passgo package passgo
@@ -8,7 +7,7 @@ import (
"os/exec" "os/exec"
) )
// Clip copies a string to the clipboard //Clip copies a string to the clipboard
func Clip(x string) { func Clip(x string) {
b := bytes.NewBuffer([]byte(x)) b := bytes.NewBuffer([]byte(x))
cmd := exec.Command("xclip") cmd := exec.Command("xclip")
+1 -2
View File
@@ -1,5 +1,4 @@
//go:build darwin || (!android && linux) //+build darwin !android,linux
// +build darwin !android,linux
package passgo package passgo
-121
View File
@@ -1,121 +0,0 @@
//#include <stdlib.h>
#include <stdio.h>
#include <jni.h>
#include "jni_android.h"
#include "_cgo_export.h"
void
registerFragment(JNIEnv *env, jobject view) {
if (view == NULL) {
// Detach signal (Gio sends ViewEvent{View: 0} when the view is
// destroyed, e.g. on a recents-wipe); the Go side already
// filters these, but GetObjectClass(null) aborts the process.
return;
}
jclass cls = (*env)->GetObjectClass(env, view);
jmethodID mid = (*env)->GetMethodID(env, cls, "getContext", "()Landroid/content/Context;");
jobject ctx = (*env)->CallObjectMethod(env, view, mid);
cls = (*env)->GetObjectClass(env, ctx);
mid = (*env)->GetMethodID(env, cls, "getClassLoader", "()Ljava/lang/ClassLoader;");
jobject loader = (*env)->CallObjectMethod(env, ctx, mid);
cls = (*env)->GetObjectClass(env, loader);
mid = (*env)->GetMethodID(env, cls, "findClass", "(Ljava/lang/String;)Ljava/lang/Class;");
jstring str = (*env)->NewStringUTF(env, "st/wow/git/passgo/PgpConnect");
cls = (*env)->CallObjectMethod(env, loader, mid, str);
mid = (*env)->GetMethodID(env, cls, "<init>", "(Landroid/view/View;)V");
jobject inst = (*env)->NewObject(env, cls, mid, view);
}
void
registerPermissionsFragment(JNIEnv *env, jobject view) {
if (view == NULL) {
return; // detach signal; see registerFragment
}
jclass cls = (*env)->GetObjectClass(env, view);
jmethodID mid = (*env)->GetMethodID(env, cls, "getContext", "()Landroid/content/Context;");
jobject ctx = (*env)->CallObjectMethod(env, view, mid);
cls = (*env)->GetObjectClass(env, ctx);
mid = (*env)->GetMethodID(env, cls, "getClassLoader", "()Ljava/lang/ClassLoader;");
jobject loader = (*env)->CallObjectMethod(env, ctx, mid);
cls = (*env)->GetObjectClass(env, loader);
mid = (*env)->GetMethodID(env, cls, "findClass", "(Ljava/lang/String;)Ljava/lang/Class;");
jstring str = (*env)->NewStringUTF(env, "st/wow/git/passgo/Permissions");
cls = (*env)->CallObjectMethod(env, loader, mid, str);
mid = (*env)->GetMethodID(env, cls, "<init>", "(Landroid/view/View;)V");
jobject inst = (*env)->NewObject(env, cls, mid, view);
}
void
GetId(JNIEnv* env, jobject p, int chint) {
jclass cls = (*env)->GetObjectClass(env, p);
jmethodID mid = (*env)->GetMethodID(env, cls, "GetId", "(I)V");
(*env)->CallObjectMethod(env, p, mid, chint);
}
void
Decrypt(JNIEnv* env, jobject p, char* cdata, int datalen, int chint) {
jbyteArray data = (*env)->NewByteArray(env, datalen);
if (datalen > 0) {
(*env)->SetByteArrayRegion(env, data, 0, datalen, cdata);
}
jclass cls = (*env)->GetObjectClass(env, p);
jmethodID mid = (*env)->GetMethodID(env, cls, "Decrypt", "([BI)V");
(*env)->CallVoidMethod(env, p, mid, data, chint);
}
void Java_st_wow_git_passgo_PgpConnect_stringResult(JNIEnv* env, jclass cls, jint requestCode, jobject response) {
if (response == 0) {
goStringResult(env, cls, requestCode, 0);
} else {
char* str = (*env)->GetStringUTFChars(env, response, NULL);
goStringResult(env, cls, requestCode, str);
}
}
void
Encrypt(JNIEnv* env, jobject p, char* cid, int idlen, char* cdata, int datalen, int chint) {
jbyteArray id = (*env)->NewByteArray(env, idlen);
if (idlen > 0) {
(*env)->SetByteArrayRegion(env, id, 0, idlen, cid);
}
jbyteArray data = (*env)->NewByteArray(env, datalen);
if (datalen > 0) {
(*env)->SetByteArrayRegion(env, data, 0, datalen, cdata);
}
jclass cls = (*env)->GetObjectClass(env, p);
jmethodID mid = (*env)->GetMethodID(env, cls, "Encrypt", "([B[BI)V");
(*env)->CallVoidMethod(env, p, mid, id, data, chint);
}
void
Clip(JNIEnv* env, jobject p, char* cdata, int datalen) {
jbyteArray data = (*env)->NewByteArray(env, datalen);
if (datalen > 0) {
(*env)->SetByteArrayRegion(env, data, 0, datalen, cdata);
}
jclass cls = (*env)->GetObjectClass(env, p);
jmethodID mid = (*env)->GetMethodID(env, cls, "Clip", "([B)V");
(*env)->CallVoidMethod(env, p, mid, data);
}
void CallVoidMethod(JNIEnv *env, jobject obj, jmethodID methodID) {
(*env)->CallVoidMethod(env, obj, methodID);
}
jint GetEnv(JavaVM *vm, JNIEnv **env, jint version) {
return (*vm)->GetEnv(vm, (void **)env, version);
}
jint AttachCurrentThread(JavaVM *vm, JNIEnv **p_env, void *thr_args) {
return (*vm)->AttachCurrentThread(vm, p_env, thr_args);
}
jint DetachCurrentThread(JavaVM *vm) {
return (*vm)->DetachCurrentThread(vm);
}
jobject
NewGlobalRef(JNIEnv *env, jobject o) {
return (*env)->NewGlobalRef(env, o);
}
-154
View File
@@ -1,154 +0,0 @@
package passgo
/*
#cgo LDFLAGS: -landroid -llog
#include <stdlib.h>
#include "jni_android.h"
*/
import "C"
import (
"errors"
"fmt"
"log"
"runtime"
"sync"
"unsafe"
)
var theJVM *C.JavaVM
type JNIEnv = C.JNIEnv
func SetJVM(jvm uintptr) {
log.Print("set theJVM")
theJVM = (*C.JavaVM)(unsafe.Pointer(jvm))
}
func JniCallVoidMethod(env *C.JNIEnv, obj C.jobject, methodID C.jmethodID) {
C.CallVoidMethod(env, obj, methodID)
}
type PGP C.jobject
var (
fragChans map[int]chan string
chmux sync.Mutex
chint int
)
func (p PGP) GetId() (string, error) {
ch := make(chan string)
chmux.Lock()
if fragChans == nil {
fragChans = make(map[int]chan string)
}
fragChans[chint] = ch
curint := chint
chint++
chmux.Unlock()
RunInJVM(func(env *JNIEnv) {
C.GetId(env, (C.jobject)(p), C.int(curint))
})
log.Printf("GetId(): waiting for response")
switch x := <-ch; {
case x == "":
log.Printf("GetId(): failed")
return "", fmt.Errorf("GetId failed")
default:
log.Printf("GetId(): got %s", x)
return x, nil
}
}
func (p PGP) Decrypt(data string) (string, error) {
ch := make(chan string)
chmux.Lock()
if fragChans == nil {
fragChans = make(map[int]chan string)
}
fragChans[chint] = ch
curint := chint
chint++
chmux.Unlock()
cdata := C.CString(data)
defer C.free(unsafe.Pointer(cdata))
RunInJVM(func(env *JNIEnv) {
C.Decrypt(env, (C.jobject)(p), (*C.char)(unsafe.Pointer(cdata)), (C.int)(len(data)), C.int(curint))
})
switch x := <-ch; {
case x == "":
return "", fmt.Errorf("Decryption failed")
default:
return x, nil
}
}
func (p PGP) Encrypt(id, data string) (string, error) {
ch := make(chan string)
chmux.Lock()
if fragChans == nil {
fragChans = make(map[int]chan string)
}
fragChans[chint] = ch
curint := chint
chint++
chmux.Unlock()
cid := C.CString(id)
defer C.free(unsafe.Pointer(cid))
cdata := C.CString(data)
defer C.free(unsafe.Pointer(cdata))
RunInJVM(func(env *JNIEnv) {
C.Encrypt(env, (C.jobject)(p), (*C.char)(unsafe.Pointer(cid)), (C.int)(len(id)), (*C.char)(unsafe.Pointer(cdata)), (C.int)(len(data)), C.int(curint))
})
switch x := <-ch; {
case x == "":
return "", fmt.Errorf("Encryption failed")
default:
return x, nil
}
}
func (p PGP) Clip(data string) {
cdata := C.CString(data)
defer C.free(unsafe.Pointer(cdata))
RunInJVM(func(env *JNIEnv) {
C.Clip(env, (C.jobject)(p), (*C.char)(unsafe.Pointer(cdata)), (C.int)(len(data)))
})
}
func RunInJVM(f func(env *C.JNIEnv)) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
var env *C.JNIEnv
var detach bool
if res := C.GetEnv(theJVM, &env, C.JNI_VERSION_1_6); res != C.JNI_OK {
if res != C.JNI_EDETACHED {
panic(fmt.Errorf("JNI GetEnv failed with error %d", res))
}
if C.AttachCurrentThread(theJVM, &env, nil) != C.JNI_OK {
panic(errors.New("runInJVM: AttachCurrentThread failed"))
}
detach = true
}
if detach {
defer func() {
C.DetachCurrentThread(theJVM)
}()
}
f(env)
}
//export goStringResult
func goStringResult(env *C.JNIEnv, class C.jclass, request C.jint, str *C.char) {
fragChans[int(request)] <- C.GoString(str)
C.free(unsafe.Pointer(str))
chmux.Lock()
delete(fragChans, int(request))
chmux.Unlock()
}
-14
View File
@@ -1,14 +0,0 @@
#include <jni.h>
void registerFragment(JNIEnv *env, jobject view);
void registerPermissionsFragment(JNIEnv *env, jobject view);
void GetId(JNIEnv* env, jobject p, int chint);
void Decrypt(JNIEnv* env, jobject p, char* cdata, int datalen, int chint);
void Encrypt(JNIEnv* env, jobject p, char* cid, int idlen, char* cdata, int datalen, int chint);
void Clip(JNIEnv* env, jobject p, char* cdata, int datalen);
void stringResult(JNIEnv* env, jclass cls, jint requestCode, jobject response);
void CallVoidMethod(JNIEnv *env, jobject obj, jmethodID methodID);
jint GetEnv(JavaVM *vm, JNIEnv **env, jint version);
jint AttachCurrentThread(JavaVM *vm, JNIEnv **p_env, void *thr_args);
jint DetachCurrentThread(JavaVM *vm);
jobject NewGlobalRef(JNIEnv *env, jobject o);
-19
View File
@@ -5,7 +5,6 @@ import (
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
"log"
"os" "os"
"os/user" "os/user"
"path" "path"
@@ -49,30 +48,15 @@ func GetStore(store *Store) error {
} }
if _, err := os.Stat(store.Dir); os.IsNotExist(err) { if _, err := os.Stat(store.Dir); os.IsNotExist(err) {
store.Empty = true store.Empty = true
} else {
store.Empty = false
} }
id, err := ioutil.ReadFile(path.Join(store.Dir, ".gpg-id")) id, err := ioutil.ReadFile(path.Join(store.Dir, ".gpg-id"))
if err != nil { if err != nil {
return fmt.Errorf("Can't read .gpg-id: %s", err) return fmt.Errorf("Can't read .gpg-id: %s", err)
} }
// extract only the email address portion of the ID (required
// for Android)
if id[len(id)-1] == '\n' { if id[len(id)-1] == '\n' {
id = id[:len(id)-1] id = id[:len(id)-1]
} }
for i := len(id) - 1; i > 0; i-- {
if id[i] == '>' {
for j := i - 1; j > 0; j-- {
if id[j] == '<' {
id = id[j+1 : i]
}
}
break
}
}
store.Id = string(id) store.Id = string(id)
log.Printf("ID = %s", store.Id)
return getKeyring() return getKeyring()
} }
@@ -150,8 +134,6 @@ func (s *Store) list(level int, p string) ([]Pass, error) {
fd, err := os.Open(dir) fd, err := os.Open(dir)
defer fd.Close() defer fd.Close()
if err != nil { if err != nil {
log.Printf("password store directory = %s", dir)
log.Printf("error is %s", err)
return nil, fmt.Errorf("Cannot open password store") return nil, fmt.Errorf("Cannot open password store")
} }
files, err := fd.Readdir(0) files, err := fd.Readdir(0)
@@ -280,7 +262,6 @@ func (s *Store) Decrypt(name string, prompts ...func() []byte) (string, error) {
} }
func Identities() ([]string, error) { func Identities() ([]string, error) {
log.Printf("Identities()")
getKeyring() getKeyring()
if useNative { if useNative {
return nativeIdentities() return nativeIdentities()
BIN
View File
Binary file not shown.
-112
View File
@@ -1,112 +0,0 @@
#!/usr/bin/env bash
# Build (and optionally install) the passgo-gui Android APK.
#
# Usage:
# ./scripts/build.sh [phone|emu] # build + install (default: phone)
# ./scripts/build.sh phone --no-install # build only
#
# Output: cmd/passgo-gui/passgo-gui.apk
#
# Prereqs on this workstation:
# - JDK (java on PATH)
# - Go + gogio (~/go/bin)
# - Android SDK at ~/android-sdk (platform-tools, build-tools 35.0.0)
# - debug keystore at ~/.android/debug.keystore
# apktool is not a prerequisite: if it is missing, the script downloads
# v3.0.3 to the stable location ~/android-sdk/tools/apktool.jar.
#
# Why the apktool detour: gogio's manifest permissions come from a hardcoded
# table (only the legacy READ/WRITE_EXTERNAL_STORAGE). On Android 11+ the
# "All files access" settings toggle is grayed out unless the app declares
# MANAGE_EXTERNAL_STORAGE, which Permissions.java opens at startup. So we
# decode the gogio APK, inject the permission, rebuild, and re-sign with
# the debug key.
set -euo pipefail
REPO=$(cd "$(dirname "$0")/.." && pwd)
export ANDROID_HOME=${ANDROID_HOME:-$HOME/android-sdk}
export PATH=$PATH:$ANDROID_HOME/platform-tools:$ANDROID_HOME/build-tools/35.0.0:$HOME/go/bin
MODE=${1:-phone}
INSTALL=1
[ "${2:-}" = "--no-install" ] && INSTALL=0
case "$MODE" in
phone) ARCH="arm64,arm";;
emu) ARCH="amd64";;
*) echo "usage: $0 [phone|emu] [--no-install]" >&2; exit 1;;
esac
die() { echo "ERROR: $*" >&2; exit 1; }
command -v java >/dev/null 2>&1 || die "java not found"
command -v gogio >/dev/null 2>&1 || die "gogio not found (need ~/go/bin)"
command -v apksigner >/dev/null 2>&1 || die "apksigner not found (need $ANDROID_HOME/build-tools/35.0.0)"
command -v adb >/dev/null 2>&1 || die "adb not found (need $ANDROID_HOME/platform-tools)"
[ -f "$HOME/.android/debug.keystore" ] || die "debug keystore missing: $HOME/.android/debug.keystore"
# apktool: auto-download to a stable location if missing.
APKTOOL="$ANDROID_HOME/tools/apktool.jar"
if [ ! -f "$APKTOOL" ]; then
echo "=== apktool missing; downloading v3.0.3 to $APKTOOL ==="
mkdir -p "$ANDROID_HOME/tools"
curl -fsSL -o "$APKTOOL" \
https://github.com/iBotPeaches/Apktool/releases/download/v3.0.3/apktool_3.0.3.jar \
|| die "apktool download failed"
fi
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
echo "=== gogio (Go -> APK) ==="
# targetSdk 34: targeting 35 makes Android 15 force edge-to-edge, which the
# app does not handle.
(cd "$REPO/cmd/passgo-gui" && gogio -target android -targetsdk 34 -arch "$ARCH" -o "$WORK/passgo-raw.apk" .)
[ -f "$WORK/passgo-raw.apk" ] || die "gogio did not produce an APK"
echo "=== apktool decode + inject MANAGE_EXTERNAL_STORAGE ==="
java -jar "$APKTOOL" d "$WORK/passgo-raw.apk" -o "$WORK/decoded" -f >/dev/null
python3 - "$WORK/decoded/AndroidManifest.xml" << 'PYEOF'
import sys, pathlib
p = pathlib.Path(sys.argv[1])
t = p.read_text()
perm = '<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>'
if perm not in t:
t = t.replace(" <application", " " + perm + "\n <application", 1)
if perm not in t:
sys.exit("ERROR: failed to inject MANAGE_EXTERNAL_STORAGE")
# Android 11+ package visibility: without <queries> the app cannot even
# resolve (let alone bind) Keychain's OpenPGP service.
queries = """ <queries>
<package android:name="org.sufficientlysecure.keychain"/>
<intent>
<action android:name="org.openintents.openpgp.IOpenPgpService2"/>
</intent>
</queries>
"""
if "<queries>" not in t:
t = t.replace(" <application", queries + " <application", 1)
if "<queries>" not in t:
sys.exit("ERROR: failed to inject <queries>")
p.write_text(t)
print("manifest: MANAGE_EXTERNAL_STORAGE + <queries> present")
PYEOF
echo "=== apktool rebuild ==="
java -jar "$APKTOOL" b "$WORK/decoded" -o "$WORK/passgo-unsigned.apk" >/dev/null
echo "=== sign ==="
apksigner sign \
--ks "$HOME/.android/debug.keystore" --ks-pass pass:android \
--key-pass pass:android --ks-key-alias androiddebugkey \
--out "$REPO/cmd/passgo-gui/passgo-gui.apk" "$WORK/passgo-unsigned.apk"
# ADB_SERIAL selects the device when several are attached (adb devices).
ADB="adb${ADB_SERIAL:+ -s $ADB_SERIAL}"
if [ "$INSTALL" = "1" ]; then
echo "=== install ==="
$ADB get-state >/dev/null 2>&1 || die "no adb device (connect the phone; set ADB_SERIAL if several are attached)"
$ADB install -r "$REPO/cmd/passgo-gui/passgo-gui.apk"
fi
echo "=== DONE: $REPO/cmd/passgo-gui/passgo-gui.apk ==="