Add Android portrait mode and scale the terminal from text size

- add orientation, text size, cap and portrait free area options
- size the cell from text size, the grid from the free area
- rebuild terminal fonts live, drawn 1:1 or at whole zoom
- keep the portrait view steady when the soft keyboard opens
- place portrait shortcuts below the view, in rows
- hide fixed terminal and font sizes on Android
This commit is contained in:
dobbry-vechur
2026-10-09 03:34:03 +04:00
parent ea8c7d89c8
commit 2e6bbe1fc5
14 changed files with 1432 additions and 145 deletions
+5 -4
View File
@@ -42,8 +42,8 @@
android:label="@string/app_name"
android:launchMode="singleInstance"
android:keepScreenOn="true"
android:screenOrientation="userLandscape"
android:configChanges="keyboardHidden|keyboard|orientation|screenSize|navigation"
android:screenOrientation="fullUser"
android:configChanges="keyboardHidden|keyboard|orientation|screenSize|smallestScreenSize|screenLayout|navigation"
android:exported="true"
>
<intent-filter>
@@ -55,8 +55,9 @@
android:label="@string/app_name"
android:launchMode="singleInstance"
android:keepScreenOn="true"
android:screenOrientation="userLandscape"
android:configChanges="keyboardHidden|keyboard|orientation|screenSize|navigation"
android:windowSoftInputMode="adjustNothing"
android:screenOrientation="fullUser"
android:configChanges="keyboardHidden|keyboard|orientation|screenSize|smallestScreenSize|screenLayout|navigation"
>
</activity>
<!-- Expose app's private data directory for backup without root -->
@@ -2,8 +2,10 @@ package com.cleverraven.cataclysmdda;
import org.libsdl.app.SDLActivity;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Insets;
import android.graphics.Rect;
@@ -26,6 +28,10 @@ public class CataclysmDDA extends SDLActivity {
public static final String SYSTEM_UI_MODE_SYSTEM_BARS = "system_bars";
public static final String SYSTEM_UI_MODE_FULLSCREEN = "fullscreen";
public static final String SYSTEM_UI_MODE_EDGE_TO_EDGE = "edge_to_edge";
public static final String PREF_SCREEN_ORIENTATION = "Android screen orientation";
public static final String SCREEN_ORIENTATION_LANDSCAPE = "landscape";
public static final String SCREEN_ORIENTATION_PORTRAIT = "portrait";
public static final String SCREEN_ORIENTATION_AUTO = "auto";
private NativeUI nativeUI = new NativeUI(CataclysmDDA.this);
private int lastImeLeft = -1;
@@ -58,6 +64,7 @@ public class CataclysmDDA extends SDLActivity {
if (mLayout != null) {
mLayout.setVisibility(View.INVISIBLE);
}
applyStoredScreenOrientation(this);
setImeInsetListener();
applySystemUiMode();
}
@@ -65,6 +72,7 @@ public class CataclysmDDA extends SDLActivity {
@Override
protected void onResume() {
super.onResume();
applyStoredScreenOrientation(this);
applySystemUiMode();
}
@@ -149,38 +157,74 @@ public class CataclysmDDA extends SDLActivity {
decor.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
@Override
public WindowInsets onApplyWindowInsets(View view, WindowInsets insets) {
reportOuterSize();
reportSafeArea(insets);
boolean imeVisible = insets.isVisible(WindowInsets.Type.ime());
Insets imeInsets = insets.getInsets(WindowInsets.Type.ime());
int[] surfaceOrigin = new int[2];
if (mSurface != null) {
mSurface.getLocationInWindow(surfaceOrigin);
}
notifyImeInsetsChanged(
imeInsets.left,
imeInsets.top,
Math.max(0, view.getWidth() - imeInsets.right),
Math.max(0, view.getHeight() - imeInsets.bottom),
surfaceOrigin,
imeVisible);
return insets;
}
});
decor.requestApplyInsets();
if (mSurface != null) {
mSurface.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom) {
reportOuterSize();
WindowInsets insets = decor.getRootWindowInsets();
if (insets != null) {
reportSafeArea(insets);
}
}
});
}
} else {
decor.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
reportOuterSize();
Rect visibleFrame = new Rect();
decor.getWindowVisibleDisplayFrame(visibleFrame);
int rootHeight = decor.getRootView().getHeight();
boolean imeVisible = rootHeight - visibleFrame.bottom > rootHeight / 5;
// visible frame is in screen coordinates
int[] surfaceOrigin = new int[2];
if (mSurface != null) {
mSurface.getLocationOnScreen(surfaceOrigin);
}
notifyImeInsetsChanged(
visibleFrame.left,
visibleFrame.top,
visibleFrame.right,
visibleFrame.bottom,
surfaceOrigin,
imeVisible);
}
});
}
}
private void notifyImeInsetsChanged(int left, int top, int right, int bottom, boolean visible) {
private void notifyImeInsetsChanged(int frameLeft, int frameTop, int frameRight, int frameBottom,
int[] surfaceOrigin, boolean visible) {
int[] scaled = scaleToSurface(frameLeft, frameTop, frameRight, frameBottom, surfaceOrigin);
if (scaled == null) {
return;
}
int left = scaled[0];
int top = scaled[1];
int right = scaled[2];
int bottom = scaled[3];
if (lastImeLeft == left && lastImeTop == top && lastImeRight == right &&
lastImeBottom == bottom && lastImeVisible == visible) {
return;
@@ -200,6 +244,162 @@ public class CataclysmDDA extends SDLActivity {
private static native void onNativeImeInsetsChanged(
int left, int top, int right, int bottom, boolean visible);
private static native void onNativeSafeAreaChanged(int left, int top, int right, int bottom);
private static native void onNativeOuterSizeChanged(int width, int height);
private int lastOuterWidth = -1;
private int lastOuterHeight = -1;
// whole-window size in pixels, system bars included. text size is picked from
// it, so bars that inset the surface in one orientation only don't change it on
// rotation
private void reportOuterSize() {
int width;
int height;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
Rect bounds = getWindowManager().getCurrentWindowMetrics().getBounds();
width = bounds.width();
height = bounds.height();
} else {
View decor = getWindow().getDecorView();
width = decor.getWidth();
height = decor.getHeight();
}
// zero while the window is still being laid out
if (width <= 0 || height <= 0 || (width == lastOuterWidth && height == lastOuterHeight)) {
return;
}
try {
onNativeOuterSizeChanged(width, height);
} catch(UnsatisfiedLinkError e) {
// early layout callbacks can arrive before native startup; resend later
return;
}
lastOuterWidth = width;
lastOuterHeight = height;
}
// ten-thousandths of the surface size; native reader uses the same scale
private static final int SAFE_AREA_SCALE = 10000;
private int lastSafeLeft = -1;
private int lastSafeTop = -1;
private int lastSafeRight = -1;
private int lastSafeBottom = -1;
// null until the first report; Insets needs API 29, so no Insets.NONE here
private Insets lastNavigationInsets = null;
// in surface units, so native code needs no Java pixel sizes or origins
private int[] scaleToSurface(int left, int top, int right, int bottom, int[] surfaceOrigin) {
if (mSurface == null) {
return null;
}
int surfaceWidth = mSurface.getWidth();
int surfaceHeight = mSurface.getHeight();
if (surfaceWidth <= 0 || surfaceHeight <= 0) {
return null;
}
left = Math.max(0, left - surfaceOrigin[0]);
top = Math.max(0, top - surfaceOrigin[1]);
right = Math.min(surfaceWidth, right - surfaceOrigin[0]);
bottom = Math.min(surfaceHeight, bottom - surfaceOrigin[1]);
if (right < left || bottom < top) {
return null;
}
return new int[] {
(int)((long)left * SAFE_AREA_SCALE / surfaceWidth),
(int)((long)top * SAFE_AREA_SCALE / surfaceHeight),
(int)((long)right * SAFE_AREA_SCALE / surfaceWidth),
(int)((long)bottom * SAFE_AREA_SCALE / surfaceHeight)
};
}
// report the part of the SDL surface clear of the camera cutout and visible
// system bars. gesture strips catch edge swipes, not taps, so the game may draw
// under them
private void reportSafeArea(WindowInsets insets) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R || mSurface == null) {
return;
}
View decor = getWindow().getDecorView();
// navigation bar can appear only while the keyboard is up; keep its
// no-keyboard layout so opening the keyboard doesn't move the view
Insets navigation;
if (insets.isVisible(WindowInsets.Type.ime())) {
navigation = lastNavigationInsets != null ? lastNavigationInsets : Insets.NONE;
} else {
navigation = insets.getInsets(WindowInsets.Type.navigationBars());
lastNavigationInsets = navigation;
}
Insets safe = Insets.max(navigation, insets.getInsets(
WindowInsets.Type.statusBars() | WindowInsets.Type.captionBar() |
WindowInsets.Type.displayCutout()));
int[] origin = new int[2];
mSurface.getLocationInWindow(origin);
int[] scaled = scaleToSurface(safe.left, safe.top, decor.getWidth() - safe.right,
decor.getHeight() - safe.bottom, origin);
if (scaled == null) {
return;
}
int scaledLeft = scaled[0];
int scaledTop = scaled[1];
int scaledRight = scaled[2];
int scaledBottom = scaled[3];
if (scaledLeft == lastSafeLeft && scaledTop == lastSafeTop &&
scaledRight == lastSafeRight && scaledBottom == lastSafeBottom) {
return;
}
try {
onNativeSafeAreaChanged(scaledLeft, scaledTop, scaledRight, scaledBottom);
} catch(UnsatisfiedLinkError e) {
// early inset callbacks can arrive before native startup; resend later
return;
}
lastSafeLeft = scaledLeft;
lastSafeTop = scaledTop;
lastSafeRight = scaledRight;
lastSafeBottom = scaledBottom;
}
static int requestedOrientationFor(String mode) {
if (SCREEN_ORIENTATION_PORTRAIT.equals(mode)) {
return ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT;
}
if (SCREEN_ORIENTATION_AUTO.equals(mode)) {
return ActivityInfo.SCREEN_ORIENTATION_FULL_USER;
}
return ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE;
}
static void applyStoredScreenOrientation(Activity activity) {
String mode = PreferenceManager.getDefaultSharedPreferences(activity.getApplicationContext())
.getString(PREF_SCREEN_ORIENTATION, SCREEN_ORIENTATION_LANDSCAPE);
activity.setRequestedOrientation(requestedOrientationFor(mode));
}
// SDL asks for orientation from its hint and window shape; the game option
// decides instead
@Override
public void setOrientationBis(int w, int h, boolean resizable, String hint) {
applyStoredScreenOrientation(this);
}
public void setScreenOrientation(final String mode) {
PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
.edit()
.putString(PREF_SCREEN_ORIENTATION, mode)
.apply();
try {
runOnUiThread(new Runnable() {
public void run() {
setRequestedOrientation(requestedOrientationFor(mode));
}
});
} catch(Exception e) {
System.err.println(e.getMessage());
}
}
public void setSystemUiMode(final String mode) {
final String normalizedMode = normalizeSystemUiMode(mode);
PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
@@ -47,6 +47,7 @@ public class SplashScreen extends Activity {
public boolean[] mSettingsValues = { false, true, true };
private int mSystemUiModeIndex = 0;
private String mScreenOrientation = CataclysmDDA.SCREEN_ORIENTATION_LANDSCAPE;
private String getVersionName() {
try {
@@ -154,6 +155,7 @@ public class SplashScreen extends Activity {
protected void onCreate(Bundle savedInstanceState) {
Log.e(TAG, "onCreate()");
super.onCreate(savedInstanceState);
CataclysmDDA.applyStoredScreenOrientation(this);
accessibilityServicesAlert = new AlertDialog.Builder(SplashScreen.this)
.setTitle(getString(R.string.accessibilityServicesTitle))
@@ -279,6 +281,7 @@ public class SplashScreen extends Activity {
public void onClick(DialogInterface dialog, int id) {
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putBoolean("Software rendering", SplashScreen.this.mSettingsValues[0]).commit();
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putString(CataclysmDDA.PREF_SYSTEM_UI_MODE, getSelectedSystemUiMode()).commit();
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putString(CataclysmDDA.PREF_SCREEN_ORIENTATION, SplashScreen.this.mScreenOrientation).commit();
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putBoolean("Trap Back button", SplashScreen.this.mSettingsValues[1]).commit();
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putBoolean("Native Android UI", SplashScreen.this.mSettingsValues[2]).commit();
SplashScreen.this.startGameActivity(false);
@@ -310,6 +313,8 @@ public class SplashScreen extends Activity {
: CataclysmDDA.SYSTEM_UI_MODE_SYSTEM_BARS;
}
SplashScreen.this.mSystemUiModeIndex = systemUiModeIndex(mode);
SplashScreen.this.mScreenOrientation = preferences.getString(
CataclysmDDA.PREF_SCREEN_ORIENTATION, CataclysmDDA.SCREEN_ORIENTATION_LANDSCAPE);
}
private ScrollView createSettingsView() {
@@ -337,6 +342,43 @@ public class SplashScreen extends Activity {
});
layout.addView(displayModeGroup);
TextView orientationLabel = new TextView(SplashScreen.this);
orientationLabel.setText(getString(R.string.androidScreenOrientation));
layout.addView(orientationLabel);
final String[] orientations = {
CataclysmDDA.SCREEN_ORIENTATION_LANDSCAPE,
CataclysmDDA.SCREEN_ORIENTATION_PORTRAIT,
CataclysmDDA.SCREEN_ORIENTATION_AUTO
};
final String[] orientationLabels = {
getString(R.string.androidScreenOrientationLandscape),
getString(R.string.androidScreenOrientationPortrait),
getString(R.string.androidScreenOrientationAuto)
};
RadioGroup orientationGroup = new RadioGroup(SplashScreen.this);
orientationGroup.setOrientation(RadioGroup.VERTICAL);
for (int i = 0; i < orientations.length; i++) {
RadioButton button = new RadioButton(SplashScreen.this);
button.setId(ORIENTATION_BUTTON_ID_BASE + i);
button.setText(orientationLabels[i]);
orientationGroup.addView(button, new RadioGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
if (orientations[i].equals(mScreenOrientation)) {
orientationGroup.check(ORIENTATION_BUTTON_ID_BASE + i);
}
}
orientationGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
SplashScreen.this.mScreenOrientation = orientations[checkedId - ORIENTATION_BUTTON_ID_BASE];
SplashScreen.this.setRequestedOrientation(
CataclysmDDA.requestedOrientationFor(SplashScreen.this.mScreenOrientation));
}
});
layout.addView(orientationGroup);
addBooleanSetting(layout, 0, getString(R.string.softwareRendering));
addBooleanSetting(layout, 1, getString(R.string.trapBackButton));
addBooleanSetting(layout, 2, getString(R.string.nativeAndroidUI));
@@ -355,6 +397,8 @@ public class SplashScreen extends Activity {
ViewGroup.LayoutParams.WRAP_CONTENT));
}
private static final int ORIENTATION_BUTTON_ID_BASE = 2000;
private int systemUiModeButtonId(int index) {
return 1000 + index;
}
@@ -13,6 +13,10 @@
<string name="androidSystemUiModeSystemBars">Show system bars</string>
<string name="androidSystemUiModeFullscreen">Fullscreen</string>
<string name="androidSystemUiModeEdgeToEdge">Edge-to-edge fullscreen</string>
<string name="androidScreenOrientation">Screen orientation</string>
<string name="androidScreenOrientationLandscape">Landscape</string>
<string name="androidScreenOrientationPortrait">Portrait</string>
<string name="androidScreenOrientationAuto">Auto</string>
<string name="trapBackButton">Trap Back button</string>
<string name="nativeAndroidUI">Native Android UI menus</string>
<string name="settings">Settings</string>
+2
View File
@@ -94,6 +94,8 @@ int projected_window_width();
int projected_window_height();
bool handle_resize( int w, int h );
void resize_term( int cell_w, int cell_h );
// re-derive terminal grid from current window and options on next drain
void request_terminal_relayout();
int get_scaling_factor();
#endif // TUI
#endif // CATA_SRC_CURSESPORT_H
+4
View File
@@ -542,9 +542,13 @@ void game_ui::init_ui()
TERMX = get_terminal_width();
TERMY = get_terminal_height();
#if !defined(__ANDROID__)
// On Android the grid follows the orientation, so a portrait grid must not
// be stored as landscape size
get_options().get_option( "TERMINAL_X" ).setValue( TERMX * get_scaling_factor() );
get_options().get_option( "TERMINAL_Y" ).setValue( TERMY * get_scaling_factor() );
get_options().save();
#endif
#else
TERMY = getmaxy( catacurses::stdscr );
TERMX = getmaxx( catacurses::stdscr );
+2
View File
@@ -10,6 +10,8 @@
// Fixed window sizes.
constexpr int EVEN_MINIMUM_TERM_WIDTH = 80;
constexpr int EVEN_MINIMUM_TERM_HEIGHT = 24;
constexpr int MAXIMUM_TERM_WIDTH = 960;
constexpr int MAXIMUM_TERM_HEIGHT = 270;
constexpr int HP_HEIGHT = 14;
constexpr int HP_WIDTH = 7;
constexpr int MINIMAP_HEIGHT = 7;
+90 -14
View File
@@ -43,6 +43,7 @@
#if defined(__ANDROID__)
#include <jni.h>
#include "sdl_wrappers.h" // for GetAndroidJNIEnv(), GetAndroidActivity()
#include "terminal_layout.h"
#endif
#if defined(TILES)
@@ -1467,20 +1468,30 @@ std::string android_get_default_string_setting( const char *settings_name,
return ans;
}
void android_apply_system_ui_mode()
static void android_call_activity_string_method( const char *method, const std::string &arg )
{
JNIEnv *env = ( JNIEnv * )GetAndroidJNIEnv();
jobject activity = ( jobject )GetAndroidActivity();
jclass clazz( env->GetObjectClass( activity ) );
jmethodID method_id = env->GetMethodID( clazz, "setSystemUiMode",
"(Ljava/lang/String;)V" );
jstring mode_arg = env->NewStringUTF(
::get_option<std::string>( "ANDROID_SYSTEM_UI_MODE" ).c_str() );
env->CallVoidMethod( activity, method_id, mode_arg );
env->DeleteLocalRef( mode_arg );
jmethodID method_id = env->GetMethodID( clazz, method, "(Ljava/lang/String;)V" );
jstring arg_str = env->NewStringUTF( arg.c_str() );
env->CallVoidMethod( activity, method_id, arg_str );
env->DeleteLocalRef( arg_str );
env->DeleteLocalRef( activity );
env->DeleteLocalRef( clazz );
}
void android_apply_system_ui_mode()
{
android_call_activity_string_method( "setSystemUiMode",
::get_option<std::string>( "ANDROID_SYSTEM_UI_MODE" ) );
}
void android_apply_screen_orientation()
{
android_call_activity_string_method( "setScreenOrientation",
::get_option<std::string>( "ANDROID_SCREEN_ORIENTATION" ) );
}
#endif
void options_manager::Page::removeRepeatedEmptyLines()
@@ -2346,6 +2357,17 @@ void options_manager::add_options_interface()
void options_manager::add_options_graphics()
{
#if defined(__ANDROID__)
// grid and cell follow screen and Android text size option
constexpr copt_hide_t terminal_size_hide = COPT_ALWAYS_HIDE;
constexpr copt_hide_t font_size_hide = COPT_ALWAYS_HIDE;
#else
constexpr copt_hide_t terminal_size_hide = COPT_POSIX_CURSES_HIDE;
#if defined(TILES)
// the font options exist only with tiles
constexpr copt_hide_t font_size_hide = COPT_CURSES_HIDE;
#endif
#endif
const auto add_empty_line = [&]() {
this->add_empty_line( "graphics" );
};
@@ -2436,12 +2458,13 @@ void options_manager::add_options_graphics()
[&]( const std::string & page_id ) {
add( "TERMINAL_X", page_id, to_translation( "Terminal width" ),
to_translation( "Set the size of the terminal along the X axis." ),
80, 960, 80, COPT_POSIX_CURSES_HIDE
EVEN_MINIMUM_TERM_WIDTH, MAXIMUM_TERM_WIDTH, EVEN_MINIMUM_TERM_WIDTH, terminal_size_hide
);
add( "TERMINAL_Y", page_id, to_translation( "Terminal height" ),
to_translation( "Set the size of the terminal along the Y axis." ),
24, 270, 24, COPT_POSIX_CURSES_HIDE
EVEN_MINIMUM_TERM_HEIGHT, MAXIMUM_TERM_HEIGHT, EVEN_MINIMUM_TERM_HEIGHT,
terminal_size_hide
);
} );
@@ -2458,17 +2481,17 @@ void options_manager::add_options_graphics()
add( "FONT_WIDTH", page_id, to_translation( "Font width" ),
to_translation( "Set the font width. Requires restart." ),
6, 100, 8, COPT_CURSES_HIDE
6, 100, 8, font_size_hide
);
add( "FONT_HEIGHT", page_id, to_translation( "Font height" ),
to_translation( "Set the font height. Requires restart." ),
8, 100, 16, COPT_CURSES_HIDE
8, 100, 16, font_size_hide
);
add( "FONT_SIZE", page_id, to_translation( "Font size" ),
to_translation( "Set the font size. Requires restart." ),
8, 100, 16, COPT_CURSES_HIDE
8, 100, 16, font_size_hide
);
add( "MAP_FONT_WIDTH", page_id, to_translation( "Map font width" ),
@@ -3011,7 +3034,7 @@ void options_manager::add_options_android()
add_option_group( "android", Group( "android_display_opts",
to_translation( "Android display options" ),
to_translation( "Options regarding Android system bars and display insets." ) ),
to_translation( "Options regarding Android orientation, text size, system bars and display insets." ) ),
[&]( const std::string & page_id ) {
add( "ANDROID_SYSTEM_UI_MODE", page_id, to_translation( "Android system bars" ),
to_translation( "Controls whether Android status and navigation bars are visible and whether the game may draw behind them. This does not control Back button handling." ),
@@ -3027,6 +3050,44 @@ void options_manager::add_options_android()
to_translation( "If true, keep the game within the screen's safe area so it does not draw under the camera cutout or other unsafe edges. If false, the game fills the entire screen. This does not show or hide Android system bars." ),
true
);
add( "ANDROID_SCREEN_ORIENTATION", page_id, to_translation( "Screen orientation" ),
to_translation( "Which screen orientations are allowed. Auto follows the device rotation and the system rotation lock." ),
{
{ "landscape", to_translation( "Landscape" ) },
{ "portrait", to_translation( "Portrait" ) },
{ "auto", to_translation( "Auto" ) }
},
android_get_default_string_setting( "Android screen orientation", "landscape" )
);
std::vector<id_and_option> text_sizes = { { "auto", to_translation( "Auto" ) } };
for( const point &cell : terminal_layout::text_size_presets() ) {
const std::string id = terminal_layout::text_size_id( cell );
text_sizes.emplace_back( id, no_translation( id ) );
}
text_sizes.emplace_back( "custom", to_translation( "Custom" ) );
add( "ANDROID_TEXT_SIZE", page_id, to_translation( "Text size" ),
to_translation( "Text size in pixels. Auto picks the largest size that fits 80 columns across the short side of the screen, so rotating doesn't change it. Larger sizes are scaled down to fit in portrait, which blurs the text. Custom sizes and other fonts may blur too." ),
text_sizes, "auto" );
add( "ANDROID_TEXT_SIZE_CUSTOM", page_id, to_translation( "Custom text size" ),
to_translation( "Text height in pixels for the Custom text size." ),
8, 64, 16 );
get_option( "ANDROID_TEXT_SIZE_CUSTOM" ).setPrerequisite( "ANDROID_TEXT_SIZE", "custom" );
add( "ANDROID_MAX_COLUMNS", page_id, to_translation( "Maximum terminal width" ),
to_translation( "Most columns the terminal may use; the area left over stays empty. 0 means no limit, and values below 80 act as 80." ),
0, MAXIMUM_TERM_WIDTH, 0 );
add( "ANDROID_MAX_ROWS", page_id, to_translation( "Maximum terminal height" ),
to_translation( "Most rows the terminal may use; the area left over stays empty. 0 means no limit, and values below 24 act as 24." ),
0, MAXIMUM_TERM_HEIGHT, 0 );
add( "ANDROID_PORTRAIT_RESERVE", page_id, to_translation( "Portrait free area" ),
to_translation( "Percentage of the usable screen height kept free at the bottom in portrait orientation, for the virtual keyboard and the shortcut strip. The usable height is the safe area when \"Confine display to safe area\" is on." ),
0, 70, 35
);
} );
add_empty_line();
@@ -3260,7 +3321,7 @@ void options_manager::add_options_android()
);
add( "ANDROID_SHORTCUT_OVERLAP", page_id, to_translation( "Shortcuts overlap screen" ),
to_translation( "If true, shortcuts will be drawn transparently overlapping the game screen. If false, the game screen size will be reduced to fit the shortcuts below." ),
to_translation( "If true, shortcuts will be drawn transparently overlapping the game screen. If false, the game screen size will be reduced to fit the shortcuts below. In portrait, shortcuts always sit in the free area below the game screen." ),
true
);
@@ -3536,6 +3597,9 @@ std::string options_manager::show( bool ingame, const bool world_options_only, b
const auto init_windows = [&]( ui_adaptor & ui ) {
recalc_startpos = true;
#if !defined(__ANDROID__)
// desktop window resize rewrites TERMINAL_X/Y; keep that out of change
// detection. android never writes them back on resize
if( OPTIONS.find( "TERMINAL_X" ) != OPTIONS.end() ) {
if( OPTIONS_OLD.find( "TERMINAL_X" ) != OPTIONS_OLD.end() ) {
OPTIONS_OLD["TERMINAL_X"] = OPTIONS["TERMINAL_X"];
@@ -3552,6 +3616,7 @@ std::string options_manager::show( bool ingame, const bool world_options_only, b
WOPTIONS_OLD["TERMINAL_Y"] = OPTIONS["TERMINAL_Y"];
}
}
#endif
iMinScreenWidth = std::max( FULL_SCREEN_WIDTH, TERMX / 2 );
const int iOffsetX = TERMX > FULL_SCREEN_WIDTH ? ( TERMX - iMinScreenWidth ) / 2 : 0;
@@ -3828,6 +3893,10 @@ std::string options_manager::show( bool ingame, const bool world_options_only, b
}
}
}
#if defined(__ANDROID__)
// the grid reads live options, so an edit shows at once
request_terminal_relayout();
#endif
};
const auto is_selectable = [&]( int i ) -> bool {
@@ -4033,6 +4102,7 @@ std::string options_manager::show( bool ingame, const bool world_options_only, b
}
#if defined(__ANDROID__)
android_apply_system_ui_mode();
android_apply_screen_orientation();
#endif
g->on_options_changed();
} else {
@@ -4071,6 +4141,11 @@ std::string options_manager::show( bool ingame, const bool world_options_only, b
resize_term( ::get_option<int>( "TERMINAL_X" ), ::get_option<int>( "TERMINAL_Y" ) );
}
#elif defined(__ANDROID__)
( void ) terminal_size_changed;
// grid follows live options, which may hold unsaved edits while the menu is
// open; re-lay out from the kept options on every exit
request_terminal_relayout();
#else
( void ) terminal_size_changed;
#endif
@@ -4242,6 +4317,7 @@ void options_manager::load()
#endif
#if defined(__ANDROID__)
android_apply_system_ui_mode();
android_apply_screen_orientation();
#endif
}
+12
View File
@@ -14,6 +14,7 @@
#include <vector>
#include "cata_tiles.h"
#include "point.h"
class Font;
struct font_config;
@@ -563,6 +564,17 @@ struct renderer_recovery_test_support {
int &paints );
// installed test font, or null
static Font *test_font();
// build terminal and gui fonts at `cell`, like a text size change. false keeps
// current fonts and cell. acquires SDL_ttf like install_test_font (fixture teardown
// releases it). teardown restores font, gui_font, the cell and
// terminal_glyphs_changed, so test order can't leak state
static bool rebuild_terminal_fonts( const point &cell, int point_size,
const std::vector<font_config> &typefaces,
const std::vector<font_config> &gui_typefaces );
// current terminal cell and live font roots
static point terminal_cell();
static const Font *terminal_font();
static const Font *terminal_gui_font();
// run `body` on an ImGui client built on the fixture renderer with the gui
// and mono fonts, then tear the client down
static void with_imgui_client( const std::vector<font_config> &gui_typefaces,
+428 -126
View File
@@ -27,6 +27,7 @@
#include <stack>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include <vector>
#include "atlas_bake_plan.h"
@@ -78,6 +79,7 @@
#endif
#include "sdlsound.h"
#include "string_formatter.h"
#include "terminal_layout.h" // IWYU pragma: keep
#include "uistate.h"
#include "ui_manager.h"
#include "wcwidth.h"
@@ -136,6 +138,11 @@ static Font_Ptr overmap_font;
// Font and SDL_ttf ownership of the renderer test fixture; empty in the game.
static Font_Ptr fixture_font;
static bool test_fixture_acquired_ttf = false;
// live terminal fonts and glyph flag held while a test rebuilds them; teardown puts them back
static bool test_fixture_fonts_saved = false;
static Font_Ptr test_fixture_saved_font;
static Font_Ptr test_fixture_saved_gui_font;
static bool test_fixture_saved_glyphs_changed = false;
static SDL_Window_Ptr window;
static SDL_Renderer_Ptr renderer;
@@ -258,7 +265,7 @@ gpu_handle_graveyard &setup_target_quarantine()
static point compute_display_buffer_dims()
{
// On desktop this matches the window over scaling up to a sub-cell remainder;
// on android TERMINAL is window-independent, the only correct buffer size.
// on android TERMINAL follows orientation and options, not exact window size
return point{ TERMINAL_WIDTH * fontwidth, TERMINAL_HEIGHT * fontheight };
}
@@ -308,6 +315,28 @@ static void refresh_drawable_dims()
}
static bool apply_resize_layout( int w, int h );
// set when the terminal glyphs were rebuilt; the next resize drain redraws everything,
// since equal buffer dims would otherwise skip the full invalidation
static bool terminal_glyphs_changed = false;
static bool rebuild_terminal_fonts( const point &cell, int point_size,
const std::vector<font_config> &typefaces,
const std::vector<font_config> &gui_typefaces, bool blending );
#if defined(__ANDROID__)
static SDL_Rect android_layout_bounds();
static float quick_shortcut_height();
// fonts.json typefaces and the FONT_BLENDING option, kept so the terminal fonts can be
// rebuilt at a new cell size
static font_loader android_fonts;
// whole zoom the display buffer is drawn at; above 1 only for a bitmap font
static int android_buffer_scale = 1;
// text cell, terminal grid and zoom wanted for the window and options
struct android_text_layout {
point cell;
point grid;
int scale = 1;
};
static android_text_layout android_desired_layout();
#endif
static bool SetupRenderTarget()
{
@@ -654,6 +683,19 @@ static void WinCreate()
::window = CreateGameWindow( "", display, WindowWidth, WindowHeight, window_flags );
throwErrorIf( !::window, "CreateWindow failed" );
#if defined(__ANDROID__)
// size the first cell and grid from the real window, so a portrait start
// doesn't build a landscape buffer first, and init_interface builds the
// fonts at the right size
GetWindowSize( ::window.get(), &WindowWidth, &WindowHeight );
const android_text_layout start = android_desired_layout();
::fontwidth = start.cell.x;
::fontheight = start.cell.y;
android_buffer_scale = start.scale;
TERMINAL_WIDTH = start.grid.x;
TERMINAL_HEIGHT = start.grid.y;
#endif
// Apply fullscreen after creation to preserve exclusive vs desktop distinction
if( desired_fullscreen != FullscreenMode::windowed ) {
SetWindowFullscreen( ::window.get(), desired_fullscreen );
@@ -815,21 +857,15 @@ static const SDL_Color &color_as_sdl( const unsigned char color )
}
#if defined(__ANDROID__)
void draw_terminal_size_preview();
void draw_quick_shortcuts();
void draw_virtual_joystick();
static bool quick_shortcuts_enabled = true;
// For previewing the terminal size with a transparent rectangle overlay when user is adjusting it in the settings
static int preview_terminal_width = -1;
static int preview_terminal_height = -1;
static uint32_t preview_terminal_change_time = 0;
// onNativeImeInsetsChanged fires from the Android UI thread; refresh and
// CheckMessages read on the SDL game-loop thread. A seqlock over per-field
// atomics hands the reader a torn-free snapshot lock-free; one serialized writer
// makes the odd/even sequence sufficient.
// onNativeImeInsetsChanged and onNativeSafeAreaChanged fire from the Android UI
// thread; refresh and CheckMessages read on the SDL game-loop thread. A seqlock
// over per-field atomics hands the reader a torn-free snapshot lock-free; one
// serialized writer makes the odd/even sequence sufficient.
struct android_visible_frame_inbox {
std::atomic<uint32_t> seq{ 0 };
std::atomic<int> x{ 0 };
@@ -894,7 +930,24 @@ static_assert( std::atomic<bool>::is_always_lock_free,
static_assert( std::atomic<uint32_t>::is_always_lock_free,
"visible-frame inbox needs lock-free uint32 atomics on every shipped ABI" );
// visible frame and safe area inboxes hold rects of the SDL surface in
// ten-thousandths of its size, so the reader scales them to window coords without
// a cross-thread window size
static constexpr int surface_rect_scale = 10000;
static android_visible_frame_inbox visible_frame_inbox;
static android_visible_frame_inbox safe_area_inbox;
// size of the outer window (bars included) in the same pixels as the SDL window
static android_visible_frame_inbox outer_size_inbox;
static SDL_Rect surface_rect_to_window( const SDL_Rect &r )
{
SDL_Rect out;
out.x = r.x * WindowWidth / surface_rect_scale;
out.y = r.y * WindowHeight / surface_rect_scale;
out.w = r.w * WindowWidth / surface_rect_scale;
out.h = r.h * WindowHeight / surface_rect_scale;
return out;
}
extern "C" {
@@ -908,53 +961,148 @@ extern "C" {
PushWakeEvent();
}
JNIEXPORT void JNICALL Java_com_cleverraven_cataclysmdda_CataclysmDDA_onNativeSafeAreaChanged(
JNIEnv *env, jclass jcls, jint left, jint top, jint right, jint bottom )
{
( void )env; // unused
( void )jcls; // unused
safe_area_inbox.publish( left, top, right, bottom, true );
PushWakeEvent();
}
JNIEXPORT void JNICALL Java_com_cleverraven_cataclysmdda_CataclysmDDA_onNativeOuterSizeChanged(
JNIEnv *env, jclass jcls, jint width, jint height )
{
( void )env; // unused
( void )jcls; // unused
outer_size_inbox.publish( 0, 0, width, height, true );
PushWakeEvent();
}
} // "C"
SDL_Rect get_android_render_rect( float DisplayBufferWidth, float DisplayBufferHeight )
// outer window size, zero before Java reports it
static point android_outer_size()
{
SDL_Rect r;
bool has = false;
bool unused_visible = false;
outer_size_inbox.read_frame( r, has, unused_visible );
return has ? point( r.w, r.h ) : point::zero;
}
// part of the window that's visible when soft keyboard is up
static std::optional<SDL_Rect> android_visible_ime_frame()
{
SDL_Rect frame;
bool has_frame = false;
bool visible = false;
visible_frame_inbox.read_frame( frame, has_frame, visible );
if( !has_frame || !visible || frame.w <= 0 || frame.h <= 0 ) {
return std::nullopt;
}
return surface_rect_to_window( frame );
}
// in portrait the shortcut strip moves to a row right above the soft keyboard
static bool android_shortcuts_above_keyboard()
{
return quick_shortcuts_enabled &&
terminal_layout::is_portrait( point( WindowWidth, WindowHeight ) ) &&
android_visible_ime_frame().has_value();
}
// area the display buffer is fitted into: the window, or its safe area with
// ANDROID_RENDER_SAFE_AREA so the game clears the camera cutout, less the space
// kept free at the bottom
static SDL_Rect android_layout_bounds()
{
// Aspect-fit the display buffer into a bounds rectangle. The bounds default to
// the whole window; with ANDROID_RENDER_SAFE_AREA the system safe area is used
// instead so the game stays clear of the camera cutout and other unsafe edges.
SDL_Rect bounds{ 0, 0, WindowWidth, WindowHeight };
if( get_option<bool>( "ANDROID_RENDER_SAFE_AREA" ) ) {
// activity reports only the cutout and visible system bars. SDL's safe
// area also excludes the gesture strips, which take taps fine
SDL_Rect safe;
if( SDL_GetWindowSafeArea( ::window.get(), &safe ) && safe.w > 0 && safe.h > 0 ) {
bool has_safe = false;
bool unused_visible = false;
safe_area_inbox.read_frame( safe, has_safe, unused_visible );
if( has_safe && safe.w > 0 && safe.h > 0 ) {
bounds = surface_rect_to_window( safe );
} else if( SDL_GetWindowSafeArea( ::window.get(), &safe ) && safe.w > 0 && safe.h > 0 ) {
bounds = safe;
}
}
// Reserve the on-screen shortcut strip along the bottom unless it overlaps.
// Keep at least one row so the aspect math never divides by a zero height.
if( !get_option<bool>( "ANDROID_SHORTCUT_OVERLAP" ) && quick_shortcuts_enabled ) {
bounds.h = std::max( 1, bounds.h - get_option<int>( "ANDROID_SHORTCUT_HEIGHT" ) );
const bool overlap = get_option<bool>( "ANDROID_SHORTCUT_OVERLAP" );
int reserved = 0;
if( terminal_layout::is_portrait( point( WindowWidth, WindowHeight ) ) ) {
// independent of the runtime shortcut toggle, so hiding the strip
// doesn't change the grid size
reserved = terminal_layout::portrait_reserved_bottom( bounds.h,
get_option<int>( "ANDROID_PORTRAIT_RESERVE" ),
overlap ? 0 : static_cast<int>( quick_shortcut_height() ) );
} else if( !overlap && quick_shortcuts_enabled ) {
reserved = static_cast<int>( quick_shortcut_height() );
}
// keep area non-empty so view is never drawn zero high
bounds.h = std::max( 1, bounds.h - reserved );
return bounds;
}
const float DisplayBufferAspect = DisplayBufferWidth / DisplayBufferHeight;
const float BoundsAspect = static_cast<float>( bounds.w ) / static_cast<float>( bounds.h );
// whether fonts.json starts the terminal typeface list with a bitmap sheet
static bool android_bitmap_typeface()
{
return !android_fonts.typeface.empty() &&
is_bitmap_typeface( android_fonts.typeface.front().path );
}
// If the bounds are wider than the buffer, top-align so the virtual keyboard
// doesn't cover the content. Otherwise center horizontally within the bounds.
SDL_Rect dstrect;
if( BoundsAspect < DisplayBufferAspect ) {
dstrect.w = bounds.w;
dstrect.h = static_cast<int>( bounds.w / DisplayBufferAspect );
dstrect.x = bounds.x;
dstrect.y = bounds.y;
// TTF point size for a cell: its height, so Terminus draws its bitmap strike.
// a bitmap font keeps FONT_SIZE for its TTF fallbacks
static int android_font_point_size( const point &cell )
{
return android_bitmap_typeface() ? get_option<int>( "FONT_SIZE" ) : cell.y;
}
static point android_grid_for( const point &cell, const int scale )
{
const SDL_Rect bounds = android_layout_bounds();
const point caps( get_option<int>( "ANDROID_MAX_COLUMNS" ), get_option<int>( "ANDROID_MAX_ROWS" ) );
return terminal_layout::fit_grid( point( bounds.w / scale, bounds.h / scale ), cell, caps );
}
static android_text_layout android_desired_layout()
{
const int reference = terminal_layout::sizing_reference( point( WindowWidth, WindowHeight ),
android_outer_size() );
android_text_layout out;
if( android_bitmap_typeface() ) {
out.cell = point( get_option<int>( "FONT_WIDTH" ), get_option<int>( "FONT_HEIGHT" ) );
out.scale = terminal_layout::bitmap_scale( reference, out.cell.x );
} else {
dstrect.w = static_cast<int>( bounds.h * DisplayBufferAspect );
dstrect.h = bounds.h;
dstrect.x = bounds.x + static_cast<int>( 0.5f * ( bounds.w - dstrect.w ) );
dstrect.y = bounds.y;
out.cell = terminal_layout::resolve_text_size( get_option<std::string>( "ANDROID_TEXT_SIZE" ),
get_option<int>( "ANDROID_TEXT_SIZE_CUSTOM" ), reference );
}
out.grid = android_grid_for( out.cell, out.scale );
return out;
}
SDL_Rect ime_visible_frame;
bool has_ime_visible_frame = false;
bool ime_visible = false;
visible_frame_inbox.read_frame( ime_visible_frame, has_ime_visible_frame, ime_visible );
if( get_option<bool>( "ANDROID_KEYBOARD_SCREEN_SCALE" ) && has_ime_visible_frame &&
ime_visible && ime_visible_frame.w > 0 && ime_visible_frame.h > 0 ) {
const int ime_right = ime_visible_frame.x + ime_visible_frame.w;
const int ime_bottom = ime_visible_frame.y + ime_visible_frame.h;
static SDL_Rect get_android_render_rect( const int buffer_w, const int buffer_h )
{
const SDL_Rect bounds = android_layout_bounds();
const point size = terminal_layout::present_size( point( buffer_w, buffer_h ),
point( bounds.w, bounds.h ), android_buffer_scale );
// top-aligned so the free area stays below the content, centered horizontally
SDL_Rect dstrect;
dstrect.w = size.x;
dstrect.h = size.y;
dstrect.x = bounds.x + ( bounds.w - size.x ) / 2;
dstrect.y = bounds.y;
const std::optional<SDL_Rect> ime_visible_frame = android_visible_ime_frame();
if( get_option<bool>( "ANDROID_KEYBOARD_SCREEN_SCALE" ) && ime_visible_frame ) {
const int ime_right = ime_visible_frame->x + ime_visible_frame->w;
int ime_bottom = ime_visible_frame->y + ime_visible_frame->h;
if( android_shortcuts_above_keyboard() ) {
ime_bottom -= static_cast<int>( quick_shortcut_height() );
}
if( ime_right < dstrect.x + dstrect.w ) {
dstrect.w = std::max( 1, ime_right - dstrect.x );
}
@@ -1063,7 +1211,6 @@ void refresh_display()
#endif
#if defined(__ANDROID__)
draw_terminal_size_preview();
if( g ) {
draw_quick_shortcuts();
}
@@ -2339,6 +2486,12 @@ void renderer_recovery_test_support::teardown_software_renderer()
// font's textures go while renderer lives; its TTF_Font closes before
// TTF_Quit
fixture_font.reset();
if( test_fixture_fonts_saved ) {
font = std::move( test_fixture_saved_font );
gui_font = std::move( test_fixture_saved_gui_font );
terminal_glyphs_changed = test_fixture_saved_glyphs_changed;
test_fixture_fonts_saved = false;
}
if( test_fixture_acquired_ttf ) {
TTF_Quit();
test_fixture_acquired_ttf = false;
@@ -2754,7 +2907,8 @@ bool renderer_resource_coordinator::apply_resize_only( const uint32_t serviced_r
}
// The drawable can change with the buffer kept (DPI-only), so re-arm present.
needupdate = true;
if( buffer_changed ) {
const bool glyphs_changed = std::exchange( terminal_glyphs_changed, false );
if( buffer_changed || glyphs_changed ) {
run_post_success_full_invalidation();
}
return true;
@@ -3885,6 +4039,44 @@ Font *renderer_recovery_test_support::test_font()
return fixture_font.get();
}
bool renderer_recovery_test_support::rebuild_terminal_fonts( const point &cell,
const int point_size, const std::vector<font_config> &typefaces,
const std::vector<font_config> &gui_typefaces )
{
if( !renderer ) {
return false;
}
if( TTF_WasInit() == 0 ) {
if( !TTF_Init() ) {
return false;
}
test_fixture_acquired_ttf = true;
}
if( !test_fixture_fonts_saved ) {
// teardown restores these, and the cell from test_fixture_saved
test_fixture_saved_font = std::move( font );
test_fixture_saved_gui_font = std::move( gui_font );
test_fixture_saved_glyphs_changed = terminal_glyphs_changed;
test_fixture_fonts_saved = true;
}
return ::rebuild_terminal_fonts( cell, point_size, typefaces, gui_typefaces, false );
}
point renderer_recovery_test_support::terminal_cell()
{
return point( fontwidth, fontheight );
}
const Font *renderer_recovery_test_support::terminal_font()
{
return font.get();
}
const Font *renderer_recovery_test_support::terminal_gui_font()
{
return gui_font.get();
}
// pixel minimap window: draw its text, clear its area, then `paint`; false
// when draw_window's shader unbind failed and invalidated `draw_scope`
static bool draw_minimap_window( Font_Ptr &font, const catacurses::window &w, const bool force_full,
@@ -4437,9 +4629,38 @@ static input_event sdl_keysym_to_keycode_evt( const CataKeysym &keysym )
return evt;
}
// Refresh the window and drawable tracks from a new logical size, and on desktop
// the terminal-derived layout. Returns whether the terminal layout was recomputed
// (false on android, which keeps a window-independent terminal across rotation).
// build the terminal and gui fonts at `cell` and swap them in, then have ImGui follow.
// false keeps the old fonts and cell
static bool rebuild_terminal_fonts( const point &cell, const int point_size,
const std::vector<font_config> &typefaces,
const std::vector<font_config> &gui_typefaces, const bool blending )
{
Font_Ptr new_font;
Font_Ptr new_gui_font;
try {
new_font = std::make_unique<FontFallbackList>( renderer, pixel_format, cell.x, cell.y,
windowsPalette, typefaces, point_size, blending );
new_gui_font = std::make_unique<FontFallbackList>( renderer, pixel_format, cell.x, cell.y,
windowsPalette, gui_typefaces, point_size, blending );
} catch( const std::exception &err ) {
dbg( D_WARNING ) << "failed to build " << cell.x << "x" << cell.y << " terminal fonts: "
<< err.what();
return false;
}
font = std::move( new_font );
gui_font = std::move( new_gui_font );
::fontwidth = cell.x;
::fontheight = cell.y;
terminal_glyphs_changed = true;
if( imclient ) {
imclient->reload_fonts( gui_typefaces, typefaces );
}
return true;
}
// Refresh the window and drawable tracks from a new logical size, and the
// terminal layout: from the window on desktop, from the orientation and options
// on android. Returns whether the terminal layout was recomputed.
static bool apply_resize_layout( int w, int h )
{
const bool logical_changed = w != WindowWidth || h != WindowHeight;
@@ -4448,7 +4669,26 @@ static bool apply_resize_layout( int w, int h )
refresh_drawable_dims();
#if defined(__ANDROID__)
( void )logical_changed;
return false;
const android_text_layout want = android_desired_layout();
android_buffer_scale = want.scale;
point grid = want.grid;
bool cell_changed = false;
if( want.cell != point( fontwidth, fontheight ) ) {
cell_changed = rebuild_terminal_fonts( want.cell, android_font_point_size( want.cell ),
android_fonts.typeface, android_fonts.gui_typeface,
android_fonts.fontblending );
if( !cell_changed ) {
grid = android_grid_for( point( fontwidth, fontheight ), want.scale );
}
}
// a new cell changes every pixel size even at the same grid, so lay out again
if( !cell_changed && grid.x == TERMINAL_WIDTH && grid.y == TERMINAL_HEIGHT ) {
return false;
}
TERMINAL_WIDTH = grid.x;
TERMINAL_HEIGHT = grid.y;
catacurses::stdscr = catacurses::newwin( TERMINAL_HEIGHT, TERMINAL_WIDTH, point::zero );
return true;
#else
if( logical_changed ) {
// A minimal window size is set during initialization, but some platforms
@@ -4471,6 +4711,13 @@ void resize_term( const int cell_w, const int cell_h )
renderer_coordinator.notify_resize();
}
void request_terminal_relayout()
{
renderer_coordinator.notify_resize();
// drain runs at the top of CheckMessages; wake a blocked input wait
PushWakeEvent();
}
void toggle_fullscreen_window()
{
// Can't enter fullscreen on Emscripten.
@@ -4603,9 +4850,18 @@ float android_get_display_density()
return ans;
}
// Drawn height of the quick shortcut strip, in window pixels.
static float quick_shortcut_height()
{
const float shortcut_dimensions_authored_density = 3.0f; // 480p xxhdpi
const float screen_density_scale = android_get_display_density() /
shortcut_dimensions_authored_density;
return std::floor( screen_density_scale * get_option<int>( "ANDROID_SHORTCUT_HEIGHT" ) );
}
// given the active quick shortcuts, returns the dimensions of each quick shortcut button.
void get_quick_shortcut_dimensions( quick_shortcuts_t &qsl, float &border, float &width,
float &height )
static void get_quick_shortcut_dimensions( quick_shortcuts_t &qsl, float &border, float &width,
float &height )
{
const float shortcut_dimensions_authored_density = 3.0f; // 480p xxhdpi
float screen_density_scale = android_get_display_density() / shortcut_dimensions_authored_density;
@@ -4623,7 +4879,61 @@ void get_quick_shortcut_dimensions( quick_shortcuts_t &qsl, float &border, float
}
}
width = std::floor( width );
height = std::floor( screen_density_scale * get_option<int>( "ANDROID_SHORTCUT_HEIGHT" ) );
height = quick_shortcut_height();
}
// quick shortcut placement. landscape: one row along the bottom edge, buttons
// shrunk to fit. portrait: rows of full-width buttons from the top of the free
// area below the game view, as many rows as fit, or one row right above the
// soft keyboard while it is up
struct quick_shortcut_layout {
float border = 0.0f;
float width = 0.0f;
float height = 0.0f;
int per_row = 0;
int count = 0;
float top = 0.0f;
bool right = false;
};
static quick_shortcut_layout get_quick_shortcut_layout( quick_shortcuts_t &qsl )
{
quick_shortcut_layout layout;
get_quick_shortcut_dimensions( qsl, layout.border, layout.width, layout.height );
layout.right = get_option<std::string>( "ANDROID_SHORTCUT_POSITION" ) == "right";
const float usable_width = WindowWidth * get_option<int>( "ANDROID_SHORTCUT_SCREEN_PERCENTAGE" ) *
0.01f;
int rows = 1;
layout.top = WindowHeight - layout.height;
if( terminal_layout::is_portrait( point( WindowWidth, WindowHeight ) ) ) {
const float density_scale = quick_shortcut_height() /
std::max( 1, get_option<int>( "ANDROID_SHORTCUT_HEIGHT" ) );
layout.width = std::floor( density_scale * get_option<int>( "ANDROID_SHORTCUT_WIDTH_MAX" ) );
const std::optional<SDL_Rect> ime_frame = android_visible_ime_frame();
if( ime_frame ) {
layout.top = ime_frame->y + ime_frame->h - layout.height;
} else {
const SDL_Rect bounds = android_layout_bounds();
const float free_top = static_cast<float>( bounds.y + bounds.h );
const int fit_rows = static_cast<int>( ( WindowHeight - free_top ) / layout.height );
if( fit_rows >= 1 ) {
rows = fit_rows;
layout.top = free_top;
}
}
}
layout.per_row = layout.width > 0.0f ? static_cast<int>( usable_width / layout.width ) : 0;
layout.count = std::min( static_cast<int>( qsl.size() ), layout.per_row * rows );
return layout;
}
// cell of button i, border included
static SDL_FRect quick_shortcut_cell( const quick_shortcut_layout &layout, const int i )
{
const int col = i % layout.per_row;
const int row = i / layout.per_row;
const float x = layout.right ? WindowWidth - ( col + 1 ) * layout.width : col * layout.width;
return SDL_FRect{ x, layout.top + row * layout.height, layout.width, layout.height };
}
// Returns the quick shortcut (if any) under the finger's current position, or finger down position if down == true
@@ -4637,31 +4947,15 @@ input_event *get_quick_shortcut_under_finger( bool down = false )
quick_shortcuts_t &qsl = quick_shortcuts_map[get_quick_shortcut_name(
touch_input_context.get_category() )];
float border, width, height;
get_quick_shortcut_dimensions( qsl, border, width, height );
float finger_y = down ? finger_down_y : finger_curr_y;
if( finger_y < WindowHeight - height ) {
return NULL;
}
const quick_shortcut_layout layout = get_quick_shortcut_layout( qsl );
const float finger_x = down ? finger_down_x : finger_curr_x;
const float finger_y = down ? finger_down_y : finger_curr_y;
int i = 0;
bool shortcut_right = get_option<std::string>( "ANDROID_SHORTCUT_POSITION" ) == "right";
float finger_x = down ? finger_down_x : finger_curr_x;
for( std::list<input_event>::iterator it = qsl.begin(); it != qsl.end(); ++it ) {
if( ( i + 1 ) * width > WindowWidth * get_option<int>( "ANDROID_SHORTCUT_SCREEN_PERCENTAGE" ) *
0.01f ) {
continue;
}
i++;
if( shortcut_right ) {
if( finger_x > WindowWidth - ( i * width ) ) {
return &( *it );
}
} else {
if( finger_x < i * width ) {
return &( *it );
}
for( auto it = qsl.begin(); it != qsl.end() && i < layout.count; ++it, ++i ) {
const SDL_FRect cell = quick_shortcut_cell( layout, i );
if( finger_x >= cell.x && finger_x < cell.x + cell.w &&
finger_y >= cell.y && finger_y < cell.y + cell.h ) {
return &( *it );
}
}
@@ -4865,26 +5159,6 @@ void remove_stale_inventory_quick_shortcuts()
}
}
// Draw preview of terminal size when adjusting values
void draw_terminal_size_preview()
{
bool preview_terminal_dirty = preview_terminal_width != get_option<int>( "TERMINAL_X" ) * fontwidth
||
preview_terminal_height != get_option<int>( "TERMINAL_Y" ) * fontheight;
if( preview_terminal_dirty ||
( preview_terminal_change_time > 0 && GetTicks() - preview_terminal_change_time < 1000 ) ) {
if( preview_terminal_dirty ) {
preview_terminal_width = get_option<int>( "TERMINAL_X" ) * fontwidth;
preview_terminal_height = get_option<int>( "TERMINAL_Y" ) * fontheight;
preview_terminal_change_time = GetTicks();
}
SetRenderDrawColor( renderer, 255, 255, 255, 255 );
SDL_Rect previewrect = get_android_render_rect( preview_terminal_width, preview_terminal_height );
RenderDrawRect( renderer, &previewrect );
SetRenderDrawColor( renderer, 0, 0, 0, 255 );
}
}
// Mark the frame dirty after an Android keyboard / shortcut-bar state change so
// the strip is rebuilt to reflect the new state on the next draw pass.
static void android_request_repaint()
@@ -4906,7 +5180,10 @@ static bool android_keyboard_occludes_shortcuts()
bool has_frame = false;
bool visible = false;
visible_frame_inbox.read_frame( frame, has_frame, visible );
return has_frame ? ( visible && frame.h > 0 ) : true;
if( !has_frame ) {
return true;
}
return visible && frame.h > 0 && !android_shortcuts_above_keyboard();
}
// Draw quick shortcuts on top of the game view
@@ -4967,17 +5244,17 @@ void draw_quick_shortcuts()
reorder_quick_shortcuts( qsl );
}
float border, width, height;
get_quick_shortcut_dimensions( qsl, border, width, height );
const quick_shortcut_layout layout = get_quick_shortcut_layout( qsl );
const float border = layout.border;
const float width = layout.width;
const float height = layout.height;
input_event *hovered_quick_shortcut = get_quick_shortcut_under_finger();
SDL_Rect rect;
bool hovered, show_hint;
int i = 0;
for( std::list<input_event>::iterator it = qsl.begin(); it != qsl.end(); ++it ) {
if( ( i + 1 ) * width > WindowWidth * get_option<int>( "ANDROID_SHORTCUT_SCREEN_PERCENTAGE" ) *
0.01f ) {
continue;
}
for( std::list<input_event>::iterator it = qsl.begin(); it != qsl.end() &&
i < layout.count; ++it ) {
const SDL_FRect cell = quick_shortcut_cell( layout, i );
input_event &event = *it;
std::string text = event.text;
int key = event.get_first_input();
@@ -5022,10 +5299,7 @@ void draw_quick_shortcuts()
show_hint = false;
}
}
if( shortcut_right )
rect = { WindowWidth - static_cast<int>( ( i + 1 ) * width + border ), static_cast<int>( WindowHeight - height ), static_cast<int>( width - border * 2 ), static_cast<int>( height ) };
else
rect = { static_cast<int>( i * width + border ), static_cast<int>( WindowHeight - height ), static_cast<int>( width - border * 2 ), static_cast<int>( height ) };
rect = { static_cast<int>( cell.x + border ), static_cast<int>( cell.y ), static_cast<int>( width - border * 2 ), static_cast<int>( height ) };
if( hovered ) {
SetRenderDrawColor( renderer, 0, 0, 0, 255 );
} else {
@@ -5036,10 +5310,7 @@ void draw_quick_shortcuts()
RenderFillRect( renderer, &rect );
if( hovered ) {
// draw a second button hovering above the first one
if( shortcut_right )
rect = { WindowWidth - static_cast<int>( ( i + 1 ) * width + border ), static_cast<int>( WindowHeight - height * 2.2f ), static_cast<int>( width - border * 2 ), static_cast<int>( height ) };
else
rect = { static_cast<int>( i * width + border ), static_cast<int>( WindowHeight - height * 2.2f ), static_cast<int>( width - border * 2 ), static_cast<int>( height ) };
rect = { static_cast<int>( cell.x + border ), static_cast<int>( cell.y - height * 1.2f ), static_cast<int>( width - border * 2 ), static_cast<int>( height ) };
SetRenderDrawColor( renderer, 0, 0, 196, 255 );
RenderFillRect( renderer, &rect );
@@ -5053,16 +5324,10 @@ void draw_quick_shortcuts()
}
SetRenderDrawBlendMode( renderer, SDL_BLENDMODE_NONE );
RenderSetScale( renderer, text_scale, text_scale );
int text_x, text_y;
if( shortcut_right ) {
text_x = ( WindowWidth - ( i + 0.5f ) * width - ( font->width * utf8_width(
text ) ) * text_scale * 0.5f ) / text_scale;
} else {
text_x = ( ( i + 0.5f ) * width - ( font->width * utf8_width( text ) ) * text_scale * 0.5f ) /
int text_x = ( cell.x + 0.5f * width - ( font->width * utf8_width( text ) ) * text_scale * 0.5f ) /
text_scale;
}
// TODO use draw_string instead
text_y = ( WindowHeight - ( height + font->height * text_scale ) * 0.5f ) / text_scale;
int text_y = ( cell.y + ( height - font->height * text_scale ) * 0.5f ) / text_scale;
font->OutputChar( renderer, text, point( text_x + 1, text_y + 1 ), 0,
get_option<int>( "ANDROID_SHORTCUT_OPACITY_SHADOW" ) * 0.01f );
font->OutputChar( renderer, text, point( text_x, text_y ),
@@ -5096,9 +5361,6 @@ void draw_quick_shortcuts()
}
RenderSetScale( renderer, 1.0f, 1.0f );
i++;
if( ( i + 1 ) * width > WindowWidth ) {
break;
}
}
}
@@ -5462,6 +5724,22 @@ static void CheckMessages()
needupdate = true;
ui_manager::redraw_invalidated();
}
static uint32_t last_seen_safe_area_seq = 0;
const uint32_t cur_safe_area_seq = safe_area_inbox.even_sequence();
if( cur_safe_area_seq != last_seen_safe_area_seq ) {
last_seen_safe_area_seq = cur_safe_area_seq;
// safe area sets render bounds and portrait free height
needupdate = true;
ui_manager::redraw_invalidated();
request_terminal_relayout();
}
static uint32_t last_seen_outer_size_seq = 0;
const uint32_t cur_outer_size_seq = outer_size_inbox.even_sequence();
if( cur_outer_size_seq != last_seen_outer_size_seq ) {
last_seen_outer_size_seq = cur_outer_size_seq;
// auto text size follows the outer window
request_terminal_relayout();
}
uint32_t ticks = GetTicks();
@@ -5693,6 +5971,8 @@ static void CheckMessages()
( get_option<int>( "ANDROID_INITIAL_DELAY" ) ) ) {
if( !quick_shortcuts_toggle_handled ) {
quick_shortcuts_enabled = !quick_shortcuts_enabled;
// landscape bounds keep room for the strip only while it shows
request_terminal_relayout();
quick_shortcuts_toggle_handled = true;
android_request_repaint();
refresh_display();
@@ -5834,6 +6114,10 @@ static void CheckMessages()
// pick up the new bounds when a cutout or inset changes.
needupdate = true;
ui_manager::redraw_invalidated();
#if defined(__ANDROID__)
// it also sets the portrait free height, so the grid can change
request_terminal_relayout();
#endif
break;
#if defined(__ANDROID__)
case CATA_WINDOWEVENT_RESTORED:
@@ -6273,6 +6557,7 @@ static void CheckMessages()
int three_tap_key = 0; //get_option<int>( "ANDROID_3_TAP_KEY" );
if( three_tap_key == 0 ) { // not set
quick_shortcuts_enabled = !quick_shortcuts_enabled;
request_terminal_relayout();
quick_shortcuts_toggle_handled = true;
@@ -6420,7 +6705,12 @@ static std::pair<float, float> get_display_scale( int display_index )
static void init_term_size_and_scaling_factor()
{
scaling_factor = 1;
#if defined(__ANDROID__)
// WinCreate sizes the grid from the screen and the text size; start from the minimum
point terminal( EVEN_MINIMUM_TERM_WIDTH, EVEN_MINIMUM_TERM_HEIGHT );
#else
point terminal( get_option<int>( "TERMINAL_X" ), get_option<int>( "TERMINAL_Y" ) );
#endif
#if !defined(__ANDROID__)
@@ -6527,9 +6817,12 @@ void catacurses::init_interface()
font_loader fl;
fl.load();
#if !defined(__ANDROID__)
// Android picks the cell in WinCreate, from the text size
fl.fontwidth = get_option<int>( "FONT_WIDTH" );
fl.fontheight = get_option<int>( "FONT_HEIGHT" );
fl.fontsize = get_option<int>( "FONT_SIZE" );
#endif
fl.fontblending = get_option<bool>( "FONT_BLENDING" );
fl.map_fontsize = get_option<int>( "MAP_FONT_SIZE" );
fl.map_fontwidth = get_option<int>( "MAP_FONT_WIDTH" );
@@ -6542,7 +6835,17 @@ void catacurses::init_interface()
init_term_size_and_scaling_factor();
#if defined(__ANDROID__)
android_fonts = fl;
#endif
WinCreate();
#if defined(__ANDROID__)
// WinCreate picked the cell for this screen; build the terminal fonts at it
fl.fontwidth = ::fontwidth;
fl.fontheight = ::fontheight;
fl.fontsize = android_font_point_size( point( ::fontwidth, ::fontheight ) );
#endif
refresh_mouse_config();
dbg( D_INFO ) << "Initializing SDL Tiles context";
fartilecontext = std::make_shared<cata_tiles>( renderer, geometry, ts_cache );
@@ -6625,9 +6928,8 @@ void catacurses::init_interface()
//newwin calls `new WINDOW`, and that will throw, but not return nullptr.
imclient->load_fonts( gui_font, font, windowsPalette, fl.gui_typeface, fl.typeface );
#if defined(__ANDROID__)
// Make sure we initialize preview_terminal_width/height to sensible values
preview_terminal_width = TERMINAL_WIDTH * fontwidth;
preview_terminal_height = TERMINAL_HEIGHT * fontheight;
// window may have rotated before resize watch was registered
renderer_coordinator.notify_resize();
#endif
// Base UI is up: allow recovery (see finish_bootstrap) and service any inbox
// work queued during startup.
+130
View File
@@ -0,0 +1,130 @@
#include "terminal_layout.h"
#include <algorithm>
#include <cstdint>
#include <optional>
#include <string>
#include <vector>
#include "game_constants.h"
namespace terminal_layout
{
bool is_portrait( const point &window )
{
return window.y > window.x;
}
int portrait_reserved_bottom( const int window_height, const int reserve_percent,
const int shortcut_strip )
{
return std::max( window_height * reserve_percent / 100, shortcut_strip );
}
const std::vector<point> &text_size_presets()
{
static const std::vector<point> presets = {
point( 6, 12 ), point( 8, 14 ), point( 8, 16 ), point( 10, 18 ), point( 10, 20 ),
point( 11, 22 ), point( 12, 24 ), point( 14, 28 ), point( 16, 32 )
};
return presets;
}
std::string text_size_id( const point &cell )
{
return std::to_string( cell.x ) + "x" + std::to_string( cell.y );
}
std::optional<point> parse_text_size( const std::string &id )
{
for( const point &cell : text_size_presets() ) {
if( text_size_id( cell ) == id ) {
return cell;
}
}
return std::nullopt;
}
point custom_text_size( const int height )
{
const int h = std::max( height, 1 );
return point( ( h + 1 ) / 2, h );
}
int narrow_side( const point &area )
{
return std::min( area.x, area.y );
}
int sizing_reference( const point &window, const point &outer )
{
if( outer.x > 0 && outer.y > 0 ) {
return narrow_side( outer );
}
return narrow_side( window );
}
point auto_text_size( const int narrow )
{
point best = text_size_presets().front();
for( const point &cell : text_size_presets() ) {
if( cell.x * EVEN_MINIMUM_TERM_WIDTH <= narrow ) {
best = cell;
}
}
return best;
}
point resolve_text_size( const std::string &choice, const int custom_height, const int narrow )
{
if( choice == "custom" ) {
return custom_text_size( custom_height );
}
const std::optional<point> preset = parse_text_size( choice );
return preset ? *preset : auto_text_size( narrow );
}
point fit_grid( const point &bounds, const point &cell, const point &caps )
{
point grid( EVEN_MINIMUM_TERM_WIDTH, EVEN_MINIMUM_TERM_HEIGHT );
if( cell.x > 0 && cell.y > 0 ) {
grid = point( std::max( bounds.x, 0 ) / cell.x, std::max( bounds.y, 0 ) / cell.y );
}
if( caps.x > 0 ) {
grid.x = std::min( grid.x, caps.x );
}
if( caps.y > 0 ) {
grid.y = std::min( grid.y, caps.y );
}
return point( std::clamp( grid.x, EVEN_MINIMUM_TERM_WIDTH, MAXIMUM_TERM_WIDTH ),
std::clamp( grid.y, EVEN_MINIMUM_TERM_HEIGHT, MAXIMUM_TERM_HEIGHT ) );
}
int bitmap_scale( const int narrow, const int cell_width )
{
if( cell_width <= 0 ) {
return 1;
}
return std::max( 1, narrow / ( cell_width * EVEN_MINIMUM_TERM_WIDTH ) );
}
point present_size( const point &buffer, const point &bounds, const int scale )
{
if( buffer.x <= 0 || buffer.y <= 0 || bounds.x <= 0 || bounds.y <= 0 ) {
return point::zero;
}
for( int k = std::max( scale, 1 ); k >= 1; --k ) {
if( buffer.x * k <= bounds.x && buffer.y * k <= bounds.y ) {
return point( buffer.x * k, buffer.y * k );
}
}
if( static_cast<int64_t>( bounds.x ) * buffer.y < static_cast<int64_t>( bounds.y ) * buffer.x ) {
return point( bounds.x, static_cast<int>( static_cast<int64_t>( bounds.x ) * buffer.y /
buffer.x ) );
}
return point( static_cast<int>( static_cast<int64_t>( bounds.y ) * buffer.x / buffer.y ),
bounds.y );
}
} // namespace terminal_layout
+52
View File
@@ -0,0 +1,52 @@
#pragma once
#ifndef CATA_SRC_TERMINAL_LAYOUT_H
#define CATA_SRC_TERMINAL_LAYOUT_H
#include <optional>
#include <string>
#include <vector>
#include "point.h"
// Terminal grid sizing for windows that change orientation (Android)
namespace terminal_layout
{
// window taller than it is wide. a square window counts as landscape
bool is_portrait( const point &window );
// pixels kept free along the bottom of a portrait window: the given share of
// the height, or the shortcut strip if that's taller
int portrait_reserved_bottom( int window_height, int reserve_percent, int shortcut_strip );
// cell sizes the bundled Terminus draws pixel-exact, smallest first. each is one
// of its bitmap strikes, used at a point size equal to the cell height
const std::vector<point> &text_size_presets();
// option id of a cell size, like "8x16"
std::string text_size_id( const point &cell );
// preset cell with this id, nullopt for anything else
std::optional<point> parse_text_size( const std::string &id );
// cell for a custom height: half as wide, rounded up
point custom_text_size( int height );
// shorter side of an area, the same in either orientation
int narrow_side( const point &area );
// pixels the text size is chosen against: the short side of the outer window, which
// keeps its size when bars inset the content, else of the SDL window
int sizing_reference( const point &window, const point &outer );
// largest preset whose 80 columns fit across `narrow` pixels, else the smallest
point auto_text_size( int narrow );
// cell for text size choice: "auto", "custom" or a preset id. unknown is auto
point resolve_text_size( const std::string &choice, int custom_height, int narrow );
// cells of `cell` fitting `bounds`, each axis lowered to its cap when the cap is
// above 0, then held within the supported terminal size. a grid held up to the
// minimum is bigger than the bounds
point fit_grid( const point &bounds, const point &cell, const point &caps );
// whole zoom of a bitmap cell `cell_width` wide so 80 columns fit `narrow`, at least 1
int bitmap_scale( int narrow, int cell_width );
// size a buffer is drawn at within bounds: `scale` times, or the largest smaller
// whole multiple that fits. a buffer bigger than bounds shrinks, keeping its aspect
point present_size( const point &buffer, const point &bounds, int scale );
} // namespace terminal_layout
#endif // CATA_SRC_TERMINAL_LAYOUT_H
+63
View File
@@ -12,6 +12,7 @@
#include "cata_imgui.h"
#include "cata_scope_helpers.h"
#include "cata_tiles.h"
#include "cursesport.h"
#include "font_loader.h"
#include "imgui/imgui.h"
#include "options_helpers.h"
@@ -20,6 +21,8 @@
#include "sdl_renderer_recovery.h"
#include "sdltiles.h"
class Font;
namespace
{
using ak = recovery_drain_planner::action_kind;
@@ -1191,4 +1194,64 @@ TEST_CASE( "imgui_font_reload_reaches_the_renderer", "[tiles][renderer_recovery]
} );
}
TEST_CASE( "terminal_font_rebuild_changes_cell_or_keeps_state", "[tiles][renderer_recovery]" )
{
software_render_fixture fx;
if( !fx.available() ) {
WARN( "dummy SDL video backend unavailable; skipping" );
return;
}
const std::vector<font_config> faces = { font_config( "data/font/Terminus.ttf" ) };
// FontFallbackList throws on empty list; missing path may resolve to a fallback
const std::vector<font_config> no_faces;
REQUIRE( renderer_recovery_test_support::rebuild_terminal_fonts( point( 8, 16 ), 16, faces,
faces ) );
const point before = renderer_recovery_test_support::terminal_cell();
const Font *font_before = renderer_recovery_test_support::terminal_font();
const Font *gui_before = renderer_recovery_test_support::terminal_gui_font();
GIVEN( "faces that load" ) {
THEN( "the cell becomes the new size" ) {
REQUIRE( renderer_recovery_test_support::rebuild_terminal_fonts( point( 12, 24 ), 24, faces,
faces ) );
CHECK( renderer_recovery_test_support::terminal_cell() == point( 12, 24 ) );
}
}
GIVEN( "no terminal face that loads" ) {
THEN( "both font roots and the cell stay as they were" ) {
CHECK_FALSE( renderer_recovery_test_support::rebuild_terminal_fonts( point( 12, 24 ), 24,
no_faces, faces ) );
CHECK( renderer_recovery_test_support::terminal_cell() == before );
CHECK( renderer_recovery_test_support::terminal_font() == font_before );
CHECK( renderer_recovery_test_support::terminal_gui_font() == gui_before );
}
}
GIVEN( "terminal font builds, gui font fails" ) {
THEN( "neither live font changes" ) {
CHECK_FALSE( renderer_recovery_test_support::rebuild_terminal_fonts( point( 12, 24 ), 24,
faces, no_faces ) );
CHECK( renderer_recovery_test_support::terminal_cell() == before );
CHECK( renderer_recovery_test_support::terminal_font() == font_before );
CHECK( renderer_recovery_test_support::terminal_gui_font() == gui_before );
}
}
}
TEST_CASE( "renderer_coordinator_font_change_redraws_in_full", "[tiles][renderer_recovery]" )
{
software_render_fixture fx;
if( !fx.available() ) {
WARN( "dummy SDL video backend unavailable; skipping" );
return;
}
// same cell size, so the display buffer keeps its dims: only the glyphs change
const point cell = renderer_recovery_test_support::terminal_cell();
const std::vector<font_config> faces = { font_config( "data/font/Terminus.ttf" ) };
REQUIRE( renderer_recovery_test_support::rebuild_terminal_fonts( cell, cell.y, faces, faces ) );
const unsigned epoch_before = cata_cursesport::curses_render_epoch;
renderer_coordinator.notify_resize();
renderer_coordinator.drain_pending();
REQUIRE( renderer_coordinator.is_render_allowed() );
CHECK( cata_cursesport::curses_render_epoch == epoch_before + 1 );
}
#endif // TILES
+395
View File
@@ -0,0 +1,395 @@
#include <optional>
#include <string>
#include <vector>
#if defined(TILES)
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <fstream>
#include <functional>
#include <iterator>
#include <SDL3_ttf/SDL_ttf.h>
#include "cata_scope_helpers.h"
#endif
#include "cata_catch.h"
#include "game_constants.h"
#include "point.h"
#include "terminal_layout.h"
TEST_CASE( "terminal_layout_orientation_follows_window_shape", "[terminal_layout]" )
{
CHECK( terminal_layout::is_portrait( point( 1080, 2400 ) ) );
CHECK_FALSE( terminal_layout::is_portrait( point( 2400, 1080 ) ) );
// square window keeps the landscape terminal
CHECK_FALSE( terminal_layout::is_portrait( point( 1000, 1000 ) ) );
}
TEST_CASE( "terminal_layout_portrait_reserve", "[terminal_layout]" )
{
GIVEN( "shortcut strip overlaps the view" ) {
THEN( "reserve is the percentage of the height" ) {
CHECK( terminal_layout::portrait_reserved_bottom( 2400, 35, 0 ) == 840 );
CHECK( terminal_layout::portrait_reserved_bottom( 2400, 0, 0 ) == 0 );
}
}
GIVEN( "shortcut strip is taller than the percentage" ) {
THEN( "strip wins" ) {
CHECK( terminal_layout::portrait_reserved_bottom( 2400, 1, 130 ) == 130 );
}
}
GIVEN( "percentage that doesn't divide the height" ) {
THEN( "reserve rounds down" ) {
CHECK( terminal_layout::portrait_reserved_bottom( 1001, 33, 0 ) == 330 );
}
}
}
TEST_CASE( "terminal_layout_text_size_ids", "[terminal_layout]" )
{
GIVEN( "preset list" ) {
THEN( "Terminus bitmap strikes, smallest first" ) {
CHECK( terminal_layout::text_size_presets() == std::vector<point> {
point( 6, 12 ), point( 8, 14 ), point( 8, 16 ), point( 10, 18 ), point( 10, 20 ),
point( 11, 22 ), point( 12, 24 ), point( 14, 28 ), point( 16, 32 )
} );
}
THEN( "every id parses back to its cell" ) {
for( const point &cell : terminal_layout::text_size_presets() ) {
CAPTURE( cell );
CHECK( terminal_layout::parse_text_size( terminal_layout::text_size_id( cell ) )
.value_or( point::zero ) == cell );
}
}
}
WHEN( "id names a preset" ) {
THEN( "parses to that cell" ) {
CHECK( terminal_layout::text_size_id( point( 8, 16 ) ) == "8x16" );
CHECK( terminal_layout::parse_text_size( "10x20" ).value_or( point::zero ) == point( 10, 20 ) );
}
}
WHEN( "id is not a preset" ) {
THEN( "nothing parses" ) {
CHECK_FALSE( terminal_layout::parse_text_size( "auto" ).has_value() );
CHECK_FALSE( terminal_layout::parse_text_size( "custom" ).has_value() );
CHECK_FALSE( terminal_layout::parse_text_size( "9x18" ).has_value() );
CHECK_FALSE( terminal_layout::parse_text_size( "8x16 " ).has_value() );
CHECK_FALSE( terminal_layout::parse_text_size( "" ).has_value() );
}
}
}
TEST_CASE( "terminal_layout_custom_text_size", "[terminal_layout]" )
{
GIVEN( "an even height" ) {
THEN( "width is half of it" ) {
CHECK( terminal_layout::custom_text_size( 16 ) == point( 8, 16 ) );
}
}
GIVEN( "odd height" ) {
THEN( "width rounds up" ) {
CHECK( terminal_layout::custom_text_size( 13 ) == point( 7, 13 ) );
CHECK( terminal_layout::custom_text_size( 25 ) == point( 13, 25 ) );
}
}
GIVEN( "a height below one" ) {
THEN( "cell is one pixel" ) {
CHECK( terminal_layout::custom_text_size( 0 ) == point::south_east );
CHECK( terminal_layout::custom_text_size( -5 ) == point::south_east );
}
}
}
TEST_CASE( "terminal_layout_auto_text_size", "[terminal_layout]" )
{
GIVEN( "1080 pixel narrow side" ) {
THEN( "80 columns of 12x24 fit" ) {
CHECK( terminal_layout::auto_text_size( 1080 ) == point( 12, 24 ) );
}
}
GIVEN( "narrow side at a preset boundary" ) {
THEN( "preset that exactly fits is picked" ) {
CHECK( terminal_layout::auto_text_size( 1120 ) == point( 14, 28 ) );
CHECK( terminal_layout::auto_text_size( 1119 ) == point( 12, 24 ) );
CHECK( terminal_layout::auto_text_size( 960 ) == point( 12, 24 ) );
CHECK( terminal_layout::auto_text_size( 959 ) == point( 11, 22 ) );
}
}
GIVEN( "two same-width presets fit" ) {
THEN( "the taller one is picked" ) {
CHECK( terminal_layout::auto_text_size( 640 ) == point( 8, 16 ) );
CHECK( terminal_layout::auto_text_size( 800 ) == point( 10, 20 ) );
}
}
GIVEN( "very wide narrow side" ) {
THEN( "the largest preset is picked" ) {
CHECK( terminal_layout::auto_text_size( 4000 ) == point( 16, 32 ) );
}
}
GIVEN( "a narrow side too small for any preset" ) {
THEN( "smallest preset is picked" ) {
CHECK( terminal_layout::auto_text_size( 479 ) == point( 6, 12 ) );
CHECK( terminal_layout::auto_text_size( 0 ) == point( 6, 12 ) );
}
}
}
TEST_CASE( "terminal_layout_sizing_reference", "[terminal_layout]" )
{
GIVEN( "a rotation with system bars insetting the content" ) {
// portrait: nav bar takes 53 at the bottom; landscape: status bar takes 72 off the
// short side, so the content surfaces are not transposes of each other
const point portrait_window( 1080, 2357 );
const point landscape_window( 2410, 1008 );
const point portrait_outer( 1080, 2410 );
const point landscape_outer( 2410, 1080 );
THEN( "content short sides differ" ) {
CHECK( terminal_layout::narrow_side( portrait_window ) !=
terminal_layout::narrow_side( landscape_window ) );
}
THEN( "outer window gives same reference and text size" ) {
const int portrait = terminal_layout::sizing_reference( portrait_window, portrait_outer );
const int landscape = terminal_layout::sizing_reference( landscape_window, landscape_outer );
CHECK( portrait == 1080 );
CHECK( landscape == 1080 );
CHECK( terminal_layout::auto_text_size( portrait ) ==
terminal_layout::auto_text_size( landscape ) );
}
}
GIVEN( "split-screen" ) {
THEN( "the smaller outer window lowers the reference" ) {
CHECK( terminal_layout::sizing_reference( point( 1080, 1180 ), point( 1080, 1205 ) ) ==
1080 );
CHECK( terminal_layout::sizing_reference( point( 1180, 1080 ), point( 1205, 1080 ) ) ==
1080 );
CHECK( terminal_layout::sizing_reference( point( 700, 1000 ), point( 720, 1000 ) ) == 720 );
}
}
GIVEN( "no outer window report yet" ) {
THEN( "SDL window is used" ) {
CHECK( terminal_layout::sizing_reference( point( 2410, 1008 ), point::zero ) == 1008 );
CHECK( terminal_layout::sizing_reference( point( 2410, 1008 ), point( 0, 1080 ) ) == 1008 );
}
}
}
#if defined(TILES)
// preset cells are bitmap strikes of the bundled Terminus, drawn at a point size equal
// to the cell height; check against the font's EBLC strike sizes and SDL_ttf advances
TEST_CASE( "terminal_layout_presets_are_terminus_strikes", "[terminal_layout]" )
{
const std::string path = "data/font/Terminus.ttf";
std::ifstream file( path, std::ios::binary );
REQUIRE( file.good() );
const std::vector<unsigned char> data( ( std::istreambuf_iterator<char>( file ) ),
std::istreambuf_iterator<char>() );
const auto u16 = [&]( size_t at ) {
return static_cast<uint32_t>( data.at( at ) << 8 | data.at( at + 1 ) );
};
const auto u32 = [&]( size_t at ) {
return u16( at ) << 16 | u16( at + 2 );
};
// table directory: numTables at 4, records of 16 bytes from 12 (tag, checksum, offset, length)
size_t eblc = 0;
for( uint32_t i = 0; i < u16( 4 ); ++i ) {
const size_t rec = 12 + i * 16;
if( std::string( data.begin() + rec, data.begin() + rec + 4 ) == "EBLC" ) {
eblc = u32( rec + 8 );
}
}
REQUIRE( eblc != 0 );
// EBLC: version (4), numSizes (4), then 48 byte BitmapSize records; ppemY at byte 45
std::vector<int> strike_heights;
strike_heights.reserve( u32( eblc + 4 ) );
for( uint32_t i = 0; i < u32( eblc + 4 ); ++i ) {
strike_heights.push_back( data.at( eblc + 8 + i * 48 + 45 ) );
}
std::sort( strike_heights.begin(), strike_heights.end() );
std::vector<int> preset_heights;
for( const point &cell : terminal_layout::text_size_presets() ) {
preset_heights.push_back( cell.y );
}
CHECK( strike_heights == preset_heights );
// balance our own TTF_Init, so this test can't hide a fixture that forgets to init
const bool acquired_ttf = TTF_WasInit() == 0;
REQUIRE( ( !acquired_ttf || TTF_Init() ) );
on_out_of_scope release_ttf( [acquired_ttf]() {
if( acquired_ttf ) {
TTF_Quit();
}
} );
for( const point &cell : terminal_layout::text_size_presets() ) {
CAPTURE( cell );
TTF_Font *font = TTF_OpenFont( path.c_str(), static_cast<float>( cell.y ) );
REQUIRE( font != nullptr );
int advance = 0;
CHECK( TTF_GetGlyphMetrics( font, 'M', nullptr, nullptr, nullptr, nullptr, &advance ) );
CHECK( advance == cell.x );
CHECK( TTF_GetFontHeight( font ) == cell.y );
TTF_CloseFont( font );
}
}
#endif
TEST_CASE( "terminal_layout_resolve_text_size", "[terminal_layout]" )
{
WHEN( "choice is auto" ) {
THEN( "narrow side picks the cell" ) {
CHECK( terminal_layout::resolve_text_size( "auto", 30, 1080 ) == point( 12, 24 ) );
}
}
WHEN( "choice is a preset" ) {
THEN( "the preset is used whatever the screen" ) {
CHECK( terminal_layout::resolve_text_size( "8x14", 30, 1080 ) == point( 8, 14 ) );
}
}
WHEN( "choice is custom" ) {
THEN( "custom height is used" ) {
CHECK( terminal_layout::resolve_text_size( "custom", 30, 1080 ) == point( 15, 30 ) );
}
}
WHEN( "choice is unknown" ) {
THEN( "falls back to auto" ) {
CHECK( terminal_layout::resolve_text_size( "bogus", 30, 1080 ) == point( 12, 24 ) );
}
}
}
TEST_CASE( "terminal_layout_fit_grid", "[terminal_layout]" )
{
const point no_caps;
const point cell( 12, 24 );
// 2340x1080 landscape less 130-pixel shortcut strip
const point landscape( 2340, 950 );
GIVEN( "a portrait area" ) {
THEN( "cells fill it" ) {
CHECK( terminal_layout::fit_grid( point( 1080, 1560 ), cell, no_caps ) == point( 90, 65 ) );
}
THEN( "a partial cell is dropped" ) {
CHECK( terminal_layout::fit_grid( point( 1091, 1583 ), cell, no_caps ) == point( 90, 65 ) );
}
}
GIVEN( "a landscape area" ) {
THEN( "cells fill it" ) {
CHECK( terminal_layout::fit_grid( landscape, cell, no_caps ) == point( 195, 39 ) );
}
WHEN( "columns are capped" ) {
THEN( "width stops at the cap" ) {
CHECK( terminal_layout::fit_grid( landscape, cell, point( 100, 0 ) ) == point( 100, 39 ) );
}
}
WHEN( "rows are capped" ) {
THEN( "height stops at the cap" ) {
CHECK( terminal_layout::fit_grid( landscape, cell, point( 0, 30 ) ) == point( 195, 30 ) );
}
}
WHEN( "caps are above what fits" ) {
THEN( "they change nothing" ) {
CHECK( terminal_layout::fit_grid( landscape, cell, point( 500, 500 ) ) == point( 195, 39 ) );
}
}
WHEN( "caps are below the minimum terminal" ) {
THEN( "minimum wins" ) {
CHECK( terminal_layout::fit_grid( landscape, cell, point( 60, 10 ) ) ==
point( EVEN_MINIMUM_TERM_WIDTH, EVEN_MINIMUM_TERM_HEIGHT ) );
}
}
}
GIVEN( "area too small for 80x24" ) {
THEN( "grid is the minimum and overflows the area" ) {
CHECK( terminal_layout::fit_grid( point( 400, 200 ), point( 8, 16 ), no_caps ) ==
point( EVEN_MINIMUM_TERM_WIDTH, EVEN_MINIMUM_TERM_HEIGHT ) );
}
}
GIVEN( "an area beyond the maximum terminal" ) {
THEN( "grid is the maximum" ) {
CHECK( terminal_layout::fit_grid( point( 100000, 100000 ), point( 6, 12 ), no_caps ) ==
point( MAXIMUM_TERM_WIDTH, MAXIMUM_TERM_HEIGHT ) );
}
}
GIVEN( "empty cell or area" ) {
THEN( "grid is the minimum" ) {
CHECK( terminal_layout::fit_grid( point( 1080, 1560 ), point( 0, 24 ), no_caps ) ==
point( EVEN_MINIMUM_TERM_WIDTH, EVEN_MINIMUM_TERM_HEIGHT ) );
CHECK( terminal_layout::fit_grid( point( -5, -5 ), point( 8, 16 ), no_caps ) ==
point( EVEN_MINIMUM_TERM_WIDTH, EVEN_MINIMUM_TERM_HEIGHT ) );
}
}
}
TEST_CASE( "terminal_layout_bitmap_scale", "[terminal_layout]" )
{
GIVEN( "8-pixel-wide bitmap cell" ) {
THEN( "zoom is the whole multiple that fits 80 columns" ) {
CHECK( terminal_layout::bitmap_scale( 1080, 8 ) == 1 );
CHECK( terminal_layout::bitmap_scale( 1279, 8 ) == 1 );
CHECK( terminal_layout::bitmap_scale( 1280, 8 ) == 2 );
CHECK( terminal_layout::bitmap_scale( 2560, 8 ) == 4 );
}
THEN( "zoom never drops below one" ) {
CHECK( terminal_layout::bitmap_scale( 300, 8 ) == 1 );
}
}
GIVEN( "6-pixel-wide bitmap cell" ) {
THEN( "smaller cells zoom more" ) {
CHECK( terminal_layout::bitmap_scale( 1080, 6 ) == 2 );
}
}
GIVEN( "empty cell" ) {
THEN( "zoom is one" ) {
CHECK( terminal_layout::bitmap_scale( 1080, 0 ) == 1 );
}
}
}
TEST_CASE( "terminal_layout_present_size", "[terminal_layout]" )
{
GIVEN( "a buffer that fits at 1:1" ) {
THEN( "it's drawn unscaled" ) {
CHECK( terminal_layout::present_size( point( 1080, 1560 ), point( 1080, 1560 ), 1 ) ==
point( 1080, 1560 ) );
CHECK( terminal_layout::present_size( point( 1080, 1560 ), point( 1090, 1600 ), 1 ) ==
point( 1080, 1560 ) );
}
}
GIVEN( "a zoom that fits" ) {
THEN( "the buffer is drawn at that zoom" ) {
CHECK( terminal_layout::present_size( point( 640, 384 ), point( 1440, 2000 ), 2 ) ==
point( 1280, 768 ) );
}
}
GIVEN( "a zoom too large for the bounds" ) {
THEN( "largest fitting zoom is used" ) {
CHECK( terminal_layout::present_size( point( 640, 384 ), point( 1440, 2000 ), 3 ) ==
point( 1280, 768 ) );
CHECK( terminal_layout::present_size( point( 800, 400 ), point( 1200, 1000 ), 2 ) ==
point( 800, 400 ) );
}
}
GIVEN( "a zoom below one" ) {
THEN( "it counts as one" ) {
CHECK( terminal_layout::present_size( point( 640, 384 ), point( 1440, 2000 ), 0 ) ==
point( 640, 384 ) );
}
}
GIVEN( "a buffer larger than the bounds" ) {
THEN( "a too wide buffer shrinks to the width" ) {
CHECK( terminal_layout::present_size( point( 640, 384 ), point( 480, 1000 ), 1 ) ==
point( 480, 288 ) );
}
THEN( "a too tall buffer shrinks to the height" ) {
CHECK( terminal_layout::present_size( point( 640, 384 ), point( 2000, 192 ), 1 ) ==
point( 320, 192 ) );
}
}
GIVEN( "empty buffer or bounds" ) {
THEN( "nothing is drawn" ) {
CHECK( terminal_layout::present_size( point( 0, 384 ), point( 1440, 2000 ), 1 ) == point::zero );
CHECK( terminal_layout::present_size( point( 640, 384 ), point::zero, 1 ) == point::zero );
}
}
}