Ariver
2026-06-25 65fc2a130aa2eb38173a3dad4eee34e6600baa11
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
import SwiftUI
import AppKit
import QuartzCore
 
final class AppDragCoordinator {
    static let shared = AppDragCoordinator()
 
    struct DropTarget {
        weak var view: AppDropTargetReceivingView?
        var tag: String
    }
 
    struct EmptyDropTarget {
        weak var view: AppEmptyDropReceivingView?
    }
 
    private var targets: [UUID: DropTarget] = [:]
    private var emptyTargets: [UUID: EmptyDropTarget] = [:]
    private weak var dragHostWindow: NSWindow?
    private weak var dragLayerHostView: NSView?
    private var dragLayer: CALayer?
    private var normalDragImage: CGImage?
    private var copyDragImage: CGImage?
    private var shredPreviewActive = false
    private var shredSliceLayers: [CALayer] = []
    private var shredGuideLayers: [CALayer] = []
    private var currentCopyMode = false
    private var dragWindow: NSWindow?
    private var dragImageSize: NSSize = .zero
    private var activePayload = ""
    private weak var hoveredTarget: AppDropTargetReceivingView?
 
    private init() {}
 
    var hasActiveDrag: Bool {
        dragLayer != nil || dragWindow != nil || !activePayload.isEmpty
    }
 
    func register(id: UUID, view: AppDropTargetReceivingView, tag: String) {
        if let existing = targets[id], existing.view === view, existing.tag == tag {
            return
        }
        if targets.count > 256 {
            pruneDeadTargets()
        }
        targets[id] = DropTarget(view: view, tag: tag)
    }
 
    func unregister(id: UUID) {
        targets.removeValue(forKey: id)
    }
 
    func registerEmptyDropTarget(id: UUID, view: AppEmptyDropReceivingView) {
        if emptyTargets.count > 64 {
            pruneDeadTargets()
        }
        emptyTargets[id] = EmptyDropTarget(view: view)
    }
 
    func unregisterEmptyDropTarget(id: UUID) {
        emptyTargets.removeValue(forKey: id)
    }
 
    func beginDrag(image: NSImage, payload: String, at screenPoint: NSPoint, copy: Bool, in hostWindow: NSWindow?) {
        endDragVisuals()
        activePayload = payload
        dragImageSize = image.size
        dragHostWindow = hostWindow
        currentCopyMode = copy
        normalDragImage = Self.cgImage(from: image)
        copyDragImage = Self.cgImage(from: Self.copyBadgeImage(from: image))
 
        let hostView: NSView
 
        if let contentView = hostWindow?.contentView {
            hostView = contentView
        } else {
            let panel = NSPanel(
                contentRect: NSRect(origin: .zero, size: image.size),
                styleMask: [.borderless, .nonactivatingPanel],
                backing: .buffered,
                defer: false
            )
            panel.isOpaque = false
            panel.backgroundColor = .clear
            panel.hasShadow = false
            panel.isFloatingPanel = true
            panel.hidesOnDeactivate = false
            panel.ignoresMouseEvents = true
            panel.level = .normal
            panel.collectionBehavior = [.moveToActiveSpace, .fullScreenAuxiliary, .stationary, .transient, .ignoresCycle]
            panel.isReleasedWhenClosed = false
            let contentView = NSView(frame: NSRect(origin: .zero, size: image.size))
            panel.contentView = contentView
            dragWindow = panel
            dragHostWindow = panel
            hostView = contentView
            panel.setFrameOrigin(NSPoint(x: screenPoint.x - image.size.width / 2, y: screenPoint.y - image.size.height / 2))
            panel.orderFrontRegardless()
        }
 
        hostView.wantsLayer = true
        guard let rootLayer = hostView.layer else { return }
 
        let layer = CALayer()
        layer.bounds = CGRect(origin: .zero, size: image.size)
        layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
        layer.contentsGravity = .resizeAspect
        layer.contentsScale = NSScreen.main?.backingScaleFactor ?? 2
        layer.contents = copy ? copyDragImage : normalDragImage
        layer.zPosition = 1_000_000
        layer.actions = [
            "position": NSNull(),
            "contents": NSNull(),
            "bounds": NSNull(),
            "opacity": NSNull()
        ]
 
        rootLayer.addSublayer(layer)
        dragLayerHostView = hostView
        dragLayer = layer
        updateDragLocation(screenPoint)
    }
 
