Standard library · Graphics and games

gui.device

Phone features for Salam apps: share sheet, haptics, permissions, notifications, location and photos on Android, with the same calls returning false on other systems.

import gui.device

gui.device reaches the features of a phone that a page cannot draw: the share sheet and more as they are added. Every call has the same signature on every system. On a desktop, or when the phone does not offer the feature, the call returns false or an empty value and the program carries on.

Platform names the system the program runs on: android, ios or none on a desktop. CanShare tells whether a share sheet exists, and Share opens it with a text and a link. Either may be empty, but not both. The call returns once the sheet is shown; it does not tell what the user chose.

Haptic gives a short system feedback (Tap, Heavy, Success or Failure) and needs no permission. Vibrate runs the motor for a number of milliseconds, at most 5000; on Android the build script adds the VIBRATE permission to the manifest only when the program calls it.

Runtime permissions: CheckPermission answers NotAsked, Granted or Denied at once, and RequestPermission opens the system dialog. The answer arrives later: OnChange sets a function that runs on the UI thread when any request finishes, and a gui.ui app calls ui.Invalidate there and reads CheckPermission in its view. A program that uses gui.window directly receives an EventKind.HostResult event and calls Notify. On Android the manifest must declare the permission: build with --permission camera (also microphone, location, notifications). Without a declaration the request is denied at once. Systems without permissions report Denied.

Notifications: ShowNotification posts one now, ScheduleNotification posts one after a number of seconds, even when the app is not in front, and CancelNotification removes it. The id replaces an earlier notification with the same id. Tapping a notification opens the app. They return false until the Notifications permission is granted (ask with RequestPermission first; from Android 13 it is asked at run time). The build script adds the permission to the manifest when the program shows or schedules a notification. A scheduled notification is inexact and does not survive a restart of the phone.

Location, one fix at a time: RequestLocation asks for the current position and returns at once, LocationStatus says Pending, Ready or Failed, and LastLocation reads the answer. OnChange runs when the fix arrives. The Location permission must be granted first; the build script declares it when the program asks for a location. GPS is used when it is on, the network provider otherwise, and a fix can take several seconds.

Photos: PickPhoto opens the system photo picker and TakePhoto opens the camera app, both without any permission, because the system apps do the work. PhotoStatus says Pending, Ready or Failed (also when the user cancels) and LastPhoto is the path of a JPEG copy in the app cache directory, which image can open. OnChange runs when the picture is ready. The camera app asks for its own permission; if the app declares the camera permission itself (--permission camera) it must be granted before TakePhoto.

App folders: DataDir is the private folder for files the app keeps, CacheDir holds files the system may delete when space runs low, DocumentsDir is the folder the user can reach (the app folder on shared storage on Android, Documents on iOS) and TempDir is for short lived files. Each returns the path of a folder that exists, or an empty string where the system has no such folder. No permission is needed.

Secure storage keeps small secrets such as a login token: SecureSet saves a value under a key, SecureGet reads it back (empty when there is none) and SecureDelete removes it. On Android the value is encrypted with an AES key that never leaves the Android Keystore; on iOS it goes to the Keychain. Keys are up to 200 bytes and values up to 16000 bytes. Where the system has no secure storage, SecureSet and SecureDelete return false and SecureGet returns an empty string.

Device and app information: Model, OSName and OSVersion name the phone and its system; Language is the preferred language tag, Languages the whole list and TimeZone the zone name; ScreenDensity is the pixels per layout point; AppVersion and BuildNumber are the values given with --version and --build when building; IsDarkMode tells the appearance. BatteryLevel gives percent, or -1 when unknown, and IsCharging tells whether the phone is plugged in. Network answers Offline, Wifi, Cellular, Ethernet or Other, and a change of connection runs the function set by OnChange, the way a permission answer does. Each call returns an empty string, zero, false or Offline where the system has no such information, and no permission is needed except ACCESS_NETWORK_STATE for Network on Android, which the build adds.

Links into the app: build with --scheme NAME to open links like NAME://path (a URL type on iOS, an intent filter on Android) and, on Android, with --link-host HOST to open https://HOST links; the site must also serve its assetlinks.json. LaunchURL is the link that started the app, empty when it was started in the usual way, and OnOpenURL sets the function that runs with a link that arrives while the app is running (the host event wakes the loop, so it runs on the UI thread). OpenSettings opens the settings page of the app, where the user can change permissions.

