Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions HackerTube.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
D59139482895851300369402 /* TopShelf.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = D591393F2895851300369402 /* TopShelf.appex */; platformFilters = (tvos, ); settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
D591394E2895854100369402 /* CCCApi in Frameworks */ = {isa = PBXBuildFile; productRef = D591394D2895854100369402 /* CCCApi */; };
D5F872252DFC3F3F002D2F28 /* AppIcon.icon in Resources */ = {isa = PBXBuildFile; fileRef = D5F872242DFC3F35002D2F28 /* AppIcon.icon */; };
D5FCC6782FFC42DA00569E27 /* NanoSVG in Frameworks */ = {isa = PBXBuildFile; productRef = D5FCC6772FFC42DA00569E27 /* NanoSVG */; };
/* End PBXBuildFile section */

/* Begin PBXContainerItemProxy section */
Expand Down Expand Up @@ -53,6 +54,7 @@
/* Begin PBXFileReference section */
D50C6F7328956D770003D1D0 /* CCCApi */ = {isa = PBXFileReference; lastKnownFileType = wrapper; path = CCCApi; sourceTree = "<group>"; };
D557E8BA2896F70400342EE2 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = "<group>"; };
D574ECF72FFC42FA0050AF63 /* NanoSVG */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = NanoSVG; path = /Users/mathijs/Developer/HackerTube/NanoSVG; sourceTree = "<absolute>"; };
D591393F2895851300369402 /* TopShelf.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = TopShelf.appex; sourceTree = BUILT_PRODUCTS_DIR; };
D59139402895851300369402 /* TVServices.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = TVServices.framework; path = System/Library/Frameworks/TVServices.framework; sourceTree = SDKROOT; };
D591395928958B2600369402 /* HackerTubeTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = HackerTubeTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
Expand Down Expand Up @@ -126,6 +128,7 @@
isa = PBXFrameworksBuildPhase;
files = (
D50C6F7628956DFC0003D1D0 /* CCCApi in Frameworks */,
D5FCC6782FFC42DA00569E27 /* NanoSVG in Frameworks */,
);
};
D5EFB1992B407683008CFE82 /* Frameworks */ = {
Expand Down Expand Up @@ -153,6 +156,7 @@
D5D2CB2A2D43EBB300E08E44 /* UnitTests.xctestplan */,
D5AFD6D92C9BFCF700BF89F5 /* HackerTube */,
D50C6F7328956D770003D1D0 /* CCCApi */,
D574ECF72FFC42FA0050AF63 /* NanoSVG */,
D5AFD6FB2C9BFCFB00BF89F5 /* TopShelf */,
D5AFD7022C9BFD0F00BF89F5 /* HackerTubeTests */,
D5AFD7052C9BFD1100BF89F5 /* HackerTubeUITests */,
Expand Down Expand Up @@ -239,6 +243,7 @@
name = HackerTube;
packageProductDependencies = (
D50C6F7528956DFC0003D1D0 /* CCCApi */,
D5FCC6772FFC42DA00569E27 /* NanoSVG */,
);
productName = HackerTube;
productReference = D5A156D4289462B3006989FF /* HackerTube.app */;
Expand Down Expand Up @@ -301,6 +306,9 @@
de,
);
mainGroup = D5A156CB289462B3006989FF;
packageReferences = (
D5FCC6762FFC42DA00569E27 /* XCLocalSwiftPackageReference "NanoSVG" */,
);
preferredProjectObjectVersion = 90;
productRefGroup = D5A156D5289462B3006989FF /* Products */;
projectDirPath = "";
Expand Down Expand Up @@ -767,6 +775,13 @@
};
/* End XCConfigurationList section */

/* Begin XCLocalSwiftPackageReference section */
D5FCC6762FFC42DA00569E27 /* XCLocalSwiftPackageReference "NanoSVG" */ = {
isa = XCLocalSwiftPackageReference;
relativePath = NanoSVG;
};
/* End XCLocalSwiftPackageReference section */

