summaryrefslogtreecommitdiff
path: root/Sora/Views/Post/Details/PostDetailsImageView.swift
blob: 67d3d681448637f0223b438828dc559811c4671e (plain) (blame)
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
import NetworkImage
import SwiftUI

struct PostDetailsImageView<Placeholder: View>: View {
  @EnvironmentObject var settings: Settings
  @EnvironmentObject var manager: BooruManager
  var url: URL?
  @Binding var loadingState: BooruPostLoadingState
  var finalLoadingState: BooruPostLoadingState
  let placeholder: () -> Placeholder
  let post: BooruPost?
  @State private var currentScale: CGFloat = 1.0
  @State private var finalScale: CGFloat = 1.0
  @State private var currentOffset: CGSize = .zero
  @State private var finalOffset: CGSize = .zero

  #if os(iOS)
    var keyWindow: UIWindow? {
      guard
        let window = UIApplication.shared.connectedScenes
          .compactMap({ $0 as? UIWindowScene })
          .flatMap(\.windows)
          .first(where: \.isKeyWindow)
      else {
        return nil
      }

      return window
    }
  #endif

  var body: some View {
    let content = NetworkImage(
      url: url,
      transaction: Transaction(animation: .default)
    ) { image in
      InteractiveImageView(image: image)
        .onAppear {
          loadingState = finalLoadingState
        }
        .background(.background)
        .contextMenu {
          #if os(iOS)
            Button {
              guard let url else { return }

              URLSession.shared.dataTask(with: url) { data, _, _ in
                guard let data, let uiImage = UIImage(data: data) else { return }

                UIImageWriteToSavedPhotosAlbum(uiImage, nil, nil, nil)
              }
              .resume()
            } label: {
              Label("Save Image", systemImage: "square.and.arrow.down")
            }
          #endif

          #if os(macOS)
            Button {
              saveImageToPicturesFolder()
            } label: {
              Label("Save Image", systemImage: "square.and.arrow.down")
            }
            .keyboardShortcut("s", modifiers: [.command])
          #endif

          #if os(iOS)
            if settings.enableShareShortcut {
              Button {
                keyWindow?.rootViewController?.present(
                  UIActivityViewController(
                    activityItems: [url ?? URL(string: "")!], applicationActivities: nil
                  ), animated: true
                )
              } label: {
                Label("Share Image", systemImage: "square.and.arrow.up")
              }
            }
          #endif

          Button {
            openURL(postURL(for: post?.id ?? ""))
          } label: {
            Label("Open in Safari", systemImage: "safari")
          }

          if let source = post?.source {
            Button {
              openURL(URL(string: source)!)
            } label: {
              Label("Open Source in Safari", systemImage: "safari")
            }
          }
        }
    } placeholder: {
      placeholder()
        .onAppear {
          loadingState = .loadingPreview
        }
    }

    #if os(macOS)
      return content.overlay(
        Button(action: saveImageToPicturesFolder) {
          EmptyView()
        }
        .keyboardShortcut("s", modifiers: [.command])
        .frame(width: 0, height: 0)
        .opacity(0)
      )
    #else
      return content
    #endif
  }

  init(
    url: URL?,
    loadingStage: Binding<BooruPostLoadingState>,
    finalLoadingState: BooruPostLoadingState = .loadingFile,
    post: BooruPost? = nil,
    @ViewBuilder placeholder: @escaping () -> Placeholder = {
      GeometryReader { geometry in
        ProgressView()
          .frame(width: geometry.size.width, height: geometry.size.height)
          .position(x: geometry.size.width / 2, y: geometry.size.height / 2)
          .padding()
      }
    }
  ) {
    self.url = url
    _loadingState = loadingStage
    self.finalLoadingState = finalLoadingState
    self.placeholder = placeholder
    self.post = post
  }

  private func postURL(for id: String) -> URL {
    switch manager.flavor {
    case .moebooru:
      return URL(string: "https://\(manager.domain)/post/show/\(id)")!

    case .gelbooru:
      return URL(string: "https://\(manager.domain)/index.php?page=post&s=view&id=\(id)")!
    }
  }

  #if os(macOS)
    private func saveImageToPicturesFolder() {
      guard let url = self.url else { return }

      URLSession.shared.dataTask(with: url) { data, _, _ in
        guard let data, let post else { return }

        let picturesURL = FileManager.default.homeDirectoryForCurrentUser
          .appendingPathComponent("Pictures/Sora/\(manager.provider.rawValue)")

        do {
          try FileManager.default.createDirectory(
            at: picturesURL,
            withIntermediateDirectories: true
          )
          try data.write(
            to:
              picturesURL
              .appendingPathComponent(
                "\(post.id)_\(settings.detailViewType.rawValue.lowercased()).\(url.pathExtension)"
              )
          )

          if settings.saveTagsToFile {
            try post.tags.joined(separator: "\n").write(
              to: picturesURL.appendingPathComponent(
                "\(post.id).txt"
              ),
              atomically: true,
              encoding: .utf8
            )
          }
        } catch {
          print("PostDetailsImageView.saveImageToPicturesFolder: \(error)")
        }
      }
      .resume()
    }
  #endif

  private func openURL(_ url: URL) {
    #if os(iOS)
      UIApplication.shared.open(url)
    #else
      NSWorkspace.shared.open(url)
    #endif
  }
}