Screen behaviour: KeepAwake stops the screen from sleeping while the app is in front, LockOrientation locks to Portrait or Landscape at run time (the build option --orientation sets the start) and Auto frees it. Immersive hides the status bar and the navigation bar for a full screen page, SetBarStyle picks light or dark status bar icons, and SetBrightness and Brightness use values from 0.0 to 1.0. They need no permission. Each returns false where the system has no such control.

Biometrics: CanAuthenticate tells whether the phone has a fingerprint or face the user has set up, and Authenticate opens the system prompt with a reason. It returns at once; AuthStatus then says Pending, Success or Failed, and OnChange runs when the answer arrives. No biometric data reaches the app, only the verdict.

Calls go through the host layer of the phone shell, so they work in apps built with tools/bash/build-android-app.sh.

Share a link

Check CanShare first when the app also runs on a desktop, and hide the button or fall back to the clipboard when it is false.

gui-device-Share.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import gui.device

func main:
    println "running on", device.Platform()
    if not device.CanShare():
        println "no share sheet here"
        ret
    end
    if device.Share("Salam is a programming language", "https://salamlang.ir"):
        println "share sheet opened"
    else:
        println "could not share"
    end
end
Outputrunning on none no share sheet here

Feedback on a button

Use Haptic for taps and confirmations, and Vibrate for a longer buzz.

gui-device-Haptic.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import gui.device

func main:
    if not device.CanVibrate():
        println "no vibration here"
        ret
    end
    _ok := device.Haptic(device.HapticKind.Tap)
    _ok2 := device.Haptic(device.HapticKind.Success)
    _ok3 := device.Vibrate(200)
end
Outputno vibration here

Ask for the camera

A button that shows the state and asks when pressed. The view runs again when the dialog closes.

gui-device-Permission.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import gui.device
import gui.ui

func label(): str:
    s := device.CheckPermission(device.Permission.Camera)
    if s == device.PermissionState.Granted:
        ret "Camera allowed"
    end
    if s == device.PermissionState.Denied:
        ret "Camera denied"
    end
    ret "Ask for the camera"
end

func main:
    println label()
    device.OnChange((): ui.Invalidate() end)
    ui.RunPage((): ret ui.NoPatches() end, (b: ui.Builder):
        b.Open("button")
        b.On("click", (): _ok := device.RequestPermission(device.Permission.Camera) end)
        b.Text(label())
        b.Close()
    end)
end

Notify the user

Check the permission, then show a notification now and schedule another one.

gui-device-Notification.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import gui.device

func main:
    if device.CheckPermission(device.Permission.Notifications) != device.PermissionState.Granted:
        println "notifications are not allowed"
        ret
    end
    _ok := device.ShowNotification(1, "Download finished", "report.pdf is ready")
    _ok2 := device.ScheduleNotification(2, "Stand up", "Time for a break", 1800)
    _ok3 := device.CancelNotification(2)
end
Outputnotifications are not allowed

Where am I

A button that asks for the permission, then for one fix, and shows the position.

gui-device-Location.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import gui.device
import gui.ui
import str

func where(): str:
    state := device.LocationStatus()
    if state == device.LocationState.Ready:
        here := device.LastLocation()
        ret "lat " + str.FromFloat(here.latitude) + " lon " + str.FromFloat(here.longitude) + " within " + str.FromFloat(here.accuracy) + " m"
    end
    if state == device.LocationState.Pending:
        ret "looking for the position"
    end
    if state == device.LocationState.Failed:
        ret "no position"
    end
    ret "tap to locate"
end

func ask():
    if device.CheckPermission(device.Permission.Location) == device.PermissionState.Granted:
        _ok := device.RequestLocation()
        ui.Invalidate()
    else:
        _ok2 := device.RequestPermission(device.Permission.Location)
    end
end

func main:
    println where()
    device.OnChange((): ui.Invalidate() end)
    ui.RunPage((): ret ui.NoPatches() end, (b: ui.Builder):
        b.Open("button")
        b.On("click", (): ask() end)
        b.Text(where())
        b.Close()
    end)
