Add c2nim generated bindings

This commit is contained in:
Joey Yakimowich-Payne 2022-12-05 20:06:16 -07:00
commit 265586cabf
No known key found for this signature in database
GPG key ID: 6BFE655FA5ABD1E1
356 changed files with 78487 additions and 395 deletions

1
.gitignore vendored
View file

@ -19,7 +19,6 @@ tags
build
*.elf
wrapper
nimcache/
nimcache*/

View file

@ -16,13 +16,9 @@ if detectOs(Windows):
username = getEnv("USERNAME")
# Deps
requires "nim >= 0.18.1", "nimgen#dc9943a22c9c8f6a5a6a92f0055e1de4dfaf87d2"
requires "nim >= 1.6.6"
requires "switch_build >= 0.1.3"
task setup, "Download and generate bindings":
echo "Building libnx..."
exec prefix & "nimgen libnxGen.cfg"
task buildExamples, "Build switch examples":
if detectOs(Windows):
let devkitPath = getEnv("DEVKITPRO")

View file

@ -1,389 +0,0 @@
[n.global]
output="src/libnx/wrapper"
c_compiler="aarch64-none-elf-gcc"
cpp_compiler="aarch64-none-elf-g++"
filter=lock
[n.include]
"${output}/nx/include"
"${output}/nx/include/switch"
"${output}/nx/include/switch/arm"
"${output}/nx/include/switch/audio"
"${output}/nx/include/switch/display"
"${output}/nx/include/switch/kernel"
"${output}/nx/include/switch/nvidia"
"${output}/nx/include/switch/runtime"
"${output}/nx/include/switch/runtime/util"
"${output}/nx/include/switch/runtime/devices"
"${output}/nx/include/switch/services"
"${DEVKITPRO}/devkitA64/aarch64-none-elf/include/"
[n.exclude]
"${output}/nim.cfg"
"${output}/config.nims"
[svc.h]
search = "PACKED"
replace = ""
search.noreturn = "NORETURN"
replace.noreturn = ""
defines=true
[result.h]
defines = true
[thread_context.h]
preprocess = false
[hid.h]
defines = true
search.static_assert = "static_assert"
replace.static_assert = "// static_assert"
search.touch = "touchPosition"
replace.touch = "TouchPosition"
[ipc.h]
defines = true
[romfs_dev.h]
search = "romfs_"
replace = "Romfs_"
[gfx.h]
defines = true
[ioctl.h]
defines = true
search = "_NV_"
replace = "UNV_"
search.nv = "__nv_"
replace.nv = "DUnv_"
[n.wildcard]
wildcard.1 = "console.h"
rename = "$replace(console=cons)"
wildcard.2 = "*.h"
search.u8 = "u8"
replace.u8 = "uint8"
search.u16 = "u16"
replace.u16 = "uint16"
search.u32 = "u32"
replace.u32 = "uint32"
search.u64 = "u64"
replace.u64 = "uint64"
wildcard.3 = "*.nim"
search.bool = "_Bool"
replace.bool = "bool"
search.lib = "src/libnx/wrapper"
replace.lib = "libnx/wrapper"
search.kimport = "../kernel/"
replace.kimport = "libnx/wrapper/"
search.resimport = "../result"
replace.resimport = "libnx/wrapper/result"
search.armimport = "../arm/"
replace.armimport = "libnx/wrapper/"
search.lock = "_LOCK"
replace.lock = "LOCK"
search.cdecl = "stdcall"
replace.cdecl = "cdecl"
[n.prepare]
git = "https://github.com/switchbrew/libnx"
execute-lin = """cd ${output}; make;"""
execute-mac = """cd ${output}; make;"""
[n.post]
reset=true
[src/libnx/wrapper/nim.cfg]
create = """
--path:"../"
--path:"../../"
"""
noprocess=true
[src/libnx/wrapper/config.nims]
create = """
switch("passC", "-I" & thisDir() & "/nx/include")
switch("passL", "-specs=" & thisDir() & "/nx/switch.specs -L" & thisDir() & "/nx/lib -lnx")
"""
noprocess=true
[switch.h]
preprocess = true
defines = true
recurse = true
[types.nim]
search.o = " uint8*"
prepend.o = """
u8* = uint8
u16* = uint16
u32* = uint32
u64* = uint64
int8_t* = int8
int16_t* = int16
int32_t* = int32
int64_t* = int64
ssize_t* = int
"""
search.s128 = " s128* = __int128_t"
replace.s128 = ""
search.u128 = " u128* = __uint128_t"
replace.u128 = ""
search.uint8 = "uint8* = uint8_t"
replace.uint8 = "uint8_t* = uint8"
search.uint16 = "uint16* = uint16_t"
replace.uint16 = "uint16_t* = uint16"
search.uint32 = "uint32* = uint32_t"
replace.uint32 = "uint32_t* = uint32"
search.uint64 = "uint64* = uint64_t"
replace.uint64 = "uint64_t* = uint64"
search.import = "type\n"
prepend.import = """
import libnx/ext/integer128
template BIT*(n): auto = (1.uint shl n)
"""
[thread_context.nim]
search.timport = "../types"
replace.timport = "libnx/wrapper/types"
prepend.o = """
import libnx/ext/integer128
"""
search.cpuall = "RegisterGroup_CpuAll ="
comment.cpuall = 1
search.fpugprs = "RegisterGroup_FpuGprs ="
prepend.fpugprs = "RegisterGroup_CpuAll = BIT(0) or BIT(1), ## /< All CPU registers."
search.fpuall = "RegisterGroup_FpuGprs or RegisterGroup_FpuSprs"
replace.fpuall = "BIT(2) or BIT(3)"
search.groupall = "RegisterGroup_CpuAll or RegisterGroup_FpuAll"
replace.groupall = "BIT(0) or BIT(1) or BIT(2) or BIT(3)"
[svc.nim]
search.timport = "../types"
replace.timport = "libnx/wrapper/types"
search.permx = "Perm_X = BIT(2), ## /< Execute permission."
replace.permx = "Perm_Rw = Perm_R.int or Perm_W.int, ## /< Read/write permissions."
search.permrw = "Perm_Rw = Perm_R or Perm_W, ## /< Read/write permissions."
replace.permrw = "Perm_X = BIT(2), ## /< Execute permission."
search.permrx = "Perm_Rx = Perm_R or Perm_X, ## /< Read/execute permissions."
replace.permrx = "Perm_Rx = Perm_R.int or Perm_X.int, ## /< Read/execute permissions."
[shmem.nim]
search.import = "type\n"
prepend.import = """
import libnx/wrapper/svc
"""
[nacp.nim]
search.t = "type"
prepend.t = """
import libnx/wrapper/types
"""
[lock.nim]
search.flock_t = " __lock_t"
replace.flock_t = " DUlock_t"
search.nlock_t = "= __lock_t"
replace.nlock_t = "= DUlock_t"
search.import = "type"
prepend.import = """
import libnx/wrapper/types
"""
search.proc_under = "proc __"
replace.proc_under = "proc DU"
[ipc.nim]
search.o = "UINT32_MAX"
replace.o = "uint32.high"
search.import = "import\n"
append.import = """
libnx/wrapper/types,
"""
[audin.nim]
search.o = "import "
prepend.o = """
import libnx/wrapper/types
"""
[audout.nim]
search.o = "import "
prepend.o = """
import libnx/wrapper/types
"""
[hid.nim]
search.servimport = "../services/"
replace.servimport = "libnx/wrapper/"
search.timport = "../types"
replace.timport = "libnx/wrapper/types"
search.o = """ KEY_JOYCON_RIGHT = BIT(0), KEY_JOYCON_DOWN = BIT(1), KEY_JOYCON_UP = BIT(2), KEY_JOYCON_LEFT = BIT(
3),"""
replace.o = ""
search.key_left = "KEY_LEFT = KEY_DLEFT or KEY_LSTICK_LEFT or KEY_RSTICK_LEFT, ## /< D-Pad Left or Sticks Left"
replace.key_left = ""
search.key_rstick_up = " KEY_RSTICK_UP"
prepend.key_rstick_up = """
KEY_LEFT = KEY_DLEFT.int or KEY_LSTICK_LEFT.int or KEY_RSTICK_LEFT.int, ## /< D-Pad Left or Sticks Left
"""
search.key_right = " KEY_RIGHT = KEY_DRIGHT or KEY_LSTICK_RIGHT or KEY_RSTICK_RIGHT ## /< D-Pad Right or Sticks Right"
replace.key_right = ""
search.key_rstick_down = " KEY_RSTICK_DOWN"
prepend.key_rstick_down = """
KEY_RIGHT = KEY_DRIGHT.int or KEY_LSTICK_RIGHT.int or KEY_RSTICK_RIGHT.int, ## /< D-Pad Right or Sticks Right
"""
search.key_up = " KEY_UP = KEY_DUP or KEY_LSTICK_UP or KEY_RSTICK_UP, ## /< D-Pad Up or Sticks Up"
replace.key_up = ""
search.key_rstick_right = " KEY_RSTICK_RIGHT"
prepend.key_rstick_right = """
KEY_UP = KEY_DUP.int or KEY_LSTICK_UP.int or KEY_RSTICK_UP.int, ## /< D-Pad Up or Sticks Up
"""
search.key_down = " KEY_DOWN = KEY_DDOWN or KEY_LSTICK_DOWN or KEY_RSTICK_DOWN, ## /< D-Pad Down or Sticks Down"
replace.key_down = ""
search.key_sl = " KEY_SL"
prepend.key_sl = """
KEY_DOWN = KEY_DDOWN.int or KEY_LSTICK_DOWN.int or KEY_RSTICK_DOWN.int, ## /< D-Pad Down or Sticks Down
"""
[nifm.nim]
search.o = "import libnx"
prepend.o = """
import libnx/wrapper/types
"""
[set.nim]
search.o = "import libnx"
prepend.o = """
import libnx/wrapper/types
"""
[parcel.nim]
search.o = "import libnx"
prepend.o = """
import libnx/wrapper/types
"""
[fs_dev.nim]
search.o = "import libnx"
prepend.o = """
import libnx/wrapper/types
"""
[buffer_producer.nim]
search.o = "import libnx"
prepend.o = """
import libnx/wrapper/types
import libnx/wrapper/binder
"""
[nxlink.nim]
search.o = "var __nxlink"
replace.o = "var DUnxlink"
[fs.nim]
search.o = "import libnx"
prepend.o = """
import libnx/ext/integer128
"""
[acc.nim]
prepend.o = """
import libnx/ext/integer128
"""
[fence.nim]
prepend.o = """
import libnx/wrapper/types
"""
[cons.nim]
search.o = "type\n"
prepend.o = """
template CONSOLE_ESC*(x: string): string = "\x1b[" & $x
# Colors
template CONSOLE_RESET*: string = CONSOLE_ESC("0m")
template CONSOLE_BLACK*: string = CONSOLE_ESC("30m")
template CONSOLE_RED*: string = CONSOLE_ESC("31;1m")
template CONSOLE_GREEN*: string = CONSOLE_ESC("32;1m")
template CONSOLE_YELLOW*: string = CONSOLE_ESC("33;1m")
template CONSOLE_BLUE*: string = CONSOLE_ESC("34;1m")
template CONSOLE_MAGENTA*: string = CONSOLE_ESC("35;1m")
template CONSOLE_CYAN*: string = CONSOLE_ESC("36;1m")
template CONSOLE_WHITE*: string = CONSOLE_ESC("37;1m")
# Styles
template CONSOLE_COLOR_BOLD*: int = BIT(0).int
template CONSOLE_COLOR_FAINT*: int = BIT(1).int
template CONSOLE_ITALIC*: int = BIT(2).int
template CONSOLE_UNDERLINE*: int = BIT(3).int
template CONSOLE_BLINK_SLOW*: int = BIT(4).int
template CONSOLE_BLINK_FAST*: int = BIT(5).int
template CONSOLE_COLOR_REVERSE*: int = BIT(6).int
template CONSOLE_CONCEAL*: int = BIT(7).int
template CONSOLE_CROSSED_OUT*: int = BIT(8).int
"""
search.threedmoo = "debugDevice_3DMOO"
replace.threedmoo = "debugDevice_3DMOO*"
[gfx.nim]
search.timport = "../types"
replace.timport = "libnx/wrapper/types"
search.fimport = "../nvidia/fence"
replace.fimport = "libnx/wrapper/fence"
[romfs_dev.nim]
search.timport = "../types"
replace.timport = "libnx/wrapper/types"
search.servimport = "../services/"
replace.servimport = "libnx/wrapper/"
search.o = "../libnx"
replace.o = "libnx"
[n.sourcefile]
"${output}/*.nim"

197
src/libnx/wrapper/switch.h Normal file
View file

@ -0,0 +1,197 @@
/**
* @file switch.h
* @brief Central Switch header. Includes all others.
* @copyright libnx Authors
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include "switch/types.h"
#include "switch/result.h"
#include "switch/nro.h"
#include "switch/nacp.h"
#include "switch/arm/tls.h"
#include "switch/arm/cache.h"
#include "switch/arm/counter.h"
#include "switch/kernel/svc.h"
#include "switch/kernel/wait.h"
#include "switch/kernel/tmem.h"
#include "switch/kernel/shmem.h"
#include "switch/kernel/mutex.h"
#include "switch/kernel/event.h"
#include "switch/kernel/levent.h"
#include "switch/kernel/uevent.h"
#include "switch/kernel/utimer.h"
#include "switch/kernel/rwlock.h"
#include "switch/kernel/condvar.h"
#include "switch/kernel/thread.h"
#include "switch/kernel/semaphore.h"
#include "switch/kernel/virtmem.h"
#include "switch/kernel/detect.h"
#include "switch/kernel/random.h"
#include "switch/kernel/jit.h"
#include "switch/kernel/barrier.h"
#include "switch/sf/hipc.h"
#include "switch/sf/cmif.h"
#include "switch/sf/service.h"
#include "switch/sf/sessionmgr.h"
#include "switch/sf/tipc.h"
#include "switch/services/sm.h"
#include "switch/services/smm.h"
#include "switch/services/fs.h"
#include "switch/services/fsldr.h"
#include "switch/services/fspr.h"
#include "switch/services/acc.h"
#include "switch/services/apm.h"
#include "switch/services/applet.h"
#include "switch/services/async.h"
#include "switch/services/audctl.h"
#include "switch/services/audin.h"
#include "switch/services/audout.h"
#include "switch/services/audrec.h"
#include "switch/services/audren.h"
#include "switch/services/auddev.h"
#include "switch/services/hwopus.h"
#include "switch/services/csrng.h"
#include "switch/services/lbl.h"
#include "switch/services/i2c.h"
#include "switch/services/gpio.h"
#include "switch/services/uart.h"
#include "switch/services/bpc.h"
#include "switch/services/pcv.h"
#include "switch/services/clkrst.h"
#include "switch/services/fan.h"
#include "switch/services/pgl.h"
#include "switch/services/psm.h"
#include "switch/services/spsm.h"
//#include "switch/services/bsd.h" Use <sys/socket.h> instead
//#include "switch/services/sfdnsres.h" Use <netdb.h> instead
//#include "switch/services/htcs.h"
#include "switch/services/fatal.h"
#include "switch/services/time.h"
#include "switch/services/usb.h"
#include "switch/services/usbds.h"
#include "switch/services/usbhs.h"
#include "switch/services/hid.h"
#include "switch/services/hidbus.h"
#include "switch/services/hiddbg.h"
#include "switch/services/hidsys.h"
#include "switch/services/irs.h"
#include "switch/services/pl.h"
#include "switch/services/vi.h"
#include "switch/services/nv.h"
#include "switch/services/nifm.h"
#include "switch/services/nim.h"
#include "switch/services/ns.h"
#include "switch/services/ldr.h"
#include "switch/services/ro.h"
#include "switch/services/tc.h"
#include "switch/services/ts.h"
#include "switch/services/pm.h"
#include "switch/services/set.h"
#include "switch/services/ssl.h"
#include "switch/services/lr.h"
#include "switch/services/bt.h"
#include "switch/services/btdrv.h"
#include "switch/services/btm.h"
#include "switch/services/btmu.h"
#include "switch/services/btmsys.h"
#include "switch/services/spl.h"
#include "switch/services/ncm.h"
#include "switch/services/psc.h"
#include "switch/services/caps.h"
#include "switch/services/capsa.h"
#include "switch/services/capsc.h"
#include "switch/services/capsdc.h"
#include "switch/services/capsu.h"
#include "switch/services/capssc.h"
#include "switch/services/capssu.h"
#include "switch/services/capmtp.h"
#include "switch/services/nfc.h"
#include "switch/services/wlaninf.h"
#include "switch/services/pctl.h"
#include "switch/services/pdm.h"
#include "switch/services/grc.h"
#include "switch/services/friends.h"
#include "switch/services/notif.h"
#include "switch/services/mii.h"
#include "switch/services/miiimg.h"
#include "switch/services/ldn.h"
#include "switch/services/lp2p.h"
#include "switch/services/news.h"
#include "switch/services/ins.h"
#include "switch/services/ectx.h"
#include "switch/services/avm.h"
#include "switch/services/mm.h"
#include "switch/display/binder.h"
#include "switch/display/parcel.h"
#include "switch/display/buffer_producer.h"
#include "switch/display/native_window.h"
#include "switch/display/framebuffer.h"
#include "switch/nvidia/ioctl.h"
#include "switch/nvidia/graphic_buffer.h"
#include "switch/nvidia/fence.h"
#include "switch/nvidia/map.h"
#include "switch/nvidia/address_space.h"
#include "switch/nvidia/channel.h"
#include "switch/nvidia/gpu.h"
#include "switch/nvidia/gpu_channel.h"
#include "switch/audio/driver.h"
#include "switch/applets/libapplet.h"
#include "switch/applets/album_la.h"
#include "switch/applets/friends_la.h"
#include "switch/applets/hid_la.h"
#include "switch/applets/mii_la.h"
#include "switch/applets/nfp_la.h"
#include "switch/applets/nifm_la.h"
#include "switch/applets/pctlauth.h"
#include "switch/applets/psel.h"
#include "switch/applets/error.h"
#include "switch/applets/swkbd.h"
#include "switch/applets/web.h"
#include "switch/runtime/env.h"
#include "switch/runtime/hosversion.h"
#include "switch/runtime/diag.h"
#include "switch/runtime/nxlink.h"
#include "switch/runtime/resolver.h"
#include "switch/runtime/pad.h"
#include "switch/runtime/ringcon.h"
#include "switch/runtime/btdev.h"
#include "switch/runtime/util/utf.h"
#include "switch/runtime/devices/console.h"
#include "switch/runtime/devices/usb_comms.h"
#include "switch/runtime/devices/fs_dev.h"
#include "switch/runtime/devices/romfs_dev.h"
#include "switch/runtime/devices/socket.h"
#include "switch/crypto/aes.h"
#include "switch/crypto/aes_cbc.h"
#include "switch/crypto/aes_ctr.h"
#include "switch/crypto/aes_xts.h"
#include "switch/crypto/cmac.h"
#include "switch/crypto/sha256.h"
#include "switch/crypto/sha1.h"
#include "switch/crypto/hmac.h"
#include "switch/crypto/crc.h"
#ifdef __cplusplus
}
#endif

View file

@ -0,0 +1,120 @@
## *
## @file switch.h
## @brief Central Switch header. Includes all others.
## @copyright libnx Authors
##
import
switch/types, switch/result, switch/nro, switch/nacp, switch/arm/tls,
switch/arm/cache, switch/arm/counter, switch/kernel/svc, switch/kernel/wait,
switch/kernel/tmem, switch/kernel/shmem, switch/kernel/mutex,
switch/kernel/event, switch/kernel/levent, switch/kernel/uevent,
switch/kernel/utimer, switch/kernel/rwlock, switch/kernel/condvar,
switch/kernel/thread, switch/kernel/semaphore, switch/kernel/virtmem,
switch/kernel/detect, switch/kernel/random, switch/kernel/jit,
switch/kernel/barrier, switch/sf/hipc, switch/sf/cmif, switch/sf/service,
switch/sf/sessionmgr, switch/sf/tipc, switch/services/sm, switch/services/smm,
switch/services/fs, switch/services/fsldr, switch/services/fspr,
switch/services/acc, switch/services/apm, switch/services/applet,
switch/services/async, switch/services/audctl, switch/services/audin,
switch/services/audout, switch/services/audrec, switch/services/audren,
switch/services/auddev, switch/services/hwopus, switch/services/csrng,
switch/services/lbl, switch/services/i2c, switch/services/gpio,
switch/services/uart, switch/services/bpc, switch/services/pcv,
switch/services/clkrst, switch/services/fan, switch/services/pgl,
switch/services/psm, switch/services/spsm
export
types, result, nro, nacp, tls,
cache, counter, svc, wait,
tmem, shmem, mutex,
event, levent, uevent,
utimer, rwlock, condvar,
thread, semaphore, virtmem,
detect, random, jit,
barrier, hipc, cmif, service,
sessionmgr, tipc, sm, smm,
fs, fsldr, fspr,
acc, apm, applet,
async, audctl, audin,
audout, audrec, audren,
auddev, hwopus, csrng,
lbl, i2c, gpio,
uart, bpc, pcv,
clkrst, fan, pgl,
psm, spsm
import
switch/services/fatal, switch/services/time, switch/services/usb,
switch/services/usbds, switch/services/usbhs, switch/services/hid,
switch/services/hidbus, switch/services/hiddbg, switch/services/hidsys,
switch/services/irs, switch/services/pl, switch/services/vi, switch/services/nv,
switch/services/nifm, switch/services/nim, switch/services/ns,
switch/services/ldr, switch/services/ro, switch/services/tc, switch/services/ts,
switch/services/pm, switch/services/set, switch/services/ssl, switch/services/lr,
switch/services/bt, switch/services/btdrv, switch/services/btm,
switch/services/btmu, switch/services/btmsys, switch/services/spl,
switch/services/ncm, switch/services/psc, switch/services/caps,
switch/services/capsa, switch/services/capsc, switch/services/capsdc,
switch/services/capsu, switch/services/capssc, switch/services/capssu,
switch/services/capmtp, switch/services/nfc, switch/services/wlaninf,
switch/services/pctl, switch/services/pdm, switch/services/grc,
switch/services/friends, switch/services/notif, switch/services/mii,
switch/services/miiimg, switch/services/ldn, switch/services/lp2p,
switch/services/news, switch/services/ins, switch/services/ectx,
switch/services/avm, switch/services/mm, switch/display/binder,
switch/display/parcel, switch/display/buffer_producer,
switch/display/native_window, switch/display/framebuffer, switch/nvidia/ioctl,
switch/nvidia/graphic_buffer, switch/nvidia/fence, switch/nvidia/map,
switch/nvidia/address_space, switch/nvidia/channel, switch/nvidia/gpu,
switch/nvidia/gpu_channel, switch/audio/driver, switch/applets/libapplet,
switch/applets/album_la, switch/applets/friends_la, switch/applets/hid_la,
switch/applets/mii_la, switch/applets/nfp_la, switch/applets/nifm_la,
switch/applets/pctlauth, switch/applets/psel, switch/applets/error,
switch/applets/swkbd, switch/applets/web, switch/runtime/env,
switch/runtime/hosversion, switch/runtime/diag, switch/runtime/nxlink,
switch/runtime/resolver, switch/runtime/pad, switch/runtime/ringcon,
switch/runtime/btdev, switch/runtime/util/utf, switch/runtime/devices/console,
switch/runtime/devices/usb_comms, switch/runtime/devices/fs_dev,
switch/runtime/devices/romfs_dev, switch/runtime/devices/socket,
switch/crypto/aes, switch/crypto/aes_cbc, switch/crypto/aes_ctr,
switch/crypto/aes_xts, switch/crypto/cmac, switch/crypto/sha256,
switch/crypto/sha1, switch/crypto/hmac, switch/crypto/crc
export
fatal, time, usb,
usbds, usbhs, hid,
hidbus, hiddbg, hidsys,
irs, pl, vi, nv,
nifm, nim, ns,
ldr, ro, tc, ts,
pm, set, ssl, lr,
bt, btdrv, btm,
btmu, btmsys, spl,
ncm, psc, caps,
capsa, capsc, capsdc,
capsu, capssc, capssu,
capmtp, nfc, wlaninf,
pctl, pdm, grc,
friends, notif, mii,
miiimg, ldn, lp2p,
news, ins, ectx,
avm, mm, binder,
parcel, buffer_producer,
native_window, framebuffer, ioctl,
graphic_buffer, fence, map,
address_space, channel, gpu,
gpu_channel, driver, libapplet,
album_la, friends_la, hid_la,
mii_la, nfp_la, nifm_la,
pctlauth, psel, error,
swkbd, web, env,
hosversion, diag, nxlink,
resolver, pad, ringcon,
btdev, utf, console,
usb_comms, fs_dev,
romfs_dev, socket,
aes, aes_cbc, aes_ctr,
aes_xts, cmac, sha256,
sha1, hmac, crc

View file

@ -0,0 +1,31 @@
/**
* @file album_la.h
* @brief Wrapper for using the Album LibraryApplet.
* @author yellows8
* @copyright libnx Authors
*/
#pragma once
#include "../types.h"
/// Arg type values pushed for the applet input storage, stored as an u8.
typedef enum {
AlbumLaArg_ShowAlbumFiles = 0, ///< ShowAlbumFiles. Only displays AlbumFiles associated with the application which launched the Album applet, with the filter button disabled.
AlbumLaArg_ShowAllAlbumFiles = 1, ///< ShowAllAlbumFiles. Displays all AlbumFiles, with filtering allowed.
AlbumLaArg_ShowAllAlbumFilesForHomeMenu = 2, ///< ShowAllAlbumFilesForHomeMenu. Similar to ::AlbumLaArg_ShowAllAlbumFiles.
} AlbumLaArg;
/**
* @brief Launches the applet with ::AlbumLaArg_ShowAlbumFiles and playStartupSound=false.
*/
Result albumLaShowAlbumFiles(void);
/**
* @brief Launches the applet with ::AlbumLaArg_ShowAllAlbumFiles and playStartupSound=false.
*/
Result albumLaShowAllAlbumFiles(void);
/**
* @brief Launches the applet with ::AlbumLaArg_ShowAllAlbumFilesForHomeMenu and playStartupSound=true.
*/
Result albumLaShowAllAlbumFilesForHomeMenu(void);

View file

@ -0,0 +1,36 @@
## *
## @file album_la.h
## @brief Wrapper for using the Album LibraryApplet.
## @author yellows8
## @copyright libnx Authors
##
import
../types
## / Arg type values pushed for the applet input storage, stored as an u8.
type
AlbumLaArg* = enum
AlbumLaArg_ShowAlbumFiles = 0, ## /< ShowAlbumFiles. Only displays AlbumFiles associated with the application which launched the Album applet, with the filter button disabled.
AlbumLaArg_ShowAllAlbumFiles = 1, ## /< ShowAllAlbumFiles. Displays all AlbumFiles, with filtering allowed.
AlbumLaArg_ShowAllAlbumFilesForHomeMenu = 2 ## /< ShowAllAlbumFilesForHomeMenu. Similar to ::AlbumLaArg_ShowAllAlbumFiles.
## *
## @brief Launches the applet with ::AlbumLaArg_ShowAlbumFiles and playStartupSound=false.
##
proc albumLaShowAlbumFiles*(): Result {.cdecl, importc: "albumLaShowAlbumFiles".}
## *
## @brief Launches the applet with ::AlbumLaArg_ShowAllAlbumFiles and playStartupSound=false.
##
proc albumLaShowAllAlbumFiles*(): Result {.cdecl,
importc: "albumLaShowAllAlbumFiles".}
## *
## @brief Launches the applet with ::AlbumLaArg_ShowAllAlbumFilesForHomeMenu and playStartupSound=true.
##
proc albumLaShowAllAlbumFilesForHomeMenu*(): Result {.cdecl,
importc: "albumLaShowAllAlbumFilesForHomeMenu".}

View file

@ -0,0 +1,314 @@
/**
* @file error.h
* @brief Wrapper for using the error LibraryApplet.
* @author StuntHacks, yellows8
* @copyright libnx Authors
*/
#pragma once
#include "../types.h"
#include "../services/set.h"
/// Error type for ErrorCommonHeader.type.
typedef enum {
ErrorType_Normal = 0, ///< Normal
ErrorType_System = 1, ///< System
ErrorType_Application = 2, ///< Application
ErrorType_Eula = 3, ///< EULA
ErrorType_Pctl = 4, ///< Parental Controls
ErrorType_Record = 5, ///< Record
ErrorType_SystemUpdateEula = 8, ///< SystemUpdateEula
} ErrorType;
/// Stores error-codes which are displayed as XXXX-XXXX, low for the former and desc for the latter.
typedef struct {
u32 low; ///< The module portion of the error, normally this should be set to module + 2000.
u32 desc; ///< The error description.
} ErrorCode;
/// Error type for ErrorContext.type
typedef enum {
ErrorContextType_None = 0, ///< None
ErrorContextType_Http = 1, ///< Http
ErrorContextType_FileSystem = 2, ///< FileSystem
ErrorContextType_WebMediaPlayer = 3, ///< WebMediaPlayer
ErrorContextType_LocalContentShare = 4, ///< LocalContentShare
} ErrorContextType;
/// Error context.
typedef struct {
u8 type; ///< Type, see \ref ErrorContextType.
u8 pad[7]; ///< Padding
u8 data[0x1f4]; ///< Data
Result res; ///< Result
} ErrorContext;
/// Common header for the start of the arg storage.
typedef struct {
u8 type; ///< Type, see \ref ErrorType.
u8 jumpFlag; ///< When clear, this indicates WithoutJump.
u8 unk_x2[3]; ///< Unknown
u8 contextFlag; ///< When set with ::ErrorType_Normal, indicates that an additional storage is pushed for \ref ErrorResultBacktrace. [4.0.0+] Otherwise, when set indicates that an additional storage is pushed for \ref ErrorContext.
u8 resultFlag; ///< ErrorCommonArg: When clear, errorCode is used, otherwise the applet generates the error-code from res.
u8 contextFlag2; ///< Similar to contextFlag except for ErrorCommonArg, indicating \ref ErrorContext is used.
} ErrorCommonHeader;
/// Common error arg data.
typedef struct {
ErrorCommonHeader hdr; ///< Common header.
ErrorCode errorCode; ///< \ref ErrorCode
Result res; ///< Result
} ErrorCommonArg;
/// Error arg data for certain errors with module PCTL.
typedef struct {
ErrorCommonHeader hdr; ///< Common header.
Result res; ///< Result
} ErrorPctlArg;
/// ResultBacktrace
typedef struct {
s32 count; ///< Total entries in the backtrace array.
Result backtrace[0x20]; ///< Result backtrace.
} ErrorResultBacktrace;
/// Error arg data for EULA.
typedef struct {
ErrorCommonHeader hdr; ///< Common header.
SetRegion regionCode; ///< \ref SetRegion
} ErrorEulaArg;
/// Additional input storage data for \ref errorSystemUpdateEulaShow.
typedef struct {
u8 data[0x20000]; ///< data
} ErrorEulaData;
/// Error arg data for Record.
typedef struct {
ErrorCommonHeader hdr; ///< Common header.
ErrorCode errorCode; ///< \ref ErrorCode
u64 timestamp; ///< POSIX timestamp.
} ErrorRecordArg;
/// SystemErrorArg
typedef struct {
ErrorCommonHeader hdr; ///< Common header.
ErrorCode errorCode; ///< \ref ErrorCode
u64 languageCode; ///< See set.h.
char dialogMessage[0x800]; ///< UTF-8 Dialog message.
char fullscreenMessage[0x800]; ///< UTF-8 Fullscreen message (displayed when the user clicks on "Details").
} ErrorSystemArg;
/// Error system config.
typedef struct {
ErrorSystemArg arg; ///< Arg data.
ErrorContext ctx; ///< Optional error context.
} ErrorSystemConfig;
/// ApplicationErrorArg
typedef struct {
ErrorCommonHeader hdr; ///< Common header.
u32 errorNumber; ///< Raw decimal error number which is displayed in the dialog.
u64 languageCode; ///< See set.h.
char dialogMessage[0x800]; ///< UTF-8 Dialog message.
char fullscreenMessage[0x800]; ///< UTF-8 Fullscreen message (displayed when the user clicks on "Details").
} PACKED ErrorApplicationArg;
/// Error application config.
typedef struct {
ErrorApplicationArg arg; ///< Arg data.
} ErrorApplicationConfig;
/**
* @brief Creates an \ref ErrorCode.
* @param low The module portion of the error, normally this should be set to module + 2000.
* @param desc The error description.
*/
static inline ErrorCode errorCodeCreate(u32 low, u32 desc) {
return (ErrorCode){low, desc};
}
/**
* @brief Creates an \ref ErrorCode with the input Result. Wrapper for \ref errorCodeCreate.
* @param res Input Result.
*/
static inline ErrorCode errorCodeCreateResult(Result res) {
return errorCodeCreate(2000 + R_MODULE(res), R_DESCRIPTION(res));
}
/**
* @brief Creates an invalid \ref ErrorCode.
*/
static inline ErrorCode errorCodeCreateInvalid(void) {
return (ErrorCode){0};
}
/**
* @brief Checks whether the input ErrorCode is valid.
* @param errorCode \ref ErrorCode
*/
static inline bool errorCodeIsValid(ErrorCode errorCode) {
return errorCode.low!=0;
}
/**
* @brief Launches the applet for displaying the specified Result.
* @param res Result
* @param jumpFlag Jump flag, normally this is true.
* @param ctx Optional \ref ErrorContext, can be NULL. Unused when jumpFlag=false. Ignored on pre-4.0.0, since it's only available for [4.0.0+].
* @note Sets the following fields: jumpFlag and contextFlag2. Uses ::ErrorType_Normal normally.
* @note For module=PCTL errors with desc 100-119 this sets uses ::ErrorType_Pctl, in which case the applet will display the following special dialog: "This software is restricted by Parental Controls".
* @note If the input Result is 0xC8A2, the applet will display a special dialog regarding the current application requiring a software update, with buttons "Later" and "Restart".
* @note [3.0.0+] If the input Result is 0xCAA2, the applet will display a special dialog related to DLC version.
* @warning This applet creates an error report that is logged in the system, when not handling the above special dialogs. Proceed at your own risk!
*/
Result errorResultShow(Result res, bool jumpFlag, const ErrorContext* ctx);
/**
* @brief Launches the applet for displaying the specified ErrorCode.
* @param errorCode \ref ErrorCode
* @param jumpFlag Jump flag, normally this is true.
* @param ctx Optional \ref ErrorContext, can be NULL. Unused when jumpFlag=false. Ignored on pre-4.0.0, since it's only available for [4.0.0+].
* @note Sets the following fields: jumpFlag and contextFlag2. resultFlag=1. Uses ::ErrorType_Normal.
* @warning This applet creates an error report that is logged in the system. Proceed at your own risk!
*/
Result errorCodeShow(ErrorCode errorCode, bool jumpFlag, const ErrorContext* ctx);
/**
* @brief Creates an ErrorResultBacktrace struct.
* @param backtrace \ref ErrorResultBacktrace struct.
* @param count Total number of entries.
* @param entries Input array of Result.
*/
Result errorResultBacktraceCreate(ErrorResultBacktrace* backtrace, s32 count, const Result* entries);
/**
* @brief Launches the applet for \ref ErrorResultBacktrace.
* @param backtrace ErrorResultBacktrace struct.
* @param res Result
* @note Sets the following fields: jumpFlag=1, contextFlag=1, and uses ::ErrorType_Normal.
* @warning This applet creates an error report that is logged in the system. Proceed at your own risk!
*/
Result errorResultBacktraceShow(Result res, const ErrorResultBacktrace* backtrace);
/**
* @brief Launches the applet for displaying the EULA.
* @param RegionCode \ref SetRegion
* @note Sets the following fields: jumpFlag=1, regionCode, and uses ::ErrorType_Eula.
*/
Result errorEulaShow(SetRegion RegionCode);
/**
* @brief Launches the applet for displaying the system-update EULA.
* @param RegionCode \ref SetRegion
* @param eula EULA data. Address must be 0x1000-byte aligned.
* @note Sets the following fields: jumpFlag=1, regionCode, and uses ::ErrorType_SystemUpdateEula.
*/
Result errorSystemUpdateEulaShow(SetRegion RegionCode, const ErrorEulaData* eula);
/**
* @brief Launches the applet for displaying an error full-screen, using the specified ErrorCode and timestamp.
* @param errorCode \ref ErrorCode
* @param timestamp POSIX timestamp.
* @note Sets the following fields: jumpFlag=1, errorCode, timestamp, and uses ::ErrorType_Record.
* @note The applet does not log an error report for this. error*RecordShow is used by qlaunch for displaying previously logged error reports.
*/
Result errorCodeRecordShow(ErrorCode errorCode, u64 timestamp);
/**
* @brief Launches the applet for displaying an error full-screen, using the specified Result and timestamp.
* @param res Result
* @param timestamp POSIX timestamp.
* @note Wrapper for \ref errorCodeRecordShow, see \ref errorCodeRecordShow notes.
*/
static inline Result errorResultRecordShow(Result res, u64 timestamp) {
return errorCodeRecordShow(errorCodeCreateResult(res), timestamp);
}
/**
* @brief Creates an ErrorSystemConfig struct.
* @param c ErrorSystemConfig struct.
* @param dialog_message UTF-8 dialog message.
* @param fullscreen_message UTF-8 fullscreen message, displayed when the user clicks on "Details". Optional, can be NULL (which disables displaying Details).
* @note Sets the following fields: {strings}, and uses ::ErrorType_System. The rest are cleared.
* @note On pre-5.0.0 this will initialize languageCode by using: setInitialize(), setMakeLanguageCode(SetLanguage_ENUS, ...), and setExit(). This is needed since an empty languageCode wasn't supported until [5.0.0+] (which would also use SetLanguage_ENUS).
* @warning This applet creates an error report that is logged in the system. Proceed at your own risk!
*/
Result errorSystemCreate(ErrorSystemConfig* c, const char* dialog_message, const char* fullscreen_message);
/**
* @brief Launches the applet with the specified config.
* @param c ErrorSystemConfig struct.
*/
Result errorSystemShow(ErrorSystemConfig* c);
/**
* @brief Sets the error code.
* @param c ErrorSystemConfig struct.
* @param errorCode \ref ErrorCode
*/
static inline void errorSystemSetCode(ErrorSystemConfig* c, ErrorCode errorCode) {
c->arg.errorCode = errorCode;
}
/**
* @brief Sets the error code, using the input Result. Wrapper for \ref errorSystemSetCode.
* @param c ErrorSystemConfig struct.
* @param res The Result to set.
*/
static inline void errorSystemSetResult(ErrorSystemConfig* c, Result res) {
errorSystemSetCode(c, errorCodeCreateResult(res));
}
/**
* @brief Sets the LanguageCode.
* @param c ErrorSystemConfig struct.
* @param LanguageCode LanguageCode, see set.h.
*/
static inline void errorSystemSetLanguageCode(ErrorSystemConfig* c, u64 LanguageCode) {
c->arg.languageCode = LanguageCode;
}
/**
* @brief Sets the ErrorContext.
* @note Only available on [4.0.0+], on older versions this will return without setting the context.
* @param c ErrorSystemConfig struct.
* @param ctx ErrorContext, NULL to clear it.
*/
void errorSystemSetContext(ErrorSystemConfig* c, const ErrorContext* ctx);
/**
* @brief Creates an ErrorApplicationConfig struct.
* @param c ErrorApplicationConfig struct.
* @param dialog_message UTF-8 dialog message.
* @param fullscreen_message UTF-8 fullscreen message, displayed when the user clicks on "Details". Optional, can be NULL (which disables displaying Details).
* @note Sets the following fields: jumpFlag=1, {strings}, and uses ::ErrorType_Application. The rest are cleared.
* @note On pre-5.0.0 this will initialize languageCode by using: setInitialize(), setMakeLanguageCode(SetLanguage_ENUS, ...), and setExit(). This is needed since an empty languageCode wasn't supported until [5.0.0+] (which would also use SetLanguage_ENUS).
* @note With [10.0.0+] this must only be used when running under an Application, since otherwise the applet will trigger a fatalerr.
* @warning This applet creates an error report that is logged in the system. Proceed at your own risk!
*/
Result errorApplicationCreate(ErrorApplicationConfig* c, const char* dialog_message, const char* fullscreen_message);
/**
* @brief Launches the applet with the specified config.
* @param c ErrorApplicationConfig struct.
*/
Result errorApplicationShow(ErrorApplicationConfig* c);
/**
* @brief Sets the error code number.
* @param c ErrorApplicationConfig struct.
* @param errorNumber Error code number. Raw decimal error number which is displayed in the dialog.
*/
static inline void errorApplicationSetNumber(ErrorApplicationConfig* c, u32 errorNumber) {
c->arg.errorNumber = errorNumber;
}
/**
* @brief Sets the LanguageCode.
* @param c ErrorApplicationConfig struct.
* @param LanguageCode LanguageCode, see set.h.
*/
static inline void errorApplicationSetLanguageCode(ErrorApplicationConfig* c, u64 LanguageCode) {
c->arg.languageCode = LanguageCode;
}

View file

@ -0,0 +1,348 @@
## *
## @file error.h
## @brief Wrapper for using the error LibraryApplet.
## @author StuntHacks, yellows8
## @copyright libnx Authors
##
import
../types, ../services/set, ../result
## / Error type for ErrorCommonHeader.type.
type
ErrorType* = enum
ErrorTypeNormal = 0, ## /< Normal
ErrorTypeSystem = 1, ## /< System
ErrorTypeApplication = 2, ## /< Application
ErrorTypeEula = 3, ## /< EULA
ErrorTypePctl = 4, ## /< Parental Controls
ErrorTypeRecord = 5, ## /< Record
ErrorTypeSystemUpdateEula = 8 ## /< SystemUpdateEula
## / Stores error-codes which are displayed as XXXX-XXXX, low for the former and desc for the latter.
type
ErrorCode* {.bycopy.} = object
low*: U32 ## /< The module portion of the error, normally this should be set to module + 2000.
desc*: U32 ## /< The error description.
## / Error type for ErrorContext.type
type
ErrorContextType* = enum
ErrorContextTypeNone = 0, ## /< None
ErrorContextTypeHttp = 1, ## /< Http
ErrorContextTypeFileSystem = 2, ## /< FileSystem
ErrorContextTypeWebMediaPlayer = 3, ## /< WebMediaPlayer
ErrorContextTypeLocalContentShare = 4 ## /< LocalContentShare
## / Error context.
type
ErrorContext* {.bycopy.} = object
`type`*: U8 ## /< Type, see \ref ErrorContextType.
pad*: array[7, U8] ## /< Padding
data*: array[0x1f4, U8] ## /< Data
res*: Result ## /< Result
## / Common header for the start of the arg storage.
type
ErrorCommonHeader* {.bycopy.} = object
`type`*: U8 ## /< Type, see \ref ErrorType.
jumpFlag*: U8 ## /< When clear, this indicates WithoutJump.
unkX2*: array[3, U8] ## /< Unknown
contextFlag*: U8 ## /< When set with ::ErrorType_Normal, indicates that an additional storage is pushed for \ref ErrorResultBacktrace. [4.0.0+] Otherwise, when set indicates that an additional storage is pushed for \ref ErrorContext.
resultFlag*: U8 ## /< ErrorCommonArg: When clear, errorCode is used, otherwise the applet generates the error-code from res.
contextFlag2*: U8 ## /< Similar to contextFlag except for ErrorCommonArg, indicating \ref ErrorContext is used.
## / Common error arg data.
type
ErrorCommonArg* {.bycopy.} = object
hdr*: ErrorCommonHeader ## /< Common header.
errorCode*: ErrorCode ## /< \ref ErrorCode
res*: Result ## /< Result
## / Error arg data for certain errors with module PCTL.
type
ErrorPctlArg* {.bycopy.} = object
hdr*: ErrorCommonHeader ## /< Common header.
res*: Result ## /< Result
## / ResultBacktrace
type
ErrorResultBacktrace* {.bycopy.} = object
count*: S32 ## /< Total entries in the backtrace array.
backtrace*: array[0x20, Result] ## /< Result backtrace.
## / Error arg data for EULA.
type
ErrorEulaArg* {.bycopy.} = object
hdr*: ErrorCommonHeader ## /< Common header.
regionCode*: SetRegion ## /< \ref SetRegion
## / Additional input storage data for \ref errorSystemUpdateEulaShow.
type
ErrorEulaData* {.bycopy.} = object
data*: array[0x20000, U8] ## /< data
## / Error arg data for Record.
type
ErrorRecordArg* {.bycopy.} = object
hdr*: ErrorCommonHeader ## /< Common header.
errorCode*: ErrorCode ## /< \ref ErrorCode
timestamp*: U64 ## /< POSIX timestamp.
## / SystemErrorArg
type
ErrorSystemArg* {.bycopy.} = object
hdr*: ErrorCommonHeader ## /< Common header.
errorCode*: ErrorCode ## /< \ref ErrorCode
languageCode*: U64 ## /< See set.h.
dialogMessage*: array[0x800, char] ## /< UTF-8 Dialog message.
fullscreenMessage*: array[0x800, char] ## /< UTF-8 Fullscreen message (displayed when the user clicks on "Details").
## / Error system config.
type
ErrorSystemConfig* {.bycopy.} = object
arg*: ErrorSystemArg ## /< Arg data.
ctx*: ErrorContext ## /< Optional error context.
## / ApplicationErrorArg
type
ErrorApplicationArg* {.bycopy.} = object
hdr*: ErrorCommonHeader ## /< Common header.
errorNumber*: U32 ## /< Raw decimal error number which is displayed in the dialog.
languageCode*: U64 ## /< See set.h.
dialogMessage*: array[0x800, char] ## /< UTF-8 Dialog message.
fullscreenMessage*: array[0x800, char] ## /< UTF-8 Fullscreen message (displayed when the user clicks on "Details").
## / Error application config.
type
ErrorApplicationConfig* {.bycopy.} = object
arg*: ErrorApplicationArg ## /< Arg data.
proc errorCodeCreate*(low: U32; desc: U32): ErrorCode {.inline, cdecl.} =
## *
## @brief Creates an \ref ErrorCode.
## @param low The module portion of the error, normally this should be set to module + 2000.
## @param desc The error description.
##
return ErrorCode(low: low, desc: desc)
proc errorCodeCreateResult*(res: Result): ErrorCode {.inline, cdecl.} =
## *
## @brief Creates an \ref ErrorCode with the input Result. Wrapper for \ref errorCodeCreate.
## @param res Input Result.
##
return errorCodeCreate(2000 + r_Module(res), r_Description(res))
proc errorCodeCreateInvalid*(): ErrorCode {.inline, cdecl,
importc: "errorCodeCreateInvalid".} =
## *
## @brief Creates an invalid \ref ErrorCode.
##
return ErrorCode(low: 0, desc: 0)
proc errorCodeIsValid*(errorCode: ErrorCode): bool {.inline, cdecl.} =
## *
## @brief Checks whether the input ErrorCode is valid.
## @param errorCode \ref ErrorCode
##
return errorCode.low != 0
proc errorResultShow*(res: Result; jumpFlag: bool; ctx: ptr ErrorContext): Result {.
cdecl, importc: "errorResultShow".}
## *
## @brief Launches the applet for displaying the specified Result.
## @param res Result
## @param jumpFlag Jump flag, normally this is true.
## @param ctx Optional \ref ErrorContext, can be NULL. Unused when jumpFlag=false. Ignored on pre-4.0.0, since it's only available for [4.0.0+].
## @note Sets the following fields: jumpFlag and contextFlag2. Uses ::ErrorType_Normal normally.
## @note For module=PCTL errors with desc 100-119 this sets uses ::ErrorType_Pctl, in which case the applet will display the following special dialog: "This software is restricted by Parental Controls".
## @note If the input Result is 0xC8A2, the applet will display a special dialog regarding the current application requiring a software update, with buttons "Later" and "Restart".
## @note [3.0.0+] If the input Result is 0xCAA2, the applet will display a special dialog related to DLC version.
## @warning This applet creates an error report that is logged in the system, when not handling the above special dialogs. Proceed at your own risk!
##
proc errorCodeShow*(errorCode: ErrorCode; jumpFlag: bool; ctx: ptr ErrorContext): Result {.
cdecl, importc: "errorCodeShow".}
## *
## @brief Launches the applet for displaying the specified ErrorCode.
## @param errorCode \ref ErrorCode
## @param jumpFlag Jump flag, normally this is true.
## @param ctx Optional \ref ErrorContext, can be NULL. Unused when jumpFlag=false. Ignored on pre-4.0.0, since it's only available for [4.0.0+].
## @note Sets the following fields: jumpFlag and contextFlag2. resultFlag=1. Uses ::ErrorType_Normal.
## @warning This applet creates an error report that is logged in the system. Proceed at your own risk!
##
proc errorResultBacktraceCreate*(backtrace: ptr ErrorResultBacktrace; count: S32;
entries: ptr Result): Result {.cdecl,
importc: "errorResultBacktraceCreate".}
## *
## @brief Creates an ErrorResultBacktrace struct.
## @param backtrace \ref ErrorResultBacktrace struct.
## @param count Total number of entries.
## @param entries Input array of Result.
##
proc errorResultBacktraceShow*(res: Result; backtrace: ptr ErrorResultBacktrace): Result {.
cdecl, importc: "errorResultBacktraceShow".}
## *
## @brief Launches the applet for \ref ErrorResultBacktrace.
## @param backtrace ErrorResultBacktrace struct.
## @param res Result
## @note Sets the following fields: jumpFlag=1, contextFlag=1, and uses ::ErrorType_Normal.
## @warning This applet creates an error report that is logged in the system. Proceed at your own risk!
##
proc errorEulaShow*(regionCode: SetRegion): Result {.cdecl, importc: "errorEulaShow".}
## *
## @brief Launches the applet for displaying the EULA.
## @param RegionCode \ref SetRegion
## @note Sets the following fields: jumpFlag=1, regionCode, and uses ::ErrorType_Eula.
##
proc errorSystemUpdateEulaShow*(regionCode: SetRegion; eula: ptr ErrorEulaData): Result {.
cdecl, importc: "errorSystemUpdateEulaShow".}
## *
## @brief Launches the applet for displaying the system-update EULA.
## @param RegionCode \ref SetRegion
## @param eula EULA data. Address must be 0x1000-byte aligned.
## @note Sets the following fields: jumpFlag=1, regionCode, and uses ::ErrorType_SystemUpdateEula.
##
proc errorCodeRecordShow*(errorCode: ErrorCode; timestamp: U64): Result {.cdecl,
importc: "errorCodeRecordShow".}
## *
## @brief Launches the applet for displaying an error full-screen, using the specified ErrorCode and timestamp.
## @param errorCode \ref ErrorCode
## @param timestamp POSIX timestamp.
## @note Sets the following fields: jumpFlag=1, errorCode, timestamp, and uses ::ErrorType_Record.
## @note The applet does not log an error report for this. error*RecordShow is used by qlaunch for displaying previously logged error reports.
##
proc errorResultRecordShow*(res: Result; timestamp: U64): Result {.inline, cdecl.} =
## *
## @brief Launches the applet for displaying an error full-screen, using the specified Result and timestamp.
## @param res Result
## @param timestamp POSIX timestamp.
## @note Wrapper for \ref errorCodeRecordShow, see \ref errorCodeRecordShow notes.
##
return errorCodeRecordShow(errorCodeCreateResult(res), timestamp)
proc errorSystemCreate*(c: ptr ErrorSystemConfig; dialogMessage: cstring;
fullscreenMessage: cstring): Result {.cdecl,
importc: "errorSystemCreate".}
## *
## @brief Creates an ErrorSystemConfig struct.
## @param c ErrorSystemConfig struct.
## @param dialog_message UTF-8 dialog message.
## @param fullscreen_message UTF-8 fullscreen message, displayed when the user clicks on "Details". Optional, can be NULL (which disables displaying Details).
## @note Sets the following fields: {strings}, and uses ::ErrorType_System. The rest are cleared.
## @note On pre-5.0.0 this will initialize languageCode by using: setInitialize(), setMakeLanguageCode(SetLanguage_ENUS, ...), and setExit(). This is needed since an empty languageCode wasn't supported until [5.0.0+] (which would also use SetLanguage_ENUS).
## @warning This applet creates an error report that is logged in the system. Proceed at your own risk!
##
proc errorSystemShow*(c: ptr ErrorSystemConfig): Result {.cdecl,
importc: "errorSystemShow".}
## *
## @brief Launches the applet with the specified config.
## @param c ErrorSystemConfig struct.
##
proc errorSystemSetCode*(c: ptr ErrorSystemConfig; errorCode: ErrorCode) {.inline,
cdecl.} =
## *
## @brief Sets the error code.
## @param c ErrorSystemConfig struct.
## @param errorCode \ref ErrorCode
##
c.arg.errorCode = errorCode
proc errorSystemSetResult*(c: ptr ErrorSystemConfig; res: Result) {.inline, cdecl.} =
## *
## @brief Sets the error code, using the input Result. Wrapper for \ref errorSystemSetCode.
## @param c ErrorSystemConfig struct.
## @param res The Result to set.
##
errorSystemSetCode(c, errorCodeCreateResult(res))
proc errorSystemSetLanguageCode*(c: ptr ErrorSystemConfig; languageCode: U64) {.
inline, cdecl.} =
## *
## @brief Sets the LanguageCode.
## @param c ErrorSystemConfig struct.
## @param LanguageCode LanguageCode, see set.h.
##
c.arg.languageCode = languageCode
proc errorSystemSetContext*(c: ptr ErrorSystemConfig; ctx: ptr ErrorContext) {.cdecl,
importc: "errorSystemSetContext".}
## *
## @brief Sets the ErrorContext.
## @note Only available on [4.0.0+], on older versions this will return without setting the context.
## @param c ErrorSystemConfig struct.
## @param ctx ErrorContext, NULL to clear it.
##
proc errorApplicationCreate*(c: ptr ErrorApplicationConfig; dialogMessage: cstring;
fullscreenMessage: cstring): Result {.cdecl,
importc: "errorApplicationCreate".}
## *
## @brief Creates an ErrorApplicationConfig struct.
## @param c ErrorApplicationConfig struct.
## @param dialog_message UTF-8 dialog message.
## @param fullscreen_message UTF-8 fullscreen message, displayed when the user clicks on "Details". Optional, can be NULL (which disables displaying Details).
## @note Sets the following fields: jumpFlag=1, {strings}, and uses ::ErrorType_Application. The rest are cleared.
## @note On pre-5.0.0 this will initialize languageCode by using: setInitialize(), setMakeLanguageCode(SetLanguage_ENUS, ...), and setExit(). This is needed since an empty languageCode wasn't supported until [5.0.0+] (which would also use SetLanguage_ENUS).
## @note With [10.0.0+] this must only be used when running under an Application, since otherwise the applet will trigger a fatalerr.
## @warning This applet creates an error report that is logged in the system. Proceed at your own risk!
##
proc errorApplicationShow*(c: ptr ErrorApplicationConfig): Result {.cdecl,
importc: "errorApplicationShow".}
## *
## @brief Launches the applet with the specified config.
## @param c ErrorApplicationConfig struct.
##
proc errorApplicationSetNumber*(c: ptr ErrorApplicationConfig; errorNumber: U32) {.
inline, cdecl.} =
## *
## @brief Sets the error code number.
## @param c ErrorApplicationConfig struct.
## @param errorNumber Error code number. Raw decimal error number which is displayed in the dialog.
##
c.arg.errorNumber = errorNumber
proc errorApplicationSetLanguageCode*(c: ptr ErrorApplicationConfig;
languageCode: U64) {.inline, cdecl.} =
## *
## @brief Sets the LanguageCode.
## @param c ErrorApplicationConfig struct.
## @param LanguageCode LanguageCode, see set.h.
##
c.arg.languageCode = languageCode

View file

@ -0,0 +1,172 @@
/**
* @file friends_la.h
* @brief Wrapper for using the MyPage (friends) LibraryApplet.
* @author yellows8
* @copyright libnx Authors
*/
#pragma once
#include "../types.h"
#include "../services/acc.h"
#include "../services/friends.h"
/// Arg type values used with \ref FriendsLaArg.
typedef enum {
FriendsLaArgType_ShowFriendList = 0, ///< ShowFriendList. Launches the applet with the "Friend List" menu initially selected.
FriendsLaArgType_ShowUserDetailInfo = 1, ///< ShowUserDetailInfo
FriendsLaArgType_StartSendingFriendRequest = 2, ///< StartSendingFriendRequest
FriendsLaArgType_ShowMethodsOfSendingFriendRequest = 3, ///< ShowMethodsOfSendingFriendRequest. Launches the applet with the "Add Friend" menu initially selected.
FriendsLaArgType_StartFacedFriendRequest = 4, ///< StartFacedFriendRequest. Launches the applet where the "Search for Local Users" menu is initially shown. Returning from this menu will exit the applet.
FriendsLaArgType_ShowReceivedFriendRequestList = 5, ///< ShowReceivedFriendRequestList. Launches the applet where the "Received Friend Requests" menu is initially shown. Returning from this menu will exit the applet.
FriendsLaArgType_ShowBlockedUserList = 6, ///< ShowBlockedUserList. Launches the applet where the "Blocked-User List" menu is initially shown. Returning from this menu will exit the applet.
FriendsLaArgType_ShowMyProfile = 7, ///< ShowMyProfile. Launches the applet with the "Profile" menu initially selected. ShowMyProfileForHomeMenu is identical to this except for playStartupSound=true.
FriendsLaArgType_StartFriendInvitation = 8, ///< [9.0.0+] StartFriendInvitation. Launches the applet for sending online-play invites to friends, where the friends are selected via the UI.
FriendsLaArgType_StartSendingFriendInvitation = 9, ///< [9.0.0+] StartSendingFriendInvitation.
FriendsLaArgType_ShowReceivedInvitationDetail = 10, ///< [9.0.0+] ShowReceivedInvitationDetail.
} FriendsLaArgType;
/// Header for the arg struct.
typedef struct {
u32 type; ///< \ref FriendsLaArgType
u32 pad; ///< Padding.
AccountUid uid; ///< \ref AccountUid
} FriendsLaArgHeader;
/// Common data for the arg struct, for the pre-9.0.0 types.
/// This is only set for ::FriendsLaArgType_ShowUserDetailInfo/::FriendsLaArgType_StartSendingFriendRequest, for everything else this is cleared.
typedef struct {
AccountNetworkServiceAccountId id; ///< \ref AccountNetworkServiceAccountId for the other account.
FriendsInAppScreenName first_inAppScreenName; ///< First InAppScreenName.
FriendsInAppScreenName second_inAppScreenName; ///< Second InAppScreenName.
} FriendsLaArgCommonData;
/// Arg struct pushed for the applet input storage, for pre-9.0.0.
typedef struct {
FriendsLaArgHeader hdr; ///< \ref FriendsLaArgHeader
FriendsLaArgCommonData data; ///< \ref FriendsLaArgCommonData
} FriendsLaArgV1;
/// Arg struct pushed for the applet input storage, for [9.0.0+].
typedef struct {
FriendsLaArgHeader hdr; ///< \ref FriendsLaArgHeader
union {
u8 raw[0x1090]; ///< Raw data.
FriendsLaArgCommonData common; ///< \ref FriendsLaArgCommonData
struct {
s32 id_count; ///< \ref AccountNetworkServiceAccountId count, must be 1-15.
u32 pad; ///< Padding.
u64 userdata_size; ///< User-data size, must be <=0x400.
u8 userdata[0x400]; ///< Arbitrary user-data, see above size.
FriendsFriendInvitationGameModeDescription desc; ///< \ref FriendsFriendInvitationGameModeDescription
} start_friend_invitation; ///< Data for ::FriendsLaArgType_StartFriendInvitation.
struct {
s32 id_count; ///< \ref AccountNetworkServiceAccountId count, must be 1-15.
u32 pad; ///< Padding.
AccountNetworkServiceAccountId id_list[16]; ///< \ref AccountNetworkServiceAccountId list, see above count.
u64 userdata_size; ///< User-data size, must be <=0x400.
u8 userdata[0x400]; ///< Arbitrary user-data, see above size.
FriendsFriendInvitationGameModeDescription desc; ///< \ref FriendsFriendInvitationGameModeDescription
} start_sending_friend_invitation; ///< Data for ::FriendsLaArgType_StartSendingFriendInvitation.
struct {
FriendsFriendInvitationId invitation_id; ///< \ref FriendsFriendInvitationId
FriendsFriendInvitationGroupId invitation_group_id; ///< \ref FriendsFriendInvitationGroupId
} show_received_invitation_detail; ///< Data for ::FriendsLaArgType_ShowReceivedInvitationDetail.
} data; ///< Data for each \ref FriendsLaArgType.
} FriendsLaArg;
/**
* @brief Launches the applet with ::FriendsLaArgType_ShowFriendList, the specified input, and playStartupSound=false.
* @param[in] uid \ref AccountUid
*/
Result friendsLaShowFriendList(AccountUid uid);
/**
* @brief Launches the applet with ::FriendsLaArgType_ShowUserDetailInfo, the specified input, and playStartupSound=false.
* @param[in] uid \ref AccountUid
* @param[in] id \ref AccountNetworkServiceAccountId for the user to show UserDetailInfo for.
* @param[in] first_inAppScreenName First \ref FriendsInAppScreenName.
* @param[in] second_inAppScreenName Second \ref FriendsInAppScreenName.
*/
Result friendsLaShowUserDetailInfo(AccountUid uid, AccountNetworkServiceAccountId id, const FriendsInAppScreenName *first_inAppScreenName, const FriendsInAppScreenName *second_inAppScreenName);
/**
* @brief Launches the applet with ::FriendsLaArgType_StartSendingFriendRequest, the specified input, and playStartupSound=false. On success, this will load the output Result from the output storage.
* @param[in] uid \ref AccountUid
* @param[in] id \ref AccountNetworkServiceAccountId to send the friend request to.
* @param[in] first_inAppScreenName First \ref FriendsInAppScreenName.
* @param[in] second_inAppScreenName Second \ref FriendsInAppScreenName.
*/
Result friendsLaStartSendingFriendRequest(AccountUid uid, AccountNetworkServiceAccountId id, const FriendsInAppScreenName *first_inAppScreenName, const FriendsInAppScreenName *second_inAppScreenName);
/**
* @brief Launches the applet with ::FriendsLaArgType_ShowMethodsOfSendingFriendRequest, the specified input, and playStartupSound=false.
* @param[in] uid \ref AccountUid
*/
Result friendsLaShowMethodsOfSendingFriendRequest(AccountUid uid);
/**
* @brief Launches the applet with ::FriendsLaArgType_StartFacedFriendRequest, the specified input, and playStartupSound=false.
* @param[in] uid \ref AccountUid
*/
Result friendsLaStartFacedFriendRequest(AccountUid uid);
/**
* @brief Launches the applet with ::FriendsLaArgType_ShowReceivedFriendRequestList, the specified input, and playStartupSound=false.
* @param[in] uid \ref AccountUid
*/
Result friendsLaShowReceivedFriendRequestList(AccountUid uid);
/**
* @brief Launches the applet with ::FriendsLaArgType_ShowBlockedUserList, the specified input, and playStartupSound=false.
* @param[in] uid \ref AccountUid
*/
Result friendsLaShowBlockedUserList(AccountUid uid);
/**
* @brief Launches the applet with ::FriendsLaArgType_ShowMyProfile, the specified input, and playStartupSound=false.
* @param[in] uid \ref AccountUid
*/
Result friendsLaShowMyProfile(AccountUid uid);
/**
* @brief Same as \ref friendsLaShowMyProfile except with playStartupSound=true.
* @param[in] uid \ref AccountUid
*/
Result friendsLaShowMyProfileForHomeMenu(AccountUid uid);
/**
* @brief Launches the applet with ::FriendsLaArgType_StartFriendInvitation, the specified input, and playStartupSound=false. On success, this will load the output Result from the output storage.
* @note Only available on [9.0.0+].
* @param[in] uid \ref AccountUid
* @param[in] id_count \ref AccountNetworkServiceAccountId count, must be 1-15. Number of friends to invite.
* @param[in] desc \ref FriendsFriendInvitationGameModeDescription
* @param[in] userdata Arbitrary user-data. Can be NULL.
* @param[in] userdata_size User-data size, must be <=0x400. Can be 0 if userdata is NULL.
*/
Result friendsLaStartFriendInvitation(AccountUid uid, s32 id_count, const FriendsFriendInvitationGameModeDescription *desc, const void* userdata, u64 userdata_size);
/**
* @brief Launches the applet with ::FriendsLaArgType_StartSendingFriendInvitation, the specified input, and playStartupSound=false. On success, this will load the output Result from the output storage.
* @note Only available on [9.0.0+].
* @param[in] uid \ref AccountUid
* @param[in] id_list \ref AccountNetworkServiceAccountId list.
* @param[in] id_count Size of the id_list array in entries, must be 1-15. Number of friends to invite.
* @param[in] desc \ref FriendsFriendInvitationGameModeDescription
* @param[in] userdata Arbitrary user-data. Can be NULL.
* @param[in] userdata_size User-data size, must be <=0x400. Can be 0 if userdata is NULL.
*/
Result friendsLaStartSendingFriendInvitation(AccountUid uid, const AccountNetworkServiceAccountId *id_list, s32 id_count, const FriendsFriendInvitationGameModeDescription *desc, const void* userdata, u64 userdata_size);
/**
* @brief Launches the applet with ::FriendsLaArgType_ShowReceivedInvitationDetail, the specified input, and playStartupSound=false.
* @note Only available on [9.0.0+].
* @param[in] uid \ref AccountUid
* @param[in] invitation_id \ref FriendsFriendInvitationId
* @param[in] invitation_group_id \ref FriendsFriendInvitationGroupId
*/
Result friendsLaShowReceivedInvitationDetail(AccountUid uid, FriendsFriendInvitationId invitation_id, FriendsFriendInvitationGroupId invitation_group_id);

View file

@ -0,0 +1,202 @@
## *
## @file friends_la.h
## @brief Wrapper for using the MyPage (friends) LibraryApplet.
## @author yellows8
## @copyright libnx Authors
##
import
../types, ../services/acc, ../services/friends
## / Arg type values used with \ref FriendsLaArg.
type
FriendsLaArgType* = enum
FriendsLaArgType_ShowFriendList = 0, ## /< ShowFriendList. Launches the applet with the "Friend List" menu initially selected.
FriendsLaArgType_ShowUserDetailInfo = 1, ## /< ShowUserDetailInfo
FriendsLaArgType_StartSendingFriendRequest = 2, ## /< StartSendingFriendRequest
FriendsLaArgType_ShowMethodsOfSendingFriendRequest = 3, ## /< ShowMethodsOfSendingFriendRequest. Launches the applet with the "Add Friend" menu initially selected.
FriendsLaArgType_StartFacedFriendRequest = 4, ## /< StartFacedFriendRequest. Launches the applet where the "Search for Local Users" menu is initially shown. Returning from this menu will exit the applet.
FriendsLaArgType_ShowReceivedFriendRequestList = 5, ## /< ShowReceivedFriendRequestList. Launches the applet where the "Received Friend Requests" menu is initially shown. Returning from this menu will exit the applet.
FriendsLaArgType_ShowBlockedUserList = 6, ## /< ShowBlockedUserList. Launches the applet where the "Blocked-User List" menu is initially shown. Returning from this menu will exit the applet.
FriendsLaArgType_ShowMyProfile = 7, ## /< ShowMyProfile. Launches the applet with the "Profile" menu initially selected. ShowMyProfileForHomeMenu is identical to this except for playStartupSound=true.
FriendsLaArgType_StartFriendInvitation = 8, ## /< [9.0.0+] StartFriendInvitation. Launches the applet for sending online-play invites to friends, where the friends are selected via the UI.
FriendsLaArgType_StartSendingFriendInvitation = 9, ## /< [9.0.0+] StartSendingFriendInvitation.
FriendsLaArgType_ShowReceivedInvitationDetail = 10 ## /< [9.0.0+] ShowReceivedInvitationDetail.
## / Header for the arg struct.
type
FriendsLaArgHeader* {.bycopy.} = object
`type`*: U32 ## /< \ref FriendsLaArgType
pad*: U32 ## /< Padding.
uid*: AccountUid ## /< \ref AccountUid
## / Common data for the arg struct, for the pre-9.0.0 types.
## / This is only set for
## ::FriendsLaArgType_ShowUserDetailInfo/::FriendsLaArgType_StartSendingFriendRequest, for everything else this is cleared.
type
FriendsLaArgCommonData* {.bycopy.} = object
id*: AccountNetworkServiceAccountId ## /< \ref AccountNetworkServiceAccountId for the other account.
first_inAppScreenName*: FriendsInAppScreenName ## /< First InAppScreenName.
second_inAppScreenName*: FriendsInAppScreenName ## /< Second InAppScreenName.
## / Arg struct pushed for the applet input storage, for pre-9.0.0.
type
FriendsLaArgV1* {.bycopy.} = object
hdr*: FriendsLaArgHeader ## /< \ref FriendsLaArgHeader
data*: FriendsLaArgCommonData ## /< \ref FriendsLaArgCommonData
## / Arg struct pushed for the applet input storage, for [9.0.0+].
type
INNER_C_STRUCT_friends_la_79* {.bycopy.} = object
id_count*: S32 ## /< \ref AccountNetworkServiceAccountId count, must be 1-15.
pad*: U32 ## /< Padding.
userdata_size*: U64 ## /< User-data size, must be <=0x400.
userdata*: array[0x400, U8] ## /< Arbitrary user-data, see above size.
desc*: FriendsFriendInvitationGameModeDescription ## /< \ref FriendsFriendInvitationGameModeDescription
INNER_C_STRUCT_friends_la_80* {.bycopy.} = object
id_count*: S32 ## /< \ref AccountNetworkServiceAccountId count, must be 1-15.
pad*: U32 ## /< Padding.
id_list*: array[16, AccountNetworkServiceAccountId] ## /< \ref AccountNetworkServiceAccountId list, see above count.
userdata_size*: U64 ## /< User-data size, must be <=0x400.
userdata*: array[0x400, U8] ## /< Arbitrary user-data, see above size.
desc*: FriendsFriendInvitationGameModeDescription ## /< \ref FriendsFriendInvitationGameModeDescription
INNER_C_STRUCT_friends_la_81* {.bycopy.} = object
invitation_id*: FriendsFriendInvitationId ## /< \ref FriendsFriendInvitationId
invitation_group_id*: FriendsFriendInvitationGroupId ## /< \ref FriendsFriendInvitationGroupId
INNER_C_UNION_friends_la_79* {.bycopy, union.} = object
raw*: array[0x1090, U8] ## /< Raw data.
common*: FriendsLaArgCommonData ## /< \ref FriendsLaArgCommonData
start_friend_invitation*: INNER_C_STRUCT_friends_la_79 ## /< Data for ::FriendsLaArgType_StartFriendInvitation.
start_sending_friend_invitation*: INNER_C_STRUCT_friends_la_80 ## /< Data for ::FriendsLaArgType_StartSendingFriendInvitation.
show_received_invitation_detail*: INNER_C_STRUCT_friends_la_81 ## /< Data for ::FriendsLaArgType_ShowReceivedInvitationDetail.
FriendsLaArg* {.bycopy.} = object
hdr*: FriendsLaArgHeader ## /< \ref FriendsLaArgHeader
data*: INNER_C_UNION_friends_la_79 ## /< Data for each \ref FriendsLaArgType.
proc friendsLaShowFriendList*(uid: AccountUid): Result {.cdecl,
importc: "friendsLaShowFriendList".}
## *
## @brief Launches the applet with ::FriendsLaArgType_ShowFriendList, the specified input, and playStartupSound=false.
## @param[in] uid \ref AccountUid
##
proc friendsLaShowUserDetailInfo*(uid: AccountUid;
id: AccountNetworkServiceAccountId;
first_inAppScreenName: ptr FriendsInAppScreenName; second_inAppScreenName: ptr FriendsInAppScreenName): Result {.
cdecl, importc: "friendsLaShowUserDetailInfo".}
## *
## @brief Launches the applet with ::FriendsLaArgType_ShowUserDetailInfo, the specified input, and playStartupSound=false.
## @param[in] uid \ref AccountUid
## @param[in] id \ref AccountNetworkServiceAccountId for the user to show UserDetailInfo for.
## @param[in] first_inAppScreenName First \ref FriendsInAppScreenName.
## @param[in] second_inAppScreenName Second \ref FriendsInAppScreenName.
##
proc friendsLaStartSendingFriendRequest*(uid: AccountUid;
id: AccountNetworkServiceAccountId;
first_inAppScreenName: ptr FriendsInAppScreenName; second_inAppScreenName: ptr FriendsInAppScreenName): Result {.
cdecl, importc: "friendsLaStartSendingFriendRequest".}
## *
## @brief Launches the applet with ::FriendsLaArgType_StartSendingFriendRequest, the specified input, and playStartupSound=false. On success, this will load the output Result from the output storage.
## @param[in] uid \ref AccountUid
## @param[in] id \ref AccountNetworkServiceAccountId to send the friend request to.
## @param[in] first_inAppScreenName First \ref FriendsInAppScreenName.
## @param[in] second_inAppScreenName Second \ref FriendsInAppScreenName.
##
proc friendsLaShowMethodsOfSendingFriendRequest*(uid: AccountUid): Result {.cdecl,
importc: "friendsLaShowMethodsOfSendingFriendRequest".}
## *
## @brief Launches the applet with ::FriendsLaArgType_ShowMethodsOfSendingFriendRequest, the specified input, and playStartupSound=false.
## @param[in] uid \ref AccountUid
##
proc friendsLaStartFacedFriendRequest*(uid: AccountUid): Result {.cdecl,
importc: "friendsLaStartFacedFriendRequest".}
## *
## @brief Launches the applet with ::FriendsLaArgType_StartFacedFriendRequest, the specified input, and playStartupSound=false.
## @param[in] uid \ref AccountUid
##
proc friendsLaShowReceivedFriendRequestList*(uid: AccountUid): Result {.cdecl,
importc: "friendsLaShowReceivedFriendRequestList".}
## *
## @brief Launches the applet with ::FriendsLaArgType_ShowReceivedFriendRequestList, the specified input, and playStartupSound=false.
## @param[in] uid \ref AccountUid
##
proc friendsLaShowBlockedUserList*(uid: AccountUid): Result {.cdecl,
importc: "friendsLaShowBlockedUserList".}
## *
## @brief Launches the applet with ::FriendsLaArgType_ShowBlockedUserList, the specified input, and playStartupSound=false.
## @param[in] uid \ref AccountUid
##
proc friendsLaShowMyProfile*(uid: AccountUid): Result {.cdecl,
importc: "friendsLaShowMyProfile".}
## *
## @brief Launches the applet with ::FriendsLaArgType_ShowMyProfile, the specified input, and playStartupSound=false.
## @param[in] uid \ref AccountUid
##
proc friendsLaShowMyProfileForHomeMenu*(uid: AccountUid): Result {.cdecl,
importc: "friendsLaShowMyProfileForHomeMenu".}
## *
## @brief Same as \ref friendsLaShowMyProfile except with playStartupSound=true.
## @param[in] uid \ref AccountUid
##
proc friendsLaStartFriendInvitation*(uid: AccountUid; id_count: S32; desc: ptr FriendsFriendInvitationGameModeDescription;
userdata: pointer; userdata_size: U64): Result {.
cdecl, importc: "friendsLaStartFriendInvitation".}
## *
## @brief Launches the applet with ::FriendsLaArgType_StartFriendInvitation, the specified input, and playStartupSound=false. On success, this will load the output Result from the output storage.
## @note Only available on [9.0.0+].
## @param[in] uid \ref AccountUid
## @param[in] id_count \ref AccountNetworkServiceAccountId count, must be 1-15. Number of friends to invite.
## @param[in] desc \ref FriendsFriendInvitationGameModeDescription
## @param[in] userdata Arbitrary user-data. Can be NULL.
## @param[in] userdata_size User-data size, must be <=0x400. Can be 0 if userdata is NULL.
##
proc friendsLaStartSendingFriendInvitation*(uid: AccountUid;
id_list: ptr AccountNetworkServiceAccountId; id_count: S32;
desc: ptr FriendsFriendInvitationGameModeDescription; userdata: pointer;
userdata_size: U64): Result {.cdecl,
importc: "friendsLaStartSendingFriendInvitation".}
## *
## @brief Launches the applet with ::FriendsLaArgType_StartSendingFriendInvitation, the specified input, and playStartupSound=false. On success, this will load the output Result from the output storage.
## @note Only available on [9.0.0+].
## @param[in] uid \ref AccountUid
## @param[in] id_list \ref AccountNetworkServiceAccountId list.
## @param[in] id_count Size of the id_list array in entries, must be 1-15. Number of friends to invite.
## @param[in] desc \ref FriendsFriendInvitationGameModeDescription
## @param[in] userdata Arbitrary user-data. Can be NULL.
## @param[in] userdata_size User-data size, must be <=0x400. Can be 0 if userdata is NULL.
##
proc friendsLaShowReceivedInvitationDetail*(uid: AccountUid;
invitation_id: FriendsFriendInvitationId;
invitation_group_id: FriendsFriendInvitationGroupId): Result {.cdecl,
importc: "friendsLaShowReceivedInvitationDetail".}
## *
## @brief Launches the applet with ::FriendsLaArgType_ShowReceivedInvitationDetail, the specified input, and playStartupSound=false.
## @note Only available on [9.0.0+].
## @param[in] uid \ref AccountUid
## @param[in] invitation_id \ref FriendsFriendInvitationId
## @param[in] invitation_group_id \ref FriendsFriendInvitationGroupId
##

View file

@ -0,0 +1,175 @@
/**
* @file hid_la.h
* @brief Wrapper for using the controller LibraryApplet.
* @author yellows8
* @copyright libnx Authors
*/
#pragma once
#include "../types.h"
#include "../services/hid.h"
/// Mode values for HidLaControllerSupportArgPrivate::mode.
typedef enum {
HidLaControllerSupportMode_ShowControllerSupport = 0, ///< ShowControllerSupport
HidLaControllerSupportMode_ShowControllerStrapGuide = 1, ///< [3.0.0+] ShowControllerStrapGuide
HidLaControllerSupportMode_ShowControllerFirmwareUpdate = 2, ///< [3.0.0+] ShowControllerFirmwareUpdate
HidLaControllerSupportMode_ShowControllerKeyRemappingForSystem = 4, ///< [11.0.0+] ShowControllerKeyRemappingForSystem
} HidLaControllerSupportMode;
/// ControllerSupportCaller
typedef enum {
HidLaControllerSupportCaller_Application = 0, ///< Application, this is the default.
HidLaControllerSupportCaller_System = 1, ///< System. Skips the firmware-update confirmation dialog. This has the same affect as using the controller-update option from qlaunch System Settings.
} HidLaControllerSupportCaller;
/// ControllerSupportArgPrivate
typedef struct {
u32 private_size; ///< Size of this ControllerSupportArgPrivate struct.
u32 arg_size; ///< Size of the storage following this one (\ref HidLaControllerSupportArg or \ref HidLaControllerFirmwareUpdateArg).
u8 flag0; ///< Flag0
u8 flag1; ///< Flag1
u8 mode; ///< \ref HidLaControllerSupportMode
u8 controller_support_caller; ///< \ref HidLaControllerSupportCaller. Always zero except with \ref hidLaShowControllerFirmwareUpdateForSystem, which sets this to the input param.
u32 npad_style_set; ///< Output from \ref hidGetSupportedNpadStyleSet. With ShowControllerSupportForSystem on pre-3.0.0 this is value 0.
u32 npad_joy_hold_type; ///< Output from \ref hidGetNpadJoyHoldType. With ShowControllerSupportForSystem on pre-3.0.0 this is value 1.
} HidLaControllerSupportArgPrivate;
/// Common header used by HidLaControllerSupportArg*.
/// max_supported_players is 4 on pre-8.0.0, 8 on [8.0.0+]. player_count_min and player_count_max are overriden with value 4 when larger than value 4, during conversion handling for \ref HidLaControllerSupportArg on pre-8.0.0.
typedef struct {
s8 player_count_min; ///< playerCountMin. Must be >=0 and <=max_supported_players.
s8 player_count_max; ///< playerCountMax. Must be >=1 and <=max_supported_players.
u8 enable_take_over_connection; ///< enableTakeOverConnection, non-zero to enable. Disconnects the controllers when not enabled.
u8 enable_left_justify; ///< enableLeftJustify, non-zero to enable.
u8 enable_permit_joy_dual; ///< enablePermitJoyDual, non-zero to enable.
u8 enable_single_mode; ///< enableSingleMode, non-zero to enable. Enables using a single player in handheld-mode, dual-mode, or single-mode (player_count_* are overridden). Using handheld-mode is not allowed if this is not enabled.
u8 enable_identification_color; ///< When non-zero enables using identification_color.
} HidLaControllerSupportArgHeader;
/// Identification color used by HidLaControllerSupportArg*. When HidLaControllerSupportArgHeader::enable_identification_color is set this controls the color of the UI player box outline.
typedef struct {
u8 r; ///< Red color component.
u8 g; ///< Green color component.
u8 b; ///< Blue color component.
u8 a; ///< Alpha color component.
} HidLaControllerSupportArgColor;
/// ControllerSupportArg for [1.0.0+].
typedef struct {
HidLaControllerSupportArgHeader hdr; ///< \ref HidLaControllerSupportArgHeader
HidLaControllerSupportArgColor identification_color[4]; ///< \ref HidLaControllerSupportArgColor for each player, see HidLaControllerSupportArgHeader::enable_identification_color.
u8 enable_explain_text; ///< Enables using the ExplainText data when non-zero.
char explain_text[4][0x81]; ///< ExplainText for each player, NUL-terminated UTF-8 strings.
} HidLaControllerSupportArgV3;
/// ControllerSupportArg for [8.0.0+], converted to \ref HidLaControllerSupportArgV3 on pre-8.0.0.
typedef struct {
HidLaControllerSupportArgHeader hdr; ///< \ref HidLaControllerSupportArgHeader
HidLaControllerSupportArgColor identification_color[8]; ///< \ref HidLaControllerSupportArgColor for each player, see HidLaControllerSupportArgHeader::enable_identification_color.
u8 enable_explain_text; ///< Enables using the ExplainText data when non-zero.
char explain_text[8][0x81]; ///< ExplainText for each player, NUL-terminated UTF-8 strings.
} HidLaControllerSupportArg;
/// ControllerFirmwareUpdateArg
typedef struct {
u8 enable_force_update; ///< enableForceUpdate, non-zero to enable. Default is 0. Forces a firmware update when enabled, without an UI option to skip it.
u8 pad[3]; ///< Padding.
} HidLaControllerFirmwareUpdateArg;
/// ControllerKeyRemappingArg
typedef struct {
u64 unk_x0; ///< Unknown
u32 unk_x8; ///< Unknown
u8 pad[0x4]; ///< Padding
} HidLaControllerKeyRemappingArg;
/// ControllerSupportResultInfo. First 8-bytes from the applet output storage.
typedef struct {
s8 player_count; ///< playerCount.
u8 pad[3]; ///< Padding.
u32 selected_id; ///< \ref HidNpadIdType, selectedId.
} HidLaControllerSupportResultInfo;
/// Struct for the applet output storage.
typedef struct {
HidLaControllerSupportResultInfo info; ///< \ref HidLaControllerSupportResultInfo
u32 res; ///< Output res value.
} HidLaControllerSupportResultInfoInternal;
/**
* @brief Initializes a \ref HidLaControllerSupportArg with the defaults.
* @note This clears the arg, then does: HidLaControllerSupportArgHeader::player_count_min = 0, HidLaControllerSupportArgHeader::player_count_max = 4, HidLaControllerSupportArgHeader::enable_take_over_connection = 1, HidLaControllerSupportArgHeader::enable_left_justify = 1, and HidLaControllerSupportArgHeader::enable_permit_joy_dual = 1.
* @note If preferred, you can also memset \ref HidLaControllerSupportArg manually and initialize it yourself.
* @param[out] arg \ref HidLaControllerSupportArg
*/
void hidLaCreateControllerSupportArg(HidLaControllerSupportArg *arg);
/**
* @brief Initializes a \ref HidLaControllerFirmwareUpdateArg with the defaults.
* @note This just uses memset() with the arg.
* @param[out] arg \ref HidLaControllerFirmwareUpdateArg
*/
void hidLaCreateControllerFirmwareUpdateArg(HidLaControllerFirmwareUpdateArg *arg);
/**
* @brief Initializes a \ref HidLaControllerKeyRemappingArg with the defaults.
* @note This just uses memset() with the arg.
* @param[out] arg \ref HidLaControllerKeyRemappingArg
*/
void hidLaCreateControllerKeyRemappingArg(HidLaControllerKeyRemappingArg *arg);
/**
* @brief Sets the ExplainText for the specified player and \ref HidLaControllerSupportArg.
* @note This string is displayed in the UI box for the player.
* @note HidLaControllerSupportArg::enable_explain_text must be set, otherwise this ExplainText is ignored.
* @param arg \ref HidLaControllerSupportArg
* @param[in] str Input ExplainText UTF-8 string, max length is 0x80 excluding NUL-terminator.
+ @oaram[in] id Player controller, must be <8.
*/
Result hidLaSetExplainText(HidLaControllerSupportArg *arg, const char *str, HidNpadIdType id);
/**
* @brief Launches the applet for ControllerSupport.
* @note This seems to only display the applet UI when doing so is actually needed? This doesn't apply to \ref hidLaShowControllerSupportForSystem.
* @param[out] result_info \ref HidLaControllerSupportResultInfo. Optional, can be NULL.
* @param[in] arg \ref HidLaControllerSupportArg
*/
Result hidLaShowControllerSupport(HidLaControllerSupportResultInfo *result_info, const HidLaControllerSupportArg *arg);
/**
* @brief Launches the applet for ControllerStrapGuide.
* @note Only available on [3.0.0+].
*/
Result hidLaShowControllerStrapGuide(void);
/**
* @brief Launches the applet for ControllerFirmwareUpdate.
* @note Only available on [3.0.0+].
* @param[in] arg \ref HidLaControllerFirmwareUpdateArg
*/
Result hidLaShowControllerFirmwareUpdate(const HidLaControllerFirmwareUpdateArg *arg);
/**
* @brief This is the system version of \ref hidLaShowControllerSupport.
* @param[out] result_info \ref HidLaControllerSupportResultInfo. Optional, can be NULL.
* @param[in] arg \ref HidLaControllerSupportArg
* @param[in] flag Input flag. When true, the applet displays the menu as if launched by qlaunch.
*/
Result hidLaShowControllerSupportForSystem(HidLaControllerSupportResultInfo *result_info, const HidLaControllerSupportArg *arg, bool flag);
/**
* @brief This is the system version of \ref hidLaShowControllerFirmwareUpdate.
* @note Only available on [3.0.0+].
* @param[in] arg \ref HidLaControllerFirmwareUpdateArg
* @param[in] caller \ref HidLaControllerSupportCaller
*/
Result hidLaShowControllerFirmwareUpdateForSystem(const HidLaControllerFirmwareUpdateArg *arg, HidLaControllerSupportCaller caller);
/**
* @brief Launches the applet for ControllerKeyRemappingForSystem.
* @note Only available on [11.0.0+].
* @param[in] arg \ref HidLaControllerKeyRemappingArg
* @param[in] caller \ref HidLaControllerSupportCaller
*/
Result hidLaShowControllerKeyRemappingForSystem(const HidLaControllerKeyRemappingArg *arg, HidLaControllerSupportCaller caller);

View file

@ -0,0 +1,214 @@
## *
## @file hid_la.h
## @brief Wrapper for using the controller LibraryApplet.
## @author yellowS8
## @copyright libnx Authors
##
import
../types, ../services/hid
## / Mode values for HidLaControllerSupportArgPrivate::mode.
type
HidLaControllerSupportMode* = enum
HidLaControllerSupportMode_ShowControllerSupport = 0, ## /< ShowControllerSupport
HidLaControllerSupportMode_ShowControllerStrapGuide = 1, ## /< [3.0.0+] ShowControllerStrapGuide
HidLaControllerSupportMode_ShowControllerFirmwareUpdate = 2, ## /< [3.0.0+] ShowControllerFirmwareUpdate
HidLaControllerSupportMode_ShowControllerKeyRemappingForSystem = 4 ## /< [11.0.0+] ShowControllerKeyRemappingForSystem
## / ControllerSupportCaller
type
HidLaControllerSupportCaller* = enum
HidLaControllerSupportCaller_Application = 0, ## /< Application, this is the default.
HidLaControllerSupportCaller_System = 1 ## /< System. Skips the firmware-update confirmation dialog. This has the same affect as using the controller-update option from qlaunch System Settings.
## / ControllerSupportArgPrivate
type
HidLaControllerSupportArgPrivate* {.bycopy.} = object
private_size*: U32 ## /< Size of this ControllerSupportArgPrivate struct.
arg_size*: U32 ## /< Size of the storage following this one (\ref HidLaControllerSupportArg or \ref HidLaControllerFirmwareUpdateArg).
flag0*: U8 ## /< Flag0
flag1*: U8 ## /< Flag1
mode*: U8 ## /< \ref HidLaControllerSupportMode
controller_support_caller*: U8 ## /< \ref HidLaControllerSupportCaller. Always zero except with \ref hidLaShowControllerFirmwareUpdateForSystem, which sets this to the input param.
npad_style_set*: U32 ## /< Output from \ref hidGetSupportedNpadStyleSet. With ShowControllerSupportForSystem on pre-3.0.0 this is value 0.
npad_joy_hold_type*: U32 ## /< Output from \ref hidGetNpadJoyHoldType. With ShowControllerSupportForSystem on pre-3.0.0 this is value 1.
## / Common header used by HidLaControllerSupportArg*.
## / max_supported_players is 4 on pre-8.0.0, 8 on [8.0.0+]. player_count_min and player_count_max are overriden with value 4 when larger than value 4, during conversion handling for \ref HidLaControllerSupportArg on pre-8.0.0.
type
HidLaControllerSupportArgHeader* {.bycopy.} = object
player_count_min*: S8 ## /< playerCountMin. Must be >=0 and <=max_supported_players.
player_count_max*: S8 ## /< playerCountMax. Must be >=1 and <=max_supported_players.
enable_take_over_connection*: U8 ## /< enableTakeOverConnection, non-zero to enable. Disconnects the controllers when not enabled.
enable_left_justify*: U8 ## /< enableLeftJustify, non-zero to enable.
enable_permit_joy_dual*: U8 ## /< enablePermitJoyDual, non-zero to enable.
enable_single_mode*: U8 ## /< enableSingleMode, non-zero to enable. Enables using a single player in handheld-mode, dual-mode, or single-mode (player_count_* are overridden). Using handheld-mode is not allowed if this is not enabled.
enable_identification_color*: U8 ## /< When non-zero enables using identification_color.
## / Identification color used by HidLaControllerSupportArg*. When HidLaControllerSupportArgHeader::enable_identification_color is set this controls the color of the UI player box outline.
type
HidLaControllerSupportArgColor* {.bycopy.} = object
r*: U8 ## /< Red color component.
g*: U8 ## /< Green color component.
b*: U8 ## /< Blue color component.
a*: U8 ## /< Alpha color component.
## / ControllerSupportArg for [1.0.0+].
type
HidLaControllerSupportArgV3* {.bycopy.} = object
hdr*: HidLaControllerSupportArgHeader ## /< \ref HidLaControllerSupportArgHeader
identification_color*: array[4, HidLaControllerSupportArgColor] ## /< \ref HidLaControllerSupportArgColor for each player, see HidLaControllerSupportArgHeader::enable_identification_color.
enable_explain_text*: U8 ## /< Enables using the ExplainText data when non-zero.
explain_text*: array[4, array[0x81, char]] ## /< ExplainText for each player, NUL-terminated UTF-8 strings.
## / ControllerSupportArg for [8.0.0+], converted to \ref HidLaControllerSupportArgV3 on pre-8.0.0.
type
HidLaControllerSupportArg* {.bycopy.} = object
hdr*: HidLaControllerSupportArgHeader ## /< \ref HidLaControllerSupportArgHeader
identification_color*: array[8, HidLaControllerSupportArgColor] ## /< \ref HidLaControllerSupportArgColor for each player, see HidLaControllerSupportArgHeader::enable_identification_color.
enable_explain_text*: U8 ## /< Enables using the ExplainText data when non-zero.
explain_text*: array[8, array[0x81, char]] ## /< ExplainText for each player, NUL-terminated UTF-8 strings.
## / ControllerFirmwareUpdateArg
type
HidLaControllerFirmwareUpdateArg* {.bycopy.} = object
enable_force_update*: U8 ## /< enableForceUpdate, non-zero to enable. Default is 0. Forces a firmware update when enabled, without an UI option to skip it.
pad*: array[3, U8] ## /< Padding.
## / ControllerKeyRemappingArg
type
HidLaControllerKeyRemappingArg* {.bycopy.} = object
unk_x0*: U64 ## /< Unknown
unk_x8*: U32 ## /< Unknown
pad*: array[0x4, U8] ## /< Padding
## / ControllerSupportResultInfo. First 8-bytes from the applet output storage.
type
HidLaControllerSupportResultInfo* {.bycopy.} = object
player_count*: S8 ## /< playerCount.
pad*: array[3, U8] ## /< Padding.
selected_id*: U32 ## /< \ref HidNpadIdType, selectedId.
## / Struct for the applet output storage.
type
HidLaControllerSupportResultInfoInternal* {.bycopy.} = object
info*: HidLaControllerSupportResultInfo ## /< \ref HidLaControllerSupportResultInfo
res*: U32 ## /< Output res value.
proc hidLaCreateControllerSupportArg*(arg: ptr HidLaControllerSupportArg) {.cdecl,
importc: "hidLaCreateControllerSupportArg".}
## *
## @brief Initializes a \ref HidLaControllerSupportArg with the defaults.
## @note This clears the arg, then does: HidLaControllerSupportArgHeader::player_count_min = 0, HidLaControllerSupportArgHeader::player_count_max = 4, HidLaControllerSupportArgHeader::enable_take_over_connection = 1, HidLaControllerSupportArgHeader::enable_left_justify = 1, and HidLaControllerSupportArgHeader::enable_permit_joy_dual = 1.
## @note If preferred, you can also memset \ref HidLaControllerSupportArg manually and initialize it yourself.
## @param[out] arg \ref HidLaControllerSupportArg
##
proc hidLaCreateControllerFirmwareUpdateArg*(
arg: ptr HidLaControllerFirmwareUpdateArg) {.cdecl,
importc: "hidLaCreateControllerFirmwareUpdateArg".}
## *
## @brief Initializes a \ref HidLaControllerFirmwareUpdateArg with the defaults.
## @note This just uses memset() with the arg.
## @param[out] arg \ref HidLaControllerFirmwareUpdateArg
##
proc hidLaCreateControllerKeyRemappingArg*(
arg: ptr HidLaControllerKeyRemappingArg) {.cdecl,
importc: "hidLaCreateControllerKeyRemappingArg".}
## *
## @brief Initializes a \ref HidLaControllerKeyRemappingArg with the defaults.
## @note This just uses memset() with the arg.
## @param[out] arg \ref HidLaControllerKeyRemappingArg
##
proc hidLaSetExplainText*(arg: ptr HidLaControllerSupportArg; str: cstring;
id: HidNpadIdType): Result {.cdecl,
importc: "hidLaSetExplainText".}
## *
## @brief Sets the ExplainText for the specified player and \ref HidLaControllerSupportArg.
## @note This string is displayed in the UI box for the player.
## @note HidLaControllerSupportArg::enable_explain_text must be set, otherwise this ExplainText is ignored.
## @param arg \ref HidLaControllerSupportArg
## @param[in] str Input ExplainText UTF-8 string, max length is 0x80 excluding NUL-terminator.
## + @oaram[in] id Player controller, must be <8.
##
proc hidLaShowControllerSupport*(result_info: ptr HidLaControllerSupportResultInfo;
arg: ptr HidLaControllerSupportArg): Result {.cdecl,
importc: "hidLaShowControllerSupport".}
## *
## @brief Launches the applet for ControllerSupport.
## @note This seems to only display the applet UI when doing so is actually needed? This doesn't apply to \ref hidLaShowControllerSupportForSystem.
## @param[out] result_info \ref HidLaControllerSupportResultInfo. Optional, can be NULL.
## @param[in] arg \ref HidLaControllerSupportArg
##
proc hidLaShowControllerStrapGuide*(): Result {.cdecl,
importc: "hidLaShowControllerStrapGuide".}
## *
## @brief Launches the applet for ControllerStrapGuide.
## @note Only available on [3.0.0+].
##
proc hidLaShowControllerFirmwareUpdate*(arg: ptr HidLaControllerFirmwareUpdateArg): Result {.
cdecl, importc: "hidLaShowControllerFirmwareUpdate".}
## *
## @brief Launches the applet for ControllerFirmwareUpdate.
## @note Only available on [3.0.0+].
## @param[in] arg \ref HidLaControllerFirmwareUpdateArg
##
proc hidLaShowControllerSupportForSystem*(
result_info: ptr HidLaControllerSupportResultInfo;
arg: ptr HidLaControllerSupportArg; flag: bool): Result {.cdecl,
importc: "hidLaShowControllerSupportForSystem".}
## *
## @brief This is the system version of \ref hidLaShowControllerSupport.
## @param[out] result_info \ref HidLaControllerSupportResultInfo. Optional, can be NULL.
## @param[in] arg \ref HidLaControllerSupportArg
## @param[in] flag Input flag. When true, the applet displays the menu as if launched by qlaunch.
##
proc hidLaShowControllerFirmwareUpdateForSystem*(
arg: ptr HidLaControllerFirmwareUpdateArg; caller: HidLaControllerSupportCaller): Result {.
cdecl, importc: "hidLaShowControllerFirmwareUpdateForSystem".}
## *
## @brief This is the system version of \ref hidLaShowControllerFirmwareUpdate.
## @note Only available on [3.0.0+].
## @param[in] arg \ref HidLaControllerFirmwareUpdateArg
## @param[in] caller \ref HidLaControllerSupportCaller
##
proc hidLaShowControllerKeyRemappingForSystem*(
arg: ptr HidLaControllerKeyRemappingArg; caller: HidLaControllerSupportCaller): Result {.
cdecl, importc: "hidLaShowControllerKeyRemappingForSystem".}
## *
## @brief Launches the applet for ControllerKeyRemappingForSystem.
## @note Only available on [11.0.0+].
## @param[in] arg \ref HidLaControllerKeyRemappingArg
## @param[in] caller \ref HidLaControllerSupportCaller
##

View file

@ -0,0 +1,136 @@
/**
* @file libapplet.h
* @brief LibraryApplet wrapper.
* @author yellows8
* @copyright libnx Authors
*/
#pragma once
#include "../types.h"
#include "../services/applet.h"
#include "../services/acc.h"
/// CommonArguments
typedef struct {
u32 CommonArgs_version; ///< \ref libappletArgsCreate sets this to 1, and \ref libappletArgsPop requires value 1. v0 is not supported.
u32 CommonArgs_size; ///< Size of this struct.
u32 LaVersion; ///< LibraryApplet API version.
s32 ExpectedThemeColor; ///< Set to the output from \ref appletGetThemeColorType by \ref libappletArgsCreate.
u8 PlayStartupSound; ///< bool flag, default is false.
u8 pad[7]; ///< Padding.
u64 tick; ///< System tick. Set to the output from \ref armGetSystemTick during \ref libappletArgsPush.
} LibAppletArgs;
/**
* @brief Creates a LibAppletArgs struct.
* @param a LibAppletArgs struct.
* @param version LaVersion for \ref LibAppletArgs.
*/
void libappletArgsCreate(LibAppletArgs* a, u32 version);
/**
* @brief Sets the PlayStartupSound field in \ref LibAppletArgs.
* @param a LibAppletArgs struct.
* @param flag Value for \ref LibAppletArgs PlayStartupSound.
*/
void libappletArgsSetPlayStartupSound(LibAppletArgs* a, bool flag);
/**
* @brief Creates an AppletStorage with the specified size and writes the buffer contents to that storage at offset 0.
* @param[out] s Storage object.
* @param buffer Input buffer.
* @param size Size to write.
*/
Result libappletCreateWriteStorage(AppletStorage* s, const void* buffer, size_t size);
/**
* @brief Reads data from offset 0 from the specified storage into the buffer. If the storage-size is smaller than the size param, the storage-size is used instead.
* @param s Storage object.
* @param buffer Output buffer.
* @param size Size to read.
* @param transfer_size Optional output size field for the actual size used for the read, can be NULL.
*/
Result libappletReadStorage(AppletStorage* s, void* buffer, size_t size, size_t *transfer_size);
/**
* @brief Sets the tick field in LibAppletArgs, then creates a storage with it which is pushed to the AppletHolder via \ref appletHolderPushInData.
* @param a LibAppletArgs struct.
* @param h AppletHolder object.
*/
Result libappletArgsPush(LibAppletArgs* a, AppletHolder *h);
/**
* @brief Uses \ref appletPopInData and reads it to the specified LibAppletArgs. The LibAppletArgs is validated, an error is thrown when invalid.
* @param[out] a LibAppletArgs struct.
*/
Result libappletArgsPop(LibAppletArgs* a);
/**
* @brief Creates a storage using the input buffer which is pushed to the AppletHolder via \ref appletHolderPushInData.
* @param h AppletHolder object.
* @param buffer Input data buffer.
* @param size Input data size.
*/
Result libappletPushInData(AppletHolder *h, const void* buffer, size_t size);
/**
* @brief Pops a storage via \ref appletHolderPopOutData, uses \ref libappletReadStorage, then closes the storage.
* @param h AppletHolder object.
* @param buffer Output buffer.
* @param size Size to read.
* @param transfer_size Optional output size field for the actual size used for the read, can be NULL.
*/
Result libappletPopOutData(AppletHolder *h, void* buffer, size_t size, size_t *transfer_size);
/**
* @brief Sets whether \ref libappletStart uses \ref appletHolderJump.
* @param flag Flag. Value true should not be used unless running as AppletType_LibraryApplet.
*/
void libappletSetJumpFlag(bool flag);
/**
* @brief If the flag from \ref libappletSetJumpFlag is set, this just uses \ref appletHolderJump. Otherwise, starts the applet and waits for it to finish, then checks the \ref LibAppletExitReason.
* @note Uses \ref appletHolderStart and \ref appletHolderJoin.
* @param h AppletHolder object.
*/
Result libappletStart(AppletHolder *h);
/**
* @brief Creates a LibraryApplet with the specified input storage data, uses \ref libappletStart, and reads the output storage reply data via \ref libappletPopOutData.
* @param id \ref AppletId
* @param commonargs \ref LibAppletArgs struct.
* @param arg Input storage data buffer. Optional, can be NULL.
* @param arg_size Size of the arg buffer.
* @param reply Output storage data buffer. Optional, can be NULL.
* @param reply_size Size to read for the reply buffer.
* @param out_reply_size Actual read reply data size, see \ref libappletPopOutData.
*/
Result libappletLaunch(AppletId id, LibAppletArgs *commonargs, const void* arg, size_t arg_size, void* reply, size_t reply_size, size_t *out_reply_size);
/// Wrapper for \ref appletPushToGeneralChannel, see appletPushToGeneralChannel regarding the requirements for using this.
/// Returns to the main Home Menu, equivalent to pressing the HOME button.
Result libappletRequestHomeMenu(void);
/// Wrapper for \ref appletPushToGeneralChannel, see appletPushToGeneralChannel regarding the requirements for using this.
/// Equivalent to entering "System Update" under System Settings. When leaving this, it returns to the main Home Menu.
Result libappletRequestJumpToSystemUpdate(void);
/**
* @brief Wrapper for \ref appletPushToGeneralChannel, see appletPushToGeneralChannel regarding the requirements for using this.
* @note Only available on [11.0.0+].
* @param[in] application_id ApplicationId
* @param[in] uid \ref AccountUid
* @param[in] buffer Input buffer.
* @param[in] size Input buffer size.
* @param[in] sender LaunchApplicationRequestSender
*/
Result libappletRequestToLaunchApplication(u64 application_id, AccountUid uid, const void* buffer, size_t size, u32 sender);
/**
* @brief Wrapper for \ref appletPushToGeneralChannel, see appletPushToGeneralChannel regarding the requirements for using this.
* @note Only available on [11.0.0+].
* @param[in] uid \ref AccountUid
* @param[in] application_id Optional ApplicationId, can be 0.
*/
Result libappletRequestJumpToStory(AccountUid uid, u64 application_id);

View file

@ -0,0 +1,153 @@
## *
## @file libapplet.h
## @brief LibraryApplet wrapper.
## @author yellows8
## @copyright libnx Authors
##
import
../types, ../services/applet, ../services/acc
## / CommonArguments
type
LibAppletArgs* {.bycopy.} = object
CommonArgs_version*: U32 ## /< \ref libappletArgsCreate sets this to 1, and \ref libappletArgsPop requires value 1. v0 is not supported.
CommonArgs_size*: U32 ## /< Size of this struct.
LaVersion*: U32 ## /< LibraryApplet API version.
ExpectedThemeColor*: S32 ## /< Set to the output from \ref appletGetThemeColorType by \ref libappletArgsCreate.
PlayStartupSound*: U8 ## /< bool flag, default is false.
pad*: array[7, U8] ## /< Padding.
tick*: U64 ## /< System tick. Set to the output from \ref armGetSystemTick during \ref libappletArgsPush.
proc libappletArgsCreate*(a: ptr LibAppletArgs; version: U32) {.cdecl,
importc: "libappletArgsCreate".}
## *
## @brief Creates a LibAppletArgs struct.
## @param a LibAppletArgs struct.
## @param version LaVersion for \ref LibAppletArgs.
##
proc libappletArgsSetPlayStartupSound*(a: ptr LibAppletArgs; flag: bool) {.cdecl,
importc: "libappletArgsSetPlayStartupSound".}
## *
## @brief Sets the PlayStartupSound field in \ref LibAppletArgs.
## @param a LibAppletArgs struct.
## @param flag Value for \ref LibAppletArgs PlayStartupSound.
##
proc libappletCreateWriteStorage*(s: ptr AppletStorage; buffer: pointer; size: csize_t): Result {.
cdecl, importc: "libappletCreateWriteStorage".}
## *
## @brief Creates an AppletStorage with the specified size and writes the buffer contents to that storage at offset 0.
## @param[out] s Storage object.
## @param buffer Input buffer.
## @param size Size to write.
##
proc libappletReadStorage*(s: ptr AppletStorage; buffer: pointer; size: csize_t;
transfer_size: ptr csize_t): Result {.cdecl,
importc: "libappletReadStorage".}
## *
## @brief Reads data from offset 0 from the specified storage into the buffer. If the storage-size is smaller than the size param, the storage-size is used instead.
## @param s Storage object.
## @param buffer Output buffer.
## @param size Size to read.
## @param transfer_size Optional output size field for the actual size used for the read, can be NULL.
##
proc libappletArgsPush*(a: ptr LibAppletArgs; h: ptr AppletHolder): Result {.cdecl,
importc: "libappletArgsPush".}
## *
## @brief Sets the tick field in LibAppletArgs, then creates a storage with it which is pushed to the AppletHolder via \ref appletHolderPushInData.
## @param a LibAppletArgs struct.
## @param h AppletHolder object.
##
proc libappletArgsPop*(a: ptr LibAppletArgs): Result {.cdecl,
importc: "libappletArgsPop".}
## *
## @brief Uses \ref appletPopInData and reads it to the specified LibAppletArgs. The LibAppletArgs is validated, an error is thrown when invalid.
## @param[out] a LibAppletArgs struct.
##
proc libappletPushInData*(h: ptr AppletHolder; buffer: pointer; size: csize_t): Result {.
cdecl, importc: "libappletPushInData".}
## *
## @brief Creates a storage using the input buffer which is pushed to the AppletHolder via \ref appletHolderPushInData.
## @param h AppletHolder object.
## @param buffer Input data buffer.
## @param size Input data size.
##
proc libappletPopOutData*(h: ptr AppletHolder; buffer: pointer; size: csize_t;
transfer_size: ptr csize_t): Result {.cdecl,
importc: "libappletPopOutData".}
## *
## @brief Pops a storage via \ref appletHolderPopOutData, uses \ref libappletReadStorage, then closes the storage.
## @param h AppletHolder object.
## @param buffer Output buffer.
## @param size Size to read.
## @param transfer_size Optional output size field for the actual size used for the read, can be NULL.
##
proc libappletSetJumpFlag*(flag: bool) {.cdecl, importc: "libappletSetJumpFlag".}
## *
## @brief Sets whether \ref libappletStart uses \ref appletHolderJump.
## @param flag Flag. Value true should not be used unless running as AppletType_LibraryApplet.
##
proc libappletStart*(h: ptr AppletHolder): Result {.cdecl, importc: "libappletStart".}
## *
## @brief If the flag from \ref libappletSetJumpFlag is set, this just uses \ref appletHolderJump. Otherwise, starts the applet and waits for it to finish, then checks the \ref LibAppletExitReason.
## @note Uses \ref appletHolderStart and \ref appletHolderJoin.
## @param h AppletHolder object.
##
proc libappletLaunch*(id: AppletId; commonargs: ptr LibAppletArgs; arg: pointer;
arg_size: csize_t; reply: pointer; reply_size: csize_t;
out_reply_size: ptr csize_t): Result {.cdecl,
importc: "libappletLaunch".}
## *
## @brief Creates a LibraryApplet with the specified input storage data, uses \ref libappletStart, and reads the output storage reply data via \ref libappletPopOutData.
## @param id \ref AppletId
## @param commonargs \ref LibAppletArgs struct.
## @param arg Input storage data buffer. Optional, can be NULL.
## @param arg_size Size of the arg buffer.
## @param reply Output storage data buffer. Optional, can be NULL.
## @param reply_size Size to read for the reply buffer.
## @param out_reply_size Actual read reply data size, see \ref libappletPopOutData.
##
proc libappletRequestHomeMenu*(): Result {.cdecl,
importc: "libappletRequestHomeMenu".}
## / Wrapper for \ref appletPushToGeneralChannel, see appletPushToGeneralChannel regarding the requirements for using this.
## / Returns to the main Home Menu, equivalent to pressing the HOME button.
proc libappletRequestJumpToSystemUpdate*(): Result {.cdecl,
importc: "libappletRequestJumpToSystemUpdate".}
## / Wrapper for \ref appletPushToGeneralChannel, see appletPushToGeneralChannel regarding the requirements for using this.
## / Equivalent to entering "System Update" under System Settings. When leaving this, it returns to the main Home Menu.
proc libappletRequestToLaunchApplication*(application_id: U64; uid: AccountUid;
buffer: pointer; size: csize_t; sender: U32): Result {.cdecl,
importc: "libappletRequestToLaunchApplication".}
## *
## @brief Wrapper for \ref appletPushToGeneralChannel, see appletPushToGeneralChannel regarding the requirements for using this.
## @note Only available on [11.0.0+].
## @param[in] application_id ApplicationId
## @param[in] uid \ref AccountUid
## @param[in] buffer Input buffer.
## @param[in] size Input buffer size.
## @param[in] sender LaunchApplicationRequestSender
##
proc libappletRequestJumpToStory*(uid: AccountUid; application_id: U64): Result {.
cdecl, importc: "libappletRequestJumpToStory".}
## *
## @brief Wrapper for \ref appletPushToGeneralChannel, see appletPushToGeneralChannel regarding the requirements for using this.
## @note Only available on [11.0.0+].
## @param[in] uid \ref AccountUid
## @param[in] application_id Optional ApplicationId, can be 0.
##

View file

@ -0,0 +1,101 @@
/**
* @file mii_la.h
* @brief Wrapper for using the MiiEdit LibraryApplet.
* @author yellows8
* @copyright libnx Authors
*/
#pragma once
#include "../types.h"
#include "../services/mii.h"
/// AppletMode
typedef enum {
MiiLaAppletMode_ShowMiiEdit = 0, ///< ShowMiiEdit
MiiLaAppletMode_AppendMii = 1, ///< AppendMii
MiiLaAppletMode_AppendMiiImage = 2, ///< AppendMiiImage
MiiLaAppletMode_UpdateMiiImage = 3, ///< UpdateMiiImage
MiiLaAppletMode_CreateMii = 4, ///< [10.2.0+] CreateMii
MiiLaAppletMode_EditMii = 5, ///< [10.2.0+] EditMii
} MiiLaAppletMode;
/// AppletInput
typedef struct {
s32 version; ///< Version
u32 mode; ///< \ref MiiLaAppletMode
s32 special_key_code; ///< \ref MiiSpecialKeyCode
union {
Uuid valid_uuid_array[8]; ///< ValidUuidArray. Only used with \ref MiiLaAppletMode ::NfpLaMiiLaAppletMode_AppendMiiImage / ::NfpLaMiiLaAppletMode_UpdateMiiImage.
struct {
MiiCharInfo char_info; ///< \ref MiiCharInfo
u8 unused_x64[0x28]; ///< Unused
} char_info;
};
Uuid used_uuid; ///< UsedUuid. Only used with \ref MiiLaAppletMode ::NfpLaMiiLaAppletMode_UpdateMiiImage.
u8 unk_x9C[0x64]; ///< Unused
} MiiLaAppletInput;
/// AppletOutput
typedef struct {
u32 res; ///< Result: 0 = Success, 1 = Cancel.
s32 index; ///< Index. Only set when Result is Success, where \ref MiiLaAppletMode isn't ::NfpLaMiiLaAppletMode_ShowMiiEdit.
u8 unk_x8[0x18]; ///< Unused
} MiiLaAppletOutput;
/// AppletOutputForCharInfoEditing
typedef struct {
u32 res; ///< MiiLaAppletOutput::res
MiiCharInfo char_info; ///< \ref MiiCharInfo
u8 unused[0x24]; ///< Unused
} MiiLaAppletOutputForCharInfoEditing;
/**
* @brief Launches the applet for ShowMiiEdit.
* @param[in] special_key_code \ref MiiSpecialKeyCode
*/
Result miiLaShowMiiEdit(MiiSpecialKeyCode special_key_code);
/**
* @brief Launches the applet for AppendMii.
* @param[in] special_key_code \ref MiiSpecialKeyCode
* @param[out] index Output Index.
*/
Result miiLaAppendMii(MiiSpecialKeyCode special_key_code, s32 *index);
/**
* @brief Launches the applet for AppendMiiImage.
* @param[in] special_key_code \ref MiiSpecialKeyCode
* @param[in] valid_uuid_array Input array of Uuid.
* @param[in] count Total entries for the valid_uuid_array. Must be 0-8.
* @param[out] index Output Index.
*/
Result miiLaAppendMiiImage(MiiSpecialKeyCode special_key_code, const Uuid *valid_uuid_array, s32 count, s32 *index);
/**
* @brief Launches the applet for UpdateMiiImage.
* @param[in] special_key_code \ref MiiSpecialKeyCode
* @param[in] valid_uuid_array Input array of Uuid.
* @param[in] count Total entries for the valid_uuid_array. Must be 0-8.
* @param[in] used_uuid UsedUuid
* @param[out] index Output Index.
*/
Result miiLaUpdateMiiImage(MiiSpecialKeyCode special_key_code, const Uuid *valid_uuid_array, s32 count, Uuid used_uuid, s32 *index);
/**
* @brief Launches the applet for CreateMii.
* @note This creates a Mii and returns it, without saving it in the database.
* @note Only available on [10.2.0+].
* @param[in] special_key_code \ref MiiSpecialKeyCode
* @param[out] out_char \ref MiiCharInfo
*/
Result miiLaCreateMii(MiiSpecialKeyCode special_key_code, MiiCharInfo *out_char);
/**
* @brief Launches the applet for EditMii.
* @note This edits the specified Mii and returns it, without saving it in the database.
* @note Only available on [10.2.0+].
* @param[in] special_key_code \ref MiiSpecialKeyCode
* @param[in] in_char \ref MiiCharInfo
* @param[out] out_char \ref MiiCharInfo
*/
Result miiLaEditMii(MiiSpecialKeyCode special_key_code, const MiiCharInfo *in_char, MiiCharInfo *out_char);

View file

@ -0,0 +1,119 @@
## *
## @file mii_la.h
## @brief Wrapper for using the MiiEdit LibraryApplet.
## @author yellowS8
## @copyright libnx Authors
##
import
../types, ../services/mii
## / AppletMode
type
MiiLaAppletMode* = enum
MiiLaAppletMode_ShowMiiEdit = 0, ## /< ShowMiiEdit
MiiLaAppletMode_AppendMii = 1, ## /< AppendMii
MiiLaAppletMode_AppendMiiImage = 2, ## /< AppendMiiImage
MiiLaAppletMode_UpdateMiiImage = 3, ## /< UpdateMiiImage
MiiLaAppletMode_CreateMii = 4, ## /< [10.2.0+] CreateMii
MiiLaAppletMode_EditMii = 5 ## /< [10.2.0+] EditMii
## / AppletInput
type
INNER_C_STRUCT_mii_la_35* {.bycopy.} = object
char_info*: MiiCharInfo ## /< \ref MiiCharInfo
unused_x64*: array[0x28, U8] ## /< Unused
INNER_C_UNION_mii_la_35* {.bycopy, union.} = object
valid_uuid_array*: array[8, Uuid] ## /< ValidUuidArray. Only used with \ref MiiLaAppletMode ::NfpLaMiiLaAppletMode_AppendMiiImage / ::NfpLaMiiLaAppletMode_UpdateMiiImage.
char_info*: INNER_C_STRUCT_mii_la_35
MiiLaAppletInput* {.bycopy.} = object
version*: S32 ## /< Version
mode*: U32 ## /< \ref MiiLaAppletMode
special_key_code*: S32 ## /< \ref MiiSpecialKeyCode
ano_mii_la_35*: INNER_C_UNION_mii_la_35
used_uuid*: Uuid ## /< UsedUuid. Only used with \ref MiiLaAppletMode ::NfpLaMiiLaAppletMode_UpdateMiiImage.
unk_x9C*: array[0x64, U8] ## /< Unused
## / AppletOutput
type
MiiLaAppletOutput* {.bycopy.} = object
res*: U32 ## /< Result: 0 = Success, 1 = Cancel.
index*: S32 ## /< Index. Only set when Result is Success, where \ref MiiLaAppletMode isn't ::NfpLaMiiLaAppletMode_ShowMiiEdit.
unk_x8*: array[0x18, U8] ## /< Unused
## / AppletOutputForCharInfoEditing
type
MiiLaAppletOutputForCharInfoEditing* {.bycopy.} = object
res*: U32 ## /< MiiLaAppletOutput::res
char_info*: MiiCharInfo ## /< \ref MiiCharInfo
unused*: array[0x24, U8] ## /< Unused
proc miiLaShowMiiEdit*(special_key_code: MiiSpecialKeyCode): Result {.cdecl,
importc: "miiLaShowMiiEdit".}
## *
## @brief Launches the applet for ShowMiiEdit.
## @param[in] special_key_code \ref MiiSpecialKeyCode
##
proc miiLaAppendMii*(special_key_code: MiiSpecialKeyCode; index: ptr S32): Result {.
cdecl, importc: "miiLaAppendMii".}
## *
## @brief Launches the applet for AppendMii.
## @param[in] special_key_code \ref MiiSpecialKeyCode
## @param[out] index Output Index.
##
proc miiLaAppendMiiImage*(special_key_code: MiiSpecialKeyCode;
valid_uuid_array: ptr Uuid; count: S32; index: ptr S32): Result {.
cdecl, importc: "miiLaAppendMiiImage".}
## *
## @brief Launches the applet for AppendMiiImage.
## @param[in] special_key_code \ref MiiSpecialKeyCode
## @param[in] valid_uuid_array Input array of Uuid.
## @param[in] count Total entries for the valid_uuid_array. Must be 0-8.
## @param[out] index Output Index.
##
proc miiLaUpdateMiiImage*(special_key_code: MiiSpecialKeyCode;
valid_uuid_array: ptr Uuid; count: S32; used_uuid: Uuid;
index: ptr S32): Result {.cdecl,
importc: "miiLaUpdateMiiImage".}
## *
## @brief Launches the applet for UpdateMiiImage.
## @param[in] special_key_code \ref MiiSpecialKeyCode
## @param[in] valid_uuid_array Input array of Uuid.
## @param[in] count Total entries for the valid_uuid_array. Must be 0-8.
## @param[in] used_uuid UsedUuid
## @param[out] index Output Index.
##
proc miiLaCreateMii*(special_key_code: MiiSpecialKeyCode; out_char: ptr MiiCharInfo): Result {.
cdecl, importc: "miiLaCreateMii".}
## *
## @brief Launches the applet for CreateMii.
## @note This creates a Mii and returns it, without saving it in the database.
## @note Only available on [10.2.0+].
## @param[in] special_key_code \ref MiiSpecialKeyCode
## @param[out] out_char \ref MiiCharInfo
##
proc miiLaEditMii*(special_key_code: MiiSpecialKeyCode; in_char: ptr MiiCharInfo;
out_char: ptr MiiCharInfo): Result {.cdecl, importc: "miiLaEditMii".}
## *
## @brief Launches the applet for EditMii.
## @note This edits the specified Mii and returns it, without saving it in the database.
## @note Only available on [10.2.0+].
## @param[in] special_key_code \ref MiiSpecialKeyCode
## @param[in] in_char \ref MiiCharInfo
## @param[out] out_char \ref MiiCharInfo
##

View file

@ -0,0 +1,89 @@
/**
* @file nfp_la.h
* @brief Wrapper for using the cabinet (amiibo) LibraryApplet.
* @author yellows8
* @copyright libnx Authors
*/
#pragma once
#include "../types.h"
#include "../services/nfc.h"
/// Values for NfpLaStartParamForAmiiboSettings::type.
typedef enum {
NfpLaStartParamTypeForAmiiboSettings_NicknameAndOwnerSettings = 0, ///< NicknameAndOwnerSettings
NfpLaStartParamTypeForAmiiboSettings_GameDataEraser = 1, ///< GameDataEraser
NfpLaStartParamTypeForAmiiboSettings_Restorer = 2, ///< Restorer
NfpLaStartParamTypeForAmiiboSettings_Formatter = 3, ///< Formatter
} NfpLaStartParamTypeForAmiiboSettings;
/// AmiiboSettingsStartParam
typedef struct {
u8 unk_x0[0x8]; ///< Unknown
u8 unk_x8[0x20]; ///< Unknown
u8 unk_x28; ///< Unknown
} NfpLaAmiiboSettingsStartParam;
/// StartParamForAmiiboSettings
typedef struct {
u8 unk_x0; ///< Unknown
u8 type; ///< \ref NfpLaStartParamTypeForAmiiboSettings
u8 flags; ///< Flags
u8 unk_x3; ///< NfpLaAmiiboSettingsStartParam::unk_x28
u8 unk_x4[0x8]; ///< NfpLaAmiiboSettingsStartParam::unk_x0
NfpTagInfo tag_info; ///< \ref NfpTagInfo, only enabled when flags bit1 is set.
NfpRegisterInfo register_info; ///< \ref NfpRegisterInfo, only enabled when flags bit2 is set.
u8 unk_x164[0x20]; ///< NfpLaAmiiboSettingsStartParam::unk_x8
u8 unk_x184[0x24]; ///< Unknown
} NfpLaStartParamForAmiiboSettings;
/// ReturnValueForAmiiboSettings
typedef struct {
u8 flags; ///< 0 = error, non-zero = success.
u8 pad[3]; ///< Padding
NfcDeviceHandle handle; ///< \ref NfcDeviceHandle
NfpTagInfo tag_info; ///< \ref NfpTagInfo
NfpRegisterInfo register_info; ///< \ref NfpRegisterInfo, only available when flags bit2 is set.
u8 unk_x164[0x24]; ///< Unknown
} NfpLaReturnValueForAmiiboSettings;
/**
* @brief Launches the applet for NicknameAndOwnerSettings.
* @note Official sw does not expose functionality for using input/output \ref NfpTagInfo at the same time.
* @param[in] in_param \ref NfpLaAmiiboSettingsStartParam
* @param[in] in_tag_info \ref NfpTagInfo. Optional, can be NULL. If specified, this must match the scanned amiibo.
* @param[in] in_reg_info \ref NfpRegisterInfo. Optional, can be NULL. If specified, this sets the \ref NfpRegisterInfo which will be used for writing, with an option for the user to change it.
* @param[out] out_tag_info \ref NfpTagInfo. Optional, can be NULL.
* @param[out] handle \ref NfcDeviceHandle
* @param[out] reg_info_flag Flag indicating whether the data for out_reg_info is set. Optional, can be NULL.
* @param[out] out_reg_info \ref NfpRegisterInfo, see reg_info_flag. Optional, can be NULL.
*/
Result nfpLaStartNicknameAndOwnerSettings(const NfpLaAmiiboSettingsStartParam *in_param, const NfpTagInfo *in_tag_info, const NfpRegisterInfo *in_reg_info, NfpTagInfo *out_tag_info, NfcDeviceHandle *handle, bool *reg_info_flag, NfpRegisterInfo *out_reg_info);
/**
* @brief Launches the applet for GameDataEraser.
* @note Official sw does not expose functionality for using input/output \ref NfpTagInfo at the same time.
* @param[in] in_param \ref NfpLaAmiiboSettingsStartParam
* @param[in] in_tag_info \ref NfpTagInfo. Optional, can be NULL. If specified, this must match the scanned amiibo.
* @param[out] out_tag_info \ref NfpTagInfo. Optional, can be NULL.
* @param[out] handle \ref NfcDeviceHandle
*/
Result nfpLaStartGameDataEraser(const NfpLaAmiiboSettingsStartParam *in_param, const NfpTagInfo *in_tag_info, NfpTagInfo *out_tag_info, NfcDeviceHandle *handle);
/**
* @brief Launches the applet for Restorer.
* @note Official sw does not expose functionality for using input/output \ref NfpTagInfo at the same time.
* @param[in] in_param \ref NfpLaAmiiboSettingsStartParam
* @param[in] in_tag_info \ref NfpTagInfo. Optional, can be NULL. If specified, this must match the scanned amiibo.
* @param[out] out_tag_info \ref NfpTagInfo. Optional, can be NULL.
* @param[out] handle \ref NfcDeviceHandle
*/
Result nfpLaStartRestorer(const NfpLaAmiiboSettingsStartParam *in_param, const NfpTagInfo *in_tag_info, NfpTagInfo *out_tag_info, NfcDeviceHandle *handle);
/**
* @brief Launches the applet for Formatter.
* @param[in] in_param \ref NfpLaAmiiboSettingsStartParam
* @param[out] out_tag_info \ref NfpTagInfo
* @param[out] handle \ref NfcDeviceHandle
*/
Result nfpLaStartFormatter(const NfpLaAmiiboSettingsStartParam *in_param, NfpTagInfo *out_tag_info, NfcDeviceHandle *handle);

View file

@ -0,0 +1,112 @@
## *
## @file nfp_la.h
## @brief Wrapper for using the cabinet (amiibo) LibraryApplet.
## @author yellowS8
## @copyright libnx Authors
##
import
../types, ../services/nfc
## / Values for NfpLaStartParamForAmiiboSettings::type.
type
NfpLaStartParamTypeForAmiiboSettings* = enum
NfpLaStartParamTypeForAmiiboSettings_NicknameAndOwnerSettings = 0, ## /< NicknameAndOwnerSettings
NfpLaStartParamTypeForAmiiboSettings_GameDataEraser = 1, ## /< GameDataEraser
NfpLaStartParamTypeForAmiiboSettings_Restorer = 2, ## /< Restorer
NfpLaStartParamTypeForAmiiboSettings_Formatter = 3 ## /< Formatter
## / AmiiboSettingsStartParam
type
NfpLaAmiiboSettingsStartParam* {.bycopy.} = object
unk_x0*: array[0x8, U8] ## /< Unknown
unk_x8*: array[0x20, U8] ## /< Unknown
unk_x28*: U8 ## /< Unknown
## / StartParamForAmiiboSettings
type
NfpLaStartParamForAmiiboSettings* {.bycopy.} = object
unk_x0*: U8 ## /< Unknown
`type`*: U8 ## /< \ref NfpLaStartParamTypeForAmiiboSettings
flags*: U8 ## /< Flags
unk_x3*: U8 ## /< NfpLaAmiiboSettingsStartParam::unk_x28
unk_x4*: array[0x8, U8] ## /< NfpLaAmiiboSettingsStartParam::unk_x0
tag_info*: NfpTagInfo ## /< \ref NfpTagInfo, only enabled when flags bit1 is set.
register_info*: NfpRegisterInfo ## /< \ref NfpRegisterInfo, only enabled when flags bit2 is set.
unk_x164*: array[0x20, U8] ## /< NfpLaAmiiboSettingsStartParam::unk_x8
unk_x184*: array[0x24, U8] ## /< Unknown
## / ReturnValueForAmiiboSettings
type
NfpLaReturnValueForAmiiboSettings* {.bycopy.} = object
flags*: U8 ## /< 0 = error, non-zero = success.
pad*: array[3, U8] ## /< Padding
handle*: NfcDeviceHandle ## /< \ref NfcDeviceHandle
tag_info*: NfpTagInfo ## /< \ref NfpTagInfo
register_info*: NfpRegisterInfo ## /< \ref NfpRegisterInfo, only available when flags bit2 is set.
unk_x164*: array[0x24, U8] ## /< Unknown
proc nfpLaStartNicknameAndOwnerSettings*(in_param: ptr NfpLaAmiiboSettingsStartParam;
in_tag_info: ptr NfpTagInfo;
in_reg_info: ptr NfpRegisterInfo;
out_tag_info: ptr NfpTagInfo;
handle: ptr NfcDeviceHandle;
reg_info_flag: ptr bool;
out_reg_info: ptr NfpRegisterInfo): Result {.
cdecl, importc: "nfpLaStartNicknameAndOwnerSettings".}
## *
## @brief Launches the applet for NicknameAndOwnerSettings.
## @note Official sw does not expose functionality for using input/output \ref NfpTagInfo at the same time.
## @param[in] in_param \ref NfpLaAmiiboSettingsStartParam
## @param[in] in_tag_info \ref NfpTagInfo. Optional, can be NULL. If specified, this must match the scanned amiibo.
## @param[in] in_reg_info \ref NfpRegisterInfo. Optional, can be NULL. If specified, this sets the \ref NfpRegisterInfo which will be used for writing, with an option for the user to change it.
## @param[out] out_tag_info \ref NfpTagInfo. Optional, can be NULL.
## @param[out] handle \ref NfcDeviceHandle
## @param[out] reg_info_flag Flag indicating whether the data for out_reg_info is set. Optional, can be NULL.
## @param[out] out_reg_info \ref NfpRegisterInfo, see reg_info_flag. Optional, can be NULL.
##
proc nfpLaStartGameDataEraser*(in_param: ptr NfpLaAmiiboSettingsStartParam;
in_tag_info: ptr NfpTagInfo;
out_tag_info: ptr NfpTagInfo;
handle: ptr NfcDeviceHandle): Result {.cdecl,
importc: "nfpLaStartGameDataEraser".}
## *
## @brief Launches the applet for GameDataEraser.
## @note Official sw does not expose functionality for using input/output \ref NfpTagInfo at the same time.
## @param[in] in_param \ref NfpLaAmiiboSettingsStartParam
## @param[in] in_tag_info \ref NfpTagInfo. Optional, can be NULL. If specified, this must match the scanned amiibo.
## @param[out] out_tag_info \ref NfpTagInfo. Optional, can be NULL.
## @param[out] handle \ref NfcDeviceHandle
##
proc nfpLaStartRestorer*(in_param: ptr NfpLaAmiiboSettingsStartParam;
in_tag_info: ptr NfpTagInfo; out_tag_info: ptr NfpTagInfo;
handle: ptr NfcDeviceHandle): Result {.cdecl,
importc: "nfpLaStartRestorer".}
## *
## @brief Launches the applet for Restorer.
## @note Official sw does not expose functionality for using input/output \ref NfpTagInfo at the same time.
## @param[in] in_param \ref NfpLaAmiiboSettingsStartParam
## @param[in] in_tag_info \ref NfpTagInfo. Optional, can be NULL. If specified, this must match the scanned amiibo.
## @param[out] out_tag_info \ref NfpTagInfo. Optional, can be NULL.
## @param[out] handle \ref NfcDeviceHandle
##
proc nfpLaStartFormatter*(in_param: ptr NfpLaAmiiboSettingsStartParam;
out_tag_info: ptr NfpTagInfo; handle: ptr NfcDeviceHandle): Result {.
cdecl, importc: "nfpLaStartFormatter".}
## *
## @brief Launches the applet for Formatter.
## @param[in] in_param \ref NfpLaAmiiboSettingsStartParam
## @param[out] out_tag_info \ref NfpTagInfo
## @param[out] handle \ref NfcDeviceHandle
##

View file

@ -0,0 +1,16 @@
/**
* @file nifm_la.h
* @brief Wrapper for using the nifm LibraryApplet (the launched applet varies).
* @author yellows8
* @copyright libnx Authors
*/
#pragma once
#include "../types.h"
#include "../services/nifm.h"
/**
* @brief Uses \ref nifmGetResult, then on failure launches the applet.
* @param r \ref NifmRequest
*/
Result nifmLaHandleNetworkRequestResult(NifmRequest* r);

View file

@ -0,0 +1,17 @@
## *
## @file nifm_la.h
## @brief Wrapper for using the nifm LibraryApplet (the launched applet varies).
## @author yellows8
## @copyright libnx Authors
##
import
../types, ../services/nifm
## *
## @brief Uses \ref nifmGetResult, then on failure launches the applet.
## @param r \ref NifmRequest
##
proc nifmLaHandleNetworkRequestResult*(r: ptr NifmRequest): Result {.cdecl,
importc: "nifmLaHandleNetworkRequestResult".}

View file

@ -0,0 +1,58 @@
/**
* @file pctlauth.h
* @brief Wrapper for using the Parental Controls authentication LibraryApplet. This applet is used by qlaunch.
* @author yellows8
* @copyright libnx Authors
*/
#pragma once
#include "../types.h"
/// Type values for PctlAuthArg::type.
typedef enum {
PctlAuthType_Show = 0, ///< ShowParentalAuthentication
PctlAuthType_RegisterPasscode = 1, ///< RegisterParentalPasscode
PctlAuthType_ChangePasscode = 2, ///< ChangeParentalPasscode
} PctlAuthType;
/// Input arg storage for the applet.
typedef struct {
u32 unk_x0; ///< Always set to 0 by the user-process.
PctlAuthType type; ///< \ref PctlAuthType
u8 arg0; ///< Arg0
u8 arg1; ///< Arg1
u8 arg2; ///< Arg2
u8 pad; ///< Padding
} PctlAuthArg;
/**
* @brief Launches the applet.
* @note Should not be used if a PIN is not already registered. See \ref pctlIsRestrictionEnabled.
* @param flag Input flag. false = temporarily disable Parental Controls. true = validate the input PIN.
*/
Result pctlauthShow(bool flag);
/**
* @brief Launches the applet. Only available with [4.0.0+].
* @param arg0 Value for PctlAuthArg.arg0.
* @param arg1 Value for PctlAuthArg.arg1.
* @param arg2 Value for PctlAuthArg.arg2.
*/
Result pctlauthShowEx(u8 arg0, u8 arg1, u8 arg2);
/**
* @brief Just calls: pctlauthShowEx(1, 0, 1). Launches the applet for checking the PIN, used when changing system-settings.
* @note Should not be used if a PIN is not already registered. See \ref pctlIsRestrictionEnabled.
*/
Result pctlauthShowForConfiguration(void);
/**
* @brief Launches the applet for registering the Parental Controls PIN.
*/
Result pctlauthRegisterPasscode(void);
/**
* @brief Launches the applet for changing the Parental Controls PIN.
* @note Should not be used if a PIN is not already registered. See \ref pctlIsRestrictionEnabled.
*/
Result pctlauthChangePasscode(void);

View file

@ -0,0 +1,65 @@
## *
## @file pctlauth.h
## @brief Wrapper for using the Parental Controls authentication LibraryApplet. This applet is used by qlaunch.
## @author yellowS8
## @copyright libnx Authors
##
import
../types
## / Type values for PctlAuthArg::type.
type
PctlAuthType* = enum
PctlAuthType_Show = 0, ## /< ShowParentalAuthentication
PctlAuthType_RegisterPasscode = 1, ## /< RegisterParentalPasscode
PctlAuthType_ChangePasscode = 2 ## /< ChangeParentalPasscode
## / Input arg storage for the applet.
type
PctlAuthArg* {.bycopy.} = object
unk_x0*: U32 ## /< Always set to 0 by the user-process.
`type`*: PctlAuthType ## /< \ref PctlAuthType
arg0*: U8 ## /< Arg0
arg1*: U8 ## /< Arg1
arg2*: U8 ## /< Arg2
pad*: U8 ## /< Padding
proc pctlauthShow*(flag: bool): Result {.cdecl, importc: "pctlauthShow".}
## *
## @brief Launches the applet.
## @note Should not be used if a PIN is not already registered. See \ref pctlIsRestrictionEnabled.
## @param flag Input flag. false = temporarily disable Parental Controls. true = validate the input PIN.
##
proc pctlauthShowEx*(arg0: U8; arg1: U8; arg2: U8): Result {.cdecl,
importc: "pctlauthShowEx".}
## *
## @brief Launches the applet. Only available with [4.0.0+].
## @param arg0 Value for PctlAuthArg.arg0.
## @param arg1 Value for PctlAuthArg.arg1.
## @param arg2 Value for PctlAuthArg.arg2.
##
proc pctlauthShowForConfiguration*(): Result {.cdecl,
importc: "pctlauthShowForConfiguration".}
## *
## @brief Just calls: pctlauthShowEx(1, 0, 1). Launches the applet for checking the PIN, used when changing system-settings.
## @note Should not be used if a PIN is not already registered. See \ref pctlIsRestrictionEnabled.
##
proc pctlauthRegisterPasscode*(): Result {.cdecl,
importc: "pctlauthRegisterPasscode".}
## *
## @brief Launches the applet for registering the Parental Controls PIN.
##
proc pctlauthChangePasscode*(): Result {.cdecl, importc: "pctlauthChangePasscode".}
## *
## @brief Launches the applet for changing the Parental Controls PIN.
## @note Should not be used if a PIN is not already registered. See \ref pctlIsRestrictionEnabled.
##

View file

@ -0,0 +1,210 @@
/**
* @file psel.h
* @brief Wrapper for using the playerSelect (user selection) LibraryApplet.
* @author XorTroll, yellows8
* @copyright libnx Authors
*/
#pragma once
#include "../types.h"
#include "../services/acc.h"
/// playerSelect UI modes.
typedef enum {
PselUiMode_UserSelector = 0, ///< UserSelector
PselUiMode_UserCreator = 1, ///< UserCreator
PselUiMode_EnsureNetworkServiceAccountAvailable = 2, ///< EnsureNetworkServiceAccountAvailable
PselUiMode_UserIconEditor = 3, ///< UserIconEditor
PselUiMode_UserNicknameEditor = 4, ///< UserNicknameEditor
PselUiMode_UserCreatorForStarter = 5, ///< UserCreatorForStarter
PselUiMode_NintendoAccountAuthorizationRequestContext = 6, ///< NintendoAccountAuthorizationRequestContext
PselUiMode_IntroduceExternalNetworkServiceAccount = 7, ///< IntroduceExternalNetworkServiceAccount
PselUiMode_IntroduceExternalNetworkServiceAccountForRegistration = 8, ///< [6.0.0+] IntroduceExternalNetworkServiceAccountForRegistration
PselUiMode_NintendoAccountNnidLinker = 9, ///< [6.0.0+] NintendoAccountNnidLinker
PselUiMode_LicenseRequirementsForNetworkService = 10, ///< [6.0.0+] LicenseRequirementsForNetworkService
PselUiMode_LicenseRequirementsForNetworkServiceWithUserContextImpl = 11, ///< [7.0.0+] LicenseRequirementsForNetworkServiceWithUserContextImpl
PselUiMode_UserCreatorForImmediateNaLoginTest = 12, ///< [7.0.0+] UserCreatorForImmediateNaLoginTest
PselUiMode_UserQualificationPromoter = 13, ///< [13.0.0+] UserQualificationPromoter
} PselUiMode;
/// UI message text to display with ::PselUiMode_UserSelector. Invalid values are handled as ::PselUserSelectionPurpose_General.
typedef enum {
PselUserSelectionPurpose_General = 0, ///< "Select a user."
PselUserSelectionPurpose_GameCardRegistration = 1, ///< [2.0.0+] "Who will receive the points?"
PselUserSelectionPurpose_EShopLaunch = 2, ///< [2.0.0+] "Who is using Nintendo eShop?"
PselUserSelectionPurpose_EShopItemShow = 3, ///< [2.0.0+] "Who is making this purchase?"
PselUserSelectionPurpose_PicturePost = 4, ///< [2.0.0+] "Who is posting?"
PselUserSelectionPurpose_NintendoAccountLinkage = 5, ///< [2.0.0+] "Select a user to link to a Nintendo Account."
PselUserSelectionPurpose_SettingsUpdate = 6, ///< [2.0.0+] "Change settings for which user?"
PselUserSelectionPurpose_SaveDataDeletion = 7, ///< [2.0.0+] "Format data for which user?"
PselUserSelectionPurpose_UserMigration = 8, ///< [4.0.0+] "Which user will be transferred to another console?"
PselUserSelectionPurpose_SaveDataTransfer = 9, ///< [8.0.0+] "Send save data for which user?"
} PselUserSelectionPurpose;
/// NintendoAccountStartupDialogType
typedef enum {
PselNintendoAccountStartupDialogType_LoginAndCreate = 0, ///< LoginAndCreate
PselNintendoAccountStartupDialogType_Login = 1, ///< Login
PselNintendoAccountStartupDialogType_Create = 2, ///< Create
} PselNintendoAccountStartupDialogType;
/// Base UI settings for playerSelect.
typedef struct {
u32 mode; ///< \ref PselUiMode
u32 pad; ///< Padding.
AccountUid invalid_uid_list[ACC_USER_LIST_SIZE]; ///< List of \ref AccountUid. TODO: This is only correct for ::PselUiMode_UserSelector, for other modes this is a single uid, followed by mode-specific data (if any).
u64 application_id; ///< ApplicationId with \ref pselShowUserSelectorForLauncher.
u8 is_network_service_account_required; ///< PselUserSelectionSettings::is_network_service_account_required.
u8 is_skip_enabled; ///< PselUserSelectionSettings::is_skip_enabled
u8 unk_x92; ///< Set to value 1 by \ref pselShowUserSelectorForSystem / \ref pselShowUserSelectorForLauncher.
u8 is_permitted; ///< isPermitted. With ::PselUiMode_UserSelector: enables the option to create a new user. Set to the output from \ref accountIsUserRegistrationRequestPermitted with pselShowUserSelector*. When not set, a dialog will be displayed when the user attempts to create an user.
u8 show_skip_button; ///< PselUserSelectionSettings::show_skip_button
u8 additional_select; ///< PselUserSelectionSettings::additional_select
u8 unk_x96; ///< [2.0.0+] Set to PselUserSelectionSettingsForSystemService::enable_user_creation_button. \ref pselShowUserSelectorForLauncher / \ref pselShowUserSelector sets this to value 1.
u8 unk_x97; ///< [6.0.0+] Set to PselUserSelectionSettings::is_unqualified_user_selectable ^ 1.
} PselUiSettingsV1;
/// UI settings for versions starting with 0x10000.
typedef struct {
PselUiSettingsV1 settings; ///< \ref PselUiSettingsV1
u32 unk_x98; ///< [2.0.0+] Set to PselUserSelectionSettingsForSystemService::purpose.
u8 unk_x9c[0x4]; ///< Unknown.
} PselUiSettings;
/// UserSelectionSettings
typedef struct {
AccountUid invalid_uid_list[ACC_USER_LIST_SIZE]; ///< invalidUidList.
u8 is_skip_enabled; ///< isSkipEnabled. When set, the first user in invalid_uid_list must not be set, and additional_select must be 0. When enabled \ref accountTrySelectUserWithoutInteraction will be used to select the user, in this case the applet will only be launched if \ref accountTrySelectUserWithoutInteraction doesn't return an user.
u8 is_network_service_account_required; ///< isNetworkServiceAccountRequired. Whether the user needs to be linked to a Nintendo account.
u8 show_skip_button; ///< showSkipButton. Enables the option to skip user selection with a button.
u8 additional_select; ///< additionalSelect.
u8 is_unqualified_user_selectable; ///< [6.0.0+] isUnqualifiedUserSelectable
} PselUserSelectionSettings;
/// [2.0.0+] UserSelectionSettingsForSystemService
typedef struct {
u32 purpose; ///< \ref PselUserSelectionPurpose
u8 enable_user_creation_button; ///< Enables the user-creation button when set. Whether user-creation when pressing the button is actually allowed is controlled by PselUiSettingsV1::is_permitted.
u8 pad[0x3]; ///< Padding.
} PselUserSelectionSettingsForSystemService;
/// Return data sent after execution.
typedef struct {
Result res; ///< Result.
AccountUid user_id; ///< Selected \ref AccountUid.
} PselUiReturnArg;
/**
* @brief Creates a new UI config for the playerSelect applet with the specified mode.
* @param ui PseluiSettings struct.
* @param mode playerSelect UI mode.
*/
Result pselUiCreate(PselUiSettings *ui, PselUiMode mode);
/**
* @brief Adds an user to the user list of the applet.
* @param ui PselUiSettings struct.
* @param[in] user_id user ID.
* @note The users will be treated as invalid users for user selection mode, and as the input user for other modes.
*/
void pselUiAddUser(PselUiSettings *ui, AccountUid user_id);
/**
* @brief Sets whether users can be created in the applet.
* @param ui PselUiSettings struct.
* @param flag Flag value.
* @note Only used for ::PselUiMode_SelectUser.
*/
NX_CONSTEXPR void pselUiSetAllowUserCreation(PselUiSettings *ui, bool flag) {
if(ui->settings.mode == PselUiMode_UserSelector) {
ui->settings.is_permitted = flag!=0;
}
}
/**
* @brief Sets whether users need to be linked to a Nintendo account.
* @param ui PselUiSettings struct.
* @param flag Flag value.
*/
NX_CONSTEXPR void pselUiSetNetworkServiceRequired(PselUiSettings *ui, bool flag) {
ui->settings.is_network_service_account_required = flag;
}
/**
* @brief Sets whether selection can be skipped with a button.
* @param ui PselUiSettings struct.
* @param flag Flag value.
*/
NX_CONSTEXPR void pselUiSetSkipButtonEnabled(PselUiSettings *ui, bool flag) {
ui->settings.show_skip_button = flag!=0;
}
/**
* @brief Shows the applet with the specified UI settings.
* @param ui PselUiSettings struct.
* @param out_user Selected user ID.
* @note If user skips (see \ref pselUiSetSkipEnabled) this will return successfully but the output ID will be 0.
*/
Result pselUiShow(PselUiSettings *ui, AccountUid *out_user);
/**
* @brief This is the System version of \ref pselShowUserSelector.
* @note This uses \ref accountIsUserRegistrationRequestPermitted, hence \ref accountInitialize must be used prior to this. See also the docs for PselUserSelectionSettings::is_skip_enabled.
* @param[out] out_user Returned selected user ID.
* @param[in] settings \ref PselUserSelectionSettings
* @param[in] settings_system [2.0.0+] \ref PselUserSelectionSettingsForSystemService, ignored on prior versions.
*/
Result pselShowUserSelectorForSystem(AccountUid *out_user, const PselUserSelectionSettings *settings, const PselUserSelectionSettingsForSystemService *settings_system);
/**
* @brief This is the Launcher version of \ref pselShowUserSelector.
* @note This uses \ref accountIsUserRegistrationRequestPermitted, hence \ref accountInitialize must be used prior to this. See also the docs for PselUserSelectionSettings::is_skip_enabled.
* @param[out] out_user Returned selected user ID.
* @param[in] settings \ref PselUserSelectionSettings
* @param[in] application_id ApplicationId
*/
Result pselShowUserSelectorForLauncher(AccountUid *out_user, const PselUserSelectionSettings *settings, u64 application_id);
/**
* @brief Shows the applet to select a user.
* @note This uses \ref accountIsUserRegistrationRequestPermitted, hence \ref accountInitialize must be used prior to this. See also the docs for PselUserSelectionSettings::is_skip_enabled.
* @param[out] out_user Returned selected user ID.
* @param[in] settings \ref PselUserSelectionSettings
*/
Result pselShowUserSelector(AccountUid *out_user, const PselUserSelectionSettings *settings);
/**
* @brief Shows the applet to create a user.
* @note This uses \ref accountIsUserRegistrationRequestPermitted, hence \ref accountInitialize must be used prior to this. If the output flag is 0, an error will be thrown.
*/
Result pselShowUserCreator(void);
/**
* @brief Shows the applet to change a user's icon.
* @param[in] user Input user ID.
*/
Result pselShowUserIconEditor(AccountUid user);
/**
* @brief Shows the applet to change a user's nickname.
* @param[in] user Input user ID.
*/
Result pselShowUserNicknameEditor(AccountUid user);
/**
* @brief Shows the applet to create a user. Used by the starter applet during system setup.
*/
Result pselShowUserCreatorForStarter(void);
/**
* @brief Shows the applet for Nintendo Account Nnid linking.
* @note Only available on [6.0.0+].
* @param[in] user Input user ID.
*/
Result pselShowNintendoAccountNnidLinker(AccountUid user);
/**
* @brief Shows the applet for UserQualificationPromoter.
* @note Only available on [13.0.0+].
* @param[in] user Input user ID.
*/
Result pselShowUserQualificationPromoter(AccountUid user);

View file

@ -0,0 +1,242 @@
## *
## @file psel.h
## @brief Wrapper for using the playerSelect (user selection) LibraryApplet.
## @author XorTroll, yellows8
## @copyright libnx Authors
##
import
../types, ../services/acc
## / playerSelect UI modes.
type
PselUiMode* = enum
PselUiModeUserSelector = 0, ## /< UserSelector
PselUiModeUserCreator = 1, ## /< UserCreator
PselUiModeEnsureNetworkServiceAccountAvailable = 2, ## /< EnsureNetworkServiceAccountAvailable
PselUiModeUserIconEditor = 3, ## /< UserIconEditor
PselUiModeUserNicknameEditor = 4, ## /< UserNicknameEditor
PselUiModeUserCreatorForStarter = 5, ## /< UserCreatorForStarter
PselUiModeNintendoAccountAuthorizationRequestContext = 6, ## /< NintendoAccountAuthorizationRequestContext
PselUiModeIntroduceExternalNetworkServiceAccount = 7, ## /< IntroduceExternalNetworkServiceAccount
PselUiModeIntroduceExternalNetworkServiceAccountForRegistration = 8, ## /< [6.0.0+] IntroduceExternalNetworkServiceAccountForRegistration
PselUiModeNintendoAccountNnidLinker = 9, ## /< [6.0.0+] NintendoAccountNnidLinker
PselUiModeLicenseRequirementsForNetworkService = 10, ## /< [6.0.0+] LicenseRequirementsForNetworkService
PselUiModeLicenseRequirementsForNetworkServiceWithUserContextImpl = 11, ## /< [7.0.0+] LicenseRequirementsForNetworkServiceWithUserContextImpl
PselUiModeUserCreatorForImmediateNaLoginTest = 12, ## /< [7.0.0+] UserCreatorForImmediateNaLoginTest
PselUiModeUserQualificationPromoter = 13 ## /< [13.0.0+] UserQualificationPromoter
## / UI message text to display with ::PselUiMode_UserSelector. Invalid values are handled as ::PselUserSelectionPurpose_General.
type
PselUserSelectionPurpose* = enum
PselUserSelectionPurposeGeneral = 0, ## /< "Select a user."
PselUserSelectionPurposeGameCardRegistration = 1, ## /< [2.0.0+] "Who will receive the points?"
PselUserSelectionPurposeEShopLaunch = 2, ## /< [2.0.0+] "Who is using Nintendo eShop?"
PselUserSelectionPurposeEShopItemShow = 3, ## /< [2.0.0+] "Who is making this purchase?"
PselUserSelectionPurposePicturePost = 4, ## /< [2.0.0+] "Who is posting?"
PselUserSelectionPurposeNintendoAccountLinkage = 5, ## /< [2.0.0+] "Select a user to link to a Nintendo Account."
PselUserSelectionPurposeSettingsUpdate = 6, ## /< [2.0.0+] "Change settings for which user?"
PselUserSelectionPurposeSaveDataDeletion = 7, ## /< [2.0.0+] "Format data for which user?"
PselUserSelectionPurposeUserMigration = 8, ## /< [4.0.0+] "Which user will be transferred to another console?"
PselUserSelectionPurposeSaveDataTransfer = 9 ## /< [8.0.0+] "Send save data for which user?"
## / NintendoAccountStartupDialogType
type
PselNintendoAccountStartupDialogType* = enum
PselNintendoAccountStartupDialogTypeLoginAndCreate = 0, ## /< LoginAndCreate
PselNintendoAccountStartupDialogTypeLogin = 1, ## /< Login
PselNintendoAccountStartupDialogTypeCreate = 2 ## /< Create
## / Base UI settings for playerSelect.
type
PselUiSettingsV1* {.bycopy.} = object
mode*: U32 ## /< \ref PselUiMode
pad*: U32 ## /< Padding.
invalidUidList*: array[Acc_User_List_Size, AccountUid] ## /< List of \ref AccountUid. TODO: This is only correct for ::PselUiMode_UserSelector, for other modes this is a single uid, followed by mode-specific data (if any).
applicationId*: U64 ## /< ApplicationId with \ref pselShowUserSelectorForLauncher.
isNetworkServiceAccountRequired*: U8 ## /< PselUserSelectionSettings::is_network_service_account_required.
isSkipEnabled*: U8 ## /< PselUserSelectionSettings::is_skip_enabled
unkX92*: U8 ## /< Set to value 1 by \ref pselShowUserSelectorForSystem / \ref pselShowUserSelectorForLauncher.
isPermitted*: U8 ## /< isPermitted. With ::PselUiMode_UserSelector: enables the option to create a new user. Set to the output from \ref accountIsUserRegistrationRequestPermitted with pselShowUserSelector*. When not set, a dialog will be displayed when the user attempts to create an user.
showSkipButton*: U8 ## /< PselUserSelectionSettings::show_skip_button
additionalSelect*: U8 ## /< PselUserSelectionSettings::additional_select
unkX96*: U8 ## /< [2.0.0+] Set to PselUserSelectionSettingsForSystemService::enable_user_creation_button. \ref pselShowUserSelectorForLauncher / \ref pselShowUserSelector sets this to value 1.
unkX97*: U8 ## /< [6.0.0+] Set to PselUserSelectionSettings::is_unqualified_user_selectable ^ 1.
## / UI settings for versions starting with 0x10000.
type
PselUiSettings* {.bycopy.} = object
settings*: PselUiSettingsV1 ## /< \ref PselUiSettingsV1
unkX98*: U32 ## /< [2.0.0+] Set to PselUserSelectionSettingsForSystemService::purpose.
unkX9c*: array[0x4, U8] ## /< Unknown.
## / UserSelectionSettings
type
PselUserSelectionSettings* {.bycopy.} = object
invalidUidList*: array[Acc_User_List_Size, AccountUid] ## /< invalidUidList.
isSkipEnabled*: U8 ## /< isSkipEnabled. When set, the first user in invalid_uid_list must not be set, and additional_select must be 0. When enabled \ref accountTrySelectUserWithoutInteraction will be used to select the user, in this case the applet will only be launched if \ref accountTrySelectUserWithoutInteraction doesn't return an user.
isNetworkServiceAccountRequired*: U8 ## /< isNetworkServiceAccountRequired. Whether the user needs to be linked to a Nintendo account.
showSkipButton*: U8 ## /< showSkipButton. Enables the option to skip user selection with a button.
additionalSelect*: U8 ## /< additionalSelect.
isUnqualifiedUserSelectable*: U8 ## /< [6.0.0+] isUnqualifiedUserSelectable
## / [2.0.0+] UserSelectionSettingsForSystemService
type
PselUserSelectionSettingsForSystemService* {.bycopy.} = object
purpose*: U32 ## /< \ref PselUserSelectionPurpose
enableUserCreationButton*: U8 ## /< Enables the user-creation button when set. Whether user-creation when pressing the button is actually allowed is controlled by PselUiSettingsV1::is_permitted.
pad*: array[0x3, U8] ## /< Padding.
## / Return data sent after execution.
type
PselUiReturnArg* {.bycopy.} = object
res*: Result ## /< Result.
userId*: AccountUid ## /< Selected \ref AccountUid.
proc pselUiCreate*(ui: ptr PselUiSettings; mode: PselUiMode): Result {.cdecl,
importc: "pselUiCreate".}
## *
## @brief Creates a new UI config for the playerSelect applet with the specified mode.
## @param ui PseluiSettings struct.
## @param mode playerSelect UI mode.
##
proc pselUiAddUser*(ui: ptr PselUiSettings; userId: AccountUid) {.cdecl,
importc: "pselUiAddUser".}
## *
## @brief Adds an user to the user list of the applet.
## @param ui PselUiSettings struct.
## @param[in] user_id user ID.
## @note The users will be treated as invalid users for user selection mode, and as the input user for other modes.
##
proc pselUiSetAllowUserCreation*(ui: ptr PselUiSettings; flag: bool) {.inline, cdecl.} =
## *
## @brief Sets whether users can be created in the applet.
## @param ui PselUiSettings struct.
## @param flag Flag value.
## @note Only used for ::PselUiMode_SelectUser.
##
if ui.settings.mode == PselUiModeUserSelector.U32:
ui.settings.isPermitted = flag.U8
proc pselUiSetNetworkServiceRequired*(ui: ptr PselUiSettings; flag: bool) {.inline,
cdecl.} =
## *
## @brief Sets whether users need to be linked to a Nintendo account.
## @param ui PselUiSettings struct.
## @param flag Flag value.
##
ui.settings.isNetworkServiceAccountRequired = flag.U8
proc pselUiSetSkipButtonEnabled*(ui: ptr PselUiSettings; flag: bool) {.inline, cdecl.} =
## *
## @brief Sets whether selection can be skipped with a button.
## @param ui PselUiSettings struct.
## @param flag Flag value.
##
ui.settings.showSkipButton = flag.U8
proc pselUiShow*(ui: ptr PselUiSettings; outUser: ptr AccountUid): Result {.cdecl,
importc: "pselUiShow".}
## *
## @brief Shows the applet with the specified UI settings.
## @param ui PselUiSettings struct.
## @param out_user Selected user ID.
## @note If user skips (see \ref pselUiSetSkipEnabled) this will return successfully but the output ID will be 0.
##
proc pselShowUserSelectorForSystem*(outUser: ptr AccountUid;
settings: ptr PselUserSelectionSettings;
settingsSystem: ptr PselUserSelectionSettingsForSystemService): Result {.cdecl,
importc: "pselShowUserSelectorForSystem".}
## *
## @brief This is the System version of \ref pselShowUserSelector.
## @note This uses \ref accountIsUserRegistrationRequestPermitted, hence \ref accountInitialize must be used prior to this. See also the docs for PselUserSelectionSettings::is_skip_enabled.
## @param[out] out_user Returned selected user ID.
## @param[in] settings \ref PselUserSelectionSettings
## @param[in] settings_system [2.0.0+] \ref PselUserSelectionSettingsForSystemService, ignored on prior versions.
##
proc pselShowUserSelectorForLauncher*(outUser: ptr AccountUid;
settings: ptr PselUserSelectionSettings;
applicationId: U64): Result {.cdecl,
importc: "pselShowUserSelectorForLauncher".}
## *
## @brief This is the Launcher version of \ref pselShowUserSelector.
## @note This uses \ref accountIsUserRegistrationRequestPermitted, hence \ref accountInitialize must be used prior to this. See also the docs for PselUserSelectionSettings::is_skip_enabled.
## @param[out] out_user Returned selected user ID.
## @param[in] settings \ref PselUserSelectionSettings
## @param[in] application_id ApplicationId
##
proc pselShowUserSelector*(outUser: ptr AccountUid;
settings: ptr PselUserSelectionSettings): Result {.cdecl,
importc: "pselShowUserSelector".}
## *
## @brief Shows the applet to select a user.
## @note This uses \ref accountIsUserRegistrationRequestPermitted, hence \ref accountInitialize must be used prior to this. See also the docs for PselUserSelectionSettings::is_skip_enabled.
## @param[out] out_user Returned selected user ID.
## @param[in] settings \ref PselUserSelectionSettings
##
proc pselShowUserCreator*(): Result {.cdecl, importc: "pselShowUserCreator".}
## *
## @brief Shows the applet to create a user.
## @note This uses \ref accountIsUserRegistrationRequestPermitted, hence \ref accountInitialize must be used prior to this. If the output flag is 0, an error will be thrown.
##
proc pselShowUserIconEditor*(user: AccountUid): Result {.cdecl,
importc: "pselShowUserIconEditor".}
## *
## @brief Shows the applet to change a user's icon.
## @param[in] user Input user ID.
##
proc pselShowUserNicknameEditor*(user: AccountUid): Result {.cdecl,
importc: "pselShowUserNicknameEditor".}
## *
## @brief Shows the applet to change a user's nickname.
## @param[in] user Input user ID.
##
proc pselShowUserCreatorForStarter*(): Result {.cdecl,
importc: "pselShowUserCreatorForStarter".}
## *
## @brief Shows the applet to create a user. Used by the starter applet during system setup.
##
proc pselShowNintendoAccountNnidLinker*(user: AccountUid): Result {.cdecl,
importc: "pselShowNintendoAccountNnidLinker".}
## *
## @brief Shows the applet for Nintendo Account Nnid linking.
## @note Only available on [6.0.0+].
## @param[in] user Input user ID.
##
proc pselShowUserQualificationPromoter*(user: AccountUid): Result {.cdecl,
importc: "pselShowUserQualificationPromoter".}
## *
## @brief Shows the applet for UserQualificationPromoter.
## @note Only available on [13.0.0+].
## @param[in] user Input user ID.
##

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,862 @@
/**
* @file web.h
* @brief Wrapper for using the web LibraryApplets. See also: https://switchbrew.org/wiki/Internet_Browser
* @author p-sam, yellows8
* @copyright libnx Authors
*/
#pragma once
#include "../types.h"
#include "../services/applet.h"
#include "../services/caps.h"
#include "../services/acc.h"
#include "../kernel/mutex.h"
/// This indicates the type of web-applet.
typedef enum {
WebShimKind_Shop = 1,
WebShimKind_Login = 2,
WebShimKind_Offline = 3,
WebShimKind_Share = 4,
WebShimKind_Web = 5,
WebShimKind_Wifi = 6,
WebShimKind_Lobby = 7,
} WebShimKind;
/// ExitReason
typedef enum {
WebExitReason_ExitButton = 0x0, ///< User pressed the X button to exit.
WebExitReason_BackButton = 0x1, ///< User pressed the B button to exit, on the initial page.
WebExitReason_Requested = 0x2, ///< The applet exited since \ref webConfigRequestExit was used.
WebExitReason_LastUrl = 0x3, ///< The applet exited due to LastUrl handling, see \ref webReplyGetLastUrl.
WebExitReason_ErrorDialog = 0x7, ///< The applet exited after displaying an error dialog.
WebExitReason_UnknownE = 0xE, ///< Unknown
} WebExitReason;
/// Button values for \ref webConfigSetBootFooterButtonVisible.
typedef enum {
WebFooterButtonId_None = 0, ///< None, for empty \ref WebBootFooterButtonEntry. Invalid for \ref webConfigSetBootFooterButtonVisible input.
WebFooterButtonId_Type1 = 1, ///< Unknown button Id 1.
WebFooterButtonId_Type2 = 2, ///< Unknown button Id 2.
WebFooterButtonId_Type3 = 3, ///< Unknown button Id 3.
WebFooterButtonId_Type4 = 4, ///< Unknown button Id 4.
WebFooterButtonId_Type5 = 5, ///< Unknown button Id 5.
WebFooterButtonId_Type6 = 6, ///< Unknown button Id 6.
WebFooterButtonId_Max, ///< Values starting with this are invalid.
} WebFooterButtonId;
/// WebSessionBootMode
typedef enum {
WebSessionBootMode_AllForeground = 0, ///< AllForeground. This is the default.
WebSessionBootMode_AllForegroundInitiallyHidden = 1, ///< AllForegroundInitiallyHidden
} WebSessionBootMode;
/// WebSessionSendMessageKind
typedef enum {
WebSessionSendMessageKind_BrowserEngineContent = 0x0, ///< BrowserEngine Content
WebSessionSendMessageKind_SystemMessageAppear = 0x100, ///< SystemMessage Appear
WebSessionSendMessageKind_Ack = 0x1000, ///< Ack
} WebSessionSendMessageKind;
/// WebSessionReceiveMessageKind
typedef enum {
WebSessionReceiveMessageKind_BrowserEngineContent = 0x0, ///< BrowserEngine Content
WebSessionReceiveMessageKind_AckBrowserEngine = 0x1000, ///< Ack BrowserEngine
WebSessionReceiveMessageKind_AckSystemMessage = 0x1001, ///< Ack SystemMessage
} WebSessionReceiveMessageKind;
/// Struct for the WebWifi applet input storage.
typedef struct {
u32 unk_x0; ///< Official sw sets this to 0 with appletStorageWrite, separately from the rest of the config struct.
char conntest_url[0x100]; ///< Connection-test URL.
char initial_url[0x400]; ///< Initial URL navigated to by the applet.
Uuid uuid; ///< NIFM Network UUID. Only used by the applet when conntest_url is set.
u32 rev; ///< Input value for nifm cmd SetRequirementByRevision. Only used by the applet when conntest_url is set.
} WebWifiPageArg;
/// Struct for the WebWifi applet output storage.
typedef struct {
u32 unk_x0; ///< Unknown.
Result res; ///< Result
} WebWifiReturnValue;
/// Config for WebWifi.
typedef struct {
WebWifiPageArg arg; ///< Arg data.
} WebWifiConfig;
/// TLV storage, starts with \ref WebArgHeader followed by \ref WebArgTLV entries.
typedef struct {
u8 data[0x2000]; ///< Raw TLV data storage.
} WebCommonTLVStorage;
/// Common struct for the applet output storage, for non-TLV-storage.
typedef struct {
WebExitReason exitReason; ///< ExitReason
u32 pad; ///< Padding
char lastUrl[0x1000]; ///< LastUrl string
u64 lastUrlSize; ///< Size of LastUrl, including NUL-terminator.
} PACKED WebCommonReturnValue;
/// Header struct at offset 0 in the web Arg storage (non-webWifi).
typedef struct {
u16 total_entries; ///< Total \ref WebArgTLV entries following this struct.
u16 pad; ///< Padding
WebShimKind shimKind; ///< ShimKind
} PACKED WebArgHeader;
/// Web TLV used in the web Arg storage.
typedef struct {
u16 type; ///< Type of this arg.
u16 size; ///< Size of the arg data following this struct.
u8 pad[4]; ///< Padding
} PACKED WebArgTLV;
/// Config struct for web applets, non-WebWifi.
typedef struct {
WebCommonTLVStorage arg; ///< TLV storage.
AppletId appletid; ///< AppletId
u32 version; ///< CommonArgs applet version.
AppletHolder holder; ///< AppletHolder
} WebCommonConfig;
/// Common container struct for applets' reply data, from the output storage.
typedef struct {
bool type; ///< Type of reply: false = ret, true = storage.
WebShimKind shimKind; ///< ShimKind
WebCommonReturnValue ret; ///< Reply data for reply=false.
WebCommonTLVStorage storage; ///< Reply data for reply=true.
} WebCommonReply;
/// Entry data for ::WebArgType_BootFooterButton.
typedef struct {
WebFooterButtonId id;
u8 visible;
u16 unk_x5;
u8 unk_x7;
} PACKED WebBootFooterButtonEntry;
/// StorageHandleQueue
typedef struct {
s32 read_pos;
s32 write_pos;
s32 max_storages;
bool is_full;
AppletStorage storages[0x10];
} WebSessionStorageHandleQueue;
/// WebSession
typedef struct {
Mutex mutex;
WebCommonConfig *config;
struct {
u32 count;
u32 cur_size;
} queue[2];
WebSessionStorageHandleQueue storage_queue;
} WebSession;
/// SessionMessageHeader
typedef struct {
u32 kind; ///< Message Kind (\ref WebSessionSendMessageKind / \ref WebSessionReceiveMessageKind)
u32 size; ///< Data size following the header.
u8 reserved[0x8]; ///< Unused
} WebSessionMessageHeader;
/// Types for \ref WebArgTLV, input storage.
typedef enum {
WebArgType_Url = 0x1, ///< [1.0.0+] String, size 0xC00. Initial URL.
WebArgType_CallbackUrl = 0x3, ///< [1.0.0+] String, size 0x400.
WebArgType_CallbackableUrl = 0x4, ///< [1.0.0+] String, size 0x400.
WebArgType_ApplicationId = 0x5, ///< [1.0.0+] Offline-applet, u64 ApplicationId
WebArgType_DocumentPath = 0x6, ///< [1.0.0+] Offline-applet, string with size 0xC00.
WebArgType_DocumentKind = 0x7, ///< [1.0.0+] Offline-applet, u32 enum \WebDocumentKind.
WebArgType_SystemDataId = 0x8, ///< [1.0.0+] Offline-applet, u64 SystemDataId
WebArgType_ShareStartPage = 0x9, ///< [1.0.0+] u32 enum \WebShareStartPage
WebArgType_Whitelist = 0xA, ///< [1.0.0+] String, size 0x1000.
WebArgType_NewsFlag = 0xB, ///< [1.0.0+] u8 bool
WebArgType_UnknownC = 0xC, ///< [1.0.0+] u8
WebArgType_UnknownD = 0xD, ///< [1.0.0+] u8
WebArgType_Uid = 0xE, ///< [1.0.0+] \ref AccountUid, controls which user-specific savedata to mount.
WebArgType_AlbumEntry0 = 0xF, ///< [1.0.0+] Share-applet caps AlbumEntry, entry 0.
WebArgType_ScreenShot = 0x10, ///< [1.0.0+] u8 bool
WebArgType_EcClientCert = 0x11, ///< [1.0.0+] u8 bool
WebArgType_Unknown12 = 0x12, ///< [1.0.0+] u8
WebArgType_PlayReport = 0x13, ///< [1.0.0+] u8 bool
WebArgType_Unknown14 = 0x14, ///< [1.0.0+] u8
WebArgType_Unknown15 = 0x15, ///< [1.0.0+] u8
WebArgType_BootDisplayKind = 0x17, ///< [1.0.0+] u32 enum \ref WebBootDisplayKind
WebArgType_BackgroundKind = 0x18, ///< [1.0.0+] u32 enum \ref WebBackgroundKind
WebArgType_Footer = 0x19, ///< [1.0.0+] u8 bool
WebArgType_Pointer = 0x1A, ///< [1.0.0+] u8 bool
WebArgType_LeftStickMode = 0x1B, ///< [1.0.0+] u32 enum \ref WebLeftStickMode
WebArgType_KeyRepeatFrame0 = 0x1C, ///< [1.0.0+] s32 KeyRepeatFrame, first param
WebArgType_KeyRepeatFrame1 = 0x1D, ///< [1.0.0+] s32 KeyRepeatFrame, second param
WebArgType_BootAsMediaPlayerInverted = 0x1E, ///< [1.0.0+] u8 bool. With News on [3.0.0+] this is set after BootAsMediaPlayer with the value inverted.
WebArgType_DisplayUrlKind = 0x1F, ///< [1.0.0+] u8 bool, DisplayUrlKind (value = (input_enumval==0x1)).
WebArgType_BootAsMediaPlayer = 0x21, ///< [2.0.0+] u8 bool
WebArgType_ShopJump = 0x22, ///< [2.0.0+] u8 bool
WebArgType_MediaPlayerUserGestureRestriction = 0x23, ///< [2.0.0-5.1.0] u8 bool
WebArgType_MediaAutoPlay = 0x23, ///< [6.0.0+] u8 bool
WebArgType_LobbyParameter = 0x24, ///< [2.0.0+] String, size 0x100.
WebArgType_ApplicationAlbumEntry = 0x26, ///< [3.0.0+] Share-applet caps ApplicationAlbumEntry
WebArgType_JsExtension = 0x27, ///< [3.0.0+] u8 bool
WebArgType_AdditionalCommentText = 0x28, ///< [4.0.0+] String, size 0x100. Share-applet AdditionalCommentText.
WebArgType_TouchEnabledOnContents = 0x29, ///< [4.0.0+] u8 bool
WebArgType_UserAgentAdditionalString = 0x2A, ///< [4.0.0+] String, size 0x80.
WebArgType_AdditionalMediaData0 = 0x2B, ///< [4.0.0+] Share-applet 0x10-byte u8 array, AdditionalMediaData. Entry 0. If the user-input size is less than 0x10, the remaining data used for the TLV is cleared.
WebArgType_MediaPlayerAutoClose = 0x2C, ///< [4.0.0+] u8 bool
WebArgType_PageCache = 0x2D, ///< [4.0.0+] u8 bool
WebArgType_WebAudio = 0x2E, ///< [4.0.0+] u8 bool
WebArgType_2F = 0x2F, ///< [5.0.0+] u8
WebArgType_YouTubeVideoFlag = 0x31, ///< [5.0.0+] u8 bool Indicates that the built-in whitelist for YouTubeVideo should be used.
WebArgType_FooterFixedKind = 0x32, ///< [5.0.0+] u32 enum \ref WebFooterFixedKind
WebArgType_PageFade = 0x33, ///< [5.0.0+] u8 bool
WebArgType_MediaCreatorApplicationRatingAge = 0x34, ///< [5.0.0+] Share-applet 0x20-byte s8 array, MediaCreatorApplicationRatingAge.
WebArgType_BootLoadingIcon = 0x35, ///< [5.0.0+] u8 bool
WebArgType_PageScrollIndicator = 0x36, ///< [5.0.0+] u8 bool
WebArgType_MediaPlayerSpeedControl = 0x37, ///< [6.0.0+] u8 bool
WebArgType_AlbumEntry1 = 0x38, ///< [6.0.0+] Share-applet caps AlbumEntry, entry 1.
WebArgType_AlbumEntry2 = 0x39, ///< [6.0.0+] Share-applet caps AlbumEntry, entry 2.
WebArgType_AlbumEntry3 = 0x3A, ///< [6.0.0+] Share-applet caps AlbumEntry, entry 3.
WebArgType_AdditionalMediaData1 = 0x3B, ///< [6.0.0+] Share-applet 0x10-byte u8 array, AdditionalMediaData. Entry 1.
WebArgType_AdditionalMediaData2 = 0x3C, ///< [6.0.0+] Share-applet 0x10-byte u8 array, AdditionalMediaData. Entry 2.
WebArgType_AdditionalMediaData3 = 0x3D, ///< [6.0.0+] Share-applet 0x10-byte u8 array, AdditionalMediaData. Entry 3.
WebArgType_BootFooterButton = 0x3E, ///< [6.0.0+] Array of \ref WebBootFooterButtonEntry with 0x10 entries.
WebArgType_OverrideWebAudioVolume = 0x3F, ///< [6.0.0+] float
WebArgType_OverrideMediaAudioVolume = 0x40, ///< [6.0.0+] float
WebArgType_SessionBootMode = 0x41, ///< [7.0.0+] u32 enum \ref WebSessionBootMode
WebArgType_SessionFlag = 0x42, ///< [7.0.0+] u8 bool, enables using WebSession when set.
WebArgType_MediaPlayerUi = 0x43, ///< [8.0.0+] u8 bool
WebArgType_TransferMemory = 0x44, ///< [11.0.0+] u8 bool
} WebArgType;
/// Types for \ref WebArgTLV, output storage.
typedef enum {
WebReplyType_ExitReason = 0x1, ///< [3.0.0+] u32 ExitReason
WebReplyType_LastUrl = 0x2, ///< [3.0.0+] string
WebReplyType_LastUrlSize = 0x3, ///< [3.0.0+] u64
WebReplyType_SharePostResult = 0x4, ///< [3.0.0+] u32 SharePostResult
WebReplyType_PostServiceName = 0x5, ///< [3.0.0+] string
WebReplyType_PostServiceNameSize = 0x6, ///< [3.0.0+] u64
WebReplyType_PostId = 0x7, ///< [3.0.0+] string
WebReplyType_PostIdSize = 0x8, ///< [3.0.0+] u64
WebReplyType_MediaPlayerAutoClosedByCompletion = 0x9, ///< [8.0.0+] u8 bool
} WebReplyType;
/// This controls the kind of content to mount with Offline-applet.
typedef enum {
WebDocumentKind_OfflineHtmlPage = 0x1, ///< Use the HtmlDocument NCA content from the application.
WebDocumentKind_ApplicationLegalInformation = 0x2, ///< Use the LegalInformation NCA content from the application.
WebDocumentKind_SystemDataPage = 0x3, ///< Use the Data NCA content from the specified SystemData, see also: https://switchbrew.org/wiki/Title_list#System_Data_Archives
} WebDocumentKind;
/// This controls the initial page for ShareApplet, used by \ref webShareCreate.
typedef enum {
WebShareStartPage_Default = 0, ///< The default "/" page.
WebShareStartPage_Settings = 1, ///< The "/settings/" page.
} WebShareStartPage;
/// Kind values for \ref webConfigSetBootDisplayKind. Controls the background color while displaying the loading screen during applet boot. Also controls the BackgroundKind when value is non-zero.
typedef enum {
WebBootDisplayKind_Default = 0, ///< Default. BackgroundKind is controlled by \ref WebBackgroundKind.
WebBootDisplayKind_White = 1, ///< White background. Used by \ref webOfflineCreate for docKind ::WebDocumentKind_ApplicationLegalInformation/::WebDocumentKind_SystemDataPage.
WebBootDisplayKind_Black = 2, ///< Black background.
WebBootDisplayKind_Unknown3 = 3, ///< Unknown. Used by \ref webShareCreate.
WebBootDisplayKind_Unknown4 = 4, ///< Unknown. Used by \ref webLobbyCreate.
} WebBootDisplayKind;
/// Kind values for \ref webConfigSetBackgroundKind. Controls the background color while displaying the loading screen during applet boot. Only used when \ref WebBootDisplayKind is ::WebBootDisplayKind_Default. If the applet was not launched by an Application, the applet will only use WebBackgroundKind_Default.
typedef enum {
WebBackgroundKind_Default = 0, ///< Default. Same as ::WebBootDisplayKind_White/::WebBootDisplayKind_Black, determined via ::WebArgType_BootAsMediaPlayer.
WebBackgroundKind_Unknown1 = 1, ///< Unknown. Same as ::WebBootDisplayKind_Unknown3.
WebBackgroundKind_Unknown2 = 2, ///< Unknown. Same as ::WebBootDisplayKind_Unknown4. Used by \ref webLobbyCreate.
} WebBackgroundKind;
/// Mode values for \ref webConfigSetLeftStickMode. Controls the initial mode, this can be toggled by the user via the pressing the left-stick button. If the Pointer flag is set to false (\ref webConfigSetPointer), only ::WebLeftStickMode_Cursor will be used and mode toggle by the user is disabled (input value ignored).
typedef enum {
WebLeftStickMode_Pointer = 0, ///< The user can directly control the pointer via the left-stick.
WebLeftStickMode_Cursor = 1, ///< The user can only select elements on the page via the left-stick.
} WebLeftStickMode;
/// Kind values for \ref webConfigSetFooterFixedKind. Controls UI footer display behaviour.
typedef enum {
WebFooterFixedKind_Default = 0, ///< Default. Footer is hidden while scrolling.
WebFooterFixedKind_Always = 1, ///< Footer is always displayed regardless of scrolling.
WebFooterFixedKind_Hidden = 2, ///< Footer is hidden regardless of scrolling.
} WebFooterFixedKind;
/**
* @brief Creates the config for WifiWebAuthApplet. This is the captive portal applet.
* @param config WebWifiConfig object.
* @param conntest_url URL used for the connection-test requests. When empty/NULL the applet will test the connection with nifm and throw an error on failure.
* @param initial_url Initial URL navigated to by the applet.
* @param uuid NIFM Network UUID, for nifm cmd SetNetworkProfileId. Value 0 can be used. Only used by the applet when conntest_url is set.
* @param rev Input value for nifm cmd SetRequirementByRevision. Value 0 can be used. Only used by the applet when conntest_url is set.
*/
void webWifiCreate(WebWifiConfig* config, const char* conntest_url, const char* initial_url, Uuid uuid, u32 rev);
/**
* @brief Launches WifiWebAuthApplet with the specified config and waits for it to exit.
* @param config WebWifiConfig object.
* @param out Optional output applet reply data, can be NULL.
*/
Result webWifiShow(WebWifiConfig* config, WebWifiReturnValue *out);
/**
* @brief Creates the config for WebApplet. This applet uses an URL whitelist loaded from the user-process host Application, which is only loaded when running under an Application.
* @note Sets ::WebArgType_UnknownD, and ::WebArgType_Unknown12 on pre-3.0.0, to value 1.
* @param config WebCommonConfig object.
* @param url Initial URL navigated to by the applet.
*/
Result webPageCreate(WebCommonConfig* config, const char* url);
/**
* @brief Creates the config for WebApplet. This is based on \ref webPageCreate, for News. Hence other functions referencing \ref webPageCreate also apply to this.
* @note The domain from the input URL is automatically whitelisted, in addition to any already loaded whitelist.
* @note Sets ::WebArgType_UnknownD to value 1, and sets ::WebArgType_NewsFlag to true. Also uses \ref webConfigSetEcClientCert and \ref webConfigSetShopJump with flag=true.
* @param config WebCommonConfig object.
* @param url Initial URL navigated to by the applet.
*/
Result webNewsCreate(WebCommonConfig* config, const char* url);
/**
* @brief Creates the config for WebApplet. This is based on \ref webPageCreate, for YouTubeVideo. Hence other functions referencing \ref webPageCreate also apply to this. This uses a whitelist which essentially only allows youtube embed/ URLs (without mounting content from the host Application).
* @note This is only available on [5.0.0+].
* @note Sets ::WebArgType_UnknownD to value 1, and sets ::WebArgType_YouTubeVideoFlag to true. Also uses \ref webConfigSetBootAsMediaPlayer with flag=true.
* @param config WebCommonConfig object.
* @param url Initial URL navigated to by the applet.
*/
Result webYouTubeVideoCreate(WebCommonConfig* config, const char* url);
/**
* @brief Creates the config for Offline-applet. This applet uses data loaded from content.
* @note Uses \ref webConfigSetLeftStickMode with ::WebLeftStickMode_Cursor and sets ::WebArgType_BootAsMediaPlayerInverted to false. Uses \ref webConfigSetPointer with flag = docKind == ::WebDocumentKind_OfflineHtmlPage.
* @note For docKind ::WebDocumentKind_ApplicationLegalInformation / ::WebDocumentKind_SystemDataPage, uses \ref webConfigSetFooter with flag=true and \ref webConfigSetBackgroundKind with ::WebBackgroundKind_Default.
* @note For docKind ::WebDocumentKind_SystemDataPage, uses \ref webConfigSetBootDisplayKind with ::WebBootDisplayKind_White.
* @note Sets ::WebArgType_Unknown14/::WebArgType_Unknown15 to value 1. With docKind ::WebDocumentKind_ApplicationLegalInformation, uses \ref webConfigSetBootDisplayKind with ::WebBootDisplayKind_White.
* @note Sets ::WebArgType_UnknownC to value 1.
* @note With docKind ::WebDocumentKind_ApplicationLegalInformation, uses \ref webConfigSetEcClientCert with flag=true.
* @note With docKind ::WebDocumentKind_OfflineHtmlPage on pre-3.0.0, sets ::WebArgType_Unknown12 to value 1.
* @note Lastly, sets the TLVs as needed for the input params.
* @param config WebCommonConfig object.
* @param docKind \ref WebDocumentKind
* @param id Id to load the content from. With docKind = ::WebDocumentKind_OfflineHtmlPage, id=0 should be used to specify the user-process application (non-zero is ignored with this docKind).
* @param docPath Initial document path in RomFS, without the leading '/'. For ::WebDocumentKind_OfflineHtmlPage, this is relative to "html-document/" in RomFS. For the other docKind values, this is relative to "/" in RomFS. This path must contain ".htdocs/".
*/
Result webOfflineCreate(WebCommonConfig* config, WebDocumentKind docKind, u64 id, const char* docPath);
/**
* @brief Creates the config for ShareApplet. This applet is for social media posting/settings.
* @note If a non-zero uid isn't set with \ref webConfigSetUid prior to using \ref webConfigShow, the applet will launch the profile-selector applet to select an account.
* @note An error will be displayed if neither \ref webConfigSetAlbumEntry, nor \ref webConfigSetApplicationAlbumEntry, nor \ref webConfigAddAlbumEntryAndMediaData are used prior to using \ref webConfigShow, with ::WebShareStartPage_Default.
* @note Uses \ref webConfigSetLeftStickMode with ::WebLeftStickMode_Cursor, \ref webConfigSetUid with uid=0, \ref webConfigSetDisplayUrlKind with kind=true, and sets ::WebArgType_Unknown14/::WebArgType_Unknown15 to value 1. Uses \ref webConfigSetBootDisplayKind with ::WebBootDisplayKind_Unknown3.
* @param config WebCommonConfig object.
* @param page \ref WebShareStartPage
*/
Result webShareCreate(WebCommonConfig* config, WebShareStartPage page);
/**
* @brief Creates the config for LobbyApplet. This applet is for "Nintendo Switch Online Lounge".
* @note Only available on [2.0.0+].
* @note If a non-zero uid isn't set with \ref webConfigSetUid prior to using \ref webConfigShow, the applet will launch the profile-selector applet to select an account.
* @note Uses \ref webConfigSetLeftStickMode with ::WebLeftStickMode_Cursor, \ref webConfigSetPointer with flag=false on [3.0.0+], \ref webConfigSetUid with uid=0, and sets ::WebArgType_Unknown14/::WebArgType_Unknown15 to value 1. Uses \ref webConfigSetBootDisplayKind with ::WebBootDisplayKind_Unknown4, \ref webConfigSetBackgroundKind with ::WebBackgroundKind_Unknown2, and sets ::WebArgType_BootAsMediaPlayerInverted to false.
* @param config WebCommonConfig object.
*/
Result webLobbyCreate(WebCommonConfig* config);
/**
* @brief Sets the CallbackUrl. See also \ref webReplyGetLastUrl.
* @note With Offline-applet for LastUrl handling, it compares the domain with "localhost" instead.
* @note Only available with config created by \ref webPageCreate or with Share-applet.
* @param config WebCommonConfig object.
* @param url URL
*/
Result webConfigSetCallbackUrl(WebCommonConfig* config, const char* url);
/**
* @brief Sets the CallbackableUrl.
* @note Only available with config created by \ref webPageCreate.
* @param config WebCommonConfig object.
* @param url URL
*/
Result webConfigSetCallbackableUrl(WebCommonConfig* config, const char* url);
/**
* @brief Sets the whitelist.
* @note Only available with config created by \ref webPageCreate.
* @note If the whitelist isn't formatted properly, the applet will exit briefly after the applet is launched.
* @param config WebCommonConfig object.
* @param whitelist Whitelist string, each line is a regex for each whitelisted URL.
*/
Result webConfigSetWhitelist(WebCommonConfig* config, const char* whitelist);
/**
* @brief Sets the account uid. Controls which user-specific savedata to mount.
* @note Only available with config created by \ref webPageCreate, \ref webLobbyCreate, or with Share-applet.
* @note Used automatically by \ref webShareCreate and \ref webLobbyCreate with uid=0.
* @param config WebCommonConfig object.
* @param uid \ref AccountUid
*/
Result webConfigSetUid(WebCommonConfig* config, AccountUid uid);
/**
* @brief Sets the Share CapsAlbumEntry.
* @note Only available with config created by \ref webShareCreate.
* @param config WebCommonConfig object.
* @param entry \ref CapsAlbumEntry
*/
Result webConfigSetAlbumEntry(WebCommonConfig* config, const CapsAlbumEntry *entry);
/**
* @brief Sets the ScreenShot flag, which controls whether screen-shot capture is allowed.
* @note Only available with config created by \ref webPageCreate.
* @param config WebCommonConfig object.
* @param flag Flag
*/
Result webConfigSetScreenShot(WebCommonConfig* config, bool flag);
/**
* @brief Sets the EcClientCert flag.
* @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate.
* @note Used automatically by \ref webOfflineCreate, depending on the docKind.
* @note Used automatically by \ref webNewsCreate with flag=true.
* @param config WebCommonConfig object.
* @param flag Flag
*/
Result webConfigSetEcClientCert(WebCommonConfig* config, bool flag);
/**
* @brief Sets whether PlayReport is enabled.
* @note Only available with config created by \ref webOfflineCreate.
* @param config WebCommonConfig object.
* @param flag Flag
*/
Result webConfigSetPlayReport(WebCommonConfig* config, bool flag);
/**
* @brief Sets the BootDisplayKind.
* @note Only available with config created by \ref webOfflineCreate, \ref webShareCreate, \ref webPageCreate, or \ref webLobbyCreate..
* @note Used automatically by \ref webOfflineCreate, depending on the docKind.
* @note Used automatically by \ref webShareCreate with kind=::WebBootDisplayKind_Unknown3.
* @note Used automatically by \ref webLobbyCreate with kind=::WebBootDisplayKind_Unknown4.
* @param config WebCommonConfig object.
* @param kind \ref WebBootDisplayKind
*/
Result webConfigSetBootDisplayKind(WebCommonConfig* config, WebBootDisplayKind kind);
/**
* @brief Sets the BackgroundKind.
* @note Only available with config created by \ref webOfflineCreate, \ref webPageCreate, or \ref webLobbyCreate.
* @note Used automatically by \ref webOfflineCreate, depending on the docKind.
* @note Used automatically by \ref webLobbyCreate with kind=2.
* @param config WebCommonConfig object.
* @param kind \ref WebBackgroundKind
*/
Result webConfigSetBackgroundKind(WebCommonConfig* config, WebBackgroundKind kind);
/**
* @brief Sets the whether the UI footer is enabled.
* @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate.
* @note Used automatically by \ref webOfflineCreate, depending on the docKind.
* @param config WebCommonConfig object.
* @param flag Flag
*/
Result webConfigSetFooter(WebCommonConfig* config, bool flag);
/**
* @brief Sets the whether the Pointer is enabled. See also \ref WebLeftStickMode.
* @note Only available with config created by \ref webOfflineCreate, \ref webPageCreate, or \ref webLobbyCreate.
* @note Used automatically by \ref webOfflineCreate.
* @note Used automatically by \ref webLobbyCreate with flag=false on [3.0.0+].
* @param config WebCommonConfig object.
* @param flag Flag
*/
Result webConfigSetPointer(WebCommonConfig* config, bool flag);
/**
* @brief Sets the LeftStickMode.
* @note Only available with config created by \ref webOfflineCreate, \ref webShareCreate, \ref webPageCreate, or \ref webLobbyCreate.
* @note Used automatically by \ref webOfflineCreate, \ref webShareCreate, and \ref webLobbyCreate with ::WebLeftStickMode_Cursor.
* @param config WebCommonConfig object.
* @param mode Mode, different enums for Web and Offline.
*/
Result webConfigSetLeftStickMode(WebCommonConfig* config, WebLeftStickMode mode);
/**
* @brief Sets the KeyRepeatFrame.
* @note Only available with config created by \ref webOfflineCreate.
* @param config WebCommonConfig object.
* @param inval0 First input param.
* @param inval1 Second input param.
*/
Result webConfigSetKeyRepeatFrame(WebCommonConfig* config, s32 inval0, s32 inval1);
/**
* @brief Sets the DisplayUrlKind.
* @note Only available with config created by \ref webShareCreate or \ref webPageCreate.
* @param config WebCommonConfig object.
* @note Used automatically by \ref webShareCreate with kind=true.
* @param kind Kind
*/
Result webConfigSetDisplayUrlKind(WebCommonConfig* config, bool kind);
/**
* @brief Sets the BootAsMediaPlayer flag.
* @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [2.0.0+].
* @note With config created by \ref webNewsCreate on [3.0.0+], this also sets ::WebArgType_BootAsMediaPlayerInverted to !flag.
* @param config WebCommonConfig object.
* @param flag Flag. true = BootAsMediaPlayer, false = BootAsWebPage.
*/
Result webConfigSetBootAsMediaPlayer(WebCommonConfig* config, bool flag);
/**
* @brief Sets the ShopJump flag.
* @note Only available with config created by \ref webPageCreate on [2.0.0+].
* @note Used automatically by \ref webNewsCreate with flag=true.
* @param config WebCommonConfig object.
* @param flag Flag
*/
Result webConfigSetShopJump(WebCommonConfig* config, bool flag);
/**
* @brief Sets the MediaPlayerUserGestureRestriction flag.
* @note Only available with config created by \ref webPageCreate on [2.0.0-5.1.0].
* @param config WebCommonConfig object.
* @param flag Flag
*/
Result webConfigSetMediaPlayerUserGestureRestriction(WebCommonConfig* config, bool flag);
/**
* @brief Sets whether MediaAutoPlay is enabled.
* @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [6.0.0+].
* @param config WebCommonConfig object.
* @param flag Flag
*/
Result webConfigSetMediaAutoPlay(WebCommonConfig* config, bool flag);
/**
* @brief Sets the LobbyParameter.
* @note Only available with config created by \ref webLobbyCreate.
* @param config WebCommonConfig object.
* @param str String
*/
Result webConfigSetLobbyParameter(WebCommonConfig* config, const char* str);
/**
* @brief Sets the Share CapsApplicationAlbumEntry.
* @note Only available with config created by \ref webShareCreate on [3.0.0+].
* @param config WebCommonConfig object.
* @param entry \ref CapsApplicationAlbumEntry, see also capssu.h.
*/
Result webConfigSetApplicationAlbumEntry(WebCommonConfig* config, CapsApplicationAlbumEntry *entry);
/**
* @brief Sets whether JsExtension is enabled.
* @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [3.0.0+].
* @param config WebCommonConfig object.
* @param flag Flag
*/
Result webConfigSetJsExtension(WebCommonConfig* config, bool flag);
/**
* @brief Sets the Share AdditionalCommentText.
* @note Only available with config created by \ref webShareCreate on [4.0.0+].
* @param config WebCommonConfig object.
* @param str String
*/
Result webConfigSetAdditionalCommentText(WebCommonConfig* config, const char* str);
/**
* @brief Sets the TouchEnabledOnContents flag.
* @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [4.0.0+].
* @param config WebCommonConfig object.
* @param flag Flag
*/
Result webConfigSetTouchEnabledOnContents(WebCommonConfig* config, bool flag);
/**
* @brief Sets the UserAgentAdditionalString. " " followed by this string are appended to the normal User-Agent string.
* @note Only available with config created by \ref webPageCreate on [4.0.0+].
* @param config WebCommonConfig object.
* @param str String
*/
Result webConfigSetUserAgentAdditionalString(WebCommonConfig* config, const char* str);
/**
* @brief Sets the Share AdditionalMediaData.
* @note Only available with config created by \ref webShareCreate on [4.0.0+].
* @param config WebCommonConfig object.
* @param data Input data
* @param size Size of the input data, max size is 0x10.
*/
Result webConfigSetAdditionalMediaData(WebCommonConfig* config, const u8* data, size_t size);
/**
* @brief Sets the MediaPlayerAutoClose flag.
* @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [4.0.0+].
* @param config WebCommonConfig object.
* @param flag Flag
*/
Result webConfigSetMediaPlayerAutoClose(WebCommonConfig* config, bool flag);
/**
* @brief Sets whether PageCache is enabled.
* @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [4.0.0+].
* @param config WebCommonConfig object.
* @param flag Flag
*/
Result webConfigSetPageCache(WebCommonConfig* config, bool flag);
/**
* @brief Sets whether WebAudio is enabled.
* @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [4.0.0+].
* @param config WebCommonConfig object.
* @param flag Flag
*/
Result webConfigSetWebAudio(WebCommonConfig* config, bool flag);
/**
* @brief Sets the FooterFixedKind.
* @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [5.0.0+].
* @param config WebCommonConfig object.
* @param kind \ref WebFooterFixedKind
*/
Result webConfigSetFooterFixedKind(WebCommonConfig* config, WebFooterFixedKind kind);
/**
* @brief Sets the PageFade flag.
* @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [5.0.0+].
* @param config WebCommonConfig object.
* @param flag Flag
*/
Result webConfigSetPageFade(WebCommonConfig* config, bool flag);
/**
* @brief Sets the Share MediaCreatorApplicationRatingAge.
* @note Only available with config created by \ref webShareCreate on [5.0.0+].
* @param config WebCommonConfig object.
* @param data 0x20-byte input data
*/
Result webConfigSetMediaCreatorApplicationRatingAge(WebCommonConfig* config, const s8 *data);
/**
* @brief Sets the BootLoadingIcon flag.
* @note Only available with config created by \ref webOfflineCreate on [5.0.0+].
* @param config WebCommonConfig object.
* @param flag Flag
*/
Result webConfigSetBootLoadingIcon(WebCommonConfig* config, bool flag);
/**
* @brief Sets the PageScrollIndicator flag.
* @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [5.0.0+].
* @param config WebCommonConfig object.
* @param flag Flag
*/
Result webConfigSetPageScrollIndicator(WebCommonConfig* config, bool flag);
/**
* @brief Sets whether MediaPlayerSpeedControl is enabled.
* @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [6.0.0+].
* @param config WebCommonConfig object.
* @param flag Flag
*/
Result webConfigSetMediaPlayerSpeedControl(WebCommonConfig* config, bool flag);
/**
* @brief Adds a pair of Share CapsAlbumEntry + optionally AdditionalMediaData. This can be used up to 4 times, for setting multiple pairs.
* @note Only available with config created by \ref webShareCreate on [6.0.0+].
* @param config WebCommonConfig object.
* @param entry \ref CapsAlbumEntry
* @param data Input data for AdditionalMediaData. Optional, can be NULL.
* @param size Size of the input data, max size is 0x10. Optional, can be 0.
*/
Result webConfigAddAlbumEntryAndMediaData(WebCommonConfig* config, const CapsAlbumEntry *entry, const u8* data, size_t size);
/**
* @brief Sets whether the specified BootFooterButton is visible.
* @note Only available with config created by \ref webOfflineCreate on [6.0.0+].
* @param config WebCommonConfig object.
* @param button \ref WebFooterButtonId
* @param visible Visible flag.
*/
Result webConfigSetBootFooterButtonVisible(WebCommonConfig* config, WebFooterButtonId button, bool visible);
/**
* @brief Sets OverrideWebAudioVolume.
* @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [6.0.0+].
* @param config WebCommonConfig object.
* @param value Value
*/
Result webConfigSetOverrideWebAudioVolume(WebCommonConfig* config, float value);
/**
* @brief Sets OverrideMediaAudioVolume.
* @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [6.0.0+].
* @param config WebCommonConfig object.
* @param value Value
*/
Result webConfigSetOverrideMediaAudioVolume(WebCommonConfig* config, float value);
/**
* @brief Sets \ref WebSessionBootMode.
* @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [7.0.0+].
* @param config WebCommonConfig object.
* @param mode \ref WebSessionBootMode
*/
Result webConfigSetBootMode(WebCommonConfig* config, WebSessionBootMode mode);
/**
* @brief Sets whether MediaPlayerUi is enabled.
* @note Only available with config created by \ref webOfflineCreate on [8.0.0+].
* @param config WebCommonConfig object.
* @param flag Flag
*/
Result webConfigSetMediaPlayerUi(WebCommonConfig* config, bool flag);
/**
* @brief Sets whether TransferMemory is enabled.
* @note Only available with config created by \ref webPageCreate on [11.0.0+].
* @param config WebCommonConfig object.
* @param flag Flag
*/
Result webConfigSetTransferMemory(WebCommonConfig* config, bool flag);
/**
* @brief Launches the {web applet} with the specified config and waits for it to exit.
* @param config WebCommonConfig object.
* @param out Optional output applet reply data, can be NULL.
*/
Result webConfigShow(WebCommonConfig* config, WebCommonReply *out);
/**
* @brief Request the applet to exit after \ref webConfigShow was used, while the applet is still running. This is for use from another thread.
* @param config WebCommonConfig object.
*/
Result webConfigRequestExit(WebCommonConfig* config);
/**
* @brief Gets the ExitReason from the specified reply.
* @param reply WebCommonReply object.
* @param exitReason Output \ref WebExitReason
*/
Result webReplyGetExitReason(WebCommonReply *reply, WebExitReason *exitReason);
/**
* @brief Gets the LastUrl from the specified reply. When the applet loads a page where the beginning of the URL matches the URL from \ref webConfigSetCallbackUrl, the applet will exit and set LastUrl to that URL (exit doesn't occur when \ref webConfigSetCallbackableUrl was used).
* @note This is only available with ::WebExitReason_LastUrl (string is empty otherwise).
* @note If you want to allocate a string buffer on heap, you can call this with outstr=NULL/outstr_maxsize=0 to get the out_size, then call it again with the allocated buffer.
* @param reply WebCommonReply object.
* @param outstr Output string buffer. If NULL, the string is not loaded.
* @param outstr_maxsize Size of the buffer, including NUL-terminator. If outstr is set, this size must be >1. The size used for the actual string-copy is this size-1, to make sure the output is NUL-terminated (the entire buffer is cleared first).
* @param out_size Output string length including NUL-terminator, for the original input string in the reply loaded from a separate size field.
*/
Result webReplyGetLastUrl(WebCommonReply *reply, char *outstr, size_t outstr_maxsize, size_t *out_size);
/**
* @brief Gets the SharePostResult from the specified reply.
* @note Only available with reply data from ShareApplet on [3.0.0+].
* @param reply WebCommonReply object.
* @param sharePostResult Output sharePostResult
*/
Result webReplyGetSharePostResult(WebCommonReply *reply, u32 *sharePostResult);
/**
* @brief Gets the PostServiceName from the specified reply.
* @note Only available with reply data from ShareApplet on [3.0.0+].
* @note If you want to allocate a string buffer on heap, you can call this with outstr=NULL/outstr_maxsize=0 to get the out_size, then call it again with the allocated buffer.
* @param reply WebCommonReply object.
* @param outstr Output string buffer. If NULL, the string is not loaded.
* @param outstr_maxsize Size of the buffer, including NUL-terminator. If outstr is set, this size must be >1. The size used for the actual string-copy is this size-1, to make sure the output is NUL-terminated (the entire buffer is cleared first).
* @param out_size Output string length including NUL-terminator, for the original input string in the reply loaded from a separate size field.
*/
Result webReplyGetPostServiceName(WebCommonReply *reply, char *outstr, size_t outstr_maxsize, size_t *out_size);
/**
* @brief Gets the PostId from the specified reply.
* @note Only available with reply data from ShareApplet on [3.0.0+].
* @note If you want to allocate a string buffer on heap, you can call this with outstr=NULL/outstr_maxsize=0 to get the out_size, then call it again with the allocated buffer.
* @param reply WebCommonReply object.
* @param outstr Output string buffer. If NULL, the string is not loaded.
* @param outstr_maxsize Size of the buffer, including NUL-terminator. If outstr is set, this size must be >1. The size used for the actual string-copy is this size-1, to make sure the output is NUL-terminated (the entire buffer is cleared first).
* @param out_size Output string length including NUL-terminator, for the original input string in the reply loaded from a separate size field.
*/
Result webReplyGetPostId(WebCommonReply *reply, char *outstr, size_t outstr_maxsize, size_t *out_size);
/**
* @brief Gets the MediaPlayerAutoClosedByCompletion flag from the specified reply.
* @note Only available with reply data from Web on [8.0.0+].
* @param reply WebCommonReply object.
* @param flag Output flag
*/
Result webReplyGetMediaPlayerAutoClosedByCompletion(WebCommonReply *reply, bool *flag);
/**
* @brief Creates a \ref WebSession object.
* @param s \ref WebSession
* @param config WebCommonConfig object.
*/
void webSessionCreate(WebSession *s, WebCommonConfig* config);
/**
* @brief Closes a \ref WebSession object.
* @param s \ref WebSession
*/
void webSessionClose(WebSession *s);
/**
* @brief Launches the applet for \ref WebSession.
* @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [7.0.0+].
* @note Do not use \ref webConfigShow when using WebSession.
* @param s \ref WebSession
* @param[out] out_event Output Event with autoclear=false, from \ref appletHolderGetExitEvent. Optional, can be NULL.
*/
Result webSessionStart(WebSession *s, Event **out_event);
/**
* @brief Waits for the applet to exit.
* @note This must be used before \ref webSessionClose, when \ref webSessionStart was used successfully.
* @param s \ref WebSession
* @param out Optional output applet reply data, can be NULL.
*/
Result webSessionWaitForExit(WebSession *s, WebCommonReply *out);
/**
* @brief Request the applet to exit.
* @note Use this instead of \ref webConfigRequestExit, when using WebSession.
* @param s \ref WebSession
*/
Result webSessionRequestExit(WebSession *s);
/**
* @brief Request the applet to Appear, this is only needed with ::WebSessionBootMode_AllForegroundInitiallyHidden.
* @note This should not be used before \ref webSessionStart.
* @param s \ref WebSession
* @param[out] flag Whether the message was sent successfully.
*/
Result webSessionAppear(WebSession *s, bool *flag);
/**
* @brief TrySendContentMessage
* @note This should not be used before \ref webSessionStart.
* @note The JS-side for this is only available when JsExtension is enabled via \ref webConfigSetJsExtension.
* @note The JS-side may ignore this if it's sent too soon after the applet launches.
* @param s \ref WebSession
* @param[in] content Input content NUL-terminated string.
* @param[in] size Size of content.
* @param[out] flag Whether the message was sent successfully.
*/
Result webSessionTrySendContentMessage(WebSession *s, const char *content, u32 size, bool *flag);
/**
* @brief TryReceiveContentMessage
* @note This should not be used before \ref webSessionStart.
* @note The JS-side for this is only available when JsExtension is enabled via \ref webConfigSetJsExtension.
* @param s \ref WebSession
* @param[out] content Output content string, always NUL-terminated.
* @param[in] size Max size of content.
* @param[out] out_size Original content size, prior to being clamped to the specified size param.
* @param[out] flag Whether the message was received successfully.
*/
Result webSessionTryReceiveContentMessage(WebSession *s, char *content, u64 size, u64 *out_size, bool *flag);

View file

@ -0,0 +1,990 @@
## *
## @file web.h
## @brief Wrapper for using the web LibraryApplets. See also: https://switchbrew.org/wiki/Internet_Browser
## @author p-sam, yellows8
## @copyright libnx Authors
##
import
../types, ../services/applet, ../services/caps, ../services/acc, ../kernel/mutex, ../kernel/event
## / This indicates the type of web-applet.
type
WebShimKind* = enum
WebShimKindShop = 1, WebShimKindLogin = 2, WebShimKindOffline = 3,
WebShimKindShare = 4, WebShimKindWeb = 5, WebShimKindWifi = 6, WebShimKindLobby = 7
## / ExitReason
type
WebExitReason* = enum
WebExitReasonExitButton = 0x0, ## /< User pressed the X button to exit.
WebExitReasonBackButton = 0x1, ## /< User pressed the B button to exit, on the initial page.
WebExitReasonRequested = 0x2, ## /< The applet exited since \ref webConfigRequestExit was used.
WebExitReasonLastUrl = 0x3, ## /< The applet exited due to LastUrl handling, see \ref webReplyGetLastUrl.
WebExitReasonErrorDialog = 0x7, ## /< The applet exited after displaying an error dialog.
WebExitReasonUnknownE = 0xE ## /< Unknown
## / Button values for \ref webConfigSetBootFooterButtonVisible.
type
WebFooterButtonId* = enum
WebFooterButtonIdNone = 0, ## /< None, for empty \ref WebBootFooterButtonEntry. Invalid for \ref webConfigSetBootFooterButtonVisible input.
WebFooterButtonIdType1 = 1, ## /< Unknown button Id 1.
WebFooterButtonIdType2 = 2, ## /< Unknown button Id 2.
WebFooterButtonIdType3 = 3, ## /< Unknown button Id 3.
WebFooterButtonIdType4 = 4, ## /< Unknown button Id 4.
WebFooterButtonIdType5 = 5, ## /< Unknown button Id 5.
WebFooterButtonIdType6 = 6, ## /< Unknown button Id 6.
WebFooterButtonIdMax ## /< Values starting with this are invalid.
## / WebSessionBootMode
type
WebSessionBootMode* = enum
WebSessionBootModeAllForeground = 0, ## /< AllForeground. This is the default.
WebSessionBootModeAllForegroundInitiallyHidden = 1 ## /< AllForegroundInitiallyHidden
## / WebSessionSendMessageKind
type
WebSessionSendMessageKind* = enum
WebSessionSendMessageKindBrowserEngineContent = 0x0, ## /< BrowserEngine Content
WebSessionSendMessageKindSystemMessageAppear = 0x100, ## /< SystemMessage Appear
WebSessionSendMessageKindAck = 0x1000 ## /< Ack
## / WebSessionReceiveMessageKind
type
WebSessionReceiveMessageKind* = enum
WebSessionReceiveMessageKindBrowserEngineContent = 0x0, ## /< BrowserEngine Content
WebSessionReceiveMessageKindAckBrowserEngine = 0x1000, ## /< Ack BrowserEngine
WebSessionReceiveMessageKindAckSystemMessage = 0x1001 ## /< Ack SystemMessage
## / Struct for the WebWifi applet input storage.
type
WebWifiPageArg* {.bycopy.} = object
unkX0*: U32 ## /< Official sw sets this to 0 with appletStorageWrite, separately from the rest of the config struct.
conntestUrl*: array[0x100, char] ## /< Connection-test URL.
initialUrl*: array[0x400, char] ## /< Initial URL navigated to by the applet.
uuid*: Uuid ## /< NIFM Network UUID. Only used by the applet when conntest_url is set.
rev*: U32 ## /< Input value for nifm cmd SetRequirementByRevision. Only used by the applet when conntest_url is set.
## / Struct for the WebWifi applet output storage.
type
WebWifiReturnValue* {.bycopy.} = object
unkX0*: U32 ## /< Unknown.
res*: Result ## /< Result
## / Config for WebWifi.
type
WebWifiConfig* {.bycopy.} = object
arg*: WebWifiPageArg ## /< Arg data.
## / TLV storage, starts with \ref WebArgHeader followed by \ref WebArgTLV entries.
type
WebCommonTLVStorage* {.bycopy.} = object
data*: array[0x2000, U8] ## /< Raw TLV data storage.
## / Common struct for the applet output storage, for non-TLV-storage.
type
WebCommonReturnValue* {.bycopy.} = object
exitReason*: WebExitReason ## /< ExitReason
pad*: U32 ## /< Padding
lastUrl*: array[0x1000, char] ## /< LastUrl string
lastUrlSize*: U64 ## /< Size of LastUrl, including NUL-terminator.
## / Header struct at offset 0 in the web Arg storage (non-webWifi).
type
WebArgHeader* {.bycopy.} = object
totalEntries*: U16 ## /< Total \ref WebArgTLV entries following this struct.
pad*: U16 ## /< Padding
shimKind*: WebShimKind ## /< ShimKind
## / Web TLV used in the web Arg storage.
type
WebArgTLV* {.bycopy.} = object
`type`*: U16 ## /< Type of this arg.
size*: U16 ## /< Size of the arg data following this struct.
pad*: array[4, U8] ## /< Padding
## / Config struct for web applets, non-WebWifi.
type
WebCommonConfig* {.bycopy.} = object
arg*: WebCommonTLVStorage ## /< TLV storage.
appletid*: AppletId ## /< AppletId
version*: U32 ## /< CommonArgs applet version.
holder*: AppletHolder ## /< AppletHolder
## / Common container struct for applets' reply data, from the output storage.
type
WebCommonReply* {.bycopy.} = object
`type`*: bool ## /< Type of reply: false = ret, true = storage.
shimKind*: WebShimKind ## /< ShimKind
ret*: WebCommonReturnValue ## /< Reply data for reply=false.
storage*: WebCommonTLVStorage ## /< Reply data for reply=true.
## / Entry data for ::WebArgType_BootFooterButton.
type
WebBootFooterButtonEntry* {.bycopy.} = object
id*: WebFooterButtonId
visible*: U8
unkX5*: U16
unkX7*: U8
## / StorageHandleQueue
type
WebSessionStorageHandleQueue* {.bycopy.} = object
readPos*: S32
writePos*: S32
maxStorages*: S32
isFull*: bool
storages*: array[0x10, AppletStorage]
## / WebSession
type
INNER_C_STRUCT_web_1* {.bycopy.} = object
count*: U32
curSize*: U32
WebSession* {.bycopy.} = object
mutex*: Mutex
config*: ptr WebCommonConfig
queue*: array[2, INNER_C_STRUCT_web_1]
storageQueue*: WebSessionStorageHandleQueue
## / SessionMessageHeader
type
WebSessionMessageHeader* {.bycopy.} = object
kind*: U32 ## /< Message Kind (\ref WebSessionSendMessageKind / \ref WebSessionReceiveMessageKind)
size*: U32 ## /< Data size following the header.
reserved*: array[0x8, U8] ## /< Unused
## / Types for \ref WebArgTLV, input storage.
type
WebArgType* = enum
WebArgTypeUrl = 0x1, ## /< [1.0.0+] String, size 0xC00. Initial URL.
WebArgTypeCallbackUrl = 0x3, ## /< [1.0.0+] String, size 0x400.
WebArgTypeCallbackableUrl = 0x4, ## /< [1.0.0+] String, size 0x400.
WebArgTypeApplicationId = 0x5, ## /< [1.0.0+] Offline-applet, u64 ApplicationId
WebArgTypeDocumentPath = 0x6, ## /< [1.0.0+] Offline-applet, string with size 0xC00.
WebArgTypeDocumentKind = 0x7, ## /< [1.0.0+] Offline-applet, u32 enum \WebDocumentKind.
WebArgTypeSystemDataId = 0x8, ## /< [1.0.0+] Offline-applet, u64 SystemDataId
WebArgTypeShareStartPage = 0x9, ## /< [1.0.0+] u32 enum \WebShareStartPage
WebArgTypeWhitelist = 0xA, ## /< [1.0.0+] String, size 0x1000.
WebArgTypeNewsFlag = 0xB, ## /< [1.0.0+] u8 bool
WebArgTypeUnknownC = 0xC, ## /< [1.0.0+] u8
WebArgTypeUnknownD = 0xD, ## /< [1.0.0+] u8
WebArgTypeUid = 0xE, ## /< [1.0.0+] \ref AccountUid, controls which user-specific savedata to mount.
WebArgTypeAlbumEntry0 = 0xF, ## /< [1.0.0+] Share-applet caps AlbumEntry, entry 0.
WebArgTypeScreenShot = 0x10, ## /< [1.0.0+] u8 bool
WebArgTypeEcClientCert = 0x11, ## /< [1.0.0+] u8 bool
WebArgTypeUnknown12 = 0x12, ## /< [1.0.0+] u8
WebArgTypePlayReport = 0x13, ## /< [1.0.0+] u8 bool
WebArgTypeUnknown14 = 0x14, ## /< [1.0.0+] u8
WebArgTypeUnknown15 = 0x15, ## /< [1.0.0+] u8
WebArgTypeBootDisplayKind = 0x17, ## /< [1.0.0+] u32 enum \ref WebBootDisplayKind
WebArgTypeBackgroundKind = 0x18, ## /< [1.0.0+] u32 enum \ref WebBackgroundKind
WebArgTypeFooter = 0x19, ## /< [1.0.0+] u8 bool
WebArgTypePointer = 0x1A, ## /< [1.0.0+] u8 bool
WebArgTypeLeftStickMode = 0x1B, ## /< [1.0.0+] u32 enum \ref WebLeftStickMode
WebArgTypeKeyRepeatFrame0 = 0x1C, ## /< [1.0.0+] s32 KeyRepeatFrame, first param
WebArgTypeKeyRepeatFrame1 = 0x1D, ## /< [1.0.0+] s32 KeyRepeatFrame, second param
WebArgTypeBootAsMediaPlayerInverted = 0x1E, ## /< [1.0.0+] u8 bool. With News on [3.0.0+] this is set after BootAsMediaPlayer with the value inverted.
WebArgTypeDisplayUrlKind = 0x1F, ## /< [1.0.0+] u8 bool, DisplayUrlKind (value = (input_enumval==0x1)).
WebArgTypeBootAsMediaPlayer = 0x21, ## /< [2.0.0+] u8 bool
WebArgTypeShopJump = 0x22, ## /< [2.0.0+] u8 bool
WebArgTypeMediaPlayerUserGestureRestriction = 0x23, ## /< [2.0.0-5.1.0] u8 bool
WebArgTypeLobbyParameter = 0x24, ## /< [2.0.0+] String, size 0x100.
WebArgTypeApplicationAlbumEntry = 0x26, ## /< [3.0.0+] Share-applet caps ApplicationAlbumEntry
WebArgTypeJsExtension = 0x27, ## /< [3.0.0+] u8 bool
WebArgTypeAdditionalCommentText = 0x28, ## /< [4.0.0+] String, size 0x100. Share-applet AdditionalCommentText.
WebArgTypeTouchEnabledOnContents = 0x29, ## /< [4.0.0+] u8 bool
WebArgTypeUserAgentAdditionalString = 0x2A, ## /< [4.0.0+] String, size 0x80.
WebArgTypeAdditionalMediaData0 = 0x2B, ## /< [4.0.0+] Share-applet 0x10-byte u8 array, AdditionalMediaData. Entry 0. If the user-input size is less than 0x10, the remaining data used for the TLV is cleared.
WebArgTypeMediaPlayerAutoClose = 0x2C, ## /< [4.0.0+] u8 bool
WebArgTypePageCache = 0x2D, ## /< [4.0.0+] u8 bool
WebArgTypeWebAudio = 0x2E, ## /< [4.0.0+] u8 bool
WebArgType2F = 0x2F, ## /< [5.0.0+] u8
WebArgTypeYouTubeVideoFlag = 0x31, ## /< [5.0.0+] u8 bool Indicates that the built-in whitelist for YouTubeVideo should be used.
WebArgTypeFooterFixedKind = 0x32, ## /< [5.0.0+] u32 enum \ref WebFooterFixedKind
WebArgTypePageFade = 0x33, ## /< [5.0.0+] u8 bool
WebArgTypeMediaCreatorApplicationRatingAge = 0x34, ## /< [5.0.0+] Share-applet 0x20-byte s8 array, MediaCreatorApplicationRatingAge.
WebArgTypeBootLoadingIcon = 0x35, ## /< [5.0.0+] u8 bool
WebArgTypePageScrollIndicator = 0x36, ## /< [5.0.0+] u8 bool
WebArgTypeMediaPlayerSpeedControl = 0x37, ## /< [6.0.0+] u8 bool
WebArgTypeAlbumEntry1 = 0x38, ## /< [6.0.0+] Share-applet caps AlbumEntry, entry 1.
WebArgTypeAlbumEntry2 = 0x39, ## /< [6.0.0+] Share-applet caps AlbumEntry, entry 2.
WebArgTypeAlbumEntry3 = 0x3A, ## /< [6.0.0+] Share-applet caps AlbumEntry, entry 3.
WebArgTypeAdditionalMediaData1 = 0x3B, ## /< [6.0.0+] Share-applet 0x10-byte u8 array, AdditionalMediaData. Entry 1.
WebArgTypeAdditionalMediaData2 = 0x3C, ## /< [6.0.0+] Share-applet 0x10-byte u8 array, AdditionalMediaData. Entry 2.
WebArgTypeAdditionalMediaData3 = 0x3D, ## /< [6.0.0+] Share-applet 0x10-byte u8 array, AdditionalMediaData. Entry 3.
WebArgTypeBootFooterButton = 0x3E, ## /< [6.0.0+] Array of \ref WebBootFooterButtonEntry with 0x10 entries.
WebArgTypeOverrideWebAudioVolume = 0x3F, ## /< [6.0.0+] float
WebArgTypeOverrideMediaAudioVolume = 0x40, ## /< [6.0.0+] float
WebArgTypeSessionBootMode = 0x41, ## /< [7.0.0+] u32 enum \ref WebSessionBootMode
WebArgTypeSessionFlag = 0x42, ## /< [7.0.0+] u8 bool, enables using WebSession when set.
WebArgTypeMediaPlayerUi = 0x43, ## /< [8.0.0+] u8 bool
WebArgTypeTransferMemory = 0x44 ## /< [11.0.0+] u8 bool
const
WebArgTypeMediaAutoPlay* = WebArgTypeMediaPlayerUserGestureRestriction
## / Types for \ref WebArgTLV, output storage.
type
WebReplyType* = enum
WebReplyTypeExitReason = 0x1, ## /< [3.0.0+] u32 ExitReason
WebReplyTypeLastUrl = 0x2, ## /< [3.0.0+] string
WebReplyTypeLastUrlSize = 0x3, ## /< [3.0.0+] u64
WebReplyTypeSharePostResult = 0x4, ## /< [3.0.0+] u32 SharePostResult
WebReplyTypePostServiceName = 0x5, ## /< [3.0.0+] string
WebReplyTypePostServiceNameSize = 0x6, ## /< [3.0.0+] u64
WebReplyTypePostId = 0x7, ## /< [3.0.0+] string
WebReplyTypePostIdSize = 0x8, ## /< [3.0.0+] u64
WebReplyTypeMediaPlayerAutoClosedByCompletion = 0x9 ## /< [8.0.0+] u8 bool
## / This controls the kind of content to mount with Offline-applet.
type
WebDocumentKind* = enum
WebDocumentKindOfflineHtmlPage = 0x1, ## /< Use the HtmlDocument NCA content from the application.
WebDocumentKindApplicationLegalInformation = 0x2, ## /< Use the LegalInformation NCA content from the application.
WebDocumentKindSystemDataPage = 0x3 ## /< Use the Data NCA content from the specified SystemData, see also: https://switchbrew.org/wiki/Title_list#System_Data_Archives
## / This controls the initial page for ShareApplet, used by \ref webShareCreate.
type
WebShareStartPage* = enum
WebShareStartPageDefault = 0, ## /< The default "/" page.
WebShareStartPageSettings = 1 ## /< The "/settings/" page.
## / Kind values for \ref webConfigSetBootDisplayKind. Controls the background color while displaying the loading screen during applet boot. Also controls the BackgroundKind when value is non-zero.
type
WebBootDisplayKind* = enum
WebBootDisplayKindDefault = 0, ## /< Default. BackgroundKind is controlled by \ref WebBackgroundKind.
WebBootDisplayKindWhite = 1, ## /< White background. Used by \ref webOfflineCreate for docKind ::WebDocumentKind_ApplicationLegalInformation/::WebDocumentKind_SystemDataPage.
WebBootDisplayKindBlack = 2, ## /< Black background.
WebBootDisplayKindUnknown3 = 3, ## /< Unknown. Used by \ref webShareCreate.
WebBootDisplayKindUnknown4 = 4 ## /< Unknown. Used by \ref webLobbyCreate.
## / Kind values for \ref webConfigSetBackgroundKind. Controls the background color while displaying the loading screen during applet boot. Only used when \ref WebBootDisplayKind is ::WebBootDisplayKind_Default. If the applet was not launched by an Application, the applet will only use WebBackgroundKind_Default.
type
WebBackgroundKind* = enum
WebBackgroundKindDefault = 0, ## /< Default. Same as ::WebBootDisplayKind_White/::WebBootDisplayKind_Black, determined via ::WebArgType_BootAsMediaPlayer.
WebBackgroundKindUnknown1 = 1, ## /< Unknown. Same as ::WebBootDisplayKind_Unknown3.
WebBackgroundKindUnknown2 = 2 ## /< Unknown. Same as ::WebBootDisplayKind_Unknown4. Used by \ref webLobbyCreate.
## / Mode values for \ref webConfigSetLeftStickMode. Controls the initial mode, this can be toggled by the user via the pressing the left-stick button. If the Pointer flag is set to false (\ref webConfigSetPointer), only ::WebLeftStickMode_Cursor will be used and mode toggle by the user is disabled (input value ignored).
type
WebLeftStickMode* = enum
WebLeftStickModePointer = 0, ## /< The user can directly control the pointer via the left-stick.
WebLeftStickModeCursor = 1 ## /< The user can only select elements on the page via the left-stick.
## / Kind values for \ref webConfigSetFooterFixedKind. Controls UI footer display behaviour.
type
WebFooterFixedKind* = enum
WebFooterFixedKindDefault = 0, ## /< Default. Footer is hidden while scrolling.
WebFooterFixedKindAlways = 1, ## /< Footer is always displayed regardless of scrolling.
WebFooterFixedKindHidden = 2 ## /< Footer is hidden regardless of scrolling.
proc webWifiCreate*(config: ptr WebWifiConfig; conntestUrl: cstring;
initialUrl: cstring; uuid: Uuid; rev: U32) {.cdecl,
importc: "webWifiCreate".}
## *
## @brief Creates the config for WifiWebAuthApplet. This is the captive portal applet.
## @param config WebWifiConfig object.
## @param conntest_url URL used for the connection-test requests. When empty/NULL the applet will test the connection with nifm and throw an error on failure.
## @param initial_url Initial URL navigated to by the applet.
## @param uuid NIFM Network UUID, for nifm cmd SetNetworkProfileId. Value 0 can be used. Only used by the applet when conntest_url is set.
## @param rev Input value for nifm cmd SetRequirementByRevision. Value 0 can be used. Only used by the applet when conntest_url is set.
##
proc webWifiShow*(config: ptr WebWifiConfig; `out`: ptr WebWifiReturnValue): Result {.
cdecl, importc: "webWifiShow".}
## *
## @brief Launches WifiWebAuthApplet with the specified config and waits for it to exit.
## @param config WebWifiConfig object.
## @param out Optional output applet reply data, can be NULL.
##
proc webPageCreate*(config: ptr WebCommonConfig; url: cstring): Result {.cdecl,
importc: "webPageCreate".}
## *
## @brief Creates the config for WebApplet. This applet uses an URL whitelist loaded from the user-process host Application, which is only loaded when running under an Application.
## @note Sets ::WebArgType_UnknownD, and ::WebArgType_Unknown12 on pre-3.0.0, to value 1.
## @param config WebCommonConfig object.
## @param url Initial URL navigated to by the applet.
##
proc webNewsCreate*(config: ptr WebCommonConfig; url: cstring): Result {.cdecl,
importc: "webNewsCreate".}
## *
## @brief Creates the config for WebApplet. This is based on \ref webPageCreate, for News. Hence other functions referencing \ref webPageCreate also apply to this.
## @note The domain from the input URL is automatically whitelisted, in addition to any already loaded whitelist.
## @note Sets ::WebArgType_UnknownD to value 1, and sets ::WebArgType_NewsFlag to true. Also uses \ref webConfigSetEcClientCert and \ref webConfigSetShopJump with flag=true.
## @param config WebCommonConfig object.
## @param url Initial URL navigated to by the applet.
##
proc webYouTubeVideoCreate*(config: ptr WebCommonConfig; url: cstring): Result {.cdecl,
importc: "webYouTubeVideoCreate".}
## *
## @brief Creates the config for WebApplet. This is based on \ref webPageCreate, for YouTubeVideo. Hence other functions referencing \ref webPageCreate also apply to this. This uses a whitelist which essentially only allows youtube embed/ URLs (without mounting content from the host Application).
## @note This is only available on [5.0.0+].
## @note Sets ::WebArgType_UnknownD to value 1, and sets ::WebArgType_YouTubeVideoFlag to true. Also uses \ref webConfigSetBootAsMediaPlayer with flag=true.
## @param config WebCommonConfig object.
## @param url Initial URL navigated to by the applet.
##
proc webOfflineCreate*(config: ptr WebCommonConfig; docKind: WebDocumentKind; id: U64;
docPath: cstring): Result {.cdecl, importc: "webOfflineCreate".}
## *
## @brief Creates the config for Offline-applet. This applet uses data loaded from content.
## @note Uses \ref webConfigSetLeftStickMode with ::WebLeftStickMode_Cursor and sets ::WebArgType_BootAsMediaPlayerInverted to false. Uses \ref webConfigSetPointer with flag = docKind == ::WebDocumentKind_OfflineHtmlPage.
## @note For docKind ::WebDocumentKind_ApplicationLegalInformation / ::WebDocumentKind_SystemDataPage, uses \ref webConfigSetFooter with flag=true and \ref webConfigSetBackgroundKind with ::WebBackgroundKind_Default.
## @note For docKind ::WebDocumentKind_SystemDataPage, uses \ref webConfigSetBootDisplayKind with ::WebBootDisplayKind_White.
## @note Sets ::WebArgType_Unknown14/::WebArgType_Unknown15 to value 1. With docKind ::WebDocumentKind_ApplicationLegalInformation, uses \ref webConfigSetBootDisplayKind with ::WebBootDisplayKind_White.
## @note Sets ::WebArgType_UnknownC to value 1.
## @note With docKind ::WebDocumentKind_ApplicationLegalInformation, uses \ref webConfigSetEcClientCert with flag=true.
## @note With docKind ::WebDocumentKind_OfflineHtmlPage on pre-3.0.0, sets ::WebArgType_Unknown12 to value 1.
## @note Lastly, sets the TLVs as needed for the input params.
## @param config WebCommonConfig object.
## @param docKind \ref WebDocumentKind
## @param id Id to load the content from. With docKind = ::WebDocumentKind_OfflineHtmlPage, id=0 should be used to specify the user-process application (non-zero is ignored with this docKind).
## @param docPath Initial document path in RomFS, without the leading '/'. For ::WebDocumentKind_OfflineHtmlPage, this is relative to "html-document/" in RomFS. For the other docKind values, this is relative to "/" in RomFS. This path must contain ".htdocs/".
##
proc webShareCreate*(config: ptr WebCommonConfig; page: WebShareStartPage): Result {.
cdecl, importc: "webShareCreate".}
## *
## @brief Creates the config for ShareApplet. This applet is for social media posting/settings.
## @note If a non-zero uid isn't set with \ref webConfigSetUid prior to using \ref webConfigShow, the applet will launch the profile-selector applet to select an account.
## @note An error will be displayed if neither \ref webConfigSetAlbumEntry, nor \ref webConfigSetApplicationAlbumEntry, nor \ref webConfigAddAlbumEntryAndMediaData are used prior to using \ref webConfigShow, with ::WebShareStartPage_Default.
## @note Uses \ref webConfigSetLeftStickMode with ::WebLeftStickMode_Cursor, \ref webConfigSetUid with uid=0, \ref webConfigSetDisplayUrlKind with kind=true, and sets ::WebArgType_Unknown14/::WebArgType_Unknown15 to value 1. Uses \ref webConfigSetBootDisplayKind with ::WebBootDisplayKind_Unknown3.
## @param config WebCommonConfig object.
## @param page \ref WebShareStartPage
##
proc webLobbyCreate*(config: ptr WebCommonConfig): Result {.cdecl,
importc: "webLobbyCreate".}
## *
## @brief Creates the config for LobbyApplet. This applet is for "Nintendo Switch Online Lounge".
## @note Only available on [2.0.0+].
## @note If a non-zero uid isn't set with \ref webConfigSetUid prior to using \ref webConfigShow, the applet will launch the profile-selector applet to select an account.
## @note Uses \ref webConfigSetLeftStickMode with ::WebLeftStickMode_Cursor, \ref webConfigSetPointer with flag=false on [3.0.0+], \ref webConfigSetUid with uid=0, and sets ::WebArgType_Unknown14/::WebArgType_Unknown15 to value 1. Uses \ref webConfigSetBootDisplayKind with ::WebBootDisplayKind_Unknown4, \ref webConfigSetBackgroundKind with ::WebBackgroundKind_Unknown2, and sets ::WebArgType_BootAsMediaPlayerInverted to false.
## @param config WebCommonConfig object.
##
proc webConfigSetCallbackUrl*(config: ptr WebCommonConfig; url: cstring): Result {.
cdecl, importc: "webConfigSetCallbackUrl".}
## *
## @brief Sets the CallbackUrl. See also \ref webReplyGetLastUrl.
## @note With Offline-applet for LastUrl handling, it compares the domain with "localhost" instead.
## @note Only available with config created by \ref webPageCreate or with Share-applet.
## @param config WebCommonConfig object.
## @param url URL
##
proc webConfigSetCallbackableUrl*(config: ptr WebCommonConfig; url: cstring): Result {.
cdecl, importc: "webConfigSetCallbackableUrl".}
## *
## @brief Sets the CallbackableUrl.
## @note Only available with config created by \ref webPageCreate.
## @param config WebCommonConfig object.
## @param url URL
##
proc webConfigSetWhitelist*(config: ptr WebCommonConfig; whitelist: cstring): Result {.
cdecl, importc: "webConfigSetWhitelist".}
## *
## @brief Sets the whitelist.
## @note Only available with config created by \ref webPageCreate.
## @note If the whitelist isn't formatted properly, the applet will exit briefly after the applet is launched.
## @param config WebCommonConfig object.
## @param whitelist Whitelist string, each line is a regex for each whitelisted URL.
##
proc webConfigSetUid*(config: ptr WebCommonConfig; uid: AccountUid): Result {.cdecl,
importc: "webConfigSetUid".}
## *
## @brief Sets the account uid. Controls which user-specific savedata to mount.
## @note Only available with config created by \ref webPageCreate, \ref webLobbyCreate, or with Share-applet.
## @note Used automatically by \ref webShareCreate and \ref webLobbyCreate with uid=0.
## @param config WebCommonConfig object.
## @param uid \ref AccountUid
##
proc webConfigSetAlbumEntry*(config: ptr WebCommonConfig; entry: ptr CapsAlbumEntry): Result {.
cdecl, importc: "webConfigSetAlbumEntry".}
## *
## @brief Sets the Share CapsAlbumEntry.
## @note Only available with config created by \ref webShareCreate.
## @param config WebCommonConfig object.
## @param entry \ref CapsAlbumEntry
##
proc webConfigSetScreenShot*(config: ptr WebCommonConfig; flag: bool): Result {.cdecl,
importc: "webConfigSetScreenShot".}
## *
## @brief Sets the ScreenShot flag, which controls whether screen-shot capture is allowed.
## @note Only available with config created by \ref webPageCreate.
## @param config WebCommonConfig object.
## @param flag Flag
##
proc webConfigSetEcClientCert*(config: ptr WebCommonConfig; flag: bool): Result {.
cdecl, importc: "webConfigSetEcClientCert".}
## *
## @brief Sets the EcClientCert flag.
## @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate.
## @note Used automatically by \ref webOfflineCreate, depending on the docKind.
## @note Used automatically by \ref webNewsCreate with flag=true.
## @param config WebCommonConfig object.
## @param flag Flag
##
proc webConfigSetPlayReport*(config: ptr WebCommonConfig; flag: bool): Result {.cdecl,
importc: "webConfigSetPlayReport".}
## *
## @brief Sets whether PlayReport is enabled.
## @note Only available with config created by \ref webOfflineCreate.
## @param config WebCommonConfig object.
## @param flag Flag
##
proc webConfigSetBootDisplayKind*(config: ptr WebCommonConfig;
kind: WebBootDisplayKind): Result {.cdecl,
importc: "webConfigSetBootDisplayKind".}
## *
## @brief Sets the BootDisplayKind.
## @note Only available with config created by \ref webOfflineCreate, \ref webShareCreate, \ref webPageCreate, or \ref webLobbyCreate..
## @note Used automatically by \ref webOfflineCreate, depending on the docKind.
## @note Used automatically by \ref webShareCreate with kind=::WebBootDisplayKind_Unknown3.
## @note Used automatically by \ref webLobbyCreate with kind=::WebBootDisplayKind_Unknown4.
## @param config WebCommonConfig object.
## @param kind \ref WebBootDisplayKind
##
proc webConfigSetBackgroundKind*(config: ptr WebCommonConfig;
kind: WebBackgroundKind): Result {.cdecl,
importc: "webConfigSetBackgroundKind".}
## *
## @brief Sets the BackgroundKind.
## @note Only available with config created by \ref webOfflineCreate, \ref webPageCreate, or \ref webLobbyCreate.
## @note Used automatically by \ref webOfflineCreate, depending on the docKind.
## @note Used automatically by \ref webLobbyCreate with kind=2.
## @param config WebCommonConfig object.
## @param kind \ref WebBackgroundKind
##
proc webConfigSetFooter*(config: ptr WebCommonConfig; flag: bool): Result {.cdecl,
importc: "webConfigSetFooter".}
## *
## @brief Sets the whether the UI footer is enabled.
## @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate.
## @note Used automatically by \ref webOfflineCreate, depending on the docKind.
## @param config WebCommonConfig object.
## @param flag Flag
##
proc webConfigSetPointer*(config: ptr WebCommonConfig; flag: bool): Result {.cdecl,
importc: "webConfigSetPointer".}
## *
## @brief Sets the whether the Pointer is enabled. See also \ref WebLeftStickMode.
## @note Only available with config created by \ref webOfflineCreate, \ref webPageCreate, or \ref webLobbyCreate.
## @note Used automatically by \ref webOfflineCreate.
## @note Used automatically by \ref webLobbyCreate with flag=false on [3.0.0+].
## @param config WebCommonConfig object.
## @param flag Flag
##
proc webConfigSetLeftStickMode*(config: ptr WebCommonConfig; mode: WebLeftStickMode): Result {.
cdecl, importc: "webConfigSetLeftStickMode".}
## *
## @brief Sets the LeftStickMode.
## @note Only available with config created by \ref webOfflineCreate, \ref webShareCreate, \ref webPageCreate, or \ref webLobbyCreate.
## @note Used automatically by \ref webOfflineCreate, \ref webShareCreate, and \ref webLobbyCreate with ::WebLeftStickMode_Cursor.
## @param config WebCommonConfig object.
## @param mode Mode, different enums for Web and Offline.
##
proc webConfigSetKeyRepeatFrame*(config: ptr WebCommonConfig; inval0: S32; inval1: S32): Result {.
cdecl, importc: "webConfigSetKeyRepeatFrame".}
## *
## @brief Sets the KeyRepeatFrame.
## @note Only available with config created by \ref webOfflineCreate.
## @param config WebCommonConfig object.
## @param inval0 First input param.
## @param inval1 Second input param.
##
proc webConfigSetDisplayUrlKind*(config: ptr WebCommonConfig; kind: bool): Result {.
cdecl, importc: "webConfigSetDisplayUrlKind".}
## *
## @brief Sets the DisplayUrlKind.
## @note Only available with config created by \ref webShareCreate or \ref webPageCreate.
## @param config WebCommonConfig object.
## @note Used automatically by \ref webShareCreate with kind=true.
## @param kind Kind
##
proc webConfigSetBootAsMediaPlayer*(config: ptr WebCommonConfig; flag: bool): Result {.
cdecl, importc: "webConfigSetBootAsMediaPlayer".}
## *
## @brief Sets the BootAsMediaPlayer flag.
## @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [2.0.0+].
## @note With config created by \ref webNewsCreate on [3.0.0+], this also sets ::WebArgType_BootAsMediaPlayerInverted to !flag.
## @param config WebCommonConfig object.
## @param flag Flag. true = BootAsMediaPlayer, false = BootAsWebPage.
##
proc webConfigSetShopJump*(config: ptr WebCommonConfig; flag: bool): Result {.cdecl,
importc: "webConfigSetShopJump".}
## *
## @brief Sets the ShopJump flag.
## @note Only available with config created by \ref webPageCreate on [2.0.0+].
## @note Used automatically by \ref webNewsCreate with flag=true.
## @param config WebCommonConfig object.
## @param flag Flag
##
proc webConfigSetMediaPlayerUserGestureRestriction*(config: ptr WebCommonConfig;
flag: bool): Result {.cdecl,
importc: "webConfigSetMediaPlayerUserGestureRestriction".}
## *
## @brief Sets the MediaPlayerUserGestureRestriction flag.
## @note Only available with config created by \ref webPageCreate on [2.0.0-5.1.0].
## @param config WebCommonConfig object.
## @param flag Flag
##
proc webConfigSetMediaAutoPlay*(config: ptr WebCommonConfig; flag: bool): Result {.
cdecl, importc: "webConfigSetMediaAutoPlay".}
## *
## @brief Sets whether MediaAutoPlay is enabled.
## @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [6.0.0+].
## @param config WebCommonConfig object.
## @param flag Flag
##
proc webConfigSetLobbyParameter*(config: ptr WebCommonConfig; str: cstring): Result {.
cdecl, importc: "webConfigSetLobbyParameter".}
## *
## @brief Sets the LobbyParameter.
## @note Only available with config created by \ref webLobbyCreate.
## @param config WebCommonConfig object.
## @param str String
##
proc webConfigSetApplicationAlbumEntry*(config: ptr WebCommonConfig;
entry: ptr CapsApplicationAlbumEntry): Result {.
cdecl, importc: "webConfigSetApplicationAlbumEntry".}
## *
## @brief Sets the Share CapsApplicationAlbumEntry.
## @note Only available with config created by \ref webShareCreate on [3.0.0+].
## @param config WebCommonConfig object.
## @param entry \ref CapsApplicationAlbumEntry, see also capssu.h.
##
proc webConfigSetJsExtension*(config: ptr WebCommonConfig; flag: bool): Result {.cdecl,
importc: "webConfigSetJsExtension".}
## *
## @brief Sets whether JsExtension is enabled.
## @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [3.0.0+].
## @param config WebCommonConfig object.
## @param flag Flag
##
proc webConfigSetAdditionalCommentText*(config: ptr WebCommonConfig; str: cstring): Result {.
cdecl, importc: "webConfigSetAdditionalCommentText".}
## *
## @brief Sets the Share AdditionalCommentText.
## @note Only available with config created by \ref webShareCreate on [4.0.0+].
## @param config WebCommonConfig object.
## @param str String
##
proc webConfigSetTouchEnabledOnContents*(config: ptr WebCommonConfig; flag: bool): Result {.
cdecl, importc: "webConfigSetTouchEnabledOnContents".}
## *
## @brief Sets the TouchEnabledOnContents flag.
## @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [4.0.0+].
## @param config WebCommonConfig object.
## @param flag Flag
##
proc webConfigSetUserAgentAdditionalString*(config: ptr WebCommonConfig;
str: cstring): Result {.cdecl, importc: "webConfigSetUserAgentAdditionalString".}
## *
## @brief Sets the UserAgentAdditionalString. " " followed by this string are appended to the normal User-Agent string.
## @note Only available with config created by \ref webPageCreate on [4.0.0+].
## @param config WebCommonConfig object.
## @param str String
##
proc webConfigSetAdditionalMediaData*(config: ptr WebCommonConfig; data: ptr U8;
size: csize_t): Result {.cdecl,
importc: "webConfigSetAdditionalMediaData".}
## *
## @brief Sets the Share AdditionalMediaData.
## @note Only available with config created by \ref webShareCreate on [4.0.0+].
## @param config WebCommonConfig object.
## @param data Input data
## @param size Size of the input data, max size is 0x10.
##
proc webConfigSetMediaPlayerAutoClose*(config: ptr WebCommonConfig; flag: bool): Result {.
cdecl, importc: "webConfigSetMediaPlayerAutoClose".}
## *
## @brief Sets the MediaPlayerAutoClose flag.
## @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [4.0.0+].
## @param config WebCommonConfig object.
## @param flag Flag
##
proc webConfigSetPageCache*(config: ptr WebCommonConfig; flag: bool): Result {.cdecl,
importc: "webConfigSetPageCache".}
## *
## @brief Sets whether PageCache is enabled.
## @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [4.0.0+].
## @param config WebCommonConfig object.
## @param flag Flag
##
proc webConfigSetWebAudio*(config: ptr WebCommonConfig; flag: bool): Result {.cdecl,
importc: "webConfigSetWebAudio".}
## *
## @brief Sets whether WebAudio is enabled.
## @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [4.0.0+].
## @param config WebCommonConfig object.
## @param flag Flag
##
proc webConfigSetFooterFixedKind*(config: ptr WebCommonConfig;
kind: WebFooterFixedKind): Result {.cdecl,
importc: "webConfigSetFooterFixedKind".}
## *
## @brief Sets the FooterFixedKind.
## @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [5.0.0+].
## @param config WebCommonConfig object.
## @param kind \ref WebFooterFixedKind
##
proc webConfigSetPageFade*(config: ptr WebCommonConfig; flag: bool): Result {.cdecl,
importc: "webConfigSetPageFade".}
## *
## @brief Sets the PageFade flag.
## @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [5.0.0+].
## @param config WebCommonConfig object.
## @param flag Flag
##
proc webConfigSetMediaCreatorApplicationRatingAge*(config: ptr WebCommonConfig;
data: ptr S8): Result {.cdecl,
importc: "webConfigSetMediaCreatorApplicationRatingAge".}
## *
## @brief Sets the Share MediaCreatorApplicationRatingAge.
## @note Only available with config created by \ref webShareCreate on [5.0.0+].
## @param config WebCommonConfig object.
## @param data 0x20-byte input data
##
proc webConfigSetBootLoadingIcon*(config: ptr WebCommonConfig; flag: bool): Result {.
cdecl, importc: "webConfigSetBootLoadingIcon".}
## *
## @brief Sets the BootLoadingIcon flag.
## @note Only available with config created by \ref webOfflineCreate on [5.0.0+].
## @param config WebCommonConfig object.
## @param flag Flag
##
proc webConfigSetPageScrollIndicator*(config: ptr WebCommonConfig; flag: bool): Result {.
cdecl, importc: "webConfigSetPageScrollIndicator".}
## *
## @brief Sets the PageScrollIndicator flag.
## @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [5.0.0+].
## @param config WebCommonConfig object.
## @param flag Flag
##
proc webConfigSetMediaPlayerSpeedControl*(config: ptr WebCommonConfig; flag: bool): Result {.
cdecl, importc: "webConfigSetMediaPlayerSpeedControl".}
## *
## @brief Sets whether MediaPlayerSpeedControl is enabled.
## @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [6.0.0+].
## @param config WebCommonConfig object.
## @param flag Flag
##
proc webConfigAddAlbumEntryAndMediaData*(config: ptr WebCommonConfig;
entry: ptr CapsAlbumEntry; data: ptr U8;
size: csize_t): Result {.cdecl,
importc: "webConfigAddAlbumEntryAndMediaData".}
## *
## @brief Adds a pair of Share CapsAlbumEntry + optionally AdditionalMediaData. This can be used up to 4 times, for setting multiple pairs.
## @note Only available with config created by \ref webShareCreate on [6.0.0+].
## @param config WebCommonConfig object.
## @param entry \ref CapsAlbumEntry
## @param data Input data for AdditionalMediaData. Optional, can be NULL.
## @param size Size of the input data, max size is 0x10. Optional, can be 0.
##
proc webConfigSetBootFooterButtonVisible*(config: ptr WebCommonConfig;
button: WebFooterButtonId; visible: bool): Result {.cdecl,
importc: "webConfigSetBootFooterButtonVisible".}
## *
## @brief Sets whether the specified BootFooterButton is visible.
## @note Only available with config created by \ref webOfflineCreate on [6.0.0+].
## @param config WebCommonConfig object.
## @param button \ref WebFooterButtonId
## @param visible Visible flag.
##
proc webConfigSetOverrideWebAudioVolume*(config: ptr WebCommonConfig; value: cfloat): Result {.
cdecl, importc: "webConfigSetOverrideWebAudioVolume".}
## *
## @brief Sets OverrideWebAudioVolume.
## @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [6.0.0+].
## @param config WebCommonConfig object.
## @param value Value
##
proc webConfigSetOverrideMediaAudioVolume*(config: ptr WebCommonConfig;
value: cfloat): Result {.cdecl, importc: "webConfigSetOverrideMediaAudioVolume".}
## *
## @brief Sets OverrideMediaAudioVolume.
## @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [6.0.0+].
## @param config WebCommonConfig object.
## @param value Value
##
proc webConfigSetBootMode*(config: ptr WebCommonConfig; mode: WebSessionBootMode): Result {.
cdecl, importc: "webConfigSetBootMode".}
## *
## @brief Sets \ref WebSessionBootMode.
## @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [7.0.0+].
## @param config WebCommonConfig object.
## @param mode \ref WebSessionBootMode
##
proc webConfigSetMediaPlayerUi*(config: ptr WebCommonConfig; flag: bool): Result {.
cdecl, importc: "webConfigSetMediaPlayerUi".}
## *
## @brief Sets whether MediaPlayerUi is enabled.
## @note Only available with config created by \ref webOfflineCreate on [8.0.0+].
## @param config WebCommonConfig object.
## @param flag Flag
##
proc webConfigSetTransferMemory*(config: ptr WebCommonConfig; flag: bool): Result {.
cdecl, importc: "webConfigSetTransferMemory".}
## *
## @brief Sets whether TransferMemory is enabled.
## @note Only available with config created by \ref webPageCreate on [11.0.0+].
## @param config WebCommonConfig object.
## @param flag Flag
##
proc webConfigShow*(config: ptr WebCommonConfig; `out`: ptr WebCommonReply): Result {.
cdecl, importc: "webConfigShow".}
## *
## @brief Launches the {web applet} with the specified config and waits for it to exit.
## @param config WebCommonConfig object.
## @param out Optional output applet reply data, can be NULL.
##
proc webConfigRequestExit*(config: ptr WebCommonConfig): Result {.cdecl,
importc: "webConfigRequestExit".}
## *
## @brief Request the applet to exit after \ref webConfigShow was used, while the applet is still running. This is for use from another thread.
## @param config WebCommonConfig object.
##
proc webReplyGetExitReason*(reply: ptr WebCommonReply; exitReason: ptr WebExitReason): Result {.
cdecl, importc: "webReplyGetExitReason".}
## *
## @brief Gets the ExitReason from the specified reply.
## @param reply WebCommonReply object.
## @param exitReason Output \ref WebExitReason
##
proc webReplyGetLastUrl*(reply: ptr WebCommonReply; outstr: cstring;
outstrMaxsize: csize_t; outSize: ptr csize_t): Result {.cdecl,
importc: "webReplyGetLastUrl".}
## *
## @brief Gets the LastUrl from the specified reply. When the applet loads a page where the beginning of the URL matches the URL from \ref webConfigSetCallbackUrl, the applet will exit and set LastUrl to that URL (exit doesn't occur when \ref webConfigSetCallbackableUrl was used).
## @note This is only available with ::WebExitReason_LastUrl (string is empty otherwise).
## @note If you want to allocate a string buffer on heap, you can call this with outstr=NULL/outstr_maxsize=0 to get the out_size, then call it again with the allocated buffer.
## @param reply WebCommonReply object.
## @param outstr Output string buffer. If NULL, the string is not loaded.
## @param outstr_maxsize Size of the buffer, including NUL-terminator. If outstr is set, this size must be >1. The size used for the actual string-copy is this size-1, to make sure the output is NUL-terminated (the entire buffer is cleared first).
## @param out_size Output string length including NUL-terminator, for the original input string in the reply loaded from a separate size field.
##
proc webReplyGetSharePostResult*(reply: ptr WebCommonReply; sharePostResult: ptr U32): Result {.
cdecl, importc: "webReplyGetSharePostResult".}
## *
## @brief Gets the SharePostResult from the specified reply.
## @note Only available with reply data from ShareApplet on [3.0.0+].
## @param reply WebCommonReply object.
## @param sharePostResult Output sharePostResult
##
proc webReplyGetPostServiceName*(reply: ptr WebCommonReply; outstr: cstring;
outstrMaxsize: csize_t; outSize: ptr csize_t): Result {.
cdecl, importc: "webReplyGetPostServiceName".}
## *
## @brief Gets the PostServiceName from the specified reply.
## @note Only available with reply data from ShareApplet on [3.0.0+].
## @note If you want to allocate a string buffer on heap, you can call this with outstr=NULL/outstr_maxsize=0 to get the out_size, then call it again with the allocated buffer.
## @param reply WebCommonReply object.
## @param outstr Output string buffer. If NULL, the string is not loaded.
## @param outstr_maxsize Size of the buffer, including NUL-terminator. If outstr is set, this size must be >1. The size used for the actual string-copy is this size-1, to make sure the output is NUL-terminated (the entire buffer is cleared first).
## @param out_size Output string length including NUL-terminator, for the original input string in the reply loaded from a separate size field.
##
proc webReplyGetPostId*(reply: ptr WebCommonReply; outstr: cstring;
outstrMaxsize: csize_t; outSize: ptr csize_t): Result {.cdecl,
importc: "webReplyGetPostId".}
## *
## @brief Gets the PostId from the specified reply.
## @note Only available with reply data from ShareApplet on [3.0.0+].
## @note If you want to allocate a string buffer on heap, you can call this with outstr=NULL/outstr_maxsize=0 to get the out_size, then call it again with the allocated buffer.
## @param reply WebCommonReply object.
## @param outstr Output string buffer. If NULL, the string is not loaded.
## @param outstr_maxsize Size of the buffer, including NUL-terminator. If outstr is set, this size must be >1. The size used for the actual string-copy is this size-1, to make sure the output is NUL-terminated (the entire buffer is cleared first).
## @param out_size Output string length including NUL-terminator, for the original input string in the reply loaded from a separate size field.
##
proc webReplyGetMediaPlayerAutoClosedByCompletion*(reply: ptr WebCommonReply;
flag: ptr bool): Result {.cdecl, importc: "webReplyGetMediaPlayerAutoClosedByCompletion".}
## *
## @brief Gets the MediaPlayerAutoClosedByCompletion flag from the specified reply.
## @note Only available with reply data from Web on [8.0.0+].
## @param reply WebCommonReply object.
## @param flag Output flag
##
proc webSessionCreate*(s: ptr WebSession; config: ptr WebCommonConfig) {.cdecl,
importc: "webSessionCreate".}
## *
## @brief Creates a \ref WebSession object.
## @param s \ref WebSession
## @param config WebCommonConfig object.
##
proc webSessionClose*(s: ptr WebSession) {.cdecl, importc: "webSessionClose".}
## *
## @brief Closes a \ref WebSession object.
## @param s \ref WebSession
##
proc webSessionStart*(s: ptr WebSession; outEvent: ptr ptr Event): Result {.cdecl,
importc: "webSessionStart".}
## *
## @brief Launches the applet for \ref WebSession.
## @note Only available with config created by \ref webOfflineCreate or \ref webPageCreate, on [7.0.0+].
## @note Do not use \ref webConfigShow when using WebSession.
## @param s \ref WebSession
## @param[out] out_event Output Event with autoclear=false, from \ref appletHolderGetExitEvent. Optional, can be NULL.
##
proc webSessionWaitForExit*(s: ptr WebSession; `out`: ptr WebCommonReply): Result {.
cdecl, importc: "webSessionWaitForExit".}
## *
## @brief Waits for the applet to exit.
## @note This must be used before \ref webSessionClose, when \ref webSessionStart was used successfully.
## @param s \ref WebSession
## @param out Optional output applet reply data, can be NULL.
##
proc webSessionRequestExit*(s: ptr WebSession): Result {.cdecl,
importc: "webSessionRequestExit".}
## *
## @brief Request the applet to exit.
## @note Use this instead of \ref webConfigRequestExit, when using WebSession.
## @param s \ref WebSession
##
proc webSessionAppear*(s: ptr WebSession; flag: ptr bool): Result {.cdecl,
importc: "webSessionAppear".}
## *
## @brief Request the applet to Appear, this is only needed with ::WebSessionBootMode_AllForegroundInitiallyHidden.
## @note This should not be used before \ref webSessionStart.
## @param s \ref WebSession
## @param[out] flag Whether the message was sent successfully.
##
proc webSessionTrySendContentMessage*(s: ptr WebSession; content: cstring; size: U32;
flag: ptr bool): Result {.cdecl,
importc: "webSessionTrySendContentMessage".}
## *
## @brief TrySendContentMessage
## @note This should not be used before \ref webSessionStart.
## @note The JS-side for this is only available when JsExtension is enabled via \ref webConfigSetJsExtension.
## @note The JS-side may ignore this if it's sent too soon after the applet launches.
## @param s \ref WebSession
## @param[in] content Input content NUL-terminated string.
## @param[in] size Size of content.
## @param[out] flag Whether the message was sent successfully.
##
proc webSessionTryReceiveContentMessage*(s: ptr WebSession; content: cstring;
size: U64; outSize: ptr U64; flag: ptr bool): Result {.
cdecl, importc: "webSessionTryReceiveContentMessage".}
## *
## @brief TryReceiveContentMessage
## @note This should not be used before \ref webSessionStart.
## @note The JS-side for this is only available when JsExtension is enabled via \ref webConfigSetJsExtension.
## @param s \ref WebSession
## @param[out] content Output content string, always NUL-terminated.
## @param[in] size Max size of content.
## @param[out] out_size Original content size, prior to being clamped to the specified size param.
## @param[out] flag Whether the message was received successfully.
##

View file

@ -0,0 +1,41 @@
/**
* @file cache.h
* @brief AArch64 cache operations.
* @author plutoo
* @copyright libnx Authors
*/
#pragma once
#include "../types.h"
/**
* @brief Performs a data cache flush on the specified buffer.
* @param addr Address of the buffer.
* @param size Size of the buffer, in bytes.
* @remarks Cache flush is defined as Clean + Invalidate.
* @note The start and end addresses of the buffer are forcibly rounded to cache line boundaries (read from CTR_EL0 system register).
*/
void armDCacheFlush(void* addr, size_t size);
/**
* @brief Performs a data cache clean on the specified buffer.
* @param addr Address of the buffer.
* @param size Size of the buffer, in bytes.
* @note The start and end addresses of the buffer are forcibly rounded to cache line boundaries (read from CTR_EL0 system register).
*/
void armDCacheClean(void* addr, size_t size);
/**
* @brief Performs an instruction cache invalidation clean on the specified buffer.
* @param addr Address of the buffer.
* @param size Size of the buffer, in bytes.
* @note The start and end addresses of the buffer are forcibly rounded to cache line boundaries (read from CTR_EL0 system register).
*/
void armICacheInvalidate(void* addr, size_t size);
/**
* @brief Performs a data cache zeroing operation on the specified buffer.
* @param addr Address of the buffer.
* @param size Size of the buffer, in bytes.
* @note The start and end addresses of the buffer are forcibly rounded to cache line boundaries (read from CTR_EL0 system register).
*/
void armDCacheZero(void* addr, size_t size);

View file

@ -0,0 +1,43 @@
## *
## @file cache.h
## @brief AArch64 cache operations.
## @author plutoo
## @copyright libnx Authors
##
proc armDCacheFlush*(`addr`: pointer; size: csize_t) {.cdecl,
importc: "armDCacheFlush".}
## *
## @brief Performs a data cache flush on the specified buffer.
## @param addr Address of the buffer.
## @param size Size of the buffer, in bytes.
## @remarks Cache flush is defined as Clean + Invalidate.
## @note The start and end addresses of the buffer are forcibly rounded to cache line boundaries (read from CTR_EL0 system register).
##
proc armDCacheClean*(`addr`: pointer; size: csize_t) {.cdecl,
importc: "armDCacheClean".}
## *
## @brief Performs a data cache clean on the specified buffer.
## @param addr Address of the buffer.
## @param size Size of the buffer, in bytes.
## @note The start and end addresses of the buffer are forcibly rounded to cache line boundaries (read from CTR_EL0 system register).
##
proc armICacheInvalidate*(`addr`: pointer; size: csize_t) {.cdecl,
importc: "armICacheInvalidate".}
## *
## @brief Performs an instruction cache invalidation clean on the specified buffer.
## @param addr Address of the buffer.
## @param size Size of the buffer, in bytes.
## @note The start and end addresses of the buffer are forcibly rounded to cache line boundaries (read from CTR_EL0 system register).
##
proc armDCacheZero*(`addr`: pointer; size: csize_t) {.cdecl, importc: "armDCacheZero".}
## *
## @brief Performs a data cache zeroing operation on the specified buffer.
## @param addr Address of the buffer.
## @param size Size of the buffer, in bytes.
## @note The start and end addresses of the buffer are forcibly rounded to cache line boundaries (read from CTR_EL0 system register).
##

View file

@ -0,0 +1,46 @@
/**
* @file counter.h
* @brief AArch64 system counter-timer.
* @author fincs
* @copyright libnx Authors
*/
#pragma once
#include "../types.h"
/**
* @brief Gets the current system tick.
* @return The current system tick.
*/
static inline u64 armGetSystemTick(void) {
u64 ret;
__asm__ __volatile__ ("mrs %x[data], cntpct_el0" : [data] "=r" (ret));
return ret;
}
/**
* @brief Gets the system counter-timer frequency
* @return The system counter-timer frequency, in Hz.
*/
static inline u64 armGetSystemTickFreq(void) {
u64 ret;
__asm__ ("mrs %x[data], cntfrq_el0" : [data] "=r" (ret));
return ret;
}
/**
* @brief Converts from nanoseconds to CPU ticks unit.
* @param ns Time in nanoseconds.
* @return Time in CPU ticks.
*/
static inline u64 armNsToTicks(u64 ns) {
return (ns * 12) / 625;
}
/**
* @brief Converts from CPU ticks unit to nanoseconds.
* @param tick Time in ticks.
* @return Time in nanoseconds.
*/
static inline u64 armTicksToNs(u64 tick) {
return (tick * 625) / 12;
}

View file

@ -0,0 +1,40 @@
## *
## @file counter.h
## @brief AArch64 system counter-timer.
## @author fincs
## @copyright libnx Authors
##
import
../types
proc armGetSystemTick*(): U64 {.inline, cdecl, importc: "armGetSystemTick".} =
## *
## @brief Gets the current system tick.
## @return The current system tick.
##
{.emit: "__asm__ __volatile__ (\"mrs %x[data], cntpct_el0\" : [data] \"=r\" (`result`));".}
proc armGetSystemTickFreq*(): U64 {.inline, cdecl, importc: "armGetSystemTickFreq".} =
## *
## @brief Gets the system counter-timer frequency
## @return The system counter-timer frequency, in Hz.
##
{.emit: "__asm__ (\"mrs %x[data], cntfrq_el0\" : [data] \"=r\" (`result`));".}
proc armNsToTicks*(ns: U64): U64 {.inline, cdecl, importc: "armNsToTicks".} =
## *
## @brief Converts from nanoseconds to CPU ticks unit.
## @param ns Time in nanoseconds.
## @return Time in CPU ticks.
##
{.emit: "return (`ns` * 12) / 625;".}
proc armTicksToNs*(tick: U64): U64 {.inline, cdecl, importc: "armTicksToNs".} =
## *
## @brief Converts from CPU ticks unit to nanoseconds.
## @param tick Time in ticks.
## @return Time in nanoseconds.
##
{.emit: "return (`tick` * 625) / 12;".}

View file

@ -0,0 +1,130 @@
/**
* @file thread_context.h
* @brief AArch64 register dump format and related definitions.
* @author TuxSH
* @copyright libnx Authors
*/
#pragma once
#include "../types.h"
/// Armv8 CPU register.
typedef union {
u64 x; ///< 64-bit AArch64 register view.
u32 w; ///< 32-bit AArch64 register view.
u32 r; ///< AArch32 register view.
} CpuRegister;
/// Armv8 NEON register.
typedef union {
u128 v; ///< 128-bit vector view.
double d; ///< 64-bit double-precision view.
float s; ///< 32-bit single-precision view.
} FpuRegister;
/// Armv8 register group. @ref svcGetThreadContext3 uses @ref RegisterGroup_All.
typedef enum {
RegisterGroup_CpuGprs = BIT(0), ///< General-purpose CPU registers (x0..x28 or r0..r10,r12).
RegisterGroup_CpuSprs = BIT(1), ///< Special-purpose CPU registers (fp, lr, sp, pc, PSTATE or cpsr, TPIDR_EL0).
RegisterGroup_FpuGprs = BIT(2), ///< General-purpose NEON registers.
RegisterGroup_FpuSprs = BIT(3), ///< Special-purpose NEON registers.
RegisterGroup_CpuAll = RegisterGroup_CpuGprs | RegisterGroup_CpuSprs, ///< All CPU registers.
RegisterGroup_FpuAll = RegisterGroup_FpuGprs | RegisterGroup_FpuSprs, ///< All NEON registers.
RegisterGroup_All = RegisterGroup_CpuAll | RegisterGroup_FpuAll, ///< All registers.
} RegisterGroup;
/// This is for \ref ThreadExceptionDump error_desc.
typedef enum {
ThreadExceptionDesc_InstructionAbort = 0x100, ///< Instruction abort
ThreadExceptionDesc_MisalignedPC = 0x102, ///< Misaligned PC
ThreadExceptionDesc_MisalignedSP = 0x103, ///< Misaligned SP
ThreadExceptionDesc_SError = 0x106, ///< SError [not in 1.0.0?]
ThreadExceptionDesc_BadSVC = 0x301, ///< Bad SVC
ThreadExceptionDesc_Trap = 0x104, ///< Uncategorized, CP15RTTrap, CP15RRTTrap, CP14RTTrap, CP14RRTTrap, IllegalState, SystemRegisterTrap
ThreadExceptionDesc_Other = 0x101, ///< None of the above, EC <= 0x34 and not a breakpoint
} ThreadExceptionDesc;
/// Thread context structure (register dump)
typedef struct {
CpuRegister cpu_gprs[29]; ///< GPRs 0..28. Note: also contains AArch32 SPRs.
u64 fp; ///< Frame pointer (x29) (AArch64). For AArch32, check r11.
u64 lr; ///< Link register (x30) (AArch64). For AArch32, check r14.
u64 sp; ///< Stack pointer (AArch64). For AArch32, check r13.
CpuRegister pc; ///< Program counter.
u32 psr; ///< PSTATE or cpsr.
FpuRegister fpu_gprs[32]; ///< 32 general-purpose NEON registers.
u32 fpcr; ///< Floating-point control register.
u32 fpsr; ///< Floating-point status register.
u64 tpidr; ///< EL0 Read/Write Software Thread ID Register.
} ThreadContext;
/// Thread exception dump structure.
typedef struct {
u32 error_desc; ///< See \ref ThreadExceptionDesc.
u32 pad[3];
CpuRegister cpu_gprs[29]; ///< GPRs 0..28. Note: also contains AArch32 registers.
CpuRegister fp; ///< Frame pointer.
CpuRegister lr; ///< Link register.
CpuRegister sp; ///< Stack pointer.
CpuRegister pc; ///< Program counter (elr_el1).
u64 padding;
FpuRegister fpu_gprs[32]; ///< 32 general-purpose NEON registers.
u32 pstate; ///< pstate & 0xFF0FFE20
u32 afsr0;
u32 afsr1;
u32 esr;
CpuRegister far; ///< Fault Address Register.
} ThreadExceptionDump;
typedef struct {
u64 cpu_gprs[9]; ///< GPRs 0..8.
u64 lr;
u64 sp;
u64 elr_el1;
u32 pstate; ///< pstate & 0xFF0FFE20
u32 afsr0;
u32 afsr1;
u32 esr;
u64 far;
} ThreadExceptionFrameA64;
typedef struct {
u32 cpu_gprs[8]; ///< GPRs 0..7.
u32 sp;
u32 lr;
u32 elr_el1;
u32 tpidr_el0; ///< tpidr_el0 = 1
u32 cpsr; ///< cpsr & 0xFF0FFE20
u32 afsr0;
u32 afsr1;
u32 esr;
u32 far;
} ThreadExceptionFrameA32;
/**
* @brief Determines whether a thread context belong to an AArch64 process based on the PSR.
* @param[in] ctx Thread context to which PSTATE/cspr has been dumped to.
* @return true if and only if the thread context belongs to an AArch64 process.
*/
static inline bool threadContextIsAArch64(const ThreadContext *ctx)
{
return (ctx->psr & 0x10) == 0;
}
/**
* @brief Determines whether a ThreadExceptionDump belongs to an AArch64 process based on the PSTATE.
* @param[in] ctx ThreadExceptionDump.
* @return true if and only if the ThreadExceptionDump belongs to an AArch64 process.
*/
static inline bool threadExceptionIsAArch64(const ThreadExceptionDump *ctx)
{
return (ctx->pstate & 0x10) == 0;
}

View file

@ -0,0 +1,130 @@
## *
## @file thread_context.h
## @brief AArch64 register dump format and related definitions.
## @author TuxSH
## @copyright libnx Authors
##
import
../types
## / Armv8 CPU register.
type
CpuRegister* {.bycopy, union.} = object
x*: U64 ## /< 64-bit AArch64 register view.
w*: U32 ## /< 32-bit AArch64 register view.
r*: U32 ## /< AArch32 register view.
## / Armv8 NEON register.
type
FpuRegister* {.bycopy, union.} = object
v*: U128 ## /< 128-bit vector view.
d*: cdouble ## /< 64-bit double-precision view.
s*: cfloat ## /< 32-bit single-precision view.
## / Armv8 register group. @ref svcGetThreadContext3 uses @ref RegisterGroup_All.
type
RegisterGroup* = enum
RegisterGroupCpuGprs = bit(0), ## /< General-purpose CPU registers (x0..x28 or r0..r10,r12).
RegisterGroupCpuSprs = bit(1), ## /< Special-purpose CPU registers (fp, lr, sp, pc, PSTATE or cpsr, TPIDR_EL0).
RegisterGroupCpuAll = RegisterGroupCpuGprs.uint or RegisterGroupCpuSprs.uint, ## /< All CPU registers.
RegisterGroupFpuGprs = bit(2), ## /< General-purpose NEON registers.
RegisterGroupFpuSprs = bit(3), ## /< Special-purpose NEON registers.
RegisterGroupFpuAll = RegisterGroupFpuGprs.uint or RegisterGroupFpuSprs.uint, ## /< All NEON registers.
RegisterGroupAll = RegisterGroupCpuAll.uint or RegisterGroupFpuAll.uint ## /< All registers.
## / This is for \ref ThreadExceptionDump error_desc.
type
ThreadExceptionDesc* = enum
ThreadExceptionDescInstructionAbort = 0x100, ## /< Instruction abort
ThreadExceptionDescOther = 0x101, ## /< None of the above, EC <= 0x34 and not a breakpoint
ThreadExceptionDescMisalignedPC = 0x102, ## /< Misaligned PC
ThreadExceptionDescMisalignedSP = 0x103, ## /< Misaligned SP
ThreadExceptionDescTrap = 0x104, ## /< Uncategorized, CP15RTTrap, CP15RRTTrap, CP14RTTrap, CP14RRTTrap, IllegalState, SystemRegisterTrap
ThreadExceptionDescSError = 0x106, ## /< SError [not in 1.0.0?]
ThreadExceptionDescBadSVC = 0x301 ## /< Bad SVC
## / Thread context structure (register dump)
type
ThreadContext* {.bycopy.} = object
cpuGprs*: array[29, CpuRegister] ## /< GPRs 0..28. Note: also contains AArch32 SPRs.
fp*: U64 ## /< Frame pointer (x29) (AArch64). For AArch32, check r11.
lr*: U64 ## /< Link register (x30) (AArch64). For AArch32, check r14.
sp*: U64 ## /< Stack pointer (AArch64). For AArch32, check r13.
pc*: CpuRegister ## /< Program counter.
psr*: U32 ## /< PSTATE or cpsr.
fpuGprs*: array[32, FpuRegister] ## /< 32 general-purpose NEON registers.
fpcr*: U32 ## /< Floating-point control register.
fpsr*: U32 ## /< Floating-point status register.
tpidr*: U64 ## /< EL0 Read/Write Software Thread ID Register.
## / Thread exception dump structure.
type
ThreadExceptionDump* {.bycopy.} = object
errorDesc*: U32 ## /< See \ref ThreadExceptionDesc.
pad*: array[3, U32]
cpuGprs*: array[29, CpuRegister] ## /< GPRs 0..28. Note: also contains AArch32 registers.
fp*: CpuRegister ## /< Frame pointer.
lr*: CpuRegister ## /< Link register.
sp*: CpuRegister ## /< Stack pointer.
pc*: CpuRegister ## /< Program counter (elr_el1).
padding*: U64
fpuGprs*: array[32, FpuRegister] ## /< 32 general-purpose NEON registers.
pstate*: U32 ## /< pstate & 0xFF0FFE20
afsr0*: U32
afsr1*: U32
esr*: U32
far*: CpuRegister ## /< Fault Address Register.
ThreadExceptionFrameA64* {.bycopy.} = object
cpuGprs*: array[9, U64] ## /< GPRs 0..8.
lr*: U64
sp*: U64
elrEl1*: U64
pstate*: U32 ## /< pstate & 0xFF0FFE20
afsr0*: U32
afsr1*: U32
esr*: U32
far*: U64
ThreadExceptionFrameA32* {.bycopy.} = object
cpuGprs*: array[8, U32] ## /< GPRs 0..7.
sp*: U32
lr*: U32
elrEl1*: U32
tpidrEl0*: U32 ## /< tpidr_el0 = 1
cpsr*: U32 ## /< cpsr & 0xFF0FFE20
afsr0*: U32
afsr1*: U32
esr*: U32
far*: U32
proc threadContextIsAArch64*(ctx: ptr ThreadContext): bool {.inline, cdecl,
importc: "threadContextIsAArch64".} =
## *
## @brief Determines whether a thread context belong to an AArch64 process based on the PSR.
## @param[in] ctx Thread context to which PSTATE/cspr has been dumped to.
## @return true if and only if the thread context belongs to an AArch64 process.
##
return (ctx.psr and 0x10) == 0
proc threadExceptionIsAArch64*(ctx: ptr ThreadExceptionDump): bool {.inline, cdecl,
importc: "threadExceptionIsAArch64".} =
## *
## @brief Determines whether a ThreadExceptionDump belongs to an AArch64 process based on the PSTATE.
## @param[in] ctx ThreadExceptionDump.
## @return true if and only if the ThreadExceptionDump belongs to an AArch64 process.
##
return (ctx.pstate and 0x10) == 0

View file

@ -0,0 +1,18 @@
/**
* @file tls.h
* @brief AArch64 thread local storage.
* @author plutoo
* @copyright libnx Authors
*/
#pragma once
#include "../types.h"
/**
* @brief Gets the thread local storage buffer.
* @return The thread local storage buffer.
*/
static inline void* armGetTls(void) {
void* ret;
__asm__ ("mrs %x[data], tpidrro_el0" : [data] "=r" (ret));
return ret;
}

View file

@ -0,0 +1,18 @@
## *
## @file tls.h
## @brief AArch64 thread local storage.
## @author plutoo
## @copyright libnx Authors
##
import
../types
export types
## *
## @brief Gets the thread local storage buffer.
## @return The thread local storage buffer.
##
proc armGetTls*(): pointer {.inline, cdecl, importc: "armGetTls".} =
{.emit: "__asm__ (\"mrs %x[data], tpidrro_el0\" : [data] \"=r\" (`result`));".}

View file

@ -0,0 +1,25 @@
/**
* @file audio.h
* @brief Global audio service.
* @author hexkyz
* @copyright libnx Authors
*/
#pragma once
#include "../types.h"
/// PcmFormat
typedef enum {
PcmFormat_Invalid = 0,
PcmFormat_Int8 = 1,
PcmFormat_Int16 = 2,
PcmFormat_Int24 = 3,
PcmFormat_Int32 = 4,
PcmFormat_Float = 5,
PcmFormat_Adpcm = 6,
} PcmFormat;
/// AudioDeviceName
typedef struct {
char name[0x100];
} AudioDeviceName;

View file

@ -0,0 +1,21 @@
## *
## @file audio.h
## @brief Global audio service.
## @author hexkyz
## @copyright libnx Authors
##
## / PcmFormat
type
PcmFormat* = enum
PcmFormatInvalid = 0, PcmFormatInt8 = 1, PcmFormatInt16 = 2, PcmFormatInt24 = 3,
PcmFormatInt32 = 4, PcmFormatFloat = 5, PcmFormatAdpcm = 6
## / AudioDeviceName
type
AudioDeviceName* {.bycopy.} = object
name*: array[0x100, char]

View file

@ -0,0 +1,145 @@
/**
* @file driver.h
* @brief Audio driver (audren wrapper).
* @author fincs
* @copyright libnx Authors
*/
#pragma once
#include "../services/audren.h"
typedef struct AudioDriverEtc AudioDriverEtc;
typedef struct {
AudioDriverEtc* etc;
AudioRendererConfig config;
AudioRendererMemPoolInfoIn* in_mempools;
AudioRendererChannelInfoIn* in_channels;
AudioRendererVoiceInfoIn* in_voices;
AudioRendererMixInfoIn* in_mixes;
AudioRendererSinkInfoIn* in_sinks;
} AudioDriver;
Result audrvCreate(AudioDriver* d, const AudioRendererConfig* config, int num_final_mix_channels);
Result audrvUpdate(AudioDriver* d);
void audrvClose(AudioDriver* d);
//-----------------------------------------------------------------------------
int audrvMemPoolAdd(AudioDriver* d, void* buffer, size_t size);
bool audrvMemPoolRemove(AudioDriver* d, int id);
bool audrvMemPoolAttach(AudioDriver* d, int id);
bool audrvMemPoolDetach(AudioDriver* d, int id);
//-----------------------------------------------------------------------------
typedef enum {
AudioDriverWaveBufState_Free,
AudioDriverWaveBufState_Waiting,
AudioDriverWaveBufState_Queued,
AudioDriverWaveBufState_Playing,
AudioDriverWaveBufState_Done,
} AudioDriverWaveBufState;
typedef struct AudioDriverWaveBuf AudioDriverWaveBuf;
struct AudioDriverWaveBuf {
union {
s16* data_pcm16;
u8* data_adpcm;
const void* data_raw;
};
u64 size;
s32 start_sample_offset;
s32 end_sample_offset;
const void* context_addr;
u64 context_sz;
AudioDriverWaveBufState state : 8;
bool is_looping;
u32 sequence_id;
AudioDriverWaveBuf* next;
};
bool audrvVoiceInit(AudioDriver* d, int id, int num_channels, PcmFormat format, int sample_rate);
void audrvVoiceDrop(AudioDriver* d, int id);
void audrvVoiceStop(AudioDriver* d, int id);
bool audrvVoiceIsPaused(AudioDriver* d, int id);
bool audrvVoiceIsPlaying(AudioDriver* d, int id);
bool audrvVoiceAddWaveBuf(AudioDriver* d, int id, AudioDriverWaveBuf* wavebuf);
u32 audrvVoiceGetWaveBufSeq(AudioDriver* d, int id);
u32 audrvVoiceGetPlayedSampleCount(AudioDriver* d, int id);
u32 audrvVoiceGetVoiceDropsCount(AudioDriver* d, int id);
void audrvVoiceSetBiquadFilter(AudioDriver* d, int id, int biquad_id, float a0, float a1, float a2, float b0, float b1, float b2);
static inline void audrvVoiceSetExtraParams(AudioDriver* d, int id, const void* params, size_t params_size)
{
d->in_voices[id].extra_params_ptr = params;
d->in_voices[id].extra_params_sz = params_size;
}
static inline void audrvVoiceSetDestinationMix(AudioDriver* d, int id, int mix_id)
{
d->in_voices[id].dest_mix_id = mix_id;
d->in_voices[id].dest_splitter_id = AUDREN_UNUSED_SPLITTER_ID;
}
static inline void audrvVoiceSetMixFactor(AudioDriver* d, int id, float factor, int src_channel_id, int dest_channel_id)
{
int channel_id = d->in_voices[id].channel_ids[src_channel_id];
d->in_channels[channel_id].mix[dest_channel_id] = factor;
}
static inline void audrvVoiceSetVolume(AudioDriver* d, int id, float volume)
{
d->in_voices[id].volume = volume;
}
static inline void audrvVoiceSetPitch(AudioDriver* d, int id, float pitch)
{
d->in_voices[id].pitch = pitch;
}
static inline void audrvVoiceSetPriority(AudioDriver* d, int id, int priority)
{
d->in_voices[id].priority = priority;
}
static inline void audrvVoiceClearBiquadFilter(AudioDriver* d, int id, int biquad_id)
{
d->in_voices[id].biquads[biquad_id].enable = false;
}
static inline void audrvVoiceSetPaused(AudioDriver* d, int id, bool paused)
{
d->in_voices[id].state = paused ? AudioRendererVoicePlayState_Paused : AudioRendererVoicePlayState_Started;
}
static inline void audrvVoiceStart(AudioDriver* d, int id)
{
audrvVoiceSetPaused(d, id, false);
}
//-----------------------------------------------------------------------------
int audrvMixAdd(AudioDriver* d, int sample_rate, int num_channels);
void audrvMixRemove(AudioDriver* d, int id);
static inline void audrvMixSetDestinationMix(AudioDriver* d, int id, int mix_id)
{
d->in_mixes[id].dest_mix_id = mix_id;
d->in_mixes[id].dest_splitter_id = AUDREN_UNUSED_SPLITTER_ID;
}
static inline void audrvMixSetMixFactor(AudioDriver* d, int id, float factor, int src_channel_id, int dest_channel_id)
{
d->in_mixes[id].mix[src_channel_id][dest_channel_id] = factor;
}
static inline void audrvMixSetVolume(AudioDriver* d, int id, float volume)
{
d->in_mixes[id].volume = volume;
}
//-----------------------------------------------------------------------------
int audrvDeviceSinkAdd(AudioDriver* d, const char* device_name, int num_channels, const u8* channel_ids);
void audrvSinkRemove(AudioDriver* d, int id);

View file

@ -0,0 +1,151 @@
## *
## @file driver.h
## @brief Audio driver (audren wrapper).
## @author fincs
## @copyright libnx Authors
##
import
../services/audren, ../result, audio
type
AudioDriverEtc* = object
AudioDriver* {.bycopy.} = object
etc*: ptr AudioDriverEtc
config*: AudioRendererConfig
inMempools*: ptr AudioRendererMemPoolInfoIn
inChannels*: ptr AudioRendererChannelInfoIn
inVoices*: ptr AudioRendererVoiceInfoIn
inMixes*: ptr AudioRendererMixInfoIn
inSinks*: ptr AudioRendererSinkInfoIn
proc audrvCreate*(d: ptr AudioDriver; config: ptr AudioRendererConfig;
numFinalMixChannels: cint): Result {.cdecl, importc: "audrvCreate".}
proc audrvUpdate*(d: ptr AudioDriver): Result {.cdecl, importc: "audrvUpdate".}
proc audrvClose*(d: ptr AudioDriver) {.cdecl, importc: "audrvClose".}
## -----------------------------------------------------------------------------
proc audrvMemPoolAdd*(d: ptr AudioDriver; buffer: pointer; size: csize_t): cint {.cdecl,
importc: "audrvMemPoolAdd".}
proc audrvMemPoolRemove*(d: ptr AudioDriver; id: cint): bool {.cdecl,
importc: "audrvMemPoolRemove".}
proc audrvMemPoolAttach*(d: ptr AudioDriver; id: cint): bool {.cdecl,
importc: "audrvMemPoolAttach".}
proc audrvMemPoolDetach*(d: ptr AudioDriver; id: cint): bool {.cdecl,
importc: "audrvMemPoolDetach".}
## -----------------------------------------------------------------------------
type
AudioDriverWaveBufState* = enum
AudioDriverWaveBufStateFree, AudioDriverWaveBufStateWaiting,
AudioDriverWaveBufStateQueued, AudioDriverWaveBufStatePlaying,
AudioDriverWaveBufStateDone
type
INNER_C_UNION_driver_0* {.bycopy, union.} = object
dataPcm16*: ptr S16
dataAdpcm*: ptr U8
dataRaw*: pointer
AudioDriverWaveBuf* {.bycopy.} = object
anoDriver1*: INNER_C_UNION_driver_0
size*: U64
startSampleOffset*: S32
endSampleOffset*: S32
contextAddr*: pointer
contextSz*: U64
state* {.bitsize: 8.}: AudioDriverWaveBufState
isLooping*: bool
sequenceId*: U32
next*: ptr AudioDriverWaveBuf
proc audrvVoiceInit*(d: ptr AudioDriver; id: cint; numChannels: cint; format: PcmFormat;
sampleRate: cint): bool {.cdecl, importc: "audrvVoiceInit".}
proc audrvVoiceDrop*(d: ptr AudioDriver; id: cint) {.cdecl, importc: "audrvVoiceDrop".}
proc audrvVoiceStop*(d: ptr AudioDriver; id: cint) {.cdecl, importc: "audrvVoiceStop".}
proc audrvVoiceIsPaused*(d: ptr AudioDriver; id: cint): bool {.cdecl,
importc: "audrvVoiceIsPaused".}
proc audrvVoiceIsPlaying*(d: ptr AudioDriver; id: cint): bool {.cdecl,
importc: "audrvVoiceIsPlaying".}
proc audrvVoiceAddWaveBuf*(d: ptr AudioDriver; id: cint;
wavebuf: ptr AudioDriverWaveBuf): bool {.cdecl,
importc: "audrvVoiceAddWaveBuf".}
proc audrvVoiceGetWaveBufSeq*(d: ptr AudioDriver; id: cint): U32 {.cdecl,
importc: "audrvVoiceGetWaveBufSeq".}
proc audrvVoiceGetPlayedSampleCount*(d: ptr AudioDriver; id: cint): U32 {.cdecl,
importc: "audrvVoiceGetPlayedSampleCount".}
proc audrvVoiceGetVoiceDropsCount*(d: ptr AudioDriver; id: cint): U32 {.cdecl,
importc: "audrvVoiceGetVoiceDropsCount".}
proc audrvVoiceSetBiquadFilter*(d: ptr AudioDriver; id: cint; biquadId: cint;
a0: cfloat; a1: cfloat; a2: cfloat; b0: cfloat;
b1: cfloat; b2: cfloat) {.cdecl,
importc: "audrvVoiceSetBiquadFilter".}
proc audrvVoiceSetExtraParams*(d: ptr AudioDriver; id: cint; params: pointer;
paramsSize: csize_t) {.inline, cdecl,
importc: "audrvVoiceSetExtraParams".} =
d.inVoices[id].extraParamsPtr = params
d.inVoices[id].extraParamsSz = paramsSize
proc audrvVoiceSetDestinationMix*(d: ptr AudioDriver; id: cint; mixId: cint) {.inline,
cdecl, importc: "audrvVoiceSetDestinationMix".} =
d.inVoices[id].destMixId = mixId.U32
d.inVoices[id].destSplitterId = Audren_Unused_Splitter_Id.U32
proc audrvVoiceSetMixFactor*(d: ptr AudioDriver; id: cint; factor: cfloat;
srcChannelId: cint; destChannelId: cint) {.inline, cdecl,
importc: "audrvVoiceSetMixFactor".} =
var channelId = d.inVoices[id].channelIds[srcChannelId]
d.inChannels[channelId].mix[destChannelId] = factor
proc audrvVoiceSetVolume*(d: ptr AudioDriver; id: cint; volume: cfloat) {.inline, cdecl,
importc: "audrvVoiceSetVolume".} =
d.inVoices[id].volume = volume
proc audrvVoiceSetPitch*(d: ptr AudioDriver; id: cint; pitch: cfloat) {.inline, cdecl,
importc: "audrvVoiceSetPitch".} =
d.inVoices[id].pitch = pitch
proc audrvVoiceSetPriority*(d: ptr AudioDriver; id: cint; priority: cint) {.inline,
cdecl, importc: "audrvVoiceSetPriority".} =
d.inVoices[id].priority = priority.U32
proc audrvVoiceClearBiquadFilter*(d: ptr AudioDriver; id: cint; biquadId: cint) {.
inline, cdecl, importc: "audrvVoiceClearBiquadFilter".} =
d.inVoices[id].biquads[biquadId].enable = false
proc audrvVoiceSetPaused*(d: ptr AudioDriver; id: cint; paused: bool) {.inline, cdecl,
importc: "audrvVoiceSetPaused".} =
d.inVoices[id].state = if paused: AudioRendererVoicePlayStatePaused else: AudioRendererVoicePlayStateStarted
proc audrvVoiceStart*(d: ptr AudioDriver; id: cint) {.inline, cdecl,
importc: "audrvVoiceStart".} =
audrvVoiceSetPaused(d, id, false)
## -----------------------------------------------------------------------------
proc audrvMixAdd*(d: ptr AudioDriver; sampleRate: cint; numChannels: cint): cint {.cdecl,
importc: "audrvMixAdd".}
proc audrvMixRemove*(d: ptr AudioDriver; id: cint) {.cdecl, importc: "audrvMixRemove".}
proc audrvMixSetDestinationMix*(d: ptr AudioDriver; id: cint; mixId: cint) {.inline,
cdecl, importc: "audrvMixSetDestinationMix".} =
d.inMixes[id].destMixId = mixId.U32
d.inMixes[id].destSplitterId = Audren_Unused_Splitter_Id.U32
proc audrvMixSetMixFactor*(d: ptr AudioDriver; id: cint; factor: cfloat;
srcChannelId: cint; destChannelId: cint) {.inline, cdecl,
importc: "audrvMixSetMixFactor".} =
d.inMixes[id].mix[srcChannelId][destChannelId] = factor
proc audrvMixSetVolume*(d: ptr AudioDriver; id: cint; volume: cfloat) {.inline, cdecl,
importc: "audrvMixSetVolume".} =
d.inMixes[id].volume = volume
## -----------------------------------------------------------------------------
proc audrvDeviceSinkAdd*(d: ptr AudioDriver; deviceName: cstring; numChannels: cint;
channelIds: ptr U8): cint {.cdecl,
importc: "audrvDeviceSinkAdd".}
proc audrvSinkRemove*(d: ptr AudioDriver; id: cint) {.cdecl, importc: "audrvSinkRemove".}

View file

@ -0,0 +1,74 @@
/**
* @file aes.h
* @brief Hardware accelerated AES-ECB implementation.
* @copyright libnx Authors
*/
#pragma once
#include "../types.h"
#ifndef AES_BLOCK_SIZE
#define AES_BLOCK_SIZE 0x10
#endif
#ifndef AES_128_KEY_SIZE
#define AES_128_KEY_SIZE 0x10
#endif
#ifndef AES_128_U32_PER_KEY
#define AES_128_U32_PER_KEY (AES_128_KEY_SIZE / sizeof(u32))
#endif
#ifndef AES_128_NUM_ROUNDS
#define AES_128_NUM_ROUNDS 10
#endif
#ifndef AES_192_KEY_SIZE
#define AES_192_KEY_SIZE 0x18
#endif
#ifndef AES_192_U32_PER_KEY
#define AES_192_U32_PER_KEY (AES_192_KEY_SIZE / sizeof(u32))
#endif
#ifndef AES_192_NUM_ROUNDS
#define AES_192_NUM_ROUNDS 12
#endif
#ifndef AES_256_KEY_SIZE
#define AES_256_KEY_SIZE 0x20
#endif
#ifndef AES_256_U32_PER_KEY
#define AES_256_U32_PER_KEY (AES_256_KEY_SIZE / sizeof(u32))
#endif
#ifndef AES_256_NUM_ROUNDS
#define AES_256_NUM_ROUNDS 14
#endif
/// Context for AES-128 operations.
typedef struct {
u8 round_keys[AES_128_NUM_ROUNDS+1][AES_BLOCK_SIZE];
} Aes128Context;
/// Context for AES-192 operations.
typedef struct {
u8 round_keys[AES_192_NUM_ROUNDS+1][AES_BLOCK_SIZE];
} Aes192Context;
/// Context for AES-256 operations.
typedef struct {
u8 round_keys[AES_256_NUM_ROUNDS+1][AES_BLOCK_SIZE];
} Aes256Context;
/// Initialize a 128-bit AES context.
void aes128ContextCreate(Aes128Context *out, const void *key, bool is_encryptor);
/// Encrypt using an AES context (Requires is_encryptor when initializing)
void aes128EncryptBlock(const Aes128Context *ctx, void *dst, const void *src);
/// Decrypt using an AES context (Requires !is_encryptor when initializing)
void aes128DecryptBlock(const Aes128Context *ctx, void *dst, const void *src);
/// Initialize a 192-bit AES context.
void aes192ContextCreate(Aes192Context *out, const void *key, bool is_encryptor);
/// Encrypt using an AES context (Requires is_encryptor when initializing)
void aes192EncryptBlock(const Aes192Context *ctx, void *dst, const void *src);
/// Decrypt using an AES context (Requires !is_encryptor when initializing)
void aes192DecryptBlock(const Aes192Context *ctx, void *dst, const void *src);
/// Initialize a 256-bit AES context.
void aes256ContextCreate(Aes256Context *out, const void *key, bool is_encryptor);
/// Encrypt using an AES context (Requires is_encryptor when initializing)
void aes256EncryptBlock(const Aes256Context *ctx, void *dst, const void *src);
/// Decrypt using an AES context (Requires !is_encryptor when initializing)
void aes256DecryptBlock(const Aes256Context *ctx, void *dst, const void *src);

View file

@ -0,0 +1,77 @@
## *
## @file aes.h
## @brief Hardware accelerated AES-ECB implementation.
## @copyright libnx Authors
##
import
../types
const
AES_BLOCK_SIZE* = 0x10
AES_128_KEY_SIZE* = 0x10
AES_128_U32_PER_KEY* = (Aes_128Key_Size div sizeof((U32)))
AES_128_NUM_ROUNDS* = 10
AES_192_KEY_SIZE* = 0x18
AES_192_U32_PER_KEY* = (Aes_192Key_Size div sizeof((U32)))
AES_192_NUM_ROUNDS* = 12
AES_256_KEY_SIZE* = 0x20
AES_256_U32_PER_KEY* = (Aes_256Key_Size div sizeof((U32)))
AES_256_NUM_ROUNDS* = 14
## / Context for AES-128 operations.
type
Aes128Context* {.bycopy.} = object
roundKeys*: array[Aes_128Num_Rounds + 1, array[Aes_Block_Size, U8]]
## / Context for AES-192 operations.
type
Aes192Context* {.bycopy.} = object
roundKeys*: array[Aes_192Num_Rounds + 1, array[Aes_Block_Size, U8]]
## / Context for AES-256 operations.
type
Aes256Context* {.bycopy.} = object
roundKeys*: array[Aes_256Num_Rounds + 1, array[Aes_Block_Size, U8]]
proc aes128ContextCreate*(`out`: ptr Aes128Context; key: pointer; isEncryptor: bool) {.
cdecl, importc: "aes128ContextCreate".}
## / Initialize a 128-bit AES context.
proc aes128EncryptBlock*(ctx: ptr Aes128Context; dst: pointer; src: pointer) {.cdecl,
importc: "aes128EncryptBlock".}
## / Encrypt using an AES context (Requires is_encryptor when initializing)
proc aes128DecryptBlock*(ctx: ptr Aes128Context; dst: pointer; src: pointer) {.cdecl,
importc: "aes128DecryptBlock".}
## / Decrypt using an AES context (Requires !is_encryptor when initializing)
proc aes192ContextCreate*(`out`: ptr Aes192Context; key: pointer; isEncryptor: bool) {.
cdecl, importc: "aes192ContextCreate".}
## / Initialize a 192-bit AES context.
proc aes192EncryptBlock*(ctx: ptr Aes192Context; dst: pointer; src: pointer) {.cdecl,
importc: "aes192EncryptBlock".}
## / Encrypt using an AES context (Requires is_encryptor when initializing)
proc aes192DecryptBlock*(ctx: ptr Aes192Context; dst: pointer; src: pointer) {.cdecl,
importc: "aes192DecryptBlock".}
## / Decrypt using an AES context (Requires !is_encryptor when initializing)
proc aes256ContextCreate*(`out`: ptr Aes256Context; key: pointer; isEncryptor: bool) {.
cdecl, importc: "aes256ContextCreate".}
## / Initialize a 256-bit AES context.
proc aes256EncryptBlock*(ctx: ptr Aes256Context; dst: pointer; src: pointer) {.cdecl,
importc: "aes256EncryptBlock".}
## / Encrypt using an AES context (Requires is_encryptor when initializing)
proc aes256DecryptBlock*(ctx: ptr Aes256Context; dst: pointer; src: pointer) {.cdecl,
importc: "aes256DecryptBlock".}
## / Decrypt using an AES context (Requires !is_encryptor when initializing)

View file

@ -0,0 +1,49 @@
/**
* @file aes_cbc.h
* @brief Hardware accelerated AES-CBC implementation.
* @copyright libnx Authors
*/
#pragma once
#include "aes.h"
/// Context for AES-128 CBC.
typedef struct {
Aes128Context aes_ctx;
u8 iv[AES_BLOCK_SIZE];
u8 buffer[AES_BLOCK_SIZE];
size_t num_buffered;
} Aes128CbcContext;
/// Context for AES-192 CBC.
typedef struct {
Aes192Context aes_ctx;
u8 iv[AES_BLOCK_SIZE];
u8 buffer[AES_BLOCK_SIZE];
size_t num_buffered;
} Aes192CbcContext;
/// Context for AES-256 CBC.
typedef struct {
Aes256Context aes_ctx;
u8 iv[AES_BLOCK_SIZE];
u8 buffer[AES_BLOCK_SIZE];
size_t num_buffered;
} Aes256CbcContext;
/// 128-bit CBC API.
void aes128CbcContextCreate(Aes128CbcContext *out, const void *key, const void *iv, bool is_encryptor);
void aes128CbcContextResetIv(Aes128CbcContext *ctx, const void *iv);
size_t aes128CbcEncrypt(Aes128CbcContext *ctx, void *dst, const void *src, size_t size);
size_t aes128CbcDecrypt(Aes128CbcContext *ctx, void *dst, const void *src, size_t size);
/// 192-bit CBC API.
void aes192CbcContextCreate(Aes192CbcContext *out, const void *key, const void *iv, bool is_encryptor);
void aes192CbcContextResetIv(Aes192CbcContext *ctx, const void *iv);
size_t aes192CbcEncrypt(Aes192CbcContext *ctx, void *dst, const void *src, size_t size);
size_t aes192CbcDecrypt(Aes192CbcContext *ctx, void *dst, const void *src, size_t size);
/// 256-bit CBC API.
void aes256CbcContextCreate(Aes256CbcContext *out, const void *key, const void *iv, bool is_encryptor);
void aes256CbcContextResetIv(Aes256CbcContext *ctx, const void *iv);
size_t aes256CbcEncrypt(Aes256CbcContext *ctx, void *dst, const void *src, size_t size);
size_t aes256CbcDecrypt(Aes256CbcContext *ctx, void *dst, const void *src, size_t size);

View file

@ -0,0 +1,74 @@
## *
## @file AES_cbc.h
## @brief Hardware accelerated AES-CBC implementation.
## @copyright libnx Authors
##
import
aes, ../types
## / Context for AES-128 CBC.
type
Aes128CbcContext* {.bycopy.} = object
aesCtx*: Aes128Context
iv*: array[AES_Block_Size, U8]
buffer*: array[AES_Block_Size, U8]
numBuffered*: csize_t
## / Context for AES-192 CBC.
type
Aes192CbcContext* {.bycopy.} = object
aesCtx*: Aes192Context
iv*: array[AES_Block_Size, U8]
buffer*: array[AES_Block_Size, U8]
numBuffered*: csize_t
## / Context for AES-256 CBC.
type
Aes256CbcContext* {.bycopy.} = object
aesCtx*: Aes256Context
iv*: array[AES_Block_Size, U8]
buffer*: array[AES_Block_Size, U8]
numBuffered*: csize_t
## / 128-bit CBC API.
proc aes128CbcContextCreate*(`out`: ptr Aes128CbcContext; key: pointer; iv: pointer;
isEncryptor: bool) {.cdecl,
importc: "aes128CbcContextCreate".}
proc aes128CbcContextResetIv*(ctx: ptr Aes128CbcContext; iv: pointer) {.cdecl,
importc: "aes128CbcContextResetIv".}
proc aes128CbcEncrypt*(ctx: ptr Aes128CbcContext; dst: pointer; src: pointer;
size: csize_t): csize_t {.cdecl, importc: "aes128CbcEncrypt".}
proc aes128CbcDecrypt*(ctx: ptr Aes128CbcContext; dst: pointer; src: pointer;
size: csize_t): csize_t {.cdecl, importc: "aes128CbcDecrypt".}
## / 192-bit CBC API.
proc aes192CbcContextCreate*(`out`: ptr Aes192CbcContext; key: pointer; iv: pointer;
isEncryptor: bool) {.cdecl,
importc: "aes192CbcContextCreate".}
proc aes192CbcContextResetIv*(ctx: ptr Aes192CbcContext; iv: pointer) {.cdecl,
importc: "aes192CbcContextResetIv".}
proc aes192CbcEncrypt*(ctx: ptr Aes192CbcContext; dst: pointer; src: pointer;
size: csize_t): csize_t {.cdecl, importc: "aes192CbcEncrypt".}
proc aes192CbcDecrypt*(ctx: ptr Aes192CbcContext; dst: pointer; src: pointer;
size: csize_t): csize_t {.cdecl, importc: "aes192CbcDecrypt".}
## / 256-bit CBC API.
proc aes256CbcContextCreate*(`out`: ptr Aes256CbcContext; key: pointer; iv: pointer;
isEncryptor: bool) {.cdecl,
importc: "aes256CbcContextCreate".}
proc aes256CbcContextResetIv*(ctx: ptr Aes256CbcContext; iv: pointer) {.cdecl,
importc: "aes256CbcContextResetIv".}
proc aes256CbcEncrypt*(ctx: ptr Aes256CbcContext; dst: pointer; src: pointer;
size: csize_t): csize_t {.cdecl, importc: "aes256CbcEncrypt".}
proc aes256CbcDecrypt*(ctx: ptr Aes256CbcContext; dst: pointer; src: pointer;
size: csize_t): csize_t {.cdecl, importc: "aes256CbcDecrypt".}

View file

@ -0,0 +1,46 @@
/**
* @file aes_ctr.h
* @brief Hardware accelerated AES-CTR implementation.
* @copyright libnx Authors
*/
#pragma once
#include "aes.h"
/// Context for AES-128 CTR.
typedef struct {
Aes128Context aes_ctx;
u8 ctr[AES_BLOCK_SIZE];
u8 enc_ctr_buffer[AES_BLOCK_SIZE];
size_t buffer_offset;
} Aes128CtrContext;
/// Context for AES-192 CTR.
typedef struct {
Aes192Context aes_ctx;
u8 ctr[AES_BLOCK_SIZE];
u8 enc_ctr_buffer[AES_BLOCK_SIZE];
size_t buffer_offset;
} Aes192CtrContext;
/// Context for AES-256 CTR.
typedef struct {
Aes256Context aes_ctx;
u8 ctr[AES_BLOCK_SIZE];
u8 enc_ctr_buffer[AES_BLOCK_SIZE];
size_t buffer_offset;
} Aes256CtrContext;
/// 128-bit CTR API.
void aes128CtrContextCreate(Aes128CtrContext *out, const void *key, const void *ctr);
void aes128CtrContextResetCtr(Aes128CtrContext *ctx, const void *ctr);
void aes128CtrCrypt(Aes128CtrContext *ctx, void *dst, const void *src, size_t size);
/// 192-bit CTR API.
void aes192CtrContextCreate(Aes192CtrContext *out, const void *key, const void *ctr);
void aes192CtrContextResetCtr(Aes192CtrContext *ctx, const void *ctr);
void aes192CtrCrypt(Aes192CtrContext *ctx, void *dst, const void *src, size_t size);
/// 256-bit CTR API.
void aes256CtrContextCreate(Aes256CtrContext *out, const void *key, const void *ctr);
void aes256CtrContextResetCtr(Aes256CtrContext *ctx, const void *ctr);
void aes256CtrCrypt(Aes256CtrContext *ctx, void *dst, const void *src, size_t size);

View file

@ -0,0 +1,65 @@
## *
## @file AES_ctr.h
## @brief Hardware accelerated AES-CTR implementation.
## @copyright libnx Authors
##
import
aes, ../types
## / Context for AES-128 CTR.
type
Aes128CtrContext* {.bycopy.} = object
aesCtx*: Aes128Context
ctr*: array[AES_Block_Size, U8]
encCtrBuffer*: array[AES_Block_Size, U8]
bufferOffset*: csize_t
## / Context for AES-192 CTR.
type
Aes192CtrContext* {.bycopy.} = object
aesCtx*: Aes192Context
ctr*: array[AES_Block_Size, U8]
encCtrBuffer*: array[AES_Block_Size, U8]
bufferOffset*: csize_t
## / Context for AES-256 CTR.
type
Aes256CtrContext* {.bycopy.} = object
aesCtx*: Aes256Context
ctr*: array[AES_Block_Size, U8]
encCtrBuffer*: array[AES_Block_Size, U8]
bufferOffset*: csize_t
## / 128-bit CTR API.
proc aes128CtrContextCreate*(`out`: ptr Aes128CtrContext; key: pointer; ctr: pointer) {.
cdecl, importc: "aes128CtrContextCreate".}
proc aes128CtrContextResetCtr*(ctx: ptr Aes128CtrContext; ctr: pointer) {.cdecl,
importc: "aes128CtrContextResetCtr".}
proc aes128CtrCrypt*(ctx: ptr Aes128CtrContext; dst: pointer; src: pointer;
size: csize_t) {.cdecl, importc: "aes128CtrCrypt".}
## / 192-bit CTR API.
proc aes192CtrContextCreate*(`out`: ptr Aes192CtrContext; key: pointer; ctr: pointer) {.
cdecl, importc: "aes192CtrContextCreate".}
proc aes192CtrContextResetCtr*(ctx: ptr Aes192CtrContext; ctr: pointer) {.cdecl,
importc: "aes192CtrContextResetCtr".}
proc aes192CtrCrypt*(ctx: ptr Aes192CtrContext; dst: pointer; src: pointer;
size: csize_t) {.cdecl, importc: "aes192CtrCrypt".}
## / 256-bit CTR API.
proc aes256CtrContextCreate*(`out`: ptr Aes256CtrContext; key: pointer; ctr: pointer) {.
cdecl, importc: "aes256CtrContextCreate".}
proc aes256CtrContextResetCtr*(ctx: ptr Aes256CtrContext; ctr: pointer) {.cdecl,
importc: "aes256CtrContextResetCtr".}
proc aes256CtrCrypt*(ctx: ptr Aes256CtrContext; dst: pointer; src: pointer;
size: csize_t) {.cdecl, importc: "aes256CtrCrypt".}

View file

@ -0,0 +1,55 @@
/**
* @file aes_xts.h
* @brief Hardware accelerated AES-XTS implementation.
* @copyright libnx Authors
*/
#pragma once
#include "aes.h"
/// Context for AES-128 XTS.
typedef struct {
Aes128Context aes_ctx;
Aes128Context tweak_ctx;
u8 tweak[AES_BLOCK_SIZE];
u8 buffer[AES_BLOCK_SIZE];
size_t num_buffered;
} Aes128XtsContext;
/// Context for AES-192 XTS.
typedef struct {
Aes192Context aes_ctx;
Aes192Context tweak_ctx;
u8 tweak[AES_BLOCK_SIZE];
u8 buffer[AES_BLOCK_SIZE];
size_t num_buffered;
} Aes192XtsContext;
/// Context for AES-256 XTS.
typedef struct {
Aes256Context aes_ctx;
Aes256Context tweak_ctx;
u8 tweak[AES_BLOCK_SIZE];
u8 buffer[AES_BLOCK_SIZE];
size_t num_buffered;
} Aes256XtsContext;
/// 128-bit XTS API.
void aes128XtsContextCreate(Aes128XtsContext *out, const void *key0, const void *key1, bool is_encryptor);
void aes128XtsContextResetTweak(Aes128XtsContext *ctx, const void *tweak);
void aes128XtsContextResetSector(Aes128XtsContext *ctx, uint64_t sector, bool is_nintendo);
size_t aes128XtsEncrypt(Aes128XtsContext *ctx, void *dst, const void *src, size_t size);
size_t aes128XtsDecrypt(Aes128XtsContext *ctx, void *dst, const void *src, size_t size);
/// 192-bit XTS API.
void aes192XtsContextCreate(Aes192XtsContext *out, const void *key0, const void *key1, bool is_encryptor);
void aes192XtsContextResetTweak(Aes192XtsContext *ctx, const void *tweak);
void aes192XtsContextResetSector(Aes192XtsContext *ctx, uint64_t sector, bool is_nintendo);
size_t aes192XtsEncrypt(Aes192XtsContext *ctx, void *dst, const void *src, size_t size);
size_t aes192XtsDecrypt(Aes192XtsContext *ctx, void *dst, const void *src, size_t size);
/// 256-bit XTS API.
void aes256XtsContextCreate(Aes256XtsContext *out, const void *key0, const void *key1, bool is_encryptor);
void aes256XtsContextResetTweak(Aes256XtsContext *ctx, const void *tweak);
void aes256XtsContextResetSector(Aes256XtsContext *ctx, uint64_t sector, bool is_nintendo);
size_t aes256XtsEncrypt(Aes256XtsContext *ctx, void *dst, const void *src, size_t size);
size_t aes256XtsDecrypt(Aes256XtsContext *ctx, void *dst, const void *src, size_t size);

View file

@ -0,0 +1,86 @@
## *
## @file AES_xts.h
## @brief Hardware accelerated AES-XTS implementation.
## @copyright libnx Authors
##
import
aes, ../types
## / Context for AES-128 XTS.
type
Aes128XtsContext* {.bycopy.} = object
aesCtx*: Aes128Context
tweakCtx*: Aes128Context
tweak*: array[AES_Block_Size, U8]
buffer*: array[AES_Block_Size, U8]
numBuffered*: csize_t
## / Context for AES-192 XTS.
type
Aes192XtsContext* {.bycopy.} = object
aesCtx*: Aes192Context
tweakCtx*: Aes192Context
tweak*: array[AES_Block_Size, U8]
buffer*: array[AES_Block_Size, U8]
numBuffered*: csize_t
## / Context for AES-256 XTS.
type
Aes256XtsContext* {.bycopy.} = object
aesCtx*: Aes256Context
tweakCtx*: Aes256Context
tweak*: array[AES_Block_Size, U8]
buffer*: array[AES_Block_Size, U8]
numBuffered*: csize_t
## / 128-bit XTS API.
proc aes128XtsContextCreate*(`out`: ptr Aes128XtsContext; key0: pointer;
key1: pointer; isEncryptor: bool) {.cdecl,
importc: "aes128XtsContextCreate".}
proc aes128XtsContextResetTweak*(ctx: ptr Aes128XtsContext; tweak: pointer) {.cdecl,
importc: "aes128XtsContextResetTweak".}
proc aes128XtsContextResetSector*(ctx: ptr Aes128XtsContext; sector: uint64;
isNintendo: bool) {.cdecl,
importc: "aes128XtsContextResetSector".}
proc aes128XtsEncrypt*(ctx: ptr Aes128XtsContext; dst: pointer; src: pointer;
size: csize_t): csize_t {.cdecl, importc: "aes128XtsEncrypt".}
proc aes128XtsDecrypt*(ctx: ptr Aes128XtsContext; dst: pointer; src: pointer;
size: csize_t): csize_t {.cdecl, importc: "aes128XtsDecrypt".}
## / 192-bit XTS API.
proc aes192XtsContextCreate*(`out`: ptr Aes192XtsContext; key0: pointer;
key1: pointer; isEncryptor: bool) {.cdecl,
importc: "aes192XtsContextCreate".}
proc aes192XtsContextResetTweak*(ctx: ptr Aes192XtsContext; tweak: pointer) {.cdecl,
importc: "aes192XtsContextResetTweak".}
proc aes192XtsContextResetSector*(ctx: ptr Aes192XtsContext; sector: uint64;
isNintendo: bool) {.cdecl,
importc: "aes192XtsContextResetSector".}
proc aes192XtsEncrypt*(ctx: ptr Aes192XtsContext; dst: pointer; src: pointer;
size: csize_t): csize_t {.cdecl, importc: "aes192XtsEncrypt".}
proc aes192XtsDecrypt*(ctx: ptr Aes192XtsContext; dst: pointer; src: pointer;
size: csize_t): csize_t {.cdecl, importc: "aes192XtsDecrypt".}
## / 256-bit XTS API.
proc aes256XtsContextCreate*(`out`: ptr Aes256XtsContext; key0: pointer;
key1: pointer; isEncryptor: bool) {.cdecl,
importc: "aes256XtsContextCreate".}
proc aes256XtsContextResetTweak*(ctx: ptr Aes256XtsContext; tweak: pointer) {.cdecl,
importc: "aes256XtsContextResetTweak".}
proc aes256XtsContextResetSector*(ctx: ptr Aes256XtsContext; sector: uint64;
isNintendo: bool) {.cdecl,
importc: "aes256XtsContextResetSector".}
proc aes256XtsEncrypt*(ctx: ptr Aes256XtsContext; dst: pointer; src: pointer;
size: csize_t): csize_t {.cdecl, importc: "aes256XtsEncrypt".}
proc aes256XtsDecrypt*(ctx: ptr Aes256XtsContext; dst: pointer; src: pointer;
size: csize_t): csize_t {.cdecl, importc: "aes256XtsDecrypt".}

View file

@ -0,0 +1,67 @@
/**
* @file cmac.h
* @brief Hardware accelerated AES-CMAC implementation.
* @copyright libnx Authors
*/
#pragma once
#include "aes.h"
/// Context for AES-128 CMAC.
typedef struct {
Aes128Context ctx;
u8 subkey[AES_BLOCK_SIZE];
u8 mac[AES_BLOCK_SIZE];
u8 buffer[AES_BLOCK_SIZE];
size_t num_buffered;
bool finalized;
} Aes128CmacContext;
/// Context for AES-192 CMAC.
typedef struct {
Aes192Context ctx;
u8 subkey[AES_BLOCK_SIZE];
u8 mac[AES_BLOCK_SIZE];
u8 buffer[AES_BLOCK_SIZE];
size_t num_buffered;
bool finalized;
} Aes192CmacContext;
/// Context for AES-256 CMAC.
typedef struct {
Aes256Context ctx;
u8 subkey[AES_BLOCK_SIZE];
u8 mac[AES_BLOCK_SIZE];
u8 buffer[AES_BLOCK_SIZE];
size_t num_buffered;
bool finalized;
} Aes256CmacContext;
/// Initialize an AES-128-CMAC context.
void cmacAes128ContextCreate(Aes128CmacContext *out, const void *key);
/// Updates AES-128-CMAC context with data to hash
void cmacAes128ContextUpdate(Aes128CmacContext *ctx, const void *src, size_t size);
/// Gets the context's output mac, finalizes the context.
void cmacAes128ContextGetMac(Aes128CmacContext *ctx, void *dst);
/// Simple all-in-one AES-128-CMAC calculator.
void cmacAes128CalculateMac(void *dst, const void *key, const void *src, size_t size);
/// Initialize an AES-192-CMAC context.
void cmacAes192ContextCreate(Aes192CmacContext *out, const void *key);
/// Updates AES-192-CMAC context with data to hash
void cmacAes192ContextUpdate(Aes192CmacContext *ctx, const void *src, size_t size);
/// Gets the context's output mac, finalizes the context.
void cmacAes192ContextGetMac(Aes192CmacContext *ctx, void *dst);
/// Simple all-in-one AES-192-CMAC calculator.
void cmacAes192CalculateMac(void *dst, const void *key, const void *src, size_t size);
/// Initialize an AES-256-CMAC context.
void cmacAes256ContextCreate(Aes256CmacContext *out, const void *key);
/// Updates AES-256-CMAC context with data to hash
void cmacAes256ContextUpdate(Aes256CmacContext *ctx, const void *src, size_t size);
/// Gets the context's output mac, finalizes the context.
void cmacAes256ContextGetMac(Aes256CmacContext *ctx, void *dst);
/// Simple all-in-one AES-256-CMAC calculator.
void cmacAes256CalculateMac(void *dst, const void *key, const void *src, size_t size);

View file

@ -0,0 +1,92 @@
## *
## @file cmac.h
## @brief Hardware accelerated AES-CMAC implementation.
## @copyright libnx Authors
##
import
aes, ../types
## / Context for AES-128 CMAC.
type
Aes128CmacContext* {.bycopy.} = object
ctx*: Aes128Context
subkey*: array[AES_Block_Size, U8]
mac*: array[AES_Block_Size, U8]
buffer*: array[AES_Block_Size, U8]
numBuffered*: csize_t
finalized*: bool
## / Context for AES-192 CMAC.
type
Aes192CmacContext* {.bycopy.} = object
ctx*: Aes192Context
subkey*: array[AES_Block_Size, U8]
mac*: array[AES_Block_Size, U8]
buffer*: array[AES_Block_Size, U8]
numBuffered*: csize_t
finalized*: bool
## / Context for AES-256 CMAC.
type
Aes256CmacContext* {.bycopy.} = object
ctx*: Aes256Context
subkey*: array[AES_Block_Size, U8]
mac*: array[AES_Block_Size, U8]
buffer*: array[AES_Block_Size, U8]
numBuffered*: csize_t
finalized*: bool
proc cmacAes128ContextCreate*(`out`: ptr Aes128CmacContext; key: pointer) {.cdecl,
importc: "cmacAes128ContextCreate".}
## / Initialize an AES-128-CMAC context.
proc cmacAes128ContextUpdate*(ctx: ptr Aes128CmacContext; src: pointer; size: csize_t) {.
cdecl, importc: "cmacAes128ContextUpdate".}
## / Updates AES-128-CMAC context with data to hash
proc cmacAes128ContextGetMac*(ctx: ptr Aes128CmacContext; dst: pointer) {.cdecl,
importc: "cmacAes128ContextGetMac".}
## / Gets the context's output mac, finalizes the context.
proc cmacAes128CalculateMac*(dst: pointer; key: pointer; src: pointer; size: csize_t) {.
cdecl, importc: "cmacAes128CalculateMac".}
## / Simple all-in-one AES-128-CMAC calculator.
proc cmacAes192ContextCreate*(`out`: ptr Aes192CmacContext; key: pointer) {.cdecl,
importc: "cmacAes192ContextCreate".}
## / Initialize an AES-192-CMAC context.
proc cmacAes192ContextUpdate*(ctx: ptr Aes192CmacContext; src: pointer; size: csize_t) {.
cdecl, importc: "cmacAes192ContextUpdate".}
## / Updates AES-192-CMAC context with data to hash
proc cmacAes192ContextGetMac*(ctx: ptr Aes192CmacContext; dst: pointer) {.cdecl,
importc: "cmacAes192ContextGetMac".}
## / Gets the context's output mac, finalizes the context.
proc cmacAes192CalculateMac*(dst: pointer; key: pointer; src: pointer; size: csize_t) {.
cdecl, importc: "cmacAes192CalculateMac".}
## / Simple all-in-one AES-192-CMAC calculator.
proc cmacAes256ContextCreate*(`out`: ptr Aes256CmacContext; key: pointer) {.cdecl,
importc: "cmacAes256ContextCreate".}
## / Initialize an AES-256-CMAC context.
proc cmacAes256ContextUpdate*(ctx: ptr Aes256CmacContext; src: pointer; size: csize_t) {.
cdecl, importc: "cmacAes256ContextUpdate".}
## / Updates AES-256-CMAC context with data to hash
proc cmacAes256ContextGetMac*(ctx: ptr Aes256CmacContext; dst: pointer) {.cdecl,
importc: "cmacAes256ContextGetMac".}
## / Gets the context's output mac, finalizes the context.
proc cmacAes256CalculateMac*(dst: pointer; key: pointer; src: pointer; size: csize_t) {.
cdecl, importc: "cmacAes256CalculateMac".}
## / Simple all-in-one AES-256-CMAC calculator.

View file

@ -0,0 +1,84 @@
/**
* @file crc.h
* @brief Hardware accelerated CRC32 implementation.
* @copyright libnx Authors
*/
#pragma once
#include <arm_acle.h>
#include "../types.h"
#define _CRC_ALIGN(sz, insn) \
do { \
if (((uintptr_t)src_u8 & sizeof(sz)) && (u64)len >= sizeof(sz)) { \
crc = __crc32##insn(crc, *((const sz *)src_u8)); \
src_u8 += sizeof(sz); \
len -= sizeof(sz); \
} \
} while (0);
#define _CRC_REMAINDER(sz, insn) \
do { \
if (len & sizeof(sz)) { \
crc = __crc32##insn(crc, *((const sz *)src_u8)); \
src_u8 += sizeof(sz); \
} \
} while (0)
/// Calculate a CRC32 over data using a seed.
/// Can be used to calculate a CRC32 in chunks using an initial seed of zero for the first chunk.
static inline u32 crc32CalculateWithSeed(u32 seed, const void *src, size_t size) {
const u8 *src_u8 = (const u8 *)src;
u32 crc = ~seed;
s64 len = size;
_CRC_ALIGN(u8, b);
_CRC_ALIGN(u16, h);
_CRC_ALIGN(u32, w);
while ((len -= sizeof(u64)) >= 0) {
crc = __crc32d(crc, *((const u64 *)src_u8));
src_u8 += sizeof(u64);
}
_CRC_REMAINDER(u32, w);
_CRC_REMAINDER(u16, h);
_CRC_REMAINDER(u8, b);
return ~crc;
}
/// Calculate a CRC32 over data.
static inline u32 crc32Calculate(const void *src, size_t size) {
return crc32CalculateWithSeed(0, src, size);
}
/// Calculate a CRC32C over data using a seed.
/// Can be used to calculate a CRC32C in chunks using an initial seed of zero for the first chunk.
static inline u32 crc32cCalculateWithSeed(u32 seed, const void *src, size_t size) {
const u8 *src_u8 = (const u8 *)src;
u32 crc = ~seed;
s64 len = size;
_CRC_ALIGN(u8, cb);
_CRC_ALIGN(u16, ch);
_CRC_ALIGN(u32, cw);
while ((len -= sizeof(u64)) >= 0) {
crc = __crc32cd(crc, *((const u64 *)src_u8));
src_u8 += sizeof(u64);
}
_CRC_REMAINDER(u32, cw);
_CRC_REMAINDER(u16, ch);
_CRC_REMAINDER(u8, cb);
return ~crc;
}
/// Calculate a CRC32C over data.
static inline u32 crc32cCalculate(const void *src, size_t size) {
return crc32cCalculateWithSeed(0, src, size);
}

View file

@ -0,0 +1,92 @@
## *
## @file crc.h
## @brief Hardware accelerated CRC32 implementation.
## @copyright libnx Authors
##
import
../types
{.emit: """
#include <arm_acle.h>
#define _CRC_ALIGN(sz, insn) \
do { \
if (((uintptr_t)src_u8 & sizeof(sz)) && (u64)len >= sizeof(sz)) { \
crc = __crc32##insn(crc, *((const sz *)src_u8)); \
src_u8 += sizeof(sz); \
len -= sizeof(sz); \
} \
} while (0);
#define _CRC_REMAINDER(sz, insn) \
do { \
if (len & sizeof(sz)) { \
crc = __crc32##insn(crc, *((const sz *)src_u8)); \
src_u8 += sizeof(sz); \
} \
} while (0)
""".}
proc crc32CalculateWithSeed*(seed: U32; src: pointer; size: csize_t): U32 {.inline,
cdecl.} =
## / Calculate a CRC32 over data using a seed.
## / Can be used to calculate a CRC32 in chunks using an initial seed of zero for the first chunk.
{.emit: """
const u8 *src_u8 = (const u8 *)src;
u32 crc = ~seed;
s64 len = size;
_CRC_ALIGN(u8, b);
_CRC_ALIGN(u16, h);
_CRC_ALIGN(u32, w);
while ((len -= sizeof(u64)) >= 0) {
crc = __crc32d(crc, *((const u64 *)src_u8));
src_u8 += sizeof(u64);
}
_CRC_REMAINDER(u32, w);
_CRC_REMAINDER(u16, h);
_CRC_REMAINDER(u8, b);
""".}
{.emit: "`result` = ~crc;".}
proc crc32Calculate*(src: pointer; size: csize_t): U32 {.inline, cdecl.} =
## / Calculate a CRC32 over data.
return crc32CalculateWithSeed(0, src, size)
proc crc32cCalculateWithSeed*(seed: U32; src: pointer; size: csize_t): U32 {.inline,
cdecl.} =
## / Calculate a CRC32C over data using a seed.
## / Can be used to calculate a CRC32C in chunks using an initial seed of zero for the first chunk.
{.emit: """
const u8 *src_u8 = (const u8 *)src;
u32 crc = ~seed;
s64 len = size;
_CRC_ALIGN(u8, cb);
_CRC_ALIGN(u16, ch);
_CRC_ALIGN(u32, cw);
while ((len -= sizeof(u64)) >= 0) {
crc = __crc32cd(crc, *((const u64 *)src_u8));
src_u8 += sizeof(u64);
}
_CRC_REMAINDER(u32, cw);
_CRC_REMAINDER(u16, ch);
_CRC_REMAINDER(u8, cb);
""".}
{.emit: "`result` = ~crc;".}
proc crc32cCalculate*(src: pointer; size: csize_t): U32 {.inline, cdecl.} =
## / Calculate a CRC32C over data.
return crc32cCalculateWithSeed(0, src, size)

View file

@ -0,0 +1,51 @@
/**
* @file hmac.h
* @brief Hardware accelerated HMAC-SHA(1, 256) implementation.
* @copyright libnx Authors
*/
#pragma once
#include "sha1.h"
#include "sha256.h"
/// Context for HMAC-SHA1 operations.
typedef struct {
Sha1Context sha_ctx;
u32 key[SHA1_BLOCK_SIZE / sizeof(u32)];
u32 mac[SHA1_HASH_SIZE / sizeof(u32)];
bool finalized;
} HmacSha1Context;
/// Context for HMAC-SHA256 operations.
typedef struct {
Sha256Context sha_ctx;
u32 key[SHA256_BLOCK_SIZE / sizeof(u32)];
u32 mac[SHA256_HASH_SIZE / sizeof(u32)];
bool finalized;
} HmacSha256Context;
#ifndef HMAC_SHA1_KEY_MAX
#define HMAC_SHA1_KEY_MAX (sizeof(((HmacSha1Context *)NULL)->key))
#endif
#ifndef HMAC_SHA256_KEY_MAX
#define HMAC_SHA256_KEY_MAX (sizeof(((HmacSha256Context *)NULL)->key))
#endif
/// Initialize a HMAC-SHA256 context.
void hmacSha256ContextCreate(HmacSha256Context *out, const void *key, size_t key_size);
/// Updates HMAC-SHA256 context with data to hash
void hmacSha256ContextUpdate(HmacSha256Context *ctx, const void *src, size_t size);
/// Gets the context's output mac, finalizes the context.
void hmacSha256ContextGetMac(HmacSha256Context *ctx, void *dst);
/// Simple all-in-one HMAC-SHA256 calculator.
void hmacSha256CalculateMac(void *dst, const void *key, size_t key_size, const void *src, size_t size);
/// Initialize a HMAC-SHA1 context.
void hmacSha1ContextCreate(HmacSha1Context *out, const void *key, size_t key_size);
/// Updates HMAC-SHA1 context with data to hash
void hmacSha1ContextUpdate(HmacSha1Context *ctx, const void *src, size_t size);
/// Gets the context's output mac, finalizes the context.
void hmacSha1ContextGetMac(HmacSha1Context *ctx, void *dst);
/// Simple all-in-one HMAC-SHA1 calculator.
void hmacSha1CalculateMac(void *dst, const void *key, size_t key_size, const void *src, size_t size);

View file

@ -0,0 +1,67 @@
## *
## @file hmac.h
## @brief Hardware accelerated HMAC-SHA(1, 256) implementation.
## @copyright libnx Authors
##
import
sha1, sha256, ../types
## / Context for HMAC-SHA1 operations.
type
HmacSha1Context* {.bycopy.} = object
shaCtx*: Sha1Context
key*: array[Sha1Block_Size div sizeof(U32), U32]
mac*: array[Sha1Hash_Size div sizeof(U32), U32]
finalized*: bool
## / Context for HMAC-SHA256 operations.
type
HmacSha256Context* {.bycopy.} = object
shaCtx*: Sha256Context
key*: array[Sha256Block_Size div sizeof((U32)), U32]
mac*: array[Sha256Hash_Size div sizeof((U32)), U32]
finalized*: bool
const
HMAC_SHA1_KEY_MAX* = (sizeof(((cast[ptr HmacSha1Context](nil)).key)))
HMAC_SHA256_KEY_MAX* = (sizeof(((cast[ptr HmacSha256Context](nil)).key)))
proc hmacSha256ContextCreate*(`out`: ptr HmacSha256Context; key: pointer;
keySize: csize_t) {.cdecl,
importc: "hmacSha256ContextCreate".}
## / Initialize a HMAC-SHA256 context.
proc hmacSha256ContextUpdate*(ctx: ptr HmacSha256Context; src: pointer; size: csize_t) {.
cdecl, importc: "hmacSha256ContextUpdate".}
## / Updates HMAC-SHA256 context with data to hash
proc hmacSha256ContextGetMac*(ctx: ptr HmacSha256Context; dst: pointer) {.cdecl,
importc: "hmacSha256ContextGetMac".}
## / Gets the context's output mac, finalizes the context.
proc hmacSha256CalculateMac*(dst: pointer; key: pointer; keySize: csize_t;
src: pointer; size: csize_t) {.cdecl,
importc: "hmacSha256CalculateMac".}
## / Simple all-in-one HMAC-SHA256 calculator.
proc hmacSha1ContextCreate*(`out`: ptr HmacSha1Context; key: pointer; keySize: csize_t) {.
cdecl, importc: "hmacSha1ContextCreate".}
## / Initialize a HMAC-SHA1 context.
proc hmacSha1ContextUpdate*(ctx: ptr HmacSha1Context; src: pointer; size: csize_t) {.
cdecl, importc: "hmacSha1ContextUpdate".}
## / Updates HMAC-SHA1 context with data to hash
proc hmacSha1ContextGetMac*(ctx: ptr HmacSha1Context; dst: pointer) {.cdecl,
importc: "hmacSha1ContextGetMac".}
## / Gets the context's output mac, finalizes the context.
proc hmacSha1CalculateMac*(dst: pointer; key: pointer; keySize: csize_t; src: pointer;
size: csize_t) {.cdecl, importc: "hmacSha1CalculateMac".}
## / Simple all-in-one HMAC-SHA1 calculator.

View file

@ -0,0 +1,34 @@
/**
* @file sha1.h
* @brief Hardware accelerated SHA1 implementation.
* @copyright libnx Authors
*/
#pragma once
#include "../types.h"
#ifndef SHA1_HASH_SIZE
#define SHA1_HASH_SIZE 0x14
#endif
#ifndef SHA1_BLOCK_SIZE
#define SHA1_BLOCK_SIZE 0x40
#endif
/// Context for SHA1 operations.
typedef struct {
u32 intermediate_hash[SHA1_HASH_SIZE / sizeof(u32)];
u8 buffer[SHA1_BLOCK_SIZE];
u64 bits_consumed;
size_t num_buffered;
bool finalized;
} Sha1Context;
/// Initialize a SHA1 context.
void sha1ContextCreate(Sha1Context *out);
/// Updates SHA1 context with data to hash
void sha1ContextUpdate(Sha1Context *ctx, const void *src, size_t size);
/// Gets the context's output hash, finalizes the context.
void sha1ContextGetHash(Sha1Context *ctx, void *dst);
/// Simple all-in-one SHA1 calculator.
void sha1CalculateHash(void *dst, const void *src, size_t size);

View file

@ -0,0 +1,37 @@
## *
## @file sha1.h
## @brief Hardware accelerated SHA1 implementation.
## @copyright libnx Authors
##
import
../types
const
SHA1_HASH_SIZE* = 0x14
SHA1_BLOCK_SIZE* = 0x40
## / Context for SHA1 operations.
type
Sha1Context* {.bycopy.} = object
intermediateHash*: array[Sha1Hash_Size div sizeof((U32)), U32]
buffer*: array[Sha1Block_Size, U8]
bitsConsumed*: U64
numBuffered*: csize_t
finalized*: bool
proc sha1ContextCreate*(`out`: ptr Sha1Context) {.cdecl, importc: "sha1ContextCreate".}
## / Initialize a SHA1 context.
proc sha1ContextUpdate*(ctx: ptr Sha1Context; src: pointer; size: csize_t) {.cdecl,
importc: "sha1ContextUpdate".}
## / Updates SHA1 context with data to hash
proc sha1ContextGetHash*(ctx: ptr Sha1Context; dst: pointer) {.cdecl,
importc: "sha1ContextGetHash".}
## / Gets the context's output hash, finalizes the context.
proc sha1CalculateHash*(dst: pointer; src: pointer; size: csize_t) {.cdecl,
importc: "sha1CalculateHash".}
## / Simple all-in-one SHA1 calculator.

View file

@ -0,0 +1,35 @@
/**
* @file sha256.h
* @brief Hardware accelerated SHA256 implementation.
* @copyright libnx Authors
*/
#pragma once
#include "../types.h"
#ifndef SHA256_HASH_SIZE
#define SHA256_HASH_SIZE 0x20
#endif
#ifndef SHA256_BLOCK_SIZE
#define SHA256_BLOCK_SIZE 0x40
#endif
/// Context for SHA256 operations.
typedef struct {
u32 intermediate_hash[SHA256_HASH_SIZE / sizeof(u32)];
u8 buffer[SHA256_BLOCK_SIZE];
u64 bits_consumed;
size_t num_buffered;
bool finalized;
} Sha256Context;
/// Initialize a SHA256 context.
void sha256ContextCreate(Sha256Context *out);
/// Updates SHA256 context with data to hash
void sha256ContextUpdate(Sha256Context *ctx, const void *src, size_t size);
/// Gets the context's output hash, finalizes the context.
void sha256ContextGetHash(Sha256Context *ctx, void *dst);
/// Simple all-in-one SHA256 calculator.
void sha256CalculateHash(void *dst, const void *src, size_t size);

View file

@ -0,0 +1,41 @@
## *
## @file sha256.h
## @brief Hardware accelerated SHA256 implementation.
## @copyright libnx Authors
##
import
../types
when not defined(SHA256_HASH_SIZE):
const
SHA256_HASH_SIZE* = 0x20
when not defined(SHA256_BLOCK_SIZE):
const
SHA256_BLOCK_SIZE* = 0x40
## / Context for SHA256 operations.
type
Sha256Context* {.bycopy.} = object
intermediateHash*: array[Sha256Hash_Size div sizeof((U32)), U32]
buffer*: array[Sha256Block_Size, U8]
bitsConsumed*: U64
numBuffered*: csize_t
finalized*: bool
proc sha256ContextCreate*(`out`: ptr Sha256Context) {.cdecl,
importc: "sha256ContextCreate".}
## / Initialize a SHA256 context.
proc sha256ContextUpdate*(ctx: ptr Sha256Context; src: pointer; size: csize_t) {.cdecl,
importc: "sha256ContextUpdate".}
## / Updates SHA256 context with data to hash
proc sha256ContextGetHash*(ctx: ptr Sha256Context; dst: pointer) {.cdecl,
importc: "sha256ContextGetHash".}
## / Gets the context's output hash, finalizes the context.
proc sha256CalculateHash*(dst: pointer; src: pointer; size: csize_t) {.cdecl,
importc: "sha256CalculateHash".}
## / Simple all-in-one SHA256 calculator.

View file

@ -0,0 +1,51 @@
#pragma once
#include "../types.h"
#include "../kernel/event.h"
#include "../sf/service.h"
#define BINDER_FIRST_CALL_TRANSACTION 0x1
typedef struct {
bool created;
bool initialized;
s32 id;
size_t dummy;
Service* relay;
} Binder;
// Note: binderClose will not close the session_handle provided to binderCreate.
void binderCreate(Binder* b, s32 id);
void binderClose(Binder* b);
Result binderInitSession(Binder* b, Service* relay);
Result binderTransactParcel(
Binder* b, u32 code,
void* parcel_data, size_t parcel_data_size,
void* parcel_reply, size_t parcel_reply_size,
u32 flags);
Result binderConvertErrorCode(s32 code);
Result binderAdjustRefcount(Binder* b, s32 addval, s32 type);
Result binderGetNativeHandle(Binder* b, u32 unk0, Event *event_out);
static inline Result binderIncreaseWeakRef(Binder* b)
{
return binderAdjustRefcount(b, 1, 0);
}
static inline Result binderDecreaseWeakRef(Binder* b)
{
return binderAdjustRefcount(b, -1, 0);
}
static inline Result binderIncreaseStrongRef(Binder* b)
{
return binderAdjustRefcount(b, 1, 1);
}
static inline Result binderDecreaseStrongRef(Binder* b)
{
return binderAdjustRefcount(b, -1, 1);
}

View file

@ -0,0 +1,46 @@
import
../types, ../kernel/event, ../sf/service
const
BINDER_FIRST_CALL_TRANSACTION* = 0x1
type
Binder* {.bycopy.} = object
created*: bool
initialized*: bool
id*: S32
dummy*: csize_t
relay*: ptr Service
## Note: binderClose will not close the session_handle provided to binderCreate.
proc binderCreate*(b: ptr Binder; id: S32) {.cdecl, importc: "binderCreate".}
proc binderClose*(b: ptr Binder) {.cdecl, importc: "binderClose".}
proc binderInitSession*(b: ptr Binder; relay: ptr Service): Result {.cdecl,
importc: "binderInitSession".}
proc binderTransactParcel*(b: ptr Binder; code: U32; parcelData: pointer;
parcelDataSize: csize_t; parcelReply: pointer;
parcelReplySize: csize_t; flags: U32): Result {.cdecl,
importc: "binderTransactParcel".}
proc binderConvertErrorCode*(code: S32): Result {.cdecl,
importc: "binderConvertErrorCode".}
proc binderAdjustRefcount*(b: ptr Binder; addval: S32; `type`: S32): Result {.cdecl,
importc: "binderAdjustRefcount".}
proc binderGetNativeHandle*(b: ptr Binder; unk0: U32; eventOut: ptr Event): Result {.
cdecl, importc: "binderGetNativeHandle".}
proc binderIncreaseWeakRef*(b: ptr Binder): Result {.inline, cdecl,
importc: "binderIncreaseWeakRef".} =
return binderAdjustRefcount(b, 1, 0)
proc binderDecreaseWeakRef*(b: ptr Binder): Result {.inline, cdecl,
importc: "binderDecreaseWeakRef".} =
return binderAdjustRefcount(b, -1, 0)
proc binderIncreaseStrongRef*(b: ptr Binder): Result {.inline, cdecl,
importc: "binderIncreaseStrongRef".} =
return binderAdjustRefcount(b, 1, 1)
proc binderDecreaseStrongRef*(b: ptr Binder): Result {.inline, cdecl,
importc: "binderDecreaseStrongRef".} =
return binderAdjustRefcount(b, -1, 1)

View file

@ -0,0 +1,49 @@
#pragma once
#include "types.h"
#include "binder.h"
#include "../nvidia/fence.h"
typedef struct {
s32 left;
s32 top;
s32 right;
s32 bottom;
} BqRect;
typedef struct {
struct { s64 timestamp; } PACKED;
s32 isAutoTimestamp;
BqRect crop;
s32 scalingMode;
u32 transform; // See the NATIVE_WINDOW_TRANSFORM_* enums.
u32 stickyTransform;
u32 unk;
u32 swapInterval;
NvMultiFence fence;
} BqBufferInput;
typedef struct {
u32 width;
u32 height;
u32 transformHint;
u32 numPendingBuffers;
} BqBufferOutput;
typedef struct {
u32 width;
u32 height;
u32 stride;
u32 format;
u32 usage;
NativeHandle* native_handle;
} BqGraphicBuffer;
Result bqRequestBuffer(Binder *b, s32 bufferIdx, BqGraphicBuffer *buf);
Result bqDequeueBuffer(Binder *b, bool async, u32 width, u32 height, s32 format, u32 usage, s32 *buf, NvMultiFence *fence);
Result bqDetachBuffer(Binder *b, s32 slot);
Result bqQueueBuffer(Binder *b, s32 buf, const BqBufferInput *input, BqBufferOutput *output);
Result bqCancelBuffer(Binder *b, s32 buf, const NvMultiFence *fence);
Result bqQuery(Binder *b, s32 what, s32* value);
Result bqConnect(Binder *b, s32 api, bool producerControlledByApp, BqBufferOutput *output);
Result bqDisconnect(Binder *b, s32 api);
Result bqSetPreallocatedBuffer(Binder *b, s32 buf, const BqGraphicBuffer *input);

View file

@ -0,0 +1,57 @@
import
types as t, binder, ../nvidia/fence, ../types
type
INNER_C_STRUCT_buffer_producer_2* {.bycopy.} = object
timestamp*: S64
BqRect* {.bycopy.} = object
left*: S32
top*: S32
right*: S32
bottom*: S32
BqBufferInput* {.bycopy.} = object
anoBufferProducer3*: INNER_C_STRUCT_buffer_producer_2
isAutoTimestamp*: S32
crop*: BqRect
scalingMode*: S32
transform*: U32 ## See the NATIVE_WINDOW_TRANSFORM_* enums.
stickyTransform*: U32
unk*: U32
swapInterval*: U32
fence*: NvMultiFence
BqBufferOutput* {.bycopy.} = object
width*: U32
height*: U32
transformHint*: U32
numPendingBuffers*: U32
BqGraphicBuffer* {.bycopy.} = object
width*: U32
height*: U32
stride*: U32
format*: U32
usage*: U32
nativeHandle*: ptr NativeHandle
proc bqRequestBuffer*(b: ptr Binder; bufferIdx: S32; buf: ptr BqGraphicBuffer): Result {.
cdecl, importc: "bqRequestBuffer".}
proc bqDequeueBuffer*(b: ptr Binder; async: bool; width: U32; height: U32; format: S32;
usage: U32; buf: ptr S32; fence: ptr NvMultiFence): Result {.cdecl,
importc: "bqDequeueBuffer".}
proc bqDetachBuffer*(b: ptr Binder; slot: S32): Result {.cdecl,
importc: "bqDetachBuffer".}
proc bqQueueBuffer*(b: ptr Binder; buf: S32; input: ptr BqBufferInput;
output: ptr BqBufferOutput): Result {.cdecl,
importc: "bqQueueBuffer".}
proc bqCancelBuffer*(b: ptr Binder; buf: S32; fence: ptr NvMultiFence): Result {.cdecl,
importc: "bqCancelBuffer".}
proc bqQuery*(b: ptr Binder; what: S32; value: ptr S32): Result {.cdecl, importc: "bqQuery".}
proc bqConnect*(b: ptr Binder; api: S32; producerControlledByApp: bool;
output: ptr BqBufferOutput): Result {.cdecl, importc: "bqConnect".}
proc bqDisconnect*(b: ptr Binder; api: S32): Result {.cdecl, importc: "bqDisconnect".}
proc bqSetPreallocatedBuffer*(b: ptr Binder; buf: S32; input: ptr BqGraphicBuffer): Result {.
cdecl, importc: "bqSetPreallocatedBuffer".}

View file

@ -0,0 +1,104 @@
/**
* @file framebuffer.h
* @brief Framebuffer wrapper object, providing support for software rendered graphics.
* @author fincs
* @copyright libnx Authors
*/
#pragma once
#include "../nvidia/map.h"
#include "native_window.h"
/// Converts red/green/blue/alpha components to packed RGBA8 (i.e. \ref PIXEL_FORMAT_RGBA_8888).
#define RGBA8(r,g,b,a) (((r)&0xff)|(((g)&0xff)<<8)|(((b)&0xff)<<16)|(((a)&0xff)<<24))
/// Same as \ref RGBA8 except with alpha=0xff.
#define RGBA8_MAXALPHA(r,g,b) RGBA8((r),(g),(b),0xff)
/// Converts red/green/blue to packed RGBX8 (i.e. \ref PIXEL_FORMAT_RGBX_8888).
#define RGBX8(r,g,b) RGBA8((r),(g),(b),0)
/// Converts red/green/blue components to packed RGB565 (i.e. \ref PIXEL_FORMAT_RGB_565)
#define RGB565(r,g,b) (((b)&0x1f)|(((g)&0x3f)<<5)|(((r)&0x1f)<<11))
/// Same as \ref RGB565 but accepting 8-bit components as input instead.
#define RGB565_FROM_RGB8(r,g,b) RGB565((r)>>3,(g)>>2,(b)>>3)
/// Converts red/green/blue/alpha components to packed BGR8 (i.e. \ref PIXEL_FORMAT_BGRA_8888).
#define BGRA8(r,g,b,a) RGBA8((b),(g),(r),(a))
/// Same as \ref BGRA8 except with alpha=0xff.
#define BGRA8_MAXALPHA(r,g,b) RGBA8((b),(g),(r),0xff)
/// Converts red/green/blue/alpha components to packed RGBA4 (i.e. \ref PIXEL_FORMAT_RGBA_4444).
#define RGBA4(r,g,b,a) (((r)&0xf)|(((g)&0xf)<<4)|(((b)&0xf)<<8)|(((a)&0xf)<<12))
/// Same as \ref RGBA4 except with alpha=0xf.
#define RGBA4_MAXALPHA(r,g,b) RGBA4((r),(g),(b),0xf)
/// Same as \ref RGBA4 but accepting 8-bit components as input instead.
#define RGBA4_FROM_RGBA8(r,g,b,a) RGBA4((r)>>4,(g)>>4,(b)>>4,(a)>>4)
/// Same as \ref RGBA4_MAXALPHA except with alpha=0xff.
#define RGBA4_FROM_RGBA8_MAXALPHA(r,g,b) RGBA4_MAXALPHA((r)>>4,(g)>>4,(b)>>4)
/// Framebuffer structure.
typedef struct Framebuffer {
NWindow *win;
NvMap map;
void* buf;
void* buf_linear;
u32 stride;
u32 width_aligned;
u32 height_aligned;
u32 num_fbs;
u32 fb_size;
bool has_init;
} Framebuffer;
/**
* @brief Creates a \ref Framebuffer object.
* @param[out] fb Output \ref Framebuffer structure.
* @param[in] win Pointer to the \ref NWindow to which the \ref Framebuffer will be registered.
* @param[in] width Desired width of the framebuffer (usually 1280).
* @param[in] height Desired height of the framebuffer (usually 720).
* @param[in] format Desired pixel format (see PIXEL_FORMAT_* enum).
* @param[in] num_fbs Number of buffers to create. Pass 1 for single-buffering, 2 for double-buffering or 3 for triple-buffering.
* @note Framebuffer images are stored in Tegra block linear format with 16Bx2 sector ordering, read TRM chapter 20.1 for more details.
* In order to use regular linear layout, consider calling \ref framebufferMakeLinear after the \ref Framebuffer object is created.
* @note Presently, only the following pixel formats are supported:
* \ref PIXEL_FORMAT_RGBA_8888
* \ref PIXEL_FORMAT_RGBX_8888
* \ref PIXEL_FORMAT_RGB_565
* \ref PIXEL_FORMAT_BGRA_8888
* \ref PIXEL_FORMAT_RGBA_4444
*/
Result framebufferCreate(Framebuffer* fb, NWindow *win, u32 width, u32 height, u32 format, u32 num_fbs);
/// Enables linear framebuffer mode in a \ref Framebuffer, allocating a shadow buffer in the process.
Result framebufferMakeLinear(Framebuffer* fb);
/// Closes a \ref Framebuffer object, freeing all resources associated with it.
void framebufferClose(Framebuffer* fb);
/**
* @brief Begins rendering a frame in a \ref Framebuffer.
* @param[in] fb Pointer to \ref Framebuffer structure.
* @param[out] out_stride Output variable containing the distance in bytes between rows of pixels in memory.
* @return Pointer to buffer to which new graphics data should be written to.
* @note When this function is called, a buffer will be dequeued from the corresponding \ref NWindow.
* @note This function will return pointers to different buffers, depending on the number of buffers it was initialized with.
* @note If \ref framebufferMakeLinear was used, this function will instead return a pointer to the shadow linear buffer.
* In this case, the offset of a pixel is \p y * \p out_stride + \p x * \p bytes_per_pixel.
* @note Each call to \ref framebufferBegin must be paired with a \ref framebufferEnd call.
*/
void* framebufferBegin(Framebuffer* fb, u32* out_stride);
/**
* @brief Finishes rendering a frame in a \ref Framebuffer.
* @param[in] fb Pointer to \ref Framebuffer structure.
* @note When this function is called, the written image data will be flushed and queued (presented) in the corresponding \ref NWindow.
* @note If \ref framebufferMakeLinear was used, this function will copy the image from the shadow linear buffer to the actual framebuffer,
* converting it in the process to the layout expected by the compositor.
* @note Each call to \ref framebufferBegin must be paired with a \ref framebufferEnd call.
*/
void framebufferEnd(Framebuffer* fb);

View file

@ -0,0 +1,133 @@
## *
## @file framebuffer.h
## @brief Framebuffer wrapper object, providing support for software rendered graphics.
## @author fincs
## @copyright libnx Authors
##
import
../nvidia/map, native_window, ../types
## / Converts red/green/blue/alpha components to packed RGBA8 (i.e. \ref PIXEL_FORMAT_RGBA_8888).
template rgba8*(r, g, b, a: untyped): untyped =
(((r) and 0xff) or (((g) and 0xff) shl 8) or (((b) and 0xff) shl 16) or
(((a) and 0xff) shl 24))
## / Same as \ref RGBA8 except with alpha=0xff.
template rgba8Maxalpha*(r, g, b: untyped): untyped =
rgba8((r), (g), (b), 0xff)
## / Converts red/green/blue to packed RGBX8 (i.e. \ref PIXEL_FORMAT_RGBX_8888).
template rgbx8*(r, g, b: untyped): untyped =
rgba8((r), (g), (b), 0)
## / Converts red/green/blue components to packed RGB565 (i.e. \ref PIXEL_FORMAT_RGB_565)
template rgb565*(r, g, b: untyped): untyped =
(((b) and 0x1f) or (((g) and 0x3f) shl 5) or (((r) and 0x1f) shl 11))
## / Same as \ref RGB565 but accepting 8-bit components as input instead.
template rgb565From_Rgb8*(r, g, b: untyped): untyped =
rgb565((r) shr 3, (g) shr 2, (b) shr 3)
## / Converts red/green/blue/alpha components to packed BGR8 (i.e. \ref PIXEL_FORMAT_BGRA_8888).
template bgra8*(r, g, b, a: untyped): untyped =
rgba8((b), (g), (r), (a))
## / Same as \ref BGRA8 except with alpha=0xff.
template bgra8Maxalpha*(r, g, b: untyped): untyped =
rgba8((b), (g), (r), 0xff)
## / Converts red/green/blue/alpha components to packed RGBA4 (i.e. \ref PIXEL_FORMAT_RGBA_4444).
template rgba4*(r, g, b, a: untyped): untyped =
(((r) and 0xf) or (((g) and 0xf) shl 4) or (((b) and 0xf) shl 8) or (((a) and 0xf) shl 12))
## / Same as \ref RGBA4 except with alpha=0xf.
template rgba4Maxalpha*(r, g, b: untyped): untyped =
rgba4((r), (g), (b), 0xf)
## / Same as \ref RGBA4 but accepting 8-bit components as input instead.
template rgba4From_Rgba8*(r, g, b, a: untyped): untyped =
rgba4((r) shr 4, (g) shr 4, (b) shr 4, (a) shr 4)
## / Same as \ref RGBA4_MAXALPHA except with alpha=0xff.
template rgba4From_Rgba8Maxalpha*(r, g, b: untyped): untyped =
rgba4Maxalpha((r) shr 4, (g) shr 4, (b) shr 4)
## / Framebuffer structure.
type
Framebuffer* {.bycopy.} = object
win*: ptr NWindow
map*: NvMap
buf*: pointer
bufLinear*: pointer
stride*: U32
widthAligned*: U32
heightAligned*: U32
numFbs*: U32
fbSize*: U32
hasInit*: bool
proc framebufferCreate*(fb: ptr Framebuffer; win: ptr NWindow; width: U32; height: U32;
format: U32; numFbs: U32): Result {.cdecl,
importc: "framebufferCreate".}
## *
## @brief Creates a \ref Framebuffer object.
## @param[out] fb Output \ref Framebuffer structure.
## @param[in] win Pointer to the \ref NWindow to which the \ref Framebuffer will be registered.
## @param[in] width Desired width of the framebuffer (usually 1280).
## @param[in] height Desired height of the framebuffer (usually 720).
## @param[in] format Desired pixel format (see PIXEL_FORMAT_* enum).
## @param[in] num_fbs Number of buffers to create. Pass 1 for single-buffering, 2 for double-buffering or 3 for triple-buffering.
## @note Framebuffer images are stored in Tegra block linear format with 16Bx2 sector ordering, read TRM chapter 20.1 for more details.
## In order to use regular linear layout, consider calling \ref framebufferMakeLinear after the \ref Framebuffer object is created.
## @note Presently, only the following pixel formats are supported:
## \ref PIXEL_FORMAT_RGBA_8888
## \ref PIXEL_FORMAT_RGBX_8888
## \ref PIXEL_FORMAT_RGB_565
## \ref PIXEL_FORMAT_BGRA_8888
## \ref PIXEL_FORMAT_RGBA_4444
##
proc framebufferMakeLinear*(fb: ptr Framebuffer): Result {.cdecl,
importc: "framebufferMakeLinear".}
## / Enables linear framebuffer mode in a \ref Framebuffer, allocating a shadow buffer in the process.
proc framebufferClose*(fb: ptr Framebuffer) {.cdecl, importc: "framebufferClose".}
## / Closes a \ref Framebuffer object, freeing all resources associated with it.
proc framebufferBegin*(fb: ptr Framebuffer; outStride: ptr U32): pointer {.cdecl,
importc: "framebufferBegin".}
## *
## @brief Begins rendering a frame in a \ref Framebuffer.
## @param[in] fb Pointer to \ref Framebuffer structure.
## @param[out] out_stride Output variable containing the distance in bytes between rows of pixels in memory.
## @return Pointer to buffer to which new graphics data should be written to.
## @note When this function is called, a buffer will be dequeued from the corresponding \ref NWindow.
## @note This function will return pointers to different buffers, depending on the number of buffers it was initialized with.
## @note If \ref framebufferMakeLinear was used, this function will instead return a pointer to the shadow linear buffer.
## In this case, the offset of a pixel is \p y * \p out_stride + \p x * \p bytes_per_pixel.
## @note Each call to \ref framebufferBegin must be paired with a \ref framebufferEnd call.
##
proc framebufferEnd*(fb: ptr Framebuffer) {.cdecl, importc: "framebufferEnd".}
## *
## @brief Finishes rendering a frame in a \ref Framebuffer.
## @param[in] fb Pointer to \ref Framebuffer structure.
## @note When this function is called, the written image data will be flushed and queued (presented) in the corresponding \ref NWindow.
## @note If \ref framebufferMakeLinear was used, this function will copy the image from the shadow linear buffer to the actual framebuffer,
## converting it in the process to the layout expected by the compositor.
## @note Each call to \ref framebufferBegin must be paired with a \ref framebufferEnd call.
##

View file

@ -0,0 +1,190 @@
/**
* @file native_window.h
* @brief Native window (NWindow) wrapper object, used for presenting images to the display (or other sinks).
* @author fincs
* @copyright libnx Authors
*/
#pragma once
#include "../kernel/mutex.h"
#include "../kernel/event.h"
#include "../services/vi.h"
#include "../nvidia/graphic_buffer.h"
#include "types.h"
#include "binder.h"
#include "buffer_producer.h"
/// Native window structure.
typedef struct NWindow {
u32 magic;
Binder bq;
Event event;
Mutex mutex;
u64 slots_configured;
u64 slots_requested;
s32 cur_slot;
u32 width;
u32 height;
u32 format;
u32 usage;
BqRect crop;
u32 scaling_mode;
u32 transform;
u32 sticky_transform;
u32 default_width;
u32 default_height;
u32 swap_interval;
bool is_connected;
bool producer_controlled_by_app;
bool consumer_running_behind;
} NWindow;
///@name Basic functions
///@{
/// Checks whether a pointer refers to a valid \ref NWindow object.
bool nwindowIsValid(NWindow* nw);
/**
* @brief Retrieves the default \ref NWindow object.
* @return Pointer to the default \ref NWindow object.
* @note When this function is used/referenced, libnx will initialize VI services
* and create a \ref NWindow object from a \ref ViLayer created on the default \ref ViDisplay;
* all of this happening automatically during application startup (i.e. before main is called).
* If creating the default \ref NWindow fails, libnx will throw a LibnxError_BadGfxInit fatal error.
* Likewise, after main returns (or exit is called) libnx will clean up all resources used by it.
*/
NWindow* nwindowGetDefault(void);
/**
* @brief Creates a \ref NWindow.
* @param[out] nw Output \ref NWindow structure.
* @param[in] binder_session Service object for the Android IGraphicBufferProducer binder session.
* @param[in] binder_id Android IGraphicBufferProducer binder session ID.
* @param[in] producer_controlled_by_app Specifies whether the producer is controlled by the application.
*/
Result nwindowCreate(NWindow* nw, Service* binder_session, s32 binder_id, bool producer_controlled_by_app);
/**
* @brief Creates a \ref NWindow operating on a \ref ViLayer.
* @param[out] nw Output \ref NWindow structure.
* @param[in] layer Pointer to \ref ViLayer structure (such as the one returned by \ref viCreateLayer).
*/
Result nwindowCreateFromLayer(NWindow* nw, const ViLayer* layer);
/// Closes a \ref NWindow, freeing all resources associated with it.
void nwindowClose(NWindow* nw);
///@}
///@name Window configuration
///@{
/**
* @brief Retrieves the dimensions of a \ref NWindow.
* @param[in] nw Pointer to \ref NWindow structure.
* @param[out] out_width Output variable containing the width of the \ref NWindow.
* @param[out] out_height Output variable containing the height of the \ref NWindow.
* @note After creation, a \ref NWindow reports a default size (usually 1280x720).
* This size can be overriden by calling \ref nwindowSetDimensions.
*/
Result nwindowGetDimensions(NWindow* nw, u32* out_width, u32* out_height);
/**
* @brief Sets the dimensions of a \ref NWindow.
* @param[in] nw Pointer to \ref NWindow structure.
* @param[in] width Desired width of the \ref NWindow.
* @param[in] height Desired width of the \ref NWindow.
* @note This function cannot be called when there are buffers registered with the \ref NWindow.
*/
Result nwindowSetDimensions(NWindow* nw, u32 width, u32 height);
/**
* @brief Configures the crop applied to images presented through a \ref NWindow.
* @param[in] nw Pointer to \ref NWindow structure.
* @param[in] left X coordinate of the left margin of the crop bounding box.
* @param[in] top Y coordinate of the top margin of the crop bounding box.
* @param[in] right X coordinate of the right margin of the crop bounding box.
* @param[in] bottom Y coordinate of the bottom margin of the crop bounding box.
* @note Passing zero to all parameters disables the crop functionality. This is also the default.
* @note The bounding box defined by the parameters will be adjusted to fit within the dimensions of the \ref NWindow.
* @note \p left must be less or equal than \p right.
* @note \p top must be less or equal than \p bottom.
*/
Result nwindowSetCrop(NWindow* nw, s32 left, s32 top, s32 right, s32 bottom);
/**
* @brief Configures the transformation applied to images presented through a \ref NWindow.
* @param[in] nw Pointer to \ref NWindow structure.
* @param[in] transform Android transformation mode (see NATIVE_WINDOW_TRANSFORM_* enum)
* @note The default transformation is 0 (i.e. no transformation applied)
*/
Result nwindowSetTransform(NWindow* nw, u32 transform);
/**
* @brief Configures the swap interval of a \ref NWindow.
* @param[in] nw Pointer to \ref NWindow structure.
* @param[in] swap_interval Value specifying the number of display refreshes (VBlanks) that must occur between presenting images.
* @note The default swap interval is 1.
* @note If the \ref NWindow has three or more buffers configured (with \ref nwindowConfigureBuffer), it is possible to pass 0
* to disable the swap interval feature and present images as fast as allowed by the compositor. Otherwise, the system
* enforces a minimum of 1 as the swap interval.
*/
Result nwindowSetSwapInterval(NWindow* nw, u32 swap_interval);
/// Checks whether the consumer of a \ref NWindow is running behind.
static inline bool nwindowIsConsumerRunningBehind(NWindow* nw)
{
return nw->consumer_running_behind;
}
///@}
///@name Buffer configuration and presentation
///@{
/**
* @brief Registers a \ref NvGraphicBuffer with a \ref NWindow.
* @param[in] nw Pointer to \ref NWindow structure.
* @param[in] slot ID of the slot to configure (starting from 0).
* @param[in] buf Pointer to \ref NvGraphicBuffer structure.
* @note When a buffer is registered, it is added to the internal queue of buffers used for presenting.
* @note All buffers registered with a \ref NWindow must have the same dimensions, format and usage.
* If \ref nwindowSetDimensions has not been previously called, the \ref NWindow will automatically
* adopt the dimensions of the first buffer registered with it. Otherwise, said buffer will need
* to match the dimensions that were previously configured.
*/
Result nwindowConfigureBuffer(NWindow* nw, s32 slot, NvGraphicBuffer* buf);
/**
* @brief Dequeues a buffer from a \ref NWindow.
* @param[in] nw Pointer to \ref NWindow structure.
* @param[out] out_slot Output variable containing the ID of the slot that has been dequeued.
* @param[out] out_fence Output variable containing a \ref NvMultiFence that will be signalled by
* the compositor when the buffer is ready to be written to. Pass NULL to wait instead
* on this fence before this function returns.
* @note For \p out_fence=NULL to work, \ref nvFenceInit must have been previously called.
*/
Result nwindowDequeueBuffer(NWindow* nw, s32* out_slot, NvMultiFence* out_fence);
/**
* @brief Cancels a buffer previously dequeued with \ref nwindowDequeueBuffer.
* @param[in] nw Pointer to \ref NWindow structure.
* @param[in] slot ID of the slot to cancel. This must match the output of the previous \ref nwindowDequeueBuffer call.
* @param[in] fence Pointer to the \ref NvMultiFence that will be waited on by the compositor before cancelling the buffer.
* Pass NULL if there is no such fence.
*/
Result nwindowCancelBuffer(NWindow* nw, s32 slot, const NvMultiFence* fence);
/**
* @brief Queues a buffer previously dequeued with \ref nwindowDequeueBuffer, making it ready for presentation.
* @param[in] nw Pointer to \ref NWindow structure.
* @param[in] slot ID of the slot to queue. This must match the output of the previous \ref nwindowDequeueBuffer call.
* @param[in] fence Pointer to the \ref NvMultiFence that will be waited on by the compositor before queuing/presenting the buffer.
* Pass NULL if there is no such fence.
*/
Result nwindowQueueBuffer(NWindow* nw, s32 slot, const NvMultiFence* fence);
/// Releases all buffers registered with a \ref NWindow.
Result nwindowReleaseBuffers(NWindow* nw);
///@}

View file

@ -0,0 +1,194 @@
## *
## @file native_window.h
## @brief Native window (NWindow) wrapper object, used for presenting images to the display (or other sinks).
## @author fincs
## @copyright libnx Authors
##
import
../kernel/mutex, ../kernel/event, ../services/vi, ../nvidia/graphic_buffer, ../types,
binder, buffer_producer, ../sf/service, ../nvidia/fence
## / Native window structure.
type
NWindow* {.bycopy.} = object
magic*: U32
bq*: Binder
event*: Event
mutex*: Mutex
slotsConfigured*: U64
slotsRequested*: U64
curSlot*: S32
width*: U32
height*: U32
format*: U32
usage*: U32
crop*: BqRect
scalingMode*: U32
transform*: U32
stickyTransform*: U32
defaultWidth*: U32
defaultHeight*: U32
swapInterval*: U32
isConnected*: bool
producerControlledByApp*: bool
consumerRunningBehind*: bool
proc nwindowIsValid*(nw: ptr NWindow): bool {.cdecl, importc: "nwindowIsValid".}
## /@name Basic functions
## /@{
## / Checks whether a pointer refers to a valid \ref NWindow object.
proc nwindowGetDefault*(): ptr NWindow {.cdecl, importc: "nwindowGetDefault".}
## *
## @brief Retrieves the default \ref NWindow object.
## @return Pointer to the default \ref NWindow object.
## @note When this function is used/referenced, libnx will initialize VI services
## and create a \ref NWindow object from a \ref ViLayer created on the default \ref ViDisplay;
## all of this happening automatically during application startup (i.e. before main is called).
## If creating the default \ref NWindow fails, libnx will throw a LibnxError_BadGfxInit fatal error.
## Likewise, after main returns (or exit is called) libnx will clean up all resources used by it.
##
proc nwindowCreate*(nw: ptr NWindow; binderSession: ptr Service; binderId: S32;
producerControlledByApp: bool): Result {.cdecl,
importc: "nwindowCreate".}
## *
## @brief Creates a \ref NWindow.
## @param[out] nw Output \ref NWindow structure.
## @param[in] binder_session Service object for the Android IGraphicBufferProducer binder session.
## @param[in] binder_id Android IGraphicBufferProducer binder session ID.
## @param[in] producer_controlled_by_app Specifies whether the producer is controlled by the application.
##
proc nwindowCreateFromLayer*(nw: ptr NWindow; layer: ptr ViLayer): Result {.cdecl,
importc: "nwindowCreateFromLayer".}
## *
## @brief Creates a \ref NWindow operating on a \ref ViLayer.
## @param[out] nw Output \ref NWindow structure.
## @param[in] layer Pointer to \ref ViLayer structure (such as the one returned by \ref viCreateLayer).
##
proc nwindowClose*(nw: ptr NWindow) {.cdecl, importc: "nwindowClose".}
## / Closes a \ref NWindow, freeing all resources associated with it.
proc nwindowGetDimensions*(nw: ptr NWindow; outWidth: ptr U32; outHeight: ptr U32): Result {.
cdecl, importc: "nwindowGetDimensions".}
## /@}
## /@name Window configuration
## /@{
## *
## @brief Retrieves the dimensions of a \ref NWindow.
## @param[in] nw Pointer to \ref NWindow structure.
## @param[out] out_width Output variable containing the width of the \ref NWindow.
## @param[out] out_height Output variable containing the height of the \ref NWindow.
## @note After creation, a \ref NWindow reports a default size (usually 1280x720).
## This size can be overriden by calling \ref nwindowSetDimensions.
##
proc nwindowSetDimensions*(nw: ptr NWindow; width: U32; height: U32): Result {.cdecl,
importc: "nwindowSetDimensions".}
## *
## @brief Sets the dimensions of a \ref NWindow.
## @param[in] nw Pointer to \ref NWindow structure.
## @param[in] width Desired width of the \ref NWindow.
## @param[in] height Desired width of the \ref NWindow.
## @note This function cannot be called when there are buffers registered with the \ref NWindow.
##
proc nwindowSetCrop*(nw: ptr NWindow; left: S32; top: S32; right: S32; bottom: S32): Result {.
cdecl, importc: "nwindowSetCrop".}
## *
## @brief Configures the crop applied to images presented through a \ref NWindow.
## @param[in] nw Pointer to \ref NWindow structure.
## @param[in] left X coordinate of the left margin of the crop bounding box.
## @param[in] top Y coordinate of the top margin of the crop bounding box.
## @param[in] right X coordinate of the right margin of the crop bounding box.
## @param[in] bottom Y coordinate of the bottom margin of the crop bounding box.
## @note Passing zero to all parameters disables the crop functionality. This is also the default.
## @note The bounding box defined by the parameters will be adjusted to fit within the dimensions of the \ref NWindow.
## @note \p left must be less or equal than \p right.
## @note \p top must be less or equal than \p bottom.
##
proc nwindowSetTransform*(nw: ptr NWindow; transform: U32): Result {.cdecl,
importc: "nwindowSetTransform".}
## *
## @brief Configures the transformation applied to images presented through a \ref NWindow.
## @param[in] nw Pointer to \ref NWindow structure.
## @param[in] transform Android transformation mode (see NATIVE_WINDOW_TRANSFORM_* enum)
## @note The default transformation is 0 (i.e. no transformation applied)
##
proc nwindowSetSwapInterval*(nw: ptr NWindow; swapInterval: U32): Result {.cdecl,
importc: "nwindowSetSwapInterval".}
## *
## @brief Configures the swap interval of a \ref NWindow.
## @param[in] nw Pointer to \ref NWindow structure.
## @param[in] swap_interval Value specifying the number of display refreshes (VBlanks) that must occur between presenting images.
## @note The default swap interval is 1.
## @note If the \ref NWindow has three or more buffers configured (with \ref nwindowConfigureBuffer), it is possible to pass 0
## to disable the swap interval feature and present images as fast as allowed by the compositor. Otherwise, the system
## enforces a minimum of 1 as the swap interval.
##
proc nwindowIsConsumerRunningBehind*(nw: ptr NWindow): bool {.inline, cdecl.} =
## / Checks whether the consumer of a \ref NWindow is running behind.
return nw.consumerRunningBehind
proc nwindowConfigureBuffer*(nw: ptr NWindow; slot: S32; buf: ptr NvGraphicBuffer): Result {.
cdecl, importc: "nwindowConfigureBuffer".}
## /@}
## /@name Buffer configuration and presentation
## /@{
## *
## @brief Registers a \ref NvGraphicBuffer with a \ref NWindow.
## @param[in] nw Pointer to \ref NWindow structure.
## @param[in] slot ID of the slot to configure (starting from 0).
## @param[in] buf Pointer to \ref NvGraphicBuffer structure.
## @note When a buffer is registered, it is added to the internal queue of buffers used for presenting.
## @note All buffers registered with a \ref NWindow must have the same dimensions, format and usage.
## If \ref nwindowSetDimensions has not been previously called, the \ref NWindow will automatically
## adopt the dimensions of the first buffer registered with it. Otherwise, said buffer will need
## to match the dimensions that were previously configured.
##
proc nwindowDequeueBuffer*(nw: ptr NWindow; outSlot: ptr S32;
outFence: ptr NvMultiFence): Result {.cdecl,
importc: "nwindowDequeueBuffer".}
## *
## @brief Dequeues a buffer from a \ref NWindow.
## @param[in] nw Pointer to \ref NWindow structure.
## @param[out] out_slot Output variable containing the ID of the slot that has been dequeued.
## @param[out] out_fence Output variable containing a \ref NvMultiFence that will be signalled by
## the compositor when the buffer is ready to be written to. Pass NULL to wait instead
## on this fence before this function returns.
## @note For \p out_fence=NULL to work, \ref nvFenceInit must have been previously called.
##
proc nwindowCancelBuffer*(nw: ptr NWindow; slot: S32; fence: ptr NvMultiFence): Result {.
cdecl, importc: "nwindowCancelBuffer".}
## *
## @brief Cancels a buffer previously dequeued with \ref nwindowDequeueBuffer.
## @param[in] nw Pointer to \ref NWindow structure.
## @param[in] slot ID of the slot to cancel. This must match the output of the previous \ref nwindowDequeueBuffer call.
## @param[in] fence Pointer to the \ref NvMultiFence that will be waited on by the compositor before cancelling the buffer.
## Pass NULL if there is no such fence.
##
proc nwindowQueueBuffer*(nw: ptr NWindow; slot: S32; fence: ptr NvMultiFence): Result {.
cdecl, importc: "nwindowQueueBuffer".}
## *
## @brief Queues a buffer previously dequeued with \ref nwindowDequeueBuffer, making it ready for presentation.
## @param[in] nw Pointer to \ref NWindow structure.
## @param[in] slot ID of the slot to queue. This must match the output of the previous \ref nwindowDequeueBuffer call.
## @param[in] fence Pointer to the \ref NvMultiFence that will be waited on by the compositor before queuing/presenting the buffer.
## Pass NULL if there is no such fence.
##
proc nwindowReleaseBuffers*(nw: ptr NWindow): Result {.cdecl,
importc: "nwindowReleaseBuffers".}
## / Releases all buffers registered with a \ref NWindow.
## /@}

View file

@ -0,0 +1,40 @@
#pragma once
#include "../result.h"
#include "../display/binder.h"
typedef struct {
u32 payload_size;
u32 payload_off;
u32 objects_size;
u32 objects_off;
} ParcelHeader;
#define PARCEL_MAX_PAYLOAD 0x400
typedef struct {
u8 payload[PARCEL_MAX_PAYLOAD];
u32 payload_size;
u8* objects;
u32 objects_size;
u32 capacity;
u32 pos;
} Parcel;
void parcelCreate(Parcel *ctx);
Result parcelTransact(Binder *session, u32 code, Parcel *in_parcel, Parcel *reply_parcel);
void* parcelWriteData(Parcel *ctx, const void* data, size_t data_size);
void* parcelReadData(Parcel *ctx, void* data, size_t data_size);
void parcelWriteInt32(Parcel *ctx, s32 val);
void parcelWriteUInt32(Parcel *ctx, u32 val);
void parcelWriteString16(Parcel *ctx, const char *str);
s32 parcelReadInt32(Parcel *ctx);
u32 parcelReadUInt32(Parcel *ctx);
void parcelWriteInterfaceToken(Parcel *ctx, const char *str);
void* parcelReadFlattenedObject(Parcel *ctx, size_t *size);
void* parcelWriteFlattenedObject(Parcel *ctx, const void* data, size_t size);

View file

@ -0,0 +1,45 @@
import
../result, ../display/binder
type
ParcelHeader* {.bycopy.} = object
payloadSize*: U32
payloadOff*: U32
objectsSize*: U32
objectsOff*: U32
const
PARCEL_MAX_PAYLOAD* = 0x400
type
Parcel* {.bycopy.} = object
payload*: array[Parcel_Max_Payload, U8]
payloadSize*: U32
objects*: ptr U8
objectsSize*: U32
capacity*: U32
pos*: U32
proc parcelCreate*(ctx: ptr Parcel) {.cdecl, importc: "parcelCreate".}
proc parcelTransact*(session: ptr Binder; code: U32; inParcel: ptr Parcel;
replyParcel: ptr Parcel): Result {.cdecl,
importc: "parcelTransact".}
proc parcelWriteData*(ctx: ptr Parcel; data: pointer; dataSize: csize_t): pointer {.
cdecl, importc: "parcelWriteData".}
proc parcelReadData*(ctx: ptr Parcel; data: pointer; dataSize: csize_t): pointer {.cdecl,
importc: "parcelReadData".}
proc parcelWriteInt32*(ctx: ptr Parcel; val: S32) {.cdecl, importc: "parcelWriteInt32".}
proc parcelWriteUInt32*(ctx: ptr Parcel; val: U32) {.cdecl,
importc: "parcelWriteUInt32".}
proc parcelWriteString16*(ctx: ptr Parcel; str: cstring) {.cdecl,
importc: "parcelWriteString16".}
proc parcelReadInt32*(ctx: ptr Parcel): S32 {.cdecl, importc: "parcelReadInt32".}
proc parcelReadUInt32*(ctx: ptr Parcel): U32 {.cdecl, importc: "parcelReadUInt32".}
proc parcelWriteInterfaceToken*(ctx: ptr Parcel; str: cstring) {.cdecl,
importc: "parcelWriteInterfaceToken".}
proc parcelReadFlattenedObject*(ctx: ptr Parcel; size: ptr csize_t): pointer {.cdecl,
importc: "parcelReadFlattenedObject".}
proc parcelWriteFlattenedObject*(ctx: ptr Parcel; data: pointer; size: csize_t): pointer {.
cdecl, importc: "parcelWriteFlattenedObject".}

View file

@ -0,0 +1,147 @@
/**
* @file display/types.h
* @brief Definitions for Android-related types and enumerations.
* @copyright libnx Authors
*/
#pragma once
#include "../types.h"
// From Android PixelFormat.h & graphics-base-v1.0.h.
enum {
PIXEL_FORMAT_RGBA_8888 = 1U,
PIXEL_FORMAT_RGBX_8888 = 2U,
PIXEL_FORMAT_RGB_888 = 3U,
PIXEL_FORMAT_RGB_565 = 4U,
PIXEL_FORMAT_BGRA_8888 = 5U,
PIXEL_FORMAT_RGBA_5551 = 6U,
PIXEL_FORMAT_RGBA_4444 = 7U,
PIXEL_FORMAT_YCRCB_420_SP = 17U,
PIXEL_FORMAT_RAW16 = 32U,
PIXEL_FORMAT_BLOB = 33U,
PIXEL_FORMAT_IMPLEMENTATION_DEFINED = 34U,
PIXEL_FORMAT_YCBCR_420_888 = 35U,
PIXEL_FORMAT_Y8 = 0x20203859U,
PIXEL_FORMAT_Y16 = 0x20363159U,
PIXEL_FORMAT_YV12 = 0x32315659U,
};
// From Android gralloc.h.
enum {
/* buffer is never read in software */
GRALLOC_USAGE_SW_READ_NEVER = 0x00000000U,
/* buffer is rarely read in software */
GRALLOC_USAGE_SW_READ_RARELY = 0x00000002U,
/* buffer is often read in software */
GRALLOC_USAGE_SW_READ_OFTEN = 0x00000003U,
/* mask for the software read values */
GRALLOC_USAGE_SW_READ_MASK = 0x0000000FU,
/* buffer is never written in software */
GRALLOC_USAGE_SW_WRITE_NEVER = 0x00000000U,
/* buffer is rarely written in software */
GRALLOC_USAGE_SW_WRITE_RARELY = 0x00000020U,
/* buffer is often written in software */
GRALLOC_USAGE_SW_WRITE_OFTEN = 0x00000030U,
/* mask for the software write values */
GRALLOC_USAGE_SW_WRITE_MASK = 0x000000F0U,
/* buffer will be used as an OpenGL ES texture */
GRALLOC_USAGE_HW_TEXTURE = 0x00000100U,
/* buffer will be used as an OpenGL ES render target */
GRALLOC_USAGE_HW_RENDER = 0x00000200U,
/* buffer will be used by the 2D hardware blitter */
GRALLOC_USAGE_HW_2D = 0x00000400U,
/* buffer will be used by the HWComposer HAL module */
GRALLOC_USAGE_HW_COMPOSER = 0x00000800U,
/* buffer will be used with the framebuffer device */
GRALLOC_USAGE_HW_FB = 0x00001000U,
/* buffer should be displayed full-screen on an external display when
* possible */
GRALLOC_USAGE_EXTERNAL_DISP = 0x00002000U,
/* Must have a hardware-protected path to external display sink for
* this buffer. If a hardware-protected path is not available, then
* either don't composite only this buffer (preferred) to the
* external sink, or (less desirable) do not route the entire
* composition to the external sink. */
GRALLOC_USAGE_PROTECTED = 0x00004000U,
/* buffer may be used as a cursor */
GRALLOC_USAGE_CURSOR = 0x00008000U,
/* buffer will be used with the HW video encoder */
GRALLOC_USAGE_HW_VIDEO_ENCODER = 0x00010000U,
/* buffer will be written by the HW camera pipeline */
GRALLOC_USAGE_HW_CAMERA_WRITE = 0x00020000U,
/* buffer will be read by the HW camera pipeline */
GRALLOC_USAGE_HW_CAMERA_READ = 0x00040000U,
/* buffer will be used as part of zero-shutter-lag queue */
GRALLOC_USAGE_HW_CAMERA_ZSL = 0x00060000U,
/* mask for the camera access values */
GRALLOC_USAGE_HW_CAMERA_MASK = 0x00060000U,
/* mask for the software usage bit-mask */
GRALLOC_USAGE_HW_MASK = 0x00071F00U,
/* buffer will be used as a RenderScript Allocation */
GRALLOC_USAGE_RENDERSCRIPT = 0x00100000U,
};
// From Android window.h.
/* attributes queriable with query() */
enum {
NATIVE_WINDOW_WIDTH = 0,
NATIVE_WINDOW_HEIGHT = 1,
NATIVE_WINDOW_FORMAT = 2,
//...
// NATIVE_WINDOW_DEFAULT_WIDTH = 6, //These two return invalid data.
// NATIVE_WINDOW_DEFAULT_HEIGHT = 7,
};
// From Android window.h.
/* parameter for NATIVE_WINDOW_[API_][DIS]CONNECT */
enum {
//...
/* Buffers will be queued after being filled using the CPU
*/
NATIVE_WINDOW_API_CPU = 2,
//...
};
// From Android hardware.h.
/**
* Transformation definitions
*
* IMPORTANT NOTE:
* HAL_TRANSFORM_ROT_90 is applied CLOCKWISE and AFTER HAL_TRANSFORM_FLIP_{H|V}.
*
*/
enum {
/* flip source image horizontally (around the vertical axis) */
HAL_TRANSFORM_FLIP_H = 0x01,
/* flip source image vertically (around the horizontal axis)*/
HAL_TRANSFORM_FLIP_V = 0x02,
/* rotate source image 90 degrees clockwise */
HAL_TRANSFORM_ROT_90 = 0x04,
/* rotate source image 180 degrees */
HAL_TRANSFORM_ROT_180 = 0x03,
/* rotate source image 270 degrees clockwise */
HAL_TRANSFORM_ROT_270 = 0x07,
};
// From Android window.h.
/* parameter for NATIVE_WINDOW_SET_BUFFERS_TRANSFORM */
enum {
/* flip source image horizontally */
NATIVE_WINDOW_TRANSFORM_FLIP_H = HAL_TRANSFORM_FLIP_H,
/* flip source image vertically */
NATIVE_WINDOW_TRANSFORM_FLIP_V = HAL_TRANSFORM_FLIP_V,
/* rotate source image 90 degrees clock-wise */
NATIVE_WINDOW_TRANSFORM_ROT_90 = HAL_TRANSFORM_ROT_90,
/* rotate source image 180 degrees */
NATIVE_WINDOW_TRANSFORM_ROT_180 = HAL_TRANSFORM_ROT_180,
/* rotate source image 270 degrees clock-wise */
NATIVE_WINDOW_TRANSFORM_ROT_270 = HAL_TRANSFORM_ROT_270,
};
// From Android native_handle.h.
typedef struct {
int version;
int num_fds;
int num_ints;
} NativeHandle;

View file

@ -0,0 +1,109 @@
## *
## @file display/types.h
## @brief Definitions for Android-related types and enumerations.
## @copyright libnx Authors
##
## From Android PixelFormat.h & graphics-base-v1.0.h.
const
PIXEL_FORMAT_RGBA_8888* = 1'u
PIXEL_FORMAT_RGBX_8888* = 2'u
PIXEL_FORMAT_RGB_888* = 3'u
PIXEL_FORMAT_RGB_565* = 4'u
PIXEL_FORMAT_BGRA_8888* = 5'u
PIXEL_FORMAT_RGBA_5551* = 6'u
PIXEL_FORMAT_RGBA_4444* = 7'u
PIXEL_FORMAT_YCRCB_420_SP* = 17'u
PIXEL_FORMAT_RAW16* = 32'u
PIXEL_FORMAT_BLOB* = 33'u
PIXEL_FORMAT_IMPLEMENTATION_DEFINED* = 34'u
PIXEL_FORMAT_YCBCR_420_888* = 35'u
PIXEL_FORMAT_Y8* = 0x20203859
PIXEL_FORMAT_Y16* = 0x20363159
PIXEL_FORMAT_YV12* = 0x32315659
## From Android gralloc.h.
const ## buffer is never read in software
GRALLOC_USAGE_SW_READ_NEVER* = 0x00000000 ## buffer is rarely read in software
GRALLOC_USAGE_SW_READ_RARELY* = 0x00000002 ## buffer is often read in software
GRALLOC_USAGE_SW_READ_OFTEN* = 0x00000003 ## mask for the software read values
GRALLOC_USAGE_SW_READ_MASK* = 0x0000000F ## buffer is never written in software
GRALLOC_USAGE_SW_WRITE_NEVER* = 0x00000000 ## buffer is rarely written in software
GRALLOC_USAGE_SW_WRITE_RARELY* = 0x00000020 ## buffer is often written in software
GRALLOC_USAGE_SW_WRITE_OFTEN* = 0x00000030 ## mask for the software write values
GRALLOC_USAGE_SW_WRITE_MASK* = 0x000000F0 ## buffer will be used as an OpenGL ES texture
GRALLOC_USAGE_HW_TEXTURE* = 0x00000100 ## buffer will be used as an OpenGL ES render target
GRALLOC_USAGE_HW_RENDER* = 0x00000200 ## buffer will be used by the 2D hardware blitter
GRALLOC_USAGE_HW_2D* = 0x00000400 ## buffer will be used by the HWComposer HAL module
GRALLOC_USAGE_HW_COMPOSER* = 0x00000800 ## buffer will be used with the framebuffer device
GRALLOC_USAGE_HW_FB* = 0x00001000 ## buffer should be displayed full-screen on an external display when
## possible
GRALLOC_USAGE_EXTERNAL_DISP* = 0x00002000 ## Must have a hardware-protected path to external display sink for
## this buffer. If a hardware-protected path is not available, then
## either don't composite only this buffer (preferred) to the
## external sink, or (less desirable) do not route the entire
## composition to the external sink.
GRALLOC_USAGE_PROTECTED* = 0x00004000 ## buffer may be used as a cursor
GRALLOC_USAGE_CURSOR* = 0x00008000 ## buffer will be used with the HW video encoder
GRALLOC_USAGE_HW_VIDEO_ENCODER* = 0x00010000 ## buffer will be written by the HW camera pipeline
GRALLOC_USAGE_HW_CAMERA_WRITE* = 0x00020000 ## buffer will be read by the HW camera pipeline
GRALLOC_USAGE_HW_CAMERA_READ* = 0x00040000 ## buffer will be used as part of zero-shutter-lag queue
GRALLOC_USAGE_HW_CAMERA_ZSL* = 0x00060000 ## mask for the camera access values
GRALLOC_USAGE_HW_CAMERA_MASK* = 0x00060000 ## mask for the software usage bit-mask
GRALLOC_USAGE_HW_MASK* = 0x00071F00 ## buffer will be used as a RenderScript Allocation
GRALLOC_USAGE_RENDERSCRIPT* = 0x00100000
## From Android window.h.
## attributes queriable with query()
const
NATIVE_WINDOW_WIDTH* = 0
NATIVE_WINDOW_HEIGHT* = 1
NATIVE_WINDOW_FORMAT* = 2 ## ...
## NATIVE_WINDOW_DEFAULT_WIDTH = 6, //These two return invalid data.
## NATIVE_WINDOW_DEFAULT_HEIGHT = 7,
## From Android window.h.
## parameter for NATIVE_WINDOW_[API_][DIS]CONNECT
const ## ...
## Buffers will be queued after being filled using the CPU
##
NATIVE_WINDOW_API_CPU* = 2 ## ...
## From Android hardware.h.
## *
## Transformation definitions
##
## IMPORTANT NOTE:
## HAL_TRANSFORM_ROT_90 is applied CLOCKWISE and AFTER HAL_TRANSFORM_FLIP_{H|V}.
##
##
const ## flip source image horizontally (around the vertical axis)
HAL_TRANSFORM_FLIP_H* = 0x01 ## flip source image vertically (around the horizontal axis)
HAL_TRANSFORM_FLIP_V* = 0x02 ## rotate source image 90 degrees clockwise
HAL_TRANSFORM_ROT_90* = 0x04 ## rotate source image 180 degrees
HAL_TRANSFORM_ROT_180* = 0x03 ## rotate source image 270 degrees clockwise
HAL_TRANSFORM_ROT_270* = 0x07
## From Android window.h.
## parameter for NATIVE_WINDOW_SET_BUFFERS_TRANSFORM
const ## flip source image horizontally
NATIVE_WINDOW_TRANSFORM_FLIP_H* = HAL_TRANSFORM_FLIP_H ## flip source image vertically
NATIVE_WINDOW_TRANSFORM_FLIP_V* = HAL_TRANSFORM_FLIP_V ## rotate source image 90 degrees clock-wise
NATIVE_WINDOW_TRANSFORM_ROT_90* = HAL_TRANSFORM_ROT_90 ## rotate source image 180 degrees
NATIVE_WINDOW_TRANSFORM_ROT_180* = HAL_TRANSFORM_ROT_180 ## rotate source image 270 degrees clock-wise
NATIVE_WINDOW_TRANSFORM_ROT_270* = HAL_TRANSFORM_ROT_270
## From Android native_handle.h.
type
NativeHandle* {.bycopy.} = object
version*: cint
numFds*: cint
numInts*: cint

View file

@ -0,0 +1,379 @@
import strutils
# Capacity of 42 because it seems
# reasonable that the number will fit.
# If it doesn't, nim will just allocate
# more memory for us anyway
const STRING_CAPACITY = 42
type
s128* {.importc: "__int128_t".} = object
high: int64
low: uint64
u128* {.importc: "__uint128_t".} = object
high, low: uint64
helperInt128 = object
hi: int64
lo: uint64
helperUInt128 = object
hi: uint64
lo: uint64
proc toHelper(val: s128): helperInt128 =
(cast[ptr helperInt128](unsafeAddr val))[]
proc lo*(val: s128): uint64 =
val.toHelper().lo
proc hi*(val: s128): int64 =
val.toHelper().hi
proc toInt128(val: helperInt128): s128 =
(cast[ptr s128](unsafeAddr val))[]
proc toHelper(val: u128): helperUInt128 =
(cast[ptr helperUInt128](unsafeAddr val))[]
proc lo*(val: u128): uint64 =
val.toHelper().lo
proc hi*(val: u128): uint64 =
val.toHelper().hi
proc toUInt128(val: helperUInt128): u128 =
(cast[ptr u128](unsafeAddr val))[]
proc newInt128*(hi: int64, lo: uint64): s128 =
let r = helperInt128(hi: hi, lo: lo)
return r.toInt128()
proc newUInt128*(hi: uint64, lo: uint64): u128 =
let r = helperUInt128(hi: hi, lo: lo)
return r.toUInt128()
proc toUInt128(val: s128): u128 =
newUInt128(val.hi.uint64, val.lo)
converter intToInt128*(val: int): s128 =
newInt128(0, val.uint64)
converter intToUInt128*(val: int): u128 =
newUInt128(0, val.uint64)
proc `<`*(val1: u128, val2: u128): bool =
let lhs = val1.toHelper()
let rhs = val2.toHelper()
if (lhs.hi < rhs.hi):
return true
if (rhs.hi < lhs.hi):
return false
if (lhs.lo < rhs.lo):
return true
return false
proc `<`*(val1: s128, val2: s128): bool =
let lhs = val1.toHelper()
let rhs = val2.toHelper()
if (lhs.hi < rhs.hi):
return true
if (rhs.hi < lhs.hi):
return false
if (lhs.lo < rhs.lo):
return true
return false
proc `>=`*(val1: s128, val2: s128): bool =
let lhs = val1.toHelper()
let rhs = val2.toHelper()
if lhs.hi == rhs.hi and lhs.lo == rhs.lo:
return true
if lhs.hi > rhs.hi:
return true
if rhs.hi > lhs.hi:
return false
if lhs.lo > rhs.lo:
return true
return false
proc `>=`*(val1: u128, val2: u128): bool =
let lhs = val1.toHelper()
let rhs = val2.toHelper()
if lhs.hi == rhs.hi and lhs.lo == rhs.lo:
return true
if lhs.hi > rhs.hi:
return true
if rhs.hi > lhs.hi:
return false
if lhs.lo > rhs.lo:
return true
return false
proc `>`*(val1: s128, val2: s128): bool =
let lhs = val1.toHelper()
let rhs = val2.toHelper()
if (lhs.hi < rhs.hi):
return true
if (rhs.hi < lhs.hi):
return false
if (lhs.lo < rhs.lo):
return true
return false
proc `>`*(val1: u128, val2: u128): bool =
let lhs = val1.toHelper()
let rhs = val2.toHelper()
if (lhs.hi < rhs.hi):
return true
if (rhs.hi < lhs.hi):
return false
if (lhs.lo < rhs.lo):
return true
return false
proc `<=`*(val1: s128, val2: s128): bool =
let lhs = val1.toHelper()
let rhs = val2.toHelper()
if lhs.hi == rhs.hi and lhs.lo == rhs.lo:
return true
if lhs.hi < rhs.hi:
return true
if rhs.hi < lhs.hi:
return false
if lhs.lo < rhs.lo:
return true
return false
proc `<=`*(val1: u128, val2: u128): bool =
let lhs = val1.toHelper()
let rhs = val2.toHelper()
if lhs.hi == rhs.hi and lhs.lo == rhs.lo:
return true
if lhs.hi < rhs.hi:
return true
if rhs.hi < lhs.hi:
return false
if lhs.lo < rhs.lo:
return true
return false
proc `!=`*(val1: s128, val2: s128): bool =
let lhs = val1.toHelper()
let rhs = val2.toHelper()
return (lhs.hi != rhs.hi) or (lhs.lo != rhs.lo)
proc `!=`*(val1: u128, val2: u128): bool =
let lhs = val1.toHelper()
let rhs = val2.toHelper()
return (lhs.hi != rhs.hi) or (lhs.lo != rhs.lo)
proc `==`*(val1: s128, val2: s128): bool =
let lhs = val1.tohelper()
let rhs = val2.tohelper()
if lhs.hi != rhs.hi:
return false
if lhs.lo != rhs.lo:
return false
return true
proc `==`*(val1: u128, val2: u128): bool =
let lhs = val1.tohelper()
let rhs = val2.tohelper()
if lhs.hi != rhs.hi:
return false
if lhs.lo != rhs.lo:
return false
return true
proc `+`*(val1, val2: s128): s128 =
let lhs = val1.toHelper()
let rhs = val2.toHelper()
var res = result.toHelper()
res.hi = lhs.hi + rhs.hi
res.lo = lhs.lo + rhs.lo
if res.lo < rhs.lo:
res.hi.inc()
result = res.toInt128()
proc `+`*(val1, val2: u128): u128 =
let lhs = val1.toHelper()
let rhs = val2.toHelper()
var res = result.toHelper()
res.hi = lhs.hi + rhs.hi
res.lo = lhs.lo + rhs.lo
if res.lo < rhs.lo:
res.hi.inc()
result = res.toUInt128()
proc `-`*(val: s128): s128 =
var res = val.toHelper()
res.hi = not res.hi
res.lo = not res.lo
res.lo += 1
if res.lo == 0:
res.hi += 1
result = res.toInt128()
proc `-`*(val: u128): s128 =
var res = newInt128(val.hi.int64, val.lo).toHelper()
res.hi = not res.hi
res.lo = not res.lo
res.lo += 1
if res.lo == 0:
res.hi += 1
result = res.toInt128()
proc `-`*(val1, val2: s128): s128 =
let lhs = val1.toHelper()
let rhs = val2.toHelper()
var res = result.toHelper()
res.hi = lhs.hi - rhs.hi
res.lo = lhs.lo - rhs.lo
if res.lo > lhs.lo:
res.hi.dec()
result = res.toInt128()
proc `-`*(val1, val2: u128): s128 =
let lhs = val1.toHelper()
let rhs = val2.toHelper()
var res = result.toHelper()
res.hi = (lhs.hi - rhs.hi).int64
res.lo = lhs.lo - rhs.lo
if res.lo > lhs.lo:
res.hi.dec()
result = res.toInt128()
proc `$`*(val: s128): string =
var v = val
if v == 0:
return "0"
var str = newStringOfCap(STRING_CAPACITY)
var
p10 = 1.s128
temp: s128
num_digits = 0
going = 1
digit = 0
if v < 0:
str.add('-')
v = -v
while (p10 <= v and going > 0):
p10 = p10 + p10
if p10 < 0:
going = 0
temp = p10
p10 = p10 + p10
if p10 < 0:
going = 0
p10 = p10 + p10
if p10 < 0:
going = 0
p10 = p10 + temp
if p10 < 0:
going = 0
num_digits.inc
while num_digits > 0:
num_digits -= 1
p10 = 1
for i in 0..<num_digits:
p10 = p10 + p10
temp = p10
p10 = p10 + p10
p10 = p10 + p10
p10 = p10 + temp
digit = 0
while(v >= p10):
v = v - p10
digit.inc
str.add(char(48 + digit))
result = str
proc toHex*(val: u128): string =
result = val.hi.toHex & val.lo.toHex
proc `$`*(val: u128): string =
var v = val
if v == 0:
return "0"
var str = newStringOfCap(STRING_CAPACITY)
var
p10 = 1.u128
temp: u128
num_digits = 0
going = 1
digit = 0
while (p10 <= v and going > 0):
p10 = p10 + p10
if p10 < 0:
going = 0
temp = p10
p10 = p10 + p10
if p10 < 0:
going = 0
p10 = p10 + p10
if p10 < 0:
going = 0
p10 = p10 + temp
if p10 < 0:
going = 0
num_digits.inc
while num_digits > 0:
num_digits -= 1
p10 = 1
for i in 0..<num_digits:
p10 = p10 + p10
temp = p10
p10 = p10 + p10
p10 = p10 + p10
p10 = p10 + temp
digit = 0
while(v >= p10):
v = (v - p10).toUInt128()
digit.inc
str.add(char(48 + digit))
result = str

View file

@ -0,0 +1,30 @@
/**
* @file barrier.h
* @brief Multi-threading Barrier
* @author tatehaga
* @copyright libnx Authors
*/
#pragma once
#include "mutex.h"
#include "condvar.h"
/// Barrier structure.
typedef struct Barrier {
u64 count; ///< Number of threads to reach the barrier.
u64 total; ///< Number of threads to wait on.
Mutex mutex;
CondVar condvar;
} Barrier;
/**
* @brief Initializes a barrier and the number of threads to wait on.
* @param b Barrier object.
* @param thread_count Initial value for the number of threads the barrier must wait for.
*/
void barrierInit(Barrier *b, u64 thread_count);
/**
* @brief Forces threads to wait until all threads have called barrierWait.
* @param b Barrier object.
*/
void barrierWait(Barrier *b);

View file

@ -0,0 +1,34 @@
## *
## @file barrier.h
## @brief Multi-threading Barrier
## @author tatehaga
## @copyright libnx Authors
##
import
mutex, condvar
import ../types
## / Barrier structure.
type
Barrier* {.bycopy.} = object
count*: U64 ## /< Number of threads to reach the barrier.
total*: U64 ## /< Number of threads to wait on.
mutex*: Mutex
condvar*: CondVar
## *
## @brief Initializes a barrier and the number of threads to wait on.
## @param b Barrier object.
## @param thread_count Initial value for the number of threads the barrier must wait for.
##
proc barrierInit*(b: ptr Barrier; threadCount: U64) {.cdecl, importc: "barrierInit".}
## *
## @brief Forces threads to wait until all threads have called barrierWait.
## @param b Barrier object.
##
proc barrierWait*(b: ptr Barrier) {.cdecl, importc: "barrierWait".}

View file

@ -0,0 +1,76 @@
/**
* @file condvar.h
* @brief Condition variable synchronization primitive.
* @author plutoo
* @copyright libnx Authors
*/
#pragma once
#include "../types.h"
#include "../kernel/svc.h"
#include "../kernel/mutex.h"
/// Condition variable.
typedef u32 CondVar;
/**
* @brief Initializes a condition variable.
* @param[in] c Condition variable object.
*/
static inline void condvarInit(CondVar* c)
{
*c = 0;
}
/**
* @brief Waits on a condition variable with a timeout.
* @param[in] c Condition variable object.
* @param[in] m Mutex object to use inside the condition variable.
* @param[in] timeout Timeout in nanoseconds.
* @return Result code (0xEA01 on timeout).
* @remark On function return, the underlying mutex is acquired.
*/
Result condvarWaitTimeout(CondVar* c, Mutex* m, u64 timeout);
/**
* @brief Waits on a condition variable.
* @param[in] c Condition variable object.
* @param[in] m Mutex object to use inside the condition variable.
* @return Result code.
* @remark On function return, the underlying mutex is acquired.
*/
static inline Result condvarWait(CondVar* c, Mutex* m)
{
return condvarWaitTimeout(c, m, UINT64_MAX);
}
/**
* @brief Wakes up up to the specified number of threads waiting on a condition variable.
* @param[in] c Condition variable object.
* @param[in] num Maximum number of threads to wake up (or -1 to wake them all up).
* @return Result code.
*/
static inline Result condvarWake(CondVar* c, int num)
{
svcSignalProcessWideKey(c, num);
return 0;
}
/**
* @brief Wakes up a single thread waiting on a condition variable.
* @param[in] c Condition variable object.
* @return Result code.
*/
static inline Result condvarWakeOne(CondVar* c)
{
return condvarWake(c, 1);
}
/**
* @brief Wakes up all thread waiting on a condition variable.
* @param[in] c Condition variable object.
* @return Result code.
*/
static inline Result condvarWakeAll(CondVar* c)
{
return condvarWake(c, -1);
}

View file

@ -0,0 +1,75 @@
## *
## @file condvar.h
## @brief Condition variable synchronization primitive.
## @author plutoo
## @copyright libnx Authors
##
import
../types, ../kernel/svc, ../kernel/mutex
## / Condition variable.
type
CondVar* = U32
## *
## @brief Initializes a condition variable.
## @param[in] c Condition variable object.
##
proc condvarInit*(c: ptr CondVar) {.inline, cdecl, importc: "condvarInit".} =
c[] = 0
## *
## @brief Waits on a condition variable with a timeout.
## @param[in] c Condition variable object.
## @param[in] m Mutex object to use inside the condition variable.
## @param[in] timeout Timeout in nanoseconds.
## @return Result code (0xEA01 on timeout).
## @remark On function return, the underlying mutex is acquired.
##
proc condvarWaitTimeout*(c: ptr CondVar; m: ptr Mutex; timeout: U64): Result {.cdecl,
importc: "condvarWaitTimeout".}
## *
## @brief Waits on a condition variable.
## @param[in] c Condition variable object.
## @param[in] m Mutex object to use inside the condition variable.
## @return Result code.
## @remark On function return, the underlying mutex is acquired.
##
proc condvarWait*(c: ptr CondVar; m: ptr Mutex): Result {.inline, cdecl,
importc: "condvarWait".} =
return condvarWaitTimeout(c, m, uint64.high)
## *
## @brief Wakes up up to the specified number of threads waiting on a condition variable.
## @param[in] c Condition variable object.
## @param[in] num Maximum number of threads to wake up (or -1 to wake them all up).
## @return Result code.
##
proc condvarWake*(c: ptr CondVar; num: cint): Result {.inline, cdecl,
importc: "condvarWake".} =
svcSignalProcessWideKey(c, num)
return 0
## *
## @brief Wakes up a single thread waiting on a condition variable.
## @param[in] c Condition variable object.
## @return Result code.
##
proc condvarWakeOne*(c: ptr CondVar): Result {.inline, cdecl, importc: "condvarWakeOne".} =
return condvarWake(c, 1)
## *
## @brief Wakes up all thread waiting on a condition variable.
## @param[in] c Condition variable object.
## @return Result code.
##
proc condvarWakeAll*(c: ptr CondVar): Result {.inline, cdecl, importc: "condvarWakeAll".} =
return condvarWake(c, -1)

View file

@ -0,0 +1,24 @@
/**
* @file detect.h
* @brief Kernel capability detection
* @author plutoo
* @copyright libnx Authors
*/
#pragma once
#include "../types.h"
#include "../result.h"
#include "svc.h"
/// Returns true if the process has a debugger attached.
NX_INLINE bool detectDebugger(void) {
u64 tmp = 0;
Result rc = svcGetInfo(&tmp, InfoType_DebuggerAttached, INVALID_HANDLE, 0);
return R_SUCCEEDED(rc) && tmp != 0;
}
/// Returns true if the underlying kernel is Mesosphère.
NX_INLINE bool detectMesosphere(void) {
u64 dummy = 0;
Result rc = svcGetInfo(&dummy, 65000, INVALID_HANDLE, 0); // InfoType_MesosphereMeta
return R_SUCCEEDED(rc);
}

View file

@ -0,0 +1,24 @@
## *
## @file detect.h
## @brief Kernel capability detection
## @author plutoo
## @copyright libnx Authors
##
import
../types, ../result, svc
## / Returns true if the process has a debugger attached.
proc detectDebugger*(): bool {.inline, cdecl, importc: "detectDebugger".} =
var tmp: U64 = 0
var rc: Result = svcGetInfo(addr(tmp), InfoTypeDebuggerAttached.uint32, Invalid_Handle, 0)
return r_Succeeded(rc) and tmp != 0
## / Returns true if the underlying kernel is Mesosphère.
proc detectMesosphere*(): bool {.inline, cdecl, importc: "detectMesosphere".} =
var dummy: U64 = 0
var rc: Result = svcGetInfo(addr(dummy), 65000, Invalid_Handle, 0)
## InfoType_MesosphereMeta
return r_Succeeded(rc)

View file

@ -0,0 +1,84 @@
/**
* @file event.h
* @brief Kernel-mode event synchronization primitive.
* @author plutoo
* @copyright libnx Authors
*/
#pragma once
#include "../types.h"
#include "../result.h"
#include "wait.h"
/// Kernel-mode event structure.
typedef struct {
Handle revent; ///< Read-only event handle
Handle wevent; ///< Write-only event handle
bool autoclear; ///< Autoclear flag
} Event;
/// Creates a \ref Waiter for a kernel-mode event.
static inline Waiter waiterForEvent(Event* t)
{
Waiter wait_obj;
wait_obj.type = t->autoclear ? WaiterType_HandleWithClear : WaiterType_Handle;
wait_obj.handle = t->revent;
return wait_obj;
}
/**
* @brief Creates a kernel-mode event.
* @param[out] t Pointer to \ref Event structure.
* @param[in] autoclear Autoclear flag.
* @return Result code.
* @warning This is a privileged operation; in normal circumstances applications shouldn't use this function.
*/
Result eventCreate(Event* t, bool autoclear);
/**
* @brief Loads a kernel-mode event obtained from IPC.
* @param[out] t Pointer to \ref Event structure.
* @param[in] handle Read-only event handle.
* @param[in] autoclear Autoclear flag.
*/
void eventLoadRemote(Event* t, Handle handle, bool autoclear);
/**
* @brief Closes a kernel-mode event.
* @param[in] t Pointer to \ref Event structure.
*/
void eventClose(Event* t);
/**
* @brief Returns whether an \ref Event is initialized.
* @param[in] t Pointer to \ref Event structure.
* @return Initialization status.
*/
static inline bool eventActive(Event* t)
{
return t->revent != INVALID_HANDLE;
}
/**
* @brief Waits on a kernel-mode event.
* @param[in] t Pointer to \ref Event structure.
* @param[in] timeout Timeout in nanoseconds (pass UINT64_MAX to wait indefinitely).
* @return Result code.
*/
Result eventWait(Event* t, u64 timeout);
/**
* @brief Signals a kernel-mode event.
* @param[in] t Pointer to \ref Event structure.
* @return Result code.
* @note This function only works for events initialized with \ref eventCreate, it doesn't work with events initialized with \ref eventLoadRemote.
* @warning This is a privileged operation; in normal circumstances applications shouldn't use this function.
*/
Result eventFire(Event* t);
/**
* @brief Clears a kernel-mode event.
* @param[in] t Pointer to \ref Event structure.
* @return Result code.
* @note This function shouldn't be used on autoclear events.
*/
Result eventClear(Event* t);

View file

@ -0,0 +1,82 @@
## *
## @file event.h
## @brief Kernel-mode event synchronization primitive.
## @author plutoo
## @copyright libnx Authors
##
import
../types, ../result, wait
## / Kernel-mode event structure.
type
Event* {.bycopy.} = object
revent*: Handle ## /< Read-only event handle
wevent*: Handle ## /< Write-only event handle
autoclear*: bool ## /< Autoclear flag
proc waiterForEvent*(t: ptr Event): Waiter {.inline, cdecl, importc: "waiterForEvent".} =
## / Creates a \ref Waiter for a kernel-mode event.
var waitObj: Waiter
waitObj.`type` = if t.autoclear: WaiterTypeHandleWithClear else: WaiterTypeHandle
waitObj.anoWait3.handle = t.revent
return waitObj
proc eventCreate*(t: ptr Event; autoclear: bool): Result {.cdecl, importc: "eventCreate".}
## *
## @brief Creates a kernel-mode event.
## @param[out] t Pointer to \ref Event structure.
## @param[in] autoclear Autoclear flag.
## @return Result code.
## @warning This is a privileged operation; in normal circumstances applications shouldn't use this function.
##
proc eventLoadRemote*(t: ptr Event; handle: Handle; autoclear: bool) {.cdecl,
importc: "eventLoadRemote".}
## *
## @brief Loads a kernel-mode event obtained from IPC.
## @param[out] t Pointer to \ref Event structure.
## @param[in] handle Read-only event handle.
## @param[in] autoclear Autoclear flag.
##
proc eventClose*(t: ptr Event) {.cdecl, importc: "eventClose".}
## *
## @brief Closes a kernel-mode event.
## @param[in] t Pointer to \ref Event structure.
##
proc eventActive*(t: ptr Event): bool {.inline, cdecl, importc: "eventActive".} =
## *
## @brief Returns whether an \ref Event is initialized.
## @param[in] t Pointer to \ref Event structure.
## @return Initialization status.
##
return t.revent != Invalid_Handle
proc eventWait*(t: ptr Event; timeout: U64): Result {.cdecl, importc: "eventWait".}
## *
## @brief Waits on a kernel-mode event.
## @param[in] t Pointer to \ref Event structure.
## @param[in] timeout Timeout in nanoseconds (pass UINT64_MAX to wait indefinitely).
## @return Result code.
##
proc eventFire*(t: ptr Event): Result {.cdecl, importc: "eventFire".}
## *
## @brief Signals a kernel-mode event.
## @param[in] t Pointer to \ref Event structure.
## @return Result code.
## @note This function only works for events initialized with \ref eventCreate, it doesn't work with events initialized with \ref eventLoadRemote.
## @warning This is a privileged operation; in normal circumstances applications shouldn't use this function.
##
proc eventClear*(t: ptr Event): Result {.cdecl, importc: "eventClear".}
## *
## @brief Clears a kernel-mode event.
## @param[in] t Pointer to \ref Event structure.
## @return Result code.
## @note This function shouldn't be used on autoclear events.
##

View file

@ -0,0 +1,76 @@
/**
* @file jit.h
* @brief Just-in-time compilation support.
* @author plutoo
* @copyright libnx Authors
*/
#pragma once
#include "../types.h"
#include "virtmem.h"
/// JIT implementation type.
typedef enum {
JitType_SetProcessMemoryPermission, ///< JIT supported using svcSetProcessMemoryPermission
JitType_CodeMemory, ///< JIT supported using [4.0.0+] CodeMemory syscalls
} JitType;
/// JIT buffer object.
typedef struct {
JitType type;
size_t size;
void* src_addr;
void* rx_addr;
void* rw_addr;
bool is_executable;
union {
Handle handle;
VirtmemReservation* rv;
};
} Jit;
/**
* @brief Creates a JIT buffer.
* @param j JIT buffer.
* @param size Size of the JIT buffer.
* @return Result code.
*/
Result jitCreate(Jit* j, size_t size);
/**
* @brief Transition a JIT buffer to have writable permission.
* @param j JIT buffer.
* @return Result code.
*/
Result jitTransitionToWritable(Jit* j);
/**
* @brief Transition a JIT buffer to have executable permission.
* @param j JIT buffer.
* @return Result code.
*/
Result jitTransitionToExecutable(Jit* j);
/**
* @brief Destroys a JIT buffer.
* @param j JIT buffer.
* @return Result code.
*/
Result jitClose(Jit* j);
/**
* @brief Gets the address of the writable memory alias of a JIT buffer.
* @param j JIT buffer.
* @return Pointer to alias of the JIT buffer that can be written to.
*/
NX_CONSTEXPR void* jitGetRwAddr(Jit* j) {
return j->rw_addr;
}
/**
* @brief Gets the address of the executable memory alias of a JIT buffer.
* @param j JIT buffer.
* @return Pointer to alias of the JIT buffer that can be executed.
*/
NX_CONSTEXPR void* jitGetRxAddr(Jit* j) {
return j->rx_addr;
}

View file

@ -0,0 +1,83 @@
## *
## @file jit.h
## @brief Just-in-time compilation support.
## @author plutoo
## @copyright libnx Authors
##
import
../types, virtmem
## / JIT implementation type.
type
JitType* = enum
JitTypeSetProcessMemoryPermission, ## /< JIT supported using svcSetProcessMemoryPermission
JitTypeCodeMemory ## /< JIT supported using [4.0.0+] CodeMemory syscalls
## / JIT buffer object.
type
INNER_C_UNION_jit_2* {.bycopy, union.} = object
handle*: Handle
rv*: ptr VirtmemReservation
Jit* {.bycopy.} = object
`type`*: JitType
size*: csize_t
srcAddr*: pointer
rxAddr*: pointer
rwAddr*: pointer
isExecutable*: bool
anoJit3*: INNER_C_UNION_jit_2
## *
## @brief Creates a JIT buffer.
## @param j JIT buffer.
## @param size Size of the JIT buffer.
## @return Result code.
##
proc jitCreate*(j: ptr Jit; size: csize_t): Result {.cdecl, importc: "jitCreate".}
## *
## @brief Transition a JIT buffer to have writable permission.
## @param j JIT buffer.
## @return Result code.
##
proc jitTransitionToWritable*(j: ptr Jit): Result {.cdecl,
importc: "jitTransitionToWritable".}
## *
## @brief Transition a JIT buffer to have executable permission.
## @param j JIT buffer.
## @return Result code.
##
proc jitTransitionToExecutable*(j: ptr Jit): Result {.cdecl,
importc: "jitTransitionToExecutable".}
## *
## @brief Destroys a JIT buffer.
## @param j JIT buffer.
## @return Result code.
##
proc jitClose*(j: ptr Jit): Result {.cdecl, importc: "jitClose".}
## *
## @brief Gets the address of the writable memory alias of a JIT buffer.
## @param j JIT buffer.
## @return Pointer to alias of the JIT buffer that can be written to.
##
proc jitGetRwAddr*(j: ptr Jit): pointer {.inline, cdecl, importc: "jitGetRwAddr".} =
return j.rwAddr
## *
## @brief Gets the address of the executable memory alias of a JIT buffer.
## @param j JIT buffer.
## @return Pointer to alias of the JIT buffer that can be executed.
##
proc jitGetRxAddr*(j: ptr Jit): pointer {.inline, cdecl, importc: "jitGetRxAddr".} =
return j.rxAddr

View file

@ -0,0 +1,54 @@
/**
* @file levent.h
* @brief Light event synchronization primitive [4.0.0+]
* @author fincs
* @copyright libnx Authors
*/
#pragma once
#include "../types.h"
#include "../result.h"
#include "svc.h"
/// User-mode light event structure.
typedef struct LEvent {
u32 counter;
bool autoclear;
} LEvent;
/**
* @brief Initializes a user-mode light event.
* @param[out] le Pointer to \ref LEvent structure.
* @param[in] signaled Whether the event starts off in signaled state.
* @param[in] autoclear Autoclear flag.
*/
NX_CONSTEXPR void leventInit(LEvent* le, bool signaled, bool autoclear) {
le->counter = signaled ? 2 : 0;
le->autoclear = autoclear;
}
/**
* @brief Waits on a user-mode light event.
* @param[in] le Pointer to \ref LEvent structure.
* @param[in] timeout_ns Timeout in nanoseconds (pass UINT64_MAX to wait indefinitely).
* @return true if wait succeeded, false if wait timed out.
*/
bool leventWait(LEvent* le, u64 timeout_ns);
/**
* @brief Polls a user-mode light event.
* @param[in] le Pointer to \ref LEvent structure.
* @return true if event is signaled, false otherwise.
*/
bool leventTryWait(LEvent* le);
/**
* @brief Signals a user-mode light event.
* @param[in] le Pointer to \ref LEvent structure.
*/
void leventSignal(LEvent* le);
/**
* @brief Clears a user-mode light event.
* @param[in] le Pointer to \ref LEvent structure.
*/
void leventClear(LEvent* le);

View file

@ -0,0 +1,56 @@
## *
## @file levent.h
## @brief Light event synchronization primitive [4.0.0+]
## @author fincs
## @copyright libnx Authors
##
import
../types, ../result
## / User-mode light event structure.
type
LEvent* {.bycopy.} = object
counter*: U32
autoclear*: bool
proc leventInit*(le: ptr LEvent; signaled: bool; autoclear: bool) {.inline, cdecl,
importc: "leventInit".} =
## *
## @brief Initializes a user-mode light event.
## @param[out] le Pointer to \ref LEvent structure.
## @param[in] signaled Whether the event starts off in signaled state.
## @param[in] autoclear Autoclear flag.
##
le.counter = if signaled: 2 else: 0
le.autoclear = autoclear
proc leventWait*(le: ptr LEvent; timeoutNs: U64): bool {.cdecl, importc: "leventWait".}
## *
## @brief Waits on a user-mode light event.
## @param[in] le Pointer to \ref LEvent structure.
## @param[in] timeout_ns Timeout in nanoseconds (pass UINT64_MAX to wait indefinitely).
## @return true if wait succeeded, false if wait timed out.
##
proc leventTryWait*(le: ptr LEvent): bool {.cdecl, importc: "leventTryWait".}
## *
## @brief Polls a user-mode light event.
## @param[in] le Pointer to \ref LEvent structure.
## @return true if event is signaled, false otherwise.
##
proc leventSignal*(le: ptr LEvent) {.cdecl, importc: "leventSignal".}
## *
## @brief Signals a user-mode light event.
## @param[in] le Pointer to \ref LEvent structure.
##
proc leventClear*(le: ptr LEvent) {.cdecl, importc: "leventClear".}
## *
## @brief Clears a user-mode light event.
## @param[in] le Pointer to \ref LEvent structure.
##

View file

@ -0,0 +1,81 @@
/**
* @file mutex.h
* @brief Mutex synchronization primitive.
* @author plutoo
* @copyright libnx Authors
*/
#pragma once
#include <sys/lock.h>
#include "../types.h"
/// Mutex datatype, defined in newlib.
typedef _LOCK_T Mutex;
/// Recursive mutex datatype, defined in newlib.
typedef _LOCK_RECURSIVE_T RMutex;
/**
* @brief Initializes a mutex.
* @param m Mutex object.
* @note A mutex can also be statically initialized by assigning 0 to it.
*/
static inline void mutexInit(Mutex* m)
{
*m = INVALID_HANDLE;
}
/**
* @brief Locks a mutex.
* @param m Mutex object.
*/
void mutexLock(Mutex* m);
/**
* @brief Attempts to lock a mutex without waiting.
* @param m Mutex object.
* @return 1 if the mutex has been acquired successfully, and 0 on contention.
*/
bool mutexTryLock(Mutex* m);
/**
* @brief Unlocks a mutex.
* @param m Mutex object.
*/
void mutexUnlock(Mutex* m);
/**
* @brief Gets whether the current thread owns the mutex.
* @param m Mutex object.
* @return 1 if the mutex is locked by the current thread, and 0 otherwise.
*/
bool mutexIsLockedByCurrentThread(const Mutex* m);
/**
* @brief Initializes a recursive mutex.
* @param m Recursive mutex object.
* @note A recursive mutex can also be statically initialized by assigning {0,0,0} to it.
*/
static inline void rmutexInit(RMutex* m)
{
m->lock = 0;
m->thread_tag = 0;
m->counter = 0;
}
/**
* @brief Locks a recursive mutex.
* @param m Recursive mutex object.
*/
void rmutexLock(RMutex* m);
/**
* @brief Attempts to lock a recursive mutex without waiting.
* @param m Recursive mutex object.
* @return 1 if the mutex has been acquired successfully, and 0 on contention.
*/
bool rmutexTryLock(RMutex* m);
/**
* @brief Unlocks a recursive mutex.
* @param m Recursive mutex object.
*/
void rmutexUnlock(RMutex* m);

View file

@ -0,0 +1,90 @@
## *
## @file mutex.h
## @brief Mutex synchronization primitive.
## @author plutoo
## @copyright libnx Authors
##
import
../types
## / Mutex datatype, defined in newlib.
type
Mutex* = distinct uint32
Lock* = distinct uint32
## / Recursive mutex datatype, defined in newlib.
type
RMutex* = object
lock*: Lock
threadTag*: uint32
counter*: uint32
## *
## @brief Initializes a mutex.
## @param m Mutex object.
## @note A mutex can also be statically initialized by assigning 0 to it.
##
proc mutexInit*(m: ptr Mutex) {.inline, cdecl, importc: "mutexInit".} =
m[] = INVALID_HANDLE.Mutex
## *
## @brief Locks a mutex.
## @param m Mutex object.
##
proc mutexLock*(m: ptr Mutex) {.cdecl, importc: "mutexLock".}
## *
## @brief Attempts to lock a mutex without waiting.
## @param m Mutex object.
## @return 1 if the mutex has been acquired successfully, and 0 on contention.
##
proc mutexTryLock*(m: ptr Mutex): bool {.cdecl, importc: "mutexTryLock".}
## *
## @brief Unlocks a mutex.
## @param m Mutex object.
##
proc mutexUnlock*(m: ptr Mutex) {.cdecl, importc: "mutexUnlock".}
## *
## @brief Gets whether the current thread owns the mutex.
## @param m Mutex object.
## @return 1 if the mutex is locked by the current thread, and 0 otherwise.
##
proc mutexIsLockedByCurrentThread*(m: ptr Mutex): bool {.cdecl,
importc: "mutexIsLockedByCurrentThread".}
## *
## @brief Initializes a recursive mutex.
## @param m Recursive mutex object.
## @note A recursive mutex can also be statically initialized by assigning {0,0,0} to it.
##
proc rmutexInit*(m: ptr RMutex) {.inline, cdecl, importc: "rmutexInit".} =
m.lock = 0.Lock
m.threadTag = 0
m.counter = 0
## *
## @brief Locks a recursive mutex.
## @param m Recursive mutex object.
##
proc rmutexLock*(m: ptr RMutex) {.cdecl, importc: "rmutexLock".}
## *
## @brief Attempts to lock a recursive mutex without waiting.
## @param m Recursive mutex object.
## @return 1 if the mutex has been acquired successfully, and 0 on contention.
##
proc rmutexTryLock*(m: ptr RMutex): bool {.cdecl, importc: "rmutexTryLock".}
## *
## @brief Unlocks a recursive mutex.
## @param m Recursive mutex object.
##
proc rmutexUnlock*(m: ptr RMutex) {.cdecl, importc: "rmutexUnlock".}

View file

@ -0,0 +1,21 @@
/**
* @file random.h
* @brief OS-seeded pseudo-random number generation support (ChaCha algorithm).
* @author plutoo
* @copyright libnx Authors
*/
#pragma once
#include "../types.h"
/**
* @brief Fills a buffer with random data.
* @param buf Pointer to the buffer.
* @param len Size of the buffer in bytes.
*/
void randomGet(void* buf, size_t len);
/**
* @brief Returns a random 64-bit value.
* @return Random value.
*/
u64 randomGet64(void);

View file

@ -0,0 +1,23 @@
## *
## @file random.h
## @brief OS-seeded pseudo-random number generation support (ChaCha algorithm).
## @author plutoo
## @copyright libnx Authors
##
import
../types
## *
## @brief Fills a buffer with random data.
## @param buf Pointer to the buffer.
## @param len Size of the buffer in bytes.
##
proc randomGet*(buf: pointer; len: csize_t) {.cdecl, importc: "randomGet".}
## *
## @brief Returns a random 64-bit value.
## @return Random value.
##
proc randomGet64*(): U64 {.cdecl, importc: "randomGet64".}

View file

@ -0,0 +1,80 @@
/**
* @file rwlock.h
* @brief Read/write lock synchronization primitive.
* @author plutoo, SciresM
* @copyright libnx Authors
*/
#pragma once
#include "../kernel/mutex.h"
#include "../kernel/condvar.h"
/// Read/write lock structure.
typedef struct {
Mutex mutex;
CondVar condvar_reader_wait;
CondVar condvar_writer_wait;
u32 read_lock_count;
u32 read_waiter_count;
u32 write_lock_count;
u32 write_waiter_count;
u32 write_owner_tag;
} RwLock;
/**
* @brief Initializes the read/write lock.
* @param r Read/write lock object.
*/
void rwlockInit(RwLock* r);
/**
* @brief Locks the read/write lock for reading.
* @param r Read/write lock object.
*/
void rwlockReadLock(RwLock* r);
/**
* @brief Attempts to lock the read/write lock for reading without waiting.
* @param r Read/write lock object.
* @return 1 if the mutex has been acquired successfully, and 0 on contention.
*/
bool rwlockTryReadLock(RwLock* r);
/**
* @brief Unlocks the read/write lock for reading.
* @param r Read/write lock object.
*/
void rwlockReadUnlock(RwLock* r);
/**
* @brief Locks the read/write lock for writing.
* @param r Read/write lock object.
*/
void rwlockWriteLock(RwLock* r);
/**
* @brief Attempts to lock the read/write lock for writing without waiting.
* @param r Read/write lock object.
* @return 1 if the mutex has been acquired successfully, and 0 on contention.
*/
bool rwlockTryWriteLock(RwLock* r);
/**
* @brief Unlocks the read/write lock for writing.
* @param r Read/write lock object.
*/
void rwlockWriteUnlock(RwLock* r);
/**
* @brief Checks if the write lock is held by the current thread.
* @param r Read/write lock object.
* @return 1 if the current hold holds the write lock, and 0 if it does not.
*/
bool rwlockIsWriteLockHeldByCurrentThread(RwLock* r);
/**
* @brief Checks if the read/write lock is owned by the current thread.
* @param r Read/write lock object.
* @return 1 if the current hold holds the write lock or if it holds read locks acquired
* while it held the write lock, and 0 if it does not.
*/
bool rwlockIsOwnedByCurrentThread(RwLock* r);

View file

@ -0,0 +1,84 @@
## *
## @file rwlock.h
## @brief Read/write lock synchronization primitive.
## @author plutoo, SciresM
## @copyright libnx Authors
##
import
../kernel/mutex, ../kernel/condvar, ../types
## / Read/write lock structure.
type
RwLock* {.bycopy.} = object
mutex*: Mutex
condvarReaderWait*: CondVar
condvarWriterWait*: CondVar
readLockCount*: U32
readWaiterCount*: U32
writeLockCount*: U32
writeWaiterCount*: U32
writeOwnerTag*: U32
proc rwlockInit*(r: ptr RwLock) {.cdecl, importc: "rwlockInit".}
## *
## @brief Initializes the read/write lock.
## @param r Read/write lock object.
##
proc rwlockReadLock*(r: ptr RwLock) {.cdecl, importc: "rwlockReadLock".}
## *
## @brief Locks the read/write lock for reading.
## @param r Read/write lock object.
##
proc rwlockTryReadLock*(r: ptr RwLock): bool {.cdecl, importc: "rwlockTryReadLock".}
## *
## @brief Attempts to lock the read/write lock for reading without waiting.
## @param r Read/write lock object.
## @return 1 if the mutex has been acquired successfully, and 0 on contention.
##
proc rwlockReadUnlock*(r: ptr RwLock) {.cdecl, importc: "rwlockReadUnlock".}
## *
## @brief Unlocks the read/write lock for reading.
## @param r Read/write lock object.
##
proc rwlockWriteLock*(r: ptr RwLock) {.cdecl, importc: "rwlockWriteLock".}
## *
## @brief Locks the read/write lock for writing.
## @param r Read/write lock object.
##
proc rwlockTryWriteLock*(r: ptr RwLock): bool {.cdecl, importc: "rwlockTryWriteLock".}
## *
## @brief Attempts to lock the read/write lock for writing without waiting.
## @param r Read/write lock object.
## @return 1 if the mutex has been acquired successfully, and 0 on contention.
##
proc rwlockWriteUnlock*(r: ptr RwLock) {.cdecl, importc: "rwlockWriteUnlock".}
## *
## @brief Unlocks the read/write lock for writing.
## @param r Read/write lock object.
##
proc rwlockIsWriteLockHeldByCurrentThread*(r: ptr RwLock): bool {.cdecl,
importc: "rwlockIsWriteLockHeldByCurrentThread".}
## *
## @brief Checks if the write lock is held by the current thread.
## @param r Read/write lock object.
## @return 1 if the current hold holds the write lock, and 0 if it does not.
##
proc rwlockIsOwnedByCurrentThread*(r: ptr RwLock): bool {.cdecl,
importc: "rwlockIsOwnedByCurrentThread".}
## *
## @brief Checks if the read/write lock is owned by the current thread.
## @param r Read/write lock object.
## @return 1 if the current hold holds the write lock or if it holds read locks acquired
## while it held the write lock, and 0 if it does not.
##

View file

@ -0,0 +1,44 @@
/**
* @file semaphore.h
* @brief Thread synchronization based on Mutex.
* @author SciresM & Kevoot
* @copyright libnx Authors
*/
#pragma once
#include "mutex.h"
#include "condvar.h"
/// Semaphore structure.
typedef struct Semaphore
{
CondVar condvar; ///< Condition variable object.
Mutex mutex; ///< Mutex object.
u64 count; ///< Internal counter.
} Semaphore;
/**
* @brief Initializes a semaphore and its internal counter.
* @param s Semaphore object.
* @param initial_count initial value for internal counter (typically the # of free resources).
*/
void semaphoreInit(Semaphore *s, u64 initial_count);
/**
* @brief Increments the Semaphore to allow other threads to continue.
* @param s Semaphore object.
*/
void semaphoreSignal(Semaphore *s);
/**
* @brief Decrements Semaphore and waits if 0.
* @param s Semaphore object.
*/
void semaphoreWait(Semaphore *s);
/**
* @brief Attempts to get lock without waiting.
* @param s Semaphore object.
* @return true if no wait and successful lock, false otherwise.
*/
bool semaphoreTryWait(Semaphore *s);

View file

@ -0,0 +1,45 @@
## *
## @file semaphore.h
## @brief Thread synchronization based on Mutex.
## @author SciresM & Kevoot
## @copyright libnx Authors
##
import
mutex, condvar, ../types
## / Semaphore structure.
type
Semaphore* {.bycopy.} = object
condvar*: CondVar ## /< Condition variable object.
mutex*: Mutex ## /< Mutex object.
count*: U64 ## /< Internal counter.
proc semaphoreInit*(s: ptr Semaphore; initialCount: U64) {.cdecl,
importc: "semaphoreInit".}
## *
## @brief Initializes a semaphore and its internal counter.
## @param s Semaphore object.
## @param initial_count initial value for internal counter (typically the # of free resources).
##
proc semaphoreSignal*(s: ptr Semaphore) {.cdecl, importc: "semaphoreSignal".}
## *
## @brief Increments the Semaphore to allow other threads to continue.
## @param s Semaphore object.
##
proc semaphoreWait*(s: ptr Semaphore) {.cdecl, importc: "semaphoreWait".}
## *
## @brief Decrements Semaphore and waits if 0.
## @param s Semaphore object.
##
proc semaphoreTryWait*(s: ptr Semaphore): bool {.cdecl, importc: "semaphoreTryWait".}
## *
## @brief Attempts to get lock without waiting.
## @param s Semaphore object.
## @return true if no wait and successful lock, false otherwise.
##

View file

@ -0,0 +1,67 @@
/**
* @file shmem.h
* @brief Shared memory object handling
* @author plutoo
* @copyright libnx Authors
* @remark Shared memory differs from transfer memory in the fact that the kernel (as opposed to the user process) allocates and owns its backing memory.
*/
#pragma once
#include "../types.h"
/// Shared memory information structure.
typedef struct {
Handle handle; ///< Kernel object handle.
size_t size; ///< Size of the shared memory object.
Permission perm; ///< Permissions.
void* map_addr; ///< Address to which the shared memory object is mapped.
} SharedMemory;
/**
* @brief Creates a shared memory object.
* @param s Shared memory information structure which will be filled in.
* @param size Size of the shared memory object to create.
* @param local_perm Permissions with which the shared memory object will be mapped in the local process.
* @param remote_perm Permissions with which the shared memory object will be mapped in the remote process (can be Perm_DontCare).
* @return Result code.
* @warning This is a privileged operation; in normal circumstances applications cannot use this function.
*/
Result shmemCreate(SharedMemory* s, size_t size, Permission local_perm, Permission remote_perm);
/**
* @brief Loads a shared memory object coming from a remote process.
* @param s Shared memory information structure which will be filled in.
* @param handle Handle of the shared memory object.
* @param size Size of the shared memory object that is being loaded.
* @param perm Permissions with which the shared memory object will be mapped in the local process.
*/
void shmemLoadRemote(SharedMemory* s, Handle handle, size_t size, Permission perm);
/**
* @brief Maps a shared memory object.
* @param s Shared memory information structure.
* @return Result code.
*/
Result shmemMap(SharedMemory* s);
/**
* @brief Unmaps a shared memory object.
* @param s Shared memory information structure.
* @return Result code.
*/
Result shmemUnmap(SharedMemory* s);
/**
* @brief Retrieves the mapped address of a shared memory object.
* @param s Shared memory information structure.
* @return Mapped address of the shared memory object.
*/
static inline void* shmemGetAddr(SharedMemory* s) {
return s->map_addr;
}
/**
* @brief Frees up resources used by a shared memory object, unmapping and closing handles, etc.
* @param s Shared memory information structure.
* @return Result code.
*/
Result shmemClose(SharedMemory* s);

View file

@ -0,0 +1,71 @@
## *
## @file shmem.h
## @brief Shared memory object handling
## @author plutoo
## @copyright libnx Authors
## @remark Shared memory differs from transfer memory in the fact that the kernel (as opposed to the user process) allocates and owns its backing memory.
##
import
../types, svc
## / Shared memory information structure.
type
SharedMemory* {.bycopy.} = object
handle*: Handle ## /< Kernel object handle.
size*: csize_t ## /< Size of the shared memory object.
perm*: Permission ## /< Permissions.
mapAddr*: pointer ## /< Address to which the shared memory object is mapped.
proc shmemCreate*(s: ptr SharedMemory; size: csize_t; localPerm: Permission;
remotePerm: Permission): Result {.cdecl, importc: "shmemCreate".}
## *
## @brief Creates a shared memory object.
## @param s Shared memory information structure which will be filled in.
## @param size Size of the shared memory object to create.
## @param local_perm Permissions with which the shared memory object will be mapped in the local process.
## @param remote_perm Permissions with which the shared memory object will be mapped in the remote process (can be Perm_DontCare).
## @return Result code.
## @warning This is a privileged operation; in normal circumstances applications cannot use this function.
##
proc shmemLoadRemote*(s: ptr SharedMemory; handle: Handle; size: csize_t;
perm: Permission) {.cdecl, importc: "shmemLoadRemote".}
## *
## @brief Loads a shared memory object coming from a remote process.
## @param s Shared memory information structure which will be filled in.
## @param handle Handle of the shared memory object.
## @param size Size of the shared memory object that is being loaded.
## @param perm Permissions with which the shared memory object will be mapped in the local process.
##
proc shmemMap*(s: ptr SharedMemory): Result {.cdecl, importc: "shmemMap".}
## *
## @brief Maps a shared memory object.
## @param s Shared memory information structure.
## @return Result code.
##
proc shmemUnmap*(s: ptr SharedMemory): Result {.cdecl, importc: "shmemUnmap".}
## *
## @brief Unmaps a shared memory object.
## @param s Shared memory information structure.
## @return Result code.
##
proc shmemGetAddr*(s: ptr SharedMemory): pointer {.inline, cdecl.} =
## *
## @brief Retrieves the mapped address of a shared memory object.
## @param s Shared memory information structure.
## @return Mapped address of the shared memory object.
##
return s.mapAddr
proc shmemClose*(s: ptr SharedMemory): Result {.cdecl, importc: "shmemClose".}
## *
## @brief Frees up resources used by a shared memory object, unmapping and closing handles, etc.
## @param s Shared memory information structure.
## @return Result code.
##

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,131 @@
/**
* @file thread.h
* @brief Multi-threading support
* @author plutoo
* @copyright libnx Authors
*/
#pragma once
#include "../types.h"
#include "../arm/thread_context.h"
#include "wait.h"
/// Thread information structure.
typedef struct Thread {
Handle handle; ///< Thread handle.
bool owns_stack_mem; ///< Whether the stack memory is automatically allocated.
void* stack_mem; ///< Pointer to stack memory.
void* stack_mirror; ///< Pointer to stack memory mirror.
size_t stack_sz; ///< Stack size.
void** tls_array;
struct Thread* next;
struct Thread** prev_next;
} Thread;
/// Creates a \ref Waiter for a \ref Thread.
static inline Waiter waiterForThread(Thread* t)
{
return waiterForHandle(t->handle);
}
/**
* @brief Creates a thread.
* @param t Thread information structure which will be filled in.
* @param entry Entrypoint of the thread.
* @param arg Argument to pass to the entrypoint.
* @param stack_mem Memory to use as backing for stack/tls/reent. Must be page-aligned. NULL argument means to allocate new memory.
* @param stack_sz If stack_mem is NULL, size to use for stack. If stack_mem is non-NULL, size to use for stack + reent + tls (must be page-aligned).
* @param prio Thread priority (0x00~0x3F); 0x2C is the usual priority of the main thread, 0x3B is a special priority on cores 0..2 that enables preemptive multithreading (0x3F on core 3).
* @param cpuid ID of the core on which to create the thread (0~3); or -2 to use the default core for the current process.
* @return Result code.
*/
Result threadCreate(
Thread* t, ThreadFunc entry, void* arg, void *stack_mem, size_t stack_sz,
int prio, int cpuid);
/**
* @brief Starts the execution of a thread.
* @param t Thread information structure.
* @return Result code.
*/
Result threadStart(Thread* t);
/**
* @brief Exits the current thread immediately.
*/
void NORETURN threadExit(void);
/**
* @brief Waits for a thread to finish executing.
* @param t Thread information structure.
* @return Result code.
*/
Result threadWaitForExit(Thread* t);
/**
* @brief Frees up resources associated with a thread.
* @param t Thread information structure.
* @return Result code.
*/
Result threadClose(Thread* t);
/**
* @brief Pauses the execution of a thread.
* @param t Thread information structure.
* @return Result code.
*/
Result threadPause(Thread* t);
/**
* @brief Resumes the execution of a thread, after having been paused.
* @param t Thread information structure.
* @return Result code.
*/
Result threadResume(Thread* t);
/**
* @brief Dumps the registers of a thread paused by @ref threadPause (register groups: all).
* @param[out] ctx Output thread context (register dump).
* @param t Thread information structure.
* @return Result code.
* @warning Official kernel will not dump x0..x18 if the thread is currently executing a system call, and prior to 6.0.0 doesn't dump TPIDR_EL0.
*/
Result threadDumpContext(ThreadContext* ctx, Thread* t);
/**
* @brief Gets a pointer to the current thread structure.
* @return Thread information structure.
*/
Thread *threadGetSelf(void);
/**
* @brief Gets the raw handle to the current thread.
* @return The current thread's handle.
*/
Handle threadGetCurHandle(void);
/**
* @brief Allocates a TLS slot.
* @param destructor Function to run automatically when a thread exits.
* @return TLS slot ID on success, or a negative value on failure.
*/
s32 threadTlsAlloc(void (* destructor)(void*));
/**
* @brief Retrieves the value stored in a TLS slot.
* @param slot_id TLS slot ID.
* @return Value.
*/
void* threadTlsGet(s32 slot_id);
/**
* @brief Stores the specified value into a TLS slot.
* @param slot_id TLS slot ID.
* @param value Value.
*/
void threadTlsSet(s32 slot_id, void* value);
/**
* @brief Frees a TLS slot.
* @param slot_id TLS slot ID.
*/
void threadTlsFree(s32 slot_id);

View file

@ -0,0 +1,133 @@
## *
## @file thread.h
## @brief Multi-threading support
## @author plutoo
## @copyright libnx Authors
##
import
../types, ../arm/thread_context, wait
## / Thread information structure.
type
Thread* {.bycopy.} = object
handle*: Handle ## /< Thread handle.
ownsStackMem*: bool ## /< Whether the stack memory is automatically allocated.
stackMem*: pointer ## /< Pointer to stack memory.
stackMirror*: pointer ## /< Pointer to stack memory mirror.
stackSz*: csize_t ## /< Stack size.
tlsArray*: ptr pointer
next*: ptr Thread
prevNext*: ptr ptr Thread
proc waiterForThread*(t: ptr Thread): Waiter {.inline, cdecl,
importc: "waiterForThread".} =
## / Creates a \ref Waiter for a \ref Thread.
return waiterForHandle(t.handle)
proc threadCreate*(t: ptr Thread; entry: ThreadFunc; arg: pointer; stackMem: pointer;
stackSz: csize_t; prio: cint; cpuid: cint): Result {.cdecl,
importc: "threadCreate".}
## *
## @brief Creates a thread.
## @param t Thread information structure which will be filled in.
## @param entry Entrypoint of the thread.
## @param arg Argument to pass to the entrypoint.
## @param stack_mem Memory to use as backing for stack/tls/reent. Must be page-aligned. NULL argument means to allocate new memory.
## @param stack_sz If stack_mem is NULL, size to use for stack. If stack_mem is non-NULL, size to use for stack + reent + tls (must be page-aligned).
## @param prio Thread priority (0x00~0x3F); 0x2C is the usual priority of the main thread, 0x3B is a special priority on cores 0..2 that enables preemptive multithreading (0x3F on core 3).
## @param cpuid ID of the core on which to create the thread (0~3); or -2 to use the default core for the current process.
## @return Result code.
##
proc threadStart*(t: ptr Thread): Result {.cdecl, importc: "threadStart".}
## *
## @brief Starts the execution of a thread.
## @param t Thread information structure.
## @return Result code.
##
proc threadExit*() {.cdecl, importc: "threadExit".}
## *
## @brief Exits the current thread immediately.
##
proc threadWaitForExit*(t: ptr Thread): Result {.cdecl, importc: "threadWaitForExit".}
## *
## @brief Waits for a thread to finish executing.
## @param t Thread information structure.
## @return Result code.
##
proc threadClose*(t: ptr Thread): Result {.cdecl, importc: "threadClose".}
## *
## @brief Frees up resources associated with a thread.
## @param t Thread information structure.
## @return Result code.
##
proc threadPause*(t: ptr Thread): Result {.cdecl, importc: "threadPause".}
## *
## @brief Pauses the execution of a thread.
## @param t Thread information structure.
## @return Result code.
##
proc threadResume*(t: ptr Thread): Result {.cdecl, importc: "threadResume".}
## *
## @brief Resumes the execution of a thread, after having been paused.
## @param t Thread information structure.
## @return Result code.
##
proc threadDumpContext*(ctx: ptr ThreadContext; t: ptr Thread): Result {.cdecl,
importc: "threadDumpContext".}
## *
## @brief Dumps the registers of a thread paused by @ref threadPause (register groups: all).
## @param[out] ctx Output thread context (register dump).
## @param t Thread information structure.
## @return Result code.
## @warning Official kernel will not dump x0..x18 if the thread is currently executing a system call, and prior to 6.0.0 doesn't dump TPIDR_EL0.
##
proc threadGetSelf*(): ptr Thread {.cdecl, importc: "threadGetSelf".}
## *
## @brief Gets a pointer to the current thread structure.
## @return Thread information structure.
##
proc threadGetCurHandle*(): Handle {.cdecl, importc: "threadGetCurHandle".}
## *
## @brief Gets the raw handle to the current thread.
## @return The current thread's handle.
##
proc threadTlsAlloc*(destructor: proc (a1: pointer) {.cdecl.}): S32 {.cdecl,
importc: "threadTlsAlloc".}
## *
## @brief Allocates a TLS slot.
## @param destructor Function to run automatically when a thread exits.
## @return TLS slot ID on success, or a negative value on failure.
##
proc threadTlsGet*(slotId: S32): pointer {.cdecl, importc: "threadTlsGet".}
## *
## @brief Retrieves the value stored in a TLS slot.
## @param slot_id TLS slot ID.
## @return Value.
##
proc threadTlsSet*(slotId: S32; value: pointer) {.cdecl, importc: "threadTlsSet".}
## *
## @brief Stores the specified value into a TLS slot.
## @param slot_id TLS slot ID.
## @param value Value.
##
proc threadTlsFree*(slotId: S32) {.cdecl, importc: "threadTlsFree".}
## *
## @brief Frees a TLS slot.
## @param slot_id TLS slot ID.
##

View file

@ -0,0 +1,80 @@
/**
* @file tmem.h
* @brief Transfer memory handling
* @author plutoo
* @copyright libnx Authors
* @remark Transfer memory differs from shared memory in the fact that the user process (as opposed to the kernel) allocates and owns its backing memory.
*/
#pragma once
#include "../types.h"
#include "../kernel/svc.h"
/// Transfer memory information structure.
typedef struct {
Handle handle; ///< Kernel object handle.
size_t size; ///< Size of the transfer memory object.
Permission perm; ///< Permissions of the transfer memory object.
void* src_addr; ///< Address of the source backing memory.
void* map_addr; ///< Address to which the transfer memory object is mapped.
} TransferMemory;
/**
* @brief Creates a transfer memory object.
* @param t Transfer memory information structure that will be filled in.
* @param size Size of the transfer memory object to create.
* @param perm Permissions with which to protect the transfer memory in the local process.
* @return Result code.
*/
Result tmemCreate(TransferMemory* t, size_t size, Permission perm);
/**
* @brief Creates a transfer memory object from existing memory.
* @param t Transfer memory information structure that will be filled in.
* @param buf Pointer to a page-aligned buffer.
* @param size Size of the transfer memory object to create.
* @param perm Permissions with which to protect the transfer memory in the local process.
* @return Result code.
*/
Result tmemCreateFromMemory(TransferMemory* t, void* buf, size_t size, Permission perm);
/**
* @brief Loads a transfer memory object coming from a remote process.
* @param t Transfer memory information structure which will be filled in.
* @param handle Handle of the transfer memory object.
* @param size Size of the transfer memory object that is being loaded.
* @param perm Permissions which the transfer memory is expected to have in the process that owns the memory.
* @warning This is a privileged operation; in normal circumstances applications shouldn't use this function.
*/
void tmemLoadRemote(TransferMemory* t, Handle handle, size_t size, Permission perm);
/**
* @brief Maps a transfer memory object.
* @param t Transfer memory information structure.
* @return Result code.
* @warning This is a privileged operation; in normal circumstances applications cannot use this function.
*/
Result tmemMap(TransferMemory* t);
/**
* @brief Unmaps a transfer memory object.
* @param t Transfer memory information structure.
* @return Result code.
* @warning This is a privileged operation; in normal circumstances applications cannot use this function.
*/
Result tmemUnmap(TransferMemory* t);
/**
* @brief Retrieves the mapped address of a transfer memory object.
* @param t Transfer memory information structure.
* @return Mapped address of the transfer memory object.
*/
static inline void* tmemGetAddr(TransferMemory* t){
return t->map_addr;
}
/**
* @brief Frees up resources used by a transfer memory object, unmapping and closing handles, etc.
* @param t Transfer memory information structure.
* @return Result code.
*/
Result tmemClose(TransferMemory* t);

View file

@ -0,0 +1,88 @@
## *
## @file tmem.h
## @brief Transfer memory handling
## @author plutoo
## @copyright libnx Authors
## @remark Transfer memory differs from shared memory in the fact that the user process (as opposed to the kernel) allocates and owns its backing memory.
##
import
../types, ../kernel/svc
## / Transfer memory information structure.
type
TransferMemory* {.bycopy.} = object
handle*: Handle ## /< Kernel object handle.
size*: csize_t ## /< Size of the transfer memory object.
perm*: Permission ## /< Permissions of the transfer memory object.
srcAddr*: pointer ## /< Address of the source backing memory.
mapAddr*: pointer ## /< Address to which the transfer memory object is mapped.
## *
## @brief Creates a transfer memory object.
## @param t Transfer memory information structure that will be filled in.
## @param size Size of the transfer memory object to create.
## @param perm Permissions with which to protect the transfer memory in the local process.
## @return Result code.
##
proc tmemCreate*(t: ptr TransferMemory; size: csize_t; perm: Permission): Result {.cdecl,
importc: "tmemCreate".}
## *
## @brief Creates a transfer memory object from existing memory.
## @param t Transfer memory information structure that will be filled in.
## @param buf Pointer to a page-aligned buffer.
## @param size Size of the transfer memory object to create.
## @param perm Permissions with which to protect the transfer memory in the local process.
## @return Result code.
##
proc tmemCreateFromMemory*(t: ptr TransferMemory; buf: pointer; size: csize_t;
perm: Permission): Result {.cdecl,
importc: "tmemCreateFromMemory".}
## *
## @brief Loads a transfer memory object coming from a remote process.
## @param t Transfer memory information structure which will be filled in.
## @param handle Handle of the transfer memory object.
## @param size Size of the transfer memory object that is being loaded.
## @param perm Permissions which the transfer memory is expected to have in the process that owns the memory.
## @warning This is a privileged operation; in normal circumstances applications shouldn't use this function.
##
proc tmemLoadRemote*(t: ptr TransferMemory; handle: Handle; size: csize_t;
perm: Permission) {.cdecl, importc: "tmemLoadRemote".}
## *
## @brief Maps a transfer memory object.
## @param t Transfer memory information structure.
## @return Result code.
## @warning This is a privileged operation; in normal circumstances applications cannot use this function.
##
proc tmemMap*(t: ptr TransferMemory): Result {.cdecl, importc: "tmemMap".}
## *
## @brief Unmaps a transfer memory object.
## @param t Transfer memory information structure.
## @return Result code.
## @warning This is a privileged operation; in normal circumstances applications cannot use this function.
##
proc tmemUnmap*(t: ptr TransferMemory): Result {.cdecl, importc: "tmemUnmap".}
## *
## @brief Retrieves the mapped address of a transfer memory object.
## @param t Transfer memory information structure.
## @return Mapped address of the transfer memory object.
##
proc tmemGetAddr*(t: ptr TransferMemory): pointer {.inline, cdecl,
importc: "tmemGetAddr".} =
return t.mapAddr
## *
## @brief Frees up resources used by a transfer memory object, unmapping and closing handles, etc.
## @param t Transfer memory information structure.
## @return Result code.
##
proc tmemClose*(t: ptr TransferMemory): Result {.cdecl, importc: "tmemClose".}

Some files were not shown because too many files have changed in this diff Show more