    func updateDragLocation(_ screenPoint: NSPoint, copy: Bool? = nil) {
        if let dragLayer, let dragHostWindow, let hostView = dragLayerHostView {
            if let copy {
                updateCopyMode(copy)
            }
            let windowPoint = dragHostWindow.convertPoint(fromScreen: screenPoint)
            let contentPoint = hostView.convert(windowPoint, from: nil)
            CATransaction.begin()
            CATransaction.setDisableActions(true)
            dragLayer.position = contentPoint
            CATransaction.commit()
            updateHoverTarget(at: screenPoint)
            updateRemoveTagPreview(at: screenPoint)
            hoveredTarget?.appDragLocationChanged(screenPoint: screenPoint, copy: currentCopyMode)
            return
        }
 
        guard let dragWindow else {
            updateHoverTarget(at: screenPoint)
            return
        }
        let origin = NSPoint(
            x: screenPoint.x - dragImageSize.width / 2,
            y: screenPoint.y - dragImageSize.height / 2
        )
        dragWindow.setFrameOrigin(origin)
        updateHoverTarget(at: screenPoint)
        updateRemoveTagPreview(at: screenPoint)
        hoveredTarget?.appDragLocationChanged(screenPoint: screenPoint, copy: currentCopyMode)
    }
 
    func finishDrag(at screenPoint: NSPoint, copy: Bool) {
        defer { endDragVisuals() }
        let parts = activePayload.components(separatedBy: "\n")
        guard let path = parts.first, !path.isEmpty else { return }
        let source = parts.dropFirst().first ?? ""
        let sourceContainerID = parts.dropFirst(2).first ?? ""
        pruneDeadTargets()
 
        if let hitTarget = dropTarget(at: screenPoint) {
            hitTarget.appDragLocationChanged(screenPoint: screenPoint, copy: copy)
            hitTarget.performDrop(
                path: path,
                source: source,
                sourceContainerID: sourceContainerID,
                copy: copy
            )
            return
        }
 
        let emptyTarget = emptyTargets.values
            .compactMap { target -> (AppEmptyDropReceivingView, CGFloat)? in
                guard let view = target.view,
                      let frame = view.screenFrame(),
                      frame.contains(screenPoint)
                else { return nil }
                return (view, frame.width * frame.height)
            }
            .sorted { $0.1 < $1.1 }
            .first?.0
 
        emptyTarget?.performEmptyDrop(path: path, source: source, screenPoint: screenPoint, copy: copy)
    }
 
    func cancelDrag() {
        endDragVisuals()
    }
 
    private func updateCopyMode(_ copy: Bool) {
        guard currentCopyMode != copy else { return }
        currentCopyMode = copy
        CATransaction.begin()
        CATransaction.setDisableActions(true)
        if shredPreviewActive {
            let image = currentDragImage
            shredSliceLayers.forEach { $0.contents = image }
        } else {
            dragLayer?.contents = currentDragImage
        }
        CATransaction.commit()
    }
 
    private func endDragVisuals() {
        stopShredPreview()
        hoveredTarget?.appDragHoverChanged(active: false)
        hoveredTarget = nil
        dragLayer?.removeFromSuperlayer()
        dragLayer = nil
        dragLayerHostView = nil
        dragHostWindow = nil
        normalDragImage = nil
        copyDragImage = nil
        currentCopyMode = false
        dragWindow?.orderOut(nil)
        dragWindow = nil
        activePayload = ""
        dragImageSize = .zero
    }
 
    private var currentDragImage: CGImage? {
        currentCopyMode ? copyDragImage : normalDragImage
    }
 