end

Pick or take a photo

Two buttons: the first picks from the gallery and shows where the copy was saved, the second opens the camera.

gui-device-Photo.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import gui.device
import gui.ui

func label(): str:
    state := device.PhotoStatus()
    if state == device.PhotoState.Ready:
        ret "saved to " + device.LastPhoto()
    end
    if state == device.PhotoState.Pending:
        ret "waiting for the photo"
    end
    if state == device.PhotoState.Failed:
        ret "no photo"
    end
    ret "choose a photo"
end

func main:
    println label()
    device.OnChange((): ui.Invalidate() end)
    ui.RunPage((): ret ui.NoPatches() end, (b: ui.Builder):
        b.Open("button")
        b.On("click", (): _ok := device.PickPhoto() end)
        b.Text(label())
        b.Close()
        b.Open("button")
        b.On("click", (): _ok2 := device.TakePhoto() end)
        b.Text("take a photo")
        b.Close()
    end)
end

Save a file

Write into the data folder, which is private to the app and survives restarts.

gui-device-Paths.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import gui.device
import io

func main:
    dir := device.DataDir()
    if dir.Len() == 0:
        println "no app folders here"
        ret
    end
    println "data", dir
    println "cache", device.CacheDir()
    println "documents", device.DocumentsDir()
    println "temp", device.TempDir()
    _ok := io.WriteFile(dir + "/notes.txt", "saved")
end
Outputno app folders here

Remember a token

Save a secret, read it back and remove it.

gui-device-Secure.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import gui.device

func main:
    if not device.SecureSet("token", "s3cret"):
        println "no secure storage here"
        ret
    end
    println "token", device.SecureGet("token")
    _gone := device.SecureDelete("token")
    println "after delete", device.SecureGet("token").Len()
end
Outputno secure storage here

Show the device

A page with the phone model, the battery and the connection. It redraws when the connection changes.

gui-device-Info.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import gui.device
import gui.ui

func network_name(): str:
    kind := device.Network()
    if kind == device.NetworkKind.Wifi:
        ret "wifi"
    end
    if kind == device.NetworkKind.Cellular:
        ret "mobile data"
    end
    if kind == device.NetworkKind.Offline:
        ret "offline"
    end
    ret "connected"
end

func main:
    if device.OSName().Len() == 0:
        println "no device info here"
        ret
    end
    device.OnChange((): ui.Invalidate() end)
    ui.RunPage((): ret ui.NoPatches() end, (b: ui.Builder):
        b.Open("button")
        b.Text(device.Model() + ", " + device.OSName() + " " + device.OSVersion())
        b.Close()
        b.Open("button")
        b.Text("battery " + device.BatteryLevel() + "%, " + network_name())
        b.Close()
        b.Open("button")
        b.Text(device.Language() + ", " + device.TimeZone() + ", v" + device.AppVersion())
        b.Close()
    end)
end
Outputno device info here

Build with --scheme demo, then open demo://hello on the phone. The page shows the link and has a button for the app settings.

gui-device-Links.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import gui.device
import gui.ui

mut last := ""

func main:
    last = device.LaunchURL()
    if last.Len() == 0 and device.Platform() == "none":
        println "no links here"
        ret
    end
    device.OnOpenURL((url: str): ui.Invalidate() last = url end)
    ui.RunPage((): ret ui.NoPatches() end, (b: ui.Builder):
        b.Open("button")
        b.Text("opened with " + last)
        b.Close()
        b.Open("button")
        b.On("click", (): _ok := device.OpenSettings() end)
        b.Text("app settings")
        b.Close()
    end)
end
Outputno links here

Full screen and bright

Keep the screen on, lock to portrait, and two buttons for full screen and full brightness.

gui-device-Screen.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import gui.device
import gui.ui

mut full := false

func main:
    if not device.KeepAwake(true):
        println "no screen control here"
        ret
    end
    _lock := device.LockOrientation(device.Orientation.Portrait)
    ui.RunPage((): ret ui.NoPatches() end, (b: ui.Builder):
        b.Open("button")
        b.On("click", (): full = not full _ok := device.Immersive(full) end)
        b.Text("full screen")
        b.Close()
        b.Open("button")
        b.On("click", (): _ok2 := device.SetBrightness(1.0) end)
        b.Text("full brightness")
        b.Close()
    end)
