From 1d54877be2ee6b12c58b184c8dea2a9609284e53 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Tue, 28 Jul 2026 10:10:49 -0700 Subject: [PATCH 1/3] =?UTF-8?q?Support=20Atom=20xml:base=20=E2=80=94=20res?= =?UTF-8?q?olve=20relative=20URLs.=20Fixes=20#5088.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../RSParser/Feeds/XML/AtomParser.swift | 72 ++- .../HTML/HTMLRelativeURLResolver.swift | 408 ++++++++++++ .../Sources/RSParser/XML/XMLASCII.swift | 2 + .../Feeds/XML/AtomParserTests.swift | 183 ++++++ .../HTML/HTMLRelativeURLResolverTests.swift | 187 ++++++ .../RSParserTests/Resources/pappacoda.atom | 586 ++++++++++++++++++ 6 files changed, 1432 insertions(+), 6 deletions(-) create mode 100644 Modules/RSParser/Sources/RSParser/HTML/HTMLRelativeURLResolver.swift create mode 100644 Modules/RSParser/Tests/RSParserTests/HTML/HTMLRelativeURLResolverTests.swift create mode 100644 Modules/RSParser/Tests/RSParserTests/Resources/pappacoda.atom diff --git a/Modules/RSParser/Sources/RSParser/Feeds/XML/AtomParser.swift b/Modules/RSParser/Sources/RSParser/Feeds/XML/AtomParser.swift index 623bb38d1..a032123cf 100644 --- a/Modules/RSParser/Sources/RSParser/Feeds/XML/AtomParser.swift +++ b/Modules/RSParser/Sources/RSParser/Feeds/XML/AtomParser.swift @@ -49,6 +49,15 @@ private final class AtomDelegate: XMLSAXParserDelegate { // Attributes per open element. private var attributesStack: [XMLAttributes] = [] + // Effective xml:base per open element — kept exactly parallel to attributesStack. + private var baseURLStack: [URL?] = [] + + private lazy var documentURL: URL? = URL(string: feedURLString) + + private var effectiveBaseURL: URL? { + baseURLStack.last ?? nil + } + init(urlString: String) { self.feedURLString = urlString self.isDaringFireball = urlString.contains("daringfireball.net/") @@ -106,6 +115,7 @@ private final class AtomDelegate: XMLSAXParserDelegate { } attributesStack.append(attributes) + pushBaseURL(attributes) if namespaceElementDepth > 0 { namespaceElementDepth += 1 @@ -172,7 +182,17 @@ private final class AtomDelegate: XMLSAXParserDelegate { guard let article = currentArticle else { return } - let html = String(decoding: bytes, as: UTF8.self) + + // The content element is still on the stacks here, so effectiveBaseURL + // includes its own xml:base. An xml:base on an element inside the captured + // content is invisible (pass-through emits no events) and unsupported. + let html: String + if let base = effectiveBaseURL { + html = HTMLRelativeURLResolver.resolvingRelativeURLs(inBytes: bytes, baseURL: base) + } else { + html = String(decoding: bytes, as: UTF8.self) + } + if localName.equals("content") { article.body = html } else if localName.equals("summary") { @@ -189,6 +209,9 @@ private final class AtomDelegate: XMLSAXParserDelegate { if !attributesStack.isEmpty { attributesStack.removeLast() } + if !baseURLStack.isEmpty { + baseURLStack.removeLast() + } } if localName.equals("feed") { @@ -250,13 +273,13 @@ private final class AtomDelegate: XMLSAXParserDelegate { // Overwrite only if there are characters — // may have been set by didCaptureRawInnerContent for raw XHTML. if let s = parser.currentStringWithTrimmedWhitespace { - article.body = s + article.body = resolvedHTMLBody(s) } } else if localName.equals("summary") { // Overwrite only if there are characters — // may have been set by didCaptureRawInnerContent for raw XHTML. if let s = parser.currentStringWithTrimmedWhitespace { - article.summary = s + article.summary = resolvedHTMLBody(s) } } else if localName.equals("link") { handleArticleLink() @@ -352,7 +375,9 @@ private final class AtomDelegate: XMLSAXParserDelegate { } else if localName.equals("email") { author.emailAddress = parser.currentStringWithTrimmedWhitespace } else if localName.equals("uri") { - author.url = parser.currentStringWithTrimmedWhitespace + if let s = parser.currentStringWithTrimmedWhitespace { + author.url = resolvedURLString(s) ?? s + } } } @@ -368,11 +393,11 @@ private final class AtomDelegate: XMLSAXParserDelegate { } } else if localName.equals("icon") { if let s = parser.currentStringWithTrimmedWhitespace, !s.isEmpty { - iconURLString = s + iconURLString = resolvedURLString(s) ?? s } } else if localName.equals("logo") { if logoURLString == nil, let s = parser.currentStringWithTrimmedWhitespace, !s.isEmpty { - logoURLString = s + logoURLString = resolvedURLString(s) ?? s } } } @@ -401,10 +426,45 @@ private final class AtomDelegate: XMLSAXParserDelegate { // MARK: - URL resolution + // RFC 4287: xml:base applies to its element and everything below it, + // and a relative xml:base resolves against the nearest enclosing base — + // the document (feed) URL when there is none. + private func pushBaseURL(_ attributes: XMLAttributes) { + let inherited = baseURLStack.last ?? nil + guard !attributes.isEmpty, let xmlBase = attributes["xml:base"], !xmlBase.isEmpty else { + baseURLStack.append(inherited) + return + } + let outerBase = inherited ?? documentURL + guard let resolved = URL(string: xmlBase, relativeTo: outerBase)?.absoluteURL, + let scheme = resolved.scheme?.lowercased(), scheme == "http" || scheme == "https" else { + // A garbage or non-http base (tag:, urn:) would poison resolution — inherit instead. + baseURLStack.append(inherited) + return + } + baseURLStack.append(resolved) + } + + // Rewrite relative URLs in an escaped-HTML body when an xml:base is in effect. + // RFC 4287 allows a MIME type as well as the "html" keyword. + // type="text" (and absent type, which means text) is never rewritten. + private func resolvedHTMLBody(_ html: String) -> String { + let type = currentAttributes["type"] + guard type == "html" || type == "text/html", let base = effectiveBaseURL else { + return html + } + return HTMLRelativeURLResolver.resolvingRelativeURLs(in: html, baseURL: base) + } + private func resolvedURLString(_ s: String) -> String? { if isValidURLString(s) { return s } + if let base = effectiveBaseURL, + let resolved = URL(string: s, relativeTo: base)?.absoluteString, + isValidURLString(resolved) { + return resolved + } var base: String? = homepageURLString if base?.isEmpty ?? true { base = feedURLString diff --git a/Modules/RSParser/Sources/RSParser/HTML/HTMLRelativeURLResolver.swift b/Modules/RSParser/Sources/RSParser/HTML/HTMLRelativeURLResolver.swift new file mode 100644 index 000000000..38489077f --- /dev/null +++ b/Modules/RSParser/Sources/RSParser/HTML/HTMLRelativeURLResolver.swift @@ -0,0 +1,408 @@ +// +// HTMLRelativeURLResolver.swift +// RSParser +// +// Created by Brent Simmons on 7/28/26. +// + +import Foundation + +/// Resolves relative URLs in HTML attribute values (href, src, poster, srcset) +/// against a base URL — used for Atom xml:base support. +/// +/// Replacement is surgical: everything outside a rewritten attribute value is +/// byte-identical to the input. Values are left alone when they are empty, +/// fragment-only (`#…` — same-document references), or already have a scheme +/// (http:, data:, mailto:, and so on). Protocol-relative values (`//…`) do get +/// resolved, taking the base URL's scheme. +/// +/// Attribute values are not entity-decoded — `URL(string:relativeTo:)` passes +/// characters like `&` through untouched, so an `&` in a relative URL +/// survives resolution byte-for-byte. +public enum HTMLRelativeURLResolver { + + public static func resolvingRelativeURLs(in html: String, baseURL: URL) -> String { + let bytes = Array(html.utf8) + guard let rewritten = rewrittenBytes(bytes[...], baseURL: baseURL) else { + return html + } + return String(decoding: rewritten, as: UTF8.self) + } + + public static func resolvingRelativeURLs(inBytes bytes: ArraySlice, baseURL: URL) -> String { + guard let rewritten = rewrittenBytes(bytes, baseURL: baseURL) else { + return String(decoding: bytes, as: UTF8.self) + } + return String(decoding: rewritten, as: UTF8.self) + } +} + +// MARK: - Private + +private extension HTMLRelativeURLResolver { + + /// Returns nil when nothing needs resolving, so callers can keep the input verbatim. + static func rewrittenBytes(_ bytes: ArraySlice, baseURL: URL) -> [UInt8]? { + var scanner = URLReplacementScanner(bytes: bytes, baseURL: baseURL) + let replacements = scanner.scan() + if replacements.isEmpty { + return nil + } + + let sizeDelta = replacements.reduce(0) { $0 + $1.bytes.count - $1.range.count } + var result = [UInt8]() + result.reserveCapacity(bytes.count + sizeDelta) + + var copyStart = bytes.startIndex + for replacement in replacements { + result.append(contentsOf: bytes[copyStart.. + let bytes: [UInt8] + } + + /// Scans HTML bytes and collects the URL attribute-value replacements to make. + struct URLReplacementScanner { + + private let bytes: ArraySlice + private let baseURL: URL + private var pos: Int + private var replacements: [Replacement] = [] + + private var end: Int { + bytes.endIndex + } + + init(bytes: ArraySlice, baseURL: URL) { + self.bytes = bytes + self.baseURL = baseURL + self.pos = bytes.startIndex + } + + mutating func scan() -> [Replacement] { + while pos < end { + if bytes[pos] == .asciiLessThan { + handleLessThan() + } else { + pos += 1 + } + } + return replacements + } + + // MARK: Markup dispatch + + private mutating func handleLessThan() { + guard pos + 1 < end else { + pos = end + return + } + + let next = bytes[pos + 1] + if next == .asciiExclamation { + handleDeclaration() + } else if next == .asciiQuestion { + skipPast("?>") + } else if next == .asciiSlash { + skipPastGreaterThan() + } else if next.isASCIILetter { + scanStartTag() + } else { + pos += 1 + } + } + + private mutating func handleDeclaration() { + if matches("") + } else if matches("") + } else { + skipPastGreaterThan() + } + } + + // MARK: Start tags + + private mutating func scanStartTag() { + let nameStart = pos + 1 + var i = nameStart + while i < end && bytes[i].isXMLNameChar { + i += 1 + } + let tagName = bytes[nameStart.. + let quote = bytes[pos] + if quote == .asciiDoubleQuote || quote == .asciiSingleQuote { + let valueStart = pos + 1 + var i = valueStart + while i < end && bytes[i] != quote { + i += 1 + } + guard i < end else { + // Unterminated quote — abandon the rest of the scan. + // Replacements recorded so far were well-formed and stay. + pos = end + return + } + valueRange = valueStart..` (the WHATWG rule). + // Deliberately not at `/`, so href=/foo/bar isn't truncated. + let valueStart = pos + var i = pos + while i < end && !bytes[i].isASCIIWhitespace && bytes[i] != .asciiGreaterThan { + i += 1 + } + valueRange = valueStart.., valueRange: Range) { + if name.equalsASCIICaseInsensitive(lowercaseLiteral: "href") || + name.equalsASCIICaseInsensitive(lowercaseLiteral: "src") || + name.equalsASCIICaseInsensitive(lowercaseLiteral: "poster") { + addReplacementIfNeeded(valueRange) + } else if name.equalsASCIICaseInsensitive(lowercaseLiteral: "srcset") { + handleSrcsetValue(valueRange) + } + } + + // MARK: srcset + + private mutating func handleSrcsetValue(_ valueRange: Range) { + var i = valueRange.lowerBound + let valueEnd = valueRange.upperBound + + while i < valueEnd { + while i < valueEnd && (bytes[i].isASCIIWhitespace || bytes[i] == .asciiComma) { + i += 1 + } + guard i < valueEnd else { + return + } + + // URL token: up to whitespace. Trailing commas are separators, not URL. + let urlStart = i + while i < valueEnd && !bytes[i].isASCIIWhitespace { + i += 1 + } + var urlEnd = i + while urlEnd > urlStart && bytes[urlEnd - 1] == .asciiComma { + urlEnd -= 1 + } + let tokenEndedWithComma = urlEnd < i + + if urlEnd > urlStart { + addReplacementIfNeeded(urlStart..) { + // Browsers strip surrounding whitespace before processing a URL value. + // Classify and replace only the trimmed part — the whitespace stays. + let trimmed = trimmingASCIIWhitespace(range) + guard let resolved = resolvedURLBytes(bytes[trimmed]) else { + return + } + replacements.append(Replacement(range: trimmed, bytes: resolved)) + } + + private func trimmingASCIIWhitespace(_ range: Range) -> Range { + var lower = range.lowerBound + var upper = range.upperBound + while lower < upper && bytes[lower].isASCIIWhitespace { + lower += 1 + } + while upper > lower && bytes[upper - 1].isASCIIWhitespace { + upper -= 1 + } + return lower..) -> [UInt8]? { + guard shouldResolve(value) else { + return nil + } + let s = String(decoding: value, as: UTF8.self) + guard let resolved = URL(string: s, relativeTo: baseURL)?.absoluteString, resolved != s else { + return nil + } + return Array(resolved.utf8) + } + + private func shouldResolve(_ value: ArraySlice) -> Bool { + guard let first = value.first else { + return false // empty + } + if first == .asciiHash { + return false // same-document reference + } + return !hasScheme(value) + } + + /// True when the value starts with a URL scheme (`[A-Za-z][A-Za-z0-9+.-]*:`). + private func hasScheme(_ value: ArraySlice) -> Bool { + guard let first = value.first, first.isASCIILetter else { + return false + } + var i = value.startIndex + 1 + while i < value.endIndex { + let b = value[i] + if b == .asciiColon { + return true + } + if !(b.isASCIILetter || b.isASCIIDigit || b == .asciiPlus || b == .asciiHyphen || b == .asciiDot) { + return false + } + i += 1 + } + return false + } + + // MARK: Scanning helpers + + private mutating func skipWhitespace() { + while pos < end && bytes[pos].isASCIIWhitespace { + pos += 1 + } + } + + private mutating func skipPastGreaterThan() { + while pos < end && bytes[pos] != .asciiGreaterThan { + pos += 1 + } + if pos < end { + pos += 1 + } + } + + private func matches(_ literal: StaticString) -> Bool { + let count = literal.utf8CodeUnitCount + guard pos + count <= end else { + return false + } + return bytes[pos.. from being mistaken for . + private func isCloseTagNameBoundary(at index: Int) -> Bool { + guard index < end else { + return true + } + let b = bytes[index] + return b == .asciiGreaterThan || b == .asciiSlash || b.isASCIIWhitespace + } + } +} diff --git a/Modules/RSParser/Sources/RSParser/XML/XMLASCII.swift b/Modules/RSParser/Sources/RSParser/XML/XMLASCII.swift index ebaa34080..eb1cfbdd2 100644 --- a/Modules/RSParser/Sources/RSParser/XML/XMLASCII.swift +++ b/Modules/RSParser/Sources/RSParser/XML/XMLASCII.swift @@ -21,6 +21,8 @@ extension UInt8 { static let asciiHash = UInt8(ascii: "#") static let asciiAmpersand = UInt8(ascii: "&") static let asciiSingleQuote = UInt8(ascii: "'") + static let asciiPlus = UInt8(ascii: "+") + static let asciiComma = UInt8(ascii: ",") static let asciiHyphen = UInt8(ascii: "-") static let asciiDot = UInt8(ascii: ".") static let asciiSlash = UInt8(ascii: "/") diff --git a/Modules/RSParser/Tests/RSParserTests/Feeds/XML/AtomParserTests.swift b/Modules/RSParser/Tests/RSParserTests/Feeds/XML/AtomParserTests.swift index 74faa1360..5427b6104 100644 --- a/Modules/RSParser/Tests/RSParserTests/Feeds/XML/AtomParserTests.swift +++ b/Modules/RSParser/Tests/RSParserTests/Feeds/XML/AtomParserTests.swift @@ -67,6 +67,189 @@ import RSParser #expect(foundTestArticle) } + // MARK: - xml:base + // + + @Test func xmlBaseResolvesRelativeURLsInXHTMLContent() throws { + let d = parserData("pappacoda", "atom", "https://andrea.pappacoda.it/blog/feed.atom") + let parsedFeed = try #require(try FeedParser.parse(d)) + + // Root-relative and resolve against the feed-level xml:base. + // iconURL prefers the logo, faviconURL is the icon. + #expect(parsedFeed.iconURL == "https://andrea.pappacoda.it/assets/debian-button.gif") + #expect(parsedFeed.faviconURL == "https://andrea.pappacoda.it/andrea_pappacoda.jpg") + + let item = try #require(parsedFeed.items.first(where: { $0.title == "C su Windows" })) + + // is never resolved, even though it looks nothing like the base. + #expect(item.uniqueID == "tag:andrea.pappacoda.it,2023-06-09:c_su_windows") + #expect(item.url == "https://andrea.pappacoda.it/blog/c_su_windows/") + + let html = try #require(item.contentHTML) + #expect(html.contains("src=\"https://andrea.pappacoda.it/blog/c_su_windows/c_su_windows_visual_studio_componenti.png\"")) + #expect(html.contains("srcset=\"https://andrea.pappacoda.it/blog/c_su_windows/c_su_windows_visual_studio_componenti_light.png\"")) + #expect(html.contains("src=\"https://andrea.pappacoda.it/blog/c_su_windows/clangd_path.png\"")) + #expect(!html.contains("src=\"clangd_path.png\"")) + + // The xhtml wrapper still comes through verbatim. + #expect(html.contains("xmlns=\"http://www.w3.org/1999/xhtml\"")) + } + + @Test func nestedRelativeXMLBase() throws { + // A feed-level base and a relative content-level base compose, + // a relative entry link resolves against xml:base rather than + // the homepage fallback, and an xml:base on the link element itself wins. + let xml = """ + + + turn:t + + + urn:t:1 + nested base + 2020-05-01T00:00:00Z + + + <a href="pic.png">pic</a> + + + """ + let d = ParserData(url: "https://example.com/blog/feed.atom", data: Data(xml.utf8)) + let parsedFeed = try #require(try FeedParser.parse(d)) + let item = try #require(parsedFeed.items.first) + + #expect(item.url == "https://example.com/blog/post1/") + #expect(item.externalURL == "https://elsewhere.example.net/dir/related.html") + let html = try #require(item.contentHTML) + #expect(html.contains("href=\"https://example.com/blog/post1/pic.png\"")) + } + + @Test func mimeTypeHTMLContentWithXMLBaseResolved() throws { + // RFC 4287 allows type="text/html" as well as type="html". + let xml = """ + + + turn:t + + urn:t:1 + mime type html + 2020-05-01T00:00:00Z + <img src="pic.png"> + + + """ + let d = ParserData(url: "https://example.com/feed.atom", data: Data(xml.utf8)) + let parsedFeed = try #require(try FeedParser.parse(d)) + let item = try #require(parsedFeed.items.first) + + let html = try #require(item.contentHTML) + #expect(html.contains("src=\"https://example.com/post/pic.png\"")) + } + + @Test func relativeXMLBaseResolvesAgainstFeedURL() throws { + // qemu-style: a root-relative xml:base with no enclosing base + // resolves against the document (feed) URL. + let xml = """ + + + turn:t + + /2024/04/23/qemu-9-0-0 + release + 2024-04-23T23:02:00Z + <a href="changelog.html">changelog</a> + + + """ + let d = ParserData(url: "https://www.qemu.org/feed.xml", data: Data(xml.utf8)) + let parsedFeed = try #require(try FeedParser.parse(d)) + let item = try #require(parsedFeed.items.first) + + // The relative-looking stays verbatim. + #expect(item.uniqueID == "/2024/04/23/qemu-9-0-0") + let html = try #require(item.contentHTML) + #expect(html.contains("href=\"https://www.qemu.org/2024/04/23/qemu-9-0-0/changelog.html\"")) + } + + @Test func fragmentAndEmptyHrefsSurviveXMLBase() throws { + // One Foot Tsunami has per-entry xml:base plus footnote links like + // href="#fn…" in bodies — those must stay untouched (the footnote JS + // in the app depends on fragment-only hrefs). Some entries also have + // empty link hrefs, which must not resolve to the base URL itself. + let d = parserData("OneFootTsunami", "atom", "http://onefoottsunami.com/feed/atom/") + let parsedFeed = try #require(try FeedParser.parse(d)) + + let bodies = parsedFeed.items.compactMap { $0.contentHTML } + let fragmentHrefs = bodies.filter { $0.contains("href=\"#fn") } + #expect(!fragmentHrefs.isEmpty, "fragment-only hrefs must stay fragment-only") + + #expect(!parsedFeed.items.contains { $0.url?.hasSuffix("wp-atom.php") ?? false }, "empty link hrefs must not resolve to the base") + } + + @Test func summaryWithXMLBaseResolved() throws { + // A summary promoted to the body (no content element) is resolved + // against its own element's base at parse time. + let xml = """ + + + turn:t + + urn:t:1 + summary only + 2020-05-01T00:00:00Z + <img src="pic.png"> + + + """ + let d = ParserData(url: "https://example.com/feed.atom", data: Data(xml.utf8)) + let parsedFeed = try #require(try FeedParser.parse(d)) + let item = try #require(parsedFeed.items.first) + + let html = try #require(item.contentHTML) + #expect(html.contains("src=\"https://example.com/post/pic.png\"")) + } + + @Test func relativeAuthorURIResolvesAgainstXMLBase() throws { + let xml = """ + + + turn:t + + urn:t:1 + relative author uri + 2020-05-01T00:00:00Z + Aliceabout/ + + + """ + let d = ParserData(url: "https://example.com/blog/feed.atom", data: Data(xml.utf8)) + let parsedFeed = try #require(try FeedParser.parse(d)) + let item = try #require(parsedFeed.items.first) + let author = try #require(item.authors?.first) + #expect(author.url == "https://example.com/blog/about/") + } + + @Test func textContentWithXMLBaseUntouched() throws { + let xml = """ + + + turn:t + + urn:t:1 + text content + 2020-05-01T00:00:00Z + See src="pic.png" for details. + + + """ + let d = ParserData(url: "https://example.com/feed.atom", data: Data(xml.utf8)) + let parsedFeed = try #require(try FeedParser.parse(d)) + let item = try #require(parsedFeed.items.first) + + let html = try #require(item.contentHTML) + #expect(html.contains("src=\"pic.png\"")) + } + @Test func articleExternalLinks() throws { var d = parserData("DaringFireball", "atom", "https://daringfireball.net/feeds/main") var parsedFeed = try #require(try FeedParser.parse(d)) diff --git a/Modules/RSParser/Tests/RSParserTests/HTML/HTMLRelativeURLResolverTests.swift b/Modules/RSParser/Tests/RSParserTests/HTML/HTMLRelativeURLResolverTests.swift new file mode 100644 index 000000000..80c39149a --- /dev/null +++ b/Modules/RSParser/Tests/RSParserTests/HTML/HTMLRelativeURLResolverTests.swift @@ -0,0 +1,187 @@ +// +// HTMLRelativeURLResolverTests.swift +// RSParser +// +// Created by Brent Simmons on 7/28/26. +// + +import Foundation +import Testing +import RSParser + +@Suite struct HTMLRelativeURLResolverTests { + + private let base = URL(string: "https://example.com/blog/post1/")! + + private func resolved(_ html: String) -> String { + HTMLRelativeURLResolver.resolvingRelativeURLs(in: html, baseURL: base) + } + + // MARK: - Values that resolve + + @Test func relativeValuesResolve() { + let cases: [(input: String, expected: String)] = [ + ("x", "x"), + ("", ""), + ("", ""), + ("x", "x"), + ("x", "x"), + ("x", "x"), + ("x", "x") + ] + for c in cases { + #expect(resolved(c.input) == c.expected, "mismatch for \(c.input)") + } + } + + @Test func ampersandEntityInRelativeURLSurvives() { + let html = "x" + #expect(resolved(html) == "x") + } + + @Test func attributeNamesAreCaseInsensitive() { + #expect(resolved("y") == "y") + #expect(resolved("") == "") + } + + @Test func unquotedAndSingleQuotedValuesResolve() { + #expect(resolved("x") == "x") + #expect(resolved("y") == "y") + } + + // MARK: - Values left alone + + @Test func untouchedValues() { + let cases = [ + "x", + "x", + "x", + "x", + "", + "x", + "x", + "not URL attributes" + ] + for html in cases { + #expect(resolved(html) == html, "expected no change for \(html)") + } + } + + @Test func scriptStyleCommentsAndCDATAUntouched() { + let cases = [ + "", + "", + "", + "]]>" + ] + for html in cases { + #expect(resolved(html) == html, "expected no change for \(html)") + } + } + + @Test func scriptSrcAttributeStillResolves() { + // The script element's own attributes are scanned — only its text content is skipped. + let html = "" + #expect(resolved(html) == "") + } + + // MARK: - srcset + + @Test func srcsetCandidatesResolve() { + let cases: [(input: String, expected: String)] = [ + ("", + ""), + ("", + ""), + ("", + ""), + ("", + ""), + ("", + "") + ] + for c in cases { + #expect(resolved(c.input) == c.expected, "mismatch for \(c.input)") + } + } + + @Test func surroundingWhitespaceInValuesIsIgnoredAndPreserved() { + // Whitespace can't hide a fragment-only href from the skip rule. + #expect(resolved("x") == "x") + + // A padded relative value resolves — the padding stays in place. + #expect(resolved("x") == "x") + } + + @Test func similarlyNamedCloseTagDoesNotEndRawText() { + // is not — everything inside stays untouched. + let html = "" + #expect(resolved(html) == html) + } + + // MARK: - Malformed input + + @Test func malformedInputIsSafe() { + // Unterminated quote: scanning stops, input preserved. + let unterminated = "y" + #expect(resolved(strayLessThan) == "1 < 2 and y") + } + + // MARK: - No-op guarantee + + @Test func allAbsoluteDocumentIsUnchanged() { + let html = """ +

