# 🖥️ NEXIUM DESKTOP MODE

**Transform your web apps into native desktop applications!**

---

## 🌟 What is Desktop Mode?

NEXIUM Desktop Mode allows you to run your web applications as **native desktop applications** on Windows, macOS, and Linux.

**No Electron. No heavy bundling. Just pure Python + pywebview.**

```python
from nexium import Nexium
from nexium.desktop import run_as_desktop

app = Nexium()

@app.get("/")
async def home():
    return {"message": "Hello Desktop!"}

if __name__ == "__main__":
    run_as_desktop(app, title="My App")
```

**That's it!** Your web app is now a desktop app! 🎉

---

## 🚀 Installation

### Basic Installation
```bash
pip install nexium
```

### With Desktop Support
```bash
pip install nexium[desktop]
```

This installs `pywebview` for native window creation.

---

## 💪 Why Desktop Mode?

### ✅ Advantages

| Feature | Description |
|---------|-------------|
| **Native Windows** | Real native windows (not browser) |
| **Cross-Platform** | Windows, macOS, Linux |
| **Lightweight** | No Electron bloat (~200MB saved) |
| **Full Web APIs** | Use all your favorite web tech |
| **Desktop APIs** | File dialogs, notifications, system tray |
| **Easy Deployment** | Bundle with PyInstaller |

### ❌ vs Electron

| Feature | Electron | NEXIUM Desktop |
|---------|----------|----------------|
| **Bundle Size** | ~200MB | **~20MB** (10x smaller!) |
| **RAM Usage** | ~100MB+ | **~30MB** (3x less!) |
| **Startup Time** | Slow | **Fast** |
| **Language** | JavaScript | **Python** |
| **Learning Curve** | High | **Low** |

---

## 📚 Quick Start

### 1. Basic Desktop App

```python
from nexium import Nexium, DesktopApp

app = Nexium()

@app.get("/")
async def home():
    return {"message": "Hello Desktop World!"}

if __name__ == "__main__":
    desktop = DesktopApp(app, title="My App")
    desktop.run()
```

### 2. With Configuration

```python
from nexium import Nexium, DesktopApp

app = Nexium()

desktop = DesktopApp(
    app,
    title="My Awesome App",
    width=1200,
    height=800,
    resizable=True,
    fullscreen=False,
    min_size=(600, 400),
    background_color="#FFFFFF",
    host="127.0.0.1",
    port=8000,
)

desktop.run(
    debug=True,           # Show dev tools
    icon="icon.png",      # Window icon
    on_top=False,         # Keep on top
    confirm_close=False,  # Confirm before close
)
```

### 3. Convenience Function

```python
from nexium import Nexium
from nexium.desktop import run_as_desktop

app = Nexium()

# One-liner!
run_as_desktop(app, title="My App", width=1000, height=700)
```

---

## 🎨 Features

### 1. Native Window Control

```python
from nexium import Nexium, DesktopAPI

app = Nexium()
desktop_api = DesktopAPI()

@app.post("/window/minimize")
async def minimize():
    desktop_api.minimize()
    return {"status": "minimized"}

@app.post("/window/maximize")
async def maximize():
    desktop_api.maximize()
    return {"status": "maximized"}

@app.post("/window/fullscreen")
async def fullscreen():
    desktop_api.toggle_fullscreen()
    return {"status": "toggled"}
```

### 2. File Dialogs

```python
@app.get("/open-file")
async def open_file():
    desktop_api = DesktopAPI()
    
    file_path = desktop_api.show_dialog(
        dialog_type="open",
        file_types=("Text Files (*.txt)", "All Files (*.*)")
    )
    
    if file_path:
        return {"file": file_path}
    return {"message": "No file selected"}

@app.get("/save-file")
async def save_file():
    desktop_api = DesktopAPI()
    
    file_path = desktop_api.show_dialog(
        dialog_type="save",
        save_filename="document.txt",
        file_types=("Text Files (*.txt)", "All Files (*.*)")
    )
    
    return {"file": file_path}

@app.get("/select-folder")
async def select_folder():
    desktop_api = DesktopAPI()
    
    folder_path = desktop_api.show_dialog(dialog_type="folder")
    return {"folder": folder_path}
```

