taler-android

Android apps for GNU Taler (wallet, PoS, cashier)
Log | Files | Refs | README | LICENSE

wallet.py (14044B)


      1 # This file is part of GNU Taler
      2 # (C) 2026 Taler Systems S.A.
      3 #
      4 # GNU Taler is free software; you can redistribute it and/or modify it under the
      5 # terms of the GNU General Public License as published by the Free Software
      6 # Foundation; either version 3, or (at your option) any later version.
      7 #
      8 # GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
      9 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
     10 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
     11 #
     12 # You should have received a copy of the GNU General Public License along with
     13 # GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
     14 """Wallet-app operations on top of the raw device driver.
     15 
     16 Only app-level knowledge lives here: the labels of the screens the simulator
     17 has to pass through to reach a feature, and the one setting the whole simulator
     18 depends on — developer mode, without which HandleUriScreen refuses every
     19 taler+http:// URI that a local http deployment produces.
     20 """
     21 
     22 from __future__ import annotations
     23 
     24 import re
     25 import time
     26 from typing import Optional
     27 
     28 from device import Device, Node, Screen
     29 
     30 DEV_MODE_LABEL = "Developer mode"
     31 # Only shown while developer mode is on, so it doubles as the check that the
     32 # toggle took effect.
     33 DEV_MODE_MARKER = "Withdraw demo KUDOS"
     34 # The wallet has two main screens and ships with a switch between them
     35 # (`MainScreen.kt`: NewMainScreen when the preference is on, LegacyMainScreen
     36 # otherwise, and since "hide new balances screen behind dev mode toggle" the
     37 # default is off).  Everything in this harness is written for the new one --
     38 # its app bar carries the scan action and the settings action, where the
     39 # legacy screen puts the actions in a modal bottom sheet nothing here opens --
     40 # so `fresh_start` turns it on, next to developer mode and for the same
     41 # reason: the app does not come up in the state the simulator needs.
     42 NEW_MAIN_SCREEN_LABEL = "New main screen"
     43 # A label that only the main screen of *either* layout shows: the new screen's
     44 # app-bar title and the legacy screen's bottom-navigation item are both
     45 # `balances_title`.  It has to cover both, because this is what the driver
     46 # steers by on the way to the switch above.
     47 HOME_MARKER = r"(?i)^(Scan QR code|Balances)$"
     48 
     49 
     50 class Wallet:
     51     def __init__(self, dev: Device):
     52         self.dev = dev
     53         # Set by Episode: dump coverage before the process is wiped.
     54         self.before_wipe = None
     55 
     56     # -- navigation -------------------------------------------------------
     57 
     58     def fresh_start(self, dev_mode: bool = True) -> None:
     59         """Wipe app data and come back up, optionally in developer mode."""
     60         # Coverage lives in the app process, so whatever ran before this point
     61         # is lost when the process goes.  The Episode sets this hook; without
     62         # it, every scenario that restarts mid-run threw its measurement away
     63         # (WalletInitErrorScreen reads 0% although db_corruption renders it).
     64         if self.before_wipe is not None:
     65             try:
     66                 self.before_wipe()
     67             except Exception as e:  # noqa: BLE001 - never fail a wipe over this
     68                 print(f"pre-wipe coverage dump failed: {e}")
     69         # Rotation outlives the app's data, so reset it before anything else.
     70         self.dev.portrait()
     71         self.dev.clear_data()
     72         # "pm clear" also revokes runtime permissions, so the camera has to be
     73         # granted again or the scan screen opens on a system dialog instead.
     74         self.dev.grant_camera()
     75         self.dev.launch()
     76         self.wait_until_up()
     77         if dev_mode:
     78             self.enable_dev_mode()
     79             # Developer mode first: the switch below is only rendered when
     80             # developer mode is on (SettingsScreen.kt gates it), so the order
     81             # is not a preference.
     82             self.enable_new_main_screen()
     83             self.wait_until_up()
     84 
     85     def in_foreground(self, screen: Optional[Screen] = None) -> bool:
     86         """Is the app the thing on screen?
     87 
     88         A label match cannot answer this, and that is not hypothetical: the
     89         launcher's own icon for this app is labelled "Taler Wallet", so a wait
     90         for `wallet|balance|withdraw` is satisfied by the *home screen* with
     91         the app not running at all -- and the scenario then fails thirty
     92         seconds later looking for something else.  The resumed activity can
     93         answer it, and `Screen` already carries it.
     94         """
     95         activity = (screen.activity if screen is not None
     96                     else self.dev.current_activity())
     97         return activity.startswith(self.dev.pkg + "/")
     98 
     99     def wait_until_up(self, timeout: int = 180) -> Screen:
    100         """Wait for the app's own main screen, cold start included.
    101 
    102         `am start -W` returns at the first frame, which after a `pm clear` is
    103         well before Compose has laid the main screen out.  Three minutes
    104         rather than one: the first start after a wipe has no AOT artifacts to
    105         use and wallet-core has to create its database, which on a shared CI
    106         worker is minutes rather than seconds.
    107         """
    108         deadline = time.monotonic() + timeout
    109         last = Screen()
    110         while time.monotonic() < deadline:
    111             last = self.dev.dump()
    112             if not self.in_foreground(last):
    113                 self.dev.launch()
    114                 time.sleep(2)
    115                 continue
    116             if last.find(HOME_MARKER):
    117                 return last
    118             time.sleep(1.5)
    119         raise TimeoutError(
    120             f"the wallet's main screen did not appear within {timeout}s; "
    121             f"activity {last.activity!r}, screen showed: {last.texts()}"
    122         )
    123 
    124     def home(self, tries: int = 6) -> Screen:
    125         """Back out to the main screen."""
    126         for _ in range(tries):
    127             screen = self.dev.dump()
    128             if screen.find(HOME_MARKER) and not screen.find(r"(?i)^Close sheet$"):
    129                 return screen
    130             # Back is only a way *back* while the app is in front.  On the
    131             # launcher it does nothing, and on the app's own main screen it
    132             # leaves the app -- so a main screen this loop did not recognise
    133             # used to end with six Back presses and every later label search
    134             # reading the launcher: "no label matching '^Settings$'; screen
    135             # showed: ['At a glance', 'Gmail', ...]".  Relaunching is what the
    136             # caller means by "go home".
    137             if not self.in_foreground(screen):
    138                 self.dev.launch()
    139                 time.sleep(2)
    140                 continue
    141             self.dev.back()
    142             time.sleep(1)
    143         return self.dev.dump()
    144 
    145     def scroll_to_text(self, pattern: str, max_scrolls: int = 8) -> Screen:
    146         """Scroll until a label shows up, downwards and then back up.
    147 
    148         Scrolling only one way misses a row that was already above the fold,
    149         and a list that has reached its end stops moving, so the upward sweep
    150         is where a missed row is usually found.
    151         """
    152         seen: list[str] = []
    153         for direction in (True, False):
    154             for _ in range(max_scrolls):
    155                 screen = self.dev.dump()
    156                 if screen.find(pattern):
    157                     return screen
    158                 signature = screen.signature()
    159                 if seen and seen[-1] == signature and not direction:
    160                     break          # the list is not moving any more
    161                 seen.append(signature)
    162                 self.dev.scroll(down=direction, screen=screen)
    163                 time.sleep(0.8)
    164         screen = self.dev.dump()
    165         if screen.find(pattern):
    166             return screen
    167         raise TimeoutError(f"{pattern!r} not reachable by scrolling; "
    168                            f"last screen: {screen.texts()}")
    169 
    170     def open_settings(self, tries: int = 3) -> Screen:
    171         """Open the Settings root and wait for it.
    172 
    173         How much of the list is on screen depends on how many rows the wallet
    174         has to show, so waiting for "Developer mode" here fails as soon as the
    175         list grows; callers scroll to the row they want. Landing in one of
    176         Settings' own sub-screens (Payment services, Bank accounts) is treated
    177         as not having arrived, and backed out of.
    178         """
    179         sub_screen = re.compile(
    180             r"(?i)^(Add payment service|Known bank accounts|No bank accounts saved"
    181             r"|Select tax authority|Alias Type)$"
    182         )
    183         for _ in range(tries):
    184             self.home()
    185             self.dev.tap_text(r"(?i)^Settings$", timeout=30)
    186             screen = self.dev.wait_for(
    187                 r"(?i)Payment services|Developer mode|About|Version|Protect access",
    188                 timeout=30,
    189             )
    190             if not any(sub_screen.match(t.strip()) for t in screen.texts()):
    191                 return screen
    192             self.dev.back()
    193             time.sleep(1.5)
    194         return self.dev.dump()
    195 
    196     # -- the one setting the simulator cannot do without ------------------
    197 
    198     def dev_mode_on(self) -> bool:
    199         screen = self.dev.dump()
    200         return screen.find(DEV_MODE_MARKER) is not None
    201 
    202     def enable_dev_mode(self) -> None:
    203         """Turn developer mode on through the UI.
    204 
    205         MainActivity pushes the persisted flag into MainViewModel on every
    206         start, so a debug build does *not* come up in developer mode however
    207         BuildConfig.DEBUG is set; it has to be switched on here.
    208         """
    209         self.open_settings()
    210         self.scroll_to_text(DEV_MODE_LABEL)
    211         if self.dev_mode_on():
    212             self.home()
    213             return
    214         screen = self.dev.dump()
    215         row = screen.find(DEV_MODE_LABEL)
    216         if row is None:
    217             # Scrolling settled differently between the search and the dump.
    218             screen = self.scroll_to_text(DEV_MODE_LABEL)
    219             row = screen.find(DEV_MODE_LABEL)
    220         if row is None:
    221             raise RuntimeError(f"the developer mode row went away; "
    222                                f"settings showed: {screen.texts()}")
    223         # Hit the switch at the right-hand end of the row rather than the label,
    224         # which is not itself the clickable node.
    225         _, y = row.center
    226         width = max(n.bounds[2] for n in screen.nodes)
    227         self.dev.tap(width - 100, y)
    228         time.sleep(1.5)
    229         if not self.dev_mode_on():
    230             # Fall back to the row itself, in case the switch moved.
    231             self.dev.tap_node(row)
    232             time.sleep(1.5)
    233         if not self.dev_mode_on():
    234             raise RuntimeError(f"could not enable developer mode; "
    235                                f"settings showed: {self.dev.dump().texts()}")
    236         self.home()
    237 
    238     def switch_state(self, screen: Screen, label: str) -> Optional[tuple[Node, bool]]:
    239         """A settings switch row, and whether it is on.
    240 
    241         The label and the switch are separate nodes; the switch is the
    242         checkable one on the same line, which is also the only thing that
    243         reports its state.
    244         """
    245         row = screen.find(label)
    246         if row is None:
    247             return None
    248         _, y = row.center
    249         for node in screen.nodes:
    250             if node.checkable and node.bounds[1] <= y <= node.bounds[3]:
    251                 return row, node.checked
    252         return row, False
    253 
    254     def enable_new_main_screen(self) -> None:
    255         """Switch the app to the main screen this harness is written for.
    256 
    257         Not cosmetic: on the legacy main screen the actions the scenarios
    258         drive -- scan, send, request, withdraw, deposit -- are inside a modal
    259         bottom sheet that nothing here opens, and its app bar has no settings
    260         action either.  A build without the switch at all is left alone, so
    261         this stays correct when the preference eventually goes away.
    262         """
    263         self.open_settings()
    264         try:
    265             screen = self.scroll_to_text(NEW_MAIN_SCREEN_LABEL)
    266         except TimeoutError:
    267             return
    268         state = self.switch_state(screen, NEW_MAIN_SCREEN_LABEL)
    269         if state is None:
    270             return
    271         row, already_on = state
    272         if already_on:
    273             self.home()
    274             return
    275         # The switch at the right-hand end of the row, as for developer mode;
    276         # the label itself is not the clickable node.
    277         width = max(n.bounds[2] for n in screen.nodes)
    278         self.dev.tap(width - 100, row.center[1])
    279         time.sleep(1.5)
    280         screen = self.dev.dump()
    281         state = self.switch_state(screen, NEW_MAIN_SCREEN_LABEL)
    282         if state is not None and not state[1]:
    283             self.dev.tap_node(row)      # in case the switch moved
    284             time.sleep(1.5)
    285         self.home()
    286 
    287     # -- entry points -----------------------------------------------------
    288 
    289     def dismiss_permission_dialog(self) -> bool:
    290         """Answer a runtime-permission dialog if one is in the way."""
    291         screen = self.dev.dump()
    292         if screen.find(r"(?i)allow .* to take pictures|While using the app") is None:
    293             return False
    294         node = screen.find(r"(?i)While using the app") or screen.find(r"(?i)^Allow$")
    295         if node is None:
    296             return False
    297         self.dev.tap_node(node, screen)
    298         time.sleep(1.5)
    299         return True
    300 
    301     def open_scanner(self) -> Screen:
    302         """Open the QR scan screen, past any permission prompt."""
    303         self.home()
    304         self.dev.tap_text(r"(?i)^Scan QR code$", timeout=30)
    305         time.sleep(1.5)
    306         self.dismiss_permission_dialog()
    307         return self.dev.wait_for(r"(?i)Scan or enter link|Scan QR", timeout=30)
    308 
    309     def handle_uri(self, uri: str) -> Screen:
    310         """Share a URI into the wallet and return the screen it produced."""
    311         self.dev.send_uri(uri)
    312         time.sleep(2)
    313         return self.dev.dump()
    314 
    315     def balances(self) -> list[str]:
    316         """Amounts visible on the main screen."""
    317         import re
    318         screen = self.home()
    319         return [t for t in screen.texts() if re.search(r"\d+[.,]\d\d", t)]