end
Outputno screen control here

Unlock with a fingerprint

A button that asks the system to recognise the user and shows the result.

gui-device-Auth.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import gui.device
import gui.ui

func label(): str:
    state := device.AuthStatus()
    if state == device.AuthState.Success:
        ret "unlocked"
    end
    if state == device.AuthState.Pending:
        ret "waiting"
    end
    if state == device.AuthState.Failed:
        ret "not recognised"
    end
    ret "locked"
end

func main:
    if not device.CanAuthenticate():
        println "no biometrics here"
        ret
    end
    device.OnChange((): ui.Invalidate() end)
    ui.RunPage((): ret ui.NoPatches() end, (b: ui.Builder):
        b.Open("button")
        b.On("click", (): _ok := device.Authenticate("Unlock the notes") end)
        b.Text(label())
        b.Close()
    end)
end
Outputno biometrics here

Types

Permission

enum Permission
A permission the app can ask for.
NameTypeDescription
CameraTaking pictures.
MicrophoneRecording sound.
LocationReading the position of the phone.
NotificationsShowing notifications (asked at run time from Android 13).
gui-device-Permission.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import gui.device
import gui.ui

func label(): str:
    s := device.CheckPermission(device.Permission.Camera)
    if s == device.PermissionState.Granted:
        ret "Camera allowed"
    end
    if s == device.PermissionState.Denied:
        ret "Camera denied"
    end
    ret "Ask for the camera"
end

func main:
    println label()
    device.OnChange((): ui.Invalidate() end)
    ui.RunPage((): ret ui.NoPatches() end, (b: ui.Builder):
        b.Open("button")
        b.On("click", (): _ok := device.RequestPermission(device.Permission.Camera) end)
        b.Text(label())
        b.Close()
    end)
end

PermissionState

enum PermissionState
What is known about a permission.
NameTypeDescription
NotAskedThe user has not been asked yet.
GrantedThe app may use the feature.
DeniedThe user refused, or the system has no such permission.

The example for this item is shown with the ones above: gui-device-Permission.salam

PhotoState

enum PhotoState
Where a photo request stands.
NameTypeDescription
IdleNo request was made.
PendingThe picker or camera is open.
ReadyA photo was saved; read its path with LastPhoto.
FailedThe user cancelled or the system has no picker or camera.
gui-device-Photo.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import gui.device
import gui.ui

func label(): str:
    state := device.PhotoStatus()
    if state == device.PhotoState.Ready:
        ret "saved to " + device.LastPhoto()
    end
    if state == device.PhotoState.Pending:
        ret "waiting for the photo"
    end
    if state == device.PhotoState.Failed:
        ret "no photo"
    end
    ret "choose a photo"
end

func main:
    println label()
    device.OnChange((): ui.Invalidate() end)
    ui.RunPage((): ret ui.NoPatches() end, (b: ui.Builder):
        b.Open("button")
        b.On("click", (): _ok := device.PickPhoto() end)
        b.Text(label())
        b.Close()
        b.Open("button")
        b.On("click", (): _ok2 := device.TakePhoto() end)
        b.Text("take a photo")
        b.Close()
    end)
end

LocationState

enum LocationState
Where a location request stands.
NameTypeDescription
IdleNo request was made.
PendingA fix is being looked for.
ReadyA fix arrived; read it with LastLocation.
FailedNo fix could be made: the permission is missing or no provider is on.
gui-device-Location.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import gui.device
import gui.ui
import str

func where(): str:
    state := device.LocationStatus()
    if state == device.LocationState.Ready:
        here := device.LastLocation()
        ret "lat " + str.FromFloat(here.latitude) + " lon " + str.FromFloat(here.longitude) + " within " + str.FromFloat(here.accuracy) + " m"
    end
    if state == device.LocationState.Pending:
        ret "looking for the position"
    end
    if state == device.LocationState.Failed:
        ret "no position"
    end
    ret "tap to locate"
end

func ask():
    if device.CheckPermission(device.Permission.Location) == device.PermissionState.Granted:
        _ok := device.RequestLocation()
        ui.Invalidate()
    else:
        _ok2 := device.RequestPermission(device.Permission.Location)
    end