Intro text with an absolute link.

+ +

More text, an footnote, and an empty href.

+ """ + #expect(resolved(html) == html) + } + + @Test func mixedDocumentIsSurgical() { + // Everything outside the two rewritten values is byte-identical — + // whitespace, attribute order, quoting, the non-URL attributes. + let html = """ +
+ + + A screenshot + +
Caption & more
+
+ """ + let expected = """ +
+ + + A screenshot + +
Caption & more
+
+ """ + #expect(resolved(html) == expected) + } + + // MARK: - Bytes entry point + + @Test func bytesEntryPointMatchesStringEntryPoint() { + let html = "" + let bytes = Array(html.utf8)[...] + let fromBytes = HTMLRelativeURLResolver.resolvingRelativeURLs(inBytes: bytes, baseURL: base) + #expect(fromBytes == resolved(html)) + + let absolute = "" + let absoluteBytes = Array(absolute.utf8)[...] + #expect(HTMLRelativeURLResolver.resolvingRelativeURLs(inBytes: absoluteBytes, baseURL: base) == absolute) + } +} diff --git a/Modules/RSParser/Tests/RSParserTests/Resources/pappacoda.atom b/Modules/RSParser/Tests/RSParserTests/Resources/pappacoda.atom new file mode 100644 index 000000000..e73bb45c1 --- /dev/null +++ b/Modules/RSParser/Tests/RSParserTests/Resources/pappacoda.atom @@ -0,0 +1,586 @@ + + + https://andrea.pappacoda.it/blog/feed.atom + + + + Andrea Pappacoda - Blog + 2026-05-24T13:02:30+02:00 + + Andrea Pappacoda + https://andrea.pappacoda.it + + Vim + /andrea_pappacoda.jpg + /assets/debian-button.gif + © 2026 Andrea Pappacoda + Faccio cose + + tag:andrea.pappacoda.it,2026-05-24:favicon_2026 + Le favicon non sono difficili + 2026-05-24T13:02:30+02:00 + 2026-05-24T13:02:30+02:00 + Una guida ragionata alle favicon (e non solo) + +
+ +

Le favicon non sono difficili

+

+ Sembra che nel mondo della creazione dei siti web ci sia una enorme confusione + su come specificare le + Favicon, ovvero l'icona di + un particolare sito web. +

+

+ Il mio sito al momento in cui sto scrivendo non ha nessuna favicon, ma in + questi giorni ho impostato quella del + sito di HackInPovo, un hacklab locale + di cui faccio parte. Doveva essere una cosa semplicissima, ma se ci sto + scrivendo un articolo a riguardo significa che qualcosa è andato storto. +

+

+ Il web, infatti, ha fatto un casino. Gente confusa che fa domande, "guru" che + danno risposte approssimative, soluzioni che "a me funzionano" sparate un po' + qua e là. Ma qual è la causa di questo caos? +

+

Il problema

+

+ In breve, il problema è che il web è vecchio. Mi spiego meglio. +

+

+ Esistono tantissimi web browser, da tantissimi anni, e se oggi la situazione è + abbastanza standardizzata, con gruppi di persone che lavorano insieme per far + sì che diverse implementazioni funzionino in maniera simile, non è sempre stato + così. +

+

+ In passato i vari autori di browser web hanno aggiunto, ognuno a modo + loro, la possibilità per un sito web di comunicare al browser una sua icona + "preferita", per dare un riferimento simbolico e visuale al sito. Nonostante + l'idea sia generica, le risposte alle domande implementative erano diverse: + quali formati immagine supportiamo? Come troviamo l'icona? Di che dimensione + dev'essere? Ma se tipo voglio aggiungere un collegamento del sito alla + home page del mio telefono che icona uso? E come + facciamo per i temi chiaro/scuro? E così via. +

+

+ È quindi naturale che in un ecosistema dove chi sviluppa dà risposte diverse a + domande che cambiano nel tempo, ogni risposta di un "guru" pubblicata da + qualche parte nell'internet lascia il tempo che trova. +

+

La soluzione

+

+ La soluzione è non ascoltare quello che dicono i guru. Sì, questo articolo + compreso. +

+

+ O meglio: dobbiamo farci dare le risposte da chi sviluppa le tecnologie del + web, in quanto sono loro davvero gli unici che conoscono la verità. A questo, + non fa mai male aggiungere un po' di buon senso proprio, più un occhio di + riguardo per chi utilizza browser vecchi o alternativi. +

+

+ Ma dove le dobbiamo cercare, quindi, queste risposte? Ci basta sapere chi + sviluppa le tecnologie del web come l'HTML, e dove vengono da loro pubblicate + le informazioni per noi comuni mortali. +

+

+ Lo standard HTML viene sviluppato principalmente da un gruppo di persone + chiamato "WHATWG", e pubblicato come una + grossa specifica nota come + "HTML Living Standard". + Potete spulciarvi tutto il documento se siete curiosi e avete abbastanza tempo + libero, ma se volete semplicemente sapere come cavolo impostare 'ste benedette + icone vi rimando direttamente alla pagina che descrive il comportamento + dell'elemento link, in particolare la sezione + 4.6.6.9 Link type "icon". +

+

+ Lo standard mostra come per specificare una icona sia necessario creare + un elemento link con l'attributo rel impostato a + icon, l'attributo type che specifichi il + media type + dell'immagine, l'attributo sizes che specifichi le dimensioni + in pixel dell'immagine e infine l'attributo href che contenga il + percorso all'immagine da usare come icona. +

+

+ Tutte queste informazioni vengono usate dal web browser per capire quale icona + scegliere a seconda del contesto. Una immagine vettoriale SVG verrà + probabilmente preferita a un PNG, a meno che il PNG non abbia una dimensione in + pixel che sia esattamente quella necessaria al browser. +

+

+ O forse no. +

+

+ Non ci importa sapere che cosa un determinato browser faccia oggi, + perché probabilmente domani agirà in maniera diversa. Quello che ci interessa + sapere è come comunicare al browser in maniera efficace tutto quello che gli + serve per fare la scelta che questo reputi più giusta. +

+

Il buon senso

+

+ Arriviamo quindi alle mie raccomandazioni personali, basate su quello che credo + sia un po' di ragionamento e buon senso. +

+

+ Storicamente i browser web hanno usato una immagine in + formato ICO + chiamata "favicon.ico" e disponibile nella cartella primaria del sito web. + Quindi, se il nostro sito è blog.example.org, dovrebbe essere + accessibile dall'URL https://blog.example.org/favicon.ico. +

+

+ È importante assicurarsi che l'immagine sia effettivamente in formato ICO, e + non semplicemente chiamata "favicon.ico". Creare una icona in questo formato è + abbastanza semplice usando il programma + ImageMagick: +

+
$ magick immagine.png -resize 256x -define icon:auto-resize favicon.ico
+

+ L'opzione + + -define + icon:auto-resize + ci permette di sfruttare una utile funzionalità dei file ICO, ovvero + quella di inserire più dimensioni della stessa immagine all'interno di un unico + file. Possiamo averne conferma sempre con ImageMagick usando il suo + sotto-comando identify: +

+
$ magick identify favicon.ico
+favicon.ico[0] ICO 256x256 256x256+0+0 8-bit sRGB 0.010u 0:00.003
+favicon.ico[1] ICO 192x192 192x192+0+0 8-bit sRGB 0.010u 0:00.001
+favicon.ico[2] ICO 128x128 128x128+0+0 8-bit sRGB 0.010u 0:00.001
+favicon.ico[3] ICO 96x96 96x96+0+0 8-bit sRGB 0.010u 0:00.000
+favicon.ico[4] ICO 64x64 64x64+0+0 8-bit sRGB 0.010u 0:00.000
+favicon.ico[5] ICO 48x48 48x48+0+0 8-bit sRGB 0.000u 0:00.000
+favicon.ico[6] ICO 40x40 40x40+0+0 8-bit sRGB 0.000u 0:00.000
+favicon.ico[7] ICO 32x32 32x32+0+0 8-bit sRGB 0.000u 0:00.000
+favicon.ico[8] ICO 24x24 24x24+0+0 8-bit sRGB 0.000u 0:00.000
+favicon.ico[9] ICO 16x16 16x16+0+0 8-bit sRGB 569494B 0.000u 0:00.000
+

+ Essendo che il formato ICO non fa uso di compressione, l'avere così tante + immagini di diverse dimensioni può portare a un file di dimensioni eccessive. + Il problema è evitabile specificando quali risoluzioni ci interessano + all'opzione -define icon:auto-resize, ad esempio con + -define icon:auto-resize=128,96,64,48,40,32,24,16. +

+

+ Infine, questa immagine dovrà essere aggiunta all'intestazione del documento + HTML del nostro sito con un elemento link: +

+
<link
+	rel="icon"
+	type="image/vnd.microsoft.icon"
+	sizes="128x128 96x96 64x64 48x48 40x40 32x32 24x24 16x16"
+	href="/favicon.ico"
+/>
+

+ Una icona di più alta risoluzione può essere aggiunta usando una immagine di + tipo PNG, che è un formato un po' più moderno ed efficiente dei file ICO di + Microsoft. Il mio consiglio è di usare una immagine che abbia una risoluzione + maggiore dell'immagine ICO, come 256x256 o 512x512 pixel, ma non più di + 1024x1024 pixel. +

+

+ Il motivo è che tipicamente le favicon vengono rappresentate come piccolissime + immagini sul nostro schermo, e diventano più grandi in condizioni particolari + (tipo quando aggiungiamo un sito alla pagina iniziale del browser). Non serve + quindi che l'immagine abbia risoluzione estremamente elevata. Per i curiosi, + i dettagli sul perché del limite di 1024 pixel sono discussi più sotto. +

+

+ Il secondo elemento link che quindi consiglio è questo qui: +

+
<link
+	rel="icon"
+	type="image/png"
+	sizes="256x256"
+	href="/favicon.png"
+/>
+

+ Ma tutte queste chiacchiere sulle dimensioni sono inutili. La vera soluzione è + quella di usare una immagine vettoriale in formato SVG, così che i siano i + browser stessi a poter scegliere la dimensione che vogliono, senza dover star + lì a impazzire creando mille mila PNG di dimensioni diverse. L'unico motivo per + cui non consiglio di usare solo un SVG è che non tutti i browser li + supportano. +

+

+ Il terzo e ultimo elemento link da aggiungere è quindi questo: +

+
<link
+	rel="icon"
+	type="image/svg+xml"
+	sizes="any"
+	href="/favicon.svg"
+/>
+

La mela

+

+ E anche oggi mi tocca parlar di Apple... +

+

+ Anche se questo articolo parla delle favicon, non posso fare a meno di parlare + anche della icona assegnata alle Web Clip su iOS, meglio nota come "Apple touch + icon". +

+

+ Nonostante Safari di Apple utilizzi le icone specificate con + rel="icon" come iconcine dei siti all'interno del browser stesso, + quando andiamo ad aggiungere il sito alla schermata Home del telefono (creando + quindi una Web Clip) quell'immagine viene totalmente ignorata. +

+

+ Al suo posto viene invece usata l'immagine specificata attraverso il valore + apple-touch-icon dell'attributo rel. Questa immagine + ha dei requisiti particolari imposti da Apple, sparsi in diverse pagine di + documentazione ufficiale. + L'originale + (e ormai obsoleto) documento mostra diverse dimensioni come esempi, + raccomandando di leggere le iOS Human Interface Guidelines per i valori effettivi. + Queste, nella + sezione dedicata alle icone + raccomandano che le icone siano quadrati di 1024 pixel. E, ancora, in una + pagina + di documentazione per sviluppatori riguardante le API di gestione del dispositivo, + viene raccomandato che l'immagine non superi i 400x400 pixel. +

+

+ Insomma, un casino. +

+

+ Per capire effettivamente cosa fare bisogna fare un passo indietro nel tempo, + quando la documentazione di Apple conteneva ancora informazioni precise. + Nel 2023, infatti, le + HIG spiegavano che i dispositivi + iOS usano icone a multipli di 60 pixel, a seconda della loro dimensione. + Il mio vecchio iPhone SE, ad esempio, usa un fattore di scala "@2x", quindi + vuole le icone di 120x120 pixel, mentre l'ultimissimo iPhone 17 Pro Max ha un + fattore di scala @3x, con icone della Home screen a 180x180 pixel. +

+

+ Potremmo quindi voler usare due immagini, una scalata @2x e una @3x. + Se proprio sentite che 180 pixel sembrano troppo pochi, potete anche inventarvi + un fattore di scala @4x con una immagine di 240x240 pixel, così da essere pronti + anche all'iPhone 28 con Diplay Retina Hyper-Dense™. +

+ +

+ Ma in termini pratici, questa distinzione non è davvero necessaria. + L'icona infatti verrà infatti riadattata automaticamente dal dispositivo se + troppo grande o troppo piccola. Per semplicità consiglio quindi di usare un + singolo PNG di 180x180 pixel chiamato apple-touch-icon.png. + Inoltre, l'immagine dev'essere quadrata, non circolare (così come le icone di iOS). +

+

+ Ed ecco quindi il vero ultimo elemento link da aggiungere alla + nostra pagina HTML: +

+
<link
+	rel="apple-touch-icon"
+	type="image/png"
+	sizes="180x180"
+	href="/apple-touch-icon.png"
+/>
+

Trick extra

+

+ Se proprio vi piace fare tutto preciso per filo e per segno allora vi consiglio + anche l'uso di tre programmini per ottimizzare e semplificare le vostre favicon: + pngquant, + oxipng e + usvg. +

+

+ I primi due servono per ridurre drasticamente le dimensioni dei file PNG. Il + primo ricodifica i PNG in un formato più efficiente, riducendo il numero di + colori usati per esprimere l'icona (talvolta con una minima, seppur + impercettibile, perdita di dettagli), mentre il secondo rimuove metadati non + necessari e ri-comprime l'immagine senza perdita di qualità. +

+

+ Ad esempio, per creare la favicon di tipo PNG che ho descritto prima potete + usare una combo di ImageMagick + pngquant + oxipng in questo modo: +

+
$ magick immagine.png -resize 256x png:- \
+| pngquant --speed 1 - \
+| oxipng --opt max --strip all --out favicon.png -
+

+ usvg, invece, semplifica drasticamente la struttura dei file SVG così che + risultino più facilmente gestibili dai vari visualizzatori, risolvendo così + eventuali problemi di visualizzazione che alcuni utenti potrebbero incontrare, + specialmente su browser vecchi o alternativi. Usarlo è molto semplice: +

+
$ usvg immagine.svg favicon.svg
+

Conclusioni

+

+ Spero che questo articolo abbia fatto un po' di chiarezza! +

+

+ Non solo: il messaggio più importante che voglio far passare è che + importantissimo sviluppare la capacità di individuare da chi + andare a prendere le risposte alle nostre domande. Il web, come ogni altra + parte del mondo, è pieno di contenuto che ci viene sparato addosso da ogni + lato. Spendere un po' di tempo ed energie per andare alla radice della + questione e trovare la vera risposta è l'unico modo per trovare quale, + tra il mare di dati, è l'informazione corretta. +

+

+ E se siete dei nerd come me, è anche divertente :D +

+

Dedicato a viirginiax

+ +
+
+ + tag:andrea.pappacoda.it,2024-12-12:tesi + Una nuova primitiva di creazione dei processi per sistemi Unix + 2024-12-12T15:30:00+01:00 + 2026-06-02T15:14:31+02:00 + + Nei sistemi Unix la creazione dei processi è stata storicamente effettuata + attraverso la famiglia di funzioni fork() ed exec(). In questa tesi verrà + introdotta e analizzata la funzione spawn(), una nuova primitiva + fondamentalmente diversa che, con un design più semplice, mira a risolvere + le problematiche legate alla natura di fork() + + + + + tag:andrea.pappacoda.it,2023-06-09:c_su_windows + C su Windows + 2023-06-09T16:00:00+01:00 + 2025-12-26T20:30:00+01:00 + Come installare un ambiente di sviluppo flessibile e moderno per C su Windows + +
+ +

C su Windows

+

Installare un compilatore C su Windows può essere semplice quanto complesso, a +seconda della procedura scelta. Ci sono due modi principali per farlo, uno più +immediato e uno più flessibile. Si può decidere di installare l'IDE Visual +Studio e lasciar fare tutto a lui, ma si sarà praticamente obbligati ad usare +l'IDE per tutte le interazioni con gli strumenti di sviluppo C, oppure si può +andare a installare gli strumenti di sviluppo manualmente senza l'IDE e andare a +configurare il nostro editor di codice per fare uso degli strumenti scaricati.

+

Qui andrò a spiegare i dettagli della seconda procedura, dato che la prima è +abbastanza semplice; basta cercare Visual Studio sul web, scaricare l'installer +e seguire le istruzioni a schermo.

+

Potrei partire subito con la lista di cose da fare, ma preferisco prima spiegare +un attimo cosa e soprattutto perché stiamo facendo le cose in questo modo. C e +C++, a differenza di altri linguaggi, sono solo "standard", documenti che +descrivono come C dovrebbe funzionare, ed esistono quindi diverse +implementazioni di questi standard, di queste specifiche. Ogni implementazione è +divisa in due componenti principali: il compilatore C, che prende il nostro +codice sorgente e lo trasforma in codice macchina eseguibile, e la libreria +standard C che contiene tutte le funzioni, appunto, "di libreria", come +printf(), scanf(), e insomma tutte le funzioni che possiamo includere nel +nostro codice con direttive come #include <stdlib.h> eccetera.

+

Dovrebbe essere ora un po' più chiaro cosa dobbiamo fare, ovvero installare un +compilatore e una libreria standard. Su Windows esistono diversi compilatori C, +ma solo una libreria standard. Questi fanno parte di "MSVC", che sta per +"Microsoft Visual C", che come dice il nome sono parte della suite di Visual +Studio. Per installarli è necessario scaricare i "Visual Studio Build Tools", +che sono gli stessi strumenti installati con l'IDE ma senza l'IDE. I Build Tools +sono sul sito di Visual Studio; basta cercarli sul web e andare in fondo alla +pagina (oppure andare direttamente su +https://visualstudio.microsoft.com/it/downloads/#build-tools-for-visual-studio-2022). +Una volta scaricato ed avviato l'installer ci ritroveremo davanti a una sezione +che permette di selezionare tanti workload diversi; a noi servono solo una +manciata di componenti, quindi bisogna spostarsi nella sezione "Singoli +componenti" selezionare "Funzionalità di base per C++ Build Tools", la versione +più recente di MSVC (nel mio caso "MSVC v143 - VS 2022 C++ Build Tools x64/x86 +(più recente)"), l'ultimo Windows SDK (nel mio caso "Windows 11 SDK +(10.0.22621.0)"), e "Windows Universal C Runtime". Una volta selezionati, +possiamo procedere con l'installazione. Il tutto andrà a occupare un paio di GB +di spazio di archiviazione.

+
+ + + Screenshot del Visual Studio Installer + +
Componenti da selezionare dal Visual Studio Installer
+
+

A questo punto abbiamo già un ambiente di sviluppo C, benché molto minimale. +Possiamo accedere al compilatore aprendo il "Prompt dei comandi di sviluppo +nativo x64", e dando il comando cl. Per compilare un file si può dare cl nomefile.c, ed eseguire il .exe generato.

+

Per come Microsoft ha sviluppato i suoi compilatori, l'uso di questo prompt di +comandi di sviluppo, a volte installato in inglese come "x64 Native Tools +Command Prompt", è obbligatorio per avere accesso al compilatore C. Quindi ogni +volta che vorremo andare a sviluppare codice C o C++ dovremo lanciare prima di +tutto uno di quei cmd, e da lì tutti i programmi (ad esempio, se vogliamo +usare VSCode, dovremo aprire un developer command prompt e digitare code per +lanciarlo direttamente dal cmd di sviluppo).

+

Con questo set up, però, aprendo un editor di codice come VSCode non ci saranno +funzionalità "smart" come segnalazione di errori, warning, suggerimenti, +eccetera. Anche qui, abbiamo due opzioni: la prima è specifica a VSCode, di +qualità relativamente bassa, (e ho visto che è un po' buggata, ma non avendola +usata molto personalmente non ne sono sicuro), mentre la seconda è utilizzabile +da pressoché tutti gli editor di codice, è più usata, dà suggerimenti migliori, +ma vanno fatti dei passaggi a mano. Ovviamente, sceglieremo la seconda opzione.

+

La seconda opzione consiste nell'usare clangd, un Language Server basato sul +compilatore Clang, che parla il Language Server Protocol (LSP). In pratica è +un programmino che parla con un qualsiasi editor di codice che supporta l'LSP e +gli dice se e cosa non va bene del codice presente nell'editor. Clang invece è +un ottimo compilatore basato sul progetto LLVM, ed è naturale che abbia +suggerimenti molto utili.

+

Per ottenere clangd è sufficiente scaricare l'ultima release pubblicata sulla +sua pagina GitHub, disponibile al link +https://github.com/clangd/clangd/releases/latest nella sezione "Assets". Una +volta scaricato lo zip, possiamo estrarlo in una cartella a piacere e informare +Windows della sua esistenza, così che possa essere eseguito dal nostro editor di +testo; in altri termini, dobbiamo aggiungere l'eseguibile clangd alla variabile +d'ambiente PATH. Per fare ciò ci basta cercare "Variabili d'ambiente" nella +casella di ricerca di sistema, aprire la pagina delle impostazioni, e andare a +modificare la variabile Path per l'utente corrente. Una volta schiacciato +"Modifica", andiamo a schiacciare "Nuovo" nella finestra di dialogo appena +aperta e incolliamo il percorso completo alla cartella bin contenuta nello zip +di clangd appena estratto. Fatto ciò, possiamo schiacciare "Ok" per chiudere +tutte le finestre appena aperte.

+
+ + Screenshot del dialogo di sistema per modificare le variabili d'ambiente + +
Variabile Path modificata per clangd
+
+

Bene, ora che abbiamo installato tutta la roba che ci serve, possiamo procedere +con l'ultimo passaggio: configurare l'editor di codice per fare uso di quello +che abbiamo installato. Essendo clangd un server LSP standard è possibile usare +un qualsiasi editor di codice molto facilmente, ed io ho scelto VSCode. Per +usare clangd su VSCode è sufficiente installare l'estensione "clangd" ed +assicurarsi che l'estensione C/C++ di Microsoft non sia installata, in quanto +andrebbe in conflitto con clangd. Finita l'installazione, il nostro editor +dovrebbe essere in grado di sfruttare tutte le funzionalità intelligenti che +potremmo desiderare, come salti a definizione di funzioni, documentazione +appoggiando il puntatore su un simbolo, eccetera.

+
+ + + Screenshot di VSCode che mostra la funzionalità di documentazione al passaggio del cursore + +
Alcune delle funzionalità abilitate da LSP
+
+

Nonostante LSP sia fantastico per quanto riguarda la scrittura di codice, non +fornisce altre funzionalità che potremmo volere, come il debug in un click di un +programma. Quest'area è meno standardizzata, per cui so dirvi solo come +configurare il debugger su VSCode. Il miglior debugger per C e C++ integrato in +VSCode è, a parer mio, contenuto nell'estensione CodeLLDB. Usa, appunto, il +debugger LLDB, parte di LLVM proprio come clangd, e supporta il debug di +programmi scritti per Windows e non. Una volta installata l'estensione, rimane +un ultima parte di configurazione da fare: bisogna dire a VSCode quale programma +vogliamo debuggare, come, e dove. Questa configurazione viene fatta creando un +file chiamato launch.json e memorizzato nella cartella .vscode del progetto, +contenente più o meno questo:

+
{
+    "version": "0.2.0",
+    "configurations": [
+        {
+            "type": "lldb",
+            "expressions": "native",
+            "request": "launch",
+            "name": "Debug",
+            "program": "${workspaceFolder}/mioprogetto.exe"
+        }
+    ]
+}
+

Quel file dice a VSCode che abbiamo creato una configurazione chiamata "Debug", +da eseguire con il debugger "lldb", che deve lanciare il programma +"mioprogetto.exe". L'opzione "expressions: native" dice a LLDB che vogliamo +usare la classica sintassi C per le espressioni inserite nel pannello "Watch" +del debugger, e non una alternativa custom di LLDB.

+

Bene! Ora ci basta soltanto compilare il nostro file .c dal terminale +integrato di VSCode e premere il triangolino verde per far partire il debugger. +Per compilare, ad esempio, un file chiamato "main.c", ci è sufficiente usare +questo comando:

+
cl -Zi main.c
+

E verrà generato l'eseguibile main.exe, insieme ad altri file intermedi che +non ci interessano. L'uso della opzione -Zi è indispensabile per il debug, in +quanto senza di questa il nostro codice C verrebbe compilato senza informazioni +di debug richieste, appunto, da LLDB per debuggare il programma.

+

Potremmo fermarci qui, ma c'è un ultima chicca che voglio lasciarvi che renderà +l'esperienza di debug un po' più gradevole. Dover ricompilare a mano tutte le +volte il programma prima di poterlo eseguire è un po' una rottura, vero? Beh, +per me lo è, ma fortunatamente VSCode può automatizzare il tutto con solo un +altro paio di righe di configurazione.

+

Per prima cosa andiamo a creare un nuovo file tasks.json all'interno della +cartella .vscode creata in precedenza che dice all'editor come compilare il +nostro progetto:

+
{
+    "version": "2.0.0",
+    "tasks": [
+        {
+            "label": "compile",
+            "type": "process",
+            "command": "cl",
+            "args": ["-Zi", "mioprogetto.c"],
+            "presentation": {
+                "reveal": "silent",
+                "focus": false
+            }
+        }
+    ]
+}
+

Il file definisce un task chiamato "compile" che lancia un "process", "cl", +passandogli gli argomenti "-Zi" e "mioprogetto.c". Visto che è un task di bassa +importanza, diciamo anche che la sua "presentation" dev'essere "silent", ovvero +che l'output della compilazione dev'essere mostrato solo in caso di errore.

+

Il secondo e ultimo passaggio è quello di dire a VSCode che il task di +compilazione dev'essere lanciato appena prima di far partire il debugger, e per +fare ciò ci basta solamente aggiungere l'opzione "preLaunchTask": "compile" al +file launch.json creato prima, che dovrebbe ora essere così:

+
{
+    "version": "0.2.0",
+    "configurations": [
+        {
+            "type": "lldb",
+            "expressions": "native",
+            "request": "launch",
+            "name": "Debug",
+            "program": "${workspaceFolder}/mioprogetto.exe",
+            "preLaunchTask": "compile"
+        }
+    ]
+}
+

E questo è tutto, potete ora giocare col vostro nuovo ambiente di sviluppo per C +e C++ sul sistema operativo di casa Microsoft! A parer mio, questo setup è il +miglior compromesso tra convenienza, semplicità e funzionalità, per non parlare +di quanto sia più leggero rispetto a un IDE completo come Visual Studio. Usare +questi strumenti in questo modo vi permette di mettere mano direttamente al +livello più basso del processo costruzione dei programmi C, così da avere la +possibilità di capire veramente cosa accade dietro alle quinte quando premete +quel bel bottone verde per far partire il programma :)

+

Dedicato al Maestro

+ +
+
+
From 5e2cdf63d8e4be45fe15cf0dff7919125e1dd51a Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Tue, 28 Jul 2026 10:26:59 -0700 Subject: [PATCH 2/3] Make sure toolbar is showing when moving focus to search field. Fixes #4896. --- Mac/MainWindow/MainWindowController.swift | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Mac/MainWindow/MainWindowController.swift b/Mac/MainWindow/MainWindowController.swift index 53ed0603d..c43f1fb6c 100644 --- a/Mac/MainWindow/MainWindowController.swift +++ b/Mac/MainWindow/MainWindowController.swift @@ -556,6 +556,11 @@ final class MainWindowController: NSWindowController, NSUserInterfaceValidations } @IBAction func moveFocusToSearchField(_ sender: Any?) { + // The search field lives in the toolbar — show it if hidden. + // + if let toolbar = window?.toolbar, !toolbar.isVisible { + toolbar.isVisible = true + } guard let searchField = currentSearchField else { return } From 40e3408f5ed8d055c8af543f048e8b995c6eb643 Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Tue, 28 Jul 2026 10:58:40 -0700 Subject: [PATCH 3/3] Fix iCloud sync progress leaks that left the Refresh button and menu item wrongly disabled. Fixes #4538. --- .../CloudKit/CloudKitAccountDelegate.swift | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift index 2278fe306..654fa479e 100644 --- a/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift +++ b/Modules/Account/Sources/Account/CloudKit/CloudKitAccountDelegate.swift @@ -456,7 +456,9 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { account.removeFolderFromTree(folder) try await account.logActivity(kind: .removeFolder, detail: folderName) { - syncProgress.addTask() + // Two tasks: finding the folder's feed externalIDs, removing the folder record. + // Every path below completes exactly two. + syncProgress.addTasks(2) let feedExternalIDs: [String] do { @@ -570,7 +572,9 @@ enum CloudKitAccountDelegateError: LocalizedError, Sendable { account.addFolderToTree(folder) } } catch { - syncProgress.completeTask() + // Only reachable when createFolder throws, before any of the + // 1 + feedsToRestore.count tasks completed — complete them all. + syncProgress.completeTasks(1 + feedsToRestore.count) postSyncError(error, account: account, operation: "Restoring folder") throw error } @@ -893,7 +897,9 @@ private extension CloudKitAccountDelegate { editedName: editedName, container: container) } catch { - syncProgress.completeTasks(3) + // When FeedFinder.find is what threw, none of the five tasks have completed yet — + // four here plus one more from the validateFeed path or addDeadFeed. + syncProgress.completeTasks(4) if validateFeed { syncProgress.completeTask() throw AccountError.createErrorNotFound @@ -991,6 +997,11 @@ private extension CloudKitAccountDelegate { func sendNewArticlesToTheCloud(_ account: Account, _ feed: Feed) { Self.logger.debug("CloudKitAccountDelegate: \(#function, privacy: .public)") Task { + // Completes createRSSFeed's fifth task. + // + defer { + syncProgress.completeTask() + } do { let articles = await account.fetchArticlesAsync(.feed(feed))