    private func pruneDeadTargets() {
        targets = targets.filter { $0.value.view != nil }
        emptyTargets = emptyTargets.filter { $0.value.view != nil }
    }
 
    private func updateHoverTarget(at screenPoint: NSPoint) {
        guard hasActiveDrag else { return }
        pruneDeadTargets()
        let nextTarget = dropTarget(at: screenPoint)
        guard nextTarget !== hoveredTarget else { return }
        hoveredTarget?.appDragHoverChanged(active: false)
        nextTarget?.appDragHoverChanged(active: true)
        hoveredTarget = nextTarget
    }
 
    private func updateRemoveTagPreview(at screenPoint: NSPoint) {
        guard hasActiveDrag else {
            setShredPreviewActive(false)
            return
        }
        setShredPreviewActive(removeTagPreviewTarget(at: screenPoint) != nil)
    }
 
    private func removeTagPreviewTarget(at screenPoint: NSPoint) -> AppEmptyDropReceivingView? {
        guard dropTarget(at: screenPoint) == nil else { return nil }
        let parts = activePayload.components(separatedBy: "\n")
        guard let path = parts.first, !path.isEmpty else { return nil }
        let source = parts.dropFirst().first ?? ""
 
        return emptyTargets.values
            .compactMap { target -> (AppEmptyDropReceivingView, CGFloat)? in
                guard let view = target.view,
                      let frame = view.screenFrame(),
                      frame.contains(screenPoint),
                      view.canPreviewEmptyDrop(
                        path: path,
                        source: source,
                        screenPoint: screenPoint,
                        copy: currentCopyMode
                      )
                else { return nil }
                return (view, frame.width * frame.height)
            }
            .sorted { $0.1 < $1.1 }
            .first?.0
    }
 
    private func setShredPreviewActive(_ active: Bool) {
        guard active != shredPreviewActive else { return }
        if active {
            startShredPreview()
        } else {
            stopShredPreview()
        }
    }
 
    private func startShredPreview() {
        guard let dragLayer,
              let image = currentDragImage,
              !shredPreviewActive,
              dragImageSize.width > 0,
              dragImageSize.height > 0
        else { return }
 
        shredPreviewActive = true
        dragLayer.contents = nil
        shredSliceLayers.removeAll()
        shredGuideLayers.removeAll()
 
        let sliceCount = 7
        let sliceWidth = dragImageSize.width / CGFloat(sliceCount)
        for index in 0..<sliceCount {
            let x = CGFloat(index) * sliceWidth
            let width = index == sliceCount - 1
                ? dragImageSize.width - x
                : ceil(sliceWidth)
            let slice = CALayer()
            slice.frame = CGRect(x: x, y: 0, width: width, height: dragImageSize.height)
            slice.contents = image
            slice.contentsGravity = .resize
            slice.contentsScale = NSScreen.main?.backingScaleFactor ?? 2
            slice.contentsRect = CGRect(
                x: CGFloat(index) / CGFloat(sliceCount),
                y: 0,
                width: 1 / CGFloat(sliceCount),
                height: 1
            )
            slice.actions = [
                "position": NSNull(),
                "opacity": NSNull(),
                "transform": NSNull()
            ]
            dragLayer.addSublayer(slice)
            addShredAnimation(to: slice, index: index)
            shredSliceLayers.append(slice)
 
            if index > 0 {
                let guide = CALayer()
                guide.frame = CGRect(
                    x: x - 0.5,
                    y: dragImageSize.height * 0.12,
                    width: 1,
                    height: dragImageSize.height * 0.76
                )
                guide.backgroundColor = NSColor.white.withAlphaComponent(0.42).cgColor
                guide.opacity = 0
                guide.actions = [
                    "opacity": NSNull(),
                    "position": NSNull()
                ]
                dragLayer.addSublayer(guide)
                addShredGuideAnimation(to: guide, index: index)
                shredGuideLayers.append(guide)
            }
        }
    }
 