end

func main:
    println where()
    device.OnChange((): ui.Invalidate() end)
    ui.RunPage((): ret ui.NoPatches() end, (b: ui.Builder):
        b.Open("button")
        b.On("click", (): ask() end)
        b.Text(where())
        b.Close()
    end)
end

Location

struct Location
One position fix.
NameTypeDescription
latitudef64 = 0Degrees north of the equator.
longitudef64 = 0Degrees east of the prime meridian.
accuracyf64 = 0The error radius in meters, 0 when unknown.

The example for this item is shown with the ones above: gui-device-Location.salam

HapticKind

enum HapticKind
The kind of feedback for Haptic.
NameTypeDescription
TapA light tap, like pressing a key.
HeavyA firmer pulse, like a long press.
SuccessA confirmation pulse.
FailureA rejection pulse.
gui-device-Haptic.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import gui.device

func main:
    if not device.CanVibrate():
        println "no vibration here"
        ret
    end
    _ok := device.Haptic(device.HapticKind.Tap)
    _ok2 := device.Haptic(device.HapticKind.Success)
    _ok3 := device.Vibrate(200)
end
Outputno vibration here

NetworkKind

enum NetworkKind
The kind of connection the phone is using.
NameTypeDescription
OfflineNo connection.
WifiConnected through Wi-Fi.
CellularConnected through the mobile network.
EthernetConnected through a cable.
OtherConnected some other way, such as a VPN or Bluetooth.
gui-device-Info.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import gui.device
import gui.ui

func network_name(): str:
    kind := device.Network()
    if kind == device.NetworkKind.Wifi:
        ret "wifi"
    end
    if kind == device.NetworkKind.Cellular:
        ret "mobile data"
    end
    if kind == device.NetworkKind.Offline:
        ret "offline"
    end
    ret "connected"
end

func main:
    if device.OSName().Len() == 0:
        println "no device info here"
        ret
    end
    device.OnChange((): ui.Invalidate() end)
    ui.RunPage((): ret ui.NoPatches() end, (b: ui.Builder):
        b.Open("button")
        b.Text(device.Model() + ", " + device.OSName() + " " + device.OSVersion())
        b.Close()
        b.Open("button")
        b.Text("battery " + device.BatteryLevel() + "%, " + network_name())
        b.Close()
        b.Open("button")
        b.Text(device.Language() + ", " + device.TimeZone() + ", v" + device.AppVersion())
        b.Close()
    end)
end
Outputno device info here

Orientation

enum Orientation
How the screen may turn.
NameTypeDescription
AutoFollow the sensor, within what the build allows.
PortraitStay upright.
LandscapeStay on its side.
gui-device-Screen.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import gui.device
import gui.ui

mut full := false

func main:
    if not device.KeepAwake(true):
        println "no screen control here"
        ret
    end
    _lock := device.LockOrientation(device.Orientation.Portrait)
    ui.RunPage((): ret ui.NoPatches() end, (b: ui.Builder):
        b.Open("button")
        b.On("click", (): full = not full _ok := device.Immersive(full) end)
        b.Text("full screen")
        b.Close()
        b.Open("button")
        b.On("click", (): _ok2 := device.SetBrightness(1.0) end)
        b.Text("full brightness")
        b.Close()
    end)
end
Outputno screen control here

BarStyle

enum BarStyle
The look of the status bar icons.
NameTypeDescription
AutoFollow the page and the system appearance.
LightIconsLight icons, for a dark page.
DarkIconsDark icons, for a light page.

The example for this item is shown with the ones above: gui-device-Screen.salam

AuthState

enum AuthState
Where an identity check stands.
NameTypeDescription
IdleNo check was asked for.
PendingThe system prompt is open.
SuccessThe user was recognised.
FailedThe user cancelled, was not recognised or the system has no biometrics.
gui-device-Auth.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import gui.device
import gui.ui

func label(): str:
    state := device.AuthStatus()
    if state == device.AuthState.Success:
        ret "unlocked"
    end
    if state == device.AuthState.Pending:
        ret "waiting"
    end
    if state == device.AuthState.Failed:
        ret "not recognised"
    end
    ret "locked"
end