### 3. JavaScript Execution

```python
@app.get("/alert")
async def show_alert():
    desktop_api = DesktopAPI()
    
    desktop_api.evaluate_js("alert('Hello from Python!')")
    return {"status": "shown"}

@app.get("/get-title")
async def get_title():
    desktop_api = DesktopAPI()
    
    title = desktop_api.evaluate_js("document.title")
    return {"title": title}
```

### 4. Window Management

```python
from nexium import DesktopAPI

desktop_api = DesktopAPI()

# Resize window
desktop_api.resize(800, 600)

# Move window
desktop_api.move(100, 100)

# Set title
desktop_api.set_title("New Title")

# Load URL
desktop_api.load_url("https://example.com")

# Load HTML
desktop_api.load_html("<h1>Hello!</h1>")

# Get DOM elements
elements = desktop_api.get_elements(".my-class")

# Close window
desktop_api.destroy()
```

---

## 🎯 Use Cases

### 1. **Internal Tools**
- Database management GUIs
- Admin dashboards
- Monitoring tools
- Configuration managers

### 2. **Productivity Apps**
- Todo lists
- Note-taking apps
- Project managers
- Time trackers

### 3. **Creative Tools**
- Image editors
- Video processors
- Audio tools
- Design apps

### 4. **Business Apps**
- CRM systems
- Inventory management
- POS systems
- Accounting software

---

## 📊 Complete Example: Todo App

See `examples/desktop_todo_app.py` for a complete, beautiful desktop todo application!

**Features:**
- ✅ Modern, gradient UI
- ✅ CRUD operations
- ✅ Statistics dashboard
- ✅ Keyboard shortcuts
- ✅ Real-time updates

**Run it:**
```bash
python examples/desktop_todo_app.py
```

---

## 🔧 Advanced Usage

### Conditional Desktop Mode

```python
from nexium import Nexium
from nexium.desktop import DesktopApp, DesktopAPI
import sys

app = Nexium()
desktop_api = DesktopAPI()

@app.get("/")
async def home():
    mode = "desktop" if desktop_api.available else "web"
    return {"mode": mode, "message": f"Running in {mode} mode"}

if __name__ == "__main__":
    # Check command line arguments
    if "--desktop" in sys.argv:
        # Run as desktop
        DesktopApp(app).run()
    else:
        # Run as web
        app.run()
```

### Custom Window Class

```python
from nexium import Nexium
from nexium.desktop import DesktopApp

class MyDesktopApp(DesktopApp):
    def __init__(self, app):
        super().__init__(
            app,
            title="My Custom App",
            width=1000,
            height=700
        )
    
    def run(self):
        print("Starting my custom desktop app!")
        super().run(debug=True)

app = Nexium()
MyDesktopApp(app).run()
```

---

## 📦 Deployment

### PyInstaller (Recommended)

Create `build.spec`:
```python
# -*- mode: python ; coding: utf-8 -*-

block_cipher = None

a = Analysis(
    ['main.py'],
    pathex=[],
    binaries=[],
    datas=[],
    hiddenimports=['nexium', 'nexium.desktop', 'webview'],
    hookspath=[],
    hooksconfig={},
    runtime_hooks=[],
    excludes=[],
    win_no_prefer_redirects=False,
    win_private_assemblies=False,
    cipher=block_cipher,
    noarchive=False,
)

pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)

exe = EXE(
    pyz,
    a.scripts,
    a.binaries,
    a.zipfiles,
    a.datas,
    [],
    name='MyApp',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    upx_exclude=[],
    runtime_tmpdir=None,
    console=False,
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
    icon='icon.ico'
)
```