    private func stopShredPreview() {
        guard shredPreviewActive || !shredSliceLayers.isEmpty || !shredGuideLayers.isEmpty else { return }
        shredPreviewActive = false
        shredSliceLayers.forEach {
            $0.removeAllAnimations()
            $0.removeFromSuperlayer()
        }
        shredGuideLayers.forEach {
            $0.removeAllAnimations()
            $0.removeFromSuperlayer()
        }
        shredSliceLayers.removeAll()
        shredGuideLayers.removeAll()
        dragLayer?.contents = currentDragImage
    }
 
    private func addShredAnimation(to layer: CALayer, index: Int) {
        let direction: CGFloat = index.isMultiple(of: 2) ? 1 : -1
        let travel = min(4.5, max(2.0, dragImageSize.height * 0.06))
        let drift = min(2.4, max(1.0, dragImageSize.width * 0.025)) * direction
 
        let y = CAKeyframeAnimation(keyPath: "transform.translation.y")
        y.values = [0, -travel, travel * 0.28, -travel * 0.52, 0]
 
        let x = CAKeyframeAnimation(keyPath: "transform.translation.x")
        x.values = [0, drift, -drift * 0.45, drift * 0.25, 0]
 
        let opacity = CAKeyframeAnimation(keyPath: "opacity")
        opacity.values = [1, 0.82, 0.96, 0.88, 1]
 
        let group = CAAnimationGroup()
        group.animations = [x, y, opacity]
        group.duration = 0.46
        group.repeatCount = .greatestFiniteMagnitude
        group.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
        group.beginTime = CACurrentMediaTime() + Double(index) * 0.018
        layer.add(group, forKey: "removeTagShredPreview")
    }
 
    private func addShredGuideAnimation(to layer: CALayer, index: Int) {
        let opacity = CAKeyframeAnimation(keyPath: "opacity")
        opacity.values = [0, 0.42, 0.18, 0.35, 0]
        opacity.duration = 0.46
        opacity.repeatCount = .greatestFiniteMagnitude
        opacity.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
        opacity.beginTime = CACurrentMediaTime() + Double(index) * 0.018
        layer.add(opacity, forKey: "removeTagShredGuide")
    }
 
    private func dropTarget(at screenPoint: NSPoint) -> AppDropTargetReceivingView? {
        targets.values
            .compactMap { target -> (AppDropTargetReceivingView, CGFloat)? in
                guard let view = target.view,
                      let frame = view.screenFrame(),
                      frame.contains(screenPoint)
                else { return nil }
                return (view, frame.width * frame.height)
            }
            .sorted { $0.1 < $1.1 }
            .first?.0
    }
 
    private static func cgImage(from image: NSImage) -> CGImage? {
        var rect = NSRect(origin: .zero, size: image.size)
        return image.cgImage(forProposedRect: &rect, context: nil, hints: [
            .interpolation: NSImageInterpolation.high
        ])
    }
 
    private static func copyBadgeImage(from baseImage: NSImage) -> NSImage {
        let image = NSImage(size: baseImage.size)
        image.lockFocus()
        NSGraphicsContext.current?.imageInterpolation = .high
        baseImage.draw(in: NSRect(origin: .zero, size: baseImage.size), from: .zero, operation: .sourceOver, fraction: 1)
 
        let bounds = NSRect(origin: .zero, size: baseImage.size)
        let badgeSize = min(bounds.width, bounds.height) * 0.28
        let badgeRect = NSRect(
            x: bounds.maxX - badgeSize - badgeSize * 0.22,
            y: bounds.maxY - badgeSize - badgeSize * 0.22,
            width: badgeSize,
            height: badgeSize
        )
 
        NSGraphicsContext.saveGraphicsState()
        let shadow = NSShadow()
        shadow.shadowColor = NSColor.black.withAlphaComponent(0.30)
        shadow.shadowBlurRadius = 8
        shadow.shadowOffset = NSSize(width: 0, height: -2)
        shadow.set()
        NSColor.systemGreen.setFill()
        NSBezierPath(ovalIn: badgeRect).fill()
        NSGraphicsContext.restoreGraphicsState()
 
        let plus = "+"
        let attrs: [NSAttributedString.Key: Any] = [
            .font: NSFont.systemFont(ofSize: badgeSize * 0.78, weight: .bold),
            .foregroundColor: NSColor.white
        ]
        let plusSize = plus.size(withAttributes: attrs)
        plus.draw(
            at: NSPoint(
                x: badgeRect.midX - plusSize.width / 2,
                y: badgeRect.midY - plusSize.height / 2 + badgeSize * 0.03
            ),
            withAttributes: attrs
        )
        image.unlockFocus()
        return image
    }
}
 