func main:
    if not device.CanAuthenticate():
        println "no biometrics here"
        ret
    end
    device.OnChange((): ui.Invalidate() end)
    ui.RunPage((): ret ui.NoPatches() end, (b: ui.Builder):
        b.Open("button")
        b.On("click", (): _ok := device.Authenticate("Unlock the notes") end)
        b.Text(label())
        b.Close()
    end)
end
Outputno biometrics here

Functions

Platform

func Platform(): str
Names the system the program runs on: android, ios or none.
gui-device-Share.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import gui.device

func main:
    println "running on", device.Platform()
    if not device.CanShare():
        println "no share sheet here"
        ret
    end
    if device.Share("Salam is a programming language", "https://salamlang.ir"):
        println "share sheet opened"
    else:
        println "could not share"
    end
end
Outputrunning on none no share sheet here

CanShare

func CanShare(): bool
Reports whether the system share sheet is available.

The example for this item is shown with the ones above: gui-device-Share.salam

Share

func Share(text: str, url: str): bool
Opens the system share sheet with a text and a link, joined on two lines. False when both are empty or the system has no share sheet.

The example for this item is shown with the ones above: gui-device-Share.salam

CanVibrate

func CanVibrate(): bool
Reports whether the system can vibrate or give haptic feedback.

The example for this item is shown with the ones above: gui-device-Haptic.salam

Vibrate

func Vibrate(ms: int): bool
Vibrates for the given milliseconds, at most 5000. False when the number is not positive or the system cannot vibrate.

The example for this item is shown with the ones above: gui-device-Haptic.salam

Haptic

func Haptic(kind: HapticKind): bool
Gives short haptic feedback of the given kind. False when the system has none.

The example for this item is shown with the ones above: gui-device-Haptic.salam

DataDir

func DataDir(): str
Returns the private folder for the files the app keeps. Empty where the system has none.
gui-device-Paths.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import gui.device
import io

func main:
    dir := device.DataDir()
    if dir.Len() == 0:
        println "no app folders here"
        ret
    end
    println "data", dir
    println "cache", device.CacheDir()
    println "documents", device.DocumentsDir()
    println "temp", device.TempDir()
    _ok := io.WriteFile(dir + "/notes.txt", "saved")
end
Outputno app folders here

CacheDir

func CacheDir(): str
Returns the folder for files the system may delete when space is low. Empty where the system has none.

The example for this item is shown with the ones above: gui-device-Paths.salam

DocumentsDir

func DocumentsDir(): str
Returns the folder the user can reach: the app folder on shared storage on Android, Documents on iOS. Empty where the system has none.

The example for this item is shown with the ones above: gui-device-Paths.salam

TempDir

func TempDir(): str
Returns the folder for short lived files. Empty where the system has none.

The example for this item is shown with the ones above: gui-device-Paths.salam

SecureSet

func SecureSet(key: str, value: str): bool
Saves a value under a key in the Android Keystore backed storage or the iOS Keychain. False when the key is empty or longer than 200 bytes, the value is longer than 16000 bytes or the system has no secure storage.
gui-device-Secure.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import gui.device

func main:
    if not device.SecureSet("token", "s3cret"):
        println "no secure storage here"
        ret
    end
    println "token", device.SecureGet("token")
    _gone := device.SecureDelete("token")
    println "after delete", device.SecureGet("token").Len()
end
Outputno secure storage here

SecureGet

func SecureGet(key: str): str
Returns the value saved under the key, or an empty string when there is none.

The example for this item is shown with the ones above: gui-device-Secure.salam

SecureDelete

func SecureDelete(key: str): bool
Removes the value saved under the key. False when there was none or the system has no secure storage.

The example for this item is shown with the ones above: gui-device-Secure.salam

Model

func Model(): str
Returns the model of the phone. Empty where the system has none.

The example for this item is shown with the ones above: gui-device-Info.salam

OSName

func OSName(): str
Returns the name of the operating system: Android or iOS. Empty on a desktop.

The example for this item is shown with the ones above: gui-device-Info.salam

OSVersion

func OSVersion(): str
Returns the version of the operating system, such as 15. Empty on a desktop.

The example for this item is shown with the ones above: gui-device-Info.salam

Language

func Language(): str
Returns the preferred language as a tag, such as en-US. Empty on a desktop.

