Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
hrefresolver.cpp
Go to the documentation of this file.
1// Copyright (C) 2026 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
3
4#include "hrefresolver.h"
5
6#ifdef QDOC_TEMPLATE_GENERATOR_ENABLED
7
8#include "collectionnode.h"
9#include "inclusionfilter.h"
10#include "locationplan.h"
11#include "outputcontext.h"
12#include "qmltypenode.h"
13#include "tree.h"
14
15#include <QtCore/qdir.h>
16
17QT_BEGIN_NAMESPACE
18
19using namespace Qt::StringLiterals;
20
21/*!
22 \struct HrefResolverConfig
23 \internal
24 \brief Configuration for HrefResolver URL computation.
25
26 The non-owning \c context pointer supplies the output directory and
27 diagnostic gating used for cross-module prefixes and warnings. The
28 non-owning \c plan pointer supplies every page name and anchor, so the
29 resolver never derives a location of its own. Both must outlive the
30 HrefResolver.
31
32 The \c qmlTypeContextFn callback returns the current QML type
33 being documented, enabling property inheritance resolution for
34 abstract QML types. An empty callback disables this resolution.
35 hrefForNode() prefers the \c relative page when it is a QML type,
36 because that page is the member's rendered documentation owner and
37 the callback may hold stale state from another generator.
38*/
39
40/*!
41 \class HrefResolver
42 \internal
43 \brief Computes URLs for documentation nodes from the planned locations.
44
45 Page names and anchors come from the LocationPlan the configuration
46 names; this class adds the link policy on top: inclusion filtering,
47 same-page suppression, the remapping of abstract QML type members onto
48 the inheriting type's page, and the relative prefix that reaches
49 another module's output directory.
50*/
51
52HrefResolver::HrefResolver(const HrefResolverConfig &config)
53 : m_config(config)
54{
55}
56
57/*!
58 Returns the planned output file name for \a node: its explicit URL if
59 one is set, otherwise the page name the LocationPlan assigned.
60*/
61QString HrefResolver::fileName(const Node *node) const
62{
63 return m_config.plan->fileName(node);
64}
65
66/*!
67 Returns the planned anchor fragment for \a node, or an empty string for
68 a page-level node or an anonymous shared comment.
69
70 Headings and links both ask here, so the id a template emits for a
71 member is the fragment every planned location names.
72*/
73QString HrefResolver::anchorForNode(const Node *node) const
74{
75 return LocationPlan::resolveFragment(node);
76}
77
78/*!
79 Computes a relative URL for \a node, relative to \a relative.
80 Returns the URL as a QString on success, or an HrefSuppressReason
81 explaining why linking should be suppressed.
82
83 External pages (declared via \c \\externalpage) pass through
84 unchanged, since their URL points by design at a resource outside
85 the current documentation set. Every other reference — including
86 URLs loaded from a dependency's \c .index file or authored with an
87 explicit \c \\url that names an absolute address such as
88 \c https://doc.qt.io/... — is reduced to a bare filename stem and
89 then prefixed with whatever relative path reaches the target
90 module's output directory from the current page's output
91 directory. The prefix is derived from OutputContext and the two
92 nodes' trees, not from a hardcoded \c ../<module>/ pattern, so it
93 comes out correct regardless of whether the qdocconf uses
94 per-module subdirs, a format subdirectory, or both.
95*/
96HrefResult HrefResolver::hrefForNode(const Node *node, const Node *relative) const
97{
98 if (node == nullptr)
99 return HrefSuppressReason::NullNode;
100
101 const bool hasExplicitUrl = !node->url().isEmpty();
102 if (hasExplicitUrl && node->isExternalPage())
103 return node->url();
104
105 // An explicit URL arrives with a directory prefix baked in by the
106 // reader that produced it (qdocindexfiles prepends ../<module>/).
107 // That prefix encodes one specific layout's depth assumption and
108 // is wrong for any other layout, so discard it and recompute from
109 // the current output paths below.
110 QString fn = hasExplicitUrl ? node->url().section('/'_L1, -1) : QString();
111 // Strip any anchor from an explicit URL: anchorForNode below is the
112 // single source of truth for the final anchor. Without this, members
113 // of cross-tree pages get the baked anchor preserved and a fresh
114 // anchor appended, producing href values like
115 // `qwindow.html#devicePixelRatio#devicePixelRatio`.
116 if (hasExplicitUrl) {
117 const qsizetype hashIndex = fn.indexOf('#'_L1);
118 if (hashIndex >= 0)
119 fn.truncate(hashIndex);
120 }
121 // A cross-module collection placeholder carries content authored in
122 // another module; its location identity (tree()) points at the
123 // consumer module, but its content-origin identity lives on the
124 // resolvedPhysicalModuleName field set during mergeCollections.
125 // Treat it the same as an index-loaded node: bypass InclusionFilter
126 // and fire the cross-module prefix.
127 const bool isCrossModulePlaceholder = node->isCollectionNode()
128 && !static_cast<const CollectionNode *>(node)
129 ->resolvedPhysicalModuleName().isEmpty();
130 const bool isLocal = !hasExplicitUrl && !node->isIndexNode() && !isCrossModulePlaceholder
131 && (!relative || node->tree() == relative->tree());
132 if (!hasExplicitUrl && !isLocal)
133 fn = fileName(node);
134
135 // Index-loaded nodes carry partial metadata (e.g., a placeholder
136 // Doc), so InclusionFilter can reject upstream-published entities
137 // on synthetic flags. Skip the check for them. Cross-module
138 // collection placeholders share that semantic without the
139 // isIndexNode flag, so admit them too.
140 if (!node->isIndexNode() && !isCrossModulePlaceholder) {
141 const NodeContext context = node->createContext();
142 if (!InclusionFilter::isIncluded(m_config.inclusionPolicy, context))
143 return HrefSuppressReason::ExcludedByPolicy;
144 }
145
146 const Node *publicationNode = node;
147 if (!hasExplicitUrl && node->parent() && node->parent()->isQmlType()
148 && node->parent()->isAbstract()) {
149 // The legacy generators record the QML type they are generating in
150 // Generator's mutable state and expose it through qmlTypeContextFn.
151 // Template generators never establish that state, so prefer the
152 // page being rendered when it is a QML type, and fall back to the
153 // callback for contexts the callback owns (for instance legacy
154 // cross-format runs).
155 const QmlTypeNode *qmlContext = nullptr;
156 if (relative && relative->isQmlType())
157 qmlContext = static_cast<const QmlTypeNode *>(relative);
158 else if (m_config.qmlTypeContextFn)
159 qmlContext = m_config.qmlTypeContextFn();
160 if (qmlContext) {
161 if (qmlContext->inherits(node->parent())) {
162 publicationNode = qmlContext;
163 fn = fileName(qmlContext);
164 // The plan gives a deprecated member an "-obsolete" suffix
165 // so it resolves to the type's obsolete sub-page. The remap
166 // above replaced that stem with the type's main page name,
167 // so re-apply the suffix when the member is deprecated and
168 // the target is a computed name rather than an explicit
169 // \url.
170 if (!node->isAggregate() && node->isDeprecated()
171 && qmlContext->url().isEmpty()) {
172 const QString ext = '.'_L1 + m_config.context->fileExtension;
173 fn.chop(ext.length());
174 fn += "-obsolete"_L1 + ext;
175 }
176 } else if (node->parent()->isInternal() && !m_config.context->noLinkErrors) {
177 node->doc().location().warning(
178 u"Cannot link to property in internal type '%1'"_s
179 .arg(node->parent()->name()));
180 return HrefSuppressReason::InternalAbstractQml;
181 }
182 }
183 }
184
185 std::optional<PublicationLocation> planned;
186 if (isLocal) {
187 planned = m_config.plan->entity(publicationNode);
188 if (!planned && m_config.publications) {
189 planned = m_config.publications->entity(
190 publicationNode, m_config.format, m_config.context->outputDir.path());
191 }
192 if (!planned)
193 return HrefSuppressReason::Unpublished;
194 fn = planned->path;
195 if (publicationNode != node) {
196 planned->fragment = anchorForNode(node);
197 if (!node->isAggregate() && node->isDeprecated()) {
198 const qsizetype dot = fn.lastIndexOf(u'.');
199 if (dot >= 0)
200 fn.insert(dot, "-obsolete"_L1);
201 }
202 }
203 }
204 if (fn.isEmpty())
205 return HrefSuppressReason::NoFileBase;
206
207 QString link = fn;
208
209 if (!node->isPageNode() || node->isPropertyGroup()) {
210 QString ref = planned ? planned->fragment : anchorForNode(node);
211 if (relative && fn == fileName(relative) && ref == anchorForNode(relative))
212 return HrefSuppressReason::SameFileAnchor;
213
214 link += '#'_L1;
215 link += ref;
216 }
217
218 if (relative && (node != relative) && !node->isExternalPage()
219 && (node->isIndexNode() || isCrossModulePlaceholder
220 || node->tree() != relative->tree())) {
221 link.prepend(crossModulePrefix(node, relative));
222 }
223
224 return link;
225}
226
227/*!
228 \internal
229 Returns a relative-path prefix (ending in \c /) that reaches \a
230 target's output directory from \a source's output directory, or
231 an empty string when the two share a directory.
232
233 The current page's output directory is the OutputContext's \c
234 outputDir. The target's output directory is derived by locating
235 the current module's name as a segment in that path and swapping
236 in the target module's name. If the current module's name isn't
237 present — a flat layout where multiple modules render into the
238 same directory — source and target share a directory and no
239 prefix is needed.
240*/
241QString HrefResolver::crossModulePrefix(const Node *target, const Node *source) const
242{
243 const QString &sourceDir = m_config.context->outputDir.path();
244 const QString currentSegment = '/'_L1 + source->tree()->physicalModuleName() + '/'_L1;
245 const qsizetype moduleIndex = sourceDir.indexOf(currentSegment);
246 if (moduleIndex < 0)
247 return {};
248
249 // Cross-module collection placeholders live in the consumer tree but
250 // mirror content from another. Prefer the recorded upstream module
251 // name so the computed prefix reflects the content origin instead of
252 // the placeholder's location.
253 QString targetModuleName;
254 if (target->isCollectionNode()) {
255 const auto *cn = static_cast<const CollectionNode *>(target);
256 targetModuleName = cn->resolvedPhysicalModuleName();
257 }
258 if (targetModuleName.isEmpty())
259 targetModuleName = target->tree()->physicalModuleName();
260 const QString targetSegment = '/'_L1 + targetModuleName + '/'_L1;
261 QString targetDir = sourceDir;
262 targetDir.replace(moduleIndex, currentSegment.size(), targetSegment);
263
264 const QString relPath = QDir(sourceDir).relativeFilePath(targetDir);
265 if (relPath.isEmpty() || relPath == "."_L1)
266 return {};
267 return relPath + '/'_L1;
268}
269
270QT_END_NAMESPACE
271
272#endif // QDOC_TEMPLATE_GENERATOR_ENABLED