Paste, drop and take photos into notes !322

merged merged by cmc on 2026-10-12 05:07 UTC · krz/orgstar:paste-images into main

34 files changed, +814 −60

Layout: unified · split

Sources/OrgApp/AttachActions.swift +55 −4
@@ -7,7 +7,8 @@ import OrgCore
77public struct AttachActions {
88 /// The open file's entry at the caret; nil when no file is open.
99 public var entry: () -> Attachments.Entry?
10 public var apply: (String) -> Void
10 /// The buffer's new text, and where the caret goes; nil keeps it where it is.
11 public var apply: (String, Int?) -> Void
1112 public var show: (String) -> Void
1213 public var ask: (Prompt, @escaping (String?) -> Void) -> Void
1314 public var storeLink: (StoredLink) -> Void
@@ -19,7 +20,7 @@ public struct AttachActions {
1920 public var pick: (Attachments.Method) -> Void
2021
2122 public init(
22 entry: @escaping () -> Attachments.Entry?, apply: @escaping (String) -> Void, show: @escaping (String) -> Void,
23 entry: @escaping () -> Attachments.Entry?, apply: @escaping (String, Int?) -> Void, show: @escaping (String) -> Void,
2324 ask: @escaping (Prompt, @escaping (String?) -> Void) -> Void, storeLink: @escaping (StoredLink) -> Void,
2425 open: @escaping (String) -> Void, reveal: @escaping (String) -> Void, pick: @escaping (Attachments.Method) -> Void
2526 ) {
@@ -47,10 +48,10 @@ public struct AttachActions {
4748 let original = entry.text
4849 do {
4950 let message = try body(&entry)
50 if entry.text != original { apply(entry.text) }
51 if entry.text != original { apply(entry.text, nil) }
5152 if let message { show(message) }
5253 } catch {
53 if entry.text != original { apply(entry.text) }
54 if entry.text != original { apply(entry.text, nil) }
5455 show((error as? Attachments.Failure)?.description ?? error.localizedDescription)
5556 }
5657 }
@@ -184,6 +185,56 @@ public struct AttachActions {
184185 }
185186 }
186187
188 /// Runs `body` on the entry and puts the links it returns at the caret.
189 private func insert(_ body: (inout Attachments.Entry) throws -> [String]) {
190 guard var entry = entry() else { return show("No file is open") }
191 let original = entry.text
192 do {
193 let links = try body(&entry)
194 guard !links.isEmpty else { return }
195 let (text, caret) = ImageYank.inserting(links, into: entry.text, at: ImageYank.map(entry.offset, from: original, to: entry.text))
196 apply(text, caret)
197 let names = links.compactMap { $0.firstMatch(of: /^\[\[attachment:(.*)\]\]$/).map { String($0.1) } }
198 if let message = Self.attached(names) { show(message) }
199 } catch {
200 if entry.text != original { apply(entry.text, nil) }
201 show((error as? Attachments.Failure)?.description ?? error.localizedDescription)
202 }
203 }
204
205 /// `yank-media` with an image: `data` saved as `org-yank-image-save-method` says, with
206 /// extension `ext`, and its link at the caret. `prefix` replaces "clipboard" in the name.
207 public func yankImage(_ data: Data, ext: String, prefix: String = "clipboard") {
208 let method = ImageYank.SaveMethod(OrgPreferences.yankImageSaveMethod())
209 insert { entry in [try ImageYank.save(data, ext: ext, method: method, in: &entry, prefix: prefix)] }
210 }
211
212 /// Files dropped or pasted, as `org-yank-dnd-method` says: attached with `attachMethod`,
213 /// opened, or linked; their links at the caret.
214 public func drop(_ files: [URL], method: ImageYank.DropMethod = OrgPreferences.yankDndMethod(), attachMethod: Attachments.Method = .cp) {
215 guard !files.isEmpty else { return }
216 switch method {
217 case .ask:
218 ask(Prompt(key: "dnd", message: "What to do with file?", choices: ["attach", "open", "insert file: link"])) { answer in
219 switch answer {
220 case "attach": drop(files, method: .attach, attachMethod: attachMethod)
221 case "open": drop(files, method: .open, attachMethod: attachMethod)
222 case "insert file: link": drop(files, method: .fileLink, attachMethod: attachMethod)
223 default: break
224 }
225 }
226 case .open:
227 for file in files { open(file.path) }
228 case .attach, .fileLink:
229 let saveMethod = ImageYank.SaveMethod(OrgPreferences.yankImageSaveMethod())
230 insert { entry in
231 let scoped = files.map { $0.startAccessingSecurityScopedResource() }
232 defer { for (file, on) in zip(files, scoped) where on { file.stopAccessingSecurityScopedResource() } }
233 return try ImageYank.drop(files, method: method, attachMethod: attachMethod, saveMethod: saveMethod, in: &entry)
234 }
235 }
236 }
237
187238 static func attached(_ names: [String]) -> String? {
188239 switch names.count {
189240 case 0: nil
Sources/OrgApp/EmacsImport.swift +5
@@ -575,6 +575,11 @@ public struct EmacsImport: Sendable {
575575 add(name, .string(dir))
576576 case "org-attach-use-inheritance":
577577 if value.symbol == "selective" { add(name, .string("selective")) } else { add(name, .string(truthy ? "t" : "nil")) }
578 case "org-yank-image-save-method":
579 if value.symbol == "attach" { add(name, .string("attach")) } else if let dir = value.string { add(name, .string(dir)) } else { note("not attach or a folder") }
580 case "org-yank-dnd-method":
581 guard let method = value.symbol, ["ask", "attach", "open", "file-link"].contains(method) else { return note("not ask, attach, open or file-link") }
582 add(name, .string(method))
578583 case "org-crypt-tag-matcher":
579584 guard let tag = value.string, tag.range(of: "^[\\w@#%]+$", options: .regularExpression) != nil else { return note("not a single tag") }
580585 add(name, .string(tag))
Sources/OrgApp/ImageYank.swift added +134
@@ -0,0 +1,134 @@
1import Foundation
2import OrgCore
3
4/// Org 9.7's `yank-media` and drag-and-drop handlers (org.el, Org 9.8.7): a pasted image saved
5/// as `org-yank-image-save-method` says, dropped files handled as `org-yank-dnd-method` says,
6/// and their links inserted at the caret. Two differences from Org: links have no
7/// description, and each goes on a line of its own, so they show as inline images.
8public enum ImageYank {
9 /// `org-yank-image-save-method`: an attachment of the entry, or a file in a folder,
10 /// relative to the org file's folder unless absolute.
11 public enum SaveMethod: Equatable, Sendable {
12 case attach
13 case directory(String)
14
15 public init(_ value: String) {
16 self = value.isEmpty || value == "attach" ? .attach : .directory(value)
17 }
18 }
19
20 /// `org-yank-dnd-method`.
21 public enum DropMethod: String, Sendable {
22 case attach, open, fileLink = "file-link", ask
23 }
24
25 /// `org-yank-image-autogen-filename` with the extension: `clipboard-20261011T232238.png`.
26 /// Org's `.%6N` is the part `file-name-with-extension` replaces, so it never shows.
27 public static func fileName(ext: String, date: Date = Date(), prefix: String = "clipboard") -> String {
28 let format = DateFormatter()
29 format.locale = Locale(identifier: "en_US_POSIX")
30 format.dateFormat = "yyyyMMdd'T'HHmmss"
31 return "\(prefix)-\(format.string(from: date)).\(ext)"
32 }
33
34 /// `name`, or `name-2`, `name-3`… before the extension, whichever `dir` doesn't have yet.
35 static func unused(_ name: String, in dir: String) -> String {
36 let base = (name as NSString).deletingPathExtension
37 let ext = (name as NSString).pathExtension
38 var candidate = name
39 var n = 2
40 while FileManager.default.fileExists(atPath: (dir as NSString).appendingPathComponent(candidate)) {
41 candidate = "\(base)-\(n)" + (ext.isEmpty ? "" : "." + ext)
42 n += 1
43 }
44 return candidate
45 }
46
47 /// A `file:` link to `path` from the org file at `orgPath`: relative when it's under the
48 /// file's folder, else absolute with `~` for the home folder.
49 static func fileLink(_ path: String, from orgPath: String) -> String {
50 let folder = (orgPath as NSString).deletingLastPathComponent + "/"
51 let target = path.hasPrefix(folder) ? String(path.dropFirst(folder.count)) : (path as NSString).abbreviatingWithTildeInPath
52 return "[[file:\(target)]]"
53 }
54
55 /// The folder a `directory` method names, made if missing.
56 static func folder(_ dir: String, for entry: Attachments.Entry) throws -> String {
57 let folder = OrgAttach.expand((dir as NSString).expandingTildeInPath, in: (entry.path as NSString).deletingLastPathComponent)
58 try FileManager.default.createDirectory(atPath: folder, withIntermediateDirectories: true)
59 return folder
60 }
61
62 /// `org--image-yank-media-handler`: `data` saved with extension `ext`; the link to it.
63 public static func save(_ data: Data, ext: String, method: SaveMethod, in entry: inout Attachments.Entry,
64 date: Date = Date(), prefix: String = "clipboard") throws -> String {
65 switch method {
66 case .attach:
67 let dir = try Attachments.directoryCreating(&entry)
68 let name = unused(fileName(ext: ext, date: date, prefix: prefix), in: dir)
69 try Attachments.attach(data, named: name, to: &entry)
70 return "[[attachment:\(name)]]"
71 case .directory(let dir):
72 let folder = try folder(dir, for: entry)
73 let file = (folder as NSString).appendingPathComponent(unused(fileName(ext: ext, date: date, prefix: prefix), in: folder))
74 try data.write(to: URL(fileURLWithPath: file))
75 return fileLink(file, from: entry.path)
76 }
77 }
78
79 static let imageExtensions: Set<String> = ["png", "jpg", "jpeg", "gif", "svg", "webp", "tif", "tiff", "bmp", "heic", "avif"]
80
81 /// `org--dnd-attach-file` and the `file-link` case of `org--dnd-local-file-handler` for
82 /// each file; `.open` and `.ask` are the caller's. With `attach`, an image goes to the
83 /// save method's folder when that is a directory, as Org does. The links, in order.
84 public static func drop(_ files: [URL], method: DropMethod, attachMethod: Attachments.Method, saveMethod: SaveMethod,
85 in entry: inout Attachments.Entry) throws -> [String] {
86 try files.map { file in
87 switch method {
88 case .fileLink, .open, .ask:
89 return fileLink(file.standardizedFileURL.path, from: entry.path)
90 case .attach:
91 if case .directory(let dir) = saveMethod, imageExtensions.contains(file.pathExtension.lowercased()) {
92 let folder = try folder(dir, for: entry)
93 let target = (folder as NSString).appendingPathComponent(file.lastPathComponent)
94 let files = FileManager.default
95 switch attachMethod {
96 case .mv: try files.moveItem(atPath: file.path, toPath: target)
97 case .cp: try files.copyItem(atPath: file.path, toPath: target)
98 case .ln: try files.linkItem(atPath: file.path, toPath: target)
99 case .lns: try files.createSymbolicLink(atPath: target, withDestinationPath: file.path)
100 }
101 return fileLink(target, from: entry.path)
102 }
103 return "[[\(try Attachments.attach(file, method: attachMethod, to: &entry).link)]]"
104 }
105 }
106 }
107
108 /// `text` with `links` inserted at `offset`, one per line: a line break goes before them
109 /// when the line has text before the caret, and after them when it has text after. The
110 /// caret after the last link.
111 public static func inserting(_ links: [String], into text: String, at offset: Int) -> (text: String, caret: Int) {
112 let ns = text as NSString
113 let offset = min(max(offset, 0), ns.length)
114 let line = ns.lineRange(for: NSRange(location: offset, length: 0))
115 var contentEnd = NSMaxRange(line)
116 while contentEnd > line.location, [0x0A, 0x0D].contains(ns.character(at: contentEnd - 1)) { contentEnd -= 1 }
117 let before = ns.substring(with: NSRange(location: line.location, length: offset - line.location))
118 let after = offset < contentEnd ? ns.substring(with: NSRange(location: offset, length: contentEnd - offset)) : ""
119 let lead = before.trimmingCharacters(in: .whitespaces).isEmpty ? "" : "\n"
120 let trail = after.trimmingCharacters(in: .whitespaces).isEmpty ? "" : "\n"
121 let body = lead + links.joined(separator: "\n")
122 let new = ns.replacingCharacters(in: NSRange(location: offset, length: 0), with: body + trail)
123 return (new, offset + (body as NSString).length)
124 }
125
126 /// `offset` in `old` moved to where it is in `new`, for a change that touched one span;
127 /// text inserted at `offset`, such as a property drawer, ends up before it.
128 public static func map(_ offset: Int, from old: String, to new: String) -> Int {
129 guard let edit = TextEdit.between(old, new).first else { return offset }
130 if offset < edit.range.lowerBound { return offset }
131 let delta = (new as NSString).length - (old as NSString).length
132 return max(offset, edit.range.upperBound) + delta
133 }
134}
Sources/OrgApp/OrgPreferences.swift +8
@@ -175,6 +175,14 @@ public enum OrgPreferences {
175175 default: nil
176176 }
177177 }
178 /// `org-yank-image-save-method`: "attach", or the folder pasted images go in.
179 public static func yankImageSaveMethod(_ defaults: UserDefaults = .standard) -> String {
180 string("yankImageSaveMethod", defaults).nonEmpty ?? "attach"
181 }
182 /// `org-yank-dnd-method`.
183 public static func yankDndMethod(_ defaults: UserDefaults = .standard) -> ImageYank.DropMethod {
184 ImageYank.DropMethod(rawValue: string("yankDndMethod", defaults)) ?? .ask
185 }
178186 /// `org-crypt-tag-matcher`, a tag.
179187 public static func cryptTag(_ defaults: UserDefaults = .standard) -> String {
180188 let tag = string("cryptTagMatcher", defaults).trimmingCharacters(in: .whitespaces)
Sources/OrgApp/UserConfig.swift +5
@@ -173,6 +173,11 @@ public enum UserConfig {
173173 Setting(section: "", key: "org-attach-use-inheritance", defaultsKey: "attachUseInheritance",
174174 kind: .choice([("selective", "selective"), ("t", "t"), ("nil", "nil")]), fallback: .string("selective"),
175175 comment: "whether DIR and ID inherit for attachments: selective (as org-use-property-inheritance), t or nil", legacy: ""),
176 Setting(section: "", key: "org-yank-image-save-method", defaultsKey: "yankImageSaveMethod", kind: .string, fallback: .string("attach"),
177 comment: "where pasted images go: attach (the entry's attachments) or a folder, relative to the org file's folder unless absolute", legacy: ""),
178 Setting(section: "", key: "org-yank-dnd-method", defaultsKey: "yankDndMethod",
179 kind: .choice([("ask", "ask"), ("attach", "attach"), ("open", "open"), ("file-link", "file-link")]), fallback: .string("ask"),
180 comment: "files dropped on the editor: ask, attach, open or file-link", legacy: ""),
176181 Setting(section: "", key: "org-crypt-tag-matcher", defaultsKey: "cryptTagMatcher", kind: .string, fallback: .string("crypt"),
177182 comment: "the tag of entries Encrypt Tagged Entries encrypts", legacy: ""),
178183 Setting(section: "", key: "org-display-remote-inline-images", defaultsKey: "remoteInlineImages",
Sources/OrgEditorAppKit/EditorCommands.swift +1
@@ -181,6 +181,7 @@ public enum EditorCommands {
181181 edit("backward-kill-word", "Kill Word Backward", "deleteWordBackward:"),
182182 edit("kill-line", "Kill Line", "deleteToEndOfParagraph:"),
183183 edit("yank", "Yank", "yank:"),
184 edit("yank-media", "Yank Media", "paste:"),
184185 edit("select-all", "Select All", "selectAll:"),
185186 edit("kill-region", "Kill Region", "cut:"),
186187 edit("copy-region", "Copy Region", "copy:"),
Sources/OrgEditorAppKit/Fragments.swift +5 −2
@@ -114,9 +114,12 @@ final class LatexFragment: NSTextLayoutFragment, @unchecked Sendable {
114114final class InlineImageBox: NSObject, @unchecked Sendable {
115115 let image: NSImage
116116 let size: CGSize
117 init(image: NSImage, size: CGSize) {
117 /// Drawn under the line's text, which shows while the caret is on it.
118 let below: Bool
119 init(image: NSImage, size: CGSize, below: Bool = false) {
118120 self.image = image
119121 self.size = size
122 self.below = below
120123 }
121124}
122125
@@ -133,7 +136,7 @@ final class ImageFragment: NSTextLayoutFragment, @unchecked Sendable {
133136
134137 private var frame: CGRect? {
135138 guard let box = (textElement as? NSTextParagraph).flatMap({ Self.image($0.attributedString) }), let line = textLineFragments.first else { return nil }
136 return CGRect(x: line.typographicBounds.minX, y: line.typographicBounds.minY + 2, width: box.size.width, height: box.size.height)
139 return CGRect(x: line.typographicBounds.minX, y: (box.below ? line.typographicBounds.maxY : line.typographicBounds.minY) + 2, width: box.size.width, height: box.size.height)
137140 }
138141
139142 override var renderingSurfaceBounds: CGRect {
Sources/OrgEditorAppKit/Keys.swift +3
@@ -17,6 +17,9 @@ final class OrgTextView: NSTextView {
1717 /// The text as shown, for accessibility.
1818 var accessibleText: (() -> AccessibleText)?
1919 var onMouseDown: (() -> Void)?
20 /// Files and an image pasted or dropped; each returns whether it took them.
21 var onFiles: (([URL]) -> Bool)?
22 var onImage: ((Data, String) -> Bool)?
2023 /// The view gained or lost focus, or its window key status: the selection's color changes.
2124 var onFocusChange: (() -> Void)?
2225 private var keyObservers: [NSObjectProtocol] = []
Sources/OrgEditorAppKit/OrgEditor+Images.swift +7 −5
@@ -65,7 +65,7 @@ extension OrgEditor {
6565 }
6666
6767 /// Image lines in `range` show the image over the link, which is hidden unless the caret is
68 /// on the line.
68 /// on the line; then the image goes under it.
6969 func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) {
7070 guard showsImages, isOrg else { return }
7171 let text = storage.string as NSString
@@ -80,13 +80,15 @@ extension OrgEditor {
8080 let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0
8181 let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0))
8282 // Invisible, keeping the line's height, so line numbers stay apart.
83 if line.location != revealed.location, content.length > 0 {
83 let shown = line.location == revealed.location && content.length > 0
84 if !shown, content.length > 0 {
8485 storage.addAttributes([.foregroundColor: NSColor.clear, .underlineStyle: 0], range: content)
8586 }
86 storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height)), range: NSRange(location: line.location, length: max(1, content.length)))
87 storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height), below: shown), range: NSRange(location: line.location, length: max(1, content.length)))
8788 let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle()
88 // The image sits where the line is; the spacing makes room for the rest of it.
89 style.paragraphSpacing = max(0, height + 4 - theme.font.boundingRectForFont.height)
89 // The image sits where the line is, or under it while the link shows; the spacing
90 // makes room for the rest of it.
91 style.paragraphSpacing = shown ? height + 4 : max(0, height + 4 - theme.font.boundingRectForFont.height)
9092 storage.addAttribute(.paragraphStyle, value: style, range: line)
9193 }
9294 }
Sources/OrgEditorAppKit/OrgEditor.swift +18
@@ -172,6 +172,18 @@ public final class OrgEditor: NSObject {
172172 self.accessibleCache = (self.storageGeneration, text)
173173 return text
174174 }
175 view.onFiles = { [weak self, unowned view] files in
176 guard let self, let onFiles = self.onFiles, self.isOrg else { return false }
177 self.active = view
178 onFiles(files)
179 return true
180 }
181 view.onImage = { [weak self, unowned view] data, ext in
182 guard let self, let onImage = self.onImage, self.isOrg else { return false }
183 self.active = view
184 onImage(data, ext)
185 return true
186 }
175187 view.onMouseDown = { [weak self, unowned view] in
176188 self?.active = view
177189 self?.markActive = false
@@ -364,6 +376,12 @@ public final class OrgEditor: NSObject {
364376 public var knownTags: @Sendable () -> [String] = { [] }
365377 /// Effects other than messages, for the app to carry out.
366378 public var onEffect: ((Effect) -> Void)?
379 /// Where paste looks for images and files; scripts checking the app set another.
380 public static var pasteboard = NSPasteboard.general
381 /// Files pasted or dropped at the caret; nil leaves them to the text view.
382 public var onFiles: (([URL]) -> Void)?
383 /// An image pasted or dropped at the caret, with its extension (`yank-media`).
384 public var onImage: ((Data, String) -> Void)?
367385
368386 public var keymap: Keymap {
369387 get { dispatcher.keymap }
Sources/OrgEditorAppKit/OrgTextView+Media.swift added +60
@@ -0,0 +1,60 @@
1#if os(macOS)
2import AppKit
3
4/// Images and files pasted or dropped on the text view, for `yank-media` and Org's
5/// drag-and-drop handlers. Text goes to the text system as before.
6extension OrgTextView {
7 static let jpeg = NSPasteboard.PasteboardType("public.jpeg")
8 static let gif = NSPasteboard.PasteboardType("com.compuserve.gif")
9
10 /// The files on `pasteboard`, if it has any.
11 static func files(on pasteboard: NSPasteboard) -> [URL]? {
12 let urls = pasteboard.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL] ?? []
13 return urls.isEmpty ? nil : urls
14 }
15
16 /// The image on `pasteboard` and the extension for it, when there is no text: PNG, JPEG
17 /// and GIF as they are, anything else AppKit reads as PNG.
18 static func image(on pasteboard: NSPasteboard) -> (data: Data, ext: String)? {
19 guard pasteboard.availableType(from: [.string]) == nil else { return nil }
20 if let data = pasteboard.data(forType: .png) { return (data, "png") }
21 if let data = pasteboard.data(forType: jpeg) { return (data, "jpeg") }
22 if let data = pasteboard.data(forType: gif) { return (data, "gif") }
23 guard let image = NSImage(pasteboard: pasteboard), let tiff = image.tiffRepresentation,
24 let png = NSBitmapImageRep(data: tiff)?.representation(using: .png, properties: [:]) else { return nil }
25 return (png, "png")
26 }
27
28 /// Hands files or an image to the editor; false when it doesn't take them.
29 func takeMedia(from pasteboard: NSPasteboard) -> Bool {
30 guard isEditable else { return false }
31 if let files = Self.files(on: pasteboard) { return onFiles?(files) ?? false }
32 if let image = Self.image(on: pasteboard) { return onImage?(image.data, image.ext) ?? false }
33 return false
34 }
35
36 override func paste(_ sender: Any?) {
37 if !takeMedia(from: OrgEditor.pasteboard) { super.paste(sender) }
38 }
39
40 override var acceptableDragTypes: [NSPasteboard.PasteboardType] {
41 super.acceptableDragTypes + [.fileURL, .png, .tiff, Self.jpeg, Self.gif]
42 }
43
44 override func dragOperation(for dragInfo: any NSDraggingInfo, type: NSPasteboard.PasteboardType) -> NSDragOperation {
45 if isEditable, Self.files(on: dragInfo.draggingPasteboard) != nil || Self.image(on: dragInfo.draggingPasteboard) != nil { return .copy }
46 return super.dragOperation(for: dragInfo, type: type)
47 }
48
49 override func performDragOperation(_ sender: any NSDraggingInfo) -> Bool {
50 let pasteboard = sender.draggingPasteboard
51 guard isEditable, Self.files(on: pasteboard) != nil || Self.image(on: pasteboard) != nil else {
52 return super.performDragOperation(sender)
53 }
54 window?.makeFirstResponder(self)
55 let index = characterIndexForInsertion(at: convert(sender.draggingLocation, from: nil))
56 setSelectedRange(NSRange(location: index, length: 0))
57 return takeMedia(from: pasteboard)
58 }
59}
60#endif
Sources/Orgstar/ContentView.swift +8 −6
@@ -295,6 +295,8 @@ struct ContentView: View {
295295 .onChange(of: editorSettings, initial: true) { _, settings in commands.editorSettings = settings }
296296 .onAppear {
297297 commands.externalHandler = runExternal
298 commands.filesHandler = { attachActions.drop($0) }
299 commands.imageHandler = { attachActions.yankImage($0, ext: $1) }
298300 // `org-clock-out-when-done`, and the notification when the Effort runs out.
299301 clock.notifications = SystemReminderCenter.isAvailable ? SystemReminderCenter() : nil
300302 session.textChanged = { [weak session, weak clock, weak commands] path in
@@ -704,7 +706,7 @@ struct ContentView: View {
704706 let context = editor.context()
705707 return Attachments.Entry(text: context.text, offset: context.caret, path: path, options: context.options)
706708 },
707 apply: applyText, show: { [commands] in commands.show($0) }, ask: { [commands] in commands.ask($0, reply: $1) },
709 apply: { applyText($0, caret: $1) }, show: { [commands] in commands.show($0) }, ask: { [commands] in commands.ask($0, reply: $1) },
708710 storeLink: { [commands] in _ = StoredLink.add($0, to: &commands.storedLinks) },
709711 open: { [session, workspace, commands] file in
710712 if let message = LinkOpener.open(OrgLink(type: "file", path: file, raw: "file:" + file), session: session, workspace: workspace) { commands.show(message) }
@@ -737,7 +739,7 @@ struct ContentView: View {
737739 case .plotImage(_, let url):
738740 PlotSheet(content: .image(url))
739741 case .crypt(_, let request):
740 CryptSheet(request: request, text: { session.document?.text ?? "" }, apply: applyText) { message in
742 CryptSheet(request: request, text: { session.document?.text ?? "" }, apply: { applyText($0) }) { message in
741743 self.panel = nil
742744 if let message { commands.show(message) }
743745 }
@@ -750,12 +752,12 @@ struct ContentView: View {
750752 }
751753 }
752754
753 /// `new` in place of the buffer's text, as one edit.
754 private func applyText(_ new: String) {
755 /// `new` in place of the buffer's text, as one edit, with the caret at `caret` or where it was.
756 private func applyText(_ new: String, caret: Int? = nil) {
755757 guard let editor = commands.editor else { return }
756758 let context = editor.context()
757 editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new),
758 selection: [min(context.caret, (new as NSString).length)..<min(context.caret, (new as NSString).length)])))
759 let caret = min(caret ?? context.caret, (new as NSString).length)
760 editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
759761 }
760762
761763 /// `org-plot/gnuplot` for the table at the caret: through gnuplot when it's installed, as
Sources/Orgstar/DevelopmentHooks.swift +4
@@ -1,4 +1,5 @@
11import AppKit
2import OrgEditorAppKit
23
34/// Switches for checking the app from scripts, read from the environment:
45/// - `ORGSTAR_DATA_DIR`: where the index and roots live (see `WorkspaceModel.defaultDirectory`).
@@ -9,6 +10,8 @@ import AppKit
910/// sheet or prompt they open is what the snapshot renders.
1011/// - `ORGSTAR_ANSWERS`: answers to the prompts those commands ask, in order, separated by commas.
1112/// - `ORGSTAR_URL`: an `org-protocol://` link to handle at launch, as if opened from a browser.
13/// - `ORGSTAR_PASTEBOARD`: the name of a pasteboard to paste images and files from, instead of
14/// the clipboard.
1215/// - `ORGSTAR_APPEARANCE`: `dark` or `light`, instead of the system's.
1316/// - `ORGSTAR_SNAPSHOT`: after `ORGSTAR_SNAPSHOT_DELAY` seconds (default 3), render the main
1417/// window to this PNG path and quit. Rendering from inside the app needs no screen-recording
@@ -24,6 +27,7 @@ enum DevelopmentHooks {
2427 @MainActor
2528 static func scheduleSnapshot() {
2629 let environment = ProcessInfo.processInfo.environment
30 if let name = environment["ORGSTAR_PASTEBOARD"] { OrgEditor.pasteboard = NSPasteboard(name: NSPasteboard.Name(name)) }
2731 if let appearance = environment["ORGSTAR_APPEARANCE"] {
2832 NSApp.appearance = NSAppearance(named: appearance == "dark" ? .darkAqua : .aqua)
2933 }
Sources/Orgstar/OrgstarApp.swift +3
@@ -31,6 +31,9 @@ final class AppCommands {
3131 var editorSettings = EditorSettings()
3232 /// Runs work outside the text (a table recalculation in Emacs); the main window sets it.
3333 var externalHandler: ((ExternalRequest) -> Void)?
34 /// Files and images pasted or dropped on an editor; the main window sets them.
35 var filesHandler: (([URL]) -> Void)?
36 var imageHandler: ((Data, String) -> Void)?
3437 /// Tags used across the workspace, for tag completion; the main window sets it.
3538 var knownTags: () -> [String] = { [] }
3639 /// The pending key prefix, and what can follow it.
Sources/Orgstar/PaneView.swift +2
@@ -124,6 +124,8 @@ struct PaneView: NSViewRepresentable {
124124 session.reveal(offset)
125125 }
126126 editor.onExternal = { [weak commands] request in commands?.externalHandler?(request) }
127 editor.onFiles = { [weak commands] in commands?.filesHandler?($0) }
128 editor.onImage = { [weak commands] in commands?.imageHandler?($0, $1) }
127129 editor.knownTags = { [weak commands] in MainActor.assumeIsolated { commands?.knownTags() ?? [] } }
128130 editor.onPrompt = { [weak commands] prompt, reply in commands?.ask(prompt, reply: reply) }
129131 editor.onEffect = { [weak commands, weak session] effect in
Sources/OrgstarMobile/CameraPicker.swift added +35
@@ -0,0 +1,35 @@
1#if os(iOS)
2import SwiftUI
3import UIKit
4
5/// The camera, for a photo to attach; `taken` gets its JPEG data, or nil when cancelled.
6struct CameraPicker: UIViewControllerRepresentable {
7 let taken: (Data?) -> Void
8
9 static var isAvailable: Bool { UIImagePickerController.isSourceTypeAvailable(.camera) }
10
11 func makeUIViewController(context: Context) -> UIImagePickerController {
12 let picker = UIImagePickerController()
13 picker.sourceType = .camera
14 picker.delegate = context.coordinator
15 return picker
16 }
17
18 func updateUIViewController(_ picker: UIImagePickerController, context: Context) {}
19
20 func makeCoordinator() -> Coordinator { Coordinator(taken: taken) }
21
22 final class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
23 let taken: (Data?) -> Void
24 init(taken: @escaping (Data?) -> Void) { self.taken = taken }
25
26 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
27 taken((info[.originalImage] as? UIImage)?.jpegData(compressionQuality: 0.9))
28 }
29
30 func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
31 taken(nil)
32 }
33 }
34}
35#endif
Sources/OrgstarMobile/EditorScreen.swift +18 −4
@@ -63,6 +63,7 @@ struct EditorScreen: View {
6363 /// org-attach's file picker is up, for this method.
6464 @State private var attaching: Attachments.Method?
6565 @State private var attachingPhotos = false
66 @State private var takingPhoto = false
6667 @State private var photos: [PhotosPickerItem] = []
6768 /// A file shown in Quick Look.
6869 @State private var previewed: URL?
@@ -149,6 +150,9 @@ struct EditorScreen: View {
149150 Menu("Attachments", systemImage: "paperclip") {
150151 Button("Attach File…", systemImage: "doc.badge.plus") { attaching = .cp }
151152 Button("Attach Photo or Video…", systemImage: "photo.badge.plus") { attachingPhotos = true }
153 if CameraPicker.isAvailable {
154 Button("Take Photo…", systemImage: "camera") { takingPhoto = true }
155 }
152156 Button("Attach File from URL…", systemImage: "link.badge.plus") { attachActions.run("app.attach.url") }
153157 Button("New Attachment…", systemImage: "square.and.pencil") { attachActions.run("app.attach.new") }
154158 Button("Open Attachment…", systemImage: "paperclip") { attachActions.run("app.attach.open") }
@@ -275,6 +279,13 @@ struct EditorScreen: View {
275279 }
276280 }
277281 .photosPicker(isPresented: $attachingPhotos, selection: $photos, matching: .any(of: [.images, .videos]))
282 .fullScreenCover(isPresented: $takingPhoto) {
283 CameraPicker { data in
284 takingPhoto = false
285 if let data { attachActions.yankImage(data, ext: "jpg", prefix: "photo") }
286 }
287 .ignoresSafeArea()
288 }
278289 .onChange(of: photos) { _, items in
279290 guard !items.isEmpty else { return }
280291 photos = []
@@ -415,6 +426,9 @@ struct EditorScreen: View {
415426 editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) }
416427 editor.keymap = model.keymap
417428 editor.modal = model.modalKeys
429 // Dropped files are copies the drop made, so they are attached, not linked or opened.
430 editor.onFiles = { attachActions.drop($0, method: .attach, attachMethod: .mv) }
431 editor.onImage = { attachActions.yankImage($0, ext: $1) }
418432 editor.onAppCommand = { id in
419433 if Self.paneCommands.contains(id) {
420434 if let onPaneCommand { onPaneCommand(id) } else { message = "Not available here" }
@@ -491,10 +505,10 @@ extension EditorScreen {
491505 let context = editor.editContext()
492506 return Attachments.Entry(text: context.text, offset: context.caret, path: path, options: context.options)
493507 },
494 apply: { new in
508 apply: { new, caret in
495509 guard let editor else { return }
496510 let context = editor.editContext()
497 let caret = min(context.caret, (new as NSString).length)
511 let caret = min(caret ?? context.caret, (new as NSString).length)
498512 _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
499513 },
500514 show: { message = $0 },
@@ -507,7 +521,7 @@ extension EditorScreen {
507521 pick: { attaching = $0 })
508522 }
509523
510 /// Photos and videos attached under the names Photos gives them.
524 /// Photos and videos attached under the names Photos gives them, linked at the caret.
511525 private func attachPhotos(_ items: [PhotosPickerItem]) {
512526 Task { @MainActor in
513527 var urls: [URL] = []
@@ -515,7 +529,7 @@ extension EditorScreen {
515529 if let picked = try? await item.loadTransferable(type: PickedFile.self) { urls.append(picked.url) }
516530 }
517531 if urls.count < items.count { message = "Can't read \(items.count - urls.count) of the items" }
518 if !urls.isEmpty { attachActions.attach(urls, method: .mv) }
532 if !urls.isEmpty { attachActions.drop(urls, method: .attach, attachMethod: .mv) }
519533 }
520534 }
521535
Sources/OrgstarMobile/KeyedTextView+Media.swift added +75
@@ -0,0 +1,75 @@
1#if os(iOS)
2import UIKit
3import UniformTypeIdentifiers
4
5/// Images pasted and files dropped on the text view, for `yank-media` and Org's drag-and-drop
6/// handlers. Text goes to the text system as before.
7extension KeyedTextView: UITextDropDelegate {
8 /// The image on `pasteboard` and the extension for it, when there is no text: PNG, JPEG
9 /// and GIF as they are, anything else UIKit reads as PNG.
10 static func image(on pasteboard: UIPasteboard) -> (data: Data, ext: String)? {
11 guard !pasteboard.hasStrings, pasteboard.hasImages else { return nil }
12 for (type, ext) in [(UTType.png, "png"), (.jpeg, "jpeg"), (.gif, "gif")] {
13 if let data = pasteboard.data(forPasteboardType: type.identifier) { return (data, ext) }
14 }
15 return pasteboard.image?.pngData().map { ($0, "png") }
16 }
17
18 override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
19 if action == #selector(paste(_:)), isEditable, onImage != nil, MobileEditor.pasteboard.hasImages { return true }
20 return super.canPerformAction(action, withSender: sender)
21 }
22
23 override func paste(_ sender: Any?) {
24 if isEditable, let image = Self.image(on: MobileEditor.pasteboard), onImage?(image.data, image.ext) == true { return }
25 super.paste(sender)
26 }
27
28 /// A drop of files without text, which the editor attaches.
29 func takesDrop(_ session: any UIDropSession) -> Bool {
30 isEditable && onFiles != nil && !session.hasItemsConforming(toTypeIdentifiers: [UTType.plainText.identifier])
31 && session.items.allSatisfy { $0.itemProvider.registeredContentTypes.contains { $0.conforms(to: .data) } }
32 }
33
34 func textDroppableView(_ textDroppableView: UIView & UITextDroppable, proposalForDrop drop: any UITextDropRequest) -> UITextDropProposal {
35 guard takesDrop(drop.dropSession) else { return drop.suggestedProposal }
36 let proposal = UITextDropProposal(operation: .copy)
37 proposal.dropPerformer = .delegate
38 return proposal
39 }
40
41 func textDroppableView(_ textDroppableView: UIView & UITextDroppable, willPerformDrop drop: any UITextDropRequest) {
42 guard takesDrop(drop.dropSession) else { return }
43 selectedRange = NSRange(location: offset(from: beginningOfDocument, to: drop.dropPosition), length: 0)
44 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("Dropped-\(UUID().uuidString)")
45 try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
46 let providers = drop.dropSession.items.map(\.itemProvider)
47 let files = DroppedFiles()
48 let group = DispatchGroup()
49 for (index, provider) in providers.enumerated() {
50 guard let type = provider.registeredContentTypes.first(where: { $0.conforms(to: .data) }) else { continue }
51 group.enter()
52 _ = provider.loadFileRepresentation(for: type, openInPlace: false) { url, _, _ in
53 defer { group.leave() }
54 guard let url else { return }
55 // Each in a folder of its own, so two drops of the same name stay apart.
56 let target = folder.appendingPathComponent("\(index)").appendingPathComponent(url.lastPathComponent)
57 try? FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
58 if (try? FileManager.default.copyItem(at: url, to: target)) != nil { files.add(target, at: index) }
59 }
60 }
61 group.notify(queue: .main) { [weak self] in
62 let dropped = files.inOrder
63 if !dropped.isEmpty { _ = self?.onFiles?(dropped) }
64 }
65 }
66}
67
68/// Files copied out of a drop's item providers, which call back on their own queues.
69private final class DroppedFiles: @unchecked Sendable {
70 private let lock = NSLock()
71 private var files: [Int: URL] = [:]
72 func add(_ file: URL, at index: Int) { lock.withLock { files[index] = file } }
73 var inOrder: [URL] { lock.withLock { files.sorted { $0.key < $1.key }.map(\.value) } }
74}
75#endif
Sources/OrgstarMobile/MobileEditor+Display.swift +7 −5
@@ -111,7 +111,7 @@ extension MobileEditor {
111111 }
112112
113113 /// Image lines in `range` show the image over the link, which is hidden unless the caret is
114 /// on the line.
114 /// on the line; then the image goes under it.
115115 func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) {
116116 guard showsImages else { return }
117117 let text = storage.string as NSString
@@ -127,13 +127,15 @@ extension MobileEditor {
127127 let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0
128128 let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0))
129129 // Invisible, keeping the line's height.
130 if line.location != revealed.location, content.length > 0 {
130 let shown = line.location == revealed.location && content.length > 0
131 if !shown, content.length > 0 {
131132 storage.addAttributes([.foregroundColor: UIColor.clear, .underlineStyle: 0], range: content)
132133 }
133 storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height)), range: NSRange(location: line.location, length: max(1, content.length)))
134 storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height), below: shown), range: NSRange(location: line.location, length: max(1, content.length)))
134135 let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle()
135 // The image sits where the line is; the spacing makes room for the rest of it.
136 style.paragraphSpacing = max(0, height + 4 - theme.font.lineHeight)
136 // The image sits where the line is, or under it while the link shows; the spacing
137 // makes room for the rest of it.
138 style.paragraphSpacing = shown ? height + 4 : max(0, height + 4 - theme.font.lineHeight)
137139 storage.addAttribute(.paragraphStyle, value: style, range: line)
138140 }
139141 }
Sources/OrgstarMobile/MobileEditor.swift +19
@@ -95,6 +95,12 @@ final class MobileEditor: NSObject, DocumentBuffer {
9595 var onColumnView: ((ColumnView.View) -> Void)?
9696 /// Commands the app runs, as `app.clock.in`.
9797 var onAppCommand: ((String) -> Void)?
98 /// Where paste looks for an image; scripts checking the app set another.
99 static var pasteboard = UIPasteboard.general
100 /// Files dropped at the caret; nil leaves them to the text view.
101 var onFiles: (([URL]) -> Void)?
102 /// An image pasted at the caret, with its extension (`yank-media`).
103 var onImage: ((Data, String) -> Void)?
98104 /// Tags used across the workspace, for completion.
99105 var knownTags: @Sendable () -> [String] = { [] }
100106
@@ -171,6 +177,19 @@ final class MobileEditor: NSObject, DocumentBuffer {
171177 return handleKey(key)
172178 }
173179 view.onLayout = { [weak self] in self?.viewResized() }
180 view.onFiles = { [weak self, weak view] files in
181 guard let self, let onFiles else { return false }
182 if let view { focus(view) }
183 onFiles(files)
184 return true
185 }
186 view.onImage = { [weak self, weak view] data, ext in
187 guard let self, let onImage else { return false }
188 if let view { focus(view) }
189 onImage(data, ext)
190 return true
191 }
192 view.textDropDelegate = view
174193 view.isEditable = editable
175194 view.autocorrectionType = .no
176195 view.autocapitalizationType = .none
Sources/OrgstarMobile/MobileFragments.swift +8 −2
@@ -36,6 +36,9 @@ final class FragmentStyle: @unchecked Sendable {
3636/// A text view that offers hardware-keyboard presses to the editor's keymap first.
3737final class KeyedTextView: UITextView {
3838 var keyHandler: ((UIKey) -> Bool)?
39 /// Files dropped and an image pasted; each returns whether it took them.
40 var onFiles: (([URL]) -> Bool)?
41 var onImage: ((Data, String) -> Bool)?
3942 /// Keys the editor took, whose release the text system doesn't see. Optional: made by
4043 /// UIKit's `init(usingTextLayoutManager:)`, the view skips Swift's default values.
4144 private var handled: Set<UIKeyboardHIDUsage>?
@@ -121,9 +124,12 @@ final class LatexBox: NSObject, @unchecked Sendable {
121124final class InlineImageBox: NSObject, @unchecked Sendable {
122125 let image: UIImage
123126 let size: CGSize
124 init(image: UIImage, size: CGSize) {
127 /// Drawn under the line's text, which shows while the caret is on it.
128 let below: Bool
129 init(image: UIImage, size: CGSize, below: Bool = false) {
125130 self.image = image
126131 self.size = size
132 self.below = below
127133 }
128134}
129135
@@ -217,7 +223,7 @@ final class OrgLineFragment: NSTextLayoutFragment, @unchecked Sendable {
217223
218224 private var imageRect: CGRect? {
219225 guard let image, let line = textLineFragments.first else { return nil }
220 return CGRect(x: line.typographicBounds.minX, y: line.typographicBounds.minY + 2, width: image.size.width, height: image.size.height)
226 return CGRect(x: line.typographicBounds.minX, y: (image.below ? line.typographicBounds.maxY : line.typographicBounds.minY) + 2, width: image.size.width, height: image.size.height)
221227 }
222228
223229 override var renderingSurfaceBounds: CGRect {
Sources/OrgstarMobile/OrgstarMobileApp.swift +6
@@ -262,6 +262,12 @@ struct RootView: View {
262262 takeShared()
263263 // Development: `ORGSTAR_ROOT` adds a folder at launch, as on the Mac.
264264 if let root = ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
265 // `ORGSTAR_PASTE_IMAGE`: paste takes this PNG from a pasteboard of the app's own.
266 if let image = ProcessInfo.processInfo.environment["ORGSTAR_PASTE_IMAGE"], let data = try? Data(contentsOf: URL(fileURLWithPath: image)),
267 let pasteboard = UIPasteboard(name: UIPasteboard.Name("orgstar-check"), create: true) {
268 pasteboard.setData(data, forPasteboardType: "public.png")
269 MobileEditor.pasteboard = pasteboard
270 }
265271 workspace.startWatching()
266272 await workspace.refresh()
267273 }
Tests/OrgAppTests/EmacsImportTests.swift +13
@@ -184,6 +184,19 @@ struct EmacsImportTests {
184184 #expect(s["org-icalendar-combined-agenda-file"] == .string("~/cal/org.ics"))
185185 }
186186
187 @Test func readsYankSettings() throws {
188 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-import-\(UUID().uuidString)")
189 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
190 defer { try? FileManager.default.removeItem(at: folder) }
191 try #"""
192 (setq org-yank-image-save-method "images/"
193 org-yank-dnd-method 'attach)
194 """#.write(to: folder.appendingPathComponent("init.el"), atomically: true, encoding: .utf8)
195 let s = settings(EmacsImport.scan(EmacsImport.files(in: folder)))
196 #expect(s["org-yank-image-save-method"] == .string("images/"))
197 #expect(s["org-yank-dnd-method"] == .string("attach"))
198 }
199
187200 @Test func readsLiterateConfig() throws {
188201 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-import-\(UUID().uuidString)")
189202 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
Tests/OrgAppTests/ImageYankTests.swift added +162
@@ -0,0 +1,162 @@
1import Foundation
2import OrgCore
3import Testing
4@testable import OrgApp
5
6struct ImageYankTests {
7 /// An ID per file, ending in its name's letter.
8 static let id = "6a1b2c3d-0000-4000-8000-00000000000"
9 static let notes = """
10 #+title: Notes
11 Free text.
12 * Task
13 Body.
14
15 """
16 static var noon: Date {
17 DateComponents(calendar: Calendar.current, year: 2024, month: 1, day: 1, hour: 12).date!
18 }
19
20 static func folder() throws -> URL {
21 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-yank-\(UUID().uuidString)").resolvingSymlinksInPath()
22 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
23 return folder
24 }
25
26 @Test func fileNameIsOrgsAutogeneratedName() {
27 #expect(ImageYank.fileName(ext: "png", date: Self.noon) == "clipboard-20240101T120000.png")
28 #expect(ImageYank.fileName(ext: "jpg", date: Self.noon, prefix: "photo") == "photo-20240101T120000.jpg")
29 }
30
31 /// The text and files `org--image-yank-media-handler` leaves, without the link it inserts:
32 /// in an entry, before the first heading (a file-level ID), and into a folder.
33 @Test func savingMatchesEmacs() throws {
34 let folder = try Self.folder()
35 defer { try? FileManager.default.removeItem(at: folder) }
36 let dir = folder.path
37 for name in ["a", "b", "c"] { try Self.notes.write(toFile: "\(dir)/\(name).org", atomically: true, encoding: .utf8) }
38 let form = #"""
39 (progn
40 (require 'org) (require 'org-attach) (require 'json)
41 (let ((out nil)
42 (org-yank-image-file-name-function (lambda () "clipboard-20240101T120000.000000")))
43 (cl-letf (((symbol-function 'org-id-new) (lambda (&rest _) (concat "\#(Self.id)" (file-name-base (buffer-file-name))))))
44 (cl-flet ((yank (file where method)
45 (with-current-buffer (find-file-noselect (concat "\#(dir)/" file))
46 (goto-char (point-min)) (search-forward where)
47 (let ((org-yank-image-save-method method) (start (copy-marker (point))))
48 (org--image-yank-media-handler 'image/png "PNG")
49 (push (buffer-substring-no-properties start (point)) out)
50 (delete-region start (point)))
51 (push (buffer-substring-no-properties (point-min) (point-max)) out))))
52 (yank "a.org" "Body." 'attach)
53 (yank "b.org" "Free text." 'attach)
54 (yank "c.org" "Body." "img/")))
55 (with-temp-file "\#(dir)/out.json" (insert (json-encode (vconcat (nreverse out)))))))
56 """#
57 let process = Process()
58 process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
59 process.arguments = [ProcessInfo.processInfo.environment["ORGSTAR_EMACS"] ?? "emacs", "-Q", "--batch", "--eval", form]
60 process.currentDirectoryURL = folder
61 let pipe = Pipe()
62 process.standardOutput = pipe
63 process.standardError = pipe
64 try process.run()
65 let log = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
66 process.waitUntilExit()
67 try #require(FileManager.default.fileExists(atPath: folder.appendingPathComponent("out.json").path), "\(log)")
68 let emacs = try JSONDecoder().decode([String].self, from: Data(contentsOf: folder.appendingPathComponent("out.json")))
69 try FileManager.default.removeItem(at: folder.appendingPathComponent("out.json"))
70 let emacsFiles = AttachmentsTests.listing(folder).filter { !$0.hasSuffix(".org") }
71 for name in ["data", "img"] { try? FileManager.default.removeItem(atPath: "\(dir)/\(name)") }
72
73 var ours: [String] = []
74 for (file, at, method) in [("a.org", "Body.", ImageYank.SaveMethod.attach), ("b.org", "Free text.", .attach), ("c.org", "Body.", .directory("img/"))] {
75 let ns = Self.notes as NSString
76 var entry = Attachments.Entry(text: Self.notes, offset: NSMaxRange(ns.range(of: at)), path: "\(dir)/\(file)", idDir: "data/")
77 if method == .attach { _ = try Attachments.directoryCreating(&entry, newID: { Self.id + (file as NSString).deletingPathExtension }) }
78 ours.append(try ImageYank.save(Data("PNG".utf8), ext: "png", method: method, in: &entry, date: Self.noon))
79 ours.append(entry.text)
80 }
81
82 #expect(emacs.count == 6, "\(log)")
83 // Org's links carry the file name as their description; ours have none.
84 #expect(ours[0] == "[[attachment:clipboard-20240101T120000.png]]")
85 #expect(emacs[0] == "[[attachment:clipboard-20240101T120000.png][clipboard-20240101T120000.png]]")
86 #expect(ours[2] == "[[attachment:clipboard-20240101T120000.png]]")
87 #expect(ours[4] == emacs[4])
88 for index in [1, 3, 5] { #expect(ours[index] == emacs[index], "step \(index)") }
89 #expect(AttachmentsTests.listing(folder).filter { !$0.hasSuffix(".org") } == emacsFiles)
90
91 // The link before the first heading shows as an image: the file-level ID's folder.
92 let (text, caret) = ImageYank.inserting([ours[2]], into: ours[3], at: NSMaxRange((ours[3] as NSString).range(of: "Free text.")))
93 #expect(DocumentSession.attachmentPath("clipboard-20240101T120000.png", at: caret, tree: OrgParser.parse(text), path: "\(dir)/b.org")
94 == "\(dir)/data/6a/1b2c3d-0000-4000-8000-00000000000b/clipboard-20240101T120000.png")
95 #expect(InlineImages.image(atLine: caret - 1, in: text as NSString, attachment: { name, _ in name })?.path == "clipboard-20240101T120000.png")
96 }
97
98 @Test func aSecondPasteInTheSameSecondGetsANewName() throws {
99 let folder = try Self.folder()
100 defer { try? FileManager.default.removeItem(at: folder) }
101 var entry = Attachments.Entry(text: Self.notes, offset: 0, path: folder.appendingPathComponent("n.org").path)
102 let first = try ImageYank.save(Data(), ext: "png", method: .directory("img"), in: &entry, date: Self.noon)
103 let second = try ImageYank.save(Data(), ext: "png", method: .directory("img"), in: &entry, date: Self.noon)
104 #expect(first == "[[file:img/clipboard-20240101T120000.png]]")
105 #expect(second == "[[file:img/clipboard-20240101T120000-2.png]]")
106 }
107
108 @Test func droppedFiles() throws {
109 let folder = try Self.folder()
110 defer { try? FileManager.default.removeItem(at: folder) }
111 let elsewhere = try Self.folder()
112 defer { try? FileManager.default.removeItem(at: elsewhere) }
113 let photo = elsewhere.appendingPathComponent("photo.jpg")
114 let doc = elsewhere.appendingPathComponent("doc.pdf")
115 try Data("j".utf8).write(to: photo)
116 try Data("p".utf8).write(to: doc)
117 let path = folder.appendingPathComponent("n.org").path
118 var entry = Attachments.Entry(text: "* Task\n", offset: 7, path: path, idDir: "data/")
119
120 let linked = try ImageYank.drop([folder.appendingPathComponent("sub/x.png"), doc], method: .fileLink, attachMethod: .cp, saveMethod: .attach, in: &entry)
121 #expect(linked == ["[[file:sub/x.png]]", "[[file:\((doc.path as NSString).abbreviatingWithTildeInPath)]]"])
122
123 let attached = try ImageYank.drop([photo, doc], method: .attach, attachMethod: .cp, saveMethod: .attach, in: &entry)
124 #expect(attached == ["[[attachment:photo.jpg]]", "[[attachment:doc.pdf]]"])
125 let dir = try #require(Attachments.directory(entry))
126 #expect(Attachments.files(in: dir) == ["doc.pdf", "photo.jpg"])
127 #expect(entry.text.hasPrefix("* Task") && entry.text.contains(":ATTACH:"))
128
129 // An image goes to the save method's folder when it is one; other files are attached.
130 let moved = try ImageYank.drop([photo], method: .attach, attachMethod: .mv, saveMethod: .directory("img"), in: &entry)
131 #expect(moved == ["[[file:img/photo.jpg]]"])
132 #expect(FileManager.default.fileExists(atPath: folder.appendingPathComponent("img/photo.jpg").path))
133 #expect(!FileManager.default.fileExists(atPath: photo.path))
134 }
135
136 @Test func linksGoOnLinesOfTheirOwn() {
137 let link = "[[attachment:a.png]]"
138 #expect(ImageYank.inserting([link], into: "a\n\nb\n", at: 2) == ("a\n\(link)\nb\n", 2 + 20))
139 #expect(ImageYank.inserting([link], into: "one two\n", at: 3) == ("one\n\(link)\n two\n", 4 + 20))
140 #expect(ImageYank.inserting([link], into: "one\n", at: 3) == ("one\n\(link)\n", 4 + 20))
141 #expect(ImageYank.inserting([link], into: "one", at: 3) == ("one\n\(link)", 4 + 20))
142 #expect(ImageYank.inserting([link], into: "two\n", at: 0) == ("\(link)\ntwo\n", 20))
143 #expect(ImageYank.inserting([link, link], into: "", at: 0) == ("\(link)\n\(link)", 41))
144 #expect(ImageYank.inserting([link], into: " - item\n ", at: 11) == (" - item\n \(link)", 31))
145 }
146
147 @Test func caretFollowsTheChangeAboveIt() {
148 let old = "* Task\nBody."
149 let new = "* Task\n:PROPERTIES:\n:ID: x\n:END:\nBody."
150 #expect(ImageYank.map(12, from: old, to: new) == (new as NSString).length)
151 #expect(ImageYank.map(3, from: old, to: new) == 3)
152 #expect(ImageYank.map(7, from: old, to: new) == 7 + 26)
153 let drawer = ":PROPERTIES:\n:ID: x\n:END:\n"
154 #expect(ImageYank.map(0, from: "#+title: a\n", to: drawer + "#+title: a\n") == (drawer as NSString).length)
155 }
156
157 @Test func settings() {
158 #expect(ImageYank.SaveMethod("attach") == .attach)
159 #expect(ImageYank.SaveMethod("") == .attach)
160 #expect(ImageYank.SaveMethod("~/img/") == .directory("~/img/"))
161 }
162}
Tests/OrgEditorAppKitTests/PasteMediaTests.swift added +64
@@ -0,0 +1,64 @@
1import AppKit
2import OrgDocument
3import Testing
4@testable import OrgEditorAppKit
5
6@MainActor
7struct PasteMediaTests {
8 static func pasteboard() -> NSPasteboard {
9 let pasteboard = NSPasteboard(name: NSPasteboard.Name("orgstar-test-\(UUID().uuidString)"))
10 pasteboard.clearContents()
11 return pasteboard
12 }
13
14 static var tiff: Data {
15 let image = NSImage(size: NSSize(width: 2, height: 2))
16 image.lockFocus()
17 NSColor.red.setFill()
18 NSRect(x: 0, y: 0, width: 2, height: 2).fill()
19 image.unlockFocus()
20 return image.tiffRepresentation!
21 }
22
23 @Test func imagesWithoutTextArePastedAsImages() {
24 let png = Self.pasteboard()
25 png.setData(Data("PNG".utf8), forType: .png)
26 #expect(OrgTextView.image(on: png)?.ext == "png")
27 #expect(OrgTextView.image(on: png)?.data == Data("PNG".utf8))
28
29 let tiff = Self.pasteboard()
30 tiff.setData(Self.tiff, forType: .tiff)
31 let converted = OrgTextView.image(on: tiff)
32 #expect(converted?.ext == "png")
33 #expect((converted.flatMap { NSBitmapImageRep(data: $0.data) }?.pixelsWide ?? 0) >= 2)
34
35 let text = Self.pasteboard()
36 text.setData(Data("PNG".utf8), forType: .png)
37 text.setString("caption", forType: .string)
38 #expect(OrgTextView.image(on: text) == nil)
39 }
40
41 @Test func filesAreFiles() {
42 let pasteboard = Self.pasteboard()
43 let url = URL(fileURLWithPath: "/tmp/a.png")
44 pasteboard.writeObjects([url as NSURL])
45 #expect(OrgTextView.files(on: pasteboard) == [url])
46 #expect(OrgTextView.files(on: Self.pasteboard()) == nil)
47 }
48
49 @Test func theEditorTakesMediaOnlyInOrgWithAHandler() {
50 let harness = Harness("* a\n")
51 let view = harness.editor.textView as! OrgTextView
52 let pasteboard = Self.pasteboard()
53 pasteboard.setData(Data("PNG".utf8), forType: .png)
54 #expect(!view.takeMedia(from: pasteboard))
55 var got: (Data, String)?
56 harness.editor.onImage = { got = ($0, $1) }
57 #expect(view.takeMedia(from: pasteboard))
58 #expect(got?.1 == "png")
59
60 let plain = Harness(DocumentState(bytes: Array("x\n".utf8)), mode: .plain(language: nil))
61 plain.editor.onImage = { _, _ in Issue.record("a plain buffer took an image") }
62 #expect(!(plain.editor.textView as! OrgTextView).takeMedia(from: pasteboard))
63 }
64}
docs/manual/guide/09-links.org +31 −3
@@ -342,9 +342,37 @@ to a file ending in =.png=, =.jpg=, =.jpeg=, =.gif=, =.svg=, =.webp=, =.tif=, =.
342342[[./photo.jpg]]
343343#+END_SRC
344344
345Relative paths are resolved against the file's folder. =attachment:= links are not
346shown as images. The link text is hidden while the image is shown, except on the line
347that holds the caret.
345Relative paths are resolved against the file's folder, and =attachment:= links against the
346entry's attachment folder. The link text is hidden while the image is shown, except on the
347line that holds the caret, where the image is drawn under the link.
348
349** Pasting and dropping images
350
351Paste (⌘V, or Edit ▸ Paste on iOS) with an image on the clipboard and no text runs
352=yank-media=, as in Emacs 29 and later: the image is saved as =org-yank-image-save-method=
353says and a link to it is inserted at the caret. M-x =yank-media= does the same on the Mac.
354
355| =org-yank-image-save-method= | Where the image goes | Link |
356|------------------------------+--------------------------------------------------------------------------+-------------------------|
357| =attach= (the default) | The entry's attachment folder, as =org-attach-attach= puts it | =[[attachment:NAME]]= |
358| a folder, such as ="images/"= | That folder, relative to the file's folder unless absolute; made if missing | =[[file:images/NAME]]= |
359
360The name is Org's: =clipboard-= and the time, as in =clipboard-20261011T232238.png=; a
361second image in the same second gets =-2=. PNG, JPEG and GIF are saved as they are, and
362other image types as PNG. Before the first heading, =attach= gives the file a file-level
363=ID=, as Emacs does.
364
365Files dropped on the editor on the Mac, or pasted after copying them in Finder, are handled
366as =org-yank-dnd-method= says: =attach= copies them into the entry's attachment folder (an
367image goes to the =org-yank-image-save-method= folder when that is a folder), =file-link=
368links to them where they are, =open= opens them, and =ask=, the default, asks which. An
369image dragged in without a file, such as one from a browser, is pasted as above. On iOS,
370dropped files are always attached, since what a drop hands over is a copy. Attach Photo or
371Video… and Take Photo… also insert their links at the caret.
372
373Two things differ from Emacs, so that a pasted image shows at once: the link has no
374description (Org writes =[[attachment:NAME][NAME]]=, which inline display skips), and it
375goes on a line of its own, breaking the line around the caret when it holds text.
348376
349377** Remote images
350378
docs/manual/guide/13-configuration.org +5
@@ -171,6 +171,7 @@ These settings have no control in the Settings window. Some are in the View menu
171171| =org-timer-format=, =org-timer-default-timer= | |
172172| =org-roam-directory=, =org-roam-dailies-directory=, =org-roam-dailies-file=, =org-roam-dailies-head=, =org-roam-dailies-entry= | |
173173| =org-attach-id-dir=, =org-attach-use-inheritance= | |
174| =org-yank-image-save-method=, =org-yank-dnd-method= | |
174175| =org-crypt-tag-matcher= | |
175176| =org-agenda-start-on-weekday= | |
176177| =org-deadline-warning-days= | |
@@ -232,6 +233,8 @@ A key you remove from the file goes back to its default. A key that isn't in the
232233| =org-timer-default-timer= | string | ="0"= | The countdown Set Countdown Timer… offers, in minutes or =h:mm:ss=; ="0"= offers none. Mirrors =org-timer-default-timer=. |
233234| =org-attach-id-dir= | string | ="data/"= | The folder ID-based attachment folders go in, relative to the org file's folder unless absolute. See [[file:04-outlines.org][Outlines]]. Mirrors =org-attach-id-dir=. |
234235| =org-attach-use-inheritance= | string | ="selective"= | Whether attachment folders come from an ancestor's =DIR= or =ID=: =selective=, ="t"= or ="nil"=. Mirrors =org-attach-use-inheritance=. |
236| =org-yank-image-save-method= | string | ="attach"= | Where a pasted image goes: =attach= for the entry's attachment folder, or a folder, relative to the org file's folder unless absolute. See [[file:09-links.org][Links]]. Mirrors =org-yank-image-save-method=. |
237| =org-yank-dnd-method= | string | ="ask"= | What dropping files on the editor does: =ask=, =attach=, =open= or =file-link=. See [[file:09-links.org][Links]]. Mirrors =org-yank-dnd-method=. |
235238| =org-crypt-tag-matcher= | string | ="crypt"= | The tag Encrypt Tagged Entries… encrypts. A single tag. See [[file:04-outlines.org][Outlines]]. Mirrors =org-crypt-tag-matcher=. |
236239| =org-startup-indented= | boolean | =true= | Indent bodies under their headings, as =org-indent-mode=. =#+STARTUP: indent= / =noindent= override it. Mirrors =org-startup-indented=. |
237240| =org-hide-leading-stars= | boolean | =false= | Show only a heading's last star, without indentation. =#+STARTUP: hidestars= / =showstars= override it. Mirrors =org-hide-leading-stars=. |
@@ -601,6 +604,8 @@ Only variables whose names start with =org-=, =appt-=, =display-line-numbers=, =
601604| =org-timer-format=, =org-timer-default-timer= | The same keys; a number becomes a string |
602605| =org-attach-id-dir= | The same key, when the value is a string or an =expand-file-name= form |
603606| =org-attach-use-inheritance= | =selective=, or =t= / =nil= as ="t"= / ="nil"= |
607| =org-yank-image-save-method= | =attach=, or a folder name |
608| =org-yank-dnd-method= | =ask=, =attach=, =open= or =file-link= |
604609| =org-crypt-tag-matcher= | The same key, when the value is a single tag |
605610| =org-archive-location= | The same key, when the value is a =file::heading= string |
606611| =org-structure-template-alist= | =[org-structure-template-alist]=: each =("key" . "type")= entry that isn't one of Org's, from =setq= or =(add-to-list 'org-structure-template-alist …)= |
docs/manual/guide/14-ios.org +2 −2
@@ -155,7 +155,7 @@ Incremental Search is in Commands, and on =C-s= and =C-r= with a hardware keyboa
155155
156156The org-timer commands are in Commands; a running timer shows above the text. See [[file:06-dates-and-clocking.org][Dates and clocking]].
157157
158More ▸ Attachments has the org-attach commands and Attach Photo or Video…; files shared to orgstar can be attached to an entry. See [[file:04-outlines.org][Outlines]].
158More ▸ Attachments has the org-attach commands, Attach Photo or Video… and Take Photo…, which insert the photo's link at the caret; files shared to orgstar can be attached to an entry. Pasting an image and dropping files on the editor attach them and link them at the caret. See [[file:04-outlines.org][Outlines]] and [[file:09-links.org][Links]].
159159
160160More ▸ Encryption has the org-crypt commands; see [[file:04-outlines.org][Outlines]]. A remembered passphrase is used after Face ID, Touch ID or the device passcode.
161161
@@ -405,7 +405,7 @@ These settings from =config.toml= apply on iOS:
405405- =org-log-done=, =org-log-reschedule=, =org-log-redeadline=, =org-log-into-drawer=
406406- =org-enforce-todo-dependencies=, =org-enforce-todo-checkbox-dependencies=, =org-track-ordered-property-with-tag=, =org-agenda-dim-blocked-tasks=
407407- =org-roam-directory=, =org-roam-dailies-directory=, =org-roam-dailies-file=, =org-roam-dailies-head=, =org-roam-dailies-entry=
408- =org-crypt-tag-matcher=, =org-attach-id-dir=, =org-attach-use-inheritance=, =org-timer-format=, =org-timer-default-timer=
408- =org-crypt-tag-matcher=, =org-attach-id-dir=, =org-attach-use-inheritance=, =org-yank-image-save-method=, =org-timer-format=, =org-timer-default-timer=
409409- =org-archive-location=, =[org-structure-template-alist]=
410410- =org-use-tag-inheritance=, =org-tags-exclude-from-inheritance=, =org-tag-alist=
411411- =org-use-speed-commands=, with a hardware keyboard
ios/Orgstar.xcodeproj/project.pbxproj +24 −24
@@ -700,7 +700,7 @@
700700 isa = XCBuildConfiguration;
701701 buildSettings = {
702702 CODE_SIGN_STYLE = Automatic;
703 CURRENT_PROJECT_VERSION = 5;
703 CURRENT_PROJECT_VERSION = 6;
704704 DEVELOPMENT_TEAM = ZCNAX3VL9D;
705705 GENERATE_INFOPLIST_FILE = NO;
706706 INFOPLIST_FILE = OrgstarQuickLook/Info.plist;
@@ -709,7 +709,7 @@
709709 "@executable_path/Frameworks",
710710 "@executable_path/../../Frameworks",
711711 );
712 MARKETING_VERSION = 0.3.2;
712 MARKETING_VERSION = 0.4.0;
713713 PRODUCT_BUNDLE_IDENTIFIER = sh.krz.orgstar.quicklook;
714714 PRODUCT_NAME = "$(TARGET_NAME)";
715715 SKIP_INSTALL = YES;
@@ -722,7 +722,7 @@
722722 buildSettings = {
723723 CODE_SIGN_ENTITLEMENTS = OrgstarShare/OrgstarShare.entitlements;
724724 CODE_SIGN_STYLE = Automatic;
725 CURRENT_PROJECT_VERSION = 5;
725 CURRENT_PROJECT_VERSION = 6;
726726 DEVELOPMENT_TEAM = ZCNAX3VL9D;
727727 GENERATE_INFOPLIST_FILE = NO;
728728 INFOPLIST_FILE = OrgstarShare/Info.plist;
@@ -731,7 +731,7 @@
731731 "@executable_path/Frameworks",
732732 "@executable_path/../../Frameworks",
733733 );
734 MARKETING_VERSION = 0.3.2;
734 MARKETING_VERSION = 0.4.0;
735735 PRODUCT_BUNDLE_IDENTIFIER = sh.krz.orgstar.share;
736736 PRODUCT_NAME = "$(TARGET_NAME)";
737737 SKIP_INSTALL = YES;
@@ -744,7 +744,7 @@
744744 buildSettings = {
745745 CODE_SIGN_ENTITLEMENTS = OrgstarShare/OrgstarShare.entitlements;
746746 CODE_SIGN_STYLE = Automatic;
747 CURRENT_PROJECT_VERSION = 5;
747 CURRENT_PROJECT_VERSION = 6;
748748 DEVELOPMENT_TEAM = ZCNAX3VL9D;
749749 GENERATE_INFOPLIST_FILE = NO;
750750 INFOPLIST_FILE = OrgstarShare/Info.plist;
@@ -753,7 +753,7 @@
753753 "@executable_path/Frameworks",
754754 "@executable_path/../../Frameworks",
755755 );
756 MARKETING_VERSION = 0.3.2;
756 MARKETING_VERSION = 0.4.0;
757757 PRODUCT_BUNDLE_IDENTIFIER = sh.krz.orgstar.share;
758758 PRODUCT_NAME = "$(TARGET_NAME)";
759759 SKIP_INSTALL = YES;
@@ -767,7 +767,7 @@
767767 ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
768768 CODE_SIGN_ENTITLEMENTS = Orgstar/Orgstar.entitlements;
769769 CODE_SIGN_STYLE = Automatic;
770 CURRENT_PROJECT_VERSION = 5;
770 CURRENT_PROJECT_VERSION = 6;
771771 DEVELOPMENT_TEAM = ZCNAX3VL9D;
772772 GENERATE_INFOPLIST_FILE = NO;
773773 INFOPLIST_FILE = Orgstar/Info.plist;
@@ -777,7 +777,7 @@
777777 "$(inherited)",
778778 "@executable_path/Frameworks",
779779 );
780 MARKETING_VERSION = 0.3.2;
780 MARKETING_VERSION = 0.4.0;
781781 PRODUCT_BUNDLE_IDENTIFIER = sh.krz.orgstar;
782782 PRODUCT_MODULE_NAME = OrgstarMobile;
783783 PRODUCT_NAME = Orgstar;
@@ -790,7 +790,7 @@
790790 buildSettings = {
791791 CODE_SIGN_ENTITLEMENTS = OrgstarWidgets/OrgstarWidgets.entitlements;
792792 CODE_SIGN_STYLE = Automatic;
793 CURRENT_PROJECT_VERSION = 5;
793 CURRENT_PROJECT_VERSION = 6;
794794 DEVELOPMENT_TEAM = ZCNAX3VL9D;
795795 GENERATE_INFOPLIST_FILE = NO;
796796 INFOPLIST_FILE = OrgstarWidgets/Info.plist;
@@ -800,7 +800,7 @@
800800 "@executable_path/Frameworks",
801801 "@executable_path/../../Frameworks",
802802 );
803 MARKETING_VERSION = 0.3.2;
803 MARKETING_VERSION = 0.4.0;
804804 PRODUCT_BUNDLE_IDENTIFIER = sh.krz.orgstar.widgets;
805805 PRODUCT_NAME = "$(TARGET_NAME)";
806806 SKIP_INSTALL = YES;
@@ -812,7 +812,7 @@
812812 isa = XCBuildConfiguration;
813813 buildSettings = {
814814 CODE_SIGN_STYLE = Automatic;
815 CURRENT_PROJECT_VERSION = 5;
815 CURRENT_PROJECT_VERSION = 6;
816816 DEVELOPMENT_TEAM = ZCNAX3VL9D;
817817 GENERATE_INFOPLIST_FILE = NO;
818818 INFOPLIST_FILE = OrgstarQuickLook/Info.plist;
@@ -821,7 +821,7 @@
821821 "@executable_path/Frameworks",
822822 "@executable_path/../../Frameworks",
823823 );
824 MARKETING_VERSION = 0.3.2;
824 MARKETING_VERSION = 0.4.0;
825825 PRODUCT_BUNDLE_IDENTIFIER = sh.krz.orgstar.quicklook;
826826 PRODUCT_NAME = "$(TARGET_NAME)";
827827 SKIP_INSTALL = YES;
@@ -852,7 +852,7 @@
852852 ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
853853 CODE_SIGN_ENTITLEMENTS = Orgstar/Orgstar.entitlements;
854854 CODE_SIGN_STYLE = Automatic;
855 CURRENT_PROJECT_VERSION = 5;
855 CURRENT_PROJECT_VERSION = 6;
856856 DEVELOPMENT_TEAM = ZCNAX3VL9D;
857857 GENERATE_INFOPLIST_FILE = NO;
858858 INFOPLIST_FILE = Orgstar/Info.plist;
@@ -862,7 +862,7 @@
862862 "$(inherited)",
863863 "@executable_path/Frameworks",
864864 );
865 MARKETING_VERSION = 0.3.2;
865 MARKETING_VERSION = 0.4.0;
866866 PRODUCT_BUNDLE_IDENTIFIER = sh.krz.orgstar;
867867 PRODUCT_MODULE_NAME = OrgstarMobile;
868868 PRODUCT_NAME = Orgstar;
@@ -875,7 +875,7 @@
875875 buildSettings = {
876876 CODE_SIGN_ENTITLEMENTS = OrgstarWidgets/OrgstarWidgets.entitlements;
877877 CODE_SIGN_STYLE = Automatic;
878 CURRENT_PROJECT_VERSION = 5;
878 CURRENT_PROJECT_VERSION = 6;
879879 DEVELOPMENT_TEAM = ZCNAX3VL9D;
880880 GENERATE_INFOPLIST_FILE = NO;
881881 INFOPLIST_FILE = OrgstarWidgets/Info.plist;
@@ -885,7 +885,7 @@
885885 "@executable_path/Frameworks",
886886 "@executable_path/../../Frameworks",
887887 );
888 MARKETING_VERSION = 0.3.2;
888 MARKETING_VERSION = 0.4.0;
889889 PRODUCT_BUNDLE_IDENTIFIER = sh.krz.orgstar.widgets;
890890 PRODUCT_NAME = "$(TARGET_NAME)";
891891 SKIP_INSTALL = YES;
@@ -919,7 +919,7 @@
919919 ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
920920 CODE_SIGN_ENTITLEMENTS = OrgstarWatch/OrgstarWatch.entitlements;
921921 CODE_SIGN_STYLE = Automatic;
922 CURRENT_PROJECT_VERSION = 5;
922 CURRENT_PROJECT_VERSION = 6;
923923 DEVELOPMENT_TEAM = ZCNAX3VL9D;
924924 GENERATE_INFOPLIST_FILE = NO;
925925 INFOPLIST_FILE = OrgstarWatch/Info.plist;
@@ -927,7 +927,7 @@
927927 "$(inherited)",
928928 "@executable_path/Frameworks",
929929 );
930 MARKETING_VERSION = 0.3.2;
930 MARKETING_VERSION = 0.4.0;
931931 PRODUCT_BUNDLE_IDENTIFIER = sh.krz.orgstar.watchkitapp;
932932 PRODUCT_NAME = "$(TARGET_NAME)";
933933 SDKROOT = watchos;
@@ -944,7 +944,7 @@
944944 ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
945945 CODE_SIGN_ENTITLEMENTS = OrgstarWatch/OrgstarWatch.entitlements;
946946 CODE_SIGN_STYLE = Automatic;
947 CURRENT_PROJECT_VERSION = 5;
947 CURRENT_PROJECT_VERSION = 6;
948948 DEVELOPMENT_TEAM = ZCNAX3VL9D;
949949 GENERATE_INFOPLIST_FILE = NO;
950950 INFOPLIST_FILE = OrgstarWatch/Info.plist;
@@ -952,7 +952,7 @@
952952 "$(inherited)",
953953 "@executable_path/Frameworks",
954954 );
955 MARKETING_VERSION = 0.3.2;
955 MARKETING_VERSION = 0.4.0;
956956 PRODUCT_BUNDLE_IDENTIFIER = sh.krz.orgstar.watchkitapp;
957957 PRODUCT_NAME = "$(TARGET_NAME)";
958958 SDKROOT = watchos;
@@ -969,7 +969,7 @@
969969 SKIP_INSTALL = YES;
970970 CODE_SIGN_ENTITLEMENTS = OrgstarWatchWidgets/OrgstarWatchWidgets.entitlements;
971971 CODE_SIGN_STYLE = Automatic;
972 CURRENT_PROJECT_VERSION = 5;
972 CURRENT_PROJECT_VERSION = 6;
973973 DEVELOPMENT_TEAM = ZCNAX3VL9D;
974974 GENERATE_INFOPLIST_FILE = NO;
975975 INFOPLIST_FILE = OrgstarWatchWidgets/Info.plist;
@@ -978,7 +978,7 @@
978978 "@executable_path/Frameworks",
979979 "@executable_path/../../Frameworks",
980980 );
981 MARKETING_VERSION = 0.3.2;
981 MARKETING_VERSION = 0.4.0;
982982 PRODUCT_BUNDLE_IDENTIFIER = sh.krz.orgstar.watchkitapp.widgets;
983983 PRODUCT_NAME = "$(TARGET_NAME)";
984984 SDKROOT = watchos;
@@ -994,7 +994,7 @@
994994 SKIP_INSTALL = YES;
995995 CODE_SIGN_ENTITLEMENTS = OrgstarWatchWidgets/OrgstarWatchWidgets.entitlements;
996996 CODE_SIGN_STYLE = Automatic;
997 CURRENT_PROJECT_VERSION = 5;
997 CURRENT_PROJECT_VERSION = 6;
998998 DEVELOPMENT_TEAM = ZCNAX3VL9D;
999999 GENERATE_INFOPLIST_FILE = NO;
10001000 INFOPLIST_FILE = OrgstarWatchWidgets/Info.plist;
@@ -1003,7 +1003,7 @@
10031003 "@executable_path/Frameworks",
10041004 "@executable_path/../../Frameworks",
10051005 );
1006 MARKETING_VERSION = 0.3.2;
1006 MARKETING_VERSION = 0.4.0;
10071007 PRODUCT_BUNDLE_IDENTIFIER = sh.krz.orgstar.watchkitapp.widgets;
10081008 PRODUCT_NAME = "$(TARGET_NAME)";
10091009 SDKROOT = watchos;
ios/Orgstar/Info.plist +2
@@ -46,6 +46,8 @@
4646 <string>public.app-category.productivity</string>
4747 <key>NSCalendarsFullAccessUsageDescription</key>
4848 <string>The agenda shows your calendar events alongside your Org entries. orgstar changes your calendars only when you edit an event or add an entry to one.</string>
49 <key>NSCameraUsageDescription</key>
50 <string>Photos you take from the editor are saved with your notes and linked where the caret is.</string>
4951 <key>NSFaceIDUsageDescription</key>
5052 <string>Face ID unlocks the passphrase of encrypted entries you asked orgstar to remember.</string>
5153 <key>NSRemindersFullAccessUsageDescription</key>
l10n/Localizable.xcstrings +20
@@ -2312,6 +2312,16 @@
23122312 }
23132313 }
23142314 },
2315 "Habits only today": {
2316 "localizations": {
2317 "de": {
2318 "stringUnit": {
2319 "state": "translated",
2320 "value": "Gewohnheiten nur heute"
2321 }
2322 }
2323 }
2324 },
23152325 "Headings": {
23162326 "localizations": {
23172327 "de": {
@@ -4783,6 +4793,16 @@
47834793 }
47844794 }
47854795 },
4796 "Take Photo…": {
4797 "localizations": {
4798 "de": {
4799 "stringUnit": {
4800 "state": "translated",
4801 "value": "Foto aufnehmen …"
4802 }
4803 }
4804 }
4805 },
47864806 "Template": {
47874807 "localizations": {
47884808 "de": {
scripts/build-app.sh +1 −1
@@ -8,7 +8,7 @@
88set -eu
99
1010cd "$(dirname "$0")/.."
11version="${1:-0.3.2}"
11version="${1:-0.4.0}"
1212build="${2:-$version}"
1313sign="${ORGSTAR_SIGN:--}"
1414app=".build/app/orgstar.app"
scripts/build-ios-app.sh +3 −1
@@ -5,7 +5,7 @@
55set -eu
66
77cd "$(dirname "$0")/.."
8version="${1:-0.3.2}"
8version="${1:-0.4.0}"
99app=".build/ios-app/orgstar.app"
1010products=".build/ios/Build/Products/Debug-iphonesimulator"
1111
@@ -53,6 +53,8 @@ cat > "$app/Info.plist" <<PLIST
5353 <array><string>iPhoneSimulator</string></array>
5454 <key>MinimumOSVersion</key>
5555 <string>26.0</string>
56 <key>NSCameraUsageDescription</key>
57 <string>Photos you take from the editor are saved with your notes and linked where the caret is.</string>
5658 <key>NSFaceIDUsageDescription</key>
5759 <string>Face ID unlocks the passphrase of encrypted entries you asked orgstar to remember.</string>
5860 <key>NSCalendarsFullAccessUsageDescription</key>
scripts/build-watch-app.sh +1 −1
@@ -7,7 +7,7 @@
77set -eu
88
99cd "$(dirname "$0")/.."
10version="${1:-0.3.2}"
10version="${1:-0.4.0}"
1111app=".build/watch-app/OrgstarWatch.app"
1212products=".build/watch/Build/Products/Debug-watchsimulator"
1313# The app group the complications read the agenda from, on the watch.