The example for this item is shown with the ones above: gui-device-Info.salam

Languages

func Languages(): Vector<str>
Returns all languages the user chose, the preferred one first. Empty on a desktop.

The example for this item is shown with the ones above: gui-device-Info.salam

TimeZone

func TimeZone(): str
Returns the name of the time zone, such as Asia/Tehran. Empty on a desktop.

The example for this item is shown with the ones above: gui-device-Info.salam

ScreenDensity

func ScreenDensity(): f64
Returns how many pixels make one point of the layout, such as 2.75. Zero on a desktop.

The example for this item is shown with the ones above: gui-device-Info.salam

AppVersion

func AppVersion(): str
Returns the version name of the app, set with --version when building. Empty on a desktop.

The example for this item is shown with the ones above: gui-device-Info.salam

BuildNumber

func BuildNumber(): int
Returns the build number of the app, set with --build when building. Zero on a desktop.

The example for this item is shown with the ones above: gui-device-Info.salam

IsDarkMode

func IsDarkMode(): bool
Reports whether the system shows the dark appearance.

The example for this item is shown with the ones above: gui-device-Info.salam

BatteryLevel

func BatteryLevel(): int
Returns the charge in percent from 0 to 100, or -1 when it is not known.

The example for this item is shown with the ones above: gui-device-Info.salam

IsCharging

func IsCharging(): bool
Reports whether the phone is plugged in and charging, or full.

The example for this item is shown with the ones above: gui-device-Info.salam

Network

func Network(): NetworkKind
Returns the kind of connection in use. When it changes, the function set by OnChange runs. On Android the build declares ACCESS_NETWORK_STATE when you call it.

The example for this item is shown with the ones above: gui-device-Info.salam

KeepAwake

func KeepAwake(enabled: bool): bool
Keeps the screen on while the app is in front, or lets it sleep again. False where the system has no such control.

The example for this item is shown with the ones above: gui-device-Screen.salam

LockOrientation

func LockOrientation(o: Orientation): bool
Locks the screen to portrait or landscape at run time, or frees it with Auto. The build option --orientation sets the start. False where the system has no such control.

The example for this item is shown with the ones above: gui-device-Screen.salam

Immersive

func Immersive(enabled: bool): bool
Hides the status bar and the navigation bar (the home indicator on iOS) for a full screen page, or shows them again. False where the system has no such control.

The example for this item is shown with the ones above: gui-device-Screen.salam

SetBarStyle

func SetBarStyle(style: BarStyle): bool
Chooses light or dark status bar icons, overriding the choice the page makes from its background. Auto gives the choice back. False where the system has no status bar.

The example for this item is shown with the ones above: gui-device-Screen.salam

SetBrightness

func SetBrightness(level: f64): bool
Sets the screen brightness from 0.0 to 1.0 while the app runs. A negative number gives control back to the system. On iOS the change is system wide until restored. False where the system has no such control.

The example for this item is shown with the ones above: gui-device-Screen.salam

Brightness

func Brightness(): f64
Returns the screen brightness from 0.0 to 1.0, or -1 when it is not known.

The example for this item is shown with the ones above: gui-device-Screen.salam

CanAuthenticate

func CanAuthenticate(): bool
Reports whether the phone has biometrics (fingerprint or face) the user has set up. Android 10 and newer, and iOS.

The example for this item is shown with the ones above: gui-device-Auth.salam

Authenticate

func Authenticate(reason: str): bool
Opens the system biometric prompt with the given reason as its title. False when there are no biometrics; the answer comes through OnChange and AuthStatus. The build declares USE_BIOMETRIC on Android and the Face ID description on iOS when you call it.

The example for this item is shown with the ones above: gui-device-Auth.salam

AuthStatus

func AuthStatus(): AuthState
Returns the state of the last identity check.

The example for this item is shown with the ones above: gui-device-Auth.salam

OnChange

func OnChange(hook: func())
Sets the function that runs on the UI thread after a permission request or another host answer arrives. gui.ui apps get it called by the event loop.

The example for this item is shown with the ones above: gui-device-Permission.salam

OnOpenURL

