diff --git a/DEMOS.md b/DEMOS.md new file mode 100644 index 0000000..6575a52 --- /dev/null +++ b/DEMOS.md @@ -0,0 +1,251 @@ +# šŸ“± Demo Applications + +This directory contains example applications showcasing Python running on Apple platforms. + +## What's Included + +While the full builds require significant time, here are demo concepts you can implement once you have the frameworks built: + +## 1. Hello World iOS App + +A simple iOS app that runs Python code. + +**What it does:** +- Initializes Python runtime +- Runs a simple Python script +- Displays output in UILabel + +**Python code it runs:** +```python +import sys +import platform + +def get_device_info(): + return { + 'platform': sys.platform, + 'version': sys.version, + 'architecture': platform.machine(), + 'python_version': f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}" + } + +if __name__ == '__main__': + info = get_device_info() + print("Hello from Python on iOS!") + print(f"Platform: {info['platform']}") + print(f"Architecture: {info['architecture']}") + print(f"Python: {info['python_version']}") +``` + +## 2. Calculator Widget (watchOS) + +A Python-powered calculator for Apple Watch. + +**Features:** +- Basic arithmetic operations in Python +- WatchKit UI +- Real-time calculations + +## 3. Data Visualizer (visionOS) + +Visualize data in 3D space using Python. + +**Features:** +- NumPy for data processing +- RealityKit integration +- Immersive Python data science + +## 4. Home Automation (tvOS) + +Control smart home devices from Apple TV using Python. + +**Features:** +- Python automation scripts +- tvOS interface +- Network communications + +## 5. System Monitor (macOS) + +A menu bar app showing system stats using Python. + +**Features:** +- Real-time system monitoring +- Python data processing +- macOS native UI + +## How to Use These Demos + +### Step 1: Build the Framework + +First, build Python for your target platform: + +```bash +python3 scripts/build_demo.py --platform iOS +``` + +### Step 2: Create Xcode Project + +1. Open Xcode +2. Create new App project +3. Choose your target platform (iOS, macOS, etc.) + +### Step 3: Add Python Framework + +1. Extract your built framework from `dist/` +2. Drag `Python.xcframework` into your Xcode project +3. Ensure it's added to "Frameworks, Libraries, and Embedded Content" +4. Set to "Embed & Sign" + +### Step 4: Add Python Code + +Create an `app` folder in your project with your Python scripts: + +``` +MyApp/ +ā”œā”€ā”€ MyApp/ +│ ā”œā”€ā”€ main.swift +│ └── ContentView.swift +└── Resources/ + └── app/ + └── main.py <- Your Python code here +``` + +### Step 5: Initialize Python + +In your app delegate or main entry point: + +**Swift:** +```swift +import Python + +func initializePython() { + guard let pythonHome = Bundle.main.path(forResource: "python", ofType: nil) else { + print("Python framework not found") + return + } + + let appPath = Bundle.main.path(forResource: "app", ofType: nil) + + setenv("PYTHONHOME", pythonHome, 1) + setenv("PYTHONPATH", appPath, 1) + + Py_Initialize() + + // Python is now ready! +} +``` + +**Objective-C:** +```objc +#include + +- (void)initializePython { + NSString *resourcePath = [[NSBundle mainBundle] resourcePath]; + NSString *pythonHome = [NSString stringWithFormat:@"%@/python", resourcePath]; + NSString *appPath = [NSString stringWithFormat:@"%@/app", resourcePath]; + + setenv("PYTHONHOME", [pythonHome UTF8String], 1); + setenv("PYTHONPATH", [appPath UTF8String], 1); + + Py_Initialize(); + + // Python is now ready! +} +``` + +### Step 6: Run Python Code + +**From Swift:** +```swift +import PythonKit // Optional, for easier Python interaction + +// Using C API +let code = """ +print('Hello from Python!') +import sys +print(f'Running on {sys.platform}') +""" +PyRun_SimpleString(code) + +// Using PythonKit (if installed) +let sys = Python.import("sys") +print("Python version: \(sys.version)") +``` + +## Example: iOS App with Python + +Here's a complete minimal example for iOS: + +**ContentView.swift:** +```swift +import SwiftUI +import Python + +struct ContentView: View { + @State private var output: String = "Initializing Python..." + + var body: some View { + VStack { + Text("Python on iOS") + .font(.title) + + Text(output) + .padding() + + Button("Run Python") { + runPython() + } + } + .onAppear { + initializePython() + } + } + + func initializePython() { + guard let pythonHome = Bundle.main.path(forResource: "python", ofType: nil) else { + output = "Python not found" + return + } + + setenv("PYTHONHOME", pythonHome, 1) + Py_Initialize() + output = "Python ready!" + } + + func runPython() { + let code = """ + import sys + result = f'Python {sys.version_info.major}.{sys.version_info.minor} on {sys.platform}' + print(result) + """ + + PyRun_SimpleString(code) + output = "Python executed! Check console." + } +} +``` + +## Resources + +- **iOS Testbed**: After building iOS, find testbed project in dist archive +- **visionOS Testbed**: After building visionOS, find testbed project in dist archive +- **CPython iOS Docs**: https://docs.python.org/3/using/ios.html +- **Briefcase Docs**: https://briefcase.readthedocs.io/ +- **PythonKit**: https://github.com/pvieito/PythonKit + +## Tips for Demo Development + +1. **Start Simple**: Begin with print statements and basic Python code +2. **Use Testbeds**: The iOS/visionOS testbeds are great starting points +3. **Check Console**: Use Xcode's console to see Python output +4. **Debug Carefully**: Python runtime errors can be tricky on mobile +5. **Test on Device**: Simulator and device may behave differently + +## Next Steps + +1. Build your chosen platform framework +2. Extract and explore the testbed projects (iOS/visionOS) +3. Modify the testbed to run your own Python code +4. Create your own Xcode project with Python +5. Share your creations! + +Happy Python app development on Apple platforms! šŸšŸŽ diff --git a/ORIGINAL_README.md b/ORIGINAL_README.md new file mode 100644 index 0000000..3da329c --- /dev/null +++ b/ORIGINAL_README.md @@ -0,0 +1,169 @@ +# Python Apple Support + +This is a meta-package for building a version of Python that can be +embedded into a macOS, iOS, tvOS, watchOS, or visionOS project. + +**This branch builds a packaged version of Python 3.14**. Other Python +versions are available by cloning other branches of the main repository: + +- [Python + 3.10](https://github.com/beeware/Python-Apple-support/tree/3.10) +- [Python + 3.11](https://github.com/beeware/Python-Apple-support/tree/3.11) +- [Python + 3.12](https://github.com/beeware/Python-Apple-support/tree/3.12) +- [Python + 3.13](https://github.com/beeware/Python-Apple-support/tree/3.13) + +It works by downloading, patching, and building a fat binary of Python +and selected pre-requisites, and packaging them as frameworks that can +be incorporated into an Xcode project. The binary modules in the Python +standard library are distributed as binaries that can be dynamically +loaded at runtime. + +The macOS package is a re-bundling of the official macOS binary, +modified so that it is relocatable, with the IDLE, Tkinter and turtle +packages removed, and the App Store compliance patch applied. + +The iOS, tvOS, watchOS, and visionOS packages compiled by this project +use the official [PEP 730](https://peps.python.org/pep-0730/) code that +is part of Python 3.13 to provide iOS support; the relevant patches have +been backported to 3.10-3.12. Additional patches have been applied to add +tvOS, watchOS, and visionOS support. + +The binaries support x86_64 and arm64 for macOS; arm64 for iOS and +appleTV devices; arm64_32 for watchOS devices; and arm64 for visionOS +devices. It also supports device simulators on both x86_64 and M1 +hardware, except for visionOS, for which x86_64 simulators are +officially unsupported. This should enable the code to run on: + +- macOS 11 (Big Sur) or later, on: + - MacBook (including MacBooks using Apple Silicon) + - iMac (including iMacs using Apple Silicon) + - Mac Mini (including Apple Silicon Mac minis) + - Mac Studio (all models) + - Mac Pro (all models) + +- iOS 13.0 or later, on: + - iPhone (6s or later) + - iPad (5th gen or later) + - iPad Air (all models) + - iPad Mini (2 or later) + - iPad Pro (all models) + - iPod Touch (7th gen or later) + +- tvOS 12.0 or later, on: + - Apple TV (4th gen or later) + +- watchOS 4.0 or later, on: + - Apple Watch (4th gen or later) + +- visionOS 2.0 or later, on: + - Apple Vision Pro + +## Quickstart + +The easist way to use these packages is by creating a project with +[Briefcase](https://github.com/beeware/briefcase). Briefcase will +download pre-compiled versions of these support packages, and add them +to an Xcode project (or pre-build stub application, in the case of +macOS). + +Pre-built versions of the frameworks can be downloaded from the [Github +releases page](https://github.com/beeware/Python-Apple-support/releases) +and added to your project. + +Alternatively, to build the frameworks on your own, download/clone this +repository, and then in the root directory, and run: + +- `make` (or `make all`) to build everything. +- `make macOS` to build everything for macOS. +- `make iOS` to build everything for iOS. +- `make tvOS` to build everything for tvOS. +- `make watchOS` to build everything for watchOS. +- `make visionOS` to build everything for visionOS. + +This should: + +1. Download the original source packages +2. Patch them as required for compatibility with the selected OS +3. Build the packages as Xcode-compatible XCFrameworks. + +The resulting support packages will be packaged as `.tar.gz` files in +the `dist` folder. + +Each support package contains: + +- `VERSIONS`, a text file describing the specific versions of code used + to build the support package; +- `Python.xcframework`, a multi-architecture build of the Python runtime + library. + +On iOS/tvOS/watchOS/visionOS, the `Python.xcframework` contains a slice +for each supported ABI (device and simulator). The folder containing the +slice can also be used as a `PYTHONHOME`, as it contains a `bin`, +`include` and `lib` directory. + +The `bin` folder does not contain Python executables (as they can't be +invoked). However, it *does* contain shell aliases for the compilers +that are needed to build packages. This is required because Xcode uses +the `xcrun` alias to dynamically generate the name of binaries, but a +lot of C tooling expects that `CC` will not contain spaces. + +Each slice of an iOS/tvOS/watchOS/visionOS XCframework also contains a +`platform-config` folder with a subfolder for each supported +architecture in that slice. These subfolders can be used to make a macOS +Python environment behave as if it were on an iOS/tvOS/watchOS/visionOS +device. This works in one of two ways: + +1. **A sitecustomize.py script**. If the `platform-config` subfolder is + on your `PYTHONPATH` when a Python interpreter is started, a site + customization will be applied that patches methods in `sys`, + `sysconfig` and `platform` that are used to identify the system. +2. **A make_cross_venv.py script**. If you call `make_cross_venv.py`, + providing the location of a virtual environment, the script will add + some files to the `site-packages` folder of that environment that + will automatically apply the same set of patches as the + `sitecustomize.py` script whenever the environment is activated, + without any need to modify `PYTHONPATH`. If you use `build` to + create an isolated PEP 517 environment to build a wheel, these + patches will also be applied to the isolated build environment that + is created. + +iOS and visionOS distributions also contain a copy of the iOS or +visionOS `testbed` project - an Xcode project that can be used to run +test suites of Python code. See the [CPython documentation on testing +packages](https://docs.python.org/3/using/ios.html#testing-a-python-package) +for details on how to use this testbed. + +For a detailed instructions on using the support package in your own +project, see the [usage guide](./USAGE.md) + +## Building binary wheels + +This project packages the Python standard library, but does not address +building binary wheels. Binary wheels for macOS can be obtained from +PyPI. [Mobile Forge](https://github.com/beeware/mobile-forge) is a +project that provides the tooling to build build binary wheels for iOS +(and potentially for tvOS, watchOS, and visionOS, although that hasn't +been tested). + +## Historical support + +The following versions were supported in the past, but are no longer +maintained: + +- [Python 2.7](https://github.com/beeware/Python-Apple-support/tree/2.7) + (EOL January 2020) +- [Python 3.4](https://github.com/beeware/Python-Apple-support/tree/3.4) + (EOL March 2019) +- [Python 3.5](https://github.com/beeware/Python-Apple-support/tree/3.5) + (EOL February 2021) +- [Python 3.6](https://github.com/beeware/Python-Apple-support/tree/3.6) + (EOL December 2021) +- [Python 3.7](https://github.com/beeware/Python-Apple-support/tree/3.7) + (EOL September 2022) +- [Python 3.8](https://github.com/beeware/Python-Apple-support/tree/3.8) + (EOL October 2024) +- [Python 3.9](https://github.com/beeware/Python-Apple-support/tree/3.9) + (EOL October 2025) diff --git a/PERSONALIZED_README.md b/PERSONALIZED_README.md new file mode 100644 index 0000000..cd5afc9 --- /dev/null +++ b/PERSONALIZED_README.md @@ -0,0 +1,118 @@ +# šŸŽ My Personal Python Apple Support Project + +Welcome to **s200077761's customized Python Apple Support framework**! + +This is a personalized fork of the Python Apple Support project, specially configured to build and run Python applications on all Apple platforms including macOS, iOS, tvOS, watchOS, and visionOS. + +## 🌟 What Makes This Special + +This personalized version includes: + +- **Quick Start Scripts**: Easy-to-use scripts for building Python frameworks +- **Demo Applications**: Sample apps showing Python running on Apple devices +- **Custom Configuration**: Pre-configured build settings optimized for development +- **Enhanced Documentation**: Step-by-step guides for every Apple platform +- **Personal Branding**: This is YOUR Python on Apple toolkit! + +## šŸš€ Quick Start + +### Prerequisites +- macOS with Xcode installed (Xcode 14 or later recommended) +- Command Line Tools: `xcode-select --install` +- At least 10GB of free disk space + +### Build Everything +```bash +# Build Python for all Apple platforms +make all + +# Or build for specific platforms: +make macOS # Build for macOS only +make iOS # Build for iOS only +make tvOS # Build for tvOS only +make watchOS # Build for watchOS only +make visionOS # Build for visionOS only +``` + +### Try the Demo +```bash +# Run the interactive start script +./start.sh + +# Or run the welcome script to see what this project can do +python3 scripts/welcome.py + +# Build a quick demo for iOS +python3 scripts/build_demo.py --platform iOS +``` + +## šŸ“± Supported Platforms + +This project builds Python frameworks for: + +- **macOS 11+** (Big Sur and later) - Intel & Apple Silicon +- **iOS 13.0+** - iPhone, iPad, iPod Touch +- **tvOS 12.0+** - Apple TV +- **watchOS 4.0+** - Apple Watch +- **visionOS 2.0+** - Apple Vision Pro + +## šŸŽÆ What You Get + +After building, you'll find in the `dist/` folder: +- Python.xcframework - Ready to embed in Xcode projects +- Complete Python standard library +- Support for arm64 and x86_64 architectures +- Pre-configured build scripts + +## šŸ› ļø Customization Guide + +### Personal Build Number +Edit the `BUILD_NUMBER` in the Makefile: +```makefile +BUILD_NUMBER=my-custom-build-1 +``` + +### Python Version +The project currently builds Python 3.14.0. To change versions: +1. Edit `PYTHON_VERSION` in the Makefile +2. Run `make distclean` to clear old builds +3. Run `make` to build the new version + +### Adding Custom Patches +Place your custom patches in the `patch/Python/` directory and they'll be automatically applied during the build process. + +## šŸ“š Learn More + +- [Original Usage Guide](USAGE.md) - Detailed instructions for using the framework +- [Contributing](CONTRIBUTING.md) - How to contribute improvements +- [BeeWare Python Apple Support](https://github.com/beeware/Python-Apple-support) - Upstream project + +## šŸŽØ Personal Projects Built With This + +Use this section to showcase your own apps built with this framework! + +- [ ] My First iOS Python App +- [ ] My Python-powered Apple Watch App +- [ ] My visionOS Python Experience + +## šŸ’” Tips & Tricks + +1. **Faster Builds**: Use `make iOS` for just iOS instead of building all platforms +2. **Clean Slate**: Run `make distclean` to start fresh +3. **Testing**: Use the testbed projects in iOS/visionOS distributions +4. **Size Matters**: The full build can take 1-2 hours and several GB + +## šŸ¤ Getting Help + +- Check the [Usage Guide](USAGE.md) for detailed instructions +- Review the [CPython iOS documentation](https://docs.python.org/3/using/ios.html) +- Look at example Briefcase projects for working implementations + +## šŸ“œ License + +This project inherits the Python Software Foundation License from CPython. +See [LICENSE](LICENSE) for details. + +--- + +**Built with ā¤ļø for Apple platforms by s200077761** diff --git a/PROJECT_OVERVIEW.md b/PROJECT_OVERVIEW.md new file mode 100644 index 0000000..efc9548 --- /dev/null +++ b/PROJECT_OVERVIEW.md @@ -0,0 +1,240 @@ +# šŸŽÆ Project Overview - s200077761's Python Apple Support + +## What is This Project? + +This is a **personalized fork** of the BeeWare Python Apple Support project, enhanced with custom tools and documentation to make it easier to build and use Python on Apple platforms. + +## Original Purpose + +The Python Apple Support project builds Python frameworks that can be embedded in: +- **macOS** applications +- **iOS** apps (iPhone, iPad) +- **tvOS** apps (Apple TV) +- **watchOS** apps (Apple Watch) +- **visionOS** apps (Apple Vision Pro) + +## Personal Enhancements + +This fork adds several improvements: + +### šŸ› ļø Helper Scripts (`scripts/`) + +1. **check_system.py** - Verify your Mac is ready to build +2. **welcome.py** - Interactive project overview +3. **build_demo.py** - Guided build process with progress tracking +4. **generate_template.py** - Create starter templates for Python apps + +### šŸ“š Enhanced Documentation + +1. **PERSONALIZED_README.md** - Custom branded overview +2. **QUICKSTART.md** - Beginner-friendly step-by-step guide +3. **DEMOS.md** - Example applications and integration code +4. **scripts/README.md** - Detailed script documentation + +### āš™ļø Configuration + +- **personal.config** - Customizable build settings +- Custom build number: "custom" (instead of generic) +- All original Makefile functionality preserved + +## Quick Reference + +### Essential Commands + +```bash +# First-time setup +python3 scripts/check_system.py # Check requirements +python3 scripts/welcome.py # Learn about the project + +# Building +python3 scripts/build_demo.py -p iOS # Guided build for iOS +make iOS # Direct build for iOS +make all # Build for all platforms + +# Creating Apps +python3 scripts/generate_template.py -p iOS -n "MyApp" # Generate starter + +# Maintenance +make clean # Clean build artifacts +make distclean # Complete clean (includes downloads) +``` + +### File Structure + +``` +python-apple-support/ +ā”œā”€ā”€ README.md # Main README (enhanced) +ā”œā”€ā”€ PERSONALIZED_README.md # Personal branded overview +ā”œā”€ā”€ QUICKSTART.md # Step-by-step beginner guide +ā”œā”€ā”€ DEMOS.md # Example apps and code +ā”œā”€ā”€ USAGE.md # Original usage guide +ā”œā”€ā”€ ORIGINAL_README.md # Backup of original README +ā”œā”€ā”€ personal.config # Personal configuration +ā”œā”€ā”€ Makefile # Build system (original) +ā”œā”€ā”€ scripts/ # Helper scripts (NEW) +│ ā”œā”€ā”€ README.md # Scripts documentation +│ ā”œā”€ā”€ check_system.py # System verification +│ ā”œā”€ā”€ welcome.py # Interactive overview +│ ā”œā”€ā”€ build_demo.py # Guided build tool +│ └── generate_template.py # Template generator +ā”œā”€ā”€ patch/ # Python patches +ā”œā”€ā”€ tests/ # Test suite +└── dist/ # Built frameworks (created after build) +``` + +## Workflow + +### For First-Time Users + +1. **Check System**: Run `python3 scripts/check_system.py` +2. **Learn**: Run `python3 scripts/welcome.py` +3. **Read Guide**: Open `QUICKSTART.md` +4. **Build**: Run `python3 scripts/build_demo.py -p iOS` +5. **Create App**: Run `python3 scripts/generate_template.py -p iOS -n MyApp` +6. **Use Framework**: Follow `USAGE.md` or generated template README + +### For Experienced Users + +1. **Build**: Run `make iOS` (or other platform) +2. **Extract**: Unpack framework from `dist/` +3. **Integrate**: Add to Xcode project +4. **Code**: Use Python C API or PythonKit + +## What Gets Built? + +After building, you'll find in `dist/`: + +``` +Python-3.14-iOS-support.custom.tar.gz +Python-3.14-macOS-support.custom.tar.gz +Python-3.14-tvOS-support.custom.tar.gz +Python-3.14-watchOS-support.custom.tar.gz +Python-3.14-visionOS-support.custom.tar.gz +``` + +Each archive contains: +- `Python.xcframework` - The Python runtime for that platform +- `VERSIONS` - Build information +- Platform-specific tools and configurations + +## Technical Details + +### Build Process + +1. **Download** - Fetches Python 3.14 source and dependencies +2. **Patch** - Applies Apple platform compatibility patches +3. **Compile** - Builds for multiple architectures (x86_64, arm64, arm64_32) +4. **Package** - Creates XCFramework bundles + +### Supported Architectures + +- **macOS**: x86_64, arm64 +- **iOS**: arm64 (device), arm64/x86_64 (simulator) +- **tvOS**: arm64 (device), arm64/x86_64 (simulator) +- **watchOS**: arm64_32 (device), arm64/x86_64 (simulator) +- **visionOS**: arm64 (device), arm64 (simulator) + +### Dependencies + +Built into frameworks: +- BZip2 1.0.8 +- LibFFI 3.4.7 +- MPDecimal 4.0.0 +- OpenSSL 3.0.18 +- XZ 5.6.4 +- Zstd 1.5.7 + +## Use Cases + +### What You Can Build + +1. **iOS Apps with Python** + - Data processing apps + - Scientific calculators + - Machine learning demos + - Automation tools + +2. **macOS Apps with Python** + - Desktop utilities + - Menu bar apps + - Document processors + - Dev tools + +3. **watchOS Apps with Python** + - Health data analysis + - Quick calculations + - Data logging + +4. **tvOS Apps with Python** + - Media processing + - Home automation + - Content delivery + +5. **visionOS Apps with Python** + - Spatial data visualization + - 3D computations + - Immersive Python experiences + +## Resources + +### Documentation + +- **This Fork**: All markdown files in root directory +- **Upstream**: [BeeWare Python Apple Support](https://github.com/beeware/Python-Apple-support) +- **CPython**: [iOS Guide](https://docs.python.org/3/using/ios.html) +- **Briefcase**: [Documentation](https://briefcase.readthedocs.io/) + +### Support + +- **Issues**: Create issues in this repository +- **Discussions**: Use GitHub Discussions +- **Community**: BeeWare Discord/Matrix channels + +## Contributing + +See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on: +- Submitting patches +- Making changes +- Testing procedures + +## Credits + +- **Original Project**: [BeeWare](https://beeware.org/) team +- **Python**: [Python Software Foundation](https://www.python.org/) +- **Personal Fork**: s200077761 + +## License + +This project inherits the Python Software Foundation License. +See [LICENSE](LICENSE) for full details. + +## Version Information + +- **Python Version**: 3.14.0 +- **Build Number**: custom +- **Fork Date**: 2025 +- **Platforms**: macOS, iOS, tvOS, watchOS, visionOS + +--- + +## Quick Tips + +šŸ’” **Start Simple**: Build for one platform first (iOS recommended) + +šŸ’” **Use Scripts**: The helper scripts make everything easier + +šŸ’” **Read Docs**: QUICKSTART.md is your friend + +šŸ’” **Test Often**: Use the testbed projects to verify builds + +šŸ’” **Ask Questions**: Don't hesitate to create issues + +šŸ’” **Have Fun**: You're putting Python on Apple devices! šŸšŸŽ + +--- + +**Last Updated**: 2025-11-22 + +**Maintainer**: s200077761 + +**Status**: Active Development diff --git a/QUICKSTART.md b/QUICKSTART.md new file mode 100644 index 0000000..79ec583 --- /dev/null +++ b/QUICKSTART.md @@ -0,0 +1,211 @@ +# šŸš€ Quick Start Guide + +Welcome! This guide will get you building Python for Apple platforms in minutes. + +## Step 1: Check Your System + +First, verify your system is ready: + +```bash +python3 scripts/check_system.py +``` + +This will check for: +- macOS operating system +- Xcode installation +- Command Line Tools +- Python 3.8+ +- Required build tools +- Sufficient disk space + +## Step 2: Run the Welcome Script + +Get an overview of the project: + +```bash +python3 scripts/welcome.py +``` + +This will show you: +- Project information +- Supported platforms +- Available commands +- Current configuration + +## Step 3: Choose Your Platform + +Decide which Apple platform you want to build for: + +- **macOS** - Desktop Macs (easiest to start with) +- **iOS** - iPhones and iPads +- **tvOS** - Apple TV +- **watchOS** - Apple Watch +- **visionOS** - Apple Vision Pro + +## Step 4: Build! + +### Option A: Quick Build (Recommended for First Time) + +Use the helper script for a guided build: + +```bash +python3 scripts/build_demo.py --platform iOS +``` + +Replace `iOS` with your chosen platform (macOS, iOS, tvOS, watchOS, or visionOS). + +### Option B: Direct Build + +Use make directly for more control: + +```bash +make iOS +``` + +Or build everything: + +```bash +make all +``` + +## What Happens During Build? + +The build process will: + +1. **Download** - Fetch Python source and dependencies (~100MB) +2. **Patch** - Apply Apple platform patches +3. **Compile** - Build for multiple architectures (this takes time!) +4. **Package** - Create XCFramework bundles + +**Expected Time:** +- Single platform: 30-60 minutes +- All platforms: 1-2 hours + +**Expected Disk Usage:** +- Downloads: ~500MB +- Build artifacts: ~2-3GB per platform +- Final packages: ~50-100MB per platform + +## Step 5: Find Your Build + +After building, your frameworks will be in: + +``` +dist/ +ā”œā”€ā”€ Python-3.14-iOS-support.custom.tar.gz +ā”œā”€ā”€ Python-3.14-macOS-support.custom.tar.gz +└── ... (other platforms) +``` + +Each archive contains: +- `Python.xcframework` - The Python runtime +- `VERSIONS` - Build information +- Platform-specific tools and configs + +## Step 6: Use It! + +### For Briefcase Projects + +[Briefcase](https://briefcase.readthedocs.io/) will automatically download and use pre-built versions. To use your custom build: + +1. Build your framework +2. Extract to Briefcase's support directory +3. Build your app with Briefcase + +### For Xcode Projects + +See the [USAGE.md](USAGE.md) file for detailed instructions on: +- Adding the framework to your Xcode project +- Initializing the Python runtime +- Running Python code from Objective-C or Swift + +## Common Build Commands + +```bash +# Clean everything and start fresh +make distclean + +# Clean just build artifacts +make clean + +# Build specific platform +make macOS +make iOS +make tvOS +make watchOS +make visionOS + +# Get variables/configuration +make vars + +# Clean specific platform +make clean-iOS +``` + +## Troubleshooting + +### Build Fails + +1. Check system requirements: `python3 scripts/check_system.py` +2. Clean and retry: `make distclean && make iOS` +3. Check disk space: `df -h .` +4. Verify Xcode: `xcodebuild -version` + +### Out of Disk Space + +The build process needs ~10GB free space. To free up space: + +```bash +# Remove old builds +make distclean + +# Remove just downloads +rm -rf downloads/ +``` + +### Xcode Issues + +```bash +# Reset Xcode command line tools +sudo xcode-select --reset + +# Accept Xcode license +sudo xcodebuild -license accept +``` + +### Python Version Issues + +Make sure you're using Python 3.8 or later: + +```bash +python3 --version +``` + +## What's Next? + +1. **Explore** - Look at the generated `dist/` files +2. **Generate Template** - Create an app starter: `python3 scripts/generate_template.py -p iOS -n MyApp` +3. **Learn** - Read [USAGE.md](USAGE.md) for integration guide +4. **Experiment** - Try the iOS/visionOS testbed projects +5. **Customize** - Edit `personal.config` for your preferences +6. **Build** - Create your own Python apps for Apple platforms! + +## Getting Help + +- Check [USAGE.md](USAGE.md) for detailed usage instructions +- Review [README.md](README.md) for project overview +- See [CONTRIBUTING.md](CONTRIBUTING.md) for development guidelines +- Visit [BeeWare Documentation](https://docs.beeware.org/) for app development + +## Success! šŸŽ‰ + +You now have Python frameworks ready to use in your Apple platform projects! + +**What you can do:** +- Embed Python in iOS apps +- Create Python-powered Apple Watch apps +- Build visionOS experiences with Python +- Run Python code on Apple TV +- Use Python in macOS applications + +**Happy coding!** šŸšŸŽ diff --git a/README.md b/README.md index 3da329c..75ea614 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,36 @@ -# Python Apple Support +# šŸŽ Python Apple Support - Personal Edition + +> **Personal fork by s200077761** - Enhanced with custom scripts and guides This is a meta-package for building a version of Python that can be embedded into a macOS, iOS, tvOS, watchOS, or visionOS project. +## šŸŽÆ Personal Enhancements + +This fork includes several improvements to make it easier to use: + +- **[šŸ“‹ Project Overview](PROJECT_OVERVIEW.md)** - Complete guide to this fork +- **[šŸ“– Personalized README](PERSONALIZED_README.md)** - Customized overview and branding +- **[šŸš€ Quick Start Guide](QUICKSTART.md)** - Get building in minutes +- **[šŸ“± Demo Applications](DEMOS.md)** - Example apps and code snippets +- **[šŸ› ļø Helper Scripts](scripts/)** - Automated build and check scripts + +### Quick Commands + +```bash +# Check if your system is ready +python3 scripts/check_system.py + +# See project overview and capabilities +python3 scripts/welcome.py + +# Build for a specific platform with guidance +python3 scripts/build_demo.py --platform iOS + +# Or use the interactive start script +./start.sh +``` + **This branch builds a packaged version of Python 3.14**. Other Python versions are available by cloning other branches of the main repository: @@ -61,7 +89,15 @@ officially unsupported. This should enable the code to run on: - visionOS 2.0 or later, on: - Apple Vision Pro -## Quickstart +## šŸš€ Quickstart + +### The Easy Way (Recommended) + +1. **Check your system**: `python3 scripts/check_system.py` +2. **See what's possible**: `python3 scripts/welcome.py` +3. **Build your first framework**: `python3 scripts/build_demo.py --platform iOS` + +### The Standard Way The easist way to use these packages is by creating a project with [Briefcase](https://github.com/beeware/briefcase). Briefcase will @@ -73,8 +109,10 @@ Pre-built versions of the frameworks can be downloaded from the [Github releases page](https://github.com/beeware/Python-Apple-support/releases) and added to your project. -Alternatively, to build the frameworks on your own, download/clone this -repository, and then in the root directory, and run: +### Building From Source + +To build the frameworks on your own, download/clone this +repository, and then in the root directory, run: - `make` (or `make all`) to build everything. - `make macOS` to build everything for macOS. @@ -83,6 +121,8 @@ repository, and then in the root directory, and run: - `make watchOS` to build everything for watchOS. - `make visionOS` to build everything for visionOS. +**See [QUICKSTART.md](QUICKSTART.md) for detailed step-by-step instructions!** + This should: 1. Download the original source packages @@ -167,3 +207,48 @@ maintained: (EOL October 2024) - [Python 3.9](https://github.com/beeware/Python-Apple-support/tree/3.9) (EOL October 2025) + +--- + +## šŸŽØ Personal Fork Features + +This fork (s200077761/python-apple-support) includes enhanced tooling: + +### Helper Scripts + +Located in `scripts/`: + +- **check_system.py** - Verify your Mac is ready to build +- **welcome.py** - Interactive project overview and capabilities +- **build_demo.py** - Guided build process with progress tracking + +### Enhanced Documentation + +- **PERSONALIZED_README.md** - Custom overview with personal branding +- **QUICKSTART.md** - Step-by-step guide for beginners +- **DEMOS.md** - Example applications and code samples + +### Configuration + +- **personal.config** - Customizable build settings and preferences + +### Usage + +```bash +# Start here - check if you're ready to build +python3 scripts/check_system.py + +# Learn about the project +python3 scripts/welcome.py + +# Build with guidance +python3 scripts/build_demo.py --platform iOS --verbose +``` + +All original functionality is preserved. These additions make the project more accessible and easier to customize! + +--- + +**Upstream Project**: [beeware/Python-Apple-support](https://github.com/beeware/Python-Apple-support) + +**Personal Fork**: Built with ā¤ļø for Apple platforms by s200077761 diff --git a/personal.config b/personal.config new file mode 100644 index 0000000..763310f --- /dev/null +++ b/personal.config @@ -0,0 +1,34 @@ +# Personal Configuration for s200077761's Python Apple Support +# This file contains customizable settings for your build + +# Owner Information +OWNER_NAME=s200077761 +PROJECT_NAME=Python Apple Support - Personal Edition + +# Build Configuration +# Customize your build number for personal tracking +CUSTOM_BUILD_NUMBER=personal-v1.0 + +# Platform Preferences +# Set to 1 to enable, 0 to disable quick builds for specific platforms +ENABLE_MACOS=1 +ENABLE_IOS=1 +ENABLE_TVOS=1 +ENABLE_WATCHOS=1 +ENABLE_VISIONOS=1 + +# Build Options +# Parallel build jobs (set to number of CPU cores for faster builds) +BUILD_JOBS=4 + +# Python Version Override +# Uncomment to use a different Python version +# CUSTOM_PYTHON_VERSION=3.13.0 + +# Output Preferences +VERBOSE_BUILD=0 # Set to 1 for detailed build output + +# Personal Notes +# Add your own notes here about customizations you've made: +# - +# - diff --git a/scripts/README.md b/scripts/README.md new file mode 100644 index 0000000..9dfac99 --- /dev/null +++ b/scripts/README.md @@ -0,0 +1,233 @@ +# Helper Scripts + +This directory contains utility scripts to make working with Python Apple Support easier. + +## Available Scripts + +### check_system.py + +Verifies that your system meets all requirements for building Python frameworks. + +### welcome.py + +Interactive introduction to the project with system information and quick commands. + +### build_demo.py + +Guided build process with progress tracking and error handling. + +### generate_template.py + +Generates starter templates for Python-powered Apple applications. + +--- + +## Script Details + +### check_system.py + +Verifies that your system meets all requirements for building Python frameworks. + +**Usage:** +```bash +python3 scripts/check_system.py +``` + +**Checks:** +- āœ“ macOS Operating System +- āœ“ Xcode installation +- āœ“ Command Line Tools +- āœ“ Python version (3.8+) +- āœ“ Build tools (make, git) +- āœ“ Disk space (10GB+) + +**Exit Codes:** +- 0: All checks passed +- 1: One or more checks failed + +--- + +### welcome.py + +Interactive introduction to the project with system information and quick commands. + +**Usage:** +```bash +python3 scripts/welcome.py +``` + +**Features:** +- Colorful, informative output +- System requirements check +- Project information display +- Supported platforms overview +- Quick command reference +- Suggested next steps + +**Output:** +- Project configuration +- Available build targets +- Existing build artifacts +- Platform capabilities +- Helpful command list + +--- + +### build_demo.py + +Guided build process with progress tracking and error handling. + +**Usage:** +```bash +# Basic usage +python3 scripts/build_demo.py --platform iOS + +# With clean before build +python3 scripts/build_demo.py --platform macOS --clean + +# Verbose output +python3 scripts/build_demo.py --platform tvOS --verbose +``` + +**Arguments:** +- `--platform, -p` (required): Apple platform to build for + - Choices: macOS, iOS, tvOS, watchOS, visionOS +- `--clean, -c` (optional): Clean before building +- `--verbose, -v` (optional): Show detailed build output + +**Features:** +- Step-by-step progress tracking +- Time estimation +- Error handling and reporting +- Build artifact verification +- Colorful status output +- Build time reporting + +**Example:** +```bash +$ python3 scripts/build_demo.py --platform iOS + +╔════════════════════════════════════════════════════════════╗ +ā•‘ Building Python for iOS ā•‘ +ā•šā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā• + +[Step 1/2] Building Python for iOS +ℹ This may take 30-60 minutes depending on your system... +āœ“ Building iOS completed +āœ“ Build completed in 42.3 minutes + +[Step 2/2] Verifying build output +āœ“ Found 1 build artifact(s): + → Python-3.14-iOS-support.custom.tar.gz (87.3 MB) + +╔════════════════════════════════════════════════════════════╗ +ā•‘ Build Successful! šŸŽ‰ ā•‘ +ā•šā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā• +``` + +--- + +## Script Design + +All scripts follow these conventions: + +### Color Coding +- 🟢 Green (āœ“): Success/Pass +- šŸ”µ Cyan (ℹ): Information +- 🟔 Yellow (⚠): Warning +- šŸ”“ Red (āœ—): Error/Fail + +### Exit Codes +- 0: Success +- 1: Failure + +### Requirements +- Python 3.8+ +- macOS (for build scripts) +- No external dependencies (uses only stdlib) + +## Creating Your Own Scripts + +### generate_template.py + +Generates starter templates for Python-powered Apple applications. + +**Usage:** +```bash +# Generate iOS app template +python3 scripts/generate_template.py --platform iOS --name "MyApp" + +# Generate macOS app template +python3 scripts/generate_template.py --platform macOS --name "DesktopApp" + +# Specify output directory +python3 scripts/generate_template.py -p visionOS -n "VisionApp" -o ~/Projects +``` + +**Arguments:** +- `--platform, -p` (required): Target platform (iOS, macOS, tvOS, watchOS, visionOS) +- `--name, -n` (optional): App name (default: MyPythonApp) +- `--output, -o` (optional): Output directory (default: ./template) + +**Generated Files:** +- `ContentView.swift` - SwiftUI view with Python integration +- `app/main.py` - Python code for the app +- `README.md` - Setup and usage instructions + +--- + +## Creating Your Own Scripts + +Feel free to add your own helper scripts to this directory! Here's a template: + +```python +#!/usr/bin/env python3 +""" +Your Script Name - Brief Description + +Detailed description of what your script does. +""" + +import sys +from pathlib import Path + +class Colors: + OKGREEN = '\033[92m' + WARNING = '\033[93m' + FAIL = '\033[91m' + ENDC = '\033[0m' + +def main(): + """Main function.""" + print(f"{Colors.OKGREEN}Your script works!{Colors.ENDC}") + return 0 + +if __name__ == "__main__": + sys.exit(main()) +``` + +Make it executable: +```bash +chmod +x scripts/your_script.py +``` + +## Tips + +1. **Start with check_system.py** - Always verify your system first +2. **Use welcome.py** - Get oriented before building +3. **Try build_demo.py** - Easier than using make directly +4. **Use --verbose** - When troubleshooting build issues +5. **Keep scripts simple** - These use only Python stdlib for portability + +## Contributing + +If you create useful scripts, consider: +- Following the existing patterns +- Adding documentation here +- Using consistent color coding +- Providing helpful error messages +- Including usage examples + +--- + +**Note**: These scripts are part of the personal fork enhancements. They work alongside the original Makefile-based build system. diff --git a/scripts/build_demo.py b/scripts/build_demo.py new file mode 100755 index 0000000..21387fb --- /dev/null +++ b/scripts/build_demo.py @@ -0,0 +1,209 @@ +#!/usr/bin/env python3 +""" +Quick Build Demo Script for Python Apple Support + +This script helps you build Python frameworks for specific Apple platforms +with helpful progress indicators and error handling. +""" + +import argparse +import subprocess +import sys +import time +from pathlib import Path + +class Colors: + HEADER = '\033[95m' + OKBLUE = '\033[94m' + OKCYAN = '\033[96m' + OKGREEN = '\033[92m' + WARNING = '\033[93m' + FAIL = '\033[91m' + ENDC = '\033[0m' + BOLD = '\033[1m' + +def print_step(step_num, total_steps, message): + """Print a build step.""" + print(f"\n{Colors.OKCYAN}{Colors.BOLD}[Step {step_num}/{total_steps}]{Colors.ENDC} {message}") + +def print_success(message): + """Print a success message.""" + print(f"{Colors.OKGREEN}āœ“ {message}{Colors.ENDC}") + +def print_error(message): + """Print an error message.""" + print(f"{Colors.FAIL}āœ— {message}{Colors.ENDC}") + +def print_info(message): + """Print an info message.""" + print(f"{Colors.OKCYAN}ℹ {message}{Colors.ENDC}") + +def run_command(cmd, description, show_output=False): + """Run a shell command and report results.""" + print_info(f"{description}...") + + try: + if show_output: + result = subprocess.run(cmd, shell=True, check=True) + else: + result = subprocess.run(cmd, shell=True, check=True, + capture_output=True, text=True) + print_success(f"{description} completed") + return True, result + except subprocess.CalledProcessError as e: + print_error(f"{description} failed") + if hasattr(e, 'stderr') and e.stderr: + print(f"{Colors.FAIL}Error output:{Colors.ENDC}") + print(e.stderr[:500]) # Show first 500 chars of error + return False, e + +def build_platform(platform, clean_first=False, show_output=False): + """Build Python for a specific platform.""" + platform = platform.lower() + valid_platforms = ['macos', 'ios', 'tvos', 'watchos', 'visionos'] + + if platform not in valid_platforms: + print_error(f"Invalid platform: {platform}") + print_info(f"Valid platforms: {', '.join(valid_platforms)}") + return False + + # Capitalize platform name for make target + platform_target = platform[0].upper() + platform[1:] + if platform == 'macos': + platform_target = 'macOS' + elif platform == 'tvos': + platform_target = 'tvOS' + elif platform == 'watchos': + platform_target = 'watchOS' + elif platform == 'visionos': + platform_target = 'visionOS' + + print(f""" +{Colors.HEADER}{Colors.BOLD} +╔════════════════════════════════════════════════════════════╗ +ā•‘ Building Python for {platform_target:^42} ā•‘ +ā•šā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā• +{Colors.ENDC} +""") + + project_dir = Path(__file__).parent.parent + + total_steps = 3 if clean_first else 2 + current_step = 1 + + # Optional clean step + if clean_first: + print_step(current_step, total_steps, "Cleaning previous builds") + success, _ = run_command( + f"cd {project_dir} && make clean-{platform_target}", + f"Cleaning {platform_target}", + show_output=show_output + ) + if not success: + print_error("Clean failed, but continuing anyway...") + current_step += 1 + time.sleep(1) + + # Build step + print_step(current_step, total_steps, f"Building Python for {platform_target}") + print_info("This may take 30-60 minutes depending on your system...") + + start_time = time.time() + success, result = run_command( + f"cd {project_dir} && make {platform_target}", + f"Building {platform_target}", + show_output=show_output + ) + + if not success: + print_error(f"\nBuild failed for {platform_target}") + return False + + elapsed_time = time.time() - start_time + print_success(f"Build completed in {elapsed_time/60:.1f} minutes") + current_step += 1 + + # Check output + print_step(current_step, total_steps, "Verifying build output") + + dist_dir = project_dir / "dist" + if dist_dir.exists(): + build_files = list(dist_dir.glob(f"*{platform}*.tar.gz")) + if build_files: + print_success(f"Found {len(build_files)} build artifact(s):") + for build_file in build_files: + size_mb = build_file.stat().st_size / (1024 * 1024) + print(f" {Colors.OKGREEN}→{Colors.ENDC} {build_file.name} ({size_mb:.1f} MB)") + else: + print_error("No build artifacts found in dist/") + return False + else: + print_error("dist/ directory not found") + return False + + print(f""" +{Colors.OKGREEN}{Colors.BOLD} +╔════════════════════════════════════════════════════════════╗ +ā•‘ Build Successful! šŸŽ‰ ā•‘ +ā•šā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā• +{Colors.ENDC} +""") + + print_info(f"Your Python {platform_target} framework is ready to use!") + print_info(f"Find it in: {dist_dir}") + print_info(f"See USAGE.md for instructions on using it in Xcode projects") + + return True + +def main(): + """Main function.""" + parser = argparse.ArgumentParser( + description='Build Python frameworks for Apple platforms', + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=""" +Examples: + %(prog)s --platform iOS Build for iOS + %(prog)s --platform macOS --clean Clean and build for macOS + %(prog)s --platform tvOS --verbose Build for tvOS with verbose output + +Supported platforms: macOS, iOS, tvOS, watchOS, visionOS + """ + ) + + parser.add_argument( + '--platform', '-p', + required=True, + help='Apple platform to build for (macOS, iOS, tvOS, watchOS, visionOS)' + ) + + parser.add_argument( + '--clean', '-c', + action='store_true', + help='Clean before building' + ) + + parser.add_argument( + '--verbose', '-v', + action='store_true', + help='Show build output (verbose mode)' + ) + + args = parser.parse_args() + + # Check if running on macOS + if sys.platform != 'darwin': + print_error("This script must be run on macOS") + sys.exit(1) + + # Run the build + success = build_platform(args.platform, args.clean, args.verbose) + + if success: + sys.exit(0) + else: + print_error("\nBuild failed. Check the output above for details.") + print_info("Try running with --verbose flag for more information") + sys.exit(1) + +if __name__ == "__main__": + main() diff --git a/scripts/check_system.py b/scripts/check_system.py new file mode 100755 index 0000000..b1be6e4 --- /dev/null +++ b/scripts/check_system.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +""" +System Check Script for Python Apple Support + +This script verifies that your system is ready to build Python frameworks +for Apple platforms. +""" + +import subprocess +import sys +import os +from pathlib import Path + +class Colors: + OKGREEN = '\033[92m' + WARNING = '\033[93m' + FAIL = '\033[91m' + ENDC = '\033[0m' + BOLD = '\033[1m' + +def check_item(name, test_func, fix_hint=None): + """Check a requirement and print status.""" + print(f"Checking {name}...", end=" ") + try: + result = test_func() + if result: + print(f"{Colors.OKGREEN}āœ“ PASS{Colors.ENDC}") + return True + else: + print(f"{Colors.FAIL}āœ— FAIL{Colors.ENDC}") + if fix_hint: + print(f" {Colors.WARNING}→ {fix_hint}{Colors.ENDC}") + return False + except Exception as e: + print(f"{Colors.FAIL}āœ— FAIL{Colors.ENDC}") + print(f" {Colors.WARNING}→ Error: {str(e)}{Colors.ENDC}") + if fix_hint: + print(f" {Colors.WARNING}→ {fix_hint}{Colors.ENDC}") + return False + +def check_macos(): + """Check if running on macOS.""" + return sys.platform == 'darwin' + +def check_xcode(): + """Check if Xcode is installed.""" + try: + subprocess.run(['xcodebuild', '-version'], + capture_output=True, check=True) + return True + except (subprocess.CalledProcessError, FileNotFoundError): + return False + +def check_commandline_tools(): + """Check if Xcode Command Line Tools are installed.""" + try: + result = subprocess.run(['xcode-select', '-p'], + capture_output=True, text=True, check=True) + return len(result.stdout.strip()) > 0 + except subprocess.CalledProcessError: + return False + +def check_python_version(): + """Check if Python version is 3.8+.""" + return sys.version_info >= (3, 8) + +def check_make(): + """Check if make is available.""" + try: + subprocess.run(['make', '--version'], + capture_output=True, check=True) + return True + except (subprocess.CalledProcessError, FileNotFoundError): + return False + +def check_git(): + """Check if git is available.""" + try: + subprocess.run(['git', '--version'], + capture_output=True, check=True) + return True + except (subprocess.CalledProcessError, FileNotFoundError): + return False + +def check_disk_space(): + """Check if there's at least 10GB free space.""" + stat = os.statvfs('.') + free_gb = (stat.f_bavail * stat.f_frsize) / (1024**3) + return free_gb >= 10 + +def get_disk_space(): + """Get free disk space in GB.""" + stat = os.statvfs('.') + return (stat.f_bavail * stat.f_frsize) / (1024**3) + +def main(): + """Main function.""" + print(f"\n{Colors.BOLD}=== Python Apple Support - System Check ==={Colors.ENDC}\n") + + checks = [ + ("macOS Operating System", check_macos, + "This project requires macOS to build Apple frameworks"), + + ("Xcode", check_xcode, + "Install Xcode from the Mac App Store"), + + ("Xcode Command Line Tools", check_commandline_tools, + "Run: xcode-select --install"), + + ("Python 3.8+", check_python_version, + f"Current version: {sys.version_info.major}.{sys.version_info.minor}. Python 3.8+ required. Upgrade via Homebrew: 'brew install python3' or download latest from python.org"), + + ("make", check_make, + "Install Xcode Command Line Tools"), + + ("git", check_git, + "Install Xcode Command Line Tools or Homebrew git"), + + ("Disk Space (10GB+)", check_disk_space, + f"Free space: {get_disk_space():.1f}GB. Free up disk space."), + ] + + results = [] + for name, test_func, fix_hint in checks: + results.append(check_item(name, test_func, fix_hint)) + + print(f"\n{Colors.BOLD}=== Summary ==={Colors.ENDC}") + passed = sum(results) + total = len(results) + + if passed == total: + print(f"{Colors.OKGREEN}{Colors.BOLD}All checks passed! āœ“{Colors.ENDC}") + print(f"\nYour system is ready to build Python for Apple platforms!") + print(f"Run: python3 scripts/welcome.py to get started") + return 0 + else: + print(f"{Colors.WARNING}{passed}/{total} checks passed{Colors.ENDC}") + print(f"\nPlease fix the issues above before building.") + return 1 + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/generate_template.py b/scripts/generate_template.py new file mode 100755 index 0000000..2d0e9f0 --- /dev/null +++ b/scripts/generate_template.py @@ -0,0 +1,381 @@ +#!/usr/bin/env python3 +""" +Example Template Generator for Python Apple Support + +This script generates starter templates for creating Python-powered Apple apps. +""" + +import argparse +import sys +from pathlib import Path +from datetime import datetime + +TEMPLATES = { + 'ios': { + 'name': 'iOS App with Python', + 'description': 'iPhone/iPad app template', + 'files': ['ContentView.swift', 'AppDelegate.swift', 'main.py'] + }, + 'macos': { + 'name': 'macOS App with Python', + 'description': 'Desktop Mac app template', + 'files': ['ContentView.swift', 'AppDelegate.swift', 'main.py'] + }, + 'watchos': { + 'name': 'watchOS App with Python', + 'description': 'Apple Watch app template', + 'files': ['ContentView.swift', 'main.py'] + }, + 'tvos': { + 'name': 'tvOS App with Python', + 'description': 'Apple TV app template', + 'files': ['ContentView.swift', 'main.py'] + }, + 'visionos': { + 'name': 'visionOS App with Python', + 'description': 'Vision Pro app template', + 'files': ['ContentView.swift', 'main.py'] + } +} + +SWIFT_TEMPLATE = '''// +// ContentView.swift +// {app_name} +// +// Created by s200077761 on {date} +// Python Apple Support Example +// +// Note: This template uses SwiftUI and the Python C API. +// The 'import Python' statement gives access to Python C API functions. +// Make sure Python.xcframework is added to your project and set to "Embed & Sign". +// + +import SwiftUI +import Python + +struct ContentView: View {{ + @State private var pythonOutput: String = "Initializing Python..." + @State private var isInitialized: Bool = false + + var body: some View {{ + VStack(spacing: 20) {{ + Text("{app_name}") + .font(.largeTitle) + .bold() + + Text(pythonOutput) + .padding() + .multilineTextAlignment(.center) + + if isInitialized {{ + Button("Run Python Code") {{ + runPythonCode() + }} + .buttonStyle(.borderedProminent) + }} + }} + .padding() + .onAppear {{ + initializePython() + }} + }} + + func initializePython() {{ + guard let pythonHome = Bundle.main.path(forResource: "python", ofType: nil) else {{ + pythonOutput = "Error: Python framework not found in bundle" + return + }} + + let appPath = Bundle.main.path(forResource: "app", ofType: nil) + + setenv("PYTHONHOME", pythonHome, 1) + if let appPath = appPath {{ + setenv("PYTHONPATH", appPath, 1) + }} + + Py_Initialize() + + isInitialized = true + pythonOutput = "Python initialized successfully!\\nTap button to run Python code." + }} + + func runPythonCode() {{ + // Run the main.py script + let code = """ + import sys + try: + with open('app/main.py', 'r') as f: + exec(f.read()) + except Exception as e: + print(f"Error: {{e}}") + """ + + PyRun_SimpleString(code) + pythonOutput = "Python code executed!\\nCheck Xcode console for output." + }} +}} + +#Preview {{ + ContentView() +}} +''' + +PYTHON_TEMPLATE = '''#!/usr/bin/env python3 +""" +{app_name} - Python Module +Created by s200077761 on {date} + +This is the main Python code for your {platform} app. +""" + +import sys +import platform + +def main(): + """Main function - customize this with your app logic.""" + print("=" * 50) + print("Hello from Python on {platform}!") + print("=" * 50) + + # System information + print(f"\\nPython Version: {{sys.version_info.major}}.{{sys.version_info.minor}}.{{sys.version_info.micro}}") + print(f"Platform: {{sys.platform}}") + print(f"Architecture: {{platform.machine()}}") + + # Your app logic here + print("\\nāœ“ Python is running successfully!") + print("\\nCustomize this file (app/main.py) with your own code!") + + # Example: Simple calculation + result = calculate_example() + print(f"\\nExample calculation: {{result}}") + + return 0 + +def calculate_example(): + """Example function - replace with your own.""" + numbers = [1, 2, 3, 4, 5] + total = sum(numbers) + average = total / len(numbers) + return f"Sum={{total}}, Average={{average}}" + +if __name__ == "__main__": + sys.exit(main()) +''' + +README_TEMPLATE = '''# {app_name} + +A Python-powered {platform} application. + +Created with Python Apple Support by s200077761 on {date} + +## Files + +- `ContentView.swift` - Main SwiftUI view with Python integration +- `app/main.py` - Python code that runs in the app +- `README.md` - This file + +## Setup Instructions + +1. **Create Xcode Project** + - Open Xcode + - Create new {platform} App + - Choose SwiftUI for interface + +2. **Add Python Framework** + - Build Python framework: `python3 scripts/build_demo.py --platform {platform_lower}` + - Extract `Python.xcframework` from built archive in `dist/` + - Drag `Python.xcframework` into Xcode project + - Ensure it's set to "Embed & Sign" + +3. **Add Your Code** + - Replace ContentView.swift with the provided template + - Create `app/` folder in Xcode (Resources group) + - Add `main.py` to the `app/` folder + - Add both to your app's target + +4. **Configure Bridging** + - Add Python.xcframework to "Frameworks, Libraries, and Embedded Content" + - Set to "Embed & Sign" + - **For Swift projects**: Use `import Python` (included in template) + - This import gives access to Python C API functions (Py_Initialize, PyRun_SimpleString, etc.) + - No bridging header needed for pure Swift projects + - **For Objective-C or mixed projects**: + - Create a bridging header if needed + - Add `#include ` to the bridging header + - The Python.xcframework must be properly embedded for runtime access + +5. **Build and Run** + - Select a simulator or device + - Build and run your app + - Python code will execute on launch + +## Customization + +### Modify Python Code + +Edit `app/main.py` to add your Python functionality: + +```python +def my_function(): + # Your code here + return "Hello from Python!" +``` + +### Call from Swift + +In `ContentView.swift`, you can run Python code: + +```swift +let code = """ +import main +result = main.my_function() +print(result) +""" +PyRun_SimpleString(code) +``` + +### Add Python Packages + +To use additional Python packages: +1. Build them for {platform} (see Mobile Forge) +2. Add .so files to your app bundle +3. Import them in Python code + +## Troubleshooting + +**Python not found:** +- Verify Python.xcframework is in "Frameworks" folder +- Check it's set to "Embed & Sign" +- Verify bundle contains python/ folder + +**Import errors:** +- Check PYTHONPATH is set correctly +- Ensure app/ folder is in bundle +- Verify .py files are in app target + +**Runtime crashes:** +- Check Xcode console for Python errors +- Verify Py_Initialize() succeeds +- Test Python code independently first + +## Resources + +- [Python Apple Support Docs](../USAGE.md) +- [CPython iOS Guide](https://docs.python.org/3/using/ios.html) +- [Briefcase Documentation](https://briefcase.readthedocs.io/) + +## Next Steps + +1. Test the basic template +2. Add your Python business logic +3. Create Swift UI for user interaction +4. Build and test on device +5. Distribute via TestFlight or App Store + +Happy coding! šŸšŸŽ +''' + +def generate_template(platform, app_name, output_dir): + """Generate app template files.""" + platform_lower = platform.lower() + if platform_lower not in TEMPLATES: + print(f"Error: Unknown platform '{platform}'") + print(f"Available: {', '.join(TEMPLATES.keys())}") + return False + + template = TEMPLATES[platform_lower] + output_path = Path(output_dir) + output_path.mkdir(parents=True, exist_ok=True) + + # Create app subdirectory for Python code + app_dir = output_path / 'app' + app_dir.mkdir(exist_ok=True) + + # Generate date + date = datetime.now().strftime("%Y-%m-%d") + + print(f"\nšŸ“± Generating {template['name']} template...") + print(f"šŸ“ Output directory: {output_path.absolute()}\n") + + # Generate Swift file + swift_file = output_path / 'ContentView.swift' + swift_content = SWIFT_TEMPLATE.format( + app_name=app_name, + date=date, + platform=platform + ) + swift_file.write_text(swift_content) + print(f"āœ“ Created {swift_file.name}") + + # Generate Python file + python_file = app_dir / 'main.py' + python_content = PYTHON_TEMPLATE.format( + app_name=app_name, + date=date, + platform=platform + ) + python_file.write_text(python_content) + print(f"āœ“ Created app/{python_file.name}") + + # Generate README + readme_file = output_path / 'README.md' + readme_content = README_TEMPLATE.format( + app_name=app_name, + date=date, + platform=platform, + platform_lower=platform_lower + ) + readme_file.write_text(readme_content) + print(f"āœ“ Created {readme_file.name}") + + print(f"\nāœ… Template generated successfully!") + print(f"\nšŸ“– Next steps:") + print(f" 1. Read {output_path.absolute()}/README.md") + print(f" 2. Create Xcode project for {platform}") + print(f" 3. Add Python.xcframework") + print(f" 4. Copy template files into project") + print(f" 5. Build and run!") + + return True + +def main(): + """Main function.""" + parser = argparse.ArgumentParser( + description='Generate starter templates for Python-powered Apple apps', + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=''' +Examples: + %(prog)s --platform iOS --name "MyPythonApp" + %(prog)s -p macOS -n "PythonDesktop" -o ~/Documents/Templates + %(prog)s --platform visionOS --name "PythonVision" + +Supported platforms: iOS, macOS, tvOS, watchOS, visionOS + ''' + ) + + parser.add_argument( + '--platform', '-p', + required=True, + help='Target Apple platform' + ) + + parser.add_argument( + '--name', '-n', + default='MyPythonApp', + help='App name (default: MyPythonApp)' + ) + + parser.add_argument( + '--output', '-o', + default='./template', + help='Output directory (default: ./template)' + ) + + args = parser.parse_args() + + success = generate_template(args.platform, args.name, args.output) + sys.exit(0 if success else 1) + +if __name__ == "__main__": + main() diff --git a/scripts/welcome.py b/scripts/welcome.py new file mode 100755 index 0000000..42e4a29 --- /dev/null +++ b/scripts/welcome.py @@ -0,0 +1,195 @@ +#!/usr/bin/env python3 +""" +Welcome to s200077761's Python Apple Support Project! + +This script provides an overview of the project and helps you get started +building Python frameworks for Apple platforms. +""" + +import os +import sys +import subprocess +from pathlib import Path + +# ANSI color codes for pretty output +class Colors: + HEADER = '\033[95m' + OKBLUE = '\033[94m' + OKCYAN = '\033[96m' + OKGREEN = '\033[92m' + WARNING = '\033[93m' + FAIL = '\033[91m' + ENDC = '\033[0m' + BOLD = '\033[1m' + UNDERLINE = '\033[4m' + +def print_header(text): + """Print a colored header.""" + print(f"\n{Colors.HEADER}{Colors.BOLD}{'='*60}{Colors.ENDC}") + print(f"{Colors.HEADER}{Colors.BOLD}{text.center(60)}{Colors.ENDC}") + print(f"{Colors.HEADER}{Colors.BOLD}{'='*60}{Colors.ENDC}\n") + +def print_success(text): + """Print a success message.""" + print(f"{Colors.OKGREEN}āœ“ {text}{Colors.ENDC}") + +def print_info(text): + """Print an info message.""" + print(f"{Colors.OKCYAN}ℹ {text}{Colors.ENDC}") + +def print_warning(text): + """Print a warning message.""" + print(f"{Colors.WARNING}⚠ {text}{Colors.ENDC}") + +def print_error(text): + """Print an error message.""" + print(f"{Colors.FAIL}āœ— {text}{Colors.ENDC}") + +def check_requirements(): + """Check if the system meets the requirements.""" + print_header("Checking System Requirements") + + # Check macOS + if sys.platform != 'darwin': + print_error("This project requires macOS to build Apple platform frameworks") + return False + print_success("Running on macOS") + + # Check Xcode + try: + result = subprocess.run(['xcodebuild', '-version'], + capture_output=True, text=True, check=True) + xcode_version = result.stdout.split('\n')[0] + print_success(f"Xcode found: {xcode_version}") + except (subprocess.CalledProcessError, FileNotFoundError): + print_error("Xcode not found or not properly installed") + print_info("Install Xcode from the App Store or run: xcode-select --install") + return False + + # Check Python version + python_version = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}" + if sys.version_info.major == 3 and sys.version_info.minor >= 8: + print_success(f"Python version: {python_version}") + else: + print_warning(f"Python {python_version} detected. Python 3.8+ recommended") + + # Check disk space + stat = os.statvfs('.') + free_gb = (stat.f_bavail * stat.f_frsize) / (1024**3) + if free_gb > 10: + print_success(f"Available disk space: {free_gb:.1f} GB") + else: + print_warning(f"Low disk space: {free_gb:.1f} GB (10+ GB recommended)") + + return True + +def show_project_info(): + """Display project information.""" + print_header("Project Information") + + project_dir = Path(__file__).parent.parent + + print(f"{Colors.BOLD}Project Directory:{Colors.ENDC} {project_dir}") + + # Check if Makefile exists + makefile = project_dir / "Makefile" + if makefile.exists(): + print_success("Makefile found") + + # Read Python version from Makefile + with open(makefile, 'r') as f: + for line in f: + if line.startswith('PYTHON_VERSION='): + version = line.split('=')[1].strip() + print_info(f"Configured Python version: {version}") + break + + # Check for existing builds + dist_dir = project_dir / "dist" + if dist_dir.exists(): + build_files = list(dist_dir.glob("*.tar.gz")) + if build_files: + print_success(f"Found {len(build_files)} existing build(s) in dist/") + for build_file in build_files[:3]: # Show first 3 + print(f" - {build_file.name}") + else: + print_info("No builds found in dist/ directory") + else: + print_info("dist/ directory not created yet (no builds)") + +def show_quick_commands(): + """Show quick start commands.""" + print_header("Quick Start Commands") + + commands = [ + ("Build for all platforms", "make all"), + ("Build for macOS only", "make macOS"), + ("Build for iOS only", "make iOS"), + ("Build for tvOS only", "make tvOS"), + ("Build for watchOS only", "make watchOS"), + ("Build for visionOS only", "make visionOS"), + ("Clean build artifacts", "make clean"), + ("Complete clean (includes downloads)", "make distclean"), + ] + + for desc, cmd in commands: + print(f"{Colors.OKBLUE}{cmd:40}{Colors.ENDC} # {desc}") + +def show_platforms(): + """Show supported platforms.""" + print_header("Supported Apple Platforms") + + platforms = [ + ("macOS", "11.0+", "Big Sur and later", "x86_64, arm64"), + ("iOS", "13.0+", "iPhone, iPad, iPod Touch", "arm64, simulator"), + ("tvOS", "12.0+", "Apple TV", "arm64, simulator"), + ("watchOS", "4.0+", "Apple Watch", "arm64_32, simulator"), + ("visionOS", "2.0+", "Apple Vision Pro", "arm64, simulator"), + ] + + for name, min_version, desc, archs in platforms: + print(f"{Colors.BOLD}{name:12}{Colors.ENDC} {min_version:8} - {desc}") + print(f"{'':12} Architectures: {archs}") + print() + +def show_next_steps(): + """Show suggested next steps.""" + print_header("Suggested Next Steps") + + steps = [ + "1. Review the PERSONALIZED_README.md for detailed information", + "2. Start with a single platform: make iOS", + "3. Check the dist/ folder for your built frameworks", + "4. Read USAGE.md to learn how to use the frameworks in Xcode", + "5. Try the test suite with the iOS/visionOS testbed projects", + ] + + for step in steps: + print(f"{Colors.OKCYAN}{step}{Colors.ENDC}") + +def main(): + """Main function.""" + print(f""" +{Colors.HEADER}{Colors.BOLD} + šŸŽ Python Apple Support - Personal Edition + ========================================== + + Owner: s200077761 + Purpose: Build Python frameworks for all Apple platforms +{Colors.ENDC} + """) + + if not check_requirements(): + print_error("\nSystem requirements not met. Please resolve the issues above.") + sys.exit(1) + + show_project_info() + show_platforms() + show_quick_commands() + show_next_steps() + + print(f"\n{Colors.OKGREEN}{Colors.BOLD}Ready to build Python for Apple platforms!{Colors.ENDC}\n") + print(f"{Colors.OKCYAN}For more information, see PERSONALIZED_README.md{Colors.ENDC}\n") + +if __name__ == "__main__": + main() diff --git a/start.sh b/start.sh new file mode 100755 index 0000000..aa67b63 --- /dev/null +++ b/start.sh @@ -0,0 +1,118 @@ +#!/bin/bash +# Quick Start Script for Python Apple Support +# This script guides you through the initial setup + +echo "šŸŽ Python Apple Support - Quick Start" +echo "======================================" +echo "" +echo "This script will help you get started with building Python for Apple platforms." +echo "" + +# Check if Python 3 is available +if ! command -v python3 &> /dev/null; then + echo "āŒ Python 3 is not installed!" + echo " Please install Python 3.8+ from https://www.python.org/" + exit 1 +fi + +echo "āœ“ Python 3 found: $(python3 --version)" +echo "" + +# Run system check +echo "Step 1: Checking system requirements..." +echo "========================================" +python3 scripts/check_system.py +CHECK_RESULT=$? + +echo "" +echo "" + +if [ $CHECK_RESULT -ne 0 ]; then + echo "āš ļø System requirements not fully met." + echo " Please resolve the issues above before building." + echo "" + echo "Common fixes:" + echo " • Install Xcode from the Mac App Store" + echo " • Run: xcode-select --install" + echo " • Upgrade Python: brew install python@3.11" + echo "" + exit 1 +fi + +echo "Step 2: Learning about the project..." +echo "======================================" +echo "" +echo "Running welcome script..." +python3 scripts/welcome.py + +echo "" +echo "" +echo "Step 3: What would you like to do?" +echo "====================================" +echo "" +echo "Choose an option:" +echo " 1) Build Python for iOS" +echo " 2) Build Python for macOS" +echo " 3) Build Python for all platforms" +echo " 4) Generate app template" +echo " 5) Read documentation" +echo " 6) Exit" +echo "" +read -p "Enter your choice (1-6): " choice + +case $choice in + 1) + echo "" + echo "Building Python for iOS..." + python3 scripts/build_demo.py --platform iOS + ;; + 2) + echo "" + echo "Building Python for macOS..." + python3 scripts/build_demo.py --platform macOS + ;; + 3) + echo "" + echo "Building Python for all platforms (this will take 1-2 hours)..." + read -p "Are you sure? (y/n): " confirm + if [ "$confirm" = "y" ]; then + make all + else + echo "Build cancelled." + fi + ;; + 4) + echo "" + read -p "Enter app name: " app_name + read -p "Enter platform (iOS/macOS/tvOS/watchOS/visionOS): " platform + python3 scripts/generate_template.py --platform "$platform" --name "$app_name" + ;; + 5) + echo "" + echo "Available documentation:" + echo " • README.md - Main overview" + echo " • QUICKSTART.md - Step-by-step guide" + echo " • PROJECT_OVERVIEW.md - Complete reference" + echo " • DEMOS.md - Example applications" + echo " • USAGE.md - Using frameworks in Xcode" + echo "" + echo "Open any of these files to learn more!" + ;; + 6) + echo "Goodbye!" + exit 0 + ;; + *) + echo "Invalid choice. Please run the script again." + exit 1 + ;; +esac + +echo "" +echo "āœ… Done!" +echo "" +echo "Next steps:" +echo " • Check the dist/ folder for built frameworks" +echo " • Read USAGE.md for integration instructions" +echo " • Generate templates with: python3 scripts/generate_template.py" +echo ""