The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.
Rust ffmpegfree-video-editormodel-context-protocolnon-linear-editoroffline-firstopen-source-video-editorself-hostedvideo-editingvideo-editing-automationvideo-editing-softwarevideo-editing-toolsvideo-editorvoice-cloningyoutube-automationyoutube-shorts
fix(ios): Import opens Photos or Files, and Files shows the app's Documents (#332)
Jareer8dfa7bb058f6
diff --git a/src/Cargo.lock b/src/Cargo.lockindex ec47e8dc..07fd64a7 100644--- a/src/Cargo.lock+++ b/src/Cargo.lock@@ -1132,6 +1132,7 @@ dependencies = [name = "concat"version = "0.2.7"dependencies = [+ "block2 0.6.2","concat-api","concat-core","concat-effects",@@ -1147,6 +1148,8 @@ dependencies = ["image","libc","log",+ "objc2 0.6.4",+ "objc2-foundation 0.3.2","opener","pollster","rfd",diff --git a/src/crates/concat/Cargo.toml b/src/crates/concat/Cargo.tomlindex c4d0a6d1..8cfe8842 100644--- a/src/crates/concat/Cargo.toml+++ b/src/crates/concat/Cargo.toml@@ -97,6 +97,20 @@ slint = { version = "1.18", default-features = false, features = [# embeds, so a preset card is drawn in its own face; see fonts.rs."unstable-fontique-011",] }+# The system's pickers for Import and Photos for an export, through the+# Objective-C runtime; see src/ios.rs. The versions Slint's winit backend+# already builds on iOS, so nothing new is compiled for them.+objc2 = "0.6"+block2 = "0.6"+objc2-foundation = { version = "0.3", default-features = false, features = [+ "std",+ "block2",+ "NSArray",+ "NSError",+ "NSObject",+ "NSString",+ "NSURL",+] }[target.'cfg(target_os = "android")'.dependencies]slint = { version = "1.18", default-features = false, features = [diff --git a/src/crates/concat/locales/ar.json b/src/crates/concat/locales/ar.jsonindex aa211715..e24ea33b 100644--- a/src/crates/concat/locales/ar.json+++ b/src/crates/concat/locales/ar.json@@ -304,6 +304,8 @@"phone.duplicate": "تكرار","phone.edit": "تحرير","phone.emptyLanes": "انقر على الوسائط بالأسفل لإحضار فيديو؛ سيظهر هنا.",+ "phone.fromFiles": "الملفات",+ "phone.fromPhotos": "الصور","phone.importMedia": "استيراد وسائط","phone.looks": "أو عنوان بأحد هذه الأنماط:","phone.more": "المزيد",diff --git a/src/crates/concat/locales/bn.json b/src/crates/concat/locales/bn.jsonindex 58e7e32a..25e5ea7c 100644--- a/src/crates/concat/locales/bn.json+++ b/src/crates/concat/locales/bn.json@@ -304,6 +304,8 @@"phone.duplicate": "ডুপ্লিকেট করুন","phone.edit": "সম্পাদনা করুন","phone.emptyLanes": "ভিডিও আনতে নিচে মিডিয়া ট্যাপ করুন; এটি এখানে আসবে।",+ "phone.fromFiles": "ফাইল",+ "phone.fromPhotos": "ফটো","phone.importMedia": "মিডিয়া ইমপোর্ট করুন","phone.looks": "অথবা এই লুকগুলোর একটিতে টাইটেল:","phone.more": "আরও",diff --git a/src/crates/concat/locales/de.json b/src/crates/concat/locales/de.jsonindex 5b2f275e..a3669d3d 100644--- a/src/crates/concat/locales/de.json+++ b/src/crates/concat/locales/de.json@@ -304,6 +304,8 @@"phone.duplicate": "Duplizieren","phone.edit": "Bearbeiten","phone.emptyLanes": "Tippe unten auf Medien, um ein Video zu holen; es landet hier.",+ "phone.fromFiles": "Dateien",+ "phone.fromPhotos": "Fotos","phone.importMedia": "Medien importieren","phone.looks": "Oder ein Titel in einem dieser Looks:","phone.more": "Mehr",diff --git a/src/crates/concat/locales/en.json b/src/crates/concat/locales/en.jsonindex ed405c16..9ebabb49 100644--- a/src/crates/concat/locales/en.json+++ b/src/crates/concat/locales/en.json@@ -319,6 +319,8 @@"phone.duplicate": "Duplicate","phone.edit": "Edit","phone.emptyLanes": "Tap Media below to bring in a video; it lands here.",+ "phone.fromFiles": "Files",+ "phone.fromPhotos": "Photos","phone.importMedia": "Import media","phone.looks": "Or a title in one of these looks:","phone.more": "More",diff --git a/src/crates/concat/locales/es.json b/src/crates/concat/locales/es.jsonindex d125d35b..497f7fba 100644--- a/src/crates/concat/locales/es.json+++ b/src/crates/concat/locales/es.json@@ -304,6 +304,8 @@"phone.duplicate": "Duplicar","phone.edit": "Editar","phone.emptyLanes": "Toca Medios abajo para traer un vídeo; aparecerá aquí.",+ "phone.fromFiles": "Archivos",+ "phone.fromPhotos": "Fotos","phone.importMedia": "Importar medios","phone.looks": "O un título con uno de estos estilos:","phone.more": "Más",diff --git a/src/crates/concat/locales/fa.json b/src/crates/concat/locales/fa.jsonindex c9a88c98..76b3cba5 100644--- a/src/crates/concat/locales/fa.json+++ b/src/crates/concat/locales/fa.json@@ -304,6 +304,8 @@"phone.duplicate": "تکثیر","phone.edit": "ویرایش","phone.emptyLanes": "برای آوردن یک ویدیو روی «رسانه» در پایین بزنید؛ اینجا قرار میگیرد.",+ "phone.fromFiles": "فایلها",+ "phone.fromPhotos": "عکسها","phone.importMedia": "وارد کردن رسانه","phone.looks": "یا عنوانی با یکی از این ظاهرها:","phone.more": "بیشتر",diff --git a/src/crates/concat/locales/fr.json b/src/crates/concat/locales/fr.jsonindex 684be9d0..1c95e9a5 100644--- a/src/crates/concat/locales/fr.json+++ b/src/crates/concat/locales/fr.json@@ -304,6 +304,8 @@"phone.duplicate": "Dupliquer","phone.edit": "Modifier","phone.emptyLanes": "Touchez Médias ci-dessous pour importer une vidéo ; elle arrivera ici.",+ "phone.fromFiles": "Fichiers",+ "phone.fromPhotos": "Photos","phone.importMedia": "Importer des médias","phone.looks": "Ou un titre dans l’un de ces styles :","phone.more": "Plus",diff --git a/src/crates/concat/locales/he.json b/src/crates/concat/locales/he.jsonindex ed4bd74c..5f5eb28b 100644--- a/src/crates/concat/locales/he.json+++ b/src/crates/concat/locales/he.json@@ -304,6 +304,8 @@"phone.duplicate": "שכפול","phone.edit": "עריכה","phone.emptyLanes": "יש להקיש על מדיה למטה כדי להביא וידאו; הוא יגיע לכאן.",+ "phone.fromFiles": "קבצים",+ "phone.fromPhotos": "תמונות","phone.importMedia": "ייבוא מדיה","phone.looks": "או כותרת באחד מהמראות האלה:","phone.more": "עוד",diff --git a/src/crates/concat/locales/hi.json b/src/crates/concat/locales/hi.jsonindex 23764120..53d37de2 100644--- a/src/crates/concat/locales/hi.json+++ b/src/crates/concat/locales/hi.json@@ -304,6 +304,8 @@"phone.duplicate": "डुप्लिकेट","phone.edit": "संपादन","phone.emptyLanes": "वीडियो लाने के लिए नीचे मीडिया पर टैप करें; वह यहां आएगा।",+ "phone.fromFiles": "फ़ाइलें",+ "phone.fromPhotos": "तस्वीरें","phone.importMedia": "मीडिया इंपोर्ट करें","phone.looks": "या इनमें से किसी लुक में टाइटल:","phone.more": "और",diff --git a/src/crates/concat/locales/hr.json b/src/crates/concat/locales/hr.jsonindex d2aea68a..96651523 100644--- a/src/crates/concat/locales/hr.json+++ b/src/crates/concat/locales/hr.json@@ -304,6 +304,8 @@"phone.duplicate": "Dupliciraj","phone.edit": "Uredi","phone.emptyLanes": "Dodirni Mediji ispod da uvezeš video; pojavit će se ovdje.",+ "phone.fromFiles": "Datoteke",+ "phone.fromPhotos": "Fotografije","phone.importMedia": "Uvezi medije","phone.looks": "Ili naslov u jednom od ovih izgleda:","phone.more": "Više",diff --git a/src/crates/concat/locales/id.json b/src/crates/concat/locales/id.jsonindex 6aa271c5..31fa17a6 100644--- a/src/crates/concat/locales/id.json+++ b/src/crates/concat/locales/id.json@@ -304,6 +304,8 @@"phone.duplicate": "Duplikat","phone.edit": "Edit","phone.emptyLanes": "Ketuk Media di bawah untuk memasukkan video; video akan muncul di sini.",+ "phone.fromFiles": "File",+ "phone.fromPhotos": "Foto","phone.importMedia": "Impor media","phone.looks": "Atau judul dengan salah satu tampilan ini:","phone.more": "Lainnya",diff --git a/src/crates/concat/locales/it.json b/src/crates/concat/locales/it.jsonindex 442072ff..52eb7e20 100644--- a/src/crates/concat/locales/it.json+++ b/src/crates/concat/locales/it.json@@ -304,6 +304,8 @@"phone.duplicate": "Duplica","phone.edit": "Modifica","phone.emptyLanes": "Tocca Media qui sotto per importare un video; comparirà qui.",+ "phone.fromFiles": "File",+ "phone.fromPhotos": "Foto","phone.importMedia": "Importa media","phone.looks": "Oppure un titolo in uno di questi stili:","phone.more": "Altro",diff --git a/src/crates/concat/locales/ja.json b/src/crates/concat/locales/ja.jsonindex 7bdd5e7c..ed64cb21 100644--- a/src/crates/concat/locales/ja.json+++ b/src/crates/concat/locales/ja.json@@ -304,6 +304,8 @@"phone.duplicate": "複製","phone.edit": "編集","phone.emptyLanes": "下の「メディア」をタップして動画を読み込むと、ここに置かれます。",+ "phone.fromFiles": "ファイル",+ "phone.fromPhotos": "写真","phone.importMedia": "メディアを読み込む","phone.looks": "または、次のスタイルでタイトルを追加:","phone.more": "その他",diff --git a/src/crates/concat/locales/ko.json b/src/crates/concat/locales/ko.jsonindex dbe98438..a208be36 100644--- a/src/crates/concat/locales/ko.json+++ b/src/crates/concat/locales/ko.json@@ -304,6 +304,8 @@"phone.duplicate": "복제","phone.edit": "편집","phone.emptyLanes": "아래의 미디어를 탭해 영상을 가져오면 여기에 놓입니다.",+ "phone.fromFiles": "파일",+ "phone.fromPhotos": "사진","phone.importMedia": "미디어 가져오기","phone.looks": "또는 다음 스타일 중 하나로 제목 추가:","phone.more": "더보기",diff --git a/src/crates/concat/locales/nl.json b/src/crates/concat/locales/nl.jsonindex 5db7ef89..d3bc19a7 100644--- a/src/crates/concat/locales/nl.json+++ b/src/crates/concat/locales/nl.json@@ -304,6 +304,8 @@"phone.duplicate": "Dupliceren","phone.edit": "Bewerken","phone.emptyLanes": "Tik hieronder op Media om een video toe te voegen; die komt hier terecht.",+ "phone.fromFiles": "Bestanden",+ "phone.fromPhotos": "Foto's","phone.importMedia": "Media importeren","phone.looks": "Of een titel in een van deze stijlen:","phone.more": "Meer",diff --git a/src/crates/concat/locales/pl.json b/src/crates/concat/locales/pl.jsonindex 928b9cd6..8dd8c67d 100644--- a/src/crates/concat/locales/pl.json+++ b/src/crates/concat/locales/pl.json@@ -304,6 +304,8 @@"phone.duplicate": "Duplikuj","phone.edit": "Edytuj","phone.emptyLanes": "Stuknij Multimedia poniżej, aby dodać wideo; pojawi się tutaj.",+ "phone.fromFiles": "Pliki",+ "phone.fromPhotos": "Zdjęcia","phone.importMedia": "Importuj multimedia","phone.looks": "Albo tytuł w jednym z tych stylów:","phone.more": "Więcej",diff --git a/src/crates/concat/locales/pt-BR.json b/src/crates/concat/locales/pt-BR.jsonindex 645f6f48..b529aed4 100644--- a/src/crates/concat/locales/pt-BR.json+++ b/src/crates/concat/locales/pt-BR.json@@ -304,6 +304,8 @@"phone.duplicate": "Duplicar","phone.edit": "Editar","phone.emptyLanes": "Toque em Mídia abaixo para trazer um vídeo; ele aparecerá aqui.",+ "phone.fromFiles": "Arquivos",+ "phone.fromPhotos": "Fotos","phone.importMedia": "Importar mídia","phone.looks": "Ou um título em um destes estilos:","phone.more": "Mais",diff --git a/src/crates/concat/locales/ru.json b/src/crates/concat/locales/ru.jsonindex c59ee909..90b816aa 100644--- a/src/crates/concat/locales/ru.json+++ b/src/crates/concat/locales/ru.json@@ -304,6 +304,8 @@"phone.duplicate": "Дублировать","phone.edit": "Правка","phone.emptyLanes": "Коснитесь «Медиа» внизу, чтобы добавить видео; оно появится здесь.",+ "phone.fromFiles": "Файлы",+ "phone.fromPhotos": "Фото","phone.importMedia": "Импортировать медиа","phone.looks": "Или титр в одном из этих стилей:","phone.more": "Ещё",diff --git a/src/crates/concat/locales/th.json b/src/crates/concat/locales/th.jsonindex a825bb0b..500f838f 100644--- a/src/crates/concat/locales/th.json+++ b/src/crates/concat/locales/th.json@@ -304,6 +304,8 @@"phone.duplicate": "ทำสำเนา","phone.edit": "แก้ไข","phone.emptyLanes": "แตะสื่อด้านล่างเพื่อนำวิดีโอเข้ามา วิดีโอจะมาอยู่ที่นี่",+ "phone.fromFiles": "ไฟล์",+ "phone.fromPhotos": "รูปภาพ","phone.importMedia": "นำเข้าสื่อ","phone.looks": "หรือไตเติลในลุคเหล่านี้:","phone.more": "เพิ่มเติม",diff --git a/src/crates/concat/locales/tr.json b/src/crates/concat/locales/tr.jsonindex 9b5ea6db..35b25300 100644--- a/src/crates/concat/locales/tr.json+++ b/src/crates/concat/locales/tr.json@@ -304,6 +304,8 @@"phone.duplicate": "Çoğalt","phone.edit": "Düzenle","phone.emptyLanes": "Bir video getirmek için aşağıdaki Medya’ya dokunun; buraya gelir.",+ "phone.fromFiles": "Dosyalar",+ "phone.fromPhotos": "Fotoğraflar","phone.importMedia": "Medya içe aktar","phone.looks": "Ya da şu görünümlerden biriyle bir başlık:","phone.more": "Daha fazla",diff --git a/src/crates/concat/locales/uk.json b/src/crates/concat/locales/uk.jsonindex 82a09d5b..5f3182a2 100644--- a/src/crates/concat/locales/uk.json+++ b/src/crates/concat/locales/uk.json@@ -304,6 +304,8 @@"phone.duplicate": "Дублювати","phone.edit": "Редагувати","phone.emptyLanes": "Торкніться «Медіа» внизу, щоб додати відео; воно з’явиться тут.",+ "phone.fromFiles": "Файли",+ "phone.fromPhotos": "Фото","phone.importMedia": "Імпортувати медіа","phone.looks": "Або титр в одному з цих стилів:","phone.more": "Більше",diff --git a/src/crates/concat/locales/ur.json b/src/crates/concat/locales/ur.jsonindex 575c26da..a9bf2919 100644--- a/src/crates/concat/locales/ur.json+++ b/src/crates/concat/locales/ur.json@@ -304,6 +304,8 @@"phone.duplicate": "نقل بنائیں","phone.edit": "ترمیم","phone.emptyLanes": "ویڈیو لانے کے لیے نیچے میڈیا پر ٹیپ کریں؛ وہ یہاں آ جائے گی۔",+ "phone.fromFiles": "فائلیں",+ "phone.fromPhotos": "تصاویر","phone.importMedia": "میڈیا امپورٹ کریں","phone.looks": "یا ان میں سے کسی انداز میں ٹائٹل:","phone.more": "مزید",diff --git a/src/crates/concat/locales/vi.json b/src/crates/concat/locales/vi.jsonindex 40b3008a..e9476d83 100644--- a/src/crates/concat/locales/vi.json+++ b/src/crates/concat/locales/vi.json@@ -304,6 +304,8 @@"phone.duplicate": "Nhân bản","phone.edit": "Chỉnh sửa","phone.emptyLanes": "Nhấn Phương tiện bên dưới để thêm video; video sẽ xuất hiện ở đây.",+ "phone.fromFiles": "Tệp",+ "phone.fromPhotos": "Ảnh","phone.importMedia": "Nhập phương tiện","phone.looks": "Hoặc chọn một kiểu tiêu đề bên dưới:","phone.more": "Thêm",diff --git a/src/crates/concat/locales/zh-Hans.json b/src/crates/concat/locales/zh-Hans.jsonindex 5c55eafd..de46307a 100644--- a/src/crates/concat/locales/zh-Hans.json+++ b/src/crates/concat/locales/zh-Hans.json@@ -304,6 +304,8 @@"phone.duplicate": "复制","phone.edit": "编辑","phone.emptyLanes": "点按下方的“媒体”导入视频,它会出现在这里。",+ "phone.fromFiles": "文件",+ "phone.fromPhotos": "照片","phone.importMedia": "导入媒体","phone.looks": "或以下面任一样式添加标题:","phone.more": "更多",diff --git a/src/crates/concat/locales/zh-TW.json b/src/crates/concat/locales/zh-TW.jsonindex 8877e176..110774b7 100644--- a/src/crates/concat/locales/zh-TW.json+++ b/src/crates/concat/locales/zh-TW.json@@ -304,6 +304,8 @@"phone.duplicate": "複製","phone.edit": "編輯","phone.emptyLanes": "點一下下方的「媒體」匯入影片,它會出現在這裡。",+ "phone.fromFiles": "檔案",+ "phone.fromPhotos": "照片","phone.importMedia": "匯入媒體","phone.looks": "或以下列任一樣式新增標題:","phone.more": "更多",diff --git a/src/crates/concat/src/ios.rs b/src/crates/concat/src/ios.rsnew file mode 100644index 00000000..83c0bef7--- /dev/null+++ b/src/crates/concat/src/ios.rs@@ -0,0 +1,502 @@+// SPDX-License-Identifier: AGPL-3.0-or-later+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors++//! The iPhone's ways in and out: the system's pickers for Import, and+//! Photos for a finished export.+//!+//! Until this, iOS installed no picker at all, and Import did nothing on+//! every iPhone the app was ever put on (#332, #338). An iPhone's videos+//! live in Photos, and its other files in Files, which are two different+//! pickers - PHPickerViewController and UIDocumentPickerViewController -+//! so Import asks which, with a sheet naming the two. Neither needs a+//! permission: PHPicker runs outside the app and hands over only what was+//! picked, and the document picker copies what was picked into the app's+//! own tmp/ (`asCopy`).+//!+//! What either answers with is moved into Documents/Imported, as+//! Android's picker copies into its Imported: the engine opens files by+//! path, and a project keeps pointing at its media long after the picker's+//! temporary copies are gone. Documents is also the one folder Files shows+//! for the app (UIFileSharingEnabled in scripts/ios-app.sh).+//!+//! Everything here is Objective-C through `objc2`'s `msg_send!`, against+//! classes looked up by name: PhotosUI and Photos have no binding crate in+//! the build, and UIKit's would take a feature per class for the handful+//! of calls made. The window's crate already links UIKit through Slint's+//! winit backend; the three frameworks below are linked here.++use std::path::{Path, PathBuf};+use std::sync::{Arc, Mutex};++use block2::{Block, RcBlock};+use objc2::rc::{Allocated, Retained};+use objc2::runtime::{AnyClass, AnyObject, NSObject};+use objc2::{MainThreadMarker, MainThreadOnly, class, define_class, msg_send};+use objc2_foundation::{NSArray, NSError, NSString, NSURL};++use crate::i18n::t;++#[link(name = "PhotosUI", kind = "framework")]+#[link(name = "Photos", kind = "framework")]+#[link(name = "UniformTypeIdentifiers", kind = "framework")]+unsafe extern "C" {}++type Picked = Box<dyn FnOnce(Vec<PathBuf>) + Send>;++/// The pick in flight, waiting for a picker to answer.+static PENDING: Mutex<Option<Picked>> = Mutex::new(None);++thread_local! {+ /// The pickers' delegate. A view controller holds its delegate weakly,+ /// so something else has to; one for the life of the app, made on the+ /// first pick, on the main thread where every picker lives.+ static DELEGATE: std::cell::OnceCell<Retained<PickDelegate>> =+ const { std::cell::OnceCell::new() };+}++/// Installs the iPhone's picker and its export publisher into the window's+/// crate. Before the window runs; see `platform::install_file_picker`.+pub fn install() {+ crate::platform::install_file_picker(Box::new(|on_picked| {+ let previous = PENDING+ .lock()+ .map(|mut slot| slot.replace(on_picked))+ .ok()+ .flatten();+ if let Some(previous) = previous {+ // A pick was already up; the one that asked first is told it+ // got nothing rather than left waiting for ever.+ previous(Vec::new());+ }+ // `pick_files_async` is called from the event loop, which on iOS+ // is the main thread; UIKit is not to be touched from any other.+ let shown = match MainThreadMarker::new() {+ Some(mtm) => choose(mtm),+ None => Err("asked for a picker off the main thread"),+ };+ if let Err(error) = shown {+ log::error!("could not show the picker: {error}");+ finish(Vec::new());+ }+ }));+ crate::platform::install_export_publisher(crate::platform::ExportPublisher {+ folder: "Photos".into(),+ publish: Box::new(save_to_photos),+ });+}++/// Hands the pick in flight what it got.+fn finish(paths: Vec<PathBuf>) {+ if let Some(pending) = PENDING.lock().ok().and_then(|mut slot| slot.take()) {+ pending(paths);+ }+}++define_class!(+ // SAFETY: NSObject has no subclassing requirements, and this class+ // has no Drop.+ #[unsafe(super(NSObject))]+ #[thread_kind = MainThreadOnly]+ #[name = "ConcatPickDelegate"]+ struct PickDelegate;++ impl PickDelegate {+ /// PHPickerViewControllerDelegate: called once, with nothing for+ /// a cancel. The picker does not go away by itself.+ #[unsafe(method(picker:didFinishPicking:))]+ fn picker_did_finish_picking(&self, picker: &AnyObject, results: &NSArray<AnyObject>) {+ let none: Option<&Block<dyn Fn()>> = None;+ // SAFETY: a view controller, on the main thread.+ let _: () = unsafe { msg_send![picker, dismissViewControllerAnimated: true, completion: none] };+ photos_picked(results);+ }++ /// UIDocumentPickerDelegate: the copies the picker made, in tmp/.+ #[unsafe(method(documentPicker:didPickDocumentsAtURLs:))]+ fn document_picker_did_pick(&self, _picker: &AnyObject, urls: &NSArray<NSURL>) {+ let picked: Vec<PathBuf> = urls.iter().filter_map(|url| url.to_file_path()).collect();+ // Off the main thread: a move within the app's container is a+ // rename, but one that falls back to a copy takes a while.+ let moved = std::thread::Builder::new()+ .name("ios import".into())+ .spawn(move || {+ let paths = picked+ .iter()+ .filter_map(|from| {+ let name = from.file_name()?.to_string_lossy().into_owned();+ adopt(from, &name)+ })+ .collect();+ finish(paths);+ });+ if moved.is_err() {+ finish(Vec::new());+ }+ }++ #[unsafe(method(documentPickerWasCancelled:))]+ fn document_picker_was_cancelled(&self, _picker: &AnyObject) {+ finish(Vec::new());+ }+ }+);++impl PickDelegate {+ fn new(mtm: MainThreadMarker) -> Retained<Self> {+ let this = mtm.alloc::<Self>().set_ivars(());+ // SAFETY: NSObject's init.+ unsafe { msg_send![super(this), init] }+ }++ /// The one delegate, as an object a picker's `setDelegate:` takes.+ fn shared(mtm: MainThreadMarker) -> Retained<AnyObject> {+ DELEGATE.with(|cell| {+ let delegate = cell.get_or_init(|| Self::new(mtm));+ Retained::into_super(Retained::into_super(delegate.clone()))+ })+ }+}++/// The view controller to present on: the key window's root, or what it+/// already shows on top of itself.+fn top_view_controller() -> Result<Retained<AnyObject>, &'static str> {+ // SAFETY: UIKit's own getters, on the main thread (the caller's+ // MainThreadMarker); each answer is nil or an object of the type named.+ unsafe {+ let app: Option<Retained<AnyObject>> = msg_send![class!(UIApplication), sharedApplication];+ let app = app.ok_or("no UIApplication")?;+ let scenes: Retained<AnyObject> = msg_send![&app, connectedScenes];+ let scenes: Retained<NSArray<AnyObject>> = msg_send![&scenes, allObjects];+ let window_scene = AnyClass::get(c"UIWindowScene").ok_or("no UIWindowScene")?;+ let mut root: Option<Retained<AnyObject>> = None;+ for scene in scenes.iter() {+ let is_window_scene: bool = msg_send![&scene, isKindOfClass: window_scene];+ if !is_window_scene {+ continue;+ }+ let key: Option<Retained<AnyObject>> = msg_send![&scene, keyWindow];+ let window = match key {+ Some(window) => Some(window),+ None => {+ let windows: Retained<NSArray<AnyObject>> = msg_send![&scene, windows];+ windows.firstObject()+ }+ };+ if let Some(window) = window {+ root = msg_send![&window, rootViewController];+ if root.is_some() {+ break;+ }+ }+ }+ let mut top = root.ok_or("no window with a root view controller")?;+ loop {+ let presented: Option<Retained<AnyObject>> = msg_send![&top, presentedViewController];+ match presented {+ Some(presented) => top = presented,+ None => return Ok(top),+ }+ }+ }+}++/// Asks where from - Photos or Files - and shows that picker. A sheet from+/// the bottom on an iPhone; an iPad's would be a popover, which needs a+/// place on the screen to point at, so there it is an alert in the middle.+fn choose(_mtm: MainThreadMarker) -> Result<(), &'static str> {+ let top = top_view_controller()?;+ let title = NSString::from_str(&t("phone.importMedia"));+ let message: Option<&NSString> = None;+ // SAFETY: UIKit on the main thread; the constants are UIKit's+ // (UIUserInterfaceIdiomPad 1, UIAlertControllerStyleActionSheet 0 and+ // Alert 1, UIAlertActionStyleDefault 0 and Cancel 1).+ unsafe {+ let device: Retained<AnyObject> = msg_send![class!(UIDevice), currentDevice];+ let idiom: isize = msg_send![&device, userInterfaceIdiom];+ let style: isize = if idiom == 1 { 1 } else { 0 };+ let alert: Retained<AnyObject> = msg_send![+ class!(UIAlertController),+ alertControllerWithTitle: &*title,+ message: message,+ preferredStyle: style+ ];+ let actions: [(String, isize, fn(MainThreadMarker) -> Result<(), &'static str>); 3] = [+ (t("phone.fromPhotos"), 0, show_photos),+ (t("phone.fromFiles"), 0, show_files),+ (t("common.cancel"), 1, |_| Err("cancelled")),+ ];+ for (label, action_style, show) in actions {+ let label = NSString::from_str(&label);+ let handler = RcBlock::new(move |_action: *mut AnyObject| {+ // UIKit calls an action's handler on the main thread, once+ // the sheet is gone.+ let shown = match MainThreadMarker::new() {+ Some(mtm) => show(mtm),+ None => Err("an alert action off the main thread"),+ };+ if let Err(error) = shown {+ if error != "cancelled" {+ log::error!("could not show the picker: {error}");+ }+ finish(Vec::new());+ }+ });+ let action: Retained<AnyObject> = msg_send![+ class!(UIAlertAction),+ actionWithTitle: &*label,+ style: action_style,+ handler: &*handler+ ];+ let _: () = msg_send![&alert, addAction: &*action];+ }+ let none: Option<&Block<dyn Fn()>> = None;+ let _: () = msg_send![&top, presentViewController: &*alert, animated: true, completion: none];+ }+ Ok(())+}++/// The photo library's picker: videos and pictures, any number, as they+/// are in the library. `Current` rather than `Automatic` so an HEVC video+/// comes over as it is instead of being transcoded first, which for a long+/// clip is minutes of a spinner; the engine decodes HEVC and HEIC itself.+fn show_photos(mtm: MainThreadMarker) -> Result<(), &'static str> {+ let top = top_view_controller()?;+ let delegate = PickDelegate::shared(mtm);+ // SAFETY: PhotosUI on the main thread; the constants are its own+ // (PHPickerConfigurationAssetRepresentationModeCurrent 1; a selection+ // limit of 0 is no limit).+ unsafe {+ let config: Allocated<AnyObject> = msg_send![class!(PHPickerConfiguration), alloc];+ let config: Retained<AnyObject> = msg_send![config, init];+ let _: () = msg_send![&config, setSelectionLimit: 0isize];+ let _: () = msg_send![&config, setPreferredAssetRepresentationMode: 1isize];+ let videos: Retained<AnyObject> = msg_send![class!(PHPickerFilter), videosFilter];+ let images: Retained<AnyObject> = msg_send![class!(PHPickerFilter), imagesFilter];+ let both = NSArray::from_retained_slice(&[videos, images]);+ let filter: Retained<AnyObject> =+ msg_send![class!(PHPickerFilter), anyFilterMatchingSubfilters: &*both];+ let _: () = msg_send![&config, setFilter: &*filter];+ let picker: Allocated<AnyObject> = msg_send![class!(PHPickerViewController), alloc];+ let picker: Retained<AnyObject> = msg_send![picker, initWithConfiguration: &*config];+ let _: () = msg_send![&picker, setDelegate: &*delegate];+ let none: Option<&Block<dyn Fn()>> = None;+ let _: () = msg_send![&top, presentViewController: &*picker, animated: true, completion: none];+ }+ Ok(())+}++/// The document picker: videos, sounds and pictures from Files - iCloud+/// Drive, the phone, a USB drive, anything a file provider offers. The+/// picker copies each into the app's tmp/ (`asCopy`), so nothing needs a+/// security-scoped bookmark to be read.+fn show_files(mtm: MainThreadMarker) -> Result<(), &'static str> {+ let top = top_view_controller()?;+ let delegate = PickDelegate::shared(mtm);+ // SAFETY: UIKit and UniformTypeIdentifiers on the main thread.+ unsafe {+ let mut types = Vec::new();+ for identifier in ["public.movie", "public.audio", "public.image"] {+ let identifier = NSString::from_str(identifier);+ let kind: Option<Retained<AnyObject>> =+ msg_send![class!(UTType), typeWithIdentifier: &*identifier];+ types.extend(kind);+ }+ let types = NSArray::from_retained_slice(&types);+ let picker: Allocated<AnyObject> =+ msg_send![class!(UIDocumentPickerViewController), alloc];+ let picker: Retained<AnyObject> =+ msg_send![picker, initForOpeningContentTypes: &*types, asCopy: true];+ let _: () = msg_send![&picker, setAllowsMultipleSelection: true];+ let _: () = msg_send![&picker, setDelegate: &*delegate];+ let none: Option<&Block<dyn Fn()>> = None;+ let _: () = msg_send![&top, presentViewController: &*picker, animated: true, completion: none];+ }+ Ok(())+}++/// What the photo picker answered with, each fetched as a file and moved+/// into Imported. Every fetch answers on a queue of its own, in no+/// particular order; the pick is answered once all have, in the order+/// they were picked.+fn photos_picked(results: &NSArray<AnyObject>) {+ let count = results.count();+ if count == 0 {+ finish(Vec::new());+ return;+ }+ struct Tally {+ left: usize,+ paths: Vec<Option<PathBuf>>,+ }+ let tally = Arc::new(Mutex::new(Tally {+ left: count,+ paths: vec![None; count],+ }));+ let done = |tally: &Mutex<Tally>, index: usize, path: Option<PathBuf>| {+ let finished = tally.lock().ok().and_then(|mut tally| {+ tally.paths[index] = path;+ tally.left -= 1;+ (tally.left == 0).then(|| tally.paths.drain(..).flatten().collect::<Vec<_>>())+ });+ if let Some(paths) = finished {+ finish(paths);+ }+ };+ for (index, result) in results.iter().enumerate() {+ // SAFETY: a PHPickerResult's itemProvider is an NSItemProvider,+ // never nil; the identifiers are system UTIs.+ let asked = unsafe {+ let provider: Retained<AnyObject> = msg_send![&result, itemProvider];+ let movie = NSString::from_str("public.movie");+ let has_movie: bool = msg_send![&provider, hasItemConformingToTypeIdentifier: &*movie];+ let kind = if has_movie { movie } else { NSString::from_str("public.image") };+ let suggested: Option<Retained<NSString>> = msg_send![&provider, suggestedName];+ let suggested = suggested.map(|name| name.to_string());+ let tally = Arc::clone(&tally);+ // The file is the provider's for as long as this block runs,+ // and is deleted after; it is moved or copied before then.+ let handler = RcBlock::new(move |url: *mut NSURL, error: *mut NSError| {+ let from = url.as_ref().and_then(|url| url.to_file_path());+ let path = match from {+ Some(from) => {+ let name = import_name(suggested.as_deref(), &from);+ adopt(&from, &name)+ }+ None => {+ let why = error+ .as_ref()+ .map(|error| error.localizedDescription().to_string())+ .unwrap_or_default();+ log::warn!("could not fetch a picked photo or video: {why}");+ None+ }+ };+ done(&tally, index, path);+ });+ let progress: Option<Retained<AnyObject>> = msg_send![+ &provider,+ loadFileRepresentationForTypeIdentifier: &*kind,+ completionHandler: &*handler+ ];+ progress.is_some()+ };+ if !asked {+ done(&tally, index, None);+ }+ }+}++/// The name a picked photo or video is kept under: the library's own+/// ("IMG_0042"), with the extension of the file it came as, or the file's+/// name where the library gave none.+fn import_name(suggested: Option<&str>, file: &Path) -> String {+ let file_name = file+ .file_name()+ .map(|name| name.to_string_lossy().into_owned())+ .unwrap_or_else(|| "import".into());+ match (suggested.filter(|name| !name.is_empty()), file.extension()) {+ (Some(name), Some(ext)) => format!("{name}.{}", ext.to_string_lossy()),+ (Some(name), None) => name.to_owned(),+ (None, _) => file_name,+ }+}++/// Moves `from` into Documents/Imported as `name` - or `name (2)` and on+/// where that is taken - and answers with where it went. A copy where the+/// move fails (another volume, a file the app may read but not move).+fn adopt(from: &Path, name: &str) -> Option<PathBuf> {+ let Some(home) = std::env::home_dir() else {+ log::warn!("no home folder to import into");+ return None;+ };+ let dir = home.join("Documents").join("Imported");+ if let Err(error) = std::fs::create_dir_all(&dir) {+ log::warn!("could not make {}: {error}", dir.display());+ return None;+ }+ // Whatever the provider called it, it is one file name.+ let name = name.replace(['/', '\\'], "_");+ let to = unique(&dir, &name);+ if std::fs::rename(from, &to).is_ok() {+ return Some(to);+ }+ match std::fs::copy(from, &to) {+ Ok(_) => Some(to),+ Err(error) => {+ log::warn!("could not import {}: {error}", from.display());+ let _ = std::fs::remove_file(&to);+ None+ }+ }+}++/// `name`, or `name (2)`, `name (3)`... until nothing is overwritten.+fn unique(dir: &Path, name: &str) -> PathBuf {+ let first = dir.join(name);+ if !first.exists() {+ return first;+ }+ let (stem, ext) = match name.rfind('.') {+ Some(dot) if dot > 0 => (&name[..dot], &name[dot..]),+ _ => (name, ""),+ };+ (2..)+ .map(|n| dir.join(format!("{stem} ({n}){ext}")))+ .find(|path| !path.exists())+ .unwrap_or(first)+}++/// Adds a finished export to Photos, where an iPhone looks for its videos,+/// and answers with the file's own path. The file stays where it was+/// written, in Documents, which Files shows: Photos keeps its own copy,+/// and a save Photos refused loses nothing. Blocking - Photos copies the+/// whole video - so it is called off the main thread, which+/// `performChangesAndWait:` requires.+fn save_to_photos(path: &Path) -> Result<String, String> {+ // PHAccessLevelAddOnly 1; PHAuthorizationStatus NotDetermined 0,+ // Authorized 3, Limited 4.+ const ADD_ONLY: isize = 1;+ // SAFETY: Photos' class methods, from any thread; the block is called+ // once, from a queue of Photos'.+ let mut status: isize = unsafe {+ msg_send![class!(PHPhotoLibrary), authorizationStatusForAccessLevel: ADD_ONLY]+ };+ if status == 0 {+ let (tx, rx) = std::sync::mpsc::channel();+ let handler = RcBlock::new(move |answer: isize| {+ let _ = tx.send(answer);+ });+ // SAFETY: as above.+ let _: () = unsafe {+ msg_send![+ class!(PHPhotoLibrary),+ requestAuthorizationForAccessLevel: ADD_ONLY,+ handler: &*handler+ ]+ };+ status = rx.recv().unwrap_or(0);+ }+ if status != 3 && status != 4 {+ return Err("Concat may not add to Photos; allow it under Settings, Concat, Photos".into());+ }+ let url = NSURL::from_file_path(path).ok_or("the export's path is not a file URL")?;+ let change = RcBlock::new(move || {+ // SAFETY: a PHAssetChangeRequest, made inside a change block as+ // Photos requires.+ let _: Option<Retained<AnyObject>> = unsafe {+ msg_send![+ class!(PHAssetChangeRequest),+ creationRequestForAssetFromVideoAtFileURL: &*url+ ]+ };+ });+ // SAFETY: Photos' shared library; `performChangesAndWait:error:` off+ // the main thread, its block called before it returns.+ let saved: Result<(), Retained<NSError>> = unsafe {+ let library: Retained<AnyObject> = msg_send![class!(PHPhotoLibrary), sharedPhotoLibrary];+ msg_send![&library, performChangesAndWait: &*change, error: _]+ };+ saved+ .map(|()| path.to_string_lossy().into_owned())+ .map_err(|error| error.localizedDescription().to_string())+}diff --git a/src/crates/concat/src/lib.rs b/src/crates/concat/src/lib.rsindex f9b2ba33..f85c97ea 100644--- a/src/crates/concat/src/lib.rs+++ b/src/crates/concat/src/lib.rs@@ -39,6 +39,9 @@ mod gpu;mod grading;mod host;mod i18n;+/// The iPhone's pickers and its way to Photos; see the module.+#[cfg(target_os = "ios")]+mod ios;mod meters;mod platform;/// What a phone's own crate installs before the window runs: the way to@@ -181,6 +184,12 @@ pub(crate) fn close_window(/// [`run_with_project`], or [`smoke`] when `smoke` is set.fn start(project: Option<std::path::PathBuf>, smoke: bool) -> Result<(), slint::PlatformError> {+ // What Import and a finished export reach on an iPhone. Android's own+ // crate installs its; iOS runs this crate's binary, so it is here.+ // https://github.com/jub0t/Concat/issues/332+ #[cfg(target_os = "ios")]+ ios::install();+// The interface scale: a percent of the display's own, applied once// the window is up and kept through moves between monitors; see// `platform::apply_ui_scale`. https://github.com/jub0t/Concat/issues/320diff --git a/src/crates/concat/src/panes/export.rs b/src/crates/concat/src/panes/export.rsindex 66bc175a..9f2dbde6 100644--- a/src/crates/concat/src/panes/export.rs+++ b/src/crates/concat/src/panes/export.rs@@ -98,7 +98,14 @@ impl Default for ExportPane {Self {open: false,name: "Untitled".into(),- folder: home_folder("Movies"),+ // An iPhone's sandbox has no Movies the app may make, as it has+ // no Desktop (#299); Documents is the folder Files shows, and a+ // finished export goes on to Photos from there.+ folder: home_folder(if cfg!(target_os = "ios") {+ "Documents/Exports"+ } else {+ "Movies"+ }),resolution: 2,rate: 0,custom: false,diff --git a/src/scripts/ios-app.sh b/src/scripts/ios-app.shindex 6dcc3b82..a7f82e6d 100755--- a/src/scripts/ios-app.sh+++ b/src/scripts/ios-app.sh@@ -51,6 +51,12 @@ platform=iPhoneOS# this file alone, so it cannot be installed at runtime instead.# CADisableMinimumFrameDurationOnPhone lets an iPhone animate at a# ProMotion display's 120Hz rather than capping it at 60.+# UIFileSharingEnabled and LSSupportsOpeningDocumentsInPlace put the app's+# Documents - projects, Imported, Exports - in the Files app; without them+# nothing the app wrote could be reached from outside it (#338).+# NSPhotoLibraryAddUsageDescription is the question asked before a finished+# export is added to Photos (crates/concat/src/ios.rs); the pickers need+# no permission.cat > "$app/Info.plist" <<PLIST<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">@@ -90,7 +96,10 @@ cat > "$app/Info.plist" <<PLIST</dict><key>CADisableMinimumFrameDurationOnPhone</key><true/><key>LSApplicationCategoryType</key><string>public.app-category.video</string>+ <key>UIFileSharingEnabled</key><true/>+ <key>LSSupportsOpeningDocumentsInPlace</key><true/><key>NSPhotoLibraryUsageDescription</key><string>Concat imports the clips you pick.</string>+ <key>NSPhotoLibraryAddUsageDescription</key><string>Concat saves your finished videos to Photos.</string><key>NSMicrophoneUsageDescription</key><string>Concat records voice-over.</string><key>NSHumanReadableCopyright</key><string>AGPL-3.0-or-later. See THIRD_PARTY_NOTICES.md.</string></dict>