func OnOpenURL(hook: func(str))
Sets the function that runs with the link when the app is opened by a link while it is already running. Needs the build option --scheme or --link-host. Several links in a row give the latest.
gui-device-Links.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import gui.device
import gui.ui

mut last := ""

func main:
    last = device.LaunchURL()
    if last.Len() == 0 and device.Platform() == "none":
        println "no links here"
        ret
    end
    device.OnOpenURL((url: str): ui.Invalidate() last = url end)
    ui.RunPage((): ret ui.NoPatches() end, (b: ui.Builder):
        b.Open("button")
        b.Text("opened with " + last)
        b.Close()
        b.Open("button")
        b.On("click", (): _ok := device.OpenSettings() end)
        b.Text("app settings")
        b.Close()
    end)
end
Outputno links here

LaunchURL

func LaunchURL(): str
Returns the link that started the app, or an empty string when it was started in the usual way or the system has no links.

The example for this item is shown with the ones above: gui-device-Links.salam

OpenSettings

func OpenSettings(): bool
Opens the settings page of the app, where the user can change its permissions. False where the system has none.

The example for this item is shown with the ones above: gui-device-Links.salam

Notify

func Notify()
Runs the function set by OnChange. gui.ui calls it for you; call it yourself from a HostResult event of gui.window.

The example for this item is shown with the ones above: gui-device-Permission.salam

CheckPermission

func CheckPermission(p: Permission): PermissionState
Returns the state of a permission without asking.

The example for this item is shown with the ones above: gui-device-Permission.salam

RequestPermission

func RequestPermission(p: Permission): bool
Opens the system dialog for a permission. Returns false when the system has no such permission or it is not declared; the answer comes through OnChange.

The example for this item is shown with the ones above: gui-device-Permission.salam

ShowNotification

func ShowNotification(id: int, title: str, body: str): bool
Posts a notification now with an id, a title and a body. False when notifications are not allowed, both texts are empty or the system has none.
gui-device-Notification.salam
/*
 * Salam Programming Language (2018-2026)
 *
 *   +-------------------+
 *   |     S A L A M     |
 *   +-------------------+
 *
 * Designed by Seyyed Ali Mohammadiyeh and the Salam Team
 *
 * Repository: https://github.com/SalamLang/Salam
 *
 */


import gui.device

func main:
    if device.CheckPermission(device.Permission.Notifications) != device.PermissionState.Granted:
        println "notifications are not allowed"
        ret
    end
    _ok := device.ShowNotification(1, "Download finished", "report.pdf is ready")
    _ok2 := device.ScheduleNotification(2, "Stand up", "Time for a break", 1800)
    _ok3 := device.CancelNotification(2)
end
Outputnotifications are not allowed

ScheduleNotification

func ScheduleNotification(id: int, title: str, body: str, seconds: int): bool
Posts a notification after the given seconds, even if the app is closed by then. False when the seconds are not positive or notifications are not allowed.

The example for this item is shown with the ones above: gui-device-Notification.salam

CancelNotification

func CancelNotification(id: int): bool
Removes the notification with the id and cancels it if it is still scheduled.

The example for this item is shown with the ones above: gui-device-Notification.salam

RequestLocation

func RequestLocation(): bool
Starts a one shot location request. False when the system has no location or the permission is missing.

The example for this item is shown with the ones above: gui-device-Location.salam

LocationStatus

func LocationStatus(): LocationState
Returns the state of the last request.

The example for this item is shown with the ones above: gui-device-Location.salam

LastLocation

func LastLocation(): Location
Returns the last fix, zeros before the first one.

The example for this item is shown with the ones above: gui-device-Location.salam

PickPhoto

func PickPhoto(): bool
Opens the system photo picker. False when the system has none; the answer comes through OnChange.

The example for this item is shown with the ones above: gui-device-Photo.salam

TakePhoto

func TakePhoto(): bool
Opens the camera app to take one picture. False when the system has none; the answer comes through OnChange.

The example for this item is shown with the ones above: gui-device-Photo.salam

PhotoStatus

func PhotoStatus(): PhotoState
Returns the state of the last photo request.

The example for this item is shown with the ones above: gui-device-Photo.salam

LastPhoto

func LastPhoto(): str
Returns the path of the last photo, empty before the first one.

The example for this item is shown with the ones above: gui-device-Photo.salam