Build:
```bash
pyinstaller build.spec
```

Your app is in `dist/MyApp.exe`!

---

## 🎨 UI Frameworks Compatibility

NEXIUM Desktop Mode works with **any** web UI framework:

### React
```python
# Serve React build folder
from nexium import Nexium
from starlette.staticfiles import StaticFiles

app = Nexium()
app.mount("/", StaticFiles(directory="build", html=True))

DesktopApp(app).run()
```

### Vue
```python
app.mount("/", StaticFiles(directory="dist", html=True))
```

### Svelte
```python
app.mount("/", StaticFiles(directory="public", html=True))
```

### Plain HTML/CSS/JS
```python
from nexium import HTMLResponse

@app.get("/")
async def home():
    return HTMLResponse("<h1>Hello!</h1>")
```

---

## 🔒 Security

### Best Practices

1. **Use localhost only**
   ```python
   DesktopApp(app, host="127.0.0.1")  # ✅ Good
   DesktopApp(app, host="0.0.0.0")    # ❌ Bad (exposed to network)
   ```

2. **Validate user input**
   ```python
   from nexium import validate, Field
   
   @app.post("/data")
   @validate
   async def save_data(text: str = Field(max_length=1000)):
       # Input is validated
       pass
   ```

3. **Use random ports (optional)**
   ```python
   import random
   port = random.randint(8000, 9000)
   DesktopApp(app, port=port).run()
   ```

---

## 🆚 Comparison

### vs Electron

| Feature | Electron | NEXIUM Desktop |
|---------|----------|----------------|
| **Size** | ~200MB | ~20MB |
| **RAM** | ~100MB | ~30MB |
| **Language** | JS/TS | Python |
| **Backend** | Node.js | NEXIUM/Python |
| **Learning** | Complex | Simple |

### vs Tkinter

| Feature | Tkinter | NEXIUM Desktop |
|---------|---------|----------------|
| **UI** | Old-school | Modern web UI |
| **Styling** | Limited | Full CSS/JS |
| **Responsive** | Manual | Automatic |
| **Frameworks** | None | React/Vue/etc |

### vs Qt (PyQt/PySide)

| Feature | Qt | NEXIUM Desktop |
|---------|---------|----------------|
| **License** | GPL/Commercial | MIT |
| **Size** | ~50MB | ~20MB |
| **UI Design** | Qt Designer | HTML/CSS |
| **Web Tech** | Limited | Full support |

---

## 🐛 Troubleshooting

### pywebview not installing?

**Windows:**
```bash
pip install pywebview[cef]
```

**macOS:**
```bash
pip install pywebview[qt]
```

**Linux:**
```bash
sudo apt-get install python3-pyqt5 python3-pyqt5.qtwebengine
pip install pywebview
```

### Window not showing?

Check that you're calling `desktop.run()` not `app.run()`:
```python
# ❌ Wrong
app.run()

# ✅ Correct
DesktopApp(app).run()
```

### Port already in use?

Use a different port:
```python
DesktopApp(app, port=8001).run()
```

---

## 📚 Resources

- **Examples:** `/nexium/examples/`
- **API Reference:** `/nexium/src/nexium/desktop.py`
- **pywebview Docs:** https://pywebview.flowrl.com/

---

## 🎉 Conclusion

NEXIUM Desktop Mode gives you the **best of both worlds**:

- ✅ Native desktop app experience
- ✅ Modern web development workflow
- ✅ Lightweight and fast
- ✅ Cross-platform by default
- ✅ Easy to deploy

**Stop fighting with Electron. Start building with NEXIUM Desktop!** 🚀

---

<div align="center">

**Made with ❤️ by [Juste Elysée MALANDILA](https://linkedin.com/in/justelm/)**

**NEXIUM** - *The Next-Gen Python Web Framework* 🌟

</div>
