Pull Request: Add native Windows (AmpleWin) and Linux (AmpleLinux) ports (#46)

* Initialize and finalize AmpleWin: Full-featured Windows Port with Adaptive UI, optimized engine, and internationalized documentation

* Update media args

* AmpleWin: Finalized Windows Port with Adaptive UI, Optimized Engine, VGM Recording, and Shared Directory Support

* Fix NameError: subprocess not defined in main.py

* UI: Remove redundant MAME path label from Paths tab

* UI: Implement smart slot validation for disabled options and click-to-browse Shared Directory

* feat(win): editable console, launch logic fixes & doc updates

* Fix path quoting issues, add file selectors for A/V, and normalize shared dir path

* feat: sync with Ample v0.285 resources, update to MAME 0.285, and add ROM search filter

* v0.285: Expand ROM library, implement download failover, and advanced SCSI sub-slot emulation

* Adjust ROM download priority: prefer callapple.org for stability, mdk.cab as fallback

* Sync roms.plist with upstream/master

* docs(agent): record upstream synchronization session

* refactor: rename mame_bin to mame directory

* chore: update .gitignore for mame directory rename

* fix(main): update download and detection paths to 'mame'

* fix(main): robust path resolution for pyinstaller builds

* docs(readme): add build_exe.bat to project structure

* fix(build): remove creation of empty mame directory to avoid confusion

* feat(build): auto-generate application icon from Assets.xcassets

* Add AmpleLinux - Linux Port of Ample (Apple II/Mac emulator frontend)

- Ported from AmpleWin with ~20 Linux-specific adaptations
- Replaced winreg with gsettings/KDE dark mode detection
- Replaced os.startfile with xdg-open
- Removed MAME auto-download (users install via package manager)
- Added system-wide MAME detection (PATH, /usr/bin, /usr/games)
- Removed all .exe suffixes from binary references
- Created AmpleLinux.sh launcher script
- Dual-language READMEs (English + Traditional Chinese)

* Fix: use python3 -m pip instead of pip3/pip for modern Linux compatibility

* feat(linux): Finalize AmpleLinux port documentation and build scripts

* Fix formatting for Windows and Linux user notes

Updated user guidance for Windows and Linux users.

* feat(linux): interactive .desktop install, runtime icon loading, updated docs

* docs(linux): clarify mame_downloader.py usage status

* docs: add PR draft template

* fix(linux): add binutils dependency check for pyinstaller

* Update: mame 0.286

---------

Co-authored-by: User <user@example.com>
This commit is contained in:
anomixerandUser authored and GitHub committed 2026-03-07 21:57:26 -05:00
1 parent 4a44e2230f
commit fdd02b9d5b
31 files changed
+7633 -1

No files matched your search

+24
View File
@@ -9,3 +9,27 @@ embedded/SDL3-*
build
embedded/mame-data.tgz
__pycache__
# Windows Port
AmpleWin/mame/
AmpleWin/dist/
AmpleWin/build/
AmpleWin/*.spec
nvram/
cfg/
diff/
inp/
comments/
sta/
*.ini
*.ico
# Linux Port
AmpleLinux/.venv
AmpleLinux/.build_venv
AmpleLinux/icons/
AmpleLinux/Ample.spec
AmpleLinux/mame/
!AmpleLinux/mame/.gitkeep
+144
View File
@@ -0,0 +1,144 @@
# Agent Task Audit Log - Ample Linux Port
## 📅 Session: 2026-03-02 (Session 3)
### 🎯 Objective: Upstream Version Tracking & Documentation Maintenance
Focused on updating the Linux port documentation to track MAME 0.286 and simplifying maintainability.
### ✅ Key Achievements:
1. **Documentation Refactoring**:
* Renamed version-specific screenshot files (e.g. `screenshot-v0.28x.png` to `screenshot.png`).
* Updated `README.md` and `README_tw.md` to use generic "latest version" terminology to prevent the need for manual text updates upon future Ample/MAME releases.
### 🚀 Current Project Status
The Linux Port documentation is updated for MAME 0.286 and future-proofed against minor version increments.
---
## 📅 Session: 2026-02-17 (Session 2)
### 🎯 Objective: Real-World Testing & Deployment Fix
Deployed the Linux Port to an actual Linux machine for testing. Identified and fixed a critical dependency installation issue.
### ✅ Key Achievements:
1. **Launcher Script Fix (`AmpleLinux.sh`)**:
* **Bug**: Original script used `pip3` / `pip` commands directly, which don't exist on many modern Linux distros (Debian 12+, Ubuntu 23+, Fedora 38+ enforce PEP 668).
* **Fix v1**: Changed to `python3 -m pip` (the universally reliable pip invocation).
* **Fix v2**: Added automatic `--break-system-packages` fallback for PEP 668-compliant systems.
* **Error Messages**: Added distro-specific guidance (apt/dnf/pacman) and venv instructions in error output.
2. **Git Workflow**:
* Created `linux` branch from `master`.
* Pushed to `origin/linux` for cross-machine testing.
### 🔍 Testing Observations (Real Linux Machine):
* `pip3` command was not in PATH → first fallback triggered.
* `python3 -m pip` also failed (PEP 668 system Python restriction) → second fallback triggered with `--break-system-packages`.
* **Conclusion**: Many modern Linux distros require either system packages (`sudo apt install python3-pyside6 python3-requests`) or a venv approach. The launcher script now documents both paths clearly.
### ⚠️ Known Issue - Pending Resolution:
* Systems without any pip module need manual package installation first. The script provides clear guidance but cannot auto-resolve this without `sudo`.
* **Recommended solutions** (in priority order):
1. System packages: `sudo apt install python3-pyside6 python3-requests`
2. Install pip: `sudo apt install python3-pip`, then re-run script
3. Use venv: `python3 -m venv venv && source venv/bin/activate && pip install -r requirements.txt && python3 main.py`
### 🚀 Current Project Status
Codebase is ported and pushed to `linux` branch. Launcher script has been hardened for modern Linux distros. Awaiting successful end-to-end test with dependencies installed.
---
## 📅 Session: 2026-02-16 (Session 1)
### 🎯 Objective: Linux Port Creation
Ported AmpleWin (Windows) to Linux, following the original author's suggestion (ksherlock/ample#45) that Linux support would be easy to add.
### ✅ Key Achievements:
1. **Codebase Porting (from AmpleWin)**:
* **Zero-Modification Files**: `data_manager.py`, `rom_manager.py`, `mame_launcher.py`, `requirements.txt` — copied directly, no changes needed.
* **Simplified `mame_downloader.py`**: Removed `MameDownloadWorker` entirely (Linux users install MAME via their package manager). Kept `VgmModDownloadWorker` with Linux adaptations (7z via PATH, no `.exe` suffix, helpful `p7zip` install instructions).
* **`main.py` (~20 changes)**: Comprehensive platform adaptation:
- Replaced `winreg` theme detection with `gsettings` (GNOME 42+ `color-scheme`) and KDE (`kdeglobals`) dark mode detection.
- Replaced all `os.startfile()` calls with `xdg-open` via a helper function `_xdg_open()`.
- Removed all `.exe` suffixes from MAME binary references (`mame.exe` → `mame`, `mame-vgm.exe` → `mame-vgm`).
- Enhanced `check_for_mame()` to search system paths (`/usr/bin/mame`, `/usr/games/mame`, `/usr/local/bin/mame`) and use `which mame`.
- Replaced `Download MAME` button with package manager guidance text.
- Updated `shlex.split()` from `posix=False` (Windows) to `posix=True` (Linux).
- Updated file browser filter from `*.exe` to `All Files (*)`.
- Changed window title and help URL.
2. **Launcher Script**:
* Created `AmpleLinux.sh` as equivalent of `AmpleWin.bat`.
* Includes Python 3 detection, pip dependency installation, and helpful error messages with distro-specific commands.
3. **Documentation**:
* Created dual-language READMEs (`README.md` English, `README_tw.md` Traditional Chinese).
* Includes installation guide for all major distros (Ubuntu, Fedora, Arch, Flatpak).
* Troubleshooting section for PySide6, MAME detection, and theme issues.
### 🔍 Design Decisions:
1. **Separate Directory (not shared codebase)**: Chose to create `AmpleLinux/` as a separate directory rather than refactoring `AmpleWin/` into a shared codebase. This maintains the project convention where each platform gets its own additive subdirectory, minimizing risk to the stable Windows port.
2. **No MAME Auto-Download**: Following the original author's guidance ("let the user download it themselves"), Linux users install MAME via their system package manager. This is the Linux cultural norm and avoids complex binary distribution issues.
3. **GNOME + KDE Theme Detection**: Implemented multi-strategy dark mode detection covering GNOME 42+ `color-scheme`, older GNOME `gtk-theme`, and KDE `kdeglobals`, with Qt palette as ultimate fallback.
### 🚀 Current Project Status
The Linux Port is functionally complete. All Windows-specific code has been adapted, and the application should work on major Linux distributions with GNOME or KDE desktops.
---
## Handover Notes for Future Agents
### 1. Platform Differences from AmpleWin
* **No `winreg`**: Theme detection uses `gsettings` and KDE config file parsing.
* **No `os.startfile()`**: Uses `xdg-open` via the `_xdg_open()` helper function.
* **No `.exe` suffixes**: All binary references use bare names (`mame`, `mame-vgm`).
* **No MAME auto-download**: Users install via package manager. Settings dialog shows guidance.
* **`shlex.split(posix=True)`**: Linux uses POSIX-mode shell parsing (no special Windows path handling).
* **MAME detection**: Checks `PATH` via `which`, plus standard Linux paths (`/usr/bin`, `/usr/games`, `/usr/local/bin`).
### 2. Deployment (CRITICAL)
* **PEP 668 Era**: Modern Linux distros (Debian 12+, Ubuntu 23.04+, Fedora 38+) block global pip installs. The launcher script handles this with `--break-system-packages` fallback.
* **Recommended Install Methods** (in priority order):
1. System packages: `sudo apt install python3-pyside6 python3-requests mame`
2. venv: `python3 -m venv venv && source venv/bin/activate && pip install -r requirements.txt`
3. pip with override: `python3 -m pip install -r requirements.txt --break-system-packages`
* **Never use `pip3` or `pip` directly** in scripts — always use `python3 -m pip` for reliability.
### 3. Known Mantras (inherited from AmpleWin)
* **Visual Parity is King**: Every margin, font size, and color was cross-referenced with macOS.
* **Authorship**: This Linux Port is based on the AmpleWin collaboration between **anomixer** and **Antigravity**.
---
## 📅 Session: 2026-02-17 (Session 2)
### 🎯 Objective: First-Run Experience, Build System & Polish
### ✅ Key Changes:
1. **Launcher Architecture (`AmpleLinux.sh`)**:
* **Refactored to venv**: Switched from system-level `apt` dependencies to a strictly isolated `python3 -m venv` approach.
* **Automated Setup**: Script now auto-creates `.venv`, installs `python3-venv` (if missing), and pip installs `requirements.txt`.
* **Distro Agnostic**: Only depends on `python3-full` and `libxcb-cursor*` (apt) for the base interpreter; all libraries (PySide6) are pulled via pip.
* **ALSA Fix**: Added auto-detection of `/proc/asound` and `usermod -a -G audio` fix for permission issues.
2. **User Experience Enhancements (`main.py`)**:
* **Ubuntu Snap Integration**: If MAME is missing on Ubuntu, offers `sudo snap install mame` with a non-blocking `QProgressDialog`.
* **Configuration Fix**: `ensure_mame_ini` now runs `mame -cc` inside `AmpleLinux/mame` to keep config portable.
* **Path Precision**: `update_command_line` now resolves absolute paths for `-inipath` and `-rompath` (e.g., `/home/user/...`).
* **BGFX Cleanup**: Removed Windows-only Direct3D options.
* **UI Polish**: "Generate VGM" now shows a "Feature not implemented" popup.
3. **Build System (New)**:
* **`make_icon.py`**: Created Linux-specific icon generator (produces standard PNG sizes: 16x16 to 512x512).
* **`build_elf.sh`**: Created PyInstaller build script that uses a temporary venv to bypass PEP 668 restrictions and produce a standalone ELF binary in `dist/`.
### 🔍 Technical Decisions:
* **PySide6 via pip**: Moved away from `python3-pyside2` (apt) because the codebase is written for PySide6. Using venv + pip ensures version consistency and avoids the "externally-managed-environment" error on modern distros.
* **MAME Snap**: For Ubuntu users, Snap is the most reliable way to get a recent MAME version without PPA complexity.
+113
View File
@@ -0,0 +1,113 @@
#!/bin/bash
echo "========================================"
echo " Ample - Linux Port Auto Launcher"
echo "========================================"
# --- First-Time Setup: Install system-level dependencies ---
if command -v apt &> /dev/null; then
# libxcb-cursor0 is required by Qt/PySide6 on X11
NEED_INSTALL=0
for pkg in python3-full libxcb-cursor0; do
if ! dpkg -s "$pkg" &> /dev/null 2>&1; then
NEED_INSTALL=1
break
fi
done
if [ $NEED_INSTALL -eq 1 ]; then
echo "[SETUP] Installing required system packages..."
echo " sudo apt install python3-full libxcb-cursor*"
sudo apt install -y python3-full libxcb-cursor*
if [ $? -ne 0 ]; then
echo "[WARN] Some packages may have failed to install. Continuing anyway..."
else
echo "[SETUP] System packages installed successfully."
fi
fi
fi
# --- ALSA Audio Permission Fix ---
if [ -d /proc/asound ]; then
if ! id -nG "$(whoami)" | grep -qw "audio"; then
echo "[SETUP] ALSA audio system detected. Adding user to 'audio' group..."
sudo usermod -a -G audio "$(whoami)"
if [ $? -eq 0 ]; then
echo "[SETUP] Added $(whoami) to 'audio' group. Please log out and back in for this to take effect."
else
echo "[WARN] Failed to add user to 'audio' group. Sound may not work properly."
fi
fi
fi
# Check for Python 3
if ! command -v python3 &> /dev/null; then
echo "[ERROR] Python 3 not found! Please install Python 3.9 or newer."
echo " Ubuntu/Debian: sudo apt install python3 python3-full"
echo " Fedora: sudo dnf install python3 python3-pip"
echo " Arch: sudo pacman -S python python-pip"
exit 1
fi
# Navigate to script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"
# --- Virtual Environment Setup ---
VENV_DIR=".venv"
# Ensure python3-venv is available
if ! python3 -m venv --help &> /dev/null; then
echo "[INFO] python3-venv is required but not installed."
if command -v apt &> /dev/null; then
PY_VER=$(python3 -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')")
echo "[INFO] Installing python3.${PY_VER}-venv ..."
sudo apt install -y "python3.${PY_VER}-venv" python3-full
else
echo "[ERROR] Please install python3-venv for your distro and try again."
exit 1
fi
fi
# Recreate if venv is broken
if [ -d "$VENV_DIR" ] && [ ! -f "$VENV_DIR/bin/activate" ]; then
echo "[WARN] Virtual environment is broken, recreating..."
rm -rf "$VENV_DIR"
fi
# Create venv if it doesn't exist
if [ ! -d "$VENV_DIR" ]; then
echo "[1/3] Creating virtual environment..."
python3 -m venv "$VENV_DIR"
else
echo "[1/3] Virtual environment found."
fi
# Activate venv
source "$VENV_DIR/bin/activate"
# Install/Update dependencies
echo "[2/3] Checking dependencies..."
pip install -r requirements.txt --quiet 2>/dev/null
if [ $? -ne 0 ]; then
echo "[WARN] pip install failed, retrying with upgrade..."
pip install --upgrade pip --quiet 2>/dev/null
pip install -r requirements.txt --quiet
if [ $? -ne 0 ]; then
echo "[ERROR] Failed to install requirements."
deactivate
exit 1
fi
fi
# Run the application
echo "[3/3] Launching Ample..."
python3 main.py
if [ $? -ne 0 ]; then
echo ""
echo "[INFO] Application exited with error."
read -p "Press Enter to continue..."
fi
deactivate
+124
View File
@@ -0,0 +1,124 @@
# AmpleLinux - Linux Port (Legacy Apple Emulator Frontend)
[English](README.md) | [繁體中文](README_tw.md)
This is a port of the macOS native [Ample](https://github.com/ksherlock/ample) project to the Linux platform, based on the [AmpleWin](../AmpleWin/) Windows Port.
![](screenshot.png)
> [!IMPORTANT]
> **Current Version Support**: Updated to stay in sync with the latest version of Ample (macOS) resources and also MAME latest binary.
## 🍎 Ample (macOS) vs. AmpleLinux (Linux) Comparison
| Feature | Ample (macOS Native) | AmpleLinux (Linux) | Notes |
| :--- | :--- | :--- | :--- |
| **Language** | Objective-C (Cocoa) | **Python 3.11 + PySide6 (Qt)** | Independent development, **zero changes to Mac source code** |
| **Installation** | .dmg Image / Homebrew | **Portable (+ .sh Auto-Config)** | One-click setup via `AmpleLinux.sh` |
| **MAME Integration** | Built-in Custom Core | **System-installed MAME** | Uses `mame` from your package manager (apt, dnf, pacman, etc.) |
| **UI** | Native macOS Components | **1:1 Pixel-Perfect QSS Replica** | With **Adaptive Light/Dark Theme** support (GNOME/KDE) |
| **Machine Selection** | Supports Default Bookmark | **Full Session Persistence (Auto-Load)** | Auto-loads last used machine state |
| **Software List Perf** | Synchronous Loading | **Deferred Loading** | Instant machine switching |
| **ROM Download** | Supports Auto-Download | **High-Speed Failover Engine** | Multi-server failover (callapple + mdk.cab) |
| **Video Support** | Metal / OpenGL / BGFX | **BGFX / OpenGL / Vulkan** | Leveraging MAME's cross-platform rendering |
## 🌟 Key Features
### 🍏 Faithful Mac Experience (Feature Parity)
* **Visual Precision**: Precision support for **Window 1x-4x** modes with machine-specific aspect ratio heuristics.
* **Software Library**: Smart filtering, search overlay, and compatibility checking.
* **Advanced Slot Emulation**: Full support for nested sub-slots (e.g. SCSI cards).
* **ROM Management**: Real-time search, multi-server failover download, extended library.
* **Shared Directory**: Full parity with `-share_directory` argument.
### 🐧 Linux-Specific Features
* **System MAME Integration**: Auto-detects MAME from `PATH`, `/usr/bin/mame`, `/usr/games/mame`, etc.
* **Adaptive Theme**: Detects GNOME (`gsettings`) and KDE dark/light mode in real-time.
* **Native File Management**: Uses `xdg-open` for file/folder/URL opening.
* **No External Dependencies**: MAME is installed via your distribution's package manager.
### ⚠️ Known Limitations
* **VGM Mod**: The "Generate VGM" feature is currently disabled on Linux because the required MAME VGM Mod binary is only available for Windows.
## 🛠️ Quick Start
### Prerequisites
- **Python 3.9+**
- **MAME** installed via your package manager
- **PySide6** and **requests** (installed via system packages or pip)
### Installation
1. **Install System Dependencies**:
* **MAME**: Install via your package manager (e.g., `sudo apt install mame`).
* **Python 3**: Ensure Python 3.9+ is installed (`sudo apt install python3-full`).
* **X11 Support**: Required for GUI (`sudo apt install libxcb-cursor0`).
2. **Launch Ample**:
```bash
cd AmpleLinux
chmod +x AmpleLinux.sh
./AmpleLinux.sh
```
The script will **automatically** create a virtual environment (`.venv`), install `PySide6` and other dependencies via pip, and launch the app. **No manual pip install required.**
3. **Fast Deployment**:
* **Ubuntu Users**: If MAME is not found, the app will offer to install it via `snap`.
* Click **🎮 ROMs** to download system firmware.
* Go to **⚙️ Settings** to verify MAME is detected.
* Select a machine and **Launch MAME**!
## 📦 Building for Release
To create a standalone Linux binary (ELF) that requires no dependencies:
```bash
cd AmpleLinux
chmod +x build_elf.sh
./build_elf.sh
```
This script uses `PyInstaller` within a temporary venv to build a portable binary.
### 4. Desktop Integration (Icon Fix)
To see the correct icon in your Dock/Taskbar, copy the generated `.desktop` file:
```bash
mkdir -p ~/.local/share/applications/
cp dist/AmpleLinux/AmpleLinux.desktop ~/.local/share/applications/
```
Then search for "**AmpleLinux**" in your applications menu.
## 📂 Project Structure
| File/Directory | Description |
| :--- | :--- |
| **`AmpleLinux.sh`** | **Start Here**. Auto-setup script (uses venv + pip). |
| **`build_elf.sh`** | **Build Script**. Creates standalone binary via PyInstaller. |
| `make_icon.py` | Helper to generate Linux PNG icons from source. |
| `main.py` | Application entry point, UI rendering, and event loop. |
| `data_manager.py` | Parser for `.plist` machine definitions and MAME `.xml` software lists. |
| `mame_launcher.py` | Command-line builder and process manager. |
| `rom_manager.py` | Management and multi-threaded downloading of system ROMs. |
| `mame_downloader.py` | VGM Mod downloader (Windows only; unused on Linux). |
## 🔧 Troubleshooting
### MAME Not Detected
If the app can't find MAME:
1. **Ubuntu**: The app will offer to run `sudo snap install mame`.
2. **Manual**: Go to **⚙️ Settings** > **Select MAME...** to browse to the binary.
3. **PATH**: Verify `which mame` returns a path.
4. Common paths: `/usr/bin/mame`, `/usr/games/mame`, `/var/lib/snapd/snap/bin/mame`
### Theme Detection
The app auto-detects GNOME and KDE dark/light themes. If your desktop environment isn't supported, the app defaults to the Qt palette for theme detection.
## 📝 Acknowledgments
* Original macOS version developer: [Kelvin Sherlock](https://github.com/ksherlock)
* **Windows Port Developers: anomixer + Antigravity**
* **Linux Port**: Adapted from AmpleWin by anomixer + Antigravity
+113
View File
@@ -0,0 +1,113 @@
# AmpleLinux - Linux Port (Legacy Apple Emulator Frontend)
[English](README.md) | [繁體中文](README_tw.md)
這是一個將 macOS 原生 [Ample](https://github.com/ksherlock/ample) 專案移植至 Linux 平台的版本,基於 [AmpleWin](../AmpleWin/) Windows 移植版改編。
![](screenshot.png)
> [!IMPORTANT]
> **版本支援說明**:目前已同步支援至 Ample (macOS) 最新版本之資源定義以及 MAME 最新版本之核心。
## 🍎 Ample (macOS) vs. AmpleLinux (Linux) 完整對照表
| 功能項目 | Ample (macOS 原生版) | AmpleLinux (Linux 版) | 說明 |
| :--- | :--- | :--- | :--- |
| **程式語言** | Objective-C (Cocoa) | **Python 3.11 + PySide6 (Qt)** | 獨立開發,**完全沒動到 Mac 版原始碼** |
| **安裝方式** | .dmg 映像檔 / Homebrew | **免安裝綠色版 (+ .sh 自動配置)** | 透過 `AmpleLinux.sh` 一鍵搞定 Python 與依賴 |
| **MAME 整合** | 內建客製版核心 | **使用系統安裝的 MAME** | 透過 apt、dnf、pacman 等套件管理器安裝 |
| **UI 介面** | macOS 原生組件 | **1:1 像素級 QSS 複刻** | 支援 **Adaptive 自適應淺色/深色主題** (GNOME/KDE) |
| **初始機器選擇** | 支援預設書籤 | **全自動持久化 (自動載入上次狀態)** | 全自動開啟上次使用的機器 |
| **軟體清單效能** | 同步加載 | **延遲遞增加載 (Deferred Loading)** | 切換機器秒開 |
| **ROM 下載** | 支援自動下載 | **高效能 Failover 引擎** | 支援多伺服器切換 (callapple + mdk.cab) |
| **Video 支援** | Metal / OpenGL / BGFX | **BGFX / OpenGL / Vulkan** | 使用 MAME 的跨平台渲染後端 |
## 🌟 核心功能
### 🍏 忠實還原 Mac 體驗 (功能對齊)
* **視覺精準度**:精準支援 **Window 1x-4x** 模式,並內建機器專屬的比例啟發邏輯。
* **軟體資料庫**:智慧過濾、搜尋遮罩、相容性檢查。
* **進階槽位模擬**:完整支援嵌套子槽位(如 SCSI 卡)。
* **ROM 管理**:即時搜尋、多伺服器 Failover 下載、擴展韌體庫。
* **共享目錄**:與 Mac 版功能完全對齊 (`-share_directory`)。
### 🐧 Linux 專屬功能
* **系統 MAME 整合**:自動偵測 `PATH`、`/usr/bin/mame`、`/usr/games/mame` 等路徑。
* **自適應主題**:即時偵測 GNOME (`gsettings`) 與 KDE 的深色/淺色模式。
* **原生檔案管理**:使用 `xdg-open` 開啟檔案、資料夾和 URL。
* **無額外依賴**:MAME 直接透過發行版的套件管理器安裝。
### ⚠️ 已知限制
* **VGM Mod**:「Generate VGM」功能目前在 Linux 暫停使用,因為 MAME VGM Mod 功能所需的執行檔目前僅有 Windows 版本。
## 🛠️ 快速開始
### 前置需求
- **Python 3.9+**
- **MAME**(透過套件管理器安裝)
- **PySide6** 和 **requests**(透過系統套件或 pip 安裝)
### 安裝步驟
1. **安裝系統依賴套件**:
* **MAME**:透過您的套件管理器安裝(例如 `sudo apt install mame`)。
* **Python 3**:確認已安裝 Python 3.9+(`sudo apt install python3-full`)。
* **X11 支援**:GUI 介面所需(`sudo apt install libxcb-cursor0`)。
2. **啟動 Ample**:
```bash
cd AmpleLinux
chmod +x AmpleLinux.sh
./AmpleLinux.sh
```
腳本會**自動**建立虛擬環境 (`.venv`),透過 pip 安裝 `PySide6` 與其他依賴套件,最後啟動程式。**您不需要手動執行 pip install。**
3. **快速部署**:
* **Ubuntu 使用者**:如果找不到 MAME,程式會詢問是否透過 `snap` 安裝。
* 點擊主介面的 **🎮 ROMs** 以補齊系統韌體。
* 前往 **⚙️ Settings** 確認 MAME 已偵測到。
* 選擇機器,然後 **Launch MAME**!
## 📦 封裝發佈 (Build for Release)
若要產生不需要依賴環境的獨立 Linux 執行檔 (ELF):
```bash
cd AmpleLinux
chmod +x build_elf.sh
./build_elf.sh
```
此腳本會在暫存的 venv 中使用 `PyInstaller` 進行打包,產出的可攜式執行檔位於 `dist/AmpleLinux/`。
## 📂 專案結構
| 檔案/目錄 | 說明 |
| :--- | :--- |
| **`AmpleLinux.sh`** | **由此開始**。自動設定腳本 (使用 venv + pip)。 |
| **`build_elf.sh`** | **封裝腳本**。透過 PyInstaller 產生獨立執行檔。 |
| `make_icon.py` | 用於從來源圖片產生 Linux PNG 圖示的工具。 |
| `main.py` | 應用程式入口,處理 UI 渲染與主要邏輯。 |
| `data_manager.py` | 負責解析 `.plist` 機器定義檔與 MAME `.xml` 軟體列表。 |
| `mame_launcher.py` | MAME 指令建構器與執行序管理器。 |
| `rom_manager.py` | 系統 ROM 的管理與多執行緒下載引擎。 |
| `mame_downloader.py` | VGM Mod 下載工具 (僅限 Windows; Linux 未使用)。 |
## 🔧 疑難排解
### MAME 未偵測到
如果程式無法找到 MAME:
1. **Ubuntu**:程式會提供 `sudo snap install mame` 的安裝選項。
2. **手動設定**:前往 **⚙️ Settings** > **Select MAME...** 手動瀏覽並選擇執行檔。
3. **PATH**:確認 `which mame` 能回傳路徑。
4. 常見路徑:`/usr/bin/mame`、`/usr/games/mame`、`/var/lib/snapd/snap/bin/mame`
### 主題偵測
程式會自動偵測 GNOME 和 KDE 的深色/淺色主題。如果你的桌面環境不受支援,程式會使用 Qt 調色盤作為主題偵測的後備方案。
## 📝 致謝
* 原始 macOS 版本開發者: [Kelvin Sherlock](https://github.com/ksherlock)
* **Windows Port 開發者: anomixer + Antigravity**
* **Linux Port**:由 anomixer + Antigravity 基於 AmpleWin 改編
Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

+149
View File
@@ -0,0 +1,149 @@
#!/bin/bash
# build_elf.sh — Build standalone Linux binary for AmpleLinux using PyInstaller
set -e
cd "$(dirname "${BASH_SOURCE[0]}")"
echo "[AmpleLinux] Building standalone Linux binary..."
# --- Step 0: Ensure python3-venv is available ---
if ! python3 -m venv --help &> /dev/null; then
echo "[INFO] python3-venv is required but not installed."
if command -v apt &> /dev/null; then
PY_VER=$(python3 -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')")
echo "[INFO] Installing python3.${PY_VER}-venv ..."
sudo apt install -y "python3.${PY_VER}-venv" python3-full
if [ $? -ne 0 ]; then
echo "[ERROR] Failed to install python3-venv. Please run manually:"
echo " sudo apt install python3-venv python3-full"
exit 1
fi
else
echo "[ERROR] Please install python3-venv for your distro and try again."
exit 1
fi
fi
# --- Step 0.1: Ensure binutils is available ---
if ! command -v objcopy &> /dev/null; then
echo "[INFO] binutils (objcopy) is required but not installed."
if command -v apt &> /dev/null; then
echo "[INFO] Installing binutils..."
sudo apt install -y binutils
else
echo "[ERROR] Please install binutils (objcopy) for your distro."
exit 1
fi
fi
# --- Step 1: Create/Activate virtual environment ---
VENV_DIR=".build_venv"
# Recreate if venv is broken (missing activate script)
if [ -d "$VENV_DIR" ] && [ ! -f "$VENV_DIR/bin/activate" ]; then
echo "[WARN] Build venv is broken, recreating..."
rm -rf "$VENV_DIR"
fi
if [ ! -d "$VENV_DIR" ]; then
echo "[INFO] Creating build virtual environment..."
python3 -m venv "$VENV_DIR"
fi
source "$VENV_DIR/bin/activate"
echo "[INFO] Using Python: $(which python3)"
# --- Step 2: Install build dependencies + app dependencies in venv ---
echo "[INFO] Installing build dependencies..."
pip install --quiet pyinstaller Pillow
pip install --quiet -r requirements.txt
# --- Step 3: Generate Application Icons ---
echo ""
echo "[0/2] Generating Application Icons..."
python3 make_icon.py
# --- Step 4: Build with PyInstaller ---
echo ""
echo "[1/2] Converting main.py to Linux binary..."
ICON_PATH="ample.png"
ICON_ARG=""
if [ -f "$ICON_PATH" ]; then
ICON_ARG="--icon $ICON_PATH"
fi
pyinstaller --noconfirm --onedir --clean \
--name "AmpleLinux" \
--add-data "ample.png:." \
$ICON_ARG \
main.py
if [ $? -ne 0 ]; then
echo "[ERROR] Build failed!"
deactivate
exit 1
fi
# --- Step 5: Copy necessary assets ---
echo ""
echo "[2/2] Copying necessary assets..."
DIST_RESOURCES="dist/AmpleLinux/Ample/Resources"
mkdir -p "$DIST_RESOURCES"
echo "Copying Resources..."
cp -r ../Ample/Resources/* "$DIST_RESOURCES/"
DIST_MAME="dist/AmpleLinux/mame"
mkdir -p "$DIST_MAME/roms"
mkdir -p "$DIST_MAME/cfg"
echo "Created mame directory structure."
cp requirements.txt dist/AmpleLinux/
cp ample.png dist/AmpleLinux/
# --- Step 6: Create .desktop file for integration ---
echo "Creating .desktop file..."
cat > dist/AmpleLinux/AmpleLinux.desktop <<EOF
[Desktop Entry]
Type=Application
Name=AmpleLinux
Comment=Apple II Frontend for MAME
Exec=$(pwd)/dist/AmpleLinux/AmpleLinux
Icon=$(pwd)/dist/AmpleLinux/ample.png
Terminal=false
Categories=Game;Emulator;
StartupWMClass=AmpleLinux
EOF
echo ""
echo "[SUCCESS] Build complete!"
# --- Step 7: Interactive Install ---
if [ -t 0 ]; then
echo ""
read -p "Do you want to install the .desktop shortcut to ~/.local/share/applications/? (y/N) " -n 1 -r
echo ""
if [[ $REPLY =~ ^[Yy]$ ]]; then
mkdir -p ~/.local/share/applications/
cp dist/AmpleLinux/AmpleLinux.desktop ~/.local/share/applications/
echo "✅ Installed! You can now search for 'AmpleLinux' in your applications menu."
# Update icon cache just in case
if command -v gtk-update-icon-cache &> /dev/null; then
gtk-update-icon-cache ~/.local/share/icons &> /dev/null || true
fi
else
echo "Skipped installation."
echo "You can manually copy it later:"
echo " cp dist/AmpleLinux/AmpleLinux.desktop ~/.local/share/applications/"
fi
fi
echo ""
echo "The standalone application is located in: dist/AmpleLinux/AmpleLinux"
echo ""
# --- Cleanup ---
echo "Cleaning up build artifacts..."
rm -rf build
rm -f AmpleLinux.spec
deactivate
echo "Done!"
+141
View File
@@ -0,0 +1,141 @@
import xml.etree.ElementTree as ET
import os
import plistlib
class DataManager:
def __init__(self, resources_path, hash_path=None):
self.resources_path = resources_path
self.hash_path = hash_path
self.models = self.load_plist('models.plist')
self.roms = self.load_plist('roms.plist')
self.machine_cache = {}
self.software_cache = {}
def load_plist(self, filename):
path = os.path.join(self.resources_path, filename)
if not os.path.exists(path):
print(f"DEBUG: DataManager failed to find: {path}")
return None
with open(path, 'rb') as f:
return plistlib.load(f)
def get_machine_description(self, machine_name):
if machine_name in self.machine_cache:
return self.machine_cache[machine_name]
desc = self.load_plist(f'{machine_name}.plist')
if desc:
self.machine_cache[machine_name] = desc
return desc
def get_software_lists(self, machine_name):
desc = self.get_machine_description(machine_name)
if not desc or 'software' not in desc:
return []
results = []
for item in desc['software']:
xml_file = None
filter_val = None
if isinstance(item, str):
xml_file = item
elif isinstance(item, dict):
xml_file = item.get('name')
filter_val = item.get('filter')
elif isinstance(item, list) and len(item) >= 1:
xml_file = item[0]
if len(item) >= 2:
filter_val = item[1]
if xml_file:
# Ensure .xml extension
if not xml_file.endswith(".xml"):
xml_file += ".xml"
list_name = xml_file.replace(".xml", "")
software_items = self.load_software_xml(xml_file)
# We always append to results if the XML exists,
# even if items are empty (to show the header at least)
if xml_file in self.software_cache:
filtered_items = software_items
if filter_val:
# Improved comma-aware filtering
filtered_items = []
for s in software_items:
comp = s.get('compatibility')
if not comp:
filtered_items.append(s)
else:
if filter_val in comp.split(','):
filtered_items.append(s)
results.append({
'name': list_name,
'description': self.software_cache[xml_file]['description'],
'items': filtered_items
})
return results
def load_software_xml(self, xml_file):
if xml_file in self.software_cache:
return self.software_cache[xml_file]['items']
if not self.hash_path:
return []
path = os.path.join(self.hash_path, xml_file)
if not os.path.exists(path):
return []
try:
tree = ET.parse(path)
root = tree.getroot()
list_desc = root.attrib.get('description', xml_file.replace(".xml", ""))
items = []
for sw in root.findall('software'):
sw_name = sw.attrib.get('name')
sw_desc = sw.find('description')
sw_desc_text = sw_desc.text if sw_desc is not None else sw_name
# Check for compatibility
compatibility = None
for sharedfeat in sw.findall('sharedfeat'):
if sharedfeat.attrib.get('name') == 'compatibility':
compatibility = sharedfeat.attrib.get('value')
break
items.append({
'name': sw_name,
'description': sw_desc_text,
'compatibility': compatibility
})
# Sort items by description
items.sort(key=lambda x: x['description'].lower())
self.software_cache[xml_file] = {
'description': list_desc,
'items': items
}
return items
except Exception as e:
print(f"Error parsing software XML {xml_file}: {e}")
return []
def get_flat_machines(self, models=None):
if models is None:
models = self.models
machines = []
for model in models:
if 'value' in model and model['value']:
machines.append({
'name': model['value'],
'description': model.get('description', model['value'])
})
if 'children' in model:
machines.extend(self.get_flat_machines(model['children']))
return machines
+2623
View File
File diff suppressed because it is too large. Load diff
+46
View File
@@ -0,0 +1,46 @@
from PIL import Image
import os
import sys
def create_linux_icons(source_png, output_dir):
"""Generate multiple PNG icon sizes for Linux desktop integration."""
print(f"Opening source: {source_png}")
try:
img = Image.open(source_png)
except Exception as e:
print(f"Error opening image: {e}")
return False
# Standard Linux icon sizes (freedesktop.org spec)
icon_sizes = [512, 256, 128, 64, 48, 32, 16]
os.makedirs(output_dir, exist_ok=True)
for size in icon_sizes:
resized = img.resize((size, size), Image.LANCZOS)
out_path = os.path.join(output_dir, f"ample_{size}x{size}.png")
resized.save(out_path, format='PNG')
print(f" Saved: {out_path}")
# Also save a default icon at top level
default_icon = os.path.join(os.path.dirname(output_dir), "ample.png")
img.resize((256, 256), Image.LANCZOS).save(default_icon, format='PNG')
print(f" Saved default icon: {default_icon}")
print("Success!")
return True
if __name__ == "__main__":
src = os.path.join("..", "Ample", "Assets.xcassets", "AppIcon.appiconset", "icon-1024.png")
dst_dir = "icons"
# Check if source exists
if not os.path.exists(src):
print(f"Source file not found: {src}")
print("Make sure you run this script from the AmpleLinux directory.")
sys.exit(1)
if create_linux_icons(src, dst_dir):
sys.exit(0)
else:
sys.exit(1)
+102
View File
@@ -0,0 +1,102 @@
import os
import requests
import subprocess
import shutil
from PySide6.QtCore import QThread, Signal
class VgmModDownloadWorker(QThread):
progress = Signal(int, int)
finished = Signal(bool, str)
status = Signal(str)
def __init__(self, dest_dir):
super().__init__()
self.dest_dir = dest_dir
def run(self):
# Try multiple URLs for VGM support
urls = [
"https://vgmrips.net/programs/creators/MAME0280_bin64_2025-11-16.7z",
"https://github.com/anomixer/ample/raw/mame-vgm/MAME0280_bin64_2025-11-16.7z",
"https://github.com/anomixer/ample/blob/mame-vgm/MAME0280_bin64_2025-11-16.7z?raw=true"
]
last_error = ""
success = False
archive_path = ""
try:
for url in urls:
try:
self.status.emit(f"Downloading MAME VGM Mod...")
response = requests.get(url, stream=True, timeout=60, allow_redirects=True)
response.raise_for_status()
total_size = int(response.headers.get('content-length', 0))
filename = "mame_vgm_mod.7z"
archive_path = os.path.join(self.dest_dir, filename)
os.makedirs(self.dest_dir, exist_ok=True)
downloaded = 0
with open(archive_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=65536):
if chunk:
f.write(chunk)
downloaded += len(chunk)
self.progress.emit(downloaded, total_size)
success = True
break
except Exception as e:
last_error = str(e)
continue
if not success:
self.finished.emit(False, f"Failed to download from all mirrors. Last error: {last_error}")
return
self.status.emit("Extracting VGM Mod...")
# Create a temporary directory for extraction to avoid overwriting existing mame
temp_extract_dir = os.path.join(self.dest_dir, "_vgm_temp")
os.makedirs(temp_extract_dir, exist_ok=True)
# Extract mame.exe (the Windows binary inside the archive) to the temp directory
# On Linux we use 7z from PATH (p7zip-full package)
extract_cmd = ["7z", "e", archive_path, "mame.exe", "-o" + temp_extract_dir, "-y"]
try:
subprocess.run(extract_cmd, check=True, capture_output=True)
except (subprocess.CalledProcessError, FileNotFoundError) as e:
raise Exception(
"7z not found. Please install p7zip-full:\n"
" Ubuntu/Debian: sudo apt install p7zip-full\n"
" Fedora: sudo dnf install p7zip-plugins\n"
" Arch: sudo pacman -S p7zip"
)
# Note: VGM Mod is Windows-only (mame.exe). On Linux, this would need
# Wine to run. We still extract and rename it for users who may use Wine.
extracted_mame = os.path.join(temp_extract_dir, "mame.exe")
target_vgm = os.path.join(self.dest_dir, "mame-vgm")
if os.path.exists(extracted_mame):
if os.path.exists(target_vgm):
os.remove(target_vgm)
os.rename(extracted_mame, target_vgm)
# Clean up temporary directory and archive
try:
if os.path.exists(temp_extract_dir):
shutil.rmtree(temp_extract_dir)
except Exception:
pass
if os.path.exists(archive_path):
os.remove(archive_path)
self.finished.emit(True, target_vgm)
except Exception as e:
self.status.emit(f"Error: {str(e)}")
self.finished.emit(False, str(e))
+108
View File
@@ -0,0 +1,108 @@
import subprocess
import os
import re
class MameLauncher:
def __init__(self):
self.mame_path = "mame"
self.working_dir = "."
self.valid_slots_cache = {}
def get_valid_slots(self, machine):
if machine in self.valid_slots_cache:
return self.valid_slots_cache[machine]
if not os.path.exists(self.mame_path) and self.mame_path != "mame":
return None
try:
cmd = [self.mame_path, machine, "-listslots"]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=5)
slots = set()
lines = result.stdout.splitlines()
# MAME -listslots has a header: "SYSTEM SLOT NAME SLOT OPTIONS"
# We want the second column.
for line in lines:
line = line.strip()
if not line or line.startswith("---") or "SLOT NAME" in line:
continue
parts = line.split()
# If the line starts with the machine name, the slot name is in index 1.
# If it's a sub-slot (starting with whitespace, now stripped), it's in index 0.
if line.startswith(machine) and len(parts) >= 2:
slots.add(parts[1])
elif len(parts) >= 1:
slots.add(parts[0])
self.valid_slots_cache[machine] = slots
return slots
except Exception as e:
print(f"Error getting slots for {machine}: {e}")
return None
def get_valid_media(self, machine):
cache_key = f"{machine}_media"
if cache_key in self.valid_slots_cache:
return self.valid_slots_cache[cache_key]
if not os.path.exists(self.mame_path) and self.mame_path != "mame":
return None
try:
cmd = [self.mame_path, machine, "-listmedia"]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=5)
media_types = set()
lines = result.stdout.splitlines()
# Extract common brief names like flop1, cass, etc inside brackets
for line in lines:
if "(" in line and ")" in line:
match = re.search(r'\((\w+)\)', line)
if match:
media_types.add(match.group(1))
self.valid_slots_cache[cache_key] = media_types
return media_types
except Exception:
return None
def build_args(self, machine, slots=None, media=None, soft_list_args=None, extra_options=None):
args = [machine]
if soft_list_args:
for sl in soft_list_args:
args.append(sl)
args.append("-skip_gameinfo")
if slots:
for slot_name, option in slots.items():
if option and not slot_name.startswith(':'):
# Pass the slot argument regardless of base machine validation
args.extend([f"-{slot_name}", option])
if media:
for media_type, path in media.items():
if path and not media_type.startswith(':'):
# Pass the media argument regardless of base machine validation
args.extend([f"-{media_type}", path])
if extra_options:
for opt in extra_options:
args.append(opt)
return args
def launch(self, machine, slots=None, media=None, soft_list_args=None, extra_options=None, alt_exe=None):
args = self.build_args(machine, slots, media, soft_list_args, extra_options)
exe = alt_exe if alt_exe else self.mame_path
full_cmd = [exe] + args
print(f"Launching: {subprocess.list2cmdline(full_cmd)}")
try:
return subprocess.Popen(full_cmd, cwd=self.working_dir)
except Exception as e:
print(f"Error launching MAME: {e}")
return None
+2
View File
@@ -0,0 +1,2 @@
PySide6
requests
+100
View File
@@ -0,0 +1,100 @@
import os
import requests
import plistlib
from PySide6.QtCore import QObject, Signal, QRunnable, QThreadPool
class DownloadSignals(QObject):
progress = Signal(int, int) # current, total
finished = Signal(str, bool) # value, success
status = Signal(str)
class DownloadWorker(QRunnable):
def __init__(self, urls, dest_path, value):
super().__init__()
self.urls = urls if isinstance(urls, list) else [urls]
self.dest_path = dest_path
self.value = value
self.signals = DownloadSignals()
self._is_cancelled = False
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
def cancel(self):
self._is_cancelled = True
def run(self):
last_error = "No URLs provided"
for url in self.urls:
try:
if self._is_cancelled: return
# For small files (ROMs), direct download is much faster than streaming
response = requests.get(url, headers=self.headers, timeout=20)
response.raise_for_status()
os.makedirs(os.path.dirname(self.dest_path), exist_ok=True)
if self._is_cancelled: return
with open(self.dest_path, 'wb') as f:
f.write(response.content)
self.signals.finished.emit(self.value, True)
return # Success!
except Exception as e:
last_error = str(e)
continue # Try next URL
# If we get here, all URLs failed
if os.path.exists(self.dest_path):
try: os.remove(self.dest_path)
except: pass
self.signals.status.emit(f"Error: {last_error}")
self.signals.finished.emit(self.value, False)
class RomManager(QObject):
def __init__(self, resources_path, roms_dir):
super().__init__()
self.resources_path = resources_path
self.roms_dir = roms_dir
self.base_urls = [
"https://www.callapple.org/roms/",
"https://mdk.cab/download/split/"
]
self.rom_list = self.load_rom_list()
def load_rom_list(self):
path = os.path.join(self.resources_path, "roms.plist")
if not os.path.exists(path):
return []
with open(path, 'rb') as f:
return plistlib.load(f)
def get_rom_status(self):
status_list = []
for rom in self.rom_list:
value = rom['value']
# Check for zip, 7z or folder
found = False
for ext in ['zip', '7z']:
path = os.path.join(self.roms_dir, f"{value}.{ext}")
if os.path.exists(path):
found = True
break
if not found:
# Check for unzipped folder
path = os.path.join(self.roms_dir, value)
if os.path.isdir(path):
found = True
status_list.append({
'value': value,
'description': rom['description'],
'exists': found
})
return status_list
def get_download_url(self, value, ext='zip'):
return f"{self.base_url}{value}.{ext}"
Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

+376
View File
@@ -0,0 +1,376 @@
# Agent Task Audit Log - Ample Windows Port
## 📅 Session: 2026-03-02 (Session 13)
### 🎯 Objective: Upstream Version Bump & Documentation Maintenance
Focused on updating the project to track MAME 0.286 and simplifying documentation maintainability.
### ✅ Key Achievements:
1. **Version Bump**: Updated `mame_downloader.py` to point to the latest **MAME 0.286** x64 Windows binary.
2. **Documentation Refactoring**:
* Renamed version-specific screenshot files (e.g. `screenshot-v0.28x.png` to `screenshot.png`) across all platforms.
* Updated `README.md` and `README_tw.md` to use generic "latest version" terminology to prevent the need for manual text updates upon future MAME releases.
### 🚀 Current Project Status
The Windows Port is functionally tracking MAME 0.286 and documentation is now future-proofed against minor version increments.
---
## 📅 Session: 2026-02-16 (Session 12)
### 🎯 Objective: Linux Port Spinoff
AmpleWin has successfully served as the foundation for a new Linux port.
### ✅ Key Achievements:
1. **Port Creation**:
* **AmpleLinux**: Created `AmpleLinux/` directory based on the AmpleWin codebase.
* **Shared DNA**: `data_manager.py` and `rom_manager.py` remain identical, while `main.py` was adapted for Linux (xdg-open, paths, dependencies).
* **Cross-Reference**: Added links to AmpleLinux in the README.
### 🚀 Current Project Status
The project now supports both Windows (AmpleWin) and Linux (AmpleLinux) natively.
---
## 📅 Session: 2026-02-09 (Session 11)
### 🎯 Objective: Upstream Synchronization & Codebase Hygiene
Focused on synchronizing the project with the latest upstream changes from `ksherlock/ample`, ensuring the `roms.plist` database is compliant with the official repository, and cleaning up diverging local branches.
### ✅ Key Achievements:
1. **Full Upstream Sync**:
* **Repository Alignment**: Merged latest `upstream/master` changes (4 new commits), bringing in the official fix for **PowerBook Duo 280 (`macpd280`)** and new definitions like **Epson RX-80 (`epson_rx80`)**.
* **Deforking roms.plist**: Discarded local custom modifications to `Ample/Resources/roms.plist`. The file is now byte-for-byte identical to the upstream version, ensuring long-term maintainability.
* **Branch Cleanup**: Removed the stale `fix-missing-roms` branch and closed the associated PR #44, as the upstream author has implemented the necessary fixes natively.
2. **AmpleWin Verification**:
* **Compatibility Verified**: Confirmed that `AmpleWin` correctly parses the new upstream `roms.plist` without errors.
* **ROM Status**: Validated that `macpd280` is now natively supported for auto-download via the new upstream definitions. Note: Custom definitions for *Pravetz* and *TK3000* are no longer in `roms.plist` but remain playable if ROMs are manually provided.
3. **Deployment & Distribution**:
* **Refactor**: Renamed `mame_bin` to `mame` across the codebase for better standards compliance.
* **Portable EXE**: Created `build_exe.bat` using **PyInstaller (OneDir)** to package the application into a standalone executable.
* **Path Logic**: Updated `main.py` with robust `sys.frozen` detection to ensure resources and downloads work correctly in both Dev and Frozen environments.
* **Documentation**: Added build instructions to READMEs.
### 🚀 Current Project Status
The codebase is now in a "Clean Slate" state. `master` is fully synced with upstream, with `AmpleWin` serving as a strictly additive extension.
## 📅 Session: 2026-02-02 (Session 10)
### 🎯 Objective: ROM Library Expansion & Advanced Slot Emulation
Focused on expanding the supported ROM library, implementing a robust failover download mechanism, and perfecting nested slot configuration logic for SCSI peripherals.
### ✅ Key Achievements:
1. **ROM Library & Search Expansion**:
* **New System Support**: Added missing ROM definitions for **Macintosh PowerBook Duo 280/280c**, **Pravetz 8C**, and **TK3000 //e**.
* **Search Parity**: Fully synchronized hardware definitions with the latest macOS release, including secondary Pravetz models (`82`, `8M`).
2. **Robust ROM Download Failover**:
* **Prioritized Multi-Server Support**: Implemented a transparent failover mechanism in `rom_manager.py`. The downloader now prioritizes **callapple.org** for maximum stability and automatically falls back to **mdk.cab** for Apple II clones and split sets unreachable on the primary server.
* **Status Integrity**: Fixed a bug in the download progress counter to ensure accurate success/failure reporting in the UI.
3. **Advanced Slot & Media Emulation**:
* **SCSI Sub-Peripheral Detection**: Rewrote `aggregate_media` to recursively detect devices attached to slot cards (e.g., finding the CD-ROM and Hard Disk on an Apple IIgs SCSI card).
* **Nested Slot Defaults**: Implemented automatic initialization for sub-slots. Plugging in a SCSI card now automatically populates its sub-slots with default devices (CD-ROM at ID 1, Hard Disk at ID 6), matching Mac parity.
* **Sub-Slot UI Parity**: Updated the "Hamburger" popup to show all configurable sub-slots, not just those with media, giving users full control over complex hardware chains.
* **Aggregator Optimization**: Refined the media scanner to ignore the global "device library" at the root level, preventing UI clutter and double-counting of unmapped drives.
### 🚀 Current Project Status
The Windows Port now offers superior hardware configuration capabilities. Complex SCSI and SmartPort chains are handled automatically, and the ROM acquisition system is more reliable than ever.
## 📅 Session: 2026-02-02 (Session 9)
### 🎯 Objective: Upstream Synchronization & Feature Parity (MAME 0.286)
Focused on synchronizing with the upstream Ample (macOS) v0.286 release, updating the core emulator backend, and implementing new UI search capabilities.
### ✅ Key Achievements:
1. **Upstream Repository Synchronization**:
* **Merge & Push**: Successfully merged latest commits from `upstream/master` (ksherlock/ample).
* **Resource Alignment**: Synchronized latest hardware definitions and slot configurations from original project.
* **A2retroNET Integration**: Inherited support for a2retronet hardware, enabling up to 8 SmartPort disk images.
2. **MAME Core Update**:
* **Version Upgrade**: Updated `mame_downloader.py` to point to the official **MAME 0.286** Windows x64 binary.
* **Download Engine Parity**: Users can now auto-download the latest MAME core directly from the Settings menu.
3. **ROM Manager Enhancements**:
* **Search Filter**: Implemented a real-time search field in the `RomManagerDialog` header (matching macOS feature parity).
* **Filtering Logic**: Updated `refresh_list` to filter ROMs by description or shortcode, allowing users to quickly find specific system firmwares.
### 🚀 Current Project Status
The Windows Port is now fully synchronized with Ample (macOS) v0.286 resources. It supports the latest MAME core and offers improved ROM management tools.
---
## 📅 Session: 2026-01-24 (Session 8)
### 🎯 Objective: Path robustness & UI Interactivity
Focused on fixing "No such file" errors when launching custom ROM paths and improving the user experience for file selection in secondary tabs.
### ✅ Key Achievements:
1. **Command Line Robustness**:
* **Quote Handling**: Patched the `shlex` logic in `main.py` to handle Windows paths correctly. Manually stripping outer quotes ensures `subprocess` doesn't double-escape them, fixing the critical "No such file or directory" error when launching files with spaces in their path.
2. **File Selection UX**:
* **A/V Path Selectors**: Implemented `mousePressEvent` on the A/V tab input fields (AVI, WAV, VGM). Clicking these text boxes now opens a native `QFileDialog` ("Save As") with appropriate extension filters, saving users from manual typing.
* **Path Normalization**: Updated the "Shared Directory" directory selector to automatically normalize paths (e.g., converting `/` to `\`), ensuring visual consistency and compatibility with Windows command line expectations.
### 🚀 Current Project Status
The application is now highly resilient to typical Windows path complexities. Users can easily select output destinations and shared folders without worrying about path syntax errors.
---
## 📅 Session: 2026-01-22 (Session 7)
### 🎯 Objective: User Freedom & flexible Command Control
Focused on giving the user complete control over the MAME launch command and ensuring a cleaner default state for machine slots.
### ✅ Key Achievements:
1. **Editable Command Console**:
* **Unlocked Preview**: The "Command Preview" text box is no longer read-only.
* **Source of Truth**: The Launch button now executes *exactly* what is typed in this box. Users can manually add, remove, or edit arguments (e.g., adding `-verbose` or removing unwanted flags) before launching.
2. **Launch Engine Integrity**:
* **Absolute Path Resolution**: Implemented `shlex` parsing to read the user's manual command string. It automatically detects the command (`mame` or `mame-vgm`) and resolves it to the absolute system path to fix `[WinError 2]` on Windows.
* **VGM Pathing**: Logic retains awareness of VGM Mod capabilities even when launching from a custom text string.
3. **Cleaner Default State**:
* **Slot Neutrality**: Removed the aggressive fallback logic that forced the first available option for slots without a default value.
* **Phantom Args Clarified**: This eliminates confusing arguments like `-fdc:0 525` appearing automatically, ensuring MAME starts with its internal defaults unless the local configuration explicitly overrides them.
### 🚀 Current Project Status
The app now respects "Power User" workflows. You can use the UI for quick setup, then fine-tune the command line manually. The codebase structure is being finalized.
---
## 📅 Session: 2026-01-21 (Session 6)
### 🎯 Objective: VGM Mod Stability & Extraction Safety
Focused on fixing critical bugs in the VGM recording workflow, ensuring extraction safety, and improving UI feedback for the modded binary.
### ✅ Key Achievements:
1. **VGM Mod Extraction Safety**:
* **Anti-Overwrite Workflow**: Implemented a temporary directory strategy (`_vgm_temp`) during VGM Mod extraction. This ensures that the mod's `mame.exe` (v0.280) never accidentally overwrites the main official `mame.exe` (v0.284).
* **Atomic Renaming**: The modded binary is now safely extracted, renamed to `mame-vgm.exe`, and moved to the destination in a single, non-destructive step.
2. **Command Line & UI Parity**:
* **Explicit Recording Toggle**: Fixed a bug where `-vgmwrite 1` was missing from the console launch command. Recording is now correctly activated when using the modded binary.
* **Dynamic UI Preview**: The 4-line console preview now correctly displays `mame-vgm` as the target executable when VGM recording is enabled and the mod is detected, matching actual runtime behavior.
3. **Thread & Lifecycle Stability**:
* **Remove Safety**: Fixed a `ValueError: list.remove(x): x not in list` in the worker cleanup logic, ensuring the thread-safe management of background tasks even if signals fire twice.
* **Worker Refactoring**: Rewrote the `VgmModDownloadWorker` and `VgmPostProcessWorker` logic to handle edge cases in file movement and process termination more gracefully.
4. **Shared Directory & UI Refinement**:
* **Logic Completion**: Fixed a missing link in the launch engine where the "Shared Directory" path from the UI wasn't being passed to the actual MAME process.
* **Standardized Argument**: Updated from `-share` to the official `-share_directory` for maximum compatibility.
* **UI Bugfix**: Removed duplicate "Paths" tab initialization in the main window.
* **Click-to-Browse**: Implemented a pop-up directory selector when clicking the Shared Directory path box, replacing manual entry.
5. **Smart Slot Validation (Mac Parity)**:
* **Disabled State Support**: Ported the `disabled` logic from the Mac version. Slot options that are technically defined but marked as unsupported in the plist (e.g., specific SCSI cards on Apple IIgs) are now visually grayed out and unselectable in the dropdown menu.
* **Prevention**: Prevents users from accidentally selecting incompatible hardware configurations that would cause MAME to crash or behave unexpectedly.
### 🚀 Current Project Status
The VGM and Shared Directory workflows are now "Production Ready." The UI has reached a high level of fidelity with the Mac original, including subtle behaviors like smart slot validation and intuitive path selection.
---
## 📅 Session: 2026-01-21 (Session 5)
### 🎯 Objective: MAME Core Logic & Command Line Robustness
Focused on improving the reliability of the MAME launch engine, specifically regarding dynamic slot media (CFFA2), multi-drive support, and shell-safe command construction.
### ✅ Key Achievements:
1. **Relaxed Parameter Validation**:
* **Dynamic Media Parity**: Removed strict `listmedia` validation in `MameLauncher` to allow secondary media types (like `hard1`, `hard2`) that only appear when a specific card (e.g., CFFA2) is plugged in.
* **Internal Filter**: Implemented logic to automatically skip internal MAME node names starting with a colon (e.g., `-:prn`) to prevent "unknown option" errors.
2. **Multi-Drive & Storage Support**:
* **Capping Removal**: Fixed a self-imposed limitation in `main.py` that forced `hard`, `cdrom`, and `cassette` counts to 1.
* **CFFA2 Ready**: AmpleWin now correctly supports machines/cards with multiple hard drives (`-hard1`, `-hard2`).
3. **Shell Integrity & Quoting**:
* **Robust Quoting**: Integrated `subprocess.list2cmdline` for both the UI Command Preview and the actual process execution.
* **Space Handling**: Guaranteed that file paths containing spaces are automatically wrapped in quotes (`""`), preventing launch failures on Windows.
* **Path Normalization**: Implemented `os.path.normpath` for all MAME arguments (`-hard`, `-rompath`, etc.), ensuring consistent Windows-style backslashes (`\`).
* **Command Line Streamlining**: Automated `mame.ini` generation via `mame -cc` upon MAME detection. This allows removing redundant path arguments (`-hashpath`, `-artpath`, etc.) from the command line, resulting in a much cleaner and more readable preview.
* **VGM Support (Advanced)**: Since modern MAME removed VGM support, AmpleWin implements a robust background workflow to download and configure the **MAME-VGM Mod (v0.280)**. It uses a non-destructive extraction process (`mame-vgm.exe`) to preserve your main MAME core while restoring high-fidelity music recording, and automatically moves the resulting `.vgm` files to the user's desired path upon MAME exit.
4. **Resolution Scaling & Visual Parity**:
* **Window Mode Scaling**: Implemented `-resolution` generation for scaling modes (2x, 3x, 4x) and **`-nomax`** for **Window 1x** mode to ensure consistent default sizing.
* **Aspect Ratio Heuristic**: Integrated a 4:3 correction heuristic for non-square pixel machines (e.g., Apple II: 560x192 -> 1120x840 at 2x) to match macOS Ample behavior.
* **Square Pixel Mode**: Implemented integer scaling for Apple II machines (e.g., **1120x768** at 2x) while adding **`-nounevenstretch`** to prevent pixel shimmering and maintain clarity.
* **UI Expansion**: Added "Window 4x" option to the Video settings tab.
* **Disk Sound Effects Integration**: Linked the "Disk Sound Effects" checkbox to the `-nosamples` argument, allowing MAME samples to load when sound effects are enabled.
* **CPU Speed & Throttle UI Alignment**: Merged the Throttle checkbox into the CPU Speed dropdown as a "No Throttle" option, perfectly matching the original macOS Ample interface and logic.
5. **BGFX Effect Synchronization**:
* **Enhanced Effects List**: Updated the video effects selection to support a standardized set of BGFX screen chains: **Unfiltered, HLSL, CRT Geometry, CRT Geometry Deluxe, LCD Grid, and Fighters**.
* **Chain Mapping**: Implemented precise mapping between UI selection and MAME's `-bgfx_screen_chains` internal identifiers.
### 🚀 Current Project Status
The MAME launch engine is now significantly more robust and "intelligent." It handles complex slot configurations and multi-disk setups like CFFA2 without manual parameter tweaking, while maintaining a clean, error-free command line preview.
---
## 📅 Session: 2026-01-19 (Session 4)
### 🎯 Objective: Real-time Adaptive Theming & UI Resilience
Focused on implementing a native Windows theme detection engine and ensuring 100% visibility/aesthetic parity across both Light and Dark modes without requiring application restarts. Refined the command console for long parameter strings.
### ✅ Key Achievements:
1. **Adaptive Theme Engine**:
* **Registry-Level Detection**: Implemented `winreg` polling to detect `AppsUseLightTheme` changes in real-time.
* **Live Synchronization**: Added a 2-second polling timer (`QTimer`) that triggers a global UI restyle, allowing the app to switch between Light and Dark modes on-the-fly.
* **Cross-Window Propagation**: Ensured theme changes flow correctly into child dialogs (ROM Manager) and dynamic overlays (Software Search, Sub-slot popups).
2. **UI Polish & Visibility Fixes**:
* **Light Mode "Ghosting" Elimination**: Fixed unreadable text by moving critical UI colors (Slot Labels, Media Headers) from hardcoded Python strings to the global adaptive stylesheet.
* **Themed Popups**: Rewrote `SoftwarePopup` and sub-slot bubble painting to dynamically adjust background colors and "triangle" indicators based on the system theme.
* **ROM Manager Parity**: Fully themed the ROM download dialog, ensuring status labels (found/missing) maintain high contrast in both modes.
3. **Command Console Expansion**:
* **Multi-line Preview**: Replaced the single-line `QLineEdit` with a 4-line `QTextEdit` console footer.
* **Parameter Visibility**: This allows users to review the entire MAME command line, including long software list paths and slot configurations, without horizontal scrolling.
4. **Stability & Bug Squashing**:
* **ROM Manager Reliability**: Corrected `@Slot` decorators and converted the dialog to `.exec()` (Modal) to prevent interaction conflicts.
* **Logic Errors**: Fixed several `NameError` bugs in the rendering engine and addressed stylesheet inheritance issues that caused transparent list views.
5. **Visual Documentation & Networking Guide**:
* **README Screenshots**: Embedded `screenshot-v0.284.png` in READMEs to match original aesthetics.
* **Networking Parity Section**: Added a specialized section in READMEs explaining **Npcap** requirements for Uthernet II simulation, clarifying that the macOS "Fix Permissions" is unnecessary on Windows.
### 🚀 Current Project Status
The Windows Port is now a "State-of-the-Art" adaptive application. It feels native on both Light and Dark Windows setups, offers robust command line verification, and maintains the premium "Apple-inspired" aesthetic consistently.
---
## 📅 Session: 2026-01-19 (Session 3)
### 🎯 Objective: Documentation Standardization & UI Finalization
This session focused on finalizing the project's documentation (internationalization), organizing the file structure to stay clean relative to the upstream repository, and refining the primary toolbar functions.
### ✅ Key Achievements:
1. **Documentation Internationalization**:
* **Dual-Language Support**: Created `README.md` (English) and `README_tw.md` (Traditional Chinese) in the `AmpleWin` directory.
* **Mutual Linking**: Implemented language-switching headers in both README files for a professional GitHub experience.
* **Parity Verification**: Deep-dived into original macOS Objective-C source code to ensure the comparison table is 100% accurate regarding ROM downloading, bookmarked machine persistence, and technical differences.
2. **UI Finalization & Utility Tools**:
* **Ample Dir Integration**: Renamed "Disk Images" to "📂 Ample Dir". It now acts as a shortcut to open the application directory in Windows Explorer.
* **Redirected Help**: Linked the "📖 Help" button directly to the official project GitHub sub-folder for instant user support.
3. **Project Structure Hygiene**:
* **Namespace Isolation**: Relocated all Windows-specific overhead files (`README_tw.md`, `AmpleWin.bat`, `requirements.txt`, `Agent.md`) into the `AmpleWin` subdirectory.
* **Upstream Integrity**: Restored the root directory to its original state, ensuring a clean "1 commit ahead" status for easy upstream maintenance.
* **Script Resilience**: Updated `AmpleWin.bat` to handle the new directory structure, allowing execution directly from within the `AmpleWin` folder.
### 🚀 Current Project Status
The Windows Port is now a "ready-to-ship" localized product. The documentation is verified against the original Mac source code, the UI buttons serve practical Windows-specific needs, and the project stays respectful to the original repository's file structure.
---
## 📅 Session: 2026-01-18 (Session 2)
### 🎯 Objective: Deployment, Performance & Path Robustness
This session focused on making the application portable, optimizing the download engine for "instant" ROM acquisition, and improving the first-run user experience with guided setup.
### ✅ Key Achievements:
1. **Deployment & Portability**:
* **Auto-Launcher**: Created `ample_win.bat` to automate dependency installation and app execution.
* **Dynamic Paths**: Replaced hardcoded absolute paths with a robust search algorithm that detects the `Ample/Resources` folder relative to the script location.
* **Environment Isolation**: Forced MAME working directory to `mame_bin`, ensuring `nvram`, `cfg`, and `diff` folders stay within the emulator directory and out of the project root.
2. **Explosive Download Engine**:
* **Threading Mastery**: Transitioned to `QThreadPool` for manageable concurrency.
* **Performance Leap**: Increased parallel download threads from 1 to **50**.
* **Small File Optimization**: For ROM files (<64KB), switched from streaming to direct `requests.content` I/O, resulting in near-instant mass downloads.
* **Anti-Throttling**: Added browser-masking `User-Agent` headers.
3. **User Experience (UX)**:
* **Startup Wizard**: Implemented sequential logic: Check MAME -> Guided Download -> Check ROMs -> Guided Download.
* **Sticky Software (Smart Carry-over)**:
* Selections and filters now persist across compatible machines.
* **Compatibility Logic**: Automatically clears selection if the new machine doesn't support the current software list.
* **Full Name Display**: The search box now displays the full, descriptive software name instead of the short MAME ID.
* **UI Cleanliness**: Software lists stay collapsed during machine switches for a sleeker look.
* **Windows 10 Fixes**: Applied global CSS overrides for `QMessageBox` and `QDialog` to fix unreadable grey-on-white text issues on Windows 10.
4. **Project Hygiene**:
* Updated `.gitignore` to exclude MAME runtime artifacts (`nvram/`, `cfg/`, `sta/`, etc.).
* Updated `README_win.md` with the new one-click launch instructions.
### 🚀 Current Project Status
Ample Windows is now highly portable and user-friendly. The download system is exceptionally fast, and the environment stays clean during emulation sessions.
## 📅 Session: 2026-01-18 (Session 1)
### 🎯 Objective: Software List Integration & Final UI Polish
This session focused on implementing the MAME Software List feature and refining the UI to achieve 100% aesthetic parity with the macOS version, including functional improvements to the MAME launch engine for Windows.
### ✅ Key Achievements:
1. **Software List Feature**:
* **XML Parsing**: Enhanced `DataManager` to parse MAME's `hash/*.xml` files.
* **Intelligent Discovery**: Implemented a search-based software browser with autocomplete-style show/hide logic.
* **Auto-Detection**: Integrated software list selection into the MAME launch command with optimized argument ordering.
2. **MAME Launch Engine**:
* **Argument Ordering**: Fixed Windows-specific software list resolution issues by placing software list items immediately after the machine name.
* **Path Isolation**: Standardized `-hashpath`, `-bgfx_path`, and `-rompath` to be relative to the application's `mame_bin` directory.
* **Resource Management**: Centralized ROM storage to `mame_bin\roms`.
3. **UI Aesthetic Refinement**:
* **Apple Launch Button**: Replicated the Mac-style 🍎 icon inside the Launch button with left-aligned icon and right-aligned text.
* **Full-Width Console**: Moved the Command Preview to a full-width footer with a console-style (black background, monospace) styling.
* **Clean Mode**: Removed "Use Samples" checkbox and hardcoded `-nosamples` for authenticity.
* **Proportional Layout**: Expanded the options area to comfortably display long software names (60+ characters).
4. **Stability & Initialization**:
* **Graceful Shutdown**: Improved thread termination logic in `closeEvent`.
* **Safe Initialization**: Fixed attribute and name errors in `DataManager` and `AmpleMainWindow` during early startup phases.
### 🚀 Current Project Status
The Windows Port is now functionally on par with the original Mac version, including the Software List feature. The UI is pixel-perfect and the launch engine is robust against common Windows path and argument pitfalls.
---
## Handover Notes for Future Agents
### 1. UI Implementation Strategy (CRITICAL)
* **Custom Combo Boxes**: Do NOT attempt to use native `QComboBox::down-arrow` CSS for the blue ↕ icon. Windows Qt has rendering issues (white dots/flicker). We use a **stacked overlay** strategy:
* A `QWidget` container holds the `QComboBox`.
* A `QLabel` with `Qt.WA_TransparentForMouseEvents` is positioned on top of the combo's right edge.
* This label has an opaque background (#3b7ee1) to mask the native Windows combo indicator dots.
* **Alignment**: The global fixed width for slot combos is **160px**. The arrow overlay is **20px** wide.
### 2. Adaptive Theming
* **Real-time Detection**: The app polls the Windows Registry every 2 seconds for theme changes.
* **Centralized CSS**: Most UI colors are defined in `apply_premium_theme` using Python f-strings, allowing instant restyling of all common widgets.
* **Persistent IDs**: Labels and special widgets use `setObjectName` to inherit styles from the global stylesheet, avoiding contrast issues during theme transitions.
### 3. State Management
* **Sub-Slot Popups**: Tracked via `self.active_popup` in `AmpleMainWindow`.
* **Toggle Logic**: Uses `time.time()` threshold (0.3s) and `id(data)` check in `show_sub_slots()` to prevent the "immediate reopening" bug when clicking the hamburger button to close the popup.
### 4. Data Processing
* `data_manager.py` handles the heavy lifting of parsing original Ample `.plist` files.
* Slot changes trigger `self.refresh_ui()`, which rebuilds the dynamic slots layout from scratch to handle nested slot dependencies.
### 5. Known Mantras
* **Visual Parity is King**: Every margin, font size (mostly 11px/12px), and color was cross-referenced with macOS high-res screenshots.
* **Authorship**: This Windows Port is a collaboration between **anomixer** and **Antigravity**.
+36
View File
@@ -0,0 +1,36 @@
@echo off
setlocal
title Ample Windows Launcher
echo ========================================
echo Ample - Windows Port Auto Launcher
echo ========================================
:: Check for Python
python --version >nul 2>&1
if %errorlevel% neq 0 (
echo [ERROR] Python not found! Please install Python 3.9 or newer.
pause
exit /b 1
)
:: Install/Update dependencies
echo [1/2] Checking dependencies...
pip install -r requirements.txt --quiet
if %errorlevel% neq 0 (
echo [ERROR] Failed to install requirements.
pause
exit /b 1
)
:: Run the application
echo [2/2] Launching Ample...
python main.py
if %errorlevel% neq 0 (
echo.
echo [INFO] Application exited with error code %errorlevel%.
pause
)
endlocal
+105
View File
@@ -0,0 +1,105 @@
# AmpleWin - Windows Port (Legacy Apple Emulator Frontend)
[English](README.md) | [繁體中文](README_tw.md)
This is a precision port of the macOS native [Ample](https://github.com/ksherlock/ample) project to the Windows platform.
> [!TIP]
> **Linux User?** Check out the [AmpleLinux](../AmpleLinux/) Port.
![](screenshot.png)
> [!IMPORTANT]
> **Current Version Support**: Updated to stay in sync with the latest version of Ample (macOS) resources and also MAME latest binary.
## 🍎 Ample (macOS) vs. AmpleWin (Windows) Comparison
| Feature | Ample (macOS Native) | AmpleWin (Windows Optimized) | Optimization & Notes |
| :--- | :--- | :--- | :--- |
| **Language** | Objective-C (Cocoa) | **Python 3.11 + PySide6 (Qt)** | Independent development, **zero changes to Mac source code** |
| **Installation** | .dmg Image / Homebrew | **Portable (+ .bat Auto-Config)** | One-click setup for Python and dependencies via `AmpleWin.bat` |
| **UI** | Native macOS Components | **1:1 Pixel-Perfect QSS Replica** | Replicates Mac aesthetic, with **Adaptive Light/Dark Theme** support |
| **MAME Integration** | Built-in Custom Core or Self-selected | **Official Core Download or Self-selected** | Users can update MAME independently or download via app |
| **Machine Selection** | Supports Default Bookmark | **Full Session Persistence (Auto-Load)** | Auto-loads last used machine state without manual bookmarking |
| **Software List Perf** | Synchronous Loading (Full XML) | **Deferred Loading** | **Major Optimization**: Instant machine switching, loads on search |
| **Software Search UI** | Standard Pop-up List | **Smart Overlay Search** | Supports real-time search and full descriptive names without UI shifts |
| **ROM Download** | Supports Auto-Download | **High-Speed Failover Engine** | **Major Optimization**: Multi-server failover (callapple + mdk.cab) |
| **Validation** | Relies on Static .plist | **Live Parameter Validation** | **Major Optimization**: Validates against MAME to prevent launch crashes |
| **Video Support** | Metal / OpenGL / BGFX | **BGFX / OpenGL / Vulkan / D3D11 / D3D12** | Optimized for Windows with multi-generational DirectX support |
| **Networking** | Apple VMNet Framework | **Npcap (WinPcap) / PCAP** | Standard networking via Npcap (no root fix needed) |
| **Operating Logic** | Sticky Software Selection | **Sticky Software Selection** | Preserves compatible software selection when switching machines |
## 🌟 Key Features
### 🍏 Faithful Mac Experience (Feature Parity)
* **Visual Precision**:
* **Resolution Scaling**: Precision support for **Window 1x-4x** modes with machine-specific aspect ratio heuristics (e.g., Apple II 4:3 correction).
* **Square Pixels**: Specialized integer-scaling mode (e.g., 1120x768) to eliminate pixel shimmering.
* **Software Library**:
* **Smart Filtering**: Automatically identifies supported media types (flop1, flop2, cass...) to match machine capabilities.
* **Search Overlay**: Integrated Mac-style search with auto-completion and full descriptive names.
* **Compatibility Check**: Options marked as `disabled` in property lists (e.g. incompatible SCSI cards) are now correctly grayed out and unselectable, matching Mac behavior.
* **Advanced Slot Emulation**: Full support for nested sub-slots (e.g. SCSI cards). Automatically initializes default devices (CD-ROM/Hard Disk) upon card selection.
* **ROM Management**:
* **Search Filter**: Real-time searching in the ROM manager window to quickly find system firmwares.
* **Download Failover**: Automatic multi-server acquisition (callapple + mdk.cab) with transparent failover for maximum stability.
* **Extended Library**: Expanded support for PowerBook Duo 280, Pravetz 8C, TK3000, and more.
* **Shared Directory**: Full parity with the Mac version, allowing direct host-to-emulator file sharing via the `-share_directory` argument. (Includes click-to-browse support).
* **VGM Support (Advanced)**: Since modern MAME removed VGM support, AmpleWin implements a robust background workflow to download and configure the **MAME-VGM Mod (v0.280)**. It uses a non-destructive extraction process (`mame-vgm.exe`) to preserve your main MAME core while restoring high-fidelity music recording.
### 🪟 Windows-Specific Optimizations
* **Performance**:
* **Concurrent Downloading**: Multi-threaded system for high-speed ROM acquisition.
* **Clean Workspace**: All MAME side-car files (nvram, cfg, sta) are strictly isolated within the `mame` directory.
* **Deferred XML Loading**: Major optimization for instant machine switching and search response.
* **UI Enhancements**:
* **Adaptive Theme**: Real-time synchronization with Windows Light/Dark system theme.
* **Command Preview**: Real-time 4-line console preview to monitor exactly what parameters are being passed to MAME.
* **Smart Path Handling**: Native file/folder selectors for A/V output and Shared Directories, with automatic path normalization (converting `/` to `\`) for maximum Windows compatibility.
* **Flexible Backend**: Full support for BGFX, OpenGL, Vulkan, and **DirectX 11/12** out of the box.
## 🛠️ Quick Start
1. **Launch Ample**:
Enter the **`AmpleWin`** folder and run **`AmpleWin.bat`**.
* The script will check the Python environment, install dependencies, and start the app.
2. **Fast Deployment**:
* Go to **⚙️ Settings** -> Click **Download MAME** to auto-configure the emulator.
* Click **🎮 ROMs** to download system firmware.
* Click **📂 Ample Dir** to quickly open the local application folder.
3. **Start playing**:
* Select a machine from the left panel.
* **Double-click** the machine name or click **Launch MAME** to start.
## 🌐 Networking (Advanced)
To simulate networking hardware like **Uthernet II**, Windows requires [Npcap](https://nmap.org/npcap/) (install in "WinPcap compatible mode"). Unlike the macOS version, no "Fix Permissions" is required as Windows handles hardware access via drivers.
## 📂 Project Structure
| File/Directory | Description |
| :--- | :--- |
| **`AmpleWin.bat`** | **Start Here**. Auto-setup script (installs Python deps & runs app). |
| `build_exe.bat` | **Packaging**. Creates a `dist` portable EXE folder using PyInstaller. |
| `main.py` | Application entry point, UI rendering, and event loop. |
| `data_manager.py` | Parser for `.plist` machine definitions and MAME `.xml` software lists. |
| `mame_launcher.py` | Command-line builder and process manager. |
| `rom_manager.py` | Management and multi-threaded downloading of system ROMs. |
| `mame_downloader.py` | Automated MAME / VGM Mod downloader and extractor. |
| `mame/` | Isolated directory for MAME executable, ROMs, and config files. |
| `Agent.md` | Development log and session history. |
## 📦 Building from Source (Portable EXE)
If you want to create a standalone executable for distribution:
1. Run `build_exe.bat` in the `AmpleWin` directory.
2. The script will automatically install PyInstaller, package the application, and copy necessary resources.
3. The output will be in `AmpleWin\dist\AmpleWin`.
4. Copy the entire `AmpleWin` folder to any location. It is fully **portable** and does not require Python to run.
## 📝 Acknowledgments
* Original macOS version developer: [Kelvin Sherlock](https://github.com/ksherlock)
* **Windows Port Developers: anomixer + Antigravity**: Dedicated to providing the ultimate Apple II / Macintosh emulation experience on Windows.
+105
View File
@@ -0,0 +1,105 @@
# AmpleWin - Windows Port (Legacy Apple Emulator Frontend)
[English](README.md) | [繁體中文](README_tw.md)
這是一個將 macOS 原生 [Ample](https://github.com/ksherlock/ample) 專案精準移植至 Windows 平台的版本。
> [!TIP]
> **Linux 使用者?** 請參考 [AmpleLinux](../AmpleLinux/) Linux 移植版。
![](screenshot.png)
> [!IMPORTANT]
> **版本支援說明**:目前已同步支援至 Ample (macOS) 最新版本之資源定義以及 MAME 最新版本之核心。
## 🍎 Ample (macOS) vs. AmpleWin (Windows) 完整對照表
| 功能項目 | Ample (macOS 原生版) | AmpleWin (Windows 優化版) | 優化重點與說明 |
| :--- | :--- | :--- | :--- |
| **程式語言** | Objective-C (Cocoa) | **Python 3.11 + PySide6 (Qt)** | 獨立開發,**完全沒動到 Mac 版原始碼** |
| **安裝方式** | .dmg 映像檔 / Homebrew | **免安裝綠色版 (+ .bat 自動配置)** | 透過 `AmpleWin.bat` 一鍵搞定 Python 與依賴 |
| **UI 介面** | macOS 原生組件 | **1:1 像素級 QSS 複刻** | 在 Windows 實現 **Adaptive 自適應淺色/深色主題** |
| **MAME 整合** | 內建客製版核心,或自選客製版本 | **額外下載官方版核心,或自選客製版本** | 使用者可隨時更新 MAME 核心,若無亦可選擇額外下載 |
| **初始機器選擇** | 支援預設書籤 (需手動設定) | **全自動持久化 (自動載入上次狀態)** | Mac 版需設為預設書籤,Windows 版則全自動開啟 |
| **軟體清單效能** | 同步加載 (解析完整 XML) | **延遲遞增加載 (Deferred Loading)** | **重大優化**:切換機器秒開,搜尋才加載,效能更佳 |
| **軟體搜尋 UI** | 標準列表 (Pop-up) | **智慧搜尋疊層 (Smart Overlay)** | 支援即時搜尋、全名顯示,且不推擠其他 UI 元素 |
| **ROM 下載** | 支援自動下載 (補齊缺失) | **高效能 Failover 引擎** | **重大優化**:支援多伺服器切換 (callapple + mdk.cab) |
| **參數驗證** | 依賴 .plist 靜態定義 | **動態查詢驗證 (Live Validation)** | **重大優化**:自動與 MAME 比對,防止指令報錯崩潰 |
| **Video 支援** | Metal / OpenGL / BGFX | **BGFX / OpenGL / Vulkan / D3D11 / D3D12** | 針對 Windows 環境最佳化,支援多代 DirectX 核心 |
| **網路連線** | Apple VMNet Framework | **Npcap (WinPcap) / PCAP** | 使用標準 Npcap 即可上網 (無須權限修復) |
| **操作邏輯** | 支援黏性軟體選取 | **支援黏性軟體選取 (Sticky Selection)** | 兩平台皆支援切換機型後保留相容的軟體選取 |
## 🌟 核心功能
### 🍏 忠實還原 Mac 體驗 (功能對齊)
* **視覺精準度**:
* **高解析度縮放**:精準支援 **Window 1x-4x** 模式,並內建機器專屬的比例啟發邏輯(如 Apple II 4:3 修正)。
* **正方形像素 (Square Pixels)**:支援特製的整數縮放模式 (如 1120x768),消除像素閃爍。
* **軟體資料庫**:
* **智慧過濾**:自動識別機器支援的媒體類型 (flop1, flop2, cass...),確保啟動參數與原始硬體一致。
* **搜尋遮罩**:完整還原 Mac 版的搜尋介面,支援自動補完與完整網格化清單顯示。
* **相容性檢查**:自動偵測屬性表中的 `disabled` 標記(如不相容的 SCSI 卡),並正確以灰色顯示不可選,與 Mac 行為一致。
* **進階槽位模擬**:完整支援嵌套子槽位(如 SCSI 卡)。在選中卡片後自動初始化預設設備(如 ID 1 CD-ROM, ID 6 Hard Disk)。
* **ROM 管理**:
* **搜尋過濾**:ROM 管理器視窗中新增即時搜尋功能,方便快速查詢系統韌體。
* **下載 Failover**:多伺服器自動獲取 (callapple + mdk.cab),主伺服器失敗時自動切換,確保最高穩定性。
* **擴展支援**:新增 Macintosh PowerBook Duo 280, Pravetz 8C, TK3000 //e 等機型。
* **共享目錄 (Shared Directory)**:與 Mac 版功能完全對齊,支援透過 `-share_directory` 直接在主機與模擬器間共享檔案 (支援點擊輸入框瀏覽)。
* **VGM 錄音支援 (進階)**:由於現代 MAME 已移除 VGM 支援,AmpleWin 實作了強韌的自動化工作流,可下載並平行配置 **MAME-VGM Mod (v0.280)**。透過非破壞性的解壓技術(保留原本的 `mame.exe` 並另存為 `mame-vgm.exe`),在不影響主核心的情況下完美還原錄音功能。
### 🪟 Windows 專屬優化與增強
* **效能優化**:
* **併發下載系統**:多線程加速 ROM 下載,大幅縮短初始配置時間。
* **零雜訊 Workspace**:所有的 MAME 產出紀錄 (nvram, cfg, sta) 嚴格隔離在 `mame` 內。
* **延遲載入 (Deferred Loading)**:大幅優化軟體清單載入速度,切換機器與搜尋皆可瞬間反應。
* **UI 增強**:
* **適配主題**:即時同步 Windows 系統的深/淺色模式。
* **指令即時預覽**:底部的 4 行式 Console 欄位,可即時監控傳送給 MAME 的所有參數細節。
* **智慧路徑處理**:針對 A/V 輸出及共享目錄欄位提供原生的檔案/目錄選擇器,並自動執行路徑正規化 (將 `/` 轉為 `\`) 以確保與 Windows 的最佳相容性。
* **彈性後端支援**:領先支援 BGFX、OpenGL、Vulkan 以及 Windows 專屬的 **DirectX 11/12**。
## 🛠️ 快速開始
1. **啟動 Ample**:
進入 **`AmpleWin`** 資料夾,執行 **`AmpleWin.bat`**。
* 腳本會自動檢查 Python 環境、安裝依賴套件並啟動程式。
2. **快速部署**:
* 前往 **⚙️ Settings** -> 點擊 **Download MAME** 以自動配置模擬器。
* 點擊主介面的 **🎮 ROMs** 以補齊系統韌體。
* 點擊 **📂 Ample Dir** 可快速開啟程式安裝目錄。
3. **開始體驗**:
* 從左側列表中選擇想要的機器。
* **雙擊** 機器名稱或點擊右下角的 **Launch MAME** 即可啟動。
## 🌐 網路功能 (進階項目)
若要在模擬器中使用 **Uthernet II** 等網路卡硬體,在 Windows 環境下需要安裝 [Npcap](https://nmap.org/npcap/) (安裝時請勾選 "WinPcap compatible mode")。與 macOS 版本不同,Windows 是透過網卡驅動程式處理硬體存取,因此不需要額外的「權限修復 (Fix Permissions)」程序。
## 📂 Project Structure (專案結構)
| 檔案/目錄 | 說明 |
| :--- | :--- |
| **`AmpleWin.bat`** | **啟動腳本**。自動安裝依賴套件並執行主程式。 |
| `build_exe.bat` | **打包腳本**。使用 PyInstaller 建立無須 Python 的可攜式 EXE。 |
| `main.py` | 應用程式入口,處理 UI 渲染與主要邏輯。 |
| `data_manager.py` | 負責解析 `.plist` 機器定義檔與 MAME `.xml` 軟體列表。 |
| `mame_launcher.py` | MAME 指令建構器與執行序管理器。 |
| `rom_manager.py` | 系統 ROM 的管理與多執行緒下載引擎。 |
| `mame_downloader.py` | 自動化 MAME 核心與 VGM Mod 下載解壓工具。 |
| `mame/` | 隔離的 MAME 工作目錄,存放執行檔、ROMs 與設定檔。 |
| `Agent.md` | 開發日誌與任務記錄。 |
## 📦 打包發布版 (Portable EXE)
如果你想將程式打包成無需 Python 環境的可執行檔:
1. 執行 `AmpleWin` 資料夾下的 `build_exe.bat`。
2. 腳本會自動安裝 PyInstaller 並打包應用程式,同時複製必要的資源檔。
3. 打包完成後的程式位於 `AmpleWin\dist\AmpleWin`。
4. 將整個 `AmpleWin` 資料夾複製到任何位置即可執行,它是完全**可攜式 (Portable)** 的。
## 📝 致謝
* 原始 macOS 版本開發者: [Kelvin Sherlock](https://github.com/ksherlock)
* **Windows Port 開發者: anomixer + Antigravity**:致力於在 Windows 生態系中提供最極致的 Apple II / Macintosh 模擬體驗。
+59
View File
@@ -0,0 +1,59 @@
@echo off
setlocal
cd /d "%~dp0"
echo [AmpleWin] Building standalone EXE...
:AskPyInstaller
where pyinstaller >nul 2>nul
if %errorlevel% neq 0 (
echo.
echo [INFO] PyInstaller not found. Installing...
pip install pyinstaller
if %errorlevel% neq 0 (
echo [ERROR] Failed to install PyInstaller.
pause
exit /b 1
)
)
echo.
echo [0/2] Generating Application Icon...
python make_icon.py
echo.
echo [1/2] Converting main.py to EXE...
rem --noconfirm: overwrite output directory without asking
rem --onedir: create a directory with exe and dependencies (easier for debugging)
rem --windowed: no console window (for final release)
rem --name: name of the executable
rem --clean: clean cache
pyinstaller --noconfirm --onedir --windowed --clean --name "AmpleWin" --icon "app_icon.ico" main.py
if %errorlevel% neq 0 (
echo [ERROR] Build failed!
pause
exit /b 1
)
echo.
echo [2/2] Copying necessary assets...
rem Copy Resource directory from ..\Ample\Resources
rem We need to copy ..\Ample\Resources to dist\AmpleWin\Ample\Resources
if not exist "dist\AmpleWin\Ample\Resources" mkdir "dist\AmpleWin\Ample\Resources"
echo Copying Resources...
xcopy /E /I /Y "..\Ample\Resources\*.*" "dist\AmpleWin\Ample\Resources\" >nul
echo.
echo [SUCCESS] Build complete!
echo The standalone application is located in: AmpleWin\dist\AmpleWin\AmpleWin.exe
echo.
echo Cleaning up build artifacts...
if exist "build" rmdir /s /q "build"
if exist "AmpleWin.spec" del "AmpleWin.spec"
pause
+141
View File
@@ -0,0 +1,141 @@
import xml.etree.ElementTree as ET
import os
import plistlib
class DataManager:
def __init__(self, resources_path, hash_path=None):
self.resources_path = resources_path
self.hash_path = hash_path
self.models = self.load_plist('models.plist')
self.roms = self.load_plist('roms.plist')
self.machine_cache = {}
self.software_cache = {}
def load_plist(self, filename):
path = os.path.join(self.resources_path, filename)
if not os.path.exists(path):
print(f"DEBUG: DataManager failed to find: {path}")
return None
with open(path, 'rb') as f:
return plistlib.load(f)
def get_machine_description(self, machine_name):
if machine_name in self.machine_cache:
return self.machine_cache[machine_name]
desc = self.load_plist(f'{machine_name}.plist')
if desc:
self.machine_cache[machine_name] = desc
return desc
def get_software_lists(self, machine_name):
desc = self.get_machine_description(machine_name)
if not desc or 'software' not in desc:
return []
results = []
for item in desc['software']:
xml_file = None
filter_val = None
if isinstance(item, str):
xml_file = item
elif isinstance(item, dict):
xml_file = item.get('name')
filter_val = item.get('filter')
elif isinstance(item, list) and len(item) >= 1:
xml_file = item[0]
if len(item) >= 2:
filter_val = item[1]
if xml_file:
# Ensure .xml extension
if not xml_file.endswith(".xml"):
xml_file += ".xml"
list_name = xml_file.replace(".xml", "")
software_items = self.load_software_xml(xml_file)
# We always append to results if the XML exists,
# even if items are empty (to show the header at least)
if xml_file in self.software_cache:
filtered_items = software_items
if filter_val:
# Improved comma-aware filtering
filtered_items = []
for s in software_items:
comp = s.get('compatibility')
if not comp:
filtered_items.append(s)
else:
if filter_val in comp.split(','):
filtered_items.append(s)
results.append({
'name': list_name,
'description': self.software_cache[xml_file]['description'],
'items': filtered_items
})
return results
def load_software_xml(self, xml_file):
if xml_file in self.software_cache:
return self.software_cache[xml_file]['items']
if not self.hash_path:
return []
path = os.path.join(self.hash_path, xml_file)
if not os.path.exists(path):
return []
try:
tree = ET.parse(path)
root = tree.getroot()
list_desc = root.attrib.get('description', xml_file.replace(".xml", ""))
items = []
for sw in root.findall('software'):
sw_name = sw.attrib.get('name')
sw_desc = sw.find('description')
sw_desc_text = sw_desc.text if sw_desc is not None else sw_name
# Check for compatibility
compatibility = None
for sharedfeat in sw.findall('sharedfeat'):
if sharedfeat.attrib.get('name') == 'compatibility':
compatibility = sharedfeat.attrib.get('value')
break
items.append({
'name': sw_name,
'description': sw_desc_text,
'compatibility': compatibility
})
# Sort items by description
items.sort(key=lambda x: x['description'].lower())
self.software_cache[xml_file] = {
'description': list_desc,
'items': items
}
return items
except Exception as e:
print(f"Error parsing software XML {xml_file}: {e}")
return []
def get_flat_machines(self, models=None):
if models is None:
models = self.models
machines = []
for model in models:
if 'value' in model and model['value']:
machines.append({
'name': model['value'],
'description': model.get('description', model['value'])
})
if 'children' in model:
machines.extend(self.get_flat_machines(model['children']))
return machines
+2492
View File
File diff suppressed because it is too large. Load diff
+37
View File
@@ -0,0 +1,37 @@
from PIL import Image
import os
import sys
def create_ico(source_png, output_ico):
print(f"Opening source: {source_png}")
try:
img = Image.open(source_png)
except Exception as e:
print(f"Error opening image: {e}")
return False
# Windows icon sizes
icon_sizes = [(256, 256), (128, 128), (64, 64), (48, 48), (32, 32), (16, 16)]
print(f"Saving icon to: {output_ico}")
try:
img.save(output_ico, format='ICO', sizes=icon_sizes)
print("Success!")
return True
except Exception as e:
print(f"Error saving ICO: {e}")
return False
if __name__ == "__main__":
src = r"..\Ample\Assets.xcassets\AppIcon.appiconset\icon-1024.png"
dst = "app_icon.ico"
# Check if source exists
if not os.path.exists(src):
print(f"Source file not found: {src}")
sys.exit(1)
if create_ico(src, dst):
sys.exit(0)
else:
sys.exit(1)
+140
View File
@@ -0,0 +1,140 @@
import os
import requests
import subprocess
from PySide6.QtCore import QThread, Signal
class MameDownloadWorker(QThread):
progress = Signal(int, int)
finished = Signal(bool, str)
status = Signal(str)
def __init__(self, dest_dir):
super().__init__()
self.dest_dir = dest_dir
# MAME official self-extracting EXE - Updated to 0.286
self.url = "https://github.com/mamedev/mame/releases/download/mame0286/mame0286b_x64.exe"
def run(self):
try:
self.status.emit("Downloading MAME installer...")
response = requests.get(self.url, stream=True, timeout=60, allow_redirects=True)
response.raise_for_status()
total_size = int(response.headers.get('content-length', 0))
# Use official filename from URL
filename = self.url.split('/')[-1]
exe_path = os.path.join(self.dest_dir, filename)
os.makedirs(self.dest_dir, exist_ok=True)
downloaded = 0
with open(exe_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=65536):
if chunk:
f.write(chunk)
downloaded += len(chunk)
self.progress.emit(downloaded, total_size)
self.status.emit("Opening installer...")
# Use os.startfile to run the self-extractor on Windows
os.startfile(exe_path)
self.finished.emit(True, exe_path)
except Exception as e:
self.status.emit(f"Error: {str(e)}")
self.finished.emit(False, str(e))
class VgmModDownloadWorker(QThread):
progress = Signal(int, int)
finished = Signal(bool, str)
status = Signal(str)
def __init__(self, dest_dir):
super().__init__()
self.dest_dir = dest_dir
def run(self):
# Try multiple URLs for VGM support
urls = [
"https://vgmrips.net/programs/creators/MAME0280_bin64_2025-11-16.7z",
"https://github.com/anomixer/ample/raw/mame-vgm/MAME0280_bin64_2025-11-16.7z",
"https://github.com/anomixer/ample/blob/mame-vgm/MAME0280_bin64_2025-11-16.7z?raw=true"
]
last_error = ""
success = False
archive_path = ""
try:
for url in urls:
try:
self.status.emit(f"Downloading MAME VGM Mod...")
response = requests.get(url, stream=True, timeout=60, allow_redirects=True)
response.raise_for_status()
total_size = int(response.headers.get('content-length', 0))
filename = "mame_vgm_mod.7z"
archive_path = os.path.join(self.dest_dir, filename)
os.makedirs(self.dest_dir, exist_ok=True)
downloaded = 0
with open(archive_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=65536):
if chunk:
f.write(chunk)
downloaded += len(chunk)
self.progress.emit(downloaded, total_size)
success = True
break
except Exception as e:
last_error = str(e)
continue
if not success:
self.finished.emit(False, f"Failed to download from all mirrors. Last error: {last_error}")
return
self.status.emit("Extracting VGM Mod...")
# Create a temporary directory for extraction to avoid overwriting existing mame.exe
temp_extract_dir = os.path.join(self.dest_dir, "_vgm_temp")
os.makedirs(temp_extract_dir, exist_ok=True)
# Extract mame.exe to the temporary directory
extract_cmd = ["7z", "e", archive_path, "mame.exe", "-o" + temp_extract_dir, "-y"]
try:
subprocess.run(extract_cmd, check=True, capture_output=True)
except (subprocess.CalledProcessError, FileNotFoundError):
# Fallback to common Program Files path if 7z not in PATH
pf_7z = r"C:\Program Files\7-Zip\7z.exe"
if os.path.exists(pf_7z):
extract_cmd[0] = pf_7z
subprocess.run(extract_cmd, check=True, capture_output=True)
else:
raise Exception("7-Zip (7z.exe) not found. Please install it to extract the VGM Mod.")
# Move and rename extracted mame.exe to mame-vgm.exe in the main dest_dir
extracted_mame = os.path.join(temp_extract_dir, "mame.exe")
target_vgm_exe = os.path.join(self.dest_dir, "mame-vgm.exe")
if os.path.exists(extracted_mame):
if os.path.exists(target_vgm_exe):
os.remove(target_vgm_exe)
os.rename(extracted_mame, target_vgm_exe)
# Clean up temporary directory and archive
try:
if os.path.exists(temp_extract_dir):
import shutil
shutil.rmtree(temp_extract_dir)
except Exception:
pass
if os.path.exists(archive_path):
os.remove(archive_path)
self.finished.emit(True, target_vgm_exe)
except Exception as e:
self.status.emit(f"Error: {str(e)}")
self.finished.emit(False, str(e))
+108
View File
@@ -0,0 +1,108 @@
import subprocess
import os
import re
class MameLauncher:
def __init__(self):
self.mame_path = "mame"
self.working_dir = "."
self.valid_slots_cache = {}
def get_valid_slots(self, machine):
if machine in self.valid_slots_cache:
return self.valid_slots_cache[machine]
if not os.path.exists(self.mame_path) and self.mame_path != "mame":
return None
try:
cmd = [self.mame_path, machine, "-listslots"]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=5)
slots = set()
lines = result.stdout.splitlines()
# MAME -listslots has a header: "SYSTEM SLOT NAME SLOT OPTIONS"
# We want the second column.
for line in lines:
line = line.strip()
if not line or line.startswith("---") or "SLOT NAME" in line:
continue
parts = line.split()
# If the line starts with the machine name, the slot name is in index 1.
# If it's a sub-slot (starting with whitespace, now stripped), it's in index 0.
if line.startswith(machine) and len(parts) >= 2:
slots.add(parts[1])
elif len(parts) >= 1:
slots.add(parts[0])
self.valid_slots_cache[machine] = slots
return slots
except Exception as e:
print(f"Error getting slots for {machine}: {e}")
return None
def get_valid_media(self, machine):
cache_key = f"{machine}_media"
if cache_key in self.valid_slots_cache:
return self.valid_slots_cache[cache_key]
if not os.path.exists(self.mame_path) and self.mame_path != "mame":
return None
try:
cmd = [self.mame_path, machine, "-listmedia"]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=5)
media_types = set()
lines = result.stdout.splitlines()
# Extract common brief names like flop1, cass, etc inside brackets
for line in lines:
if "(" in line and ")" in line:
match = re.search(r'\((\w+)\)', line)
if match:
media_types.add(match.group(1))
self.valid_slots_cache[cache_key] = media_types
return media_types
except Exception:
return None
def build_args(self, machine, slots=None, media=None, soft_list_args=None, extra_options=None):
args = [machine]
if soft_list_args:
for sl in soft_list_args:
args.append(sl)
args.append("-skip_gameinfo")
if slots:
for slot_name, option in slots.items():
if option and not slot_name.startswith(':'):
# Pass the slot argument regardless of base machine validation
args.extend([f"-{slot_name}", option])
if media:
for media_type, path in media.items():
if path and not media_type.startswith(':'):
# Pass the media argument regardless of base machine validation
args.extend([f"-{media_type}", path])
if extra_options:
for opt in extra_options:
args.append(opt)
return args
def launch(self, machine, slots=None, media=None, soft_list_args=None, extra_options=None, alt_exe=None):
args = self.build_args(machine, slots, media, soft_list_args, extra_options)
exe = alt_exe if alt_exe else self.mame_path
full_cmd = [exe] + args
print(f"Launching: {subprocess.list2cmdline(full_cmd)}")
try:
return subprocess.Popen(full_cmd, cwd=self.working_dir)
except Exception as e:
print(f"Error launching MAME: {e}")
return None
+2
View File
@@ -0,0 +1,2 @@
PySide6
requests
+100
View File
@@ -0,0 +1,100 @@
import os
import requests
import plistlib
from PySide6.QtCore import QObject, Signal, QRunnable, QThreadPool
class DownloadSignals(QObject):
progress = Signal(int, int) # current, total
finished = Signal(str, bool) # value, success
status = Signal(str)
class DownloadWorker(QRunnable):
def __init__(self, urls, dest_path, value):
super().__init__()
self.urls = urls if isinstance(urls, list) else [urls]
self.dest_path = dest_path
self.value = value
self.signals = DownloadSignals()
self._is_cancelled = False
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
def cancel(self):
self._is_cancelled = True
def run(self):
last_error = "No URLs provided"
for url in self.urls:
try:
if self._is_cancelled: return
# For small files (ROMs), direct download is much faster than streaming
response = requests.get(url, headers=self.headers, timeout=20)
response.raise_for_status()
os.makedirs(os.path.dirname(self.dest_path), exist_ok=True)
if self._is_cancelled: return
with open(self.dest_path, 'wb') as f:
f.write(response.content)
self.signals.finished.emit(self.value, True)
return # Success!
except Exception as e:
last_error = str(e)
continue # Try next URL
# If we get here, all URLs failed
if os.path.exists(self.dest_path):
try: os.remove(self.dest_path)
except: pass
self.signals.status.emit(f"Error: {last_error}")
self.signals.finished.emit(self.value, False)
class RomManager(QObject):
def __init__(self, resources_path, roms_dir):
super().__init__()
self.resources_path = resources_path
self.roms_dir = roms_dir
self.base_urls = [
"https://www.callapple.org/roms/",
"https://mdk.cab/download/split/"
]
self.rom_list = self.load_rom_list()
def load_rom_list(self):
path = os.path.join(self.resources_path, "roms.plist")
if not os.path.exists(path):
return []
with open(path, 'rb') as f:
return plistlib.load(f)
def get_rom_status(self):
status_list = []
for rom in self.rom_list:
value = rom['value']
# Check for zip, 7z or folder
found = False
for ext in ['zip', '7z']:
path = os.path.join(self.roms_dir, f"{value}.{ext}")
if os.path.exists(path):
found = True
break
if not found:
# Check for unzipped folder
path = os.path.join(self.roms_dir, value)
if os.path.isdir(path):
found = True
status_list.append({
'value': value,
'description': rom['description'],
'exists': found
})
return status_list
def get_download_url(self, value, ext='zip'):
return f"{self.base_url}{value}.{ext}"
Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

+103
View File
@@ -0,0 +1,103 @@
# Pull Request: Fix missing ROM definitions and suggest updated download URL
## 🔍 Symptom
When selecting certain machines in Ample—specifically the **Macintosh PowerBook Duo 280**, **PowerBook Duo 280c**, **Pravetz 8C/82/8M**, and **TK3000 //e**—the application reports missing firmwares. However, these ROMs cannot be found or downloaded through the built-in firmware manager because they are missing from the `roms.plist` definitions, despite being correctly referenced in `models.plist`.
## 🎯 Objective
This PR fixes this discrepancy by adding the missing ROM entries to `Ample/Resources/roms.plist`. It ensures that all machines currently supported by the model definitions can actually be used by allowing the UI to identify and acquire their necessary firmwares. Additionally, we include a suggestion for the download source to improve overall reliability.
---
## 🛠️ Changes in `Ample/Resources/roms.plist`
The following system ROMs were defined in `models.plist` but missing from the firmware management list, preventing users from identifying or downloading required files via the UI.
### 1. Macintosh Additions
* **Target**: After `macpd270c` (around line 1636).
* **Added**: `macpd280` (Macintosh PowerBook Duo 280).
* **Reason**: Consistency with the already present `macpd280c`.
### 2. Apple II Clone & Sub-system Additions
* **Target**: After `ym2608` (around line 2488).
* **Added**:
* `prav8c` (Pravetz 8C)
* `prav82` (Pravetz 82)
* `prav8m` (Pravetz 8M)
* `tk3000` (TK3000 //e)
* `prav8ckb` (Pravetz 8C Keyboard)
* **Reason**: These machines are functional in the core but currently report firmwares as "Not Specified" or "Download Failed" due to missing plist descriptors.
---
## 📝 Proposed XML Snippets
### Location 1: PowerBook Duo Series
```xml
<dict>
<key>value</key>
<string>macpd280</string>
<key>description</key>
<string>Macintosh PowerBook Duo 280</string>
</dict>
```
### Location 2: Apple II Clones & Peripherals
```xml
<dict>
<key>value</key>
<string>prav8c</string>
<key>description</key>
<string>Pravetz 8C</string>
</dict>
<dict>
<key>value</key>
<string>tk3000</string>
<key>description</key>
<string>TK3000 //e</string>
</dict>
<dict>
<key>value</key>
<string>prav82</string>
<key>description</key>
<string>Pravetz 82</string>
</dict>
<dict>
<key>value</key>
<string>prav8m</string>
<key>description</key>
<string>Pravetz 8M</string>
</dict>
<dict>
<key>value</key>
<string>prav8ckb</string>
<key>description</key>
<string>Pravetz 8C Keyboard</string>
</dict>
```
---
## 🌐 Download URL Suggestion
Currently, Ample relies on `callapple.org`. During testing for the Windows port, we observed that:
* `callapple.org` successfully covers the **PowerBook Duo 280/280c** ROMs.
* However, it **lacks coverage** for some Apple II clones such as the **Pravetz** series and **TK3000 //e**.
Therefore, we suggest adding:
**`https://mdk.cab/download/split/`**
as a secondary/fallback URL. It provides complete coverage for these clones and more modern MAME split sets, ensuring a 100% success rate for the systems that are missing on the primary server.
You might also consider implementing a selectable URL list (similar to the **AmpleWin** port) that allows users to pick their preferred source (e.g., mdk.cab or callapple) or automatically failover between them for maximum reliability.
---
## 🎨 About the AmpleWin Port
This PR is submitted in conjunction with the development of **AmpleWin**, a precision Windows port of your project. You can explore the project and its detailed documentation here:
* Project Home: **[https://github.com/anomixer/ample](https://github.com/anomixer/ample)**
* Windows Subdirectory & README: **[https://github.com/anomixer/ample/tree/master/AmpleWin](https://github.com/anomixer/ample/tree/master/AmpleWin)**
Our goal is to achieve **near 100% UI fidelity** and feature parity for Windows users. To maintain a clean integration, all Windows-specific logic, scripts, and binaries are strictly isolated within the `AmpleWin/` subdirectory. We strive to keep the upstream root directory and resources untouched. We are only proposing these changes to `Ample/Resources/roms.plist` because they are functionally essential to allow all machines in the library to be fully "bootable" via the UI for all users.
Thanks for your consideration.
---
*Note: This PR content was prepared by Antigravity AI as part of the AmpleWin Windows port project.*
+37
View File
@@ -0,0 +1,37 @@
# Pull Request: Add native Windows (AmpleWin) and Linux (AmpleLinux) ports
This PR introduces full support for **Windows** and **Linux** platforms, expanding Ample from a macOS-exclusive tool to a cross-platform frontend.
To ensure stability and avoid conflicts with the existing macOS codebase, the new ports are contained in their own dedicated directories (`AmpleWin/` and `AmpleLinux/`) while keeping the root structure clean.
### � Isolation & Safety
**I have NOT touched any of your original macOS code.** The only file modified in the root directory is `README.md`, simply to add links to the new Windows/Linux ports.
You can freely modify these links to point to your own repository structure if you choose to merge this.
### �🚀 Key Features
#### 🪟 Windows Port (`AmpleWin/`)
* **Launcher**: `AmpleWin.bat` script for easy startup.
* **Portable**: Designed to work as a portable app without complex installation.
* **Docs**: Includes detailed installation and usage instructions (English + Traditional Chinese).
#### 🐧 Linux Port (`AmpleLinux/`)
* **One-Click Setup**: `AmpleLinux.sh` automatically creates a virtual environment (`venv`) and installs dependencies (`PySide6`, etc.) on the first run.
* **Desktop Integration**: Includes a `build_elf.sh` script using PyInstaller to create a standalone binary. It also generates and installs a `.desktop` file for proper application menu integration.
* **Smart Detection**:
* Auto-detects system dark/light mode (GNOME/KDE).
* Detects if MAME is missing and offers `snap install mame` on Ubuntu.
* Checks for and installs missing build tools (`binutils`/`objcopy`) required by PyInstaller.
* Fixes common audio permission issues (ALSA group check).
### 📝 Documentation
* Updated the root `README.md` to reference the new ports.
* Added comprehensive `README.md` and `README_tw.md` inside each port directory.
### ✅ Verification
I have tested these changes on:
* **Windows 10/11**: Confirmed launch and ROM management.
* **Ubuntu 22.04 / 24.04**: Verified `AmpleLinux.sh` setup, `build_elf.sh` binary generation, and icon integration.
Hope this helps expand the user base for Ample! Thanks for the great original work.
+3 -1
View File
@@ -2,7 +2,9 @@
A slightly more user-friendly front-end for using MAME as an Apple II emulator. Requires Mac OS X 10.14+
> Windows users might want to check out [AmpleWin](https://github.com/anomixer/ample/tree/master/AmpleWin)
> Windows users might want to check out [AmpleWin](https://github.com/anomixer/ample/tree/master/AmpleWin).
> Linux users might want to check out [AmpleLinux](https://github.com/anomixer/ample/tree/master/AmpleLinux).
![](screenshots/2021-07-01.png)