/* Begin XCSwiftPackageProductDependency section */
D50C6F7528956DFC0003D1D0 /* CCCApi */ = {
isa = XCSwiftPackageProductDependency;
Expand All @@ -776,6 +791,10 @@
isa = XCSwiftPackageProductDependency;
productName = CCCApi;
};
D5FCC6772FFC42DA00569E27 /* NanoSVG */ = {
isa = XCSwiftPackageProductDependency;
productName = NanoSVG;
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = D5A156CC289462B3006989FF /* Project object */;
Expand Down
53 changes: 34 additions & 19 deletions HackerTube/Features/Conferences/ConferenceThumbnail.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,33 +8,48 @@
import CCCApi
import SwiftUI

/// Renders the thumbnail of a conference.
/// Some conferences have an SVG image as their thumbnail. This is not supported by Apple's `AsyncImage` so a custom
/// `SVGImageView` is used. It downloads the SVG, renders it to a bitmap and displays it.
struct ConferenceThumbnail: View {
let conference: Conference
@State private var id: UUID?

var body: some View {
AsyncImage(url: conference.logoURL) { phase in
if let image = phase.image {
image.resizable().scaledToFit()
} else if let error = phase.error as? NSError {
Text(conference.acronym)
.font(.title3.monospaced())
.frame(maxWidth: .infinity, maxHeight: .infinity)
.onAppear {
// Needed to reload the image when the request has been cancelled.
// This happens when the image scrolls out of view before it has finished loading.
if error.domain == NSURLErrorDomain, error.code == NSURLErrorCancelled {
id = UUID()
thumbnail
.frame(maxWidth: .infinity, maxHeight: .infinity)
.aspectRatio(16 / 9, contentMode: .fit)
.background(.regularMaterial)
.id(id)
}

@ViewBuilder private var thumbnail: some View {
if conference.logoURL.pathExtension.caseInsensitiveCompare("svg") == .orderedSame {
SVGImageView(url: conference.logoURL) { fallback }
} else {
AsyncImage(url: conference.logoURL) { phase in
if let image = phase.image {
image.resizable().scaledToFit()
} else if let error = phase.error as? NSError {
fallback
.onAppear {
// Needed to reload the image when the request has been cancelled.
// This happens when the image scrolls out of view before it has finished loading.
if error.domain == NSURLErrorDomain, error.code == NSURLErrorCancelled {
id = UUID()
}
}
}
} else {
ProgressView()
} else {
ProgressView()
}
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.aspectRatio(16 / 9, contentMode: .fit)
.background(.regularMaterial)
.id(id)
}

private var fallback: some View {
Text(conference.acronym)
.font(.title3.monospaced())
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}

Expand Down
137 changes: 137 additions & 0 deletions HackerTube/SVGImageView.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
//
// SVGImageView.swift
// HackerTube
//
// Created by Mathijs Bernson on 06/07/2026.
//

import SwiftUI
import NanoSVG

/// Loads an SVG from a URL and rasterizes it to a bitmap using `NanoSVG`.
struct SVGImageView<Fallback: View>: View {
let url: URL
@ViewBuilder var fallback: () -> Fallback

private var cache = SVGImageCache.shared
@Environment(\.displayScale) private var displayScale
@State private var image: CGImage?
@State private var didFail = false

init(url: URL, @ViewBuilder fallback: @escaping () -> Fallback) {
self.url = url
self.fallback = fallback
}

var body: some View {
GeometryReader { proxy in
content
.frame(width: proxy.size.width, height: proxy.size.height)
.task(id: RenderKey(url: url, size: proxy.size, scale: displayScale)) {
await load(size: proxy.size)
}
}
}

@ViewBuilder private var content: some View {
if let image {
Image(decorative: image, scale: displayScale, orientation: .up)
.resizable()
.scaledToFit()
} else if didFail {
fallback()
} else {
ProgressView()
}
}

private func load(size: CGSize) async {
guard size.width > 0, size.height > 0 else { return }
let key = RenderKey(url: url, size: size, scale: displayScale)

if let cached = cache[key] {
image = cached
return
}

didFail = false
do {
let (data, _) = try await URLSession.shared.data(from: url)
try Task.checkCancellation()
let rendered = try await rasterizeSVG(data: data, size: size, scale: displayScale)
cache[key] = rendered
image = rendered
} catch is CancellationError {
// View scrolled away mid-load; task will re-run on reappearance.
} catch {
image = nil
didFail = true
}
}
}

/// Equatable identity for the render task, so it re-runs only when the URL or
/// the target pixel size meaningfully changes (rounded to whole pixels to avoid
/// thrashing on sub-pixel layout changes).
private struct RenderKey: Equatable, CustomStringConvertible {
let url: URL
let pixelWidth: Int
let pixelHeight: Int

init(url: URL, size: CGSize, scale: CGFloat) {
self.url = url
self.pixelWidth = Int((size.width * scale).rounded())
self.pixelHeight = Int((size.height * scale).rounded())
}

var description: String {
"\(url.absoluteString)|\(pixelWidth)x\(pixelHeight)"
}
}

/// Off-main, CPU-bound rasterization. The non-Sendable `NanoSVGRenderer` is
/// created and consumed entirely here, so it never crosses a concurrency domain.
@concurrent
private func rasterizeSVG(data: Data, size: CGSize, scale: CGFloat) async throws -> CGImage {
try NanoSVGRenderer().render(svgData: data, targetSize: size, scale: scale)
}

// MARK: Caching

/// In-memory cache of rasterized SVG bitmaps, keyed by source URL and target
/// pixel size, so identical thumbnails aren't re-downloaded and re-rendered.
///
/// `NSCache` is thread-safe and automatically evicts entries under memory
/// pressure, so no manual eviction is needed.
private final class SVGImageCache {
private let cache = NSCache<NSString, CGImage>()

static let shared = SVGImageCache()

private init() {
cache.countLimit = 5 // Maximum number of cached images
}

subscript(key: RenderKey) -> CGImage? {
get {
let key = key.description as NSString
return cache.object(forKey: key)
}
set(image) {
let key = key.description as NSString
if let image {
cache.setObject(image, forKey: key)
} else {
cache.removeObject(forKey: key)
}
}
}
}

#Preview("SVG logo") {
SVGImageView(url: URL(string: "https://static.media.ccc.de/media/events/gpn/gpn24/logo.svg")!) {
Text("GPN42")
}
.frame(width: 320, height: 180)
.border(.blue)
}
8 changes: 8 additions & 0 deletions NanoSVG/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
.DS_Store
/.build
/Packages
xcuserdata/
DerivedData/
.swiftpm/configuration/registries.json
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
.netrc
18 changes: 18 additions & 0 deletions NanoSVG/LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
Copyright (c) 2013-14 Mikko Mononen memon@inside.org

This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.

Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.

27 changes: 27 additions & 0 deletions NanoSVG/Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// swift-tools-version: 6.0
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
name: "NanoSVG",
products: [
.library(
name: "NanoSVG",
targets: ["NanoSVG"]
),
],
targets: [
.target(
name: "NanoSVG",
dependencies: ["CNanoSVG"]
),
.target(name: "CNanoSVG"),

.testTarget(
name: "NanoSVGTests",
dependencies: ["NanoSVG"],
resources: [.copy("TestData")]
),
]
)
Loading
Loading