From e479301275f48cf99baaff42fc0e813f6bdbe16b Mon Sep 17 00:00:00 2001 From: Max Starikov Date: Mon, 14 Sep 2026 20:28:42 +0200 Subject: [PATCH 1/5] update tests --- .../textpad/test/EditorNavigationTest.java | 449 ++++++++++++++++++ .../textpad/activities/EditorActivity.java | 130 +++-- app/src/main/res/menu/main_menu.xml | 13 +- app/src/main/res/values-ar/strings.xml | 2 - app/src/main/res/values-de/strings.xml | 2 - app/src/main/res/values-es/strings.xml | 2 - app/src/main/res/values-fr/strings.xml | 2 - app/src/main/res/values-hi/strings.xml | 2 - app/src/main/res/values-it/strings.xml | 2 - app/src/main/res/values-ja/strings.xml | 2 - app/src/main/res/values-pl/strings.xml | 2 - app/src/main/res/values-pt/strings.xml | 2 - app/src/main/res/values-ru/strings.xml | 2 - app/src/main/res/values-tr/strings.xml | 2 - app/src/main/res/values-uk/strings.xml | 2 - app/src/main/res/values-zh-rCN/strings.xml | 2 - app/src/main/res/values-zh-rTW/strings.xml | 2 - app/src/main/res/values-zh/strings.xml | 2 - app/src/main/res/values/strings.xml | 2 - 19 files changed, 541 insertions(+), 83 deletions(-) create mode 100644 app/src/androidTest/java/com/maxistar/textpad/test/EditorNavigationTest.java diff --git a/app/src/androidTest/java/com/maxistar/textpad/test/EditorNavigationTest.java b/app/src/androidTest/java/com/maxistar/textpad/test/EditorNavigationTest.java new file mode 100644 index 00000000..3cb91e1b --- /dev/null +++ b/app/src/androidTest/java/com/maxistar/textpad/test/EditorNavigationTest.java @@ -0,0 +1,449 @@ +package com.maxistar.textpad.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import android.content.Context; +import android.graphics.Rect; +import android.os.SystemClock; +import android.preference.PreferenceManager; +import android.view.InputDevice; +import android.view.Menu; +import android.view.MenuItem; +import android.view.MotionEvent; +import android.widget.EditText; +import android.widget.PopupMenu; +import android.widget.ScrollView; + +import androidx.test.core.app.ActivityScenario; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import androidx.test.platform.app.InstrumentationRegistry; + +import com.maxistar.textpad.R; +import com.maxistar.textpad.ServiceLocator; +import com.maxistar.textpad.activities.EditorActivity; +import com.maxistar.textpad.recovery.RecoveryRepository; +import com.maxistar.textpad.service.SettingsService; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.io.File; + +@RunWith(AndroidJUnit4.class) +public class EditorNavigationTest { + private Context context; + + @Before + public void setUp() { + context = ApplicationProvider.getApplicationContext(); + clearRecovery(); + setEditorPreferences(false, false); + } + + @After + public void tearDown() { + clearRecovery(); + setEditorPreferences(false, true); + } + + @Test + public void twoFingerPanRoutesAxesInStandardScrolling() { + setEditorPreferences(false, false); + + try (ActivityScenario scenario = launchWithContent(longDocument())) { + scenario.onActivity(activity -> { + EditText editor = activity.findViewById(R.id.editText1); + ScrollView scrollView = activity.findViewById(R.id.vscroll); + assertNotNull(scrollView); + resetScroll(editor, scrollView); + + performCompletedPan(editor, 600, 600, 800, 800, 500, 500, 700, 700); + + assertEquals(100, editor.getScrollX()); + assertEquals(0, editor.getScrollY()); + assertEquals(100, scrollView.getScrollY()); + }); + } + } + + @Test + public void twoFingerPanRoutesBothAxesInSimpleScrolling() { + setEditorPreferences(true, false); + + try (ActivityScenario scenario = launchWithContent(longDocument())) { + scenario.onActivity(activity -> { + EditText editor = activity.findViewById(R.id.editText1); + assertNotNull(activity.findViewById(R.id.linear_layout)); + resetScroll(editor, null); + + performCompletedPan(editor, 600, 600, 800, 800, 500, 500, 700, 700); + + assertEquals(100, editor.getScrollX()); + assertEquals(100, editor.getScrollY()); + }); + } + } + + @Test + public void pointerReleaseStopsPanBeforeRemainingPointerMoves() { + setEditorPreferences(true, false); + + try (ActivityScenario scenario = launchWithContent(longDocument())) { + scenario.onActivity(activity -> { + EditText editor = activity.findViewById(R.id.editText1); + resetScroll(editor, null); + long downTime = SystemClock.uptimeMillis(); + + dispatch(editor, event(downTime, downTime, MotionEvent.ACTION_DOWN, + point(300, 300))); + dispatch(editor, event(downTime, downTime + 10, + pointerAction(MotionEvent.ACTION_POINTER_DOWN, 1), + point(300, 300), point(500, 500))); + dispatch(editor, event(downTime, downTime + 20, MotionEvent.ACTION_MOVE, + point(300, 300), point(400, 400))); + dispatch(editor, event(downTime, downTime + 30, + pointerAction(MotionEvent.ACTION_POINTER_UP, 1), + point(300, 300), point(400, 400))); + + int scrollX = editor.getScrollX(); + int scrollY = editor.getScrollY(); + dispatch(editor, event(downTime, downTime + 40, MotionEvent.ACTION_MOVE, + point(300, 300))); + + assertEquals(scrollX, editor.getScrollX()); + assertEquals(scrollY, editor.getScrollY()); + dispatch(editor, event(downTime, downTime + 50, MotionEvent.ACTION_UP, + point(300, 300))); + }); + } + } + + @Test + public void cancelAndThirdPointerTransitionsStopPan() { + setEditorPreferences(true, false); + + try (ActivityScenario scenario = launchWithContent(longDocument())) { + scenario.onActivity(activity -> { + EditText editor = activity.findViewById(R.id.editText1); + resetScroll(editor, null); + + long cancelDownTime = SystemClock.uptimeMillis(); + startPanWithOffset(editor, cancelDownTime); + dispatch(editor, event(cancelDownTime, cancelDownTime + 30, + MotionEvent.ACTION_CANCEL, point(300, 300), point(400, 400))); + int scrollAfterCancelX = editor.getScrollX(); + int scrollAfterCancelY = editor.getScrollY(); + dispatch(editor, event(cancelDownTime, cancelDownTime + 40, + MotionEvent.ACTION_MOVE, point(300, 300))); + assertEquals(scrollAfterCancelX, editor.getScrollX()); + assertEquals(scrollAfterCancelY, editor.getScrollY()); + + resetScroll(editor, null); + long thirdPointerDownTime = SystemClock.uptimeMillis() + 100; + startPanWithOffset(editor, thirdPointerDownTime); + dispatch(editor, event(thirdPointerDownTime, thirdPointerDownTime + 30, + pointerAction(MotionEvent.ACTION_POINTER_DOWN, 2), + point(300, 300), point(400, 400), point(700, 700))); + int scrollAfterThirdPointerX = editor.getScrollX(); + int scrollAfterThirdPointerY = editor.getScrollY(); + dispatch(editor, event(thirdPointerDownTime, thirdPointerDownTime + 40, + MotionEvent.ACTION_MOVE, + point(300, 300), point(400, 400), point(700, 700))); + assertEquals(scrollAfterThirdPointerX, editor.getScrollX()); + assertEquals(scrollAfterThirdPointerY, editor.getScrollY()); + dispatch(editor, event(thirdPointerDownTime, thirdPointerDownTime + 50, + MotionEvent.ACTION_CANCEL, + point(300, 300), point(400, 400), point(700, 700))); + }); + } + } + + @Test + public void panClampsShortAndLongContentBounds() { + setEditorPreferences(true, false); + + try (ActivityScenario shortScenario = launchWithContent("short")) { + shortScenario.onActivity(activity -> { + EditText editor = activity.findViewById(R.id.editText1); + resetScroll(editor, null); + performCompletedPan(editor, 600, 600, 800, 800, 500, 500, 700, 700); + assertEquals(0, editor.getScrollX()); + assertEquals(0, editor.getScrollY()); + }); + } + + try (ActivityScenario longScenario = launchWithContent(longDocument())) { + longScenario.onActivity(activity -> { + EditText editor = activity.findViewById(R.id.editText1); + int maxX = maxHorizontalScroll(editor); + int maxY = Math.max(0, editor.getLayout().getHeight() + + editor.getTotalPaddingTop() + editor.getTotalPaddingBottom() + - editor.getHeight()); + assertTrue(maxX > 0); + assertTrue(maxY > 0); + + editor.scrollTo(maxX, maxY); + performCompletedPan(editor, 600, 600, 800, 800, 500, 500, 700, 700); + assertEquals(maxX, editor.getScrollX()); + assertEquals(maxY, editor.getScrollY()); + + performCompletedPan(editor, 100, 100, 200, 200, + maxX + 300, maxY + 300, maxX + 400, maxY + 400); + assertEquals(0, editor.getScrollX()); + assertEquals(0, editor.getScrollY()); + }); + } + } + + @Test + public void goToMenuStateAndDestinationsWorkInBothLayouts() { + verifyGoToNavigation(false); + verifyGoToNavigation(true); + } + + private void verifyGoToNavigation(boolean simpleScrolling) { + setEditorPreferences(simpleScrolling, true); + try (ActivityScenario scenario = ActivityScenario.launch(EditorActivity.class)) { + scenario.onActivity(activity -> { + EditText editor = activity.findViewById(R.id.editText1); + Menu emptyMenu = inflateEditorMenu(activity, editor); + activity.onPrepareOptionsMenu(emptyMenu); + assertFalse(emptyMenu.findItem(R.id.menu_document_go_to).isEnabled()); + + editor.setText(longDocument()); + editor.setSelection(0); + }); + waitForIdle(); + + scenario.onActivity(activity -> { + EditText editor = activity.findViewById(R.id.editText1); + Menu menu = inflateEditorMenu(activity, editor); + activity.onPrepareOptionsMenu(menu); + MenuItem goTo = menu.findItem(R.id.menu_document_go_to); + assertTrue(goTo.isEnabled()); + assertTrue(goTo.hasSubMenu()); + assertNotNull(menu.findItem(R.id.menu_document_go_to_beginning)); + assertNotNull(menu.findItem(R.id.menu_document_go_to_end)); + + activity.onOptionsItemSelected(menu.findItem(R.id.menu_document_go_to_end)); + }); + waitForIdle(); + scenario.onActivity(activity -> { + EditText editor = activity.findViewById(R.id.editText1); + assertEquals(editor.length(), editor.getSelectionStart()); + assertCaretVisible(editor); + if (simpleScrolling) { + assertTrue(editor.getScrollY() > 0); + } else { + ScrollView scrollView = activity.findViewById(R.id.vscroll); + assertTrue(scrollView.getScrollY() > 0); + } + + Menu menu = inflateEditorMenu(activity, editor); + activity.onOptionsItemSelected(menu.findItem(R.id.menu_document_go_to_beginning)); + }); + waitForIdle(); + scenario.onActivity(activity -> { + EditText editor = activity.findViewById(R.id.editText1); + assertEquals(0, editor.getSelectionStart()); + assertCaretVisible(editor); + }); + } + } + + private ActivityScenario launchWithContent(String content) { + ActivityScenario scenario = ActivityScenario.launch(EditorActivity.class); + scenario.onActivity(activity -> { + EditText editor = activity.findViewById(R.id.editText1); + editor.setText(content); + editor.setSelection(0); + editor.requestFocus(); + }); + waitForIdle(); + return scenario; + } + + private static Menu inflateEditorMenu(EditorActivity activity, EditText anchor) { + PopupMenu popupMenu = new PopupMenu(activity, anchor); + activity.getMenuInflater().inflate(R.menu.main_menu, popupMenu.getMenu()); + return popupMenu.getMenu(); + } + + private static void assertCaretVisible(EditText editor) { + assertNotNull(editor.getLayout()); + int line = editor.getLayout().getLineForOffset(editor.getSelectionStart()); + int[] editorLocation = new int[2]; + editor.getLocationOnScreen(editorLocation); + int caretTop = editorLocation[1] + editor.getTotalPaddingTop() + + editor.getLayout().getLineTop(line) - editor.getScrollY(); + int caretBottom = editorLocation[1] + editor.getTotalPaddingTop() + + editor.getLayout().getLineBottom(line) - editor.getScrollY(); + Rect visible = new Rect(); + assertTrue(editor.getGlobalVisibleRect(visible)); + assertTrue("Caret top must be visible", caretTop >= visible.top); + assertTrue("Caret bottom must be visible", caretBottom <= visible.bottom); + } + + private static int maxHorizontalScroll(EditText editor) { + float maxLineWidth = 0; + for (int line = 0; line < editor.getLayout().getLineCount(); line++) { + maxLineWidth = Math.max(maxLineWidth, editor.getLayout().getLineWidth(line)); + } + int contentWidth = (int) Math.ceil(maxLineWidth) + + editor.getTotalPaddingLeft() + editor.getTotalPaddingRight(); + return Math.max(0, contentWidth - editor.getWidth()); + } + + private static void resetScroll(EditText editor, ScrollView scrollView) { + editor.setSelection(0); + editor.scrollTo(0, 0); + if (scrollView != null) { + scrollView.scrollTo(0, 0); + } + } + + private static void startPanWithOffset(EditText editor, long downTime) { + dispatch(editor, event(downTime, downTime, MotionEvent.ACTION_DOWN, + point(300, 300))); + dispatch(editor, event(downTime, downTime + 10, + pointerAction(MotionEvent.ACTION_POINTER_DOWN, 1), + point(300, 300), point(500, 500))); + dispatch(editor, event(downTime, downTime + 20, MotionEvent.ACTION_MOVE, + point(300, 300), point(400, 400))); + } + + private static void performCompletedPan( + EditText editor, + float startX0, + float startY0, + float startX1, + float startY1, + float endX0, + float endY0, + float endX1, + float endY1 + ) { + long downTime = SystemClock.uptimeMillis(); + dispatch(editor, event(downTime, downTime, MotionEvent.ACTION_DOWN, + point(startX0, startY0))); + dispatch(editor, event(downTime, downTime + 10, + pointerAction(MotionEvent.ACTION_POINTER_DOWN, 1), + point(startX0, startY0), point(startX1, startY1))); + dispatch(editor, event(downTime, downTime + 20, MotionEvent.ACTION_MOVE, + point(endX0, endY0), point(endX1, endY1))); + dispatch(editor, event(downTime, downTime + 30, + pointerAction(MotionEvent.ACTION_POINTER_UP, 1), + point(endX0, endY0), point(endX1, endY1))); + dispatch(editor, event(downTime, downTime + 40, MotionEvent.ACTION_UP, + point(endX0, endY0))); + } + + private static int pointerAction(int action, int pointerIndex) { + return action | (pointerIndex << MotionEvent.ACTION_POINTER_INDEX_SHIFT); + } + + private static float[] point(float x, float y) { + return new float[]{x, y}; + } + + private static MotionEvent event( + long downTime, + long eventTime, + int action, + float[]... points + ) { + MotionEvent.PointerProperties[] properties = + new MotionEvent.PointerProperties[points.length]; + MotionEvent.PointerCoords[] coordinates = new MotionEvent.PointerCoords[points.length]; + for (int index = 0; index < points.length; index++) { + MotionEvent.PointerProperties pointerProperties = new MotionEvent.PointerProperties(); + pointerProperties.id = index; + pointerProperties.toolType = MotionEvent.TOOL_TYPE_FINGER; + properties[index] = pointerProperties; + + MotionEvent.PointerCoords pointerCoords = new MotionEvent.PointerCoords(); + pointerCoords.x = points[index][0]; + pointerCoords.y = points[index][1]; + pointerCoords.pressure = 1; + pointerCoords.size = 1; + coordinates[index] = pointerCoords; + } + return MotionEvent.obtain( + downTime, + eventTime, + action, + points.length, + properties, + coordinates, + 0, + 0, + 1, + 1, + 0, + 0, + InputDevice.SOURCE_TOUCHSCREEN, + 0 + ); + } + + private static void dispatch(EditText editor, MotionEvent event) { + try { + editor.dispatchTouchEvent(event); + } finally { + event.recycle(); + } + } + + private static String longDocument() { + StringBuilder document = new StringBuilder(); + for (int line = 0; line < 120; line++) { + document.append("Line ").append(line).append(' '); + for (int column = 0; column < 120; column++) { + document.append("0123456789"); + } + document.append('\n'); + } + return document.toString(); + } + + private void setEditorPreferences(boolean simpleScrolling, boolean autoWrapping) { + PreferenceManager.getDefaultSharedPreferences(context) + .edit() + .putBoolean(SettingsService.SETTING_USE_SIMPLE_SCROLLING, simpleScrolling) + .putBoolean(SettingsService.SETTING_AUTO_WRAPPING, autoWrapping) + .putBoolean(SettingsService.SETTING_OPEN_LAST_FILE, false) + .commit(); + ServiceLocator.getInstance().getSettingsService(context).reloadSettings(context); + } + + private static void waitForIdle() { + InstrumentationRegistry.getInstrumentation().waitForIdleSync(); + } + + private void clearRecovery() { + context.getSharedPreferences("editor_recovery", Context.MODE_PRIVATE) + .edit() + .clear() + .commit(); + deleteRecursively(new RecoveryRepository(context).getDirectoryForTests()); + } + + private static void deleteRecursively(File file) { + if (!file.exists()) { + return; + } + File[] children = file.listFiles(); + if (children != null) { + for (File child : children) { + deleteRecursively(child); + } + } + file.delete(); + } +} diff --git a/app/src/main/java/com/maxistar/textpad/activities/EditorActivity.java b/app/src/main/java/com/maxistar/textpad/activities/EditorActivity.java index 397ddf2d..0549272f 100644 --- a/app/src/main/java/com/maxistar/textpad/activities/EditorActivity.java +++ b/app/src/main/java/com/maxistar/textpad/activities/EditorActivity.java @@ -46,6 +46,7 @@ import android.view.MotionEvent; import android.view.Menu; import android.view.MenuItem; +import android.view.ViewParent; import android.view.WindowInsets; import android.view.inputmethod.EditorInfo; import android.webkit.WebView; @@ -217,9 +218,6 @@ public void onCreate(Bundle savedInstanceState) { mText = this.findViewById(R.id.editText1); mText.setBackgroundResource(android.R.color.transparent); mText.setOnTouchListener(new TwoFingerPanTouchListener()); - if (!settingsService.isAutoWrapping()) { - disableEditorAutowrapping(); - } editTextUndoRedo = new EditTextUndoRedo(mText, this); setTextWatcher(); @@ -229,6 +227,9 @@ public void onCreate(Bundle savedInstanceState) { scrollView = findViewById(R.id.vscroll); } applyPreferences(); + if (!settingsService.isAutoWrapping()) { + disableEditorAutowrapping(); + } if (savedInstanceState != null) { restoreState(savedInstanceState); @@ -865,6 +866,9 @@ public boolean onPrepareOptionsMenu(Menu menu) { MenuItem redoMenu = menu.findItem(R.id.menu_edit_redo); redoMenu.setEnabled(editTextUndoRedo.getCanRedo()); + MenuItem goToMenu = menu.findItem(R.id.menu_document_go_to); + goToMenu.setEnabled(mText.length() > 0); + updateRecentFiles(menu); if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { @@ -996,8 +1000,10 @@ public boolean onOptionsItemSelected(@NonNull MenuItem item) { saveFile(); } else if (itemId == R.id.menu_document_save_as) { saveAs(); - } else if (itemId == R.id.menu_document_go_to) { - moveCaretPosition(); + } else if (itemId == R.id.menu_document_go_to_beginning) { + moveCaretPosition(0); + } else if (itemId == R.id.menu_document_go_to_end) { + moveCaretPosition(mText.length()); } else if (itemId == R.id.menu_edit_undo) { editUndo(); } else if (itemId == R.id.menu_edit_redo) { @@ -1971,50 +1977,76 @@ private class TwoFingerPanTouchListener implements View.OnTouchListener { private boolean panningActive = false; private float lastFocalX; private float lastFocalY; + private int maxScrollX; + private int maxScrollY; @Override public boolean onTouch(View view, MotionEvent event) { switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: - panningActive = false; + stopPanning(view); return false; case MotionEvent.ACTION_POINTER_DOWN: if (event.getPointerCount() == 2) { - panningActive = true; - view.getParent().requestDisallowInterceptTouchEvent(true); - lastFocalX = focalX(event); - lastFocalY = focalY(event); + startPanning(view, event); + } else { + return stopPanning(view); } return panningActive; case MotionEvent.ACTION_MOVE: if (!panningActive) { return false; } + if (event.getPointerCount() != 2) { + return stopPanning(view); + } float focalX = focalX(event); float focalY = focalY(event); panContent( Math.round(focalX - lastFocalX), - Math.round(focalY - lastFocalY) + Math.round(focalY - lastFocalY), + maxScrollX, + maxScrollY ); lastFocalX = focalX; lastFocalY = focalY; return true; case MotionEvent.ACTION_POINTER_UP: - if (panningActive) { - view.getParent().requestDisallowInterceptTouchEvent(false); - } - return panningActive; + return stopPanning(view); case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: - boolean wasPanning = panningActive; - panningActive = false; - view.getParent().requestDisallowInterceptTouchEvent(false); - return wasPanning; + return stopPanning(view); default: return panningActive; } } + private void startPanning(View view, MotionEvent event) { + panningActive = true; + requestParentInterception(view, true); + lastFocalX = focalX(event); + lastFocalY = focalY(event); + Layout layout = mText.getLayout(); + maxScrollX = calculateMaxHorizontalScroll(layout); + maxScrollY = calculateMaxVerticalScroll(layout); + } + + private boolean stopPanning(View view) { + boolean wasPanning = panningActive; + panningActive = false; + if (wasPanning) { + requestParentInterception(view, false); + } + return wasPanning; + } + + private void requestParentInterception(View view, boolean disallow) { + ViewParent parent = view.getParent(); + if (parent != null) { + parent.requestDisallowInterceptTouchEvent(disallow); + } + } + private float focalX(MotionEvent event) { float sum = 0; for (int i = 0; i < event.getPointerCount(); i++) { @@ -2032,18 +2064,11 @@ private float focalY(MotionEvent event) { } } - private void panContent(int deltaX, int deltaY) { - Layout layout = mText.getLayout(); - int maxX = layout == null ? 0 : - layout.getWidth() + mText.getTotalPaddingLeft() + mText.getTotalPaddingRight() - - mText.getWidth(); - int newX = clampScroll(mText.getScrollX() - deltaX, maxX); + private void panContent(int deltaX, int deltaY, int maxScrollX, int maxScrollY) { + int newX = clampScroll(mText.getScrollX() - deltaX, maxScrollX); if (simpleScrolling()) { - int maxY = layout == null ? 0 : - layout.getHeight() + mText.getTotalPaddingTop() + mText.getTotalPaddingBottom() - - mText.getHeight(); - int newY = clampScroll(mText.getScrollY() - deltaY, maxY); + int newY = clampScroll(mText.getScrollY() - deltaY, maxScrollY); mText.scrollTo(newX, newY); return; } @@ -2054,14 +2079,31 @@ private void panContent(int deltaX, int deltaY) { mText.scrollTo(newX, mText.getScrollY()); } - private int clampScroll(int value, int max) { - if (value < 0) { + private int calculateMaxHorizontalScroll(Layout layout) { + if (layout == null) { return 0; } - if (max > 0 && value > max) { - return max; + float maxLineWidth = 0; + for (int line = 0; line < layout.getLineCount(); line++) { + maxLineWidth = Math.max(maxLineWidth, layout.getLineWidth(line)); } - return value; + int contentWidth = (int) Math.ceil(maxLineWidth) + + mText.getTotalPaddingLeft() + mText.getTotalPaddingRight(); + return Math.max(0, contentWidth - mText.getWidth()); + } + + private int calculateMaxVerticalScroll(Layout layout) { + if (layout == null) { + return 0; + } + int contentHeight = layout.getHeight() + + mText.getTotalPaddingTop() + mText.getTotalPaddingBottom(); + return Math.max(0, contentHeight - mText.getHeight()); + } + + private int clampScroll(int value, int max) { + int boundedMax = Math.max(0, max); + return Math.max(0, Math.min(value, boundedMax)); } // QueryTextListener @@ -2178,20 +2220,10 @@ public boolean onMenuItemActionCollapse(MenuItem menuItem) { } } - private void moveCaretPosition() { - if (mText.length() != 0) { - new AlertDialog.Builder(this) - .setIcon(android.R.drawable.ic_menu_directions) - .setTitle(R.string.Go_To_Title) - .setMessage(R.string.Go_To_Description) - .setPositiveButton(R.string.Go_To_End, - (dialog, which) -> { - mText.setSelection(mText.length()); - }) - .setNegativeButton(R.string.Go_To_Beginning, - (dialog, which) -> { - mText.setSelection(0); - }).show(); - } + private void moveCaretPosition(int position) { + mText.requestFocus(); + mText.setSelection(position); + View editorRoot = findViewById(R.id.editor_root); + mText.post(() -> requestFocusedCaretOnScreen(editorRoot)); } } diff --git a/app/src/main/res/menu/main_menu.xml b/app/src/main/res/menu/main_menu.xml index 5ab60ec8..87afb362 100644 --- a/app/src/main/res/menu/main_menu.xml +++ b/app/src/main/res/menu/main_menu.xml @@ -89,7 +89,16 @@ android:id="@+id/menu_document_go_to" android:title="@string/Go_To" android:icon="@drawable/ic_arrow_forward" - app:iconTint="@color/colorIcon" /> + app:iconTint="@color/colorIcon"> + + + + + - \ No newline at end of file + diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 198bb9ee..1ef88162 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -7,8 +7,6 @@ حفظ حفظ كـ الانتقال إلى - الانتقال إلى الموضع - إلى أين تريد نقل المؤشر؟ البداية النهاية الموقع: %s diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index ac9f22f4..6c62e491 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -7,8 +7,6 @@ Speichern Speichern unter Gehe zu - Zu Position gehen - Wohin möchten Sie den Cursor bewegen? Anfang Ende Lage: %s diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index dbf9145f..a6fb78e9 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -7,8 +7,6 @@ Guardar Guardar como Ir a - Ir a la posición - ¿Dónde quieres mover el cursor? Principio Final Ubicación: %s diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index bc6dd0b0..b9dba8fc 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -6,8 +6,6 @@ Enregistrer Enregistrer sous Aller à - Aller à la position - Où souhaitez-vous déplacer le curseur ? Début Fin Emplacement : %s diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 44fa8864..e9ff88c9 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -9,8 +9,6 @@ सहेजें इस रूप में सहेजें पर जाएँ - स्थिति पर जाएँ - आप कर्सर को कहाँ ले जाना चाहते हैं? शुरुआत अंत स्थान: %s diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 1219f0ab..0563e7e3 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -7,8 +7,6 @@ Salva Salva come Vai a - Vai alla posizione - Dove vuoi spostare il cursore? Inizio Fine Posizione: %s diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index d4f63d94..e74e7475 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -8,8 +8,6 @@ 上書き保存 別名で保存 移動 - 位置に移動 - カーソルをどこに移動しますか? 先頭 末尾 パス: %s diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index ddf5d4a9..3df03186 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -8,8 +8,6 @@ Zapisz Zapisz jako Przejdź do - Przejdź do pozycji - Gdzie chcesz przenieść kursor? Początek Koniec Lokalizacja: %s diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 7ca4cd77..520ed448 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -7,8 +7,6 @@ Salvar Salvar como Ir para - Ir para a posição - Para onde você deseja mover o cursor? Início Fim Local: %s diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 5132e425..8c6f70d8 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -7,8 +7,6 @@ Сохранить Сохранить Как Перейти - Перейти к позиции - Куда вы хотите переместить курсор? Начало Конец Путь: %s diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index efe51a98..eb9c2f87 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -7,8 +7,6 @@ Kaydet Farklı Kaydet Git - Konuma Git - mleci nereye taşımak istiyorsunuz? Başlangıç Son Yer: %s diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 01ba67c9..6c40c517 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -8,8 +8,6 @@ Зберегти Зберегти як Перейти - Перейти до позиції - Куди ви хочете перемістити курсор? Початок Кінець Розташування: %s diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 4baba443..bb4bdc55 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -9,8 +9,6 @@ 保存 另存为 转到 - 转到位置 - 您要将光标移动到哪里? 开头 结尾 位置: %s diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 654e7cdd..267de3bf 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -8,8 +8,6 @@ 儲存 另存新檔 前往 - 前往位置 - 您要將游標移動到哪裡? 開頭 結尾 位置:%s diff --git a/app/src/main/res/values-zh/strings.xml b/app/src/main/res/values-zh/strings.xml index 9985c29b..592c448c 100644 --- a/app/src/main/res/values-zh/strings.xml +++ b/app/src/main/res/values-zh/strings.xml @@ -9,8 +9,6 @@ 保存 另存为 转到 - 转到位置 - 您要将光标移动到哪里? 开头 结尾 位置: %s diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index efa5c79b..0ff1d643 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -8,8 +8,6 @@ Save Save As Go To - Go to Position - Where would you like to move the cursor? Beginning End Location: %s From 5be28d9d5fa8f3aaa038ee922c895b0bd3663598 Mon Sep 17 00:00:00 2001 From: Max Starikov Date: Mon, 14 Sep 2026 20:51:15 +0200 Subject: [PATCH 2/5] fix code review suggestions --- .../textpad/test/EditorNavigationTest.java | 66 +++++++++++++++ .../textpad/activities/EditorActivity.java | 83 +++++++++++++++---- 2 files changed, 132 insertions(+), 17 deletions(-) diff --git a/app/src/androidTest/java/com/maxistar/textpad/test/EditorNavigationTest.java b/app/src/androidTest/java/com/maxistar/textpad/test/EditorNavigationTest.java index 3cb91e1b..747896d7 100644 --- a/app/src/androidTest/java/com/maxistar/textpad/test/EditorNavigationTest.java +++ b/app/src/androidTest/java/com/maxistar/textpad/test/EditorNavigationTest.java @@ -124,6 +124,39 @@ public void pointerReleaseStopsPanBeforeRemainingPointerMoves() { } } + @Test + public void finalUpAfterPanDoesNotMoveCaret() { + setEditorPreferences(true, false); + + try (ActivityScenario scenario = launchWithContent(longDocument())) { + scenario.onActivity(activity -> { + EditText editor = activity.findViewById(R.id.editText1); + resetScroll(editor, null); + editor.setSelection(0); + long downTime = SystemClock.uptimeMillis(); + + dispatch(editor, event(downTime, downTime, MotionEvent.ACTION_DOWN, + point(300, 300))); + dispatch(editor, event(downTime, downTime + 10, + pointerAction(MotionEvent.ACTION_POINTER_DOWN, 1), + point(300, 300), point(500, 500))); + dispatch(editor, event(downTime, downTime + 20, MotionEvent.ACTION_MOVE, + point(250, 250), point(450, 450))); + dispatch(editor, event(downTime, downTime + 30, + pointerAction(MotionEvent.ACTION_POINTER_UP, 1), + point(250, 250), point(450, 450))); + + int selectionStart = editor.getSelectionStart(); + int selectionEnd = editor.getSelectionEnd(); + dispatch(editor, event(downTime, downTime + 40, MotionEvent.ACTION_UP, + point(450, 450))); + + assertEquals(selectionStart, editor.getSelectionStart()); + assertEquals(selectionEnd, editor.getSelectionEnd()); + }); + } + } + @Test public void cancelAndThirdPointerTransitionsStopPan() { setEditorPreferences(true, false); @@ -201,6 +234,39 @@ public void panClampsShortAndLongContentBounds() { } } + @Test + public void horizontalPanBoundsAreCachedAndInvalidatedByTextChanges() { + setEditorPreferences(true, false); + + try (ActivityScenario scenario = launchWithContent(longDocument())) { + scenario.onActivity(activity -> { + EditText editor = activity.findViewById(R.id.editText1); + resetScroll(editor, null); + + int initialCalculations = activity.getHorizontalScrollBoundsCalculationCountForTests(); + performCompletedPan(editor, 600, 600, 800, 800, 500, 500, 700, 700); + int afterFirstPan = activity.getHorizontalScrollBoundsCalculationCountForTests(); + assertEquals(initialCalculations + 1, afterFirstPan); + + resetScroll(editor, null); + performCompletedPan(editor, 600, 600, 800, 800, 500, 500, 700, 700); + assertEquals(afterFirstPan, + activity.getHorizontalScrollBoundsCalculationCountForTests()); + + editor.setText(longDocument() + "extra text invalidates horizontal bounds"); + }); + waitForIdle(); + scenario.onActivity(activity -> { + EditText editor = activity.findViewById(R.id.editText1); + resetScroll(editor, null); + int beforeInvalidatedPan = activity.getHorizontalScrollBoundsCalculationCountForTests(); + performCompletedPan(editor, 600, 600, 800, 800, 500, 500, 700, 700); + assertEquals(beforeInvalidatedPan + 1, + activity.getHorizontalScrollBoundsCalculationCountForTests()); + }); + } + } + @Test public void goToMenuStateAndDestinationsWorkInBothLayouts() { verifyGoToNavigation(false); diff --git a/app/src/main/java/com/maxistar/textpad/activities/EditorActivity.java b/app/src/main/java/com/maxistar/textpad/activities/EditorActivity.java index 0549272f..cd681982 100644 --- a/app/src/main/java/com/maxistar/textpad/activities/EditorActivity.java +++ b/app/src/main/java/com/maxistar/textpad/activities/EditorActivity.java @@ -191,6 +191,11 @@ private static final class SaveRequest { WebView mWebView; + private int cachedMaxHorizontalScroll = 0; + private int cachedHorizontalScrollEditorWidth = -1; + private boolean horizontalScrollBoundsDirty = true; + private int horizontalScrollBoundsCalculationCount = 0; + /** * Called when the activity is first created. */ @@ -218,6 +223,13 @@ public void onCreate(Bundle savedInstanceState) { mText = this.findViewById(R.id.editText1); mText.setBackgroundResource(android.R.color.transparent); mText.setOnTouchListener(new TwoFingerPanTouchListener()); + mText.addOnLayoutChangeListener((view, left, top, right, bottom, + oldLeft, oldTop, oldRight, oldBottom) -> { + if ((right - left) != (oldRight - oldLeft) + || (bottom - top) != (oldBottom - oldTop)) { + invalidateHorizontalScrollBounds(); + } + }); editTextUndoRedo = new EditTextUndoRedo(mText, this); setTextWatcher(); @@ -339,6 +351,7 @@ public void beforeTextChanged(CharSequence s, int start, int count, int after) { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { + invalidateHorizontalScrollBounds(); if (suppressRecoveryTracking) { return; } @@ -760,12 +773,14 @@ private boolean isFilenameEmpty() { } void applyPreferences() { + invalidateHorizontalScrollBounds(); applyFontFace(); applyFontSize(); applyColors(); } private void disableEditorAutowrapping() { + invalidateHorizontalScrollBounds(); mText.setHorizontallyScrolling(true); mText.setHorizontalScrollBarEnabled(true); mText.setMaxLines(Integer.MAX_VALUE); @@ -1975,6 +1990,7 @@ protected void showToast(String toast_str) { private class TwoFingerPanTouchListener implements View.OnTouchListener { private boolean panningActive = false; + private boolean panGestureOwned = false; private float lastFocalX; private float lastFocalY; private int maxScrollX; @@ -1984,21 +2000,25 @@ private class TwoFingerPanTouchListener implements View.OnTouchListener { public boolean onTouch(View view, MotionEvent event) { switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: - stopPanning(view); + endPanGesture(view); return false; case MotionEvent.ACTION_POINTER_DOWN: if (event.getPointerCount() == 2) { startPanning(view, event); } else { - return stopPanning(view); + stopActivePanning(view); } - return panningActive; + return panGestureOwned; case MotionEvent.ACTION_MOVE: - if (!panningActive) { + if (!panGestureOwned) { return false; } + if (!panningActive) { + return true; + } if (event.getPointerCount() != 2) { - return stopPanning(view); + stopActivePanning(view); + return true; } float focalX = focalX(event); float focalY = focalY(event); @@ -2012,32 +2032,42 @@ public boolean onTouch(View view, MotionEvent event) { lastFocalY = focalY; return true; case MotionEvent.ACTION_POINTER_UP: - return stopPanning(view); + if (panGestureOwned) { + stopActivePanning(view); + return true; + } + return false; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: - return stopPanning(view); + return endPanGesture(view); default: - return panningActive; + return panGestureOwned; } } private void startPanning(View view, MotionEvent event) { panningActive = true; + panGestureOwned = true; requestParentInterception(view, true); lastFocalX = focalX(event); lastFocalY = focalY(event); Layout layout = mText.getLayout(); - maxScrollX = calculateMaxHorizontalScroll(layout); + maxScrollX = getMaxHorizontalScroll(layout); maxScrollY = calculateMaxVerticalScroll(layout); } - private boolean stopPanning(View view) { - boolean wasPanning = panningActive; - panningActive = false; - if (wasPanning) { + private void stopActivePanning(View view) { + if (panningActive) { requestParentInterception(view, false); } - return wasPanning; + panningActive = false; + } + + private boolean endPanGesture(View view) { + boolean shouldConsume = panGestureOwned || panningActive; + stopActivePanning(view); + panGestureOwned = false; + return shouldConsume; } private void requestParentInterception(View view, boolean disallow) { @@ -2079,17 +2109,36 @@ private void panContent(int deltaX, int deltaY, int maxScrollX, int maxScrollY) mText.scrollTo(newX, mText.getScrollY()); } - private int calculateMaxHorizontalScroll(Layout layout) { - if (layout == null) { + private int getMaxHorizontalScroll(Layout layout) { + int editorWidth = mText.getWidth(); + if (layout == null || editorWidth <= 0) { return 0; } + if (horizontalScrollBoundsDirty || cachedHorizontalScrollEditorWidth != editorWidth) { + cachedMaxHorizontalScroll = calculateMaxHorizontalScroll(layout, editorWidth); + cachedHorizontalScrollEditorWidth = editorWidth; + horizontalScrollBoundsDirty = false; + } + return cachedMaxHorizontalScroll; + } + + private void invalidateHorizontalScrollBounds() { + horizontalScrollBoundsDirty = true; + } + + public int getHorizontalScrollBoundsCalculationCountForTests() { + return horizontalScrollBoundsCalculationCount; + } + + private int calculateMaxHorizontalScroll(Layout layout, int editorWidth) { + horizontalScrollBoundsCalculationCount++; float maxLineWidth = 0; for (int line = 0; line < layout.getLineCount(); line++) { maxLineWidth = Math.max(maxLineWidth, layout.getLineWidth(line)); } int contentWidth = (int) Math.ceil(maxLineWidth) + mText.getTotalPaddingLeft() + mText.getTotalPaddingRight(); - return Math.max(0, contentWidth - mText.getWidth()); + return Math.max(0, contentWidth - editorWidth); } private int calculateMaxVerticalScroll(Layout layout) { From b2e6b6407f9e3a7fc0d74fd3a1309c9ea303346e Mon Sep 17 00:00:00 2001 From: Max Starikov Date: Sat, 3 Oct 2026 18:56:07 +0200 Subject: [PATCH 3/5] streamline Android release workflow --- .github/workflows/android-test.yml | 6 + .github/workflows/create-release.yml | 71 ++++++--- .github/workflows/promote-production.yml | 21 +-- .github/workflows/release-pr.yml | 6 +- .github/workflows/sync-master-to-dev.yml | 5 + README.md | 4 + docs/RELEASING.md | 158 +++++++++++++++++++ fastlane/README.md | 62 +++++--- release-protection.json | 34 ++++ scripts/release_protection.py | 193 +++++++++++++++++++++++ scripts/release_tool.py | 122 +++++++++++++- scripts/test_release_protection.py | 150 ++++++++++++++++++ scripts/test_release_tool.py | 144 +++++++++++++++++ scripts/test_release_workflows.py | 84 +++++++--- 14 files changed, 988 insertions(+), 72 deletions(-) create mode 100644 docs/RELEASING.md create mode 100644 release-protection.json create mode 100644 scripts/release_protection.py create mode 100644 scripts/test_release_protection.py diff --git a/.github/workflows/android-test.yml b/.github/workflows/android-test.yml index ca292efd..677af37e 100644 --- a/.github/workflows/android-test.yml +++ b/.github/workflows/android-test.yml @@ -24,6 +24,12 @@ jobs: - name: Grant execute permission for gradlew run: chmod +x gradlew + - name: Test release tooling + run: >- + python3 -m unittest + scripts/test_release_tool.py + scripts/test_release_workflows.py + scripts/test_release_protection.py - name: Build with Gradle run: ./gradlew test - uses: actions/upload-artifact@v6 diff --git a/.github/workflows/create-release.yml b/.github/workflows/create-release.yml index fe7afae4..44a97afe 100644 --- a/.github/workflows/create-release.yml +++ b/.github/workflows/create-release.yml @@ -1,22 +1,36 @@ name: Create Android Release on: + pull_request: + branches: [master] + types: [closed] workflow_dispatch: inputs: - version: - description: Expected versionName without the v prefix + head_branch: + description: Merged release/* or hotfix/* branch for recovery required: true type: string commit_sha: - description: Exact merged master commit to tag + description: Exact merge commit contained in master required: true type: string permissions: contents: write + checks: read + pull-requests: read + +concurrency: + group: android-release-${{ github.event.pull_request.merge_commit_sha || inputs.commit_sha }} + cancel-in-progress: false jobs: create-tag: + if: >- + github.event_name == 'workflow_dispatch' || + (github.event.pull_request.merged == true && + (startsWith(github.event.pull_request.head.ref, 'release/') || + startsWith(github.event.pull_request.head.ref, 'hotfix/'))) runs-on: ubuntu-latest environment: release outputs: @@ -24,29 +38,34 @@ jobs: steps: - uses: actions/checkout@v6 with: - ref: master + ref: ${{ github.event.pull_request.merge_commit_sha || inputs.commit_sha }} fetch-depth: 0 - uses: ruby/setup-ruby@v1 with: ruby-version: '3.3' bundler-cache: true - - name: Verify exact master commit + - name: Fetch stable history and tags + run: git fetch origin master --tags + - name: Require successful protected pull-request checks + if: github.event_name == 'pull_request' env: - EXPECTED_SHA: ${{ inputs.commit_sha }} - run: | - git fetch origin master --tags - test "$(git rev-parse HEAD)" = "$EXPECTED_SHA" - test "$(git rev-parse origin/master)" = "$EXPECTED_SHA" - - name: Resolve and verify identity + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: gh pr checks "$PR_NUMBER" --required + - name: Resolve merged release identity id: identity env: - EXPECTED_VERSION: ${{ inputs.version }} + HEAD_BRANCH: ${{ github.event.pull_request.head.ref || inputs.head_branch }} + BASE_BRANCH: ${{ github.event.pull_request.base.ref || 'master' }} + MERGE_COMMIT: ${{ github.event.pull_request.merge_commit_sha || inputs.commit_sha }} + MERGED: ${{ github.event_name == 'workflow_dispatch' || github.event.pull_request.merged }} run: | - python3 scripts/release_tool.py metadata > release-metadata.json - ACTUAL_VERSION=$(python3 -c 'import json; print(json.load(open("release-metadata.json"))["versionName"])') - TAG=$(python3 -c 'import json; print(json.load(open("release-metadata.json"))["tag"])') - test "$ACTUAL_VERSION" = "$EXPECTED_VERSION" - echo "tag=$TAG" >> "$GITHUB_OUTPUT" + python3 scripts/release_tool.py candidate \ + --head-branch "$HEAD_BRANCH" \ + --base-branch "$BASE_BRANCH" \ + --merge-commit "$MERGE_COMMIT" \ + --merged "$MERGED" > release-candidate.json + echo "tag=$(python3 -c 'import json; print(json.load(open("release-candidate.json"))["tag"])')" >> "$GITHUB_OUTPUT" - name: Decode Google Play service account env: SERVICE_ACCOUNT_BASE64: ${{ secrets.GOOGLE_PLAY_SERVICE_ACCOUNT }} @@ -58,12 +77,12 @@ jobs: - name: Create immutable annotated tag env: TAG: ${{ steps.identity.outputs.tag }} - EXPECTED_SHA: ${{ inputs.commit_sha }} + MERGE_COMMIT: ${{ github.event.pull_request.merge_commit_sha || inputs.commit_sha }} run: | test -z "$(git tag --list "$TAG")" git config user.name "github-actions[bot]" git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - git tag -a "$TAG" "$EXPECTED_SHA" -m "Release $TAG" + git tag -a "$TAG" "$MERGE_COMMIT" -m "Release $TAG" git push origin "refs/tags/$TAG" publish: @@ -72,3 +91,17 @@ jobs: with: tag: ${{ needs.create-tag.outputs.tag }} secrets: inherit + + sync-development: + needs: [create-tag, publish] + uses: ./.github/workflows/sync-master-to-dev.yml + with: + tag: ${{ needs.create-tag.outputs.tag }} + secrets: inherit + + promote-production: + needs: [create-tag, publish] + uses: ./.github/workflows/promote-production.yml + with: + tag: ${{ needs.create-tag.outputs.tag }} + secrets: inherit diff --git a/.github/workflows/promote-production.yml b/.github/workflows/promote-production.yml index eee3d51c..c0f8ea0c 100644 --- a/.github/workflows/promote-production.yml +++ b/.github/workflows/promote-production.yml @@ -7,10 +7,11 @@ on: description: Immutable v release tag required: true type: string - version_code: - description: Existing internal-track versionCode + workflow_call: + inputs: + tag: required: true - type: number + type: string permissions: contents: read @@ -28,15 +29,17 @@ jobs: with: ruby-version: '3.3' bundler-cache: true - - name: Verify tag, commit, and versionCode + - name: Verify tag and derive versionCode + id: identity env: TAG: ${{ inputs.tag }} - EXPECTED_CODE: ${{ inputs.version_code }} run: | git fetch origin --tags + test "$(git cat-file -t "$TAG")" = "tag" test "$(git rev-parse HEAD)" = "$(git rev-list -n 1 "$TAG")" - test "$(python3 scripts/release_tool.py metadata | python3 -c 'import json,sys; print(json.load(sys.stdin)["tag"])')" = "$TAG" - test "$(python3 scripts/release_tool.py metadata | python3 -c 'import json,sys; print(json.load(sys.stdin)["versionCode"])')" = "$EXPECTED_CODE" + python3 scripts/release_tool.py metadata > release-metadata.json + test "$(python3 -c 'import json; print(json.load(open("release-metadata.json"))["tag"])')" = "$TAG" + echo "version_code=$(python3 -c 'import json; print(json.load(open("release-metadata.json"))["versionCode"])')" >> "$GITHUB_OUTPUT" - name: Decode Google Play service account env: SERVICE_ACCOUNT_BASE64: ${{ secrets.GOOGLE_PLAY_SERVICE_ACCOUNT }} @@ -44,10 +47,10 @@ jobs: - name: Require the exact version on internal run: >- bundle exec fastlane android assert_track_version_code - version_code:${{ inputs.version_code }} track:internal + version_code:${{ steps.identity.outputs.version_code }} track:internal json_key:${{ github.workspace }}/service-account.json - name: Promote existing internal artifact to completed production run: >- bundle exec fastlane android promote_release - version_code:${{ inputs.version_code }} + version_code:${{ steps.identity.outputs.version_code }} json_key:${{ github.workspace }}/service-account.json diff --git a/.github/workflows/release-pr.yml b/.github/workflows/release-pr.yml index b64c755b..5a91e2e9 100644 --- a/.github/workflows/release-pr.yml +++ b/.github/workflows/release-pr.yml @@ -24,7 +24,11 @@ jobs: - name: Validate release identity and localized notes run: python3 scripts/release_tool.py validate - name: Test release tooling - run: python3 -m unittest scripts/test_release_tool.py + run: >- + python3 -m unittest + scripts/test_release_tool.py + scripts/test_release_workflows.py + scripts/test_release_protection.py - name: Test, lint, and assemble release outputs run: ./gradlew test lint assembleRelease bundleRelease --no-daemon - name: Verify assembled release identity diff --git a/.github/workflows/sync-master-to-dev.yml b/.github/workflows/sync-master-to-dev.yml index b26937bc..537d740a 100644 --- a/.github/workflows/sync-master-to-dev.yml +++ b/.github/workflows/sync-master-to-dev.yml @@ -7,6 +7,11 @@ on: description: Released v tag on master required: true type: string + workflow_call: + inputs: + tag: + required: true + type: string permissions: contents: write diff --git a/README.md b/README.md index fe885c3e..fbe96292 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,10 @@ in pipeline an application uses [maxistar/android](https://github.com/maxistar/a You can use [this service](https://crowdin.com/project/simple-text-editor) to add a new translation or suggest better one +### Maintainer documentation + +- [Android release process](docs/RELEASING.md) + ### To Do many many things to do. diff --git a/docs/RELEASING.md b/docs/RELEASING.md new file mode 100644 index 00000000..5e0385c3 --- /dev/null +++ b/docs/RELEASING.md @@ -0,0 +1,158 @@ +# Android release process + +This is the canonical maintainer guide for TextPad Android releases. The release automation keeps one immutable identity across Gradle, the Git tag, GitHub Release assets, Google Play, and F-Droid. + +## Release identity and invariants + +- `app/build.gradle` is the source of truth for `versionName` and `versionCode`. +- Release tags are annotated and use `v`. Never move or reuse a tag or version code. +- Every Fastlane locale contains `changelogs/.txt` before merge. +- The signed APK and AAB are built once from the tag and published with `SHA256SUMS`. +- Only the APK is uploaded to Google Play because the existing application is not enrolled in Play App Signing. The AAB remains a GitHub Release artifact. +- Production promotion reuses the version already uploaded to Internal; it never rebuilds or resigns the app. +- F-Droid treats the immutable source tag as the canonical release boundary and builds independently. + +## Normal release + +Start from a clean `dev` that exactly matches `origin/dev`. Preview the next identity: + +```sh +python3 scripts/release_tool.py prepare --bump patch --dry-run +python3 scripts/release_tool.py prepare --bump minor --dry-run +python3 scripts/release_tool.py prepare --bump major --dry-run +python3 scripts/release_tool.py prepare --version 2.0.0 --dry-run +``` + +Remove `--dry-run` to create and push `release/`, increment the Gradle version, create localized changelog placeholders, commit them, and open a pull request to `master`: + +```sh +python3 scripts/release_tool.py prepare --bump patch +``` + +Replace every `TODO: RELEASE NOTES` placeholder with reviewed user-facing text. English becomes the GitHub Release body; every configured locale is uploaded to Google Play. The release PR must pass the `build` and `validate` checks and must be merged with a merge commit. + +Merging the validated PR is the release command. No standard Create/Sync dispatch is required: + +```text +dev → release/x.y.z → merge commit on master + │ + ▼ + validate identity and Play + │ + ▼ + tag vX.Y.Z + │ + ▼ + signed APK/AAB + checksums + │ + ▼ + GitHub Release → Play Internal + │ + ┌───────────┴───────────┐ + ▼ ▼ + merge current master → dev Production approval + │ + ▼ + promote existing APK +``` + +The synchronization job does not wait for production approval. Review the Internal release, then approve the pending `production` deployment in GitHub Actions. Delete the release branch only after synchronization succeeds. + +## Hotfix + +Start from a clean `master` that exactly matches `origin/master`: + +```sh +python3 scripts/release_tool.py prepare --bump patch --hotfix --dry-run +python3 scripts/release_tool.py prepare --bump patch --hotfix +``` + +This creates `hotfix/` from the published line and opens a PR to `master`. The same merge-triggered pipeline publishes it and synchronizes `master` back into `dev`; unreleased `dev` work is not part of the tagged artifact. + +```text +master → hotfix/x.y.z → master → tag → Internal + └──────────────→ dev +``` + +## Repository protection audit + +The workflow is safe to activate only when the live GitHub settings match `release-protection.json`: + +```sh +python3 scripts/release_protection.py audit +``` + +The expected settings are: + +- `master`: pull requests required; checks `build` and `validate` required from GitHub Actions app `15368`; force pushes and deletion disabled. +- `dev`: force pushes and deletion disabled. Ordinary fast-forward pushes remain allowed so the narrowly scoped synchronization workflow can push its merge commit; this is the recorded synchronization exception. +- `release`: deployments limited to the `master` branch and `v*` tags. +- `production`: deployments limited to the same refs and approval required from `maxistar`. + +The production environment rule—not the YAML environment name by itself—is the human publication gate. Do not remove its required reviewer while automatic orchestration is enabled. + +## Manual recovery + +Recovery workflows recompute identity from repository state or an immutable tag. They must never be used to move a tag or reuse a version code. + +### Preparation stopped before creating a branch + +Fix the reported preflight condition and rerun `prepare`. It is safe because no mutation occurred. + +### Candidate branch or PR already exists + +Continue editing and validating the existing candidate. Do not rerun preparation to create a competing branch. + +### Release PR merged but tag creation failed + +Run **Create Android Release** manually with the merged `release/*` or `hotfix/*` head branch and exact merge commit SHA. The workflow derives the version and refuses a non-merge, divergent, mismatched, or already-tagged candidate. + +### Tag exists but GitHub or Internal publication failed + +Run **Publish Tagged Android Release** with the existing tag. Complete GitHub assets are downloaded and checksum-verified; the tag is never moved. If a partial GitHub Release is invalid, inspect it before retrying rather than replacing source identity. + +### Internal upload succeeded but synchronization failed + +Resolve the `master`/`dev` conflict without force-pushing, then run **Sync Released Master to Dev** with the release tag. Do not delete the candidate branch until the sync succeeds. + +### Production approval was delayed, rejected, or the job expired + +Run **Promote Android Production** with the tag only. The workflow derives `versionCode`, requires that exact code on Internal, and promotes it without a build or Android keystore. + +### Published artifact is invalid + +Do not roll back by reusing an old code. Prepare a corrected release with a higher `versionCode`. Never move the published tag. + +## Safe verification + +Run repository-owned checks before changing live settings or merging release automation: + +```sh +python3 -m unittest \ + scripts/test_release_tool.py \ + scripts/test_release_workflows.py \ + scripts/test_release_protection.py + +python3 scripts/release_tool.py prepare --bump patch --dry-run +python3 scripts/release_tool.py prepare --bump minor --dry-run +python3 scripts/release_tool.py prepare --bump major --dry-run +python3 scripts/release_tool.py prepare --version 2.0.0 --dry-run +python3 scripts/release_tool.py prepare --bump patch --hotfix --dry-run +``` + +A non-publishing approval rehearsal may dispatch **Promote Android Production** for an existing tag and cancel the run while it is waiting for `production` approval. Do not approve that rehearsal; verify that no tag, GitHub Release, or Play track changes, then cancel it. + +## First real release observation checklist + +- [ ] The merged PR head is `release/` or `hotfix/` and the tagged commit is its merge commit. +- [ ] Exactly one annotated `v` tag exists. +- [ ] GitHub Release contains APK, AAB, and a passing `SHA256SUMS` file from that tag. +- [ ] Google Play Internal contains the same `versionCode` and localized notes. +- [ ] `master` was synchronized into `dev` without a force push. +- [ ] Production remained unchanged until an authorized reviewer approved the deployment. +- [ ] Production received the existing Internal version without a Gradle build or keystore access. +- [ ] Manual publish, sync, and promotion recovery inputs require only immutable or derived identity. + +## Emergency override + +Repository administrators own emergency overrides. Record the reason and retain the same invariants: reviewed source, unique version code, immutable annotated tag, signed checksummed artifacts, Internal-before-Production progression, and `master`-to-`dev` synchronization. diff --git a/fastlane/README.md b/fastlane/README.md index 7ec1207f..d2b5d148 100644 --- a/fastlane/README.md +++ b/fastlane/README.md @@ -1,48 +1,66 @@ -fastlane documentation ----- +# TextPad Fastlane lanes -# Installation - -Make sure you have the latest version of the Xcode command line tools installed: +Install the pinned Ruby dependencies from the repository root: ```sh -xcode-select --install +bundle install ``` -For _fastlane_ installation instructions, see [Installing _fastlane_](https://docs.fastlane.tools/#installing-fastlane) +Release automation normally invokes these lanes from GitHub Actions. Each release lane requires explicit artifact, metadata, credential, track, or version inputs so a local invocation cannot silently publish using defaults. -# Available Actions +## Android lanes -## Android +### `android test` -### android test +Runs Gradle unit tests: ```sh -[bundle exec] fastlane android test +bundle exec fastlane android test ``` -Runs all the tests +### `android beta` + +Legacy Crashlytics Beta lane retained for compatibility. It is not part of the GitHub/Google Play release process. + +### `android validate_play_version_code` -### android beta +Fails if the supplied `versionCode` already exists on Internal, Alpha, Beta, or Production: ```sh -[bundle exec] fastlane android beta +bundle exec fastlane android validate_play_version_code \ + version_code:63 json_key:/absolute/path/service-account.json ``` -Submit a new Beta Build to Crashlytics Beta +### `android assert_track_version_code` -### android deploy +Requires the supplied version code to exist on one explicit Play track: ```sh -[bundle exec] fastlane android deploy +bundle exec fastlane android assert_track_version_code \ + version_code:63 track:internal json_key:/absolute/path/service-account.json ``` -Deploy a new version to the Google Play +### `android upload_release` ----- +Uploads one already-built signed APK and localized metadata to an explicit track. The AAB path is validated and retained by the GitHub release workflow, but `skip_upload_aab` remains enabled because this existing Play application is not enrolled in Play App Signing. -This README.md is auto-generated and will be re-generated every time [_fastlane_](https://fastlane.tools) is run. +```sh +bundle exec fastlane android upload_release \ + apk:/absolute/path/TextPad-v1.31.2.apk \ + aab:/absolute/path/TextPad-v1.31.2.aab \ + version_code:63 \ + metadata_path:/absolute/path/fastlane/metadata/android \ + json_key:/absolute/path/service-account.json \ + track:internal +``` -More information about _fastlane_ can be found on [fastlane.tools](https://fastlane.tools). +### `android promote_release` + +Promotes an existing Internal version to a completed Production release without rebuilding, resigning, or staged rollout. The workflow derives `versionCode` from the immutable release tag before calling this lane. + +```sh +bundle exec fastlane android promote_release \ + version_code:63 json_key:/absolute/path/service-account.json +``` -The documentation of _fastlane_ can be found on [docs.fastlane.tools](https://docs.fastlane.tools). +The end-to-end maintainer process and recovery paths are documented in [the canonical release guide](../docs/RELEASING.md). diff --git a/release-protection.json b/release-protection.json new file mode 100644 index 00000000..a7bc1015 --- /dev/null +++ b/release-protection.json @@ -0,0 +1,34 @@ +{ + "repository": "maxistar/TextPad", + "branches": { + "master": { + "requirePullRequest": true, + "requiredChecks": ["build", "validate"], + "requiredCheckAppId": 15368, + "allowForcePushes": false, + "allowDeletions": false + }, + "dev": { + "requirePullRequest": false, + "requiredChecks": [], + "allowForcePushes": false, + "allowDeletions": false + } + }, + "environments": { + "release": { + "allowedRefs": [ + {"name": "master", "type": "branch"}, + {"name": "v*", "type": "tag"} + ], + "requiredReviewers": [] + }, + "production": { + "allowedRefs": [ + {"name": "master", "type": "branch"}, + {"name": "v*", "type": "tag"} + ], + "requiredReviewers": ["maxistar"] + } + } +} diff --git a/scripts/release_protection.py b/scripts/release_protection.py new file mode 100644 index 00000000..79c6a297 --- /dev/null +++ b/scripts/release_protection.py @@ -0,0 +1,193 @@ +#!/usr/bin/env python3 +"""Audit GitHub repository settings required by the Android release workflow.""" + +from __future__ import annotations + +import argparse +import json +import shutil +import subprocess +import sys +from pathlib import Path +from typing import Sequence + + +ROOT = Path(__file__).resolve().parents[1] +CONFIG_PATH = ROOT / "release-protection.json" + + +class ProtectionError(RuntimeError): + pass + + +def load_config(path: Path = CONFIG_PATH) -> dict: + with path.open(encoding="utf-8") as stream: + config = json.load(stream) + if not config.get("repository") or not config.get("branches") or not config.get("environments"): + raise ProtectionError("release-protection.json is incomplete") + return config + + +def gh_json(endpoint: str, *, allow_missing: bool = False) -> dict: + result = subprocess.run( + ["gh", "api", endpoint], cwd=ROOT, text=True, capture_output=True, check=False + ) + if result.returncode: + message = result.stderr.strip() or result.stdout.strip() or "GitHub API request failed" + if allow_missing and "HTTP 404" in message: + return {} + raise ProtectionError(f"{endpoint}: {message}") + return json.loads(result.stdout) + + +def collect_live_snapshot(config: dict) -> dict: + if not shutil.which("gh"): + raise ProtectionError("GitHub CLI (gh) is required for a live settings audit") + repository = config["repository"] + branches = { + name: gh_json( + f"repos/{repository}/branches/{name}/protection", allow_missing=True + ) + for name in config["branches"] + } + environments = {} + for name in config["environments"]: + environments[name] = { + "environment": gh_json( + f"repos/{repository}/environments/{name}", allow_missing=True + ), + "policies": gh_json( + f"repos/{repository}/environments/{name}/deployment-branch-policies", + allow_missing=True, + ), + } + return {"branches": branches, "environments": environments} + + +def enabled(value: object) -> bool: + if isinstance(value, dict): + return bool(value.get("enabled")) + return bool(value) + + +def reviewer_logins(environment: dict) -> set[str]: + reviewers: set[str] = set() + for rule in environment.get("protection_rules", []): + if rule.get("type") != "required_reviewers": + continue + for item in rule.get("reviewers", []): + reviewer = item.get("reviewer") or {} + login = reviewer.get("login") + if login: + reviewers.add(login) + return reviewers + + +def policy_keys(policies: dict) -> set[tuple[str, str | None]]: + return { + (item.get("name", ""), item.get("type")) + for item in policies.get("branch_policies", []) + } + + +def audit_snapshot(snapshot: dict, config: dict) -> list[str]: + errors: list[str] = [] + actual_branches = snapshot.get("branches", {}) + for name, expected in config["branches"].items(): + actual = actual_branches.get(name) + if not actual: + errors.append(f"branch {name} has no protection") + continue + if expected.get("requirePullRequest") and not actual.get("required_pull_request_reviews"): + errors.append(f"branch {name} does not require pull requests") + contexts = set((actual.get("required_status_checks") or {}).get("contexts", [])) + missing_checks = sorted(set(expected.get("requiredChecks", [])) - contexts) + if missing_checks: + errors.append(f"branch {name} is missing required checks: {', '.join(missing_checks)}") + expected_app_id = expected.get("requiredCheckAppId") + if expected_app_id is not None: + checks = { + item.get("context"): item.get("app_id") + for item in (actual.get("required_status_checks") or {}).get("checks", []) + } + wrong_apps = sorted( + context for context in expected.get("requiredChecks", []) + if checks.get(context) != expected_app_id + ) + if wrong_apps: + errors.append( + f"branch {name} checks are not pinned to app {expected_app_id}: " + + ", ".join(wrong_apps) + ) + if enabled(actual.get("allow_force_pushes")) != expected.get("allowForcePushes", False): + errors.append(f"branch {name} force-push policy does not match") + if enabled(actual.get("allow_deletions")) != expected.get("allowDeletions", False): + errors.append(f"branch {name} deletion policy does not match") + + actual_environments = snapshot.get("environments", {}) + for name, expected in config["environments"].items(): + bundle = actual_environments.get(name) + if not bundle: + errors.append(f"environment {name} is missing") + continue + environment = bundle.get("environment", {}) + branch_policy = environment.get("deployment_branch_policy") or {} + if not branch_policy.get("custom_branch_policies"): + errors.append(f"environment {name} does not restrict deployment refs") + actual_policies = policy_keys(bundle.get("policies", {})) + for required in expected.get("allowedRefs", []): + key = (required["name"], required.get("type")) + legacy_key = (required["name"], None) + if key not in actual_policies and legacy_key not in actual_policies: + errors.append( + f'environment {name} is missing {required.get("type", "ref")} ' + f'policy {required["name"]}' + ) + missing_reviewers = sorted( + set(expected.get("requiredReviewers", [])) - reviewer_logins(environment) + ) + if missing_reviewers: + errors.append( + f"environment {name} is missing required reviewers: " + + ", ".join(missing_reviewers) + ) + return errors + + +def audit(args: argparse.Namespace) -> None: + config = load_config(Path(args.config)) + if args.snapshot: + with Path(args.snapshot).open(encoding="utf-8") as stream: + snapshot = json.load(stream) + else: + snapshot = collect_live_snapshot(config) + errors = audit_snapshot(snapshot, config) + print(json.dumps({ + "valid": not errors, + "repository": config["repository"], + "errors": errors, + }, indent=2)) + if errors: + raise ProtectionError("GitHub release protections do not match the repository contract") + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser() + parser.add_argument("command", choices=("audit",)) + parser.add_argument("--config", default=str(CONFIG_PATH)) + parser.add_argument("--snapshot") + return parser + + +def main(argv: Sequence[str] | None = None) -> int: + try: + args = build_parser().parse_args(argv) + audit(args) + return 0 + except (ProtectionError, OSError, json.JSONDecodeError) as error: + print(f"release-protection: {error}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/release_tool.py b/scripts/release_tool.py index 9f57a806..209f1cce 100644 --- a/scripts/release_tool.py +++ b/scripts/release_tool.py @@ -38,6 +38,16 @@ def semver(self) -> tuple[int, int, int]: return parse_semver(self.name) +@dataclass(frozen=True) +class ReleaseCandidate: + mode: str + head_branch: str + base_branch: str + merge_commit: str + version: Version + tag: str + + def load_config(path: Path = CONFIG_PATH) -> dict: with path.open(encoding="utf-8") as stream: config = json.load(stream) @@ -48,8 +58,7 @@ def load_config(path: Path = CONFIG_PATH) -> dict: return config -def read_version(path: Path = GRADLE_PATH) -> Version: - text = path.read_text(encoding="utf-8") +def parse_version_text(text: str) -> Version: codes = VERSION_CODE_RE.findall(text) names = VERSION_NAME_RE.findall(text) if len(codes) != 1 or len(names) != 1: @@ -58,6 +67,17 @@ def read_version(path: Path = GRADLE_PATH) -> Version: return Version(names[0], int(codes[0])) +def read_version(path: Path = GRADLE_PATH) -> Version: + return parse_version_text(path.read_text(encoding="utf-8")) + + +def read_version_from_ref(ref: str) -> Version: + gradle = run(["git", "show", f"{ref}:app/build.gradle"], check=False) + if not gradle: + raise ReleaseError(f"Candidate {ref} does not contain app/build.gradle") + return parse_version_text(gradle) + + def write_version(version: Version, path: Path = GRADLE_PATH) -> None: text = path.read_text(encoding="utf-8") text, code_count = VERSION_CODE_RE.subn(f" versionCode {version.code}", text) @@ -106,6 +126,14 @@ def git_ref_exists(ref: str) -> bool: ).returncode == 0 +def git_is_ancestor(ancestor: str, descendant: str) -> bool: + return subprocess.run( + ["git", "merge-base", "--is-ancestor", ancestor, descendant], + cwd=ROOT, + check=False, + ).returncode == 0 + + def discover_locales(config: dict, root: Path = ROOT) -> list[str]: metadata_root = root / config["metadataRoot"] ignored = set(config.get("ignoredLocales", [])) @@ -218,6 +246,71 @@ def validate_branch(version: Version, config: dict, *, mode: str | None = None) return inferred +def resolve_release_candidate( + *, + head_branch: str, + base_branch: str, + merge_commit: str, + merged: bool, + config: dict, + stable_ref: str | None = None, +) -> ReleaseCandidate: + branches = config["branches"] + stable = branches["stable"] + if not merged: + raise ReleaseError("Release pull request was closed without being merged") + if base_branch != stable: + raise ReleaseError(f"Release pull request must target {stable}, found {base_branch}") + + version = read_version_from_ref(merge_commit) + expected_release = f'{branches["releasePrefix"]}{version.name}' + expected_hotfix = f'{branches["hotfixPrefix"]}{version.name}' + if head_branch == expected_release: + mode = "release" + elif head_branch == expected_hotfix: + mode = "hotfix" + else: + raise ReleaseError( + f"Candidate branch {head_branch} does not match version {version.name}" + ) + + commit_type = run( + ["git", "cat-file", "-t", f"{merge_commit}^{{commit}}"], check=False + ) + if commit_type != "commit": + raise ReleaseError(f"Candidate is not a commit: {merge_commit}") + parents = run( + ["git", "rev-list", "--parents", "-n", "1", merge_commit], check=False + ).split() + if len(parents) < 3 or parents[0] != merge_commit: + raise ReleaseError(f"Candidate is not a merge commit: {merge_commit}") + + if stable_ref is None: + remote_ref = f"origin/{stable}" + stable_ref = ( + remote_ref + if git_ref_exists(f"refs/remotes/{remote_ref}") + else stable + ) + if not git_is_ancestor(merge_commit, stable_ref): + raise ReleaseError( + f"Candidate {merge_commit} is not contained in {stable_ref}" + ) + + tag = config["tagPrefix"] + version.name + if git_ref_exists(f"refs/tags/{tag}"): + raise ReleaseError(f"Tag already exists: {tag}") + + return ReleaseCandidate( + mode=mode, + head_branch=head_branch, + base_branch=base_branch, + merge_commit=merge_commit, + version=version, + tag=tag, + ) + + def candidate_conflicts(version: Version, config: dict, mode: str) -> list[str]: branches = config["branches"] branch = f'{branches[mode + "Prefix"]}{version.name}' @@ -307,6 +400,25 @@ def metadata(args: argparse.Namespace) -> None: }, indent=2)) +def candidate(args: argparse.Namespace) -> None: + resolved = resolve_release_candidate( + head_branch=args.head_branch, + base_branch=args.base_branch, + merge_commit=args.merge_commit, + merged=args.merged == "true", + config=load_config(), + ) + print(json.dumps({ + "mode": resolved.mode, + "headBranch": resolved.head_branch, + "baseBranch": resolved.base_branch, + "mergeCommit": resolved.merge_commit, + "versionName": resolved.version.name, + "versionCode": resolved.version.code, + "tag": resolved.tag, + }, indent=2)) + + def validate(args: argparse.Namespace) -> None: config = load_config() version = read_version() @@ -338,6 +450,12 @@ def build_parser() -> argparse.ArgumentParser: commands = parser.add_subparsers(dest="command", required=True) metadata_parser = commands.add_parser("metadata") metadata_parser.set_defaults(handler=metadata) + candidate_parser = commands.add_parser("candidate") + candidate_parser.add_argument("--head-branch", required=True) + candidate_parser.add_argument("--base-branch", required=True) + candidate_parser.add_argument("--merge-commit", required=True) + candidate_parser.add_argument("--merged", required=True, choices=("true", "false")) + candidate_parser.set_defaults(handler=candidate) validate_parser = commands.add_parser("validate") validate_parser.add_argument("--mode", choices=("release", "hotfix")) validate_parser.add_argument("--skip-branch", action="store_true") diff --git a/scripts/test_release_protection.py b/scripts/test_release_protection.py new file mode 100644 index 00000000..e96ec73c --- /dev/null +++ b/scripts/test_release_protection.py @@ -0,0 +1,150 @@ +import unittest + +from pathlib import Path +import sys + + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import release_protection + + +class ReleaseProtectionTest(unittest.TestCase): + def setUp(self): + self.config = { + "repository": "maxistar/TextPad", + "branches": { + "master": { + "requirePullRequest": True, + "requiredChecks": ["build", "validate"], + "requiredCheckAppId": 15368, + "allowForcePushes": False, + "allowDeletions": False, + }, + "dev": { + "requirePullRequest": False, + "requiredChecks": [], + "allowForcePushes": False, + "allowDeletions": False, + }, + }, + "environments": { + "release": { + "allowedRefs": [ + {"name": "master", "type": "branch"}, + {"name": "v*", "type": "tag"}, + ], + "requiredReviewers": [], + }, + "production": { + "allowedRefs": [ + {"name": "master", "type": "branch"}, + {"name": "v*", "type": "tag"}, + ], + "requiredReviewers": ["maxistar"], + }, + }, + } + + def test_accepts_compliant_snapshot(self): + self.assertEqual([], release_protection.audit_snapshot(self.snapshot(), self.config)) + + def test_reports_absent_branch_protection(self): + snapshot = self.snapshot() + del snapshot["branches"]["dev"] + self.assertIn( + "branch dev has no protection", + release_protection.audit_snapshot(snapshot, self.config), + ) + + def test_reports_missing_required_check(self): + snapshot = self.snapshot() + snapshot["branches"]["master"]["required_status_checks"]["contexts"] = ["build"] + self.assertIn( + "branch master is missing required checks: validate", + release_protection.audit_snapshot(snapshot, self.config), + ) + + def test_reports_required_check_from_wrong_app(self): + snapshot = self.snapshot() + snapshot["branches"]["master"]["required_status_checks"]["checks"][1]["app_id"] = None + self.assertIn( + "branch master checks are not pinned to app 15368: validate", + release_protection.audit_snapshot(snapshot, self.config), + ) + + def test_reports_unprotected_environment(self): + snapshot = self.snapshot() + snapshot["environments"]["release"]["environment"]["deployment_branch_policy"] = None + self.assertIn( + "environment release does not restrict deployment refs", + release_protection.audit_snapshot(snapshot, self.config), + ) + + def test_reports_missing_production_reviewer(self): + snapshot = self.snapshot() + snapshot["environments"]["production"]["environment"]["protection_rules"] = [] + self.assertIn( + "environment production is missing required reviewers: maxistar", + release_protection.audit_snapshot(snapshot, self.config), + ) + + @staticmethod + def branch(required_checks, require_pull_request=False): + return { + "required_status_checks": { + "contexts": required_checks, + "checks": [ + {"context": context, "app_id": 15368} + for context in required_checks + ], + }, + "required_pull_request_reviews": ( + {"required_approving_review_count": 0} + if require_pull_request else None + ), + "allow_force_pushes": {"enabled": False}, + "allow_deletions": {"enabled": False}, + } + + @staticmethod + def environment(required_reviewer=None): + rules = [] + if required_reviewer: + rules.append({ + "type": "required_reviewers", + "reviewers": [{ + "type": "User", + "reviewer": {"login": required_reviewer}, + }], + }) + return { + "environment": { + "deployment_branch_policy": { + "protected_branches": False, + "custom_branch_policies": True, + }, + "protection_rules": rules, + }, + "policies": { + "branch_policies": [ + {"name": "master", "type": "branch"}, + {"name": "v*", "type": "tag"}, + ] + }, + } + + def snapshot(self): + return { + "branches": { + "master": self.branch(["build", "validate"], require_pull_request=True), + "dev": self.branch([]), + }, + "environments": { + "release": self.environment(), + "production": self.environment("maxistar"), + }, + } + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/test_release_tool.py b/scripts/test_release_tool.py index ea7df062..e66cac5e 100644 --- a/scripts/test_release_tool.py +++ b/scripts/test_release_tool.py @@ -144,6 +144,150 @@ def test_protected_validation_passes_code_to_fastlane(self, config, version, his self.assertIn("validate_play_version_code", command) self.assertIn("version_code:61", command) + @mock.patch.object(release_tool, "git_ref_exists", return_value=False) + @mock.patch.object(release_tool, "git_is_ancestor", return_value=True) + @mock.patch.object(release_tool, "run") + @mock.patch.object(release_tool, "read_version_from_ref") + def test_resolves_release_and_hotfix_merge_candidates( + self, read_version, run, is_ancestor, ref_exists + ): + read_version.return_value = release_tool.Version("1.31.2", 63) + run.side_effect = lambda command, check=True: ( + "commit" if command[1:3] == ["cat-file", "-t"] + else "abc123 parent-one parent-two" + ) + config = self.candidate_config() + + for mode, branch in ( + ("release", "release/1.31.2"), + ("hotfix", "hotfix/1.31.2"), + ): + with self.subTest(mode=mode): + candidate = release_tool.resolve_release_candidate( + head_branch=branch, + base_branch="master", + merge_commit="abc123", + merged=True, + config=config, + stable_ref="origin/master", + ) + self.assertEqual(mode, candidate.mode) + self.assertEqual("v1.31.2", candidate.tag) + self.assertEqual(63, candidate.version.code) + is_ancestor.assert_called_with("abc123", "origin/master") + + @mock.patch.object(release_tool, "read_version_from_ref") + def test_rejects_closed_but_unmerged_candidate(self, read_version): + with self.assertRaisesRegex(release_tool.ReleaseError, "without being merged"): + release_tool.resolve_release_candidate( + head_branch="release/1.31.2", + base_branch="master", + merge_commit="abc123", + merged=False, + config=self.candidate_config(), + stable_ref="origin/master", + ) + read_version.assert_not_called() + + @mock.patch.object(release_tool, "read_version_from_ref") + def test_rejects_candidate_branch_version_mismatch(self, read_version): + read_version.return_value = release_tool.Version("1.31.2", 63) + with self.assertRaisesRegex(release_tool.ReleaseError, "does not match"): + release_tool.resolve_release_candidate( + head_branch="release/1.31.3", + base_branch="master", + merge_commit="abc123", + merged=True, + config=self.candidate_config(), + stable_ref="origin/master", + ) + + @mock.patch.object(release_tool, "git_ref_exists", return_value=False) + @mock.patch.object(release_tool, "run") + @mock.patch.object(release_tool, "read_version_from_ref") + def test_rejects_non_merge_candidate(self, read_version, run, ref_exists): + read_version.return_value = release_tool.Version("1.31.2", 63) + run.side_effect = ["commit", "abc123 one-parent"] + with self.assertRaisesRegex(release_tool.ReleaseError, "not a merge commit"): + release_tool.resolve_release_candidate( + head_branch="release/1.31.2", + base_branch="master", + merge_commit="abc123", + merged=True, + config=self.candidate_config(), + stable_ref="origin/master", + ) + + @mock.patch.object(release_tool, "git_ref_exists", return_value=False) + @mock.patch.object(release_tool, "git_is_ancestor", return_value=True) + @mock.patch.object(release_tool, "run") + @mock.patch.object(release_tool, "read_version_from_ref") + def test_accepts_candidate_behind_advanced_master( + self, read_version, run, is_ancestor, ref_exists + ): + read_version.return_value = release_tool.Version("1.31.2", 63) + run.side_effect = ["commit", "abc123 parent-one parent-two"] + candidate = release_tool.resolve_release_candidate( + head_branch="release/1.31.2", + base_branch="master", + merge_commit="abc123", + merged=True, + config=self.candidate_config(), + stable_ref="origin/master", + ) + self.assertEqual("abc123", candidate.merge_commit) + is_ancestor.assert_called_once_with("abc123", "origin/master") + + @mock.patch.object(release_tool, "git_ref_exists", return_value=False) + @mock.patch.object(release_tool, "git_is_ancestor", return_value=False) + @mock.patch.object(release_tool, "run") + @mock.patch.object(release_tool, "read_version_from_ref") + def test_rejects_candidate_divergent_from_master( + self, read_version, run, is_ancestor, ref_exists + ): + read_version.return_value = release_tool.Version("1.31.2", 63) + run.side_effect = ["commit", "abc123 parent-one parent-two"] + with self.assertRaisesRegex(release_tool.ReleaseError, "not contained"): + release_tool.resolve_release_candidate( + head_branch="release/1.31.2", + base_branch="master", + merge_commit="abc123", + merged=True, + config=self.candidate_config(), + stable_ref="origin/master", + ) + + @mock.patch.object(release_tool, "git_ref_exists", return_value=True) + @mock.patch.object(release_tool, "git_is_ancestor", return_value=True) + @mock.patch.object(release_tool, "run") + @mock.patch.object(release_tool, "read_version_from_ref") + def test_rejects_candidate_with_existing_tag( + self, read_version, run, is_ancestor, ref_exists + ): + read_version.return_value = release_tool.Version("1.31.2", 63) + run.side_effect = ["commit", "abc123 parent-one parent-two"] + with self.assertRaisesRegex(release_tool.ReleaseError, "Tag already exists"): + release_tool.resolve_release_candidate( + head_branch="release/1.31.2", + base_branch="master", + merge_commit="abc123", + merged=True, + config=self.candidate_config(), + stable_ref="origin/master", + ) + + @staticmethod + def candidate_config(): + return { + "tagPrefix": "v", + "branches": { + "development": "dev", + "stable": "master", + "releasePrefix": "release/", + "hotfixPrefix": "hotfix/", + }, + } + if __name__ == "__main__": unittest.main() diff --git a/scripts/test_release_workflows.py b/scripts/test_release_workflows.py index 8e0fddcb..bd943df4 100644 --- a/scripts/test_release_workflows.py +++ b/scripts/test_release_workflows.py @@ -17,42 +17,85 @@ def test_release_pr_is_read_only_and_has_no_protected_secrets(self): self.assertNotIn("secrets.", workflow) self.assertNotIn("git tag", workflow) self.assertIn("assembleRelease bundleRelease", workflow) + self.assertIn("scripts/test_release_workflows.py", workflow) + self.assertIn("scripts/test_release_protection.py", workflow) - def test_create_release_checks_exact_master_before_annotated_tag(self): + def test_orchestrator_only_accepts_merged_release_candidates(self): workflow = self.read("create-release.yml") - self.assertIn('git rev-parse origin/master', workflow) - self.assertIn('git tag -a', workflow) - self.assertIn('git config user.name "github-actions[bot]"', workflow) - self.assertIn('git config user.email "41898282+github-actions[bot]@users.noreply.github.com"', workflow) + self.assertIn("pull_request:", workflow) + self.assertIn("types: [closed]", workflow) + self.assertIn("github.event.pull_request.merged == true", workflow) + self.assertIn("startsWith(github.event.pull_request.head.ref, 'release/')", workflow) + self.assertIn("startsWith(github.event.pull_request.head.ref, 'hotfix/')", workflow) + self.assertIn("scripts/release_tool.py candidate", workflow) + self.assertIn('gh pr checks "$PR_NUMBER" --required', workflow) self.assertIn("--check-play", workflow) + + def test_orchestrator_derives_version_and_creates_annotated_tag(self): + workflow = self.read("create-release.yml") + dispatch_inputs = workflow.split("workflow_dispatch:", 1)[1].split("permissions:", 1)[0] + self.assertIn("head_branch:", dispatch_inputs) + self.assertIn("commit_sha:", dispatch_inputs) + self.assertNotIn("version:", dispatch_inputs) + self.assertIn('git tag -a "$TAG" "$MERGE_COMMIT"', workflow) + self.assertIn('git push origin "refs/tags/$TAG"', workflow) self.assertIn("environment: release", workflow) - def test_tagged_publication_orders_github_before_play(self): + def test_orchestrator_reuses_publish_sync_and_promotion_workflows(self): + workflow = self.read("create-release.yml") + self.assertIn("uses: ./.github/workflows/tagged-release.yml", workflow) + self.assertIn("uses: ./.github/workflows/sync-master-to-dev.yml", workflow) + self.assertIn("uses: ./.github/workflows/promote-production.yml", workflow) + self.assertEqual(2, workflow.count("needs: [create-tag, publish]")) + self.assertLess(workflow.index(" publish:"), workflow.index(" sync-development:")) + self.assertLess(workflow.index(" publish:"), workflow.index(" promote-production:")) + + def test_tagged_publication_orders_github_before_play_and_is_recoverable(self): workflow = self.read("tagged-release.yml") - github = workflow.index('gh release create') - play = workflow.index('fastlane android upload_release') + github = workflow.index("gh release create") + play = workflow.index("fastlane android upload_release") self.assertLess(github, play) self.assertIn("workflow_dispatch:", workflow) + self.assertIn("workflow_call:", workflow) self.assertIn('if [ -n "$INPUT_TAG" ]', workflow) - self.assertNotIn('EVENT_NAME: ${{ github.event_name }}', workflow) - self.assertIn("if: github.event_name == 'workflow_dispatch'", workflow) - self.assertIn("git show origin/master:fastlane/Fastfile > fastlane/Fastfile", workflow) self.assertIn("sha256sum --check SHA256SUMS", workflow) self.assertIn("environment: release", workflow) + self.assertIn('gh release view "$TAG"', workflow) + self.assertIn('gh release download "$TAG"', workflow) + self.assertIn('echo "complete=true"', workflow) - def test_production_has_approval_but_no_build_or_keystore(self): + def test_production_is_reusable_tag_only_and_has_no_build_or_keystore(self): workflow = self.read("promote-production.yml") + dispatch_inputs = workflow.split("workflow_dispatch:", 1)[1].split("workflow_call:", 1)[0] + self.assertIn("tag:", dispatch_inputs) + self.assertNotIn("version_code:", dispatch_inputs) + self.assertIn("workflow_call:", workflow) self.assertIn("environment: production", workflow) + self.assertIn("steps.identity.outputs.version_code", workflow) self.assertIn("assert_track_version_code", workflow) self.assertIn("promote_release", workflow) self.assertNotIn("gradlew", workflow) self.assertNotIn("ANDROID_KEYSTORE", workflow) - def test_master_sync_accepts_post_tag_release_fixes(self): + def test_master_sync_is_reusable_and_accepts_post_tag_release_fixes(self): workflow = self.read("sync-master-to-dev.yml") + self.assertIn("workflow_dispatch:", workflow) + self.assertIn("workflow_call:", workflow) self.assertIn('test "$(git cat-file -t "$TAG")" = "tag"', workflow) self.assertIn('git merge-base --is-ancestor "$TAG^{}" origin/master', workflow) - self.assertNotIn('git rev-list -n 1 "$TAG")" = "$(git rev-parse origin/master)', workflow) + self.assertIn("git merge --no-ff origin/master", workflow) + self.assertNotIn('git push --force', workflow) + + def test_release_permissions_keep_trust_boundaries(self): + release_pr = self.read("release-pr.yml") + orchestrator = self.read("create-release.yml") + production = self.read("promote-production.yml") + self.assertIn("contents: read", release_pr) + self.assertIn("contents: write", orchestrator) + self.assertIn("pull-requests: read", orchestrator) + self.assertIn("checks: read", orchestrator) + self.assertIn("contents: read", production) + self.assertNotIn("ANDROID_KEYSTORE", production) def test_actions_are_versioned(self): for path in WORKFLOWS.glob("*.yml"): @@ -70,6 +113,13 @@ def test_fastlane_release_arguments_are_explicit(self): self.assertIn('track_promote_release_status: "completed"', fastfile) self.assertNotIn("rollout:", fastfile) + def test_fastlane_upload_and_promotion_are_idempotent(self): + fastfile = (ROOT / "fastlane" / "Fastfile").read_text(encoding="utf-8") + self.assertIn("if existing.include?(version_code)", fastfile) + self.assertIn("upload is complete", fastfile) + self.assertIn("if production_codes.include?(version_code)", fastfile) + self.assertIn("promotion is complete", fastfile) + def test_fastlane_handles_empty_google_play_tracks(self): gemfile = (ROOT / "Gemfile").read_text(encoding="utf-8") lockfile = (ROOT / "Gemfile.lock").read_text(encoding="utf-8") @@ -77,11 +127,7 @@ def test_fastlane_handles_empty_google_play_tracks(self): self.assertIn('gem "multi_json", "~> 1.15"', gemfile) self.assertIn("fastlane (2.235.0)", lockfile) self.assertIn("multi_json (", lockfile) - for name in ( - "create-release.yml", - "tagged-release.yml", - "promote-production.yml", - ): + for name in ("create-release.yml", "tagged-release.yml", "promote-production.yml"): self.assertIn("ruby-version: '3.3'", self.read(name)) def test_legacy_direct_production_deploy_is_removed(self): From ca1b9293aced32a824c080c782477472bef76ea7 Mon Sep 17 00:00:00 2001 From: Max Starikov Date: Sat, 3 Oct 2026 18:59:16 +0200 Subject: [PATCH 4/5] Prepare release 1.31.2 --- app/build.gradle | 4 ++-- fastlane/metadata/android/en-US/changelogs/63.txt | 1 + fastlane/metadata/android/es-ES/changelogs/63.txt | 1 + fastlane/metadata/android/pl-PL/changelogs/63.txt | 1 + fastlane/metadata/android/ru-RU/changelogs/63.txt | 1 + 5 files changed, 6 insertions(+), 2 deletions(-) create mode 100644 fastlane/metadata/android/en-US/changelogs/63.txt create mode 100644 fastlane/metadata/android/es-ES/changelogs/63.txt create mode 100644 fastlane/metadata/android/pl-PL/changelogs/63.txt create mode 100644 fastlane/metadata/android/ru-RU/changelogs/63.txt diff --git a/app/build.gradle b/app/build.gradle index 1435393b..1fe9c66a 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -3,8 +3,8 @@ apply plugin: 'com.android.application' android { defaultConfig { applicationId "com.maxistar.textpad" - versionCode 62 - versionName "1.31.1" + versionCode 63 + versionName "1.31.2" minSdkVersion 21 compileSdkVersion 36 targetSdkVersion 36 diff --git a/fastlane/metadata/android/en-US/changelogs/63.txt b/fastlane/metadata/android/en-US/changelogs/63.txt new file mode 100644 index 00000000..8774d24a --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/63.txt @@ -0,0 +1 @@ +TODO: RELEASE NOTES (1.31.2) diff --git a/fastlane/metadata/android/es-ES/changelogs/63.txt b/fastlane/metadata/android/es-ES/changelogs/63.txt new file mode 100644 index 00000000..8774d24a --- /dev/null +++ b/fastlane/metadata/android/es-ES/changelogs/63.txt @@ -0,0 +1 @@ +TODO: RELEASE NOTES (1.31.2) diff --git a/fastlane/metadata/android/pl-PL/changelogs/63.txt b/fastlane/metadata/android/pl-PL/changelogs/63.txt new file mode 100644 index 00000000..8774d24a --- /dev/null +++ b/fastlane/metadata/android/pl-PL/changelogs/63.txt @@ -0,0 +1 @@ +TODO: RELEASE NOTES (1.31.2) diff --git a/fastlane/metadata/android/ru-RU/changelogs/63.txt b/fastlane/metadata/android/ru-RU/changelogs/63.txt new file mode 100644 index 00000000..8774d24a --- /dev/null +++ b/fastlane/metadata/android/ru-RU/changelogs/63.txt @@ -0,0 +1 @@ +TODO: RELEASE NOTES (1.31.2) From fbb50a467c830ea8353256083f49a63ea26cda6a Mon Sep 17 00:00:00 2001 From: Max Starikov Date: Sat, 3 Oct 2026 18:59:53 +0200 Subject: [PATCH 5/5] Add release notes for 1.31.2 --- fastlane/metadata/android/en-US/changelogs/63.txt | 4 +++- fastlane/metadata/android/es-ES/changelogs/63.txt | 4 +++- fastlane/metadata/android/pl-PL/changelogs/63.txt | 4 +++- fastlane/metadata/android/ru-RU/changelogs/63.txt | 4 +++- 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/fastlane/metadata/android/en-US/changelogs/63.txt b/fastlane/metadata/android/en-US/changelogs/63.txt index 8774d24a..5aa87b37 100644 --- a/fastlane/metadata/android/en-US/changelogs/63.txt +++ b/fastlane/metadata/android/en-US/changelogs/63.txt @@ -1 +1,3 @@ -TODO: RELEASE NOTES (1.31.2) +- scroll long lines and documents in any direction with a two-finger gesture +- jump directly to a line and column from the editor menu +- adds a Hindi translation and improves editor navigation reliability diff --git a/fastlane/metadata/android/es-ES/changelogs/63.txt b/fastlane/metadata/android/es-ES/changelogs/63.txt index 8774d24a..1b904ca0 100644 --- a/fastlane/metadata/android/es-ES/changelogs/63.txt +++ b/fastlane/metadata/android/es-ES/changelogs/63.txt @@ -1 +1,3 @@ -TODO: RELEASE NOTES (1.31.2) +- desplázate por líneas largas y documentos en cualquier dirección con un gesto de dos dedos +- salta directamente a una línea y columna desde el menú del editor +- añade la traducción al hindi y mejora la fiabilidad de la navegación diff --git a/fastlane/metadata/android/pl-PL/changelogs/63.txt b/fastlane/metadata/android/pl-PL/changelogs/63.txt index 8774d24a..19c3b349 100644 --- a/fastlane/metadata/android/pl-PL/changelogs/63.txt +++ b/fastlane/metadata/android/pl-PL/changelogs/63.txt @@ -1 +1,3 @@ -TODO: RELEASE NOTES (1.31.2) +- przewijaj długie wiersze i dokumenty w dowolnym kierunku gestem dwóch palców +- przechodź bezpośrednio do wiersza i kolumny z menu edytora +- dodaje tłumaczenie na hindi i zwiększa niezawodność nawigacji diff --git a/fastlane/metadata/android/ru-RU/changelogs/63.txt b/fastlane/metadata/android/ru-RU/changelogs/63.txt index 8774d24a..a21b7295 100644 --- a/fastlane/metadata/android/ru-RU/changelogs/63.txt +++ b/fastlane/metadata/android/ru-RU/changelogs/63.txt @@ -1 +1,3 @@ -TODO: RELEASE NOTES (1.31.2) +- прокручивайте длинные строки и документы в любом направлении жестом двумя пальцами +- переходите сразу к нужной строке и столбцу из меню редактора +- добавлен перевод на хинди и повышена надёжность навигации