protocol AppDropTargetReceivingView: AnyObject {
    func screenFrame() -> NSRect?
    func appDragHoverChanged(active: Bool)
    func appDragLocationChanged(screenPoint: NSPoint, copy: Bool)
    func performDrop(path: String, source: String, copy: Bool)
    func performDrop(path: String, source: String, sourceContainerID: String, copy: Bool)
}
 
protocol AppEmptyDropReceivingView: AnyObject {
    func screenFrame() -> NSRect?
    func canPreviewEmptyDrop(path: String, source: String, screenPoint: NSPoint, copy: Bool) -> Bool
    func performEmptyDrop(path: String, source: String, screenPoint: NSPoint, copy: Bool)
}
 
extension AppDropTargetReceivingView where Self: NSView {
    func screenFrame() -> NSRect? {
        guard let window else { return nil }
        let rectInWindow = convert(bounds, to: nil)
        return window.convertToScreen(rectInWindow)
    }
}
 
extension AppDropTargetReceivingView {
    func appDragHoverChanged(active: Bool) {}
    func appDragLocationChanged(screenPoint: NSPoint, copy: Bool) {}
    func performDrop(path: String, source: String, sourceContainerID: String, copy: Bool) {
        performDrop(path: path, source: source, copy: copy)
    }
}
 
extension AppEmptyDropReceivingView where Self: NSView {
    func screenFrame() -> NSRect? {
        guard let window else { return nil }
        let rectInWindow = convert(bounds, to: nil)
        return window.convertToScreen(rectInWindow)
    }
}
 
extension AppEmptyDropReceivingView {
    func canPreviewEmptyDrop(path: String, source: String, screenPoint: NSPoint, copy: Bool) -> Bool {
        true
    }
}
 
struct AppDropTargetView: NSViewRepresentable {
    let targetTag: String
    let onDropApp: (String, String, Bool) -> Void
 
    func makeNSView(context: Context) -> AppDropTargetNSView {
        let view = AppDropTargetNSView()
        view.configure(targetTag: targetTag, onDropApp: onDropApp)
        return view
    }
 
    func updateNSView(_ view: AppDropTargetNSView, context: Context) {
        view.configure(targetTag: targetTag, onDropApp: onDropApp)
    }
 
    static func dismantleNSView(_ view: AppDropTargetNSView, coordinator: ()) {
        view.onDropApp = nil
        AppDragCoordinator.shared.unregister(id: view.id)
    }
}
 
final class AppDropTargetNSView: NSView, AppDropTargetReceivingView {
    let id = UUID()
    var targetTag = ""
    var onDropApp: ((String, String, Bool) -> Void)?
 
    func configure(targetTag: String, onDropApp: @escaping (String, String, Bool) -> Void) {
        let tagChanged = self.targetTag != targetTag
        self.targetTag = targetTag
        self.onDropApp = onDropApp
        if tagChanged {
            registerTarget()
        }
    }
 
    override func viewDidMoveToWindow() {
        super.viewDidMoveToWindow()
        if window == nil {
            AppDragCoordinator.shared.unregister(id: id)
        } else {
            registerTarget()
        }
    }
 
    func registerTarget() {
        guard window != nil else { return }
        AppDragCoordinator.shared.register(id: id, view: self, tag: targetTag)
    }
 
    func performDrop(path: String, source: String, copy: Bool) {
        onDropApp?(path, source, copy)
    }
 
    deinit {
        AppDragCoordinator.shared.unregister(id: id)
    }
}