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
} }
} }
+19 -26
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() if err != nil {
regular, err = sfnt.Parse(goregular.TTF)
if err != nil {
log(Fatal, "Cannot parse default font: ", err)
}
} }
func getConfDir() (string, error) {
usr, err := user.Current() usr, err := user.Current()
if err != nil { if err != nil {
log(Error, "Cannot get current user: ", err) log(Fatal, "Cannot get current user: ", err)
return "", err
} }
ret := path.Join(usr.HomeDir, ".config/passgo") confDir = path.Join(usr.HomeDir, ".config/passgo")
if _, err := os.Stat(ret); os.IsNotExist(err) { if _, err := os.Stat(confDir); os.IsNotExist(err) {
err = os.MkdirAll(ret, 0700) err = os.MkdirAll(confDir, 0700)
if err != nil { if err != nil {
log(Info, "Cannot create configuration directory ", confDir) 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
} }
} }
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) {
}
+182 -395
View File
@@ -1,3 +1,5 @@
// +build darwin linux
package main package main
import ( import (
@@ -10,17 +12,16 @@ import (
"strconv" "strconv"
"strings" "strings"
"sync" "sync"
"sync/atomic"
"time" "time"
"gioui.org/app" "gioui.org/app"
"gioui.org/font/gofont" "gioui.org/io/key"
"gioui.org/layout" "gioui.org/layout"
"gioui.org/op"
"gioui.org/text" "gioui.org/text"
"gioui.org/text/shape"
"gioui.org/unit" "gioui.org/unit"
"gioui.org/widget"
"gioui.org/widget/material" "golang.org/x/image/font/sfnt"
"github.com/fsnotify/fsnotify" "github.com/fsnotify/fsnotify"
"gopkg.in/yaml.v2" "gopkg.in/yaml.v2"
@@ -29,18 +30,12 @@ import (
"git.wow.st/gmp/rand" "git.wow.st/gmp/rand"
) )
type (
D = layout.Dimensions
C = layout.Context
)
type conf struct { type conf struct {
StoreDir string StoreDir string
ClearDelay int ClearDelay int
} }
func main() { func main() {
if false {
go func() { go func() {
f, err := os.Create("cpuprofile") f, err := os.Create("cpuprofile")
if err != nil { if err != nil {
@@ -59,14 +54,7 @@ func main() {
f.Close() f.Close()
fmt.Printf("CPU profile written\n") fmt.Printf("CPU profile written\n")
}() }()
}
var fd *os.File var fd *os.File
var err error
confDir, err = getConfDir()
if err != nil {
fmt.Printf("Can't get config directory")
os.Exit(-1)
}
confFile := path.Join(confDir, "config.yml") confFile := path.Join(confDir, "config.yml")
if _, err := os.Stat(confFile); os.IsNotExist(err) { if _, err := os.Stat(confFile); os.IsNotExist(err) {
fd, err = os.Create(confFile) fd, err = os.Create(confFile)
@@ -100,14 +88,11 @@ func main() {
} }
reload = make(chan struct{}) reload = make(chan struct{})
updated = make(chan struct{}, 1) updated = make(chan struct{})
chdir = make(chan struct{}) chdir = make(chan struct{})
passch = make(chan []byte) passch = make(chan []byte)
go func() {
log(Info, "passgo.Identities()")
passgo.Identities() passgo.Identities()
}()
go Updater() go Updater()
log(Info, "Staring event loop") log(Info, "Staring event loop")
go eventLoop() go eventLoop()
@@ -116,9 +101,8 @@ func main() {
} }
var ( var (
fontSize float32
collection []text.FontFace
confDir string confDir string
regular *sfnt.Font
Config conf Config conf
l []passgo.Pass l []passgo.Pass
mux sync.Mutex mux sync.Mutex
@@ -127,12 +111,9 @@ var (
updated chan struct{} updated chan struct{}
chdir chan struct{} chdir chan struct{}
passch chan []byte passch chan []byte
th *material.Theme
win atomic.Pointer[app.Window]
) )
func Updater() { func Updater() {
//time.Sleep(time.Second * 2)
update := func() { update := func() {
fmt.Printf("update()\n") fmt.Printf("update()\n")
ltmp, err := store.List() ltmp, err := store.List()
@@ -142,20 +123,7 @@ func Updater() {
mux.Lock() mux.Lock()
l = ltmp l = ltmp
mux.Unlock() mux.Unlock()
// Non-blocking: if a refresh is already pending it will pick up updated <- struct{}{}
// the latest list, so dropping the duplicate is fine.
select {
case updated <- struct{}{}:
default:
}
// Wake the window: the event loop blocks in w.Event(), which only
// returns when the window is invalidated or the user interacts
// with it. Without this, a list refresh signalled while the loop
// is blocked (e.g. the initial load on startup) would not be
// drawn until the next tap.
if w := win.Load(); w != nil {
w.Invalidate()
}
} }
update() update()
@@ -192,8 +160,7 @@ func saveConf(fds ...*os.File) {
} else { } else {
fd, err = os.Create(path.Join(confDir, "config.yml")) fd, err = os.Create(path.Join(confDir, "config.yml"))
if err != nil { if err != nil {
log(Error, "Config file = ", path.Join(confDir, "config.yml")) log(Fatal, "Cannot open config file: ", err)
log(Fatal, "Cannot open config file: ", err.Error())
} }
} }
defer fd.Close() defer fd.Close()
@@ -209,36 +176,23 @@ func saveConf(fds ...*os.File) {
} }
func eventLoop() { func eventLoop() {
var ops op.Ops w := app.NewWindow(
th = material.NewTheme()
th.TextSize = unit.Sp(fontSize)
if len(collection) > 0 {
// Use the embedded Go font plus the platform fonts (e.g. the
// Unicode font installed on Darwin) instead of the system fonts.
th.Shaper = text.NewShaper(text.NoSystemFonts(),
text.WithCollection(append(gofont.Collection(), collection...)))
} else {
// Always provide the embedded Go font: the system font scan
// finds no fonts on Android, and a fontless shaper renders a
// blank screen.
th.Shaper = text.NewShaper(text.WithCollection(gofont.Collection()))
}
w := new(app.Window)
w.Option(
app.Size(unit.Dp(250), unit.Dp(500)), app.Size(unit.Dp(250), unit.Dp(500)),
app.Title("passgo")) app.Title("passgo"))
win.Store(w) gtx := &layout.Context{Queue: w.Queue()}
var margincs layout.Constraints var margincs layout.Constraints
family := &shape.Family{Regular: regular}
var c1 layout.FlexChild // flex child for title bar var c1 layout.FlexChild // flex child for title bar
sysinset := &layout.Inset{}
margin := layout.UniformInset(unit.Dp(10)) margin := layout.UniformInset(unit.Dp(10))
title := material.Body1(th, "passgo") title := &text.Label{Size: unit.Sp(16), Text: "passgo"}
dotsBtn := &Button{ dotsBtn := &Button{
Size: unit.Sp(fontSize), Size: unit.Sp(16),
Label: "\u2026", Label: "\xe2\x8b\xae",
Alignment: text.Middle, Alignment: text.Middle,
Color: black, Color: black,
Background: gray, Background: gray,
@@ -250,12 +204,12 @@ func eventLoop() {
lst := &layout.List{Axis: layout.Vertical} lst := &layout.List{Axis: layout.Vertical}
passBtns := make([]*Button, 0) passBtns := make([]*Button, 0)
pathnames := make([]string, 0) pathnames := make([]string, 0)
copied := &Overlay{Size: unit.Sp(fontSize), Text: "copied to clipboard", copied := &Overlay{Size: unit.Sp(16), Text: "copied to clipboard",
Color: black, Color: black,
Background: darkgray, Background: darkgray,
Alignment: text.Middle, Alignment: text.Middle,
} }
cleared := &Overlay{Size: unit.Sp(fontSize), Text: "clipboard cleared", cleared := &Overlay{Size: unit.Sp(16), Text: "clipboard cleared",
Color: black, Color: black,
Background: darkgray, Background: darkgray,
Alignment: text.Middle, Alignment: text.Middle,
@@ -263,72 +217,31 @@ func eventLoop() {
overlay := copied overlay := copied
var overlayStart time.Time var overlayStart time.Time
FilterEd := &widget.Editor{SingleLine: true}
var lastFilter string
updateBtns := func() { updateBtns := func() {
passBtns = passBtns[:0] passBtns = passBtns[:0]
pathnames = pathnames[:0] pathnames = pathnames[:0]
dirs := make(map[string]bool) // visited pathnames
var addd, addf func(x passgo.Pass)
addd = func(x passgo.Pass) {
if x.Level < 1 {
return
}
d, n := path.Split(x.Pathname)
x = passgo.Pass{
Pathname: d,
Level: x.Level - 1,
Dir: true,
}
fmt.Printf("addd(): d/n = '%s'/'%s'\n", d, n)
if dirs[d] != true {
addd(x)
}
dirs[x.Pathname] = true
s := strings.Repeat(" /", x.Level)
lbl := strings.Join([]string{s, d}, "")
passBtns = append(passBtns, &Button{
Size: unit.Sp(fontSize),
Label: lbl,
Color: black,
Background: gray,
})
pathnames = append(pathnames, x.Pathname)
}
flt := strings.ToUpper(FilterEd.Text())
addf = func(x passgo.Pass) {
if !strings.Contains(strings.ToUpper(x.Pathname), flt) {
return
}
d, n := path.Split(x.Pathname)
s := strings.Repeat(" /", x.Level)
lbl := strings.Join([]string{s, n}, "")
if dirs[d] != true {
addd(x)
}
passBtns = append(passBtns, &Button{
Size: unit.Sp(fontSize),
Label: lbl,
Color: black,
Background: gray,
})
pathnames = append(pathnames, x.Pathname)
}
mux.Lock() mux.Lock()
for _, x := range l { for _, x := range l {
if !x.Dir { _, n := path.Split(x.Pathname)
addf(x) s := strings.Repeat(" /", x.Level)
z := ""
if x.Dir {
z = "/"
} }
passBtns = append(passBtns, &Button{
Size: unit.Sp(16),
Label: strings.Join([]string{s, n, z}, ""),
Background: gray,
})
pathnames = append(pathnames, x.Pathname)
} }
mux.Unlock() mux.Unlock()
} }
updateBtns()
idBtns := make([]*Button, 0) idBtns := make([]*Button, 0)
updateIdBtns := func() { updateIdBtns := func() {
log(Info, "passgo.Identities()")
ids, err := passgo.Identities() ids, err := passgo.Identities()
if err != nil { if err != nil {
log(Info, err) log(Info, err)
@@ -337,7 +250,7 @@ func eventLoop() {
for i, n := range ids { for i, n := range ids {
if i >= len(idBtns) { if i >= len(idBtns) {
idBtns = append(idBtns, &Button{ idBtns = append(idBtns, &Button{
Size: unit.Sp(fontSize), Size: unit.Sp(16),
Label: n, Label: n,
Alignment: text.End, Alignment: text.End,
Color: black, Color: black,
@@ -351,119 +264,80 @@ func eventLoop() {
} }
confBtn := &Button{ confBtn := &Button{
Size: unit.Sp(fontSize), Size: unit.Sp(16),
Label: "configure", Label: "configure",
Alignment: text.Middle, Alignment: text.Middle,
Color: black, Color: black,
Background: gray, Background: gray,
} }
storeDirLabel := material.Label(th, unit.Sp(fontSize), "Store directory") storeDirLabel := &text.Label{Size: unit.Sp(16), Text: "Store directory"}
storeDirEd := &widget.Editor{SingleLine: true} storeDirEd := &text.Editor{Size: unit.Sp(16), Family: family, SingleLine: true}
storeDirEd.SetText(store.Dir) storeDirEd.SetText(store.Dir)
saveBtn := &Button{ saveBtn := &Button{
Size: unit.Sp(fontSize), Size: unit.Sp(16),
Label: "save", Label: "save",
Alignment: text.End, Alignment: text.End,
Color: black, Color: black,
Background: gray, Background: gray,
} }
backBtn := &Button{ backBtn := &Button{
Size: unit.Sp(fontSize), Size: unit.Sp(16),
Label: "back", Label: "back",
Alignment: text.End, Alignment: text.End,
Color: black, Color: black,
Background: gray, Background: gray,
} }
confirmLabel := material.Label(th, unit.Sp(fontSize), "Password exists. Overwrite?") confirmLabel := &text.Label{Size: unit.Sp(16), Text: "Password exists. Overwrite?"}
yesBtn := &Button{ yesBtn := &Button{
Size: unit.Sp(fontSize), Size: unit.Sp(16),
Label: "yes", Label: "yes",
Alignment: text.End, Alignment: text.End,
Color: black, Color: black,
Background: gray, Background: gray,
} }
promptLabel := material.Label(th, unit.Sp(fontSize), "passphrase") promptLabel := &text.Label{Size: unit.Sp(16), Text: "passphrase"}
promptEd := &widget.Editor{SingleLine: true, Submit: true} promptEd := &text.Editor{Size: unit.Sp(16), Family: family, SingleLine: true, Submit: true}
okBtn := &Button{ okBtn := &Button{
Size: unit.Sp(fontSize), Size: unit.Sp(16),
Label: "ok", Label: "ok",
Alignment: text.End, Alignment: text.End,
Color: black, Color: black,
Background: gray, Background: gray,
} }
plusBtn := &Button{ plusBtn := &Button{
Size: unit.Sp(fontSize), Size: unit.Sp(16),
Label: "+", Label: "+",
Alignment: text.Middle, Alignment: text.Middle,
Color: black, Color: black,
Background: gray, Background: gray,
} }
xBtn := &Button{
Size: unit.Sp(fontSize),
Label: "X",
Alignment: text.Middle,
Color: black,
Background: gray,
}
insertLabel := material.Label(th, unit.Sp(fontSize), "Insert") insertLabel := &text.Label{Size: unit.Sp(16), Text: "Insert"}
passnameLabel := material.Label(th, unit.Sp(fontSize), "password name:") passnameLabel := &text.Label{Size: unit.Sp(16), Text: "password name:"}
passnameEd := &widget.Editor{SingleLine: true} passnameEd := &text.Editor{Size: unit.Sp(16), Family: family, SingleLine: true, Submit: true}
passvalLabel := material.Label(th, unit.Sp(fontSize), "password value:") passvalLabel := &text.Label{Size: unit.Sp(16), Text: "password value:"}
passvalEd := &widget.Editor{SingleLine: true, Submit: true} passvalEd := &text.Editor{Size: unit.Sp(16), Family: family, SingleLine: true, Submit: true}
noidLabel := material.Label(th, unit.Sp(fontSize), noidLabelText) noidLabel := &text.Label{Size: unit.Sp(16), Text: "No GPG ids available. Please create a private key"}
idLabel := material.Label(th, unit.Sp(fontSize), "Select ID") idLabel := &text.Label{Size: unit.Sp(16), Text: "Select ID"}
// timing variables used for the "copied to clipboard" animation
// (seconds relative to overlayStart)
fade1a, fade1b := 1.5, 2.0
start2 := float64(Config.ClearDelay)
fade2a, end := start2+1.5, start2+2.0
anim := &time.Ticker{} anim := &time.Ticker{}
var animDone chan struct{}
animating := false animating := false
animOn := func() { animOn := func() {
log(Info, "animOn()") log(Info, "animOn()")
anim = time.NewTicker(time.Second / 90) anim = time.NewTicker(time.Second / 30)
animating = true animating = true
w.Invalidate() w.Invalidate()
// The event loop blocks in w.Event() between frames, so ticks it
// misses never trigger a redraw and the fade would freeze. Wake
// the window on each tick, but only while a fade is actually
// visible.
t := anim
animDone = make(chan struct{})
d := animDone
go func() {
for {
select {
case <-t.C:
x := time.Since(overlayStart).Seconds()
if (x >= fade1a && x < fade1b) || (x > fade2a && x < end) {
w.Invalidate()
}
case <-d:
return
}
}
}()
} }
animOff := func() { animOff := func() {
log(Info, "animOff()") log(Info, "animOff()")
anim.Stop() anim.Stop()
animating = false animating = false
if animDone != nil { // stops the wake-up goroutine started by animOn
close(animDone)
animDone = nil
}
} }
var listPage, idPage, insertPage, confirmPage, confPage, promptPage, page func(C) D var listPage, idPage, insertPage, confirmPage, confPage, promptPage, page func()
_ = idPage
prompt := func() []byte { prompt := func() []byte {
page = promptPage page = promptPage
@@ -472,42 +346,33 @@ func eventLoop() {
return <-passch return <-passch
} }
lpf1 := &layout.Flex{Axis: layout.Horizontal} listPage = func() {
listPage = func(gtx C) D { // timing variables used for animation
c2 := layout.Rigid(func(gtx C) D { fade1a, fade1b := 1.5, 2.0
c21 := layout.Flexed(1, func(gtx C) D { start2 := float64(Config.ClearDelay)
return material.Editor(th, FilterEd, "filter").Layout(gtx) fade2a, end := start2+1.5, start2+2.0
})
c22 := layout.Rigid(func(gtx C) D { c2 := flex.Flex(gtx, 1.0, func() {
return xBtn.Layout(gtx)
})
if xBtn.Clicked() {
FilterEd.SetText("")
lastFilter = ""
updateBtns()
}
return lpf1.Layout(gtx, c21, c22)
})
c3 := layout.Flexed(1.0, func(gtx C) D {
var ret D
mux.Lock() mux.Lock()
if lst.Dragging() {
key.HideInputOp{}.Add(gtx.Ops)
}
switch { switch {
case store.Empty: case store.Empty:
confBtn.Layout(gtx) confBtn.Layout(gtx, family)
if confBtn.Clicked() { if confBtn.Clicked() {
log(Info, "Configure") log(Info, "Configure")
w.Invalidate() w.Invalidate()
page = confPage page = confPage
} }
case store.Id == "": case store.Id == "":
idLabel.Layout(gtx) idLabel.Layout(gtx, family)
w.Invalidate() w.Invalidate()
page = idPage page = idPage
default: default:
ret = lst.Layout(gtx, len(passBtns), func(gtx C, i int) D { lst.Layout(gtx, len(passBtns), func(i int) {
btn := passBtns[i] btn := passBtns[i]
gtx.Constraints.Min.X = gtx.Constraints.Max.X btn.Layout(gtx, family)
ret := btn.Layout(gtx)
if btn.Clicked() { if btn.Clicked() {
log(Info, "Clicked ", btn.Label) log(Info, "Clicked ", btn.Label)
// don't block UI thread on decryption attempt // don't block UI thread on decryption attempt
@@ -536,13 +401,11 @@ func eventLoop() {
} }
}(pathnames[i]) }(pathnames[i])
} }
return ret
}) })
} }
mux.Unlock() mux.Unlock()
return ret
}) })
ret := flex.Layout(gtx, c1, c2, c3) flex.Layout(gtx, c1, c2)
x := time.Since(overlayStart).Seconds() x := time.Since(overlayStart).Seconds()
if x >= fade1b && x < start2 && animating { if x >= fade1b && x < start2 && animating {
animOff() animOff()
@@ -580,9 +443,10 @@ func eventLoop() {
overlay.Background = darkgray overlay.Background = darkgray
} }
gtx.Constraints = margincs gtx.Constraints = margincs
layout.SE.Layout(gtx, func(gtx C) D { al := layout.Align(layout.SE)
gtx.Constraints.Min.X = gtx.Constraints.Max.X al.Layout(gtx, func() {
return overlay.Layout(gtx) gtx.Constraints.Width.Min = gtx.Constraints.Width.Max
overlay.Layout(gtx, family)
}) })
} }
if x > start2 && x < fade2a { if x > start2 && x < fade2a {
@@ -591,80 +455,25 @@ func eventLoop() {
if animating && x > end { if animating && x > end {
animOff() animOff()
} }
// material.Editor.Layout (above) already consumes the editor's
// input events, so we detect a filter change by comparing the
// current text against the previous frame's.
if t := FilterEd.Text(); t != lastFilter {
lastFilter = t
updateBtns()
}
return ret
} }
updateBtn := &Button{ idPage = func() {
Size: unit.Sp(fontSize),
Label: "Update",
Alignment: text.Middle,
Color: black,
Background: gray,
}
idEd := &widget.Editor{SingleLine: true, Submit: true}
idSubmitBtn := &Button{
Size: unit.Sp(fontSize),
Label: "Submit",
Alignment: text.Middle,
Color: black,
Background: gray,
}
idPage = func(gtx C) D {
if !animating { if !animating {
animOn() animOn()
} }
c2 := layout.Rigid(func(gtx C) D { c2 := flex.Rigid(gtx, func() {
return idLabel.Layout(gtx) idLabel.Layout(gtx, family)
}) })
var c3 layout.FlexChild //if len(idBtns) == 0 {
var c4 layout.FlexChild
var c5 layout.FlexChild
var c6 layout.FlexChild
var c7 layout.FlexChild
if len(idBtns) == 0 {
c3 = layout.Rigid(func(gtx C) D {
return updateBtn.Layout(gtx)
})
if updateBtn.Clicked() {
updateIdBtns() updateIdBtns()
w.Invalidate() //}
} c3 := flex.Rigid(gtx, func() {
c4 = layout.Rigid(func(gtx C) D { if len(idBtns) == 0 { // still zero after update
return material.Editor(th, idEd, "id").Layout(gtx) noidLabel.Layout(gtx, family)
})
c5 = layout.Rigid(func(gtx C) D {
return idSubmitBtn.Layout(gtx)
})
if idSubmitBtn.Clicked() {
store.Id = idEd.Text()
// Persist the ID so it survives a restart (the manual entry
// path has no keyring to re-derive it from).
store.SetID(store.Id)
page = listPage
}
c6 = layout.Rigid(func(gtx C) D {
return noidLabel.Layout(gtx)
})
} else { } else {
c3 = layout.Rigid(func(gtx C) D { return D{} })
c4 = layout.Rigid(func(gtx C) D { return D{} })
c5 = layout.Rigid(func(gtx C) D { return D{} })
c6 = layout.Rigid(func(gtx C) D { return D{} })
}
c7 = layout.Rigid(func(gtx C) D {
var ret D
if len(idBtns) > 0 { // still zero after update
for i := 0; i < len(idBtns); i++ { for i := 0; i < len(idBtns); i++ {
ret = lst.Layout(gtx, len(idBtns), func(gtx C, i int) D { lst.Layout(gtx, len(idBtns), func(i int) {
return idBtns[i].Layout(gtx) idBtns[i].Layout(gtx, family)
}) })
} }
for _, btn := range idBtns { for _, btn := range idBtns {
@@ -677,33 +486,23 @@ func eventLoop() {
} }
} }
} }
return ret
}) })
if ev, ok := idEd.Update(gtx); ok { flex.Layout(gtx, c1, c2, c3)
if _, isSubmit := ev.(widget.SubmitEvent); isSubmit {
log(Info, "Submit")
store.Id = idEd.Text()
store.SetID(store.Id)
w.Invalidate()
page = listPage
}
}
return flex.Layout(gtx, c1, c2, c3, c4, c5, c6, c7)
} }
var insName, insValue string var insName, insValue string
genBtn := &SelButton{SelColor: gray} genBtn := &SelButton{SelColor: gray}
genBtn.Button = Button{Size: unit.Sp(fontSize), Label: "generate", Color: black} genBtn.Button = Button{Size: unit.Sp(16), Label: "generate"}
symBtn := &SelButton{SelColor: gray} symBtn := &SelButton{SelColor: gray}
numBtn := &SelButton{SelColor: gray} numBtn := &SelButton{SelColor: gray}
symBtn.Button = Button{Size: unit.Sp(fontSize), Label: "@", Color: black} symBtn.Button = Button{Size: unit.Sp(16), Label: "@"}
numBtn.Button = Button{Size: unit.Sp(fontSize), Label: "#", Color: black} numBtn.Button = Button{Size: unit.Sp(16), Label: "#"}
symBtn.Select() symBtn.Select()
numBtn.Select() numBtn.Select()
lenEd := &widget.Editor{SingleLine: true, Alignment: text.End} lenEd := &text.Editor{Size: unit.Sp(16), Family: family, SingleLine: true, Alignment: text.End}
lenEd.SetText("15") lenEd.SetText("15")
lBtn := &Button{Size: unit.Sp(fontSize), Label: "<", Color: black, Background: gray} lBtn := &Button{Size: unit.Sp(16), Label: "<", Background: gray}
rBtn := &Button{Size: unit.Sp(fontSize), Label: ">", Color: black, Background: gray} rBtn := &Button{Size: unit.Sp(16), Label: ">", Background: gray}
updatePw := func() { updatePw := func() {
if !genBtn.Selected { if !genBtn.Selected {
@@ -726,40 +525,41 @@ func eventLoop() {
passvalEd.SetText(string(pw)) passvalEd.SetText(string(pw))
} }
insertPage = func(gtx C) D { insertPage = func() {
c2 := layout.Rigid(func(gtx C) D { return insertLabel.Layout(gtx) }) c2 := flex.Rigid(gtx, func() { insertLabel.Layout(gtx, family) })
c3 := layout.Rigid(func(gtx C) D { return passnameLabel.Layout(gtx) }) c3 := flex.Rigid(gtx, func() { passnameLabel.Layout(gtx, family) })
c4 := layout.Rigid(func(gtx C) D { return material.Editor(th, passnameEd, "name").Layout(gtx) }) c4 := flex.Rigid(gtx, func() { passnameEd.Layout(gtx) })
c5 := layout.Rigid(func(gtx C) D { return passvalLabel.Layout(gtx) }) c5 := flex.Rigid(gtx, func() { passvalLabel.Layout(gtx, family) })
c6 := layout.Rigid(func(gtx C) D { return material.Editor(th, passvalEd, "password").Layout(gtx) }) c6 := flex.Rigid(gtx, func() { passvalEd.Layout(gtx) })
btnflx := &layout.Flex{Axis: layout.Horizontal} btnflx := &layout.Flex{Axis: layout.Horizontal}
c7 := layout.Rigid(func(gtx C) D { al := layout.Align(layout.E)
bc1 := layout.Rigid(func(gtx C) D { return lBtn.Layout(gtx) }) c7 := flex.Rigid(gtx, func() {
bc2 := layout.Rigid(func(gtx C) D { bc1 := btnflx.Rigid(gtx, func() { lBtn.Layout(gtx, family) })
gtx.Constraints.Min.X = 60 bc2 := btnflx.Rigid(gtx, func() {
return material.Editor(th, lenEd, "len").Layout(gtx) gtx.Constraints.Width.Min = 60
lenEd.Layout(gtx)
}) })
bc3 := layout.Rigid(func(gtx C) D { return rBtn.Layout(gtx) }) bc3 := btnflx.Rigid(gtx, func() { rBtn.Layout(gtx, family) })
bc4 := layout.Rigid(func(gtx C) D { return symBtn.Layout(gtx) }) bc4 := btnflx.Rigid(gtx, func() { symBtn.Layout(gtx, family) })
bc5 := layout.Rigid(func(gtx C) D { return numBtn.Layout(gtx) }) bc5 := btnflx.Rigid(gtx, func() { numBtn.Layout(gtx, family) })
bc6 := layout.Rigid(func(gtx C) D { return genBtn.Layout(gtx) }) bc6 := btnflx.Rigid(gtx, func() { genBtn.Layout(gtx, family) })
return layout.E.Layout(gtx, func(gtx C) D { al.Layout(gtx, func() {
return btnflx.Layout(gtx, bc1, bc2, bc3, bc4, bc5, bc6) btnflx.Layout(gtx, bc1, bc2, bc3, bc4, bc5, bc6)
}) })
}) })
c8 := layout.Rigid(func(gtx C) D { c8 := flex.Rigid(gtx, func() {
bc1 := layout.Rigid(func(gtx C) D { return backBtn.Layout(gtx) }) bc1 := btnflx.Rigid(gtx, func() { backBtn.Layout(gtx, family) })
bc2 := layout.Rigid(func(gtx C) D { return saveBtn.Layout(gtx) }) bc2 := btnflx.Rigid(gtx, func() { saveBtn.Layout(gtx, family) })
return layout.E.Layout(gtx, func(gtx C) D { al.Layout(gtx, func() {
return btnflx.Layout(gtx, bc1, bc2) btnflx.Layout(gtx, bc1, bc2)
}) })
}) })
ret := flex.Layout(gtx, c1, c2, c3, c4, c5, c6, c7, c8) flex.Layout(gtx, c1, c2, c3, c4, c5, c6, c7, c8)
if lBtn.Clicked() { if lBtn.Clicked() {
l, _ := strconv.Atoi(lenEd.Text()) l, _ := strconv.Atoi(lenEd.Text())
@@ -802,34 +602,28 @@ func eventLoop() {
log(Info, "Password exists") log(Info, "Password exists")
page = confirmPage page = confirmPage
w.Invalidate() w.Invalidate()
return ret return
} }
} }
//Do not block the UI thread. store.Insert(passnameEd.Text(), passvalEd.Text())
go func() {
err := store.Insert(passnameEd.Text(), passvalEd.Text())
if err != nil {
page = idPage
} }
}()
}
return ret
} }
confirmPage = func(gtx C) D { confirmPage = func() {
c2 := layout.Rigid(func(gtx C) D { c2 := flex.Rigid(gtx, func() {
return confirmLabel.Layout(gtx) confirmLabel.Layout(gtx, family)
}) })
al := layout.Align(layout.E)
btnflx := &layout.Flex{Axis: layout.Horizontal} btnflx := &layout.Flex{Axis: layout.Horizontal}
c3 := layout.Rigid(func(gtx C) D { c3 := flex.Rigid(gtx, func() {
bc1 := layout.Rigid(func(gtx C) D { return backBtn.Layout(gtx) }) bc1 := btnflx.Rigid(gtx, func() { backBtn.Layout(gtx, family) })
bc2 := layout.Rigid(func(gtx C) D { return yesBtn.Layout(gtx) }) bc2 := btnflx.Rigid(gtx, func() { yesBtn.Layout(gtx, family) })
return layout.E.Layout(gtx, func(gtx C) D { al.Layout(gtx, func() {
return btnflx.Layout(gtx, bc1, bc2) btnflx.Layout(gtx, bc1, bc2)
}) })
}) })
ret := flex.Layout(gtx, c1, c2, c3) flex.Layout(gtx, c1, c2, c3)
if backBtn.Clicked() { if backBtn.Clicked() {
w.Invalidate() w.Invalidate()
@@ -838,33 +632,28 @@ func eventLoop() {
if yesBtn.Clicked() { if yesBtn.Clicked() {
w.Invalidate() w.Invalidate()
page = listPage page = listPage
go func() { store.Insert(insName, insValue)
err := store.Insert(insName, insValue)
if err != nil {
page = idPage
} }
}()
}
return ret
} }
confPage = func(gtx C) D { confPage = func() {
c2 := layout.Rigid(func(gtx C) D { return storeDirLabel.Layout(gtx) }) c2 := flex.Rigid(gtx, func() { storeDirLabel.Layout(gtx, family) })
c3 := layout.Rigid(func(gtx C) D { return material.Editor(th, storeDirEd, "directory").Layout(gtx) }) c3 := flex.Rigid(gtx, func() { storeDirEd.Layout(gtx) })
c4 := layout.Rigid(func(gtx C) D { al := layout.Align(layout.E)
c4 := flex.Rigid(gtx, func() {
btnflx := &layout.Flex{Axis: layout.Horizontal} btnflx := &layout.Flex{Axis: layout.Horizontal}
bc1 := layout.Rigid(func(gtx C) D { bc1 := btnflx.Rigid(gtx, func() {
return backBtn.Layout(gtx) backBtn.Layout(gtx, family)
}) })
bc2 := layout.Rigid(func(gtx C) D { bc2 := btnflx.Rigid(gtx, func() {
return saveBtn.Layout(gtx) saveBtn.Layout(gtx, family)
}) })
return layout.E.Layout(gtx, func(gtx C) D { al.Layout(gtx, func() {
return btnflx.Layout(gtx, bc1, bc2) btnflx.Layout(gtx, bc1, bc2)
}) })
}) })
ret := flex.Layout(gtx, c1, c2, c3, c4) flex.Layout(gtx, c1, c2, c3, c4)
if backBtn.Clicked() { if backBtn.Clicked() {
log(Info, "Back") log(Info, "Back")
@@ -886,32 +675,33 @@ func eventLoop() {
w.Invalidate() w.Invalidate()
page = listPage page = listPage
} }
return ret
} }
promptPage = func(gtx C) D { promptPage = func() {
submit := false submit := false
if ev, ok := promptEd.Update(gtx); ok { for e, ok := promptEd.Event(gtx); ok; e, ok = promptEd.Event(gtx) {
if _, isSubmit := ev.(widget.SubmitEvent); isSubmit { switch e.(type) {
case text.SubmitEvent:
log(Info, "Submit") log(Info, "Submit")
submit = true submit = true
} }
} }
c2 := layout.Rigid(func(gtx C) D { return promptLabel.Layout(gtx) }) c2 := flex.Rigid(gtx, func() { promptLabel.Layout(gtx, family) })
c3 := layout.Rigid(func(gtx C) D { return material.Editor(th, promptEd, "password").Layout(gtx) }) c3 := flex.Rigid(gtx, func() { promptEd.Layout(gtx) })
c4 := layout.Rigid(func(gtx C) D { c4 := flex.Rigid(gtx, func() {
al := layout.Align(layout.E)
btnflx := &layout.Flex{Axis: layout.Horizontal} btnflx := &layout.Flex{Axis: layout.Horizontal}
bc1 := layout.Rigid(func(gtx C) D { bc1 := btnflx.Rigid(gtx, func() {
return backBtn.Layout(gtx) backBtn.Layout(gtx, family)
}) })
bc2 := layout.Rigid(func(gtx C) D { bc2 := btnflx.Rigid(gtx, func() {
return okBtn.Layout(gtx) okBtn.Layout(gtx, family)
}) })
return layout.E.Layout(gtx, func(gtx C) D { al.Layout(gtx, func() {
return btnflx.Layout(gtx, bc1, bc2) btnflx.Layout(gtx, bc1, bc2)
}) })
}) })
ret := flex.Layout(gtx, c1, c2, c3, c4) flex.Layout(gtx, c1, c2, c3, c4)
if submit || okBtn.Clicked() { if submit || okBtn.Clicked() {
log(Info, "Ok") log(Info, "Ok")
@@ -929,7 +719,6 @@ func eventLoop() {
w.Invalidate() w.Invalidate()
page = listPage page = listPage
} }
return ret
} }
page = listPage page = listPage
@@ -937,52 +726,51 @@ func eventLoop() {
ms := &runtime.MemStats{} ms := &runtime.MemStats{}
x := 0 x := 0
var mallocs uint64 var mallocs uint64
var idsInit bool
for { for {
// Window.Event and FrameEvent.Frame must be called from the same
// goroutine; drain the auxiliary channels non-blocking instead of
// bridging the window events through a channel.
select { select {
case <-updated: case <-updated:
log(Info, "UPDATE") log(Info, "UPDATE")
updateBtns() updateBtns()
w.Invalidate() w.Invalidate()
default:
}
select {
case <-anim.C: case <-anim.C:
w.Invalidate() w.Invalidate()
default: case e := <-w.Events():
}
switch e := w.Event().(type) {
case app.DestroyEvent:
os.Exit(0)
case app.FrameEvent:
x++ x++
if !idsInit { // the app is running; refresh the ID list if x == 100 {
idsInit = true runtime.ReadMemStats(ms)
go updateIdBtns() mallocs = ms.Mallocs
} }
// NewContext resets ops and adjusts for e.Insets. switch e := e.(type) {
gtx := app.NewContext(&ops, e) case app.DestroyEvent:
return
case app.UpdateEvent:
fmt.Printf("UpdateEvent\n")
gtx.Reset(&e.Config, e.Size)
margin.Layout(gtx, func(gtx C) D { sysinset.Top = e.Insets.Top
sysinset.Bottom = e.Insets.Bottom
sysinset.Left = e.Insets.Left
sysinset.Right = e.Insets.Right
sysinset.Layout(gtx, func() {
margin.Layout(gtx, func() {
margincs = gtx.Constraints margincs = gtx.Constraints
c1 = layout.Rigid(func(gtx C) D { c1 = flex.Rigid(gtx, func() {
ct2 := layout.Rigid(func(gtx C) D { ct2 := titleflex.Rigid(gtx, func() {
return plusBtn.Layout(gtx) plusBtn.Layout(gtx, family)
}) })
ct3 := layout.Rigid(func(gtx C) D { ct3 := titleflex.Rigid(gtx, func() {
return dotsBtn.Layout(gtx) dotsBtn.Layout(gtx, family)
}) })
ct1 := layout.Flexed(1.0, func(gtx C) D { ct1 := titleflex.Flex(gtx, 1.0, func() {
gtx.Constraints.Min.X = gtx.Constraints.Max.X gtx.Constraints.Width.Min = gtx.Constraints.Width.Max
return title.Layout(gtx) title.Layout(gtx, family)
}) })
return titleflex.Layout(gtx, ct1, ct2, ct3) titleflex.Layout(gtx, ct1, ct2, ct3)
}) })
return page(gtx) page()
})
}) })
if dotsBtn.Clicked() { if dotsBtn.Clicked() {
@@ -996,9 +784,7 @@ func eventLoop() {
insName, insValue = "", "" insName, insValue = "", ""
page = insertPage page = insertPage
} }
e.Frame(&ops) w.Update(gtx.Ops)
default:
handleEvent(e)
} }
if x == 100 { if x == 100 {
x = 0 x = 0
@@ -1007,3 +793,4 @@ func eventLoop() {
} }
} }
} }
}
+77 -66
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
ins := layout.UniformInset(unit.Dp(1)) for _, ev := range b.Click.Events(gtx) {
return ins.Layout(gtx, func(gtx C) D { if ev.Type == gesture.TypeClick {
st := layout.Stack{}
c2 := layout.Stacked(func(gtx C) D {
l := material.Label(th, b.Size, b.Label)
l.Color = b.Color
ins := layout.UniformInset(unit.Dp(4))
ret := ins.Layout(gtx, func(gtx C) D {
return l.Layout(gtx)
})
// Register the click handler for the whole button area, not
// 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)
stk.Pop()
for {
ev, ok := b.Click.Update(gtx.Source)
if !ok {
break
}
if ev.Kind == gesture.KindClick {
b.clicked = true b.clicked = true
} }
} }
return ret ins := layout.UniformInset(unit.Dp(1))
ins.Layout(gtx, func() {
st := layout.Stack{}
c2 := st.Rigid(gtx, func() {
l := text.Label{
Size: b.Size,
Text: b.Label,
Alignment: b.Alignment,
}
ins := layout.UniformInset(unit.Dp(4))
//paint.ColorOp{Color: b.Color}.Add(ops)
ins.Layout(gtx, func() {
l.Layout(gtx, family)
}) })
c1 := layout.Expanded(func(gtx C) D { pointer.RectAreaOp{image.Rect(0, 0, gtx.Dimensions.Size.X, gtx.Dimensions.Size.Y)}.Add(gtx.Ops)
gtx.Constraints.Min.X = mwidth b.Click.Add(gtx.Ops)
return layoutRRect(b.Background, gtx)
}) })
return st.Layout(gtx, c1, c2) c1 := st.Expand(gtx, func() {
layoutRRect(b.Background, gtx)
})
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=
+4 -95
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 (
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 //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
} }
-1
View File
@@ -1,4 +1,3 @@
//go:build darwin
//+build darwin //+build darwin
package passgo package passgo
-1
View File
@@ -1,4 +1,3 @@
//go:build !android && linux
//+build !android,linux //+build !android,linux
package passgo package passgo
-1
View File
@@ -1,4 +1,3 @@
//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 ==="