taler-android

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

wallet.py (8421B)


      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 
     27 from device import Device, Screen
     28 
     29 DEV_MODE_LABEL = "Developer mode"
     30 # Only shown while developer mode is on, so it doubles as the check that the
     31 # toggle took effect.
     32 DEV_MODE_MARKER = "Withdraw demo KUDOS"
     33 
     34 
     35 class Wallet:
     36     def __init__(self, dev: Device):
     37         self.dev = dev
     38         # Set by Episode: dump coverage before the process is wiped.
     39         self.before_wipe = None
     40 
     41     # -- navigation -------------------------------------------------------
     42 
     43     def fresh_start(self, dev_mode: bool = True) -> None:
     44         """Wipe app data and come back up, optionally in developer mode."""
     45         # Coverage lives in the app process, so whatever ran before this point
     46         # is lost when the process goes.  The Episode sets this hook; without
     47         # it, every scenario that restarts mid-run threw its measurement away
     48         # (WalletInitErrorScreen reads 0% although db_corruption renders it).
     49         if self.before_wipe is not None:
     50             try:
     51                 self.before_wipe()
     52             except Exception as e:  # noqa: BLE001 - never fail a wipe over this
     53                 print(f"pre-wipe coverage dump failed: {e}")
     54         # Rotation outlives the app's data, so reset it before anything else.
     55         self.dev.portrait()
     56         self.dev.clear_data()
     57         # "pm clear" also revokes runtime permissions, so the camera has to be
     58         # granted again or the scan screen opens on a system dialog instead.
     59         self.dev.grant_camera()
     60         self.dev.launch()
     61         self.dev.wait_for(r"(?i)wallet|balance|withdraw", timeout=90)
     62         if dev_mode:
     63             self.enable_dev_mode()
     64 
     65     def home(self, tries: int = 6) -> Screen:
     66         """Back out to the main screen."""
     67         for _ in range(tries):
     68             screen = self.dev.dump()
     69             if screen.find(r"(?i)^Scan QR code$") and not screen.find(r"(?i)^Close sheet$"):
     70                 return screen
     71             self.dev.back()
     72             time.sleep(1)
     73         return self.dev.dump()
     74 
     75     def scroll_to_text(self, pattern: str, max_scrolls: int = 8) -> Screen:
     76         """Scroll until a label shows up, downwards and then back up.
     77 
     78         Scrolling only one way misses a row that was already above the fold,
     79         and a list that has reached its end stops moving, so the upward sweep
     80         is where a missed row is usually found.
     81         """
     82         seen: list[str] = []
     83         for direction in (True, False):
     84             for _ in range(max_scrolls):
     85                 screen = self.dev.dump()
     86                 if screen.find(pattern):
     87                     return screen
     88                 signature = screen.signature()
     89                 if seen and seen[-1] == signature and not direction:
     90                     break          # the list is not moving any more
     91                 seen.append(signature)
     92                 self.dev.scroll(down=direction, screen=screen)
     93                 time.sleep(0.8)
     94         screen = self.dev.dump()
     95         if screen.find(pattern):
     96             return screen
     97         raise TimeoutError(f"{pattern!r} not reachable by scrolling; "
     98                            f"last screen: {screen.texts()}")
     99 
    100     def open_settings(self, tries: int = 3) -> Screen:
    101         """Open the Settings root and wait for it.
    102 
    103         How much of the list is on screen depends on how many rows the wallet
    104         has to show, so waiting for "Developer mode" here fails as soon as the
    105         list grows; callers scroll to the row they want. Landing in one of
    106         Settings' own sub-screens (Payment services, Bank accounts) is treated
    107         as not having arrived, and backed out of.
    108         """
    109         sub_screen = re.compile(
    110             r"(?i)^(Add payment service|Known bank accounts|No bank accounts saved"
    111             r"|Select tax authority|Alias Type)$"
    112         )
    113         for _ in range(tries):
    114             self.home()
    115             self.dev.tap_text(r"(?i)^Settings$", timeout=30)
    116             screen = self.dev.wait_for(
    117                 r"(?i)Payment services|Developer mode|About|Version|Protect access",
    118                 timeout=30,
    119             )
    120             if not any(sub_screen.match(t.strip()) for t in screen.texts()):
    121                 return screen
    122             self.dev.back()
    123             time.sleep(1.5)
    124         return self.dev.dump()
    125 
    126     # -- the one setting the simulator cannot do without ------------------
    127 
    128     def dev_mode_on(self) -> bool:
    129         screen = self.dev.dump()
    130         return screen.find(DEV_MODE_MARKER) is not None
    131 
    132     def enable_dev_mode(self) -> None:
    133         """Turn developer mode on through the UI.
    134 
    135         MainActivity pushes the persisted flag into MainViewModel on every
    136         start, so a debug build does *not* come up in developer mode however
    137         BuildConfig.DEBUG is set; it has to be switched on here.
    138         """
    139         self.open_settings()
    140         self.scroll_to_text(DEV_MODE_LABEL)
    141         if self.dev_mode_on():
    142             self.home()
    143             return
    144         screen = self.dev.dump()
    145         row = screen.find(DEV_MODE_LABEL)
    146         if row is None:
    147             # Scrolling settled differently between the search and the dump.
    148             screen = self.scroll_to_text(DEV_MODE_LABEL)
    149             row = screen.find(DEV_MODE_LABEL)
    150         if row is None:
    151             raise RuntimeError(f"the developer mode row went away; "
    152                                f"settings showed: {screen.texts()}")
    153         # Hit the switch at the right-hand end of the row rather than the label,
    154         # which is not itself the clickable node.
    155         _, y = row.center
    156         width = max(n.bounds[2] for n in screen.nodes)
    157         self.dev.tap(width - 100, y)
    158         time.sleep(1.5)
    159         if not self.dev_mode_on():
    160             # Fall back to the row itself, in case the switch moved.
    161             self.dev.tap_node(row)
    162             time.sleep(1.5)
    163         if not self.dev_mode_on():
    164             raise RuntimeError(f"could not enable developer mode; "
    165                                f"settings showed: {self.dev.dump().texts()}")
    166         self.home()
    167 
    168     # -- entry points -----------------------------------------------------
    169 
    170     def dismiss_permission_dialog(self) -> bool:
    171         """Answer a runtime-permission dialog if one is in the way."""
    172         screen = self.dev.dump()
    173         if screen.find(r"(?i)allow .* to take pictures|While using the app") is None:
    174             return False
    175         node = screen.find(r"(?i)While using the app") or screen.find(r"(?i)^Allow$")
    176         if node is None:
    177             return False
    178         self.dev.tap_node(node, screen)
    179         time.sleep(1.5)
    180         return True
    181 
    182     def open_scanner(self) -> Screen:
    183         """Open the QR scan screen, past any permission prompt."""
    184         self.home()
    185         self.dev.tap_text(r"(?i)^Scan QR code$", timeout=30)
    186         time.sleep(1.5)
    187         self.dismiss_permission_dialog()
    188         return self.dev.wait_for(r"(?i)Scan or enter link|Scan QR", timeout=30)
    189 
    190     def handle_uri(self, uri: str) -> Screen:
    191         """Share a URI into the wallet and return the screen it produced."""
    192         self.dev.send_uri(uri)
    193         time.sleep(2)
    194         return self.dev.dump()
    195 
    196     def balances(self) -> list[str]:
    197         """Amounts visible on the main screen."""
    198         import re
    199         screen = self.home()
    200         return [t for t in screen.texts() if re.search(r"\d+[.,]\d\d", t)]