mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-26 00:06:02 +00:00
build: vendor pinned SDL3 bridge sources
This commit is contained in:
1 parent
5115b4416a
commit
6d6b6726fa
42 files changed
+1111
-27
No files matched your search
@@ -0,0 +1,765 @@
|
||||
package com.example.dsedge;
|
||||
|
||||
import android.app.PendingIntent;
|
||||
import android.content.Intent;
|
||||
import android.hardware.usb.UsbInterface;
|
||||
import android.os.Build;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Typeface;
|
||||
import android.graphics.drawable.GradientDrawable;
|
||||
import android.content.res.ColorStateList;
|
||||
import android.util.TypedValue;
|
||||
import android.hardware.usb.UsbDevice;
|
||||
import android.hardware.usb.UsbManager;
|
||||
import android.media.AudioDeviceInfo;
|
||||
import android.media.AudioManager;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.view.Gravity;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.AdapterView;
|
||||
import android.widget.ArrayAdapter;
|
||||
import android.widget.Button;
|
||||
import android.widget.CheckBox;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.ScrollView;
|
||||
import android.widget.SeekBar;
|
||||
import android.widget.Spinner;
|
||||
import android.widget.TextView;
|
||||
|
||||
import org.libsdl.app.SDLControllerManager;
|
||||
|
||||
/**
|
||||
* The bridge's screen: live controller test and settings. SDL3 itself runs in the background service
|
||||
* (SdlEngine), so this screen can open and close at any time without affecting the controllers. (Fallback, if
|
||||
* SDL3 can't run in the background with this build: opening this screen starts SDL3 in a hidden screen behind it.)
|
||||
*/
|
||||
public class BridgeActivity extends android.app.Activity implements NativeBridge.Listener {
|
||||
private interface IntSink { void set(int v); }
|
||||
|
||||
private final Handler ui = new Handler(Looper.getMainLooper());
|
||||
private TextView statusView, summaryView, usbView;
|
||||
private Button updateButton;
|
||||
private ControllerView pad;
|
||||
private String updateUrl;
|
||||
private long lastSummary;
|
||||
private static final float RAD_TO_DEG = 57.29578f;
|
||||
private static final int CALIB_SAMPLES = 180; // ~0.7s at 4ms/frame
|
||||
private volatile int calibCount = -1; // -1 = not calibrating
|
||||
private final float[] calibSum = new float[3];
|
||||
private int calibPlayer = 0;
|
||||
private int uiPlayer = 0;
|
||||
private LinearLayout playerBox;
|
||||
private Button[] playerTabs;
|
||||
private TextView gyroCalibView;
|
||||
private boolean pendingBubble; // user asked for the bubble; waiting for overlay permission
|
||||
private TextView audioView;
|
||||
|
||||
|
||||
// ---- design tokens ----
|
||||
private static final int BG = 0xFF0E1116, CARD = 0xFF171C24, CARD2 = 0xFF222A35,
|
||||
ACCENT = 0xFF4FC3F7, TEXT = 0xFFECEFF1, SUB = 0xFF8A97A7,
|
||||
OKC = 0xFF34D399, WARNC = 0xFFF59E0B, BADC = 0xFFEF4444;
|
||||
private TextView statusPill;
|
||||
|
||||
private int dp(int v) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, v, getResources().getDisplayMetrics()); }
|
||||
|
||||
/** True while the bridge screen is open. */
|
||||
static volatile boolean running;
|
||||
|
||||
@Override protected void onCreate(Bundle state) {
|
||||
NativeBridge.appContext = getApplicationContext();
|
||||
running = true;
|
||||
super.onCreate(state);
|
||||
Settings.init(this);
|
||||
SdlEngine.start(this);
|
||||
// Android 13+: the status bar icon (the bridge's notification) needs this permission.
|
||||
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS)
|
||||
!= android.content.pm.PackageManager.PERMISSION_GRANTED) {
|
||||
requestPermissions(new String[] { android.Manifest.permission.POST_NOTIFICATIONS }, 1);
|
||||
}
|
||||
UpdateChecker.BuildInfo info = UpdateChecker.readBuildInfo(this);
|
||||
|
||||
LinearLayout root = new LinearLayout(this);
|
||||
root.setOrientation(LinearLayout.VERTICAL);
|
||||
root.setBackgroundColor(BG);
|
||||
root.setPadding(dp(14), dp(18), dp(14), dp(18));
|
||||
|
||||
// ---- header bar ----
|
||||
LinearLayout bar = new LinearLayout(this);
|
||||
bar.setOrientation(LinearLayout.HORIZONTAL);
|
||||
bar.setGravity(Gravity.CENTER_VERTICAL);
|
||||
LinearLayout titleCol = new LinearLayout(this);
|
||||
titleCol.setOrientation(LinearLayout.VERTICAL);
|
||||
TextView appTitle = new TextView(this);
|
||||
appTitle.setText("SDL3 Bridge");
|
||||
appTitle.setTextColor(TEXT);
|
||||
appTitle.setTextSize(21f);
|
||||
appTitle.setTypeface(Typeface.DEFAULT_BOLD);
|
||||
TextView appSub = new TextView(this);
|
||||
appSub.setText(info.tag + " · SDL " + info.sdl);
|
||||
appSub.setTextColor(SUB);
|
||||
appSub.setTextSize(11f);
|
||||
titleCol.addView(appTitle);
|
||||
titleCol.addView(appSub);
|
||||
bar.addView(titleCol, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f));
|
||||
statusPill = new TextView(this);
|
||||
statusPill.setText("Starting");
|
||||
statusPill.setTextColor(0xFF0E1116);
|
||||
statusPill.setTextSize(11f);
|
||||
statusPill.setTypeface(Typeface.DEFAULT_BOLD);
|
||||
statusPill.setPadding(dp(12), dp(6), dp(12), dp(6));
|
||||
statusPill.setBackground(pill(SUB));
|
||||
bar.addView(statusPill);
|
||||
root.addView(bar);
|
||||
spacer(root, 14);
|
||||
|
||||
// ---- controller test card ----
|
||||
LinearLayout test = card(root);
|
||||
statusView = sub(NativeBridge.lastStatus, 12f);
|
||||
usbView = sub("USB: checking...", 11f);
|
||||
pad = new ControllerView(this);
|
||||
test.addView(statusView);
|
||||
LinearLayout padWrap = new LinearLayout(this);
|
||||
padWrap.setBackground(rounded(0xFF0B0E13, dp(10)));
|
||||
padWrap.setPadding(dp(4), dp(4), dp(4), dp(4));
|
||||
padWrap.addView(pad, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
|
||||
LinearLayout.LayoutParams pw = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||
pw.topMargin = dp(8); pw.bottomMargin = dp(8);
|
||||
test.addView(padWrap, pw);
|
||||
summaryView = sub("Press every button and move everything to test it.", 12f);
|
||||
test.addView(summaryView);
|
||||
test.addView(usbView);
|
||||
LinearLayout row = new LinearLayout(this);
|
||||
row.setOrientation(LinearLayout.HORIZONTAL);
|
||||
LinearLayout.LayoutParams rp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||
rp.topMargin = dp(8);
|
||||
row.addView(primaryButton("Test rumble", v -> rumbleTest()), weight());
|
||||
gap(row);
|
||||
row.addView(button("Reset", v -> { pad.resetTested(); summaryView.setText(pad.summary()); }), weight());
|
||||
gap(row);
|
||||
updateButton = button("Update", v -> { if (updateUrl != null) openUrl(updateUrl); else checkUpdate(); });
|
||||
row.addView(updateButton, weight());
|
||||
test.addView(row, rp);
|
||||
|
||||
// ---- per-player settings ----
|
||||
LinearLayout playerCard = card(root);
|
||||
cardTitle(playerCard, "Player settings");
|
||||
LinearLayout tabs = new LinearLayout(this);
|
||||
tabs.setOrientation(LinearLayout.HORIZONTAL);
|
||||
tabs.setBackground(rounded(CARD2, dp(10)));
|
||||
tabs.setPadding(dp(4), dp(4), dp(4), dp(4));
|
||||
playerTabs = new Button[Settings.PLAYERS];
|
||||
for (int i = 0; i < Settings.PLAYERS; i++) {
|
||||
final int pi = i;
|
||||
Button t = new Button(this);
|
||||
t.setText("P" + (i + 1));
|
||||
t.setAllCaps(false);
|
||||
t.setTextSize(13f);
|
||||
t.setOnClickListener(v -> showPlayer(pi));
|
||||
playerTabs[i] = t;
|
||||
tabs.addView(t, weight());
|
||||
}
|
||||
playerCard.addView(tabs);
|
||||
playerBox = new LinearLayout(this);
|
||||
playerBox.setOrientation(LinearLayout.VERTICAL);
|
||||
LinearLayout.LayoutParams pbp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||
pbp.topMargin = dp(10);
|
||||
playerCard.addView(playerBox, pbp);
|
||||
showPlayer(0);
|
||||
|
||||
// ---- SDL3 driver ----
|
||||
LinearLayout drv = card(root);
|
||||
cardTitle(drv, "SDL3 driver");
|
||||
addSpinner(drv, "Controller source", new String[] {
|
||||
"Auto: any controller (SDL3 USB driver when plugged in, else Android/Bluetooth)",
|
||||
"Forced: only SDL3's USB driver (USB cable only)"
|
||||
}, Settings.forceUsb ? 1 : 0, v -> {
|
||||
Settings.forceUsb = v == 1;
|
||||
Settings.save();
|
||||
NativeBridge.applyForce();
|
||||
});
|
||||
drv.addView(primaryButton("Force SDL3 USB driver", v -> forceUsbDriver()));
|
||||
drv.addView(sub("Plug the controller in with USB-C, tap the button and allow USB access "
|
||||
+ "(choose 'always' to skip this next time). Works for any SDL3-supported controller.", 11f));
|
||||
|
||||
// ---- Controller mode ----
|
||||
LinearLayout mode = card(root);
|
||||
cardTitle(mode, "Controller mode");
|
||||
addSpinner(mode, "Present controller as", Settings.PRESENT_NAMES, Settings.presentAs, v -> {
|
||||
Settings.presentAs = v;
|
||||
if (!Settings.isHookup()) Settings.lastPresentAs = v;
|
||||
Settings.save();
|
||||
NativeBridge.applyHookup();
|
||||
BridgeService.refreshBubble();
|
||||
});
|
||||
mode.addView(sub("Steam Deck: the controller is DroidDeck's Deck pad (default, full features). "
|
||||
+ "DualSense / DualShock 4: Steam sees a NATIVE Sony controller (hidraw) with gyro, touchpad and back buttons. "
|
||||
+ "Steam Native Hook-up: every USB controller is handed to Steam as itself (its real name and ids), "
|
||||
+ "so Steam's own driver gives it all its features, like on a PC; Bluetooth controllers stay a Deck pad. "
|
||||
+ "Give Steam a few seconds, or restart the session, after changing.", 11f));
|
||||
addSpinner(mode, "Poll rate", Settings.RATE_NAMES, rateIndex(), v -> {
|
||||
Settings.pollMs = Settings.RATE_MS[v];
|
||||
Settings.save();
|
||||
NativeBridge.applyRate();
|
||||
});
|
||||
mode.addView(sub("Higher rate = lower gyro/trackpad latency, a little more CPU and battery. No accuracy is lost either way.", 11f));
|
||||
|
||||
// ---- Floating bubble ----
|
||||
LinearLayout bub = card(root);
|
||||
cardTitle(bub, "Floating bubble");
|
||||
addCheck(bub, "Show floating bubble over other apps", Settings.bubble, on -> {
|
||||
if (on) {
|
||||
if (!android.provider.Settings.canDrawOverlays(this)) {
|
||||
pendingBubble = true;
|
||||
try {
|
||||
startActivity(new Intent(android.provider.Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
|
||||
Uri.parse("package:" + getPackageName())));
|
||||
} catch (RuntimeException ignored) { }
|
||||
return;
|
||||
}
|
||||
Settings.bubble = true;
|
||||
startService(new Intent(this, BridgeService.class).setAction("BUBBLE").putExtra("on", true));
|
||||
} else {
|
||||
Settings.bubble = false;
|
||||
startService(new Intent(this, BridgeService.class).setAction("BUBBLE").putExtra("on", false));
|
||||
}
|
||||
});
|
||||
bub.addView(sub("A draggable chat-head: tap toggles the SDL3 driver (green on / red off), hold 3s opens this app, "
|
||||
+ "drag to the bottom to remove. Needs the \"Draw over other apps\" permission.", 11f));
|
||||
|
||||
// ---- USB audio ----
|
||||
LinearLayout aud = card(root);
|
||||
cardTitle(aud, "USB audio");
|
||||
audioView = sub(audioInfo(), 12f);
|
||||
aud.addView(audioView);
|
||||
aud.addView(button("Developer options → USB audio routing", v -> openDevSettings()));
|
||||
aud.addView(sub("When the controller is plugged in via USB-C, Android may grab it as an audio device and route sound to it. "
|
||||
+ "This opens Developer options — turn ON \"Disable USB audio routing\" to keep audio on the phone. "
|
||||
+ "(If Developer options aren't enabled, tap Build number 7 times in About phone first.)", 11f));
|
||||
|
||||
root.addView(sub("Orange = held now, green = worked at least once. Leave this app open once, then switch to DroidDeck.", 11f));
|
||||
|
||||
ScrollView scroll = new ScrollView(this);
|
||||
scroll.setBackgroundColor(BG);
|
||||
scroll.addView(root);
|
||||
addContentView(scroll, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
|
||||
|
||||
NativeBridge.listeners.add(this);
|
||||
try {
|
||||
startForegroundService(new Intent(this, BridgeService.class));
|
||||
} catch (RuntimeException ignored) { }
|
||||
NativeBridge.applyDriver();
|
||||
NativeBridge.applyRate();
|
||||
NativeBridge.applyOutput();
|
||||
checkUpdate();
|
||||
ui.post(usbRefresh);
|
||||
}
|
||||
|
||||
private void showPlayer(int p) {
|
||||
uiPlayer = p;
|
||||
for (int i = 0; i < playerTabs.length; i++) {
|
||||
boolean sel = i == p;
|
||||
playerTabs[i].setBackground(rounded(sel ? ACCENT : 0x00000000, dp(8)));
|
||||
playerTabs[i].setTextColor(sel ? 0xFF0E1116 : SUB);
|
||||
playerTabs[i].setTypeface(sel ? Typeface.DEFAULT_BOLD : Typeface.DEFAULT);
|
||||
}
|
||||
playerBox.removeAllViews();
|
||||
buildPlayerSection(playerBox, p);
|
||||
}
|
||||
|
||||
private void buildPlayerSection(LinearLayout box, final int p) {
|
||||
subhead(box, "Gyro");
|
||||
addSlider(box, "Gyro speed % (100 = 1:1)", 800, Settings.gyroGain[p], v -> Settings.gyroGain[p] = Math.max(1, v));
|
||||
addSpinner(box, "Invert gyro axes", Settings.GYRO_INV_NAMES, Settings.gyroInvert[p], v -> { Settings.gyroInvert[p] = v; Settings.save(); });
|
||||
for (int i = 0; i < 3; i++) {
|
||||
final int out = i;
|
||||
addSpinner(box, "DroidDeck gyro " + "XYZ".charAt(i) + " comes from", Settings.AXIS_NAMES, Settings.gyroMap[p][i], v -> { Settings.gyroMap[p][out] = v; Settings.save(); });
|
||||
}
|
||||
addSpinner(box, "Apply remap/invert to accelerometer too", new String[] { "Yes (recommended)", "No" },
|
||||
Settings.accelFollows[p] ? 0 : 1, v -> { Settings.accelFollows[p] = v == 0; Settings.save(); });
|
||||
addSlider(box, "Gyro deadzone (deg/s)", 50, Settings.gyroDeadzone[p], v -> Settings.gyroDeadzone[p] = v);
|
||||
gyroCalibView = sub(calibLabel(p), 11f);
|
||||
LinearLayout gc = new LinearLayout(this);
|
||||
gc.setOrientation(LinearLayout.HORIZONTAL);
|
||||
gc.addView(button("Calibrate (hold still)", v -> startGyroCalibration()), weight());
|
||||
gap(gc);
|
||||
gc.addView(button("Reset calibration", v -> resetGyroCalibration()), weight());
|
||||
box.addView(gc);
|
||||
box.addView(gyroCalibView);
|
||||
box.addView(sub("Calibration samples the controller shown above (player 1 slot). Deadzone ignores tiny drift.", 11f));
|
||||
|
||||
subhead(box, "Touchpad");
|
||||
addCheck(box, "Invert touchpad X (left/right)", Settings.touchInvX[p], on -> Settings.touchInvX[p] = on);
|
||||
addCheck(box, "Invert touchpad Y (up/down)", Settings.touchInvY[p], on -> Settings.touchInvY[p] = on);
|
||||
addCheck(box, "Swap touchpad X and Y (before invert)", Settings.touchSwap[p], on -> Settings.touchSwap[p] = on);
|
||||
addSpinner(box, "Layout", Settings.TOUCH_NAMES, Settings.touchMode[p], v -> { Settings.touchMode[p] = v; Settings.save(); pad.postInvalidate(); });
|
||||
|
||||
subhead(box, "Button remap");
|
||||
box.addView(sub("Map any controller button to a Deck grip (L4/R4/L5/R5) or a trackpad touch/click. "
|
||||
+ "Useful for extra buttons like a Flydigi's C and Z.", 11f));
|
||||
for (int i = 0; i < Settings.REMAP_COUNT; i++) {
|
||||
final int target = i;
|
||||
addSpinner(box, Settings.REMAP_TARGETS[i] + " pressed by", Settings.SRC_NAMES, Settings.remap[p][i], v -> { Settings.remap[p][target] = v; Settings.save(); });
|
||||
}
|
||||
|
||||
subhead(box, "Light");
|
||||
addSlider(box, "Red", 255, Settings.lightR[p], v -> { Settings.lightR[p] = v; applyLight(p); });
|
||||
addSlider(box, "Green", 255, Settings.lightG[p], v -> { Settings.lightG[p] = v; applyLight(p); });
|
||||
addSlider(box, "Blue", 255, Settings.lightB[p], v -> { Settings.lightB[p] = v; applyLight(p); });
|
||||
addSlider(box, "Brightness %", 100, Settings.brightness[p], v -> { Settings.brightness[p] = v; applyLight(p); });
|
||||
addSpinner(box, "Player LEDs", Settings.PLAYER_NAMES, Settings.playerLed[p], v -> { Settings.playerLed[p] = v; Settings.save(); applyLight(p); });
|
||||
}
|
||||
|
||||
private void applyLight(int p) { NativeBridge.applyOutput(p); }
|
||||
|
||||
// ---------- styled UI helpers ----------
|
||||
|
||||
private GradientDrawable rounded(int color, int radius) {
|
||||
GradientDrawable g = new GradientDrawable();
|
||||
g.setColor(color);
|
||||
g.setCornerRadius(radius);
|
||||
return g;
|
||||
}
|
||||
|
||||
private GradientDrawable pill(int color) {
|
||||
GradientDrawable g = new GradientDrawable();
|
||||
g.setColor(color);
|
||||
g.setCornerRadius(dp(20));
|
||||
return g;
|
||||
}
|
||||
|
||||
private LinearLayout card(LinearLayout parent) {
|
||||
LinearLayout c = new LinearLayout(this);
|
||||
c.setOrientation(LinearLayout.VERTICAL);
|
||||
c.setBackground(rounded(CARD, dp(16)));
|
||||
c.setPadding(dp(16), dp(14), dp(16), dp(14));
|
||||
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||
lp.bottomMargin = dp(12);
|
||||
parent.addView(c, lp);
|
||||
return c;
|
||||
}
|
||||
|
||||
private void cardTitle(LinearLayout card, String s) {
|
||||
TextView t = new TextView(this);
|
||||
t.setText(s.toUpperCase(java.util.Locale.ROOT));
|
||||
t.setTextColor(ACCENT);
|
||||
t.setTextSize(12f);
|
||||
t.setTypeface(Typeface.DEFAULT_BOLD);
|
||||
t.setLetterSpacing(0.08f);
|
||||
t.setPadding(0, 0, 0, dp(8));
|
||||
card.addView(t);
|
||||
}
|
||||
|
||||
private void subhead(LinearLayout box, String s) {
|
||||
TextView t = new TextView(this);
|
||||
t.setText(s);
|
||||
t.setTextColor(TEXT);
|
||||
t.setTextSize(14f);
|
||||
t.setTypeface(Typeface.DEFAULT_BOLD);
|
||||
t.setPadding(0, dp(14), 0, dp(4));
|
||||
box.addView(t);
|
||||
}
|
||||
|
||||
private void spacer(LinearLayout parent, int h) {
|
||||
View v = new View(this);
|
||||
parent.addView(v, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(h)));
|
||||
}
|
||||
|
||||
private void gap(LinearLayout row) {
|
||||
View v = new View(this);
|
||||
row.addView(v, new LinearLayout.LayoutParams(dp(8), 1));
|
||||
}
|
||||
|
||||
private TextView text(String s, float size) {
|
||||
TextView t = new TextView(this);
|
||||
t.setTextColor(TEXT);
|
||||
t.setTextSize(size);
|
||||
t.setPadding(0, dp(4), 0, dp(4));
|
||||
t.setText(s);
|
||||
return t;
|
||||
}
|
||||
|
||||
private TextView sub(String s, float size) {
|
||||
TextView t = text(s, size);
|
||||
t.setTextColor(SUB);
|
||||
t.setLineSpacing(dp(2), 1f);
|
||||
return t;
|
||||
}
|
||||
|
||||
private Button button(String s, View.OnClickListener l) {
|
||||
Button b = new Button(this);
|
||||
b.setText(s);
|
||||
b.setAllCaps(false);
|
||||
b.setTextSize(13f);
|
||||
b.setTextColor(TEXT);
|
||||
b.setBackground(rounded(CARD2, dp(10)));
|
||||
b.setStateListAnimator(null);
|
||||
b.setPadding(dp(14), dp(10), dp(14), dp(10));
|
||||
b.setOnClickListener(l);
|
||||
return b;
|
||||
}
|
||||
|
||||
private Button primaryButton(String s, View.OnClickListener l) {
|
||||
Button b = button(s, l);
|
||||
b.setBackground(rounded(ACCENT, dp(10)));
|
||||
b.setTextColor(0xFF0E1116);
|
||||
b.setTypeface(Typeface.DEFAULT_BOLD);
|
||||
return b;
|
||||
}
|
||||
|
||||
private static LinearLayout.LayoutParams weight() {
|
||||
return new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f);
|
||||
}
|
||||
|
||||
private ArrayAdapter<String> styledAdapter(String[] names) {
|
||||
return new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, names) {
|
||||
@Override public View getView(int pos, View cv, ViewGroup parent) {
|
||||
TextView t = (TextView) super.getView(pos, cv, parent);
|
||||
t.setTextColor(TEXT); t.setTextSize(13f);
|
||||
return t;
|
||||
}
|
||||
@Override public View getDropDownView(int pos, View cv, ViewGroup parent) {
|
||||
TextView t = (TextView) super.getDropDownView(pos, cv, parent);
|
||||
t.setTextColor(0xFF10151C); t.setTextSize(14f);
|
||||
t.setPadding(dp(14), dp(12), dp(14), dp(12));
|
||||
return t;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private void addSpinner(LinearLayout root, String label, String[] names, int selected, final IntSink sink) {
|
||||
root.addView(sub(label, 12f));
|
||||
Spinner sp = new Spinner(this);
|
||||
sp.setAdapter(styledAdapter(names));
|
||||
sp.setSelection(selected);
|
||||
sp.setBackground(rounded(CARD2, dp(8)));
|
||||
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||
lp.bottomMargin = dp(6);
|
||||
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
|
||||
@Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { sink.set(position); }
|
||||
@Override public void onNothingSelected(AdapterView<?> parent) { }
|
||||
});
|
||||
root.addView(sp, lp);
|
||||
}
|
||||
|
||||
private void addSlider(LinearLayout root, final String label, int max, int value, final IntSink sink) {
|
||||
final TextView t = sub(label + ": " + value, 12f);
|
||||
SeekBar sb = new SeekBar(this);
|
||||
sb.setMax(max);
|
||||
sb.setProgress(value);
|
||||
sb.setProgressTintList(ColorStateList.valueOf(ACCENT));
|
||||
sb.setThumbTintList(ColorStateList.valueOf(ACCENT));
|
||||
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
|
||||
@Override public void onProgressChanged(SeekBar s, int v, boolean fromUser) {
|
||||
t.setText(label + ": " + v);
|
||||
if (fromUser) sink.set(v);
|
||||
}
|
||||
@Override public void onStartTrackingTouch(SeekBar s) { }
|
||||
@Override public void onStopTrackingTouch(SeekBar s) { Settings.save(); }
|
||||
});
|
||||
root.addView(t);
|
||||
root.addView(sb);
|
||||
}
|
||||
|
||||
private interface BoolSink { void set(boolean on); }
|
||||
|
||||
private void addCheck(LinearLayout root, String label, boolean value, final BoolSink sink) {
|
||||
CheckBox c = new CheckBox(this);
|
||||
c.setText(label);
|
||||
c.setTextColor(TEXT);
|
||||
c.setTextSize(13f);
|
||||
c.setButtonTintList(ColorStateList.valueOf(ACCENT));
|
||||
c.setPadding(dp(6), dp(6), 0, dp(6));
|
||||
c.setChecked(value);
|
||||
c.setOnCheckedChangeListener((v, on) -> { sink.set(on); Settings.save(); });
|
||||
root.addView(c);
|
||||
}
|
||||
|
||||
// ---------- USB diagnostics ----------
|
||||
|
||||
private final Runnable usbRefresh = new Runnable() {
|
||||
@Override public void run() {
|
||||
int n = BridgeService.clientCount;
|
||||
usbView.setText(usbInfo() + "\nDroidDeck link: " + (n > 0 ? (n + " app(s) bound — sending frames") : "NOT bound (open a DroidDeck game session)"));
|
||||
ui.postDelayed(this, 2000);
|
||||
}
|
||||
};
|
||||
|
||||
/** Android's view of the controller on USB: is it there, and may this app talk to it? */
|
||||
private String usbInfo() {
|
||||
try {
|
||||
UsbManager um = (UsbManager) getSystemService(USB_SERVICE);
|
||||
StringBuilder sb = new StringBuilder("USB: ");
|
||||
boolean any = false;
|
||||
for (UsbDevice d : um.getDeviceList().values()) {
|
||||
if (!looksLikeController(d)) continue;
|
||||
any = true;
|
||||
String name = d.getProductName() != null ? d.getProductName() : "controller";
|
||||
sb.append(String.format(java.util.Locale.ROOT, "%s %04x:%04x access=%s ", name,
|
||||
d.getVendorId(), d.getProductId(), um.hasPermission(d) ? "yes" : "NO (unplug and replug, tap OK)"));
|
||||
}
|
||||
if (!any) sb.append("no controller on USB (use a USB-C data cable)");
|
||||
return sb.toString();
|
||||
} catch (RuntimeException e) {
|
||||
return "USB: unavailable";
|
||||
}
|
||||
}
|
||||
|
||||
/** Lists any USB / headset audio outputs Android currently sees (e.g. the controller's audio device). */
|
||||
private int rateIndex() {
|
||||
for (int i = 0; i < Settings.RATE_MS.length; i++) if (Settings.RATE_MS[i] == Settings.pollMs) return i;
|
||||
return 1;
|
||||
}
|
||||
|
||||
private String audioInfo() {
|
||||
try {
|
||||
AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
|
||||
StringBuilder sb = new StringBuilder("Audio out: ");
|
||||
boolean any = false;
|
||||
for (AudioDeviceInfo d : am.getDevices(AudioManager.GET_DEVICES_OUTPUTS)) {
|
||||
int t = d.getType();
|
||||
if (t == AudioDeviceInfo.TYPE_USB_DEVICE || t == AudioDeviceInfo.TYPE_USB_HEADSET || t == AudioDeviceInfo.TYPE_USB_ACCESSORY) {
|
||||
any = true;
|
||||
CharSequence nm = d.getProductName();
|
||||
sb.append(nm != null ? nm : (t == AudioDeviceInfo.TYPE_USB_HEADSET ? "USB headset" : "USB audio")).append(" ");
|
||||
}
|
||||
}
|
||||
if (!any) sb.append("no USB audio device (plug the controller in with USB-C, or no audio interface)");
|
||||
return sb.toString();
|
||||
} catch (RuntimeException e) {
|
||||
return "Audio out: unavailable";
|
||||
}
|
||||
}
|
||||
|
||||
/** Opens Developer options, where "Disable USB audio routing" keeps audio on the phone. */
|
||||
private void openDevSettings() {
|
||||
// There is no public intent to a single developer toggle, so open the Developer options screen.
|
||||
try {
|
||||
startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
|
||||
return;
|
||||
} catch (RuntimeException ignored) { }
|
||||
// Developer options not enabled or unavailable: fall back to the main Settings app.
|
||||
try {
|
||||
startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
|
||||
} catch (RuntimeException ignored) { }
|
||||
}
|
||||
|
||||
// ---------- tests ----------
|
||||
|
||||
private void rumbleTest() {
|
||||
NativeBridge.setRumble(uiPlayer, 220, 220);
|
||||
ui.postDelayed(() -> NativeBridge.setRumble(uiPlayer, 0, 0), 700);
|
||||
}
|
||||
|
||||
// ---------- updates ----------
|
||||
|
||||
private void checkUpdate() {
|
||||
updateUrl = null;
|
||||
updateButton.setText("Checking for updates...");
|
||||
UpdateChecker.check(this, (msg, url) -> {
|
||||
updateUrl = url;
|
||||
updateButton.setText(msg);
|
||||
});
|
||||
}
|
||||
|
||||
private void openUrl(String url) {
|
||||
try {
|
||||
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
|
||||
} catch (RuntimeException e) {
|
||||
updateButton.setText("Could not open the download link.");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- SDL USB handling ----------
|
||||
|
||||
@Override protected void onDestroy() {
|
||||
running = false;
|
||||
ui.removeCallbacks(usbRefresh);
|
||||
NativeBridge.listeners.remove(this);
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
// SDL releases the USB controller when the activity pauses or loses focus. Undo that so input
|
||||
// keeps flowing while DroidDeck is in front.
|
||||
/** Asks Android for USB access to every game-controller-like device, using SDL's own permission
|
||||
* action so SDL's receiver opens the device straight away, then restarts SDL's enumeration. */
|
||||
private void forceUsbDriver() {
|
||||
UsbManager um = (UsbManager) getSystemService(USB_SERVICE);
|
||||
int asked = 0, have = 0, seen = 0;
|
||||
if (um != null) {
|
||||
for (UsbDevice d : um.getDeviceList().values()) {
|
||||
if (!looksLikeController(d)) continue;
|
||||
seen++;
|
||||
if (um.hasPermission(d)) { have++; continue; }
|
||||
Intent i = new Intent("org.libsdl.app.USB_PERMISSION").setPackage(getPackageName());
|
||||
int flags = Build.VERSION.SDK_INT >= 31 ? 0x02000000 : 0; // FLAG_MUTABLE
|
||||
try {
|
||||
um.requestPermission(d, PendingIntent.getBroadcast(this, 0, i, flags));
|
||||
asked++;
|
||||
} catch (RuntimeException ignored) { }
|
||||
}
|
||||
}
|
||||
usbView.setText(seen == 0
|
||||
? "No USB controller found. Use a USB-C cable (Bluetooth is not enough) and try again."
|
||||
: "USB controllers: " + seen + ", already allowed: " + have + ", asked now: " + asked);
|
||||
keepControllerClaimed();
|
||||
ui.postDelayed(NativeBridge::rescan, asked > 0 ? 4000 : 300);
|
||||
}
|
||||
|
||||
/** Any USB device with a HID or vendor-specific interface (SDL3 decides whether it really is a controller). */
|
||||
private static boolean looksLikeController(UsbDevice d) {
|
||||
for (int n = 0; n < d.getInterfaceCount(); n++) {
|
||||
UsbInterface f = d.getInterface(n);
|
||||
int c = f.getInterfaceClass();
|
||||
if (c == 255 || (c == 3 && f.getInterfaceProtocol() == 0)) return true; // vendor-specific (Xbox) or generic HID
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override protected void onResume() {
|
||||
super.onResume();
|
||||
if (android.provider.Settings.canDrawOverlays(this)) {
|
||||
if (pendingBubble) {
|
||||
pendingBubble = false;
|
||||
Settings.bubble = true;
|
||||
Settings.save();
|
||||
}
|
||||
if (Settings.bubble) {
|
||||
startService(new Intent(this, BridgeService.class).setAction("BUBBLE").putExtra("on", true));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override protected void onPause() {
|
||||
super.onPause();
|
||||
if (isFinishing()) running = false;
|
||||
keepControllerClaimed();
|
||||
}
|
||||
|
||||
@Override public void onBackPressed() {
|
||||
// Fallback only: SDL3 runs in a screen behind this one, and closing them would stop it -- step back instead.
|
||||
if (SdlHostActivity.running) moveTaskToBack(true);
|
||||
else super.onBackPressed();
|
||||
}
|
||||
|
||||
@Override public void onWindowFocusChanged(boolean hasFocus) {
|
||||
super.onWindowFocusChanged(hasFocus);
|
||||
keepControllerClaimed();
|
||||
}
|
||||
|
||||
private void keepControllerClaimed() {
|
||||
// When the driver is off, let go of the controller (freeze = release the USB interface) so Android can use it.
|
||||
SdlEngine.setHidFrozen(!Settings.driverEnabled);
|
||||
}
|
||||
|
||||
/** Release or re-claim the USB interface (the driver was switched off / on). */
|
||||
static void setHidFrozen(boolean frozen) {
|
||||
SdlEngine.setHidFrozen(frozen);
|
||||
}
|
||||
|
||||
// Controllers that reach the phone through Android's input (Bluetooth) deliver their buttons and sticks to the
|
||||
// focused window: while this screen is in front, hand them to SDL like SDL's own activity did.
|
||||
private static boolean fromGamepad(int source) {
|
||||
return (source & android.view.InputDevice.SOURCE_GAMEPAD) == android.view.InputDevice.SOURCE_GAMEPAD
|
||||
|| (source & android.view.InputDevice.SOURCE_JOYSTICK) == android.view.InputDevice.SOURCE_JOYSTICK
|
||||
|| (source & android.view.InputDevice.SOURCE_DPAD) == android.view.InputDevice.SOURCE_DPAD;
|
||||
}
|
||||
|
||||
@Override public boolean dispatchKeyEvent(android.view.KeyEvent e) {
|
||||
if (SdlEngine.isRunning() && fromGamepad(e.getSource())) {
|
||||
try {
|
||||
if (SDLControllerManager.isDeviceSDLJoystick(e.getDeviceId())) {
|
||||
if (e.getAction() == android.view.KeyEvent.ACTION_DOWN
|
||||
&& SDLControllerManager.onNativePadDown(e.getDeviceId(), e.getKeyCode(), e.getScanCode())) return true;
|
||||
if (e.getAction() == android.view.KeyEvent.ACTION_UP
|
||||
&& SDLControllerManager.onNativePadUp(e.getDeviceId(), e.getKeyCode(), e.getScanCode())) return true;
|
||||
}
|
||||
} catch (UnsatisfiedLinkError | RuntimeException ignored) { }
|
||||
}
|
||||
return super.dispatchKeyEvent(e);
|
||||
}
|
||||
|
||||
@Override public boolean dispatchGenericMotionEvent(android.view.MotionEvent e) {
|
||||
if (SdlEngine.isRunning() && (e.getSource() & android.view.InputDevice.SOURCE_JOYSTICK) == android.view.InputDevice.SOURCE_JOYSTICK) {
|
||||
try {
|
||||
if (SDLControllerManager.handleJoystickMotionEvent(e)) return true;
|
||||
} catch (UnsatisfiedLinkError | RuntimeException ignored) { }
|
||||
}
|
||||
return super.dispatchGenericMotionEvent(e);
|
||||
}
|
||||
|
||||
// ---------- NativeBridge.Listener ----------
|
||||
|
||||
private String calibLabel(int p) {
|
||||
float[] b = Settings.gyroBias[p];
|
||||
if (b[0] == 0f && b[1] == 0f && b[2] == 0f) return "Calibration: none";
|
||||
return String.format(java.util.Locale.ROOT, "Calibration bias (deg/s): x=%.2f y=%.2f z=%.2f", b[0], b[1], b[2]);
|
||||
}
|
||||
|
||||
private void startGyroCalibration() {
|
||||
calibPlayer = uiPlayer;
|
||||
calibSum[0] = calibSum[1] = calibSum[2] = 0f;
|
||||
calibCount = 0;
|
||||
if (gyroCalibView != null) gyroCalibView.setText("Hold the controller still...");
|
||||
}
|
||||
|
||||
private void resetGyroCalibration() {
|
||||
calibCount = -1;
|
||||
float[] b = Settings.gyroBias[uiPlayer];
|
||||
b[0] = b[1] = b[2] = 0f;
|
||||
Settings.save();
|
||||
if (gyroCalibView != null) gyroCalibView.setText(calibLabel(uiPlayer));
|
||||
}
|
||||
|
||||
@Override public void onFrame(float[] f, int slot) {
|
||||
if (slot != 0) return; // the test screen shows player 1
|
||||
if (calibCount >= 0 && f.length >= 13) {
|
||||
calibSum[0] += f[7]; calibSum[1] += f[8]; calibSum[2] += f[9];
|
||||
if (++calibCount >= CALIB_SAMPLES) {
|
||||
float[] b = Settings.gyroBias[calibPlayer];
|
||||
b[0] = calibSum[0] / CALIB_SAMPLES * RAD_TO_DEG;
|
||||
b[1] = calibSum[1] / CALIB_SAMPLES * RAD_TO_DEG;
|
||||
b[2] = calibSum[2] / CALIB_SAMPLES * RAD_TO_DEG;
|
||||
Settings.save();
|
||||
calibCount = -1;
|
||||
ui.post(() -> { if (gyroCalibView != null && uiPlayer == calibPlayer) gyroCalibView.setText(calibLabel(calibPlayer)); });
|
||||
}
|
||||
}
|
||||
pad.update(f);
|
||||
long now = System.nanoTime();
|
||||
if (now - lastSummary > 300_000_000L) {
|
||||
lastSummary = now;
|
||||
ui.post(() -> summaryView.setText(pad.summary()));
|
||||
}
|
||||
}
|
||||
|
||||
@Override public void onPadCaps(int slot, int present, int axes, int touchpads, String kind) {
|
||||
if (slot != 0) return;
|
||||
pad.setCaps(present, axes, touchpads, kind);
|
||||
}
|
||||
|
||||
@Override public void onStatus(final String s) {
|
||||
ui.post(() -> {
|
||||
statusView.setText(s);
|
||||
boolean off = s.contains("driver OFF");
|
||||
boolean waiting = s.startsWith("Controller disconnected") || s.startsWith("Waiting") || s.startsWith("Starting");
|
||||
if (off) {
|
||||
statusPill.setText("Driver off");
|
||||
statusPill.setBackground(pill(BADC));
|
||||
} else if (waiting) {
|
||||
statusPill.setText("Waiting");
|
||||
statusPill.setBackground(pill(WARNC));
|
||||
} else {
|
||||
statusPill.setText("Connected");
|
||||
statusPill.setBackground(pill(OKC));
|
||||
}
|
||||
if (off || waiting) pad.setDisconnected();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,975 @@
|
||||
package com.example.dsedge;
|
||||
|
||||
import android.app.Notification;
|
||||
import android.app.NotificationChannel;
|
||||
import android.app.NotificationManager;
|
||||
import android.app.Service;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.ServiceInfo;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.PixelFormat;
|
||||
import android.graphics.drawable.GradientDrawable;
|
||||
import android.util.TypedValue;
|
||||
import android.view.Gravity;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.view.WindowManager;
|
||||
import android.widget.TextView;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.IBinder;
|
||||
import android.os.Looper;
|
||||
import android.os.Message;
|
||||
import android.os.Messenger;
|
||||
import android.os.RemoteException;
|
||||
import android.os.SystemClock;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
/**
|
||||
* Streams controller frames (from the SDL3 loop) to bound clients such as DroidDeck, and passes their
|
||||
* rumble / lightbar requests back. Same wire protocol as the first bridge, plus decoupled touchpad data.
|
||||
*/
|
||||
public class BridgeService extends Service implements NativeBridge.Listener {
|
||||
static final int MSG_REGISTER = 1;
|
||||
static final int MSG_UNREGISTER = 2;
|
||||
static final int MSG_OUTPUT = 3;
|
||||
static final int MSG_FRAME = 10;
|
||||
static final int MSG_STATUS = 11;
|
||||
static final int MSG_PAD_GONE = 12;
|
||||
// Steam Controller (2026) raw passthrough. Client -> bridge:
|
||||
static final int MSG_TRITON_OUTPUT = 4; // "data": report (id first), "feature": feature write?
|
||||
static final int MSG_TRITON_GET = 5; // "request": long, "id": feature report id
|
||||
static final int MSG_TRITON_RUMBLE = 6; // "l", "r": 0..65535
|
||||
// Bridge -> client:
|
||||
static final int MSG_TRITON_STATE = 13; // "id": report id, "data": payload
|
||||
static final int MSG_TRITON_CONN = 14; // "on": boolean, "what": description
|
||||
static final int MSG_TRITON_FEATURE = 15; // "request": long, "data": reply (absent = no answer)
|
||||
// Steam Native Hook-up. Client -> bridge:
|
||||
static final int MSG_HOOKUP_OUT = 7; // "slot", "kind" (0 output report, 1 feature write), "data"
|
||||
static final int MSG_HOOKUP_GET = 8; // "slot", "request", "id", "input", "length"
|
||||
// Bridge -> client:
|
||||
static final int MSG_HOOKUP_ADD = 20; // HookupIdentity bundle
|
||||
static final int MSG_HOOKUP_INPUT = 21; // "slot", "data"
|
||||
static final int MSG_HOOKUP_REMOVE = 22; // "slot"
|
||||
static final int MSG_HOOKUP_REPLY = 23; // "slot", "request", "data" (absent = no answer)
|
||||
static final int MSG_BRIDGE_LOG = 30; // "text": one or more log lines (newline separated)
|
||||
static final int MSG_HOOKUP_SYNC = 9; // client watchdog: resend what is handed over (re-registers if needed)
|
||||
static final int MSG_HOOKUP_STATE = 24; // "slots": int[] of live hook-up slots; "fast_ino": mapped shared file
|
||||
static final int MSG_HOOKUP_SHM = 25; // <- DroidDeck: "fd": its shared hook-up file (fast path)
|
||||
// DroidDeck's SDL3Bridge settings tab (no REGISTER needed: it gets no frames, only replies)
|
||||
static final int MSG_SETTINGS_GET = 40; // <- replyTo: send MSG_SETTINGS
|
||||
static final int MSG_SETTINGS_SET = 41; // <- "key" [+ "p" player, "i" index] + "int" / "bool"; replyTo: send MSG_SETTINGS
|
||||
static final int MSG_SETTINGS = 42; // -> the whole settings state + controller status (see settingsSnapshot)
|
||||
|
||||
private static final float RAD_TO_DEG = 57.29578f;
|
||||
private static final float G = 9.80665f;
|
||||
private static final float PAD_W = 1920f, PAD_H = 1080f;
|
||||
|
||||
private final CopyOnWriteArrayList<Messenger> clients = new CopyOnWriteArrayList<>();
|
||||
static volatile int clientCount; // how many clients (DroidDeck) are bound + registered
|
||||
|
||||
private final Handler handler = new Handler(Looper.getMainLooper()) {
|
||||
@Override public void handleMessage(Message m) {
|
||||
switch (m.what) {
|
||||
case MSG_REGISTER:
|
||||
if (m.replyTo != null) {
|
||||
if (!clients.contains(m.replyTo)) clients.add(m.replyTo); // re-register = resend state, no duplicate
|
||||
clientCount = clients.size(); sendStatus(m.replyTo, NativeBridge.lastStatus);
|
||||
if (NativeBridge.tritonConnected) sendTritonConn(m.replyTo, true, NativeBridge.tritonWhat);
|
||||
String backlog;
|
||||
synchronized (NativeBridge.bridgeLog) { backlog = String.join("\n", NativeBridge.bridgeLog); }
|
||||
if (!backlog.isEmpty()) {
|
||||
Bundle lb = new Bundle();
|
||||
lb.putString("text", "(earlier) " + backlog.replace("\n", "\n(earlier) "));
|
||||
sendOne(m.replyTo, MSG_BRIDGE_LOG, lb);
|
||||
}
|
||||
for (Bundle id : NativeBridge.hookupIdentity) if (id != null) sendOne(m.replyTo, MSG_HOOKUP_ADD, id);
|
||||
}
|
||||
break;
|
||||
case MSG_UNREGISTER:
|
||||
if (m.replyTo != null) { clients.remove(m.replyTo); clientCount = clients.size(); }
|
||||
if (clients.isEmpty()) NativeBridge.setSteamAway(false); // DroidDeck's session ended
|
||||
break;
|
||||
case MSG_OUTPUT:
|
||||
mergeOutput(m.getData());
|
||||
break;
|
||||
case MSG_TRITON_OUTPUT: {
|
||||
byte[] data = m.getData().getByteArray("data");
|
||||
if (data != null) NativeBridge.tritonOutput(data, m.getData().getBoolean("feature"));
|
||||
break;
|
||||
}
|
||||
case MSG_TRITON_GET:
|
||||
NativeBridge.tritonGetFeature(m.getData().getLong("request"), m.getData().getInt("id", 1));
|
||||
break;
|
||||
case MSG_HOOKUP_OUT: {
|
||||
byte[] data = m.getData().getByteArray("data");
|
||||
if (data != null) NativeBridge.hookupOutput(m.getData().getInt("slot"), m.getData().getInt("kind"), data);
|
||||
break;
|
||||
}
|
||||
case MSG_HOOKUP_SYNC:
|
||||
// DroidDeck's desktop: is the Steam client running there? (Absent = yes: the Steam session.)
|
||||
NativeBridge.setSteamAway(m.getData() != null && m.getData().getBoolean("steamAway", false));
|
||||
handler.removeCallbacks(steamAwayLapse);
|
||||
if (NativeBridge.hookupWaitsForSteam()) handler.postDelayed(steamAwayLapse, 10100);
|
||||
if (m.replyTo != null) {
|
||||
// A client the bridge forgot (the bridge was restarted) is registered again.
|
||||
if (!clients.contains(m.replyTo)) {
|
||||
clients.add(m.replyTo); clientCount = clients.size();
|
||||
sendStatus(m.replyTo, NativeBridge.lastStatus);
|
||||
}
|
||||
if (NativeBridge.tritonConnected) sendTritonConn(m.replyTo, true, NativeBridge.tritonWhat);
|
||||
int[] live = new int[NativeBridge.MAX_PADS];
|
||||
int n = 0;
|
||||
for (int i = 0; i < NativeBridge.MAX_PADS; i++) {
|
||||
Bundle id = NativeBridge.hookupIdentity[i];
|
||||
if (id == null) continue;
|
||||
sendOne(m.replyTo, MSG_HOOKUP_ADD, id);
|
||||
live[n++] = i;
|
||||
}
|
||||
NativeBridge.retryUndescribed();
|
||||
Bundle st = new Bundle();
|
||||
st.putIntArray("slots", java.util.Arrays.copyOf(live, n));
|
||||
st.putLong("fast_ino", NativeBridge.hookupShmInode());
|
||||
sendOne(m.replyTo, MSG_HOOKUP_STATE, st);
|
||||
}
|
||||
ensureBridgeLoop();
|
||||
break;
|
||||
case MSG_HOOKUP_SHM: {
|
||||
Bundle d = m.getData();
|
||||
if (d != null) d.setClassLoader(android.os.ParcelFileDescriptor.class.getClassLoader());
|
||||
@SuppressWarnings("deprecation")
|
||||
android.os.ParcelFileDescriptor pfd = d == null ? null : d.getParcelable("fd");
|
||||
NativeBridge.hookupMapShm(pfd);
|
||||
break;
|
||||
}
|
||||
case MSG_SETTINGS_SET:
|
||||
applyRemote(m.getData());
|
||||
// fall through: answer with the new state
|
||||
case MSG_SETTINGS_GET:
|
||||
if (m.replyTo != null) sendOne(m.replyTo, MSG_SETTINGS, settingsSnapshot());
|
||||
if (m.what == MSG_SETTINGS_GET) ensureBridgeLoop(); // the tab shows live controllers
|
||||
break;
|
||||
case MSG_HOOKUP_GET:
|
||||
NativeBridge.hookupGet(m.getData().getInt("slot"), m.getData().getLong("request"), m.getData().getInt("id"),
|
||||
m.getData().getBoolean("input"), m.getData().getInt("length", 64));
|
||||
break;
|
||||
case MSG_TRITON_RUMBLE:
|
||||
NativeBridge.tritonRumble(m.getData().getInt("l"), m.getData().getInt("r"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
private final Messenger messenger = new Messenger(handler);
|
||||
/** DroidDeck stopped saying that Steam is away (it went away itself): hook-up goes on again. */
|
||||
private final Runnable steamAwayLapse = NativeBridge::recheckHookup;
|
||||
|
||||
// ---- floating bubble ----
|
||||
private final Handler main = new Handler(Looper.getMainLooper());
|
||||
private WindowManager wm;
|
||||
private TextView bubble;
|
||||
private WindowManager.LayoutParams bubbleLp;
|
||||
private int bubbleSize;
|
||||
private View removeZone;
|
||||
private boolean longPressFired;
|
||||
private Runnable bubbleLongPress;
|
||||
private volatile boolean connectedState;
|
||||
|
||||
static volatile BridgeService instance;
|
||||
|
||||
@Override public void onCreate() {
|
||||
NativeBridge.appContext = getApplicationContext();
|
||||
NativeBridge.clients = clients::size;
|
||||
instance = this;
|
||||
super.onCreate();
|
||||
Settings.init(this);
|
||||
NativeBridge.listeners.add(this);
|
||||
// SDL3 runs here, in the background: nothing has to open when DroidDeck (or a plugged-in controller)
|
||||
// starts the bridge. The notification is the bridge's icon in the status bar.
|
||||
SdlEngine.start(this);
|
||||
// The status bar icon. Started by DroidDeck's connection it is a plain ongoing notification (that
|
||||
// connection keeps the bridge alive); started from the bridge screen or a plugged-in controller,
|
||||
// onStartCommand turns it into the foreground service's notification.
|
||||
postNotification(false);
|
||||
}
|
||||
|
||||
// ---------- status bar notification ----------
|
||||
private static final int NOTE_ID = 1;
|
||||
private String noteText = "";
|
||||
private long noteMs;
|
||||
|
||||
private Notification buildNotification() {
|
||||
NotificationManager nm = getSystemService(NotificationManager.class);
|
||||
nm.createNotificationChannel(new NotificationChannel("bridge", "Controller bridge", NotificationManager.IMPORTANCE_LOW));
|
||||
android.app.PendingIntent open = android.app.PendingIntent.getActivity(this, 0,
|
||||
new Intent(this, BridgeActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
android.app.PendingIntent.FLAG_IMMUTABLE | android.app.PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
String text = SdlEngine.error != null ? SdlEngine.error : NativeBridge.lastStatus;
|
||||
return new Notification.Builder(this, "bridge")
|
||||
.setContentTitle(!Settings.isHookup() ? "SDL3Bridge"
|
||||
: NativeBridge.hookupWaitsForSteam() ? "SDL3Bridge · Hook-up waits for Steam (DroidDeck desktop)"
|
||||
: "SDL3Bridge · Steam Native Hook-up")
|
||||
.setContentText(text)
|
||||
.setStyle(new Notification.BigTextStyle().bigText(text))
|
||||
.setSmallIcon(R.drawable.ic_stat_bridge)
|
||||
.setColor(0xFF4FC3F7)
|
||||
.setContentIntent(open)
|
||||
.setOngoing(true)
|
||||
.setShowWhen(false)
|
||||
.setOnlyAlertOnce(true)
|
||||
.build();
|
||||
}
|
||||
|
||||
/** foreground: as the foreground service's notification; else a plain ongoing notification. */
|
||||
private boolean postNotification(boolean foreground) {
|
||||
try {
|
||||
Notification n = buildNotification();
|
||||
if (foreground) {
|
||||
if (Build.VERSION.SDK_INT >= 34) startForeground(NOTE_ID, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE);
|
||||
else startForeground(NOTE_ID, n);
|
||||
} else {
|
||||
getSystemService(NotificationManager.class).notify(NOTE_ID, n);
|
||||
}
|
||||
return true;
|
||||
} catch (RuntimeException e) {
|
||||
android.util.Log.w("SDL3Bridge", "notification: " + e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Status changed: refresh the notification text (at most every 2 s). */
|
||||
private void refreshNotification(String status) {
|
||||
if (status == null || status.equals(noteText)) return;
|
||||
long now = SystemClock.uptimeMillis();
|
||||
if (now - noteMs < 2000) {
|
||||
main.removeCallbacks(noteRefresh);
|
||||
main.postDelayed(noteRefresh, 2000 - (now - noteMs));
|
||||
return;
|
||||
}
|
||||
noteText = status;
|
||||
noteMs = now;
|
||||
try { getSystemService(NotificationManager.class).notify(NOTE_ID, buildNotification()); } catch (RuntimeException ignored) { }
|
||||
}
|
||||
private final Runnable noteRefresh = () -> refreshNotification(NativeBridge.lastStatus);
|
||||
|
||||
@Override public IBinder onBind(Intent i) { return messenger.getBinder(); }
|
||||
|
||||
@Override public int onStartCommand(Intent i, int flags, int startId) {
|
||||
SdlEngine.start(this);
|
||||
if (i != null && "BUBBLE".equals(i.getAction())) {
|
||||
if (i.getBooleanExtra("on", false)) showBubble(); else hideBubble();
|
||||
} else if (Settings.bubble) {
|
||||
showBubble();
|
||||
}
|
||||
if (!postNotification(true)) postNotification(false);
|
||||
return START_NOT_STICKY;
|
||||
}
|
||||
|
||||
@Override public void onDestroy() {
|
||||
if (instance == this) instance = null;
|
||||
NativeBridge.listeners.remove(this);
|
||||
hideBubble();
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
// ---------- floating bubble (chat-head) ----------
|
||||
// tap -> toggle the SDL3 forced driver (green = on, red = off)
|
||||
// double tap -> toggle Steam Native Hook-up (blue = on: Steam gets the real controllers)
|
||||
// hold 3s -> open the bridge app
|
||||
// drag to the bottom remove zone -> dismiss the bubble
|
||||
|
||||
@SuppressWarnings("ClickableViewAccessibility")
|
||||
private void showBubble() {
|
||||
if (bubble != null) return;
|
||||
if (!android.provider.Settings.canDrawOverlays(this)) return; // no permission yet
|
||||
wm = (WindowManager) getSystemService(WINDOW_SERVICE);
|
||||
|
||||
bubbleSize = dp(52);
|
||||
TextView b = new TextView(this);
|
||||
b.setText(Settings.isHookup() ? "HOOK" : "SDL3");
|
||||
b.setTextColor(Color.WHITE);
|
||||
b.setGravity(Gravity.CENTER);
|
||||
b.setTextSize(12f);
|
||||
b.setWidth(bubbleSize);
|
||||
b.setHeight(bubbleSize);
|
||||
b.setBackground(bubbleBg(Settings.driverEnabled));
|
||||
b.setElevation(dp(4));
|
||||
|
||||
int type = Build.VERSION.SDK_INT >= 26
|
||||
? WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
|
||||
: WindowManager.LayoutParams.TYPE_PHONE;
|
||||
WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
|
||||
WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, type,
|
||||
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
|
||||
PixelFormat.TRANSLUCENT);
|
||||
lp.gravity = Gravity.TOP | Gravity.START;
|
||||
lp.x = Settings.bubbleX;
|
||||
lp.y = Settings.bubbleY;
|
||||
|
||||
final int slop = dp(10);
|
||||
b.setOnTouchListener(new View.OnTouchListener() {
|
||||
float downX, downY; int startX, startY; boolean moved;
|
||||
@Override public boolean onTouch(View v, MotionEvent e) {
|
||||
switch (e.getAction()) {
|
||||
case MotionEvent.ACTION_DOWN:
|
||||
downX = e.getRawX(); downY = e.getRawY();
|
||||
startX = bubbleLp.x; startY = bubbleLp.y; moved = false; longPressFired = false;
|
||||
bubbleLongPress = () -> { longPressFired = true; openBridgeApp(); };
|
||||
main.postDelayed(bubbleLongPress, 3000);
|
||||
return true;
|
||||
case MotionEvent.ACTION_MOVE: {
|
||||
int nx = startX + (int) (e.getRawX() - downX);
|
||||
int ny = startY + (int) (e.getRawY() - downY);
|
||||
if (!moved && Math.abs(nx - startX) + Math.abs(ny - startY) > slop) {
|
||||
moved = true;
|
||||
if (bubbleLongPress != null) main.removeCallbacks(bubbleLongPress);
|
||||
showRemoveZone();
|
||||
}
|
||||
bubbleLp.x = nx; bubbleLp.y = ny;
|
||||
try { wm.updateViewLayout(bubble, bubbleLp); } catch (RuntimeException ignored) { }
|
||||
if (moved) highlightRemoveZone(overRemoveZone());
|
||||
return true;
|
||||
}
|
||||
case MotionEvent.ACTION_CANCEL:
|
||||
case MotionEvent.ACTION_UP:
|
||||
if (bubbleLongPress != null) main.removeCallbacks(bubbleLongPress);
|
||||
boolean removed = false;
|
||||
if (moved && overRemoveZone()) { removeBubbleByUser(); removed = true; }
|
||||
hideRemoveZone();
|
||||
if (!removed) {
|
||||
Settings.bubbleX = bubbleLp.x; Settings.bubbleY = bubbleLp.y; Settings.save();
|
||||
if (!moved && !longPressFired) onBubbleTap();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
wm.addView(b, lp);
|
||||
bubble = b;
|
||||
bubbleLp = lp;
|
||||
} catch (RuntimeException e) {
|
||||
bubble = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void openBridgeApp() {
|
||||
try {
|
||||
startActivity(new Intent(BridgeService.this, BridgeActivity.class)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
|
||||
} catch (RuntimeException ignored) { }
|
||||
}
|
||||
|
||||
// A single tap waits this long for a second tap before it acts, so a double tap doesn't also flip the driver.
|
||||
private static final long DOUBLE_TAP_MS = 300;
|
||||
private boolean tapPending;
|
||||
|
||||
private void onBubbleTap() {
|
||||
if (tapPending) {
|
||||
tapPending = false; // the pending single tap sees this and does nothing
|
||||
toggleHookup();
|
||||
} else {
|
||||
tapPending = true;
|
||||
main.postDelayed(() -> { if (tapPending) { tapPending = false; toggleDriver(); } }, DOUBLE_TAP_MS);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Double-tap action: Steam Native Hook-up on/off. Hook-up needs the SDL3 driver, so switching it on also
|
||||
* switches the driver on; switching it off puts back what was there before -- including the driver being
|
||||
* off (red bubble), so the controller goes back to Android / DroidDeck's own input instead of SDL3.
|
||||
*/
|
||||
private void toggleHookup() {
|
||||
boolean on = !Settings.isHookup();
|
||||
boolean freeze = false;
|
||||
if (on) {
|
||||
Settings.lastPresentAs = Settings.presentAs;
|
||||
Settings.driverBeforeHookup = Settings.driverEnabled;
|
||||
Settings.presentAs = Settings.PRESENT_HOOKUP;
|
||||
if (!Settings.driverEnabled) {
|
||||
Settings.driverEnabled = true;
|
||||
try { SdlEngine.setHidFrozen(false); } catch (Throwable ignored) { }
|
||||
}
|
||||
} else {
|
||||
Settings.presentAs = Settings.lastPresentAs;
|
||||
if (!Settings.driverBeforeHookup && Settings.driverEnabled) {
|
||||
Settings.driverEnabled = false;
|
||||
freeze = true;
|
||||
}
|
||||
}
|
||||
Settings.save();
|
||||
NativeBridge.applyDriver(); // also applies hook-up (native code releases the hooked-up controllers)
|
||||
if (freeze) {
|
||||
try { SdlEngine.setHidFrozen(true); } catch (Throwable ignored) { }
|
||||
}
|
||||
updateBubble();
|
||||
try {
|
||||
android.widget.Toast.makeText(this, on
|
||||
? "Steam Native Hook-up ON: Steam gets the real USB controllers"
|
||||
: !Settings.driverEnabled ? "Steam Native Hook-up OFF: SDL3 driver off again"
|
||||
: "Steam Native Hook-up OFF: back to " + Settings.PRESENT_NAMES[Settings.presentAs],
|
||||
android.widget.Toast.LENGTH_SHORT).show();
|
||||
} catch (RuntimeException ignored) { }
|
||||
}
|
||||
|
||||
/** Recolor the bubble after a settings change made elsewhere (the app screen). */
|
||||
static void refreshBubble() {
|
||||
BridgeService s = instance;
|
||||
if (s != null) s.updateBubble();
|
||||
}
|
||||
|
||||
/** Tap action: flip the SDL3 forced driver and recolor the bubble. */
|
||||
private void toggleDriver() {
|
||||
Settings.driverEnabled = !Settings.driverEnabled;
|
||||
Settings.save();
|
||||
NativeBridge.applyDriver();
|
||||
try { SdlEngine.setHidFrozen(!Settings.driverEnabled); } catch (Throwable ignored) { }
|
||||
updateBubble();
|
||||
}
|
||||
|
||||
private void removeBubbleByUser() {
|
||||
Settings.bubble = false;
|
||||
Settings.save();
|
||||
hideBubble();
|
||||
}
|
||||
|
||||
private void hideBubble() {
|
||||
if (bubble != null && wm != null) {
|
||||
try { wm.removeView(bubble); } catch (RuntimeException ignored) { }
|
||||
}
|
||||
bubble = null;
|
||||
hideRemoveZone();
|
||||
}
|
||||
|
||||
// ---- remove zone (the drop target at the bottom) ----
|
||||
|
||||
private void showRemoveZone() {
|
||||
if (removeZone != null || wm == null) return;
|
||||
int zs = dp(64);
|
||||
TextView z = new TextView(this);
|
||||
z.setText("✕");
|
||||
z.setTextColor(Color.WHITE);
|
||||
z.setGravity(Gravity.CENTER);
|
||||
z.setTextSize(22f);
|
||||
z.setWidth(zs);
|
||||
z.setHeight(zs);
|
||||
z.setBackground(removeZoneBg(false));
|
||||
WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
|
||||
WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT,
|
||||
bubbleLp.type,
|
||||
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
|
||||
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
|
||||
PixelFormat.TRANSLUCENT);
|
||||
lp.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
|
||||
lp.y = dp(48);
|
||||
try { wm.addView(z, lp); removeZone = z; } catch (RuntimeException e) { removeZone = null; }
|
||||
}
|
||||
|
||||
private void hideRemoveZone() {
|
||||
if (removeZone != null && wm != null) {
|
||||
try { wm.removeView(removeZone); } catch (RuntimeException ignored) { }
|
||||
}
|
||||
removeZone = null;
|
||||
}
|
||||
|
||||
private void highlightRemoveZone(boolean over) {
|
||||
if (removeZone instanceof TextView) {
|
||||
removeZone.setBackground(removeZoneBg(over));
|
||||
((TextView) removeZone).setScaleX(over ? 1.25f : 1f);
|
||||
((TextView) removeZone).setScaleY(over ? 1.25f : 1f);
|
||||
}
|
||||
}
|
||||
|
||||
private GradientDrawable removeZoneBg(boolean over) {
|
||||
GradientDrawable g = new GradientDrawable();
|
||||
g.setShape(GradientDrawable.OVAL);
|
||||
g.setColor(over ? 0xFFC62828 : 0xCC424242);
|
||||
g.setStroke(dp(2), 0xCCFFFFFF);
|
||||
return g;
|
||||
}
|
||||
|
||||
/** True when the bubble's centre is over the bottom remove zone. */
|
||||
private boolean overRemoveZone() {
|
||||
if (removeZone == null) return false;
|
||||
android.util.DisplayMetrics dm = getResources().getDisplayMetrics();
|
||||
float bx = bubbleLp.x + bubbleSize / 2f;
|
||||
float by = bubbleLp.y + bubbleSize / 2f;
|
||||
float zx = dm.widthPixels / 2f;
|
||||
float zy = dm.heightPixels - dp(48) - dp(32); // zone centre (bottom margin + half height)
|
||||
float dx = bx - zx, dy = by - zy;
|
||||
return Math.sqrt(dx * dx + dy * dy) < dp(80);
|
||||
}
|
||||
|
||||
private GradientDrawable bubbleBg(boolean driverOn) {
|
||||
GradientDrawable g = new GradientDrawable();
|
||||
g.setShape(GradientDrawable.OVAL);
|
||||
// blue = Steam Native Hook-up, green = SDL3 driver on, red = off
|
||||
g.setColor(!driverOn ? 0xFFC62828 : Settings.isHookup() ? 0xFF1565C0 : 0xFF2E7D32);
|
||||
g.setStroke(dp(2), 0xCCFFFFFF);
|
||||
return g;
|
||||
}
|
||||
|
||||
private void updateBubble() {
|
||||
if (bubble == null) return;
|
||||
main.post(() -> {
|
||||
if (bubble == null) return;
|
||||
bubble.setBackground(bubbleBg(Settings.driverEnabled));
|
||||
bubble.setText(Settings.isHookup() ? "HOOK" : "SDL3");
|
||||
});
|
||||
}
|
||||
|
||||
private int dp(int v) {
|
||||
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, v, getResources().getDisplayMetrics());
|
||||
}
|
||||
|
||||
// ---------- client -> controller ----------
|
||||
|
||||
/** Applies the touchpad swap / invert settings to one trackpad's [down, x, y]. */
|
||||
private static void orient(float[] p, int player) {
|
||||
if (Settings.touchSwap[player]) { float t = p[1]; p[1] = p[2]; p[2] = t; }
|
||||
if (Settings.touchInvX[player]) p[1] = -p[1];
|
||||
if (Settings.touchInvY[player]) p[2] = -p[2];
|
||||
}
|
||||
|
||||
private void mergeOutput(Bundle b) {
|
||||
if (b == null) return;
|
||||
if (b.containsKey("rl") || b.containsKey("rr")) {
|
||||
NativeBridge.setRumble(b.getInt("slot", 0), clamp(b.getInt("rl")), clamp(b.getInt("rr")));
|
||||
}
|
||||
// A client that sets the lightbar overrides the saved colour until the bridge screen changes it again.
|
||||
if (b.containsKey("r") || b.containsKey("g") || b.containsKey("b")) {
|
||||
int ps = Math.max(0, Math.min(Settings.PLAYERS - 1, b.getInt("slot", 0)));
|
||||
if (b.containsKey("r")) Settings.lightR[ps] = clamp(b.getInt("r"));
|
||||
if (b.containsKey("g")) Settings.lightG[ps] = clamp(b.getInt("g"));
|
||||
if (b.containsKey("b")) Settings.lightB[ps] = clamp(b.getInt("b"));
|
||||
NativeBridge.applyOutput(ps);
|
||||
}
|
||||
}
|
||||
|
||||
private static int clamp(int v) { return Math.max(0, Math.min(255, v)); }
|
||||
|
||||
// ---------- controller -> clients ----------
|
||||
|
||||
// A frame goes to DroidDeck only when the controller state changed (and for FRAME_SETTLE_MS after a change, so
|
||||
// DroidDeck's stick throttle always gets the final position), plus a keep-alive every FRAME_KEEPALIVE_MS. The
|
||||
// loop runs at up to 1000 Hz but most controllers report at 250-500 Hz, and an idle controller not at all:
|
||||
// sending every pass only fills DroidDeck's queue with copies.
|
||||
private static final long FRAME_SETTLE_MS = 20, FRAME_KEEPALIVE_MS = 100;
|
||||
private final float[][] lastFrame = new float[NativeBridge.MAX_PADS][];
|
||||
private final long[] lastFrameChangeMs = new long[NativeBridge.MAX_PADS], lastFrameSentMs = new long[NativeBridge.MAX_PADS];
|
||||
|
||||
private boolean frameWorthSending(float[] f, int slot) {
|
||||
if (slot < 0 || slot >= NativeBridge.MAX_PADS) return true;
|
||||
long now = SystemClock.uptimeMillis();
|
||||
float[] last = lastFrame[slot];
|
||||
if (last == null || last.length != f.length) last = lastFrame[slot] = new float[f.length];
|
||||
if (!java.util.Arrays.equals(f, last)) {
|
||||
System.arraycopy(f, 0, last, 0, f.length); // f is native's reused array: keep a copy
|
||||
lastFrameChangeMs[slot] = now;
|
||||
} else if (now - lastFrameChangeMs[slot] > FRAME_SETTLE_MS && now - lastFrameSentMs[slot] < FRAME_KEEPALIVE_MS) {
|
||||
return false;
|
||||
}
|
||||
lastFrameSentMs[slot] = now;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override public void onFrame(float[] f, int slot) {
|
||||
if (slot >= 0 && slot < NativeBridge.MAX_PADS && f.length >= NativeBridge.FRAME_LEN) {
|
||||
lastBattery[slot] = (int) f[19];
|
||||
calibrationSample(f, slot);
|
||||
}
|
||||
if (clients.isEmpty() || f.length < NativeBridge.FRAME_LEN) return;
|
||||
if (!frameWorthSending(f, slot)) return;
|
||||
Bundle b = new Bundle();
|
||||
b.putByteArray("raw", new byte[0]);
|
||||
b.putLong("t", SystemClock.elapsedRealtimeNanos());
|
||||
int rawMask = (int) f[0];
|
||||
int mask2 = f.length >= 22 ? (int) f[21] : 0; // extra buttons (MISC2..6, e.g. Flydigi C/Z)
|
||||
int mask = Settings.applyGripRemap(rawMask, mask2, slot); // user button -> L4/R4/L5/R5
|
||||
b.putInt("mask", mask);
|
||||
b.putInt("lx", (int) f[1]); b.putInt("ly", (int) f[2]);
|
||||
b.putInt("rx", (int) f[3]); b.putInt("ry", (int) f[4]);
|
||||
b.putInt("l2", (int) f[5]); b.putInt("r2", (int) f[6]);
|
||||
float gk = Settings.gyroGain[slot] / 100f;
|
||||
int inv = Settings.gyroInvert[slot];
|
||||
float dz = Settings.gyroDeadzone[slot];
|
||||
float[] bias = Settings.gyroBias[slot];
|
||||
int[] gmap = Settings.gyroMap[slot];
|
||||
boolean accFollows = Settings.accelFollows[slot];
|
||||
float[] gy = {f[7] * RAD_TO_DEG, f[8] * RAD_TO_DEG, f[9] * RAD_TO_DEG}; // deg/s
|
||||
float[] ac = {f[10] / G, f[11] / G, f[12] / G}; // g
|
||||
for (int k = 0; k < 3; k++) {
|
||||
gy[k] -= bias[k]; // remove resting drift (from Calibrate)
|
||||
if (Math.abs(gy[k]) < dz) gy[k] = 0f; // deadzone, in real deg/s (before gain)
|
||||
}
|
||||
float[] go = new float[3], ao = new float[3];
|
||||
for (int i = 0; i < 3; i++) {
|
||||
float sign = (inv & (1 << i)) != 0 ? -1f : 1f;
|
||||
int src = gmap[i];
|
||||
go[i] = gy[src] * gk * sign;
|
||||
ao[i] = accFollows ? ac[src] * sign : ac[i];
|
||||
}
|
||||
// Sony family only (DualShock 4 = 3, DualSense = 4, DualSense Edge = 5): their report has ONE
|
||||
// full-width multitouch pad and remaps the IMU axes (X, Z, -Y) vs the Deck IMU. The Steam Deck (0)
|
||||
// and Steam Controller (1) have two trackpads and use the Deck IMU convention, so they are left as-is.
|
||||
int presentType = Settings.PRESENT_PAD_TYPE[Settings.presentAs];
|
||||
boolean sony = Settings.isSonyPadType(presentType);
|
||||
if (sony) {
|
||||
float tg = go[1]; go[1] = -go[2]; go[2] = tg;
|
||||
float ta = ao[1]; ao[1] = -ao[2]; ao[2] = ta;
|
||||
}
|
||||
b.putFloatArray("gyro", go);
|
||||
b.putFloatArray("accel", ao);
|
||||
|
||||
|
||||
// Raw fingers (kept for older clients) ...
|
||||
List<Integer> t = new ArrayList<>();
|
||||
for (int i = 0; i < 2; i++) {
|
||||
if (f[13 + 3 * i] > 0.5f) { t.add(i + 1); t.add((int) f[14 + 3 * i]); t.add((int) f[15 + 3 * i]); }
|
||||
}
|
||||
int[] touch = new int[t.size()];
|
||||
for (int i = 0; i < touch.length; i++) touch[i] = t.get(i);
|
||||
b.putIntArray("touch", touch);
|
||||
|
||||
// ... and the decoupled version: each half is its own trackpad with local -1..1 coordinates.
|
||||
float[] padL = new float[3], padR = new float[3];
|
||||
int mode = Settings.touchMode[slot];
|
||||
// A 2015 Steam Controller has two real trackpads: always split the touchpad into left/right halves.
|
||||
if (presentType == Settings.PAD_TYPE_STEAM_2015 && mode != Settings.TOUCH_OFF) mode = Settings.TOUCH_SPLIT;
|
||||
// A native Sony pad (DualShock 4, DualSense, DualSense Edge) has ONE full-width multitouch
|
||||
// surface, so ignore the Deck split there: keep SDL's finger slots (finger 0 is the primary
|
||||
// touch the game tracks) and map both across the whole pad. padL carries finger 0, padR finger 1.
|
||||
// Only the Steam Deck pad (type 0) keeps the left/right split, since it has two real trackpads.
|
||||
if (mode != Settings.TOUCH_OFF) {
|
||||
if (sony) {
|
||||
for (int i = 0; i < 2; i++) {
|
||||
if (f[13 + 3 * i] <= 0.5f) continue;
|
||||
float[] p = (i == 0) ? padL : padR;
|
||||
p[0] = 1f; p[1] = f[14 + 3 * i] / PAD_W * 2f - 1f; p[2] = f[15 + 3 * i] / PAD_H * 2f - 1f;
|
||||
}
|
||||
} else for (int i = 0; i < 2; i++) {
|
||||
if (f[13 + 3 * i] <= 0.5f) continue;
|
||||
float x = f[14 + 3 * i], y = f[15 + 3 * i];
|
||||
float ny = y / PAD_H * 2f - 1f;
|
||||
if (mode == Settings.TOUCH_SINGLE) {
|
||||
if (padR[0] == 0f) { padR[0] = 1f; padR[1] = x / PAD_W * 2f - 1f; padR[2] = ny; }
|
||||
} else if (x < PAD_W / 2f) {
|
||||
if (padL[0] == 0f) { padL[0] = 1f; padL[1] = x / (PAD_W / 2f) * 2f - 1f; padL[2] = ny; }
|
||||
} else {
|
||||
if (padR[0] == 0f) { padR[0] = 1f; padR[1] = (x - PAD_W / 2f) / (PAD_W / 2f) * 2f - 1f; padR[2] = ny; }
|
||||
}
|
||||
}
|
||||
}
|
||||
int click = -1; // -1 none, 0 left trackpad, 1 right trackpad
|
||||
if (((mask >> 13) & 1) != 0 && mode != Settings.TOUCH_OFF) {
|
||||
click = (mode == Settings.TOUCH_SPLIT && padL[0] > 0f && padR[0] == 0f) ? 0 : 1;
|
||||
}
|
||||
// Button -> trackpad touch / click remaps (targets 4..7)
|
||||
int[] rm = Settings.remap[slot];
|
||||
if (Settings.srcDown(rawMask, mask2, rm[6]) && padL[0] == 0f) { padL[0] = 1f; padL[1] = 0f; padL[2] = 0f; }
|
||||
if (Settings.srcDown(rawMask, mask2, rm[7]) && padR[0] == 0f) { padR[0] = 1f; padR[1] = 0f; padR[2] = 0f; }
|
||||
if (Settings.srcDown(rawMask, mask2, rm[4])) { if (padL[0] == 0f) padL[0] = 1f; click = 0; }
|
||||
if (Settings.srcDown(rawMask, mask2, rm[5])) { if (padR[0] == 0f) padR[0] = 1f; click = 1; }
|
||||
orient(padL, slot);
|
||||
orient(padR, slot);
|
||||
b.putFloatArray("padL", padL);
|
||||
b.putFloatArray("padR", padR);
|
||||
b.putInt("padClick", click);
|
||||
|
||||
int state = (int) f[20];
|
||||
b.putInt("slot", slot);
|
||||
b.putInt("ptype", Settings.PRESENT_PAD_TYPE[Settings.presentAs]);
|
||||
b.putInt("vid", NativeBridge.vids[slot]);
|
||||
b.putInt("pid", NativeBridge.pids[slot]);
|
||||
b.putInt("battery", Math.max(0, (int) f[19]));
|
||||
b.putString("charge", state == 3 ? "charging" : state == 4 ? "full" : state == 1 ? "discharging" : "unknown");
|
||||
for (Messenger c : clients) {
|
||||
try {
|
||||
Message m = Message.obtain(null, MSG_FRAME);
|
||||
m.setData(b);
|
||||
c.send(m);
|
||||
} catch (RemoteException e) { clients.remove(c); clientCount = clients.size(); }
|
||||
}
|
||||
}
|
||||
|
||||
@Override public void onPadGone(int slot) {
|
||||
for (Messenger c : clients) {
|
||||
try {
|
||||
Bundle b = new Bundle();
|
||||
b.putInt("slot", slot);
|
||||
Message m = Message.obtain(null, MSG_PAD_GONE);
|
||||
m.setData(b);
|
||||
c.send(m);
|
||||
} catch (RemoteException e) { clients.remove(c); }
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Steam Controller (2026) raw passthrough -> clients ----------
|
||||
@Override public void onTritonState(int reportId, byte[] payload) {
|
||||
if (clients.isEmpty() || payload == null) return;
|
||||
Bundle b = new Bundle();
|
||||
b.putInt("id", reportId);
|
||||
b.putByteArray("data", payload);
|
||||
sendAll(MSG_TRITON_STATE, b);
|
||||
}
|
||||
|
||||
@Override public void onTritonConnected(boolean on, String what) {
|
||||
for (Messenger c : clients) sendTritonConn(c, on, what);
|
||||
}
|
||||
|
||||
@Override public void onTritonFeature(long request, byte[] report) {
|
||||
Bundle b = new Bundle();
|
||||
b.putLong("request", request);
|
||||
if (report != null) b.putByteArray("data", report);
|
||||
sendAll(MSG_TRITON_FEATURE, b);
|
||||
}
|
||||
|
||||
private void sendTritonConn(Messenger c, boolean on, String what) {
|
||||
try {
|
||||
Bundle b = new Bundle();
|
||||
b.putBoolean("on", on);
|
||||
b.putString("what", what);
|
||||
Message m = Message.obtain(null, MSG_TRITON_CONN);
|
||||
m.setData(b);
|
||||
c.send(m);
|
||||
} catch (RemoteException e) { clients.remove(c); clientCount = clients.size(); }
|
||||
}
|
||||
|
||||
/** SDL3's loop must run for controllers to work: it runs in this service, no screen needed. */
|
||||
private void ensureBridgeLoop() {
|
||||
SdlEngine.start(this);
|
||||
}
|
||||
|
||||
// ---------- Steam Native Hook-up -> clients ----------
|
||||
@Override public void onHookupAdded(int slot, Bundle identity) { sendAll(MSG_HOOKUP_ADD, identity); }
|
||||
|
||||
@Override public void onHookupInput(int slot, byte[] report) {
|
||||
if (clients.isEmpty() || report == null) return;
|
||||
Bundle b = new Bundle();
|
||||
b.putInt("slot", slot);
|
||||
b.putByteArray("data", report);
|
||||
sendAll(MSG_HOOKUP_INPUT, b);
|
||||
}
|
||||
|
||||
@Override public void onBridgeLog(String line) {
|
||||
Bundle b = new Bundle();
|
||||
b.putString("text", line);
|
||||
sendAll(MSG_BRIDGE_LOG, b);
|
||||
}
|
||||
|
||||
@Override public void onHookupRemoved(int slot) {
|
||||
Bundle b = new Bundle();
|
||||
b.putInt("slot", slot);
|
||||
sendAll(MSG_HOOKUP_REMOVE, b);
|
||||
}
|
||||
|
||||
@Override public void onHookupReply(int slot, long request, byte[] report) {
|
||||
Bundle b = new Bundle();
|
||||
b.putInt("slot", slot);
|
||||
b.putLong("request", request);
|
||||
if (report != null) b.putByteArray("data", report);
|
||||
sendAll(MSG_HOOKUP_REPLY, b);
|
||||
}
|
||||
|
||||
// ---------- DroidDeck's SDL3Bridge settings tab ----------
|
||||
private final int[] lastBattery = { -1, -1, -1, -1 };
|
||||
|
||||
// Gyro calibration started from DroidDeck: averages the resting gyro of that player's own controller.
|
||||
private static final int CALIB_SAMPLES = 180; // ~0.7 s at 4 ms per frame
|
||||
private final Object calibLock = new Object();
|
||||
private int calibPlayer = -1, calibCount;
|
||||
private final float[] calibSum = new float[3];
|
||||
|
||||
private void startCalibration(int p) {
|
||||
synchronized (calibLock) { calibPlayer = p; calibCount = 0; calibSum[0] = calibSum[1] = calibSum[2] = 0f; }
|
||||
}
|
||||
|
||||
private void calibrationSample(float[] f, int slot) {
|
||||
synchronized (calibLock) {
|
||||
if (calibPlayer != slot) return;
|
||||
calibSum[0] += f[7]; calibSum[1] += f[8]; calibSum[2] += f[9];
|
||||
if (++calibCount < CALIB_SAMPLES) return;
|
||||
float[] b = Settings.gyroBias[slot];
|
||||
for (int k = 0; k < 3; k++) b[k] = calibSum[k] / CALIB_SAMPLES * RAD_TO_DEG;
|
||||
calibPlayer = -1;
|
||||
}
|
||||
Settings.save();
|
||||
}
|
||||
|
||||
/** Everything the tab shows: settings, their choices (so DroidDeck needs no copy of them) and live status. */
|
||||
private Bundle settingsSnapshot() {
|
||||
Bundle b = new Bundle();
|
||||
b.putInt("v", 1);
|
||||
b.putString("status", NativeBridge.lastStatus);
|
||||
b.putBoolean("overlayAllowed", android.provider.Settings.canDrawOverlays(this));
|
||||
b.putBoolean("notifications", getSystemService(NotificationManager.class).areNotificationsEnabled());
|
||||
b.putString("engineError", SdlEngine.error == null ? "" : SdlEngine.error);
|
||||
b.putString("engineMode", SdlEngine.mode);
|
||||
b.putBoolean("fastPath", NativeBridge.hookupShmInode() != 0);
|
||||
b.putString("triton", NativeBridge.tritonConnected ? NativeBridge.tritonWhat : "");
|
||||
String[] padNames = new String[NativeBridge.MAX_PADS], padIds = new String[NativeBridge.MAX_PADS];
|
||||
String[] hookNames = new String[NativeBridge.MAX_PADS], hookIds = new String[NativeBridge.MAX_PADS];
|
||||
for (int i = 0; i < NativeBridge.MAX_PADS; i++) {
|
||||
String n = NativeBridge.names[i];
|
||||
padNames[i] = n == null ? "" : n;
|
||||
padIds[i] = n == null ? "" : String.format("%04x:%04x", NativeBridge.vids[i], NativeBridge.pids[i]);
|
||||
Bundle h = NativeBridge.hookupIdentity[i];
|
||||
hookNames[i] = h == null ? "" : h.getString("name", "");
|
||||
hookIds[i] = h == null ? "" : String.format("%04x:%04x", h.getInt("vid"), h.getInt("pid"));
|
||||
}
|
||||
b.putStringArray("padNames", padNames);
|
||||
b.putStringArray("padIds", padIds);
|
||||
b.putIntArray("padBattery", lastBattery.clone());
|
||||
b.putStringArray("hookNames", hookNames);
|
||||
b.putStringArray("hookIds", hookIds);
|
||||
synchronized (calibLock) { b.putInt("calibrating", calibPlayer); }
|
||||
// global settings
|
||||
b.putInt("presentAs", Settings.presentAs);
|
||||
b.putBoolean("driverEnabled", Settings.driverEnabled);
|
||||
b.putBoolean("forceUsb", Settings.forceUsb);
|
||||
b.putInt("pollMs", Settings.pollMs);
|
||||
b.putBoolean("bubble", Settings.bubble);
|
||||
// choices
|
||||
b.putStringArray("presentNames", Settings.PRESENT_NAMES);
|
||||
b.putStringArray("rateNames", Settings.RATE_NAMES);
|
||||
b.putIntArray("rateMs", Settings.RATE_MS);
|
||||
b.putStringArray("touchNames", Settings.TOUCH_NAMES);
|
||||
b.putStringArray("srcNames", Settings.SRC_NAMES);
|
||||
b.putStringArray("remapTargets", Settings.REMAP_TARGETS);
|
||||
b.putStringArray("axisNames", Settings.AXIS_NAMES);
|
||||
b.putStringArray("gyroInvNames", Settings.GYRO_INV_NAMES);
|
||||
b.putStringArray("playerLedNames", Settings.PLAYER_NAMES);
|
||||
// per player (index p, or p * n + i for the ones with several entries)
|
||||
int P = Settings.PLAYERS;
|
||||
int[] gyroMap = new int[P * 3], remap = new int[P * Settings.REMAP_COUNT];
|
||||
float[] bias = new float[P * 3];
|
||||
for (int p = 0; p < P; p++) {
|
||||
for (int i = 0; i < 3; i++) { gyroMap[p * 3 + i] = Settings.gyroMap[p][i]; bias[p * 3 + i] = Settings.gyroBias[p][i]; }
|
||||
for (int i = 0; i < Settings.REMAP_COUNT; i++) remap[p * Settings.REMAP_COUNT + i] = Settings.remap[p][i];
|
||||
}
|
||||
b.putIntArray("touchMode", Settings.touchMode.clone());
|
||||
b.putBooleanArray("touchInvX", Settings.touchInvX.clone());
|
||||
b.putBooleanArray("touchInvY", Settings.touchInvY.clone());
|
||||
b.putBooleanArray("touchSwap", Settings.touchSwap.clone());
|
||||
b.putIntArray("gyroGain", Settings.gyroGain.clone());
|
||||
b.putIntArray("gyroInvert", Settings.gyroInvert.clone());
|
||||
b.putIntArray("gyroDeadzone", Settings.gyroDeadzone.clone());
|
||||
b.putIntArray("gyroMap", gyroMap);
|
||||
b.putFloatArray("gyroBias", bias);
|
||||
b.putBooleanArray("accelFollows", Settings.accelFollows.clone());
|
||||
b.putIntArray("remap", remap);
|
||||
b.putIntArray("lightR", Settings.lightR.clone());
|
||||
b.putIntArray("lightG", Settings.lightG.clone());
|
||||
b.putIntArray("lightB", Settings.lightB.clone());
|
||||
b.putIntArray("brightness", Settings.brightness.clone());
|
||||
b.putIntArray("playerLed", Settings.playerLed.clone());
|
||||
return b;
|
||||
}
|
||||
|
||||
private static int clampInt(int v, int lo, int hi) { return Math.max(lo, Math.min(hi, v)); }
|
||||
|
||||
/** One change from DroidDeck's tab, with the same effect as the same change on this app's own screen. */
|
||||
private void applyRemote(Bundle d) {
|
||||
if (d == null) return;
|
||||
String key = d.getString("key", "");
|
||||
int p = clampInt(d.getInt("p", 0), 0, Settings.PLAYERS - 1);
|
||||
int i = d.getInt("i", 0);
|
||||
int v = d.getInt("int", 0);
|
||||
boolean on = d.getBoolean("bool", false);
|
||||
switch (key) {
|
||||
case "presentAs":
|
||||
Settings.presentAs = clampInt(v, 0, Settings.PRESENT_NAMES.length - 1);
|
||||
if (!Settings.isHookup()) Settings.lastPresentAs = Settings.presentAs;
|
||||
Settings.save();
|
||||
NativeBridge.applyHookup();
|
||||
updateBubble();
|
||||
break;
|
||||
case "driverEnabled":
|
||||
if (Settings.driverEnabled != on) toggleDriver();
|
||||
break;
|
||||
case "forceUsb":
|
||||
Settings.forceUsb = on;
|
||||
Settings.save();
|
||||
NativeBridge.applyForce();
|
||||
break;
|
||||
case "pollMs":
|
||||
Settings.pollMs = clampInt(v, 1, 16);
|
||||
Settings.save();
|
||||
NativeBridge.applyRate();
|
||||
break;
|
||||
case "bubble":
|
||||
if (on && !android.provider.Settings.canDrawOverlays(this)) break; // needs the permission first
|
||||
Settings.bubble = on;
|
||||
Settings.save();
|
||||
if (on) showBubble(); else hideBubble();
|
||||
break;
|
||||
case "touchMode": Settings.touchMode[p] = clampInt(v, 0, 2); Settings.save(); break;
|
||||
case "touchInvX": Settings.touchInvX[p] = on; Settings.save(); break;
|
||||
case "touchInvY": Settings.touchInvY[p] = on; Settings.save(); break;
|
||||
case "touchSwap": Settings.touchSwap[p] = on; Settings.save(); break;
|
||||
case "gyroGain": Settings.gyroGain[p] = clampInt(v, 1, 800); Settings.save(); break;
|
||||
case "gyroInvert": Settings.gyroInvert[p] = clampInt(v, 0, 7); Settings.save(); break;
|
||||
case "gyroDeadzone": Settings.gyroDeadzone[p] = clampInt(v, 0, 50); Settings.save(); break;
|
||||
case "gyroMap":
|
||||
if (i >= 0 && i < 3) { Settings.gyroMap[p][i] = clampInt(v, 0, 2); Settings.save(); }
|
||||
break;
|
||||
case "accelFollows": Settings.accelFollows[p] = on; Settings.save(); break;
|
||||
case "remap":
|
||||
if (i >= 0 && i < Settings.REMAP_COUNT) { Settings.remap[p][i] = clampInt(v, 0, Settings.SRC_NAMES.length - 1); Settings.save(); }
|
||||
break;
|
||||
case "lightR": Settings.lightR[p] = clampInt(v, 0, 255); Settings.save(); NativeBridge.applyOutput(p); break;
|
||||
case "lightG": Settings.lightG[p] = clampInt(v, 0, 255); Settings.save(); NativeBridge.applyOutput(p); break;
|
||||
case "lightB": Settings.lightB[p] = clampInt(v, 0, 255); Settings.save(); NativeBridge.applyOutput(p); break;
|
||||
case "brightness": Settings.brightness[p] = clampInt(v, 0, 100); Settings.save(); NativeBridge.applyOutput(p); break;
|
||||
case "playerLed": Settings.playerLed[p] = clampInt(v, 0, 4); Settings.save(); NativeBridge.applyOutput(p); break;
|
||||
case "calibrate": startCalibration(p); break;
|
||||
case "resetCalibration":
|
||||
synchronized (calibLock) { if (calibPlayer == p) calibPlayer = -1; }
|
||||
Settings.gyroBias[p][0] = Settings.gyroBias[p][1] = Settings.gyroBias[p][2] = 0f;
|
||||
Settings.save();
|
||||
break;
|
||||
default:
|
||||
android.util.Log.w("SDL3Bridge", "settings: unknown key from DroidDeck: " + key);
|
||||
}
|
||||
}
|
||||
|
||||
private void sendOne(Messenger c, int what, Bundle b) {
|
||||
try {
|
||||
Message m = Message.obtain(null, what);
|
||||
m.setData(b);
|
||||
c.send(m);
|
||||
} catch (RemoteException e) { clients.remove(c); clientCount = clients.size(); }
|
||||
}
|
||||
|
||||
private void sendAll(int what, Bundle b) {
|
||||
for (Messenger c : clients) {
|
||||
try {
|
||||
Message m = Message.obtain(null, what);
|
||||
m.setData(b);
|
||||
c.send(m);
|
||||
} catch (RemoteException e) { clients.remove(c); clientCount = clients.size(); }
|
||||
}
|
||||
}
|
||||
|
||||
@Override public void onStatus(String s) {
|
||||
connectedState = s != null && s.startsWith("Connected");
|
||||
updateBubble();
|
||||
main.post(() -> refreshNotification(s));
|
||||
for (Messenger c : clients) sendStatus(c, s);
|
||||
}
|
||||
|
||||
private void sendStatus(Messenger c, String s) {
|
||||
try {
|
||||
Bundle b = new Bundle();
|
||||
b.putString("text", s);
|
||||
Message m = Message.obtain(null, MSG_STATUS);
|
||||
m.setData(b);
|
||||
c.send(m);
|
||||
} catch (RemoteException e) { clients.remove(c); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
package com.example.dsedge;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.RectF;
|
||||
import android.view.View;
|
||||
|
||||
/**
|
||||
* Universal live gamepad diagram for any SDL3 controller (DualSense / Edge, Xbox, Switch Pro,
|
||||
* Steam Controller 2015 & 2026, generic pads). It draws only the controls the controller actually
|
||||
* reports (via NativeBridge caps) and labels the face / menu buttons for the controller kind.
|
||||
*
|
||||
* Orange = held now, green = pressed at least once (works), grey = present but untested.
|
||||
*/
|
||||
public class ControllerView extends View {
|
||||
private static final int ORANGE = 0xFFFF9800, GREEN = 0xFF2E7D32, GRAY = 0xFF37474F, LINE = 0xFF90A4AE;
|
||||
|
||||
// frame-mask bit numbers
|
||||
private static final int B_SOUTH = 0, B_EAST = 1, B_WEST = 2, B_NORTH = 3, B_L1 = 4, B_R1 = 5,
|
||||
B_L2 = 6, B_R2 = 7, B_BACK = 8, B_START = 9, B_L3 = 10, B_R3 = 11, B_GUIDE = 12,
|
||||
B_TOUCH = 13, B_MISC = 14, B_UP = 15, B_DOWN = 16, B_LEFT = 17, B_RIGHT = 18,
|
||||
B_P1 = 19, B_P2 = 20, B_P3 = 21, B_P4 = 22;
|
||||
|
||||
// tested-flag bits (not button bits)
|
||||
private static final int T_LS = 1, T_RS = 2, T_L2 = 4, T_R2 = 8, T_GYRO = 16, T_ACCEL = 32, T_TOUCH = 64;
|
||||
|
||||
private final Paint fill = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
private final Paint stroke = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
private final Paint text = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
private final RectF rect = new RectF();
|
||||
|
||||
private volatile float[] frame = new float[NativeBridge.FRAME_LEN];
|
||||
private volatile int mask;
|
||||
private volatile int testedButtons;
|
||||
private volatile int testedFlags;
|
||||
private volatile boolean connected;
|
||||
private long lastInvalidate;
|
||||
|
||||
// capabilities (default: assume everything until the controller reports otherwise)
|
||||
private volatile int present = (1 << 23) - 1;
|
||||
private volatile int axes = 0xF;
|
||||
private volatile int touchpads = 1;
|
||||
private volatile String kind = "generic";
|
||||
|
||||
public ControllerView(Context c) {
|
||||
super(c);
|
||||
setBackgroundColor(0xFF111111);
|
||||
stroke.setStyle(Paint.Style.STROKE);
|
||||
stroke.setStrokeWidth(0.5f);
|
||||
text.setTextAlign(Paint.Align.CENTER);
|
||||
text.setColor(0xFFECEFF1);
|
||||
frame[1] = frame[2] = frame[3] = frame[4] = 128f;
|
||||
}
|
||||
|
||||
/** Capabilities of the displayed controller, from the native layer. */
|
||||
public void setCaps(int present, int axes, int touchpads, String kind) {
|
||||
this.present = present;
|
||||
this.axes = axes;
|
||||
this.touchpads = touchpads;
|
||||
this.kind = kind == null ? "generic" : kind;
|
||||
postInvalidate();
|
||||
}
|
||||
|
||||
/** Called from any thread with each native frame. */
|
||||
public void update(float[] f) {
|
||||
if (f == null || f.length < NativeBridge.FRAME_LEN) return;
|
||||
float[] c = f.clone();
|
||||
frame = c;
|
||||
connected = true;
|
||||
int m = (int) c[0];
|
||||
mask = m;
|
||||
testedButtons |= m;
|
||||
int t = testedFlags;
|
||||
if (Math.abs(c[1] - 128f) > 60f || Math.abs(c[2] - 128f) > 60f) t |= T_LS;
|
||||
if (Math.abs(c[3] - 128f) > 60f || Math.abs(c[4] - 128f) > 60f) t |= T_RS;
|
||||
if (c[5] > 100f) t |= T_L2;
|
||||
if (c[6] > 100f) t |= T_R2;
|
||||
if (Math.abs(c[7]) + Math.abs(c[8]) + Math.abs(c[9]) > 0.6f) t |= T_GYRO;
|
||||
if (Math.abs(c[10]) + Math.abs(c[11]) + Math.abs(c[12]) > 3f) t |= T_ACCEL;
|
||||
if (c[13] > 0.5f || c[16] > 0.5f) t |= T_TOUCH;
|
||||
testedFlags = t;
|
||||
long now = System.nanoTime();
|
||||
if (now - lastInvalidate > 16_000_000L) {
|
||||
lastInvalidate = now;
|
||||
postInvalidate();
|
||||
}
|
||||
}
|
||||
|
||||
public void setDisconnected() { connected = false; mask = 0; postInvalidate(); }
|
||||
|
||||
public void resetTested() { testedButtons = 0; testedFlags = 0; postInvalidate(); }
|
||||
|
||||
/** One-line summary of what has been verified so far (only counts controls the pad has). */
|
||||
public String summary() {
|
||||
int p = present & ((1 << 23) - 1);
|
||||
int n = Integer.bitCount(p);
|
||||
int done = Integer.bitCount(testedButtons & p);
|
||||
int t = testedFlags;
|
||||
StringBuilder sb = new StringBuilder("Tested: buttons ").append(done).append('/').append(n);
|
||||
if ((axes & 1) != 0 || (axes & 2) != 0) sb.append(" sticks ").append(mark(stickOk(t)));
|
||||
if ((axes & 12) != 0) sb.append(" triggers ").append(mark(trigOk(t)));
|
||||
sb.append(" gyro ").append(mark((t & T_GYRO) != 0));
|
||||
sb.append(" accel ").append(mark((t & T_ACCEL) != 0));
|
||||
if (touchpads > 0) sb.append(" touchpad ").append(mark((t & T_TOUCH) != 0));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private boolean stickOk(int t) {
|
||||
boolean l = (axes & 1) == 0 || (t & T_LS) != 0;
|
||||
boolean r = (axes & 2) == 0 || (t & T_RS) != 0;
|
||||
return l && r;
|
||||
}
|
||||
|
||||
private boolean trigOk(int t) {
|
||||
boolean l = (axes & 4) == 0 || (t & T_L2) != 0;
|
||||
boolean r = (axes & 8) == 0 || (t & T_R2) != 0;
|
||||
return l && r;
|
||||
}
|
||||
|
||||
private static String mark(boolean ok) { return ok ? "OK" : "-"; }
|
||||
|
||||
@Override protected void onMeasure(int w, int h) {
|
||||
int width = MeasureSpec.getSize(w);
|
||||
setMeasuredDimension(width, (int) (width * 0.82f));
|
||||
}
|
||||
|
||||
// ---------------- labels per controller kind ----------------
|
||||
|
||||
private String[] faceLabels() {
|
||||
switch (kind) {
|
||||
case "ps": return new String[] {"✕", "●", "■", "▲"}; // ✕ ● ■ ▲
|
||||
case "nintendo": return new String[] {"B", "A", "Y", "X"};
|
||||
default: return new String[] {"A", "B", "X", "Y"}; // xbox / steam / generic
|
||||
}
|
||||
}
|
||||
|
||||
private String backLabel() { switch (kind) { case "ps": return "Create"; case "xbox": return "View"; case "nintendo": return "-"; case "steam": return "Back"; default: return "Back"; } }
|
||||
private String startLabel() { switch (kind) { case "ps": return "Options"; case "xbox": return "Menu"; case "nintendo": return "+"; case "steam": return "Start"; default: return "Start"; } }
|
||||
private String guideLabel() { switch (kind) { case "ps": return "PS"; case "nintendo": return "Home"; case "steam": return "Steam"; default: return "Guide"; } }
|
||||
private String miscLabel() { switch (kind) { case "ps": return "Mute"; case "xbox": return "Share"; case "nintendo": return "Capt"; default: return "Misc"; } }
|
||||
|
||||
// ---------------- drawing (100 x 72 unit canvas) ----------------
|
||||
|
||||
private boolean has(int bit) { return ((present >> bit) & 1) != 0; }
|
||||
|
||||
private int col(int bit) {
|
||||
if (((mask >> bit) & 1) != 0) return ORANGE;
|
||||
if (((testedButtons >> bit) & 1) != 0) return GREEN;
|
||||
return GRAY;
|
||||
}
|
||||
|
||||
private void label(Canvas c, String s, float x, float y, float size) {
|
||||
text.setTextSize(size);
|
||||
c.drawText(s, x, y + size * 0.35f, text);
|
||||
}
|
||||
|
||||
/** Rounded rectangle button, drawn only if present. */
|
||||
private void rbtn(Canvas c, float l, float t, float r, float b, int bit, String s) {
|
||||
if (!has(bit)) return;
|
||||
rect.set(l, t, r, b);
|
||||
fill.setColor(col(bit));
|
||||
c.drawRoundRect(rect, 1f, 1f, fill);
|
||||
stroke.setColor(LINE);
|
||||
c.drawRoundRect(rect, 1f, 1f, stroke);
|
||||
if (s != null && !s.isEmpty()) label(c, s, (l + r) / 2f, (t + b) / 2f, 2.2f);
|
||||
}
|
||||
|
||||
private void cbtn(Canvas c, float cx, float cy, float rad, int bit, String s) {
|
||||
if (!has(bit)) return;
|
||||
fill.setColor(col(bit));
|
||||
c.drawCircle(cx, cy, rad, fill);
|
||||
stroke.setColor(LINE);
|
||||
c.drawCircle(cx, cy, rad, stroke);
|
||||
label(c, s, cx, cy, 2.4f);
|
||||
}
|
||||
|
||||
private void meter(Canvas c, float l, float t, float r, float b, float value01, boolean tested) {
|
||||
rect.set(l, t, r, b);
|
||||
fill.setColor(0xFF263238);
|
||||
c.drawRect(rect, fill);
|
||||
rect.set(l, t, l + (r - l) * Math.max(0f, Math.min(1f, value01)), b);
|
||||
fill.setColor(value01 > 0.02f ? ORANGE : (tested ? GREEN : GRAY));
|
||||
c.drawRect(rect, fill);
|
||||
rect.set(l, t, r, b);
|
||||
stroke.setColor(LINE);
|
||||
c.drawRect(rect, stroke);
|
||||
}
|
||||
|
||||
private void stick(Canvas c, float cx, float cy, float x, float y, int clickBit, boolean tested) {
|
||||
boolean clickable = has(clickBit);
|
||||
boolean down = clickable && ((mask >> clickBit) & 1) != 0;
|
||||
stroke.setColor(down ? ORANGE : (tested ? 0xFF66BB6A : LINE));
|
||||
stroke.setStrokeWidth(1f);
|
||||
c.drawCircle(cx, cy, 9f, stroke);
|
||||
stroke.setStrokeWidth(0.5f);
|
||||
fill.setColor(down ? ORANGE : (tested ? GREEN : GRAY));
|
||||
float dx = (x - 128f) / 128f * 6f, dy = (y - 128f) / 128f * 6f;
|
||||
c.drawCircle(cx + dx, cy + dy, 3.6f, fill);
|
||||
}
|
||||
|
||||
@Override protected void onDraw(Canvas c) {
|
||||
super.onDraw(c);
|
||||
float u = getWidth() / 100f;
|
||||
c.save();
|
||||
c.scale(u, u);
|
||||
float[] f = frame;
|
||||
int t = testedFlags;
|
||||
String[] fl = faceLabels();
|
||||
|
||||
// shoulders + triggers
|
||||
if ((axes & 4) != 0) meter(c, 6, 1, 30, 4, f[5] / 255f, (t & T_L2) != 0); else rbtn(c, 6, 1, 30, 4, B_L2, "L2");
|
||||
if ((axes & 8) != 0) meter(c, 70, 1, 94, 4, f[6] / 255f, (t & T_R2) != 0); else rbtn(c, 70, 1, 94, 4, B_R2, "R2");
|
||||
rbtn(c, 6, 5.5f, 30, 10, B_L1, "L1");
|
||||
rbtn(c, 70, 5.5f, 94, 10, B_R1, "R1");
|
||||
|
||||
drawTouchpads(c);
|
||||
|
||||
rbtn(c, 27, 14, 36, 18, B_BACK, backLabel());
|
||||
rbtn(c, 64, 14, 73, 18, B_START, startLabel());
|
||||
rbtn(c, 45, 36, 55, 39.5f, B_MISC, miscLabel());
|
||||
cbtn(c, 50, 44, 2.8f, B_GUIDE, guideLabel());
|
||||
|
||||
// d-pad
|
||||
if (has(B_UP) || has(B_DOWN) || has(B_LEFT) || has(B_RIGHT)) {
|
||||
rbtn(c, 18, 20, 22, 24, B_UP, "");
|
||||
rbtn(c, 18, 32, 22, 36, B_DOWN, "");
|
||||
rbtn(c, 14, 26, 18, 30, B_LEFT, "");
|
||||
rbtn(c, 22, 26, 26, 30, B_RIGHT, "");
|
||||
label(c, "D-pad", 20, 40, 2.2f);
|
||||
}
|
||||
|
||||
// face buttons (diamond): N top, S bottom, W left, E right
|
||||
cbtn(c, 80, 21, 3.2f, B_NORTH, fl[3]);
|
||||
cbtn(c, 80, 35, 3.2f, B_SOUTH, fl[0]);
|
||||
cbtn(c, 73, 28, 3.2f, B_WEST, fl[2]);
|
||||
cbtn(c, 87, 28, 3.2f, B_EAST, fl[1]);
|
||||
|
||||
// sticks
|
||||
if ((axes & 1) != 0) { stick(c, 34, 53, f[1], f[2], B_L3, (t & T_LS) != 0); label(c, has(B_L3) ? "L3" : "L", 34, 64.5f, 2.2f); }
|
||||
if ((axes & 2) != 0) { stick(c, 66, 53, f[3], f[4], B_R3, (t & T_RS) != 0); label(c, has(B_R3) ? "R3" : "R", 66, 64.5f, 2.2f); }
|
||||
|
||||
// paddles / grips
|
||||
rbtn(c, 1.5f, 40, 6.5f, 56, B_P1, "L4");
|
||||
rbtn(c, 93.5f, 40, 98.5f, 56, B_P2, "R4");
|
||||
rbtn(c, 9, 60, 21, 64.5f, B_P3, "L5");
|
||||
rbtn(c, 79, 60, 91, 64.5f, B_P4, "R5");
|
||||
|
||||
// ---- bottom readout strip (own background + divider, clear of the diagram) ----
|
||||
rect.set(0, 66.5f, 100, getHeight() / u);
|
||||
fill.setColor(0xFF0B0E13);
|
||||
c.drawRect(rect, fill);
|
||||
stroke.setColor(0xFF2A3340);
|
||||
c.drawLine(3, 66.5f, 97, 66.5f, stroke);
|
||||
|
||||
String s1 = connected
|
||||
? String.format(java.util.Locale.ROOT, "%s · Gyro %.0f, %.0f, %.0f °/s",
|
||||
kindName(), f[7] * 57.29578f, f[8] * 57.29578f, f[9] * 57.29578f)
|
||||
: "No controller connected";
|
||||
String s2 = connected
|
||||
? String.format(java.util.Locale.ROOT, "Accel %.2f, %.2f, %.2f g · Battery %d%%",
|
||||
f[10] / 9.80665f, f[11] / 9.80665f, f[12] / 9.80665f, (int) Math.max(0f, f[19]))
|
||||
: "";
|
||||
label(c, s1, 50, 71.3f, 2.6f);
|
||||
if (!s2.isEmpty()) label(c, s2, 50, 76.3f, 2.6f);
|
||||
|
||||
c.restore();
|
||||
}
|
||||
|
||||
private String kindName() {
|
||||
switch (kind) {
|
||||
case "ps": return "PlayStation";
|
||||
case "xbox": return "Xbox";
|
||||
case "nintendo": return "Nintendo";
|
||||
case "steam": return "Steam Controller";
|
||||
default: return "Gamepad";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/** Draws 0, 1 or 2 trackpads with their finger dots. */
|
||||
private void drawTouchpads(Canvas c) {
|
||||
float[] f = frame;
|
||||
if (touchpads <= 0) {
|
||||
label(c, "no touchpad", 50, 24, 2.2f);
|
||||
return;
|
||||
}
|
||||
if (touchpads >= 2) {
|
||||
padRect(c, 30, 12, 48, 34, "L pad", B_TOUCH);
|
||||
padRect(c, 52, 12, 70, 34, "R pad", B_TOUCH);
|
||||
fingerOnRect(c, 30, 48, 12, 34, 0, 0xFFFFFFFF); // finger slot 0 -> left pad
|
||||
fingerOnRect(c, 52, 70, 12, 34, 1, 0xFF4FC3F7); // finger slot 1 -> right pad
|
||||
return;
|
||||
}
|
||||
// single touchpad
|
||||
padRect(c, 36, 12, 64, 34, null, B_TOUCH);
|
||||
if (Settings.touchMode[0] == Settings.TOUCH_SPLIT) {
|
||||
stroke.setColor(LINE);
|
||||
c.drawLine(50, 12, 50, 34, stroke);
|
||||
label(c, "L pad", 43, 32.5f, 2f);
|
||||
label(c, "R pad", 57, 32.5f, 2f);
|
||||
} else if (Settings.touchMode[0] == Settings.TOUCH_OFF) {
|
||||
label(c, "touchpad off", 50, 32.5f, 2f);
|
||||
} else {
|
||||
label(c, "whole pad", 50, 32.5f, 2f);
|
||||
}
|
||||
fingerOnRect(c, 36, 64, 12, 34, 0, 0xFFFFFFFF);
|
||||
fingerOnRect(c, 36, 64, 12, 34, 1, 0xFF4FC3F7);
|
||||
}
|
||||
|
||||
private void padRect(Canvas c, float l, float t, float r, float b, String lbl, int bit) {
|
||||
rect.set(l, t, r, b);
|
||||
fill.setColor(((mask >> bit) & 1) != 0 ? ORANGE : (((testedButtons >> bit) & 1) != 0 ? GREEN : 0xFF263238));
|
||||
c.drawRoundRect(rect, 2f, 2f, fill);
|
||||
stroke.setColor(LINE);
|
||||
c.drawRoundRect(rect, 2f, 2f, stroke);
|
||||
if (lbl != null) label(c, lbl, (l + r) / 2f, b - 1.5f, 2f);
|
||||
}
|
||||
|
||||
private void fingerOnRect(Canvas c, float l, float r, float t, float b, int fingerSlot, int color) {
|
||||
float[] f = frame;
|
||||
if (f[13 + 3 * fingerSlot] <= 0.5f) return;
|
||||
float nx = f[14 + 3 * fingerSlot] / 1919f, ny = f[15 + 3 * fingerSlot] / 1079f;
|
||||
if (Settings.touchInvX[0]) nx = 1f - nx;
|
||||
if (Settings.touchInvY[0]) ny = 1f - ny;
|
||||
fill.setColor(color);
|
||||
c.drawCircle(l + nx * (r - l), t + ny * (b - t), 1.8f, fill);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package com.example.dsedge;
|
||||
|
||||
import android.content.Context;
|
||||
import android.hardware.usb.UsbConstants;
|
||||
import android.hardware.usb.UsbDevice;
|
||||
import android.hardware.usb.UsbDeviceConnection;
|
||||
import android.hardware.usb.UsbInterface;
|
||||
import android.hardware.usb.UsbManager;
|
||||
import android.os.Bundle;
|
||||
import android.util.Log;
|
||||
|
||||
/**
|
||||
* Steam Native Hook-up: everything Steam on Linux reads about a USB HID controller before it picks a driver --
|
||||
* vendor/product id, release number, name, serial, interface and the HID report descriptor -- taken from the
|
||||
* real USB device, so DroidDeck can describe a hidraw node that is indistinguishable from it.
|
||||
*/
|
||||
final class HookupIdentity {
|
||||
private static final String TAG = "SDL3Bridge";
|
||||
|
||||
// Generic Desktop / Gamepad collection with 64-byte vendor in/out reports. Used for controllers that have
|
||||
// no HID descriptor of their own (Xbox controllers speak GIP on a vendor-class interface).
|
||||
private static final byte[] VENDOR_GAMEPAD_DESCRIPTOR = bytes(
|
||||
0x05, 0x01, 0x09, 0x05, 0xa1, 0x01, 0x06, 0x00, 0xff, 0x09, 0x01, 0x15, 0x00, 0x26, 0xff, 0x00,
|
||||
0x75, 0x08, 0x95, 0x40, 0x81, 0x02, 0x09, 0x02, 0x95, 0x40, 0x91, 0x02, 0xc0);
|
||||
|
||||
private HookupIdentity() {}
|
||||
|
||||
/** Report descriptors read before the raw open, by SDL hid path. */
|
||||
private static final java.util.Map<String, byte[]> prefetched = new java.util.concurrent.ConcurrentHashMap<>();
|
||||
/** Report descriptors already read once, by "vid:pid:interface" -- reused when the same controller is handed
|
||||
* over again (hook-up off/on, replug), so the USB device is not asked again while a connection holds it. */
|
||||
private static final java.util.Map<String, byte[]> known = new java.util.concurrent.ConcurrentHashMap<>();
|
||||
/** How the last build() got its descriptor ("prefetched", "remembered", "read", "fallback"). */
|
||||
static volatile String lastSource = "";
|
||||
|
||||
private static String key(String path) {
|
||||
String[] p = path.split("/");
|
||||
int n = p.length;
|
||||
return n >= 3 ? p[n - 3] + ":" + p[n - 2] + ":" + p[n - 1] : path;
|
||||
}
|
||||
|
||||
static void prefetch(Context context, String path) {
|
||||
if (known.containsKey(key(path))) return; // nothing to read: it is remembered
|
||||
try {
|
||||
UsbManager um = (UsbManager) context.getSystemService(Context.USB_SERVICE);
|
||||
UsbDevice dev = um == null ? null : um.getDeviceList().get(deviceName(path));
|
||||
int index = ifaceIndex(path);
|
||||
if (dev == null || index < 0 || index >= dev.getInterfaceCount()) return;
|
||||
UsbInterface f = dev.getInterface(index);
|
||||
if (f.getInterfaceClass() != UsbConstants.USB_CLASS_HID) return;
|
||||
byte[] d = readWithTimeout(um, dev, f);
|
||||
if (d != null) { prefetched.put(path, d); known.put(key(path), d); }
|
||||
Log.i(TAG, "hookup: report descriptor of " + path + ": " + (d == null ? "unreadable" : d.length + " bytes"));
|
||||
} catch (RuntimeException e) {
|
||||
Log.w(TAG, "hookup: descriptor prefetch failed: " + e);
|
||||
}
|
||||
}
|
||||
|
||||
private static String deviceName(String path) {
|
||||
String n = path;
|
||||
for (int i = 0; i < 3 && n.lastIndexOf('/') > 0; i++) n = n.substring(0, n.lastIndexOf('/'));
|
||||
return n;
|
||||
}
|
||||
|
||||
private static int ifaceIndex(String path) {
|
||||
try { return Integer.parseInt(path.substring(path.lastIndexOf('/') + 1)); } catch (RuntimeException e) { return -1; }
|
||||
}
|
||||
|
||||
private static byte[] bytes(int... v) {
|
||||
byte[] b = new byte[v.length];
|
||||
for (int i = 0; i < v.length; i++) b[i] = (byte) v[i];
|
||||
return b;
|
||||
}
|
||||
|
||||
/** SDL's Android HID path is "<usb device name>/<vid hex>/<pid hex>/<interface index>". */
|
||||
static Bundle build(Context context, int slot, String path, int vid, int pid, int ifaceIndex) {
|
||||
Bundle b = new Bundle();
|
||||
b.putInt("slot", slot);
|
||||
b.putInt("vid", vid);
|
||||
b.putInt("pid", pid);
|
||||
b.putInt("bus", 3);
|
||||
String name = String.format("Controller %04x:%04x", vid, pid);
|
||||
String manufacturer = "", product = "", serial = "";
|
||||
int ifaceNumber = ifaceIndex, ifaceClass = UsbConstants.USB_CLASS_HID, ifaceSub = 0, ifaceProto = 0, version = 0x0100;
|
||||
byte[] descriptor = null;
|
||||
try {
|
||||
UsbManager um = (UsbManager) context.getSystemService(Context.USB_SERVICE);
|
||||
UsbDevice dev = um == null ? null : um.getDeviceList().get(deviceName(path));
|
||||
if (dev != null) {
|
||||
if (ifaceIndex >= 0 && ifaceIndex < dev.getInterfaceCount()) {
|
||||
UsbInterface f = dev.getInterface(ifaceIndex);
|
||||
ifaceNumber = f.getId();
|
||||
ifaceClass = f.getInterfaceClass();
|
||||
ifaceSub = f.getInterfaceSubclass();
|
||||
ifaceProto = f.getInterfaceProtocol();
|
||||
}
|
||||
try { manufacturer = nz(dev.getManufacturerName()); } catch (SecurityException ignored) { }
|
||||
try { product = nz(dev.getProductName()); } catch (SecurityException ignored) { }
|
||||
try { serial = nz(dev.getSerialNumber()); } catch (SecurityException ignored) { }
|
||||
version = parseBcd(dev.getVersion());
|
||||
descriptor = prefetched.remove(path);
|
||||
if (descriptor != null) lastSource = "prefetched";
|
||||
if (descriptor == null && (descriptor = known.get(key(path))) != null) lastSource = "remembered";
|
||||
if (descriptor == null && ifaceClass == UsbConstants.USB_CLASS_HID && ifaceIndex >= 0 && ifaceIndex < dev.getInterfaceCount()) {
|
||||
descriptor = readWithTimeout(um, dev, dev.getInterface(ifaceIndex));
|
||||
if (descriptor != null) { known.put(key(path), descriptor); lastSource = "read"; }
|
||||
}
|
||||
String joined = (manufacturer.isEmpty() || product.startsWith(manufacturer)) ? product : manufacturer + " " + product;
|
||||
if (!joined.trim().isEmpty()) name = joined.trim();
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
Log.w(TAG, "hookup: identity of " + path + " incomplete: " + e);
|
||||
}
|
||||
if (descriptor == null || descriptor.length == 0) { descriptor = VENDOR_GAMEPAD_DESCRIPTOR; lastSource = "fallback"; }
|
||||
b.putInt("version", version);
|
||||
b.putInt("iface", ifaceNumber);
|
||||
b.putInt("ifclass", ifaceClass);
|
||||
b.putInt("ifsub", ifaceSub);
|
||||
b.putInt("ifproto", ifaceProto);
|
||||
b.putString("name", name);
|
||||
b.putString("manufacturer", manufacturer);
|
||||
b.putString("product", product.isEmpty() ? name : product);
|
||||
b.putString("serial", serial);
|
||||
b.putByteArray("desc", descriptor);
|
||||
Log.i(TAG, String.format("hookup: slot %d = %04x:%04x \"%s\" interface %d class %d, descriptor %d bytes",
|
||||
slot, vid, pid, name, ifaceNumber, ifaceClass, descriptor.length));
|
||||
return b;
|
||||
}
|
||||
|
||||
private static String nz(String s) { return s == null ? "" : s.trim(); }
|
||||
|
||||
/** "1.00" / "2.24" -> bcdDevice. */
|
||||
private static int parseBcd(String v) {
|
||||
try {
|
||||
if (v == null) return 0x0100;
|
||||
String[] p = v.split("\\.");
|
||||
int major = Integer.parseInt(p[0], 16), minor = p.length > 1 ? Integer.parseInt(p[1], 16) : 0;
|
||||
return ((major & 0xff) << 8) | (minor & 0xff);
|
||||
} catch (RuntimeException e) {
|
||||
return 0x0100;
|
||||
}
|
||||
}
|
||||
|
||||
/** [readReportDescriptor] on its own thread, given up after 1.5 s: a USB request that never comes back must
|
||||
* not freeze the SDL thread (that would stop every controller until the app is restarted). */
|
||||
private static byte[] readWithTimeout(UsbManager um, UsbDevice dev, UsbInterface iface) {
|
||||
final byte[][] out = new byte[1][];
|
||||
Thread t = new Thread(() -> out[0] = readReportDescriptor(um, dev, iface), "hookup-descriptor");
|
||||
t.setDaemon(true);
|
||||
t.start();
|
||||
try { t.join(1500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
|
||||
if (t.isAlive()) {
|
||||
Log.w(TAG, "hookup: report descriptor read timed out");
|
||||
return null;
|
||||
}
|
||||
return out[0];
|
||||
}
|
||||
|
||||
/** GET_DESCRIPTOR(HID report) on the interface, over a second connection. */
|
||||
private static byte[] readReportDescriptor(UsbManager um, UsbDevice dev, UsbInterface iface) {
|
||||
UsbDeviceConnection c = null;
|
||||
try {
|
||||
c = um.openDevice(dev);
|
||||
if (c == null) return null;
|
||||
byte[] buf = new byte[4096];
|
||||
int ifaceNumber = iface.getId();
|
||||
// Interface-recipient request (the standard one). If another connection holds the interface,
|
||||
// Android refuses it; claim it briefly (nobody holds it right before the raw open), and as a last
|
||||
// resort ask with device recipient, which most controllers answer the same way.
|
||||
int n = c.controlTransfer(0x81, 0x06, 0x2200, ifaceNumber, buf, buf.length, 500);
|
||||
if (n <= 0 && c.claimInterface(iface, false)) {
|
||||
n = c.controlTransfer(0x81, 0x06, 0x2200, ifaceNumber, buf, buf.length, 500);
|
||||
c.releaseInterface(iface);
|
||||
}
|
||||
if (n <= 0) n = c.controlTransfer(0x80, 0x06, 0x2200, ifaceNumber, buf, buf.length, 500);
|
||||
if (n <= 0) return null;
|
||||
byte[] out = new byte[n];
|
||||
System.arraycopy(buf, 0, out, 0, n);
|
||||
return out;
|
||||
} catch (RuntimeException e) {
|
||||
return null;
|
||||
} finally {
|
||||
if (c != null) c.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.example.dsedge;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
/**
|
||||
* Where this bridge runs: as its own app (SDL3Bridge, package com.example.dsedge), or built into SDL3DroidDeck --
|
||||
* the same code, in that app's ":sdl3" process. Built in, its settings are kept under their own names next to
|
||||
* DroidDeck's, and it updates together with SDL3DroidDeck (no update check of its own).
|
||||
*/
|
||||
final class Host {
|
||||
static final String OWN_PACKAGE = "com.example.dsedge";
|
||||
|
||||
private Host() {}
|
||||
|
||||
static boolean embedded(Context c) {
|
||||
return c != null && !OWN_PACKAGE.equals(c.getPackageName());
|
||||
}
|
||||
|
||||
/** A preferences file name of the bridge: unchanged as its own app, prefixed when built into another app. */
|
||||
static String prefs(Context c, String name) {
|
||||
return embedded(c) ? "sdl3bridge_" + name : name;
|
||||
}
|
||||
|
||||
/** The app's name as Android shows it ("SDL3DroidDeck" when built in). */
|
||||
static String appName(Context c) {
|
||||
try {
|
||||
CharSequence label = c.getPackageManager().getApplicationLabel(c.getApplicationInfo());
|
||||
return label != null ? label.toString() : c.getPackageName();
|
||||
} catch (RuntimeException e) {
|
||||
return c.getPackageName();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
package com.example.dsedge;
|
||||
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
/** Glue between the native SDL3 loop (libmain.so) and the Java service. */
|
||||
public final class NativeBridge {
|
||||
public interface Listener {
|
||||
void onFrame(float[] f, int slot);
|
||||
void onStatus(String s);
|
||||
/** The controller in this slot (0..3) was unplugged. */
|
||||
default void onPadGone(int slot) { }
|
||||
/** Capabilities of the controller in this slot: which buttons/axes exist, touchpad count, and kind. */
|
||||
default void onPadCaps(int slot, int present, int axes, int touchpads, String kind) { }
|
||||
/** Steam Controller (2026) raw passthrough: one input report (id + payload without the id byte). */
|
||||
default void onTritonState(int reportId, byte[] payload) { }
|
||||
/** The passed-through Steam Controller (2026) appeared / went away. */
|
||||
default void onTritonConnected(boolean connected, String what) { }
|
||||
/** Answer to a feature read DroidDeck forwarded (null = the controller did not answer). */
|
||||
default void onTritonFeature(long request, byte[] report) { }
|
||||
/** Steam Native Hook-up: a controller was handed to Steam in [slot]; identity = HookupIdentity bundle. */
|
||||
default void onHookupAdded(int slot, android.os.Bundle identity) { }
|
||||
default void onHookupInput(int slot, byte[] report) { }
|
||||
default void onHookupRemoved(int slot) { }
|
||||
default void onHookupReply(int slot, long request, byte[] report) { }
|
||||
/** A line from the bridge's hook-up / passthrough code, for DroidDeck's session log. */
|
||||
default void onBridgeLog(String line) { }
|
||||
}
|
||||
|
||||
/** Layout of the float[] frame sent from native code. */
|
||||
public static final int FRAME_LEN = 22;
|
||||
// 0 mask | 1..4 lx ly rx ry (0..255) | 5,6 l2 r2 (0..255) | 7..9 gyro rad/s | 10..12 accel m/s^2
|
||||
// 13..15 finger0 (down,x,y) | 16..18 finger1 | 19 battery % (-1 unknown) | 20 SDL power state | 21 extra-button mask (MISC2..6)
|
||||
|
||||
static final CopyOnWriteArrayList<Listener> listeners = new CopyOnWriteArrayList<>();
|
||||
static volatile String lastStatus = "Starting...";
|
||||
|
||||
static final int MAX_PADS = 4;
|
||||
/** USB ids and names of the controller in each slot, so DroidDeck can ignore the Android duplicate of it. */
|
||||
static final int[] vids = new int[MAX_PADS], pids = new int[MAX_PADS];
|
||||
static final String[] names = new String[MAX_PADS];
|
||||
|
||||
private NativeBridge() {}
|
||||
|
||||
/** Called from the native SDL thread. */
|
||||
static void onFrame(float[] f, int slot) {
|
||||
for (Listener l : listeners) l.onFrame(f, slot);
|
||||
}
|
||||
|
||||
/** Called from the native SDL thread when a controller is opened in a slot. */
|
||||
static void onPadInfo(int slot, int vid, int pid, String name) {
|
||||
if (slot < 0 || slot >= MAX_PADS) return;
|
||||
vids[slot] = vid;
|
||||
pids[slot] = pid;
|
||||
names[slot] = name;
|
||||
}
|
||||
|
||||
/** Capabilities of each slot's controller (present-button mask, axis flags, touchpad count, kind). */
|
||||
static final int[] present = new int[MAX_PADS];
|
||||
static final int[] axesMask = new int[MAX_PADS];
|
||||
static final int[] touchpadCount = new int[MAX_PADS];
|
||||
static final String[] kind = new String[MAX_PADS];
|
||||
|
||||
/** Called from the native SDL thread when a controller is opened in a slot. */
|
||||
static void onPadCaps(int slot, int p, int a, int tp, String k) {
|
||||
if (slot < 0 || slot >= MAX_PADS) return;
|
||||
present[slot] = p;
|
||||
axesMask[slot] = a;
|
||||
touchpadCount[slot] = tp;
|
||||
kind[slot] = k;
|
||||
for (Listener l : listeners) l.onPadCaps(slot, p, a, tp, k);
|
||||
}
|
||||
|
||||
/** Called from the native SDL thread when a slot's controller goes away. */
|
||||
static void onPadGone(int slot) {
|
||||
if (slot < 0 || slot >= MAX_PADS) return;
|
||||
vids[slot] = 0;
|
||||
pids[slot] = 0;
|
||||
names[slot] = null;
|
||||
for (Listener l : listeners) l.onPadGone(slot);
|
||||
}
|
||||
|
||||
// ---------- Steam Controller (2026) raw passthrough (native/triton.h) ----------
|
||||
static volatile boolean tritonConnected;
|
||||
static volatile String tritonWhat = "";
|
||||
|
||||
/** Called from the native SDL thread for every state report. */
|
||||
static void onTritonState(int reportId, byte[] payload) {
|
||||
for (Listener l : listeners) l.onTritonState(reportId, payload);
|
||||
}
|
||||
|
||||
/** Called from the native SDL thread. */
|
||||
static void onTritonConnected(boolean connected, String what) {
|
||||
tritonConnected = connected;
|
||||
tritonWhat = what == null ? "" : what;
|
||||
for (Listener l : listeners) l.onTritonConnected(connected, tritonWhat);
|
||||
}
|
||||
|
||||
/** Called from the native SDL thread. */
|
||||
static void onTritonFeature(long request, byte[] report) {
|
||||
for (Listener l : listeners) l.onTritonFeature(request, report);
|
||||
}
|
||||
|
||||
/** An output report (feature = false) or a feature-report write (feature = true) from Steam, report id first. */
|
||||
static void tritonOutput(byte[] report, boolean feature) {
|
||||
try { nativeTritonOutput(report, feature); } catch (UnsatisfiedLinkError e) { }
|
||||
}
|
||||
|
||||
static void tritonGetFeature(long request, int reportId) {
|
||||
try { nativeTritonGetFeature(request, reportId); } catch (UnsatisfiedLinkError e) { }
|
||||
}
|
||||
|
||||
/** Game rumble for the passed-through controller, 0..65535 per motor. */
|
||||
static void tritonRumble(int left, int right) {
|
||||
try { nativeTritonRumble(left, right); } catch (UnsatisfiedLinkError e) { }
|
||||
}
|
||||
|
||||
static native void nativeTritonOutput(byte[] report, boolean feature);
|
||||
static native void nativeTritonGetFeature(long request, int reportId);
|
||||
static native void nativeTritonRumble(int left, int right);
|
||||
|
||||
// ---------- Steam Native Hook-up (native/hookup.h) ----------
|
||||
static volatile android.content.Context appContext;
|
||||
static final android.os.Bundle[] hookupIdentity = new android.os.Bundle[MAX_PADS];
|
||||
/** Controllers opened raw by native code: {path, vid, pid, interface}; kept until they are released. */
|
||||
static final Object[][] hookupPending = new Object[MAX_PADS][];
|
||||
|
||||
/** A controller that is open but was never described (that failed): try again, off the SDL thread. */
|
||||
static void retryUndescribed() {
|
||||
for (int i = 0; i < MAX_PADS; i++) {
|
||||
Object[] p = hookupPending[i];
|
||||
if (p == null || hookupIdentity[i] != null) continue;
|
||||
final int slot = i;
|
||||
new Thread(() -> {
|
||||
if (hookupPending[slot] == p && hookupIdentity[slot] == null)
|
||||
onHookupAdded(slot, (String) p[0], (Integer) p[1], (Integer) p[2], (Integer) p[3]);
|
||||
}, "hookup-retry").start();
|
||||
}
|
||||
}
|
||||
|
||||
static void onHookupAdded(int slot, String path, int vid, int pid, int ifaceIndex) {
|
||||
if (slot < 0 || slot >= MAX_PADS) return;
|
||||
hookupPending[slot] = new Object[] { path, vid, pid, ifaceIndex };
|
||||
android.content.Context c = appContext;
|
||||
if (c == null) {
|
||||
onBridgeLog("hookup: slot " + slot + " cannot be described (the app is not fully started); it is retried");
|
||||
return;
|
||||
}
|
||||
long t0 = android.os.SystemClock.uptimeMillis();
|
||||
android.os.Bundle id;
|
||||
try {
|
||||
id = HookupIdentity.build(c, slot, path, vid, pid, ifaceIndex);
|
||||
} catch (Throwable e) {
|
||||
onBridgeLog("hookup: slot " + slot + " could not be described: " + e);
|
||||
return;
|
||||
}
|
||||
hookupIdentity[slot] = id;
|
||||
byte[] d = id.getByteArray("desc");
|
||||
onBridgeLog(String.format(java.util.Locale.US, "hookup: slot %d described in %d ms (descriptor %d bytes, %s); sent to %d DroidDeck connection(s)",
|
||||
slot, android.os.SystemClock.uptimeMillis() - t0, d == null ? 0 : d.length, HookupIdentity.lastSource, clientCount()));
|
||||
for (Listener l : listeners) {
|
||||
try { l.onHookupAdded(slot, id); } catch (RuntimeException e) { android.util.Log.w("SDL3Bridge", "hookup: listener failed: " + e); }
|
||||
}
|
||||
}
|
||||
|
||||
/** DroidDeck connections, for the log (set by BridgeService). */
|
||||
static volatile java.util.function.IntSupplier clients;
|
||||
private static int clientCount() {
|
||||
java.util.function.IntSupplier s = clients;
|
||||
return s == null ? -1 : s.getAsInt();
|
||||
}
|
||||
|
||||
/** Recent bridge log lines (newest last), replayed to DroidDeck when it connects. */
|
||||
static final java.util.ArrayDeque<String> bridgeLog = new java.util.ArrayDeque<>();
|
||||
|
||||
/** Called from the native SDL thread. */
|
||||
static void onBridgeLog(String line) {
|
||||
String stamped = new java.text.SimpleDateFormat("HH:mm:ss.SSS", java.util.Locale.US).format(new java.util.Date()) + " " + line;
|
||||
synchronized (bridgeLog) {
|
||||
bridgeLog.addLast(stamped);
|
||||
while (bridgeLog.size() > 200) bridgeLog.removeFirst();
|
||||
}
|
||||
for (Listener l : listeners) l.onBridgeLog(stamped);
|
||||
}
|
||||
|
||||
/** Called from the native SDL thread just before a controller is opened raw. */
|
||||
static void prefetchHookupDescriptor(String path) {
|
||||
android.content.Context c = appContext;
|
||||
if (c != null) HookupIdentity.prefetch(c, path);
|
||||
}
|
||||
|
||||
static void onHookupInput(int slot, byte[] report) {
|
||||
for (Listener l : listeners) l.onHookupInput(slot, report);
|
||||
}
|
||||
|
||||
static void onHookupRemoved(int slot) {
|
||||
if (slot < 0 || slot >= MAX_PADS) return;
|
||||
hookupPending[slot] = null;
|
||||
hookupIdentity[slot] = null;
|
||||
for (Listener l : listeners) l.onHookupRemoved(slot);
|
||||
}
|
||||
|
||||
static void onHookupReply(int slot, long request, byte[] report) {
|
||||
for (Listener l : listeners) l.onHookupReply(slot, request, report);
|
||||
}
|
||||
|
||||
static void applyHookup() {
|
||||
try { nativeSetHookup(hookupMode()); } catch (UnsatisfiedLinkError e) { }
|
||||
}
|
||||
|
||||
// ---- DroidDeck's desktop: Steam Native Hook-up waits for Steam ----
|
||||
// On DroidDeck's desktop Steam is one program among others and may not be running. DroidDeck says so with each
|
||||
// watchdog sync (every 1.5 s); while it does, hook-up waits: controllers stay ordinary gamepads every program
|
||||
// can use, and are handed to Steam once its client runs. Lapses by itself if DroidDeck stops saying it.
|
||||
private static volatile long steamAwayUntilMs;
|
||||
private static volatile int hookupApplied = -1;
|
||||
|
||||
/** 0 off, 1 on, 2 on but waiting for Steam (DroidDeck's desktop without Steam running). */
|
||||
static int hookupMode() {
|
||||
if (!Settings.isHookup()) return 0;
|
||||
return android.os.SystemClock.uptimeMillis() < steamAwayUntilMs ? 2 : 1;
|
||||
}
|
||||
|
||||
static boolean hookupWaitsForSteam() { return hookupMode() == 2; }
|
||||
|
||||
/** From DroidDeck's sync: is Steam away (its desktop without the Steam client running)? */
|
||||
static void setSteamAway(boolean away) {
|
||||
steamAwayUntilMs = away ? android.os.SystemClock.uptimeMillis() + 10000 : 0;
|
||||
recheckHookup();
|
||||
}
|
||||
|
||||
/** Applies hook-up again if waiting for Steam started or ended (also when the wait lapsed). */
|
||||
static void recheckHookup() {
|
||||
int mode = hookupMode();
|
||||
if (mode == hookupApplied) return;
|
||||
int was = hookupApplied;
|
||||
hookupApplied = mode;
|
||||
if (mode == 2) onBridgeLog("hookup: DroidDeck's desktop has no Steam running: controllers stay ordinary gamepads until it starts");
|
||||
else if (was == 2 && mode == 1) onBridgeLog("hookup: Steam runs on DroidDeck's desktop: controllers are handed to Steam");
|
||||
applyHookup();
|
||||
}
|
||||
|
||||
static void hookupOutput(int slot, int kind, byte[] report) {
|
||||
try { nativeHookupOutput(slot, kind, report); } catch (UnsatisfiedLinkError e) { }
|
||||
}
|
||||
|
||||
static void hookupGet(int slot, long request, int reportId, boolean input, int length) {
|
||||
try { nativeHookupGet(slot, request, reportId, input, length); } catch (UnsatisfiedLinkError e) { }
|
||||
}
|
||||
|
||||
static native void nativeSetHookup(int on);
|
||||
static native int nativeHookupMapShm(int fd);
|
||||
static native long nativeHookupShmInode();
|
||||
|
||||
/** DroidDeck's shared hook-up file (fast path: reports written straight into it). Takes ownership of pfd. */
|
||||
static void hookupMapShm(android.os.ParcelFileDescriptor pfd) {
|
||||
if (pfd == null) return;
|
||||
try { nativeHookupMapShm(pfd.detachFd()); }
|
||||
catch (UnsatisfiedLinkError e) { try { pfd.close(); } catch (java.io.IOException ignored) { } }
|
||||
}
|
||||
|
||||
/** Inode of the mapped (still live) shared file, 0 if none. */
|
||||
static long hookupShmInode() {
|
||||
try { return nativeHookupShmInode(); } catch (UnsatisfiedLinkError e) { return 0; }
|
||||
}
|
||||
static native void nativeHookupOutput(int slot, int kind, byte[] report);
|
||||
static native void nativeHookupGet(int slot, long request, int reportId, boolean input, int length);
|
||||
|
||||
/** Called from the native SDL thread. */
|
||||
static void onStatus(String s) {
|
||||
SdlEngine.onNativeStatus();
|
||||
lastStatus = s;
|
||||
for (Listener l : listeners) l.onStatus(s);
|
||||
}
|
||||
|
||||
/** Rumble for any player slot (0..3). */
|
||||
static void setRumble(int slot, int strong, int weak) {
|
||||
if (slot < 0 || slot >= MAX_PADS) return;
|
||||
try { nativeSetRumble(slot, strong, weak); } catch (UnsatisfiedLinkError e) { }
|
||||
}
|
||||
|
||||
static native void nativeSetRumble(int slot, int rumbleStrong, int rumbleWeak);
|
||||
|
||||
/** Pushes each player's lightbar (scaled by brightness) and player LED to its controller. */
|
||||
static void applyOutput() {
|
||||
try {
|
||||
for (int p = 0; p < MAX_PADS; p++) {
|
||||
int b = Settings.brightness[p];
|
||||
nativeSetLed(p, Settings.lightR[p] * b / 100, Settings.lightG[p] * b / 100, Settings.lightB[p] * b / 100);
|
||||
nativeSetPlayerLed(p, Settings.playerLed[p] - 1); // -1 = player LEDs off
|
||||
}
|
||||
} catch (UnsatisfiedLinkError e) {
|
||||
// The bridge screen has not been opened yet, so the native library is not loaded.
|
||||
}
|
||||
}
|
||||
|
||||
/** Apply just one player's light (on a settings change). */
|
||||
static void applyOutput(int p) {
|
||||
if (p < 0 || p >= MAX_PADS) return;
|
||||
try {
|
||||
int b = Settings.brightness[p];
|
||||
nativeSetLed(p, Settings.lightR[p] * b / 100, Settings.lightG[p] * b / 100, Settings.lightB[p] * b / 100);
|
||||
nativeSetPlayerLed(p, Settings.playerLed[p] - 1);
|
||||
} catch (UnsatisfiedLinkError e) { }
|
||||
}
|
||||
|
||||
/** Forced mode: ignore Android's basic input and only use SDL's own USB driver. */
|
||||
static void applyForce() {
|
||||
try { nativeSetForce(Settings.forceUsb ? 1 : 0); } catch (UnsatisfiedLinkError e) { }
|
||||
}
|
||||
|
||||
static void rescan() {
|
||||
try { nativeRescan(); } catch (UnsatisfiedLinkError e) { }
|
||||
}
|
||||
|
||||
static native void nativeSetForce(int on);
|
||||
|
||||
static native void nativeRescan();
|
||||
|
||||
/** Hard on/off for the SDL3 driver: on = forced SDL3 USB, off = release the controller to Android. */
|
||||
static void applyDriver() {
|
||||
try {
|
||||
nativeSetDriver(Settings.driverEnabled ? 1 : 0);
|
||||
nativeSetHookup(hookupMode());
|
||||
if (Settings.driverEnabled) nativeSetForce(Settings.forceUsb ? 1 : 0);
|
||||
} catch (UnsatisfiedLinkError e) { }
|
||||
}
|
||||
|
||||
static native void nativeSetDriver(int on);
|
||||
|
||||
/** Controller poll rate (loop period in ms). */
|
||||
static void applyRate() {
|
||||
try { nativeSetPollMs(Settings.pollMs); } catch (UnsatisfiedLinkError e) { }
|
||||
}
|
||||
|
||||
static native void nativeSetPollMs(int ms);
|
||||
|
||||
/** Per-slot lightbar rgb 0..255. */
|
||||
static native void nativeSetLed(int slot, int r, int g, int b);
|
||||
|
||||
/** Per-slot player LEDs: -1 = off, 0..3 = player 1..4. */
|
||||
static native void nativeSetPlayerLed(int slot, int index);
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
package com.example.dsedge;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.SharedPreferences;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.os.SystemClock;
|
||||
import android.util.Log;
|
||||
|
||||
import org.libsdl.app.HIDDeviceManager;
|
||||
import org.libsdl.app.SDL;
|
||||
import org.libsdl.app.SDLActivity;
|
||||
|
||||
/**
|
||||
* Where SDL3 runs.
|
||||
*
|
||||
* Normally headless, inside the bridge's background service -- no screen has to open for the bridge to work. It
|
||||
* does what SDL's own SDLActivity does at start-up, minus the window: load the libraries, set up SDL's Java side,
|
||||
* take USB/HID access (HIDDeviceManager), then run SDL_main (main.c) on its own thread. The bridge only uses SDL's
|
||||
* gamepad / joystick / hidapi parts, which need no window.
|
||||
*
|
||||
* SDL's Java side does expect "the app's screen" as its context (SDL.getContext()): SDL3 reads the app's files
|
||||
* and assets through it while it starts (gamepad mappings), and crashes the whole app without one. Headless there
|
||||
* is no screen, so AppContext stands in for it -- an Activity object that is never started or shown, whose calls
|
||||
* all go to the app. The mappings file is also handed to SDL3 directly, so it never needs the assets for it.
|
||||
*
|
||||
* Self-protecting: a marker is saved before every background start and cleared when SDL3's loop reports its first
|
||||
* status. If SDL3 stays silent for 10 s (the process is then restarted), or the app died during the attempt, this
|
||||
* build uses the fallback instead: SDL3 runs inside the bridge's own screen, started when you open SDL3Bridge
|
||||
* (nothing opens by itself). Every step, and the previous run's crash report if there was one, is sent to
|
||||
* DroidDeck's session log ("sdl3bridge: engine: ...").
|
||||
*/
|
||||
final class SdlEngine {
|
||||
private static final String TAG = "SDL3Bridge";
|
||||
private static final long CONFIRM_MS = 10_000;
|
||||
private static volatile boolean started, confirmed, fallback, failed;
|
||||
private static volatile HIDDeviceManager hid;
|
||||
private static long hostStartMs;
|
||||
/** Why SDL3 is not running (shown in the status, the notification and DroidDeck's tab), or null. */
|
||||
static volatile String error;
|
||||
/** How SDL3 runs now, for the status / DroidDeck's tab. */
|
||||
static volatile String mode = "not started";
|
||||
private static String fallbackWhy = "";
|
||||
|
||||
private SdlEngine() {}
|
||||
|
||||
static boolean isRunning() { return started && (fallback ? SdlHostActivity.running : true); }
|
||||
|
||||
private static void log(String line) {
|
||||
Log.i(TAG, line);
|
||||
NativeBridge.onBridgeLog("engine: " + line);
|
||||
}
|
||||
|
||||
private static SharedPreferences prefs(Context c) { return c.getSharedPreferences(Host.prefs(c, "engine"), Context.MODE_PRIVATE); }
|
||||
|
||||
/** Which build this is: the version code, or -- built into SDL3DroidDeck, whose version code stays the same from
|
||||
* build to build -- when it was installed, so a new build tries the background again. */
|
||||
private static long version(Context c) {
|
||||
try {
|
||||
android.content.pm.PackageInfo pi = c.getPackageManager().getPackageInfo(c.getPackageName(), 0);
|
||||
if (Host.embedded(c)) return pi.lastUpdateTime;
|
||||
return android.os.Build.VERSION.SDK_INT >= 28 ? pi.getLongVersionCode() : pi.versionCode;
|
||||
} catch (Exception e) { return 0; }
|
||||
}
|
||||
|
||||
/** Stands in for "the app's screen" in SDL's Java side (see the class comment). Never started or shown. */
|
||||
static final class AppContext extends Activity {
|
||||
AppContext(Context base) { attachBaseContext(base); }
|
||||
}
|
||||
|
||||
private static Activity standIn(Context app) {
|
||||
try {
|
||||
Context base;
|
||||
// its own copy of the app's context, so nothing set on the stand-in reaches the app's real one
|
||||
try { base = app.createConfigurationContext(app.getResources().getConfiguration()); }
|
||||
catch (RuntimeException e) { base = app; }
|
||||
return new AppContext(base);
|
||||
} catch (Throwable e) {
|
||||
log("could not make SDL3's stand-in context (" + e + "); starting without one");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** SDL3's gamepad mappings file (empty unless you add mappings), as an absolute path; null if unavailable. */
|
||||
static String mappingFile(Context c) {
|
||||
try {
|
||||
java.io.File f = new java.io.File(c.getFilesDir(), "gamepad_map.txt");
|
||||
if (!f.exists() && !f.createNewFile()) return null;
|
||||
return f.getAbsolutePath();
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Starts SDL once per process (safe to call again, from any thread). */
|
||||
static void start(Context context) {
|
||||
if (Looper.myLooper() != Looper.getMainLooper()) { // the stand-in context must be made on the main thread
|
||||
new Handler(Looper.getMainLooper()).post(() -> start(context));
|
||||
return;
|
||||
}
|
||||
startOnMain(context);
|
||||
}
|
||||
|
||||
private static synchronized void startOnMain(Context context) {
|
||||
final Context app = context.getApplicationContext();
|
||||
NativeBridge.appContext = app;
|
||||
Settings.init(app);
|
||||
if (started) {
|
||||
if (fallback && !SdlHostActivity.running && context instanceof Activity) startHost((Activity) context);
|
||||
return;
|
||||
}
|
||||
started = true;
|
||||
SharedPreferences p = prefs(app);
|
||||
long ver = version(app);
|
||||
String last = p.getString("state", "");
|
||||
boolean sameBuild = p.getLong("version", -1) == ver;
|
||||
if (sameBuild && (last.equals("starting") || last.startsWith("failed"))) {
|
||||
boolean crashed = last.equals("starting");
|
||||
fallbackWhy = crashed ? "the app stopped while SDL3 was starting in the background" : last.substring(last.indexOf(':') + 1).trim();
|
||||
if (crashed) p.edit().putString("state", "failed: " + fallbackWhy).commit();
|
||||
fallback = true;
|
||||
mode = "the SDL3Bridge screen (fallback)";
|
||||
error = "Open SDL3Bridge once to start SDL3 (it could not run in the background on this phone: " + fallbackWhy + ")";
|
||||
log("SDL3 can't run in the background service with this build (" + fallbackWhy + "). Fallback: SDL3 runs "
|
||||
+ "inside the SDL3Bridge screen -- open SDL3Bridge once (nothing opens by itself). A new build tries "
|
||||
+ "the background again.");
|
||||
if (crashed) forwardPreviousLog();
|
||||
if (context instanceof Activity) startHost((Activity) context);
|
||||
return;
|
||||
}
|
||||
p.edit().putString("state", "starting").putLong("version", ver).commit(); // commit: must survive a crash
|
||||
log("starting SDL3 in the background service (build " + ver + ")");
|
||||
try {
|
||||
System.loadLibrary("SDL3");
|
||||
System.loadLibrary("main");
|
||||
log("libraries loaded");
|
||||
SDL.setupJNI();
|
||||
SDL.initialize(); // (this also clears SDL's context)
|
||||
Activity ctx = standIn(app);
|
||||
if (ctx != null) SDL.setContext(ctx);
|
||||
log("SDL3's Java side ready" + (ctx != null ? " (stand-in context)" : " (no context)"));
|
||||
hid = HIDDeviceManager.acquire(app);
|
||||
hid.setFrozen(!Settings.driverEnabled);
|
||||
log("USB/HID access ready");
|
||||
} catch (Throwable e) {
|
||||
fail(app, "SDL3 could not start: " + e);
|
||||
restartForFallback("SDL3 could not start in the background service");
|
||||
return;
|
||||
}
|
||||
final String main = app.getApplicationInfo().nativeLibraryDir + "/libmain.so";
|
||||
final String map = mappingFile(app);
|
||||
final String[] args = map != null ? new String[] { map } : new String[0];
|
||||
Thread t = new Thread(() -> {
|
||||
try { android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_DISPLAY); } catch (RuntimeException ignored) { }
|
||||
try {
|
||||
SDLActivity.nativeInitMainThread();
|
||||
int rc = SDLActivity.nativeRunMain(main, "SDL_main", args);
|
||||
SDLActivity.nativeCleanupMainThread();
|
||||
fail(app, "SDL3's loop ended (" + rc + ")");
|
||||
} catch (Throwable e) {
|
||||
fail(app, "SDL3 stopped: " + e);
|
||||
}
|
||||
restartForFallback("SDL3's loop is not running");
|
||||
}, "SDLThread");
|
||||
error = null;
|
||||
mode = "background service";
|
||||
t.start();
|
||||
log("SDL3 thread started; waiting for its first status");
|
||||
// Settings the native loop reads (driver, hook-up, rate, lights), as the bridge screen used to apply.
|
||||
NativeBridge.applyDriver();
|
||||
NativeBridge.applyRate();
|
||||
NativeBridge.applyOutput();
|
||||
new Handler(Looper.getMainLooper()).postDelayed(() -> {
|
||||
if (confirmed || fallback || failed) return; // working, or already failed (and restarting)
|
||||
fail(app, "SDL3 did not answer within " + (CONFIRM_MS / 1000) + " s in the background service");
|
||||
restartForFallback("SDL3 did not answer");
|
||||
}, CONFIRM_MS);
|
||||
}
|
||||
|
||||
/** SDL3's loop reported a status: it runs. */
|
||||
static void onNativeStatus() {
|
||||
if (!started) return;
|
||||
if (fallback) {
|
||||
if (error != null && SdlHostActivity.running) {
|
||||
error = null;
|
||||
log("SDL3 is running in the SDL3Bridge screen (fallback); you can leave the screen, it keeps running");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (confirmed) return;
|
||||
confirmed = true;
|
||||
Context c = NativeBridge.appContext;
|
||||
if (c != null) prefs(c).edit().putString("state", "ok").apply();
|
||||
log("SDL3 is running in the background service");
|
||||
}
|
||||
|
||||
/**
|
||||
* The fallback screen was closed for good (its task was swiped away): SDL3 can't be restarted cleanly in the
|
||||
* same process, so the process restarts (DroidDeck's connection brings the service back) and the bridge waits
|
||||
* to be opened again.
|
||||
*/
|
||||
static void onHostGone() {
|
||||
if (!fallback) return;
|
||||
error = "Open SDL3Bridge to start SDL3 again (fallback: " + fallbackWhy + ")";
|
||||
log("the SDL3Bridge screen that ran SDL3 was closed; restarting SDL3Bridge -- open it again to start SDL3");
|
||||
new Handler(Looper.getMainLooper()).postDelayed(
|
||||
() -> android.os.Process.killProcess(android.os.Process.myPid()), 1500);
|
||||
}
|
||||
|
||||
/** The process restarts (DroidDeck's connection brings the service back) and the next start uses the fallback. */
|
||||
private static void restartForFallback(String why) {
|
||||
log(why + "; restarting SDL3Bridge in 2 s so the fallback takes over");
|
||||
new Handler(Looper.getMainLooper()).postDelayed(
|
||||
() -> android.os.Process.killProcess(android.os.Process.myPid()), 2000); // lets the log reach DroidDeck
|
||||
}
|
||||
|
||||
private static void fail(Context app, String why) {
|
||||
failed = true;
|
||||
error = why;
|
||||
Log.e(TAG, why);
|
||||
NativeBridge.onBridgeLog("engine: " + why);
|
||||
prefs(app).edit().putString("state", "failed: " + why).commit();
|
||||
}
|
||||
|
||||
/** Fallback only, and only from the bridge's own screen while you look at it: SDL3's host screen on top of it. */
|
||||
private static void startHost(Activity from) {
|
||||
long now = SystemClock.uptimeMillis();
|
||||
if (hostStartMs != 0 && now - hostStartMs < 5000) return; // never in a loop
|
||||
hostStartMs = now;
|
||||
try {
|
||||
from.startActivity(new Intent(from, SdlHostActivity.class).addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION));
|
||||
log("starting SDL3 in the SDL3Bridge screen (fallback)");
|
||||
} catch (RuntimeException e) {
|
||||
log("could not start SDL3 in the SDL3Bridge screen: " + e);
|
||||
}
|
||||
}
|
||||
|
||||
/** The previous run's own log lines about SDL / the bridge / a crash, into DroidDeck's session log. */
|
||||
private static void forwardPreviousLog() {
|
||||
new Thread(() -> {
|
||||
java.util.ArrayDeque<String> keep = new java.util.ArrayDeque<>();
|
||||
try {
|
||||
java.lang.Process p = Runtime.getRuntime().exec(new String[] { "logcat", "-d", "-v", "time", "-t", "3000" });
|
||||
try (java.io.BufferedReader r = new java.io.BufferedReader(new java.io.InputStreamReader(p.getInputStream()))) {
|
||||
String line;
|
||||
while ((line = r.readLine()) != null) {
|
||||
if (line.contains("AndroidRuntime") || line.contains(" F/") || line.contains("/SDL")
|
||||
|| line.contains("SDL3Bridge") || line.contains("libc") || line.contains("DEBUG")
|
||||
|| line.contains("/hidapi") || line.contains("JNI DETECTED")) {
|
||||
keep.addLast(line);
|
||||
while (keep.size() > 80) keep.removeFirst();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
keep.addLast("(could not read the log: " + e + ")");
|
||||
}
|
||||
NativeBridge.onBridgeLog("engine: ---- the bridge's own log (last " + keep.size() + " relevant lines) ----");
|
||||
for (String l : keep) NativeBridge.onBridgeLog("engine: | " + l);
|
||||
}, "engine-log").start();
|
||||
}
|
||||
|
||||
/** Driver off = release the USB interface so Android can use the controller; on = claim it again. */
|
||||
static void setHidFrozen(boolean frozen) {
|
||||
HIDDeviceManager h = hid;
|
||||
if (h != null) h.setFrozen(frozen);
|
||||
else SdlHostActivity.setHidFrozen(frozen);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.example.dsedge;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.view.ViewGroup;
|
||||
|
||||
import org.libsdl.app.SDLActivity;
|
||||
|
||||
/**
|
||||
* Fallback host for SDL3, used only when SDL3 could not run in the background service with this build
|
||||
* (SdlEngine decides, and says why). SDL's own screen class starts SDL3 the classic way; it is opened only from the
|
||||
* bridge's screen while you look at it, never by itself.
|
||||
*
|
||||
* It stays out of sight: its window is transparent and SDL's drawing surface is shrunk to one pixel (the bridge
|
||||
* draws nothing). SDL3 starts once this screen is in front, then the bridge's screen is brought back on top of it
|
||||
* in the same task; SDL3 keeps running behind it, and when you leave SDL3Bridge (Home, Back, switching apps).
|
||||
*/
|
||||
public class SdlHostActivity extends SDLActivity {
|
||||
static volatile boolean running;
|
||||
private final Handler ui = new Handler(Looper.getMainLooper());
|
||||
private int waits;
|
||||
|
||||
@Override protected String[] getLibraries() {
|
||||
return new String[] { "SDL3", "main" };
|
||||
}
|
||||
|
||||
@Override protected String[] getArguments() {
|
||||
String map = SdlEngine.mappingFile(this);
|
||||
return map != null ? new String[] { map } : new String[0];
|
||||
}
|
||||
|
||||
@Override protected void onCreate(Bundle state) {
|
||||
running = true;
|
||||
NativeBridge.appContext = getApplicationContext();
|
||||
Settings.init(this);
|
||||
super.onCreate(state);
|
||||
if (mSurface != null) { // SDL's drawing surface: the bridge draws nothing, keep it out of sight
|
||||
ViewGroup.LayoutParams lp = mSurface.getLayoutParams();
|
||||
if (lp != null) {
|
||||
lp.width = 1;
|
||||
lp.height = 1;
|
||||
mSurface.setLayoutParams(lp);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override protected void onResume() {
|
||||
super.onResume();
|
||||
keepControllerClaimed();
|
||||
waits = 0;
|
||||
ui.removeCallbacks(handBack);
|
||||
ui.post(handBack);
|
||||
}
|
||||
|
||||
/** As soon as SDL3's thread runs: the bridge's screen back on top (or, if it is gone, out of the way). */
|
||||
private final Runnable handBack = new Runnable() {
|
||||
@Override public void run() {
|
||||
if (isFinishing()) return;
|
||||
if (mSDLThread == null && ++waits < 60) { // SDL starts once its surface is ready (~100 ms)
|
||||
ui.postDelayed(this, 50);
|
||||
return;
|
||||
}
|
||||
if (BridgeActivity.running) {
|
||||
startActivity(new Intent(SdlHostActivity.this, BridgeActivity.class)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NO_ANIMATION));
|
||||
} else {
|
||||
moveTaskToBack(true);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@Override public void onBackPressed() {
|
||||
moveTaskToBack(true); // closing this screen would stop SDL3
|
||||
}
|
||||
|
||||
@Override protected void onPause() {
|
||||
super.onPause();
|
||||
ui.removeCallbacks(handBack);
|
||||
keepControllerClaimed(); // SDL releases the USB controller on pause; keep it while DroidDeck is in front
|
||||
}
|
||||
|
||||
@Override public void onWindowFocusChanged(boolean hasFocus) {
|
||||
super.onWindowFocusChanged(hasFocus);
|
||||
keepControllerClaimed();
|
||||
}
|
||||
|
||||
@Override protected void onDestroy() {
|
||||
ui.removeCallbacks(handBack);
|
||||
running = false;
|
||||
boolean forGood = !isChangingConfigurations();
|
||||
super.onDestroy();
|
||||
if (forGood) SdlEngine.onHostGone();
|
||||
}
|
||||
|
||||
private static void keepControllerClaimed() {
|
||||
if (mHIDDeviceManager != null) mHIDDeviceManager.setFrozen(!Settings.driverEnabled);
|
||||
}
|
||||
|
||||
static void setHidFrozen(boolean frozen) {
|
||||
if (mHIDDeviceManager != null) mHIDDeviceManager.setFrozen(frozen);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package com.example.dsedge;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
|
||||
/**
|
||||
* User settings, shared by the screen and the background service (same process).
|
||||
* Gyro / touchpad / back-button remap / lightbar are per player (0..3); the rest are global.
|
||||
*/
|
||||
final class Settings {
|
||||
static final int PLAYERS = 4;
|
||||
|
||||
static final int TOUCH_SPLIT = 0, TOUCH_SINGLE = 1, TOUCH_OFF = 2;
|
||||
static final String[] TOUCH_NAMES = {
|
||||
"Split (decoupled): left half = left trackpad, right half = right trackpad",
|
||||
"Single: whole touchpad = right trackpad",
|
||||
"Off"
|
||||
};
|
||||
|
||||
/** Remap targets: 4 Deck grips + the two trackpads' touch / click. */
|
||||
static final String[] REMAP_TARGETS = {
|
||||
"L4", "R4", "L5", "R5",
|
||||
"Left trackpad click", "Right trackpad click",
|
||||
"Left trackpad touch", "Right trackpad touch"
|
||||
};
|
||||
static final int REMAP_COUNT = 8;
|
||||
static final int[] TARGET_BITS = { 19, 20, 21, 22 }; // grip targets (first 4) -> mask bits
|
||||
|
||||
/** Any controller button can be a source. sel: -1 none, 0 = main mask, 1 = extra mask (MISC2..6). */
|
||||
static final String[] SRC_NAMES = {
|
||||
"None",
|
||||
"A / Cross", "B / Circle", "X / Square", "Y / Triangle",
|
||||
"L1", "R1", "L2", "R2",
|
||||
"Create / Back / Share", "Options / Start / Menu", "L3", "R3",
|
||||
"Guide / PS", "Touchpad click", "Mute / Misc1",
|
||||
"D-pad Up", "D-pad Down", "D-pad Left", "D-pad Right",
|
||||
"Left paddle (L4)", "Right paddle (R4)", "Left Fn (L5)", "Right Fn (R5)",
|
||||
"Extra C / Misc2", "Extra Z / Misc3", "Misc4", "Misc5", "Misc6"
|
||||
};
|
||||
static final int[] SRC_SEL = { -1, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0, 0,0,0,0, 0,0,0,0, 1,1,1,1,1 };
|
||||
static final int[] SRC_BIT = { -1, 0,1,2,3, 4,5,6,7, 8,9,10,11, 12,13,14, 15,16,17,18, 19,20,21,22, 0,1,2,3,4 };
|
||||
static final String[] PLAYER_NAMES = { "Off", "Player 1", "Player 2", "Player 3", "Player 4" };
|
||||
static final String[] AXIS_NAMES = { "Controller X (pitch)", "Controller Y (yaw)", "Controller Z (roll)" };
|
||||
static final String[] GYRO_INV_NAMES = { "None", "X", "Y", "Z", "X + Y", "X + Z", "Y + Z", "X + Y + Z" };
|
||||
|
||||
// ---- per-player settings (index 0..3) ----
|
||||
static final int[] touchMode = fill(TOUCH_SPLIT);
|
||||
static final int[][] remap = new int[PLAYERS][REMAP_COUNT];
|
||||
static final boolean[] touchInvX = new boolean[PLAYERS];
|
||||
static final boolean[] touchInvY = new boolean[PLAYERS];
|
||||
static final boolean[] touchSwap = new boolean[PLAYERS];
|
||||
static final int[] gyroGain = fill(100);
|
||||
static final int[] gyroInvert = new int[PLAYERS];
|
||||
static final int[] gyroDeadzone = new int[PLAYERS];
|
||||
static final float[][] gyroBias = new float[PLAYERS][3];
|
||||
static final int[][] gyroMap = new int[PLAYERS][3];
|
||||
static final boolean[] accelFollows = fill(true);
|
||||
static final int[] lightR = new int[PLAYERS];
|
||||
static final int[] lightG = new int[PLAYERS];
|
||||
static final int[] lightB = fill(255);
|
||||
static final int[] brightness = fill(100);
|
||||
static final int[] playerLed = new int[PLAYERS];
|
||||
|
||||
// ---- global settings ----
|
||||
// Auto by default: any SDL3-supported controller is used -- through SDL3's own USB driver when possible
|
||||
// (full features), otherwise through Android's input (e.g. Bluetooth). An Android duplicate of a controller
|
||||
// SDL3 already drives over USB is still ignored, so nothing is doubled.
|
||||
static volatile boolean forceUsb = false;
|
||||
static volatile boolean driverEnabled = true;
|
||||
static volatile int presentAs = 0;
|
||||
static final String[] PRESENT_NAMES = { "Steam Deck (default)", "DualSense (native)", "DualSense Edge (native)", "DualShock 4 (native)",
|
||||
"Steam Controller 2026 (native)", "Steam Controller 2015 (native)",
|
||||
"Steam Native Hook-up (Steam sees the real controller)" };
|
||||
// DroidDeck pad types: 0 Deck, 4 DualSense, 5 DualSense Edge, 3 DualShock 4, 1 Steam Controller 2026 (28de:1302),
|
||||
// 6 Steam Controller 2015 (28de:1102)
|
||||
// Hook-up hands USB controllers to Steam as themselves; any controller it can't (Bluetooth) stays a Deck pad.
|
||||
static final int[] PRESENT_PAD_TYPE = { 0, 4, 5, 3, 1, 6, 0 };
|
||||
static final int PRESENT_HOOKUP = 6;
|
||||
static boolean isHookup() { return presentAs == PRESENT_HOOKUP; }
|
||||
/** The "Present controller as" choice to go back to when hook-up is switched off from the bubble. */
|
||||
static volatile int lastPresentAs = 0;
|
||||
/** Was the SDL3 driver on before the bubble switched hook-up on? Switching hook-up off goes back to it. */
|
||||
static volatile boolean driverBeforeHookup = true;
|
||||
static final int PAD_TYPE_STEAM_2015 = 6;
|
||||
static boolean isSonyPadType(int t) { return t >= 3 && t <= 5; }
|
||||
static volatile int pollMs = 2;
|
||||
static final String[] RATE_NAMES = { "250 Hz (low CPU)", "500 Hz (recommended)", "1000 Hz (max)" };
|
||||
static final int[] RATE_MS = { 4, 2, 1 };
|
||||
static volatile boolean bubble = false;
|
||||
static volatile int bubbleX = 24, bubbleY = 160;
|
||||
|
||||
private static SharedPreferences prefs;
|
||||
|
||||
private Settings() {}
|
||||
|
||||
private static int[] fill(int v) { int[] a = new int[PLAYERS]; java.util.Arrays.fill(a, v); return a; }
|
||||
private static boolean[] fill(boolean v) { boolean[] a = new boolean[PLAYERS]; java.util.Arrays.fill(a, v); return a; }
|
||||
|
||||
static synchronized void init(Context c) {
|
||||
if (prefs != null) return;
|
||||
prefs = c.getApplicationContext().getSharedPreferences(Host.prefs(c, "bridge"), Context.MODE_PRIVATE);
|
||||
for (int p = 0; p < PLAYERS; p++) {
|
||||
String s = "_p" + p;
|
||||
touchMode[p] = clamp(prefs.getInt("touchMode" + s, TOUCH_SPLIT), 0, 2);
|
||||
for (int i = 0; i < REMAP_COUNT; i++) remap[p][i] = clamp(prefs.getInt("remap" + i + s, 0), 0, SRC_NAMES.length - 1);
|
||||
touchInvX[p] = prefs.getBoolean("touchInvX" + s, false);
|
||||
touchInvY[p] = prefs.getBoolean("touchInvY" + s, false);
|
||||
touchSwap[p] = prefs.getBoolean("touchSwap" + s, false);
|
||||
gyroGain[p] = clamp(prefs.getInt("gyroGain" + s, 100), 1, 800);
|
||||
gyroInvert[p] = clamp(prefs.getInt("gyroInvert" + s, 0), 0, 7);
|
||||
gyroDeadzone[p] = clamp(prefs.getInt("gyroDeadzone" + s, 0), 0, 50);
|
||||
gyroBias[p][0] = prefs.getFloat("gyroBiasX" + s, 0f);
|
||||
gyroBias[p][1] = prefs.getFloat("gyroBiasY" + s, 0f);
|
||||
gyroBias[p][2] = prefs.getFloat("gyroBiasZ" + s, 0f);
|
||||
for (int i = 0; i < 3; i++) gyroMap[p][i] = clamp(prefs.getInt("gyroMap" + i + s, i), 0, 2);
|
||||
accelFollows[p] = prefs.getBoolean("accelFollows" + s, true);
|
||||
lightR[p] = clamp(prefs.getInt("lightR" + s, 0), 0, 255);
|
||||
lightG[p] = clamp(prefs.getInt("lightG" + s, 0), 0, 255);
|
||||
lightB[p] = clamp(prefs.getInt("lightB" + s, 255), 0, 255);
|
||||
brightness[p] = clamp(prefs.getInt("brightness" + s, 100), 0, 100);
|
||||
playerLed[p] = clamp(prefs.getInt("playerLed" + s, 0), 0, 4);
|
||||
}
|
||||
forceUsb = prefs.getBoolean("forceUsbV2", false);
|
||||
driverEnabled = prefs.getBoolean("driverEnabled", true);
|
||||
presentAs = clamp(prefs.getInt("presentAs", 0), 0, PRESENT_NAMES.length - 1);
|
||||
lastPresentAs = clamp(prefs.getInt("lastPresentAs", 0), 0, PRESENT_NAMES.length - 1);
|
||||
if (lastPresentAs == PRESENT_HOOKUP) lastPresentAs = 0;
|
||||
driverBeforeHookup = prefs.getBoolean("driverBeforeHookup", true);
|
||||
pollMs = clamp(prefs.getInt("pollMs", 2), 1, 16);
|
||||
bubble = prefs.getBoolean("bubble", false);
|
||||
bubbleX = prefs.getInt("bubbleX", 24);
|
||||
bubbleY = prefs.getInt("bubbleY", 160);
|
||||
}
|
||||
|
||||
static void save() {
|
||||
SharedPreferences pr = prefs;
|
||||
if (pr == null) return;
|
||||
SharedPreferences.Editor e = pr.edit();
|
||||
for (int p = 0; p < PLAYERS; p++) {
|
||||
String s = "_p" + p;
|
||||
e.putInt("touchMode" + s, touchMode[p]);
|
||||
for (int i = 0; i < REMAP_COUNT; i++) e.putInt("remap" + i + s, remap[p][i]);
|
||||
e.putBoolean("touchInvX" + s, touchInvX[p]).putBoolean("touchInvY" + s, touchInvY[p]).putBoolean("touchSwap" + s, touchSwap[p]);
|
||||
e.putInt("gyroGain" + s, gyroGain[p]).putInt("gyroInvert" + s, gyroInvert[p]).putInt("gyroDeadzone" + s, gyroDeadzone[p]);
|
||||
e.putFloat("gyroBiasX" + s, gyroBias[p][0]).putFloat("gyroBiasY" + s, gyroBias[p][1]).putFloat("gyroBiasZ" + s, gyroBias[p][2]);
|
||||
for (int i = 0; i < 3; i++) e.putInt("gyroMap" + i + s, gyroMap[p][i]);
|
||||
e.putBoolean("accelFollows" + s, accelFollows[p]);
|
||||
e.putInt("lightR" + s, lightR[p]).putInt("lightG" + s, lightG[p]).putInt("lightB" + s, lightB[p]);
|
||||
e.putInt("brightness" + s, brightness[p]).putInt("playerLed" + s, playerLed[p]);
|
||||
}
|
||||
e.putBoolean("forceUsbV2", forceUsb);
|
||||
e.putBoolean("driverEnabled", driverEnabled);
|
||||
e.putInt("presentAs", presentAs);
|
||||
e.putInt("lastPresentAs", lastPresentAs);
|
||||
e.putBoolean("driverBeforeHookup", driverBeforeHookup);
|
||||
e.putInt("pollMs", pollMs);
|
||||
e.putBoolean("bubble", bubble).putInt("bubbleX", bubbleX).putInt("bubbleY", bubbleY);
|
||||
e.apply();
|
||||
}
|
||||
|
||||
private static int clamp(int v, int lo, int hi) { return Math.max(lo, Math.min(hi, v)); }
|
||||
|
||||
/** Is the source button [srcIndex] currently pressed, given the two button masks? */
|
||||
static boolean srcDown(int mask, int mask2, int srcIndex) {
|
||||
if (srcIndex <= 0 || srcIndex >= SRC_NAMES.length) return false;
|
||||
int m = SRC_SEL[srcIndex] == 1 ? mask2 : mask;
|
||||
return ((m >> SRC_BIT[srcIndex]) & 1) != 0;
|
||||
}
|
||||
|
||||
/** Applies the 4 grip remaps (targets 0..3) to the mask for player [p]; a mapped source stops acting as itself. */
|
||||
static int applyGripRemap(int mask, int mask2, int p) {
|
||||
if (p < 0 || p >= PLAYERS) p = 0;
|
||||
int[] rm = remap[p];
|
||||
int add = 0, consumed = 0;
|
||||
for (int t = 0; t < 4; t++) {
|
||||
int srcIndex = rm[t];
|
||||
if (srcDown(mask, mask2, srcIndex)) {
|
||||
add |= 1 << TARGET_BITS[t];
|
||||
if (SRC_SEL[srcIndex] == 0) consumed |= 1 << SRC_BIT[srcIndex];
|
||||
}
|
||||
}
|
||||
return (mask | add) & ~consumed;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package com.example.dsedge;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
|
||||
/**
|
||||
* Checks the GitHub Releases of the repo this APK was built in (CI writes assets/build.txt).
|
||||
* The repo must be public for the unauthenticated GitHub API to see its releases.
|
||||
*/
|
||||
final class UpdateChecker {
|
||||
interface Callback {
|
||||
/** url is non-null only when a newer build exists. Called on the main thread. */
|
||||
void onResult(String message, String url);
|
||||
}
|
||||
|
||||
static final class BuildInfo {
|
||||
String repo = "UNKNOWN", tag = "dev", sdl = "unknown";
|
||||
}
|
||||
|
||||
private UpdateChecker() {}
|
||||
|
||||
static BuildInfo readBuildInfo(Context ctx) {
|
||||
BuildInfo b = new BuildInfo();
|
||||
// Built into another app (SDL3DroidDeck), the bridge's build info has its own name next to that app's assets.
|
||||
try (InputStream in = ctx.getAssets().open(Host.embedded(ctx) ? "sdl3bridge-build.txt" : "build.txt");
|
||||
BufferedReader r = new BufferedReader(new InputStreamReader(in))) {
|
||||
String line;
|
||||
while ((line = r.readLine()) != null) {
|
||||
int eq = line.indexOf('=');
|
||||
if (eq <= 0) continue;
|
||||
String k = line.substring(0, eq).trim(), v = line.substring(eq + 1).trim();
|
||||
if (k.equals("repo")) b.repo = v;
|
||||
else if (k.equals("tag")) b.tag = v;
|
||||
else if (k.equals("sdl")) b.sdl = v;
|
||||
}
|
||||
} catch (Exception ignored) { }
|
||||
return b;
|
||||
}
|
||||
|
||||
static void check(final Context ctx, final Callback cb) {
|
||||
final Handler main = new Handler(Looper.getMainLooper());
|
||||
final BuildInfo cur = readBuildInfo(ctx);
|
||||
new Thread(() -> {
|
||||
String msg;
|
||||
String url = null;
|
||||
if (Host.embedded(ctx)) {
|
||||
msg = "Built into " + Host.appName(ctx) + ": it updates together with it.";
|
||||
} else if (cur.repo.equals("UNKNOWN")) {
|
||||
msg = "Updates are off: this APK was not built by the GitHub workflow.";
|
||||
} else {
|
||||
try {
|
||||
HttpURLConnection c = (HttpURLConnection) new URL(
|
||||
"https://api.github.com/repos/" + cur.repo + "/releases/latest").openConnection();
|
||||
c.setConnectTimeout(8000);
|
||||
c.setReadTimeout(8000);
|
||||
c.setRequestProperty("Accept", "application/vnd.github+json");
|
||||
int code = c.getResponseCode();
|
||||
if (code == 404) {
|
||||
msg = "No release found. The repo must be public and have a finished build.";
|
||||
} else if (code != 200) {
|
||||
msg = "Update check failed (HTTP " + code + ").";
|
||||
} else {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
try (BufferedReader r = new BufferedReader(new InputStreamReader(c.getInputStream()))) {
|
||||
String line;
|
||||
while ((line = r.readLine()) != null) sb.append(line);
|
||||
}
|
||||
JSONObject j = new JSONObject(sb.toString());
|
||||
String latest = j.optString("tag_name", "");
|
||||
String notes = j.optString("body", "");
|
||||
String sdl = "";
|
||||
int i = notes.indexOf("sdl=");
|
||||
if (i >= 0) sdl = notes.substring(i + 4).split("\\s")[0];
|
||||
String apk = null;
|
||||
JSONArray assets = j.optJSONArray("assets");
|
||||
for (int k = 0; assets != null && k < assets.length(); k++) {
|
||||
JSONObject a = assets.getJSONObject(k);
|
||||
if (a.optString("name").endsWith(".apk")) { apk = a.optString("browser_download_url"); break; }
|
||||
}
|
||||
if (apk != null && newer(latest, cur.tag)) {
|
||||
msg = "Update available: " + latest + (sdl.isEmpty() ? "" : " (SDL " + sdl + ")") + ". Tap to download.";
|
||||
url = apk;
|
||||
} else {
|
||||
msg = "Up to date (" + cur.tag + ", SDL " + cur.sdl + ").";
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
msg = "Update check failed: " + e.getClass().getSimpleName();
|
||||
}
|
||||
}
|
||||
final String m = msg;
|
||||
final String u = url;
|
||||
main.post(() -> cb.onResult(m, u));
|
||||
}, "update-check").start();
|
||||
}
|
||||
|
||||
/** Tags look like "build-12". Anything unparsable on our side ("dev") counts as older. */
|
||||
private static boolean newer(String latest, String current) {
|
||||
long a = number(latest), b = number(current);
|
||||
return a > b;
|
||||
}
|
||||
|
||||
private static long number(String tag) {
|
||||
try { return Long.parseLong(tag.replaceAll("[^0-9]", "")); } catch (NumberFormatException e) { return -1; }
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.example.dsedge;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
|
||||
/**
|
||||
* Receives "controller plugged in" from Android. Accepting Android's prompt gives the bridge USB access to the
|
||||
* controller; nothing needs to be shown for that. The bridge's background service (with SDL3 in it) is started
|
||||
* if it isn't running yet, and picks the controller up; no screen opens.
|
||||
*/
|
||||
public class UsbAttachActivity extends Activity {
|
||||
@Override protected void onCreate(Bundle state) {
|
||||
super.onCreate(state);
|
||||
// The bridge runs in its background service (SDL3 included): start that, nothing comes to the front.
|
||||
try {
|
||||
startForegroundService(new Intent(this, BridgeService.class));
|
||||
} catch (RuntimeException ignored) { }
|
||||
finish();
|
||||
overridePendingTransition(0, 0);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user