Compare commits

...

306 Commits

Author SHA1 Message Date
Fredrik Fornwall 53f75a8da3 Changed: Update gradle, android gradle plugin and dependencies 2026-01-04 03:16:28 +01:00
dependabot[bot] bcb61c387c Changed: Bump actions/upload-artifact from 4 to 6
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 4 to 6.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v4...v6)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-04 03:08:14 +01:00
dependabot[bot] c6ec1cb64f
Changed: Bump actions/checkout from 4 to 6 (#4859)
Bumps [actions/checkout](https://github.com/actions/checkout) from 4 to 6.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v4...v6)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Fredrik Fornwall <fredrik@fornwall.net>
2026-01-04 03:06:03 +01:00
Fredrik Fornwall 382c9708b3 Fixed: Update gradle wrapper validation in CI
Replace `gradle/wrapper-validation-action@v3` with
`gradle/actions/wrapper-validation@5` which should fix the error seen
e.g. [here](https://github.com/termux/termux-app/actions/runs/20685857619/job/59386383274):

> Error: The action gradle/actions/wrapper-validation@v3.5.0 is not allowed in termux/termux-app because all actions must be from a repository owned by termux, created by GitHub, or match one of the patterns: gradle/actions/dependency-submission@*, gradle/wrapper-validation-action@v*.
2026-01-04 02:55:26 +01:00
dependabot[bot] edd44d2ce9 Changed: Bump actions/setup-java from 4 to 5
Bumps [actions/setup-java](https://github.com/actions/setup-java) from 4 to 5.
- [Release notes](https://github.com/actions/setup-java/releases)
- [Commits](https://github.com/actions/setup-java/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/setup-java
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-04 02:42:55 +01:00
dependabot[bot] 4183ffa122 Changed: Bump gradle/actions from 4 to 5
Bumps [gradle/actions](https://github.com/gradle/actions) from 4 to 5.
- [Release notes](https://github.com/gradle/actions/releases)
- [Commits](https://github.com/gradle/actions/compare/v4...v5)

---
updated-dependencies:
- dependency-name: gradle/actions
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-04 02:42:31 +01:00
agnostic-apollo 8aca6dbbf4
Added: Add Warp sponsors logo
- https://www.warp.dev

The logo is sourced from 640dffd347/Github/Sponsor/Warp-Github-LG-03.png
2025-09-26 23:04:22 +05:00
agnostic-apollo 1812a405ee
Added: Add Clouflare funders logo
- https://www.cloudflare.com
- https://packages-cf.termux.dev

Clouflare has served around 36TB (32TB cached) data, 39M requests, 1M unique visitors in last 30 days for our https://termux.dev domain, and has potentially served 100s to 1000s of TBs of data over the years for free for Termux, primarily from the https://packages-cf.termux.dev `apt` packages repo, which is a cloudflare backed variant of our primary repo https://packages.termux.dev.

The `cloudflare.png` logo is sourced from www.cloudflare.com/press-kit
2025-09-26 23:04:22 +05:00
agnostic-apollo 338fb66e5c
Added: Add NLnet NGI Mobifree sponsors logo
- https://nlnet.nl/mobifree
- https://nlnet.nl/news/2024/20241111-NGI-Mobifree-grants.html
- https://termux.dev/en/posts/general/2024/11/11/termux-selected-for-nlnet-ngi-mobifree-grant.html

The `nlnet-ngi-mobifree.png` logo is sourced from https://nlnet.nl/logo
2025-09-25 00:56:11 +05:00
agnostic-apollo f852dca0ef
Added: Add GitHub Secure Open Source Fund sponsors logo
- https://resources.github.com/github-secure-open-source-fund
- https://github.blog/open-source/maintainers/securing-the-supply-chain-at-scale-starting-with-71-important-open-source-projects
- https://termux.dev/en/posts/general/2025/08/11/termux-selected-for-github-secure-open-source-fund-session-2.html

The `github.png` logo is sourced from https://github.com/logos
2025-09-25 00:56:05 +05:00
agnostic-apollo 8174a995ae
Added: Add GitHub Accelerator sponsors logo
- https://github.com/accelerator
- https://github.blog/2023-04-12-github-accelerator-our-first-cohort-and-whats-next

The `github.png` logo is sourced from https://github.com/logos
2025-09-25 00:56:05 +05:00
agnostic-apollo 7bceab88e2
Added: Add `SECURITY.md` 2025-06-25 21:10:52 +05:00
agnostic-apollo 2c1bd650b0
Added: Enable workflow dispatch trigger for Automatic Dependency Submission workflow 2025-06-20 13:30:51 +05:00
agnostic-apollo 4a9ad910dd
Added: Add Automatic Dependency Submission for SBOM
- https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/configuring-automatic-dependency-submission-for-your-repository#gradle-projects
- https://github.com/actions/gradle-build-tools-actions#the-dependency-submission-action
2025-06-17 10:17:44 +05:00
agnostic-apollo 9d2ac14557
Fixed: Use `ndkVersion` specified in project properties or `$JITPACK_NDK_VERSION` env variable for `termux-shared` library 2025-05-30 12:06:45 +05:00
agnostic-apollo c6e2ca7fde
Changed(README): Set latest version to 0.118.3 2025-05-23 15:01:53 +05:00
agnostic-apollo da3a0ac4e2
Fixed: Add explicit `serialVersionUID` to `Serializable` classes like `ReportInfo` and `TextIOInfo`
Reading `ReportInfo` with `Bundle.getSerializable()` by `ReportActivity` is triggering exception when default algorithm is used for `serialVersionUID` in Termux:API plugin app when error notification created in `ResultReturner.returnData()` by `TermuxPluginUtils.sendPluginCommandErrorNotification()` is clicked.

```
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.termux/com.termux.shared.activities.ReportActivity}: android.os.BadParcelableException: Parcelable encountered IOException reading a Serializable object (name = com.termux.shared.models.ReportInfo)
	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4280)
	at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4467)
	at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:222)
	at android.app.servertransaction.TransactionExecutor.executeNonLifecycleItem(TransactionExecutor.java:133)
	at android.app.servertransaction.TransactionExecutor.executeTransactionItems(TransactionExecutor.java:103)
	at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:80)
	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2823)
	at android.os.Handler.dispatchMessage(Handler.java:110)
	at android.os.Looper.loopOnce(Looper.java:248)
	at android.os.Looper.loop(Looper.java:338)
	at android.app.ActivityThread.main(ActivityThread.java:9067)
	at java.lang.reflect.Method.invoke(Native Method)
	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:593)
	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:932)
Caused by: android.os.BadParcelableException: Parcelable encountered IOException reading a Serializable object (name = com.termux.shared.models.ReportInfo)
	at android.os.Parcel.readSerializableInternal(Parcel.java:5520)
	at android.os.Parcel.readValue(Parcel.java:5038)
	at android.os.Parcel.readValue(Parcel.java:4702)
	at android.os.Parcel.-$$Nest$mreadValue(Unknown Source:0)
	at android.os.Parcel$LazyValue.apply(Parcel.java:4811)
	at android.os.Parcel$LazyValue.apply(Parcel.java:4764)
	at android.os.BaseBundle.unwrapLazyValueFromMapLocked(BaseBundle.java:446)
	at android.os.BaseBundle.getValueAt(BaseBundle.java:426)
	at android.os.BaseBundle.getValue(BaseBundle.java:397)
	at android.os.BaseBundle.getValue(BaseBundle.java:380)
	at android.os.BaseBundle.getValue(BaseBundle.java:373)
	at android.os.BaseBundle.getSerializable(BaseBundle.java:1522)
	at android.os.Bundle.getSerializable(Bundle.java:1339)
	at com.termux.shared.activities.ReportActivity.updateUI(ReportActivity.java:140)
	at com.termux.shared.activities.ReportActivity.onCreate(ReportActivity.java:93)
	at android.app.Activity.performCreate(Activity.java:9155)
	at android.app.Activity.performCreate(Activity.java:9133)
	at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1521)
	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4262)
	... 13 more
Caused by: java.io.InvalidClassException: com.termux.shared.models.ReportInfo; local class incompatible: stream classdesc serialVersionUID = -5165426368218339031, local class serialVersionUID = 1
	at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:652)
	at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1743)
	at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1624)
	at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1902)
	at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1442)
	at java.io.ObjectInputStream.readObject(ObjectInputStream.java:430)
	at android.os.Parcel.readSerializableInternal(Parcel.java:5507)
	... 31 more

```

If using release APK with obfuscation enabled, then following exception will be triggered.

```
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.termux/com.termux.shared.activities.ReportActivity}: android.os.BadParcelableException: Parcelable encountered ClassNotFoundException reading a Serializable object (name = I0.a)
	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3864)
	at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4006)
	at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:111)
	at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
	at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2462)
	at android.os.Handler.dispatchMessage(Handler.java:106)
	at android.os.Looper.loopOnce(Looper.java:240)
	at android.os.Looper.loop(Looper.java:351)
	at android.app.ActivityThread.main(ActivityThread.java:8377)
	at java.lang.reflect.Method.invoke(Native Method)
	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:584)
	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1013)
Caused by: android.os.BadParcelableException: Parcelable encountered ClassNotFoundException reading a Serializable object (name = I0.a)
	at android.os.Parcel.readSerializableInternal(Parcel.java:5113)
	at android.os.Parcel.readValue(Parcel.java:4655)
	at android.os.Parcel.readValue(Parcel.java:4363)
	at android.os.Parcel.-$$Nest$mreadValue(Unknown Source:0)
	at android.os.Parcel$LazyValue.apply(Parcel.java:4461)
	at android.os.Parcel$LazyValue.apply(Parcel.java:4420)
	at android.os.BaseBundle.getValueAt(BaseBundle.java:394)
	at android.os.BaseBundle.getValue(BaseBundle.java:374)
	at android.os.BaseBundle.getValue(BaseBundle.java:357)
	at android.os.BaseBundle.getValue(BaseBundle.java:350)
	at android.os.BaseBundle.getSerializable(BaseBundle.java:1451)
	at android.os.Bundle.getSerializable(Bundle.java:1144)
	at com.termux.shared.activities.ReportActivity.updateUI(ReportActivity.java:136)
	at com.termux.shared.activities.ReportActivity.onCreate(ReportActivity.java:89)
	at android.app.Activity.performCreate(Activity.java:8397)
	at android.app.Activity.performCreate(Activity.java:8370)
	at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1403)
	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3837)
	... 12 more
Caused by: java.lang.ClassNotFoundException: I0.a
	at java.lang.Class.classForName(Native Method)
	at java.lang.Class.forName(Class.java:536)
	at android.os.Parcel$2.resolveClass(Parcel.java:5090)
	at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1733)
	at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1624)
	at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1902)
	at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1442)
	at java.io.ObjectInputStream.readObject(ObjectInputStream.java:430)
	at android.os.Parcel.readSerializableInternal(Parcel.java:5096)
	... 29 more
Caused by: java.lang.ClassNotFoundException: I0.a
	... 38 more
```

Related issue https://github.com/termux/termux-api/issues/762
2025-05-23 02:27:29 +05:00
Wang Han 4de0caac5b Changed|Fixed: Bump `org.lsposed.hiddenapibypass:hiddenapibypass` to `6.1` to fix crash on Android 16 QPR1
```
Build fingerprint: 'google/shiba_beta/shiba:16/BP31.250502.008/13497110:user/release-keys'
Revision: 'MP1.0'
ABI: 'arm64'
Executable: /system/bin/app_process64
Cmdline: com.termux
pid: 22617, tid: 22617, name: com.termux  >>> com.termux <<<
uid: 10323
tagged_addr_ctrl: 0000000000000001 (PR_TAGGED_ADDR_ENABLE)
pac_enabled_keys: 000000000000000f (PR_PAC_APIAKEY, PR_PAC_APIBKEY, PR_PAC_APDAKEY, PR_PAC_APDBKEY)
esr: 0000000092000006 (Data Abort Exception 0x24)
signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x000000000000000c
Cause: null pointer dereference
    x0  0000000070b6f798  x1  0000000002159228  x2  000000000000000c  x3  00000000ebad6073
    x4  00000000ebad6074  x5  00000000ebad6075  x6  00000000ebad6076  x7  00000000ebad6077
    x8  00000000ebad6078  x9  00000000ebad6079  x10 00000000ebad607a  x11 00000000ebad607b
    x12 00000000ebad607c  x13 00000000ebad607d  x14 00000000ebad607e  x15 00000000ebad607f
    x16 0000007feda203f0  x17 0000007976776a9c  x18 0000007cd0e44000  x19 b400007b850b8be0
    x20 0000000000000000  x21 b400007b850b8ca0  x22 0000000000000000  x23 00000000021592b8
    x24 000000006413b378  x25 0000000070b99ee0  x26 0000000070b9fc78  x27 0000000000000000
    x28 0000000000000053  x29 0000000070b99ee0
    lr  0000007976776a98  sp  0000007feda203f0  pc  0000007976776b0c  pst 0000000080001000
    esr 0000000092000006
26 total frames
backtrace:
      #00 pc 00000000000c8b0c  /data/app/~~p_sHRwZKj3QVf_xeRMrR3g==/com.termux-rodTRD4IY6G2qtCPCrHfhw==/oat/arm64/base.odex (org.lsposed.hiddenapibypass.HiddenApiBypass.getDeclaredMethods+780)
      #01 pc 00000000000c8dc4  /data/app/~~p_sHRwZKj3QVf_xeRMrR3g==/com.termux-rodTRD4IY6G2qtCPCrHfhw==/oat/arm64/base.odex (org.lsposed.hiddenapibypass.HiddenApiBypass.setHiddenApiExemptions+68)
      #02 pc 00000000000ae560  /data/app/~~p_sHRwZKj3QVf_xeRMrR3g==/com.termux-rodTRD4IY6G2qtCPCrHfhw==/oat/arm64/base.odex (com.termux.shared.reflection.ReflectionUtils.bypassHiddenAPIReflectionRestrictions+448)
      #03 pc 00000000000a342c  /data/app/~~p_sHRwZKj3QVf_xeRMrR3g==/com.termux-rodTRD4IY6G2qtCPCrHfhw==/oat/arm64/base.odex (com.termux.shared.android.SELinuxUtils.getContext+108)
      #04 pc 00000000000c0b60  /data/app/~~p_sHRwZKj3QVf_xeRMrR3g==/com.termux-rodTRD4IY6G2qtCPCrHfhw==/oat/arm64/base.odex (com.termux.shared.termux.shell.command.environment.TermuxAppShellEnvironment.setTermuxAppEnvironment+3216)
      #05 pc 000000000009eafc  /data/app/~~p_sHRwZKj3QVf_xeRMrR3g==/com.termux-rodTRD4IY6G2qtCPCrHfhw==/oat/arm64/base.odex (com.termux.app.TermuxApplication.onCreate+1596)
      ...
      #22 pc 0000000000105c98  /system/lib64/libandroid_runtime.so (_JNIEnv::CallStaticVoidMethod(_jclass*, _jmethodID*, ...)+104) (BuildId: ea93df5e792bbd2e0cbb71b2a7599aaa)
      #23 pc 000000000013121c  /system/lib64/libandroid_runtime.so (android::AndroidRuntime::start(char const*, android::Vector<android::String8> const&, bool)+908) (BuildId: ea93df5e792bbd2e0cbb71b2a7599aaa)
      #24 pc 000000000000459c  /system/bin/app_process64 (main+1212) (BuildId: a237cfae6965d7f0b950e5955c73432c)
      #25 pc 000000000006bb88  /apex/com.android.runtime/lib64/bionic/libc.so (__libc_init+120) (BuildId: eecb0fc2ec8128ec92c091c0160586d1)
```

Related commit https://github.com/LSPosed/AndroidHiddenApiBypass/commit/9efadf06
Related commit https://android-review.googlesource.com/c/platform/libcore/+/3380841
Related commit https://cs.android.com/android/_/android/platform/libcore/+/0dc31afe

Closes #4556
2025-05-23 02:26:47 +05:00
agnostic-apollo bc321d0a7c
Changed(README): Set latest version to 0.118.2 2025-03-29 12:15:10 +05:00
agnostic-apollo 9ee1c9d5ad
Fixed: Use `openjdk11` for jitpack builds of termux libraries
`Unrecognized option: --add-exports=java.base/sun.nio.ch=ALL-UNNAMED`

Related commit 52da00e5
2025-03-29 10:34:17 +05:00
Johannes Altmanninger a988383e01 Fixed: Fully consume unknown CSI sequences containing unsupported parameter and intermediate bytes
Standard ECMA-48: Control Functions for Coded Character Sets specifies the format of CSI commands.
- https://en.wikipedia.org/wiki/ANSI_escape_code#Control_Sequence_Introducer_commands
- https://invisible-island.net/xterm/ecma-48-parameter-format.html#section5.4

Previously unsupported bytes would be echoed to the terminal.

```shell
$ printf '\x1b[=u' # PF
u
$ printf '\x1b[=5u' # PPF
5u
$ printf '\x1b[=5!u' # PPIF
5!u
$ printf '\x1b[=5!%u' # PPIIF
5!0
$ printf '\x1b[=?5!%u' # PPPIIF
?5!0
```

This fixes a problem with fish shell 4.0.0 which uses that sequence.

Closes #4338

Co-authored-by: @krobelus <aclopte@gmail.com>
Co-authored-by: @agnostic-apollo  <agnosticapollo@gmail.com>
2025-03-15 11:26:11 +05:00
agnostic-apollo d2cd6ac2e5
Changed|Fixed: Bump `org.lsposed.hiddenapibypass:hiddenapibypass` to `5.0` to fix crash on Android 16
```
Build fingerprint: 'google/sdk_gphone64_x86_64/emu64xa:Baklava/BP22.250103.008/12932282:userdebug/dev-keys'
Revision: '0'
ABI: 'x86_64'
Timestamp: 2025-01-25
Process uptime: 1s
Cmdline: com.termux
pid: 4700, tid: 4700, name: com.termux  >>> com.termux <<<
uid: 10212
signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x000000000000000c
Cause: null pointer dereference
    rax 0000000000000000  rbx 000071ad67c247b0  rcx 000000000000000c  rdx 000071abc520c888
    r8  00005f2000006018  r9  0000607c00006004  r10 000071abc423d68c  r11 000071abc4cca7c0
    r12 00007ffc65da8240  r13 000071ad67c24858  r14 00007ffc65da85d8  r15 000071ad67c247b0
    rdi 000071ad87c26110  rsi 00007ffc65da8148
    rbp 00007ffc65da8050  rsp 00007ffc65da8040  rip 000071abc4cca817
124 total frames
backtrace:
      #00 pc 00000000008ca817  /apex/com.android.art/lib64/libart.so (art::Unsafe_getObject(_JNIEnv*, _jobject*, _jobject*, long) (.__uniq.306581074569039686346581217366878976736)+87) (BuildId: 99c067c739342eb9769974bbb229d3b3)
      #01 pc 000000000022c80b  /apex/com.android.art/lib64/libart.so (art_quick_generic_jni_trampoline+219) (BuildId: 99c067c739342eb9769974bbb229d3b3)
      #02 pc 0000000000211dd4  /apex/com.android.art/lib64/libart.so (art_quick_invoke_stub+756) (BuildId: 99c067c739342eb9769974bbb229d3b3)
      #03 pc 0000000000556155  /apex/com.android.art/lib64/libart.so (art::ArtMethod::Invoke(art::Thread*, unsigned int*, unsigned int, art::JValue*, char const*)+181) (BuildId: 99c067c739342eb9769974bbb229d3b3)
      #04 pc 00000000006dd182  /apex/com.android.art/lib64/libart.so (bool art::interpreter::DoCall<false>(art::ArtMethod*, art::Thread*, art::ShadowFrame&, art::Instruction const*, unsigned short, bool, art::JValue*)+2434) (BuildId: 99c067c739342eb9769974bbb229d3b3)
      #05 pc 0000000000233564  /apex/com.android.art/lib64/libart.so (void art::interpreter::ExecuteSwitchImplCpp<false>(art::interpreter::SwitchImplContext*)+10804) (BuildId: 99c067c739342eb9769974bbb229d3b3)
      #06 pc 000000000022eb25  /apex/com.android.art/lib64/libart.so (ExecuteSwitchImplAsm+5) (BuildId: 99c067c739342eb9769974bbb229d3b3)
      #07 pc 0000000000080eb4  <anonymous:71ab3d335000> (org.lsposed.hiddenapibypass.HiddenApiBypass.getDeclaredMethods+0)
      ...
      #13 pc 0000000000080dd0  <anonymous:71ab3d335000> (org.lsposed.hiddenapibypass.HiddenApiBypass.setHiddenApiExemptions+0)
      ...
      #19 pc 0000000000080cf8  <anonymous:71ab3d335000> (org.lsposed.hiddenapibypass.HiddenApiBypass.addHiddenApiExemptions+0)
      ...
      #25 pc 0000000000005ab4  <anonymous:71ae82992000> (com.termux.shared.reflection.ReflectionUtils.bypassHiddenAPIReflectionRestrictions+0)
      ...
      #31 pc 0000000000004738  <anonymous:71ae86607000> (com.termux.shared.android.SELinuxUtils.getContext+0)
      ...
      #37 pc 0000000000005b48  <anonymous:71ae825d8000> (com.termux.shared.termux.shell.command.environment.TermuxAppShellEnvironment.setTermuxAppEnvironment+0)
      ...
      #43 pc 000000000000603c  <anonymous:71ae825d8000> (com.termux.shared.termux.shell.command.environment.TermuxShellEnvironment.init+0)
      ...
      #49 pc 0000000000006a68  <anonymous:71ae7e1c2000> (com.termux.app.TermuxApplication.onCreate+0)
```

Related commit 40b4cafa47
Related issue https://github.com/LSPosed/AndroidHiddenApiBypass/issues/52

Closes #4368
2025-01-25 02:30:20 +05:00
agnostic-apollo 52da00e5c2
Fixed: Fix gradle build error if using jdk `17`
`Unable to make field private final java.lang.String java.io.File.path accessible: module java.base does not "opens java.io" to unnamed module`
2025-01-13 03:41:34 +05:00
agnostic-apollo b0e1dbc3da
Fixed: Use `TERMUX_STYLING_APP` for `TERMUX_STYLING_ACTIVITY_NAME` as per 078eea2b 2025-01-13 01:50:45 +05:00
agnostic-apollo 078eea2b74
Added: Rename app classes in `TermuxConstants` with `_APP` suffix added and add `TERMUX_*_MAIN_ACTIVITY_NAME` and `TERMUX_*_LAUNCHER_ACTIVITY_NAME` constants to each app class 2025-01-13 01:30:06 +05:00
agnostic-apollo fb01127ff2
Fixed: Fix tests added in b84dc703 2024-10-28 12:45:39 +05:00
Jason Yu b84dc703e8 Added: Add empty and null strings tests for invalid urls to `FileReceiverActivityTest` 2024-10-28 12:34:31 +05:00
Fredrik Fornwall 8be53336c3 Fixed: Implement colon separated CSI parameters 2024-10-02 17:27:08 +02:00
Evgeny Zhabotinsky d90e3fbca1 Fixed: Make ScrollDown escape respect margins
SD sequence (`${CSI}${N}T`) was scrolling the whole width
 of the terminal instead of just between the margins.
RI sequence (`${ESC}M`, move cursor up 1 line) was doing the same.
Fixed that.

Fixes #2576 where in tmux scrolling one of several
 side-by-side panels down resulted in all visually scrolling.
2024-09-29 23:37:28 +02:00
Tom Kranz 245158ceb9 Added: Basic MIME type recognition in ContentProvider 2024-09-28 01:19:50 +02:00
Matan Ziv-Av 6c00f1fc61 Fixed: Use Canvas.drawTextRun instead of drawText
drawText does (very) basic BiDi, which causes inconsistent behaviour.
This ensures everything is LtR.
2024-09-27 11:27:38 +02:00
Fredrik Fornwall 03142590ff Added: Terminal CSI reporting of window and cell pixel size
Implement the following CSI escape sequences from
https://invisible-island.net/xterm/ctlseqs/ctlseqs.html:

> CSI Ps ; Ps ; Ps t
> [..]
>    Ps = 1 4  ⇒  Report xterm text area size in pixels.
>    Result is CSI  4 ;  height ;  width t
> [..]
>    Ps = 1 6  ⇒  Report xterm character cell size in pixels.
>    Result is CSI  6 ;  height ;  width t

Extracted from changes in https://github.com/termux/termux-app/pull/2973
by @MatanZ and adopted to play well with the just merged #3098 (.ws_xpixel
and .ws_ypixel values in winsize).
2024-09-26 21:53:52 +02:00
Artem Chepurnyi 4443b657bf Fixed: Mark view as important for AutoFill before requesting an AutoFill
Co-authored-by: @AChep <mail@artemchep.com>
Co-authored-by: @agnostic-apollo  <agnosticapollo@gmail.com>
2024-09-26 20:34:18 +05:00
Dvd-Znf a8a69c6d80 Update latest version in README.md to v0.118.1 2024-09-26 16:55:56 +02:00
Krunal Patel 438cd73fff Added|Changed: Fill `.ws_xpixel` and `.ws_ypixel` in `winsize`
This allows to get terminal size in pixel using `TIOCGWINSZ` ioctl.
Set `.ws_xpixel` using `columns * cell_width` and set `.ws_ypixel` using `rows * cell_height`.
Cell width and height is font width and line spacing, respectively.
2024-09-26 15:09:09 +02:00
Fredrik Fornwall 36d811ea7d Fixed: Parse (but ignore for now) terminal APC sequences 2024-09-18 22:28:16 +02:00
agnostic-apollo c2d57f2ed8
Added|Fixed: Do not show AutoFill UI on Termux start and add support for usernames
- The AutoFill type and hints are no longer hardcoded in `TerminalView` class and `TermuxActivity` layout xml. They are dynamically set to required values before making a manual AutoFill request and reverted back afterwards to default values. The hardcoded value `AUTOFILL_TYPE_TEXT` returned by `getAutofillType()` was causing the AutoFill UI to show on Activity starts, this will return `AUTOFILL_TYPE_NONE` by default now so that AutoFill UI isn't shown automatically.
- The AutoFill importance is no longer hardcoded in `TermuxActivity` layout xml and is returned by `TerminalView` class itself by `getImportantForAutofill()`.
- The AutoFill function in `TermuxActivity` for making a manual AutoFill request is moved to `TerminalView` class. This and moving of hardcoded values to `TerminalView` class mentioned above is done as complete logic of AutoFill should be handled by `TerminalView` class itself and not scattered in various places.
- The Terminal context menu now supports AutoFilling a username. Note that GBoard/Google Password Manager seems to have a bug where it will still show `Pick a saved password` instead of username, even though `AUTOFILL_HINT_USERNAME` is being requested, however it will still AutoFill a username of selected entry correctly.
- Pressing the back button to close the keyboard will also cancel the current manually requested AutoFill request and UI will not show when keyboard is opened again.

Closes #3909
2024-08-27 20:44:05 +05:00
Josh Triplett 661c37501f Make Shift-PgUp and Shift-PgDn scroll by pages rather than lines
In other terminals, such as gnome-terminal, Shift-PgUp and Shift-PgDn
scroll the screen by a full page, rather than a single line. Adjust
termux to match.
2024-08-16 12:18:54 +02:00
Fredrik Fornwall f80b46487d Fixed: Improve handling of empty ';' SGR sequences
Currently the Termux terminal emulator prints "HI" in red with:

```sh
printf "\e[31;m HI \e[0m"
```

This is not how other terminals (tested on xterm, gnome-terminal,
alacritty and the mac built in terminal) handle it, since they parse
""\e[31;m" as "\e[31;0m", where the "0" resets the colors.

This change aligns with other terminals, as well as improves performance
by avoiding allocating a new int[] array for each byte processed by
`parseArg()`, and most importantly simplifies things by removing the
`mIsCSIStart` and `mLastCSIArg` state, preparing for supporting ':'
separated sub parameters such as used in
https://sw.kovidgoyal.net/kitty/underlines/
2024-08-13 19:20:38 +02:00
Fredrik Fornwall a5de3d3a2b Fixed: Use current bg color when scrolling with horizontal margins
Fixes https://github.com/termux/termux-packages/issues/12556

Issue was also reported here:
https://www.reddit.com/r/termux/comments/1df1dii/how_can_i_fix_this_annoying_screenfilling_thing/
2024-08-13 19:14:53 +02:00
agnostic-apollo 57e4ef456b
Added: Add support for GitHub action builds for `github-releases/**` branches 2024-06-18 02:08:34 +05:00
Fredrik Fornwall d90be9cd50 Changed: Update information regarding Google Play in README 2024-06-16 01:26:48 +02:00
agnostic-apollo 062c9771a9
Added: Request `SET_ALARM` permission to allow broadcasting an intent to set an alarm or timer in an alarm clock app
- https://developer.android.com/reference/android/Manifest.permission#SET_ALARM
- https://developer.android.com/reference/android/provider/AlarmClock

Closes #3990
2024-06-05 19:13:57 +05:00
dependabot[bot] 2f40df91e5 Changed: Bump gradle/wrapper-validation-action from 2 to 3
Bumps [gradle/wrapper-validation-action](https://github.com/gradle/wrapper-validation-action) from 2 to 3.
- [Release notes](https://github.com/gradle/wrapper-validation-action/releases)
- [Commits](https://github.com/gradle/wrapper-validation-action/compare/v2...v3)

---
updated-dependencies:
- dependency-name: gradle/wrapper-validation-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-18 21:12:09 +05:00
agnostic-apollo 755b752a95
Reverted: Revert "ci: use termux/upload-release-actions to attach debug builds to new releases"
This reverts commit 2ac7fd1e56.

Do not use `upload-release-action` for uploading artifacts and generating checksum and instead keep using standard `sha256sum` and internal github tools. `upload-release-action` also generates checksum in the wrong format, check https://github.com/termux/termux-app/pull/3241#discussion_r1106019790.
2024-04-16 12:34:31 +05:00
agnostic-apollo 67f4891580 Fixed: Limit max combining characters in TerminalRow to 15 characters to prevent buffer overflows
The exception below causing app crash happens because of malicious input where combining characters keep getting added to same column of the row and this increases the size of `mSpaceUsed` and `mText`, eventually causing a buffer overflow of `mSpaceUsed`, which is limited to max `32767` value as per java `short` limit, but the limit itself isn't the issue, but an endless number of combining characters being added. Check `MAX_COMBINING_CHARACTERS_PER_COLUMN` field javadocs for why the limit `15` was chosen.

```
curl -o matroska.js https://kimapr.net/lappy/matroska.js
cat matroska.js
```

The `charCount` below refers to value of `Character.charCount(codePoint)`, like before `oldCharactersUsedForColumn` is appended to `newCharactersUsedForColumn`.

```
TerminalRow: codePoint=112, mColumns=98, mText=637, columnToSet=18, mSpaceUsed=590, javaCharDifference=0, oldStartOfColumnIndex=510, oldCharactersUsedForColumn=1, newCharactersUsedForColumn=1, oldNextColumnIndex=511, newNextColumnIndex=511, charCount=1, oldCodePointDisplayWidth=1, newCodePointDisplayWidth=1
TerminalRow: codePoint=40, mColumns=98, mText=637, columnToSet=19, mSpaceUsed=590, javaCharDifference=0, oldStartOfColumnIndex=511, oldCharactersUsedForColumn=1, newCharactersUsedForColumn=1, oldNextColumnIndex=512, newNextColumnIndex=512, charCount=1, oldCodePointDisplayWidth=1, newCodePointDisplayWidth=1
TerminalRow: codePoint=40, mColumns=98, mText=637, columnToSet=20, mSpaceUsed=590, javaCharDifference=0, oldStartOfColumnIndex=512, oldCharactersUsedForColumn=1, newCharactersUsedForColumn=1, oldNextColumnIndex=513, newNextColumnIndex=513, charCount=1, oldCodePointDisplayWidth=1, newCodePointDisplayWidth=1
TerminalRow: codePoint=101, mColumns=98, mText=637, columnToSet=21, mSpaceUsed=590, javaCharDifference=0, oldStartOfColumnIndex=513, oldCharactersUsedForColumn=1, newCharactersUsedForColumn=1, oldNextColumnIndex=514, newNextColumnIndex=514, charCount=1, oldCodePointDisplayWidth=1, newCodePointDisplayWidth=1
TerminalRow: codePoint=917772, mColumns=98, mText=147, columnToSet=18, mSpaceUsed=98, javaCharDifference=2, oldStartOfColumnIndex=18, oldCharactersUsedForColumn=1, newCharactersUsedForColumn=3, oldNextColumnIndex=19, newNextColumnIndex=21, charCount=2, oldCodePointDisplayWidth=1, newCodePointDisplayWidth=0
I TerminalRow: codePoint=65024, mColumns=98, mText=147, columnToSet=18, mSpaceUsed=100, javaCharDifference=1, oldStartOfColumnIndex=18, oldCharactersUsedForColumn=3, newCharactersUsedForColumn=4, oldNextColumnIndex=21, newNextColumnIndex=22, charCount=1, oldCodePointDisplayWidth=1, newCodePointDisplayWidth=0
TerminalRow: codePoint=917772, mColumns=98, mText=147, columnToSet=18, mSpaceUsed=101, javaCharDifference=2, oldStartOfColumnIndex=18, oldCharactersUsedForColumn=4, newCharactersUsedForColumn=6, oldNextColumnIndex=22, newNextColumnIndex=24, charCount=2, oldCodePointDisplayWidth=1, newCodePointDisplayWidth=0
...
TerminalRow: codePoint=917959, mColumns=98, mText=32781, columnToSet=18, mSpaceUsed=32763, javaCharDifference=2, oldStartOfColumnIndex=18, oldCharactersUsedForColumn=32666, newCharactersUsedForColumn=32668, oldNextColumnIndex=32684, newNextColumnIndex=32686, charCount=2, oldCodePointDisplayWidth=1, newCodePointDisplayWidth=0
TerminalRow: codePoint=917939, mColumns=98, mText=32781, columnToSet=18, mSpaceUsed=32765, javaCharDifference=2, oldStartOfColumnIndex=18, oldCharactersUsedForColumn=32668, newCharactersUsedForColumn=32670, oldNextColumnIndex=32686, newNextColumnIndex=32688, charCount=2, oldCodePointDisplayWidth=1, newCodePointDisplayWidth=0
TerminalRow: codePoint=917961, mColumns=98, mText=32781, columnToSet=18, mSpaceUsed=32767, javaCharDifference=2, oldStartOfColumnIndex=18, oldCharactersUsedForColumn=32670, newCharactersUsedForColumn=32672, oldNextColumnIndex=32688, newNextColumnIndex=32690, charCount=2, oldCodePointDisplayWidth=1, newCodePointDisplayWidth=0
TerminalRow: codePoint=917804, mColumns=98, mText=32781, columnToSet=18, mSpaceUsed=-32767, javaCharDifference=2, oldStartOfColumnIndex=18, oldCharactersUsedForColumn=1, newCharactersUsedForColumn=3, oldNextColumnIndex=19, newNextColumnIndex=21, charCount=2, oldCodePointDisplayWidth=1, newCodePointDisplayWidth=0
```

```
java.lang.ArrayIndexOutOfBoundsException: src.length=32781 srcPos=19 dst.length=32781 dstPos=21 length=-32786
	at java.lang.System.arraycopy(System.java:469)
	at com.termux.terminal.TerminalRow.setChar(TerminalRow.java:196)
	at com.termux.terminal.TerminalBuffer.setChar(TerminalBuffer.java:455)
	at com.termux.terminal.TerminalEmulator.emitCodePoint(TerminalEmulator.java:2380)
	at com.termux.terminal.TerminalEmulator.processCodePoint(TerminalEmulator.java:624)
	at com.termux.terminal.TerminalEmulator.processByte(TerminalEmulator.java:520)
	at com.termux.terminal.TerminalEmulator.append(TerminalEmulator.java:487)
	at com.termux.terminal.TerminalSession$MainThreadHandler.handleMessage(TerminalSession.java:358)
	at android.os.Handler.dispatchMessage(Handler.java:106)
	at android.os.Looper.loop(Looper.java:223)
	at android.app.ActivityThread.main(ActivityThread.java:7664)
	at java.lang.reflect.Method.invoke(Native Method)
	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
```

See also following links for history of related changes to `TerminalRow` for combining characters. Note that jackpal terminal does not crash for above, which termux-app is based on, but changes were done by fornwall in initial commit of termux-app to change the behaviour, hence the crash, but he added the `FIXME: Put a limit of combining characters` comment as a note to solve the current issue in future, which is now.

- 9a47042620
- https://github.com/jackpal/Android-Terminal-Emulator/pull/338
- a18ee58f7a (diff-f84d215b18106c037e01986a3968fa54b74691174a78fcc99493f745d3805be5)

Closes #3839
2024-04-07 15:52:48 +05:00
dependabot[bot] 7b19cd2f5a Changed: Bump termux/upload-release-action from 4.1.0 to 4.2.0
Bumps [termux/upload-release-action](https://github.com/termux/upload-release-action) from 4.1.0 to 4.2.0.
- [Release notes](https://github.com/termux/upload-release-action/releases)
- [Changelog](https://github.com/termux/upload-release-action/blob/master/CHANGELOG.md)
- [Commits](https://github.com/termux/upload-release-action/compare/v4.1.0...v4.2.0)

---
updated-dependencies:
- dependency-name: termux/upload-release-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-02 01:05:37 +05:00
dependabot[bot] 882da34fcd Changed: Bump gradle/wrapper-validation-action from 1 to 2
Bumps [gradle/wrapper-validation-action](https://github.com/gradle/wrapper-validation-action) from 1 to 2.
- [Release notes](https://github.com/gradle/wrapper-validation-action/releases)
- [Commits](https://github.com/gradle/wrapper-validation-action/compare/v1...v2)

---
updated-dependencies:
- dependency-name: gradle/wrapper-validation-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-02 00:34:43 +05:00
dependabot[bot] 8e3a8980a8
Changed: Bump actions/upload-artifact from 3 to 4 (#3735) 2024-01-01 15:19:33 +00:00
dependabot[bot] e4385832b7
Changed: Bump actions/download-artifact from 3 to 4 (#3736)
l
2024-01-01 15:19:09 +00:00
agnostic-apollo 3b5018b4c7
Changed: Update `Twitter` to `X (Twitter)` in README
Co-authored-by: @BandhiyaHardik <bandhiya.hardik1905@gmail.com>
Co-authored-by: @agnostic-apollo  <agnosticapollo@gmail.com>

Related pull #3681
2023-11-02 09:20:21 +05:00
agnostic-apollo c84d4804c8
Changed!: Update commit messages guidelines in README to be more clear and remove `Docs` as a valid type
The `Docs` refer to "something" that is changed, and not the type of change being made. If docs are to be changed in future, it should be added as a scope instead, like `Added(docs): Add some docs` or `Fixed(docs): Fix some docs`.
2023-11-01 17:30:43 +05:00
agnostic-apollo 6727bbecc4
Changed: Put GitHub debug keystore information in README in dropdown 2023-10-19 08:04:45 +05:00
agnostic-apollo e27f9fa979
Changed: Update README with info on how to install termux for android 5 and 6 2023-10-19 08:00:31 +05:00
Fredrik Fornwall e2f0edf4d2
Chore: Add vim swap files to .gitignore 2023-10-08 22:03:27 +02:00
dependabot[bot] c5b69975e1 Changed: Bump actions/checkout from 3 to 4
Bumps [actions/checkout](https://github.com/actions/checkout) from 3 to 4.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-10-07 06:55:28 +05:00
agnostic-apollo cce78cc274
Fixed: Fix dependabot commit format to use convetional commit format
All commit messages will now be prefixed with "Changed: "
2023-10-07 06:46:22 +05:00
Leonid Pliushch 32cd8a9384
Changed: Remove info from README.md that fornwall is inactive and issue #1072 needs extra attention
Fornwall is active again and work is already being done on #1072 for an alternate variant at https://github.com/termux/termux-exec/pull/24 and the other alternate https://github.com/termux/termux-app/issues/2155#issuecomment-1636732850 will be worked on in future.
2023-10-07 06:36:50 +05:00
agnostic-apollo eef5ac43a7
Fixed: Fix headings in README.md 2023-08-22 05:01:47 +05:00
agnostic-apollo 55cdef01e7
Fixed: Allow numbers and hyphens in domain extension for url selector
Closes #3550
2023-08-19 03:59:10 +05:00
agnostic-apollo 7c262b8d99
Fixed: Fix toggle toolbar not working due to accidental comment of function in a56ed577
Closes #3258
2023-08-14 20:45:30 +05:00
agnostic-apollo 06230f95df
Changed: Only show github action builds for pushes to master branch and not of other branches and pull requests 2023-08-10 00:46:44 +05:00
Leonid Pliushch 9d308c2331
update readme
Presence of phantom process killer on Android 12 doesn't mean Termux is
broken. It could be unstable because of abrupt termination of all
processes by signal 9 under certain cases. But this doesn't mean it is
unusable on all devices with Android 12 or higher.

The word "broken" could be too scary for new users.
2023-06-25 22:39:36 +03:00
Leonid Pliushch 11d8e4ff8f
update readme
Clarification why Termux is still not unpublished from Play Store.
2023-05-25 12:42:54 +03:00
agnostic-apollo 66a9495d91 Fixed: Fix `SHIFT+PAGE_UP` and `SHIFT+PAGE_DOWN` behaviour to scroll `1` line of scrollback history instead of scrolling command history or changing pages
This will work for both `SHIFT` extra key and hardware keyboards. The `SHIFT` extra key can be long held to lock it in an enabled state and `PGUP` and `PGDN` keys can be long held to repeat scrolling.

Closes #867
2023-05-21 07:58:35 +05:00
agnostic-apollo 33295decbb Changed: Add `PGUP` and `PGDN` extra keys to repetitive keys so that long holding them triggers page scrolling instead of having to repeatedly press the key to change pages 2023-05-21 07:58:35 +05:00
maheshnikam ba1fb850bf Changed(README.md): Improved some links to Hyperlinks 2023-05-02 07:20:35 +08:00
Kevin Williams 1240c5ca47 Revert "[doc](readme)modified the links in file"
This reverts commit c1dca29076.
2023-05-02 07:20:35 +08:00
maheshnikam c1dca29076 [doc](readme)modified the links in file
improved some links to Hyperlinks.
2023-04-30 20:47:04 +08:00
utzcoz 93eafffb90 Changed: Bump Robolectric to 4.10 2023-04-16 22:43:38 +05:00
utzcoz 9b274f9a0d Changed: Bump robolectric to 4.9.2 2023-03-22 11:18:41 +05:00
Sandelinos b800f1cc81 Added: Add monochrome icon 2023-03-04 21:24:18 +08:00
Yaksh Bariya 2ac7fd1e56
ci: use termux/upload-release-actions to attach debug builds to new releases 2023-02-08 19:15:51 +05:30
Young-Lord c6dce12510 Fix GitHub spelling 2023-01-23 11:13:48 +02:00
Lucy Phipps 2f5a6f7de6
WcWidth.c: fix 2nd typo 2022-12-16 07:01:40 +00:00
Lucy Phipps 82f83a2970
WcWidth.c: fix typo 2022-12-16 06:58:37 +00:00
Lucy Phipps b1c043d540
update WcWidth.java to Unicode 15.0.0 2022-12-16 06:56:27 +00:00
Lucy Phipps cff6cff609
Create dependabot.yml 2022-11-07 01:16:28 +00:00
Frieder Bluemle 29cf9820e1 Fix GitHub spelling 2022-10-27 11:37:17 +03:00
Yaksh Bariya c8a74dc588
feat(KeyHandler): respect modifiers with PgUp and PgDn 2022-10-24 07:58:37 +05:30
daywalk3r666 20dee0e940 Update actions/upload-artifact to v3 2022-10-14 10:02:36 +03:00
Sushrut1101 3516f1979f Update actions/checkout to v3 2022-10-13 10:56:35 +03:00
EduardDurech 5bc3d2db8d Added: Add `KEY_LAST_PENDING_INTENT_REQUEST_CODE` to `TermuxAPIAppSharedPreferences` 2022-10-13 08:48:31 +05:00
agnostic-apollo 3f7a939313 Added: Add support for `Share selected text` of terminal in long hold `MORE` menu so that users don't have to copy and paste to move text between apps 2022-10-04 04:47:58 +05:00
agnostic-apollo 0c14c291b2 Changed: Use `ShareUtils` to copy and paste text and prevent potential `NPE`
The `copyTextToClipboard()` method has been updated to pass clip label when copying text to clipboard and `getTextFromClipboard()` and `getTextStringFromClipboardIfSet()` methods have been added to get current clipboard.
2022-10-04 04:29:15 +05:00
agnostic-apollo 63d035ce39
Changed: Update phantom process links 2022-10-03 15:37:26 +05:00
agnostic-apollo 8c1749ef96 Added|Changed: Add `AppSharedPreferences` to hold `SharedPreferences` of apps and inherit termux app prefrences from it 2022-09-29 02:45:31 +05:00
Leonid Pliushch 6c56073958
readme: add notes about test keystore 2022-09-21 20:01:13 +03:00
Leonid Pliushch 061dc776bd
rename dev_keystore.jks to testkey_untrusted.jks
Hopefully the new name of keystore file would provide to potential user
more info about what it actually is.
2022-09-21 10:30:24 +03:00
agnostic-apollo 211340781b Added: Add multi language i18n support for docs per termux/termux.github.io@f234d089e 2022-07-17 08:48:03 +05:00
agnostic-apollo 605dd6c192 Added: Add check for if Termux has been granted Display Over Apps Permission if starting activities and services with termux-am-socket on Android 10+ 2022-07-06 02:53:36 +05:00
agnostic-apollo 4646aca597 Added: Start termux app docs support at https://termux.dev/docs/apps/termux as per termux/termux.github.io@612fa084 and termux/termux.github.io@f9c8d848 2022-06-21 04:11:23 +05:00
agnostic-apollo f1d411a5ab Fixed: Fix shared terminal transcript joining back lines
Regression of 370ac2bd caused in 5f71e3e7 by the (in)famous @trygveaa
2022-06-19 03:08:28 +05:00
agnostic-apollo 5fc2b4cd4a Added: Add `SCROLL` extra key to toggle auto scrolling of terminal to bottom on terminal text updates and termux activity return
The toggle will apply to each terminal session separately.

Closes #2535
2022-06-18 22:45:48 +05:00
agnostic-apollo a2df7d791a Fixed: Fix bootstrap not installing on app install
Previously, bootstrap was only installed if `$PREFIX` didn't exist, was empty or only had `$PREFIX/tmp`. But now with 03e1d14e, `$PREFIX/etc/termux/termux.env` was also created at app startup before bootstrap check was made, hence it was being assumed that bootstrap was already installed.

Now, bootstrap will be installed even if `$PREFIX/tmp`, `$PREFIX/etc/termux/termux.env.tmp` or `$PREFIX/etc/termux/termux.env` exist but no other files do.

Closes #2844
2022-06-18 05:53:26 +05:00
agnostic-apollo 82b1580312 Fixed: Fix `termux.properties` reload not working if the properties file didn't exist at app startup
Closes #2836
2022-06-15 18:31:29 +05:00
agnostic-apollo e92a6db06b Fixed: Ensure CSI parameter value is not greater than `9999` as per vt510 2022-06-15 05:05:04 +05:00
agnostic-apollo 4c47f4f732 Fixed: Fix CSI parameters parsing like for SGR sequences that start with a `;` or have sequential `;` characters
https://vt100.net/docs/vt510-rm/chapter4.html#S4.3.3

https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

Credits for finding the issue belongs to @Screwtapello

https://github.com/mawww/kakoune/issues/4339#issuecomment-916980723

Closes #2272, Closes mawww/kakoune#4339
2022-06-15 05:05:04 +05:00
agnostic-apollo 26ff978b0f Changed: Use black or white cursor color based on terminal background instead of always white if colors.properties didn't have cursor color set
Credit for algorithm link belong to @Jamie-Landeg-Jones

Closes #2653
2022-06-14 19:13:19 +05:00
agnostic-apollo b80126fd61 Fixed: Catch exceptions if failed to bypass hidden API restrictions
Attempting to bypass restrictions while tests are running will fail due to call to `TermuxApplication.onCreate()` -> `TermuxShellEnvironment.init()` -> `SELinuxUtils.getContext()`
2022-06-14 04:08:03 +05:00
agnostic-apollo 162469f7ce Fixed: Fix message dialog button text not showing in day mode due to white text 2022-06-14 04:05:00 +05:00
agnostic-apollo e75680a884 Changed: Do not re-set component state if current state equals new state in `PackageUtils.setComponentState()` 2022-06-14 04:04:09 +05:00
agnostic-apollo af6ac30bb1 Added: Allow users to disable termux file view and share receivers
The user can add `disable-file-share-receiver=true` entry to `termux.properties` file to disable termux from showing in Android file `Share With` apps list.
The user can add `disable-file-view-receiver=true` entry to `termux.properties` file to disable termux from showing in Android file `Open With` apps list.

The default value is `false`. Restarting termux app or running `termux-reload-settings` command will update the behaviour instantaneously if changed.

Closes #2549
2022-06-14 04:03:29 +05:00
agnostic-apollo 79d799a99d Fixed: Fix `ExecutionCommand.pid` not being set for first and background terminal sessions since `TermuxTerminalSessionClientBase` was still being used instead of `TermuxTerminalSessionActivityClient`
This commit adds onto 841c41bf and implements the `setTerminalShellPid()` interface method in `TermuxTerminalSessionServiceClient` so that `pid` is set properly for all cases.
2022-06-13 16:11:13 +05:00
agnostic-apollo 841c41bf37 Added|Changed: Added `TermuxTerminalSessionServiceClient` and renamed `TermuxTerminalSessionClient` to `TermuxTerminalSessionActivityClient`
Addition of `TermuxTerminalSessionServiceClient` is required so that interface methods that `TermuxService` can handle without `TermuxActivity` should implemented instead of relying on base implementation of `TermuxTerminalSessionClientBase`.
2022-06-13 16:07:04 +05:00
agnostic-apollo c2ddc23ae5 Added: Add `MAX_PHANTOM_PROCESSES` and `DEVICE_CONFIG_SYNC_DISABLED` value to device info output like shown in Termux About page
Related commit b6963035
2022-06-12 02:50:38 +05:00
agnostic-apollo b69630355a Added: Add `PhantomProcessUtils` to get phantom processes related settings values
- `settings_enable_monitor_phantom_procs` feature flag value can be received with a call to `getFeatureFlagMonitorPhantomProcsValueString()`. Likely only available on Android `12L+`.

- `max_phantom_processes` value from `dumpsys activity settings` output can be received with a call to `getActivityManagerMaxPhantomProcesses()`. Requires granting Termux `DUMP` and `PACKAGE_USAGE_STATS` permission. Can be granted with `adb shell "pm grant com.termux android.permission.PACKAGE_USAGE_STATS; pm grant com.termux android.permission.DUMP"` and revoked with `adb shell "pm revoke com.termux android.permission.PACKAGE_USAGE_STATS; pm revoke com.termux android.permission.DUMP"`.

- `device_config_sync_disabled` settings global namespace value can be received with a call to `getSettingsGlobalDeviceConfigSyncDisabled()`.
2022-06-12 02:48:36 +05:00
agnostic-apollo 42eee49d30 Added: Add `SettingsProviderUtils` to get `Setting` global, secure and system namespace values 2022-06-12 02:35:46 +05:00
agnostic-apollo 03e1d14e1e Added: Write termux shell environment to `/data/data/com.termux/files/usr/etc/termux/termux.env` on app startup and package changes
The `termux.env` can be sourced by shells to set termux environment normally exported. This can be useful for users starting termux shells with `adb` `run-as` or `root`. The file will not contain `SHELL_CMD__` variables since those are shell command specific.

The items in the `termux.env` file have the format `export name="value"`.
The `"`\$` characters will be escaped with `a backslash `\`, like `\"` if characters are for literal value. Note that if `$` is escaped and if its part of variable, then variable expansion will not happen if `.env` file is sourced. The `\` at the end of a value line means line continuation. Value can contain newline characters.

The `termux.env` file should be sourceable by `POSIX` compliant shells like `bash`, `zsh`, `sh`, android's `mksh`, etc. Other shells with require manual parsing of the file to export variables.

Related discussion #2565
2022-06-12 00:51:19 +05:00
agnostic-apollo f76c20d036 Added: Init `TermuxShellEnvironment` at app startup
This will currently cache `TermuxAppShellEnvironment` so that its not regenerated for each shell started since it contains some slightly expensive operations.
2022-06-12 00:38:02 +05:00
agnostic-apollo 150b1ff99c Added: Add `ShellCommandShellEnvironment` and `TermuxShellCommandShellEnvironment` to export `ExecutionCommand` variables
This adds onto f102ea20 to build termux environment. Variables for `ExecutionCommand` app have the `SHELL_CMD__` scope. Docs will be provided for details of the variables.

- `SHELL_CMD__SHELL_ID`
- `SHELL_CMD__SHELL_NAME`
- `SHELL_CMD__APP_SHELL_NUMBER_SINCE_BOOT`
- `SHELL_CMD__TERMINAL_SESSION_NUMBER_SINCE_BOOT`
- `SHELL_CMD__APP_SHELL_NUMBER_SINCE_APP_START`
- `SHELL_CMD__TERMINAL_SESSION_NUMBER_SINCE_APP_START`

The commit also adds `SystemEventReceiver` to Termux app that will receive `ACTION_BOOT_COMPLETED`.
2022-06-12 00:38:02 +05:00
agnostic-apollo ebdab0e59c Changed: Update `TERMUX_APP__AM_SOCKET_SERVER_ENABLED` environment variable value if `termux-am-socket` server state changes 2022-06-12 00:33:08 +05:00
agnostic-apollo afc06cfd0a Added|Changed!: Add `TermuxAppShellEnvironment` and `TermuxAPIShellEnvironment` to export `Termux` and `Termux:API` app variables in `TermuxShellEnvironment`
This adds onto f102ea20 to build termux environment. Variables for `Termux` app have the `TERMUX_APP__` scope and variables for `Termux:API` app have `TERMUX_API_APP__` scope, which allows easier management for variables and know which variable belongs to which component. Some variables that were added in the last `termux-app` `v0.118.0` release have been renamed as per scoped variable design. The `TERMUX_VERSION` variable will stay as is for backward compatibility and will be duplicate of `TERMUX_APP__VERSION_NAME`. Docs will be provided for details of the variables.

- `TERMUX_APP__VERSION_NAME`
- `TERMUX_APP__VERSION_CODE`
- `TERMUX_APP__PACKAGE_NAME`
- `TERMUX_APP__PID` (previously `TERMUX_APP_PID`)
- `TERMUX_APP__UID`
- `TERMUX_APP__TARGET_SDK`
- `TERMUX_APP__IS_DEBUGGABLE_BUILD` (previously `TERMUX_IS_DEBUGGABLE_BUILD`)
- `TERMUX_APP__APK_RELEASE` (previously `TERMUX_APK_RELEASE`)
- `TERMUX_APP__APK_PATH`
- `TERMUX_APP__IS_INSTALLED_ON_EXTERNAL_STORAGE`
- `TERMUX_APP__SE_PROCESS_CONTEXT`
- `TERMUX_APP__SE_FILE_CONTEXT`
- `TERMUX_APP__SE_INFO`
- `TERMUX_APP__USER_ID`
- `TERMUX_APP__PROFILE_OWNER`
- `TERMUX_APP__PACKAGE_MANAGER` (previously `TERMUX_APP_PACKAGE_MANAGER`)
- `TERMUX_APP__PACKAGE_VARIANT` (previously `TERMUX_APP_PACKAGE_VARIANT`)
- `TERMUX_APP__FILES_DIR`
- `TERMUX_APP__AM_SOCKET_SERVER_ENABLED` (previously `TERMUX_APP_AM_SOCKET_SERVER_ENABLED`)

- `TERMUX_API_APP__VERSION_NAME` (previously `TERMUX_API_VERSION`)
2022-06-12 00:33:07 +05:00
agnostic-apollo 9749360caa Added: Add `UnixShellEnvironment.LOGIN_SHELL_BINARIES` variable for common/supported login shell binaries searched and add `fish` and `sh` shell as additional backups 2022-06-12 00:32:18 +05:00
agnostic-apollo 29d05cc72c Changed: All `ExecutionCommands` not managed by `TermuxShellManager` should have `id` `-1` 2022-06-12 00:32:18 +05:00
agnostic-apollo 2998558e9f Added: Add support in `AppShell` and `TermuxSession` for caller to add/override additional environment variables not added by `IShellEnvironment.setupShellCommandEnvironment()` 2022-06-12 00:32:18 +05:00
agnostic-apollo 13d93ccac7 Added: Add `TermuxShellManager` to manage all termux app wide shells 2022-06-12 00:32:18 +05:00
agnostic-apollo f102ea20b2 Added|Changed!: Implement new design for shell environment generation and add support for `MIT` licensed shell environment client
- `ShellEnvironmentClient` has been renamed to `IShellEnvironment` with certain changes to its interface methods, including requirement for `Execution` command itself for `setupShellCommandEnvironment()`.
- `UnixShellEnvironment` implements the `IShellEnvironment` interface as is the abstract base class of all other shell environments.
- `AndroidShellEnvironment` extends from the `UnixShellEnvironment` class and provides an environment that would work for Android shells. This is `MIT` licensed and can be used by users importing the `termux-shared` library or the library itself to run `AppShell` shells. Previously, `TermuxShellEnvironmentClient` existed which was `GPLv3` licensed and it would not have been possible to use it for non-GPL code.
- `TermuxShellEnvironment` extends from the `AndroidShellEnvironment` class and adds/overrides additional environment variables required for Termux shells to work, including setting `HOME`, `TMPDIR`, `PATH` and `LD_LIBRARY_PATH` appropriately. Termux app related variables will be added in a later commit. `TermuxShellEnvironment` replaces `TermuxShellEnvironmentClient` and is `GPLv3` licensed.
2022-06-12 00:32:18 +05:00
agnostic-apollo 0328d15ea7 Fixed: Fix duplicate logging of `file` word in `FileUtils.copyOrMoveFile()` 2022-06-11 14:24:26 +05:00
agnostic-apollo f9e9193c4e Added: Add package `APK_PATH`, `SE_PROCESS_CONTEXT`, `SE_FILE_CONTEXT` and `SE_INFO` when generating app info markdown string 2022-06-11 14:15:33 +05:00
agnostic-apollo 790481b802 Added: Add functions to `PackageUtils` to get base APK path of package 2022-06-11 14:12:58 +05:00
agnostic-apollo 1788013c80 Added: Add functions to `PackageUtils` to get `seInfo` and `seInfoUser` of package 2022-06-11 14:11:58 +05:00
agnostic-apollo 5759411109 Added: Add `SELinuxUtils` to get process and file paths security contexts 2022-06-11 14:10:34 +05:00
agnostic-apollo 0fd354a469 Changed: Ensure `TermuxSession` executable is `null` if its empty so that `login` shell can start 2022-06-11 13:55:49 +05:00
agnostic-apollo 042487c2b4 Changed: Ensure `AppShell` executable is not `null` before trying to execute it 2022-06-11 13:52:10 +05:00
agnostic-apollo b96fcb78fd Changed: Update termux twitter to https://twitter.com/termuxdevs 2022-06-11 02:41:09 +05:00
agnostic-apollo 9547869a52 Changed: Update funding link to https://termux.dev/donate 2022-06-11 02:41:09 +05:00
agnostic-apollo d29e20b0d0 Removed: Remove Termux game, root, science, unstable and x11 repo links since they have all been merged with https://github.com/termux/termux-packages 2022-06-11 02:41:09 +05:00
agnostic-apollo 0c22067b5e Added|Changed: Add termux site url and change donate url to https://termux.dev/donate 2022-06-11 02:41:09 +05:00
agnostic-apollo d287734aba Added|Changed!: Rename `SESSION_NAME` and `SESSION_CREATE_MODE` to `SHELL_NAME` and `SHELL_CREATE_MODE` and add support for `ShellCreateMode` to `AppShells`
Renamed extras `TERMUX_APP.TERMUX_SERVICE.EXTRA_SESSION_NAME` to `*.EXTRA_SHELL_NAME`, `TERMUX_APP.RUN_COMMAND_SERVICE.EXTRA_SESSION_NAME` to `*.EXTRA_SHELL_NAME`, `TERMUX_APP.TERMUX_SERVICE.EXTRA_SESSION_CREATE_MODE` to `*.EXTRA_SHELL_CREATE_MODE` and `TERMUX_APP.RUN_COMMAND_SERVICE.EXTRA_SESSION_CREATE_MODE` to `*.EXTRA_SHELL_CREATE_MODE`.

Renamed `enum` class `SessionCreateMode` to `ShellCreateMode`, `sessionName` field to `shellName`, `sessionCreateMode` to `shellCreateMode` in `ExecutionCommand`.

The `TermuxService` `AppShells`/`TermuxTasks` will now consider `ShellCreateMode` as well before starting tasks as done for `TermuxSessions` via 5794ab9a

New task command to not create new foreground session and switch to existing session if one already exits with `shellName` is

```
am startservice --user 0 -n com.termux/com.termux.app.RunCommandService \
-a com.termux.RUN_COMMAND \
--es com.termux.RUN_COMMAND_PATH '/data/data/com.termux/files/usr/bin/bash' \
--es com.termux.RUN_COMMAND_SHELL_CREATE_MODE 'no-shell-with-name' \
--es com.termux.RUN_COMMAND_SHELL_NAME "custom-name"
```

New task command to not create new background task if one already exits with `shellName` is

```
am startservice --user 0 -n com.termux/com.termux.app.RunCommandService \
-a com.termux.RUN_COMMAND \
--es com.termux.RUN_COMMAND_PATH '/data/data/com.termux/files/usr/bin/top' \
--esa com.termux.RUN_COMMAND_ARGUMENTS '-n,5' \
--es com.termux.RUN_COMMAND_SHELL_CREATE_MODE 'no-shell-with-name' \
--es com.termux.RUN_COMMAND_SHELL_NAME "custom-name" \
--es com.termux.RUN_COMMAND_RUNNER "app-shell"
```
2022-06-11 02:41:09 +05:00
agnostic-apollo 46cfea09ec Added: Add support for plugin apps to set TERMUX_APP_PACKAGE_VARIANT and TERMUX_APP_PACKAGE_MANAGER from Termux app APK BuildConfig.TERMUX_PACKAGE_VARIANT 2022-06-03 00:09:18 +05:00
agnostic-apollo 980bf8f0ae Added: Add support to get termux app package context with code classloader for plugin usage 2022-06-01 00:06:05 +05:00
agnostic-apollo 231ecff5f0 Changed: Do not modify code points for virtual or soft keyboard events
Closes #2799
2022-05-29 22:44:57 +05:00
agnostic-apollo c1c46dfcfc Changed: Change `TERMUX_APP.APPS_DIR_PATH` basename from `termux-app` to `com.termux`
The apps directory will now use the unique package name of apps for basename that can be automatically generated instead of having to be hardcoded.

`termux-am-socket` will be upgraded to `v1.4.0` for respective change.
2022-05-29 08:28:20 +05:00
agnostic-apollo 37f08c4fcc Fixed: Fix `Settings.ACTION_*` permission requests for non-activity contexts
This was caused by ce12b8ad

Closes #2769
2022-05-29 07:42:53 +05:00
agnostic-apollo a50387b553 Changed: Change termux support email from termuxreports@groups.io to support@termux.dev 2022-05-29 07:42:53 +05:00
agnostic-apollo 30cb848639 Fixed: Do not setup plugin and crash notification channel on API `< 24` since NotificationManager.IMPORTANCE_HIGH requires API 24 2022-05-29 06:54:01 +05:00
agnostic-apollo b04f209f17 Added: Add TERMUX_DEVS key SHA-256 digest to official signing keys list 2022-05-24 01:20:44 +05:00
agnostic-apollo 7b222ba392 Changed: Export correct PATH and also export LD_LIBRARY_PATH for `apt-android-5` variant instead of on Android 5/6
Overrides 4e08f76f
2022-05-24 01:20:43 +05:00
Henrik Grimler 899ef71e17 Changed: Bump android-7 bootstraps to v2022.04.28-r5 2022-05-24 01:19:45 +05:00
Henrik Grimler 4d084c02e7 Changed: Bump android-5 bootstraps to v2022.04.28-r6 2022-05-24 01:19:45 +05:00
agnostic-apollo 18a1a33e83 Added: Enable `TERMUX_PACKAGE_VARIANT` `apt-android-5` builds 2022-05-24 01:19:45 +05:00
agnostic-apollo 7677633e8f Fixed: Catch `UnsatisfiedLinkError` for `local-socket` library 2022-05-24 01:19:45 +05:00
agnostic-apollo 007bef8132 Added: Add message to bootstrap error if user installed termux on portable/external/removable sd card since its not supported on some devices 2022-05-24 01:19:45 +05:00
agnostic-apollo 5290ce1f77 Added|Fixed: Add `TermuxNotificationUtils.getTermuxOrPluginAppNotificationBuilder()` helper function and fix notification icon drawable resource id issue on Android 5 2022-05-24 01:19:45 +05:00
agnostic-apollo ab9b620c88 Added: Add ResourceUtils to get resource ids from names
This will mainly be used later when MediaViewer gets added.
2022-05-24 01:19:45 +05:00
agnostic-apollo 4e08f76fd2 Changed: Export correct PATH and also export LD_LIBRARY_PATH for Android 5/6 since packages won't use DT_RUNPATH 2022-05-24 01:19:45 +05:00
agnostic-apollo c549988434 Fixed: Fix broken javadocs links 2022-05-24 01:19:45 +05:00
agnostic-apollo 55dcd09a09 Fixed: Fixed extra keys not showing properly on Android 5
Related issue #739
2022-05-24 01:19:45 +05:00
agnostic-apollo 677a580042 Changed: Add general compatibility fixes for `minSdkVerion` `21` 2022-05-24 01:19:45 +05:00
agnostic-apollo fa829623a8 Added: Add `ViewUtils.pxToDp()` 2022-05-24 01:19:45 +05:00
agnostic-apollo 14e9a8b6fc Changed: Use float dp parameter instead of int for `ViewUtils.dpToPx()` to not lose precision 2022-05-24 01:19:45 +05:00
agnostic-apollo a1719d91b3 Changed: Bump `termux-am-library` to 2.0.0 that uses `minSdkVersion` `21` 2022-05-24 01:19:45 +05:00
agnostic-apollo 9143ebdc22 Changed: Enable desugaring support to enable support for new language APIs like Java 8 on old android versions
https://developer.android.com/studio/write/java8-support
2022-05-24 01:19:45 +05:00
agnostic-apollo 623aaebb4a Changed: Bump down `minSdkVersion` from `24` to `21` to restart supporting android 5/6 for the time being
Compatibility fixes will come in later commits.
2022-05-24 01:19:45 +05:00
agnostic-apollo 6213b7f782 Changed: Use double quotes instead of single quotes for all gradle dependencies 2022-05-24 01:19:45 +05:00
Henrik Grimler 0b4f456132
Changed: Write only our open collective to FUNDING.yml
Promote https://opencollective.com/termux instead of the old donation
channels that we have no control over.
2022-05-23 22:03:41 +02:00
agnostic-apollo b950efec27 Added: Add support for `TERMUX_APP_PACKAGE_MANAGER` and `TERMUX_APP_PACKAGE_VARIANT` to build APKs with different package manager configurations
The `TermuxBootstrap` class has been added that defines the `PackageManager` and `PackageVariant` classes for the supported package manager configurations for the app. The variant is defined by the `project.ext.packageVariant` value in the `app/build.gradle` and its value is used by the `build.gradle` to pack its respective bootstrap zips in the app APK at build time and the value is used to set `TermuxBootstrap.TERMUX_APP_PACKAGE_MANAGER` and `TermuxBootstrap.TERMUX_APP_PACKAGE_VARIANT` static values that are used at runtime by the app to run variant specific code. The manager is automatically extracted from the variant as the substring before first dash `-`.

The default variant is `apt-android-7` and it can either be replaced in `app/build.gradle` manually or the `TERMUX_PACKAGE_VARIANT` env variable can be exported in which the build command is run.

The `TERMUX_APP_PACKAGE_MANAGER` and `TERMUX_APP_PACKAGE_VARIANT` environmental variables will be exported by the app and they will also be added in Termux app info in about page and reports, allowing users and devs to know which variant is currently installed.

Bootstrap of a different variant must not be manually installed by the user after app installation by replacing `$PREFIX` since app code is dependant on the variant used to build the APK.

Currently, `apt-android-7` and `apt-android-5` variants will be built for by the workflows but they will fail for `apt-android-5` since `build.gradle` support is currently not enabled and will be enabled by a pull request that adds support for Android 5. The workflow needs to try to build the `apt-android-5` variant so that pull request builds are generated.
2022-04-28 09:33:20 +05:00
agnostic-apollo 4b3b1a5b6a Changed: Bump bootstrap to v2022.04.22-r1 2022-04-23 01:49:36 +05:00
agnostic-apollo 7f7d889dd0 Fixed: Fix proguard removing JNI used methods for release builds
```
Exception in createServerSocketNative():
java.lang.NoSuchMethodError: no non-static method "Lcom/termux/shared/jni/models/JniResult;.<init>(IILjava/lang/String;I)V"
	at com.termux.shared.net.socket.local.LocalSocketManager.createServerSocketNative(Native Method)
	at com.termux.shared.net.socket.local.LocalSocketManager.createServerSocket(LocalSocketManager.java:125)
	at com.termux.shared.net.socket.local.LocalServerSocket.start(LocalServerSocket.java:100)
	at com.termux.shared.net.socket.local.LocalSocketManager.start(LocalSocketManager.java:84)
	at com.termux.shared.shell.am.AmSocketServer.start(AmSocketServer.java:68)
	at com.termux.shared.termux.shell.am.TermuxAmSocketServer.start(TermuxAmSocketServer.java:101)
	at com.termux.shared.termux.shell.am.TermuxAmSocketServer.setupTermuxAmSocketServer(TermuxAmSocketServer.java:77)
	at com.termux.app.TermuxApplication.onCreate(TermuxApplication.java:53)
	at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1192)
	at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6719)
	at android.app.ActivityThread.access$1300(ActivityThread.java:237)
	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1913)
	at android.os.Handler.dispatchMessage(Handler.java:106)
	at android.os.Looper.loop(Looper.java:223)
	at android.app.ActivityThread.main(ActivityThread.java:7664)
	at java.lang.reflect.Method.invoke(Native Method)
	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
```
2022-04-23 00:39:00 +05:00
agnostic-apollo 53f26c9659 Changed: Refactor am socket server
The `AmSocketServer` now handles the entire logic for processing of am commands sent by clients and its results. This can be used by other apps as well to run their own am servers. The server started by `termux-app` will be managed by `TermuxAmSocketServer`. Read their javadocs for details.

The extended implementation `TermuxAmSocketServerClient` of `AmSocketServer.AmSocketServerClient`/`ILocalSocketManager` will also send a plugin error notification for all errors to the user instead of just logging to logcat since users are not very good at checking those, this should save dev time debugging problems. We may need to ignore notifications for some errors like broken pipe, based on their `Error` objects if they are normally expected, this requires further investigation.

The `TERMUX_APP_AM_SOCKET_SERVER_ENABLED` env variable will also be exported for all shell sessions and tasks for whether the server was successfully started on app startup. The user can disable the server by adding "run-termux-am-socket-server=false" to the "~/.termux/termux.properties" as implemented in 5f8a9222. The env variable will be checked by `$PREFIX/bin/termux-am` before attempting to connect.

The new path for the server socket is `/data/data/com.termux/files/apps/termux-app/termux-am/am.sock` as per `TERMUX_APP.APPS_DIR_PATH` added in bcd8f4c4.
2022-04-23 00:39:00 +05:00
agnostic-apollo 2aa7f43d1c Added|Changed|Fixed: Refactor local socket server implementation and make client handling abstract
- Added `LocalSocketManager` to manage the server, `LocalServerSocket` to represent server socket, `LocalClientSocket` to represent client socket, `LocalSocketRunConfig` to store server run config and `ILocalSocketManager` as interface for the `LocalSocketManager` to handle callbacks from the server to handle clients.
- Added support to get full `PeerCred` for client socket, including `pid`, `pname`, `uid`, `uname`, `gid`, `gname` and `cmdline` instead of just `uid`. This should provide more info for error logs about which client failed or tried to connect in case of disallowed clients. Some data is filled in native code and some in java. Native support for added to get process name and `cmdline` of a process with a specific pid.
- Added `JniResult` to get results for JNI calls. Previously only an int was returned and incomplete errors logged. With `JniResult`, both `retval` and `errno` will be returned and full error messages in `errmsg`, including all `strerror()` output for `errno`s. This would provide more helpful info on errors.
- Added `Error` support via `LocalSocketErrno` which contains full error messages and stacktraces for all native and java calls, allowing much better error reporting to users and devs. The errors will be logged by `LocalSocketManagerClientBase` if log level is debug or higher since `PeerCred` `cmdline` may contain private info of users.
- Added support in java to check if socket path was an absolute path and not greater than `108` bytes, after canonicalizing it since otherwise it would result in creation of useless parent directories on failure.
- Added `readDataOnInputStream()` and `sendDataToOutputStream()` functions to `LocalClientSocket` so that server manager client can easily read and send data.

- Renamed the variables and functions as per convention, specially one letter variables. https://source.android.com/setup/contribute/code-style#follow-field-naming-conventions
- Rename `local-filesystem-socket` to `local-filesystem` since abstract namespace sockets can also be created.
- Previously, it was assumed that all local server would expect a shell command string that should be converted to command args with `ArgumentTokenizer` and then should be passed to `LocalSocketHandler.handle()` and then result sent back to client with exit code, stdout and stderr, but there could be any kind of servers in which behaviour is different. Such client handling should not be hard coded and the server manager client should handle the client themselves however they like, including closing the client socket. This will now be done with `ILocalSocketManager. onClientAccepted(LocalSocketManager, LocalClientSocket)`.

- Ensure app does not crash if `local-socket` library is not found or for any other exceptions in the server since anything running in the `Application` class is critical that it does not fail since user would not be able to recover from it, specially non rooted users without SAF support to disable the server with a prop.
- Make sure all reasonable JNI exceptions are caught instead of crashing the app.
- Fixed issue where client logic (`LocalSocketHandler.handle()` was being run in the same thread as the new client acceptable thread, basically blocking new clients until previous client's am command was fully processed. Now all client interface callbacks are started in new threads by `LocalSocketManager`.
- Fix bug where timeout would not be greater than `1000ms` due to only using `tv_usec` which caps at `999,999`.
2022-04-23 00:36:12 +05:00
agnostic-apollo 5f8a922201 Added: Allow users to disable `termux-am` server
The user can add `run-termux-am-socket-server=false` entry to `termux.properties` file to disable the `termux-am` server to run at app startup which is connected to by `$PREFIX/bin/termux-am` from the `termux-am-socket` package. The default value is `true`. Changes require `termux-app` to be force stopped and restarted to provide consistent state for all termux sessions and tasks.

The prop will be used in a later commit.
2022-04-23 00:36:12 +05:00
agnostic-apollo 9a71074c7d Added: Add function to `ProcessUtils` to get app process name for a pid from `ActivityManager` 2022-04-23 00:36:12 +05:00
agnostic-apollo 69cc65c3ac Added: Add functions to `UserUtils` to get user name for user id from `PackageManager` and `Libcore` 2022-04-23 00:36:12 +05:00
agnostic-apollo bcd8f4c419 Added: Add `TERMUX_APPS_DIR_PATH` and `TERMUX_APP.APPS_DIR_PATH` and create them at application startup.
The termux files directory will also be checked and created if required at startup and code related to it will only be run if it is accessible. This can later also be used for init execution commands.

The `TERMUX_APP.APPS_DIR_PATH` will act as app specific directory for `termux-app` app related files. Other plugin apps will have their own directories under `TERMUX_APPS_DIR_PATH` if required.
2022-04-23 00:36:12 +05:00
agnostic-apollo 6bda7c4fc4 Added|Changed: Add `Logger.logErrorPrivate*()` functions which do not log errors that may contain potentially private info unless log level is debug or higher
Execution commands and other errors that may contain potentially private info should not be logged unless user has explicitly allowed it since apps with `READ_LOGS` permission would be able to read the data. A notification for failed executions commands would still be shown if enabled and required.
2022-04-23 00:36:12 +05:00
agnostic-apollo 89a08ff01a Fixed: Allow `Object` class object to be passed to `ReflectionUtils.invokeField()` 2022-04-23 00:36:12 +05:00
agnostic-apollo c81d9c3346 Added: Add `FileType.SOCKET` support and add `FileUtils.deleteSocketFile()` function 2022-04-23 00:36:12 +05:00
agnostic-apollo 58c3d427e8 Fixed: Log and add to Error the current file type in `FileUtils.deleteFile()` in addition to allowed file types 2022-04-23 00:36:12 +05:00
agnostic-apollo 1b9ca91da5 Added: Add functions to `DataUtils` to get generic, space and tab indented strings 2022-04-23 00:36:12 +05:00
agnostic-apollo 9c7ec0cebd Added: Add functions that can be used by non main threads to set `CrashHandler` as the `UncaughtExceptionHandler` 2022-04-23 00:36:12 +05:00
agnostic-apollo 6b60adc079 Fixed: Do not stop the app if `UncaughtExceptionHandler` implemented by `CrashHandler` receives an exception on a non main thread
Rename function that should be used by main thread of apps to `setDefaultCrashHandler()`.

Functions for other threads will be added in a later commit.
2022-04-23 00:36:12 +05:00
agnostic-apollo 5116d886c3 Changed: Add label parameter to `ExecutionCommand` `getArgumentsLogString()` and `getArgumentsMarkdownString()` functions for external usage 2022-04-23 00:36:12 +05:00
agnostic-apollo 02ab8324e9 Changed|Fixed: Do not add empty stacktraces entry to Error log and markdown String 2022-04-23 00:36:12 +05:00
agnostic-apollo c095a6184b Changed: Rename `TermuxCrashUtils` `sendPluginCrashReportNotification() to `sendCrashReportNotification()` 2022-04-23 00:36:12 +05:00
agnostic-apollo cc981d8a03 Changed: Move `com.termux.app.utils.PluginUtils` to `com.termux.shared.termux.plugins.TermuxPluginUtils`
This will allow plugins and `termux-shared` library to trigger plugin error notifications too and process plugin command results.
2022-04-23 00:36:12 +05:00
tareksander 007f9cd7f1 Changed: Set socket dir to /data/data/com.termux/files/api/
Using the TermuxConstants.TERMUX_FILES_DIR variable to get full path
TermuxConstants.TERMUX_FILES_DIR_PATH/api/am-socket.
2022-04-23 00:36:12 +05:00
tareksander b025872029 Changed: Updated the termux-am-library dependency, because the repo is now part of the Termux github organization. 2022-04-23 00:36:12 +05:00
tareksander 2851175d8b Changed: Moved the am socket to PREFIX/var/run/am-socket 2022-04-23 00:36:12 +05:00
tareksander 3dee2eb486 Changed: Allow connections from root o sockets. 2022-04-23 00:36:12 +05:00
tareksander 33b88b5d4b Changed: Set termux-am-library to a tag instead of following the main branch. 2022-04-23 00:36:12 +05:00
tareksander f366db0cb3 Added: LocalFilesystemSocket as an Interface to UNIX sockets in the filesystem. The UID of connecting programs is automatically checked against the processes UID and connections where the UID doesn't match are automatically rejected and logged.
Changed: LocalSocketListener now uses sockets in the filesystem.
2022-04-23 00:36:12 +05:00
tareksander 4aca16326c Added: termux-am-library to integrate am with Termux. 2022-04-23 00:36:12 +05:00
tareksander e597ece75f Added: ArgumentTokenizer to com.termux.shared.shell 2022-04-23 00:36:12 +05:00
Henrik Grimler 9e06bfce1f
Changed: Bump bootstrap to v2022.04.21-r1 2022-04-21 21:55:09 +02:00
agnostic-apollo 5794ab9a56 Added|Changed: Add support to switch to existing session instead of creating duplicate session for `RUN_COMMAND` intent
This is done via addition of the `com.termux.RUN_COMMAND_SESSION_CREATE_MODE` extra, which currently supports two values.

- `always` to always create a new session every time.
- `no-session-with-name` to create a new session only if no existing session exits with the same terminal session name.

The terminal session name will equal executable basename by default and dashes `-` in the basename will no longer be replaced with spaces when session name as done previously. The `com.termux.RUN_COMMAND_SESSION_NAME` extra can be used to set custom session name.

Usage:

You can use this with `Termux:Tasker` or `Termux:Widget`.

For example for `Termux:Widget`

- Create a wrapper script at `~/.shortcuts/tasks/my-script.sh` with following contents under `tasks` directory so that it runs in background app shell instead of a terminal session. Do not use terminal session runner for wrapper script, since it will open two sessions everytime otherwise, first for wrapper script, then for actual target executable. There would also be conflicts if both wrapper script and target executable have the same basename and it would be incorrectly assumed that session is already running.
- Replace the `bash` executable with actual target executable that you want to run in the terminal session if its not already running.
- Optionally set custom session name. By default it will set to executable basename and not the wrapper script name. To set it to wrapper script name, you can pass `$(basename "$0")`.
- Launch the wrapper script with widget. On first launch, a new terminal session should open but on subsequent launches, same terminal session should open.

Note that you can also pass `com.termux.RUN_COMMAND_SESSION_ACTION` to modify session action behaviour. Check https://github.com/termux/termux-app/wiki/RUN_COMMAND-Intent#run_command-intent-command-extras.

```

am startservice --user 0 -n com.termux/com.termux.app.RunCommandService \
-a com.termux.RUN_COMMAND \
--es com.termux.RUN_COMMAND_PATH '/data/data/com.termux/files/usr/bin/bash' \
--es com.termux.RUN_COMMAND_SESSION_CREATE_MODE 'no-session-with-name' \
--es com.termux.RUN_COMMAND_SESSION_NAME "custom-name"
```
2022-04-08 02:42:54 +05:00
agnostic-apollo ee32ef0c7e Changed: Maintain terminal session name in `ExecutionCommand.sessionName` in addition to `TerminalSession.mSessionName` 2022-04-08 02:42:54 +05:00
Alan Christian 8746db0d22
chore(gitignore): Remove unused ignore rules for crashlytics (#2683)
* Fix typo

* Remove crashlytics
2022-04-02 18:26:43 +05:30
agnostic-apollo ce12b8ad2d Fixed: Fix `Settings.ACTION_*` permission requests result callback
Adding `FLAG_ACTIVITY_NEW_TASK` will start permission activity in separate task and `onActivityResult()` will be called early in the calling activity without grant/not-grant result being actually set.
2022-03-30 19:45:55 +05:00
agnostic-apollo 87a79a9b24 Added: Log intents received by and 2022-03-30 19:42:38 +05:00
agnostic-apollo caa13b7047 Fixed: Fix pull request APKs commit hash 2022-03-18 06:31:43 +05:00
agnostic-apollo 5e820ad249 Added: Allow users to adjust `$TMPDIR` clear mechanism on termux exit
The `delete-tmpdir-files-older-than-x-days-on-exit` key can be used to adjust how many days old the access time should be of files that should be deleted from `$TMPDIR` on termux exit. The user can set an integer value between `-1` and `100000`. Set `-1` to delete no files, `0` to delete all files and `> 0` for `x` days. The default value is `3` days. So adding an entry like `delete-tmpdir-files-older-than-x-days-on-exit=10` to `termux.properties` file will make termux delete files older than `10` when termux is exited. After updating the value, either restart termux or run `termux-reload-settings` for changes to take effect.

Note that currently `> 0` will revert back to `0` since deletion is currently broken for empty sub directories and deletion needs to be done based on access time instead of modified time. It will need to be fixed in a later commit. Check `FileUtils.deleteFilesOlderThanXDays()`.

Related issue #2350
2022-03-17 22:35:31 +05:00
agnostic-apollo 25d21e9d2e Fixed: Fix wrong input type selected if toolbar is switched back to extra keys after tapping terminal if in text input mode
Closes #2503
2022-03-17 05:30:25 +05:00
agnostic-apollo dd378738e3 Fixed: Add `media-*` symlinks to `Android/media` for all storages and `external-0` symlink to `Android/media` of primary storage
The `~/external-0` and `~/media-0` should point to primary storage and `1+` to others, possibly portable sd cards.

Note that one can make portable sd card as primary storage as well instead of internal sd card with adoptable storage, which then links it to `/storage/emulated`, so the concept of `internal` and `external` sd card does not apply to primary storage for all cases.

https://android.stackexchange.com/questions/214233/how-to-free-internal-storage-by-moving-data-or-using-symlink-bind-mount-with-a/214706#214706

https://android.stackexchange.com/questions/217741/how-to-bind-mount-a-folder-inside-sdcard-with-correct-permissions/217936#217936

https://android.stackexchange.com/questions/205430/what-is-storage-emulated-0/205494#205494

https://source.android.com/devices/storage/adoptable

```
$ ls -l storage | cut -d ' ' -f 9-

audiobooks -> /storage/emulated/0/Audiobooks
dcim -> /storage/emulated/0/DCIM
documents -> /storage/emulated/0/Documents
downloads -> /storage/emulated/0/Download
external-0 -> /storage/emulated/0/Android/data/com.termux/files
external-1 -> /storage/XXXX-XXXX/Android/data/com.termux/files
media-0 -> /storage/emulated/0/Android/media/com.termux
media-1 -> /storage/XXXX-XXXX/Android/media/com.termux
movies -> /storage/emulated/0/Movies
music -> /storage/emulated/0/Music
pictures -> /storage/emulated/0/Pictures
podcasts -> /storage/emulated/0/Podcasts
shared -> /storage/emulated/0

```

Closes #2481
2022-03-17 05:30:25 +05:00
agnostic-apollo 93d57f053b Added: Add `~/storage` symlinks for `documents`, `podcasts` and `audiobooks`
The `audiobooks` symlink will only be made on Android `10+`

Closes #2648
2022-03-17 05:30:25 +05:00
agnostic-apollo 26e0fa2b9e Changed: Use thread to setup settings components
Getting plugin contexts may be considered as too much work on main thread in certain situations resulting in android complaining that app is not responding
2022-03-17 05:30:25 +05:00
agnostic-apollo d25f7afd97 Changed: Share terminal transcript with `ShareUtils` 2022-03-17 05:30:25 +05:00
agnostic-apollo e0074f280f Fixed: Fix typos 2022-03-17 05:30:25 +05:00
agnostic-apollo cc58ddde31 Changed: Check crash log file whenever `TermuxActivity` is resumed instead of only on app startup
This adds onto 06dbfbdb since receiver would not be registered to receive `ACTION_NOTIFY_APP_CRASH` if `TermuxActivity` was not be in foreground
2022-03-17 02:10:51 +05:00
agnostic-apollo 477b36acd1 Added: Add support for `ACTION_NOTIFY_APP_CRASH` in receiver registered by `TermuxActivity` to notify users of plugin app crashes
Once plugins integrate changes for `TermuxCrashUtils.onPostLogCrash()`, they will send the `ACTION_NOTIFY_APP_CRASH` broadcast when an uncaught exception is caught by `CrashHandler`. If `TermuxActivity` is in foreground, then it will receive the broadcast and notify user of the crash by reading it from the crash log file without the user having to restart termux app to be notified.
2022-03-17 02:10:51 +05:00
agnostic-apollo 5f00531381 Changed: Move `com.termux.app.utils.CrashUtils` to `com.termux.shared.termux.crash.TermuxCrashUtils` so that plugins trigger plugin notifications too
Calls to `notifyAppCrashFromCrashLogFile()` will now be synchronized as well.
2022-03-17 02:10:51 +05:00
agnostic-apollo 4dbfc1fac8 Added: Add support for `onPreLogCrash()` and `onPostLogCrash()` in `CrashHandler` so that `CrashHandlerClient` can decide which exceptions to log and add custom logic 2022-03-17 02:10:51 +05:00
agnostic-apollo 4b07e4f4c0 Added: Add multi process support in `TermuxAppSharedPreferences` since plugin apps may need to read values modified by termux app process 2022-03-17 02:10:51 +05:00
agnostic-apollo 621545dd0a Added: Add support for getting termux app and plugin app info only in `TermuxUtils.getAppInfoMarkdownString()` 2022-03-17 02:10:51 +05:00
agnostic-apollo 9a65aa4589 Fixed: Do not add double heading if callingPackageName passed to `TermuxUtils.getAppInfoMarkdownString()` is a plugin app 2022-03-17 02:10:51 +05:00
agnostic-apollo 021cb60e23 Added: Add `TERMUX_API_APT_*` constants 2022-03-17 02:10:51 +05:00
agnostic-apollo 14c5fc7b1e Fixed: Suppress warnings for requiring android 11 to request `MANAGE_EXTERNAL_STORAGE` permission and call `Environment.isExternalStorageManager()` 2022-03-17 02:10:51 +05:00
agnostic-apollo 792c33c9a5 Fixed: Fix `PermissionUtils.requestPermissions()` not requesting multiple permissions correctly 2022-03-17 02:10:51 +05:00
agnostic-apollo 760ae78aff Docs: Add termux apps vulnerability disclosure post links to README 2022-03-11 20:17:48 +05:00
agnostic-apollo c3ac30e2fb Added: Add ic_info and ic_settings 2022-03-11 20:16:50 +05:00
agnostic-apollo b94dc7eea9 Changed|Deprecated: Move from shell command background mode to command runner
This starts the support for adb, root and other custom runners for shell commands. Previously only terminal and background tasks in app shells were supported.

`TERMUX_SERVICE.EXTRA_BACKGROUND` and `RUN_COMMAND_SERVICE.EXTRA_BACKGROUND` extras have been deprecated and instead respective `EXTRA_RUNNER` extra keys should be used. Currently supported extra values are `terminal-session` and `app-shell`. In future, `adb-shell` and `root-shell` are planned to be supported as well.
2022-03-10 02:51:56 +05:00
agnostic-apollo 05283bd774 Changed: Load termux.properties into a single static app wide TermuxAppSharedProperties class
The `TermuxAppSharedProperties.properties` will exist in `termux-shared` library and only the single static instance will be reloaded whenever needed, instead of different activities and services maintaining their own instances. The classes in `termux-shared` library will also get access to the properties for their own needs.

The night mode set in `TermuxApplication` and terminal rows set in `TermuxService` will no longer require loading props from disk.

Updating `allow-external-apps` value will now require restarting termux or running `termux-reload-settings` since value will no longer be loaded from disk every time.
2022-03-10 02:37:10 +05:00
agnostic-apollo 6d944b5f7f Changed: Use application context for SharedProperties 2022-03-10 02:37:10 +05:00
agnostic-apollo bd004514df
Merge pull request #2612 from Nickoriginal/master
Docs: Fix typo
2022-02-24 06:41:22 +05:00
Nickoriginal 270e41fae5
Update README.md 2022-02-23 11:10:58 +02:00
agnostic-apollo 68cdbd6ff4 Added: Add support for getting feature flag values and show MONITOR_PHANTOM_PROCS value in about page
MONITOR_PHANTOM_PROCS will only be shown in Android 12+ devices and will be marked "<unsupported>" if its not supported in current android build. It will show in Termux Settings->About->Device Info->Software and in reports. Flag is available on Pixel Android 12L beta 3 and Android 13. Check FeatureFlagUtils for more details.

Getting supported feature flags and their values is done through reflection on android "android.util.FeatureFlagUtils" class and requires bypassing android hidden API restrictions.

Related issue #2366
https://issuetracker.google.com/u/1/issues/205156966#comment27
2022-02-13 00:37:41 +05:00
agnostic-apollo 280e284488 Docs: Add building bootstrap link 2022-02-08 23:33:46 +05:00
agnostic-apollo a01ff018b3 Docs: Update matrix invite links 2022-02-08 23:31:20 +05:00
agnostic-apollo f8e7ada143 Fixed: Fix typo from 43858dfb 2022-02-05 07:28:43 +05:00
agnostic-apollo f33758c7c0 Fixed: Fix typo from 43858dfb 2022-02-05 07:25:01 +05:00
agnostic-apollo c567cc3b92 Fixed: Fix app crash if failed to start TermuxService while in background due to android bg restrictions
The crash happens due to android 8.0 background restrictions if TermuxActivity is not in foreground/whitelist and attempts to start TermuxService. With this commit, the app will not crash but will just exit with a toast message.

https://developer.android.com/about/versions/oreo/background#services

https://cs.android.com/android/platform/superproject/+/android-12.0.0_r4:frameworks/base/services/core/java/com/android/server/am/ActiveServices.java;l=722

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.termux/com.termux.app.TermuxActivity}: java.lang.IllegalStateException: Not allowed to start service Intent { cmp=com.termux/.app.TermuxService }: app is in background uid UidRecord{533ae62 u0a187 TPSL idle procs:1 seq(0,0,0)}
 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2947)
 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3082)
 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1832)
 at android.os.Handler.dispatchMessage(Handler.java:106)
 at android.os.Looper.loop(Looper.java:201)
 at android.app.ActivityThread.main(ActivityThread.java:6821)
 at java.lang.reflect.Method.invoke(Native Method)
 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.IllegalStateException: Not allowed to start service Intent { cmp=com.termux/.app.TermuxService }: app is in background uid UidRecord{533ae62 u0a187 TPSL idle procs:1 seq(0,0,0)}
 at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1587)
 at android.app.ContextImpl.startService(ContextImpl.java:1542)
 at android.content.ContextWrapper.startService(ContextWrapper.java:674)
 at com.termux.app.TermuxActivity.onCreate(TermuxActivity.java:242)
 at android.app.Activity.performCreate(Activity.java:7224)
 at android.app.Activity.performCreate(Activity.java:7213)
 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
 ... 11 more

Closes #2552
2022-02-05 07:19:36 +05:00
agnostic-apollo 43858dfbb1 Fixed: Rename TermuxActivity isOnResumeAfterOnCreate to mIsOnResumeAfterOnCreate as per variable naming convention 2022-02-05 06:30:48 +05:00
agnostic-apollo b8c3db0b6e Fixed: Change extra keys and terminal input view background to black
Required for day/night theming and should fix issues where both views were translucent with light terminal color themes.
2022-02-05 06:28:22 +05:00
agnostic-apollo 622ff4fad4 Fixed: Fix issue where a colour tint/highlight would be added to the terminal on activity re-creation
The fix in c6b4114f was not working for it.
2022-02-05 06:26:23 +05:00
agnostic-apollo a56ed5771d Fixed: Fix terminal sessions being re-added if "New Session" shortcut or termux-reload-settings was used
If TermuxActivity was recreated then the original intent was re-delivered, resulting in a new session being re-added each time.

Closes #2566
2022-02-05 06:22:49 +05:00
agnostic-apollo 2a1c5a70da Docs: Fix issue link 2022-01-29 02:39:17 +05:00
agnostic-apollo 9b5aad9416 Fixed: Fix AppShell failsafe env 2022-01-28 18:06:05 +05:00
agnostic-apollo 95d7a154a4 Docs: Add notice that termux is broken on Android 12 2022-01-28 04:23:59 +05:00
agnostic-apollo 172a75e578 Changed: Do not recreate TermuxActivity enabled in 6631599f when TermuxService starts a session
Activity will only be recreated when `termux-reload-settings` is run or `night-mode` config does not equal current system mode when TermuxActivity is initially started. Running `termux-reload-settings` can cause some problems if some variable whose state should be maintained or reset is not being done so correctly, like termux session shortcuts weren't before 4fd48a5a. It requires further testing and any bugs should be reported.
2022-01-28 04:03:48 +05:00
agnostic-apollo 4fd48a5aed Fixed: Fix termux session shortcuts not working after TermuxActivity recreation
The `List<KeyboardShortcut> mSessionShortcuts = new ArrayList<>()` declaration was causing shortcuts list to be of size 0 in `TermuxTerminalViewClient.onCodePoint()` after re-creation, which resulted in session shortcuts not working.
2022-01-28 03:56:39 +05:00
agnostic-apollo 81dd113157 Docs: Add notice that users should upgrade to v0.118.0 ASAP 2022-01-24 23:39:06 +05:00
agnostic-apollo 2452399a13 Added: Add explicit exported attribute for app components as required by Android 12
https://developer.android.com/about/versions/12/behavior-changes-12#exported
2022-01-23 19:46:46 +05:00
agnostic-apollo 6631599fb6 Added: Add support for shared day/night theming across termux apps
With this commit, activities will automatically change theme between day/night if `night-mode` `termux.properties` is not set or is set to `system` without requiring app restart.

Dialog theming will be fully added in a later commit and may currently be in an inconsistent state or have crashes.

The `uiMode` has been removed from `configChanges` of `TermuxActivity`, this may cause termux app to restart if samsung DEX mode is changed, if it does, then users should report it so that it can be fixed by re-adding the value and ignoring the change inside `TermuxActivity.onConfigurationChanged()`. The docs don't state if its necessary. Check related pull request #1446.

Running `termux-reload-settings` will also restart `TermuxActivity`, the activity data should be preserved.
2022-01-23 01:42:26 +05:00
agnostic-apollo f3f434af92 Changed: Rename ShareUtils openURL() to openUrl() 2022-01-23 01:42:26 +05:00
agnostic-apollo 6fea1fbddc Changed: Change ShareUtils.openSystemAppChooser() to public 2022-01-23 01:42:26 +05:00
agnostic-apollo a3cd058fb4 Update: Remove duplicate log tag prefix from TermuxOpenReceiver 2022-01-23 01:42:26 +05:00
agnostic-apollo b435d94888 Fixed: Do not open null or empty file paths passed to TermuxOpenReceiver 2022-01-23 01:42:26 +05:00
agnostic-apollo 3898ebdc74 Changed: Rename UriUtils getUriFilePath() to getUriFilePathWithFragment() 2022-01-23 01:42:26 +05:00
agnostic-apollo 1f3d3616a4 Fixed: Fix termux app restarting on samsung dex version < 3.0 when switching modes 2022-01-23 01:42:26 +05:00
agnostic-apollo b45ff8a407 Added: Store pid in ExecutionCommand for sessions and tasks 2022-01-23 01:42:26 +05:00
agnostic-apollo bf10c72661 Added: Add annotations and modifiers 2022-01-23 01:42:26 +05:00
agnostic-apollo 1fb4fe2510 Fixed: Fix FileUtils labels 2022-01-23 01:42:26 +05:00
agnostic-apollo 8e7e355fcb Fixed: Add accidentally removed import in 5252fbbe 2022-01-23 01:42:25 +05:00
agnostic-apollo 0fa0738cf6 Changed: Add uncommitted changes from 361bfb39 2022-01-23 01:41:57 +05:00
agnostic-apollo 998499d991 Changed: Remove redundant double quotes from string resources 2022-01-23 01:40:22 +05:00
agnostic-apollo 20a70b1a22 Fixed: Add uncommitted string resource changes 2022-01-23 01:40:22 +05:00
agnostic-apollo 5d202d082f Changed: Replace extra-keys Button with MaterialButton 2022-01-23 01:40:22 +05:00
agnostic-apollo bb1584decb Fixed: Remove unused imports 2022-01-23 01:40:22 +05:00
agnostic-apollo c1a0d6deff Changed: Rename ActivityUtilsErrno to ActivityErrno 2022-01-23 01:40:22 +05:00
agnostic-apollo 3f84b5345f Changed: Make ExtraKeysView private functions public and variables protected 2022-01-23 01:40:22 +05:00
agnostic-apollo 006bfeac8d Fixed: Fix termux background command logging at verbose level if CUSTOM_LOG_LEVEL was not passed 2022-01-23 01:40:22 +05:00
agnostic-apollo d222102635 Fixed: Catch rare RuntimeException while loading bell
java.lang.RuntimeException: Unable to resume activity {com.termux/com.termux.app.TermuxActivity}: android.content.res.Resources$NotFoundException: File res/raw/bell.ogg from drawable resource ID #0x7f0f0001
        at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3480)
        at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3520)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1554)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6247)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
        at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:107)
     Caused by: android.content.res.Resources$NotFoundException: File res/raw/bell.ogg from drawable resource ID #0x7f0f0001
        at android.content.res.ResourcesImpl.openRawResourceFd(ResourcesImpl.java:308)
        at android.content.res.Resources.openRawResourceFd(Resources.java:1272)
        at android.media.SoundPool.load(SoundPool.java:247)
        at com.termux.app.terminal.TermuxTerminalSessionClient.getBellSoundPool(TermuxTerminalSessionClient.java:257)
        at com.termux.app.terminal.TermuxTerminalSessionClient.onResume(TermuxTerminalSessionClient.java:82)
        at com.termux.app.TermuxActivity.onResume(TermuxActivity.java:290)
        at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1270)
        at android.app.Activity.performResume(Activity.java:6861)
        at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3457)
        at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3520)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1554)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6247)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
        at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:107)
     Caused by: java.io.FileNotFoundException: This file can not be opened as a file descriptor; it is probably compressed
        at android.content.res.AssetManager.openNonAssetFdNative(Native Method)
        at android.content.res.AssetManager.openNonAssetFd(AssetManager.java:467)
        at android.content.res.ResourcesImpl.openRawResourceFd(ResourcesImpl.java:306)
        at android.content.res.Resources.openRawResourceFd(Resources.java:1272)
        at android.media.SoundPool.load(SoundPool.java:247)
        at com.termux.app.terminal.TermuxTerminalSessionClient.getBellSoundPool(TermuxTerminalSessionClient.java:257)
        at com.termux.app.terminal.TermuxTerminalSessionClient.onResume(TermuxTerminalSessionClient.java:82)
        at com.termux.app.TermuxActivity.onResume(TermuxActivity.java:290)
        at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1270)
        at android.app.Activity.performResume(Activity.java:6861)
        at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3457)
        at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3520)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1554)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6247)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
        at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:107)
2022-01-23 01:40:22 +05:00
agnostic-apollo 7a386a7f2a Fixed: Fix ArrayIndexOutOfBoundsException when setting zero width terminal character
java.lang.ArrayIndexOutOfBoundsException: length=64; index=-1
at com.termux.terminal.TerminalRow.setChar(TerminalRow.java:127)
at com.termux.terminal.TerminalBuffer.setChar(TerminalBuffer.java:413)
at com.termux.terminal.TerminalEmulator.emitCodePoint(TerminalEmulator.java:2329)
at com.termux.terminal.TerminalEmulator.processCodePoint(TerminalEmulator.java:617)
at com.termux.terminal.TerminalEmulator.processByte(TerminalEmulator.java:513)
at com.termux.terminal.TerminalEmulator.append(TerminalEmulator.java:480)
at com.termux.terminal.TerminalSession$MainThreadHandler.handleMessage(TerminalSession.java:339)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:219)
at android.app.ActivityThread.main(ActivityThread.java:8349)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1055)
2022-01-23 01:40:22 +05:00
agnostic-apollo b79ed509f1 Changed: Store app wide night mode in NightMode.APP_NIGHT_MODE so that libraries can use it directly without having to load or get it from termux properties 2022-01-23 01:40:22 +05:00
agnostic-apollo 1b794b3518 Fixed: Do not use colon character ":" in log tag since it is invalid and breaks logcat command filterspecs argument 2022-01-23 01:40:22 +05:00
agnostic-apollo 0a3efc537d Changed: Use PermissionUtils to request disabling battery optimizations in TermuxService 2022-01-23 01:40:22 +05:00
agnostic-apollo 36e49707ec Added: Add support to request Settings.ACTION* permissions to be requested via Service context 2022-01-23 01:40:22 +05:00
agnostic-apollo f857bf2968 Added: Add ActivityUtils.startActivity() and catch uncaught exceptions in TermuxActivity 2022-01-23 01:40:22 +05:00
agnostic-apollo b69d14119e Changed: Return Error instead of boolean for ActivityUtils.startActivityForResult() 2022-01-23 01:40:22 +05:00
agnostic-apollo 8c43b7f0a1 Changed: Remove TermuxConstants reference from PackageUtils 2022-01-23 01:40:22 +05:00
agnostic-apollo 6ff5572999 Changed!: Remove TermuxConstants reference from Logger and set DEFAULT_LOG_TAG at application startup
Plugin apps must do the same
2022-01-23 01:40:22 +05:00
agnostic-apollo 8e506859a6 Changed!: Rename TermuxTask to AppShell since its not part of termux-app or com.termux.shared.termux package 2022-01-23 01:40:22 +05:00
agnostic-apollo 361bfb3961 Changed!: Move to package-by-feature hierarchy for classes not using it since termux-shared is growing too big and layers are getting out of hand 2022-01-23 01:40:22 +05:00
agnostic-apollo 549a772d45 Added: Add UriScheme and move UriUtils to com.termux.shared.net package 2022-01-23 01:40:22 +05:00
agnostic-apollo 37b9bcf5af Changed!: Rename FileUtils readStringFromFile() to readTextFromFile() and writeStringToFile() to writeTextToFile() 2022-01-23 01:40:22 +05:00
agnostic-apollo 7bbc12c7c9 Fixed: Get file basename from Uri path when opening files in termux if failed to get it ContentResolver and EXTRA_TITLE 2022-01-23 01:40:22 +05:00
agnostic-apollo 74b23cb209 Fixed: Fix TermuxFileReceiverActivity failing to open files with "#" and remove hardcoded "content" and "file" strings and fix indentation
am start -a android.intent.action.VIEW -n com.termux/.filepicker.TermuxFileReceiverActivity -d "file:///data/data/com.termux/files/home/te#st.sh"
2022-01-23 01:40:22 +05:00
agnostic-apollo b559d5a0bd Fixed: Fix TermuxService failing to execute files with "#"
am startservice --user 0 -n com.termux/.app.TermuxService -a com.termux.service_execute -d "file:///data/data/com.termux/files/home/te#st.sh"
2022-01-23 01:40:22 +05:00
agnostic-apollo 3e518a6a75 Fixed: Fix termux-open failing to open files with "#" and remove hardcoded "content" and "file" strings
termux-open "/data/data/com.termux/files/home/te#st.sh"
2022-01-23 01:40:22 +05:00
agnostic-apollo d96883c4d6 Changed|Deprecated: Deprecate `use-black-ui` termux property and replace it with `night-mode`
This will not break existing `use-black-ui` settings for users and it will automatically be converted to `night-mode` when properties are loaded from disk but a deprecation message will be logged.

This `night-mode` key can be used to set the day/night theme variant for activities used by termux app and its plugin. The user can set a string value to `true` to force use dark variant of theme, `false` to force use light variant of theme or `system` to automatically set theme based on current system settings. The default value is still `system`. The app must be restarted for changes to take effect for existing activities, including main terminal `TermuxActivity`.

This is required since "theme != night mode". In future custom theme or color support may be provided that will have both dark and night modes for the same theme.
2022-01-23 01:40:22 +05:00
agnostic-apollo 28ecb64992 Changed: Automatically use default properties file and client for TermuxSharedProperties.getTermuxInternalPropertyValue() 2022-01-23 01:40:22 +05:00
agnostic-apollo 5d64f1225c Added: Add support in SharedProperties to modify properties loaded from disk before they are mapped to internal values 2022-01-23 01:40:22 +05:00
agnostic-apollo aed4b96a31 Added: Add FileUtils.regularOrDirectoryFileExists() 2022-01-23 01:40:22 +05:00
agnostic-apollo 5b2aca9cf7 Changed: Fix minor typos in FileUtils and FileUtilsErrno 2022-01-23 01:40:22 +05:00
agnostic-apollo 93d738ae63 Fixed: Remove all trailing slashes when normalizing path 2022-01-23 01:40:22 +05:00
agnostic-apollo f7ebcae7b3 Added: Add functions to get dirname and basename in FileUtils 2022-01-23 01:40:22 +05:00
agnostic-apollo 63c106c746 Added: Add Error.logErrorAndShowToast() and provide non-static logging functions to be used when Error may not be null 2022-01-23 01:40:22 +05:00
agnostic-apollo 2c0e9c6c5c Added: Add Logger.logInfoAndShowToast() and log messages even if not showing toast due to null Context 2022-01-23 01:40:22 +05:00
agnostic-apollo 9eeb2babd7 Added: Add support for MANAGE_EXTERNAL_STORAGE when targeting targetSdkVersion 30
Termux will now automatically request legacy `WRITE_EXTERNAL_STORAGE` or `MANAGE_EXTERNAL_STORAGE` permissions if targeting targetSdkVersion `30` (android `11`) and running on sdk `30` (android `11`) and higher when `termux-setup-storage` is run.

Functions have been added to `PermissionUtils` to automatically check and request either permission depending on app `targetSdkVersion` and android version. Functions have been added to `PackagUtils` to get `requestLegacyExternalStorage` value from app manifest if added. If legacy storage is possible, then it must be set to `true`. Check `PermissionUtils.checkAndRequestLegacyOrManageExternalStoragePermission()`, `PermissionUtils.isLegacyExternalStoragePossible()` and `PermissionUtils.checkIfHasRequestedLegacyExternalStorage()` for details.
2022-01-23 01:40:22 +05:00
agnostic-apollo 32dd7eab03 Changed|Fixed: Add java docs to PermissionUtils and fix permission checking
ContextCompat.checkSelfPermission() may return true for permissions not even requested so it now checked if permissions are even requested in app manifest before checking if they are granted and before asking for permission to be granted.

Also some general improvements in code quality, including using ActivityUtils to request non-standard permissions and added support for AppCompatActivity instances to request permissions in addition to Activity instances.
2022-01-23 01:40:22 +05:00
agnostic-apollo 50a97b1977 Added: Add ReflectionUtils and add dependency for org.lsposed.hiddenapibypass:hiddenapibypass
The call to bypassHiddenAPIReflectionRestrictions() must be made before trying to reflect hidden or non-sdk APIs.

Reflection will be used for accessing hidden (@hide) APIs by Termux and its plugins later.

https://github.com/LSPosed/AndroidHiddenApiBypass
https://developer.android.com/guide/app-compatibility/restrictions-non-sdk-interfaces
2022-01-23 01:40:22 +05:00
agnostic-apollo f4a997b7dd Added: Add ActivityUtils with functions to start activities for result 2022-01-23 01:40:22 +05:00
agnostic-apollo 3c202928b4 Changed: Fix typos is PackageUtils 2022-01-23 01:40:22 +05:00
agnostic-apollo aca0000ee6 Update LICENSE.md as per 5252fbbe 2022-01-23 01:40:21 +05:00
agnostic-apollo 5252fbbe11 Changed!: Move Termux specific classes to com.termux.shared.termux package
This will allow segregation of Termux utils/classes from general ones and also allow easier management of GPLv3 License for Termux classes
2022-01-23 01:36:41 +05:00
agnostic-apollo 304aed3063 Added: Add UrlUtils 2022-01-23 01:36:41 +05:00
agnostic-apollo cbac7c8fbd Changed: Get user handle for package instead of process user handle when getting profile user serial number 2022-01-23 01:36:41 +05:00
agnostic-apollo 65252dc640 Changed: Use cached PackageInfo while getting version code and name for app 2022-01-23 01:36:41 +05:00
agnostic-apollo 2c6d009657 Added: Add uid to app info 2022-01-23 01:36:41 +05:00
agnostic-apollo a987246bd8 Added: Add comment for why clearing of $TMPDIR may be skipped on termux exit 2022-01-23 01:36:41 +05:00
agnostic-apollo 059feaacf1 Changed: Move UrlUtils to TermuxUrlUtils 2022-01-23 01:36:41 +05:00
agnostic-apollo f62997a60e Fixed: Log exception instead of crashing app on NumberFormatException for invalid termcap/terminfo string requested
java.lang.NumberFormatException: For input string: " a"
at java.lang.Long.parseLong(Long.java:583)
at java.lang.Long.valueOf(Long.java:781)
at java.lang.Long.decode(Long.java:933)
at com.termux.terminal.TerminalEmulator.doDeviceControl(TerminalEmulator.java:940)
at com.termux.terminal.TerminalEmulator.processCodePoint(TerminalEmulator.java:813)
2022-01-23 01:36:41 +05:00
agnostic-apollo 79980a07a8 Fixed: Use android.util.Log for terminal-emulator logging if TerminalSessionClient is null like when running tests 2022-01-23 01:36:41 +05:00
agnostic-apollo 4faf2b9d28 Fixed: Fix CSI Delete Ps Column(s) (DECDC)
Firstly, `TerminalBuffer.blockSet()` was throwing the exception since `sx + w > mColumns` which was technically passed by TerminalEmulator.blockClear()`. Actual value would be `mCursorRow + columnsToMove + columnsToDelete > mColumns`.

Secondly, the call to `blockClear()` should not be needed since it the `blockCopy()` would overwrite the columns to be deleted on copy.

Run `printf "\e['~"` to delete 1 column and `printf "\e[3'~"` to delete 3 columns. Run `printf "\e[3'}"` to insert 2 columns.

java.lang.IllegalArgumentException: Illegal arguments! blockSet(78, 0, 1, 30, 32, 56, 30)
at com.termux.terminal.TerminalBuffer.blockSet(TerminalBuffer.java:397)
at com.termux.terminal.TerminalEmulator.blockClear(TerminalEmulator.java:2035)
at com.termux.terminal.TerminalEmulator.processCodePoint(TerminalEmulator.java:799)
2022-01-23 01:36:41 +05:00
agnostic-apollo 701b5ccd5c Fixed: Fix ArrayIndexOutOfBoundsException thrown because length was less than 0 when selecting text from terminal buffer
java.lang.ArrayIndexOutOfBoundsException: src.length=132 srcPos=90 dst.length=16 dstPos=0 length=-2
at java.lang.System.arraycopy(System.java:469)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:597)
at java.lang.StringBuilder.append(StringBuilder.java:191)
at com.termux.terminal.TerminalBuffer.getSelectedText(TerminalBuffer.java:97)
at com.termux.terminal.TerminalBuffer.getSelectedText(TerminalBuffer.java:57)
at com.termux.terminal.TerminalBuffer.getSelectedText(TerminalBuffer.java:53)
at com.termux.terminal.TerminalEmulator.getSelectedText(TerminalEmulator.java:2401)
at com.termux.view.textselection.TextSelectionCursorController$1.onActionItemClicked(TextSelectionCursorController.java:140)
2022-01-23 01:36:41 +05:00
agnostic-apollo 9798b30c76 Fixed: Fix issue where menu wouldn't show when text on bottom row of terminal was selected
Closes #2233
2022-01-23 01:36:41 +05:00
agnostic-apollo fa91205bca Changed!: Move ReportInfo parameters from constructor to functions 2022-01-23 01:36:41 +05:00
agnostic-apollo 64adc521de Added: Add info of all Termux plugins in bootstrap error reports and refactor notification functions
Now in case of bootstrap failure, the app info of all installed termux plugin apps will be added as well, including whether they are installed on external/portable sd card. Apparently, as per reports, installing termux app or even plugin apps on external/portable sd cards prevents termux apps from accessing its files directory `/data/data/com.termux/file` and bootstrap checks fail. This commit should provide more info or proof of it.

Moreover, adding plugin info would be useful in future for diagnosing targetsdk mismatch between Termux and its plugins when sdk `30` is targeted by Termux app.
2022-01-23 01:36:41 +05:00
agnostic-apollo 9814438ae5 Added: Add info of Termux API calling app in plugin command error reports and refactor notification functions
Now when a Termux API command like `RUN_COMMAND` intent is called by an external app with PendingIntent, then the info of the app will be shown in error reports as well. This should provide more info about the caller which should be useful for debugging or in case a malicious app ran commands with `allow-external-app` disabled.

Moreover, `PluginUtils.sendPluginCommandErrorNotification()` has been refactored to send generic messages instead of just for `ExecutionCommand`. This will allow usage with other Termux APIs as well.
2022-01-23 01:36:41 +05:00
agnostic-apollo ae7f141aca Added: Add info of installed plugin apps when report issue report is generated with debug mode enabled 2022-01-23 01:36:41 +05:00
agnostic-apollo fd4159f1ba Added: Add generic function TermuxUtils to get app info for termux app, its installed plugin apps and external apps 2022-01-23 01:36:41 +05:00
agnostic-apollo 1327cef7b4 Added: Add support for getting external app info
PackageUtils were previously based on using `Context` object to get app info, which was only possible to get for Termux app and its sharedUserId plugins. Now it has been refactored to used `PackageInfo` and `ApplicationInfo` objects to get the info, which will also allow getting info of external apps. However, when targeting sdk `30`, queries entries or `QUERY_ALL_PACKAGES` permission will be required. Check `PackageUtils.isAppInstalled()` for more info.
2022-01-23 01:36:41 +05:00
agnostic-apollo 0da1984b59 Changed: Do not show toast if text null or empty 2022-01-23 01:36:41 +05:00
agnostic-apollo 09412da9d7 Fixed: Fix NullPointerException when getting spanned markdown like for notification 2022-01-23 01:36:41 +05:00
agnostic-apollo 009c128052 Changed: Move termux apps properties file list to TermuxConstants and do not follow symlinks 2022-01-23 01:36:41 +05:00
241 changed files with 14820 additions and 3609 deletions

3
.github/FUNDING.yml vendored
View File

@ -1,2 +1 @@
patreon: termux
custom: https://paypal.me/fornwall
custom: https://termux.dev/donate

9
.github/dependabot.yml vendored Normal file
View File

@ -0,0 +1,9 @@
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule:
interval: daily
commit-message:
# Prefix all commit messages with "Changed: "
prefix: "Changed"

View File

@ -8,16 +8,23 @@ on:
jobs:
attach-apks:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
package_variant: [ apt-android-7, apt-android-5 ]
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
steps:
- name: Clone repository
uses: actions/checkout@v2
uses: actions/checkout@v6
with:
ref: ${{ env.GITHUB_REF }}
- name: Build and attach APKs to release
shell: bash {0}
env:
PACKAGE_VARIANT: ${{ matrix.package_variant }}
run: |
exit_on_error() {
echo "$1"
@ -34,13 +41,14 @@ jobs:
fi
APK_DIR_PATH="./app/build/outputs/apk/debug"
APK_VERSION_TAG="$RELEASE_VERSION_NAME+github-debug"
APK_VERSION_TAG="$RELEASE_VERSION_NAME+${{ env.PACKAGE_VARIANT }}-github-debug"
APK_BASENAME_PREFIX="termux-app_$APK_VERSION_TAG"
echo "Building APKs for '$RELEASE_VERSION_NAME' release"
echo "Building APKs for 'APK_VERSION_TAG' release"
export TERMUX_APK_VERSION_TAG="$APK_VERSION_TAG" # Used by app/build.gradle
export TERMUX_PACKAGE_VARIANT="${{ env.PACKAGE_VARIANT }}" # Used by app/build.gradle
if ! ./gradlew assembleDebug; then
exit_on_error "Build failed for '$RELEASE_VERSION_NAME' release."
exit_on_error "Build failed for '$APK_VERSION_TAG' release."
fi
echo "Validating APKs"
@ -58,8 +66,8 @@ jobs:
"${APK_BASENAME_PREFIX}_armeabi-v7a.apk" \
"${APK_BASENAME_PREFIX}_x86_64.apk" \
"${APK_BASENAME_PREFIX}_x86.apk" \
> sha256sums); then
exit_on_error "Generate sha25sums failed for '$RELEASE_VERSION_NAME' release."
> "${APK_BASENAME_PREFIX}_sha256sums"); then
exit_on_error "Generate sha25sums failed for '$APK_VERSION_TAG' release."
fi
echo "Attaching APKs to github release"
@ -70,7 +78,7 @@ jobs:
-a "$APK_DIR_PATH/${APK_BASENAME_PREFIX}_armeabi-v7a.apk" \
-a "$APK_DIR_PATH/${APK_BASENAME_PREFIX}_x86_64.apk" \
-a "$APK_DIR_PATH/${APK_BASENAME_PREFIX}_x86.apk" \
-a "$APK_DIR_PATH/sha256sums" \
-a "$APK_DIR_PATH/${APK_BASENAME_PREFIX}_sha256sums" \
"$RELEASE_VERSION_NAME"; then
exit_on_error "Attach APKs to release failed for '$RELEASE_VERSION_NAME' release."
exit_on_error "Attach APKs to release failed for '$APK_VERSION_TAG' release."
fi

View File

@ -4,6 +4,7 @@ on:
push:
branches:
- master
- 'github-releases/**'
pull_request:
branches:
- master
@ -11,16 +12,34 @@ on:
jobs:
build:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
package_variant: [ apt-android-7, apt-android-5 ]
steps:
- name: Clone repository
uses: actions/checkout@v2
uses: actions/checkout@v6
- name: Setup java 17
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: '17'
- name: Build APKs
shell: bash {0}
env:
PACKAGE_VARIANT: ${{ matrix.package_variant }}
run: |
exit_on_error() { echo "$1"; exit 1; }
echo "Setting vars"
if [ "$GITHUB_EVENT_NAME" == "pull_request" ]; then
GITHUB_SHA="${{ github.event.pull_request.head.sha }}" # Do not use last merge commit set in GITHUB_SHA
fi
# Set RELEASE_VERSION_NAME to "<CURRENT_VERSION_NAME>+<last_commit_hash>"
CURRENT_VERSION_NAME_REGEX='\s+versionName "([^"]+)"$'
CURRENT_VERSION_NAME="$(grep -m 1 -E "$CURRENT_VERSION_NAME_REGEX" ./app/build.gradle | sed -r "s/$CURRENT_VERSION_NAME_REGEX/\1/")"
@ -30,7 +49,7 @@ jobs:
fi
APK_DIR_PATH="./app/build/outputs/apk/debug"
APK_VERSION_TAG="$RELEASE_VERSION_NAME-github-debug" # Note the "-", GITHUB_SHA will already have "+" before it
APK_VERSION_TAG="$RELEASE_VERSION_NAME-${{ env.PACKAGE_VARIANT }}-github-debug" # Note the "-", GITHUB_SHA will already have "+" before it
APK_BASENAME_PREFIX="termux-app_$APK_VERSION_TAG"
# Used by attachment steps later
@ -38,11 +57,12 @@ jobs:
echo "APK_VERSION_TAG=$APK_VERSION_TAG" >> $GITHUB_ENV
echo "APK_BASENAME_PREFIX=$APK_BASENAME_PREFIX" >> $GITHUB_ENV
echo "Building APKs for '$RELEASE_VERSION_NAME' build"
echo "Building APKs for 'APK_VERSION_TAG' build"
export TERMUX_APP_VERSION_NAME="${RELEASE_VERSION_NAME/v/}" # Used by app/build.gradle
export TERMUX_APK_VERSION_TAG="$APK_VERSION_TAG" # Used by app/build.gradle
export TERMUX_PACKAGE_VARIANT="${{ env.PACKAGE_VARIANT }}" # Used by app/build.gradle
if ! ./gradlew assembleDebug; then
exit_on_error "Build failed for '$RELEASE_VERSION_NAME' build."
exit_on_error "Build failed for '$APK_VERSION_TAG' build."
fi
echo "Validating APKs"
@ -60,12 +80,12 @@ jobs:
"${APK_BASENAME_PREFIX}_armeabi-v7a.apk" \
"${APK_BASENAME_PREFIX}_x86_64.apk" \
"${APK_BASENAME_PREFIX}_x86.apk" \
> sha256sums); then
exit_on_error "Generate sha25sums failed for '$RELEASE_VERSION_NAME' release."
> "${APK_BASENAME_PREFIX}_sha256sums"); then
exit_on_error "Generate sha25sums failed for '$APK_VERSION_TAG' release."
fi
- name: Attach universal APK file
uses: actions/upload-artifact@v2
uses: actions/upload-artifact@v6
with:
name: ${{ env.APK_BASENAME_PREFIX }}_universal
path: |
@ -73,7 +93,7 @@ jobs:
${{ env.APK_DIR_PATH }}/output-metadata.json
- name: Attach arm64-v8a APK file
uses: actions/upload-artifact@v2
uses: actions/upload-artifact@v6
with:
name: ${{ env.APK_BASENAME_PREFIX }}_arm64-v8a
path: |
@ -81,7 +101,7 @@ jobs:
${{ env.APK_DIR_PATH }}/output-metadata.json
- name: Attach armeabi-v7a APK file
uses: actions/upload-artifact@v2
uses: actions/upload-artifact@v6
with:
name: ${{ env.APK_BASENAME_PREFIX }}_armeabi-v7a
path: |
@ -89,7 +109,7 @@ jobs:
${{ env.APK_DIR_PATH }}/output-metadata.json
- name: Attach x86_64 APK file
uses: actions/upload-artifact@v2
uses: actions/upload-artifact@v6
with:
name: ${{ env.APK_BASENAME_PREFIX }}_x86_64
path: |
@ -97,7 +117,7 @@ jobs:
${{ env.APK_DIR_PATH }}/output-metadata.json
- name: Attach x86 APK file
uses: actions/upload-artifact@v2
uses: actions/upload-artifact@v6
with:
name: ${{ env.APK_BASENAME_PREFIX }}_x86
path: |
@ -105,9 +125,9 @@ jobs:
${{ env.APK_DIR_PATH }}/output-metadata.json
- name: Attach sha256sums file
uses: actions/upload-artifact@v2
uses: actions/upload-artifact@v6
with:
name: sha256sums
name: ${{ env.APK_BASENAME_PREFIX }}_sha256sums
path: |
${{ env.APK_DIR_PATH }}/sha256sums
${{ env.APK_DIR_PATH }}/${{ env.APK_BASENAME_PREFIX }}_sha256sums
${{ env.APK_DIR_PATH }}/output-metadata.json

View File

@ -0,0 +1,23 @@
name: Automatic Dependency Submission
on:
push:
branches: [ 'master' ]
workflow_dispatch:
permissions:
contents: write
jobs:
dependency-submission:
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v6
- name: Setup Java
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: 17
- name: Generate and submit dependency graph
uses: gradle/actions/dependency-submission@v5

View File

@ -15,5 +15,5 @@ jobs:
name: "Validation"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: gradle/wrapper-validation-action@v1
- uses: actions/checkout@v6
- uses: gradle/actions/wrapper-validation@5

View File

@ -15,7 +15,12 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Clone repository
uses: actions/checkout@v2
uses: actions/checkout@v6
- name: Setup java 17
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: '17'
- name: Execute tests
run: |
./gradlew test

7
.gitignore vendored
View File

@ -11,9 +11,6 @@ release/
.cxx
*.zip
# Crashlytics configuations
com_crashlytics_export_strings.xml
# Local configuration file (sdk path, etc)
local.properties
@ -27,6 +24,10 @@ local.properties
.idea/
*.iml
# Vim
*.swo
*.swp
# OS-specific files
.DS_Store
.DS_Store?

View File

@ -2,5 +2,5 @@ The `termux/termux-app` repository is released under [GPLv3 only](https://www.gn
### Exceptions
- [Terminal Emulator for Android](https://github.com/jackpal/Android-Terminal-Emulator) code is used which is released under [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). Check [`terminal-view`](terminal-view) and [`terminal-emulator`](terminal-emulator) libraries.
- [Terminal Emulator for Android](https://github.com/jackpal/Android-Terminal-Emulator) code is used which is released under [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0) license. Check [`terminal-view`](terminal-view) and [`terminal-emulator`](terminal-emulator) libraries.
- Check [`termux-shared/LICENSE.md`](termux-shared/LICENSE.md) for `termux-shared` library related exceptions.

165
README.md
View File

@ -13,22 +13,23 @@ Note that this repository is for the app itself (the user interface and the term
Quick how-to about Termux package management is available at [Package Management](https://github.com/termux/termux-packages/wiki/Package-Management). It also has info on how to fix **`repository is under maintenance or down`** errors when running `apt` or `pkg` commands.
***
**@termux is looking for Termux Application maintainers for implementing new features, fixing bugs and reviewing pull requests since the current one (@fornwall) is inactive.**
Issue https://github.com/termux/termux-app/issues/1072 needs extra attention.
**We are looking for Termux Android application maintainers.**
***
### Contents
- [Termux App and Plugins](#Termux-App-and-Plugins)
- [Installation](#Installation)
- [Uninstallation](#Uninstallation)
- [Important Links](#Important-Links)
- [Debugging](#Debugging)
- [For Maintainers and Contributors](#For-Maintainers-and-Contributors)
- [Forking](#Forking)
**NOTICE: Termux may be unstable on Android 12+.** Android OS will kill any (phantom) processes greater than 32 (limit is for all apps combined) and also kill any processes using excessive CPU. You may get `[Process completed (signal 9) - press Enter]` message in the terminal without actually exiting the shell process yourself. Check the related issue [#2366](https://github.com/termux/termux-app/issues/2366), [issue tracker](https://issuetracker.google.com/u/1/issues/205156966), [phantom cached and empty processes docs](https://github.com/agnostic-apollo/Android-Docs/blob/master/en/docs/apps/processes/phantom-cached-and-empty-processes.md) and [this TLDR comment](https://github.com/termux/termux-app/issues/2366#issuecomment-1237468220) on how to disable trimming of phantom and excessive cpu usage processes. A proper docs page will be added later. An option to disable the killing should be available in Android 12L or 13, so upgrade at your own risk if you are on Android 11, specially if you are not rooted.
***
## Contents
- [Termux App and Plugins](#termux-app-and-plugins)
- [Installation](#installation)
- [Uninstallation](#uninstallation)
- [Important Links](#important-links)
- [Debugging](#debugging)
- [For Maintainers and Contributors](#for-maintainers-and-contributors)
- [Forking](#forking)
- [Sponsors and Funders](#sponsors-and-funders)
##
@ -49,13 +50,17 @@ The core [Termux](https://github.com/termux/termux-app) app comes with the follo
## Installation
Latest version is `v0.118.0`.
Latest version is `v0.118.3`.
Termux can be obtained through various sources listed below for **only** Android `>= 7`. Support was dropped for Android `5` and `6` on [2020-01-01](https://www.reddit.com/r/termux/comments/dnzdbs/end_of_android56_support_on_20200101/) at `v0.83`, old builds are available on [archive.org](https://archive.org/details/termux-repositories-legacy).
**NOTICE: It is highly recommended that you update to `v0.118.0` or higher ASAP for various bug fixes, including a critical world-readable vulnerability reported [here](https://termux.github.io/general/2022/02/15/termux-apps-vulnerability-disclosures.html). See [below](#google-play-store-experimental-branch) for information regarding Termux on Google Play.**
The APK files of different sources are signed with different signature keys. The `Termux` app and all its plugins use the same [`sharedUserId`](https://developer.android.com/guide/topics/manifest/manifest-element) `com.termux` and so all their APKs installed on a device must have been signed with the same signature key to work together and so they must all be installed from the same source. Do not attempt to mix them together, i.e do not try to install an app or plugin from `F-Droid` and another one from a different source like `Github`. Android Package Manager will also normally not allow installation of APKs with different signatures and you will get errors on installation like `App not installed`, `Failed to install due to an unknown error`, `INSTALL_FAILED_UPDATE_INCOMPATIBLE`, `INSTALL_FAILED_SHARED_USER_INCOMPATIBLE`, `signatures do not match previously installed version`, etc. This restriction can be bypassed with root or with custom roms.
Termux can be obtained through various sources listed below for **only** Android `>= 7` with full support for apps and packages.
If you wish to install from a different source, then you must **uninstall any and all existing Termux or its plugin app APKs** from your device first, then install all new APKs from the same new source. Check [Uninstallation](#Uninstallation) section for details. You may also want to consider [Backing up Termux](https://wiki.termux.com/wiki/Backing_up_Termux) before the uninstallation so that you can restore it after re-installing from Termux different source.
Support for both app and packages was dropped for Android `5` and `6` on [2020-01-01](https://www.reddit.com/r/termux/comments/dnzdbs/end_of_android56_support_on_20200101/) at `v0.83`, however it was re-added just for the app *without any support for package updates* on [2022-05-24](https://github.com/termux/termux-app/pull/2740) via the [GitHub](#github) sources. Check [here](https://github.com/termux/termux-app/wiki/Termux-on-android-5-or-6) for the details.
The APK files of different sources are signed with different signature keys. The `Termux` app and all its plugins use the same [`sharedUserId`](https://developer.android.com/guide/topics/manifest/manifest-element) `com.termux` and so all their APKs installed on a device must have been signed with the same signature key to work together and so they must all be installed from the same source. Do not attempt to mix them together, i.e do not try to install an app or plugin from `F-Droid` and another one from a different source like `GitHub`. Android Package Manager will also normally not allow installation of APKs with different signatures and you will get errors on installation like `App not installed`, `Failed to install due to an unknown error`, `INSTALL_FAILED_UPDATE_INCOMPATIBLE`, `INSTALL_FAILED_SHARED_USER_INCOMPATIBLE`, `signatures do not match previously installed version`, etc. This restriction can be bypassed with root or with custom roms.
If you wish to install from a different source, then you must **uninstall any and all existing Termux or its plugin app APKs** from your device first, then install all new APKs from the same new source. Check [Uninstallation](#uninstallation) section for details. You may also want to consider [Backing up Termux](https://wiki.termux.com/wiki/Backing_up_Termux) before the uninstallation so that you can restore it after re-installing from Termux different source.
In the following paragraphs, *"bootstrap"* refers to the minimal packages that are shipped with the `termux-app` itself to start a working shell environment. Its zips are built and released [here](https://github.com/termux/termux-packages/releases).
@ -65,67 +70,64 @@ Termux application can be obtained from `F-Droid` from [here](https://f-droid.or
You **do not** need to download the `F-Droid` app (via the `Download F-Droid` link) to install Termux. You can download the Termux APK directly from the site by clicking the `Download APK` link at the bottom of each version section.
It usually takes a few days (or even a week or more) for updates to be available on `F-Droid` once an update has been released on `Github`. The `F-Droid` releases are built and published by `F-Droid` once they [detect](https://gitlab.com/fdroid/fdroiddata/-/blob/master/metadata/com.termux.yml) a new `Github` release. The Termux maintainers **do not** have any control over the building and publishing of the Termux apps on `F-Droid`. Moreover, the Termux maintainers also do not have access to the APK signing keys of `F-Droid` releases, so we cannot release an APK ourselves on `Github` that would be compatible with `F-Droid` releases.
It usually takes a few days (or even a week or more) for updates to be available on `F-Droid` once an update has been released on `GitHub`. The `F-Droid` releases are built and published by `F-Droid` once they [detect](https://gitlab.com/fdroid/fdroiddata/-/blob/master/metadata/com.termux.yml) a new `GitHub` release. The Termux maintainers **do not** have any control over the building and publishing of the Termux apps on `F-Droid`. Moreover, the Termux maintainers also do not have access to the APK signing keys of `F-Droid` releases, so we cannot release an APK ourselves on `GitHub` that would be compatible with `F-Droid` releases.
The `F-Droid` app often may not notify you of updates and you will manually have to do a pull down swipe action in the `Updates` tab of the app for it to check updates. Make sure battery optimizations are disabled for the app, check https://dontkillmyapp.com/ for details on how to do that.
Only a universal APK is released, which will work on all supported architectures. The APK and bootstrap installation size will be `~180MB`. `F-Droid` does [not support](https://github.com/termux/termux-app/pull/1904) architecture specific APKs.
### Github
### GitHub
Termux application can be obtained on `Github` either from [`Github Releases`](https://github.com/termux/termux-app/releases) for version `>= 0.118.0` or from [`Github Build`](https://github.com/termux/termux-app/actions/workflows/debug_build.yml) action workflows.
Termux application can be obtained on `GitHub` either from [`GitHub Releases`](https://github.com/termux/termux-app/releases) for version `>= 0.118.0` or from [`GitHub Build Action`](https://github.com/termux/termux-app/actions/workflows/debug_build.yml?query=branch%3Amaster+event%3Apush) workflows. **For android `>= 7`, only install `apt-android-7` variants. For android `5` and `6`, only install `apt-android-5` variants.**
The APKs for `Github Releases` will be listed under `Assets` drop-down of a release. These are automatically attached when a new version is released.
The APKs for `GitHub Releases` will be listed under `Assets` drop-down of a release. These are automatically attached when a new version is released.
The APKs for `Github Build` action workflows will be listed under `Artifacts` section of a workflow run. These are created for each commit/push done to the repository and can be used by users who don't want to wait for releases and want to try out the latest features immediately or want to test their pull requests. Note that for action workflows, you need to be [**logged into a `Github` account**](https://github.com/login) for the `Artifacts` links to be enabled/clickable. If you are using the [`Github` app](https://github.com/mobile), then make sure to open workflow link in a browser like Chrome or Firefox that has your Github account logged in since the in-app browser may not be logged in.
The APKs for `GitHub Build` action workflows will be listed under `Artifacts` section of a workflow run. These are created for each commit/push done to the repository and can be used by users who don't want to wait for releases and want to try out the latest features immediately or want to test their pull requests. Note that for action workflows, you need to be [**logged into a `GitHub` account**](https://github.com/login) for the `Artifacts` links to be enabled/clickable. If you are using the [`GitHub` app](https://github.com/mobile), then make sure to open workflow link in a browser like Chrome or Firefox that has your GitHub account logged in since the in-app browser may not be logged in.
The APKs for both of these are [`debuggable`](https://developer.android.com/studio/debug) and are compatible with each other but they are not compatible with other sources.
Both universal and architecture specific APKs are released. The APK and bootstrap installation size will be `~180MB` if using universal and `~120MB` if using architecture specific. Check [here](https://github.com/termux/termux-app/issues/2153) for details.
### Google Play Store **(Deprecated)**
**Security warning**: APK files on GitHub are signed with a test key that has been [shared with community](https://github.com/termux/termux-app/blob/master/app/testkey_untrusted.jks). This IS NOT an official developer key and everyone can use it to generate releases for own testing. Be very careful when using Termux GitHub builds obtained elsewhere except https://github.com/termux/termux-app. Everyone is able to use it to forge a malicious Termux update installable over the GitHub build. Think twice about installing Termux builds distributed via Telegram or other social media. If your device get caught by malware, we will not be able to help you.
**Termux and its plugins are no longer updated on [Google Play Store](https://play.google.com/store/apps/details?id=com.termux) due to [android 10 issues](https://github.com/termux/termux-packages/wiki/Termux-and-Android-10) and have been deprecated.** The last version released for Android `>= 7` was `v0.101`. **It is highly recommended to not install Termux apps from Play Store any more.**
There are plans for **unpublishing** the Termux app and all its plugins on Play Store soon so that new users cannot install it and for **disabling** the Termux apps with updates so that existing users **cannot continue using outdated versions**. You are encouraged to move to `F-Droid` or `Github` builds as soon as possible.
You **will not need to buy plugins again** if you bought them on Play Store. All plugins are free on `F-Droid` and `Github`.
You can backup all your data under `$HOME/` and `$PREFIX/` before changing installation source, and then restore it afterwards, by following instructions at [Backing up Termux](https://wiki.termux.com/wiki/Backing_up_Termux) before the uninstallation.
There is currently no work being done to solve android `10` issues and *working* updates will not be resumed on Google Play Store any time soon. We will continue targeting sdk `28` for now. So there is not much point in staying on Play Store builds and waiting for updates to be resumed. If for some reason you don't want to move to `F-Droid` or `Github` sources for now, then at least check [Package Management](https://github.com/termux/termux-packages/wiki/Package-Management) to **change your mirror**, otherwise, you will get **`repository is under maintenance or down`** errors when running `apt` or `pkg` commands. After that, it is also **highly advisable** to run `pkg upgrade` command to update all packages to the latest available versions, or at least update `termux-tools` package with `pkg install termux-tools` command.
Note that by upgrading old packages to latest versions, like that of `python` may break your setups/scripts since they may not be compatible anymore. Moreover, you will not be able to downgrade the package versions since termux repos only keep the latest version and you will have to manually rebuild the old versions of the packages if required as per https://github.com/termux/termux-packages/wiki/Building-packages.
If you plan on staying on Play Store sources in future as well, then you may want to **disable automatic updates in Play Store** for Termux apps, since if and when updates to disable Termux apps are released, then **you will not be able to downgrade** and **will be forced** to move since apps won't work anymore. Only a way to backup `termux-app` data may be provided. The `termux-tools` [version `>= 0.135`](https://github.com/termux/termux-packages/pull/7493) will also show a banner at the top of the terminal saying `You are likely using a very old version of Termux, probably installed from the Google Play Store.`, you can remove it by running `rm -f /data/data/com.termux/files/usr/etc/motd-playstore` and restarting the app.
#### Why Disable?
The [test key](https://github.com/termux/termux-app/blob/master/app/testkey_untrusted.jks) shall not be used to impersonate @termux and can't be used for this anyway. This key is not trusted by us and it is quite easy to detect its use in user generated content.
<details>
<summary></summary>
<summary>Keystore information</summary>
- They should be disabled because deprecated things get removed and are not supported after some time, its the standard practice. It has been many months now since deprecation was announced and updates have not been released on Play Store since after `29 September 2020`.
```
Alias name: alias
Creation date: Oct 4, 2019
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=APK Signer, OU=Earth, O=Earth
Issuer: CN=APK Signer, OU=Earth, O=Earth
Serial number: 29be297b
Valid from: Wed Sep 04 02:03:24 EEST 2019 until: Tue Oct 26 02:03:24 EEST 2049
Certificate fingerprints:
SHA1: 51:79:55:EA:BF:69:FC:05:7C:41:C7:D3:79:DB:BC:EF:20:AD:85:F2
SHA256: B6:DA:01:48:0E:EF:D5:FB:F2:CD:37:71:B8:D1:02:1E:C7:91:30:4B:DD:6C:4B:F4:1D:3F:AA:BA:D4:8E:E5:E1
Signature algorithm name: SHA1withRSA (disabled)
Subject Public Key Algorithm: 2048-bit RSA key
Version: 3
```
- The new versions have lots of **new features and fixes** which you can mostly check out in the Changelog of [`Github Releases`](https://github.com/termux/termux-app/releases) that you may be missing out. Extra detail is usually provided in [commit messages](https://github.com/termux/termux-app/commits/master).
- Users on old versions are quite often reporting issues in multiple repositories and support forums that were **fixed months ago**, which we then have to deal with. The maintainers of @termux work in their free time, majorly for free, to work on development and provide support and having to re-re-deal with old issues takes away the already limited time from current work and is not possible to continue doing. Play Store page of `termux-app` has been filled with bad reviews of *"broken app"*, even though its clearly mentioned on the page that app is not being updated, yet users don't read and still install and report issues.
- Asking people to pay for plugins when the `termux-app` at installation time is broken due to repository issues and has bugs is unethical.
- Old versions don't have proper logging/debugging and crash report support. Reporting bugs without logs or detailed info is not helpful in solving them.
- It's also easier for us to solve package related issues and provide custom functionality with app updates, which can't be done if users continue using old versions. For example, the [bintray shudown](https://github.com/termux/termux-packages/wiki/Package-Management) causing package install/update failures for new Play Store users is/was not an issue for F-Droid users since it is being shipped with updated bootstrap and repo info, hence no reported issues from new F-Droid users.
</details>
##
### Google Play Store **(Experimental branch)**
There is currently a build of Termux available on Google Play for Android 11+ devices, with extensive adjustments in order to pass policy requirements there. This is under development and has missing functionality and bugs (see [here](https://github.com/termux-play-store/) for status updates) compared to the stable F-Droid build, which is why most users who can should still use F-Droid or GitHub build as mentioned above.
Currently, Google Play will try to update installations away from F-Droid ones. Updating will still fail as [sharedUserId](https://developer.android.com/guide/topics/manifest/manifest-element#uid) has been removed. A planned 0.118.1 F-Droid release will fix this by setting a higher version code than used for the PlayStore app. Meanwhile, to prevent Google Play from attempting to download and then fail to install the Google Play releases over existing installations, you can open the Termux apps pages on Google Play and then click on the 3 dots options button in the top right and then disable the Enable auto update toggle. However, the Termux apps updates will still show in the PlayStore app updates list.
If you want to help out with testing the Google Play build (or cannot install Termux from other sources), be aware that it's built from a separate repository (https://github.com/termux-play-store/) - be sure to report issues [there](https://github.com/termux-play-store/termux-issues/issues/new/choose), as any issues encountered might very well be specific to that repository.
## Uninstallation
Uninstallation may be required if a user doesn't want Termux installed in their device anymore or is switching to a different [install source](#Installation). You may also want to consider [Backing up Termux](https://wiki.termux.com/wiki/Backing_up_Termux) before the uninstallation.
Uninstallation may be required if a user doesn't want Termux installed in their device anymore or is switching to a different [install source](#installation). You may also want to consider [Backing up Termux](https://wiki.termux.com/wiki/Backing_up_Termux) before the uninstallation.
To uninstall Termux completely, you must uninstall **any and all existing Termux or its plugin app APKs** listed in [Termux App and Plugins](#Termux-App-and-Plugins).
To uninstall Termux completely, you must uninstall **any and all existing Termux or its plugin app APKs** listed in [Termux App and Plugins](#termux-app-and-plugins).
Go to `Android Settings` -> `Applications` and then look for those apps. You can also use the search feature if its available on your device and search `termux` in the applications list.
@ -142,10 +144,10 @@ All community links are available [here](https://wiki.termux.com/wiki/Community)
The main ones are the following.
- [Termux Reddit community](https://reddit.com/r/termux)
- [Termux Matrix Channel](https://matrix.to/#termux_termux:gitter.im)
- [Termux Dev Matrix Channel](https://matrix.to/#termux_dev:gitter.im)
- [Termux Twitter](https://twitter.com/termux/)
- [Termux Reports Email](mailto:termuxreports@groups.io)
- [Termux User Matrix Channel](https://matrix.to/#/#termux_termux:gitter.im) ([Gitter](https://gitter.im/termux/termux))
- [Termux Dev Matrix Channel](https://matrix.to/#/#termux_dev:gitter.im) ([Gitter](https://gitter.im/termux/dev))
- [Termux X (Twitter)](https://twitter.com/termuxdevs)
- [Termux Support Email](mailto:support@termux.dev)
### Wikis
@ -231,7 +233,21 @@ The main Termux constants are defined by [`TermuxConstants`](https://github.com/
Check [Termux Libraries](https://github.com/termux/termux-app/wiki/Termux-Libraries) for how to import termux libraries in plugin apps and [Forking and Local Development](https://github.com/termux/termux-app/wiki/Termux-Libraries#forking-and-local-development) for how to update termux libraries for plugins.
Commit messages **must** use [Conventional Commits](https://www.conventionalcommits.org) specs so that chagelogs can automatically be generated by the [`create-conventional-changelog`](https://github.com/termux/create-conventional-changelog) script, check its repo for further details on the spec. Use the following `types` as `Added: Add foo`, `Added|Fixed: Add foo and fix bar`, `Changed!: Change baz as a breaking change`, etc. You can optionally add a scope as well, like `Fixed(terminal): Some bug`. The space after `:` is necessary.
The `versionName` in `build.gradle` files of Termux and its plugin apps must follow the [semantic version `2.0.0` spec](https://semver.org/spec/v2.0.0.html) in the format `major.minor.patch(-prerelease)(+buildmetadata)`. When bumping `versionName` in `build.gradle` files and when creating a tag for new releases on GitHub, make sure to include the patch number as well, like `v0.1.0` instead of just `v0.1`. The `build.gradle` files and `attach_debug_apks_to_release` workflow validates the version as well and the build/attachment will fail if `versionName` does not follow the spec.
### Commit Messages Guidelines
Commit messages **must** use the [Conventional Commits](https://www.conventionalcommits.org) spec so that chagelogs as per the [Keep a Changelog](https://github.com/olivierlacan/keep-a-changelog) spec can automatically be generated by the [`create-conventional-changelog`](https://github.com/termux/create-conventional-changelog) script, check its repo for further details on the spec. **The first letter for `type` and `description` must be capital and description should be in the present tense.** The space after the colon `:` is necessary. For a breaking change, add an exclamation mark `!` before the colon `:`, so that it is highlighted in the chagelog automatically.
```
<type>[optional scope]: <description>
[optional body]
[optional footer(s)]
```
**Only the `types` listed below must be used exactly as they are used in the changelog headings.** For example, `Added: Add foo`, `Added|Fixed: Add foo and fix bar`, `Changed!: Change baz as a breaking change`, etc. You can optionally add a scope as well, like `Fixed(terminal): Fix some bug`. **Do not use anything else as type, like `add` instead of `Added`, etc.**
- **Added** for new features.
- **Changed** for changes in existing functionality.
@ -239,11 +255,6 @@ Commit messages **must** use [Conventional Commits](https://www.conventionalcomm
- **Removed** for now removed features.
- **Fixed** for any bug fixes.
- **Security** in case of vulnerabilities.
- **Docs** for updating documentation.
Changelogs for releases are generated based on [Keep a Changelog](https://github.com/olivierlacan/keep-a-changelog) specs.
The `versionName` in `build.gradle` files of Termux and its plugin apps must follow the [semantic version `2.0.0` spec](https://semver.org/spec/v2.0.0.html) in the format `major.minor.patch(-prerelease)(+buildmetadata)`. When bumping `versionName` in `build.gradle` files and when creating a tag for new releases on github, make sure to include the patch number as well, like `v0.1.0` instead of just `v0.1`. The `build.gradle` files and `attach_debug_apks_to_release` workflow validates the version as well and the build/attachment will fail if `versionName` does not follow the spec.
##
@ -251,6 +262,34 @@ The `versionName` in `build.gradle` files of Termux and its plugin apps must fol
## Forking
- Check [`TermuxConstants`](https://github.com/termux/termux-app/blob/master/termux-shared/src/main/java/com/termux/shared/termux/TermuxConstants.java) javadocs for instructions on what changes to make in the app to change package name.
- You also need to recompile bootstrap zip for the new package name. Check [here](https://github.com/termux/termux-app/issues/1983) and [here](https://github.com/termux/termux-app/issues/2081#issuecomment-865280111) for experimental work on it.
- You also need to recompile bootstrap zip for the new package name. Check [building bootstrap](https://github.com/termux/termux-packages/wiki/For-maintainers#build-bootstrap-archives), [here](https://github.com/termux/termux-app/issues/1983) and [here](https://github.com/termux/termux-app/issues/2081#issuecomment-865280111).
- Currently, not all plugins use `TermuxConstants` from `termux-shared` library and have hardcoded `com.termux` values and will need to be manually patched.
- If forking termux plugins, check [Forking and Local Development](https://github.com/termux/termux-app/wiki/Termux-Libraries#forking-and-local-development) for info on how to use termux libraries for plugins.
##
## Sponsors and Funders
[<img alt="GitHub Accelerator" width="25%" src="site/assets/sponsors/github.png" />](https://github.com)
*[GitHub Accelerator](https://github.com/accelerator) ([1](https://github.blog/2023-04-12-github-accelerator-our-first-cohort-and-whats-next))*
&nbsp;
[<img alt="GitHub Secure Open Source Fund" width="25%" src="site/assets/sponsors/github.png" />](https://github.com)
*[GitHub Secure Open Source Fund](https://resources.github.com/github-secure-open-source-fund) ([1](https://github.blog/open-source/maintainers/securing-the-supply-chain-at-scale-starting-with-71-important-open-source-projects), [2](https://termux.dev/en/posts/general/2025/08/11/termux-selected-for-github-secure-open-source-fund-session-2.html))*
&nbsp;
[<img alt="NLnet NGI Mobifree" width="25%" src="site/assets/sponsors/nlnet-ngi-mobifree.png" />](https://nlnet.nl/mobifree)
*[NLnet NGI Mobifree](https://nlnet.nl/mobifree) ([1](https://nlnet.nl/news/2024/20241111-NGI-Mobifree-grants.html), [2](https://termux.dev/en/posts/general/2024/11/11/termux-selected-for-nlnet-ngi-mobifree-grant.html))*
&nbsp;
[<img alt="Cloudflare" width="25%" src="site/assets/sponsors/cloudflare.png" />](https://www.cloudflare.com)
*[Cloudflare](https://www.cloudflare.com) ([1](https://packages-cf.termux.dev))*
&nbsp;
[<img alt="Warp" width="25%" src="https://github.com/warpdotdev/brand-assets/blob/640dffd347439bbcb535321ab36b7281cf4446c0/Github/Sponsor/Warp-Github-LG-03.png" />](https://www.warp.dev/?utm_source=github&utm_medium=readme&utm_campaign=termux)
[*Warp, built for coding with multiple AI agents*](https://www.warp.dev/?utm_source=github&utm_medium=readme&utm_campaign=termux)

1
SECURITY.md Normal file
View File

@ -0,0 +1 @@
Check https://termux.dev/security for info on Termux security policies and how to report vulnerabilities.

View File

@ -2,7 +2,19 @@ plugins {
id "com.android.application"
}
ext {
// The packageVariant defines the bootstrap variant that will be included in the app APK.
// This must be supported by com.termux.shared.termux.TermuxBootstrap.PackageVariant or app will
// crash at startup.
// Bootstrap of a different variant must not be manually installed by the user after app installation
// by replacing $PREFIX since app code is dependant on the variant used to build the APK.
// Currently supported values are: [ "apt-android-7" "apt-android-5" ]
packageVariant = System.getenv("TERMUX_PACKAGE_VARIANT") ?: "apt-android-7" // Default: "apt-android-7"
}
android {
namespace "com.termux"
compileSdkVersion project.properties.compileSdkVersion.toInteger()
ndkVersion = System.getenv("JITPACK_NDK_VERSION") ?: project.properties.ndkVersion
def appVersionName = System.getenv("TERMUX_APP_VERSION_NAME") ?: ""
@ -11,23 +23,24 @@ android {
def splitAPKsForReleaseBuilds = System.getenv("TERMUX_SPLIT_APKS_FOR_RELEASE_BUILDS") ?: "0" // F-Droid does not support split APKs #1904
dependencies {
implementation "androidx.annotation:annotation:1.3.0"
implementation "androidx.core:core:1.6.0"
implementation "androidx.drawerlayout:drawerlayout:1.1.1"
implementation "androidx.preference:preference:1.1.1"
implementation "androidx.annotation:annotation:1.9.0"
implementation "androidx.core:core:1.13.1"
implementation "androidx.drawerlayout:drawerlayout:1.2.0"
implementation "androidx.preference:preference:1.2.1"
implementation "androidx.viewpager:viewpager:1.0.0"
implementation "com.google.android.material:material:1.12.0"
implementation "com.google.guava:guava:24.1-jre"
implementation "io.noties.markwon:core:$markwonVersion"
implementation "io.noties.markwon:ext-strikethrough:$markwonVersion"
implementation "io.noties.markwon:linkify:$markwonVersion"
implementation "io.noties.markwon:recycler:$markwonVersion"
implementation 'com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava'
implementation project(":terminal-view")
implementation project(":termux-shared")
}
defaultConfig {
applicationId "com.termux"
minSdkVersion project.properties.minSdkVersion.toInteger()
targetSdkVersion project.properties.targetSdkVersion.toInteger()
versionCode 118
@ -36,6 +49,8 @@ android {
if (appVersionName) versionName = appVersionName
validateVersionName(versionName)
buildConfigField "String", "TERMUX_PACKAGE_VARIANT", "\"" + project.ext.packageVariant + "\"" // Used by TermuxApplication class
manifestPlaceholders.TERMUX_PACKAGE_NAME = "com.termux"
manifestPlaceholders.TERMUX_APP_NAME = "Termux"
manifestPlaceholders.TERMUX_API_APP_NAME = "Termux:API"
@ -64,7 +79,7 @@ android {
signingConfigs {
debug {
storeFile file('dev_keystore.jks')
storeFile file('testkey_untrusted.jks')
keyAlias 'alias'
storePassword 'xrj45yWGLbsO7W0v'
keyPassword 'xrj45yWGLbsO7W0v'
@ -84,6 +99,9 @@ android {
}
compileOptions {
// Flag to enable support for the new language APIs
coreLibraryDesugaringEnabled true
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
@ -94,7 +112,7 @@ android {
}
}
lintOptions {
lint {
disable 'ProtectedPermissions'
}
@ -114,19 +132,23 @@ android {
variant.outputs.all { output ->
if (variant.buildType.name == "debug") {
def abi = output.getFilter(com.android.build.OutputFile.ABI)
outputFileName = new File("termux-app_" + (apkVersionTag ? apkVersionTag : "debug") + "_" + (abi ? abi : "universal") + ".apk")
outputFileName = new File("termux-app_" + (apkVersionTag ? apkVersionTag : project.ext.packageVariant + "-" + "debug") + "_" + (abi ? abi : "universal") + ".apk")
} else if (variant.buildType.name == "release") {
def abi = output.getFilter(com.android.build.OutputFile.ABI)
outputFileName = new File("termux-app_" + (apkVersionTag ? apkVersionTag : "release") + "_" + (abi ? abi : "universal") + ".apk")
outputFileName = new File("termux-app_" + (apkVersionTag ? apkVersionTag : project.ext.packageVariant + "-" + "release") + "_" + (abi ? abi : "universal") + ".apk")
}
}
}
buildFeatures {
buildConfig true
}
}
dependencies {
testImplementation "junit:junit:4.13.2"
testImplementation "org.robolectric:robolectric:4.4"
testImplementation "org.robolectric:robolectric:4.10"
coreLibraryDesugaring "com.android.tools:desugar_jdk_libs:2.1.2"
}
task versionName {
@ -160,7 +182,7 @@ def downloadBootstrap(String arch, String expectedChecksum, String version) {
if (checksum == expectedChecksum) {
return
} else {
logger.quiet("Deleting old local file with wrong hash: " + localUrl)
logger.quiet("Deleting old local file with wrong hash: " + localUrl + ": expected: " + expectedChecksum + ", actual: " + checksum)
file.delete()
}
}
@ -195,11 +217,22 @@ clean {
task downloadBootstraps() {
doLast {
def version = "2022.01.07-r1"
downloadBootstrap("aarch64", "0fe6d0159d12fcb8baf7750ce9072b9b36f742662b02ad4da145ab85873614cd", version)
downloadBootstrap("arm", "0a6014e2ec3b7079524fee3caabd02be05bcb4add3c6cd9e5ad98408b428c717", version)
downloadBootstrap("i686", "c55369a9af1316dc3d99457aa23cce64b29c1e60e375159352c0d4b9cfed4ac6", version)
downloadBootstrap("x86_64", "e93a7c66d15edb7d1b5ceca906255c85ead35a8b6a52f93524e117cfb07e6778", version)
def packageVariant = project.ext.packageVariant
if (packageVariant == "apt-android-7") {
def version = "2022.04.28-r5" + "+" + packageVariant
downloadBootstrap("aarch64", "4a51a7eb209fe82efc24d52e3cccc13165f27377290687cb82038cbd8e948430", version)
downloadBootstrap("arm", "6459a786acbae50d4c8a36fa1c3de6a4dd2d482572f6d54f73274709bd627325", version)
downloadBootstrap("i686", "919d212b2f19e08600938db4079e794e947365022dbfd50ac342c50fcedcd7be", version)
downloadBootstrap("x86_64", "61b02fdc03ea4f5d9da8d8cf018013fdc6659e6da6cbf44e9b24d1c623580b89", version)
} else if (packageVariant == "apt-android-5") {
def version = "2022.04.28-r6" + "+" + packageVariant
downloadBootstrap("aarch64", "913609d439415c828c5640be1b0561467e539cb1c7080662decaaca2fb4820e7", version)
downloadBootstrap("arm", "26bfb45304c946170db69108e5eb6e3641aad751406ce106c80df80cad2eccf8", version)
downloadBootstrap("i686", "46dcfeb5eef67ba765498db9fe4c50dc4690805139aa0dd141a9d8ee0693cd27", version)
downloadBootstrap("x86_64", "615b590679ee6cd885b7fd2ff9473c845e920f9b422f790bb158c63fe42b8481", version)
} else {
throw new GradleException("Unsupported TERMUX_PACKAGE_VARIANT \"" + packageVariant + "\"")
}
}
}

View File

@ -10,8 +10,3 @@
-dontobfuscate
#-renamesourcefileattribute SourceFile
#-keepattributes SourceFile,LineNumberTable
# Temp fix for androidx.window:window:1.0.0-alpha09 imported by termux-shared
# https://issuetracker.google.com/issues/189001730
# https://android-review.googlesource.com/c/platform/frameworks/support/+/1757630
-keep class androidx.window.** { *; }

View File

@ -1,7 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.termux"
android:installLocation="internalOnly"
android:sharedUserId="${TERMUX_PACKAGE_NAME}"
android:sharedUserLabel="@string/shared_user_label">
@ -22,7 +21,9 @@
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" tools:ignore="ScopedStorage" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
@ -32,7 +33,9 @@
<uses-permission android:name="android.permission.DUMP" />
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" tools:ignore="ProtectedPermissions" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<application
android:name=".app.TermuxApplication"
@ -41,16 +44,21 @@
android:extractNativeLibs="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/application_name"
android:requestLegacyExternalStorage="true"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="false"
android:theme="@style/Theme.Termux">
android:theme="@style/Theme.TermuxApp.DayNight.DarkActionBar"
tools:targetApi="m">
<activity
android:name=".app.TermuxActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|uiMode|keyboard|keyboardHidden|navigation"
android:exported="true"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"
android:label="@string/application_name"
android:launchMode="singleTask"
android:resizeableActivity="true">
android:resizeableActivity="true"
android:theme="@style/Theme.TermuxActivity.DayNight.NoActionBar"
tools:targetApi="n">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
@ -69,6 +77,7 @@
<activity-alias
android:name=".HomeActivity"
android:exported="true"
android:targetActivity=".app.TermuxActivity">
<!-- Launch activity automatically on boot on Android Things devices -->
@ -86,27 +95,33 @@
android:label="@string/application_name"
android:parentActivityName=".app.TermuxActivity"
android:resizeableActivity="true"
android:theme="@android:style/Theme.Material.Light.DarkActionBar" />
tools:targetApi="n" />
<activity
android:name=".app.activities.SettingsActivity"
android:exported="true"
android:label="@string/title_activity_termux_settings"
android:theme="@style/Theme.AppCompat.Light.DarkActionBar" />
android:theme="@style/Theme.TermuxApp.DayNight.NoActionBar" />
<activity
android:name=".shared.activities.ReportActivity"
android:theme="@style/Theme.AppCompat.TermuxReportActivity"
android:documentLaunchMode="intoExisting"
/>
android:theme="@style/Theme.MarkdownViewActivity.DayNight"
android:documentLaunchMode="intoExisting" />
<activity
android:name=".filepicker.TermuxFileReceiverActivity"
android:name=".app.api.file.FileReceiverActivity"
android:excludeFromRecents="true"
android:label="@string/application_name"
android:exported="false"
android:noHistory="true"
android:resizeableActivity="true"
android:taskAffinity="${TERMUX_PACKAGE_NAME}.filereceiver">
android:taskAffinity="${TERMUX_PACKAGE_NAME}.filereceiver"
tools:targetApi="n">
</activity>
<activity-alias
android:name=".app.api.file.FileShareReceiverActivity"
android:exported="true"
android:targetActivity=".app.api.file.FileReceiverActivity">
<!-- Accept multiple file types when sending. -->
<intent-filter>
@ -122,6 +137,13 @@
<data android:mimeType="text/*" />
<data android:mimeType="video/*" />
</intent-filter>
</activity-alias>
<activity-alias
android:name=".app.api.file.FileViewReceiverActivity"
android:exported="true"
android:targetActivity=".app.api.file.FileReceiverActivity">
<!-- Accept multiple file types to let Termux be usable as generic file viewer. -->
<intent-filter tools:ignore="AppLinkUrlError">
<action android:name="android.intent.action.VIEW" />
@ -134,8 +156,7 @@
<data android:mimeType="text/*" />
<data android:mimeType="video/*" />
</intent-filter>
</activity>
</activity-alias>
<provider
android:name=".filepicker.TermuxDocumentsProvider"
@ -156,9 +177,21 @@
android:permission="${TERMUX_PACKAGE_NAME}.permission.RUN_COMMAND" />
<receiver android:name=".app.TermuxOpenReceiver" android:exported="false" />
<receiver
android:name=".app.TermuxOpenReceiver"
android:exported="false" />
<receiver android:name=".shared.activities.ReportActivity$ReportActivityBroadcastReceiver" android:exported="false" />
<receiver
android:name=".app.event.SystemEventReceiver"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<receiver
android:name=".shared.activities.ReportActivity$ReportActivityBroadcastReceiver"
android:exported="false" />
<service
@ -180,13 +213,24 @@
<meta-data
android:name="android.max_aspect"
android:value="10.0" />
<!-- https://developer.samsung.com/samsung-dex/modify-optimizing.html -->
<!-- Version < 3.0. DeX Mode and Screen Mirroring support -->
<meta-data
android:name="com.sec.android.support.multiwindow"
android:name="com.samsung.android.keepalive.density"
android:value="true" />
<!-- Version >= 3.0. DeX Dual Mode support -->
<meta-data
android:name="com.samsung.android.multidisplay.keep_process_alive"
android:value="true" />
<meta-data
android:name="com.sec.android.support.multiwindow"
android:value="true" />
</application>
</manifest>

View File

@ -12,18 +12,19 @@ import android.os.IBinder;
import com.termux.R;
import com.termux.shared.data.DataUtils;
import com.termux.shared.data.IntentUtils;
import com.termux.shared.file.TermuxFileUtils;
import com.termux.shared.termux.plugins.TermuxPluginUtils;
import com.termux.shared.termux.file.TermuxFileUtils;
import com.termux.shared.file.filesystem.FileType;
import com.termux.shared.models.errors.Errno;
import com.termux.shared.models.errors.Error;
import com.termux.shared.errors.Errno;
import com.termux.shared.errors.Error;
import com.termux.shared.termux.TermuxConstants;
import com.termux.shared.termux.TermuxConstants.TERMUX_APP.RUN_COMMAND_SERVICE;
import com.termux.shared.termux.TermuxConstants.TERMUX_APP.TERMUX_SERVICE;
import com.termux.shared.file.FileUtils;
import com.termux.shared.logger.Logger;
import com.termux.shared.notification.NotificationUtils;
import com.termux.app.utils.PluginUtils;
import com.termux.shared.models.ExecutionCommand;
import com.termux.shared.shell.command.ExecutionCommand;
import com.termux.shared.shell.command.ExecutionCommand.Runner;
/**
* A service that receives {@link RUN_COMMAND_SERVICE#ACTION_RUN_COMMAND} intent from third party apps and
@ -62,6 +63,8 @@ public class RunCommandService extends Service {
// Run again in case service is already started and onCreate() is not called
runStartForeground();
Logger.logVerboseExtended(LOG_TAG, "Intent Received:\n" + IntentUtils.getIntentString(intent));
ExecutionCommand executionCommand = new ExecutionCommand();
executionCommand.pluginAPIHelp = this.getString(R.string.error_run_command_service_api_help, RUN_COMMAND_SERVICE.RUN_COMMAND_API_HELP_URL);
@ -72,7 +75,7 @@ public class RunCommandService extends Service {
if (!RUN_COMMAND_SERVICE.ACTION_RUN_COMMAND.equals(intent.getAction())) {
errmsg = this.getString(R.string.error_run_command_service_invalid_intent_action, intent.getAction());
executionCommand.setStateFailed(Errno.ERRNO_FAILED.getCode(), errmsg);
PluginUtils.processPluginExecutionCommandError(this, LOG_TAG, executionCommand, false);
TermuxPluginUtils.processPluginExecutionCommandError(this, LOG_TAG, executionCommand, false);
return stopService();
}
@ -100,9 +103,21 @@ public class RunCommandService extends Service {
executionCommand.stdin = IntentUtils.getStringExtraIfSet(intent, RUN_COMMAND_SERVICE.EXTRA_STDIN, null);
executionCommand.workingDirectory = IntentUtils.getStringExtraIfSet(intent, RUN_COMMAND_SERVICE.EXTRA_WORKDIR, null);
executionCommand.inBackground = intent.getBooleanExtra(RUN_COMMAND_SERVICE.EXTRA_BACKGROUND, false);
// If EXTRA_RUNNER is passed, use that, otherwise check EXTRA_BACKGROUND and default to Runner.TERMINAL_SESSION
executionCommand.runner = IntentUtils.getStringExtraIfSet(intent, RUN_COMMAND_SERVICE.EXTRA_RUNNER,
(intent.getBooleanExtra(RUN_COMMAND_SERVICE.EXTRA_BACKGROUND, false) ? Runner.APP_SHELL.getName() : Runner.TERMINAL_SESSION.getName()));
if (Runner.runnerOf(executionCommand.runner) == null) {
errmsg = this.getString(R.string.error_run_command_service_invalid_execution_command_runner, executionCommand.runner);
executionCommand.setStateFailed(Errno.ERRNO_FAILED.getCode(), errmsg);
TermuxPluginUtils.processPluginExecutionCommandError(this, LOG_TAG, executionCommand, false);
return stopService();
}
executionCommand.backgroundCustomLogLevel = IntentUtils.getIntegerExtraIfSet(intent, RUN_COMMAND_SERVICE.EXTRA_BACKGROUND_CUSTOM_LOG_LEVEL, null);
executionCommand.sessionAction = intent.getStringExtra(RUN_COMMAND_SERVICE.EXTRA_SESSION_ACTION);
executionCommand.shellName = IntentUtils.getStringExtraIfSet(intent, RUN_COMMAND_SERVICE.EXTRA_SHELL_NAME, null);
executionCommand.shellCreateMode = IntentUtils.getStringExtraIfSet(intent, RUN_COMMAND_SERVICE.EXTRA_SHELL_CREATE_MODE, null);
executionCommand.commandLabel = IntentUtils.getStringExtraIfSet(intent, RUN_COMMAND_SERVICE.EXTRA_COMMAND_LABEL, "RUN_COMMAND Execution Intent Command");
executionCommand.commandDescription = IntentUtils.getStringExtraIfSet(intent, RUN_COMMAND_SERVICE.EXTRA_COMMAND_DESCRIPTION, null);
executionCommand.commandHelp = IntentUtils.getStringExtraIfSet(intent, RUN_COMMAND_SERVICE.EXTRA_COMMAND_HELP, null);
@ -122,10 +137,10 @@ public class RunCommandService extends Service {
// user knows someone tried to run a command in termux context, since it may be malicious
// app or imported (tasker) plugin project and not the user himself. If a pending intent is
// also sent, then its creator is also logged and shown.
errmsg = PluginUtils.checkIfAllowExternalAppsPolicyIsViolated(this, LOG_TAG);
errmsg = TermuxPluginUtils.checkIfAllowExternalAppsPolicyIsViolated(this, LOG_TAG);
if (errmsg != null) {
executionCommand.setStateFailed(Errno.ERRNO_FAILED.getCode(), errmsg);
PluginUtils.processPluginExecutionCommandError(this, LOG_TAG, executionCommand, true);
TermuxPluginUtils.processPluginExecutionCommandError(this, LOG_TAG, executionCommand, true);
return stopService();
}
@ -135,7 +150,7 @@ public class RunCommandService extends Service {
if (executionCommand.executable == null || executionCommand.executable.isEmpty()) {
errmsg = this.getString(R.string.error_run_command_service_mandatory_extra_missing, RUN_COMMAND_SERVICE.EXTRA_COMMAND_PATH);
executionCommand.setStateFailed(Errno.ERRNO_FAILED.getCode(), errmsg);
PluginUtils.processPluginExecutionCommandError(this, LOG_TAG, executionCommand, false);
TermuxPluginUtils.processPluginExecutionCommandError(this, LOG_TAG, executionCommand, false);
return stopService();
}
@ -149,7 +164,7 @@ public class RunCommandService extends Service {
false);
if (error != null) {
executionCommand.setStateFailed(error);
PluginUtils.processPluginExecutionCommandError(this, LOG_TAG, executionCommand, false);
TermuxPluginUtils.processPluginExecutionCommandError(this, LOG_TAG, executionCommand, false);
return stopService();
}
@ -170,7 +185,7 @@ public class RunCommandService extends Service {
false, true);
if (error != null) {
executionCommand.setStateFailed(error);
PluginUtils.processPluginExecutionCommandError(this, LOG_TAG, executionCommand, false);
TermuxPluginUtils.processPluginExecutionCommandError(this, LOG_TAG, executionCommand, false);
return stopService();
}
}
@ -195,9 +210,11 @@ public class RunCommandService extends Service {
execIntent.putExtra(TERMUX_SERVICE.EXTRA_ARGUMENTS, executionCommand.arguments);
execIntent.putExtra(TERMUX_SERVICE.EXTRA_STDIN, executionCommand.stdin);
if (executionCommand.workingDirectory != null && !executionCommand.workingDirectory.isEmpty()) execIntent.putExtra(TERMUX_SERVICE.EXTRA_WORKDIR, executionCommand.workingDirectory);
execIntent.putExtra(TERMUX_SERVICE.EXTRA_BACKGROUND, executionCommand.inBackground);
execIntent.putExtra(TERMUX_SERVICE.EXTRA_RUNNER, executionCommand.runner);
execIntent.putExtra(TERMUX_SERVICE.EXTRA_BACKGROUND_CUSTOM_LOG_LEVEL, DataUtils.getStringFromInteger(executionCommand.backgroundCustomLogLevel, null));
execIntent.putExtra(TERMUX_SERVICE.EXTRA_SESSION_ACTION, executionCommand.sessionAction);
execIntent.putExtra(TERMUX_SERVICE.EXTRA_SHELL_NAME, executionCommand.shellName);
execIntent.putExtra(TERMUX_SERVICE.EXTRA_SHELL_CREATE_MODE, executionCommand.shellCreateMode);
execIntent.putExtra(TERMUX_SERVICE.EXTRA_COMMAND_LABEL, executionCommand.commandLabel);
execIntent.putExtra(TERMUX_SERVICE.EXTRA_COMMAND_DESCRIPTION, executionCommand.commandDescription);
execIntent.putExtra(TERMUX_SERVICE.EXTRA_COMMAND_HELP, executionCommand.commandHelp);

View File

@ -1,8 +1,6 @@
package com.termux.app;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
@ -11,10 +9,7 @@ import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.view.ContextMenu;
@ -25,7 +20,6 @@ import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.autofill.AutofillManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
@ -33,36 +27,46 @@ import android.widget.RelativeLayout;
import android.widget.Toast;
import com.termux.R;
import com.termux.app.api.file.FileReceiverActivity;
import com.termux.app.terminal.TermuxActivityRootView;
import com.termux.app.terminal.TermuxTerminalSessionActivityClient;
import com.termux.app.terminal.io.TermuxTerminalExtraKeys;
import com.termux.shared.activities.ReportActivity;
import com.termux.shared.packages.PermissionUtils;
import com.termux.shared.activity.ActivityUtils;
import com.termux.shared.activity.media.AppCompatActivityUtils;
import com.termux.shared.data.IntentUtils;
import com.termux.shared.android.PermissionUtils;
import com.termux.shared.data.DataUtils;
import com.termux.shared.termux.TermuxConstants;
import com.termux.shared.termux.TermuxConstants.TERMUX_APP.TERMUX_ACTIVITY;
import com.termux.app.activities.HelpActivity;
import com.termux.app.activities.SettingsActivity;
import com.termux.shared.settings.preferences.TermuxAppSharedPreferences;
import com.termux.shared.termux.crash.TermuxCrashUtils;
import com.termux.shared.termux.settings.preferences.TermuxAppSharedPreferences;
import com.termux.app.terminal.TermuxSessionsListViewController;
import com.termux.app.terminal.io.TerminalToolbarViewPager;
import com.termux.app.terminal.TermuxTerminalSessionClient;
import com.termux.app.terminal.TermuxTerminalViewClient;
import com.termux.shared.terminal.io.extrakeys.ExtraKeysView;
import com.termux.app.settings.properties.TermuxAppSharedProperties;
import com.termux.shared.interact.TextInputDialogUtils;
import com.termux.shared.termux.extrakeys.ExtraKeysView;
import com.termux.shared.termux.interact.TextInputDialogUtils;
import com.termux.shared.logger.Logger;
import com.termux.shared.termux.TermuxUtils;
import com.termux.shared.termux.settings.properties.TermuxAppSharedProperties;
import com.termux.shared.termux.theme.TermuxThemeUtils;
import com.termux.shared.theme.NightMode;
import com.termux.shared.view.ViewUtils;
import com.termux.terminal.TerminalSession;
import com.termux.terminal.TerminalSessionClient;
import com.termux.app.utils.CrashUtils;
import com.termux.view.TerminalView;
import com.termux.view.TerminalViewClient;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.viewpager.widget.ViewPager;
import java.util.Arrays;
/**
* A terminal emulator activity.
* <p/>
@ -73,7 +77,7 @@ import androidx.viewpager.widget.ViewPager;
* </ul>
* about memory leaks.
*/
public final class TermuxActivity extends Activity implements ServiceConnection {
public final class TermuxActivity extends AppCompatActivity implements ServiceConnection {
/**
* The connection to the {@link TermuxService}. Requested in {@link #onCreate(Bundle)} with a call to
@ -97,7 +101,7 @@ public final class TermuxActivity extends Activity implements ServiceConnection
* The {@link TerminalSessionClient} interface implementation to allow for communication between
* {@link TerminalSession} and {@link TermuxActivity}.
*/
TermuxTerminalSessionClient mTermuxTerminalSessionClient;
TermuxTerminalSessionActivityClient mTermuxTerminalSessionActivityClient;
/**
* Termux app shared preferences manager.
@ -105,7 +109,7 @@ public final class TermuxActivity extends Activity implements ServiceConnection
private TermuxAppSharedPreferences mPreferences;
/**
* Termux app shared properties manager, loaded from termux.properties
* Termux app SharedProperties loaded from termux.properties
*/
private TermuxAppSharedProperties mProperties;
@ -124,6 +128,11 @@ public final class TermuxActivity extends Activity implements ServiceConnection
*/
ExtraKeysView mExtraKeysView;
/**
* The client for the {@link #mExtraKeysView}.
*/
TermuxTerminalExtraKeys mTermuxTerminalExtraKeys;
/**
* The termux sessions list controller.
*/
@ -148,7 +157,14 @@ public final class TermuxActivity extends Activity implements ServiceConnection
/**
* If onResume() was called after onCreate().
*/
private boolean isOnResumeAfterOnCreate = false;
private boolean mIsOnResumeAfterOnCreate = false;
/**
* If activity was restarted like due to call to {@link #recreate()} after receiving
* {@link TERMUX_ACTIVITY#ACTION_RELOAD_STYLE}, system dark night mode was changed or activity
* was killed by android.
*/
private boolean mIsActivityRecreated = false;
/**
* The {@link TermuxActivity} is in an invalid state and must not be run.
@ -157,12 +173,14 @@ public final class TermuxActivity extends Activity implements ServiceConnection
private int mNavBarHeight;
private int mTerminalToolbarDefaultHeight;
private float mTerminalToolbarDefaultHeight;
private static final int CONTEXT_MENU_SELECT_URL_ID = 0;
private static final int CONTEXT_MENU_SHARE_TRANSCRIPT_ID = 1;
private static final int CONTEXT_MENU_AUTOFILL_ID = 2;
private static final int CONTEXT_MENU_SHARE_SELECTED_TEXT = 10;
private static final int CONTEXT_MENU_AUTOFILL_USERNAME = 11;
private static final int CONTEXT_MENU_AUTOFILL_PASSWORD = 2;
private static final int CONTEXT_MENU_RESET_TERMINAL_ID = 3;
private static final int CONTEXT_MENU_KILL_PROCESS_ID = 4;
private static final int CONTEXT_MENU_STYLING_ID = 5;
@ -172,24 +190,24 @@ public final class TermuxActivity extends Activity implements ServiceConnection
private static final int CONTEXT_MENU_REPORT_ID = 9;
private static final String ARG_TERMINAL_TOOLBAR_TEXT_INPUT = "terminal_toolbar_text_input";
private static final String ARG_ACTIVITY_RECREATED = "activity_recreated";
private static final String LOG_TAG = "TermuxActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
Logger.logDebug(LOG_TAG, "onCreate");
isOnResumeAfterOnCreate = true;
mIsOnResumeAfterOnCreate = true;
// Check if a crash happened on last run of the app and show a
// notification with the crash details if it did
CrashUtils.notifyAppCrashOnLastRun(this, LOG_TAG);
if (savedInstanceState != null)
mIsActivityRecreated = savedInstanceState.getBoolean(ARG_ACTIVITY_RECREATED, false);
// Delete ReportInfo serialized object files from cache older than 14 days
ReportActivity.deleteReportInfoFilesOlderThanXDays(this, 14, false);
// Load termux shared properties
mProperties = new TermuxAppSharedProperties(this);
// Load Termux app SharedProperties from disk
mProperties = TermuxAppSharedProperties.getProperties();
reloadProperties();
setActivityTheme();
@ -223,8 +241,6 @@ public final class TermuxActivity extends Activity implements ServiceConnection
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
setDrawerTheme();
setTermuxTerminalViewAndClients();
setTerminalToolbarView(savedInstanceState);
@ -237,14 +253,26 @@ public final class TermuxActivity extends Activity implements ServiceConnection
registerForContextMenu(mTerminalView);
// Start the {@link TermuxService} and make it run regardless of who is bound to it
Intent serviceIntent = new Intent(this, TermuxService.class);
startService(serviceIntent);
FileReceiverActivity.updateFileReceiverActivityComponentsState(this);
// Attempt to bind to the service, this will call the {@link #onServiceConnected(ComponentName, IBinder)}
// callback if it succeeds.
if (!bindService(serviceIntent, this, 0))
throw new RuntimeException("bindService() failed");
try {
// Start the {@link TermuxService} and make it run regardless of who is bound to it
Intent serviceIntent = new Intent(this, TermuxService.class);
startService(serviceIntent);
// Attempt to bind to the service, this will call the {@link #onServiceConnected(ComponentName, IBinder)}
// callback if it succeeds.
if (!bindService(serviceIntent, this, 0))
throw new RuntimeException("bindService() failed");
} catch (Exception e) {
Logger.logStackTraceWithMessage(LOG_TAG,"TermuxActivity failed to start TermuxService", e);
Logger.showToast(this,
getString(e.getMessage() != null && e.getMessage().contains("app is in background") ?
R.string.error_termux_service_start_failed_bg : R.string.error_termux_service_start_failed_general),
true);
mIsInvalidState = true;
return;
}
// Send the {@link TermuxConstants#BROADCAST_TERMUX_OPENED} broadcast to notify apps that Termux
// app has been opened.
@ -261,8 +289,8 @@ public final class TermuxActivity extends Activity implements ServiceConnection
mIsVisible = true;
if (mTermuxTerminalSessionClient != null)
mTermuxTerminalSessionClient.onStart();
if (mTermuxTerminalSessionActivityClient != null)
mTermuxTerminalSessionActivityClient.onStart();
if (mTermuxTerminalViewClient != null)
mTermuxTerminalViewClient.onStart();
@ -281,13 +309,17 @@ public final class TermuxActivity extends Activity implements ServiceConnection
if (mIsInvalidState) return;
if (mTermuxTerminalSessionClient != null)
mTermuxTerminalSessionClient.onResume();
if (mTermuxTerminalSessionActivityClient != null)
mTermuxTerminalSessionActivityClient.onResume();
if (mTermuxTerminalViewClient != null)
mTermuxTerminalViewClient.onResume();
isOnResumeAfterOnCreate = false;
// Check if a crash happened on last run of the app or if a plugin crashed and show a
// notification with the crash details if it did
TermuxCrashUtils.notifyAppCrashFromCrashLogFile(this, LOG_TAG);
mIsOnResumeAfterOnCreate = false;
}
@Override
@ -300,15 +332,15 @@ public final class TermuxActivity extends Activity implements ServiceConnection
mIsVisible = false;
if (mTermuxTerminalSessionClient != null)
mTermuxTerminalSessionClient.onStop();
if (mTermuxTerminalSessionActivityClient != null)
mTermuxTerminalSessionActivityClient.onStop();
if (mTermuxTerminalViewClient != null)
mTermuxTerminalViewClient.onStop();
removeTermuxActivityRootViewGlobalLayoutListener();
unregisterTermuxActivityBroadcastReceiever();
unregisterTermuxActivityBroadcastReceiver();
getDrawer().closeDrawers();
}
@ -335,8 +367,11 @@ public final class TermuxActivity extends Activity implements ServiceConnection
@Override
public void onSaveInstanceState(@NonNull Bundle savedInstanceState) {
Logger.logVerbose(LOG_TAG, "onSaveInstanceState");
super.onSaveInstanceState(savedInstanceState);
saveTerminalToolbarTextInput(savedInstanceState);
savedInstanceState.putBoolean(ARG_ACTIVITY_RECREATED, true);
}
@ -350,24 +385,25 @@ public final class TermuxActivity extends Activity implements ServiceConnection
*/
@Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
Logger.logDebug(LOG_TAG, "onServiceConnected");
mTermuxService = ((TermuxService.LocalBinder) service).service;
setTermuxSessionsListView();
final Intent intent = getIntent();
setIntent(null);
if (mTermuxService.isTermuxSessionsEmpty()) {
if (mIsVisible) {
TermuxInstaller.setupBootstrapIfNeeded(TermuxActivity.this, () -> {
if (mTermuxService == null) return; // Activity might have been destroyed.
try {
Bundle bundle = getIntent().getExtras();
boolean launchFailsafe = false;
if (bundle != null) {
launchFailsafe = bundle.getBoolean(TERMUX_ACTIVITY.EXTRA_FAILSAFE_SESSION, false);
if (intent != null && intent.getExtras() != null) {
launchFailsafe = intent.getExtras().getBoolean(TERMUX_ACTIVITY.EXTRA_FAILSAFE_SESSION, false);
}
mTermuxTerminalSessionClient.addNewSession(launchFailsafe, null);
mTermuxTerminalSessionActivityClient.addNewSession(launchFailsafe, null);
} catch (WindowManager.BadTokenException e) {
// Activity finished - ignore.
}
@ -377,23 +413,24 @@ public final class TermuxActivity extends Activity implements ServiceConnection
finishActivityIfNotFinishing();
}
} else {
Intent i = getIntent();
if (i != null && Intent.ACTION_RUN.equals(i.getAction())) {
// If termux was started from launcher "New session" shortcut and activity is recreated,
// then the original intent will be re-delivered, resulting in a new session being re-added
// each time.
if (!mIsActivityRecreated && intent != null && Intent.ACTION_RUN.equals(intent.getAction())) {
// Android 7.1 app shortcut from res/xml/shortcuts.xml.
boolean isFailSafe = i.getBooleanExtra(TERMUX_ACTIVITY.EXTRA_FAILSAFE_SESSION, false);
mTermuxTerminalSessionClient.addNewSession(isFailSafe, null);
boolean isFailSafe = intent.getBooleanExtra(TERMUX_ACTIVITY.EXTRA_FAILSAFE_SESSION, false);
mTermuxTerminalSessionActivityClient.addNewSession(isFailSafe, null);
} else {
mTermuxTerminalSessionClient.setCurrentSession(mTermuxTerminalSessionClient.getCurrentStoredSessionOrLast());
mTermuxTerminalSessionActivityClient.setCurrentSession(mTermuxTerminalSessionActivityClient.getCurrentStoredSessionOrLast());
}
}
// Update the {@link TerminalSession} and {@link TerminalEmulator} clients.
mTermuxService.setTermuxTerminalSessionClient(mTermuxTerminalSessionClient);
mTermuxService.setTermuxTerminalSessionClient(mTermuxTerminalSessionActivityClient);
}
@Override
public void onServiceDisconnected(ComponentName name) {
Logger.logDebug(LOG_TAG, "onServiceDisconnected");
// Respect being stopped from the {@link TermuxService} notification action.
@ -404,20 +441,24 @@ public final class TermuxActivity extends Activity implements ServiceConnection
private void setActivityTheme() {
if (mProperties.isUsingBlackUI()) {
this.setTheme(R.style.Theme_Termux_Black);
} else {
this.setTheme(R.style.Theme_Termux);
}
private void reloadProperties() {
mProperties.loadTermuxPropertiesFromDisk();
if (mTermuxTerminalViewClient != null)
mTermuxTerminalViewClient.onReloadProperties();
}
private void setDrawerTheme() {
if (mProperties.isUsingBlackUI()) {
findViewById(R.id.left_drawer).setBackgroundColor(ContextCompat.getColor(this,
android.R.color.background_dark));
((ImageButton) findViewById(R.id.settings_button)).setColorFilter(Color.WHITE);
}
private void setActivityTheme() {
// Update NightMode.APP_NIGHT_MODE
TermuxThemeUtils.setAppNightMode(mProperties.getNightMode());
// Set activity night mode. If NightMode.SYSTEM is set, then android will automatically
// trigger recreation of activity when uiMode/dark mode configuration is changed so that
// day or night theme takes affect.
AppCompatActivityUtils.setNightMode(this, NightMode.getAppNightMode().getName(), true);
}
private void setMargins() {
@ -442,8 +483,8 @@ public final class TermuxActivity extends Activity implements ServiceConnection
private void setTermuxTerminalViewAndClients() {
// Set termux terminal view and session clients
mTermuxTerminalSessionClient = new TermuxTerminalSessionClient(this);
mTermuxTerminalViewClient = new TermuxTerminalViewClient(this, mTermuxTerminalSessionClient);
mTermuxTerminalSessionActivityClient = new TermuxTerminalSessionActivityClient(this);
mTermuxTerminalViewClient = new TermuxTerminalViewClient(this, mTermuxTerminalSessionActivityClient);
// Set termux terminal view
mTerminalView = findViewById(R.id.terminal_view);
@ -452,8 +493,8 @@ public final class TermuxActivity extends Activity implements ServiceConnection
if (mTermuxTerminalViewClient != null)
mTermuxTerminalViewClient.onCreate();
if (mTermuxTerminalSessionClient != null)
mTermuxTerminalSessionClient.onCreate();
if (mTermuxTerminalSessionActivityClient != null)
mTermuxTerminalSessionActivityClient.onCreate();
}
private void setTermuxSessionsListView() {
@ -467,6 +508,9 @@ public final class TermuxActivity extends Activity implements ServiceConnection
private void setTerminalToolbarView(Bundle savedInstanceState) {
mTermuxTerminalExtraKeys = new TermuxTerminalExtraKeys(this, mTerminalView,
mTermuxTerminalViewClient, mTermuxTerminalSessionActivityClient);
final ViewPager terminalToolbarViewPager = getTerminalToolbarViewPager();
if (mPreferences.shouldShowTerminalToolbar()) terminalToolbarViewPager.setVisibility(View.VISIBLE);
@ -488,8 +532,8 @@ public final class TermuxActivity extends Activity implements ServiceConnection
if (terminalToolbarViewPager == null) return;
ViewGroup.LayoutParams layoutParams = terminalToolbarViewPager.getLayoutParams();
layoutParams.height = (int) Math.round(mTerminalToolbarDefaultHeight *
(mProperties.getExtraKeysInfo() == null ? 0 : mProperties.getExtraKeysInfo().getMatrix().length) *
layoutParams.height = Math.round(mTerminalToolbarDefaultHeight *
(mTermuxTerminalExtraKeys.getExtraKeysInfo() == null ? 0 : mTermuxTerminalExtraKeys.getExtraKeysInfo().getMatrix().length) *
mProperties.getTerminalToolbarHeightScaleFactor());
terminalToolbarViewPager.setLayoutParams(layoutParams);
}
@ -510,7 +554,7 @@ public final class TermuxActivity extends Activity implements ServiceConnection
private void saveTerminalToolbarTextInput(Bundle savedInstanceState) {
if (savedInstanceState == null) return;
final EditText textInputView = findViewById(R.id.terminal_toolbar_text_input);
final EditText textInputView = findViewById(R.id.terminal_toolbar_text_input);
if (textInputView != null) {
String textInput = textInputView.getText().toString();
if (!textInput.isEmpty()) savedInstanceState.putString(ARG_TERMINAL_TOOLBAR_TEXT_INPUT, textInput);
@ -522,17 +566,17 @@ public final class TermuxActivity extends Activity implements ServiceConnection
private void setSettingsButtonView() {
ImageButton settingsButton = findViewById(R.id.settings_button);
settingsButton.setOnClickListener(v -> {
startActivity(new Intent(this, SettingsActivity.class));
ActivityUtils.startActivity(this, new Intent(this, SettingsActivity.class));
});
}
private void setNewSessionButtonView() {
View newSessionButton = findViewById(R.id.new_session_button);
newSessionButton.setOnClickListener(v -> mTermuxTerminalSessionClient.addNewSession(false, null));
newSessionButton.setOnClickListener(v -> mTermuxTerminalSessionActivityClient.addNewSession(false, null));
newSessionButton.setOnLongClickListener(v -> {
TextInputDialogUtils.textInput(TermuxActivity.this, R.string.title_create_named_session, null,
R.string.action_create_named_session_confirm, text -> mTermuxTerminalSessionClient.addNewSession(false, text),
R.string.action_new_session_failsafe, text -> mTermuxTerminalSessionClient.addNewSession(true, text),
R.string.action_create_named_session_confirm, text -> mTermuxTerminalSessionActivityClient.addNewSession(false, text),
R.string.action_new_session_failsafe, text -> mTermuxTerminalSessionActivityClient.addNewSession(true, text),
-1, null, null);
return true;
});
@ -587,17 +631,16 @@ public final class TermuxActivity extends Activity implements ServiceConnection
TerminalSession currentSession = getCurrentSession();
if (currentSession == null) return;
boolean addAutoFillMenu = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
AutofillManager autofillManager = getSystemService(AutofillManager.class);
if (autofillManager != null && autofillManager.isEnabled()) {
addAutoFillMenu = true;
}
}
boolean autoFillEnabled = mTerminalView.isAutoFillEnabled();
menu.add(Menu.NONE, CONTEXT_MENU_SELECT_URL_ID, Menu.NONE, R.string.action_select_url);
menu.add(Menu.NONE, CONTEXT_MENU_SHARE_TRANSCRIPT_ID, Menu.NONE, R.string.action_share_transcript);
if (addAutoFillMenu) menu.add(Menu.NONE, CONTEXT_MENU_AUTOFILL_ID, Menu.NONE, R.string.action_autofill_password);
if (!DataUtils.isNullOrEmpty(mTerminalView.getStoredSelectedText()))
menu.add(Menu.NONE, CONTEXT_MENU_SHARE_SELECTED_TEXT, Menu.NONE, R.string.action_share_selected_text);
if (autoFillEnabled)
menu.add(Menu.NONE, CONTEXT_MENU_AUTOFILL_USERNAME, Menu.NONE, R.string.action_autofill_username);
if (autoFillEnabled)
menu.add(Menu.NONE, CONTEXT_MENU_AUTOFILL_PASSWORD, Menu.NONE, R.string.action_autofill_password);
menu.add(Menu.NONE, CONTEXT_MENU_RESET_TERMINAL_ID, Menu.NONE, R.string.action_reset_terminal);
menu.add(Menu.NONE, CONTEXT_MENU_KILL_PROCESS_ID, Menu.NONE, getResources().getString(R.string.action_kill_process, getCurrentSession().getPid())).setEnabled(currentSession.isRunning());
menu.add(Menu.NONE, CONTEXT_MENU_STYLING_ID, Menu.NONE, R.string.action_style_terminal);
@ -625,8 +668,14 @@ public final class TermuxActivity extends Activity implements ServiceConnection
case CONTEXT_MENU_SHARE_TRANSCRIPT_ID:
mTermuxTerminalViewClient.shareSessionTranscript();
return true;
case CONTEXT_MENU_AUTOFILL_ID:
requestAutoFill();
case CONTEXT_MENU_SHARE_SELECTED_TEXT:
mTermuxTerminalViewClient.shareSelectedText();
return true;
case CONTEXT_MENU_AUTOFILL_USERNAME:
mTerminalView.requestAutoFillUsername();
return true;
case CONTEXT_MENU_AUTOFILL_PASSWORD:
mTerminalView.requestAutoFillPassword();
return true;
case CONTEXT_MENU_RESET_TERMINAL_ID:
onResetTerminalSession(session);
@ -641,10 +690,10 @@ public final class TermuxActivity extends Activity implements ServiceConnection
toggleKeepScreenOn();
return true;
case CONTEXT_MENU_HELP_ID:
startActivity(new Intent(this, HelpActivity.class));
ActivityUtils.startActivity(this, new Intent(this, HelpActivity.class));
return true;
case CONTEXT_MENU_SETTINGS_ID:
startActivity(new Intent(this, SettingsActivity.class));
ActivityUtils.startActivity(this, new Intent(this, SettingsActivity.class));
return true;
case CONTEXT_MENU_REPORT_ID:
mTermuxTerminalViewClient.reportIssueFromTranscript();
@ -654,6 +703,13 @@ public final class TermuxActivity extends Activity implements ServiceConnection
}
}
@Override
public void onContextMenuClosed(Menu menu) {
super.onContextMenuClosed(menu);
// onContextMenuClosed() is triggered twice if back button is pressed to dismiss instead of tap for some reason
mTerminalView.onContextMenuClosed(menu);
}
private void showKillSessionDialog(TerminalSession session) {
if (session == null) return;
@ -673,21 +729,23 @@ public final class TermuxActivity extends Activity implements ServiceConnection
session.reset();
showToast(getResources().getString(R.string.msg_terminal_reset), true);
if (mTermuxTerminalSessionClient != null)
mTermuxTerminalSessionClient.onResetTerminalSession();
if (mTermuxTerminalSessionActivityClient != null)
mTermuxTerminalSessionActivityClient.onResetTerminalSession();
}
}
private void showStylingDialog() {
Intent stylingIntent = new Intent();
stylingIntent.setClassName(TermuxConstants.TERMUX_STYLING_PACKAGE_NAME, TermuxConstants.TERMUX_STYLING.TERMUX_STYLING_ACTIVITY_NAME);
stylingIntent.setClassName(TermuxConstants.TERMUX_STYLING_PACKAGE_NAME, TermuxConstants.TERMUX_STYLING_APP.TERMUX_STYLING_ACTIVITY_NAME);
try {
startActivity(stylingIntent);
} catch (ActivityNotFoundException | IllegalArgumentException e) {
// The startActivity() call is not documented to throw IllegalArgumentException.
// However, crash reporting shows that it sometimes does, so catch it here.
new AlertDialog.Builder(this).setMessage(getString(R.string.error_styling_not_installed))
.setPositiveButton(R.string.action_styling_install, (dialog, which) -> startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(TermuxConstants.TERMUX_STYLING_FDROID_PACKAGE_URL)))).setNegativeButton(android.R.string.cancel, null).show();
.setPositiveButton(R.string.action_styling_install,
(dialog, which) -> ActivityUtils.startActivity(this, new Intent(Intent.ACTION_VIEW, Uri.parse(TermuxConstants.TERMUX_STYLING_FDROID_PACKAGE_URL))))
.setNegativeButton(android.R.string.cancel, null).show();
}
}
private void toggleKeepScreenOn() {
@ -700,37 +758,52 @@ public final class TermuxActivity extends Activity implements ServiceConnection
}
}
private void requestAutoFill() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
AutofillManager autofillManager = getSystemService(AutofillManager.class);
if (autofillManager != null && autofillManager.isEnabled()) {
autofillManager.requestAutofill(mTerminalView);
}
}
}
/**
* For processes to access shared internal storage (/sdcard) we need this permission.
* For processes to access primary external storage (/sdcard, /storage/emulated/0, ~/storage/shared),
* termux needs to be granted legacy WRITE_EXTERNAL_STORAGE or MANAGE_EXTERNAL_STORAGE permissions
* if targeting targetSdkVersion 30 (android 11) and running on sdk 30 (android 11) and higher.
*/
public boolean ensureStoragePermissionGranted() {
if (PermissionUtils.checkPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
return true;
} else {
Logger.logInfo(LOG_TAG, "Storage permission not granted, requesting permission.");
PermissionUtils.requestPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE, PermissionUtils.REQUEST_GRANT_STORAGE_PERMISSION);
return false;
public void requestStoragePermission(boolean isPermissionCallback) {
new Thread() {
@Override
public void run() {
// Do not ask for permission again
int requestCode = isPermissionCallback ? -1 : PermissionUtils.REQUEST_GRANT_STORAGE_PERMISSION;
// If permission is granted, then also setup storage symlinks.
if(PermissionUtils.checkAndRequestLegacyOrManageExternalStoragePermission(
TermuxActivity.this, requestCode, !isPermissionCallback)) {
if (isPermissionCallback)
Logger.logInfoAndShowToast(TermuxActivity.this, LOG_TAG,
getString(com.termux.shared.R.string.msg_storage_permission_granted_on_request));
TermuxInstaller.setupStorageSymlinks(TermuxActivity.this);
} else {
if (isPermissionCallback)
Logger.logInfoAndShowToast(TermuxActivity.this, LOG_TAG,
getString(com.termux.shared.R.string.msg_storage_permission_not_granted_on_request));
}
}
}.start();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Logger.logVerbose(LOG_TAG, "onActivityResult: requestCode: " + requestCode + ", resultCode: " + resultCode + ", data: " + IntentUtils.getIntentString(data));
if (requestCode == PermissionUtils.REQUEST_GRANT_STORAGE_PERMISSION) {
requestStoragePermission(true);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == PermissionUtils.REQUEST_GRANT_STORAGE_PERMISSION && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Logger.logInfo(LOG_TAG, "Storage permission granted by user on request.");
TermuxInstaller.setupStorageSymlinks(this);
} else {
Logger.logInfo(LOG_TAG, "Storage permission denied by user on request.");
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Logger.logVerbose(LOG_TAG, "onRequestPermissionsResult: requestCode: " + requestCode + ", permissions: " + Arrays.toString(permissions) + ", grantResults: " + Arrays.toString(grantResults));
if (requestCode == PermissionUtils.REQUEST_GRANT_STORAGE_PERMISSION) {
requestStoragePermission(true);
}
}
@ -752,6 +825,10 @@ public final class TermuxActivity extends Activity implements ServiceConnection
return mExtraKeysView;
}
public TermuxTerminalExtraKeys getTermuxTerminalExtraKeys() {
return mTermuxTerminalExtraKeys;
}
public void setExtraKeysView(ExtraKeysView extraKeysView) {
mExtraKeysView = extraKeysView;
}
@ -765,6 +842,10 @@ public final class TermuxActivity extends Activity implements ServiceConnection
return (ViewPager) findViewById(R.id.terminal_toolbar_view_pager);
}
public float getTerminalToolbarDefaultHeight() {
return mTerminalToolbarDefaultHeight;
}
public boolean isTerminalViewSelected() {
return getTerminalToolbarViewPager().getCurrentItem() == 0;
}
@ -783,7 +864,11 @@ public final class TermuxActivity extends Activity implements ServiceConnection
}
public boolean isOnResumeAfterOnCreate() {
return isOnResumeAfterOnCreate;
return mIsOnResumeAfterOnCreate;
}
public boolean isActivityRecreated() {
return mIsActivityRecreated;
}
@ -800,8 +885,8 @@ public final class TermuxActivity extends Activity implements ServiceConnection
return mTermuxTerminalViewClient;
}
public TermuxTerminalSessionClient getTermuxTerminalSessionClient() {
return mTermuxTerminalSessionClient;
public TermuxTerminalSessionActivityClient getTermuxTerminalSessionClient() {
return mTermuxTerminalSessionActivityClient;
}
@Nullable
@ -823,25 +908,27 @@ public final class TermuxActivity extends Activity implements ServiceConnection
public static void updateTermuxActivityStyling(Context context) {
public static void updateTermuxActivityStyling(Context context, boolean recreateActivity) {
// Make sure that terminal styling is always applied.
Intent stylingIntent = new Intent(TERMUX_ACTIVITY.ACTION_RELOAD_STYLE);
stylingIntent.putExtra(TERMUX_ACTIVITY.EXTRA_RECREATE_ACTIVITY, recreateActivity);
context.sendBroadcast(stylingIntent);
}
private void registerTermuxActivityBroadcastReceiver() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(TERMUX_ACTIVITY.ACTION_REQUEST_PERMISSIONS);
intentFilter.addAction(TERMUX_ACTIVITY.ACTION_NOTIFY_APP_CRASH);
intentFilter.addAction(TERMUX_ACTIVITY.ACTION_RELOAD_STYLE);
intentFilter.addAction(TERMUX_ACTIVITY.ACTION_REQUEST_PERMISSIONS);
registerReceiver(mTermuxActivityBroadcastReceiver, intentFilter);
}
private void unregisterTermuxActivityBroadcastReceiever() {
private void unregisterTermuxActivityBroadcastReceiver() {
unregisterReceiver(mTermuxActivityBroadcastReceiver);
}
private void fixTermuxActivityBroadcastReceieverIntent(Intent intent) {
private void fixTermuxActivityBroadcastReceiverIntent(Intent intent) {
if (intent == null) return;
String extraReloadStyle = intent.getStringExtra(TERMUX_ACTIVITY.EXTRA_RELOAD_STYLE);
@ -857,17 +944,20 @@ public final class TermuxActivity extends Activity implements ServiceConnection
if (intent == null) return;
if (mIsVisible) {
fixTermuxActivityBroadcastReceieverIntent(intent);
fixTermuxActivityBroadcastReceiverIntent(intent);
switch (intent.getAction()) {
case TERMUX_ACTIVITY.ACTION_REQUEST_PERMISSIONS:
Logger.logDebug(LOG_TAG, "Received intent to request storage permissions");
if (ensureStoragePermissionGranted())
TermuxInstaller.setupStorageSymlinks(TermuxActivity.this);
case TERMUX_ACTIVITY.ACTION_NOTIFY_APP_CRASH:
Logger.logDebug(LOG_TAG, "Received intent to notify app crash");
TermuxCrashUtils.notifyAppCrashFromCrashLogFile(context, LOG_TAG);
return;
case TERMUX_ACTIVITY.ACTION_RELOAD_STYLE:
Logger.logDebug(LOG_TAG, "Received intent to reload styling");
reloadActivityStyling();
reloadActivityStyling(intent.getBooleanExtra(TERMUX_ACTIVITY.EXTRA_RECREATE_ACTIVITY, true));
return;
case TERMUX_ACTIVITY.ACTION_REQUEST_PERMISSIONS:
Logger.logDebug(LOG_TAG, "Received intent to request storage permissions");
requestStoragePermission(false);
return;
default:
}
@ -875,41 +965,43 @@ public final class TermuxActivity extends Activity implements ServiceConnection
}
}
private void reloadActivityStyling() {
if (mProperties!= null) {
mProperties.loadTermuxPropertiesFromDisk();
private void reloadActivityStyling(boolean recreateActivity) {
if (mProperties != null) {
reloadProperties();
if (mExtraKeysView != null) {
mExtraKeysView.setButtonTextAllCaps(mProperties.shouldExtraKeysTextBeAllCaps());
mExtraKeysView.reload(mProperties.getExtraKeysInfo());
mExtraKeysView.reload(mTermuxTerminalExtraKeys.getExtraKeysInfo(), mTerminalToolbarDefaultHeight);
}
// Update NightMode.APP_NIGHT_MODE
TermuxThemeUtils.setAppNightMode(mProperties.getNightMode());
}
setMargins();
setTerminalToolbarHeight();
if (mTermuxTerminalSessionClient != null)
mTermuxTerminalSessionClient.onReload();
FileReceiverActivity.updateFileReceiverActivityComponentsState(this);
if (mTermuxTerminalSessionActivityClient != null)
mTermuxTerminalSessionActivityClient.onReloadActivityStyling();
if (mTermuxTerminalViewClient != null)
mTermuxTerminalViewClient.onReload();
if (mTermuxService != null)
mTermuxService.setTerminalTranscriptRows();
mTermuxTerminalViewClient.onReloadActivityStyling();
// To change the activity and drawer theme, activity needs to be recreated.
// But this will destroy the activity, and will call the onCreate() again.
// We need to investigate if enabling this is wise, since all stored variables and
// views will be destroyed and bindService() will be called again. Extra keys input
// text will we restored since that has already been implemented. Terminal sessions
// and transcripts are also already preserved. Theme does change properly too.
// TermuxActivity.this.recreate();
// It will destroy the activity, including all stored variables and views, and onCreate()
// will be called again. Extra keys input text, terminal sessions and transcripts will be preserved.
if (recreateActivity) {
Logger.logDebug(LOG_TAG, "Recreating activity");
TermuxActivity.this.recreate();
}
}
public static void startTermuxActivity(@NonNull final Context context) {
context.startActivity(newInstance(context));
ActivityUtils.startActivity(context, newInstance(context));
}
public static Intent newInstance(@NonNull final Context context) {

View File

@ -1,29 +1,85 @@
package com.termux.app;
import android.app.Application;
import android.content.Context;
import com.termux.shared.crash.TermuxCrashUtils;
import com.termux.shared.settings.preferences.TermuxAppSharedPreferences;
import com.termux.BuildConfig;
import com.termux.shared.errors.Error;
import com.termux.shared.logger.Logger;
import com.termux.shared.termux.TermuxBootstrap;
import com.termux.shared.termux.TermuxConstants;
import com.termux.shared.termux.crash.TermuxCrashUtils;
import com.termux.shared.termux.file.TermuxFileUtils;
import com.termux.shared.termux.settings.preferences.TermuxAppSharedPreferences;
import com.termux.shared.termux.settings.properties.TermuxAppSharedProperties;
import com.termux.shared.termux.shell.command.environment.TermuxShellEnvironment;
import com.termux.shared.termux.shell.am.TermuxAmSocketServer;
import com.termux.shared.termux.shell.TermuxShellManager;
import com.termux.shared.termux.theme.TermuxThemeUtils;
public class TermuxApplication extends Application {
private static final String LOG_TAG = "TermuxApplication";
public void onCreate() {
super.onCreate();
// Set crash handler for the app
TermuxCrashUtils.setCrashHandler(this);
Context context = getApplicationContext();
// Set log level for the app
setLogLevel();
// Set crash handler for the app
TermuxCrashUtils.setDefaultCrashHandler(this);
// Set log config for the app
setLogConfig(context);
Logger.logDebug("Starting Application");
// Set TermuxBootstrap.TERMUX_APP_PACKAGE_MANAGER and TermuxBootstrap.TERMUX_APP_PACKAGE_VARIANT
TermuxBootstrap.setTermuxPackageManagerAndVariant(BuildConfig.TERMUX_PACKAGE_VARIANT);
// Init app wide SharedProperties loaded from termux.properties
TermuxAppSharedProperties properties = TermuxAppSharedProperties.init(context);
// Init app wide shell manager
TermuxShellManager shellManager = TermuxShellManager.init(context);
// Set NightMode.APP_NIGHT_MODE
TermuxThemeUtils.setAppNightMode(properties.getNightMode());
// Check and create termux files directory. If failed to access it like in case of secondary
// user or external sd card installation, then don't run files directory related code
Error error = TermuxFileUtils.isTermuxFilesDirectoryAccessible(this, true, true);
boolean isTermuxFilesDirectoryAccessible = error == null;
if (isTermuxFilesDirectoryAccessible) {
Logger.logInfo(LOG_TAG, "Termux files directory is accessible");
error = TermuxFileUtils.isAppsTermuxAppDirectoryAccessible(true, true);
if (error != null) {
Logger.logErrorExtended(LOG_TAG, "Create apps/termux-app directory failed\n" + error);
return;
}
// Setup termux-am-socket server
TermuxAmSocketServer.setupTermuxAmSocketServer(context);
} else {
Logger.logErrorExtended(LOG_TAG, "Termux files directory is not accessible\n" + error);
}
// Init TermuxShellEnvironment constants and caches after everything has been setup including termux-am-socket server
TermuxShellEnvironment.init(this);
if (isTermuxFilesDirectoryAccessible) {
TermuxShellEnvironment.writeEnvironmentToFile(this);
}
}
private void setLogLevel() {
public static void setLogConfig(Context context) {
Logger.setDefaultLogTag(TermuxConstants.TERMUX_APP_NAME);
// Load the log level from shared preferences and set it to the {@link Logger.CURRENT_LOG_LEVEL}
TermuxAppSharedPreferences preferences = TermuxAppSharedPreferences.build(getApplicationContext());
TermuxAppSharedPreferences preferences = TermuxAppSharedPreferences.build(context);
if (preferences == null) return;
preferences.setLogLevel(null, preferences.getLogLevel());
Logger.logDebug("Starting Application");
}
}
}

View File

@ -4,22 +4,24 @@ import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.system.Os;
import android.util.Pair;
import android.view.WindowManager;
import com.termux.R;
import com.termux.app.utils.CrashUtils;
import com.termux.shared.file.FileUtils;
import com.termux.shared.file.TermuxFileUtils;
import com.termux.shared.termux.crash.TermuxCrashUtils;
import com.termux.shared.termux.file.TermuxFileUtils;
import com.termux.shared.interact.MessageDialogUtils;
import com.termux.shared.logger.Logger;
import com.termux.shared.markdown.MarkdownUtils;
import com.termux.shared.models.errors.Error;
import com.termux.shared.packages.PackageUtils;
import com.termux.shared.errors.Error;
import com.termux.shared.android.PackageUtils;
import com.termux.shared.termux.TermuxConstants;
import com.termux.shared.termux.TermuxUtils;
import com.termux.shared.termux.shell.command.environment.TermuxShellEnvironment;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
@ -71,8 +73,9 @@ final class TermuxInstaller {
// Termux can only be run as the primary user (device owner) since only that
// account has the expected file system paths. Verify that:
if (!PackageUtils.isCurrentUserThePrimaryUser(activity)) {
bootstrapErrorMessage = activity.getString(R.string.bootstrap_error_not_primary_user_message, MarkdownUtils.getMarkdownCodeForString(TERMUX_PREFIX_DIR_PATH, false));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && !PackageUtils.isCurrentUserThePrimaryUser(activity)) {
bootstrapErrorMessage = activity.getString(R.string.bootstrap_error_not_primary_user_message,
MarkdownUtils.getMarkdownCodeForString(TERMUX_PREFIX_DIR_PATH, false));
Logger.logError(LOG_TAG, "isFilesDirectoryAccessible: " + isFilesDirectoryAccessible);
Logger.logError(LOG_TAG, bootstrapErrorMessage);
sendBootstrapCrashReportNotification(activity, bootstrapErrorMessage);
@ -83,7 +86,14 @@ final class TermuxInstaller {
}
if (!isFilesDirectoryAccessible) {
bootstrapErrorMessage = Error.getMinimalErrorString(filesDirectoryAccessibleError) + "\nTERMUX_FILES_DIR: " + MarkdownUtils.getMarkdownCodeForString(TermuxConstants.TERMUX_FILES_DIR_PATH, false);
bootstrapErrorMessage = Error.getMinimalErrorString(filesDirectoryAccessibleError);
//noinspection SdCardPath
if (PackageUtils.isAppInstalledOnExternalStorage(activity) &&
!TermuxConstants.TERMUX_FILES_DIR_PATH.equals(activity.getFilesDir().getAbsolutePath().replaceAll("^/data/user/0/", "/data/data/"))) {
bootstrapErrorMessage += "\n\n" + activity.getString(R.string.bootstrap_error_installed_on_portable_sd,
MarkdownUtils.getMarkdownCodeForString(TERMUX_PREFIX_DIR_PATH, false));
}
Logger.logError(LOG_TAG, bootstrapErrorMessage);
sendBootstrapCrashReportNotification(activity, bootstrapErrorMessage);
MessageDialogUtils.showMessage(activity,
@ -94,10 +104,8 @@ final class TermuxInstaller {
// If prefix directory exists, even if its a symlink to a valid directory and symlink is not broken/dangling
if (FileUtils.directoryFileExists(TERMUX_PREFIX_DIR_PATH, true)) {
File[] PREFIX_FILE_LIST = TERMUX_PREFIX_DIR.listFiles();
// If prefix directory is empty or only contains the tmp directory
if(PREFIX_FILE_LIST == null || PREFIX_FILE_LIST.length == 0 || (PREFIX_FILE_LIST.length == 1 && TermuxConstants.TERMUX_TMP_PREFIX_DIR_PATH.equals(PREFIX_FILE_LIST[0].getAbsolutePath()))) {
Logger.logInfo(LOG_TAG, "The termux prefix directory \"" + TERMUX_PREFIX_DIR_PATH + "\" exists but is empty or only contains the tmp directory.");
if (TermuxFileUtils.isTermuxPrefixDirectoryEmpty()) {
Logger.logInfo(LOG_TAG, "The termux prefix directory \"" + TERMUX_PREFIX_DIR_PATH + "\" exists but is empty or only contains specific unimportant files.");
} else {
whenDone.run();
return;
@ -209,6 +217,10 @@ final class TermuxInstaller {
}
Logger.logInfo(LOG_TAG, "Bootstrap packages installed successfully.");
// Recreate env file since termux prefix was wiped earlier
TermuxShellEnvironment.writeEnvironmentToFile(activity);
activity.runOnUiThread(whenDone);
} catch (final Exception e) {
@ -252,14 +264,19 @@ final class TermuxInstaller {
}
private static void sendBootstrapCrashReportNotification(Activity activity, String message) {
CrashUtils.sendCrashReportNotification(activity, LOG_TAG,
"## Bootstrap Error\n\n" + message + "\n\n" +
final String title = TermuxConstants.TERMUX_APP_NAME + " Bootstrap Error";
// Add info of all install Termux plugin apps as well since their target sdk or installation
// on external/portable sd card can affect Termux app files directory access or exec.
TermuxCrashUtils.sendCrashReportNotification(activity, LOG_TAG,
title, null, "## " + title + "\n\n" + message + "\n\n" +
TermuxUtils.getTermuxDebugMarkdownString(activity),
true, true);
true, false, TermuxUtils.AppInfoMode.TERMUX_AND_PLUGIN_PACKAGES, true);
}
static void setupStorageSymlinks(final Context context) {
final String LOG_TAG = "termux-storage";
final String title = TermuxConstants.TERMUX_APP_NAME + " Setup Storage Error";
Logger.logInfo(LOG_TAG, "Setting up storage symlinks.");
@ -273,15 +290,21 @@ final class TermuxInstaller {
if (error != null) {
Logger.logErrorAndShowToast(context, LOG_TAG, error.getMessage());
Logger.logErrorExtended(LOG_TAG, "Setup Storage Error\n" + error.toString());
CrashUtils.sendCrashReportNotification(context, LOG_TAG, "## Setup Storage Error\n\n" + Error.getErrorMarkdownString(error), true, true);
TermuxCrashUtils.sendCrashReportNotification(context, LOG_TAG, title, null,
"## " + title + "\n\n" + Error.getErrorMarkdownString(error),
true, false, TermuxUtils.AppInfoMode.TERMUX_PACKAGE, true);
return;
}
Logger.logInfo(LOG_TAG, "Setting up storage symlinks at ~/storage/shared, ~/storage/downloads, ~/storage/dcim, ~/storage/pictures, ~/storage/music and ~/storage/movies for directories in \"" + Environment.getExternalStorageDirectory().getAbsolutePath() + "\".");
// Get primary storage root "/storage/emulated/0" symlink
File sharedDir = Environment.getExternalStorageDirectory();
Os.symlink(sharedDir.getAbsolutePath(), new File(storageDir, "shared").getAbsolutePath());
File documentsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
Os.symlink(documentsDir.getAbsolutePath(), new File(storageDir, "documents").getAbsolutePath());
File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Os.symlink(downloadsDir.getAbsolutePath(), new File(storageDir, "downloads").getAbsolutePath());
@ -297,9 +320,25 @@ final class TermuxInstaller {
File moviesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
Os.symlink(moviesDir.getAbsolutePath(), new File(storageDir, "movies").getAbsolutePath());
final File[] dirs = context.getExternalFilesDirs(null);
if (dirs != null && dirs.length > 1) {
for (int i = 1; i < dirs.length; i++) {
File podcastsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PODCASTS);
Os.symlink(podcastsDir.getAbsolutePath(), new File(storageDir, "podcasts").getAbsolutePath());
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
File audiobooksDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_AUDIOBOOKS);
Os.symlink(audiobooksDir.getAbsolutePath(), new File(storageDir, "audiobooks").getAbsolutePath());
}
// Dir 0 should ideally be for primary storage
// https://cs.android.com/android/platform/superproject/+/android-12.0.0_r32:frameworks/base/core/java/android/app/ContextImpl.java;l=818
// https://cs.android.com/android/platform/superproject/+/android-12.0.0_r32:frameworks/base/core/java/android/os/Environment.java;l=219
// https://cs.android.com/android/platform/superproject/+/android-12.0.0_r32:frameworks/base/core/java/android/os/Environment.java;l=181
// https://cs.android.com/android/platform/superproject/+/android-12.0.0_r32:frameworks/base/services/core/java/com/android/server/StorageManagerService.java;l=3796
// https://cs.android.com/android/platform/superproject/+/android-7.0.0_r36:frameworks/base/services/core/java/com/android/server/MountService.java;l=3053
// Create "Android/data/com.termux" symlinks
File[] dirs = context.getExternalFilesDirs(null);
if (dirs != null && dirs.length > 0) {
for (int i = 0; i < dirs.length; i++) {
File dir = dirs[i];
if (dir == null) continue;
String symlinkName = "external-" + i;
@ -308,11 +347,25 @@ final class TermuxInstaller {
}
}
// Create "Android/media/com.termux" symlinks
dirs = context.getExternalMediaDirs();
if (dirs != null && dirs.length > 0) {
for (int i = 0; i < dirs.length; i++) {
File dir = dirs[i];
if (dir == null) continue;
String symlinkName = "media-" + i;
Logger.logInfo(LOG_TAG, "Setting up storage symlinks at ~/storage/" + symlinkName + " for \"" + dir.getAbsolutePath() + "\".");
Os.symlink(dir.getAbsolutePath(), new File(storageDir, symlinkName).getAbsolutePath());
}
}
Logger.logInfo(LOG_TAG, "Storage symlinks created successfully.");
} catch (Exception e) {
Logger.logErrorAndShowToast(context, LOG_TAG, e.getMessage());
Logger.logStackTraceWithMessage(LOG_TAG, "Setup Storage Error: Error setting up link", e);
CrashUtils.sendCrashReportNotification(context, LOG_TAG, "## Setup Storage Error\n\n" + Logger.getStackTracesMarkdownString(null, Logger.getStackTracesStringArray(e)), true, true);
TermuxCrashUtils.sendCrashReportNotification(context, LOG_TAG, title, null,
"## " + title + "\n\n" + Logger.getStackTracesMarkdownString(null, Logger.getStackTracesStringArray(e)),
true, false, TermuxUtils.AppInfoMode.TERMUX_PACKAGE, true);
}
}
}.start();

View File

@ -13,9 +13,12 @@ import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.webkit.MimeTypeMap;
import com.termux.app.utils.PluginUtils;
import com.termux.shared.termux.plugins.TermuxPluginUtils;
import com.termux.shared.data.DataUtils;
import com.termux.shared.data.IntentUtils;
import com.termux.shared.net.uri.UriUtils;
import com.termux.shared.logger.Logger;
import com.termux.shared.net.uri.UriScheme;
import com.termux.shared.termux.TermuxConstants;
import java.io.File;
@ -32,13 +35,13 @@ public class TermuxOpenReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
final Uri data = intent.getData();
if (data == null) {
Logger.logError(LOG_TAG, "termux-open: Called without intent data");
Logger.logError(LOG_TAG, "Called without intent data");
return;
}
Logger.logVerbose(LOG_TAG, "Intent Received:\n" + IntentUtils.getIntentString(intent));
Logger.logVerbose(LOG_TAG, "uri: \"" + data + "\", path: \"" + data.getPath() + "\", fragment: \"" + data.getFragment() + "\"");
final String filePath = data.getPath();
final String contentTypeExtra = intent.getStringExtra("content-type");
final boolean useChooser = intent.getBooleanExtra("chooser", false);
final String intentAction = intent.getAction() == null ? Intent.ACTION_VIEW : intent.getAction();
@ -52,8 +55,8 @@ public class TermuxOpenReceiver extends BroadcastReceiver {
break;
}
final boolean isExternalUrl = data.getScheme() != null && !data.getScheme().equals("file");
if (isExternalUrl) {
String scheme = data.getScheme();
if (scheme != null && !UriScheme.SCHEME_FILE.equals(scheme)) {
Intent urlIntent = new Intent(intentAction, data);
if (intentAction.equals(Intent.ACTION_SEND)) {
urlIntent.putExtra(Intent.EXTRA_TEXT, data.toString());
@ -65,14 +68,21 @@ public class TermuxOpenReceiver extends BroadcastReceiver {
try {
context.startActivity(urlIntent);
} catch (ActivityNotFoundException e) {
Logger.logError(LOG_TAG, "termux-open: No app handles the url " + data);
Logger.logError(LOG_TAG, "No app handles the url " + data);
}
return;
}
// Get full path including fragment (anything after last "#")
String filePath = UriUtils.getUriFilePathWithFragment(data);
if (DataUtils.isNullOrEmpty(filePath)) {
Logger.logError(LOG_TAG, "filePath is null or empty");
return;
}
final File fileToShare = new File(filePath);
if (!(fileToShare.isFile() && fileToShare.canRead())) {
Logger.logError(LOG_TAG, "termux-open: Not a readable file: '" + fileToShare.getAbsolutePath() + "'");
Logger.logError(LOG_TAG, "Not a readable file: '" + fileToShare.getAbsolutePath() + "'");
return;
}
@ -93,7 +103,8 @@ public class TermuxOpenReceiver extends BroadcastReceiver {
contentTypeToUse = contentTypeExtra;
}
Uri uriToShare = Uri.parse("content://" + TermuxConstants.TERMUX_FILE_SHARE_URI_AUTHORITY + fileToShare.getAbsolutePath());
// Do not create Uri with Uri.parse() and use Uri.Builder().path(), check UriUtils.getUriFilePath().
Uri uriToShare = UriUtils.getContentUri(TermuxConstants.TERMUX_FILE_SHARE_URI_AUTHORITY, fileToShare.getAbsolutePath());
if (Intent.ACTION_SEND.equals(intentAction)) {
sendIntent.putExtra(Intent.EXTRA_STREAM, uriToShare);
@ -109,7 +120,7 @@ public class TermuxOpenReceiver extends BroadcastReceiver {
try {
context.startActivity(sendIntent);
} catch (ActivityNotFoundException e) {
Logger.logError(LOG_TAG, "termux-open: No app handles the url " + data);
Logger.logError(LOG_TAG, "No app handles the url " + data);
}
}
@ -161,6 +172,13 @@ public class TermuxOpenReceiver extends BroadcastReceiver {
@Override
public String getType(@NonNull Uri uri) {
String path = uri.getLastPathSegment();
int extIndex = path.lastIndexOf('.') + 1;
if (extIndex > 0) {
MimeTypeMap mimeMap = MimeTypeMap.getSingleton();
String ext = path.substring(extIndex).toLowerCase();
return mimeMap.getMimeTypeFromExtension(ext);
}
return null;
}
@ -184,25 +202,25 @@ public class TermuxOpenReceiver extends BroadcastReceiver {
File file = new File(uri.getPath());
try {
String path = file.getCanonicalPath();
Logger.logDebug(LOG_TAG, "Open file request received for \"" + path + "\" with mode \"" + mode + "\"");
String callingPackageName = getCallingPackage();
Logger.logDebug(LOG_TAG, "Open file request received from " + callingPackageName + " for \"" + path + "\" with mode \"" + mode + "\"");
String storagePath = Environment.getExternalStorageDirectory().getCanonicalPath();
// See https://support.google.com/faqs/answer/7496913:
if (!(path.startsWith(TermuxConstants.TERMUX_FILES_DIR_PATH) || path.startsWith(storagePath))) {
throw new IllegalArgumentException("Invalid path: " + path);
}
// If "allow-external-apps" property to not set to "true", then throw exception
String errmsg = PluginUtils.checkIfAllowExternalAppsPolicyIsViolated(getContext(), LOG_TAG);
// If TermuxConstants.PROP_ALLOW_EXTERNAL_APPS property to not set to "true", then throw exception
String errmsg = TermuxPluginUtils.checkIfAllowExternalAppsPolicyIsViolated(getContext(), LOG_TAG);
if (errmsg != null) {
throw new IllegalArgumentException(errmsg);
}
// Do not allow apps with RUN_COMMAND permission to modify termux apps properties files,
// including allow-external-apps
if (TermuxConstants.TERMUX_PROPERTIES_PRIMARY_FILE_PATH.equals(path) ||
TermuxConstants.TERMUX_PROPERTIES_SECONDARY_FILE_PATH.equals(path) ||
TermuxConstants.TERMUX_FLOAT_PROPERTIES_PRIMARY_FILE_PATH.equals(path) ||
TermuxConstants.TERMUX_FLOAT_PROPERTIES_SECONDARY_FILE_PATH.equals(path)) {
// **DO NOT** allow these files to be modified by ContentProvider exposed to external
// apps, since they may silently modify the values for security properties like
// TermuxConstants.PROP_ALLOW_EXTERNAL_APPS set by users without their explicit consent.
if (TermuxConstants.TERMUX_PROPERTIES_FILE_PATHS_LIST.contains(path) ||
TermuxConstants.TERMUX_FLOAT_PROPERTIES_FILE_PATHS_LIST.contains(path)) {
mode = "r";
}

View File

@ -5,43 +5,46 @@ import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.provider.Settings;
import android.widget.ArrayAdapter;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.termux.R;
import com.termux.app.settings.properties.TermuxAppSharedProperties;
import com.termux.app.terminal.TermuxTerminalSessionClient;
import com.termux.app.utils.PluginUtils;
import com.termux.app.event.SystemEventReceiver;
import com.termux.app.terminal.TermuxTerminalSessionActivityClient;
import com.termux.app.terminal.TermuxTerminalSessionServiceClient;
import com.termux.shared.termux.plugins.TermuxPluginUtils;
import com.termux.shared.data.IntentUtils;
import com.termux.shared.models.errors.Errno;
import com.termux.shared.net.uri.UriUtils;
import com.termux.shared.errors.Errno;
import com.termux.shared.shell.ShellUtils;
import com.termux.shared.shell.TermuxShellEnvironmentClient;
import com.termux.shared.shell.TermuxShellUtils;
import com.termux.shared.shell.command.runner.app.AppShell;
import com.termux.shared.termux.settings.properties.TermuxAppSharedProperties;
import com.termux.shared.termux.shell.command.environment.TermuxShellEnvironment;
import com.termux.shared.termux.shell.TermuxShellUtils;
import com.termux.shared.termux.TermuxConstants;
import com.termux.shared.termux.TermuxConstants.TERMUX_APP.TERMUX_ACTIVITY;
import com.termux.shared.termux.TermuxConstants.TERMUX_APP.TERMUX_SERVICE;
import com.termux.shared.settings.preferences.TermuxAppSharedPreferences;
import com.termux.shared.shell.TermuxSession;
import com.termux.shared.terminal.TermuxTerminalSessionClientBase;
import com.termux.shared.termux.settings.preferences.TermuxAppSharedPreferences;
import com.termux.shared.termux.shell.TermuxShellManager;
import com.termux.shared.termux.shell.command.runner.terminal.TermuxSession;
import com.termux.shared.termux.terminal.TermuxTerminalSessionClientBase;
import com.termux.shared.logger.Logger;
import com.termux.shared.notification.NotificationUtils;
import com.termux.shared.packages.PermissionUtils;
import com.termux.shared.android.PermissionUtils;
import com.termux.shared.data.DataUtils;
import com.termux.shared.models.ExecutionCommand;
import com.termux.shared.shell.TermuxTask;
import com.termux.shared.shell.command.ExecutionCommand;
import com.termux.shared.shell.command.ExecutionCommand.Runner;
import com.termux.shared.shell.command.ExecutionCommand.ShellCreateMode;
import com.termux.terminal.TerminalEmulator;
import com.termux.terminal.TerminalSession;
import com.termux.terminal.TerminalSessionClient;
@ -50,8 +53,8 @@ import java.util.ArrayList;
import java.util.List;
/**
* A service holding a list of {@link TermuxSession} in {@link #mTermuxSessions} and background {@link TermuxTask}
* in {@link #mTermuxTasks}, showing a foreground notification while running so that it is not terminated.
* A service holding a list of {@link TermuxSession} in {@link TermuxShellManager#mTermuxSessions} and background {@link AppShell}
* in {@link TermuxShellManager#mTermuxTasks}, showing a foreground notification while running so that it is not terminated.
* The user interacts with the session through {@link TermuxActivity}, but this service may outlive
* the activity when the user or the system disposes of the activity. In that case the user may
* restart {@link TermuxActivity} later to yet again access the sessions.
@ -62,9 +65,7 @@ import java.util.List;
* Optionally may hold a wake and a wifi lock, in which case that is shown in the notification - see
* {@link #buildNotification()}.
*/
public final class TermuxService extends Service implements TermuxTask.TermuxTaskClient, TermuxSession.TermuxSessionClient {
private static int EXECUTION_ID = 1000;
public final class TermuxService extends Service implements AppShell.AppShellClient, TermuxSession.TermuxSessionClient {
/** This service is only bound from inside the same process and never uses IPC. */
class LocalBinder extends Binder {
@ -75,34 +76,27 @@ public final class TermuxService extends Service implements TermuxTask.TermuxTas
private final Handler mHandler = new Handler();
/**
* The foreground TermuxSessions which this service manages.
* Note that this list is observed by {@link TermuxActivity#mTermuxSessionListViewController},
* so any changes must be made on the UI thread and followed by a call to
* {@link ArrayAdapter#notifyDataSetChanged()} }.
*/
final List<TermuxSession> mTermuxSessions = new ArrayList<>();
/**
* The background TermuxTasks which this service manages.
*/
final List<TermuxTask> mTermuxTasks = new ArrayList<>();
/**
* The pending plugin ExecutionCommands that have yet to be processed by this service.
*/
final List<ExecutionCommand> mPendingPluginExecutionCommands = new ArrayList<>();
/** The full implementation of the {@link TerminalSessionClient} interface to be used by {@link TerminalSession}
* that holds activity references for activity related functions.
* Note that the service may often outlive the activity, so need to clear this reference.
*/
TermuxTerminalSessionClient mTermuxTerminalSessionClient;
private TermuxTerminalSessionActivityClient mTermuxTerminalSessionActivityClient;
/** The basic implementation of the {@link TerminalSessionClient} interface to be used by {@link TerminalSession}
* that does not hold activity references.
* that does not hold activity references and only a service reference.
*/
final TermuxTerminalSessionClientBase mTermuxTerminalSessionClientBase = new TermuxTerminalSessionClientBase();
private final TermuxTerminalSessionServiceClient mTermuxTerminalSessionServiceClient = new TermuxTerminalSessionServiceClient(this);
/**
* Termux app shared properties manager, loaded from termux.properties
*/
private TermuxAppSharedProperties mProperties;
/**
* Termux app shell manager
*/
private TermuxShellManager mShellManager;
/** The wake lock and wifi lock are always acquired and released together. */
private PowerManager.WakeLock mWakeLock;
@ -111,14 +105,21 @@ public final class TermuxService extends Service implements TermuxTask.TermuxTas
/** If the user has executed the {@link TERMUX_SERVICE#ACTION_STOP_SERVICE} intent. */
boolean mWantsToStop = false;
public Integer mTerminalTranscriptRows;
private static final String LOG_TAG = "TermuxService";
@Override
public void onCreate() {
Logger.logVerbose(LOG_TAG, "onCreate");
// Get Termux app SharedProperties without loading from disk since TermuxApplication handles
// load and TermuxActivity handles reloads
mProperties = TermuxAppSharedProperties.getProperties();
mShellManager = TermuxShellManager.getShellManager();
runStartForeground();
SystemEventReceiver.registerPackageUpdateEvents(this);
}
@SuppressLint("Wakelock")
@ -129,7 +130,11 @@ public final class TermuxService extends Service implements TermuxTask.TermuxTas
// Run again in case service is already started and onCreate() is not called
runStartForeground();
String action = intent.getAction();
String action = null;
if (intent != null) {
Logger.logVerboseExtended(LOG_TAG, "Intent Received:\n" + IntentUtils.getIntentString(intent));
action = intent.getAction();
}
if (action != null) {
switch (action) {
@ -169,6 +174,11 @@ public final class TermuxService extends Service implements TermuxTask.TermuxTas
actionReleaseWakeLock(false);
if (!mWantsToStop)
killAllTermuxExecutionCommands();
TermuxShellManager.onAppExit(this);
SystemEventReceiver.unregisterPackageUpdateEvents(this);
runStopForeground();
}
@ -185,7 +195,7 @@ public final class TermuxService extends Service implements TermuxTask.TermuxTas
// Since we cannot rely on {@link TermuxActivity.onDestroy()} to always complete,
// we unset clients here as well if it failed, so that we do not leave service and session
// clients with references to the activity.
if (mTermuxTerminalSessionClient != null)
if (mTermuxTerminalSessionActivityClient != null)
unsetTermuxTerminalSessionClient();
return false;
}
@ -253,28 +263,36 @@ public final class TermuxService extends Service implements TermuxTask.TermuxTas
private synchronized void killAllTermuxExecutionCommands() {
boolean processResult;
Logger.logDebug(LOG_TAG, "Killing TermuxSessions=" + mTermuxSessions.size() + ", TermuxTasks=" + mTermuxTasks.size() + ", PendingPluginExecutionCommands=" + mPendingPluginExecutionCommands.size());
Logger.logDebug(LOG_TAG, "Killing TermuxSessions=" + mShellManager.mTermuxSessions.size() +
", TermuxTasks=" + mShellManager.mTermuxTasks.size() +
", PendingPluginExecutionCommands=" + mShellManager.mPendingPluginExecutionCommands.size());
List<TermuxSession> termuxSessions = new ArrayList<>(mShellManager.mTermuxSessions);
List<AppShell> termuxTasks = new ArrayList<>(mShellManager.mTermuxTasks);
List<ExecutionCommand> pendingPluginExecutionCommands = new ArrayList<>(mShellManager.mPendingPluginExecutionCommands);
List<TermuxSession> termuxSessions = new ArrayList<>(mTermuxSessions);
for (int i = 0; i < termuxSessions.size(); i++) {
ExecutionCommand executionCommand = termuxSessions.get(i).getExecutionCommand();
processResult = mWantsToStop || executionCommand.isPluginExecutionCommandWithPendingResult();
termuxSessions.get(i).killIfExecuting(this, processResult);
if (!processResult)
mShellManager.mTermuxSessions.remove(termuxSessions.get(i));
}
List<TermuxTask> termuxTasks = new ArrayList<>(mTermuxTasks);
for (int i = 0; i < termuxTasks.size(); i++) {
ExecutionCommand executionCommand = termuxTasks.get(i).getExecutionCommand();
if (executionCommand.isPluginExecutionCommandWithPendingResult())
termuxTasks.get(i).killIfExecuting(this, true);
else
mShellManager.mTermuxTasks.remove(termuxTasks.get(i));
}
List<ExecutionCommand> pendingPluginExecutionCommands = new ArrayList<>(mPendingPluginExecutionCommands);
for (int i = 0; i < pendingPluginExecutionCommands.size(); i++) {
ExecutionCommand executionCommand = pendingPluginExecutionCommands.get(i);
if (!executionCommand.shouldNotProcessResults() && executionCommand.isPluginExecutionCommandWithPendingResult()) {
if (executionCommand.setStateFailed(Errno.ERRNO_CANCELLED.getCode(), this.getString(com.termux.shared.R.string.error_execution_cancelled))) {
PluginUtils.processPluginExecutionCommandResult(this, LOG_TAG, executionCommand);
TermuxPluginUtils.processPluginExecutionCommandResult(this, LOG_TAG, executionCommand);
}
}
}
@ -301,18 +319,8 @@ public final class TermuxService extends Service implements TermuxTask.TermuxTas
mWifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, TermuxConstants.TERMUX_APP_NAME.toLowerCase());
mWifiLock.acquire();
String packageName = getPackageName();
if (!pm.isIgnoringBatteryOptimizations(packageName)) {
Intent whitelist = new Intent();
whitelist.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
whitelist.setData(Uri.parse("package:" + packageName));
whitelist.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
startActivity(whitelist);
} catch (ActivityNotFoundException e) {
Logger.logStackTraceWithMessage(LOG_TAG, "Failed to call ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS", e);
}
if (!PermissionUtils.checkIfBatteryOptimizationsDisabled(this)) {
PermissionUtils.requestDisableBatteryOptimizations(this);
}
updateNotification();
@ -354,27 +362,41 @@ public final class TermuxService extends Service implements TermuxTask.TermuxTas
return;
}
ExecutionCommand executionCommand = new ExecutionCommand(getNextExecutionId());
ExecutionCommand executionCommand = new ExecutionCommand(TermuxShellManager.getNextShellId());
executionCommand.executableUri = intent.getData();
executionCommand.inBackground = intent.getBooleanExtra(TERMUX_SERVICE.EXTRA_BACKGROUND, false);
executionCommand.isPluginExecutionCommand = true;
// If EXTRA_RUNNER is passed, use that, otherwise check EXTRA_BACKGROUND and default to Runner.TERMINAL_SESSION
executionCommand.runner = IntentUtils.getStringExtraIfSet(intent, TERMUX_SERVICE.EXTRA_RUNNER,
(intent.getBooleanExtra(TERMUX_SERVICE.EXTRA_BACKGROUND, false) ? Runner.APP_SHELL.getName() : Runner.TERMINAL_SESSION.getName()));
if (Runner.runnerOf(executionCommand.runner) == null) {
String errmsg = this.getString(R.string.error_termux_service_invalid_execution_command_runner, executionCommand.runner);
executionCommand.setStateFailed(Errno.ERRNO_FAILED.getCode(), errmsg);
TermuxPluginUtils.processPluginExecutionCommandError(this, LOG_TAG, executionCommand, false);
return;
}
if (executionCommand.executableUri != null) {
executionCommand.executable = executionCommand.executableUri.getPath();
Logger.logVerbose(LOG_TAG, "uri: \"" + executionCommand.executableUri + "\", path: \"" + executionCommand.executableUri.getPath() + "\", fragment: \"" + executionCommand.executableUri.getFragment() + "\"");
// Get full path including fragment (anything after last "#")
executionCommand.executable = UriUtils.getUriFilePathWithFragment(executionCommand.executableUri);
executionCommand.arguments = IntentUtils.getStringArrayExtraIfSet(intent, TERMUX_SERVICE.EXTRA_ARGUMENTS, null);
if (executionCommand.inBackground)
if (Runner.APP_SHELL.equalsRunner(executionCommand.runner))
executionCommand.stdin = IntentUtils.getStringExtraIfSet(intent, TERMUX_SERVICE.EXTRA_STDIN, null);
executionCommand.backgroundCustomLogLevel = IntentUtils.getIntegerExtraIfSet(intent, TERMUX_SERVICE.EXTRA_BACKGROUND_CUSTOM_LOG_LEVEL, null);
executionCommand.backgroundCustomLogLevel = IntentUtils.getIntegerExtraIfSet(intent, TERMUX_SERVICE.EXTRA_BACKGROUND_CUSTOM_LOG_LEVEL, null);
}
executionCommand.workingDirectory = IntentUtils.getStringExtraIfSet(intent, TERMUX_SERVICE.EXTRA_WORKDIR, null);
executionCommand.isFailsafe = intent.getBooleanExtra(TERMUX_ACTIVITY.EXTRA_FAILSAFE_SESSION, false);
executionCommand.sessionAction = intent.getStringExtra(TERMUX_SERVICE.EXTRA_SESSION_ACTION);
executionCommand.shellName = IntentUtils.getStringExtraIfSet(intent, TERMUX_SERVICE.EXTRA_SHELL_NAME, null);
executionCommand.shellCreateMode = IntentUtils.getStringExtraIfSet(intent, TERMUX_SERVICE.EXTRA_SHELL_CREATE_MODE, null);
executionCommand.commandLabel = IntentUtils.getStringExtraIfSet(intent, TERMUX_SERVICE.EXTRA_COMMAND_LABEL, "Execution Intent Command");
executionCommand.commandDescription = IntentUtils.getStringExtraIfSet(intent, TERMUX_SERVICE.EXTRA_COMMAND_DESCRIPTION, null);
executionCommand.commandHelp = IntentUtils.getStringExtraIfSet(intent, TERMUX_SERVICE.EXTRA_COMMAND_HELP, null);
executionCommand.pluginAPIHelp = IntentUtils.getStringExtraIfSet(intent, TERMUX_SERVICE.EXTRA_PLUGIN_API_HELP, null);
executionCommand.isPluginExecutionCommand = true;
executionCommand.resultConfig.resultPendingIntent = intent.getParcelableExtra(TERMUX_SERVICE.EXTRA_PENDING_INTENT);
executionCommand.resultConfig.resultDirectoryPath = IntentUtils.getStringExtraIfSet(intent, TERMUX_SERVICE.EXTRA_RESULT_DIRECTORY, null);
if (executionCommand.resultConfig.resultDirectoryPath != null) {
@ -385,13 +407,20 @@ public final class TermuxService extends Service implements TermuxTask.TermuxTas
executionCommand.resultConfig.resultFilesSuffix = IntentUtils.getStringExtraIfSet(intent, TERMUX_SERVICE.EXTRA_RESULT_FILES_SUFFIX, null);
}
// Add the execution command to pending plugin execution commands list
mPendingPluginExecutionCommands.add(executionCommand);
if (executionCommand.shellCreateMode == null)
executionCommand.shellCreateMode = ShellCreateMode.ALWAYS.getMode();
if (executionCommand.inBackground) {
// Add the execution command to pending plugin execution commands list
mShellManager.mPendingPluginExecutionCommands.add(executionCommand);
if (Runner.APP_SHELL.equalsRunner(executionCommand.runner))
executeTermuxTaskCommand(executionCommand);
} else {
else if (Runner.TERMINAL_SESSION.equalsRunner(executionCommand.runner))
executeTermuxSessionCommand(executionCommand);
else {
String errmsg = getString(R.string.error_termux_service_unsupported_execution_command_runner, executionCommand.runner);
executionCommand.setStateFailed(Errno.ERRNO_FAILED.getCode(), errmsg);
TermuxPluginUtils.processPluginExecutionCommandError(this, LOG_TAG, executionCommand, false);
}
}
@ -399,62 +428,84 @@ public final class TermuxService extends Service implements TermuxTask.TermuxTas
/** Execute a shell command in background {@link TermuxTask}. */
/** Execute a shell command in background TermuxTask. */
private void executeTermuxTaskCommand(ExecutionCommand executionCommand) {
if (executionCommand == null) return;
Logger.logDebug(LOG_TAG, "Executing background \"" + executionCommand.getCommandIdAndLabelLogString() + "\" TermuxTask command");
TermuxTask newTermuxTask = createTermuxTask(executionCommand);
// Transform executable path to shell/session name, e.g. "/bin/do-something.sh" => "do-something.sh".
if (executionCommand.shellName == null && executionCommand.executable != null)
executionCommand.shellName = ShellUtils.getExecutableBasename(executionCommand.executable);
AppShell newTermuxTask = null;
ShellCreateMode shellCreateMode = processShellCreateMode(executionCommand);
if (shellCreateMode == null) return;
if (ShellCreateMode.NO_SHELL_WITH_NAME.equals(shellCreateMode)) {
newTermuxTask = getTermuxTaskForShellName(executionCommand.shellName);
if (newTermuxTask != null)
Logger.logVerbose(LOG_TAG, "Existing TermuxTask with \"" + executionCommand.shellName + "\" shell name found for shell create mode \"" + shellCreateMode.getMode() + "\"");
else
Logger.logVerbose(LOG_TAG, "No existing TermuxTask with \"" + executionCommand.shellName + "\" shell name found for shell create mode \"" + shellCreateMode.getMode() + "\"");
}
if (newTermuxTask == null)
newTermuxTask = createTermuxTask(executionCommand);
}
/** Create a {@link TermuxTask}. */
/** Create a TermuxTask. */
@Nullable
public TermuxTask createTermuxTask(String executablePath, String[] arguments, String stdin, String workingDirectory) {
return createTermuxTask(new ExecutionCommand(getNextExecutionId(), executablePath, arguments, stdin, workingDirectory, true, false));
public AppShell createTermuxTask(String executablePath, String[] arguments, String stdin, String workingDirectory) {
return createTermuxTask(new ExecutionCommand(TermuxShellManager.getNextShellId(), executablePath,
arguments, stdin, workingDirectory, Runner.APP_SHELL.getName(), false));
}
/** Create a {@link TermuxTask}. */
/** Create a TermuxTask. */
@Nullable
public synchronized TermuxTask createTermuxTask(ExecutionCommand executionCommand) {
public synchronized AppShell createTermuxTask(ExecutionCommand executionCommand) {
if (executionCommand == null) return null;
Logger.logDebug(LOG_TAG, "Creating \"" + executionCommand.getCommandIdAndLabelLogString() + "\" TermuxTask");
if (!executionCommand.inBackground) {
Logger.logDebug(LOG_TAG, "Ignoring a foreground execution command passed to createTermuxTask()");
if (!Runner.APP_SHELL.equalsRunner(executionCommand.runner)) {
Logger.logDebug(LOG_TAG, "Ignoring wrong runner \"" + executionCommand.runner + "\" command passed to createTermuxTask()");
return null;
}
executionCommand.setShellCommandShellEnvironment = true;
if (Logger.getLogLevel() >= Logger.LOG_LEVEL_VERBOSE)
Logger.logVerboseExtended(LOG_TAG, executionCommand.toString());
TermuxTask newTermuxTask = TermuxTask.execute(this, executionCommand, this, new TermuxShellEnvironmentClient(), false);
AppShell newTermuxTask = AppShell.execute(this, executionCommand, this,
new TermuxShellEnvironment(), null,false);
if (newTermuxTask == null) {
Logger.logError(LOG_TAG, "Failed to execute new TermuxTask command for:\n" + executionCommand.getCommandIdAndLabelLogString());
// If the execution command was started for a plugin, then process the error
if (executionCommand.isPluginExecutionCommand)
PluginUtils.processPluginExecutionCommandError(this, LOG_TAG, executionCommand, false);
else
Logger.logErrorExtended(LOG_TAG, executionCommand.toString());
TermuxPluginUtils.processPluginExecutionCommandError(this, LOG_TAG, executionCommand, false);
else {
Logger.logError(LOG_TAG, "Set log level to debug or higher to see error in logs");
Logger.logErrorPrivateExtended(LOG_TAG, executionCommand.toString());
}
return null;
}
mTermuxTasks.add(newTermuxTask);
mShellManager.mTermuxTasks.add(newTermuxTask);
// Remove the execution command from the pending plugin execution commands list since it has
// now been processed
if (executionCommand.isPluginExecutionCommand)
mPendingPluginExecutionCommands.remove(executionCommand);
mShellManager.mPendingPluginExecutionCommands.remove(executionCommand);
updateNotification();
return newTermuxTask;
}
/** Callback received when a {@link TermuxTask} finishes. */
/** Callback received when a TermuxTask finishes. */
@Override
public void onTermuxTaskExited(final TermuxTask termuxTask) {
public void onAppShellExited(final AppShell termuxTask) {
mHandler.post(() -> {
if (termuxTask != null) {
ExecutionCommand executionCommand = termuxTask.getExecutionCommand();
@ -463,9 +514,9 @@ public final class TermuxService extends Service implements TermuxTask.TermuxTas
// If the execution command was started for a plugin, then process the results
if (executionCommand != null && executionCommand.isPluginExecutionCommand)
PluginUtils.processPluginExecutionCommandResult(this, LOG_TAG, executionCommand);
TermuxPluginUtils.processPluginExecutionCommandResult(this, LOG_TAG, executionCommand);
mTermuxTasks.remove(termuxTask);
mShellManager.mTermuxTasks.remove(termuxTask);
}
updateNotification();
@ -482,14 +533,23 @@ public final class TermuxService extends Service implements TermuxTask.TermuxTas
Logger.logDebug(LOG_TAG, "Executing foreground \"" + executionCommand.getCommandIdAndLabelLogString() + "\" TermuxSession command");
String sessionName = null;
// Transform executable path to shell/session name, e.g. "/bin/do-something.sh" => "do-something.sh".
if (executionCommand.shellName == null && executionCommand.executable != null)
executionCommand.shellName = ShellUtils.getExecutableBasename(executionCommand.executable);
// Transform executable path to session name, e.g. "/bin/do-something.sh" => "do something.sh".
if (executionCommand.executable != null) {
sessionName = ShellUtils.getExecutableBasename(executionCommand.executable).replace('-', ' ');
TermuxSession newTermuxSession = null;
ShellCreateMode shellCreateMode = processShellCreateMode(executionCommand);
if (shellCreateMode == null) return;
if (ShellCreateMode.NO_SHELL_WITH_NAME.equals(shellCreateMode)) {
newTermuxSession = getTermuxSessionForShellName(executionCommand.shellName);
if (newTermuxSession != null)
Logger.logVerbose(LOG_TAG, "Existing TermuxSession with \"" + executionCommand.shellName + "\" shell name found for shell create mode \"" + shellCreateMode.getMode() + "\"");
else
Logger.logVerbose(LOG_TAG, "No existing TermuxSession with \"" + executionCommand.shellName + "\" shell name found for shell create mode \"" + shellCreateMode.getMode() + "\"");
}
TermuxSession newTermuxSession = createTermuxSession(executionCommand, sessionName);
if (newTermuxSession == null)
newTermuxSession = createTermuxSession(executionCommand);
if (newTermuxSession == null) return;
handleSessionAction(DataUtils.getIntFromString(executionCommand.sessionAction,
@ -499,57 +559,68 @@ public final class TermuxService extends Service implements TermuxTask.TermuxTas
/**
* Create a {@link TermuxSession}.
* Currently called by {@link TermuxTerminalSessionClient#addNewSession(boolean, String)} to add a new {@link TermuxSession}.
* Currently called by {@link TermuxTerminalSessionActivityClient#addNewSession(boolean, String)} to add a new {@link TermuxSession}.
*/
@Nullable
public TermuxSession createTermuxSession(String executablePath, String[] arguments, String stdin, String workingDirectory, boolean isFailSafe, String sessionName) {
return createTermuxSession(new ExecutionCommand(getNextExecutionId(), executablePath, arguments, stdin, workingDirectory, false, isFailSafe), sessionName);
public TermuxSession createTermuxSession(String executablePath, String[] arguments, String stdin,
String workingDirectory, boolean isFailSafe, String sessionName) {
ExecutionCommand executionCommand = new ExecutionCommand(TermuxShellManager.getNextShellId(),
executablePath, arguments, stdin, workingDirectory, Runner.TERMINAL_SESSION.getName(), isFailSafe);
executionCommand.shellName = sessionName;
return createTermuxSession(executionCommand);
}
/** Create a {@link TermuxSession}. */
@Nullable
public synchronized TermuxSession createTermuxSession(ExecutionCommand executionCommand, String sessionName) {
public synchronized TermuxSession createTermuxSession(ExecutionCommand executionCommand) {
if (executionCommand == null) return null;
Logger.logDebug(LOG_TAG, "Creating \"" + executionCommand.getCommandIdAndLabelLogString() + "\" TermuxSession");
if (executionCommand.inBackground) {
Logger.logDebug(LOG_TAG, "Ignoring a background execution command passed to createTermuxSession()");
if (!Runner.TERMINAL_SESSION.equalsRunner(executionCommand.runner)) {
Logger.logDebug(LOG_TAG, "Ignoring wrong runner \"" + executionCommand.runner + "\" command passed to createTermuxSession()");
return null;
}
executionCommand.setShellCommandShellEnvironment = true;
executionCommand.terminalTranscriptRows = mProperties.getTerminalTranscriptRows();
if (Logger.getLogLevel() >= Logger.LOG_LEVEL_VERBOSE)
Logger.logVerboseExtended(LOG_TAG, executionCommand.toString());
// If the execution command was started for a plugin, only then will the stdout be set
// Otherwise if command was manually started by the user like by adding a new terminal session,
// then no need to set stdout
executionCommand.terminalTranscriptRows = getTerminalTranscriptRows();
TermuxSession newTermuxSession = TermuxSession.execute(this, executionCommand, getTermuxTerminalSessionClient(), this, new TermuxShellEnvironmentClient(), sessionName, executionCommand.isPluginExecutionCommand);
TermuxSession newTermuxSession = TermuxSession.execute(this, executionCommand, getTermuxTerminalSessionClient(),
this, new TermuxShellEnvironment(), null, executionCommand.isPluginExecutionCommand);
if (newTermuxSession == null) {
Logger.logError(LOG_TAG, "Failed to execute new TermuxSession command for:\n" + executionCommand.getCommandIdAndLabelLogString());
// If the execution command was started for a plugin, then process the error
if (executionCommand.isPluginExecutionCommand)
PluginUtils.processPluginExecutionCommandError(this, LOG_TAG, executionCommand, false);
else
Logger.logErrorExtended(LOG_TAG, executionCommand.toString());
TermuxPluginUtils.processPluginExecutionCommandError(this, LOG_TAG, executionCommand, false);
else {
Logger.logError(LOG_TAG, "Set log level to debug or higher to see error in logs");
Logger.logErrorPrivateExtended(LOG_TAG, executionCommand.toString());
}
return null;
}
mTermuxSessions.add(newTermuxSession);
mShellManager.mTermuxSessions.add(newTermuxSession);
// Remove the execution command from the pending plugin execution commands list since it has
// now been processed
if (executionCommand.isPluginExecutionCommand)
mPendingPluginExecutionCommands.remove(executionCommand);
mShellManager.mPendingPluginExecutionCommands.remove(executionCommand);
// Notify {@link TermuxSessionsListViewController} that sessions list has been updated if
// activity in is foreground
if (mTermuxTerminalSessionClient != null)
mTermuxTerminalSessionClient.termuxSessionListNotifyUpdated();
if (mTermuxTerminalSessionActivityClient != null)
mTermuxTerminalSessionActivityClient.termuxSessionListNotifyUpdated();
updateNotification();
TermuxActivity.updateTermuxActivityStyling(this);
// No need to recreate the activity since it likely just started and theme should already have applied
TermuxActivity.updateTermuxActivityStyling(this, false);
return newTermuxSession;
}
@ -559,7 +630,7 @@ public final class TermuxService extends Service implements TermuxTask.TermuxTas
int index = getIndexOfSession(sessionToRemove);
if (index >= 0)
mTermuxSessions.get(index).finish();
mShellManager.mTermuxSessions.get(index).finish();
return index;
}
@ -574,36 +645,41 @@ public final class TermuxService extends Service implements TermuxTask.TermuxTas
// If the execution command was started for a plugin, then process the results
if (executionCommand != null && executionCommand.isPluginExecutionCommand)
PluginUtils.processPluginExecutionCommandResult(this, LOG_TAG, executionCommand);
TermuxPluginUtils.processPluginExecutionCommandResult(this, LOG_TAG, executionCommand);
mTermuxSessions.remove(termuxSession);
mShellManager.mTermuxSessions.remove(termuxSession);
// Notify {@link TermuxSessionsListViewController} that sessions list has been updated if
// activity in is foreground
if (mTermuxTerminalSessionClient != null)
mTermuxTerminalSessionClient.termuxSessionListNotifyUpdated();
if (mTermuxTerminalSessionActivityClient != null)
mTermuxTerminalSessionActivityClient.termuxSessionListNotifyUpdated();
}
updateNotification();
}
/** Get the terminal transcript rows to be used for new {@link TermuxSession}. */
public Integer getTerminalTranscriptRows() {
if (mTerminalTranscriptRows == null)
setTerminalTranscriptRows();
return mTerminalTranscriptRows;
private ShellCreateMode processShellCreateMode(@NonNull ExecutionCommand executionCommand) {
if (ShellCreateMode.ALWAYS.equalsMode(executionCommand.shellCreateMode))
return ShellCreateMode.ALWAYS; // Default
else if (ShellCreateMode.NO_SHELL_WITH_NAME.equalsMode(executionCommand.shellCreateMode))
if (DataUtils.isNullOrEmpty(executionCommand.shellName)) {
TermuxPluginUtils.setAndProcessPluginExecutionCommandError(this, LOG_TAG, executionCommand, false,
getString(R.string.error_termux_service_execution_command_shell_name_unset, executionCommand.shellCreateMode));
return null;
} else {
return ShellCreateMode.NO_SHELL_WITH_NAME;
}
else {
TermuxPluginUtils.setAndProcessPluginExecutionCommandError(this, LOG_TAG, executionCommand, false,
getString(R.string.error_termux_service_unsupported_execution_command_shell_create_mode, executionCommand.shellCreateMode));
return null;
}
}
public void setTerminalTranscriptRows() {
// TermuxService only uses this termux property currently, so no need to load them all into
// an internal values map like TermuxActivity does
mTerminalTranscriptRows = TermuxAppSharedProperties.getTerminalTranscriptRows(this);
}
/** Process session action for new session. */
private void handleSessionAction(int sessionAction, TerminalSession newTerminalSession) {
Logger.logDebug(LOG_TAG, "Processing sessionAction \"" + sessionAction + "\" for session \"" + newTerminalSession.mSessionName + "\"");
@ -611,8 +687,8 @@ public final class TermuxService extends Service implements TermuxTask.TermuxTas
switch (sessionAction) {
case TERMUX_SERVICE.VALUE_EXTRA_SESSION_ACTION_SWITCH_TO_NEW_SESSION_AND_OPEN_ACTIVITY:
setCurrentStoredTerminalSession(newTerminalSession);
if (mTermuxTerminalSessionClient != null)
mTermuxTerminalSessionClient.setCurrentSession(newTerminalSession);
if (mTermuxTerminalSessionActivityClient != null)
mTermuxTerminalSessionActivityClient.setCurrentSession(newTerminalSession);
startTermuxActivity();
break;
case TERMUX_SERVICE.VALUE_EXTRA_SESSION_ACTION_KEEP_CURRENT_SESSION_AND_OPEN_ACTIVITY:
@ -622,8 +698,8 @@ public final class TermuxService extends Service implements TermuxTask.TermuxTas
break;
case TERMUX_SERVICE.VALUE_EXTRA_SESSION_ACTION_SWITCH_TO_NEW_SESSION_AND_DONT_OPEN_ACTIVITY:
setCurrentStoredTerminalSession(newTerminalSession);
if (mTermuxTerminalSessionClient != null)
mTermuxTerminalSessionClient.setCurrentSession(newTerminalSession);
if (mTermuxTerminalSessionActivityClient != null)
mTermuxTerminalSessionActivityClient.setCurrentSession(newTerminalSession);
break;
case TERMUX_SERVICE.VALUE_EXTRA_SESSION_ACTION_KEEP_CURRENT_SESSION_AND_DONT_OPEN_ACTIVITY:
if (getTermuxSessionsSize() == 1)
@ -646,8 +722,8 @@ public final class TermuxService extends Service implements TermuxTask.TermuxTas
} else {
TermuxAppSharedPreferences preferences = TermuxAppSharedPreferences.build(this);
if (preferences == null) return;
if (preferences.arePluginErrorNotificationsEnabled())
Logger.showToast(this, this.getString(R.string.error_display_over_other_apps_permission_not_granted), true);
if (preferences.arePluginErrorNotificationsEnabled(false))
Logger.showToast(this, this.getString(R.string.error_display_over_other_apps_permission_not_granted_to_start_terminal), true);
}
}
@ -657,35 +733,35 @@ public final class TermuxService extends Service implements TermuxTask.TermuxTas
/** If {@link TermuxActivity} has not bound to the {@link TermuxService} yet or is destroyed, then
* interface functions requiring the activity should not be available to the terminal sessions,
* so we just return the {@link #mTermuxTerminalSessionClientBase}. Once {@link TermuxActivity} bind
* so we just return the {@link #mTermuxTerminalSessionServiceClient}. Once {@link TermuxActivity} bind
* callback is received, it should call {@link #setTermuxTerminalSessionClient} to set the
* {@link TermuxService#mTermuxTerminalSessionClient} so that further terminal sessions are directly
* passed the {@link TermuxTerminalSessionClient} object which fully implements the
* {@link TermuxService#mTermuxTerminalSessionActivityClient} so that further terminal sessions are directly
* passed the {@link TermuxTerminalSessionActivityClient} object which fully implements the
* {@link TerminalSessionClient} interface.
*
* @return Returns the {@link TermuxTerminalSessionClient} if {@link TermuxActivity} has bound with
* {@link TermuxService}, otherwise {@link TermuxTerminalSessionClientBase}.
* @return Returns the {@link TermuxTerminalSessionActivityClient} if {@link TermuxActivity} has bound with
* {@link TermuxService}, otherwise {@link TermuxTerminalSessionServiceClient}.
*/
public synchronized TermuxTerminalSessionClientBase getTermuxTerminalSessionClient() {
if (mTermuxTerminalSessionClient != null)
return mTermuxTerminalSessionClient;
if (mTermuxTerminalSessionActivityClient != null)
return mTermuxTerminalSessionActivityClient;
else
return mTermuxTerminalSessionClientBase;
return mTermuxTerminalSessionServiceClient;
}
/** This should be called when {@link TermuxActivity#onServiceConnected} is called to set the
* {@link TermuxService#mTermuxTerminalSessionClient} variable and update the {@link TerminalSession}
* and {@link TerminalEmulator} clients in case they were passed {@link TermuxTerminalSessionClientBase}
* {@link TermuxService#mTermuxTerminalSessionActivityClient} variable and update the {@link TerminalSession}
* and {@link TerminalEmulator} clients in case they were passed {@link TermuxTerminalSessionServiceClient}
* earlier.
*
* @param termuxTerminalSessionClient The {@link TermuxTerminalSessionClient} object that fully
* @param termuxTerminalSessionActivityClient The {@link TermuxTerminalSessionActivityClient} object that fully
* implements the {@link TerminalSessionClient} interface.
*/
public synchronized void setTermuxTerminalSessionClient(TermuxTerminalSessionClient termuxTerminalSessionClient) {
mTermuxTerminalSessionClient = termuxTerminalSessionClient;
public synchronized void setTermuxTerminalSessionClient(TermuxTerminalSessionActivityClient termuxTerminalSessionActivityClient) {
mTermuxTerminalSessionActivityClient = termuxTerminalSessionActivityClient;
for (int i = 0; i < mTermuxSessions.size(); i++)
mTermuxSessions.get(i).getTerminalSession().updateTerminalSessionClient(mTermuxTerminalSessionClient);
for (int i = 0; i < mShellManager.mTermuxSessions.size(); i++)
mShellManager.mTermuxSessions.get(i).getTerminalSession().updateTerminalSessionClient(mTermuxTerminalSessionActivityClient);
}
/** This should be called when {@link TermuxActivity} has been destroyed and in {@link #onUnbind(Intent)}
@ -693,10 +769,10 @@ public final class TermuxService extends Service implements TermuxTask.TermuxTas
* clients do not hold an activity references.
*/
public synchronized void unsetTermuxTerminalSessionClient() {
for (int i = 0; i < mTermuxSessions.size(); i++)
mTermuxSessions.get(i).getTerminalSession().updateTerminalSessionClient(mTermuxTerminalSessionClientBase);
for (int i = 0; i < mShellManager.mTermuxSessions.size(); i++)
mShellManager.mTermuxSessions.get(i).getTerminalSession().updateTerminalSessionClient(mTermuxTerminalSessionServiceClient);
mTermuxTerminalSessionClient = null;
mTermuxTerminalSessionActivityClient = null;
}
@ -713,7 +789,7 @@ public final class TermuxService extends Service implements TermuxTask.TermuxTas
// Set notification text
int sessionCount = getTermuxSessionsSize();
int taskCount = mTermuxTasks.size();
int taskCount = mShellManager.mTermuxTasks.size();
String notificationText = sessionCount + " session" + (sessionCount == 1 ? "" : "s");
if (taskCount > 0) {
notificationText += ", " + taskCount + " task" + (taskCount == 1 ? "" : "s");
@ -774,7 +850,7 @@ public final class TermuxService extends Service implements TermuxTask.TermuxTas
/** Update the shown foreground service notification after making any changes that affect it. */
private synchronized void updateNotification() {
if (mWakeLock == null && mTermuxSessions.isEmpty() && mTermuxTasks.isEmpty()) {
if (mWakeLock == null && mShellManager.mTermuxSessions.isEmpty() && mShellManager.mTermuxTasks.isEmpty()) {
// Exit if we are updating after the user disabled all locks with no sessions or tasks running.
requestStopService();
} else {
@ -786,41 +862,55 @@ public final class TermuxService extends Service implements TermuxTask.TermuxTas
private void setCurrentStoredTerminalSession(TerminalSession session) {
if (session == null) return;
private void setCurrentStoredTerminalSession(TerminalSession terminalSession) {
if (terminalSession == null) return;
// Make the newly created session the current one to be displayed
TermuxAppSharedPreferences preferences = TermuxAppSharedPreferences.build(this);
if (preferences == null) return;
preferences.setCurrentSession(session.mHandle);
preferences.setCurrentSession(terminalSession.mHandle);
}
public synchronized boolean isTermuxSessionsEmpty() {
return mTermuxSessions.isEmpty();
return mShellManager.mTermuxSessions.isEmpty();
}
public synchronized int getTermuxSessionsSize() {
return mTermuxSessions.size();
return mShellManager.mTermuxSessions.size();
}
public synchronized List<TermuxSession> getTermuxSessions() {
return mTermuxSessions;
return mShellManager.mTermuxSessions;
}
@Nullable
public synchronized TermuxSession getTermuxSession(int index) {
if (index >= 0 && index < mTermuxSessions.size())
return mTermuxSessions.get(index);
if (index >= 0 && index < mShellManager.mTermuxSessions.size())
return mShellManager.mTermuxSessions.get(index);
else
return null;
}
@Nullable
public synchronized TermuxSession getTermuxSessionForTerminalSession(TerminalSession terminalSession) {
if (terminalSession == null) return null;
for (int i = 0; i < mShellManager.mTermuxSessions.size(); i++) {
if (mShellManager.mTermuxSessions.get(i).getTerminalSession().equals(terminalSession))
return mShellManager.mTermuxSessions.get(i);
}
return null;
}
public synchronized TermuxSession getLastTermuxSession() {
return mTermuxSessions.isEmpty() ? null : mTermuxSessions.get(mTermuxSessions.size() - 1);
return mShellManager.mTermuxSessions.isEmpty() ? null : mShellManager.mTermuxSessions.get(mShellManager.mTermuxSessions.size() - 1);
}
public synchronized int getIndexOfSession(TerminalSession terminalSession) {
for (int i = 0; i < mTermuxSessions.size(); i++) {
if (mTermuxSessions.get(i).getTerminalSession().equals(terminalSession))
if (terminalSession == null) return -1;
for (int i = 0; i < mShellManager.mTermuxSessions.size(); i++) {
if (mShellManager.mTermuxSessions.get(i).getTerminalSession().equals(terminalSession))
return i;
}
return -1;
@ -828,20 +918,40 @@ public final class TermuxService extends Service implements TermuxTask.TermuxTas
public synchronized TerminalSession getTerminalSessionForHandle(String sessionHandle) {
TerminalSession terminalSession;
for (int i = 0, len = mTermuxSessions.size(); i < len; i++) {
terminalSession = mTermuxSessions.get(i).getTerminalSession();
for (int i = 0, len = mShellManager.mTermuxSessions.size(); i < len; i++) {
terminalSession = mShellManager.mTermuxSessions.get(i).getTerminalSession();
if (terminalSession.mHandle.equals(sessionHandle))
return terminalSession;
}
return null;
}
public static synchronized int getNextExecutionId() {
return EXECUTION_ID++;
public synchronized AppShell getTermuxTaskForShellName(String name) {
if (DataUtils.isNullOrEmpty(name)) return null;
AppShell appShell;
for (int i = 0, len = mShellManager.mTermuxTasks.size(); i < len; i++) {
appShell = mShellManager.mTermuxTasks.get(i);
String shellName = appShell.getExecutionCommand().shellName;
if (shellName != null && shellName.equals(name))
return appShell;
}
return null;
}
public synchronized TermuxSession getTermuxSessionForShellName(String name) {
if (DataUtils.isNullOrEmpty(name)) return null;
TermuxSession termuxSession;
for (int i = 0, len = mShellManager.mTermuxSessions.size(); i < len; i++) {
termuxSession = mShellManager.mTermuxSessions.get(i);
String shellName = termuxSession.getExecutionCommand().shellName;
if (shellName != null && shellName.equals(name))
return termuxSession;
}
return null;
}
public boolean wantsToStop() {
return mWantsToStop;
}

View File

@ -1,6 +1,5 @@
package com.termux.app.activities;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
@ -12,10 +11,12 @@ import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import androidx.appcompat.app.AppCompatActivity;
import com.termux.shared.termux.TermuxConstants;
/** Basic embedded browser for viewing help pages. */
public final class HelpActivity extends Activity {
public final class HelpActivity extends AppCompatActivity {
WebView mWebView;
@ -34,7 +35,6 @@ public final class HelpActivity extends Activity {
mWebView = new WebView(this);
WebSettings settings = mWebView.getSettings();
settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
settings.setAppCacheEnabled(false);
setContentView(progressLayout);
mWebView.clearCache(true);

View File

@ -5,7 +5,6 @@ import android.os.Bundle;
import android.os.Environment;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
@ -16,20 +15,25 @@ import com.termux.shared.file.FileUtils;
import com.termux.shared.models.ReportInfo;
import com.termux.app.models.UserAction;
import com.termux.shared.interact.ShareUtils;
import com.termux.shared.packages.PackageUtils;
import com.termux.shared.settings.preferences.TermuxAPIAppSharedPreferences;
import com.termux.shared.settings.preferences.TermuxFloatAppSharedPreferences;
import com.termux.shared.settings.preferences.TermuxTaskerAppSharedPreferences;
import com.termux.shared.settings.preferences.TermuxWidgetAppSharedPreferences;
import com.termux.shared.termux.AndroidUtils;
import com.termux.shared.android.PackageUtils;
import com.termux.shared.termux.settings.preferences.TermuxAPIAppSharedPreferences;
import com.termux.shared.termux.settings.preferences.TermuxFloatAppSharedPreferences;
import com.termux.shared.termux.settings.preferences.TermuxTaskerAppSharedPreferences;
import com.termux.shared.termux.settings.preferences.TermuxWidgetAppSharedPreferences;
import com.termux.shared.android.AndroidUtils;
import com.termux.shared.termux.TermuxConstants;
import com.termux.shared.termux.TermuxUtils;
import com.termux.shared.activity.media.AppCompatActivityUtils;
import com.termux.shared.theme.NightMode;
public class SettingsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppCompatActivityUtils.setNightMode(this, NightMode.getAppNightMode().getName(), true);
setContentView(R.layout.activity_settings);
if (savedInstanceState == null) {
getSupportFragmentManager()
@ -37,11 +41,9 @@ public class SettingsActivity extends AppCompatActivity {
.replace(R.id.settings, new RootPreferencesFragment())
.commit();
}
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
AppCompatActivityUtils.setToolbar(this, com.termux.shared.R.id.toolbar);
AppCompatActivityUtils.setShowBackButtonInActionBar(this, true);
}
@Override
@ -58,12 +60,17 @@ public class SettingsActivity extends AppCompatActivity {
setPreferencesFromResource(R.xml.root_preferences, rootKey);
configureTermuxAPIPreference(context);
configureTermuxFloatPreference(context);
configureTermuxTaskerPreference(context);
configureTermuxWidgetPreference(context);
configureAboutPreference(context);
configureDonatePreference(context);
new Thread() {
@Override
public void run() {
configureTermuxAPIPreference(context);
configureTermuxFloatPreference(context);
configureTermuxTaskerPreference(context);
configureTermuxWidgetPreference(context);
configureAboutPreference(context);
configureDonatePreference(context);
}
}.start();
}
private void configureTermuxAPIPreference(@NonNull Context context) {
@ -112,22 +119,20 @@ public class SettingsActivity extends AppCompatActivity {
String title = "About";
StringBuilder aboutString = new StringBuilder();
aboutString.append(TermuxUtils.getAppInfoMarkdownString(context, false));
String termuxPluginAppsInfo = TermuxUtils.getTermuxPluginAppsInfoMarkdownString(context);
if (termuxPluginAppsInfo != null)
aboutString.append("\n\n").append(termuxPluginAppsInfo);
aboutString.append("\n\n").append(AndroidUtils.getDeviceInfoMarkdownString(context));
aboutString.append(TermuxUtils.getAppInfoMarkdownString(context, TermuxUtils.AppInfoMode.TERMUX_AND_PLUGIN_PACKAGES));
aboutString.append("\n\n").append(AndroidUtils.getDeviceInfoMarkdownString(context, true));
aboutString.append("\n\n").append(TermuxUtils.getImportantLinksMarkdownString(context));
String userActionName = UserAction.ABOUT.getName();
ReportActivity.startReportActivity(context, new ReportInfo(userActionName,
TermuxConstants.TERMUX_APP.TERMUX_SETTINGS_ACTIVITY_NAME, title, null,
aboutString.toString(), null, false,
userActionName,
ReportInfo reportInfo = new ReportInfo(userActionName,
TermuxConstants.TERMUX_APP.TERMUX_SETTINGS_ACTIVITY_NAME, title);
reportInfo.setReportString(aboutString.toString());
reportInfo.setReportSaveFileLabelAndPath(userActionName,
Environment.getExternalStorageDirectory() + "/" +
FileUtils.sanitizeFileName(TermuxConstants.TERMUX_APP_NAME + "-" + userActionName + ".log", true, true)));
FileUtils.sanitizeFileName(TermuxConstants.TERMUX_APP_NAME + "-" + userActionName + ".log", true, true));
ReportActivity.startReportActivity(context, reportInfo);
}
}.start();
@ -154,7 +159,7 @@ public class SettingsActivity extends AppCompatActivity {
}
donatePreference.setOnPreferenceClickListener(preference -> {
ShareUtils.openURL(context, TermuxConstants.TERMUX_DONATE_URL);
ShareUtils.openUrl(context, TermuxConstants.TERMUX_DONATE_URL);
return true;
});
}

View File

@ -1,21 +1,30 @@
package com.termux.filepicker;
package com.termux.app.api.file;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.OpenableColumns;
import android.util.Patterns;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.termux.R;
import com.termux.shared.android.PackageUtils;
import com.termux.shared.data.DataUtils;
import com.termux.shared.data.IntentUtils;
import com.termux.shared.net.uri.UriUtils;
import com.termux.shared.interact.MessageDialogUtils;
import com.termux.shared.interact.TextInputDialogUtils;
import com.termux.shared.net.uri.UriScheme;
import com.termux.shared.termux.interact.TextInputDialogUtils;
import com.termux.shared.termux.TermuxConstants;
import com.termux.shared.termux.TermuxConstants.TERMUX_APP;
import com.termux.shared.termux.TermuxConstants.TERMUX_APP.TERMUX_SERVICE;
import com.termux.app.TermuxService;
import com.termux.shared.logger.Logger;
import com.termux.shared.termux.settings.properties.TermuxAppSharedProperties;
import com.termux.shared.termux.settings.properties.TermuxPropertyConstants;
import java.io.ByteArrayInputStream;
import java.io.File;
@ -27,7 +36,7 @@ import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;
public class TermuxFileReceiverActivity extends Activity {
public class FileReceiverActivity extends AppCompatActivity {
static final String TERMUX_RECEIVEDIR = TermuxConstants.TERMUX_FILES_DIR_PATH + "/home/downloads";
static final String EDITOR_PROGRAM = TermuxConstants.TERMUX_HOME_DIR_PATH + "/bin/termux-file-editor";
@ -43,9 +52,11 @@ public class TermuxFileReceiverActivity extends Activity {
private static final String API_TAG = TermuxConstants.TERMUX_APP_NAME + "FileReceiver";
private static final String LOG_TAG = "TermuxFileReceiverActivity";
private static final String LOG_TAG = "FileReceiverActivity";
static boolean isSharedTextAnUrl(String sharedText) {
if (sharedText == null || sharedText.isEmpty()) return false;
return Patterns.WEB_URL.matcher(sharedText).matches()
|| Pattern.matches("magnet:\\?xt=urn:btih:.*?", sharedText);
}
@ -89,11 +100,13 @@ public class TermuxFileReceiverActivity extends Activity {
return;
}
if ("content".equals(scheme)) {
if (UriScheme.SCHEME_CONTENT.equals(scheme)) {
handleContentUri(dataUri, sharedTitle);
} else if ("file".equals(scheme)) {
// When e.g. clicking on a downloaded apk:
String path = dataUri.getPath();
} else if (UriScheme.SCHEME_FILE.equals(scheme)) {
Logger.logVerbose(LOG_TAG, "uri: \"" + dataUri + "\", path: \"" + dataUri.getPath() + "\", fragment: \"" + dataUri.getFragment() + "\"");
// Get full path including fragment (anything after last "#")
String path = UriUtils.getUriFilePathWithFragment(dataUri);
if (DataUtils.isNullOrEmpty(path)) {
showErrorDialogAndQuit("File path from data uri is null, empty or invalid.");
return;
@ -121,8 +134,10 @@ public class TermuxFileReceiverActivity extends Activity {
dialog -> finish());
}
void handleContentUri(final Uri uri, String subjectFromIntent) {
void handleContentUri(@NonNull final Uri uri, String subjectFromIntent) {
try {
Logger.logVerbose(LOG_TAG, "uri: \"" + uri + "\", path: \"" + uri.getPath() + "\", fragment: \"" + uri.getFragment() + "\"");
String attachmentFileName = null;
String[] projection = new String[]{OpenableColumns.DISPLAY_NAME};
@ -134,6 +149,7 @@ public class TermuxFileReceiverActivity extends Activity {
}
if (attachmentFileName == null) attachmentFileName = subjectFromIntent;
if (attachmentFileName == null) attachmentFileName = UriUtils.getUriFileBasename(uri, true);
InputStream in = getContentResolver().openInputStream(uri);
promptNameAndSave(in, attachmentFileName);
@ -144,35 +160,36 @@ public class TermuxFileReceiverActivity extends Activity {
}
void promptNameAndSave(final InputStream in, final String attachmentFileName) {
TextInputDialogUtils.textInput(this, R.string.title_file_received, attachmentFileName, R.string.action_file_received_edit, text -> {
File outFile = saveStreamWithName(in, text);
if (outFile == null) return;
TextInputDialogUtils.textInput(this, R.string.title_file_received, attachmentFileName,
R.string.action_file_received_edit, text -> {
File outFile = saveStreamWithName(in, text);
if (outFile == null) return;
final File editorProgramFile = new File(EDITOR_PROGRAM);
if (!editorProgramFile.isFile()) {
showErrorDialogAndQuit("The following file does not exist:\n$HOME/bin/termux-file-editor\n\n"
+ "Create this file as a script or a symlink - it will be called with the received file as only argument.");
return;
}
final File editorProgramFile = new File(EDITOR_PROGRAM);
if (!editorProgramFile.isFile()) {
showErrorDialogAndQuit("The following file does not exist:\n$HOME/bin/termux-file-editor\n\n"
+ "Create this file as a script or a symlink - it will be called with the received file as only argument.");
return;
}
// Do this for the user if necessary:
//noinspection ResultOfMethodCallIgnored
editorProgramFile.setExecutable(true);
// Do this for the user if necessary:
//noinspection ResultOfMethodCallIgnored
editorProgramFile.setExecutable(true);
final Uri scriptUri = new Uri.Builder().scheme("file").path(EDITOR_PROGRAM).build();
final Uri scriptUri = UriUtils.getFileUri(EDITOR_PROGRAM);
Intent executeIntent = new Intent(TERMUX_SERVICE.ACTION_SERVICE_EXECUTE, scriptUri);
executeIntent.setClass(TermuxFileReceiverActivity.this, TermuxService.class);
executeIntent.putExtra(TERMUX_SERVICE.EXTRA_ARGUMENTS, new String[]{outFile.getAbsolutePath()});
startService(executeIntent);
finish();
},
Intent executeIntent = new Intent(TERMUX_SERVICE.ACTION_SERVICE_EXECUTE, scriptUri);
executeIntent.setClass(FileReceiverActivity.this, TermuxService.class);
executeIntent.putExtra(TERMUX_SERVICE.EXTRA_ARGUMENTS, new String[]{outFile.getAbsolutePath()});
startService(executeIntent);
finish();
},
R.string.action_file_received_open_directory, text -> {
if (saveStreamWithName(in, text) == null) return;
Intent executeIntent = new Intent(TERMUX_SERVICE.ACTION_SERVICE_EXECUTE);
executeIntent.putExtra(TERMUX_SERVICE.EXTRA_WORKDIR, TERMUX_RECEIVEDIR);
executeIntent.setClass(TermuxFileReceiverActivity.this, TermuxService.class);
executeIntent.setClass(FileReceiverActivity.this, TermuxService.class);
startService(executeIntent);
finish();
},
@ -223,13 +240,48 @@ public class TermuxFileReceiverActivity extends Activity {
//noinspection ResultOfMethodCallIgnored
urlOpenerProgramFile.setExecutable(true);
final Uri urlOpenerProgramUri = new Uri.Builder().scheme("file").path(URL_OPENER_PROGRAM).build();
final Uri urlOpenerProgramUri = UriUtils.getFileUri(URL_OPENER_PROGRAM);
Intent executeIntent = new Intent(TERMUX_SERVICE.ACTION_SERVICE_EXECUTE, urlOpenerProgramUri);
executeIntent.setClass(TermuxFileReceiverActivity.this, TermuxService.class);
executeIntent.setClass(FileReceiverActivity.this, TermuxService.class);
executeIntent.putExtra(TERMUX_SERVICE.EXTRA_ARGUMENTS, new String[]{url});
startService(executeIntent);
finish();
}
/**
* Update {@link TERMUX_APP#FILE_SHARE_RECEIVER_ACTIVITY_CLASS_NAME} component state depending on
* {@link TermuxPropertyConstants#KEY_DISABLE_FILE_SHARE_RECEIVER} value and
* {@link TERMUX_APP#FILE_VIEW_RECEIVER_ACTIVITY_CLASS_NAME} component state depending on
* {@link TermuxPropertyConstants#KEY_DISABLE_FILE_VIEW_RECEIVER} value.
*/
public static void updateFileReceiverActivityComponentsState(@NonNull Context context) {
new Thread() {
@Override
public void run() {
TermuxAppSharedProperties properties = TermuxAppSharedProperties.getProperties();
String errmsg;
boolean state;
state = !properties.isFileShareReceiverDisabled();
Logger.logVerbose(LOG_TAG, "Setting " + TERMUX_APP.FILE_SHARE_RECEIVER_ACTIVITY_CLASS_NAME + " component state to " + state);
errmsg = PackageUtils.setComponentState(context,TermuxConstants.TERMUX_PACKAGE_NAME,
TERMUX_APP.FILE_SHARE_RECEIVER_ACTIVITY_CLASS_NAME,
state, null, false, false);
if (errmsg != null)
Logger.logError(LOG_TAG, errmsg);
state = !properties.isFileViewReceiverDisabled();
Logger.logVerbose(LOG_TAG, "Setting " + TERMUX_APP.FILE_VIEW_RECEIVER_ACTIVITY_CLASS_NAME + " component state to " + state);
errmsg = PackageUtils.setComponentState(context,TermuxConstants.TERMUX_PACKAGE_NAME,
TERMUX_APP.FILE_VIEW_RECEIVER_ACTIVITY_CLASS_NAME,
state, null, false, false);
if (errmsg != null)
Logger.logError(LOG_TAG, errmsg);
}
}.start();
}
}

View File

@ -0,0 +1,91 @@
package com.termux.app.event;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.termux.shared.data.IntentUtils;
import com.termux.shared.logger.Logger;
import com.termux.shared.termux.TermuxUtils;
import com.termux.shared.termux.file.TermuxFileUtils;
import com.termux.shared.termux.shell.command.environment.TermuxShellEnvironment;
import com.termux.shared.termux.shell.TermuxShellManager;
public class SystemEventReceiver extends BroadcastReceiver {
private static SystemEventReceiver mInstance;
private static final String LOG_TAG = "SystemEventReceiver";
public static synchronized SystemEventReceiver getInstance() {
if (mInstance == null) {
mInstance = new SystemEventReceiver();
}
return mInstance;
}
@Override
public void onReceive(@NonNull Context context, @Nullable Intent intent) {
if (intent == null) return;
Logger.logDebug(LOG_TAG, "Intent Received:\n" + IntentUtils.getIntentString(intent));
String action = intent.getAction();
if (action == null) return;
switch (action) {
case Intent.ACTION_BOOT_COMPLETED:
onActionBootCompleted(context, intent);
break;
case Intent.ACTION_PACKAGE_ADDED:
case Intent.ACTION_PACKAGE_REMOVED:
case Intent.ACTION_PACKAGE_REPLACED:
onActionPackageUpdated(context, intent);
break;
default:
Logger.logError(LOG_TAG, "Invalid action \"" + action + "\" passed to " + LOG_TAG);
}
}
public synchronized void onActionBootCompleted(@NonNull Context context, @NonNull Intent intent) {
TermuxShellManager.onActionBootCompleted(context, intent);
}
public synchronized void onActionPackageUpdated(@NonNull Context context, @NonNull Intent intent) {
Uri data = intent.getData();
if (data != null && TermuxUtils.isUriDataForTermuxPluginPackage(data)) {
Logger.logDebug(LOG_TAG, intent.getAction().replaceAll("^android.intent.action.", "") +
" event received for \"" + data.toString().replaceAll("^package:", "") + "\"");
if (TermuxFileUtils.isTermuxFilesDirectoryAccessible(context, false, false) == null)
TermuxShellEnvironment.writeEnvironmentToFile(context);
}
}
/**
* Register {@link SystemEventReceiver} to listen to {@link Intent#ACTION_PACKAGE_ADDED},
* {@link Intent#ACTION_PACKAGE_REMOVED} and {@link Intent#ACTION_PACKAGE_REPLACED} broadcasts.
* They must be registered dynamically and cannot be registered implicitly in
* the AndroidManifest.xml due to Android 8+ restrictions.
*
* https://developer.android.com/guide/components/broadcast-exceptions
*/
public synchronized static void registerPackageUpdateEvents(@NonNull Context context) {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
intentFilter.addDataScheme("package");
context.registerReceiver(getInstance(), intentFilter);
}
public synchronized static void unregisterPackageUpdateEvents(@NonNull Context context) {
context.unregisterReceiver(getInstance());
}
}

View File

@ -9,7 +9,7 @@ import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;
import com.termux.R;
import com.termux.shared.settings.preferences.TermuxAPIAppSharedPreferences;
import com.termux.shared.termux.settings.preferences.TermuxAPIAppSharedPreferences;
@Keep
public class TermuxAPIPreferencesFragment extends PreferenceFragmentCompat {

View File

@ -9,7 +9,7 @@ import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;
import com.termux.R;
import com.termux.shared.settings.preferences.TermuxFloatAppSharedPreferences;
import com.termux.shared.termux.settings.preferences.TermuxFloatAppSharedPreferences;
@Keep
public class TermuxFloatPreferencesFragment extends PreferenceFragmentCompat {

View File

@ -9,7 +9,7 @@ import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;
import com.termux.R;
import com.termux.shared.settings.preferences.TermuxAppSharedPreferences;
import com.termux.shared.termux.settings.preferences.TermuxAppSharedPreferences;
@Keep
public class TermuxPreferencesFragment extends PreferenceFragmentCompat {

View File

@ -9,7 +9,7 @@ import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;
import com.termux.R;
import com.termux.shared.settings.preferences.TermuxTaskerAppSharedPreferences;
import com.termux.shared.termux.settings.preferences.TermuxTaskerAppSharedPreferences;
@Keep
public class TermuxTaskerPreferencesFragment extends PreferenceFragmentCompat {

View File

@ -9,7 +9,7 @@ import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;
import com.termux.R;
import com.termux.shared.settings.preferences.TermuxWidgetAppSharedPreferences;
import com.termux.shared.termux.settings.preferences.TermuxWidgetAppSharedPreferences;
@Keep
public class TermuxWidgetPreferencesFragment extends PreferenceFragmentCompat {

View File

@ -13,7 +13,7 @@ import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;
import com.termux.R;
import com.termux.shared.settings.preferences.TermuxAppSharedPreferences;
import com.termux.shared.termux.settings.preferences.TermuxAppSharedPreferences;
import com.termux.shared.logger.Logger;
@Keep
@ -144,9 +144,9 @@ class DebuggingPreferencesDataStore extends PreferenceDataStore {
case "terminal_view_key_logging_enabled":
return mPreferences.isTerminalViewKeyLoggingEnabled();
case "plugin_error_notifications_enabled":
return mPreferences.arePluginErrorNotificationsEnabled();
return mPreferences.arePluginErrorNotificationsEnabled(false);
case "crash_report_notifications_enabled":
return mPreferences.areCrashReportNotificationsEnabled();
return mPreferences.areCrashReportNotificationsEnabled(false);
default:
return false;
}

View File

@ -9,7 +9,7 @@ import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;
import com.termux.R;
import com.termux.shared.settings.preferences.TermuxAppSharedPreferences;
import com.termux.shared.termux.settings.preferences.TermuxAppSharedPreferences;
@Keep
public class TerminalIOPreferencesFragment extends PreferenceFragmentCompat {

View File

@ -9,7 +9,7 @@ import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;
import com.termux.R;
import com.termux.shared.settings.preferences.TermuxAppSharedPreferences;
import com.termux.shared.termux.settings.preferences.TermuxAppSharedPreferences;
@Keep
public class TerminalViewPreferencesFragment extends PreferenceFragmentCompat {

View File

@ -13,7 +13,7 @@ import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;
import com.termux.R;
import com.termux.shared.settings.preferences.TermuxAPIAppSharedPreferences;
import com.termux.shared.termux.settings.preferences.TermuxAPIAppSharedPreferences;
@Keep
public class DebuggingPreferencesFragment extends PreferenceFragmentCompat {

View File

@ -13,7 +13,7 @@ import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;
import com.termux.R;
import com.termux.shared.settings.preferences.TermuxFloatAppSharedPreferences;
import com.termux.shared.termux.settings.preferences.TermuxFloatAppSharedPreferences;
@Keep
public class DebuggingPreferencesFragment extends PreferenceFragmentCompat {

View File

@ -13,7 +13,7 @@ import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;
import com.termux.R;
import com.termux.shared.settings.preferences.TermuxTaskerAppSharedPreferences;
import com.termux.shared.termux.settings.preferences.TermuxTaskerAppSharedPreferences;
@Keep
public class DebuggingPreferencesFragment extends PreferenceFragmentCompat {

View File

@ -13,7 +13,7 @@ import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;
import com.termux.R;
import com.termux.shared.settings.preferences.TermuxWidgetAppSharedPreferences;
import com.termux.shared.termux.settings.preferences.TermuxWidgetAppSharedPreferences;
@Keep
public class DebuggingPreferencesFragment extends PreferenceFragmentCompat {

View File

@ -3,8 +3,6 @@ package com.termux.app.models;
public enum UserAction {
ABOUT("about"),
CRASH_REPORT("crash report"),
PLUGIN_EXECUTION_COMMAND("plugin execution command"),
REPORT_ISSUE_FROM_TRANSCRIPT("report issue from transcript");
private final String name;

View File

@ -1,119 +0,0 @@
package com.termux.app.settings.properties;
import android.content.Context;
import androidx.annotation.NonNull;
import com.termux.app.terminal.io.KeyboardShortcut;
import com.termux.shared.terminal.io.extrakeys.ExtraKeysConstants;
import com.termux.shared.terminal.io.extrakeys.ExtraKeysConstants.EXTRA_KEY_DISPLAY_MAPS;
import com.termux.shared.terminal.io.extrakeys.ExtraKeysInfo;
import com.termux.shared.logger.Logger;
import com.termux.shared.settings.properties.TermuxPropertyConstants;
import com.termux.shared.settings.properties.TermuxSharedProperties;
import com.termux.shared.termux.TermuxConstants;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class TermuxAppSharedProperties extends TermuxSharedProperties {
private ExtraKeysInfo mExtraKeysInfo;
private List<KeyboardShortcut> mSessionShortcuts = new ArrayList<>();
private static final String LOG_TAG = "TermuxAppSharedProperties";
public TermuxAppSharedProperties(@NonNull Context context) {
super(context, TermuxConstants.TERMUX_APP_NAME, TermuxPropertyConstants.getTermuxPropertiesFile(),
TermuxPropertyConstants.TERMUX_PROPERTIES_LIST, new SharedPropertiesParserClient());
}
/**
* Reload the termux properties from disk into an in-memory cache.
*/
@Override
public void loadTermuxPropertiesFromDisk() {
super.loadTermuxPropertiesFromDisk();
setExtraKeys();
setSessionShortcuts();
}
/**
* Set the terminal extra keys and style.
*/
private void setExtraKeys() {
mExtraKeysInfo = null;
try {
// The mMap stores the extra key and style string values while loading properties
// Check {@link #getExtraKeysInternalPropertyValueFromValue(String)} and
// {@link #getExtraKeysStyleInternalPropertyValueFromValue(String)}
String extrakeys = (String) getInternalPropertyValue(TermuxPropertyConstants.KEY_EXTRA_KEYS, true);
String extraKeysStyle = (String) getInternalPropertyValue(TermuxPropertyConstants.KEY_EXTRA_KEYS_STYLE, true);
ExtraKeysConstants.ExtraKeyDisplayMap extraKeyDisplayMap = ExtraKeysInfo.getCharDisplayMapForStyle(extraKeysStyle);
if (EXTRA_KEY_DISPLAY_MAPS.DEFAULT_CHAR_DISPLAY.equals(extraKeyDisplayMap) && !TermuxPropertyConstants.DEFAULT_IVALUE_EXTRA_KEYS_STYLE.equals(extraKeysStyle)) {
Logger.logError(TermuxSharedProperties.LOG_TAG, "The style \"" + extraKeysStyle + "\" for the key \"" + TermuxPropertyConstants.KEY_EXTRA_KEYS_STYLE + "\" is invalid. Using default style instead.");
extraKeysStyle = TermuxPropertyConstants.DEFAULT_IVALUE_EXTRA_KEYS_STYLE;
}
mExtraKeysInfo = new ExtraKeysInfo(extrakeys, extraKeysStyle, ExtraKeysConstants.CONTROL_CHARS_ALIASES);
} catch (JSONException e) {
Logger.showToast(mContext, "Could not load and set the \"" + TermuxPropertyConstants.KEY_EXTRA_KEYS + "\" property from the properties file: " + e.toString(), true);
Logger.logStackTraceWithMessage(LOG_TAG, "Could not load and set the \"" + TermuxPropertyConstants.KEY_EXTRA_KEYS + "\" property from the properties file: ", e);
try {
mExtraKeysInfo = new ExtraKeysInfo(TermuxPropertyConstants.DEFAULT_IVALUE_EXTRA_KEYS, TermuxPropertyConstants.DEFAULT_IVALUE_EXTRA_KEYS_STYLE, ExtraKeysConstants.CONTROL_CHARS_ALIASES);
} catch (JSONException e2) {
Logger.showToast(mContext, "Can't create default extra keys",true);
Logger.logStackTraceWithMessage(LOG_TAG, "Could create default extra keys: ", e);
mExtraKeysInfo = null;
}
}
}
/**
* Set the terminal sessions shortcuts.
*/
private void setSessionShortcuts() {
if (mSessionShortcuts == null)
mSessionShortcuts = new ArrayList<>();
else
mSessionShortcuts.clear();
// The {@link TermuxPropertyConstants#MAP_SESSION_SHORTCUTS} stores the session shortcut key and action pair
for (Map.Entry<String, Integer> entry : TermuxPropertyConstants.MAP_SESSION_SHORTCUTS.entrySet()) {
// The mMap stores the code points for the session shortcuts while loading properties
Integer codePoint = (Integer) getInternalPropertyValue(entry.getKey(), true);
// If codePoint is null, then session shortcut did not exist in properties or was invalid
// as parsed by {@link #getCodePointForSessionShortcuts(String,String)}
// If codePoint is not null, then get the action for the MAP_SESSION_SHORTCUTS key and
// add the code point to sessionShortcuts
if (codePoint != null)
mSessionShortcuts.add(new KeyboardShortcut(codePoint, entry.getValue()));
}
}
public List<KeyboardShortcut> getSessionShortcuts() {
return mSessionShortcuts;
}
public ExtraKeysInfo getExtraKeysInfo() {
return mExtraKeysInfo;
}
/**
* Load the {@link TermuxPropertyConstants#KEY_TERMINAL_TRANSCRIPT_ROWS} value from termux properties file on disk.
*/
public static int getTerminalTranscriptRows(Context context) {
return (int) TermuxSharedProperties.getInternalPropertyValue(context, TermuxPropertyConstants.getTermuxPropertiesFile(),
TermuxPropertyConstants.KEY_TERMINAL_TRANSCRIPT_ROWS, new SharedPropertiesParserClient());
}
}

View File

@ -20,7 +20,9 @@ import androidx.core.content.ContextCompat;
import com.termux.R;
import com.termux.app.TermuxActivity;
import com.termux.shared.shell.TermuxSession;
import com.termux.shared.termux.shell.command.runner.terminal.TermuxSession;
import com.termux.shared.theme.NightMode;
import com.termux.shared.theme.ThemeUtils;
import com.termux.terminal.TerminalSession;
import java.util.List;
@ -55,9 +57,9 @@ public class TermuxSessionsListViewController extends ArrayAdapter<TermuxSession
return sessionRowView;
}
boolean isUsingBlackUI = mActivity.getProperties().isUsingBlackUI();
boolean shouldEnableDarkTheme = ThemeUtils.shouldEnableDarkTheme(mActivity, NightMode.getAppNightMode().getName());
if (isUsingBlackUI) {
if (shouldEnableDarkTheme) {
sessionTitleView.setBackground(
ContextCompat.getDrawable(mActivity, R.drawable.session_background_black_selected)
);
@ -84,7 +86,7 @@ public class TermuxSessionsListViewController extends ArrayAdapter<TermuxSession
} else {
sessionTitleView.setPaintFlags(sessionTitleView.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
int defaultColor = isUsingBlackUI ? Color.WHITE : Color.BLACK;
int defaultColor = shouldEnableDarkTheme ? Color.WHITE : Color.BLACK;
int color = sessionRunning || sessionAtRow.getExitStatus() == 0 ? defaultColor : Color.RED;
sessionTitleView.setTextColor(color);
return sessionRowView;

View File

@ -1,6 +1,7 @@
package com.termux.app.terminal;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
@ -12,18 +13,23 @@ import android.media.SoundPool;
import android.text.TextUtils;
import android.widget.ListView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.termux.R;
import com.termux.shared.shell.TermuxSession;
import com.termux.shared.interact.TextInputDialogUtils;
import com.termux.shared.interact.ShareUtils;
import com.termux.shared.termux.shell.command.runner.terminal.TermuxSession;
import com.termux.shared.termux.interact.TextInputDialogUtils;
import com.termux.app.TermuxActivity;
import com.termux.shared.terminal.TermuxTerminalSessionClientBase;
import com.termux.shared.termux.terminal.TermuxTerminalSessionClientBase;
import com.termux.shared.termux.TermuxConstants;
import com.termux.app.TermuxService;
import com.termux.shared.settings.properties.TermuxPropertyConstants;
import com.termux.shared.terminal.io.BellHandler;
import com.termux.shared.termux.settings.properties.TermuxPropertyConstants;
import com.termux.shared.termux.terminal.io.BellHandler;
import com.termux.shared.logger.Logger;
import com.termux.terminal.TerminalColors;
import com.termux.terminal.TerminalSession;
import com.termux.terminal.TerminalSessionClient;
import com.termux.terminal.TextStyle;
import java.io.File;
@ -31,7 +37,8 @@ import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
public class TermuxTerminalSessionClient extends TermuxTerminalSessionClientBase {
/** The {@link TerminalSessionClient} implementation that may require an {@link Activity} for its interface methods. */
public class TermuxTerminalSessionActivityClient extends TermuxTerminalSessionClientBase {
private final TermuxActivity mActivity;
@ -41,9 +48,9 @@ public class TermuxTerminalSessionClient extends TermuxTerminalSessionClientBase
private int mBellSoundId;
private static final String LOG_TAG = "TermuxTerminalSessionClient";
private static final String LOG_TAG = "TermuxTerminalSessionActivityClient";
public TermuxTerminalSessionClient(TermuxActivity activity) {
public TermuxTerminalSessionActivityClient(TermuxActivity activity) {
this.mActivity = activity;
}
@ -79,7 +86,7 @@ public class TermuxTerminalSessionClient extends TermuxTerminalSessionClientBase
// Just initialize the mBellSoundPool and load the sound, otherwise bell might not run
// the first time bell key is pressed and play() is called, since sound may not be loaded
// quickly enough before the call to play(). https://stackoverflow.com/questions/35435625
getBellSoundPool();
loadBellSoundPool();
}
/**
@ -100,7 +107,7 @@ public class TermuxTerminalSessionClient extends TermuxTerminalSessionClientBase
/**
* Should be called when mActivity.reloadActivityStyling() is called
*/
public void onReload() {
public void onReloadActivityStyling() {
// Set terminal fonts and colors
checkForFontAndColors();
}
@ -108,14 +115,14 @@ public class TermuxTerminalSessionClient extends TermuxTerminalSessionClientBase
@Override
public void onTextChanged(TerminalSession changedSession) {
public void onTextChanged(@NonNull TerminalSession changedSession) {
if (!mActivity.isVisible()) return;
if (mActivity.getCurrentSession() == changedSession) mActivity.getTerminalView().onScreenUpdated();
}
@Override
public void onTitleChanged(TerminalSession updatedSession) {
public void onTitleChanged(@NonNull TerminalSession updatedSession) {
if (!mActivity.isVisible()) return;
if (updatedSession != mActivity.getCurrentSession()) {
@ -129,7 +136,7 @@ public class TermuxTerminalSessionClient extends TermuxTerminalSessionClientBase
}
@Override
public void onSessionFinished(final TerminalSession finishedSession) {
public void onSessionFinished(@NonNull TerminalSession finishedSession) {
TermuxService service = mActivity.getTermuxService();
if (service == null || service.wantsToStop()) {
@ -174,27 +181,23 @@ public class TermuxTerminalSessionClient extends TermuxTerminalSessionClientBase
}
@Override
public void onCopyTextToClipboard(TerminalSession session, String text) {
public void onCopyTextToClipboard(@NonNull TerminalSession session, String text) {
if (!mActivity.isVisible()) return;
ClipboardManager clipboard = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setPrimaryClip(new ClipData(null, new String[]{"text/plain"}, new ClipData.Item(text)));
ShareUtils.copyTextToClipboard(mActivity, text);
}
@Override
public void onPasteTextFromClipboard(TerminalSession session) {
public void onPasteTextFromClipboard(@Nullable TerminalSession session) {
if (!mActivity.isVisible()) return;
ClipboardManager clipboard = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clipData = clipboard.getPrimaryClip();
if (clipData != null) {
CharSequence paste = clipData.getItemAt(0).coerceToText(mActivity);
if (!TextUtils.isEmpty(paste)) mActivity.getTerminalView().mEmulator.paste(paste.toString());
}
String text = ShareUtils.getTextStringFromClipboardIfSet(mActivity, true);
if (text != null)
mActivity.getTerminalView().mEmulator.paste(text);
}
@Override
public void onBell(TerminalSession session) {
public void onBell(@NonNull TerminalSession session) {
if (!mActivity.isVisible()) return;
switch (mActivity.getProperties().getBellBehaviour()) {
@ -202,7 +205,9 @@ public class TermuxTerminalSessionClient extends TermuxTerminalSessionClientBase
BellHandler.getInstance(mActivity).doBell();
break;
case TermuxPropertyConstants.IVALUE_BELL_BEHAVIOUR_BEEP:
getBellSoundPool().play(mBellSoundId, 1.f, 1.f, 1, 0, 1.f);
loadBellSoundPool();
if (mBellSoundPool != null)
mBellSoundPool.play(mBellSoundId, 1.f, 1.f, 1, 0, 1.f);
break;
case TermuxPropertyConstants.IVALUE_BELL_BEHAVIOUR_IGNORE:
// Ignore the bell character.
@ -211,7 +216,7 @@ public class TermuxTerminalSessionClient extends TermuxTerminalSessionClientBase
}
@Override
public void onColorsChanged(TerminalSession changedSession) {
public void onColorsChanged(@NonNull TerminalSession changedSession) {
if (mActivity.getCurrentSession() == changedSession)
updateBackgroundColor();
}
@ -229,6 +234,17 @@ public class TermuxTerminalSessionClient extends TermuxTerminalSessionClientBase
mActivity.getTerminalView().setTerminalCursorBlinkerState(enabled, false);
}
@Override
public void setTerminalShellPid(@NonNull TerminalSession terminalSession, int pid) {
TermuxService service = mActivity.getTermuxService();
if (service == null) return;
TermuxSession termuxSession = service.getTermuxSessionForTerminalSession(terminalSession);
if (termuxSession != null)
termuxSession.getExecutionCommand().mPid = pid;
}
/**
* Should be called when mActivity.onResetTerminalSession() is called
*/
@ -247,17 +263,20 @@ public class TermuxTerminalSessionClient extends TermuxTerminalSessionClientBase
/** Initialize and get mBellSoundPool */
private synchronized SoundPool getBellSoundPool() {
/** Load mBellSoundPool */
private synchronized void loadBellSoundPool() {
if (mBellSoundPool == null) {
mBellSoundPool = new SoundPool.Builder().setMaxStreams(1).setAudioAttributes(
new AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION).build()).build();
mBellSoundId = mBellSoundPool.load(mActivity, R.raw.bell, 1);
try {
mBellSoundId = mBellSoundPool.load(mActivity, com.termux.shared.R.raw.bell, 1);
} catch (Exception e){
// Catch java.lang.RuntimeException: Unable to resume activity {com.termux/com.termux.app.TermuxActivity}: android.content.res.Resources$NotFoundException: File res/raw/bell.ogg from drawable resource ID
Logger.logStackTraceWithMessage(LOG_TAG, "Failed to load bell sound pool", e);
}
}
return mBellSoundPool;
}
/** Release mBellSoundPool resources */
@ -326,11 +345,22 @@ public class TermuxTerminalSessionClient extends TermuxTerminalSessionClientBase
if (sessionToRename == null) return;
TextInputDialogUtils.textInput(mActivity, R.string.title_rename_session, sessionToRename.mSessionName, R.string.action_rename_session_confirm, text -> {
sessionToRename.mSessionName = text;
renameSession(sessionToRename, text);
termuxSessionListNotifyUpdated();
}, -1, null, -1, null, null);
}
private void renameSession(TerminalSession sessionToRename, String text) {
if (sessionToRename == null) return;
sessionToRename.mSessionName = text;
TermuxService service = mActivity.getTermuxService();
if (service != null) {
TermuxSession termuxSession = service.getTermuxSessionForTerminalSession(sessionToRename);
if (termuxSession != null)
termuxSession.getExecutionCommand().shellName = text;
}
}
public void addNewSession(boolean isFailSafe, String sessionName) {
TermuxService service = mActivity.getTermuxService();
if (service == null) return;

View File

@ -0,0 +1,31 @@
package com.termux.app.terminal;
import android.app.Service;
import androidx.annotation.NonNull;
import com.termux.app.TermuxService;
import com.termux.shared.termux.shell.command.runner.terminal.TermuxSession;
import com.termux.shared.termux.terminal.TermuxTerminalSessionClientBase;
import com.termux.terminal.TerminalSession;
import com.termux.terminal.TerminalSessionClient;
/** The {@link TerminalSessionClient} implementation that may require a {@link Service} for its interface methods. */
public class TermuxTerminalSessionServiceClient extends TermuxTerminalSessionClientBase {
private static final String LOG_TAG = "TermuxTerminalSessionServiceClient";
private final TermuxService mService;
public TermuxTerminalSessionServiceClient(TermuxService service) {
this.mService = service;
}
@Override
public void setTerminalShellPid(@NonNull TerminalSession terminalSession, int pid) {
TermuxSession termuxSession = mService.getTermuxSessionForTerminalSession(terminalSession);
if (termuxSession != null)
termuxSession.getExecutionCommand().mPid = pid;
}
}

View File

@ -2,13 +2,10 @@ package com.termux.app.terminal;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Gravity;
@ -22,35 +19,37 @@ import android.widget.Toast;
import com.termux.R;
import com.termux.app.TermuxActivity;
import com.termux.shared.data.UrlUtils;
import com.termux.shared.file.FileUtils;
import com.termux.shared.interact.MessageDialogUtils;
import com.termux.shared.interact.ShareUtils;
import com.termux.shared.shell.ShellUtils;
import com.termux.shared.terminal.TermuxTerminalViewClientBase;
import com.termux.shared.terminal.io.extrakeys.SpecialButton;
import com.termux.shared.termux.AndroidUtils;
import com.termux.shared.termux.TermuxBootstrap;
import com.termux.shared.termux.terminal.TermuxTerminalViewClientBase;
import com.termux.shared.termux.extrakeys.SpecialButton;
import com.termux.shared.android.AndroidUtils;
import com.termux.shared.termux.TermuxConstants;
import com.termux.shared.activities.ReportActivity;
import com.termux.shared.models.ReportInfo;
import com.termux.app.models.UserAction;
import com.termux.app.terminal.io.KeyboardShortcut;
import com.termux.shared.settings.properties.TermuxPropertyConstants;
import com.termux.shared.termux.settings.properties.TermuxPropertyConstants;
import com.termux.shared.data.DataUtils;
import com.termux.shared.logger.Logger;
import com.termux.shared.markdown.MarkdownUtils;
import com.termux.shared.termux.TermuxUtils;
import com.termux.shared.termux.data.TermuxUrlUtils;
import com.termux.shared.view.KeyboardUtils;
import com.termux.shared.view.ViewUtils;
import com.termux.terminal.KeyHandler;
import com.termux.terminal.TerminalBuffer;
import com.termux.terminal.TerminalEmulator;
import com.termux.terminal.TerminalSession;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import androidx.drawerlayout.widget.DrawerLayout;
@ -58,7 +57,7 @@ public class TermuxTerminalViewClient extends TermuxTerminalViewClientBase {
final TermuxActivity mActivity;
final TermuxTerminalSessionClient mTermuxTerminalSessionClient;
final TermuxTerminalSessionActivityClient mTermuxTerminalSessionActivityClient;
/** Keeping track of the special keys acting as Ctrl and Fn for the soft keyboard and other hardware keys. */
boolean mVirtualControlKeyDown, mVirtualFnKeyDown;
@ -70,11 +69,13 @@ public class TermuxTerminalViewClient extends TermuxTerminalViewClientBase {
private boolean mTerminalCursorBlinkerStateAlreadySet;
private List<KeyboardShortcut> mSessionShortcuts;
private static final String LOG_TAG = "TermuxTerminalViewClient";
public TermuxTerminalViewClient(TermuxActivity activity, TermuxTerminalSessionClient termuxTerminalSessionClient) {
public TermuxTerminalViewClient(TermuxActivity activity, TermuxTerminalSessionActivityClient termuxTerminalSessionActivityClient) {
this.mActivity = activity;
this.mTermuxTerminalSessionClient = termuxTerminalSessionClient;
this.mTermuxTerminalSessionActivityClient = termuxTerminalSessionActivityClient;
}
public TermuxActivity getActivity() {
@ -85,6 +86,8 @@ public class TermuxTerminalViewClient extends TermuxTerminalViewClientBase {
* Should be called when mActivity.onCreate() is called
*/
public void onCreate() {
onReloadProperties();
mActivity.getTerminalView().setTextSize(mActivity.getPreferences().getFontSize());
mActivity.getTerminalView().setKeepScreenOn(mActivity.getPreferences().shouldKeepScreenOn());
}
@ -108,7 +111,7 @@ public class TermuxTerminalViewClient extends TermuxTerminalViewClientBase {
*/
public void onResume() {
// Show the soft keyboard if required
setSoftKeyboardState(true, false);
setSoftKeyboardState(true, mActivity.isActivityRecreated());
mTerminalCursorBlinkerStateAlreadySet = false;
@ -130,10 +133,17 @@ public class TermuxTerminalViewClient extends TermuxTerminalViewClientBase {
setTerminalCursorBlinkerState(false);
}
/**
* Should be called when mActivity.reloadProperties() is called
*/
public void onReloadProperties() {
setSessionShortcuts();
}
/**
* Should be called when mActivity.reloadActivityStyling() is called
*/
public void onReload() {
public void onReloadActivityStyling() {
// Show the soft keyboard if required
setSoftKeyboardState(false, true);
@ -179,11 +189,11 @@ public class TermuxTerminalViewClient extends TermuxTerminalViewClientBase {
if (mActivity.getProperties().shouldOpenTerminalTranscriptURLOnClick()) {
int[] columnAndRow = mActivity.getTerminalView().getColumnAndRow(e, true);
String wordAtTap = term.getScreen().getWordAtLocation(columnAndRow[0], columnAndRow[1]);
LinkedHashSet<CharSequence> urlSet = UrlUtils.extractUrls(wordAtTap);
LinkedHashSet<CharSequence> urlSet = TermuxUrlUtils.extractUrls(wordAtTap);
if (!urlSet.isEmpty()) {
String url = (String) urlSet.iterator().next();
ShareUtils.openURL(mActivity, url);
ShareUtils.openUrl(mActivity, url);
return;
}
}
@ -213,7 +223,7 @@ public class TermuxTerminalViewClient extends TermuxTerminalViewClientBase {
@Override
public boolean isTerminalViewSelected() {
return mActivity.getTerminalToolbarViewPager() == null || mActivity.isTerminalViewSelected();
return mActivity.getTerminalToolbarViewPager() == null || mActivity.isTerminalViewSelected() || mActivity.getTerminalView().hasFocus();
}
@ -232,7 +242,7 @@ public class TermuxTerminalViewClient extends TermuxTerminalViewClientBase {
if (handleVirtualKeys(keyCode, e, true)) return true;
if (keyCode == KeyEvent.KEYCODE_ENTER && !currentSession.isRunning()) {
mTermuxTerminalSessionClient.removeFinishedSession(currentSession);
mTermuxTerminalSessionActivityClient.removeFinishedSession(currentSession);
return true;
} else if (!mActivity.getProperties().areHardwareKeyboardShortcutsDisabled() &&
e.isCtrlPressed() && e.isAltPressed()) {
@ -240,9 +250,9 @@ public class TermuxTerminalViewClient extends TermuxTerminalViewClientBase {
int unicodeChar = e.getUnicodeChar(0);
if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN || unicodeChar == 'n'/* next */) {
mTermuxTerminalSessionClient.switchToSession(true);
mTermuxTerminalSessionActivityClient.switchToSession(true);
} else if (keyCode == KeyEvent.KEYCODE_DPAD_UP || unicodeChar == 'p' /* previous */) {
mTermuxTerminalSessionClient.switchToSession(false);
mTermuxTerminalSessionActivityClient.switchToSession(false);
} else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
mActivity.getDrawer().openDrawer(Gravity.LEFT);
} else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
@ -252,9 +262,9 @@ public class TermuxTerminalViewClient extends TermuxTerminalViewClientBase {
} else if (unicodeChar == 'm'/* menu */) {
mActivity.getTerminalView().showContextMenu();
} else if (unicodeChar == 'r'/* rename */) {
mTermuxTerminalSessionClient.renameSession(currentSession);
mTermuxTerminalSessionActivityClient.renameSession(currentSession);
} else if (unicodeChar == 'c'/* create */) {
mTermuxTerminalSessionClient.addNewSession(false, null);
mTermuxTerminalSessionActivityClient.addNewSession(false, null);
} else if (unicodeChar == 'u' /* urls */) {
showUrlSelection();
} else if (unicodeChar == 'v') {
@ -267,7 +277,7 @@ public class TermuxTerminalViewClient extends TermuxTerminalViewClientBase {
changeFontSize(false);
} else if (unicodeChar >= '1' && unicodeChar <= '9') {
int index = unicodeChar - '1';
mTermuxTerminalSessionClient.switchToSession(index);
mTermuxTerminalSessionActivityClient.switchToSession(index);
}
return true;
}
@ -451,11 +461,11 @@ public class TermuxTerminalViewClient extends TermuxTerminalViewClientBase {
return true;
} else if (ctrlDown) {
if (codePoint == 106 /* Ctrl+j or \n */ && !session.isRunning()) {
mTermuxTerminalSessionClient.removeFinishedSession(session);
mTermuxTerminalSessionActivityClient.removeFinishedSession(session);
return true;
}
List<KeyboardShortcut> shortcuts = mActivity.getProperties().getSessionShortcuts();
List<KeyboardShortcut> shortcuts = mSessionShortcuts;
if (shortcuts != null && !shortcuts.isEmpty()) {
int codePointLowerCase = Character.toLowerCase(codePoint);
for (int i = shortcuts.size() - 1; i >= 0; i--) {
@ -463,16 +473,16 @@ public class TermuxTerminalViewClient extends TermuxTerminalViewClientBase {
if (codePointLowerCase == shortcut.codePoint) {
switch (shortcut.shortcutAction) {
case TermuxPropertyConstants.ACTION_SHORTCUT_CREATE_SESSION:
mTermuxTerminalSessionClient.addNewSession(false, null);
mTermuxTerminalSessionActivityClient.addNewSession(false, null);
return true;
case TermuxPropertyConstants.ACTION_SHORTCUT_NEXT_SESSION:
mTermuxTerminalSessionClient.switchToSession(true);
mTermuxTerminalSessionActivityClient.switchToSession(true);
return true;
case TermuxPropertyConstants.ACTION_SHORTCUT_PREVIOUS_SESSION:
mTermuxTerminalSessionClient.switchToSession(false);
mTermuxTerminalSessionActivityClient.switchToSession(false);
return true;
case TermuxPropertyConstants.ACTION_SHORTCUT_RENAME_SESSION:
mTermuxTerminalSessionClient.renameSession(mActivity.getCurrentSession());
mTermuxTerminalSessionActivityClient.renameSession(mActivity.getCurrentSession());
return true;
}
}
@ -483,6 +493,27 @@ public class TermuxTerminalViewClient extends TermuxTerminalViewClientBase {
return false;
}
/**
* Set the terminal sessions shortcuts.
*/
private void setSessionShortcuts() {
mSessionShortcuts = new ArrayList<>();
// The {@link TermuxPropertyConstants#MAP_SESSION_SHORTCUTS} stores the session shortcut key and action pair
for (Map.Entry<String, Integer> entry : TermuxPropertyConstants.MAP_SESSION_SHORTCUTS.entrySet()) {
// The mMap stores the code points for the session shortcuts while loading properties
Integer codePoint = (Integer) mActivity.getProperties().getInternalPropertyValue(entry.getKey(), true);
// If codePoint is null, then session shortcut did not exist in properties or was invalid
// as parsed by {@link #getCodePointForSessionShortcuts(String,String)}
// If codePoint is not null, then get the action for the MAP_SESSION_SHORTCUTS key and
// add the code point to sessionShortcuts
if (codePoint != null)
mSessionShortcuts.add(new KeyboardShortcut(codePoint, entry.getValue()));
}
}
public void changeFontSize(boolean increase) {
@ -541,7 +572,8 @@ public class TermuxTerminalViewClient extends TermuxTerminalViewClientBase {
// disabled or hidden at startup, otherwise if hardware keyboard is attached and user
// starts typing on hardware keyboard without tapping on the terminal first, then a colour
// tint will be added to the terminal as highlight for the focussed view. Test with a light
// theme.
// theme. For android 8.+, the "defaultFocusHighlightEnabled" attribute is also set to false
// in TerminalView layout to fix the issue.
// If soft keyboard is disabled by user for Termux (check function docs for Termux behaviour info)
if (KeyboardUtils.shouldSoftKeyboardBeDisabled(mActivity,
@ -646,17 +678,17 @@ public class TermuxTerminalViewClient extends TermuxTerminalViewClientBase {
String transcriptText = ShellUtils.getTerminalSessionTranscriptText(session, false, true);
if (transcriptText == null) return;
try {
// See https://github.com/termux/termux-app/issues/1166.
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
transcriptText = DataUtils.getTruncatedCommandOutput(transcriptText, DataUtils.TRANSACTION_SIZE_LIMIT_IN_BYTES, false, true, false).trim();
intent.putExtra(Intent.EXTRA_TEXT, transcriptText);
intent.putExtra(Intent.EXTRA_SUBJECT, mActivity.getString(R.string.title_share_transcript));
mActivity.startActivity(Intent.createChooser(intent, mActivity.getString(R.string.title_share_transcript_with)));
} catch (Exception e) {
Logger.logStackTraceWithMessage(LOG_TAG,"Failed to get share session transcript of length " + transcriptText.length(), e);
}
// See https://github.com/termux/termux-app/issues/1166.
transcriptText = DataUtils.getTruncatedCommandOutput(transcriptText, DataUtils.TRANSACTION_SIZE_LIMIT_IN_BYTES, false, true, false).trim();
ShareUtils.shareText(mActivity, mActivity.getString(R.string.title_share_transcript),
transcriptText, mActivity.getString(R.string.title_share_transcript_with));
}
public void shareSelectedText() {
String selectedText = mActivity.getTerminalView().getStoredSelectedText();
if (DataUtils.isNullOrEmpty(selectedText)) return;
ShareUtils.shareText(mActivity, mActivity.getString(R.string.title_share_selected_text),
selectedText, mActivity.getString(R.string.title_share_selected_text_with));
}
public void showUrlSelection() {
@ -665,7 +697,7 @@ public class TermuxTerminalViewClient extends TermuxTerminalViewClientBase {
String text = ShellUtils.getTerminalSessionTranscriptText(session, true, true);
LinkedHashSet<CharSequence> urlSet = UrlUtils.extractUrls(text);
LinkedHashSet<CharSequence> urlSet = TermuxUrlUtils.extractUrls(text);
if (urlSet.isEmpty()) {
new AlertDialog.Builder(mActivity).setMessage(R.string.title_select_url_none_found).show();
return;
@ -677,9 +709,7 @@ public class TermuxTerminalViewClient extends TermuxTerminalViewClientBase {
// Click to copy url to clipboard:
final AlertDialog dialog = new AlertDialog.Builder(mActivity).setItems(urls, (di, which) -> {
String url = (String) urls[which];
ClipboardManager clipboard = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setPrimaryClip(new ClipData(null, new String[]{"text/plain"}, new ClipData.Item(url)));
Toast.makeText(mActivity, R.string.msg_select_url_copied_to_clipboard, Toast.LENGTH_LONG).show();
ShareUtils.copyTextToClipboard(mActivity, url, mActivity.getString(R.string.msg_select_url_copied_to_clipboard));
}).setTitle(R.string.title_select_url_dialog).create();
// Long press to open URL:
@ -688,7 +718,7 @@ public class TermuxTerminalViewClient extends TermuxTerminalViewClientBase {
lv.setOnItemLongClickListener((parent, view, position, id) -> {
dialog.dismiss();
String url = (String) urls[position];
ShareUtils.openURL(mActivity, url);
ShareUtils.openUrl(mActivity, url);
return true;
});
});
@ -705,8 +735,8 @@ public class TermuxTerminalViewClient extends TermuxTerminalViewClientBase {
MessageDialogUtils.showMessage(mActivity, TermuxConstants.TERMUX_APP_NAME + " Report Issue",
mActivity.getString(R.string.msg_add_termux_debug_info),
mActivity.getString(R.string.action_yes), (dialog, which) -> reportIssueFromTranscript(transcriptText, true),
mActivity.getString(R.string.action_no), (dialog, which) -> reportIssueFromTranscript(transcriptText, false),
mActivity.getString(com.termux.shared.R.string.action_yes), (dialog, which) -> reportIssueFromTranscript(transcriptText, true),
mActivity.getString(com.termux.shared.R.string.action_no), (dialog, which) -> reportIssueFromTranscript(transcriptText, false),
null);
}
@ -724,12 +754,19 @@ public class TermuxTerminalViewClient extends TermuxTerminalViewClientBase {
reportString.append("\n").append(MarkdownUtils.getMarkdownCodeForString(transcriptText, true));
reportString.append("\n##\n");
reportString.append("\n\n").append(TermuxUtils.getAppInfoMarkdownString(mActivity, true));
reportString.append("\n\n").append(AndroidUtils.getDeviceInfoMarkdownString(mActivity));
if (addTermuxDebugInfo) {
reportString.append("\n\n").append(TermuxUtils.getAppInfoMarkdownString(mActivity, TermuxUtils.AppInfoMode.TERMUX_AND_PLUGIN_PACKAGES));
} else {
reportString.append("\n\n").append(TermuxUtils.getAppInfoMarkdownString(mActivity, TermuxUtils.AppInfoMode.TERMUX_PACKAGE));
}
String termuxAptInfo = TermuxUtils.geAPTInfoMarkdownString(mActivity);
if (termuxAptInfo != null)
reportString.append("\n\n").append(termuxAptInfo);
reportString.append("\n\n").append(AndroidUtils.getDeviceInfoMarkdownString(mActivity, true));
if (TermuxBootstrap.isAppPackageManagerAPT()) {
String termuxAptInfo = TermuxUtils.geAPTInfoMarkdownString(mActivity);
if (termuxAptInfo != null)
reportString.append("\n\n").append(termuxAptInfo);
}
if (addTermuxDebugInfo) {
String termuxDebugInfo = TermuxUtils.getTermuxDebugMarkdownString(mActivity);
@ -738,14 +775,16 @@ public class TermuxTerminalViewClient extends TermuxTerminalViewClientBase {
}
String userActionName = UserAction.REPORT_ISSUE_FROM_TRANSCRIPT.getName();
ReportActivity.startReportActivity(mActivity,
new ReportInfo(userActionName,
TermuxConstants.TERMUX_APP.TERMUX_ACTIVITY_NAME, title, null,
reportString.toString(), "\n\n" + TermuxUtils.getReportIssueMarkdownString(mActivity),
false,
userActionName,
Environment.getExternalStorageDirectory() + "/" +
FileUtils.sanitizeFileName(TermuxConstants.TERMUX_APP_NAME + "-" + userActionName + ".log", true, true)));
ReportInfo reportInfo = new ReportInfo(userActionName,
TermuxConstants.TERMUX_APP.TERMUX_ACTIVITY_NAME, title);
reportInfo.setReportString(reportString.toString());
reportInfo.setReportStringSuffix("\n\n" + TermuxUtils.getReportIssueMarkdownString(mActivity));
reportInfo.setReportSaveFileLabelAndPath(userActionName,
Environment.getExternalStorageDirectory() + "/" +
FileUtils.sanitizeFileName(TermuxConstants.TERMUX_APP_NAME + "-" + userActionName + ".log", true, true));
ReportActivity.startReportActivity(mActivity, reportInfo);
}
}.start();
}
@ -755,12 +794,9 @@ public class TermuxTerminalViewClient extends TermuxTerminalViewClientBase {
if (session == null) return;
if (!session.isRunning()) return;
ClipboardManager clipboard = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clipData = clipboard.getPrimaryClip();
if (clipData == null) return;
CharSequence paste = clipData.getItemAt(0).coerceToText(mActivity);
if (!TextUtils.isEmpty(paste))
session.getEmulator().paste(paste.toString());
String text = ShareUtils.getTextStringFromClipboardIfSet(mActivity, true);
if (text != null)
session.getEmulator().paste(text);
}
}

View File

@ -11,7 +11,7 @@ import androidx.viewpager.widget.ViewPager;
import com.termux.R;
import com.termux.app.TermuxActivity;
import com.termux.shared.terminal.io.extrakeys.ExtraKeysView;
import com.termux.shared.termux.extrakeys.ExtraKeysView;
import com.termux.terminal.TerminalSession;
public class TerminalToolbarViewPager {
@ -44,11 +44,11 @@ public class TerminalToolbarViewPager {
if (position == 0) {
layout = inflater.inflate(R.layout.view_terminal_toolbar_extra_keys, collection, false);
ExtraKeysView extraKeysView = (ExtraKeysView) layout;
extraKeysView.setExtraKeysViewClient(new TermuxTerminalExtraKeys(mActivity.getTerminalView(),
mActivity.getTermuxTerminalViewClient(), mActivity.getTermuxTerminalSessionClient()));
extraKeysView.setExtraKeysViewClient(mActivity.getTermuxTerminalExtraKeys());
extraKeysView.setButtonTextAllCaps(mActivity.getProperties().shouldExtraKeysTextBeAllCaps());
mActivity.setExtraKeysView(extraKeysView);
extraKeysView.reload(mActivity.getProperties().getExtraKeysInfo());
extraKeysView.reload(mActivity.getTermuxTerminalExtraKeys().getExtraKeysInfo(),
mActivity.getTerminalToolbarDefaultHeight());
// apply extra keys fix if enabled in prefs
if (mActivity.getProperties().isUsingFullScreen() && mActivity.getProperties().isUsingFullScreenWorkAround()) {

View File

@ -7,23 +7,78 @@ import android.view.View;
import androidx.annotation.NonNull;
import androidx.drawerlayout.widget.DrawerLayout;
import com.termux.app.terminal.TermuxTerminalSessionClient;
import com.termux.app.TermuxActivity;
import com.termux.app.terminal.TermuxTerminalSessionActivityClient;
import com.termux.app.terminal.TermuxTerminalViewClient;
import com.termux.shared.terminal.io.TerminalExtraKeys;
import com.termux.shared.logger.Logger;
import com.termux.shared.termux.extrakeys.ExtraKeysConstants;
import com.termux.shared.termux.extrakeys.ExtraKeysInfo;
import com.termux.shared.termux.settings.properties.TermuxPropertyConstants;
import com.termux.shared.termux.settings.properties.TermuxSharedProperties;
import com.termux.shared.termux.terminal.io.TerminalExtraKeys;
import com.termux.view.TerminalView;
import org.json.JSONException;
public class TermuxTerminalExtraKeys extends TerminalExtraKeys {
private ExtraKeysInfo mExtraKeysInfo;
TermuxTerminalViewClient mTermuxTerminalViewClient;
TermuxTerminalSessionClient mTermuxTerminalSessionClient;
final TermuxActivity mActivity;
final TermuxTerminalViewClient mTermuxTerminalViewClient;
final TermuxTerminalSessionActivityClient mTermuxTerminalSessionActivityClient;
public TermuxTerminalExtraKeys(@NonNull TerminalView terminalView,
private static final String LOG_TAG = "TermuxTerminalExtraKeys";
public TermuxTerminalExtraKeys(TermuxActivity activity, @NonNull TerminalView terminalView,
TermuxTerminalViewClient termuxTerminalViewClient,
TermuxTerminalSessionClient termuxTerminalSessionClient) {
TermuxTerminalSessionActivityClient termuxTerminalSessionActivityClient) {
super(terminalView);
mActivity = activity;
mTermuxTerminalViewClient = termuxTerminalViewClient;
mTermuxTerminalSessionClient = termuxTerminalSessionClient;
mTermuxTerminalSessionActivityClient = termuxTerminalSessionActivityClient;
setExtraKeys();
}
/**
* Set the terminal extra keys and style.
*/
private void setExtraKeys() {
mExtraKeysInfo = null;
try {
// The mMap stores the extra key and style string values while loading properties
// Check {@link #getExtraKeysInternalPropertyValueFromValue(String)} and
// {@link #getExtraKeysStyleInternalPropertyValueFromValue(String)}
String extrakeys = (String) mActivity.getProperties().getInternalPropertyValue(TermuxPropertyConstants.KEY_EXTRA_KEYS, true);
String extraKeysStyle = (String) mActivity.getProperties().getInternalPropertyValue(TermuxPropertyConstants.KEY_EXTRA_KEYS_STYLE, true);
ExtraKeysConstants.ExtraKeyDisplayMap extraKeyDisplayMap = ExtraKeysInfo.getCharDisplayMapForStyle(extraKeysStyle);
if (ExtraKeysConstants.EXTRA_KEY_DISPLAY_MAPS.DEFAULT_CHAR_DISPLAY.equals(extraKeyDisplayMap) && !TermuxPropertyConstants.DEFAULT_IVALUE_EXTRA_KEYS_STYLE.equals(extraKeysStyle)) {
Logger.logError(TermuxSharedProperties.LOG_TAG, "The style \"" + extraKeysStyle + "\" for the key \"" + TermuxPropertyConstants.KEY_EXTRA_KEYS_STYLE + "\" is invalid. Using default style instead.");
extraKeysStyle = TermuxPropertyConstants.DEFAULT_IVALUE_EXTRA_KEYS_STYLE;
}
mExtraKeysInfo = new ExtraKeysInfo(extrakeys, extraKeysStyle, ExtraKeysConstants.CONTROL_CHARS_ALIASES);
} catch (JSONException e) {
Logger.showToast(mActivity, "Could not load and set the \"" + TermuxPropertyConstants.KEY_EXTRA_KEYS + "\" property from the properties file: " + e.toString(), true);
Logger.logStackTraceWithMessage(LOG_TAG, "Could not load and set the \"" + TermuxPropertyConstants.KEY_EXTRA_KEYS + "\" property from the properties file: ", e);
try {
mExtraKeysInfo = new ExtraKeysInfo(TermuxPropertyConstants.DEFAULT_IVALUE_EXTRA_KEYS, TermuxPropertyConstants.DEFAULT_IVALUE_EXTRA_KEYS_STYLE, ExtraKeysConstants.CONTROL_CHARS_ALIASES);
} catch (JSONException e2) {
Logger.showToast(mActivity, "Can't create default extra keys",true);
Logger.logStackTraceWithMessage(LOG_TAG, "Could create default extra keys: ", e);
mExtraKeysInfo = null;
}
}
}
public ExtraKeysInfo getExtraKeysInfo() {
return mExtraKeysInfo;
}
@SuppressLint("RtlHardcoded")
@ -39,8 +94,12 @@ public class TermuxTerminalExtraKeys extends TerminalExtraKeys {
else
drawerLayout.openDrawer(Gravity.LEFT);
} else if ("PASTE".equals(key)) {
if(mTermuxTerminalSessionClient != null)
mTermuxTerminalSessionClient.onPasteTextFromClipboard(null);
if(mTermuxTerminalSessionActivityClient != null)
mTermuxTerminalSessionActivityClient.onPasteTextFromClipboard(null);
} else if ("SCROLL".equals(key)) {
TerminalView terminalView = mTermuxTerminalViewClient.getActivity().getTerminalView();
if (terminalView != null && terminalView.mEmulator != null)
terminalView.mEmulator.toggleAutoScrollDisabled();
} else {
super.onTerminalExtraKeyButtonClick(view, key, ctrlDown, altDown, shiftDown, fnDown);
}

View File

@ -1,214 +0,0 @@
package com.termux.app.utils;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.os.Environment;
import androidx.annotation.Nullable;
import com.termux.R;
import com.termux.shared.activities.ReportActivity;
import com.termux.shared.models.errors.Error;
import com.termux.shared.notification.NotificationUtils;
import com.termux.shared.file.FileUtils;
import com.termux.shared.models.ReportInfo;
import com.termux.app.models.UserAction;
import com.termux.shared.notification.TermuxNotificationUtils;
import com.termux.shared.settings.preferences.TermuxAppSharedPreferences;
import com.termux.shared.settings.preferences.TermuxPreferenceConstants;
import com.termux.shared.data.DataUtils;
import com.termux.shared.logger.Logger;
import com.termux.shared.termux.AndroidUtils;
import com.termux.shared.termux.TermuxUtils;
import com.termux.shared.termux.TermuxConstants;
import java.nio.charset.Charset;
public class CrashUtils {
private static final String LOG_TAG = "CrashUtils";
/**
* Notify the user of an app crash at last run by reading the crash info from the crash log file
* at {@link TermuxConstants#TERMUX_CRASH_LOG_FILE_PATH}. The crash log file would have been
* created by {@link com.termux.shared.crash.CrashHandler}.
*
* If the crash log file exists and is not empty and
* {@link TermuxPreferenceConstants.TERMUX_APP#KEY_CRASH_REPORT_NOTIFICATIONS_ENABLED} is
* enabled, then a notification will be shown for the crash on the
* {@link TermuxConstants#TERMUX_CRASH_REPORTS_NOTIFICATION_CHANNEL_NAME} channel, otherwise nothing will be done.
*
* After reading from the crash log file, it will be moved to {@link TermuxConstants#TERMUX_CRASH_LOG_BACKUP_FILE_PATH}.
*
* @param context The {@link Context} for operations.
* @param logTagParam The log tag to use for logging.
*/
public static void notifyAppCrashOnLastRun(final Context context, final String logTagParam) {
if (context == null) return;
TermuxAppSharedPreferences preferences = TermuxAppSharedPreferences.build(context);
if (preferences == null) return;
// If user has disabled notifications for crashes
if (!preferences.areCrashReportNotificationsEnabled())
return;
new Thread() {
@Override
public void run() {
String logTag = DataUtils.getDefaultIfNull(logTagParam, LOG_TAG);
if (!FileUtils.regularFileExists(TermuxConstants.TERMUX_CRASH_LOG_FILE_PATH, false))
return;
Error error;
StringBuilder reportStringBuilder = new StringBuilder();
// Read report string from crash log file
error = FileUtils.readStringFromFile("crash log", TermuxConstants.TERMUX_CRASH_LOG_FILE_PATH, Charset.defaultCharset(), reportStringBuilder, false);
if (error != null) {
Logger.logErrorExtended(logTag, error.toString());
return;
}
// Move crash log file to backup location if it exists
error = FileUtils.moveRegularFile("crash log", TermuxConstants.TERMUX_CRASH_LOG_FILE_PATH, TermuxConstants.TERMUX_CRASH_LOG_BACKUP_FILE_PATH, true);
if (error != null) {
Logger.logErrorExtended(logTag, error.toString());
}
String reportString = reportStringBuilder.toString();
if (reportString.isEmpty())
return;
Logger.logDebug(logTag, "A crash log file found at \"" + TermuxConstants.TERMUX_CRASH_LOG_FILE_PATH + "\".");
sendCrashReportNotification(context, logTag, reportString, false, false);
}
}.start();
}
/**
* Send a crash report notification for {@link TermuxConstants#TERMUX_CRASH_REPORTS_NOTIFICATION_CHANNEL_ID}
* and {@link TermuxConstants#TERMUX_CRASH_REPORTS_NOTIFICATION_CHANNEL_NAME}.
*
* @param context The {@link Context} for operations.
* @param logTag The log tag to use for logging.
* @param message The message for the crash report.
* @param forceNotification If set to {@code true}, then a notification will be shown
* regardless of if pending intent is {@code null} or
* {@link TermuxPreferenceConstants.TERMUX_APP#KEY_CRASH_REPORT_NOTIFICATIONS_ENABLED}
* is {@code false}.
* @param addAppAndDeviceInfo If set to {@code true}, then app and device info will be appended
* to the message.
*/
public static void sendCrashReportNotification(final Context context, String logTag, String message, boolean forceNotification, boolean addAppAndDeviceInfo) {
if (context == null) return;
TermuxAppSharedPreferences preferences = TermuxAppSharedPreferences.build(context);
if (preferences == null) return;
// If user has disabled notifications for crashes
if (!preferences.areCrashReportNotificationsEnabled() && !forceNotification)
return;
logTag = DataUtils.getDefaultIfNull(logTag, LOG_TAG);
// Send a notification to show the crash log which when clicked will open the {@link ReportActivity}
// to show the details of the crash
String title = TermuxConstants.TERMUX_APP_NAME + " Crash Report";
Logger.logDebug(logTag, "Sending \"" + title + "\" notification.");
StringBuilder reportString = new StringBuilder(message);
if (addAppAndDeviceInfo) {
reportString.append("\n\n").append(TermuxUtils.getAppInfoMarkdownString(context, true));
reportString.append("\n\n").append(AndroidUtils.getDeviceInfoMarkdownString(context));
}
String userActionName = UserAction.CRASH_REPORT.getName();
ReportActivity.NewInstanceResult result = ReportActivity.newInstance(context, new ReportInfo(userActionName,
logTag, title, null, reportString.toString(),
"\n\n" + TermuxUtils.getReportIssueMarkdownString(context), true,
userActionName,
Environment.getExternalStorageDirectory() + "/" +
FileUtils.sanitizeFileName(TermuxConstants.TERMUX_APP_NAME + "-" + userActionName + ".log", true, true)));
if (result.contentIntent == null) return;
// Must ensure result code for PendingIntents and id for notification are unique otherwise will override previous
int nextNotificationId = TermuxNotificationUtils.getNextNotificationId(context);
PendingIntent contentIntent = PendingIntent.getActivity(context, nextNotificationId, result.contentIntent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent deleteIntent = null;
if (result.deleteIntent != null)
deleteIntent = PendingIntent.getBroadcast(context, nextNotificationId, result.deleteIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// Setup the notification channel if not already set up
setupCrashReportsNotificationChannel(context);
// Build the notification
Notification.Builder builder = getCrashReportsNotificationBuilder(context, title, null,
null, contentIntent, deleteIntent, NotificationUtils.NOTIFICATION_MODE_VIBRATE);
if (builder == null) return;
// Send the notification
NotificationManager notificationManager = NotificationUtils.getNotificationManager(context);
if (notificationManager != null)
notificationManager.notify(nextNotificationId, builder.build());
}
/**
* Get {@link Notification.Builder} for {@link TermuxConstants#TERMUX_CRASH_REPORTS_NOTIFICATION_CHANNEL_ID}
* and {@link TermuxConstants#TERMUX_CRASH_REPORTS_NOTIFICATION_CHANNEL_NAME}.
*
* @param context The {@link Context} for operations.
* @param title The title for the notification.
* @param notificationText The second line text of the notification.
* @param notificationBigText The full text of the notification that may optionally be styled.
* @param contentIntent The {@link PendingIntent} which should be sent when notification is clicked.
* @param deleteIntent The {@link PendingIntent} which should be sent when notification is deleted.
* @param notificationMode The notification mode. It must be one of {@code NotificationUtils.NOTIFICATION_MODE_*}.
* @return Returns the {@link Notification.Builder}.
*/
@Nullable
public static Notification.Builder getCrashReportsNotificationBuilder(final Context context, final CharSequence title, final CharSequence notificationText, final CharSequence notificationBigText, final PendingIntent contentIntent, final PendingIntent deleteIntent, final int notificationMode) {
Notification.Builder builder = NotificationUtils.geNotificationBuilder(context,
TermuxConstants.TERMUX_CRASH_REPORTS_NOTIFICATION_CHANNEL_ID, Notification.PRIORITY_HIGH,
title, notificationText, notificationBigText, contentIntent, deleteIntent, notificationMode);
if (builder == null) return null;
// Enable timestamp
builder.setShowWhen(true);
// Set notification icon
builder.setSmallIcon(R.drawable.ic_error_notification);
// Set background color for small notification icon
builder.setColor(0xFF607D8B);
// Dismiss on click
builder.setAutoCancel(true);
return builder;
}
/**
* Setup the notification channel for {@link TermuxConstants#TERMUX_CRASH_REPORTS_NOTIFICATION_CHANNEL_ID} and
* {@link TermuxConstants#TERMUX_CRASH_REPORTS_NOTIFICATION_CHANNEL_NAME}.
*
* @param context The {@link Context} for operations.
*/
public static void setupCrashReportsNotificationChannel(final Context context) {
NotificationUtils.setupNotificationChannel(context, TermuxConstants.TERMUX_CRASH_REPORTS_NOTIFICATION_CHANNEL_ID,
TermuxConstants.TERMUX_CRASH_REPORTS_NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
}
}

View File

@ -1,9 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
android:layout_height="match_parent"
android:orientation="vertical">
<include
layout="@layout/partial_primary_toolbar"
android:id="@+id/partial_primary_toolbar"/>
<FrameLayout
android:id="@+id/settings"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>

View File

@ -1,4 +1,6 @@
<com.termux.app.terminal.TermuxActivityRootView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_termux_root_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
@ -25,23 +27,23 @@
android:id="@+id/terminal_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:defaultFocusHighlightEnabled="false"
android:focusableInTouchMode="true"
android:scrollbarThumbVertical="@drawable/terminal_scroll_shape"
android:scrollbars="vertical"
android:importantForAutofill="no"
android:autofillHints="password" />
tools:ignore="UnusedAttribute" />
<LinearLayout
android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@android:color/white"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
android:descendantFocusability="blocksDescendants"
android:orientation="vertical">
android:orientation="vertical"
android:background="?attr/termuxActivityDrawerBackground">
<LinearLayout
android:layout_width="match_parent"
@ -53,7 +55,8 @@
android:layout_height="40dp"
android:src="@drawable/ic_settings"
android:background="@null"
android:contentDescription="@string/action_open_settings" />
android:contentDescription="@string/action_open_settings"
app:tint="?attr/termuxActivityDrawerImageTint" />
</LinearLayout>
<ListView
@ -71,7 +74,7 @@
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
<com.google.android.material.button.MaterialButton
android:id="@+id/toggle_keyboard_button"
style="?android:attr/buttonBarButtonStyle"
android:layout_width="match_parent"
@ -79,7 +82,7 @@
android:layout_weight="1"
android:text="@string/action_toggle_soft_keyboard" />
<Button
<com.google.android.material.button.MaterialButton
android:id="@+id/new_session_button"
style="?android:attr/buttonBarButtonStyle"
android:layout_width="match_parent"
@ -96,7 +99,7 @@
android:visibility="gone"
android:layout_width="match_parent"
android:layout_height="37.5dp"
android:background="@android:drawable/screen_background_dark_transparent"
android:background="@color/black"
android:layout_alignParentBottom="true" />
</RelativeLayout>

View File

@ -1,4 +1,4 @@
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
<com.google.android.material.textview.MaterialTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/session_title"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<com.termux.shared.terminal.io.extrakeys.ExtraKeysView xmlns:android="http://schemas.android.com/apk/res/android"
<com.termux.shared.termux.extrakeys.ExtraKeysView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/terminal_toolbar_extra_keys"
style="?android:attr/buttonBarStyle"
android:layout_width="match_parent"

View File

@ -2,4 +2,5 @@
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@android:color/black"/>
<foreground android:drawable="@drawable/ic_foreground"/>
<monochrome android:drawable="@drawable/ic_foreground"/>
</adaptive-icon>

View File

@ -2,4 +2,5 @@
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@android:color/black"/>
<foreground android:drawable="@drawable/ic_foreground"/>
<monochrome android:drawable="@drawable/ic_foreground"/>
</adaptive-icon>

View File

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!--
https://material.io/develop/android/theming/dark
-->
<!-- TermuxActivity DayNight NoActionBar theme. -->
<!-- See https://developer.android.com/training/material/theme.html for how to customize the Material theme. -->
<!-- NOTE: Cannot use "Light." since it hides the terminal scrollbar on the default black background. -->
<style name="Theme.TermuxActivity.DayNight.NoActionBar" parent="Theme.TermuxApp.DayNight.NoActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/black</item>
<item name="colorPrimaryVariant">@color/black</item>
<item name="android:windowBackground">@color/black</item>
<!-- Avoid action mode toolbar pushing down terminal content when
selecting text on pre-6.0 (non-floating toolbar). -->
<item name="android:windowActionModeOverlay">true</item>
<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowTranslucentNavigation">true</item>
<!-- https://developer.android.com/training/tv/start/start.html#transition-color -->
<item name="android:windowAllowReturnTransitionOverlap">true</item>
<item name="android:windowAllowEnterTransitionOverlap">true</item>
<!-- Left drawer. -->
<item name="buttonBarButtonStyle">@style/TermuxActivity.Drawer.ButtonBarStyle.Dark</item>
<item name="termuxActivityDrawerBackground">@color/black</item>
<item name="termuxActivityDrawerImageTint">@color/white</item>
<!-- Extra keys colors. -->
<item name="extraKeysButtonTextColor">@color/white</item>
<item name="extraKeysButtonActiveTextColor">@color/red_400</item>
<item name="extraKeysButtonBackgroundColor">@color/black</item>
<item name="extraKeysButtonActiveBackgroundColor">@color/grey_500</item>
</style>
</resources>

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="termuxActivityDrawerBackground" format="reference" />
<attr name="termuxActivityDrawerImageTint" format="reference" />
</resources>

View File

@ -33,7 +33,11 @@
<string name="bootstrap_error_try_again">Try again</string>
<string name="bootstrap_error_not_primary_user_message">&TERMUX_APP_NAME; can only be run as the primary user.
\nBootstrap binaries compiled for &TERMUX_APP_NAME; have hardcoded $PREFIX path and cannot be installed
under any path other than %1$s.</string>
under any path other than:\n%1$s.</string>
<string name="bootstrap_error_installed_on_portable_sd">&TERMUX_APP_NAME; cannot be installed on
portable/external/removable sd card on your device.
\nBootstrap binaries compiled for &TERMUX_APP_NAME; have hardcoded $PREFIX path and cannot be installed
under any path other than:\n%1$s.</string>
@ -65,6 +69,11 @@
<string name="title_share_transcript">Terminal transcript</string>
<string name="title_share_transcript_with">Send transcript to:</string>
<string name="action_share_selected_text">Share selected text</string>
<string name="title_share_selected_text">Terminal Text</string>
<string name="title_share_selected_text_with">Send selected text to:</string>
<string name="action_autofill_username">Autofill username</string>
<string name="action_autofill_password">Autofill password</string>
<string name="action_reset_terminal">Reset</string>
@ -95,14 +104,19 @@
<!-- TermuxService -->
<string name="error_display_over_other_apps_permission_not_granted">&TERMUX_APP_NAME; requires
<string name="error_display_over_other_apps_permission_not_granted_to_start_terminal">&TERMUX_APP_NAME; requires
\"Display over other apps\" permission to start terminal sessions from background on Android >= 10.
Grants it from Settings -> Apps -> &TERMUX_APP_NAME; -> Advanced</string>
<string name="error_termux_service_invalid_execution_command_runner">Invalid execution command runner to TermuxService: `%1$s`</string>
<string name="error_termux_service_unsupported_execution_command_runner">Unsupported execution command runner to TermuxService: `%1$s`</string>
<string name="error_termux_service_unsupported_execution_command_shell_create_mode">Unsupported execution command shell create mode to TermuxService: `%1$s`</string>
<string name="error_termux_service_execution_command_shell_name_unset">Shell name not set but `%1$s` shell create mode passed</string>
<!-- Termux RunCommandService -->
<string name="error_run_command_service_invalid_intent_action">Invalid intent action to RunCommandService: `%1$s`</string>
<string name="error_run_command_service_invalid_execution_command_runner">Invalid execution command runner to RunCommandService: `%1$s`</string>
<string name="error_run_command_service_mandatory_extra_missing">Mandatory extra missing to RunCommandService: \"%1$s\"</string>
<string name="error_run_command_service_api_help">Visit %1$s for more info on RUN_COMMAND Intent usage.</string>
@ -116,8 +130,8 @@
<!-- Miscellaneous -->
<string name="error_allow_external_apps_ungranted">%1$s requires `allow-external-apps`
property to be set to `true` in `%2$s` file.</string>
<string name="error_termux_service_start_failed_general">Failed to start TermuxService. Check logcat for exception message.</string>
<string name="error_termux_service_start_failed_bg">Failed to start TermuxService while app is in background due to android bg restrictions.</string>

View File

@ -1,52 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="Theme.Termux" parent="@android:style/Theme.Material.Light.NoActionBar">
<item name="android:statusBarColor">#000000</item>
<item name="android:colorPrimary">#FF000000</item>
<item name="android:windowBackground">@android:color/black</item>
<!-- Seen in buttons on left drawer: -->
<item name="android:colorAccent">#212121</item>
<item name="android:alertDialogTheme">@style/TermuxAlertDialogStyle</item>
<!-- Avoid action mode toolbar pushing down terminal content when
selecting text on pre-6.0 (non-floating toolbar). -->
<item name="android:windowActionModeOverlay">true</item>
<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowTranslucentNavigation">true</item>
<!-- https://developer.android.com/training/tv/start/start.html#transition-color -->
<item name="android:windowAllowReturnTransitionOverlap">true</item>
<item name="android:windowAllowEnterTransitionOverlap">true</item>
</style>
<!-- See https://developer.android.com/training/material/theme.html for how to customize the Material theme. -->
<!-- NOTE: Cannot use "Light." since it hides the terminal scrollbar on the default black background. -->
<style name="Theme.Termux.Black" parent="@android:style/Theme.Material.NoActionBar">
<item name="android:statusBarColor">#000000</item>
<item name="android:colorPrimary">#FF000000</item>
<item name="android:windowBackground">@android:color/black</item>
<!-- Seen in buttons on left drawer: -->
<item name="android:colorAccent">#FDFDFD</item>
<!-- Avoid action mode toolbar pushing down terminal content when
selecting text on pre-6.0 (non-floating toolbar). -->
<item name="android:windowActionModeOverlay">true</item>
<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowTranslucentNavigation">true</item>
<!-- https://developer.android.com/training/tv/start/start.html#transition-color -->
<item name="android:windowAllowReturnTransitionOverlap">true</item>
<item name="android:windowAllowEnterTransitionOverlap">true</item>
</style>
<style name="TermuxAlertDialogStyle" parent="@android:style/Theme.Material.Light.Dialog.Alert">
<!-- Seen in buttons on alert dialog: -->
<item name="android:colorAccent">#212121</item>
</style>
<style name="TermuxActivity.Drawer.ButtonBarStyle.Light" parent="@style/Widget.MaterialComponents.Button.TextButton">
<item name="android:textColor">@color/black</item>
</style>
<style name="TermuxActivity.Drawer.ButtonBarStyle.Dark" parent="@style/Widget.MaterialComponents.Button.TextButton">
<item name="android:textColor">@color/white</item>
</style>
</resources>

View File

@ -0,0 +1,49 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!--
https://material.io/develop/android/theming/dark
-->
<!-- TermuxApp Light DarkActionBar theme. -->
<style name="Theme.TermuxApp.Light.DarkActionBar" parent="Theme.BaseActivity.Light.DarkActionBar"/>
<!-- TermuxApp Light NoActionBar theme. -->
<style name="Theme.TermuxApp.Light.NoActionBar" parent="Theme.BaseActivity.Light.NoActionBar"/>
<!-- TermuxApp DayNight DarkActionBar theme. -->
<style name="Theme.TermuxApp.DayNight.DarkActionBar" parent="Theme.BaseActivity.DayNight.DarkActionBar"/>
<!-- TermuxApp DayNight NoActionBar theme. -->
<style name="Theme.TermuxApp.DayNight.NoActionBar" parent="Theme.BaseActivity.DayNight.NoActionBar"/>
<!-- TermuxActivity DayNight NoActionBar theme. -->
<style name="Theme.TermuxActivity.DayNight.NoActionBar" parent="Theme.TermuxApp.DayNight.NoActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/black</item>
<item name="colorPrimaryVariant">@color/black</item>
<item name="android:windowBackground">@color/black</item>
<!-- Avoid action mode toolbar pushing down terminal content when
selecting text on pre-6.0 (non-floating toolbar). -->
<item name="android:windowActionModeOverlay">true</item>
<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowTranslucentNavigation">true</item>
<!-- https://developer.android.com/training/tv/start/start.html#transition-color -->
<item name="android:windowAllowReturnTransitionOverlap">true</item>
<item name="android:windowAllowEnterTransitionOverlap">true</item>
<!-- Left drawer. -->
<item name="buttonBarButtonStyle">@style/TermuxActivity.Drawer.ButtonBarStyle.Light</item>
<item name="termuxActivityDrawerBackground">@color/white</item>
<item name="termuxActivityDrawerImageTint">@color/black</item>
<!-- Extra keys colors. -->
<item name="extraKeysButtonTextColor">@color/white</item>
<item name="extraKeysButtonActiveTextColor">@color/red_400</item>
<item name="extraKeysButtonBackgroundColor">@color/black</item>
<item name="extraKeysButtonActiveBackgroundColor">@color/grey_500</item>
</style>
</resources>

View File

@ -1,6 +1,6 @@
package com.termux.app;
import com.termux.shared.data.UrlUtils;
import com.termux.shared.termux.data.TermuxUrlUtils;
import org.junit.Assert;
import org.junit.Test;
@ -13,7 +13,7 @@ public class TermuxActivityTest {
private void assertUrlsAre(String text, String... urls) {
LinkedHashSet<String> expected = new LinkedHashSet<>();
Collections.addAll(expected, urls);
Assert.assertEquals(expected, UrlUtils.extractUrls(text));
Assert.assertEquals(expected, TermuxUrlUtils.extractUrls(text));
}
@Test

View File

@ -1,4 +1,6 @@
package com.termux.filepicker;
package com.termux.app.api.file;
import com.termux.app.api.file.FileReceiverActivity;
import org.junit.Assert;
import org.junit.Test;
@ -9,7 +11,7 @@ import java.util.ArrayList;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
public class TermuxFileReceiverActivityTest {
public class FileReceiverActivityTest {
@Test
public void testIsSharedTextAnUrl() {
@ -19,13 +21,15 @@ public class TermuxFileReceiverActivityTest {
validUrls.add("https://example.com/path/parameter=foo");
validUrls.add("magnet:?xt=urn:btih:d540fc48eb12f2833163eed6421d449dd8f1ce1f&dn=Ubuntu+desktop+19.04+%2864bit%29&tr=udp%3A%2F%2Ftracker.openbittorrent.com%3A80&tr=udp%3A%2F%2Ftracker.publicbt.com%3A80&tr=udp%3A%2F%2Ftracker.ccc.de%3A80");
for (String url : validUrls) {
Assert.assertTrue(TermuxFileReceiverActivity.isSharedTextAnUrl(url));
Assert.assertTrue(FileReceiverActivity.isSharedTextAnUrl(url));
}
List<String> invalidUrls = new ArrayList<>();
invalidUrls.add("a test with example.com");
invalidUrls.add("");
invalidUrls.add(null);
for (String url : invalidUrls) {
Assert.assertFalse(TermuxFileReceiverActivity.isSharedTextAnUrl(url));
Assert.assertFalse(FileReceiverActivity.isSharedTextAnUrl(url));
}
}

View File

@ -4,7 +4,7 @@ buildscript {
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.2.2'
classpath "com.android.tools.build:gradle:8.13.2"
}
}
@ -15,7 +15,3 @@ allprojects {
maven { url "https://jitpack.io" }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

13
docs/en/index.md Normal file
View File

@ -0,0 +1,13 @@
---
page_ref: /docs/apps/termux/index.html
---
# Termux App Docs
<!--- DOC_HEADER_PLACEHOLDER -->
Welcome to documentation for the [Termux App].
##
[Termux App]: https://github.com/termux/termux-app

View File

@ -12,13 +12,17 @@
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
org.gradle.jvmargs=-Xmx2048M
org.gradle.jvmargs=-Xmx2048M \
--add-exports=java.base/sun.nio.ch=ALL-UNNAMED \
--add-opens=java.base/java.lang=ALL-UNNAMED \
--add-opens=java.base/java.lang.reflect=ALL-UNNAMED \
--add-opens=java.base/java.io=ALL-UNNAMED \
--add-exports=jdk.unsupported/sun.misc=ALL-UNNAMED
android.useAndroidX=true
minSdkVersion=24
minSdkVersion=21
targetSdkVersion=28
ndkVersion=22.1.7171670
compileSdkVersion=30
ndkVersion=29.0.14206865
compileSdkVersion=36
markwonVersion=4.6.2

Binary file not shown.

View File

@ -1,5 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

295
gradlew vendored
View File

@ -1,7 +1,7 @@
#!/usr/bin/env sh
#!/bin/sh
#
# Copyright 2015 the original author or authors.
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -15,81 +15,114 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
##
## Gradle start up script for UN*X
##
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
MAX_FD=maximum
warn () {
echo "$*"
}
} >&2
die () {
echo
echo "$*"
echo
exit 1
}
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@ -98,88 +131,118 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

40
gradlew.bat vendored
View File

@ -13,8 +13,10 @@
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%" == "" @echo off
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@ -25,7 +27,8 @@
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@ -40,13 +43,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
@ -56,32 +59,33 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal

View File

@ -1,2 +1,4 @@
jdk:
- openjdk17
env:
JITPACK_NDK_VERSION: "21.1.6352462"
JITPACK_NDK_VERSION: "29.0.14206865"

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

View File

@ -2,6 +2,8 @@ apply plugin: 'com.android.library'
apply plugin: 'maven-publish'
android {
namespace "com.termux.emulator"
compileSdkVersion project.properties.compileSdkVersion.toInteger()
ndkVersion = System.getenv("JITPACK_NDK_VERSION") ?: project.properties.ndkVersion
@ -50,12 +52,13 @@ tasks.withType(Test) {
}
dependencies {
testImplementation 'junit:junit:4.13.2'
implementation "androidx.annotation:annotation:1.9.0"
testImplementation "junit:junit:4.13.2"
}
task sourceJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier "sources"
archiveClassifier = "sources"
}
afterEvaluate {
@ -63,7 +66,7 @@ afterEvaluate {
publications {
// Creates a Maven publication called "release".
release(MavenPublication) {
from components.release
from components.findByName('release')
groupId = 'com.termux'
artifactId = 'terminal-emulator'
version = '0.118.0'

View File

@ -1,2 +1,2 @@
<manifest package="com.termux.terminal">
<manifest>
</manifest>

View File

@ -23,10 +23,10 @@ final class JNI {
* @return the file descriptor resulting from opening /dev/ptmx master device. The sub process will have opened the
* slave device counterpart (/dev/pts/$N) and have it as stdint, stdout and stderr.
*/
public static native int createSubprocess(String cmd, String cwd, String[] args, String[] envVars, int[] processId, int rows, int columns);
public static native int createSubprocess(String cmd, String cwd, String[] args, String[] envVars, int[] processId, int rows, int columns, int cellWidth, int cellHeight);
/** Set the window size for a given pty, which allows connected programs to learn how large their screen is. */
public static native void setPtyWindowSize(int fd, int rows, int cols);
public static native void setPtyWindowSize(int fd, int rows, int cols, int cellWidth, int cellHeight);
/**
* Causes the calling thread to wait for the process associated with the receiver to finish executing.

View File

@ -227,9 +227,9 @@ public final class KeyHandler {
return transformForModifiers("\033[3", keyMode, '~');
case KEYCODE_PAGE_UP:
return "\033[5~";
return transformForModifiers("\033[5", keyMode, '~');
case KEYCODE_PAGE_DOWN:
return "\033[6~";
return transformForModifiers("\033[6", keyMode, '~');
case KEYCODE_DEL:
String prefix = ((keyMode & KEYMOD_ALT) == 0) ? "" : "\033";
// Just do what xterm and gnome-terminal does:

View File

@ -0,0 +1,80 @@
package com.termux.terminal;
import android.util.Log;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
public class Logger {
public static void logError(TerminalSessionClient client, String logTag, String message) {
if (client != null)
client.logError(logTag, message);
else
Log.e(logTag, message);
}
public static void logWarn(TerminalSessionClient client, String logTag, String message) {
if (client != null)
client.logWarn(logTag, message);
else
Log.w(logTag, message);
}
public static void logInfo(TerminalSessionClient client, String logTag, String message) {
if (client != null)
client.logInfo(logTag, message);
else
Log.i(logTag, message);
}
public static void logDebug(TerminalSessionClient client, String logTag, String message) {
if (client != null)
client.logDebug(logTag, message);
else
Log.d(logTag, message);
}
public static void logVerbose(TerminalSessionClient client, String logTag, String message) {
if (client != null)
client.logVerbose(logTag, message);
else
Log.v(logTag, message);
}
public static void logStackTraceWithMessage(TerminalSessionClient client, String tag, String message, Throwable throwable) {
logError(client, tag, getMessageAndStackTraceString(message, throwable));
}
public static String getMessageAndStackTraceString(String message, Throwable throwable) {
if (message == null && throwable == null)
return null;
else if (message != null && throwable != null)
return message + ":\n" + getStackTraceString(throwable);
else if (throwable == null)
return message;
else
return getStackTraceString(throwable);
}
public static String getStackTraceString(Throwable throwable) {
if (throwable == null) return null;
String stackTraceString = null;
try {
StringWriter errors = new StringWriter();
PrintWriter pw = new PrintWriter(errors);
throwable.printStackTrace(pw);
pw.close();
stackTraceString = errors.toString();
errors.close();
} catch (IOException e) {
e.printStackTrace();
}
return stackTraceString;
}
}

View File

@ -54,7 +54,7 @@ public final class TerminalBuffer {
}
public String getSelectedText(int selX1, int selY1, int selX2, int selY2, boolean joinBackLines) {
return getSelectedText(selX1, selY1, selX2, selY2, true, false);
return getSelectedText(selX1, selY1, selX2, selY2, joinBackLines, false);
}
public String getSelectedText(int selX1, int selY1, int selX2, int selY2, boolean joinBackLines, boolean joinFullLines) {
@ -93,8 +93,11 @@ public final class TerminalBuffer {
if (c != ' ') lastPrintingCharIndex = i;
}
}
if (lastPrintingCharIndex != -1)
builder.append(line, x1Index, lastPrintingCharIndex - x1Index + 1);
int len = lastPrintingCharIndex - x1Index + 1;
if (lastPrintingCharIndex != -1 && len > 0)
builder.append(line, x1Index, len);
boolean lineFillsWidth = lastPrintingCharIndex == x2Index - 1;
if ((!joinBackLines || !rowLineWrap) && (!joinFullLines || !lineFillsWidth)
&& row < selY2 && row < mScreenRows - 1) builder.append('\n');
@ -446,8 +449,8 @@ public final class TerminalBuffer {
}
public void setChar(int column, int row, int codePoint, long style) {
if (row >= mScreenRows || column >= mColumns)
throw new IllegalArgumentException("row=" + row + ", column=" + column + ", mScreenRows=" + mScreenRows + ", mColumns=" + mColumns);
if (row < 0 || row >= mScreenRows || column < 0 || column >= mColumns)
throw new IllegalArgumentException("TerminalBuffer.setChar(): row=" + row + ", column=" + column + ", mScreenRows=" + mScreenRows + ", mColumns=" + mColumns);
row = externalToInternalRow(row);
allocateFullLineIfNecessary(row).setChar(column, codePoint, style);
}

View File

@ -71,6 +71,7 @@ public final class TerminalColorScheme {
public void updateWith(Properties props) {
reset();
boolean cursorPropExists = false;
for (Map.Entry<Object, Object> entries : props.entrySet()) {
String key = (String) entries.getKey();
String value = (String) entries.getValue();
@ -82,6 +83,7 @@ public final class TerminalColorScheme {
colorIndex = TextStyle.COLOR_INDEX_BACKGROUND;
} else if (key.equals("cursor")) {
colorIndex = TextStyle.COLOR_INDEX_CURSOR;
cursorPropExists = true;
} else if (key.startsWith("color")) {
try {
colorIndex = Integer.parseInt(key.substring(5));
@ -98,6 +100,27 @@ public final class TerminalColorScheme {
mDefaultColors[colorIndex] = colorValue;
}
if (!cursorPropExists)
setCursorColorForBackground();
}
/**
* If the "cursor" color is not set by user, we need to decide on the appropriate color that will
* be visible on the current terminal background. White will not be visible on light backgrounds
* and black won't be visible on dark backgrounds. So we find the perceived brightness of the
* background color and if its below the threshold (too dark), we use white cursor and if its
* above (too bright), we use black cursor.
*/
public void setCursorColorForBackground() {
int backgroundColor = mDefaultColors[TextStyle.COLOR_INDEX_BACKGROUND];
int brightness = TerminalColors.getPerceivedBrightnessOfColor(backgroundColor);
if (brightness > 0) {
if (brightness < 130)
mDefaultColors[TextStyle.COLOR_INDEX_CURSOR] = 0xffffffff;
else
mDefaultColors[TextStyle.COLOR_INDEX_CURSOR] = 0xff000000;
}
}
}

View File

@ -1,5 +1,7 @@
package com.termux.terminal;
import android.graphics.Color;
/** Current terminal colors (if different from default). */
public final class TerminalColors {
@ -73,4 +75,22 @@ public final class TerminalColors {
if (c != 0) mCurrentColors[intoIndex] = c;
}
/**
* Get the perceived brightness of the color based on its RGB components.
*
* https://www.nbdtech.com/Blog/archive/2008/04/27/Calculating-the-Perceived-Brightness-of-a-Color.aspx
* http://alienryderflex.com/hsp.html
*
* @param color The color code int.
* @return Returns value between 0-255.
*/
public static int getPerceivedBrightnessOfColor(int color) {
return (int)
Math.floor(Math.sqrt(
Math.pow(Color.red(color), 2) * 0.241 +
Math.pow(Color.green(color), 2) * 0.691 +
Math.pow(Color.blue(color), 2) * 0.068
));
}
}

View File

@ -79,9 +79,17 @@ public final class TerminalEmulator {
private static final int ESC_CSI_SINGLE_QUOTE = 18;
/** Escape processing: CSI ! */
private static final int ESC_CSI_EXCLAMATION = 19;
/** Escape processing: "ESC _" or Application Program Command (APC). */
private static final int ESC_APC = 20;
/** Escape processing: "ESC _" or Application Program Command (APC), followed by Escape. */
private static final int ESC_APC_ESCAPE = 21;
/** Escape processing: ESC [ <parameter bytes> */
private static final int ESC_CSI_UNSUPPORTED_PARAMETER_BYTE = 22;
/** Escape processing: ESC [ <parameter bytes> <intermediate bytes> */
private static final int ESC_CSI_UNSUPPORTED_INTERMEDIATE_BYTE = 23;
/** The number of parameter arguments. This name comes from the ANSI standard for terminal escape codes. */
private static final int MAX_ESCAPE_PARAMETERS = 16;
/** The number of parameter arguments including colon separated sub-parameters. */
private static final int MAX_ESCAPE_PARAMETERS = 32;
/** Needs to be large enough to contain reasonable OSC 52 pastes. */
private static final int MAX_OSC_STRING_LENGTH = 8192;
@ -126,13 +134,15 @@ public final class TerminalEmulator {
private String mTitle;
private final Stack<String> mTitleStack = new Stack<>();
/** The cursor position. Between (0,0) and (mRows-1, mColumns-1). */
private int mCursorRow, mCursorCol;
/** The number of character rows and columns in the terminal screen. */
public int mRows, mColumns;
/** Size of a terminal cell in pixels. */
private int mCellWidthPixels, mCellHeightPixels;
/** The number of terminal transcript rows that can be scrolled back to. */
public static final int TERMINAL_TRANSCRIPT_ROWS_MIN = 100;
public static final int TERMINAL_TRANSCRIPT_ROWS_MAX = 50000;
@ -172,6 +182,8 @@ public final class TerminalEmulator {
private int mArgIndex;
/** Holds the arguments of the current escape sequence. */
private final int[] mArgs = new int[MAX_ESCAPE_PARAMETERS];
/** Holds the bit flags which arguments are sub parameters (after a colon) - bit N is set if <code>mArgs[N]</code> is a sub parameter. */
private int mArgsSubParamsBitSet = 0;
/** Holds OSC and device control arguments, which can be strings. */
private final StringBuilder mOSCOrDeviceControlArgs = new StringBuilder();
@ -232,15 +244,17 @@ public final class TerminalEmulator {
private boolean mCursorBlinkState;
/**
* Current foreground and background colors. Can either be a color index in [0,259] or a truecolor (24-bit) value.
* Current foreground, background and underline colors. Can either be a color index in [0,259] or a truecolor (24-bit) value.
* For a 24-bit value the top byte (0xff000000) is set.
*
* <p>Note that the underline color is currently parsed but not yet used during rendering.
*
* @see TextStyle
*/
int mForeColor, mBackColor;
int mForeColor, mBackColor, mUnderlineColor;
/** Current {@link TextStyle} effect. */
private int mEffect;
int mEffect;
/**
* The number of scrolled lines since last calling {@link #clearScrollCounter()}. Used for moving selection up along
@ -248,6 +262,9 @@ public final class TerminalEmulator {
*/
private int mScrollCounter = 0;
/** If automatic scrolling of terminal is disabled */
private boolean mAutoScrollDisabled;
private byte mUtf8ToFollow, mUtf8Index;
private final byte[] mUtf8InputBuffer = new byte[4];
private int mLastEmittedCodePoint = -1;
@ -308,13 +325,15 @@ public final class TerminalEmulator {
}
}
public TerminalEmulator(TerminalOutput session, int columns, int rows, Integer transcriptRows, TerminalSessionClient client) {
public TerminalEmulator(TerminalOutput session, int columns, int rows, int cellWidthPixels, int cellHeightPixels, Integer transcriptRows, TerminalSessionClient client) {
mSession = session;
mScreen = mMainBuffer = new TerminalBuffer(columns, getTerminalTranscriptRows(transcriptRows), rows);
mAltBuffer = new TerminalBuffer(columns, rows, rows);
mClient = client;
mRows = rows;
mColumns = columns;
mCellWidthPixels = cellWidthPixels;
mCellHeightPixels = cellHeightPixels;
mTabStop = new boolean[mColumns];
reset();
}
@ -364,7 +383,10 @@ public final class TerminalEmulator {
}
}
public void resize(int columns, int rows) {
public void resize(int columns, int rows, int cellWidthPixels, int cellHeightPixels) {
this.mCellWidthPixels = cellWidthPixels;
this.mCellHeightPixels = cellHeightPixels;
if (mRows == rows && mColumns == columns) {
return;
} else if (columns < 2 || rows < 2) {
@ -546,6 +568,15 @@ public final class TerminalEmulator {
}
public void processCodePoint(int b) {
// The Application Program-Control (APC) string might be arbitrary non-printable characters, so handle that early.
if (mEscapeState == ESC_APC) {
doApc(b);
return;
} else if (mEscapeState == ESC_APC_ESCAPE) {
doApcEscape(b);
return;
}
switch (b) {
case 0: // Null character (NUL, ^@). Do nothing.
break;
@ -631,6 +662,10 @@ public final class TerminalEmulator {
case ESC_CSI:
doCsi(b);
break;
case ESC_CSI_UNSUPPORTED_PARAMETER_BYTE:
case ESC_CSI_UNSUPPORTED_INTERMEDIATE_BYTE:
doCsiUnsupportedParameterOrIntermediateByte(b);
break;
case ESC_CSI_EXCLAMATION:
if (b == 'p') { // Soft terminal reset (DECSTR, http://vt100.net/docs/vt510-rm/DECSTR).
reset();
@ -796,7 +831,6 @@ public final class TerminalEmulator {
int columnsToDelete = Math.min(getArg0(1), columnsAfterCursor);
int columnsToMove = columnsAfterCursor - columnsToDelete;
mScreen.blockCopy(mCursorCol + columnsToDelete, 0, columnsToMove, mRows, mCursorCol, 0);
blockClear(mCursorRow + columnsToMove, 0, columnsToDelete, mRows);
} else {
unknownSequence(b);
}
@ -825,7 +859,7 @@ public final class TerminalEmulator {
if (internalBit != -1) {
value = isDecsetInternalBitSet(internalBit) ? 1 : 2; // 1=set, 2=reset.
} else {
mClient.logError(LOG_TAG, "Got DECRQM for unrecognized private DEC mode=" + mode);
Logger.logError(mClient, LOG_TAG, "Got DECRQM for unrecognized private DEC mode=" + mode);
value = 0; // 0=not recognized, 3=permanently set, 4=permanently reset
}
}
@ -936,10 +970,17 @@ public final class TerminalEmulator {
for (String part : dcs.substring(2).split(";")) {
if (part.length() % 2 == 0) {
StringBuilder transBuffer = new StringBuilder();
char c;
for (int i = 0; i < part.length(); i += 2) {
char c = (char) Long.decode("0x" + part.charAt(i) + "" + part.charAt(i + 1)).longValue();
try {
c = (char) Long.decode("0x" + part.charAt(i) + "" + part.charAt(i + 1)).longValue();
} catch (NumberFormatException e) {
Logger.logStackTraceWithMessage(mClient, LOG_TAG, "Invalid device termcap/terminfo encoded name \"" + part + "\"", e);
continue;
}
transBuffer.append(c);
}
String trans = transBuffer.toString();
String responseValue;
switch (trans) {
@ -962,7 +1003,7 @@ public final class TerminalEmulator {
case "&8": // Undo key - ignore.
break;
default:
mClient.logWarn(LOG_TAG, "Unhandled termcap/terminfo name: '" + trans + "'");
Logger.logWarn(mClient, LOG_TAG, "Unhandled termcap/terminfo name: '" + trans + "'");
}
// Respond with invalid request:
mSession.write("\033P0+r" + part + "\033\\");
@ -974,12 +1015,12 @@ public final class TerminalEmulator {
mSession.write("\033P1+r" + part + "=" + hexEncoded + "\033\\");
}
} else {
mClient.logError(LOG_TAG, "Invalid device termcap/terminfo name of odd length: " + part);
Logger.logError(mClient, LOG_TAG, "Invalid device termcap/terminfo name of odd length: " + part);
}
}
} else {
if (LOG_ESCAPE_SEQUENCES)
mClient.logError(LOG_TAG, "Unrecognized device control string: " + dcs);
Logger.logError(mClient, LOG_TAG, "Unrecognized device control string: " + dcs);
}
finishSequence();
}
@ -996,12 +1037,67 @@ public final class TerminalEmulator {
}
}
/**
* When in {@link #ESC_APC} (APC, Application Program Command) sequence.
*/
private void doApc(int b) {
if (b == 27) {
continueSequence(ESC_APC_ESCAPE);
}
// Eat APC sequences silently for now.
}
/**
* When in {@link #ESC_APC} (APC, Application Program Command) sequence.
*/
private void doApcEscape(int b) {
if (b == '\\') {
// A String Terminator (ST), ending the APC escape sequence.
finishSequence();
} else {
// The Escape character was not the start of a String Terminator (ST),
// but instead just data inside of the APC escape sequence.
continueSequence(ESC_APC);
}
}
private int nextTabStop(int numTabs) {
for (int i = mCursorCol + 1; i < mColumns; i++)
if (mTabStop[i] && --numTabs == 0) return Math.min(i, mRightMargin);
return mRightMargin - 1;
}
/**
* Process byte while in the {@link #ESC_CSI_UNSUPPORTED_PARAMETER_BYTE} or
* {@link #ESC_CSI_UNSUPPORTED_INTERMEDIATE_BYTE} escape state.
*
* Parse unsupported parameter, intermediate and final bytes but ignore them.
*
* > For Control Sequence Introducer, ... the ESC [ is followed by
* > - any number (including none) of "parameter bytes" in the range 0x300x3F (ASCII 09:;<=>?),
* > - then by any number of "intermediate bytes" in the range 0x200x2F (ASCII space and !"#$%&'()*+,-./),
* > - then finally by a single "final byte" in the range 0x400x7E (ASCII @AZ[\]^_`az{|}~).
*
* - https://en.wikipedia.org/wiki/ANSI_escape_code#Control_Sequence_Introducer_commands
* - https://invisible-island.net/xterm/ecma-48-parameter-format.html#section5.4
*/
private void doCsiUnsupportedParameterOrIntermediateByte(int b) {
if (mEscapeState == ESC_CSI_UNSUPPORTED_PARAMETER_BYTE && b >= 0x30 && b <= 0x3F) {
// Supported `09:;>?` or unsupported `<=` parameter byte after an
// initial unsupported parameter byte in `doCsi()`, or a sequential parameter byte.
continueSequence(ESC_CSI_UNSUPPORTED_PARAMETER_BYTE);
} else if (b >= 0x20 && b <= 0x2F) {
// Optional intermediate byte `!"#$%&'()*+,-./` after parameter or intermediate byte.
continueSequence(ESC_CSI_UNSUPPORTED_INTERMEDIATE_BYTE);
} else if (b >= 0x40 && b <= 0x7E) {
// Final byte `@AZ[\]^_`az{|}~` after parameter or intermediate byte.
// Calling `unknownSequence()` would log an error with only a final byte, so ignore it for now.
finishSequence();
} else {
unknownSequence(b);
}
}
/** Process byte while in the {@link #ESC_CSI_QUESTIONMARK} escape state. */
private void doCsiQuestionMark(int b) {
switch (b) {
@ -1069,7 +1165,7 @@ public final class TerminalEmulator {
int externalBit = mArgs[i];
int internalBit = mapDecSetBitToInternalBit(externalBit);
if (internalBit == -1) {
mClient.logWarn(LOG_TAG, "Ignoring request to save/recall decset bit=" + externalBit);
Logger.logWarn(mClient, LOG_TAG, "Ignoring request to save/recall decset bit=" + externalBit);
} else {
if (b == 's') {
mSavedDecSetFlags |= internalBit;
@ -1259,7 +1355,7 @@ public final class TerminalEmulator {
// (1) enables this feature for keys except for those with well-known behavior, e.g., Tab, Backarrow and
// some special control character cases, e.g., Control-Space to make a NUL.
// (2) enables this feature for keys including the exceptions listed.
mClient.logError(LOG_TAG, "(ignored) CSI > MODIFY RESOURCE: " + getArg0(-1) + " to " + getArg1(-1));
Logger.logError(mClient, LOG_TAG, "(ignored) CSI > MODIFY RESOURCE: " + getArg0(-1) + " to " + getArg1(-1));
break;
default:
parseArg(b);
@ -1271,6 +1367,7 @@ public final class TerminalEmulator {
mEscapeState = ESC;
mArgIndex = 0;
Arrays.fill(mArgs, -1);
mArgsSubParamsBitSet = 0;
}
private void doLinefeed() {
@ -1365,8 +1462,8 @@ public final class TerminalEmulator {
// http://www.vt100.net/docs/vt100-ug/chapter3.html: "Move the active position to the same horizontal
// position on the preceding line. If the active position is at the top margin, a scroll down is performed".
if (mCursorRow <= mTopMargin) {
mScreen.blockCopy(0, mTopMargin, mColumns, mBottomMargin - (mTopMargin + 1), 0, mTopMargin + 1);
blockClear(0, mTopMargin, mColumns);
mScreen.blockCopy(mLeftMargin, mTopMargin, mRightMargin - mLeftMargin, mBottomMargin - (mTopMargin + 1), mLeftMargin, mTopMargin + 1);
blockClear(mLeftMargin, mTopMargin, mRightMargin - mLeftMargin);
} else {
mCursorRow--;
}
@ -1391,6 +1488,9 @@ public final class TerminalEmulator {
case '>': // DECKPNM
setDecsetinternalBit(DECSET_BIT_APPLICATION_KEYPAD, false);
break;
case '_': // APC - Application Program Command.
continueSequence(ESC_APC);
break;
default:
unknownSequence(b);
break;
@ -1572,8 +1672,8 @@ public final class TerminalEmulator {
final int linesToScrollArg = getArg0(1);
final int linesBetweenTopAndBottomMargins = mBottomMargin - mTopMargin;
final int linesToScroll = Math.min(linesBetweenTopAndBottomMargins, linesToScrollArg);
mScreen.blockCopy(0, mTopMargin, mColumns, linesBetweenTopAndBottomMargins - linesToScroll, 0, mTopMargin + linesToScroll);
blockClear(0, mTopMargin, mColumns, linesToScroll);
mScreen.blockCopy(mLeftMargin, mTopMargin, mRightMargin - mLeftMargin, linesBetweenTopAndBottomMargins - linesToScroll, mLeftMargin, mTopMargin + linesToScroll);
blockClear(mLeftMargin, mTopMargin, mRightMargin - mLeftMargin, linesToScroll);
} else {
// "${CSI}${func};${startx};${starty};${firstrow};${lastrow}T" - initiate highlight mouse tracking.
unimplementedSequence(b);
@ -1595,12 +1695,16 @@ public final class TerminalEmulator {
}
mCursorCol = newCol;
break;
case '?': // Esc [ ? -- start of a private mode set
case '?': // Esc [ ? -- start of a private parameter byte
continueSequence(ESC_CSI_QUESTIONMARK);
break;
case '>': // "Esc [ >" --
case '>': // "Esc [ >" -- start of a private parameter byte
continueSequence(ESC_CSI_BIGGERTHAN);
break;
case '<': // "Esc [ <" -- start of a private parameter byte
case '=': // "Esc [ =" -- start of a private parameter byte
continueSequence(ESC_CSI_UNSUPPORTED_PARAMETER_BYTE);
break;
case '`': // Horizontal position absolute (HPA - http://www.vt100.net/docs/vt510-rm/HPA).
setCursorColRespectingOriginMode(getArg0(1) - 1);
break;
@ -1700,8 +1804,10 @@ public final class TerminalEmulator {
mSession.write("\033[3;0;0t");
break;
case 14: // Report xterm window in pixels. Result is CSI 4 ; height ; width t
// We just report characters time 12 here.
mSession.write(String.format(Locale.US, "\033[4;%d;%dt", mRows * 12, mColumns * 12));
mSession.write(String.format(Locale.US, "\033[4;%d;%dt", mRows * mCellHeightPixels, mColumns * mCellWidthPixels));
break;
case 16: // Report xterm character cell size in pixels. Result is CSI 6 ; height ; width t
mSession.write(String.format(Locale.US, "\033[6;%d;%dt", mCellHeightPixels, mCellWidthPixels));
break;
case 18: // Report the size of the text area in characters. Result is CSI 8 ; height ; width t
mSession.write(String.format(Locale.US, "\033[8;%d;%dt", mRows, mColumns));
@ -1750,7 +1856,12 @@ public final class TerminalEmulator {
private void selectGraphicRendition() {
if (mArgIndex >= mArgs.length) mArgIndex = mArgs.length - 1;
for (int i = 0; i <= mArgIndex; i++) {
int code = mArgs[i];
// Skip leading sub parameters:
if ((mArgsSubParamsBitSet & (1 << i)) != 0) {
continue;
}
int code = getArg(i, 0, false);
if (code < 0) {
if (mArgIndex > 0) {
continue;
@ -1769,7 +1880,19 @@ public final class TerminalEmulator {
} else if (code == 3) {
mEffect |= TextStyle.CHARACTER_ATTRIBUTE_ITALIC;
} else if (code == 4) {
mEffect |= TextStyle.CHARACTER_ATTRIBUTE_UNDERLINE;
if (i + 1 <= mArgIndex && ((mArgsSubParamsBitSet & (1 << (i + 1))) != 0)) {
// Sub parameter, see https://sw.kovidgoyal.net/kitty/underlines/
i++;
if (mArgs[i] == 0) {
// No underline.
mEffect &= ~TextStyle.CHARACTER_ATTRIBUTE_UNDERLINE;
} else {
// Different variations of underlines: https://sw.kovidgoyal.net/kitty/underlines/
mEffect |= TextStyle.CHARACTER_ATTRIBUTE_UNDERLINE;
}
} else {
mEffect |= TextStyle.CHARACTER_ATTRIBUTE_UNDERLINE;
}
} else if (code == 5) {
mEffect |= TextStyle.CHARACTER_ATTRIBUTE_BLINK;
} else if (code == 7) {
@ -1798,40 +1921,43 @@ public final class TerminalEmulator {
mEffect &= ~TextStyle.CHARACTER_ATTRIBUTE_STRIKETHROUGH;
} else if (code >= 30 && code <= 37) {
mForeColor = code - 30;
} else if (code == 38 || code == 48) {
// Extended set foreground(38)/background (48) color.
} else if (code == 38 || code == 48 || code == 58) {
// Extended set foreground(38)/background(48)/underline(58) color.
// This is followed by either "2;$R;$G;$B" to set a 24-bit color or
// "5;$INDEX" to set an indexed color.
if (i + 2 > mArgIndex) continue;
int firstArg = mArgs[i + 1];
if (firstArg == 2) {
if (i + 4 > mArgIndex) {
mClient.logWarn(LOG_TAG, "Too few CSI" + code + ";2 RGB arguments");
Logger.logWarn(mClient, LOG_TAG, "Too few CSI" + code + ";2 RGB arguments");
} else {
int red = mArgs[i + 2], green = mArgs[i + 3], blue = mArgs[i + 4];
int red = getArg(i + 2, 0, false);
int green = getArg(i + 3, 0, false);
int blue = getArg(i + 4, 0, false);
if (red < 0 || green < 0 || blue < 0 || red > 255 || green > 255 || blue > 255) {
finishSequenceAndLogError("Invalid RGB: " + red + "," + green + "," + blue);
} else {
int argbColor = 0xff000000 | (red << 16) | (green << 8) | blue;
if (code == 38) {
mForeColor = argbColor;
} else {
mBackColor = argbColor;
int argbColor = 0xff_00_00_00 | (red << 16) | (green << 8) | blue;
switch (code) {
case 38: mForeColor = argbColor; break;
case 48: mBackColor = argbColor; break;
case 58: mUnderlineColor = argbColor; break;
}
}
i += 4; // "2;P_r;P_g;P_r"
}
} else if (firstArg == 5) {
int color = mArgs[i + 2];
int color = getArg(i + 2, 0, false);
i += 2; // "5;P_s"
if (color >= 0 && color < TextStyle.NUM_INDEXED_COLORS) {
if (code == 38) {
mForeColor = color;
} else {
mBackColor = color;
switch (code) {
case 38: mForeColor = color; break;
case 48: mBackColor = color; break;
case 58: mUnderlineColor = color; break;
}
} else {
if (LOG_ESCAPE_SEQUENCES) mClient.logWarn(LOG_TAG, "Invalid color index: " + color);
if (LOG_ESCAPE_SEQUENCES) Logger.logWarn(mClient, LOG_TAG, "Invalid color index: " + color);
}
} else {
finishSequenceAndLogError("Invalid ISO-8613-3 SGR first argument: " + firstArg);
@ -1842,13 +1968,15 @@ public final class TerminalEmulator {
mBackColor = code - 40;
} else if (code == 49) { // Set default background color.
mBackColor = TextStyle.COLOR_INDEX_BACKGROUND;
} else if (code == 59) { // Set default underline color.
mUnderlineColor = TextStyle.COLOR_INDEX_FOREGROUND;
} else if (code >= 90 && code <= 97) { // Bright foreground colors (aixterm codes).
mForeColor = code - 90 + 8;
} else if (code >= 100 && code <= 107) { // Bright background color (aixterm codes).
mBackColor = code - 100 + 8;
} else {
if (LOG_ESCAPE_SEQUENCES)
mClient.logWarn(LOG_TAG, String.format("SGR unknown code %d", code));
Logger.logWarn(mClient, LOG_TAG, String.format("SGR unknown code %d", code));
}
}
}
@ -1982,7 +2110,7 @@ public final class TerminalEmulator {
String clipboardText = new String(Base64.decode(textParameter.substring(startIndex), 0), StandardCharsets.UTF_8);
mSession.onCopyTextToClipboard(clipboardText);
} catch (Exception e) {
mClient.logError(LOG_TAG, "OSC Manipulate selection, invalid string '" + textParameter + "");
Logger.logError(mClient, LOG_TAG, "OSC Manipulate selection, invalid string '" + textParameter + "");
}
break;
case 104:
@ -2077,17 +2205,36 @@ public final class TerminalEmulator {
private void scrollDownOneLine() {
mScrollCounter++;
long currentStyle = getStyle();
if (mLeftMargin != 0 || mRightMargin != mColumns) {
// Horizontal margin: Do not put anything into scroll history, just non-margin part of screen up.
mScreen.blockCopy(mLeftMargin, mTopMargin + 1, mRightMargin - mLeftMargin, mBottomMargin - mTopMargin - 1, mLeftMargin, mTopMargin);
// .. and blank bottom row between margins:
mScreen.blockSet(mLeftMargin, mBottomMargin - 1, mRightMargin - mLeftMargin, 1, ' ', mEffect);
mScreen.blockSet(mLeftMargin, mBottomMargin - 1, mRightMargin - mLeftMargin, 1, ' ', currentStyle);
} else {
mScreen.scrollDownOneLine(mTopMargin, mBottomMargin, getStyle());
mScreen.scrollDownOneLine(mTopMargin, mBottomMargin, currentStyle);
}
}
/** Process the next ASCII character of a parameter. */
/**
* Process the next ASCII character of a parameter.
*
* <p>You must use the ; character to separate parameters and : to separate sub-parameters.
*
* <p>Parameter characters modify the action or interpretation of the sequence. Originally
* you can use up to 16 parameters per sequence, but following at least xterm and alacritty
* we use a common space for parameters and sub-parameters, allowing 32 in total.
*
* <p>All parameters are unsigned, positive decimal integers, with the most significant
* digit sent first. Any parameter greater than 9999 (decimal) is set to 9999
* (decimal). If you do not specify a value, a 0 value is assumed. A 0 value
* or omitted parameter indicates a default value for the sequence. For most
* sequences, the default value is 1.
*
* <p>References:
* <a href="https://vt100.net/docs/vt510-rm/chapter4.html#S4.3.3">VT510 Video Terminal Programmer Information: Control Sequences</a>
* <a href="https://github.com/alacritty/vte/issues/22">alacritty/vte: Implement colon separated CSI parameters</a>
* */
private void parseArg(int b) {
if (b >= '0' && b <= '9') {
if (mArgIndex < mArgs.length) {
@ -2099,12 +2246,19 @@ public final class TerminalEmulator {
} else {
value = thisDigit;
}
if (value > 9999)
value = 9999;
mArgs[mArgIndex] = value;
}
continueSequence(mEscapeState);
} else if (b == ';') {
if (mArgIndex < mArgs.length) {
} else if (b == ';' || b == ':') {
if (mArgIndex + 1 < mArgs.length) {
mArgIndex++;
if (b == ':') {
mArgsSubParamsBitSet |= 1 << mArgIndex;
}
} else {
logError("Too many parameters when in state: " + mEscapeState);
}
continueSequence(mEscapeState);
} else {
@ -2178,7 +2332,7 @@ public final class TerminalEmulator {
}
private void finishSequenceAndLogError(String error) {
if (LOG_ESCAPE_SEQUENCES) mClient.logWarn(LOG_TAG, error);
if (LOG_ESCAPE_SEQUENCES) Logger.logWarn(mClient, LOG_TAG, error);
finishSequence();
}
@ -2326,7 +2480,14 @@ public final class TerminalEmulator {
}
int offsetDueToCombiningChar = ((displayWidth <= 0 && mCursorCol > 0 && !mAboutToAutoWrap) ? 1 : 0);
mScreen.setChar(mCursorCol - offsetDueToCombiningChar, mCursorRow, codePoint, getStyle());
int column = mCursorCol - offsetDueToCombiningChar;
// Fix TerminalRow.setChar() ArrayIndexOutOfBoundsException index=-1 exception reported
// The offsetDueToCombiningChar would never be 1 if mCursorCol was 0 to get column/index=-1,
// so was mCursorCol changed after the offsetDueToCombiningChar conditional by another thread?
// TODO: Check if there are thread synchronization issues with mCursorCol and mCursorRow, possibly causing others bugs too.
if (column < 0) column = 0;
mScreen.setChar(column, mCursorRow, codePoint, getStyle());
if (autoWrap && displayWidth > 0)
mAboutToAutoWrap = (mCursorCol == mRightMargin - displayWidth);
@ -2364,6 +2525,15 @@ public final class TerminalEmulator {
mScrollCounter = 0;
}
public boolean isAutoScrollDisabled() {
return mAutoScrollDisabled;
}
public void toggleAutoScrollDisabled() {
mAutoScrollDisabled = !mAutoScrollDisabled;
}
/** Reset terminal state so user can interact with it regardless of present state. */
public void reset() {
setCursorStyle();

View File

@ -11,11 +11,37 @@ public final class TerminalRow {
private static final float SPARE_CAPACITY_FACTOR = 1.5f;
/**
* Max combining characters that can exist in a column, that are separate from the base character
* itself. Any additional combining characters will be ignored and not added to the column.
*
* There does not seem to be limit in unicode standard for max number of combination characters
* that can be combined but such characters are primarily under 10.
*
* "Section 3.6 Combination" of unicode standard contains combining characters info.
* - https://www.unicode.org/versions/Unicode15.0.0/ch03.pdf
* - https://en.wikipedia.org/wiki/Combining_character#Unicode_ranges
* - https://stackoverflow.com/questions/71237212/what-is-the-maximum-number-of-unicode-combined-characters-that-may-be-needed-to
*
* UAX15-D3 Stream-Safe Text Format limits to max 30 combining characters.
* > The value of 30 is chosen to be significantly beyond what is required for any linguistic or technical usage.
* > While it would have been feasible to chose a smaller number, this value provides a very wide margin,
* > yet is well within the buffer size limits of practical implementations.
* - https://unicode.org/reports/tr15/#Stream_Safe_Text_Format
* - https://stackoverflow.com/a/11983435/14686958
*
* We choose the value 15 because it should be enough for terminal based applications and keep
* the memory usage low for a terminal row, won't affect performance or cause terminal to
* lag or hang, and will keep malicious applications from causing harm. The value can be
* increased if ever needed for legitimate applications.
*/
private static final int MAX_COMBINING_CHARACTERS_PER_COLUMN = 15;
/** The number of columns in this terminal row. */
private final int mColumns;
/** The text filling this terminal row. */
public char[] mText;
/** The number of java char:s used in {@link #mText}. */
/** The number of java chars used in {@link #mText}. */
private short mSpaceUsed;
/** If this row has been line wrapped due to text output at the end of line. */
boolean mLineWrap;
@ -124,6 +150,9 @@ public final class TerminalRow {
// https://github.com/steven676/Android-Terminal-Emulator/commit/9a47042620bec87617f0b4f5d50568535668fe26
public void setChar(int columnToSet, int codePoint, long style) {
if (columnToSet < 0 || columnToSet >= mStyle.length)
throw new IllegalArgumentException("TerminalRow.setChar(): columnToSet=" + columnToSet + ", codePoint=" + codePoint + ", style=" + style);
mStyle[columnToSet] = style;
final int newCodePointDisplayWidth = WcWidth.width(codePoint);
@ -160,18 +189,25 @@ public final class TerminalRow {
// Get the number of elements in the mText array this column uses now
int oldCharactersUsedForColumn;
if (columnToSet + oldCodePointDisplayWidth < mColumns) {
oldCharactersUsedForColumn = findStartOfColumn(columnToSet + oldCodePointDisplayWidth) - oldStartOfColumnIndex;
int oldEndOfColumnIndex = findStartOfColumn(columnToSet + oldCodePointDisplayWidth);
oldCharactersUsedForColumn = oldEndOfColumnIndex - oldStartOfColumnIndex;
} else {
// Last character.
oldCharactersUsedForColumn = mSpaceUsed - oldStartOfColumnIndex;
}
// If MAX_COMBINING_CHARACTERS_PER_COLUMN already exist in column, then ignore adding additional combining characters.
if (newIsCombining) {
int combiningCharsCount = WcWidth.zeroWidthCharsCount(mText, oldStartOfColumnIndex, oldStartOfColumnIndex + oldCharactersUsedForColumn);
if (combiningCharsCount >= MAX_COMBINING_CHARACTERS_PER_COLUMN)
return;
}
// Find how many chars this column will need
int newCharactersUsedForColumn = Character.charCount(codePoint);
if (newIsCombining) {
// Combining characters are added to the contents of the column instead of overwriting them, so that they
// modify the existing contents.
// FIXME: Put a limit of combining characters.
// FIXME: Unassigned characters also get width=0.
newCharactersUsedForColumn += oldCharactersUsedForColumn;
}
@ -186,7 +222,7 @@ public final class TerminalRow {
if (mSpaceUsed + javaCharDifference > text.length) {
// We need to grow the array
char[] newText = new char[text.length + mColumns];
System.arraycopy(text, 0, newText, 0, oldStartOfColumnIndex + oldCharactersUsedForColumn);
System.arraycopy(text, 0, newText, 0, oldNextColumnIndex);
System.arraycopy(text, oldNextColumnIndex, newText, newNextColumnIndex, oldCharactersAfterColumn);
mText = text = newText;
} else {

View File

@ -21,7 +21,7 @@ import java.util.UUID;
* A terminal session, consisting of a process coupled to a terminal interface.
* <p>
* The subprocess will be executed by the constructor, and when the size is made known by a call to
* {@link #updateSize(int, int)} terminal emulation will begin and threads will be spawned to handle the subprocess I/O.
* {@link #updateSize(int, int, int, int)} terminal emulation will begin and threads will be spawned to handle the subprocess I/O.
* All terminal emulation and callback methods will be performed on the main thread.
* <p>
* The child process may be exited forcefully by using the {@link #finishIfRunning()} method.
@ -61,7 +61,7 @@ public final class TerminalSession extends TerminalOutput {
/**
* The file descriptor referencing the master half of a pseudo-terminal pair, resulting from calling
* {@link JNI#createSubprocess(String, String, String[], String[], int[], int, int)}.
* {@link JNI#createSubprocess(String, String, String[], String[], int[], int, int, int, int)}.
*/
private int mTerminalFileDescriptor;
@ -100,12 +100,12 @@ public final class TerminalSession extends TerminalOutput {
}
/** Inform the attached pty of the new size and reflow or initialize the emulator. */
public void updateSize(int columns, int rows) {
public void updateSize(int columns, int rows, int cellWidthPixels, int cellHeightPixels) {
if (mEmulator == null) {
initializeEmulator(columns, rows);
initializeEmulator(columns, rows, cellWidthPixels, cellHeightPixels);
} else {
JNI.setPtyWindowSize(mTerminalFileDescriptor, rows, columns);
mEmulator.resize(columns, rows);
JNI.setPtyWindowSize(mTerminalFileDescriptor, rows, columns, cellWidthPixels, cellHeightPixels);
mEmulator.resize(columns, rows, cellWidthPixels, cellHeightPixels);
}
}
@ -120,12 +120,13 @@ public final class TerminalSession extends TerminalOutput {
* @param columns The number of columns in the terminal window.
* @param rows The number of rows in the terminal window.
*/
public void initializeEmulator(int columns, int rows) {
mEmulator = new TerminalEmulator(this, columns, rows, mTranscriptRows, mClient);
public void initializeEmulator(int columns, int rows, int cellWidthPixels, int cellHeightPixels) {
mEmulator = new TerminalEmulator(this, columns, rows, cellWidthPixels, cellHeightPixels, mTranscriptRows, mClient);
int[] processId = new int[1];
mTerminalFileDescriptor = JNI.createSubprocess(mShellPath, mCwd, mArgs, mEnv, processId, rows, columns);
mTerminalFileDescriptor = JNI.createSubprocess(mShellPath, mCwd, mArgs, mEnv, processId, rows, columns, cellWidthPixels, cellHeightPixels);
mShellPid = processId[0];
mClient.setTerminalShellPid(this, mShellPid);
final FileDescriptor terminalFileDescriptorWrapped = wrapFileDescriptor(mTerminalFileDescriptor, mClient);
@ -236,7 +237,7 @@ public final class TerminalSession extends TerminalOutput {
try {
Os.kill(mShellPid, OsConstants.SIGKILL);
} catch (ErrnoException e) {
mClient.logWarn(LOG_TAG, "Failed sending SIGKILL: " + e.getMessage());
Logger.logWarn(mClient, LOG_TAG, "Failed sending SIGKILL: " + e.getMessage());
}
}
}
@ -308,7 +309,7 @@ public final class TerminalSession extends TerminalOutput {
return outputPath;
}
} catch (IOException | SecurityException e) {
mClient.logStackTraceWithMessage(LOG_TAG, "Error getting current directory", e);
Logger.logStackTraceWithMessage(mClient, LOG_TAG, "Error getting current directory", e);
}
return null;
}
@ -326,7 +327,7 @@ public final class TerminalSession extends TerminalOutput {
descriptorField.setAccessible(true);
descriptorField.set(result, fileDescriptor);
} catch (NoSuchFieldException | IllegalAccessException | IllegalArgumentException e) {
client.logStackTraceWithMessage(LOG_TAG, "Error accessing FileDescriptor#descriptor private field", e);
Logger.logStackTraceWithMessage(client, LOG_TAG, "Error accessing FileDescriptor#descriptor private field", e);
System.exit(1);
}
return result;

View File

@ -1,5 +1,8 @@
package com.termux.terminal;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
/**
* The interface for communication between {@link TerminalSession} and its client. It is used to
* send callbacks to the client when {@link TerminalSession} changes or for sending other
@ -7,22 +10,24 @@ package com.termux.terminal;
*/
public interface TerminalSessionClient {
void onTextChanged(TerminalSession changedSession);
void onTextChanged(@NonNull TerminalSession changedSession);
void onTitleChanged(TerminalSession changedSession);
void onTitleChanged(@NonNull TerminalSession changedSession);
void onSessionFinished(TerminalSession finishedSession);
void onSessionFinished(@NonNull TerminalSession finishedSession);
void onCopyTextToClipboard(TerminalSession session, String text);
void onCopyTextToClipboard(@NonNull TerminalSession session, String text);
void onPasteTextFromClipboard(TerminalSession session);
void onPasteTextFromClipboard(@Nullable TerminalSession session);
void onBell(TerminalSession session);
void onBell(@NonNull TerminalSession session);
void onColorsChanged(TerminalSession session);
void onColorsChanged(@NonNull TerminalSession session);
void onTerminalCursorStateChange(boolean state);
void setTerminalShellPid(@NonNull TerminalSession session, int pid);
Integer getTerminalCursorStyle();

View File

@ -1,7 +1,7 @@
package com.termux.terminal;
/**
* Implementation of wcwidth(3) for Unicode 9.
* Implementation of wcwidth(3) for Unicode 15.
*
* Implementation from https://github.com/jquast/wcwidth but we return 0 for unprintable characters.
*
@ -9,12 +9,13 @@ package com.termux.terminal;
* Must be kept in sync with the following:
* https://github.com/termux/wcwidth
* https://github.com/termux/libandroid-support
* https://github.com/termux/termux-packages/tree/master/libandroid-support
* https://github.com/termux/termux-packages/tree/master/packages/libandroid-support
*/
public final class WcWidth {
// From https://github.com/jquast/wcwidth/blob/master/wcwidth/table_zero.py
// at commit b29897e5a1b403a0e36f7fc991614981cbc42475 (2020-07-14):
// from https://github.com/jquast/wcwidth/pull/64
// at commit 1b9b6585b0080ea5cb88dc9815796505724793fe (2022-12-16):
private static final int[][] ZERO_WIDTH = {
{0x00300, 0x0036f}, // Combining Grave Accent ..Combining Latin Small Le
{0x00483, 0x00489}, // Combining Cyrillic Titlo..Combining Cyrillic Milli
@ -40,7 +41,8 @@ public final class WcWidth {
{0x00825, 0x00827}, // Samaritan Vowel Sign Sho..Samaritan Vowel Sign U
{0x00829, 0x0082d}, // Samaritan Vowel Sign Lon..Samaritan Mark Nequdaa
{0x00859, 0x0085b}, // Mandaic Affrication Mark..Mandaic Gemination Mark
{0x008d3, 0x008e1}, // Arabic Small Low Waw ..Arabic Small High Sign S
{0x00898, 0x0089f}, // Arabic Small High Word A..Arabic Half Madda Over M
{0x008ca, 0x008e1}, // Arabic Small High Farsi ..Arabic Small High Sign S
{0x008e3, 0x00902}, // Arabic Turned Damma Belo..Devanagari Sign Anusvara
{0x0093a, 0x0093a}, // Devanagari Vowel Sign Oe..Devanagari Vowel Sign Oe
{0x0093c, 0x0093c}, // Devanagari Sign Nukta ..Devanagari Sign Nukta
@ -74,13 +76,14 @@ public final class WcWidth {
{0x00b3f, 0x00b3f}, // Oriya Vowel Sign I ..Oriya Vowel Sign I
{0x00b41, 0x00b44}, // Oriya Vowel Sign U ..Oriya Vowel Sign Vocalic
{0x00b4d, 0x00b4d}, // Oriya Sign Virama ..Oriya Sign Virama
{0x00b55, 0x00b56}, // (nil) ..Oriya Ai Length Mark
{0x00b55, 0x00b56}, // Oriya Sign Overline ..Oriya Ai Length Mark
{0x00b62, 0x00b63}, // Oriya Vowel Sign Vocalic..Oriya Vowel Sign Vocalic
{0x00b82, 0x00b82}, // Tamil Sign Anusvara ..Tamil Sign Anusvara
{0x00bc0, 0x00bc0}, // Tamil Vowel Sign Ii ..Tamil Vowel Sign Ii
{0x00bcd, 0x00bcd}, // Tamil Sign Virama ..Tamil Sign Virama
{0x00c00, 0x00c00}, // Telugu Sign Combining Ca..Telugu Sign Combining Ca
{0x00c04, 0x00c04}, // Telugu Sign Combining An..Telugu Sign Combining An
{0x00c3c, 0x00c3c}, // Telugu Sign Nukta ..Telugu Sign Nukta
{0x00c3e, 0x00c40}, // Telugu Vowel Sign Aa ..Telugu Vowel Sign Ii
{0x00c46, 0x00c48}, // Telugu Vowel Sign E ..Telugu Vowel Sign Ai
{0x00c4a, 0x00c4d}, // Telugu Vowel Sign O ..Telugu Sign Virama
@ -97,7 +100,7 @@ public final class WcWidth {
{0x00d41, 0x00d44}, // Malayalam Vowel Sign U ..Malayalam Vowel Sign Voc
{0x00d4d, 0x00d4d}, // Malayalam Sign Virama ..Malayalam Sign Virama
{0x00d62, 0x00d63}, // Malayalam Vowel Sign Voc..Malayalam Vowel Sign Voc
{0x00d81, 0x00d81}, // (nil) ..(nil)
{0x00d81, 0x00d81}, // Sinhala Sign Candrabindu..Sinhala Sign Candrabindu
{0x00dca, 0x00dca}, // Sinhala Sign Al-lakuna ..Sinhala Sign Al-lakuna
{0x00dd2, 0x00dd4}, // Sinhala Vowel Sign Ketti..Sinhala Vowel Sign Ketti
{0x00dd6, 0x00dd6}, // Sinhala Vowel Sign Diga ..Sinhala Vowel Sign Diga
@ -106,7 +109,7 @@ public final class WcWidth {
{0x00e47, 0x00e4e}, // Thai Character Maitaikhu..Thai Character Yamakkan
{0x00eb1, 0x00eb1}, // Lao Vowel Sign Mai Kan ..Lao Vowel Sign Mai Kan
{0x00eb4, 0x00ebc}, // Lao Vowel Sign I ..Lao Semivowel Sign Lo
{0x00ec8, 0x00ecd}, // Lao Tone Mai Ek ..Lao Niggahita
{0x00ec8, 0x00ece}, // Lao Tone Mai Ek ..(nil)
{0x00f18, 0x00f19}, // Tibetan Astrological Sig..Tibetan Astrological Sig
{0x00f35, 0x00f35}, // Tibetan Mark Ngas Bzung ..Tibetan Mark Ngas Bzung
{0x00f37, 0x00f37}, // Tibetan Mark Ngas Bzung ..Tibetan Mark Ngas Bzung
@ -130,7 +133,7 @@ public final class WcWidth {
{0x0109d, 0x0109d}, // Myanmar Vowel Sign Aiton..Myanmar Vowel Sign Aiton
{0x0135d, 0x0135f}, // Ethiopic Combining Gemin..Ethiopic Combining Gemin
{0x01712, 0x01714}, // Tagalog Vowel Sign I ..Tagalog Sign Virama
{0x01732, 0x01734}, // Hanunoo Vowel Sign I ..Hanunoo Sign Pamudpod
{0x01732, 0x01733}, // Hanunoo Vowel Sign I ..Hanunoo Vowel Sign U
{0x01752, 0x01753}, // Buhid Vowel Sign I ..Buhid Vowel Sign U
{0x01772, 0x01773}, // Tagbanwa Vowel Sign I ..Tagbanwa Vowel Sign U
{0x017b4, 0x017b5}, // Khmer Vowel Inherent Aq ..Khmer Vowel Inherent Aa
@ -139,6 +142,7 @@ public final class WcWidth {
{0x017c9, 0x017d3}, // Khmer Sign Muusikatoan ..Khmer Sign Bathamasat
{0x017dd, 0x017dd}, // Khmer Sign Atthacan ..Khmer Sign Atthacan
{0x0180b, 0x0180d}, // Mongolian Free Variation..Mongolian Free Variation
{0x0180f, 0x0180f}, // Mongolian Free Variation..Mongolian Free Variation
{0x01885, 0x01886}, // Mongolian Letter Ali Gal..Mongolian Letter Ali Gal
{0x018a9, 0x018a9}, // Mongolian Letter Ali Gal..Mongolian Letter Ali Gal
{0x01920, 0x01922}, // Limbu Vowel Sign A ..Limbu Vowel Sign U
@ -154,7 +158,7 @@ public final class WcWidth {
{0x01a65, 0x01a6c}, // Tai Tham Vowel Sign I ..Tai Tham Vowel Sign Oa B
{0x01a73, 0x01a7c}, // Tai Tham Vowel Sign Oa A..Tai Tham Sign Khuen-lue
{0x01a7f, 0x01a7f}, // Tai Tham Combining Crypt..Tai Tham Combining Crypt
{0x01ab0, 0x01ac0}, // Combining Doubled Circum..(nil)
{0x01ab0, 0x01ace}, // Combining Doubled Circum..Combining Latin Small Le
{0x01b00, 0x01b03}, // Balinese Sign Ulu Ricem ..Balinese Sign Surang
{0x01b34, 0x01b34}, // Balinese Sign Rerekan ..Balinese Sign Rerekan
{0x01b36, 0x01b3a}, // Balinese Vowel Sign Ulu ..Balinese Vowel Sign Ra R
@ -177,8 +181,7 @@ public final class WcWidth {
{0x01ced, 0x01ced}, // Vedic Sign Tiryak ..Vedic Sign Tiryak
{0x01cf4, 0x01cf4}, // Vedic Tone Candra Above ..Vedic Tone Candra Above
{0x01cf8, 0x01cf9}, // Vedic Tone Ring Above ..Vedic Tone Double Ring A
{0x01dc0, 0x01df9}, // Combining Dotted Grave A..Combining Wide Inverted
{0x01dfb, 0x01dff}, // Combining Deletion Mark ..Combining Right Arrowhea
{0x01dc0, 0x01dff}, // Combining Dotted Grave A..Combining Right Arrowhea
{0x020d0, 0x020f0}, // Combining Left Harpoon A..Combining Asterisk Above
{0x02cef, 0x02cf1}, // Coptic Combining Ni Abov..Coptic Combining Spiritu
{0x02d7f, 0x02d7f}, // Tifinagh Consonant Joine..Tifinagh Consonant Joine
@ -193,7 +196,7 @@ public final class WcWidth {
{0x0a806, 0x0a806}, // Syloti Nagri Sign Hasant..Syloti Nagri Sign Hasant
{0x0a80b, 0x0a80b}, // Syloti Nagri Sign Anusva..Syloti Nagri Sign Anusva
{0x0a825, 0x0a826}, // Syloti Nagri Vowel Sign ..Syloti Nagri Vowel Sign
{0x0a82c, 0x0a82c}, // (nil) ..(nil)
{0x0a82c, 0x0a82c}, // Syloti Nagri Sign Altern..Syloti Nagri Sign Altern
{0x0a8c4, 0x0a8c5}, // Saurashtra Sign Virama ..Saurashtra Sign Candrabi
{0x0a8e0, 0x0a8f1}, // Combining Devanagari Dig..Combining Devanagari Sig
{0x0a8ff, 0x0a8ff}, // Devanagari Vowel Sign Ay..Devanagari Vowel Sign Ay
@ -233,13 +236,18 @@ public final class WcWidth {
{0x10a3f, 0x10a3f}, // Kharoshthi Virama ..Kharoshthi Virama
{0x10ae5, 0x10ae6}, // Manichaean Abbreviation ..Manichaean Abbreviation
{0x10d24, 0x10d27}, // Hanifi Rohingya Sign Har..Hanifi Rohingya Sign Tas
{0x10eab, 0x10eac}, // (nil) ..(nil)
{0x10eab, 0x10eac}, // Yezidi Combining Hamza M..Yezidi Combining Madda M
{0x10efd, 0x10eff}, // (nil) ..(nil)
{0x10f46, 0x10f50}, // Sogdian Combining Dot Be..Sogdian Combining Stroke
{0x10f82, 0x10f85}, // Old Uyghur Combining Dot..Old Uyghur Combining Two
{0x11001, 0x11001}, // Brahmi Sign Anusvara ..Brahmi Sign Anusvara
{0x11038, 0x11046}, // Brahmi Vowel Sign Aa ..Brahmi Virama
{0x11070, 0x11070}, // Brahmi Sign Old Tamil Vi..Brahmi Sign Old Tamil Vi
{0x11073, 0x11074}, // Brahmi Vowel Sign Old Ta..Brahmi Vowel Sign Old Ta
{0x1107f, 0x11081}, // Brahmi Number Joiner ..Kaithi Sign Anusvara
{0x110b3, 0x110b6}, // Kaithi Vowel Sign U ..Kaithi Vowel Sign Ai
{0x110b9, 0x110ba}, // Kaithi Sign Virama ..Kaithi Sign Nukta
{0x110c2, 0x110c2}, // Kaithi Vowel Sign Vocali..Kaithi Vowel Sign Vocali
{0x11100, 0x11102}, // Chakma Sign Candrabindu ..Chakma Sign Visarga
{0x11127, 0x1112b}, // Chakma Vowel Sign A ..Chakma Vowel Sign Uu
{0x1112d, 0x11134}, // Chakma Vowel Sign Ai ..Chakma Maayyaa
@ -247,11 +255,12 @@ public final class WcWidth {
{0x11180, 0x11181}, // Sharada Sign Candrabindu..Sharada Sign Anusvara
{0x111b6, 0x111be}, // Sharada Vowel Sign U ..Sharada Vowel Sign O
{0x111c9, 0x111cc}, // Sharada Sandhi Mark ..Sharada Extra Short Vowe
{0x111cf, 0x111cf}, // (nil) ..(nil)
{0x111cf, 0x111cf}, // Sharada Sign Inverted Ca..Sharada Sign Inverted Ca
{0x1122f, 0x11231}, // Khojki Vowel Sign U ..Khojki Vowel Sign Ai
{0x11234, 0x11234}, // Khojki Sign Anusvara ..Khojki Sign Anusvara
{0x11236, 0x11237}, // Khojki Sign Nukta ..Khojki Sign Shadda
{0x1123e, 0x1123e}, // Khojki Sign Sukun ..Khojki Sign Sukun
{0x11241, 0x11241}, // (nil) ..(nil)
{0x112df, 0x112df}, // Khudawadi Sign Anusvara ..Khudawadi Sign Anusvara
{0x112e3, 0x112ea}, // Khudawadi Vowel Sign U ..Khudawadi Sign Virama
{0x11300, 0x11301}, // Grantha Sign Combining A..Grantha Sign Candrabindu
@ -283,9 +292,9 @@ public final class WcWidth {
{0x11727, 0x1172b}, // Ahom Vowel Sign Aw ..Ahom Sign Killer
{0x1182f, 0x11837}, // Dogra Vowel Sign U ..Dogra Sign Anusvara
{0x11839, 0x1183a}, // Dogra Sign Virama ..Dogra Sign Nukta
{0x1193b, 0x1193c}, // (nil) ..(nil)
{0x1193e, 0x1193e}, // (nil) ..(nil)
{0x11943, 0x11943}, // (nil) ..(nil)
{0x1193b, 0x1193c}, // Dives Akuru Sign Anusvar..Dives Akuru Sign Candrab
{0x1193e, 0x1193e}, // Dives Akuru Virama ..Dives Akuru Virama
{0x11943, 0x11943}, // Dives Akuru Sign Nukta ..Dives Akuru Sign Nukta
{0x119d4, 0x119d7}, // Nandinagari Vowel Sign U..Nandinagari Vowel Sign V
{0x119da, 0x119db}, // Nandinagari Vowel Sign E..Nandinagari Vowel Sign A
{0x119e0, 0x119e0}, // Nandinagari Sign Virama ..Nandinagari Sign Virama
@ -313,12 +322,20 @@ public final class WcWidth {
{0x11d95, 0x11d95}, // Gunjala Gondi Sign Anusv..Gunjala Gondi Sign Anusv
{0x11d97, 0x11d97}, // Gunjala Gondi Virama ..Gunjala Gondi Virama
{0x11ef3, 0x11ef4}, // Makasar Vowel Sign I ..Makasar Vowel Sign U
{0x11f00, 0x11f01}, // (nil) ..(nil)
{0x11f36, 0x11f3a}, // (nil) ..(nil)
{0x11f40, 0x11f40}, // (nil) ..(nil)
{0x11f42, 0x11f42}, // (nil) ..(nil)
{0x13440, 0x13440}, // (nil) ..(nil)
{0x13447, 0x13455}, // (nil) ..(nil)
{0x16af0, 0x16af4}, // Bassa Vah Combining High..Bassa Vah Combining High
{0x16b30, 0x16b36}, // Pahawh Hmong Mark Cim Tu..Pahawh Hmong Mark Cim Ta
{0x16f4f, 0x16f4f}, // Miao Sign Consonant Modi..Miao Sign Consonant Modi
{0x16f8f, 0x16f92}, // Miao Tone Right ..Miao Tone Below
{0x16fe4, 0x16fe4}, // (nil) ..(nil)
{0x16fe4, 0x16fe4}, // Khitan Small Script Fill..Khitan Small Script Fill
{0x1bc9d, 0x1bc9e}, // Duployan Thick Letter Se..Duployan Double Mark
{0x1cf00, 0x1cf2d}, // Znamenny Combining Mark ..Znamenny Combining Mark
{0x1cf30, 0x1cf46}, // Znamenny Combining Tonal..Znamenny Priznak Modifie
{0x1d167, 0x1d169}, // Musical Symbol Combining..Musical Symbol Combining
{0x1d17b, 0x1d182}, // Musical Symbol Combining..Musical Symbol Combining
{0x1d185, 0x1d18b}, // Musical Symbol Combining..Musical Symbol Combining
@ -335,15 +352,19 @@ public final class WcWidth {
{0x1e01b, 0x1e021}, // Combining Glagolitic Let..Combining Glagolitic Let
{0x1e023, 0x1e024}, // Combining Glagolitic Let..Combining Glagolitic Let
{0x1e026, 0x1e02a}, // Combining Glagolitic Let..Combining Glagolitic Let
{0x1e08f, 0x1e08f}, // (nil) ..(nil)
{0x1e130, 0x1e136}, // Nyiakeng Puachue Hmong T..Nyiakeng Puachue Hmong T
{0x1e2ae, 0x1e2ae}, // Toto Sign Rising Tone ..Toto Sign Rising Tone
{0x1e2ec, 0x1e2ef}, // Wancho Tone Tup ..Wancho Tone Koini
{0x1e4ec, 0x1e4ef}, // (nil) ..(nil)
{0x1e8d0, 0x1e8d6}, // Mende Kikakui Combining ..Mende Kikakui Combining
{0x1e944, 0x1e94a}, // Adlam Alif Lengthener ..Adlam Nukta
{0xe0100, 0xe01ef}, // Variation Selector-17 ..Variation Selector-256
};
// https://github.com/jquast/wcwidth/blob/master/wcwidth/table_wide.py
// at commit b29897e5a1b403a0e36f7fc991614981cbc42475 (2020-07-14):
// from https://github.com/jquast/wcwidth/pull/64
// at commit 1b9b6585b0080ea5cb88dc9815796505724793fe (2022-12-16):
private static final int[][] WIDE_EASTASIAN = {
{0x01100, 0x0115f}, // Hangul Choseong Kiyeok ..Hangul Choseong Filler
{0x0231a, 0x0231b}, // Watch ..Hourglass
@ -392,7 +413,7 @@ public final class WcWidth {
{0x03190, 0x031e3}, // Ideographic Annotation L..Cjk Stroke Q
{0x031f0, 0x0321e}, // Katakana Letter Small Ku..Parenthesized Korean Cha
{0x03220, 0x03247}, // Parenthesized Ideograph ..Circled Ideograph Koto
{0x03250, 0x04dbf}, // Partnership Sign ..(nil)
{0x03250, 0x04dbf}, // Partnership Sign ..Cjk Unified Ideograph-4d
{0x04e00, 0x0a48c}, // Cjk Unified Ideograph-4e..Yi Syllable Yyr
{0x0a490, 0x0a4c6}, // Yi Radical Qot ..Yi Radical Ke
{0x0a960, 0x0a97c}, // Hangul Choseong Tikeut-m..Hangul Choseong Ssangyeo
@ -404,13 +425,18 @@ public final class WcWidth {
{0x0fe68, 0x0fe6b}, // Small Reverse Solidus ..Small Commercial At
{0x0ff01, 0x0ff60}, // Fullwidth Exclamation Ma..Fullwidth Right White Pa
{0x0ffe0, 0x0ffe6}, // Fullwidth Cent Sign ..Fullwidth Won Sign
{0x16fe0, 0x16fe4}, // Tangut Iteration Mark ..(nil)
{0x16ff0, 0x16ff1}, // (nil) ..(nil)
{0x16fe0, 0x16fe4}, // Tangut Iteration Mark ..Khitan Small Script Fill
{0x16ff0, 0x16ff1}, // Vietnamese Alternate Rea..Vietnamese Alternate Rea
{0x17000, 0x187f7}, // (nil) ..(nil)
{0x18800, 0x18cd5}, // Tangut Component-001 ..(nil)
{0x18800, 0x18cd5}, // Tangut Component-001 ..Khitan Small Script Char
{0x18d00, 0x18d08}, // (nil) ..(nil)
{0x1b000, 0x1b11e}, // Katakana Letter Archaic ..Hentaigana Letter N-mu-m
{0x1aff0, 0x1aff3}, // Katakana Letter Minnan T..Katakana Letter Minnan T
{0x1aff5, 0x1affb}, // Katakana Letter Minnan T..Katakana Letter Minnan N
{0x1affd, 0x1affe}, // Katakana Letter Minnan N..Katakana Letter Minnan N
{0x1b000, 0x1b122}, // Katakana Letter Archaic ..Katakana Letter Archaic
{0x1b132, 0x1b132}, // (nil) ..(nil)
{0x1b150, 0x1b152}, // Hiragana Letter Small Wi..Hiragana Letter Small Wo
{0x1b155, 0x1b155}, // (nil) ..(nil)
{0x1b164, 0x1b167}, // Katakana Letter Small Wi..Katakana Letter Small N
{0x1b170, 0x1b2fb}, // Nushu Character-1b170 ..Nushu Character-1b2fb
{0x1f004, 0x1f004}, // Mahjong Tile Red Dragon ..Mahjong Tile Red Dragon
@ -443,24 +469,24 @@ public final class WcWidth {
{0x1f680, 0x1f6c5}, // Rocket ..Left Luggage
{0x1f6cc, 0x1f6cc}, // Sleeping Accommodation ..Sleeping Accommodation
{0x1f6d0, 0x1f6d2}, // Place Of Worship ..Shopping Trolley
{0x1f6d5, 0x1f6d7}, // Hindu Temple ..(nil)
{0x1f6d5, 0x1f6d7}, // Hindu Temple ..Elevator
{0x1f6dc, 0x1f6df}, // (nil) ..Ring Buoy
{0x1f6eb, 0x1f6ec}, // Airplane Departure ..Airplane Arriving
{0x1f6f4, 0x1f6fc}, // Scooter ..(nil)
{0x1f6f4, 0x1f6fc}, // Scooter ..Roller Skate
{0x1f7e0, 0x1f7eb}, // Large Orange Circle ..Large Brown Square
{0x1f90c, 0x1f93a}, // (nil) ..Fencer
{0x1f7f0, 0x1f7f0}, // Heavy Equals Sign ..Heavy Equals Sign
{0x1f90c, 0x1f93a}, // Pinched Fingers ..Fencer
{0x1f93c, 0x1f945}, // Wrestlers ..Goal Net
{0x1f947, 0x1f978}, // First Place Medal ..(nil)
{0x1f97a, 0x1f9cb}, // Face With Pleading Eyes ..(nil)
{0x1f9cd, 0x1f9ff}, // Standing Person ..Nazar Amulet
{0x1fa70, 0x1fa74}, // Ballet Shoes ..(nil)
{0x1fa78, 0x1fa7a}, // Drop Of Blood ..Stethoscope
{0x1fa80, 0x1fa86}, // Yo-yo ..(nil)
{0x1fa90, 0x1faa8}, // Ringed Planet ..(nil)
{0x1fab0, 0x1fab6}, // (nil) ..(nil)
{0x1fac0, 0x1fac2}, // (nil) ..(nil)
{0x1fad0, 0x1fad6}, // (nil) ..(nil)
{0x1f947, 0x1f9ff}, // First Place Medal ..Nazar Amulet
{0x1fa70, 0x1fa7c}, // Ballet Shoes ..Crutch
{0x1fa80, 0x1fa88}, // Yo-yo ..(nil)
{0x1fa90, 0x1fabd}, // Ringed Planet ..(nil)
{0x1fabf, 0x1fac5}, // (nil) ..Person With Crown
{0x1face, 0x1fadb}, // (nil) ..(nil)
{0x1fae0, 0x1fae8}, // Melting Face ..(nil)
{0x1faf0, 0x1faf8}, // Hand With Index Finger A..(nil)
{0x20000, 0x2fffd}, // Cjk Unified Ideograph-20..(nil)
{0x30000, 0x3fffd}, // (nil) ..(nil)
{0x30000, 0x3fffd}, // Cjk Unified Ideograph-30..(nil)
};
@ -512,4 +538,29 @@ public final class WcWidth {
return Character.isHighSurrogate(c) ? width(Character.toCodePoint(c, chars[index + 1])) : width(c);
}
/**
* The zero width characters count like combining characters in the `chars` array from start
* index to end index (exclusive).
*/
public static int zeroWidthCharsCount(char[] chars, int start, int end) {
if (start < 0 || start >= chars.length)
return 0;
int count = 0;
for (int i = start; i < end && i < chars.length;) {
if (Character.isHighSurrogate(chars[i])) {
if (width(Character.toCodePoint(chars[i], chars[i + 1])) <= 0) {
count++;
}
i += 2;
} else {
if (width(chars[i]) <= 0) {
count++;
}
i++;
}
}
return count;
}
}

View File

@ -29,7 +29,9 @@ static int create_subprocess(JNIEnv* env,
char** envp,
int* pProcessId,
jint rows,
jint columns)
jint columns,
jint cell_width,
jint cell_height)
{
int ptm = open("/dev/ptmx", O_RDWR | O_CLOEXEC);
if (ptm < 0) return throw_runtime_exception(env, "Cannot open /dev/ptmx");
@ -57,7 +59,7 @@ static int create_subprocess(JNIEnv* env,
tcsetattr(ptm, TCSANOW, &tios);
/** Set initial winsize. */
struct winsize sz = { .ws_row = (unsigned short) rows, .ws_col = (unsigned short) columns };
struct winsize sz = { .ws_row = (unsigned short) rows, .ws_col = (unsigned short) columns, .ws_xpixel = (unsigned short) (columns * cell_width), .ws_ypixel = (unsigned short) (rows * cell_height)};
ioctl(ptm, TIOCSWINSZ, &sz);
pid_t pid = fork();
@ -121,7 +123,9 @@ JNIEXPORT jint JNICALL Java_com_termux_terminal_JNI_createSubprocess(
jobjectArray envVars,
jintArray processIdArray,
jint rows,
jint columns)
jint columns,
jint cell_width,
jint cell_height)
{
jsize size = args ? (*env)->GetArrayLength(env, args) : 0;
char** argv = NULL;
@ -156,7 +160,7 @@ JNIEXPORT jint JNICALL Java_com_termux_terminal_JNI_createSubprocess(
int procId = 0;
char const* cmd_cwd = (*env)->GetStringUTFChars(env, cwd, NULL);
char const* cmd_utf8 = (*env)->GetStringUTFChars(env, cmd, NULL);
int ptm = create_subprocess(env, cmd_utf8, cmd_cwd, argv, envp, &procId, rows, columns);
int ptm = create_subprocess(env, cmd_utf8, cmd_cwd, argv, envp, &procId, rows, columns, cell_width, cell_height);
(*env)->ReleaseStringUTFChars(env, cmd, cmd_utf8);
(*env)->ReleaseStringUTFChars(env, cmd, cmd_cwd);
@ -178,9 +182,9 @@ JNIEXPORT jint JNICALL Java_com_termux_terminal_JNI_createSubprocess(
return ptm;
}
JNIEXPORT void JNICALL Java_com_termux_terminal_JNI_setPtyWindowSize(JNIEnv* TERMUX_UNUSED(env), jclass TERMUX_UNUSED(clazz), jint fd, jint rows, jint cols)
JNIEXPORT void JNICALL Java_com_termux_terminal_JNI_setPtyWindowSize(JNIEnv* TERMUX_UNUSED(env), jclass TERMUX_UNUSED(clazz), jint fd, jint rows, jint cols, jint cell_width, jint cell_height)
{
struct winsize sz = { .ws_row = (unsigned short) rows, .ws_col = (unsigned short) cols };
struct winsize sz = { .ws_row = (unsigned short) rows, .ws_col = (unsigned short) cols, .ws_xpixel = (unsigned short) (cols * cell_width), .ws_ypixel = (unsigned short) (rows * cell_height) };
ioctl(fd, TIOCSWINSZ, &sz);
}

View File

@ -0,0 +1,21 @@
package com.termux.terminal;
public class ApcTest extends TerminalTestCase {
public void testApcConsumed() {
// At time of writing this is part of what yazi sends for probing for kitty graphics protocol support:
// https://github.com/sxyazi/yazi/blob/0cdaff98d0b3723caff63eebf1974e7907a43a2c/yazi-adapter/src/emulator.rs#L129
// This should not result in anything being written to the screen: If kitty graphics protocol support
// is implemented it should instead result in an error code on stdin, and if not it should be consumed
// silently just as xterm does. See https://sw.kovidgoyal.net/kitty/graphics-protocol/.
withTerminalSized(2, 2)
.enterString("\033_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\033\\")
.assertLinesAre(" ", " ");
// It is ok for the APC content to be non printable characters:
withTerminalSized(12, 2)
.enterString("hello \033_some\023\033_\\apc#end\033\\ world")
.assertLinesAre("hello world", " ");
}
}

View File

@ -1,5 +1,7 @@
package com.termux.terminal;
import java.util.List;
/** "\033[" is the Control Sequence Introducer char sequence (CSI). */
public class ControlSequenceIntroducerTest extends TerminalTestCase {
@ -62,4 +64,68 @@ public class ControlSequenceIntroducerTest extends TerminalTestCase {
assertEquals("y\nz", mTerminal.getScreen().getTranscriptText());
}
public void testReportPixelSize() {
int columns = 3;
int rows = 3;
withTerminalSized(columns, rows);
int cellWidth = TerminalTest.INITIAL_CELL_WIDTH_PIXELS;
int cellHeight = TerminalTest.INITIAL_CELL_HEIGHT_PIXELS;
assertEnteringStringGivesResponse("\033[14t", "\033[4;" + (rows*cellHeight) + ";" + (columns*cellWidth) + "t");
assertEnteringStringGivesResponse("\033[16t", "\033[6;" + cellHeight + ";" + cellWidth + "t");
columns = 23;
rows = 33;
resize(columns, rows);
assertEnteringStringGivesResponse("\033[14t", "\033[4;" + (rows*cellHeight) + ";" + (columns*cellWidth) + "t");
assertEnteringStringGivesResponse("\033[16t", "\033[6;" + cellHeight + ";" + cellWidth + "t");
cellWidth = 8;
cellHeight = 18;
mTerminal.resize(columns, rows, cellWidth, cellHeight);
assertEnteringStringGivesResponse("\033[14t", "\033[4;" + (rows*cellHeight) + ";" + (columns*cellWidth) + "t");
assertEnteringStringGivesResponse("\033[16t", "\033[6;" + cellHeight + ";" + cellWidth + "t");
}
/**
* See <a href="https://sw.kovidgoyal.net/kitty/underlines/">Colored and styled underlines</a>:
*
* <pre>
* <ESC>[4:0m # no underline
* <ESC>[4:1m # straight underline
* <ESC>[4:2m # double underline
* <ESC>[4:3m # curly underline
* <ESC>[4:4m # dotted underline
* <ESC>[4:5m # dashed underline
* <ESC>[4m # straight underline (for backwards compat)
* <ESC>[24m # no underline (for backwards compat)
* </pre>
* <p>
* We currently parse the variants, but map them to normal/no underlines as appropriate
*/
public void testUnderlineVariants() {
for (String suffix : List.of("", ":1", ":2", ":3", ":4", ":5")) {
for (String stop : List.of("24", "4:0")) {
withTerminalSized(3, 3);
enterString("\033[4" + suffix + "m").assertLinesAre(" ", " ", " ");
assertEquals(TextStyle.CHARACTER_ATTRIBUTE_UNDERLINE, mTerminal.mEffect);
enterString("\033[4;1m").assertLinesAre(" ", " ", " ");
assertEquals(TextStyle.CHARACTER_ATTRIBUTE_BOLD | TextStyle.CHARACTER_ATTRIBUTE_UNDERLINE, mTerminal.mEffect);
enterString("\033[" + stop + "m").assertLinesAre(" ", " ", " ");
assertEquals(TextStyle.CHARACTER_ATTRIBUTE_BOLD, mTerminal.mEffect);
}
}
}
public void testManyParameters() {
StringBuilder b = new StringBuilder("\033[");
for (int i = 0; i < 30; i++) {
b.append("0;");
}
b.append("4:2");
// This clearing of underline should be ignored as the parameters pass the threshold for too many parameters:
b.append("4:0m");
withTerminalSized(3, 3)
.enterString(b.toString())
.assertLinesAre(" ", " ", " ");
assertEquals(TextStyle.CHARACTER_ATTRIBUTE_UNDERLINE, mTerminal.mEffect);
}
}

View File

@ -11,10 +11,10 @@ public class HistoryTest extends TerminalTestCase {
assertLinesAre("777", "888", "999");
assertHistoryStartsWith("666", "555");
mTerminal.resize(cols, 2);
resize(cols, 2);
assertHistoryStartsWith("777", "666", "555");
mTerminal.resize(cols, 3);
resize(cols, 3);
assertHistoryStartsWith("666", "555");
}

View File

@ -72,11 +72,11 @@ public class ResizeTest extends TerminalTestCase {
enterString("\r\n");
}
assertLinesAre("998 ", "999 ", " ");
mTerminal.resize(cols, 2);
resize(cols, 2);
assertLinesAre("999 ", " ");
mTerminal.resize(cols, 5);
resize(cols, 5);
assertLinesAre("996 ", "997 ", "998 ", "999 ", " ");
mTerminal.resize(cols, rows);
resize(cols, rows);
assertLinesAre("998 ", "999 ", " ");
}

View File

@ -75,6 +75,16 @@ public class ScrollRegionTest extends TerminalTestCase {
withTerminalSized(3, 3).enterString("\033[?69h\033[2sABC\033[?6h\033ED").assertLinesAre("ABC", " D ", " ");
}
public void testRiRespectsLeftMargin() {
// Reverse Index (RI), ${ESC}M, should respect horizontal margins:
withTerminalSized(4, 3).enterString("ABCD\033[?69h\033[2;3s\033[?6h\033M").assertLinesAre("A D", " BC ", " ");
}
public void testSdRespectsLeftMargin() {
// Scroll Down (SD), ${CSI}${N}T, should respect horizontal margins:
withTerminalSized(4, 3).enterString("ABCD\033[?69h\033[2;3s\033[?6h\033[2T").assertLinesAre("A D", " ", " BC ");
}
public void testBackwardIndex() {
// vttest "Menu 11.3.2: VT420 Cursor-Movement Test", test 7.
// Without margins:
@ -127,4 +137,31 @@ public class ScrollRegionTest extends TerminalTestCase {
" xxx"
);
}
/**
* See <a href="https://github.com/termux/termux-packages/issues/12556">reported issue</a>.
*/
public void testClearingWhenScrollingWithMargins() {
int newForeground = 2;
int newBackground = 3;
int size = 3;
TerminalTestCase terminal = withTerminalSized(size, size)
// Enable horizontal margin and set left margin to 1:
.enterString("\033[?69h\033[2s")
// Set foreground and background color:
.enterString("\033[" + (30 + newForeground) + ";" + (40 + newBackground) + "m")
// Enter newlines to scroll down:
.enterString("\r\n\r\n\r\n\r\n\r\n");
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
// The first column (outside of the scrolling area, due to us setting a left scroll
// margin of 1) should be unmodified, the others should use the current style:
int expectedForeground = col == 0 ? TextStyle.COLOR_INDEX_FOREGROUND : newForeground;
int expectedBackground = col == 0 ? TextStyle.COLOR_INDEX_BACKGROUND : newBackground;
terminal.assertForegroundColorAt(row, col, expectedForeground);
terminal.assertBackgroundColorAt(row, col, expectedBackground);
}
}
}
}

View File

@ -82,7 +82,7 @@ public class TerminalTest extends TerminalTestCase {
assertEnteringStringGivesResponse("\033[18t", "\033[8;5;5t");
for (int width = 3; width < 12; width++) {
for (int height = 3; height < 12; height++) {
mTerminal.resize(width, height);
resize(width, height);
assertEnteringStringGivesResponse("\033[18t", "\033[8;" + height + ";" + width + "t");
}
}
@ -137,6 +137,11 @@ public class TerminalTest extends TerminalTestCase {
}
public void testSelectGraphics() {
selectGraphicsTestRun(';');
selectGraphicsTestRun(':');
}
public void selectGraphicsTestRun(char separator) {
withTerminalSized(5, 5);
enterString("\033[31m");
assertEquals(mTerminal.mForeColor, 1);
@ -151,31 +156,63 @@ public class TerminalTest extends TerminalTestCase {
assertEquals(TextStyle.COLOR_INDEX_FOREGROUND, mTerminal.mForeColor);
assertEquals(TextStyle.COLOR_INDEX_BACKGROUND, mTerminal.mBackColor);
// Test CSI resetting to default if sequence starts with ; or has sequential ;;
// Check TerminalEmulator.parseArg()
enterString("\033[31m\033[m");
assertEquals(TextStyle.COLOR_INDEX_FOREGROUND, mTerminal.mForeColor);
enterString("\033[31m\033[;m".replace(';', separator));
assertEquals(TextStyle.COLOR_INDEX_FOREGROUND, mTerminal.mForeColor);
enterString("\033[31m\033[0m");
assertEquals(TextStyle.COLOR_INDEX_FOREGROUND, mTerminal.mForeColor);
enterString("\033[31m\033[0;m".replace(';', separator));
assertEquals(TextStyle.COLOR_INDEX_FOREGROUND, mTerminal.mForeColor);
enterString("\033[31;;m");
assertEquals(TextStyle.COLOR_INDEX_FOREGROUND, mTerminal.mForeColor);
enterString("\033[31::m");
assertEquals(1, mTerminal.mForeColor);
enterString("\033[31;m");
assertEquals(TextStyle.COLOR_INDEX_FOREGROUND, mTerminal.mForeColor);
enterString("\033[31:m");
assertEquals(1, mTerminal.mForeColor);
enterString("\033[31;;41m");
assertEquals(TextStyle.COLOR_INDEX_FOREGROUND, mTerminal.mForeColor);
assertEquals(1, mTerminal.mBackColor);
enterString("\033[0m");
assertEquals(TextStyle.COLOR_INDEX_BACKGROUND, mTerminal.mBackColor);
// 256 colors:
enterString("\033[38;5;119m");
enterString("\033[38;5;119m".replace(';', separator));
assertEquals(119, mTerminal.mForeColor);
assertEquals(TextStyle.COLOR_INDEX_BACKGROUND, mTerminal.mBackColor);
enterString("\033[48;5;129m");
enterString("\033[48;5;129m".replace(';', separator));
assertEquals(119, mTerminal.mForeColor);
assertEquals(129, mTerminal.mBackColor);
// Invalid parameter:
enterString("\033[48;8;129m");
enterString("\033[48;8;129m".replace(';', separator));
assertEquals(119, mTerminal.mForeColor);
assertEquals(129, mTerminal.mBackColor);
// Multiple parameters at once:
enterString("\033[38;5;178;48;5;179;m");
enterString("\033[38;5;178".replace(';', separator) + ";" + "48;5;179m".replace(';', separator));
assertEquals(178, mTerminal.mForeColor);
assertEquals(179, mTerminal.mBackColor);
// Omitted parameter means zero:
enterString("\033[38;5;m".replace(';', separator));
assertEquals(0, mTerminal.mForeColor);
assertEquals(179, mTerminal.mBackColor);
enterString("\033[48;5;m".replace(';', separator));
assertEquals(0, mTerminal.mForeColor);
assertEquals(0, mTerminal.mBackColor);
// 24 bit colors:
enterString(("\033[0m")); // Reset fg and bg colors.
enterString("\033[38;2;255;127;2m");
enterString("\033[38;2;255;127;2m".replace(';', separator));
int expectedForeground = 0xff000000 | (255 << 16) | (127 << 8) | 2;
assertEquals(expectedForeground, mTerminal.mForeColor);
assertEquals(TextStyle.COLOR_INDEX_BACKGROUND, mTerminal.mBackColor);
enterString("\033[48;2;1;2;254m");
enterString("\033[48;2;1;2;254m".replace(';', separator));
int expectedBackground = 0xff000000 | (1 << 16) | (2 << 8) | 254;
assertEquals(expectedForeground, mTerminal.mForeColor);
assertEquals(expectedBackground, mTerminal.mBackColor);
@ -184,14 +221,30 @@ public class TerminalTest extends TerminalTestCase {
enterString(("\033[0m")); // Reset fg and bg colors.
assertEquals(TextStyle.COLOR_INDEX_FOREGROUND, mTerminal.mForeColor);
assertEquals(TextStyle.COLOR_INDEX_BACKGROUND, mTerminal.mBackColor);
enterString("\033[38;2;255;127;2;48;2;1;2;254m");
enterString("\033[38;2;255;127;2".replace(';', separator) + ";" + "48;2;1;2;254m".replace(';', separator));
assertEquals(expectedForeground, mTerminal.mForeColor);
assertEquals(expectedBackground, mTerminal.mBackColor);
// 24 bit colors, invalid input:
enterString("\033[38;2;300;127;2;48;2;1;300;254m");
enterString("\033[38;2;300;127;2;48;2;1;300;254m".replace(';', separator));
assertEquals(expectedForeground, mTerminal.mForeColor);
assertEquals(expectedBackground, mTerminal.mBackColor);
// 24 bit colors, omitted parameter means zero:
enterString("\033[38;2;255;127;m".replace(';', separator));
expectedForeground = 0xff000000 | (255 << 16) | (127 << 8);
assertEquals(expectedForeground, mTerminal.mForeColor);
assertEquals(expectedBackground, mTerminal.mBackColor);
enterString("\033[38;2;123;;77m".replace(';', separator));
expectedForeground = 0xff000000 | (123 << 16) | 77;
assertEquals(expectedForeground, mTerminal.mForeColor);
assertEquals(expectedBackground, mTerminal.mBackColor);
// 24 bit colors, extra sub-parameters are skipped:
expectedForeground = 0xff000000 | (255 << 16) | (127 << 8) | 2;
enterString("\033[0;38:2:255:127:2:48:2:1:2:254m");
assertEquals(expectedForeground, mTerminal.mForeColor);
assertEquals(TextStyle.COLOR_INDEX_BACKGROUND, mTerminal.mBackColor);
}
public void testBackgroundColorErase() {

View File

@ -13,7 +13,10 @@ import java.util.Set;
public abstract class TerminalTestCase extends TestCase {
public static class MockTerminalOutput extends TerminalOutput {
public static final int INITIAL_CELL_WIDTH_PIXELS = 13;
public static final int INITIAL_CELL_HEIGHT_PIXELS = 15;
public static class MockTerminalOutput extends TerminalOutput {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
public final List<ChangedTitle> titleChanges = new ArrayList<>();
public final List<String> clipboardPuts = new ArrayList<>();
@ -108,7 +111,7 @@ public abstract class TerminalTestCase extends TestCase {
protected TerminalTestCase withTerminalSized(int columns, int rows) {
// The tests aren't currently using the client, so a null client will suffice, a dummy client should be implemented if needed
mTerminal = new TerminalEmulator(mOutput, columns, rows, rows * 2, null);
mTerminal = new TerminalEmulator(mOutput, columns, rows, INITIAL_CELL_WIDTH_PIXELS, INITIAL_CELL_HEIGHT_PIXELS, rows * 2, null);
return this;
}
@ -201,7 +204,7 @@ public abstract class TerminalTestCase extends TestCase {
}
public TerminalTestCase resize(int cols, int rows) {
mTerminal.resize(cols, rows);
mTerminal.resize(cols, rows, INITIAL_CELL_WIDTH_PIXELS, INITIAL_CELL_HEIGHT_PIXELS);
assertInvariants();
return this;
}
@ -301,6 +304,11 @@ public abstract class TerminalTestCase extends TestCase {
assertEquals(color, TextStyle.decodeForeColor(style));
}
public void assertBackgroundColorAt(int externalRow, int column, int color) {
long style = mTerminal.getScreen().mLines[mTerminal.getScreen().externalToInternalRow(externalRow)].getStyle(column);
assertEquals(color, TextStyle.decodeBackColor(style));
}
public TerminalTestCase assertColor(int colorIndex, int expected) {
int actual = mTerminal.mColors.mCurrentColors[colorIndex];
if (expected != actual) {

View File

@ -2,10 +2,11 @@ apply plugin: 'com.android.library'
apply plugin: 'maven-publish'
android {
namespace "com.termux.view"
compileSdkVersion project.properties.compileSdkVersion.toInteger()
dependencies {
implementation "androidx.annotation:annotation:1.3.0"
implementation "androidx.annotation:annotation:1.9.0"
api project(":terminal-emulator")
}
@ -29,12 +30,12 @@ android {
}
dependencies {
testImplementation 'junit:junit:4.13.2'
testImplementation "junit:junit:4.13.2"
}
task sourceJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier "sources"
archiveClassifier = "sources"
}
afterEvaluate {
@ -42,7 +43,7 @@ afterEvaluate {
publications {
// Creates a Maven publication called "release".
release(MavenPublication) {
from components.release
from components.findByName('release')
groupId = 'com.termux'
artifactId = 'terminal-view'
version = '0.118.0'
@ -51,3 +52,4 @@ afterEvaluate {
}
}
}

View File

@ -1,2 +1,2 @@
<manifest package="com.termux.view">
<manifest>
</manifest>

View File

@ -233,7 +233,7 @@ public final class TerminalRenderer {
mTextPaint.setColor(foreColor);
// The text alignment is the default Paint.Align.LEFT.
canvas.drawText(text, startCharIndex, runWidthChars, left, y - mFontLineSpacingAndAscent, mTextPaint);
canvas.drawTextRun(text, startCharIndex, runWidthChars, startCharIndex, runWidthChars, left, y - mFontLineSpacingAndAscent, false, mTextPaint);
}
if (savedMatrix) canvas.restore();

View File

@ -2,6 +2,7 @@ package com.termux.view;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
@ -10,6 +11,7 @@ import android.graphics.Typeface;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
@ -19,17 +21,20 @@ import android.view.HapticFeedbackConstants;
import android.view.InputDevice;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewTreeObserver;
import android.view.accessibility.AccessibilityManager;
import android.view.autofill.AutofillManager;
import android.view.autofill.AutofillValue;
import android.view.inputmethod.BaseInputConnection;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.widget.Scroller;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.termux.terminal.KeyHandler;
@ -81,8 +86,51 @@ public final class TerminalView extends View {
/** If non-zero, this is the last unicode code point received if that was a combining character. */
int mCombiningAccent;
/**
* The current AutoFill type returned for {@link View#getAutofillType()} by {@link #getAutofillType()}.
*
* The default is {@link #AUTOFILL_TYPE_NONE} so that AutoFill UI, like toolbar above keyboard
* is not shown automatically, like on Activity starts/View create. This value should be updated
* to required value, like {@link #AUTOFILL_TYPE_TEXT} before calling
* {@link AutofillManager#requestAutofill(View)} so that AutoFill UI shows. The updated value
* set will automatically be restored to {@link #AUTOFILL_TYPE_NONE} in
* {@link #autofill(AutofillValue)} so that AutoFill UI isn't shown anymore by calling
* {@link #resetAutoFill()}.
*/
@RequiresApi(api = Build.VERSION_CODES.O)
private int mAutoFillType = AUTOFILL_TYPE_NONE;
/**
* The current AutoFill type returned for {@link View#getImportantForAutofill()} by
* {@link #getImportantForAutofill()}.
*
* The default is {@link #IMPORTANT_FOR_AUTOFILL_NO} so that view is not considered important
* for AutoFill. This value should be updated to required value, like
* {@link #IMPORTANT_FOR_AUTOFILL_YES} before calling {@link AutofillManager#requestAutofill(View)}
* so that Android and apps consider the view as important for AutoFill to process the request.
* The updated value set will automatically be restored to {@link #IMPORTANT_FOR_AUTOFILL_NO} in
* {@link #autofill(AutofillValue)} by calling {@link #resetAutoFill()}.
*/
@RequiresApi(api = Build.VERSION_CODES.O)
private int mAutoFillImportance = IMPORTANT_FOR_AUTOFILL_NO;
/**
* The current AutoFill hints returned for {@link View#getAutofillHints()} ()} by {@link #getAutofillHints()} ()}.
*
* The default is an empty `string[]`. This value should be updated to required value. The
* updated value set will automatically be restored an empty `string[]` in
* {@link #autofill(AutofillValue)} by calling {@link #resetAutoFill()}.
*/
private String[] mAutoFillHints = new String[0];
private final boolean mAccessibilityEnabled;
/** The {@link KeyEvent} is generated from a virtual keyboard, like manually with the {@link KeyEvent#KeyEvent(int, int)} constructor. */
public final static int KEY_EVENT_SOURCE_VIRTUAL_KEYBOARD = KeyCharacterMap.VIRTUAL_KEYBOARD; // -1
/** The {@link KeyEvent} is generated from a non-physical device, like if 0 value is returned by {@link KeyEvent#getDeviceId()}. */
public final static int KEY_EVENT_SOURCE_SOFT_KEYBOARD = 0;
private static final String LOG_TAG = "TerminalView";
public TerminalView(Context context, AttributeSet attributes) { // NO_UCD (unused code)
@ -380,7 +428,7 @@ public final class TerminalView extends View {
}
}
inputCodePoint(codePoint, ctrlHeld, false);
inputCodePoint(KEY_EVENT_SOURCE_SOFT_KEYBOARD, codePoint, ctrlHeld, false);
}
}
@ -403,19 +451,29 @@ public final class TerminalView extends View {
}
public void onScreenUpdated() {
onScreenUpdated(false);
}
public void onScreenUpdated(boolean skipScrolling) {
if (mEmulator == null) return;
int rowsInHistory = mEmulator.getScreen().getActiveTranscriptRows();
if (mTopRow < -rowsInHistory) mTopRow = -rowsInHistory;
boolean skipScrolling = false;
if (isSelectingText()) {
if (isSelectingText() || mEmulator.isAutoScrollDisabled()) {
// Do not scroll when selecting text.
int rowShift = mEmulator.getScrollCounter();
if (-mTopRow + rowShift > rowsInHistory) {
// .. unless we're hitting the end of history transcript, in which
// case we abort text selection and scroll to end.
stopTextSelectionMode();
if (isSelectingText())
stopTextSelectionMode();
if (mEmulator.isAutoScrollDisabled()) {
mTopRow = -rowsInHistory;
skipScrolling = true;
}
} else {
skipScrolling = true;
mTopRow -= rowShift;
@ -440,6 +498,14 @@ public final class TerminalView extends View {
if (mAccessibilityEnabled) setContentDescription(getText());
}
/** This must be called by the hosting activity in {@link Activity#onContextMenuClosed(Menu)}
* when context menu for the {@link TerminalView} is started by
* {@link TextSelectionCursorController#ACTION_MORE} is closed. */
public void onContextMenuClosed(Menu menu) {
// Unset the stored text since it shouldn't be used anymore and should be cleared from memory
unsetStoredSelectedText();
}
/**
* Sets the text size, which in turn sets the number of rows and columns.
*
@ -550,11 +616,14 @@ public final class TerminalView extends View {
if (action == MotionEvent.ACTION_DOWN) showContextMenu();
return true;
} else if (event.isButtonPressed(MotionEvent.BUTTON_TERTIARY)) {
ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clipData = clipboard.getPrimaryClip();
ClipboardManager clipboardManager = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clipData = clipboardManager.getPrimaryClip();
if (clipData != null) {
CharSequence paste = clipData.getItemAt(0).coerceToText(getContext());
if (!TextUtils.isEmpty(paste)) mEmulator.paste(paste.toString());
ClipData.Item clipItem = clipData.getItemAt(0);
if (clipItem != null) {
CharSequence text = clipItem.coerceToText(getContext());
if (!TextUtils.isEmpty(text)) mEmulator.paste(text.toString());
}
}
} else if (mEmulator.isMouseTrackingActive()) { // BUTTON_PRIMARY.
switch (event.getAction()) {
@ -578,6 +647,7 @@ public final class TerminalView extends View {
if (TERMINAL_VIEW_KEY_LOGGING_ENABLED)
mClient.logInfo(LOG_TAG, "onKeyPreIme(keyCode=" + keyCode + ", event=" + event + ")");
if (keyCode == KeyEvent.KEYCODE_BACK) {
cancelRequestAutoFill();
if (isSelectingText()) {
stopTextSelectionMode();
return true;
@ -755,7 +825,7 @@ public final class TerminalView extends View {
if ((result & KeyCharacterMap.COMBINING_ACCENT) != 0) {
// If entered combining accent previously, write it out:
if (mCombiningAccent != 0)
inputCodePoint(mCombiningAccent, controlDown, leftAltDown);
inputCodePoint(event.getDeviceId(), mCombiningAccent, controlDown, leftAltDown);
mCombiningAccent = result & KeyCharacterMap.COMBINING_ACCENT_MASK;
} else {
if (mCombiningAccent != 0) {
@ -763,7 +833,7 @@ public final class TerminalView extends View {
if (combinedChar > 0) result = combinedChar;
mCombiningAccent = 0;
}
inputCodePoint(result, controlDown, leftAltDown);
inputCodePoint(event.getDeviceId(), result, controlDown, leftAltDown);
}
if (mCombiningAccent != oldCombiningAccent) invalidate();
@ -771,9 +841,9 @@ public final class TerminalView extends View {
return true;
}
public void inputCodePoint(int codePoint, boolean controlDownFromEvent, boolean leftAltDownFromEvent) {
public void inputCodePoint(int eventSource, int codePoint, boolean controlDownFromEvent, boolean leftAltDownFromEvent) {
if (TERMINAL_VIEW_KEY_LOGGING_ENABLED) {
mClient.logInfo(LOG_TAG, "inputCodePoint(codePoint=" + codePoint + ", controlDownFromEvent=" + controlDownFromEvent + ", leftAltDownFromEvent="
mClient.logInfo(LOG_TAG, "inputCodePoint(eventSource=" + eventSource + ", codePoint=" + codePoint + ", controlDownFromEvent=" + controlDownFromEvent + ", leftAltDownFromEvent="
+ leftAltDownFromEvent + ")");
}
@ -813,19 +883,22 @@ public final class TerminalView extends View {
}
if (codePoint > -1) {
// Work around bluetooth keyboards sending funny unicode characters instead
// of the more normal ones from ASCII that terminal programs expect - the
// desire to input the original characters should be low.
switch (codePoint) {
case 0x02DC: // SMALL TILDE.
codePoint = 0x007E; // TILDE (~).
break;
case 0x02CB: // MODIFIER LETTER GRAVE ACCENT.
codePoint = 0x0060; // GRAVE ACCENT (`).
break;
case 0x02C6: // MODIFIER LETTER CIRCUMFLEX ACCENT.
codePoint = 0x005E; // CIRCUMFLEX ACCENT (^).
break;
// If not virtual or soft keyboard.
if (eventSource > KEY_EVENT_SOURCE_SOFT_KEYBOARD) {
// Work around bluetooth keyboards sending funny unicode characters instead
// of the more normal ones from ASCII that terminal programs expect - the
// desire to input the original characters should be low.
switch (codePoint) {
case 0x02DC: // SMALL TILDE.
codePoint = 0x007E; // TILDE (~).
break;
case 0x02CB: // MODIFIER LETTER GRAVE ACCENT.
codePoint = 0x0060; // GRAVE ACCENT (`).
break;
case 0x02C6: // MODIFIER LETTER CIRCUMFLEX ACCENT.
codePoint = 0x005E; // CIRCUMFLEX ACCENT (^).
break;
}
}
// If left alt, send escape before the code point to make e.g. Alt+B and Alt+F work in readline:
@ -839,6 +912,9 @@ public final class TerminalView extends View {
if (mEmulator != null)
mEmulator.setCursorBlinkState(true);
if (handleKeyCodeAction(keyCode, keyMod))
return true;
TerminalEmulator term = mTermSession.getEmulator();
String code = KeyHandler.getCode(keyCode, keyMod, term.isCursorKeysApplicationMode(), term.isKeypadApplicationMode());
if (code == null) return false;
@ -846,6 +922,26 @@ public final class TerminalView extends View {
return true;
}
public boolean handleKeyCodeAction(int keyCode, int keyMod) {
boolean shiftDown = (keyMod & KeyHandler.KEYMOD_SHIFT) != 0;
switch (keyCode) {
case KeyEvent.KEYCODE_PAGE_UP:
case KeyEvent.KEYCODE_PAGE_DOWN:
// shift+page_up and shift+page_down should scroll scrollback history instead of
// scrolling command history or changing pages
if (shiftDown) {
long time = SystemClock.uptimeMillis();
MotionEvent motionEvent = MotionEvent.obtain(time, time, MotionEvent.ACTION_DOWN, 0, 0, 0);
doScroll(motionEvent, keyCode == KeyEvent.KEYCODE_PAGE_UP ? -mEmulator.mRows : mEmulator.mRows);
motionEvent.recycle();
return true;
}
}
return false;
}
/**
* Called when a key is released in the view.
*
@ -893,7 +989,7 @@ public final class TerminalView extends View {
int newRows = Math.max(4, (viewHeight - mRenderer.mFontLineSpacingAndAscent) / mRenderer.mFontLineSpacing);
if (mEmulator == null || (newColumns != mEmulator.mColumns || newRows != mEmulator.mRows)) {
mTermSession.updateSize(newColumns, newRows);
mTermSession.updateSize(newColumns, newRows, (int) mRenderer.getFontWidth(), mRenderer.getFontLineSpacing());
mEmulator = mTermSession.getEmulator();
mClient.onEmulatorSet();
@ -971,12 +1067,20 @@ public final class TerminalView extends View {
if (value.isText()) {
mTermSession.write(value.getTextValue().toString());
}
resetAutoFill();
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public int getAutofillType() {
return AUTOFILL_TYPE_TEXT;
return mAutoFillType;
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public String[] getAutofillHints() {
return mAutoFillHints;
}
@RequiresApi(api = Build.VERSION_CODES.O)
@ -985,6 +1089,95 @@ public final class TerminalView extends View {
return AutofillValue.forText("");
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public int getImportantForAutofill() {
return mAutoFillImportance;
}
@RequiresApi(api = Build.VERSION_CODES.O)
private synchronized void resetAutoFill() {
// Restore none type so that AutoFill UI isn't shown anymore.
mAutoFillType = AUTOFILL_TYPE_NONE;
mAutoFillImportance = IMPORTANT_FOR_AUTOFILL_NO;
mAutoFillHints = new String[0];
}
public AutofillManager getAutoFillManagerService() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return null;
try {
Context context = getContext();
if (context == null) return null;
return context.getSystemService(AutofillManager.class);
} catch (Exception e) {
mClient.logStackTraceWithMessage(LOG_TAG, "Failed to get AutofillManager service", e);
return null;
}
}
public boolean isAutoFillEnabled() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return false;
try {
AutofillManager autofillManager = getAutoFillManagerService();
return autofillManager != null && autofillManager.isEnabled();
} catch (Exception e) {
mClient.logStackTraceWithMessage(LOG_TAG, "Failed to check if Autofill is enabled", e);
return false;
}
}
public synchronized void requestAutoFillUsername() {
requestAutoFill(
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? new String[]{View.AUTOFILL_HINT_USERNAME} :
null);
}
public synchronized void requestAutoFillPassword() {
requestAutoFill(
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? new String[]{View.AUTOFILL_HINT_PASSWORD} :
null);
}
public synchronized void requestAutoFill(String[] autoFillHints) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return;
if (autoFillHints == null || autoFillHints.length < 1) return;
try {
AutofillManager autofillManager = getAutoFillManagerService();
if (autofillManager != null && autofillManager.isEnabled()) {
// Update type that will be returned by `getAutofillType()` so that AutoFill UI is shown.
mAutoFillType = AUTOFILL_TYPE_TEXT;
// Update importance that will be returned by `getImportantForAutofill()` so that
// AutoFill considers the view as important.
mAutoFillImportance = IMPORTANT_FOR_AUTOFILL_YES;
// Update hints that will be returned by `getAutofillHints()` for which to show AutoFill UI.
mAutoFillHints = autoFillHints;
autofillManager.requestAutofill(this);
}
} catch (Exception e) {
mClient.logStackTraceWithMessage(LOG_TAG, "Failed to request Autofill", e);
}
}
public synchronized void cancelRequestAutoFill() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return;
if (mAutoFillType == AUTOFILL_TYPE_NONE) return;
try {
AutofillManager autofillManager = getAutoFillManagerService();
if (autofillManager != null && autofillManager.isEnabled()) {
resetAutoFill();
autofillManager.cancel();
}
} catch (Exception e) {
mClient.logStackTraceWithMessage(LOG_TAG, "Failed to cancel Autofill request", e);
}
}
/**
@ -1184,6 +1377,25 @@ public final class TerminalView extends View {
}
}
/** Get the currently selected text if selecting. */
public String getSelectedText() {
if (isSelectingText() && mTextSelectionCursorController != null)
return mTextSelectionCursorController.getSelectedText();
else
return null;
}
/** Get the selected text stored before "MORE" button was pressed on the context menu. */
@Nullable
public String getStoredSelectedText() {
return mTextSelectionCursorController != null ? mTextSelectionCursorController.getStoredSelectedText() : null;
}
/** Unset the selected text stored before "MORE" button was pressed on the context menu. */
public void unsetStoredSelectedText() {
if (mTextSelectionCursorController != null) mTextSelectionCursorController.unsetStoredSelectedText();
}
private ActionMode getTextSelectionActionMode() {
if (mTextSelectionCursorController != null) {
return mTextSelectionCursorController.getActionMode();
@ -1245,6 +1457,7 @@ public final class TerminalView extends View {
* Define functions required for long hold toolbar.
*/
private final Runnable mShowFloatingToolbar = new Runnable() {
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void run() {
if (getTextSelectionActionMode() != null) {
@ -1253,6 +1466,7 @@ public final class TerminalView extends View {
}
};
@RequiresApi(api = Build.VERSION_CODES.M)
private void showFloatingToolbar() {
if (getTextSelectionActionMode() != null) {
int delay = ViewConfiguration.getDoubleTapTimeout();
@ -1260,6 +1474,7 @@ public final class TerminalView extends View {
}
}
@RequiresApi(api = Build.VERSION_CODES.M)
void hideFloatingToolbar() {
if (getTextSelectionActionMode() != null) {
removeCallbacks(mShowFloatingToolbar);
@ -1268,7 +1483,7 @@ public final class TerminalView extends View {
}
public void updateFloatingToolbarVisibility(MotionEvent event) {
if (getTextSelectionActionMode() != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && getTextSelectionActionMode() != null) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_MOVE:
hideFloatingToolbar();

View File

@ -0,0 +1,75 @@
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.termux.view.support;
import android.util.Log;
import android.widget.PopupWindow;
import java.lang.reflect.Method;
/**
* Implementation of PopupWindow compatibility that can call Gingerbread APIs.
* https://chromium.googlesource.com/android_tools/+/HEAD/sdk/extras/android/support/v4/src/gingerbread/android/support/v4/widget/PopupWindowCompatGingerbread.java
*/
public class PopupWindowCompatGingerbread {
private static Method sSetWindowLayoutTypeMethod;
private static boolean sSetWindowLayoutTypeMethodAttempted;
private static Method sGetWindowLayoutTypeMethod;
private static boolean sGetWindowLayoutTypeMethodAttempted;
public static void setWindowLayoutType(PopupWindow popupWindow, int layoutType) {
if (!sSetWindowLayoutTypeMethodAttempted) {
try {
sSetWindowLayoutTypeMethod = PopupWindow.class.getDeclaredMethod(
"setWindowLayoutType", int.class);
sSetWindowLayoutTypeMethod.setAccessible(true);
} catch (Exception e) {
// Reflection method fetch failed. Oh well.
}
sSetWindowLayoutTypeMethodAttempted = true;
}
if (sSetWindowLayoutTypeMethod != null) {
try {
sSetWindowLayoutTypeMethod.invoke(popupWindow, layoutType);
} catch (Exception e) {
// Reflection call failed. Oh well.
}
}
}
public static int getWindowLayoutType(PopupWindow popupWindow) {
if (!sGetWindowLayoutTypeMethodAttempted) {
try {
sGetWindowLayoutTypeMethod = PopupWindow.class.getDeclaredMethod(
"getWindowLayoutType");
sGetWindowLayoutTypeMethod.setAccessible(true);
} catch (Exception e) {
// Reflection method fetch failed. Oh well.
}
sGetWindowLayoutTypeMethodAttempted = true;
}
if (sGetWindowLayoutTypeMethod != null) {
try {
return (Integer) sGetWindowLayoutTypeMethod.invoke(popupWindow);
} catch (Exception e) {
// Reflection call failed. Oh well.
}
}
return 0;
}
}

View File

@ -1,17 +1,18 @@
package com.termux.view.textselection;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.text.TextUtils;
import android.view.ActionMode;
import android.view.InputDevice;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import com.termux.terminal.TerminalBuffer;
import com.termux.terminal.WcWidth;
import com.termux.view.R;
@ -21,6 +22,7 @@ public class TextSelectionCursorController implements CursorController {
private final TerminalView terminalView;
private final TextSelectionHandleView mStartHandle, mEndHandle;
private String mStoredSelectedText;
private boolean mIsSelectingText = false;
private long mShowStartTime = System.currentTimeMillis();
@ -28,9 +30,9 @@ public class TextSelectionCursorController implements CursorController {
private int mSelX1 = -1, mSelX2 = -1, mSelY1 = -1, mSelY2 = -1;
private ActionMode mActionMode;
private final int ACTION_COPY = 1;
private final int ACTION_PASTE = 2;
private final int ACTION_MORE = 3;
public final int ACTION_COPY = 1;
public final int ACTION_PASTE = 2;
public final int ACTION_MORE = 3;
public TextSelectionCursorController(TerminalView terminalView) {
this.terminalView = terminalView;
@ -113,7 +115,7 @@ public class TextSelectionCursorController implements CursorController {
ClipboardManager clipboard = (ClipboardManager) terminalView.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
menu.add(Menu.NONE, ACTION_COPY, Menu.NONE, R.string.copy_text).setShowAsAction(show);
menu.add(Menu.NONE, ACTION_PASTE, Menu.NONE, R.string.paste_text).setEnabled(clipboard.hasPrimaryClip()).setShowAsAction(show);
menu.add(Menu.NONE, ACTION_PASTE, Menu.NONE, R.string.paste_text).setEnabled(clipboard != null && clipboard.hasPrimaryClip()).setShowAsAction(show);
menu.add(Menu.NONE, ACTION_MORE, Menu.NONE, R.string.text_selection_more);
return true;
}
@ -132,7 +134,7 @@ public class TextSelectionCursorController implements CursorController {
switch (item.getItemId()) {
case ACTION_COPY:
String selectedText = terminalView.mEmulator.getSelectedText(mSelX1, mSelY1, mSelX2, mSelY2).trim();
String selectedText = getSelectedText();
terminalView.mTermSession.onCopyTextToClipboard(selectedText);
terminalView.stopTextSelectionMode();
break;
@ -141,7 +143,13 @@ public class TextSelectionCursorController implements CursorController {
terminalView.mTermSession.onPasteTextFromClipboard();
break;
case ACTION_MORE:
terminalView.stopTextSelectionMode(); //we stop text selection first, otherwise handles will show above popup
// We first store the selected text in case TerminalViewClient needs the
// selected text before MORE button was pressed since we are going to
// stop selection mode
mStoredSelectedText = getSelectedText();
// The text selection needs to be stopped before showing context menu,
// otherwise handles will show above popup
terminalView.stopTextSelectionMode();
terminalView.showContextMenu();
break;
}
@ -155,6 +163,12 @@ public class TextSelectionCursorController implements CursorController {
};
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
mActionMode = terminalView.startActionMode(callback);
return;
}
//noinspection NewApi
mActionMode = terminalView.startActionMode(new ActionMode.Callback2() {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
@ -183,14 +197,19 @@ public class TextSelectionCursorController implements CursorController {
int y1 = Math.round((mSelY1 - 1 - terminalView.getTopRow()) * terminalView.mRenderer.getFontLineSpacing());
int y2 = Math.round((mSelY2 + 1 - terminalView.getTopRow()) * terminalView.mRenderer.getFontLineSpacing());
if (x1 > x2) {
int tmp = x1;
x1 = x2;
x2 = tmp;
}
outRect.set(x1, y1 + mHandleHeight, x2, y2 + mHandleHeight);
int terminalBottom = terminalView.getBottom();
int top = y1 + mHandleHeight;
int bottom = y2 + mHandleHeight;
if (top > terminalBottom) top = terminalBottom;
if (bottom > terminalBottom) bottom = terminalBottom;
outRect.set(x1, top, x2, bottom);
}
}, ActionMode.TYPE_FLOATING);
}
@ -351,6 +370,22 @@ public class TextSelectionCursorController implements CursorController {
sel[3] = mSelX2;
}
/** Get the currently selected text. */
public String getSelectedText() {
return terminalView.mEmulator.getSelectedText(mSelX1, mSelY1, mSelX2, mSelY2);
}
/** Get the selected text stored before "MORE" button was pressed on the context menu. */
@Nullable
public String getStoredSelectedText() {
return mStoredSelectedText;
}
/** Unset the selected text stored before "MORE" button was pressed on the context menu. */
public void unsetStoredSelectedText() {
mStoredSelectedText = null;
}
public ActionMode getActionMode() {
return mActionMode;
}

View File

@ -4,6 +4,7 @@ import android.annotation.SuppressLint;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.SystemClock;
import android.view.MotionEvent;
import android.view.View;
@ -14,6 +15,7 @@ import android.widget.PopupWindow;
import com.termux.view.R;
import com.termux.view.TerminalView;
import com.termux.view.support.PopupWindowCompatGingerbread;
@SuppressLint("ViewConstructor")
public class TextSelectionHandleView extends View {
@ -68,13 +70,18 @@ public class TextSelectionHandleView extends View {
android.R.attr.textSelectHandleWindowStyle);
mHandle.setSplitTouchEnabled(true);
mHandle.setClippingEnabled(false);
mHandle.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL);
mHandle.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
mHandle.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
mHandle.setBackgroundDrawable(null);
mHandle.setAnimationStyle(0);
mHandle.setEnterTransition(null);
mHandle.setExitTransition(null);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mHandle.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL);
mHandle.setEnterTransition(null);
mHandle.setExitTransition(null);
} else {
PopupWindowCompatGingerbread.setWindowLayoutType(mHandle, WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL);
}
mHandle.setContentView(this);
}

View File

@ -1,55 +1,12 @@
The `termux-shared` library is released under [GPLv3 only](https://www.gnu.org/licenses/gpl-3.0.html) license.
The `termux-shared` library is released under [MIT](https://opensource.org/licenses/MIT) license.
### Exceptions
#### [MIT License](https://opensource.org/licenses/MIT)
#### [GPLv3 only](https://www.gnu.org/licenses/gpl-3.0.html)
- [`src/main/java/com/termux/shared/termux/TermuxConstants.java`](src/main/java/com/termux/shared/termux/TermuxConstants.java).
- [`src/main/java/com/termux/shared/settings/properties/TermuxPropertyConstants.java`](src/main/java/com/termux/shared/settings/properties/TermuxPropertyConstants.java).
- [`src/main/java/com/termux/shared/termux/*`](src/main/java/com/termux/shared/termux).
- [`src/main/java/com/termux/shared/activities/*`](src/main/java/com/termux/shared/activities).
- [`src/main/java/com/termux/shared/crash/CrashHandler.java`](src/main/java/com/termux/shared/crash/CrashHandler.java).
- [`src/main/java/com/termux/shared/data/DataUtils.java`](src/main/java/com/termux/shared/data/DataUtils.java).
- [`src/main/java/com/termux/shared/data/IntentUtils.java`](src/main/java/com/termux/shared/data/IntentUtils.java).
- [`src/main/java/com/termux/shared/file/filesystem/FileType.java`](src/main/java/com/termux/shared/file/filesystem/FileType.java).
- [`src/main/java/com/termux/shared/file/filesystem/FileTypes.java`](src/main/java/com/termux/shared/file/filesystem/FileTypes.java).
- [`src/main/java/com/termux/shared/file/filesystem/NativeDispatcher.java`](src/main/java/com/termux/shared/file/filesystem/NativeDispatcher.java).
- [`src/main/java/com/termux/shared/file/tests/FileUtilsTests.java`](src/main/java/com/termux/shared/file/tests/FileUtilsTests.java).
- [`src/main/java/com/termux/shared/file/FileUtils.java`](src/main/java/com/termux/shared/file/FileUtils.java).
- [`src/main/java/com/termux/shared/interact/ShareUtils.java`](src/main/java/com/termux/shared/interact/ShareUtils.java).
- [`src/main/java/com/termux/shared/interact/MessageDialogUtils.java`](src/main/java/com/termux/shared/interact/MessageDialogUtils.java).
- [`src/main/java/com/termux/shared/logger/Logger.java`](src/main/java/com/termux/shared/logger/Logger.java).
- [`src/main/java/com/termux/shared/markdown/MarkdownUtils.java`](src/main/java/com/termux/shared/markdown/MarkdownUtils.java).
- [`src/main/java/com/termux/shared/models/*`](src/main/java/com/termux/shared/models).
- [`src/main/java/com/termux/shared/notification/NotificationUtils.java`](src/main/java/com/termux/shared/notification/NotificationUtils.java).
- [`src/main/java/com/termux/shared/settings/preferences/SharedPreferenceUtils.java`](src/main/java/com/termux/shared/settings/preferences/SharedPreferenceUtils.java).
- [`src/main/java/com/termux/shared/settings/properties/SharedPropertiesParser.java`](src/main/java/com/termux/shared/settings/properties/SharedPropertiesParser.java).
- [`src/main/java/com/termux/shared/settings/properties/SharedProperties.java`](src/main/java/com/termux/shared/settings/properties/SharedProperties.java).
- [`src/main/java/com/termux/shared/shell/ResultSender.java`](src/main/java/com/termux/shared/shell/ResultSender.java).
- [`src/main/java/com/termux/shared/shell/ShellEnvironmentClient.java`](src/main/java/com/termux/shared/shell/ShellEnvironmentClient.java).
- [`src/main/java/com/termux/shared/shell/ShellUtils.java`](src/main/java/com/termux/shared/shell/ShellUtils.java).
- [`src/main/java/com/termux/shared/shell/TermuxTask.java`](src/main/java/com/termux/shared/shell/TermuxTask.java).
- [`src/main/java/com/termux/shared/termux/AndroidUtils.java`](src/main/java/com/termux/shared/termux/AndroidUtils.java).
- [`src/main/java/com/termux/shared/view/KeyboardUtils.java`](src/main/java/com/termux/shared/view/KeyboardUtils.java).
- [`src/main/java/com/termux/shared/view/ViewUtils.java`](src/main/java/com/termux/shared/view/ViewUtils.java).
- [`src/main/res/drawable/*`](src/main/res/drawable).
- [`src/main/res/layout/*`](src/main/res/layout).
- [`src/main/res/menu/*`](src/main/res/menu).
- [`src/main/res/values/*`](src/main/res/values).
The `GPLv3 only` license applies to all files unless specifically specified by a file/directory, like the [`src/main/java/com/termux/shared/termux/TermuxConstants.java`](src/main/java/com/termux/shared/termux/TermuxConstants.java) and [`src/main/java/com/termux/shared/termux/settings/properties/TermuxPropertyConstants.java`](src/main/java/com/termux/shared/termux/settings/properties/TermuxPropertyConstants.java) files are released under the `MIT` license.
##
@ -59,7 +16,7 @@ The `termux-shared` library is released under [GPLv3 only](https://www.gnu.org/l
##
#### [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0)
#### [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0)
- [`src/main/java/com/termux/shared/shell/StreamGobbler.java`](src/main/java/com/termux/shared/shell/StreamGobbler.java) uses code from [libsuperuser ](https://github.com/Chainfire/libsuperuser).
##

View File

@ -2,22 +2,24 @@ apply plugin: 'com.android.library'
apply plugin: 'maven-publish'
android {
namespace = "com.termux.shared"
compileSdkVersion project.properties.compileSdkVersion.toInteger()
ndkVersion = System.getenv("JITPACK_NDK_VERSION") ?: project.properties.ndkVersion
dependencies {
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation "androidx.annotation:annotation:1.3.0"
implementation "androidx.core:core:1.6.0"
implementation 'com.google.android.material:material:1.4.0'
implementation "androidx.appcompat:appcompat:1.6.1"
implementation "androidx.annotation:annotation:1.9.0"
implementation "androidx.core:core:1.13.1"
implementation "com.google.android.material:material:1.12.0"
implementation "com.google.guava:guava:24.1-jre"
implementation "io.noties.markwon:core:$markwonVersion"
implementation "io.noties.markwon:ext-strikethrough:$markwonVersion"
implementation "io.noties.markwon:linkify:$markwonVersion"
implementation "io.noties.markwon:recycler:$markwonVersion"
implementation "org.lsposed.hiddenapibypass:hiddenapibypass:6.1"
// Do not increment version higher than 1.0.0-alpha09 since it will break ViewUtils and needs to be looked into
// noinspection GradleDependency
implementation "androidx.window:window:1.0.0-alpha09"
implementation "androidx.window:window:1.1.0"
// Do not increment version higher than 2.5 or there
// will be runtime exceptions on android < 8
@ -25,12 +27,20 @@ android {
implementation "commons-io:commons-io:2.5"
implementation project(":terminal-view")
implementation "com.termux:termux-am-library:v2.0.0"
}
defaultConfig {
compileSdkVersion project.properties.compileSdkVersion.toInteger()
minSdkVersion project.properties.minSdkVersion.toInteger()
targetSdkVersion project.properties.targetSdkVersion.toInteger()
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
externalNativeBuild {
ndkBuild {
cppFlags ''
}
}
}
buildTypes {
@ -41,20 +51,29 @@ android {
}
compileOptions {
// Flag to enable support for the new language APIs
coreLibraryDesugaringEnabled true
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
externalNativeBuild {
ndkBuild {
path file('src/main/cpp/Android.mk')
}
}
}
dependencies {
testImplementation "junit:junit:4.13.2"
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
androidTestImplementation "androidx.test.ext:junit:1.1.5"
coreLibraryDesugaring "com.android.tools:desugar_jdk_libs:2.1.2"
}
task sourceJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier "sources"
archiveClassifier = "sources"
}
afterEvaluate {
@ -62,7 +81,7 @@ afterEvaluate {
publications {
// Creates a Maven publication called "release".
release(MavenPublication) {
from components.release
from components.findByName('release')
groupId = 'com.termux'
artifactId = 'termux-shared'
version = '0.118.0'

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