# Technical Documentation: TeamAmaze/AmazeFileManager

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/TeamAmaze/AmazeFileManager)

### Overview (`README.md`)

[](https://app.codacy.com/gh/TeamAmaze/AmazeFileManager?utm_source=github.com&utm_medium=referral&utm_content=TeamAmaze/AmazeFileManager&utm_campaign=Badge_Grade_Settings)
[](https://www.codacy.com/gh/TeamAmaze/AmazeFileManager?utm_source=github.com&utm_medium=referral&utm_content=TeamAmaze/AmazeFileManager&utm_campaign=Badge_Coverage)
[](https://www.appbrain.com/app/amaze-file-manager/com.amaze.filemanager)
[](https://github.com/TeamAmaze/AmazeFileManager/releases)
[](https://apt.izzysoft.de/fdroid/index/apk/com.amaze.filemanager)  
[](https://t.me/AmazeFileManager)
[](http://forum.xda-developers.com/android/apps-games/app-amaze-file-managermaterial-theme-t2937314)  
[](https://liberapay.com/Team-Amaze/donate)  

# <a href="https://teamamaze.xyz">Amaze File Manager</a>

Simple and attractive Material Design file manager for Android

Overview
---

<img src="icon.png" align="right" width="40%" height="100%"></img>

<div style="display:flex;">
    
- Open Source, light and smooth
- Based on Material Design guidelines
- Basic features like cut, copy, delete, compress, extract etc. easily accessible
- Work on multiple tabs at same time
- Multiple themes with cool icons
- Navigation drawer for quick navigation
- App Manager to open, backup, or directly uninstall any app
- Quickly access history, access bookmarks or search for any file
- Root explorer for advanced users
- AES Encryption and Decryption of files for security (Jellybean v4.3+)
- Cloud services support (Jellybean v4.3+ / requires additional plug-in)
- Inbuilt Database Reader, Zip/Rar Reader, Apk Reader, Text Reader
- No ads or In-app purchases
- lots more...

</div>

Downloads
---

[<img alt="Get it on Google Play" height="80" src="https://play.google.com/intl/en_us/badges/images/generic/en_badge_web_generic.png">](https://play.google.com/store/apps/details?id=com.amaze.filemanager)
[<img alt="Get it on F-Droid" height="80" src="https://fdroid.gitlab.io/artwork/badge/get-it-on.png">](https://f-droid.org/packages/com.amaze.filemanager/)
[<img alt="Get it on IzzyOnDroid" height="80" src="https://gitlab.com/IzzyOnDroid/repo/-/raw/master/assets/IzzyOnDroid.png">](https://apt.izzysoft.de/fdroid/index/apk/com.amaze.filemanager)
[<img alt="Get it on GitHub" height="80" src="https://i.ibb.co/q0mdc4Z/get-it-on-github.png">](https://github.com/TeamAmaze/AmazeFileManager/releases/latest)
[<img alt="Get it on AFH" height="50px" src="https://www.androidfilehost.com/images/afh.png">](https://www.androidfilehost.com/?w=files&flid=73967)

Contribute
---
You can contribute via one of the following ways:
- Help us with the translations of either [Amaze File Manager](https://app.transifex.com/amaze/amaze-file-manager) or [Amaze Utilities](https://crowdin.com/project/amaze-file-utilities)
- [Contribute](https://github.com/TeamAmaze/AmazeFileManager/blob/release/4.0/CONTRIBUTING.md) directly to the code, help us in fixing the bugs / implement new features.

_If we feel your contribution is a significant help to us, we'll award you a bounty with any of your preferred mode of payment._

Support
---
<a href="https://opencollective.com/TeamAmaze"><img width="20%" alt="OpenCollective" src="opencollective.svg" ></a>
<a href="https://www.paypal.me/vishalnehra"><img width="20%" src="paypal.svg" alt="PayPal"></a>
<a href="https://liberapay.com/Team-Amaze/donate"><img src="https://upload.wikimedia.org/wikipedia/commons/2/27/Liberapay_logo_v2_white-on-yellow.svg" alt="Liberapay" width="80px" ></a>  
Or buy the [Cloud Plugin](https://play.google.com/store/apps/details?id=com.filemanager.amazecloud) supports Google Drive™, Dropbox, OneDrive and Box accounts.  
Try our app - [Amaze File Utilities](https://play.google.com/store/apps/details?id=com.amaze.fileutilities) ([Fdroid](https://f-droid.org/en/packages/com.amaze.fileutilities/))
1. List videos / images / music documents in your device in a interactive UI where you're able to group / sort and quickly jump to any headers.
2. Open videos / images / music / documents (pdf / docx / epub) with inbuilt player.
3. Share / delete / cast on your tv
4. Analyse internal storage for junk files, duplicate files, large videos / old downloads / screenshots or recordings.
5. Analyse and group images between memes, low light / blurry / selfies / group pics.
7. Transfer files directly between two mobile devices on same wifi network using high speed peer to peer network
8. Gesture support in image / video player, play in background, picture in picture mode, download subtitles within the player.

Warning
---

Basic r/w operations might not work on external memory on Kitkat devices. Don't use cut/paste from or to external SD Card. You might lose your files.

***Under the license we are not responsible for damages.***

See our [Privacy Policy](https://github.com/TeamAmaze/AmazeFileManager/wiki/Privacy-Policy)

Vendors/Developers
----
The device vendors/ROM developers are free to include Amaze apk pre-installed in system. There is no fee required; *but you must comply with the license* (for more information read the [GNU GPL v3](https://www.gnu.org/licenses/gpl-3.0.en.html) or newer).

We strongly recommend using apk signed by us (either Play Store version or from AFH link above) so that users would be able to update directly from Play Store after distribution. Furthermore, a change in digital signature will break plug-ins.

### License: 

    Copyright (C) 2014-2018 Arpit Khurana <arpitkh96@gmail.com>
    Copyright (C) 2014-2024 Vishal Nehra <vishalmeham2@gmail.com>
    Copyright (C) 2017-2024 Emmanuel Messulam <emmanuelbendavid@gmail.com>
    Copyright (C) 2018-2024 Raymond Lai <airwave209gt at gmail.com>
    Copyright (C) 2019-2024 Vishnu Sanal T <t.v.s10123 at gmail.com>
    This file is part of Amaze File Manager.
    Amaze File Manager is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

---

### Overview (`file_operations/src/main/rust/README.md`)

# Rust File Operations Module

This directory contains the Rust implementation of file operations for the Amaze File Manager, which
was migrated from C/C++ to Rust for more modern, maintainable more safe code, with Rust's inherent
type-safety and memory-safety features.

Please refer to [RUST_MIGRATION.md](../doc/RUST_MIGRATION.md) for detailed information
about the migration process, key changes, and advantages of using Rust.

## Module Structure

The code is organized into separate modules for better maintainability and extensibility:

### `lib.rs` - Main Library File
- **Purpose**: Organizes and re-exports functionality from various modules
- **Content**: Module declarations and re-exports for easy access
- **Note**: This is the entry point for the Rust library

### `rootoperations.rs` - Root Operations
- **Purpose**: Contains root-specific file operations (migrated from C++)
- **Functions**:
  - `Java_com_amaze_filemanager_fileoperations_filesystem_root_NativeOperations_isDirectory` - JNI function for directory checking
  - `check_is_directory` - Helper function to check if a path is a directory
  - `check_path_exists` - Helper function to check if a path exists
  - `check_is_file` - Helper function to check if a path is a file
  - `get_file_size` - Helper function to get file size

## Usage

### From Kotlin/Java
The JNI functions are automatically exported and can be called from Kotlin:

```kotlin
// In NativeOperations.kt
@JvmStatic
external fun isDirectory(path: String?): Boolean

// Usage
val isDir = NativeOperations.isDirectory("/some/path")
```

### From Rust (Internal)
Functions can be called directly within the Rust codebase:

```rust
use crate::rootoperations::check_is_directory;

let is_dir = check_is_directory("/some/path")?;
```

### Through Re-exports
Functions can be accessed through the main library:

```rust
use crate::check_is_directory;

let is_dir = check_is_directory("/some/path")?;
```

## Adding New Functionality

### 1. Create a New Module
Create a new `.rs` file (e.g., `network_ops.rs`):

```rust
// network_ops.rs
pub fn download_file(url: &str, destination: &str) -> Result<(), Box<dyn std::error::Error>> {
    // Implementation
    Ok(())
}
```

### 2. Add Module Declaration
In `lib.rs`, add the module declaration:

```rust
pub mod network_ops;
```

### 3. Re-export Functions (Optional)
In `lib.rs`, add re-exports for easy access:

```rust
pub use network_ops::{
    download_file,
    upload_file,
};
```

### 4. Add JNI Functions (If Needed)
If you need to call the function from Kotlin:

```rust
// In network_ops.rs
#[no_mangle]
pub extern "system" fn Java_com_amaze_filemanager_fileoperations_filesystem_root_NativeOperations_downloadFile(
    env: JNIEnv,
    _class: JClass,
    url: JString,
    destination: JString,
) -> jboolean {
    // Convert JString to Rust String
    let url_str: String = env.get_string(url).unwrap().into();
    let dest_str: String = env.get_string(destination).unwrap().into();
    
    // Call the actual function
    match download_file(&url_str, &dest_str) {
        Ok(_) => 1, // true
        Err(_) => 0, // false
    }
}
```

Then add the corresponding method in `NativeOperations.kt`:

```kotlin
@JvmStatic
external fun downloadFile(url: String?, destination: String?): Boolean
```

## Testing

Each module includes its own tests. Run tests with:

```bash
cd file_operations
cargo test
```

To test a specific module:

```bash
cargo test rootoperations::tests
```

## Best Practices

1. **Separation of Concerns**: Keep related functions in the same module
2. **Error Handling**: Use `Result<T, E>` for functions that can fail
3. **Documentation**: Add doc comments to all public functions
4. **Testing**: Include unit tests for all functions
5. **JNI Safety**: Always handle JNI string conversion errors
6. **Logging**: Use the `log` crate for debugging information

## Example: Complete Function Implementation

```
/* Detailed source-code truncated for AI context efficiency. */
```

This structure makes the codebase highly maintainable and easy to extend with new functionality while keeping everything organized and well-tested.

---

### File Operations Doc RUST MIGRATION (`file_operations/doc/RUST_MIGRATION.md`)

# C++ to Rust Migration Guide

This document outlines the migration from C++ to Rust in the `file_operations` module using Mozilla's Rust Android Gradle plugin.

## Overview

The migration replaces the C++ implementation in `src/main/c/rootoperations.c` with a Rust implementation while maintaining the same JNI interface for seamless integration with the existing Kotlin code.

## What Was Migrated

### Original C++ Code
- **File**: `src/main/c/rootoperations.c`
- **Function**: `Java_com_amaze_filemanager_fileoperations_filesystem_root_NativeOperations_isDirectory`
- **Purpose**: Checks if a given path is a directory using the `stat()` system call
- **Build System**: CMake

### New Rust Code
- **File**: `src/lib.rs`
- **Function**: Same JNI function signature
- **Purpose**: Identical functionality using Rust's `std::fs::metadata()`
- **Build System**: Cargo with Mozilla's Rust Android Gradle plugin

## Prerequisites

1. **Rust Installation**: Install Rust from https://rustup.rs/
2. **Android NDK**: Install via Android Studio → Tools → SDK Manager → SDK Tools → NDK
3. **Environment Variables**: Set `ANDROID_HOME` or `ANDROID_NDK_ROOT`
4. **Rust-compatible IDE**: Before Android Studio gets first-class Rust support, consider using [Visual Studio Code](https://code.visualstudio.com) with Rust extensions for coding.

## Setup Instructions

### 1. Automated Setup (Recommended)

The project includes an automated setup script that detects your system configuration and generates the correct configuration files:

```bash
cd file_operations
./setup_rust_android.sh
```

This script will:
- **Auto-detect your operating system** (macOS, Linux, Windows)
- **Find your Android SDK** path (from `ANDROID_HOME`, `ANDROID_SDK_ROOT`, or common locations)
- **Detect the latest NDK version** installed
- **Extract API level** from your `build.gradle`
- **Install necessary Rust targets** for Android
- **Generate `.cargo/config.toml`** with correct linker paths

### 2. Manual Setup (If Needed)

If the automated setup doesn't work, you can manually configure:

1. **Install Android Rust targets:**
   ```bash
   rustup target add aarch64-linux-android
   rustup target add armv7-linux-androideabi
   rustup target add i686-linux-android
   rustup target add x86_64-linux-android
   ```

2. **Create `.cargo/config.toml`** based on your system:
   - Copy `.cargo/config.toml.template` to `.cargo/config.toml`
   - Replace placeholders with your actual paths:
     - `{{NDK_PATH}}`: Path to your NDK toolchain binaries
     - `{{API_LEVEL}}`: Your minimum API level (e.g., 21)
     - `{{EXE_SUFFIX}}`: `.exe` for Windows, empty for Unix systems

### 3. System Requirements

**Android SDK/NDK:**
- Android SDK installed (via Android Studio or command-line tools)
- NDK installed (via SDK Manager)
- Set `ANDROID_HOME` environment variable

**Supported Platforms:**
- macOS (`darwin-x86_64`)
- Linux (`linux-x86_64`)
- Windows (`windows-x86_64`)

### 4. Build Configuration

The `build.gradle` file now includes:
- Mozilla's Rust Android Gradle plugin
- Cargo configuration for cross-compilation
- Automatic building of Rust code during Android build

## File Structure

```
file_operations/
├── src/
│   └── main/
│       └── rust/
│           ├── lib.rs                 # Main library file (module organizer)
│           └── rootoperations.rs      # Root operations functions
├── .cargo/
│   ├── config.toml           # Auto-generated Cargo configuration for Android
│   └── config.toml.template  # Template for generating config.toml
├── Cargo.toml                # Rust project configuration
├── setup_rust_android.sh     # Automated setup script
├── build.gradle              # Updated with Rust plugin
└── RUST_MIGRATION.md         # This file
```

## Key Changes

### 1. Build System
- **Before**: CMake with `externalNativeBuild`
- **After**: Cargo with Mozilla's Rust Android Gradle plugin

### 2. Dependencies
- **Added**: `jni`, `libc`, `android_logger`, `log` crates
- **Removed**: CMake build configuration

### 3. Function Implementation
- **Before**: C function using `stat()` system call
- **After**: Rust function using `std::fs::metadata()`

### 4. Error Handling
- **Before**: errno-based error handling
- **After**: Rust's `Result` type with proper error handling

### 5. Modular Structure
- **Before**: Single C file with all functions
- **After**: Organized module structure:
  - `lib.rs`: Main library file that organizes and re-exports modules
  - `rootoperations.rs`: Root-specific operations (migrated from C)

## Testing

The Rust implementation includes unit tests:
```bash
cd file_operations
cargo test
```

## Building

The Rust code is automatically built when you build the Android project:
```bash
./gradlew :file_operations:build
```

## Advantages of the Migration

1. **Memory Safety**: Rust prevents memory leaks and buffer overflows
2. **Better Error Handling**: Rust's type system catches errors at compile time
3. **Cross-Platform**: Easier to port to other platforms
4. **Modern Tooling**: Cargo package manager and ecosystem
5. **Performance**: Comparable performance to C++ with better safety

## Troubleshooting

### Configuration Issues
First, try re-running the automated setup script:
```bash
cd file_operations
./setup_rust_android.sh
```

This will re-detect your system configuration and regenerate `.cargo/config.toml`.

### NDK Path Issues
If the automated setup fails to find your NDK, ensure your Android SDK is properly configured:
```bash
export ANDROID_HOME=/path/to/android/sdk
# The script will automatically find the NDK in $ANDROID_HOME/ndk/[version]
```

### Linker Not Found
If you see linker errors, verify your NDK installation:
1. Check that NDK is installed via Android Studio → SDK Manager → SDK Tools → NDK
2. The setup script will automatically use the latest NDK version found
3. If needed, manually verify the generated `.cargo/config.toml` paths exist

### Build Errors
Clean and rebuild:
```bash
cd file_operations
cargo clean
cd ..
./gradlew clean
./gradlew :file_operations:build
```

### Cross-Platform Issues
The setup script supports:
- **macOS**: Automatically detects `darwin-x86_64` platform
- **Linux**: Automatically detects `linux-x86_64` platform  
- **Windows**: Automatically detects `windows-x86_64` platform and adds `.exe` suffix

If you encounter platform-specific issues, check the generated linker paths in `.cargo/config.toml`.

## Extending the Codebase

The modular structure makes it easy to add new functionality:

### Adding a New Module

1. **Create a new `.rs` file** in `src/main/rust/` (e.g., `network_ops.rs`)
2. **Add the module declaration** in `lib.rs`:
   ```rust
   pub mod network_ops;
   ```
3. **Re-export functions** in `lib.rs` for easy access:
   ```rust
   pub use network_ops::{
       download_file,
       upload_file,
   };
   ```

### Adding JNI Functions

To add new JNI functions that can be called from Kotlin:

1. **Add the function** in the appropriate module:
   ```rust
   #[no_mangle]
   pub extern "system" fn Java_com_amaze_filemanager_fileoperations_filesystem_root_NativeOperations_newFunction(
       env: JNIEnv,
       _class: JClass,
       param: JString,
   ) -> jboolean {
       // Implementation
   }
   ```

2. **Add the corresponding method** in `NativeOperations.kt`:
   ```kotlin
   @JvmStatic
   external fun newFunction(param: String?): Boolean
   ```

### Example: Adding Compression Operations

```rust
// In src/main/rust/compression_ops.rs
pub mod compression_ops {
    use jni::objects::{JClass, JString};
    use jni::JNIEnv;
    use jni::sys::jboolean;
    
    #[no_mangle]
    pub extern "system" fn Java_com_amaze_filemanager_fileoperations_filesystem_root_NativeOperations_compressFile(
        env: JNIEnv,
        _class: JClass,
        source: JString,
        destination: JString,
    ) -> jboolean {
        // Implementation
    }
}
```

## Future Enhancements

1. **Add More Functions**: Migrate additional C++ functions to Rust
2. **Async Operations**: Use Rust's async/await for non-blocking operations
3. **Better Logging**: Enhanced logging with structured logs
4. **Performance Monitoring**: Add metrics collection
5. **Cross-Platform Support**: Extend to other platforms (iOS, Windows, etc.)
6. **Error Types**: Create custom error types for better error handling
7. **Benchmarking**: Add performance benchmarks for critical operations

## Resources

- [Mozilla Rust Android Gradle Plugin](https://github.com/mozilla/rust-android-gradle)
- [JNI for Rust](https://docs.rs/jni/latest/jni/)
- [Android NDK Documentation](https://developer.android.com/ndk)
- [Rust Cross-Compilation](https://rust-lang.github.io/rustup/cross-compilation.html)

## Support

For questions or issues with the migration, please refer to:
- [Mozilla Rust Android Gradle Issues](https://github.com/mozilla/rust-android-gradle/issues)
- [Rust Android Development](https://mozilla.github.io/firefox-browser-architecture/experiments/2017-09-21-rust-on-android.html)

---

--- METRICS ---
- Files Extracted: 3
- Estimated Token Budget: ~4947 tokens
- Canonical Reference: https://codewiki.google/github.com/TeamAmaze/AmazeFileManager
