Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import android.content.Context

private const val PREFS_NAME = "shellwave_prefs"
private const val KEY_FULL_WIDTH_TERMINAL = "full_width_terminal"
private const val KEY_HIDE_KEY_BAR_WITH_HARDWARE_KEYBOARD = "hide_key_bar_with_hardware_keyboard"

/**
* Whether the terminal takes the whole wide/unfolded window. Two panes are a choice, never a tax:
Expand All @@ -18,4 +19,20 @@ object SessionLayoutPreferences {
context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit()
.putBoolean(KEY_FULL_WIDTH_TERMINAL, fullWidth).apply()
}

/**
* Whether the on-screen key bar gives way to a connected physical keyboard, which has every
* key on it already and leaves the terminal its rows. On by default, with a switch in settings
* and an entry in the session menu for a mouse or other HID device that reports itself as a
* keyboard.
*/
fun getHideKeyBarWithHardwareKeyboard(context: Context): Boolean =
context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
.getBoolean(KEY_HIDE_KEY_BAR_WITH_HARDWARE_KEYBOARD, true)

/** Sets whether the key bar is hidden while a physical keyboard is connected. */
fun setHideKeyBarWithHardwareKeyboard(context: Context, hide: Boolean) {
context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit()
.putBoolean(KEY_HIDE_KEY_BAR_WITH_HARDWARE_KEYBOARD, hide).apply()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
package io.github.lordofpolls.shellwave.feature.session

import android.content.res.Configuration
import android.hardware.input.InputManager
import android.os.Handler
import android.os.Looper
import android.view.InputDevice
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext

/**
* The few `InputDevice` facts [hasPhysicalKeyboard] decides on, sampled into a plain class so the
* decision runs in a JVM test without an Android device.
*/
internal data class KeyboardDeviceInfo(
val isVirtual: Boolean,
val isExternal: Boolean,
val isEnabled: Boolean,
val isKeyboard: Boolean,
val isAlphabetic: Boolean,
)

internal fun InputDevice.toKeyboardDeviceInfo() =
KeyboardDeviceInfo(
isVirtual = isVirtual,
isExternal = isExternal,
isEnabled = isEnabled,
isKeyboard = supportsSource(InputDevice.SOURCE_KEYBOARD),
isAlphabetic = keyboardType == InputDevice.KEYBOARD_TYPE_ALPHABETIC,
)

/**
* Whether a usable physical keyboard is attached. A closed slider keyboard still reports
* `KEYBOARD_QWERTY`, so for the `Configuration` and for built-in devices `HARDKEYBOARDHIDDEN_YES`
* rules the keyboard out. An external keyboard is exempt from that: with the system setting "Show
* on-screen keyboard while physical keyboard is active" on, the window manager reports the
* keyboard as hidden to keep the soft IME showing, though one is plainly attached. Tablet
* keyboard covers, some Bluetooth keyboards and OEM skins also show up only as an `InputDevice`
* and never set `Configuration.keyboard`.
*/
internal fun hasPhysicalKeyboard(
devices: List<KeyboardDeviceInfo>,
configKeyboardQwerty: Boolean,
hardKeyboardHidden: Int,
): Boolean {
val usable =
devices.filter { it.isKeyboard && it.isAlphabetic && it.isEnabled && !it.isVirtual }
if (usable.any { it.isExternal }) return true
return hardKeyboardHidden != Configuration.HARDKEYBOARDHIDDEN_YES &&
(configKeyboardQwerty || usable.isNotEmpty())
}

/**
* Live [hasPhysicalKeyboard] for the current device list. The `Configuration` alone is not enough
* to follow a keyboard coming and going, so this listens to `InputManager` and recomputes on every
* device change.
*/
@Composable
internal fun physicalKeyboardConnected(): Boolean {
val context = LocalContext.current
val configuration = LocalConfiguration.current
val configQwerty = configuration.keyboard == Configuration.KEYBOARD_QWERTY
val hardKeyboardHidden = configuration.hardKeyboardHidden
val inputManager = remember(context) { context.getSystemService(InputManager::class.java) }

fun sample(): List<KeyboardDeviceInfo> =
InputDevice.getDeviceIds().toList().mapNotNull { id ->
InputDevice.getDevice(id)?.toKeyboardDeviceInfo()
}

var devices by remember { mutableStateOf(sample()) }
DisposableEffect(inputManager) {
val listener =
object : InputManager.InputDeviceListener {
override fun onInputDeviceAdded(deviceId: Int) {
devices = sample()
}

override fun onInputDeviceRemoved(deviceId: Int) {
devices = sample()
}

override fun onInputDeviceChanged(deviceId: Int) {
devices = sample()
}
}
devices = sample()
inputManager.registerInputDeviceListener(listener, Handler(Looper.getMainLooper()))
onDispose { inputManager.unregisterInputDeviceListener(listener) }
}
return hasPhysicalKeyboard(devices, configQwerty, hardKeyboardHidden)
}
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,10 @@ fun SessionsScreen(

val bellContext = LocalContext.current
val bellMode by rememberPrefState { BellPreferences.get(it) }
val hideKeyBarWithHardwareKeyboard by rememberPrefState {
SessionLayoutPreferences.getHideKeyBarWithHardwareKeyboard(it)
}
val physicalKeyboard = physicalKeyboardConnected()

// WindowInfoTracker reports per-Activity window metrics. Degrades to Flat rather than crashing
// without one, e.g. in a @Preview.
Expand Down Expand Up @@ -261,6 +265,10 @@ fun SessionsScreen(
connection = overflowConnection,
bellMode = bellMode,
onBellMode = { mode -> BellPreferences.set(bellContext, mode) },
keyBarHidden = if (physicalKeyboard) hideKeyBarWithHardwareKeyboard else null,
onKeyBarHidden = { hide ->
SessionLayoutPreferences.setHideKeyBarWithHardwareKeyboard(bellContext, hide)
},
onDownload = { connection -> fileTransferController.requestDownload(connection) },
onUpload = { connection -> fileTransferController.requestUpload(connection) },
onBrowseFiles = { connection ->
Expand Down Expand Up @@ -396,6 +404,10 @@ internal fun SessionTabBody(
val keyBarKeys = overrideLayout?.let { decodeKeyBarKeys(it.keysJson) } ?: DEFAULT_KEY_BAR_KEYS
// From the same per-host layout override the keys come from. No override means one row.
val keyBarRows = overrideLayout?.rows ?: 1
val hideKeyBarWithHardwareKeyboard by rememberPrefState {
SessionLayoutPreferences.getHideKeyBarWithHardwareKeyboard(it)
}
val keyBarHidden = hideKeyBarWithHardwareKeyboard && physicalKeyboardConnected()
val fontContext = LocalContext.current
val terminalTypeface =
remember(fontFamily, profileOrDefault.customFontUri) {
Expand All @@ -407,6 +419,13 @@ internal fun SessionTabBody(
var measuredSize by remember { mutableStateOf<TerminalSize?>(null) }
var ctrlLatched by remember { mutableStateOf(false) }
var altLatched by remember { mutableStateOf(false) }
// A latch set on the key bar would otherwise outlive the bar and silently modify the next key.
LaunchedEffect(keyBarHidden) {
if (keyBarHidden) {
ctrlLatched = false
altLatched = false
}
}

// topRow <= 0 is how far into the scrollback the view is; scrollDragRemainderPx carries a
// drag's sub-cell remainder between events, so slow swipes accumulate to a full row instead of
Expand Down Expand Up @@ -653,7 +672,8 @@ internal fun SessionTabBody(
runCatching { localContext.startActivity(Intent(Intent.ACTION_VIEW, uri)) }
}

// imePadding lives on KeyBar itself below, not on this Column - see that call site.
// imePadding lives on the KeyBar (or its stand-in Spacer) below, not on this Column - see that
// call site.
Column(modifier = modifier) {
if (searchController.open) {
TerminalSearchBar(
Expand Down Expand Up @@ -839,35 +859,41 @@ internal fun SessionTabBody(
if (preKeyBarGap > 0.dp) Spacer(modifier = Modifier
.fillMaxWidth()
.height(preKeyBarGap))
// `imePadding()` belongs here, on the key bar alone, never on the outer Column. With it on
// `imePadding()` belongs here, on the key bar (or its Spacer) alone, never on the outer Column. With it on
// the Column - whose other child is a `weight(1f)` Box - each frame of the IME-hide
// animation recomputes the remaining-space split from a bottom padding that is itself still
// animating. If one frame's inset makes the padding read larger than the Column's height,
// `weight(1f)` clamps the terminal to zero for that frame and the key bar is placed
// immediately after it, at the top, which reads as a second key bar flashing. Padding the
// key bar alone removes the weighted sibling from the equation.
KeyBar(
ctrlLatched = ctrlLatched,
altLatched = altLatched,
onCtrlToggle = { ctrlLatched = !ctrlLatched },
onAltToggle = { altLatched = !altLatched },
onSpecialKey = { keyCode -> sendSpecialKey(keyCode) },
// Through the same text-input path as typed IME input, so it inherits sendText's
// Ctrl/Alt latch behaviour.
onMacro = { text -> sendText(text) },
keyboardVisible = imeVisible,
onKeyboardToggle = {
if (imeVisible) {
keyboardController?.hide()
} else {
focusRequester.requestFocus()
keyboardController?.show()
}
},
keys = keyBarKeys,
rows = keyBarRows,
modifier = Modifier.imePadding(),
)
if (!keyBarHidden) {
KeyBar(
ctrlLatched = ctrlLatched,
altLatched = altLatched,
onCtrlToggle = { ctrlLatched = !ctrlLatched },
onAltToggle = { altLatched = !altLatched },
onSpecialKey = { keyCode -> sendSpecialKey(keyCode) },
// Through the same text-input path as typed IME input, so it inherits sendText's
// Ctrl/Alt latch behaviour.
onMacro = { text -> sendText(text) },
keyboardVisible = imeVisible,
onKeyboardToggle = {
if (imeVisible) {
keyboardController?.hide()
} else {
focusRequester.requestFocus()
keyboardController?.show()
}
},
keys = keyBarKeys,
rows = keyBarRows,
modifier = Modifier.imePadding(),
)
} else {
// Carries the IME inset the key bar would have, so the terminal still shrinks above the
// keyboard.
Spacer(Modifier.imePadding())
}
}

LaunchedEffect(sessionId) { focusRequester.requestFocus() }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import androidx.compose.material.icons.automirrored.outlined.KeyboardArrowRight
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.Download
import androidx.compose.material.icons.outlined.Folder
import androidx.compose.material.icons.outlined.Keyboard
import androidx.compose.material.icons.outlined.MoreVert
import androidx.compose.material.icons.outlined.Notifications
import androidx.compose.material.icons.outlined.PlayArrow
Expand Down Expand Up @@ -41,6 +42,11 @@ import io.github.lordofpolls.shellwave.ssh.SshConnection
* that need a live channel. [onClose] is not gated - closing a session stuck mid-connect is exactly
* when it is needed.
*
* [keyBarHidden] is null while no physical keyboard is connected, which hides the key bar item:
* with the key bar always shown there is nothing to toggle. It exists because some mice and other
* HID devices report themselves as a keyboard, which would otherwise leave the key bar hidden with
* no way back short of the settings screen.
*
* Bell is a nested single-choice group carrying its value in the parent item's label, so the mode
* reads without opening the submenu, which is the one thing the permanent toggle did well.
*/
Expand All @@ -49,6 +55,8 @@ internal fun TerminalOverflowMenu(
connection: SshConnection?,
bellMode: BellMode,
onBellMode: (BellMode) -> Unit,
keyBarHidden: Boolean?,
onKeyBarHidden: (Boolean) -> Unit,
onDownload: (SshConnection) -> Unit,
onUpload: (SshConnection) -> Unit,
onBrowseFiles: (SshConnection) -> Unit,
Expand Down Expand Up @@ -148,6 +156,16 @@ internal fun TerminalOverflowMenu(
},
onClick = { showingBell = true },
)
if (keyBarHidden != null) {
DropdownMenuItem(
text = { Text(if (keyBarHidden) "Show key bar" else "Hide key bar") },
leadingIcon = { Icon(Icons.Outlined.Keyboard, contentDescription = null) },
onClick = {
expanded = false
onKeyBarHidden(!keyBarHidden)
},
)
}
if (onClose != null) {
DropdownMenuItem(
text = { Text("Close session") },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,8 @@ constructor(
"exactSchemeColours" to AppearancePreferences.getExactSchemeColours(context),
"bellMode" to BellPreferences.get(context).name,
"fullWidthTerminal" to SessionLayoutPreferences.getFullWidthTerminal(context),
"hideKeyBarWithHardwareKeyboard" to
SessionLayoutPreferences.getHideKeyBarWithHardwareKeyboard(context),
"reachabilityEnabled" to ReachabilityPreferences.isEnabled(context),
"reachabilityInterval" to ReachabilityPreferences.interval(context).name,
"reachabilityAllowsMetered" to ReachabilityPreferences.allowsMetered(context),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ data class ImportedSettings(
val exactSchemeColours: Boolean? = null,
val bellMode: BellMode? = null,
val fullWidthTerminal: Boolean? = null,
val hideKeyBarWithHardwareKeyboard: Boolean? = null,
val reachabilityEnabled: Boolean? = null,
val reachabilityInterval: ReachabilityInterval? = null,
val reachabilityAllowsMetered: Boolean? = null,
Expand Down Expand Up @@ -236,6 +237,7 @@ private fun JSONObject?.toImportedSettings(): ImportedSettings {
exactSchemeColours = booleanOrNull("exactSchemeColours"),
bellMode = enumOrNull(stringOrNull("bellMode")),
fullWidthTerminal = booleanOrNull("fullWidthTerminal"),
hideKeyBarWithHardwareKeyboard = booleanOrNull("hideKeyBarWithHardwareKeyboard"),
reachabilityEnabled = booleanOrNull("reachabilityEnabled"),
reachabilityInterval = enumOrNull(stringOrNull("reachabilityInterval")),
reachabilityAllowsMetered = booleanOrNull("reachabilityAllowsMetered"),
Expand Down Expand Up @@ -386,6 +388,9 @@ constructor(
settings.fullWidthTerminal?.let {
SessionLayoutPreferences.setFullWidthTerminal(context, it)
}
settings.hideKeyBarWithHardwareKeyboard?.let {
SessionLayoutPreferences.setHideKeyBarWithHardwareKeyboard(context, it)
}
settings.reachabilityEnabled?.let { ReachabilityPreferences.setEnabled(context, it) }
settings.reachabilityInterval?.let { ReachabilityPreferences.setInterval(context, it) }
settings.reachabilityAllowsMetered?.let {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import io.github.lordofpolls.shellwave.core.prefs.BellMode
import io.github.lordofpolls.shellwave.core.prefs.BellPreferences
import io.github.lordofpolls.shellwave.core.prefs.SessionLayoutPreferences
import io.github.lordofpolls.shellwave.core.prefs.rememberPrefState
import io.github.lordofpolls.shellwave.feature.session.physicalKeyboardConnected
import io.github.lordofpolls.shellwave.terminal.DEFAULT_COLOR_SCHEME
import io.github.lordofpolls.shellwave.terminal.DEFAULT_TERMINAL_PROFILE
import io.github.lordofpolls.shellwave.ui.design.BackTopBar
Expand All @@ -52,6 +53,8 @@ fun TerminalSettingsScreen(
val context = LocalContext.current
val bellMode by rememberPrefState { BellPreferences.get(it) }
val fullWidthTerminal by rememberPrefState { SessionLayoutPreferences.getFullWidthTerminal(it) }
val hideKeyBar by rememberPrefState { SessionLayoutPreferences.getHideKeyBarWithHardwareKeyboard(it) }
val physicalKeyboard = physicalKeyboardConnected()

var profile by remember { mutableStateOf(DEFAULT_TERMINAL_PROFILE) }
LaunchedEffect(Unit) {
Expand Down Expand Up @@ -114,6 +117,18 @@ fun TerminalSettingsScreen(
chevron = true,
onClick = onOpenKeyBarLayouts,
)
SettingsSwitch(
title = "Hide key bar with a physical keyboard",
description =
"While a physical keyboard is connected, the key bar is hidden and the " +
"terminal gets its rows. " +
if (physicalKeyboard) "A physical keyboard is connected now."
else "No physical keyboard is detected right now.",
checked = hideKeyBar,
onCheckedChange = {
SessionLayoutPreferences.setHideKeyBarWithHardwareKeyboard(context, it)
},
)

SettingsSectionHeader("Sessions")
SettingsRadioGroup(
Expand Down
Loading
Loading